code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
<?php
# Database Configuration
define( 'DB_NAME', 'wp_promedia' );
define( 'DB_USER', 'promedia' );
define( 'DB_PASSWORD', 'Hgcjr1nz4UG6M7kD4a2W' );
define( 'DB_HOST', '127.0.0.1' );
define( 'DB_HOST_SLAVE', '127.0.0.1' );
define('DB_CHARSET', 'utf8');
define('DB_COLLATE', 'utf8_unicode_ci');
$table_prefix = 'wp_';
# Security Salts, Keys, Etc
define('AUTH_KEY', 'a`F4guyG[^ Y}d c{idj5&MhTD&|JP[[]~@3:[oUZ0C+8}dUu9hqiW9ZJ-5c}6+|');
define('SECURE_AUTH_KEY', 'eU7MN1?7~|AT,pN|!qQ$3BhT%iYHi~}Uf%`R_eH#$I_XJy3utwjOa}-`Z8rP;eZ;');
define('LOGGED_IN_KEY', 'szAvG,^<>/so:#:-(6RKz~caq+*)lRek+o{44r$2?}?Qd.)taRY0+rd+d<6|nb>s');
define('NONCE_KEY', '0Sd#vgoYj|3 _{zHx+O!@bT*l13wu1=N+fNV]P7Cx|JzL_&=_5Kjs$y^P7?IEss+');
define('AUTH_SALT', 'vrQ2560/7/rdC)gXpr+&2;`w-RD%VyZwu+a5sV)!X<5s_Wq,7}S*7Q~vR|K(Lf*B');
define('SECURE_AUTH_SALT', 'wV^Lf;y6[zqv4!Bm8eZuE!u]k||b!mF]vAx|/)5,aQP`,Mav3SFC;2g`gL4*0F{R');
define('LOGGED_IN_SALT', '?|e&TXiXjP$H5#)*!6I+2]^w#?iL? G3H%pG[MvLgr|kT8+0?w&4BTX+nWnp57f`');
define('NONCE_SALT', '4~7piruf+MjyI%%H(U>r|GPuZDtb#EbJ|@ISBwf+V5+nzEzGNv>ihd#?#wpa+~/|');
# Localized Language Stuff
define( 'WP_CACHE', TRUE );
define( 'WP_AUTO_UPDATE_CORE', false );
define( 'PWP_NAME', 'promedia' );
define( 'FS_METHOD', 'direct' );
define( 'FS_CHMOD_DIR', 0775 );
define( 'FS_CHMOD_FILE', 0664 );
define( 'PWP_ROOT_DIR', '/nas/wp' );
define( 'WPE_APIKEY', 'dfdfa423dd9708ad4a65f5e571606be13b075046' );
define( 'WPE_FOOTER_HTML', "" );
define( 'WPE_CLUSTER_ID', '1986' );
define( 'WPE_CLUSTER_TYPE', 'pod' );
define( 'WPE_ISP', true );
define( 'WPE_BPOD', false );
define( 'WPE_RO_FILESYSTEM', false );
define( 'WPE_LARGEFS_BUCKET', 'largefs.wpengine' );
define( 'WPE_LBMASTER_IP', '212.71.255.152' );
define( 'WPE_CDN_DISABLE_ALLOWED', true );
define( 'DISALLOW_FILE_EDIT', FALSE );
define( 'DISALLOW_FILE_MODS', FALSE );
define( 'DISABLE_WP_CRON', false );
define( 'WPE_FORCE_SSL_LOGIN', false );
define( 'FORCE_SSL_LOGIN', false );
/*SSLSTART*/ if ( isset($_SERVER['HTTP_X_WPE_SSL']) && $_SERVER['HTTP_X_WPE_SSL'] ) $_SERVER['HTTPS'] = 'on'; /*SSLEND*/
define( 'WPE_EXTERNAL_URL', false );
define( 'WP_POST_REVISIONS', FALSE );
define( 'WPE_WHITELABEL', 'wpengine' );
define( 'WP_TURN_OFF_ADMIN_BAR', false );
define( 'WPE_BETA_TESTER', false );
umask(0002);
$wpe_cdn_uris=array ( );
$wpe_no_cdn_uris=array ( );
$wpe_content_regexs=array ( );
$wpe_all_domains=array ( 0 => 'promedia.wpengine.com', );
$wpe_varnish_servers=array ( 0 => 'pod-1986', );
$wpe_special_ips=array ( 0 => '212.71.255.152', );
$wpe_ec_servers=array ( );
$wpe_largefs=array ( );
$wpe_netdna_domains=array ( );
$wpe_netdna_domains_secure=array ( );
$wpe_netdna_push_domains=array ( );
$wpe_domain_mappings=array ( );
$memcached_servers=array ( );
define( 'WPE_SFTP_PORT', 22 );
define('WPLANG','');
# WP Engine ID
# WP Engine Settings
# That's It. Pencils down
if ( !defined('ABSPATH') )
define('ABSPATH', dirname(__FILE__) . '/');
require_once(ABSPATH . 'wp-settings.php');
$_wpe_preamble_path = null; if(false){}
| clientrelation/promedia | wp-config.php | PHP | gpl-2.0 | 3,089 |
#ifndef _SS_CONSTS_HPP_
#define _SS_CONSTS_HPP_
#include "StrideSearchConfig.h"
namespace StrideSearch {
/// Meters per second to Kilometers per hour conversion factor
static const Real MPS2KPH = 3.6;
/// Knots to meters per second conversion factor
static const Real KTS2MPS = 0.5144444;
/// Nautical miles to kilometers conversion factor
static const Real NM2KM = 1.852;
/// Pi
static constexpr Real PI = 3.1415926535897932384626433832795027975;
/// Radians to degrees conversion factor
static constexpr Real RAD2DEG = 180.0 / PI;
/// Degrees to radians conversion factor
static constexpr Real DEG2RAD = PI / 180.0;
/// Hours to days conversion factor
static constexpr Real HOURS2DAYS = 1.0/24.0;
/// Minutes to days conversion factor
static constexpr Real MINUTES2DAYS = 1.0/24.0/60.0;
/// Gravitational acceleration
static constexpr Real G = 9.80616;
/// Mean sea level radius of the Earth (meters)
static constexpr Real EARTH_RADIUS_KM = 6371.220;
static constexpr Real SQ_EARTH_RADIUS_KM = EARTH_RADIUS_KM*EARTH_RADIUS_KM;
/// One sidereal day, in units of seconds
static constexpr Real SIDEREAL_DAY_SEC = 24.0 * 3600.0;
/// Rotational rate of Earth about its z-axis
static constexpr Real EARTH_OMEGA_HZ = 2.0 * PI / SIDEREAL_DAY_SEC;
/// Floating point zero
static constexpr Real ZERO_TOL = 1.0e-11;
}
#endif | pbosler/StrideSearch | src/SSConsts.hpp | C++ | gpl-2.0 | 1,435 |
<?php
/*
$Id$
osCmax e-Commerce
http://www.oscmax.com
Copyright 2000 - 2011 osCmax
Released under the GNU General Public License
*/
define('NAVBAR_TITLE', 'Cuénteselo a un amigo');
define('HEADING_TITLE', 'Háblele a un amigo sobre \'%s\'');
define('FORM_TITLE_CUSTOMER_DETAILS', 'Sus datos');
define('FORM_TITLE_FRIEND_DETAILS', 'Los datos de sus amigo');
define('FORM_TITLE_FRIEND_MESSAGE', 'Su mensaje');
define('FORM_FIELD_CUSTOMER_NAME', 'Su nombre:');
define('FORM_FIELD_CUSTOMER_EMAIL', 'Su dirección e-mail:');
define('FORM_FIELD_FRIEND_NAME', 'Nombre de su amigo:');
define('FORM_FIELD_FRIEND_EMAIL', 'Dirección e-mail de su amigo:');
define('TEXT_EMAIL_SUCCESSFUL_SENT', 'Su e-mail acerca de <b>%s</b> ha sido correctamente enviado a <b>%s</b>.');
define('TEXT_EMAIL_SUBJECT', 'Tu amigo %s te ha recomendado este fantástico producto de %s');
define('TEXT_EMAIL_INTRO', '¡Hola %s!' . "\n\n" . 'Tu amigo, %s, cree que puedes estar interesado en %s de %s.');
define('TEXT_EMAIL_LINK', 'Para ver el producto pulsa en el siguiente enlace o bien copia y pega el enlace en tu navegador:' . "\n\n" . '%s');
// LINE ADDED: MOD - ARTICLE MANAGER
define('TEXT_EMAIL_LINK_ARTICLE', 'Para ver la noticia pulsa en el siguiente enlace o bien copia y pega el enlace en tu navegador:' . "\n\n" . '%s');
define('TEXT_EMAIL_SIGNATURE', 'Saludos,' . "\n\n" . '%s');
define('ERROR_TO_NAME', 'Error: Debe rellenar el nombre de tu amigo.');
define('ERROR_TO_ADDRESS', 'Error: La dirección e-mail de su amigo debe ser una dirección válida.');
define('ERROR_FROM_NAME', 'Error: Debes rellenar su nombre.');
define('ERROR_FROM_ADDRESS', 'Error: Su dirección e-mail debe ser una dirección válida.');
?>
| osCmax/oscmax2 | catalog/includes/languages/espanol/tell_a_friend.php | PHP | gpl-2.0 | 1,742 |
package eu.ttbox.geoping.ui.admob;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import eu.ttbox.geoping.BuildConfig;
import eu.ttbox.geoping.R;
import eu.ttbox.geoping.core.AppConstants;
public class AdmobHelper {
private static final String TAG = "AdmobHelper";
// ===========================================================
// AdView : https://developers.google.com/mobile-ads-sdk/docs/admob/fundamentals
// https://groups.google.com/forum/#!msg/google-admob-ads-sdk/8MCNsiVAc7A/pkRLcQ9zPtYJ
// ===========================================================
public static AdView bindAdMobView(Activity context) {
// Admob
final View admob = context.findViewById(R.id.admob);
final AdView adView = (AdView) context.findViewById(R.id.adView);
if (isAddBlocked(context)) {
Log.d(TAG, "### is Add Blocked adsContainer : " + admob);
if (admob != null) {
admob.setVisibility(View.GONE);
Log.d(TAG, "### is Add Blocked adsContainer ==> GONE");
}
} else {
// Container
Log.d(TAG, "### is Add Not Blocked adsContainer : " + admob);
if (admob != null) {
admob.setVisibility(View.VISIBLE);
Log.d(TAG, "### is Add Not Blocked adsContainer ==> VISIBLE");
}
}
// Request Ad
if (adView != null) {
// http://stackoverflow.com/questions/11790376/animated-mopub-admob-native-ads-overlayed-on-a-game-black-out-screen
//adView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
// Listener
adView.setAdListener(new AdListener() {
public void onAdOpened() {
Log.d(TAG, "### AdListener onAdOpened AdView");
}
public void onAdLoaded() {
Log.d(TAG, "### AdListener onAdLoaded AdView");
}
public void onAdFailedToLoad(int errorcode) {
if (admob!=null) {
Log.d(TAG, "### AdListener onAdFailedToLoad ==> HIDE adsContainer : " + admob);
admob.setVisibility(View.GONE);
}
switch (errorcode) {
case AdRequest.ERROR_CODE_INTERNAL_ERROR:
Log.d(TAG, "### ########################################################################## ###");
Log.d(TAG, "### AdListener onAdFailedToLoad AdView : errorcode = ERROR_CODE_INTERNAL_ERROR ###");
Log.d(TAG, "### ########################################################################## ###");
break;
case AdRequest.ERROR_CODE_INVALID_REQUEST:
Log.d(TAG, "### ########################################################################### ###");
Log.d(TAG, "### AdListener onAdFailedToLoad AdView : errorcode = ERROR_CODE_INVALID_REQUEST ###");
Log.d(TAG, "### ########################################################################### ###");
break;
case AdRequest.ERROR_CODE_NETWORK_ERROR:
Log.d(TAG, "### ######################################################################### ###");
Log.d(TAG, "### AdListener onAdFailedToLoad AdView : errorcode = ERROR_CODE_NETWORK_ERROR ###");
Log.d(TAG, "### ######################################################################### ###");
break;
case AdRequest.ERROR_CODE_NO_FILL:
Log.d(TAG, "### ################################################################### ###");
Log.d(TAG, "### AdListener onAdFailedToLoad AdView : errorcode = ERROR_CODE_NO_FILL ###");
Log.d(TAG, "### ################################################################### ###");
break;
default:
Log.d(TAG, "### ########################################################################### ###");
Log.d(TAG, "### AdListener onAdFailedToLoad AdView : errorcode = " + errorcode + " ###");
Log.d(TAG, "### ########################################################################### ###");
}
}
});
// adView.setAdUnitId(context.getString(R.string.admob_key));
// adView.setAdSize(AdSize.SMART_BANNER);
AdRequest.Builder adRequestBuilder = new AdRequest.Builder();
if (BuildConfig.DEBUG) {
adRequestBuilder
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.addTestDevice("149D6C776DC12F380715698A396A64C4");
}
AdRequest adRequest = adRequestBuilder.build();
adView.loadAd(adRequest);
Log.d(TAG, "### Load adRequest AdView");
} else {
Log.e(TAG, "### Null AdView");
}
return adView;
}
public static boolean isAddBlocked(Context context) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
boolean isAddBlocked = sharedPreferences != null ? sharedPreferences.getBoolean(AppConstants.PREFS_ADD_BLOCKED, false) : false;
return isAddBlocked;
}
// ===========================================================
// InterstitialAd
// ===========================================================
public static class AppAdListener extends AdListener {
InterstitialAd interstitial;
public AppAdListener() {
}
public AppAdListener(InterstitialAd interstitial) {
this.interstitial = interstitial;
}
@Override
public void onAdLoaded() {
Log.i(TAG, "### AdListener : onAdLoaded");
super.onAdLoaded();
interstitial.show();
}
}
public static InterstitialAd displayInterstitialAd(Context context) {
return displayInterstitialAd(context, new AppAdListener());
}
public static InterstitialAd displayInterstitialAd(Context context, AppAdListener adListener) {
final InterstitialAd interstitial = new InterstitialAd(context);
interstitial.setAdUnitId(context.getString(R.string.admob_key));
// Add Listener
adListener.interstitial = interstitial;
interstitial.setAdListener(adListener);
// Create ad request.
AdRequest adRequest = new AdRequest.Builder().build();
// Begin loading your interstitial.
interstitial.loadAd(adRequest);
return interstitial;
}
}
| gabuzomeu/geoPingProject | geoPing/src/main/java/eu/ttbox/geoping/ui/admob/AdmobHelper.java | Java | gpl-2.0 | 7,327 |
package org.cohorte.utilities.security;
/**
* @author ogattaz
*
*/
public class CXPassphraseBuilder {
/**
* @param aValue
* @return
* @throws InstantiationException
* @throws CXPassphraseSchemeException
*/
public static IXPassphrase buildB64(final IXPassphrase aPassphrase)
throws InstantiationException, CXPassphraseSchemeException {
return new CXPassphraseB64(aPassphrase);
}
/**
* @param aValue
* @return
* @throws InstantiationException
* @throws CXPassphraseSchemeException
*/
public static IXPassphrase buildB64(final String aValue)
throws InstantiationException, CXPassphraseSchemeException {
return new CXPassphraseB64(aValue);
}
/**
* @param aValue
* @return
* @throws InstantiationException
* @throws CXPassphraseSchemeException
*/
public static IXPassphrase buildB64OBFRDM(final String aValue)
throws InstantiationException, CXPassphraseSchemeException {
return new CXPassphraseB64(new CXPassphraseOBF(new CXPassphraseRDM(
aValue)));
}
/**
* @param aValue
* @return
* @throws InstantiationException
* @throws CXPassphraseSchemeException
*/
public static IXPassphrase buildOBF(final IXPassphrase aPassphrase)
throws InstantiationException, CXPassphraseSchemeException {
return new CXPassphraseOBF(aPassphrase);
}
/**
* @param aValue
* @return
* @throws InstantiationException
* @throws CXPassphraseSchemeException
*/
public static IXPassphrase buildOBF(final String aValue)
throws InstantiationException, CXPassphraseSchemeException {
return new CXPassphraseOBF(aValue);
}
/**
* @param aPassphrase
* @return
* @throws InstantiationException
* @throws CXPassphraseSchemeException
*/
public static IXPassphrase buildRDM(final IXPassphrase aPassphrase)
throws InstantiationException, CXPassphraseSchemeException {
return new CXPassphraseRDM(aPassphrase);
}
/**
* @param aValue
* @return
* @throws InstantiationException
* @throws CXPassphraseSchemeException
*/
public static IXPassphrase buildRDM(final String aValue)
throws InstantiationException, CXPassphraseSchemeException {
return new CXPassphraseRDM(aValue);
}
}
| isandlaTech/cohorte-utilities | org.cohorte.utilities/src/org/cohorte/utilities/security/CXPassphraseBuilder.java | Java | gpl-2.0 | 2,174 |
#!/usr/bin/python
"""
Since functions are function instances you can wrap them
Allow you to
- modify arguments
- modify function
- modify results
"""
call_count = 0
def count(func):
def wrapper(*args, **kw):
global call_count
call_count += 1
return func(*args, **kw)
return wrapper
def hello():
print 'Invoked hello'
hello = count(hello) ## Now decorating hello to increment call count
hello()
print call_count
hello()
print call_count
"""
## Syntactic Sugar
>>> @count
... def hello():
... print "Invoked hello"
equals
hello = count(hello)
## Syntactic Sugar 2
Dont add parens to the decorator
>>> @count()
... def hello():
... print "Invoked hello"
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: count() takes exactly 1 argument (0 given)
>>>
##Decorator Template
def decorator(func_to_decorate):
def wrapper(*args, **kwargs):
# do something before invocation
result = func_to_decorate(*args,**kwargs)
# do something after invocation
return result
#update wrapper.__doc__ and .func_name
# or functools.wraps
return wrapper
##Decorators can also be classes, to have a class that Decorates
class decorator(object):
def __init__(self, function):
self.function = function
def __call__(self, *args, **kw):
# do something before invocation
result = self.function(*args, **kw)
# do something after
return result
##Decorators can also be classes 2, to have a instance that Decorates
class decorator(object):
def __init__(self, function):
self.function = function
def __call__(self, *args, **kw):
def wrapper(*args, **kw):
# do something before invocation
result = self.function(*args, **kw)
# do something after
return result
return wrapper
## The aboves lets you have an instance of a decorator that stores state
(rather than using global state)
## Parameterized decorators (need 2 closures)
def limit(length):
def decorator(function):
def wrapper(*args, **kw):
result = function(*args, **kw)
result = result[:length]
return result
return wrapper
return decorator
>>> @limit(5) ## Decorating the simple function echo with limit 5 as parameter
... def echo(foo):
... return foo
...
>>> echo ('123456')
'12345'
>>>
Or you can use following as well , to limit the echo function with 3 as parameter
>>> echo = limit(3)(echo)
>>> echo ('123456')
'123'
>>>
## Decorator Tidying
function attributes get mangled
>>> def echo2(input):
... ###return input### I used ### instead of 3 coz that was causing some error
... return input
...
>>> echo2.__doc__
'return input'
>>> echo2.func_name
'echo2'
>>>
>>> echo3 = limit(3)(echo2)
>>> echo3.__doc__
>>> echo3.func_name
'wrapper'
>>>
#Now to fix above define your limit decorator as below
def limit(length):
def decorator(function):
def wrapper(*args, **kw):
result = function(*args, **kw)
result = result[:length]
return result
wrapper.__doc__ = function.__doc__
wrapper.func_name = function.func_name
return wrapper
return decorator
>>> echo4 = limit(3)(echo2)
>>> echo4.__doc__
'return input'
>>> echo4.func_name
'echo2'
>>>
#Decorator tidying (3) , using functools , more simple
import functools
def limit(length):
def decorator(function):
@functools.wraps(function)
def wrapper(*args, **kw):
result = function(*args, **kw)
result = result[:length]
return result
#wrapper.__doc__ = function.__doc__
#wrapper.func_name = function.func_name
return wrapper
return decorator
Uses for decorator
- caching
- monkey patching stdio
- memoize
- jsonify
- logging time in function call
- change cwd
"""
def cwd_decorator(func):
"""
decorator to change cwd to directory containing rst for this function
"""
def wrapper(*args, **kw):
cur_dir = os.getcwd()
found = False
for arg in sys.argv:
if arg.endswith(".rst"):
found = arg
break
if found:
directory = os.path.dirname(arg)
if directory:
os.chdir(directory)
data = func(*args, **kw)
os.chdir(cur_dir)
return data
return wrapper
"""
###
Properties
Call get/set methods via an instance attributes
class C(object):
def getx(self):
return self._x
def setx(self, value):
self._x = value
def delx(self):
del self._x
x = property(getx, setx, delx, "I'm the 'x' property.")
from property.__doc__
"""
import os
def find_files(base_dir, recurse=True):
"""
yeild files found in base_dir
"""
for name in os.listdir(base_dir):
filepath = os.path.join(base_dir, name)
if os.path.isdir(filepath) and recurse:
for child in find_files(filepath, recurse):
yield child
else:
yield filepath
| hiteshagrawal/python | generator-decorator/decorator.py | Python | gpl-2.0 | 4,681 |
<?php
// ini_set('display_errors','1');
function nzshpcrt_getcategoryform($catid)
{
global $wpdb,$nzshpcrt_imagesize_info;
$product = $wpdb->get_row("SELECT * FROM `".WPSC_TABLE_PRODUCT_CATEGORIES."` WHERE `id`=$catid LIMIT 1",ARRAY_A);
$output = '';
$output .= "<div class='editing_this_group form_table'>";
$output .= "<p>".str_replace("[categorisation]", htmlentities(stripslashes($product['name'])), TXT_WPSC_EDITING_GROUP)."</p>\n\r";
$output .= "<p><a href='' onclick='return showaddform()' class='add_category_link'><span>".str_replace(""[categorisation]"", "current", TXT_WPSC_ADDNEWCATEGORY)."</span></a></p>";
$output .="<dl>\n\r";
$output .=" <dt>Display Category Shortcode: </dt>\n\r";
$output .=" <dd> [wpsc_products category_url_name='{$product['nice-name']}']</dd>\n\r";
$output .=" <dt>Display Category Template Tag: </dt>\n\r";
$output .=" <dd> <?php echo wpsc_display_products_page(array('category_url_name'=>'{$product['nice-name']}')); ?></dd>\n\r";
$output .="</dl>\n\r";
//$output .= " [ <a href='#' onclick='return showedit_categorisation_form()'>".TXT_WPSC_EDIT_THIS_GROUP."</a> ]";
$output .= "</div>";
$output .= " <table class='category_forms'>\n\r";
$output .= " <tr>\n\r";
$output .= " <td>\n\r";
$output .= TXT_WPSC_NAME.": ";
$output .= " </td>\n\r";
$output .= " <td>\n\r";
$output .= "<input type='text' class='text' name='title' value='".htmlentities(stripslashes($product['name']), ENT_QUOTES, 'UTF-8')."' />";
$output .= " </td>\n\r";
$output .= " </tr>\n\r";
$output .= " <tr>\n\r";
$output .= " <td>\n\r";
$output .= TXT_WPSC_DESCRIPTION.": ";
$output .= " </td>\n\r";
$output .= " <td>\n\r";
$output .= "<textarea name='description' cols='40' rows='8' >".stripslashes($product['description'])."</textarea>";
$output .= " </td>\n\r";
$output .= " </tr>\n\r";
$output .= " </tr>\n\r";
$output .= " <tr>\n\r";
$output .= " <td>\n\r";
$output .= TXT_WPSC_CATEGORY_PARENT.": ";
$output .= " </td>\n\r";
$output .= " <td>\n\r";
$output .= wpsc_parent_category_list($product['group_id'], $product['id'], $product['category_parent']);
$output .= " </td>\n\r";
$output .= " </tr>\n\r";
$output .= " </tr>\n\r";
if ($product['display_type'] == 'grid') {
$display_type1="selected='selected'";
} else if ($product['display_type'] == 'default') {
$display_type2="selected='selected'";
}
switch($product['display_type']) {
case "default":
$product_view1 = "selected ='selected'";
break;
case "grid":
if(function_exists('product_display_grid')) {
$product_view3 = "selected ='selected'";
break;
}
case "list":
if(function_exists('product_display_list')) {
$product_view2 = "selected ='selected'";
break;
}
default:
$product_view0 = "selected ='selected'";
break;
}
$output .= " <tr>\n\r";
$output .= " <td>\n\r";
$output .= TXT_WPSC_GROUP_IMAGE.": ";
$output .= " </td>\n\r";
$output .= " <td>\n\r";
$output .= "<input type='file' name='image' value='' />";
$output .= " </td>\n\r";
$output .= " </tr>\n\r";
$output .= " </tr>\n\r";
if(function_exists("getimagesize")) {
if($product['image'] != '') {
$imagepath = WPSC_CATEGORY_DIR . $product['image'];
$imagetype = @getimagesize($imagepath); //previously exif_imagetype()
$output .= " <tr>\n\r";
$output .= " <td>\n\r";
$output .= " </td>\n\r";
$output .= " <td>\n\r";
$output .= TXT_WPSC_HEIGHT.":<input type='text' size='6' name='height' value='".$imagetype[1]."' /> ".TXT_WPSC_WIDTH.":<input type='text' size='6' name='width' value='".$imagetype[0]."' /><br /><span class='wpscsmall description'>$nzshpcrt_imagesize_info</span><br />\n\r";
$output .= "<span class='wpscsmall description'>".TXT_WPSC_GROUP_IMAGE_TEXT."</span>\n\r";
$output .= " </td>\n\r";
$output .= " </tr>\n\r";
} else {
$output .= " <tr>\n\r";
$output .= " <td>\n\r";
$output .= " </td>\n\r";
$output .= " <td>\n\r";
$output .= TXT_WPSC_HEIGHT.":<input type='text' size='6' name='height' value='".get_option('product_image_height')."' /> ".TXT_WPSC_WIDTH.":<input type='text' size='6' name='width' value='".get_option('product_image_width')."' /><br /><span class='wpscsmall description'>$nzshpcrt_imagesize_info</span><br />\n\r";
$output .= "<span class='wpscsmall description'>".TXT_WPSC_GROUP_IMAGE_TEXT."</span>\n\r";
$output .= " </td>\n\r";
$output .= " </tr>\n\r";
}
}
$output .= " <tr>\n\r";
$output .= " <td>\n\r";
$output .= TXT_WPSC_DELETEIMAGE.": ";
$output .= " </td>\n\r";
$output .= " <td>\n\r";
$output .= "<input type='checkbox' name='deleteimage' value='1' />";
$output .= " </td>\n\r";
$output .= " </tr>\n\r";
$output .= " </tr>\n\r";
/* START OF TARGET MARKET SELECTION */
$countrylist = $wpdb->get_results("SELECT id,country,visible FROM `".WPSC_TABLE_CURRENCY_LIST."` ORDER BY country ASC ",ARRAY_A);
$selectedCountries = $wpdb->get_col("SELECT countryid FROM `".WPSC_TABLE_CATEGORY_TM."` WHERE categoryid=".$product['id']." AND visible= 1");
// exit('<pre>'.print_r($countrylist,true).'</pre><br /><pre>'.print_r($selectedCountries,true).'</pre>');
$output .= " <tr>\n\r";
$output .= " <td colspan='2'><h4>Target Market Restrictions</h4></td></tr><tr><td> </td></tr><tr>\n\r";
$output .= " <td>\n\r";
$output .= TXT_WPSC_TM.":\n\r";
$output .= " </td>\n\r";
$output .= " <td>\n\r";
if(@extension_loaded('suhosin')) {
$output .= "<em>".__("The Target Markets feature has been disabled because you have the Suhosin PHP extension installed on this server. If you need to use the Target Markets feature then disable the suhosin extension, if you can not do this, you will need to contact your hosting provider.
",'wpsc')."</em>";
} else {
$output .= "<span>Select: <a href='' class='wpsc_select_all'>All</a> <a href='' class='wpsc_select_none'>None</a></span><br />";
$output .= " <div id='resizeable' class='ui-widget-content multiple-select'>\n\r";
foreach($countrylist as $country){
if(in_array($country['id'], $selectedCountries))
/* if($country['visible'] == 1) */{
$output .= " <input type='checkbox' name='countrylist2[]' value='".$country['id']."' checked='".$country['visible']."' />".$country['country']."<br />\n\r";
}else{
$output .= " <input type='checkbox' name='countrylist2[]' value='".$country['id']."' />".$country['country']."<br />\n\r";
}
}
$output .= " </div><br /><br />";
$output .= " <span class='wpscsmall description'>Select the markets you are selling this category to.<span>\n\r";
}
$output .= " </td>\n\r";
$output .= " </tr>\n\r";
////////
$output .= " <tr>\n\r";
$output .= " <td colspan='2' class='category_presentation_settings'>\n\r";
$output .= " <h4>".TXT_WPSC_PRESENTATIONSETTINGS."</h4>\n\r";
$output .= " <span class='small'>".TXT_WPSC_GROUP_PRESENTATION_TEXT."</span>\n\r";
$output .= " </td>\n\r";
$output .= " </tr>\n\r";
$output .= " <tr>\n\r";
$output .= " <td>\n\r";
$output .= " ". TXT_WPSC_CATALOG_VIEW.":\n\r";
$output .= " </td>\n\r";
$output .= " <td>\n\r";
$output .= " <select name='display_type'>\n\r";
$output .= " <option value='' $product_view0 >".TXT_WPSC_PLEASE_SELECT."</option>\n\r";
$output .= " <option value='default' $product_view1 >".TXT_WPSC_DEFAULT."</option>\n\r";
if(function_exists('product_display_list')) {
$output .= " <option value='list' ". $product_view2.">". TXT_WPSC_LIST."</option>\n\r";
} else {
$output .= " <option value='list' disabled='disabled' ". $product_view2.">". TXT_WPSC_LIST."</option>\n\r";
}
if(function_exists('product_display_grid')) {
$output .= " <option value='grid' ". $product_view3.">". TXT_WPSC_GRID."</option>\n\r";
} else {
$output .= " <option value='grid' disabled='disabled' ". $product_view3.">". TXT_WPSC_GRID."</option>\n\r";
}
$output .= " </select>\n\r";
$output .= " </td>\n\r";
$output .= " </tr>\n\r";
$output .= " <tr>\n\r";
if(function_exists("getimagesize")) {
$output .= " <tr>\n\r";
$output .= " <td>\n\r";
$output .= TXT_WPSC_THUMBNAIL_SIZE.": ";
$output .= " </td>\n\r";
$output .= " <td>\n\r";
$output .= TXT_WPSC_HEIGHT.": <input type='text' value='".$product['image_height']."' name='product_height' size='6'/> ";
$output .= TXT_WPSC_WIDTH.": <input type='text' value='".$product['image_width']."' name='product_width' size='6'/> <br/>";
$output .= " </td>\n\r";
$output .= " </tr>\n\r";
$output .= " </tr>\n\r";
}
$output .= " <tr>\n\r";
$output .= " <td>\n\r";
$output .= " </td>\n\r";
$output .= " <td class='last_row'>\n\r";
$output .= "<input type='hidden' name='prodid' value='".$product['id']."' />";
$output .= "<input type='hidden' name='submit_action' value='edit' />";
$output .= "<input class='button-primary' style='float:left;' type='submit' name='submit' value='".TXT_WPSC_EDIT_GROUP."' />";
$output .= "<a class='delete_button' href='".add_query_arg('deleteid', $product['id'], 'admin.php?page=wpsc-edit-groups')."' onclick=\"return conf();\" >".TXT_WPSC_DELETE."</a>";
$output .= " </td>\n\r";
$output .= " </tr>\n\r";
$output .= " </table>\n\r";
return $output;
}
function nzshpcrt_getvariationform($variation_id)
{
global $wpdb,$nzshpcrt_imagesize_info;
$variation_sql = "SELECT * FROM `".WPSC_TABLE_PRODUCT_VARIATIONS."` WHERE `id`='$variation_id' LIMIT 1";
$variation_data = $wpdb->get_results($variation_sql,ARRAY_A) ;
$variation = $variation_data[0];
$output .= " <table class='category_forms' >\n\r";
$output .= " <tr>\n\r";
$output .= " <td>\n\r";
$output .= TXT_WPSC_NAME.": ";
$output .= " </td>\n\r";
$output .= " <td>\n\r";
$output .= "<input type='text' class='text' name='title' value='".htmlentities(stripslashes($variation['name']), ENT_QUOTES, 'UTF-8')."' />";
$output .= " </td>\n\r";
$output .= " </tr>\n\r";
$output .= " <tr>\n\r";
$output .= " <td>\n\r";
$output .= TXT_WPSC_VARIATION_VALUES.": ";
$output .= " </td>\n\r";
$output .= " <td>\n\r";
$variation_values_sql = "SELECT * FROM `".WPSC_TABLE_VARIATION_VALUES."` WHERE `variation_id`='$variation_id' ORDER BY `id` ASC";
$variation_values = $wpdb->get_results($variation_values_sql,ARRAY_A);
$variation_value_count = count($variation_values);
$output .= "<div id='edit_variation_values'>";
$num = 0;
foreach($variation_values as $variation_value) {
$output .= "<span class='variation_value'>";
$output .= "<input type='text' class='text' name='variation_values[".$variation_value['id']."]' value='".htmlentities(stripslashes($variation_value['name']), ENT_QUOTES, 'UTF-8')."' />";
if($variation_value_count > 1) {
$output .= " <a class='image_link' onclick='return remove_variation_value(this,".$variation_value['id'].")' href='#'><img src='".WPSC_URL."/images/trash.gif' alt='".TXT_WPSC_DELETE."' title='".TXT_WPSC_DELETE."' /></a>";
}
$output .= "<br />";
$output .= "</span>";
$num++;
}
$output .= "</div>";
$output .= "<a href='#' onclick='return add_variation_value(\"edit\")'>".TXT_WPSC_ADD."</a>";
$output .= " </td>\n\r";
$output .= " </tr>\n\r";
$output .= " </tr>\n\r";
$output .= " <tr>\n\r";
$output .= " <td>\n\r";
$output .= " </td>\n\r";
$output .= " <td>\n\r";
$output .= "<input type='hidden' name='prodid' value='".$variation['id']."' />";
$output .= "<input type='hidden' name='submit_action' value='edit' />";
$output .= "<input class='button' style='float:left;' type='submit' name='submit' value='".TXT_WPSC_EDIT."' />";
$output .= "<a class='button delete_button' href='admin.php?page=".WPSC_DIR_NAME."/display_variations.php&deleteid=".$variation['id']."' onclick=\"return conf();\" >".TXT_WPSC_DELETE."</a>";
$output .= " </td>\n\r";
$output .= " </tr>\n\r";
$output .= " </table>\n\r";
return $output;
}
function coupon_edit_form($coupon) {
$conditions = unserialize($coupon['condition']);
$conditions = $conditions[0];
//exit('<pre>'.print_r($conditions, true).'</pre>');
$start_timestamp = strtotime($coupon['start']);
$end_timestamp = strtotime($coupon['expiry']);
$id = $coupon['id'];
$output = '';
$output .= "<form name='edit_coupon' method='post' action='admin.php?page=".WPSC_DIR_NAME."/display-coupons.php'>\n\r";
$output .= " <input type='hidden' value='true' name='is_edit_coupon' />\n\r";
$output .= "<table class='add-coupon'>\n\r";
$output .= " <tr>\n\r";
$output .= " <th>".TXT_WPSC_COUPON_CODE."</th>\n\r";
$output .= " <th>".TXT_WPSC_DISCOUNT."</th>\n\r";
$output .= " <th>".TXT_WPSC_START."</th>\n\r";
$output .= " <th>".TXT_WPSC_EXPIRY."</th>\n\r";
$output .= " <th>".TXT_WPSC_USE_ONCE."</th>\n\r";
$output .= " <th>".TXT_WPSC_ACTIVE."</th>\n\r";
$output .= " <th>".TXT_WPSC_PERTICKED."</th>\n\r";
$output .= " <th></th>\n\r";
$output .= " </tr>\n\r";
$output .= " <tr>\n\r";
$output .= " <td>\n\r";
$output .= " <input type='text' size='8' value='".$coupon['coupon_code']."' name='edit_coupon[".$id."][coupon_code]' />\n\r";
$output .= " </td>\n\r";
$output .= " <td>\n\r";
$output .= " <input type='text' style='width:28px;' value='".$coupon['value']."' name=edit_coupon[".$id."][value]' />";
$output .= " <select style='width:20px;' name='edit_coupon[".$id."][is-percentage]'>";
$output .= " <option value='0' ".(($coupon['is-percentage'] == 0) ? "selected='true'" : '')." >$</option>\n\r";//
$output .= " <option value='1' ".(($coupon['is-percentage'] == 1) ? "selected='true'" : '')." >%</option>\n\r";
$output .= " </select>\n\r";
$output .= " </td>\n\r";
$output .= " <td>\n\r";
$coupon_start = explode(" ",$coupon['start']);
$output .= "<input type='text' class='pickdate' size='8' name='edit_coupon[".$id."][start]' value='{$coupon_start[0]}'>";
/* $output .= " <select name='edit_coupon[".$id."][start][day]'>\n\r";
for($i = 1; $i <=31; ++$i) {
$selected = '';
if($i == date("d", $start_timestamp)) { $selected = "selected='true'"; }
$output .= " <option $selected value='$i'>$i</option>";
}
$output .= " </select>\n\r";
$output .= " <select name='edit_coupon[".$id."][start][month]'>\n\r";
for($i = 1; $i <=12; ++$i) {
$selected = '';
if($i == (int)date("m", $start_timestamp)) { $selected = "selected='true'"; }
$output .= " <option $selected value='$i'>".date("M",mktime(0, 0, 0, $i, 1, date("Y")))."</option>";
}
$output .= " </select>\n\r";
$output .= " <select name='edit_coupon[".$id."][start][year]'>\n\r";
for($i = date("Y"); $i <= (date("Y") +12); ++$i) {
$selected = '';
if($i == date("Y", $start_timestamp)) { $selected = "selected='true'"; }
$output .= " <option $selected value='$i'>".$i."</option>";
}
$output .= " </select>\n\r";*/
$output .= " </td>\n\r";
$output .= " <td>\n\r";
$coupon_expiry = explode(" ",$coupon['expiry']);
$output .= "<input type='text' class='pickdate' size='8' name='edit_coupon[".$id."][expiry]' value='{$coupon_expiry[0]}'>";
/*$output .= " <select name='edit_coupon[".$id."][expiry][day]'>\n\r";
for($i = 1; $i <=31; ++$i) {
$selected = '';
if($i == date("d", $end_timestamp)) { $selected = "selected='true'"; }
$output .= " <option $selected value='$i'>$i</option>";
}
$output .= " </select>\n\r";
$output .= " <select name='edit_coupon[".$id."][expiry][month]'>\n\r";
for($i = 1; $i <=12; ++$i) {
$selected = '';
if($i == (int)date("m", $end_timestamp)) { $selected = "selected='true'"; }
$output .= " <option $selected value='$i'>".date("M",mktime(0, 0, 0, $i, 1, date("Y")))."</option>";
}
$output .= " </select>\n\r";
$output .= " <select name='edit_coupon[".$id."][expiry][year]'>\n\r";
for($i = date("Y"); $i <= (date("Y") +12); ++$i) {
$selected = '';
if($i == (date("Y", $end_timestamp))) { $selected = "selected='true'"; }
$output .= " <option $selected value='$i'>".$i."</option>\n\r";
}
$output .= " </select>\n\r";*/
$output .= " </td>\n\r";
$output .= " <td>\n\r";
$output .= " <input type='hidden' value='0' name='edit_coupon[".$id."][use-once]' />\n\r";
$output .= " <input type='checkbox' value='1' ".(($coupon['use-once'] == 1) ? "checked='checked'" : '')." name='edit_coupon[".$id."][use-once]' />\n\r";
$output .= " </td>\n\r";
$output .= " <td>\n\r";
$output .= " <input type='hidden' value='0' name='edit_coupon[".$id."][active]' />\n\r";
$output .= " <input type='checkbox' value='1' ".(($coupon['active'] == 1) ? "checked='checked'" : '')." name='edit_coupon[".$id."][active]' />\n\r";
$output .= " </td>\n\r";
$output .= " <td>\n\r";
$output .= " <input type='hidden' value='0' name='edit_coupon[".$id."][every_product]' />\n\r";
$output .= " <input type='checkbox' value='1' ".(($coupon['every_product'] == 1) ? "checked='checked'" : '')." name='edit_coupon[".$id."][every_product]' />\n\r";
$output .= " </td>\n\r";
$output .= " <td>\n\r";
$output .= " <input type='hidden' value='".$id."' name='edit_coupon[".$id."][id]' />\n\r";
//$output .= " <input type='hidden' value='false' name='add_coupon' />\n\r";
$output .= " <input type='submit' value='".TXT_WPSC_SUBMIT."' name='edit_coupon[".$id."][submit_coupon]' />\n\r";
$output .= " <input type='submit' value='".TXT_WPSC_DELETE."' name='edit_coupon[".$id."][delete_coupon]' />\n\r";
$output .= " </td>\n\r";
$output .= " </tr>\n\r";
if($conditions != null){
$output .= "<tr>";
$output .= "<th>";
$output .= "Conditions";
$output .= "</th>";
$output .= "</tr>";
$output .= "<th>";
$output .= "Delete";
$output .= "</th>";
$output .= "<th>";
$output .= "Property";
$output .= "</th>";
$output .= "<th>";
$output .= "Logic";
$output .= "</th>";
$output .= "<th>";
$output .= "Value";
$output .= "</th>";
$output .= " </tr>\n\r";
$output .= "<tr>";
$output .= "<td>";
$output .= "<input type='hidden' name='coupon_id' value='".$id."' />";
$output .= "<input type='submit' value='Delete' name='delete_condition' />";
$output .= "</td>";
$output .= "<td>";
$output .= $conditions['property'];
$output .= "</td>";
$output .= "<td>";
$output .= $conditions['logic'];
$output .= "</td>";
$output .= "<td>";
$output .= $conditions['value'];
$output .= "</td>";
$output .= "</tr>";
}elseif($conditions == null){
$output .= wpsc_coupons_conditions( $id);
}
?>
<!--
<tr><td colspan="8">
<div class="coupon_condition">
<div><img height="16" width="16" class="delete" alt="Delete" src="<?=WPSC_URL?>/images/cross.png"/></button>
<select class="ruleprops" name="rules[property][]">
<option value="item_name" rel="order">Item name</option>
<option value="item_quantity" rel="order">Item quantity</option>
<option value="total_quantity" rel="order">Total quantity</option>
<option value="subtotal_amount" rel="order">Subtotal amount</option>
</select>
<select name="rules[logic][]">
<option value="equal">Is equal to</option>
<option value="greater">Is greater than</option>
<option value="less">Is less than</option>
<option value="contains">Contains</option>
<option value="not_contain">Does not contain</option>
<option value="begins">Begins with</option>
<option value="ends">Ends with</option>
</select>
<span>
<input type="text" name="rules[value][]"/>
</span>
<span>
<button class="add" type="button">
<img height="16" width="16" alt="Add" src="<?=WPSC_URL?>/images/add.png"/>
</button>
</span>
</div>
</div>
</tr>
-->
<?php
$output .= "</table>\n\r";
$output .= "</form>\n\r";
echo $output;
return $output;
}
function wpsc_coupons_conditions($id){
?>
<?php
$output ='
<input type="hidden" name="coupon_id" value="'.$id.'" />
<tr><td colspan="3"><b>Conditions</b></td></tr>
<tr><td colspan="8">
<div class="coupon_condition">
<div>
<select class="ruleprops" name="rules[property][]">
<option value="item_name" rel="order">Item name</option>
<option value="item_quantity" rel="order">Item quantity</option>
<option value="total_quantity" rel="order">Total quantity</option>
<option value="subtotal_amount" rel="order">Subtotal amount</option>
</select>
<select name="rules[logic][]">
<option value="equal">Is equal to</option>
<option value="greater">Is greater than</option>
<option value="less">Is less than</option>
<option value="contains">Contains</option>
<option value="not_contain">Does not contain</option>
<option value="begins">Begins with</option>
<option value="ends">Ends with</option>
</select>
<span>
<input type="text" name="rules[value][]"/>
</span>
<span>
<input type="submit" value="add" name="submit_condition" />
</span>
</div>
</div>
</tr>
';
return $output;
}
function setting_button(){
$itemsFeedURL = "http://www.google.com/base/feeds/items";
$next_url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']."?page=wpsc-edit-products";
$redirect_url = 'https://www.google.com/accounts/AuthSubRequest?session=1';
$redirect_url .= '&next=';
$redirect_url .= urlencode($next_url);
$redirect_url .= "&scope=";
$redirect_url .= urlencode($itemsFeedURL);
// $output.="<div><img src='".get_option('siteurl')."/wp-content/plugins/".WPSC_DIR_NAME."/images/settings_button.jpg' onclick='display_settings_button()'>";
$output.="<div style='float: right; margin-top: 0px; position: relative;'> | <a href='#' onclick='display_settings_button(); return false;' style='text-decoration: underline;'>".TXT_WPSC_SETTINGS." »</a>";
$output.="<span id='settings_button' style='width:180px;background-color:#f1f1f1;position:absolute; right: 10px; border:1px solid black; display:none;'>";
$output.="<ul class='settings_button'>";
$output.="<li><a href='admin.php?page=wpsc-settings'>".TXT_WPSC_SHOP_SETTINGS."</a></li>";
$output.="<li><a href='admin.php?page=wpsc-settings&tab=gateway'>".TXT_WPSC_MONEY_AND_PAYMENT."</a></li>";
$output.="<li><a href='admin.php?page=wpsc-settings&tab=checkout'>".TXT_WPSC_CHECKOUT_PAGE_SETTINGS."</a></li>";
//$output.="<li><a href='?page=".WPSC_DIR_NAME."/instructions.php'>Help/Upgrade</a></li>";
//$output.="<li><a href='{$redirect_url}'>".TXT_WPSC_LOGIN_TO_GOOGLE_BASE."</a></li>";
$output.="</ul>";
// $output.="<div>Checkout Settings</div>";
$output.="</span>  </div>";
return $output;
}
function wpsc_right_now() {
global $wpdb,$nzshpcrt_imagesize_info;
$year = date("Y");
$month = date("m");
$start_timestamp = mktime(0, 0, 0, $month, 1, $year);
$end_timestamp = mktime(0, 0, 0, ($month+1), 0, $year);
$replace_values[":productcount:"] = $wpdb->get_var("SELECT COUNT(*) FROM `".WPSC_TABLE_PRODUCT_LIST."` WHERE `active` IN ('1')");
$product_count = $wpdb->get_var("SELECT COUNT(*) FROM `".WPSC_TABLE_PRODUCT_LIST."` WHERE `active` IN ('1')");
$replace_values[":productcount:"] .= " ".(($replace_values[":productcount:"] == 1) ? TXT_WPSC_PRODUCTCOUNT_SINGULAR : TXT_WPSC_PRODUCTCOUNT_PLURAL);
$product_unit = (($replace_values[":productcount:"] == 1) ? TXT_WPSC_PRODUCTCOUNT_SINGULAR : TXT_WPSC_PRODUCTCOUNT_PLURAL);
$replace_values[":groupcount:"] = $wpdb->get_var("SELECT COUNT(*) FROM `".WPSC_TABLE_PRODUCT_CATEGORIES."` WHERE `active` IN ('1')");
$group_count = $wpdb->get_var("SELECT COUNT(*) FROM `".WPSC_TABLE_PRODUCT_CATEGORIES."` WHERE `active` IN ('1')");
$replace_values[":groupcount:"] .= " ".(($replace_values[":groupcount:"] == 1) ? TXT_WPSC_GROUPCOUNT_SINGULAR : TXT_WPSC_GROUPCOUNT_PLURAL);
$group_unit = (($replace_values[":groupcount:"] == 1) ? TXT_WPSC_GROUPCOUNT_SINGULAR : TXT_WPSC_GROUPCOUNT_PLURAL);
$replace_values[":salecount:"] = $wpdb->get_var("SELECT COUNT(*) FROM `".WPSC_TABLE_PURCHASE_LOGS."` WHERE `date` BETWEEN '".$start_timestamp."' AND '".$end_timestamp."'");
$sales_count = $wpdb->get_var("SELECT COUNT(*) FROM `".WPSC_TABLE_PURCHASE_LOGS."` WHERE `date` BETWEEN '".$start_timestamp."' AND '".$end_timestamp."'");
$replace_values[":salecount:"] .= " ".(($replace_values[":salecount:"] == 1) ? TXT_WPSC_SALECOUNT_SINGULAR : TXT_WPSC_SALECOUNT_PLURAL);
$sales_unit = (($replace_values[":salecount:"] == 1) ? TXT_WPSC_SALECOUNT_SINGULAR : TXT_WPSC_SALECOUNT_PLURAL);
$replace_values[":monthtotal:"] = nzshpcrt_currency_display(admin_display_total_price($start_timestamp, $end_timestamp),1);
$replace_values[":overaltotal:"] = nzshpcrt_currency_display(admin_display_total_price(),1);
$variation_count = $wpdb->get_var("SELECT COUNT(*) FROM `".WPSC_TABLE_PRODUCT_VARIATIONS."`");
$variation_unit = (($variation_count == 1) ? TXT_WPSC_VARIATION_SINGULAR : TXT_WPSC_VARIATION_PLURAL);
$replace_values[":pendingcount:"] = $wpdb->get_var("SELECT COUNT(*) FROM `".WPSC_TABLE_PURCHASE_LOGS."` WHERE `processed` IN ('1')");
$pending_sales = $wpdb->get_var("SELECT COUNT(*) FROM `".WPSC_TABLE_PURCHASE_LOGS."` WHERE `processed` IN ('1')");
$replace_values[":pendingcount:"] .= " " . (($replace_values[":pendingcount:"] == 1) ? TXT_WPSC_PENDINGCOUNT_SINGULAR : TXT_WPSC_PENDINGCOUNT_PLURAL);
$pending_sales_unit = (($replace_values[":pendingcount:"] == 1) ? TXT_WPSC_PENDINGCOUNT_SINGULAR : TXT_WPSC_PENDINGCOUNT_PLURAL);
$accept_sales = $wpdb->get_var("SELECT COUNT(*) FROM `".WPSC_TABLE_PURCHASE_LOGS."` WHERE `processed` IN ('2' ,'3', '4')");
$accept_sales_unit = (($accept_sales == 1) ? TXT_WPSC_PENDINGCOUNT_SINGULAR : TXT_WPSC_PENDINGCOUNT_PLURAL);
$replace_values[":theme:"] = get_option('wpsc_selected_theme');
$replace_values[":versionnumber:"] = WPSC_PRESENTABLE_VERSION;
if (function_exists('add_object_page')) {
$output="";
$output.="<div id='dashboard_right_now' class='postbox'>";
$output.=" <h3 class='hndle'>";
$output.=" <span>".TXT_WPSC_CURRENT_MONTH."</span>";
$output.=" <br class='clear'/>";
$output.=" </h3>";
$output .= "<div class='inside'>";
$output .= "<p class='sub'>".TXT_WPSC_AT_A_GLANCE."</p>";
//$output.="<p class='youhave'>".TXT_WPSC_SALES_DASHBOARD."</p>";
$output .= "<div class='table'>";
$output .= "<table>";
$output .= "<tr class='first'>";
$output .= "<td class='first b'>";
$output .= "<a href='?page=wpsc-edit-products'>".$product_count."</a>";
$output .= "</td>";
$output .= "<td class='t'>";
$output .= ucfirst($product_unit);
$output .= "</td>";
$output .= "<td class='b'>";
$output .= "<a href='?page=wpsc-sales-logs'>".$sales_count."</a>";
$output .= "</td>";
$output .= "<td class='last'>";
$output .= ucfirst($sales_unit);
$output .= "</td>";
$output .= "</tr>";
$output .= "<tr>";
$output .= "<td class='first b'>";
$output .= "<a href='?page=wpsc-edit-groups'>".$group_count."</a>";
$output .= "</td>";
$output .= "<td class='t'>";
$output .= ucfirst($group_unit);
$output .= "</td>";
$output .= "<td class='b'>";
$output .= "<a href='?page=wpsc-sales-logs'>".$pending_sales."</a>";
$output .= "</td>";
$output .= "<td class='last t waiting'>".TXT_WPSC_PENDING." ";
$output .= ucfirst($pending_sales_unit);
$output .= "</td>";
$output .= "</tr>";
$output .= "<tr>";
$output .= "<td class='first b'>";
$output .= "<a href='?page=wpsc-edit-variations'>".$variation_count."</a>";
$output .= "</td>";
$output .= "<td class='t'>";
$output .= ucfirst($variation_unit);
$output .= "</td>";
$output .= "<td class='b'>";
$output .= "<a href='?page=wpsc-sales-logs'>".$accept_sales."</a>";
$output .= "</td>";
$output .= "<td class='last t approved'>".TXT_WPSC_CLOSED." ";
$output .= ucfirst($accept_sales_unit);
$output .= "</td>";
$output .= "</tr>";
$output .= "</table>";
$output .= "</div>";
$output .= "<div class='versions'>";
$output .= "<p><a class='button rbutton' href='admin.php?page=wpsc-edit-products'><strong>".TXT_WPSC_ADD_NEW_PRODUCT."</strong></a>".TXT_WPSC_HERE_YOU_CAN_ADD."</p>";
$output .= "</div>";
$output .= "</div>";
$output.="</div>";
} else {
$output="";
$output.="<div id='rightnow'>\n\r";
$output.=" <h3 class='reallynow'>\n\r";
$output.=" <a class='rbutton' href='admin.php?page=wpsc-edit-products'><strong>".TXT_WPSC_ADD_NEW_PRODUCT."</strong></a>\n\r";
$output.=" <span>"._('Right Now')."</span>\n\r";
//$output.=" <br class='clear'/>\n\r";
$output.=" </h3>\n\r";
$output.="<p class='youhave'>".TXT_WPSC_SALES_DASHBOARD."</p>\n\r";
$output.=" <p class='youare'>\n\r";
$output.=" ".TXT_WPSC_YOUAREUSING."\n\r";
//$output.=" <a class='rbutton' href='themes.php'>Change Theme</a>\n\r";
//$output.="<span id='wp-version-message'>This is WordPress version 2.6. <a class='rbutton' href='http://wordpress.org/download/'>Update to 2.6.1</a></span>\n\r";
$output.=" </p>\n\r";
$output.="</div>\n\r";
$output.="<br />\n\r";
$output = str_replace(array_keys($replace_values), array_values($replace_values),$output);
}
return $output;
}
function wpsc_packing_slip($purchase_id) {
global $wpdb;
$purch_sql = "SELECT * FROM `".WPSC_TABLE_PURCHASE_LOGS."` WHERE `id`='".$purchase_id."'";
$purch_data = $wpdb->get_row($purch_sql,ARRAY_A) ;
//echo "<p style='padding-left: 5px;'><strong>".TXT_WPSC_DATE."</strong>:".date("jS M Y", $purch_data['date'])."</p>";
$cartsql = "SELECT * FROM `".WPSC_TABLE_CART_CONTENTS."` WHERE `purchaseid`=".$purchase_id."";
$cart_log = $wpdb->get_results($cartsql,ARRAY_A) ;
$j = 0;
if($cart_log != null) {
echo "<div class='packing_slip'>\n\r";
echo "<h2>".TXT_WPSC_PACKING_SLIP."</h2>\n\r";
echo "<strong>".TXT_WPSC_ORDER." #</strong> ".$purchase_id."<br /><br />\n\r";
echo "<table>\n\r";
$form_sql = "SELECT * FROM `".WPSC_TABLE_SUBMITED_FORM_DATA."` WHERE `log_id` = '".(int)$purchase_id."'";
$input_data = $wpdb->get_results($form_sql,ARRAY_A);
foreach($input_data as $input_row) {
$rekeyed_input[$input_row['form_id']] = $input_row;
}
if($input_data != null) {
$form_data = $wpdb->get_results("SELECT * FROM `".WPSC_TABLE_CHECKOUT_FORMS."` WHERE `active` = '1'",ARRAY_A);
foreach($form_data as $form_field) {
switch($form_field['type']) {
case 'country':
$delivery_region_count = $wpdb->get_var("SELECT COUNT(`regions`.`id`) FROM `".WPSC_TABLE_REGION_TAX."` AS `regions` INNER JOIN `".WPSC_TABLE_CURRENCY_LIST."` AS `country` ON `country`.`id` = `regions`.`country_id` WHERE `country`.`isocode` IN('".$wpdb->escape( $purch_data['billing_country'])."')");
if(is_numeric($purch_data['shipping_region']) && ($delivery_region_count > 0)) {
echo " <tr><td>".__('State', 'wpsc').":</td><td>".wpsc_get_region($purch_data['shipping_region'])."</td></tr>\n\r";
}
echo " <tr><td>".wp_kses($form_field['name'], array() ).":</td><td>".wpsc_get_country($purch_data['billing_country'])."</td></tr>\n\r";
break;
case 'delivery_country':
echo " <tr><td>".wp_kses($form_field['name'], array() ).":</td><td>".wpsc_get_country($purch_data['shipping_country'])."</td></tr>\n\r";
break;
case 'heading':
echo " <tr><td colspan='2'><strong>".wp_kses($form_field['name'], array() ).":</strong></td></tr>\n\r";
break;
default:
echo " <tr><td>".wp_kses($form_field['name'], array() ).":</td><td>".htmlentities(stripslashes($rekeyed_input[$form_field['id']]['value']), ENT_QUOTES)."</td></tr>\n\r";
break;
}
}
} else {
echo " <tr><td>".TXT_WPSC_NAME.":</td><td>".$purch_data['firstname']." ".$purch_data['lastname']."</td></tr>\n\r";
echo " <tr><td>".TXT_WPSC_ADDRESS.":</td><td>".$purch_data['address']."</td></tr>\n\r";
echo " <tr><td>".TXT_WPSC_PHONE.":</td><td>".$purch_data['phone']."</td></tr>\n\r";
echo " <tr><td>".TXT_WPSC_EMAIL.":</td><td>".$purch_data['email']."</td></tr>\n\r";
}
if(get_option('payment_method') == 2) {
$gateway_name = '';
foreach($GLOBALS['nzshpcrt_gateways'] as $gateway) {
if($purch_data['gateway'] != 'testmode') {
if($gateway['internalname'] == $purch_data['gateway'] ) {
$gateway_name = $gateway['name'];
}
} else {
$gateway_name = "Manual Payment";
}
}
}
// echo " <tr><td colspan='2'></td></tr>\n\r";
// echo " <tr><td>".TXT_WPSC_PAYMENT_METHOD.":</td><td>".$gateway_name."</td></tr>\n\r";
// //echo " <tr><td>".TXT_WPSC_PURCHASE_NUMBER.":</td><td>".$purch_data['id']."</td></tr>\n\r";
// echo " <tr><td>".TXT_WPSC_HOWCUSTOMERFINDUS.":</td><td>".$purch_data['find_us']."</td></tr>\n\r";
// $engrave_line = explode(",",$purch_data['engravetext']);
// echo " <tr><td>".TXT_WPSC_ENGRAVE."</td><td></td></tr>\n\r";
// echo " <tr><td>".TXT_WPSC_ENGRAVE_LINE_ONE.":</td><td>".$engrave_line[0]."</td></tr>\n\r";
// echo " <tr><td>".TXT_WPSC_ENGRAVE_LINE_TWO.":</td><td>".$engrave_line[1]."</td></tr>\n\r";
// if($purch_data['transactid'] != '') {
// echo " <tr><td>".TXT_WPSC_TXN_ID.":</td><td>".$purch_data['transactid']."</td></tr>\n\r";
// }
echo "</table>\n\r";
echo "<table class='packing_slip'>";
echo "<tr>";
echo " <th>".TXT_WPSC_QUANTITY." </th>";
echo " <th>".TXT_WPSC_NAME."</th>";
echo " <th>".TXT_WPSC_PRICE." </th>";
echo " <th>".TXT_WPSC_SHIPPING." </th>";
echo '<th>Tax</th>';
echo '</tr>';
$endtotal = 0;
$all_donations = true;
$all_no_shipping = true;
$file_link_list = array();
foreach($cart_log as $cart_row) {
$alternate = "";
$j++;
if(($j % 2) != 0) {
$alternate = "class='alt'";
}
$productsql= "SELECT * FROM `".WPSC_TABLE_PRODUCT_LIST."` WHERE `id`=".$cart_row['prodid']."";
$product_data = $wpdb->get_results($productsql,ARRAY_A);
$variation_sql = "SELECT * FROM `".WPSC_TABLE_CART_ITEM_VARIATIONS."` WHERE `cart_id`='".$cart_row['id']."'";
$variation_data = $wpdb->get_results($variation_sql,ARRAY_A);
$variation_count = count($variation_data);
if($variation_count > 1) {
$variation_list = " (";
$i = 0;
foreach($variation_data as $variation) {
if($i > 0) {
$variation_list .= ", ";
}
$value_id = $variation['value_id'];
$value_data = $wpdb->get_results("SELECT * FROM `".WPSC_TABLE_VARIATION_VALUES."` WHERE `id`='".$value_id."' LIMIT 1",ARRAY_A);
$variation_list .= $value_data[0]['name'];
$i++;
}
$variation_list .= ")";
} else if($variation_count == 1) {
$value_id = $variation_data[0]['value_id'];
$value_data = $wpdb->get_results("SELECT * FROM `".WPSC_TABLE_VARIATION_VALUES."` WHERE `id`='".$value_id."' LIMIT 1",ARRAY_A);
$variation_list = " (".$value_data[0]['name'].")";
} else {
$variation_list = '';
}
if($cart_row['donation'] != 1) {
$all_donations = false;
}
if($cart_row['no_shipping'] != 1) {
$shipping = $cart_row['pnp'] * $cart_row['quantity'];
$total_shipping += $shipping;
$all_no_shipping = false;
} else {
$shipping = 0;
}
$price = $cart_row['price'] * $cart_row['quantity'];
$gst = $price - ($price / (1+($cart_row['gst'] / 100)));
if($gst > 0) {
$tax_per_item = $gst / $cart_row['quantity'];
}
echo "<tr $alternate>";
echo " <td>";
echo $cart_row['quantity'];
echo " </td>";
echo " <td>";
echo $product_data[0]['name'];
echo stripslashes($variation_list);
echo " </td>";
echo " <td>";
echo nzshpcrt_currency_display( $price, 1);
echo " </td>";
echo " <td>";
echo nzshpcrt_currency_display($shipping, 1);
echo " </td>";
echo '<td>';
echo nzshpcrt_currency_display($cart_row['tax_charged'],1);
echo '<td>';
echo '</tr>';
}
echo "</table>";
echo "</div>\n\r";
} else {
echo "<br />".TXT_WPSC_USERSCARTWASEMPTY;
}
}
function wpsc_product_item_row() {
}
?>
| alx/SimplePress | wp-content/plugins/wp-e-commerce/admin-form-functions.php | PHP | gpl-2.0 | 37,491 |
//////////////////////////////////////////////////////////////////////////////
// oxygensizegrip.cpp
// bottom right size grip for borderless windows
// -------------------
//
// Copyright (c) 2009 Hugo Pereira Da Costa <hugo.pereira@free.fr>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//////////////////////////////////////////////////////////////////////////////
#include "oxygensizegrip.h"
#include "oxygenbutton.h"
#include "oxygenclient.h"
#include <cassert>
#include <QtGui/QPainter>
#include <QtGui/QPolygon>
#include <QtCore/QTimer>
#include <QtGui/QX11Info>
#include <X11/Xlib.h>
namespace Oxygen
{
//_____________________________________________
SizeGrip::SizeGrip( Client* client ):
QWidget(0),
_client( client )
{
setAttribute(Qt::WA_NoSystemBackground );
setAutoFillBackground( false );
// cursor
setCursor( Qt::SizeFDiagCursor );
// size
setFixedSize( QSize( GRIP_SIZE, GRIP_SIZE ) );
// mask
QPolygon p;
p << QPoint( 0, GRIP_SIZE )
<< QPoint( GRIP_SIZE, 0 )
<< QPoint( GRIP_SIZE, GRIP_SIZE )
<< QPoint( 0, GRIP_SIZE );
setMask( QRegion( p ) );
// embed
embed();
updatePosition();
// event filter
client->widget()->installEventFilter( this );
// show
show();
}
//_____________________________________________
SizeGrip::~SizeGrip( void )
{}
//_____________________________________________
void SizeGrip::activeChange( void )
{ XMapRaised( QX11Info::display(), winId() ); }
//_____________________________________________
void SizeGrip::embed( void )
{
WId window_id = client().windowId();
if( client().isPreview() ) {
setParent( client().widget() );
} else if( window_id ) {
WId current = window_id;
while( true )
{
WId root, parent = 0;
WId *children = 0L;
uint child_count = 0;
XQueryTree(QX11Info::display(), current, &root, &parent, &children, &child_count);
if( parent && parent != root && parent != current ) current = parent;
else break;
}
// reparent
XReparentWindow( QX11Info::display(), winId(), current, 0, 0 );
} else {
hide();
}
}
//_____________________________________________
bool SizeGrip::eventFilter( QObject*, QEvent* event )
{
if ( event->type() == QEvent::Resize) updatePosition();
return false;
}
//_____________________________________________
void SizeGrip::paintEvent( QPaintEvent* )
{
// get relevant colors
QColor base( client().backgroundColor( this, palette(), client().isActive() ) );
QColor light( client().helper().calcDarkColor( base ) );
QColor dark( client().helper().calcDarkColor( base.darker(150) ) );
// create and configure painter
QPainter painter(this);
painter.setRenderHints(QPainter::Antialiasing );
painter.setPen( Qt::NoPen );
painter.setBrush( base );
// polygon
QPolygon p;
p << QPoint( 0, GRIP_SIZE )
<< QPoint( GRIP_SIZE, 0 )
<< QPoint( GRIP_SIZE, GRIP_SIZE )
<< QPoint( 0, GRIP_SIZE );
painter.drawPolygon( p );
// diagonal border
painter.setBrush( Qt::NoBrush );
painter.setPen( QPen( dark, 3 ) );
painter.drawLine( QPoint( 0, GRIP_SIZE ), QPoint( GRIP_SIZE, 0 ) );
// side borders
painter.setPen( QPen( light, 1.5 ) );
painter.drawLine( QPoint( 1, GRIP_SIZE ), QPoint( GRIP_SIZE, GRIP_SIZE ) );
painter.drawLine( QPoint( GRIP_SIZE, 1 ), QPoint( GRIP_SIZE, GRIP_SIZE ) );
painter.end();
}
//_____________________________________________
void SizeGrip::mousePressEvent( QMouseEvent* event )
{
switch (event->button())
{
case Qt::RightButton:
{
hide();
QTimer::singleShot(5000, this, SLOT(show()));
break;
}
case Qt::MidButton:
{
hide();
break;
}
case Qt::LeftButton:
if( rect().contains( event->pos() ) )
{
// check client window id
if( !client().windowId() ) break;
client().widget()->setFocus();
if( client().decoration() )
{ client().decoration()->performWindowOperation( KDecorationDefines::ResizeOp ); }
}
break;
default: break;
}
return;
}
//_______________________________________________________________________________
void SizeGrip::updatePosition( void )
{
QPoint position(
client().width() - GRIP_SIZE - OFFSET,
client().height() - GRIP_SIZE - OFFSET );
if( client().isPreview() )
{
position -= QPoint(
client().layoutMetric( Client::LM_BorderRight )+
client().layoutMetric( Client::LM_OuterPaddingRight ),
client().layoutMetric( Client::LM_OuterPaddingBottom )+
client().layoutMetric( Client::LM_BorderBottom )
);
} else {
position -= QPoint(
client().layoutMetric( Client::LM_BorderRight ),
client().layoutMetric( Client::LM_BorderBottom ) );
}
move( position );
}
}
| mgottschlag/kwin-tiling | kwin/clients/oxygen/oxygensizegrip.cpp | C++ | gpl-2.0 | 6,748 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace gokiTagDB
{
public class Settings
{
public static float[] zoomLevels = new float[7] { .25f, .50f, .75f, 1.0f, 1.25f, 1.5f, 2.0f };
public static int[] updateIntervals = new int[] { 15, 30, 100 };
private string fileFilter;
public string FileFilter
{
get { return fileFilter; }
set { fileFilter = value; }
}
private SortType sortType;
public SortType SortType
{
get { return sortType; }
set { sortType = value; }
}
private SelectionMode selectionMode;
public SelectionMode SelectionMode
{
get { return selectionMode; }
set { selectionMode = value; }
}
private int thumbnailWidth;
public int ThumbnailWidth
{
get { return thumbnailWidth; }
set { thumbnailWidth = value; }
}
private int thumbnailHeight;
public int ThumbnailHeight
{
get { return thumbnailHeight; }
set { thumbnailHeight = value; }
}
private int zoomIndex;
public int ZoomIndex
{
get { return zoomIndex; }
set { zoomIndex = value; }
}
private int updateInterval;
public int UpdateInterval
{
get { return updateInterval; }
set { updateInterval = value; }
}
private Padding panelPadding ;
public Padding PanelPadding
{
get { return panelPadding; }
set { panelPadding = value; }
}
private Padding entryMargin;
public Padding EntryMargin
{
get { return entryMargin; }
set { entryMargin = value; }
}
private Padding entryPadding;
public Padding EntryPadding
{
get { return entryPadding; }
set { entryPadding = value; }
}
private int borderSize;
public int BorderSize
{
get { return borderSize; }
set
{
borderSize = value;
if (borderSize < 1)
{
borderSize = 1;
}
}
}
private long approximateMemoryUsage;
public long ApproximateMemoryUsage
{
get { return approximateMemoryUsage; }
set { approximateMemoryUsage = value; }
}
private int maximumSuggestions;
public int MaximumSuggestions
{
get { return maximumSuggestions; }
set { maximumSuggestions = value; }
}
private ThumbnailGenerationMethod thumbnailGenerationMethod;
public ThumbnailGenerationMethod ThumbnailGenerationMethod
{
get { return thumbnailGenerationMethod; }
set { thumbnailGenerationMethod = value; }
}
public Settings()
{
FileFilter = @".*(\.jpeg|\.jpg|\.png|\.gif|\.bmp|\.webm)";
SortType = SortType.Location;
SelectionMode = SelectionMode.Explorer;
ThumbnailWidth = 200;
ThumbnailHeight = 200;
ZoomIndex = 3;
UpdateInterval = updateIntervals[0];
PanelPadding = new Padding(2);
EntryMargin = new Padding(1);
EntryPadding = new Padding(1);
BorderSize = 1;
ApproximateMemoryUsage = 100000000;
MaximumSuggestions = 10;
ThumbnailGenerationMethod = gokiTagDB.ThumbnailGenerationMethod.Smart;
}
}
}
| gokiburikin/gokiTagDB | gokiTagDB/Settings.cs | C# | gpl-2.0 | 3,782 |
using JBB.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JBB.DAL.EF
{
public class JBInitializer : System.Data.Entity.DropCreateDatabaseIfModelChanges<JBContext>
{
protected override void Seed(JBContext context)
{
//base.Seed(context);
var companies = new List<Company> {
new Company{Name="Haagi Mettals"},
new Company{Name="Morkels Manufacture Pty Ltd"}
};
companies.ForEach(c => context.Companies.Add(c));
context.SaveChanges();
var offers = new List<Offer>
{
new Offer{Company=companies[0],ShortDescription="Motor Maintenance", LongDescription="A student is required to maintain electric motors for the companies manufacturing division."},
new Offer{Company=companies[0], ShortDescription="Quality Assurance", LongDescription="A student is required to test the diameter of the product. Tcl/Tk and basic electronic skills (soldering) required."},
new Offer{Company=companies[1], ShortDescription="Lathe Operator", LongDescription="Partime work to earn some extras cash by operating a lathe in our furniture workshop in Doornfontein."}
};
offers.ForEach(o => context.Offers.Add(o));
context.SaveChanges();
}
}
}
| relyah/JB | JobBourseBackend/JBB.DAL.EF/JBInitializer.cs | C# | gpl-2.0 | 1,266 |
package com.tachys.moneyshare.dataaccess.db.contracts;
import android.provider.BaseColumns;
public class SettlementContract {
public SettlementContract() {
}
public static class SettlementEntry implements BaseColumns {
public static final String TABLE_NAME = "settlement";
public static final String COLUMN_NAME_PAYERID = "payer";
public static final String COLUMN_NAME_PAYEEID = "payee";
public static final String COLUMN_NAME_AMOUNT = "amount";
}
}
| StrawHatPirates/MoneyShare | src/app/src/main/java/com/tachys/moneyshare/dataaccess/db/contracts/SettlementContract.java | Java | gpl-2.0 | 502 |
<?php
namespace UmnLib\Core\XmlRecord;
class NlmCatalog extends Record
{
// Must be an id type that uniquely identifies the record,
// usually the record-creating organization's id.
public static function primaryIdType()
{
return 'nlm';
}
// Must return array( 'type' => $type, 'value' => $value ) pairs.
public function ids()
{
if (!isset($this->ids)) {
// output
$ids = array();
$array = $this->asArray();
// TODO: Not sure this array key lookup will work with Titon...
$nlmUniqueId = $array['NlmUniqueID'];
$ids[] = array('type' => 'nlm', 'value' => $nlmUniqueId);
if (array_key_exists('OtherID', $array)) {
$otherIds = $array['OtherID'];
if (!array_key_exists(0, $otherIds)) {
$otherIds = array($otherIds);
}
foreach ($otherIds as $otherId) {
if ('OCLC' == $otherId['attributes']['Source']) {
$oclcId = trim($otherId['value']);
// For some goofy reason, some of the OCLC ids are prefixed with 'ocm':
$oclcId = preg_replace('/^ocm/', '', $oclcId);
$ids[] = array('type' => 'oclc', 'value' => $oclcId);
}
}
}
$this->ids = $ids;
}
return $this->ids;
}
}
| UMNLibraries/xml-record-php | src/NlmCatalog.php | PHP | gpl-2.0 | 1,268 |
my_inf = float('Inf')
print 99999999 > my_inf
# False
my_neg_inf = float('-Inf')
print my_neg_inf < -99999999
# True
| jabbalaci/PrimCom | data/python/infinity.py | Python | gpl-2.0 | 118 |
/* ----------------------------------------------------------------------
LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator
http://lammps.sandia.gov, Sandia National Laboratories
Steve Plimpton, sjplimp@sandia.gov
Copyright (2003) Sandia Corporation. Under the terms of Contract
DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains
certain rights in this software. This software is distributed under
the GNU General Public License.
See the README file in the top-level LAMMPS directory.
------------------------------------------------------------------------- */
#include "fix_rigid.h"
#include <mpi.h>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include "math_extra.h"
#include "atom.h"
#include "atom_vec_ellipsoid.h"
#include "atom_vec_line.h"
#include "atom_vec_tri.h"
#include "domain.h"
#include "update.h"
#include "respa.h"
#include "modify.h"
#include "group.h"
#include "comm.h"
#include "random_mars.h"
#include "force.h"
#include "input.h"
#include "variable.h"
#include "math_const.h"
#include "memory.h"
#include "error.h"
#include "rigid_const.h"
using namespace LAMMPS_NS;
using namespace FixConst;
using namespace MathConst;
using namespace RigidConst;
/* ---------------------------------------------------------------------- */
FixRigid::FixRigid(LAMMPS *lmp, int narg, char **arg) :
Fix(lmp, narg, arg), step_respa(NULL),
inpfile(NULL), nrigid(NULL), mol2body(NULL), body2mol(NULL),
body(NULL), displace(NULL), masstotal(NULL), xcm(NULL),
vcm(NULL), fcm(NULL), inertia(NULL), ex_space(NULL),
ey_space(NULL), ez_space(NULL), angmom(NULL), omega(NULL),
torque(NULL), quat(NULL), imagebody(NULL), fflag(NULL),
tflag(NULL), langextra(NULL), sum(NULL), all(NULL),
remapflag(NULL), xcmimage(NULL), eflags(NULL), orient(NULL),
dorient(NULL), id_dilate(NULL), id_gravity(NULL), random(NULL),
avec_ellipsoid(NULL), avec_line(NULL), avec_tri(NULL)
{
int i,ibody;
scalar_flag = 1;
extscalar = 0;
time_integrate = 1;
rigid_flag = 1;
virial_flag = 1;
thermo_virial = 1;
create_attribute = 1;
dof_flag = 1;
enforce2d_flag = 1;
MPI_Comm_rank(world,&me);
MPI_Comm_size(world,&nprocs);
// perform initial allocation of atom-based arrays
// register with Atom class
extended = orientflag = dorientflag = 0;
body = NULL;
xcmimage = NULL;
displace = NULL;
eflags = NULL;
orient = NULL;
dorient = NULL;
grow_arrays(atom->nmax);
atom->add_callback(0);
// parse args for rigid body specification
// set nbody and body[i] for each atom
if (narg < 4) error->all(FLERR,"Illegal fix rigid command");
int iarg;
mol2body = NULL;
body2mol = NULL;
// single rigid body
// nbody = 1
// all atoms in fix group are part of body
if (strcmp(arg[3],"single") == 0) {
rstyle = SINGLE;
iarg = 4;
nbody = 1;
int *mask = atom->mask;
int nlocal = atom->nlocal;
for (i = 0; i < nlocal; i++) {
body[i] = -1;
if (mask[i] & groupbit) body[i] = 0;
}
// each molecule in fix group is a rigid body
// maxmol = largest molecule ID
// ncount = # of atoms in each molecule (have to sum across procs)
// nbody = # of non-zero ncount values
// use nall as incremented ptr to set body[] values for each atom
} else if (strcmp(arg[3],"molecule") == 0 || strcmp(arg[3],"custom") == 0) {
rstyle = MOLECULE;
tagint *molecule;
int *mask = atom->mask;
int nlocal = atom->nlocal;
int custom_flag = strcmp(arg[3],"custom") == 0;
if (custom_flag) {
if (narg < 5) error->all(FLERR,"Illegal fix rigid command");
// determine whether atom-style variable or atom property is used
if (strstr(arg[4],"i_") == arg[4]) {
int is_double=0;
int custom_index = atom->find_custom(arg[4]+2,is_double);
if (custom_index == -1)
error->all(FLERR,"Fix rigid custom requires "
"previously defined property/atom");
else if (is_double)
error->all(FLERR,"Fix rigid custom requires "
"integer-valued property/atom");
int minval = INT_MAX;
int *value = atom->ivector[custom_index];
for (i = 0; i < nlocal; i++)
if (mask[i] & groupbit) minval = MIN(minval,value[i]);
int vmin = minval;
MPI_Allreduce(&vmin,&minval,1,MPI_INT,MPI_MIN,world);
molecule = new tagint[nlocal];
for (i = 0; i < nlocal; i++)
if (mask[i] & groupbit)
molecule[i] = (tagint)(value[i] - minval + 1);
else
molecule[i] = 0;
} else if (strstr(arg[4],"v_") == arg[4]) {
int ivariable = input->variable->find(arg[4]+2);
if (ivariable < 0)
error->all(FLERR,"Variable name for fix rigid custom does not exist");
if (input->variable->atomstyle(ivariable) == 0)
error->all(FLERR,"Fix rigid custom variable is no atom-style variable");
double *value = new double[nlocal];
input->variable->compute_atom(ivariable,0,value,1,0);
int minval = INT_MAX;
for (i = 0; i < nlocal; i++)
if (mask[i] & groupbit) minval = MIN(minval,(int)value[i]);
int vmin = minval;
MPI_Allreduce(&vmin,&minval,1,MPI_INT,MPI_MIN,world);
molecule = new tagint[nlocal];
for (i = 0; i < nlocal; i++)
if (mask[i] & groupbit)
molecule[i] = (tagint)((tagint)value[i] - minval + 1);
delete[] value;
} else error->all(FLERR,"Unsupported fix rigid custom property");
} else {
if (atom->molecule_flag == 0)
error->all(FLERR,"Fix rigid molecule requires atom attribute molecule");
molecule = atom->molecule;
}
iarg = 4 + custom_flag;
tagint maxmol_tag = -1;
for (i = 0; i < nlocal; i++)
if (mask[i] & groupbit) maxmol_tag = MAX(maxmol_tag,molecule[i]);
tagint itmp;
MPI_Allreduce(&maxmol_tag,&itmp,1,MPI_LMP_TAGINT,MPI_MAX,world);
if (itmp+1 > MAXSMALLINT)
error->all(FLERR,"Too many molecules for fix rigid");
maxmol = (int) itmp;
int *ncount;
memory->create(ncount,maxmol+1,"rigid:ncount");
for (i = 0; i <= maxmol; i++) ncount[i] = 0;
for (i = 0; i < nlocal; i++)
if (mask[i] & groupbit) ncount[molecule[i]]++;
memory->create(mol2body,maxmol+1,"rigid:mol2body");
MPI_Allreduce(ncount,mol2body,maxmol+1,MPI_INT,MPI_SUM,world);
nbody = 0;
for (i = 0; i <= maxmol; i++)
if (mol2body[i]) mol2body[i] = nbody++;
else mol2body[i] = -1;
memory->create(body2mol,nbody,"rigid:body2mol");
nbody = 0;
for (i = 0; i <= maxmol; i++)
if (mol2body[i] >= 0) body2mol[nbody++] = i;
for (i = 0; i < nlocal; i++) {
body[i] = -1;
if (mask[i] & groupbit) body[i] = mol2body[molecule[i]];
}
memory->destroy(ncount);
if (custom_flag) delete [] molecule;
// each listed group is a rigid body
// check if all listed groups exist
// an atom must belong to fix group and listed group to be in rigid body
// error if atom belongs to more than 1 rigid body
} else if (strcmp(arg[3],"group") == 0) {
if (narg < 5) error->all(FLERR,"Illegal fix rigid command");
rstyle = GROUP;
nbody = force->inumeric(FLERR,arg[4]);
if (nbody <= 0) error->all(FLERR,"Illegal fix rigid command");
if (narg < 5+nbody) error->all(FLERR,"Illegal fix rigid command");
iarg = 5+nbody;
int *igroups = new int[nbody];
for (ibody = 0; ibody < nbody; ibody++) {
igroups[ibody] = group->find(arg[5+ibody]);
if (igroups[ibody] == -1)
error->all(FLERR,"Could not find fix rigid group ID");
}
int *mask = atom->mask;
int nlocal = atom->nlocal;
int flag = 0;
for (i = 0; i < nlocal; i++) {
body[i] = -1;
if (mask[i] & groupbit)
for (ibody = 0; ibody < nbody; ibody++)
if (mask[i] & group->bitmask[igroups[ibody]]) {
if (body[i] >= 0) flag = 1;
body[i] = ibody;
}
}
int flagall;
MPI_Allreduce(&flag,&flagall,1,MPI_INT,MPI_SUM,world);
if (flagall)
error->all(FLERR,"One or more atoms belong to multiple rigid bodies");
delete [] igroups;
} else error->all(FLERR,"Illegal fix rigid command");
// error check on nbody
if (nbody == 0) error->all(FLERR,"No rigid bodies defined");
// create all nbody-length arrays
memory->create(nrigid,nbody,"rigid:nrigid");
memory->create(masstotal,nbody,"rigid:masstotal");
memory->create(xcm,nbody,3,"rigid:xcm");
memory->create(vcm,nbody,3,"rigid:vcm");
memory->create(fcm,nbody,3,"rigid:fcm");
memory->create(inertia,nbody,3,"rigid:inertia");
memory->create(ex_space,nbody,3,"rigid:ex_space");
memory->create(ey_space,nbody,3,"rigid:ey_space");
memory->create(ez_space,nbody,3,"rigid:ez_space");
memory->create(angmom,nbody,3,"rigid:angmom");
memory->create(omega,nbody,3,"rigid:omega");
memory->create(torque,nbody,3,"rigid:torque");
memory->create(quat,nbody,4,"rigid:quat");
memory->create(imagebody,nbody,"rigid:imagebody");
memory->create(fflag,nbody,3,"rigid:fflag");
memory->create(tflag,nbody,3,"rigid:tflag");
memory->create(langextra,nbody,6,"rigid:langextra");
memory->create(sum,nbody,6,"rigid:sum");
memory->create(all,nbody,6,"rigid:all");
memory->create(remapflag,nbody,4,"rigid:remapflag");
// initialize force/torque flags to default = 1.0
// for 2d: fz, tx, ty = 0.0
array_flag = 1;
size_array_rows = nbody;
size_array_cols = 15;
global_freq = 1;
extarray = 0;
for (i = 0; i < nbody; i++) {
fflag[i][0] = fflag[i][1] = fflag[i][2] = 1.0;
tflag[i][0] = tflag[i][1] = tflag[i][2] = 1.0;
if (domain->dimension == 2) fflag[i][2] = tflag[i][0] = tflag[i][1] = 0.0;
}
// number of linear rigid bodies is counted later
nlinear = 0;
// parse optional args
int seed;
langflag = 0;
reinitflag = 1;
tstat_flag = 0;
pstat_flag = 0;
allremap = 1;
t_chain = 10;
t_iter = 1;
t_order = 3;
p_chain = 10;
inpfile = NULL;
id_gravity = NULL;
id_dilate = NULL;
pcouple = NONE;
pstyle = ANISO;
dimension = domain->dimension;
for (int i = 0; i < 3; i++) {
p_start[i] = p_stop[i] = p_period[i] = 0.0;
p_flag[i] = 0;
}
while (iarg < narg) {
if (strcmp(arg[iarg],"force") == 0) {
if (iarg+5 > narg) error->all(FLERR,"Illegal fix rigid command");
int mlo,mhi;
force->bounds(FLERR,arg[iarg+1],nbody,mlo,mhi);
double xflag,yflag,zflag;
if (strcmp(arg[iarg+2],"off") == 0) xflag = 0.0;
else if (strcmp(arg[iarg+2],"on") == 0) xflag = 1.0;
else error->all(FLERR,"Illegal fix rigid command");
if (strcmp(arg[iarg+3],"off") == 0) yflag = 0.0;
else if (strcmp(arg[iarg+3],"on") == 0) yflag = 1.0;
else error->all(FLERR,"Illegal fix rigid command");
if (strcmp(arg[iarg+4],"off") == 0) zflag = 0.0;
else if (strcmp(arg[iarg+4],"on") == 0) zflag = 1.0;
else error->all(FLERR,"Illegal fix rigid command");
if (domain->dimension == 2 && zflag == 1.0)
error->all(FLERR,"Fix rigid z force cannot be on for 2d simulation");
int count = 0;
for (int m = mlo; m <= mhi; m++) {
fflag[m-1][0] = xflag;
fflag[m-1][1] = yflag;
fflag[m-1][2] = zflag;
count++;
}
if (count == 0) error->all(FLERR,"Illegal fix rigid command");
iarg += 5;
} else if (strcmp(arg[iarg],"torque") == 0) {
if (iarg+5 > narg) error->all(FLERR,"Illegal fix rigid command");
int mlo,mhi;
force->bounds(FLERR,arg[iarg+1],nbody,mlo,mhi);
double xflag,yflag,zflag;
if (strcmp(arg[iarg+2],"off") == 0) xflag = 0.0;
else if (strcmp(arg[iarg+2],"on") == 0) xflag = 1.0;
else error->all(FLERR,"Illegal fix rigid command");
if (strcmp(arg[iarg+3],"off") == 0) yflag = 0.0;
else if (strcmp(arg[iarg+3],"on") == 0) yflag = 1.0;
else error->all(FLERR,"Illegal fix rigid command");
if (strcmp(arg[iarg+4],"off") == 0) zflag = 0.0;
else if (strcmp(arg[iarg+4],"on") == 0) zflag = 1.0;
else error->all(FLERR,"Illegal fix rigid command");
if (domain->dimension == 2 && (xflag == 1.0 || yflag == 1.0))
error->all(FLERR,"Fix rigid xy torque cannot be on for 2d simulation");
int count = 0;
for (int m = mlo; m <= mhi; m++) {
tflag[m-1][0] = xflag;
tflag[m-1][1] = yflag;
tflag[m-1][2] = zflag;
count++;
}
if (count == 0) error->all(FLERR,"Illegal fix rigid command");
iarg += 5;
} else if (strcmp(arg[iarg],"langevin") == 0) {
if (iarg+5 > narg) error->all(FLERR,"Illegal fix rigid command");
if (strcmp(style,"rigid") != 0 && strcmp(style,"rigid/nve") != 0 &&
strcmp(style,"rigid/omp") != 0 && strcmp(style,"rigid/nve/omp") != 0)
error->all(FLERR,"Illegal fix rigid command");
langflag = 1;
t_start = force->numeric(FLERR,arg[iarg+1]);
t_stop = force->numeric(FLERR,arg[iarg+2]);
t_period = force->numeric(FLERR,arg[iarg+3]);
seed = force->inumeric(FLERR,arg[iarg+4]);
if (t_period <= 0.0)
error->all(FLERR,"Fix rigid langevin period must be > 0.0");
if (seed <= 0) error->all(FLERR,"Illegal fix rigid command");
iarg += 5;
} else if (strcmp(arg[iarg],"temp") == 0) {
if (iarg+4 > narg) error->all(FLERR,"Illegal fix rigid command");
if (strcmp(style,"rigid/nvt") != 0 && strcmp(style,"rigid/npt") != 0 &&
strcmp(style,"rigid/nvt/omp") != 0 &&
strcmp(style,"rigid/npt/omp") != 0)
error->all(FLERR,"Illegal fix rigid command");
tstat_flag = 1;
t_start = force->numeric(FLERR,arg[iarg+1]);
t_stop = force->numeric(FLERR,arg[iarg+2]);
t_period = force->numeric(FLERR,arg[iarg+3]);
iarg += 4;
} else if (strcmp(arg[iarg],"iso") == 0) {
if (iarg+4 > narg) error->all(FLERR,"Illegal fix rigid command");
if (strcmp(style,"rigid/npt") != 0 && strcmp(style,"rigid/nph") != 0 &&
strcmp(style,"rigid/npt/omp") != 0 &&
strcmp(style,"rigid/nph/omp") != 0)
error->all(FLERR,"Illegal fix rigid command");
pcouple = XYZ;
p_start[0] = p_start[1] = p_start[2] = force->numeric(FLERR,arg[iarg+1]);
p_stop[0] = p_stop[1] = p_stop[2] = force->numeric(FLERR,arg[iarg+2]);
p_period[0] = p_period[1] = p_period[2] =
force->numeric(FLERR,arg[iarg+3]);
p_flag[0] = p_flag[1] = p_flag[2] = 1;
if (dimension == 2) {
p_start[2] = p_stop[2] = p_period[2] = 0.0;
p_flag[2] = 0;
}
iarg += 4;
} else if (strcmp(arg[iarg],"aniso") == 0) {
if (iarg+4 > narg) error->all(FLERR,"Illegal fix rigid command");
if (strcmp(style,"rigid/npt") != 0 && strcmp(style,"rigid/nph") != 0 &&
strcmp(style,"rigid/npt/omp") != 0 &&
strcmp(style,"rigid/nph/omp") != 0)
error->all(FLERR,"Illegal fix rigid command");
p_start[0] = p_start[1] = p_start[2] = force->numeric(FLERR,arg[iarg+1]);
p_stop[0] = p_stop[1] = p_stop[2] = force->numeric(FLERR,arg[iarg+2]);
p_period[0] = p_period[1] = p_period[2] =
force->numeric(FLERR,arg[iarg+3]);
p_flag[0] = p_flag[1] = p_flag[2] = 1;
if (dimension == 2) {
p_start[2] = p_stop[2] = p_period[2] = 0.0;
p_flag[2] = 0;
}
iarg += 4;
} else if (strcmp(arg[iarg],"x") == 0) {
if (iarg+4 > narg) error->all(FLERR,"Illegal fix rigid command");
if (strcmp(style,"rigid/npt") != 0 && strcmp(style,"rigid/nph") != 0 &&
strcmp(style,"rigid/npt/omp") != 0 &&
strcmp(style,"rigid/nph/omp") != 0)
error->all(FLERR,"Illegal fix rigid command");
p_start[0] = force->numeric(FLERR,arg[iarg+1]);
p_stop[0] = force->numeric(FLERR,arg[iarg+2]);
p_period[0] = force->numeric(FLERR,arg[iarg+3]);
p_flag[0] = 1;
iarg += 4;
} else if (strcmp(arg[iarg],"y") == 0) {
if (iarg+4 > narg) error->all(FLERR,"Illegal fix rigid command");
if (strcmp(style,"rigid/npt") != 0 && strcmp(style,"rigid/nph") != 0 &&
strcmp(style,"rigid/npt/omp") != 0 &&
strcmp(style,"rigid/nph/omp") != 0)
error->all(FLERR,"Illegal fix rigid command");
p_start[1] = force->numeric(FLERR,arg[iarg+1]);
p_stop[1] = force->numeric(FLERR,arg[iarg+2]);
p_period[1] = force->numeric(FLERR,arg[iarg+3]);
p_flag[1] = 1;
iarg += 4;
} else if (strcmp(arg[iarg],"z") == 0) {
if (iarg+4 > narg) error->all(FLERR,"Illegal fix rigid command");
if (strcmp(style,"rigid/npt") != 0 && strcmp(style,"rigid/nph") != 0 &&
strcmp(style,"rigid/npt/omp") != 0 &&
strcmp(style,"rigid/nph/omp") != 0)
error->all(FLERR,"Illegal fix rigid command");
p_start[2] = force->numeric(FLERR,arg[iarg+1]);
p_stop[2] = force->numeric(FLERR,arg[iarg+2]);
p_period[2] = force->numeric(FLERR,arg[iarg+3]);
p_flag[2] = 1;
iarg += 4;
} else if (strcmp(arg[iarg],"couple") == 0) {
if (iarg+2 > narg) error->all(FLERR,"Illegal fix rigid command");
if (strcmp(arg[iarg+1],"xyz") == 0) pcouple = XYZ;
else if (strcmp(arg[iarg+1],"xy") == 0) pcouple = XY;
else if (strcmp(arg[iarg+1],"yz") == 0) pcouple = YZ;
else if (strcmp(arg[iarg+1],"xz") == 0) pcouple = XZ;
else if (strcmp(arg[iarg+1],"none") == 0) pcouple = NONE;
else error->all(FLERR,"Illegal fix rigid command");
iarg += 2;
} else if (strcmp(arg[iarg],"dilate") == 0) {
if (iarg+2 > narg)
error->all(FLERR,"Illegal fix rigid npt/nph command");
if (strcmp(arg[iarg+1],"all") == 0) allremap = 1;
else {
allremap = 0;
delete [] id_dilate;
int n = strlen(arg[iarg+1]) + 1;
id_dilate = new char[n];
strcpy(id_dilate,arg[iarg+1]);
int idilate = group->find(id_dilate);
if (idilate == -1)
error->all(FLERR,
"Fix rigid npt/nph dilate group ID does not exist");
}
iarg += 2;
} else if (strcmp(arg[iarg],"tparam") == 0) {
if (iarg+4 > narg) error->all(FLERR,"Illegal fix rigid command");
if (strcmp(style,"rigid/nvt") != 0 && strcmp(style,"rigid/npt") != 0 &&
strcmp(style,"rigid/nvt/omp") != 0 &&
strcmp(style,"rigid/npt/omp") != 0)
error->all(FLERR,"Illegal fix rigid command");
t_chain = force->inumeric(FLERR,arg[iarg+1]);
t_iter = force->inumeric(FLERR,arg[iarg+2]);
t_order = force->inumeric(FLERR,arg[iarg+3]);
iarg += 4;
} else if (strcmp(arg[iarg],"pchain") == 0) {
if (iarg+2 > narg) error->all(FLERR,"Illegal fix rigid command");
if (strcmp(style,"rigid/npt") != 0 && strcmp(style,"rigid/nph") != 0 &&
strcmp(style,"rigid/npt/omp") != 0 &&
strcmp(style,"rigid/nph/omp") != 0)
error->all(FLERR,"Illegal fix rigid command");
p_chain = force->inumeric(FLERR,arg[iarg+1]);
iarg += 2;
} else if (strcmp(arg[iarg],"infile") == 0) {
if (iarg+2 > narg) error->all(FLERR,"Illegal fix rigid command");
delete [] inpfile;
int n = strlen(arg[iarg+1]) + 1;
inpfile = new char[n];
strcpy(inpfile,arg[iarg+1]);
restart_file = 1;
reinitflag = 0;
iarg += 2;
} else if (strcmp(arg[iarg],"reinit") == 0) {
if (iarg+2 > narg) error->all(FLERR,"Illegal fix rigid command");
if (strcmp("yes",arg[iarg+1]) == 0) reinitflag = 1;
else if (strcmp("no",arg[iarg+1]) == 0) reinitflag = 0;
else error->all(FLERR,"Illegal fix rigid command");
iarg += 2;
} else if (strcmp(arg[iarg],"gravity") == 0) {
if (iarg+2 > narg) error->all(FLERR,"Illegal fix rigid command");
delete [] id_gravity;
int n = strlen(arg[iarg+1]) + 1;
id_gravity = new char[n];
strcpy(id_gravity,arg[iarg+1]);
iarg += 2;
} else error->all(FLERR,"Illegal fix rigid command");
}
// set pstat_flag
pstat_flag = 0;
for (int i = 0; i < 3; i++)
if (p_flag[i]) pstat_flag = 1;
if (pcouple == XYZ || (dimension == 2 && pcouple == XY)) pstyle = ISO;
else pstyle = ANISO;
// initialize Marsaglia RNG with processor-unique seed
if (langflag) random = new RanMars(lmp,seed + me);
else random = NULL;
// initialize vector output quantities in case accessed before run
for (i = 0; i < nbody; i++) {
xcm[i][0] = xcm[i][1] = xcm[i][2] = 0.0;
vcm[i][0] = vcm[i][1] = vcm[i][2] = 0.0;
fcm[i][0] = fcm[i][1] = fcm[i][2] = 0.0;
torque[i][0] = torque[i][1] = torque[i][2] = 0.0;
}
// nrigid[n] = # of atoms in Nth rigid body
// error if one or zero atoms
int *ncount = new int[nbody];
for (ibody = 0; ibody < nbody; ibody++) ncount[ibody] = 0;
int nlocal = atom->nlocal;
for (i = 0; i < nlocal; i++)
if (body[i] >= 0) ncount[body[i]]++;
MPI_Allreduce(ncount,nrigid,nbody,MPI_INT,MPI_SUM,world);
delete [] ncount;
for (ibody = 0; ibody < nbody; ibody++)
if (nrigid[ibody] <= 1) error->all(FLERR,"One or zero atoms in rigid body");
// wait to setup bodies until first init() using current atom properties
setupflag = 0;
// compute per body forces and torques at final_integrate() by default
earlyflag = 0;
// print statistics
int nsum = 0;
for (ibody = 0; ibody < nbody; ibody++) nsum += nrigid[ibody];
if (me == 0) {
if (screen) fprintf(screen,"%d rigid bodies with %d atoms\n",nbody,nsum);
if (logfile) fprintf(logfile,"%d rigid bodies with %d atoms\n",nbody,nsum);
}
}
/* ---------------------------------------------------------------------- */
FixRigid::~FixRigid()
{
// unregister callbacks to this fix from Atom class
atom->delete_callback(id,0);
delete random;
delete [] inpfile;
delete [] id_dilate;
delete [] id_gravity;
memory->destroy(mol2body);
memory->destroy(body2mol);
// delete locally stored per-atom arrays
memory->destroy(body);
memory->destroy(xcmimage);
memory->destroy(displace);
memory->destroy(eflags);
memory->destroy(orient);
memory->destroy(dorient);
// delete nbody-length arrays
memory->destroy(nrigid);
memory->destroy(masstotal);
memory->destroy(xcm);
memory->destroy(vcm);
memory->destroy(fcm);
memory->destroy(inertia);
memory->destroy(ex_space);
memory->destroy(ey_space);
memory->destroy(ez_space);
memory->destroy(angmom);
memory->destroy(omega);
memory->destroy(torque);
memory->destroy(quat);
memory->destroy(imagebody);
memory->destroy(fflag);
memory->destroy(tflag);
memory->destroy(langextra);
memory->destroy(sum);
memory->destroy(all);
memory->destroy(remapflag);
}
/* ---------------------------------------------------------------------- */
int FixRigid::setmask()
{
int mask = 0;
mask |= INITIAL_INTEGRATE;
mask |= FINAL_INTEGRATE;
if (langflag) mask |= POST_FORCE;
mask |= PRE_NEIGHBOR;
mask |= INITIAL_INTEGRATE_RESPA;
mask |= FINAL_INTEGRATE_RESPA;
return mask;
}
/* ---------------------------------------------------------------------- */
void FixRigid::init()
{
int i,ibody;
triclinic = domain->triclinic;
// atom style pointers to particles that store extra info
avec_ellipsoid = (AtomVecEllipsoid *) atom->style_match("ellipsoid");
avec_line = (AtomVecLine *) atom->style_match("line");
avec_tri = (AtomVecTri *) atom->style_match("tri");
// warn if more than one rigid fix
// if earlyflag, warn if any post-force fixes come after a rigid fix
int count = 0;
for (i = 0; i < modify->nfix; i++)
if (modify->fix[i]->rigid_flag) count++;
if (count > 1 && me == 0) error->warning(FLERR,"More than one fix rigid");
if (earlyflag) {
int rflag = 0;
for (i = 0; i < modify->nfix; i++) {
if (modify->fix[i]->rigid_flag) rflag = 1;
if (rflag && (modify->fmask[i] & POST_FORCE) &&
!modify->fix[i]->rigid_flag) {
char str[128];
snprintf(str,128,"Fix %s alters forces after fix rigid",
modify->fix[i]->id);
error->warning(FLERR,str);
}
}
}
// warn if body properties are read from inpfile
// and the gravity keyword is not set and a gravity fix exists
// this could mean body particles are overlapped
// and gravity is not applied correctly
if (inpfile && !id_gravity) {
for (i = 0; i < modify->nfix; i++) {
if (strcmp(modify->fix[i]->style,"gravity") == 0) {
if (comm->me == 0)
error->warning(FLERR,"Gravity may not be correctly applied "
"to rigid bodies if they consist of "
"overlapped particles");
break;
}
}
}
// error if npt,nph fix comes before rigid fix
for (i = 0; i < modify->nfix; i++) {
if (strcmp(modify->fix[i]->style,"npt") == 0) break;
if (strcmp(modify->fix[i]->style,"nph") == 0) break;
}
if (i < modify->nfix) {
for (int j = i; j < modify->nfix; j++)
if (strcmp(modify->fix[j]->style,"rigid") == 0)
error->all(FLERR,"Rigid fix must come before NPT/NPH fix");
}
// add gravity forces based on gravity vector from fix
if (id_gravity) {
int ifix = modify->find_fix(id_gravity);
if (ifix < 0) error->all(FLERR,"Fix rigid cannot find fix gravity ID");
if (strcmp(modify->fix[ifix]->style,"gravity") != 0)
error->all(FLERR,"Fix rigid gravity fix is invalid");
int tmp;
gvec = (double *) modify->fix[ifix]->extract("gvec",tmp);
}
// timestep info
dtv = update->dt;
dtf = 0.5 * update->dt * force->ftm2v;
dtq = 0.5 * update->dt;
if (strstr(update->integrate_style,"respa"))
step_respa = ((Respa *) update->integrate)->step;
// setup rigid bodies, using current atom info. if reinitflag is not set,
// do the initialization only once, b/c properties may not be re-computable
// especially if overlapping particles.
// do not do dynamic init if read body properties from inpfile.
// this is b/c the inpfile defines the static and dynamic properties and may
// not be computable if contain overlapping particles.
// setup_bodies_static() reads inpfile itself
if (reinitflag || !setupflag) {
setup_bodies_static();
if (!inpfile) setup_bodies_dynamic();
setupflag = 1;
}
// temperature scale factor
double ndof = 0.0;
for (ibody = 0; ibody < nbody; ibody++) {
ndof += fflag[ibody][0] + fflag[ibody][1] + fflag[ibody][2];
ndof += tflag[ibody][0] + tflag[ibody][1] + tflag[ibody][2];
}
ndof -= nlinear;
if (ndof > 0.0) tfactor = force->mvv2e / (ndof * force->boltz);
else tfactor = 0.0;
}
/* ----------------------------------------------------------------------
invoke pre_neighbor() to insure body xcmimage flags are reset
needed if Verlet::setup::pbc() has remapped/migrated atoms for 2nd run
------------------------------------------------------------------------- */
void FixRigid::setup_pre_neighbor()
{
pre_neighbor();
}
/* ----------------------------------------------------------------------
compute initial fcm and torque on bodies, also initial virial
reset all particle velocities to be consistent with vcm and omega
------------------------------------------------------------------------- */
void FixRigid::setup(int vflag)
{
int i,n,ibody;
// fcm = force on center-of-mass of each rigid body
double **f = atom->f;
int nlocal = atom->nlocal;
for (ibody = 0; ibody < nbody; ibody++)
for (i = 0; i < 6; i++) sum[ibody][i] = 0.0;
for (i = 0; i < nlocal; i++) {
if (body[i] < 0) continue;
ibody = body[i];
sum[ibody][0] += f[i][0];
sum[ibody][1] += f[i][1];
sum[ibody][2] += f[i][2];
}
MPI_Allreduce(sum[0],all[0],6*nbody,MPI_DOUBLE,MPI_SUM,world);
for (ibody = 0; ibody < nbody; ibody++) {
fcm[ibody][0] = all[ibody][0];
fcm[ibody][1] = all[ibody][1];
fcm[ibody][2] = all[ibody][2];
}
// torque = torque on each rigid body
double **x = atom->x;
double dx,dy,dz;
double unwrap[3];
for (ibody = 0; ibody < nbody; ibody++)
for (i = 0; i < 6; i++) sum[ibody][i] = 0.0;
for (i = 0; i < nlocal; i++) {
if (body[i] < 0) continue;
ibody = body[i];
domain->unmap(x[i],xcmimage[i],unwrap);
dx = unwrap[0] - xcm[ibody][0];
dy = unwrap[1] - xcm[ibody][1];
dz = unwrap[2] - xcm[ibody][2];
sum[ibody][0] += dy * f[i][2] - dz * f[i][1];
sum[ibody][1] += dz * f[i][0] - dx * f[i][2];
sum[ibody][2] += dx * f[i][1] - dy * f[i][0];
}
// extended particles add their torque to torque of body
if (extended) {
double **torque_one = atom->torque;
for (i = 0; i < nlocal; i++) {
if (body[i] < 0) continue;
ibody = body[i];
if (eflags[i] & TORQUE) {
sum[ibody][0] += torque_one[i][0];
sum[ibody][1] += torque_one[i][1];
sum[ibody][2] += torque_one[i][2];
}
}
}
MPI_Allreduce(sum[0],all[0],6*nbody,MPI_DOUBLE,MPI_SUM,world);
for (ibody = 0; ibody < nbody; ibody++) {
torque[ibody][0] = all[ibody][0];
torque[ibody][1] = all[ibody][1];
torque[ibody][2] = all[ibody][2];
}
// zero langextra in case Langevin thermostat not used
// no point to calling post_force() here since langextra
// is only added to fcm/torque in final_integrate()
for (ibody = 0; ibody < nbody; ibody++)
for (i = 0; i < 6; i++) langextra[ibody][i] = 0.0;
// virial setup before call to set_v
if (vflag) v_setup(vflag);
else evflag = 0;
// set velocities from angmom & omega
for (ibody = 0; ibody < nbody; ibody++)
MathExtra::angmom_to_omega(angmom[ibody],ex_space[ibody],ey_space[ibody],
ez_space[ibody],inertia[ibody],omega[ibody]);
set_v();
// guesstimate virial as 2x the set_v contribution
if (vflag_global)
for (n = 0; n < 6; n++) virial[n] *= 2.0;
if (vflag_atom) {
for (i = 0; i < nlocal; i++)
for (n = 0; n < 6; n++)
vatom[i][n] *= 2.0;
}
}
/* ---------------------------------------------------------------------- */
void FixRigid::initial_integrate(int vflag)
{
double dtfm;
for (int ibody = 0; ibody < nbody; ibody++) {
// update vcm by 1/2 step
dtfm = dtf / masstotal[ibody];
vcm[ibody][0] += dtfm * fcm[ibody][0] * fflag[ibody][0];
vcm[ibody][1] += dtfm * fcm[ibody][1] * fflag[ibody][1];
vcm[ibody][2] += dtfm * fcm[ibody][2] * fflag[ibody][2];
// update xcm by full step
xcm[ibody][0] += dtv * vcm[ibody][0];
xcm[ibody][1] += dtv * vcm[ibody][1];
xcm[ibody][2] += dtv * vcm[ibody][2];
// update angular momentum by 1/2 step
angmom[ibody][0] += dtf * torque[ibody][0] * tflag[ibody][0];
angmom[ibody][1] += dtf * torque[ibody][1] * tflag[ibody][1];
angmom[ibody][2] += dtf * torque[ibody][2] * tflag[ibody][2];
// compute omega at 1/2 step from angmom at 1/2 step and current q
// update quaternion a full step via Richardson iteration
// returns new normalized quaternion, also updated omega at 1/2 step
// update ex,ey,ez to reflect new quaternion
MathExtra::angmom_to_omega(angmom[ibody],ex_space[ibody],ey_space[ibody],
ez_space[ibody],inertia[ibody],omega[ibody]);
MathExtra::richardson(quat[ibody],angmom[ibody],omega[ibody],
inertia[ibody],dtq);
MathExtra::q_to_exyz(quat[ibody],
ex_space[ibody],ey_space[ibody],ez_space[ibody]);
}
// virial setup before call to set_xv
if (vflag) v_setup(vflag);
else evflag = 0;
// set coords/orient and velocity/rotation of atoms in rigid bodies
// from quarternion and omega
set_xv();
}
/* ----------------------------------------------------------------------
apply Langevin thermostat to all 6 DOF of rigid bodies
computed by proc 0, broadcast to other procs
unlike fix langevin, this stores extra force in extra arrays,
which are added in when final_integrate() calculates a new fcm/torque
------------------------------------------------------------------------- */
void FixRigid::apply_langevin_thermostat()
{
if (me == 0) {
double gamma1,gamma2;
double delta = update->ntimestep - update->beginstep;
if (delta != 0.0) delta /= update->endstep - update->beginstep;
t_target = t_start + delta * (t_stop-t_start);
double tsqrt = sqrt(t_target);
double boltz = force->boltz;
double dt = update->dt;
double mvv2e = force->mvv2e;
double ftm2v = force->ftm2v;
for (int i = 0; i < nbody; i++) {
gamma1 = -masstotal[i] / t_period / ftm2v;
gamma2 = sqrt(masstotal[i]) * tsqrt *
sqrt(24.0*boltz/t_period/dt/mvv2e) / ftm2v;
langextra[i][0] = gamma1*vcm[i][0] + gamma2*(random->uniform()-0.5);
langextra[i][1] = gamma1*vcm[i][1] + gamma2*(random->uniform()-0.5);
langextra[i][2] = gamma1*vcm[i][2] + gamma2*(random->uniform()-0.5);
gamma1 = -1.0 / t_period / ftm2v;
gamma2 = tsqrt * sqrt(24.0*boltz/t_period/dt/mvv2e) / ftm2v;
langextra[i][3] = inertia[i][0]*gamma1*omega[i][0] +
sqrt(inertia[i][0])*gamma2*(random->uniform()-0.5);
langextra[i][4] = inertia[i][1]*gamma1*omega[i][1] +
sqrt(inertia[i][1])*gamma2*(random->uniform()-0.5);
langextra[i][5] = inertia[i][2]*gamma1*omega[i][2] +
sqrt(inertia[i][2])*gamma2*(random->uniform()-0.5);
}
}
MPI_Bcast(&langextra[0][0],6*nbody,MPI_DOUBLE,0,world);
}
/* ----------------------------------------------------------------------
called from FixEnforce2d post_force() for 2d problems
zero all body values that should be zero for 2d model
------------------------------------------------------------------------- */
void FixRigid::enforce2d()
{
for (int ibody = 0; ibody < nbody; ibody++) {
xcm[ibody][2] = 0.0;
vcm[ibody][2] = 0.0;
fcm[ibody][2] = 0.0;
torque[ibody][0] = 0.0;
torque[ibody][1] = 0.0;
angmom[ibody][0] = 0.0;
angmom[ibody][1] = 0.0;
omega[ibody][0] = 0.0;
omega[ibody][1] = 0.0;
if (langflag && langextra) {
langextra[ibody][2] = 0.0;
langextra[ibody][3] = 0.0;
langextra[ibody][4] = 0.0;
}
}
}
/* ---------------------------------------------------------------------- */
void FixRigid::compute_forces_and_torques()
{
int i,ibody;
// sum over atoms to get force and torque on rigid body
double **x = atom->x;
double **f = atom->f;
int nlocal = atom->nlocal;
double dx,dy,dz;
double unwrap[3];
for (ibody = 0; ibody < nbody; ibody++)
for (i = 0; i < 6; i++) sum[ibody][i] = 0.0;
for (i = 0; i < nlocal; i++) {
if (body[i] < 0) continue;
ibody = body[i];
sum[ibody][0] += f[i][0];
sum[ibody][1] += f[i][1];
sum[ibody][2] += f[i][2];
domain->unmap(x[i],xcmimage[i],unwrap);
dx = unwrap[0] - xcm[ibody][0];
dy = unwrap[1] - xcm[ibody][1];
dz = unwrap[2] - xcm[ibody][2];
sum[ibody][3] += dy*f[i][2] - dz*f[i][1];
sum[ibody][4] += dz*f[i][0] - dx*f[i][2];
sum[ibody][5] += dx*f[i][1] - dy*f[i][0];
}
// extended particles add their torque to torque of body
if (extended) {
double **torque_one = atom->torque;
for (i = 0; i < nlocal; i++) {
if (body[i] < 0) continue;
ibody = body[i];
if (eflags[i] & TORQUE) {
sum[ibody][3] += torque_one[i][0];
sum[ibody][4] += torque_one[i][1];
sum[ibody][5] += torque_one[i][2];
}
}
}
MPI_Allreduce(sum[0],all[0],6*nbody,MPI_DOUBLE,MPI_SUM,world);
// include Langevin thermostat forces
for (ibody = 0; ibody < nbody; ibody++) {
fcm[ibody][0] = all[ibody][0] + langextra[ibody][0];
fcm[ibody][1] = all[ibody][1] + langextra[ibody][1];
fcm[ibody][2] = all[ibody][2] + langextra[ibody][2];
torque[ibody][0] = all[ibody][3] + langextra[ibody][3];
torque[ibody][1] = all[ibody][4] + langextra[ibody][4];
torque[ibody][2] = all[ibody][5] + langextra[ibody][5];
}
// add gravity force to COM of each body
if (id_gravity) {
for (ibody = 0; ibody < nbody; ibody++) {
fcm[ibody][0] += gvec[0]*masstotal[ibody];
fcm[ibody][1] += gvec[1]*masstotal[ibody];
fcm[ibody][2] += gvec[2]*masstotal[ibody];
}
}
}
/* ---------------------------------------------------------------------- */
void FixRigid::post_force(int /*vflag*/)
{
if (langflag) apply_langevin_thermostat();
if (earlyflag) compute_forces_and_torques();
}
/* ---------------------------------------------------------------------- */
void FixRigid::final_integrate()
{
int ibody;
double dtfm;
if (!earlyflag) compute_forces_and_torques();
// update vcm and angmom
// fflag,tflag = 0 for some dimensions in 2d
for (ibody = 0; ibody < nbody; ibody++) {
// update vcm by 1/2 step
dtfm = dtf / masstotal[ibody];
vcm[ibody][0] += dtfm * fcm[ibody][0] * fflag[ibody][0];
vcm[ibody][1] += dtfm * fcm[ibody][1] * fflag[ibody][1];
vcm[ibody][2] += dtfm * fcm[ibody][2] * fflag[ibody][2];
// update angular momentum by 1/2 step
angmom[ibody][0] += dtf * torque[ibody][0] * tflag[ibody][0];
angmom[ibody][1] += dtf * torque[ibody][1] * tflag[ibody][1];
angmom[ibody][2] += dtf * torque[ibody][2] * tflag[ibody][2];
MathExtra::angmom_to_omega(angmom[ibody],ex_space[ibody],ey_space[ibody],
ez_space[ibody],inertia[ibody],omega[ibody]);
}
// set velocity/rotation of atoms in rigid bodies
// virial is already setup from initial_integrate
set_v();
}
/* ---------------------------------------------------------------------- */
void FixRigid::initial_integrate_respa(int vflag, int ilevel, int /*iloop*/)
{
dtv = step_respa[ilevel];
dtf = 0.5 * step_respa[ilevel] * force->ftm2v;
dtq = 0.5 * step_respa[ilevel];
if (ilevel == 0) initial_integrate(vflag);
else final_integrate();
}
/* ---------------------------------------------------------------------- */
void FixRigid::final_integrate_respa(int ilevel, int /*iloop*/)
{
dtf = 0.5 * step_respa[ilevel] * force->ftm2v;
final_integrate();
}
/* ----------------------------------------------------------------------
remap xcm of each rigid body back into periodic simulation box
done during pre_neighbor so will be after call to pbc()
and after fix_deform::pre_exchange() may have flipped box
use domain->remap() in case xcm is far away from box
due to first-time definition of rigid body in setup_bodies_static()
or due to box flip
also adjust imagebody = rigid body image flags, due to xcm remap
also reset body xcmimage flags of all atoms in bodies
xcmimage flags are relative to xcm so that body can be unwrapped
if don't do this, would need xcm to move with true image flags
then a body could end up very far away from box
set_xv() will then compute huge displacements every step to
reset coords of all body atoms to be back inside the box,
ditto for triclinic box flip, which causes numeric problems
------------------------------------------------------------------------- */
void FixRigid::pre_neighbor()
{
for (int ibody = 0; ibody < nbody; ibody++)
domain->remap(xcm[ibody],imagebody[ibody]);
image_shift();
}
/* ----------------------------------------------------------------------
reset body xcmimage flags of atoms in bodies
xcmimage flags are relative to xcm so that body can be unwrapped
xcmimage = true image flag - imagebody flag
------------------------------------------------------------------------- */
void FixRigid::image_shift()
{
int ibody;
imageint tdim,bdim,xdim[3];
imageint *image = atom->image;
int nlocal = atom->nlocal;
for (int i = 0; i < nlocal; i++) {
if (body[i] < 0) continue;
ibody = body[i];
tdim = image[i] & IMGMASK;
bdim = imagebody[ibody] & IMGMASK;
xdim[0] = IMGMAX + tdim - bdim;
tdim = (image[i] >> IMGBITS) & IMGMASK;
bdim = (imagebody[ibody] >> IMGBITS) & IMGMASK;
xdim[1] = IMGMAX + tdim - bdim;
tdim = image[i] >> IMG2BITS;
bdim = imagebody[ibody] >> IMG2BITS;
xdim[2] = IMGMAX + tdim - bdim;
xcmimage[i] = (xdim[2] << IMG2BITS) | (xdim[1] << IMGBITS) | xdim[0];
}
}
/* ----------------------------------------------------------------------
count # of DOF removed by rigid bodies for atoms in igroup
return total count of DOF
------------------------------------------------------------------------- */
int FixRigid::dof(int tgroup)
{
// cannot count DOF correctly unless setup_bodies_static() has been called
if (!setupflag) {
if (comm->me == 0)
error->warning(FLERR,"Cannot count rigid body degrees-of-freedom "
"before bodies are initialized");
return 0;
}
int tgroupbit = group->bitmask[tgroup];
// nall = # of point particles in each rigid body
// mall = # of finite-size particles in each rigid body
// particles must also be in temperature group
int *mask = atom->mask;
int nlocal = atom->nlocal;
int *ncount = new int[nbody];
int *mcount = new int[nbody];
for (int ibody = 0; ibody < nbody; ibody++)
ncount[ibody] = mcount[ibody] = 0;
for (int i = 0; i < nlocal; i++)
if (body[i] >= 0 && mask[i] & tgroupbit) {
// do not count point particles or point dipoles as extended particles
// a spheroid dipole will be counted as extended
if (extended && (eflags[i] & ~(POINT | DIPOLE))) mcount[body[i]]++;
else ncount[body[i]]++;
}
int *nall = new int[nbody];
int *mall = new int[nbody];
MPI_Allreduce(ncount,nall,nbody,MPI_INT,MPI_SUM,world);
MPI_Allreduce(mcount,mall,nbody,MPI_INT,MPI_SUM,world);
// warn if nall+mall != nrigid for any body included in temperature group
int flag = 0;
for (int ibody = 0; ibody < nbody; ibody++) {
if (nall[ibody]+mall[ibody] > 0 &&
nall[ibody]+mall[ibody] != nrigid[ibody]) flag = 1;
}
if (flag && me == 0)
error->warning(FLERR,"Computing temperature of portions of rigid bodies");
// remove appropriate DOFs for each rigid body wholly in temperature group
// N = # of point particles in body
// M = # of finite-size particles in body
// 3d body has 3N + 6M dof to start with
// 2d body has 2N + 3M dof to start with
// 3d point-particle body with all non-zero I should have 6 dof, remove 3N-6
// 3d point-particle body (linear) with a 0 I should have 5 dof, remove 3N-5
// 2d point-particle body should have 3 dof, remove 2N-3
// 3d body with any finite-size M should have 6 dof, remove (3N+6M) - 6
// 2d body with any finite-size M should have 3 dof, remove (2N+3M) - 3
int n = 0;
nlinear = 0;
if (domain->dimension == 3) {
for (int ibody = 0; ibody < nbody; ibody++)
if (nall[ibody]+mall[ibody] == nrigid[ibody]) {
n += 3*nall[ibody] + 6*mall[ibody] - 6;
if (inertia[ibody][0] == 0.0 || inertia[ibody][1] == 0.0 ||
inertia[ibody][2] == 0.0) {
n++;
nlinear++;
}
}
} else if (domain->dimension == 2) {
for (int ibody = 0; ibody < nbody; ibody++)
if (nall[ibody]+mall[ibody] == nrigid[ibody])
n += 2*nall[ibody] + 3*mall[ibody] - 3;
}
delete [] ncount;
delete [] mcount;
delete [] nall;
delete [] mall;
return n;
}
/* ----------------------------------------------------------------------
adjust xcm of each rigid body due to box deformation
called by various fixes that change box size/shape
flag = 0/1 means map from box to lamda coords or vice versa
------------------------------------------------------------------------- */
void FixRigid::deform(int flag)
{
if (flag == 0)
for (int ibody = 0; ibody < nbody; ibody++)
domain->x2lamda(xcm[ibody],xcm[ibody]);
else
for (int ibody = 0; ibody < nbody; ibody++)
domain->lamda2x(xcm[ibody],xcm[ibody]);
}
/* ----------------------------------------------------------------------
set space-frame coords and velocity of each atom in each rigid body
set orientation and rotation of extended particles
x = Q displace + Xcm, mapped back to periodic box
v = Vcm + (W cross (x - Xcm))
------------------------------------------------------------------------- */
void FixRigid::set_xv()
{
int ibody;
int xbox,ybox,zbox;
double x0,x1,x2,v0,v1,v2,fc0,fc1,fc2,massone;
double xy,xz,yz;
double ione[3],exone[3],eyone[3],ezone[3],vr[6],p[3][3];
double **x = atom->x;
double **v = atom->v;
double **f = atom->f;
double *rmass = atom->rmass;
double *mass = atom->mass;
int *type = atom->type;
int nlocal = atom->nlocal;
double xprd = domain->xprd;
double yprd = domain->yprd;
double zprd = domain->zprd;
if (triclinic) {
xy = domain->xy;
xz = domain->xz;
yz = domain->yz;
}
// set x and v of each atom
for (int i = 0; i < nlocal; i++) {
if (body[i] < 0) continue;
ibody = body[i];
xbox = (xcmimage[i] & IMGMASK) - IMGMAX;
ybox = (xcmimage[i] >> IMGBITS & IMGMASK) - IMGMAX;
zbox = (xcmimage[i] >> IMG2BITS) - IMGMAX;
// save old positions and velocities for virial
if (evflag) {
if (triclinic == 0) {
x0 = x[i][0] + xbox*xprd;
x1 = x[i][1] + ybox*yprd;
x2 = x[i][2] + zbox*zprd;
} else {
x0 = x[i][0] + xbox*xprd + ybox*xy + zbox*xz;
x1 = x[i][1] + ybox*yprd + zbox*yz;
x2 = x[i][2] + zbox*zprd;
}
v0 = v[i][0];
v1 = v[i][1];
v2 = v[i][2];
}
// x = displacement from center-of-mass, based on body orientation
// v = vcm + omega around center-of-mass
MathExtra::matvec(ex_space[ibody],ey_space[ibody],
ez_space[ibody],displace[i],x[i]);
v[i][0] = omega[ibody][1]*x[i][2] - omega[ibody][2]*x[i][1] +
vcm[ibody][0];
v[i][1] = omega[ibody][2]*x[i][0] - omega[ibody][0]*x[i][2] +
vcm[ibody][1];
v[i][2] = omega[ibody][0]*x[i][1] - omega[ibody][1]*x[i][0] +
vcm[ibody][2];
// add center of mass to displacement
// map back into periodic box via xbox,ybox,zbox
// for triclinic, add in box tilt factors as well
if (triclinic == 0) {
x[i][0] += xcm[ibody][0] - xbox*xprd;
x[i][1] += xcm[ibody][1] - ybox*yprd;
x[i][2] += xcm[ibody][2] - zbox*zprd;
} else {
x[i][0] += xcm[ibody][0] - xbox*xprd - ybox*xy - zbox*xz;
x[i][1] += xcm[ibody][1] - ybox*yprd - zbox*yz;
x[i][2] += xcm[ibody][2] - zbox*zprd;
}
// virial = unwrapped coords dotted into body constraint force
// body constraint force = implied force due to v change minus f external
// assume f does not include forces internal to body
// 1/2 factor b/c final_integrate contributes other half
// assume per-atom contribution is due to constraint force on that atom
if (evflag) {
if (rmass) massone = rmass[i];
else massone = mass[type[i]];
fc0 = massone*(v[i][0] - v0)/dtf - f[i][0];
fc1 = massone*(v[i][1] - v1)/dtf - f[i][1];
fc2 = massone*(v[i][2] - v2)/dtf - f[i][2];
vr[0] = 0.5*x0*fc0;
vr[1] = 0.5*x1*fc1;
vr[2] = 0.5*x2*fc2;
vr[3] = 0.5*x0*fc1;
vr[4] = 0.5*x0*fc2;
vr[5] = 0.5*x1*fc2;
v_tally(1,&i,1.0,vr);
}
}
// set orientation, omega, angmom of each extended particle
if (extended) {
double theta_body,theta;
double *shape,*quatatom,*inertiaatom;
AtomVecEllipsoid::Bonus *ebonus;
if (avec_ellipsoid) ebonus = avec_ellipsoid->bonus;
AtomVecLine::Bonus *lbonus;
if (avec_line) lbonus = avec_line->bonus;
AtomVecTri::Bonus *tbonus;
if (avec_tri) tbonus = avec_tri->bonus;
double **omega_one = atom->omega;
double **angmom_one = atom->angmom;
double **mu = atom->mu;
int *ellipsoid = atom->ellipsoid;
int *line = atom->line;
int *tri = atom->tri;
for (int i = 0; i < nlocal; i++) {
if (body[i] < 0) continue;
ibody = body[i];
if (eflags[i] & SPHERE) {
omega_one[i][0] = omega[ibody][0];
omega_one[i][1] = omega[ibody][1];
omega_one[i][2] = omega[ibody][2];
} else if (eflags[i] & ELLIPSOID) {
shape = ebonus[ellipsoid[i]].shape;
quatatom = ebonus[ellipsoid[i]].quat;
MathExtra::quatquat(quat[ibody],orient[i],quatatom);
MathExtra::qnormalize(quatatom);
ione[0] = EINERTIA*rmass[i] * (shape[1]*shape[1] + shape[2]*shape[2]);
ione[1] = EINERTIA*rmass[i] * (shape[0]*shape[0] + shape[2]*shape[2]);
ione[2] = EINERTIA*rmass[i] * (shape[0]*shape[0] + shape[1]*shape[1]);
MathExtra::q_to_exyz(quatatom,exone,eyone,ezone);
MathExtra::omega_to_angmom(omega[ibody],exone,eyone,ezone,ione,
angmom_one[i]);
} else if (eflags[i] & LINE) {
if (quat[ibody][3] >= 0.0) theta_body = 2.0*acos(quat[ibody][0]);
else theta_body = -2.0*acos(quat[ibody][0]);
theta = orient[i][0] + theta_body;
while (theta <= -MY_PI) theta += MY_2PI;
while (theta > MY_PI) theta -= MY_2PI;
lbonus[line[i]].theta = theta;
omega_one[i][0] = omega[ibody][0];
omega_one[i][1] = omega[ibody][1];
omega_one[i][2] = omega[ibody][2];
} else if (eflags[i] & TRIANGLE) {
inertiaatom = tbonus[tri[i]].inertia;
quatatom = tbonus[tri[i]].quat;
MathExtra::quatquat(quat[ibody],orient[i],quatatom);
MathExtra::qnormalize(quatatom);
MathExtra::q_to_exyz(quatatom,exone,eyone,ezone);
MathExtra::omega_to_angmom(omega[ibody],exone,eyone,ezone,
inertiaatom,angmom_one[i]);
}
if (eflags[i] & DIPOLE) {
MathExtra::quat_to_mat(quat[ibody],p);
MathExtra::matvec(p,dorient[i],mu[i]);
MathExtra::snormalize3(mu[i][3],mu[i],mu[i]);
}
}
}
}
/* ----------------------------------------------------------------------
set space-frame velocity of each atom in a rigid body
set omega and angmom of extended particles
v = Vcm + (W cross (x - Xcm))
------------------------------------------------------------------------- */
void FixRigid::set_v()
{
int xbox,ybox,zbox;
double x0,x1,x2,v0,v1,v2,fc0,fc1,fc2,massone;
double xy,xz,yz;
double ione[3],exone[3],eyone[3],ezone[3],delta[3],vr[6];
double **x = atom->x;
double **v = atom->v;
double **f = atom->f;
double *rmass = atom->rmass;
double *mass = atom->mass;
int *type = atom->type;
int nlocal = atom->nlocal;
double xprd = domain->xprd;
double yprd = domain->yprd;
double zprd = domain->zprd;
if (triclinic) {
xy = domain->xy;
xz = domain->xz;
yz = domain->yz;
}
// set v of each atom
for (int i = 0; i < nlocal; i++) {
if (body[i] < 0) continue;
const int ibody = body[i];
MathExtra::matvec(ex_space[ibody],ey_space[ibody],
ez_space[ibody],displace[i],delta);
// save old velocities for virial
if (evflag) {
v0 = v[i][0];
v1 = v[i][1];
v2 = v[i][2];
}
v[i][0] = omega[ibody][1]*delta[2] - omega[ibody][2]*delta[1] +
vcm[ibody][0];
v[i][1] = omega[ibody][2]*delta[0] - omega[ibody][0]*delta[2] +
vcm[ibody][1];
v[i][2] = omega[ibody][0]*delta[1] - omega[ibody][1]*delta[0] +
vcm[ibody][2];
// virial = unwrapped coords dotted into body constraint force
// body constraint force = implied force due to v change minus f external
// assume f does not include forces internal to body
// 1/2 factor b/c initial_integrate contributes other half
// assume per-atom contribution is due to constraint force on that atom
if (evflag) {
if (rmass) massone = rmass[i];
else massone = mass[type[i]];
fc0 = massone*(v[i][0] - v0)/dtf - f[i][0];
fc1 = massone*(v[i][1] - v1)/dtf - f[i][1];
fc2 = massone*(v[i][2] - v2)/dtf - f[i][2];
xbox = (xcmimage[i] & IMGMASK) - IMGMAX;
ybox = (xcmimage[i] >> IMGBITS & IMGMASK) - IMGMAX;
zbox = (xcmimage[i] >> IMG2BITS) - IMGMAX;
if (triclinic == 0) {
x0 = x[i][0] + xbox*xprd;
x1 = x[i][1] + ybox*yprd;
x2 = x[i][2] + zbox*zprd;
} else {
x0 = x[i][0] + xbox*xprd + ybox*xy + zbox*xz;
x1 = x[i][1] + ybox*yprd + zbox*yz;
x2 = x[i][2] + zbox*zprd;
}
vr[0] = 0.5*x0*fc0;
vr[1] = 0.5*x1*fc1;
vr[2] = 0.5*x2*fc2;
vr[3] = 0.5*x0*fc1;
vr[4] = 0.5*x0*fc2;
vr[5] = 0.5*x1*fc2;
v_tally(1,&i,1.0,vr);
}
}
// set omega, angmom of each extended particle
if (extended) {
double *shape,*quatatom,*inertiaatom;
AtomVecEllipsoid::Bonus *ebonus;
if (avec_ellipsoid) ebonus = avec_ellipsoid->bonus;
AtomVecTri::Bonus *tbonus;
if (avec_tri) tbonus = avec_tri->bonus;
double **omega_one = atom->omega;
double **angmom_one = atom->angmom;
int *ellipsoid = atom->ellipsoid;
int *tri = atom->tri;
for (int i = 0; i < nlocal; i++) {
if (body[i] < 0) continue;
const int ibody = body[i];
if (eflags[i] & SPHERE) {
omega_one[i][0] = omega[ibody][0];
omega_one[i][1] = omega[ibody][1];
omega_one[i][2] = omega[ibody][2];
} else if (eflags[i] & ELLIPSOID) {
shape = ebonus[ellipsoid[i]].shape;
quatatom = ebonus[ellipsoid[i]].quat;
ione[0] = EINERTIA*rmass[i] * (shape[1]*shape[1] + shape[2]*shape[2]);
ione[1] = EINERTIA*rmass[i] * (shape[0]*shape[0] + shape[2]*shape[2]);
ione[2] = EINERTIA*rmass[i] * (shape[0]*shape[0] + shape[1]*shape[1]);
MathExtra::q_to_exyz(quatatom,exone,eyone,ezone);
MathExtra::omega_to_angmom(omega[ibody],exone,eyone,ezone,ione,
angmom_one[i]);
} else if (eflags[i] & LINE) {
omega_one[i][0] = omega[ibody][0];
omega_one[i][1] = omega[ibody][1];
omega_one[i][2] = omega[ibody][2];
} else if (eflags[i] & TRIANGLE) {
inertiaatom = tbonus[tri[i]].inertia;
quatatom = tbonus[tri[i]].quat;
MathExtra::q_to_exyz(quatatom,exone,eyone,ezone);
MathExtra::omega_to_angmom(omega[ibody],exone,eyone,ezone,
inertiaatom,angmom_one[i]);
}
}
}
}
/* ----------------------------------------------------------------------
one-time initialization of static rigid body attributes
sets extended flags, masstotal, center-of-mass
sets Cartesian and diagonalized inertia tensor
sets body image flags
may read some properties from inpfile
------------------------------------------------------------------------- */
void FixRigid::setup_bodies_static()
{
int i,ibody;
// extended = 1 if any particle in a rigid body is finite size
// or has a dipole moment
extended = orientflag = dorientflag = 0;
AtomVecEllipsoid::Bonus *ebonus;
if (avec_ellipsoid) ebonus = avec_ellipsoid->bonus;
AtomVecLine::Bonus *lbonus;
if (avec_line) lbonus = avec_line->bonus;
AtomVecTri::Bonus *tbonus;
if (avec_tri) tbonus = avec_tri->bonus;
double **mu = atom->mu;
double *radius = atom->radius;
double *rmass = atom->rmass;
double *mass = atom->mass;
int *ellipsoid = atom->ellipsoid;
int *line = atom->line;
int *tri = atom->tri;
int *type = atom->type;
int nlocal = atom->nlocal;
if (atom->radius_flag || atom->ellipsoid_flag || atom->line_flag ||
atom->tri_flag || atom->mu_flag) {
int flag = 0;
for (i = 0; i < nlocal; i++) {
if (body[i] < 0) continue;
if (radius && radius[i] > 0.0) flag = 1;
if (ellipsoid && ellipsoid[i] >= 0) flag = 1;
if (line && line[i] >= 0) flag = 1;
if (tri && tri[i] >= 0) flag = 1;
if (mu && mu[i][3] > 0.0) flag = 1;
}
MPI_Allreduce(&flag,&extended,1,MPI_INT,MPI_MAX,world);
}
// grow extended arrays and set extended flags for each particle
// orientflag = 4 if any particle stores ellipsoid or tri orientation
// orientflag = 1 if any particle stores line orientation
// dorientflag = 1 if any particle stores dipole orientation
if (extended) {
if (atom->ellipsoid_flag) orientflag = 4;
if (atom->line_flag) orientflag = 1;
if (atom->tri_flag) orientflag = 4;
if (atom->mu_flag) dorientflag = 1;
grow_arrays(atom->nmax);
for (i = 0; i < nlocal; i++) {
eflags[i] = 0;
if (body[i] < 0) continue;
// set to POINT or SPHERE or ELLIPSOID or LINE
if (radius && radius[i] > 0.0) {
eflags[i] |= SPHERE;
eflags[i] |= OMEGA;
eflags[i] |= TORQUE;
} else if (ellipsoid && ellipsoid[i] >= 0) {
eflags[i] |= ELLIPSOID;
eflags[i] |= ANGMOM;
eflags[i] |= TORQUE;
} else if (line && line[i] >= 0) {
eflags[i] |= LINE;
eflags[i] |= OMEGA;
eflags[i] |= TORQUE;
} else if (tri && tri[i] >= 0) {
eflags[i] |= TRIANGLE;
eflags[i] |= ANGMOM;
eflags[i] |= TORQUE;
} else eflags[i] |= POINT;
// set DIPOLE if atom->mu and mu[3] > 0.0
if (atom->mu_flag && mu[i][3] > 0.0)
eflags[i] |= DIPOLE;
}
}
// set body xcmimage flags = true image flags
imageint *image = atom->image;
for (i = 0; i < nlocal; i++)
if (body[i] >= 0) xcmimage[i] = image[i];
else xcmimage[i] = 0;
// compute masstotal & center-of-mass of each rigid body
// error if image flag is not 0 in a non-periodic dim
double **x = atom->x;
int *periodicity = domain->periodicity;
double xprd = domain->xprd;
double yprd = domain->yprd;
double zprd = domain->zprd;
double xy = domain->xy;
double xz = domain->xz;
double yz = domain->yz;
for (ibody = 0; ibody < nbody; ibody++)
for (i = 0; i < 6; i++) sum[ibody][i] = 0.0;
int xbox,ybox,zbox;
double massone,xunwrap,yunwrap,zunwrap;
for (i = 0; i < nlocal; i++) {
if (body[i] < 0) continue;
ibody = body[i];
xbox = (xcmimage[i] & IMGMASK) - IMGMAX;
ybox = (xcmimage[i] >> IMGBITS & IMGMASK) - IMGMAX;
zbox = (xcmimage[i] >> IMG2BITS) - IMGMAX;
if (rmass) massone = rmass[i];
else massone = mass[type[i]];
if ((xbox && !periodicity[0]) || (ybox && !periodicity[1]) ||
(zbox && !periodicity[2]))
error->one(FLERR,"Fix rigid atom has non-zero image flag "
"in a non-periodic dimension");
if (triclinic == 0) {
xunwrap = x[i][0] + xbox*xprd;
yunwrap = x[i][1] + ybox*yprd;
zunwrap = x[i][2] + zbox*zprd;
} else {
xunwrap = x[i][0] + xbox*xprd + ybox*xy + zbox*xz;
yunwrap = x[i][1] + ybox*yprd + zbox*yz;
zunwrap = x[i][2] + zbox*zprd;
}
sum[ibody][0] += xunwrap * massone;
sum[ibody][1] += yunwrap * massone;
sum[ibody][2] += zunwrap * massone;
sum[ibody][3] += massone;
}
MPI_Allreduce(sum[0],all[0],6*nbody,MPI_DOUBLE,MPI_SUM,world);
for (ibody = 0; ibody < nbody; ibody++) {
masstotal[ibody] = all[ibody][3];
xcm[ibody][0] = all[ibody][0]/masstotal[ibody];
xcm[ibody][1] = all[ibody][1]/masstotal[ibody];
xcm[ibody][2] = all[ibody][2]/masstotal[ibody];
}
// set vcm, angmom = 0.0 in case inpfile is used
// and doesn't overwrite all body's values
// since setup_bodies_dynamic() will not be called
for (ibody = 0; ibody < nbody; ibody++) {
vcm[ibody][0] = vcm[ibody][1] = vcm[ibody][2] = 0.0;
angmom[ibody][0] = angmom[ibody][1] = angmom[ibody][2] = 0.0;
}
// set rigid body image flags to default values
for (ibody = 0; ibody < nbody; ibody++)
imagebody[ibody] = ((imageint) IMGMAX << IMG2BITS) |
((imageint) IMGMAX << IMGBITS) | IMGMAX;
// overwrite masstotal, center-of-mass, image flags with file values
// inbody[i] = 0/1 if Ith rigid body is initialized by file
int *inbody;
if (inpfile) {
memory->create(inbody,nbody,"rigid:inbody");
for (ibody = 0; ibody < nbody; ibody++) inbody[ibody] = 0;
readfile(0,masstotal,xcm,vcm,angmom,imagebody,inbody);
}
// remap the xcm of each body back into simulation box
// and reset body and atom xcmimage flags via pre_neighbor()
pre_neighbor();
// compute 6 moments of inertia of each body in Cartesian reference frame
// dx,dy,dz = coords relative to center-of-mass
// symmetric 3x3 inertia tensor stored in Voigt notation as 6-vector
double dx,dy,dz;
for (ibody = 0; ibody < nbody; ibody++)
for (i = 0; i < 6; i++) sum[ibody][i] = 0.0;
for (i = 0; i < nlocal; i++) {
if (body[i] < 0) continue;
ibody = body[i];
xbox = (xcmimage[i] & IMGMASK) - IMGMAX;
ybox = (xcmimage[i] >> IMGBITS & IMGMASK) - IMGMAX;
zbox = (xcmimage[i] >> IMG2BITS) - IMGMAX;
if (triclinic == 0) {
xunwrap = x[i][0] + xbox*xprd;
yunwrap = x[i][1] + ybox*yprd;
zunwrap = x[i][2] + zbox*zprd;
} else {
xunwrap = x[i][0] + xbox*xprd + ybox*xy + zbox*xz;
yunwrap = x[i][1] + ybox*yprd + zbox*yz;
zunwrap = x[i][2] + zbox*zprd;
}
dx = xunwrap - xcm[ibody][0];
dy = yunwrap - xcm[ibody][1];
dz = zunwrap - xcm[ibody][2];
if (rmass) massone = rmass[i];
else massone = mass[type[i]];
sum[ibody][0] += massone * (dy*dy + dz*dz);
sum[ibody][1] += massone * (dx*dx + dz*dz);
sum[ibody][2] += massone * (dx*dx + dy*dy);
sum[ibody][3] -= massone * dy*dz;
sum[ibody][4] -= massone * dx*dz;
sum[ibody][5] -= massone * dx*dy;
}
// extended particles may contribute extra terms to moments of inertia
if (extended) {
double ivec[6];
double *shape,*quatatom,*inertiaatom;
double length,theta;
for (i = 0; i < nlocal; i++) {
if (body[i] < 0) continue;
ibody = body[i];
if (rmass) massone = rmass[i];
else massone = mass[type[i]];
if (eflags[i] & SPHERE) {
sum[ibody][0] += SINERTIA*massone * radius[i]*radius[i];
sum[ibody][1] += SINERTIA*massone * radius[i]*radius[i];
sum[ibody][2] += SINERTIA*massone * radius[i]*radius[i];
} else if (eflags[i] & ELLIPSOID) {
shape = ebonus[ellipsoid[i]].shape;
quatatom = ebonus[ellipsoid[i]].quat;
MathExtra::inertia_ellipsoid(shape,quatatom,massone,ivec);
sum[ibody][0] += ivec[0];
sum[ibody][1] += ivec[1];
sum[ibody][2] += ivec[2];
sum[ibody][3] += ivec[3];
sum[ibody][4] += ivec[4];
sum[ibody][5] += ivec[5];
} else if (eflags[i] & LINE) {
length = lbonus[line[i]].length;
theta = lbonus[line[i]].theta;
MathExtra::inertia_line(length,theta,massone,ivec);
sum[ibody][0] += ivec[0];
sum[ibody][1] += ivec[1];
sum[ibody][2] += ivec[2];
sum[ibody][3] += ivec[3];
sum[ibody][4] += ivec[4];
sum[ibody][5] += ivec[5];
} else if (eflags[i] & TRIANGLE) {
inertiaatom = tbonus[tri[i]].inertia;
quatatom = tbonus[tri[i]].quat;
MathExtra::inertia_triangle(inertiaatom,quatatom,massone,ivec);
sum[ibody][0] += ivec[0];
sum[ibody][1] += ivec[1];
sum[ibody][2] += ivec[2];
sum[ibody][3] += ivec[3];
sum[ibody][4] += ivec[4];
sum[ibody][5] += ivec[5];
}
}
}
MPI_Allreduce(sum[0],all[0],6*nbody,MPI_DOUBLE,MPI_SUM,world);
// overwrite Cartesian inertia tensor with file values
if (inpfile) readfile(1,NULL,all,NULL,NULL,NULL,inbody);
// diagonalize inertia tensor for each body via Jacobi rotations
// inertia = 3 eigenvalues = principal moments of inertia
// evectors and exzy_space = 3 evectors = principal axes of rigid body
int ierror;
double cross[3];
double tensor[3][3],evectors[3][3];
for (ibody = 0; ibody < nbody; ibody++) {
tensor[0][0] = all[ibody][0];
tensor[1][1] = all[ibody][1];
tensor[2][2] = all[ibody][2];
tensor[1][2] = tensor[2][1] = all[ibody][3];
tensor[0][2] = tensor[2][0] = all[ibody][4];
tensor[0][1] = tensor[1][0] = all[ibody][5];
ierror = MathExtra::jacobi(tensor,inertia[ibody],evectors);
if (ierror) error->all(FLERR,
"Insufficient Jacobi rotations for rigid body");
ex_space[ibody][0] = evectors[0][0];
ex_space[ibody][1] = evectors[1][0];
ex_space[ibody][2] = evectors[2][0];
ey_space[ibody][0] = evectors[0][1];
ey_space[ibody][1] = evectors[1][1];
ey_space[ibody][2] = evectors[2][1];
ez_space[ibody][0] = evectors[0][2];
ez_space[ibody][1] = evectors[1][2];
ez_space[ibody][2] = evectors[2][2];
// if any principal moment < scaled EPSILON, set to 0.0
double max;
max = MAX(inertia[ibody][0],inertia[ibody][1]);
max = MAX(max,inertia[ibody][2]);
if (inertia[ibody][0] < EPSILON*max) inertia[ibody][0] = 0.0;
if (inertia[ibody][1] < EPSILON*max) inertia[ibody][1] = 0.0;
if (inertia[ibody][2] < EPSILON*max) inertia[ibody][2] = 0.0;
// enforce 3 evectors as a right-handed coordinate system
// flip 3rd vector if needed
MathExtra::cross3(ex_space[ibody],ey_space[ibody],cross);
if (MathExtra::dot3(cross,ez_space[ibody]) < 0.0)
MathExtra::negate3(ez_space[ibody]);
// create initial quaternion
MathExtra::exyz_to_q(ex_space[ibody],ey_space[ibody],ez_space[ibody],
quat[ibody]);
}
// displace = initial atom coords in basis of principal axes
// set displace = 0.0 for atoms not in any rigid body
// for extended particles, set their orientation wrt to rigid body
double qc[4],delta[3];
double *quatatom;
double theta_body;
for (i = 0; i < nlocal; i++) {
if (body[i] < 0) {
displace[i][0] = displace[i][1] = displace[i][2] = 0.0;
continue;
}
ibody = body[i];
xbox = (xcmimage[i] & IMGMASK) - IMGMAX;
ybox = (xcmimage[i] >> IMGBITS & IMGMASK) - IMGMAX;
zbox = (xcmimage[i] >> IMG2BITS) - IMGMAX;
if (triclinic == 0) {
xunwrap = x[i][0] + xbox*xprd;
yunwrap = x[i][1] + ybox*yprd;
zunwrap = x[i][2] + zbox*zprd;
} else {
xunwrap = x[i][0] + xbox*xprd + ybox*xy + zbox*xz;
yunwrap = x[i][1] + ybox*yprd + zbox*yz;
zunwrap = x[i][2] + zbox*zprd;
}
delta[0] = xunwrap - xcm[ibody][0];
delta[1] = yunwrap - xcm[ibody][1];
delta[2] = zunwrap - xcm[ibody][2];
MathExtra::transpose_matvec(ex_space[ibody],ey_space[ibody],
ez_space[ibody],delta,displace[i]);
if (extended) {
if (eflags[i] & ELLIPSOID) {
quatatom = ebonus[ellipsoid[i]].quat;
MathExtra::qconjugate(quat[ibody],qc);
MathExtra::quatquat(qc,quatatom,orient[i]);
MathExtra::qnormalize(orient[i]);
} else if (eflags[i] & LINE) {
if (quat[ibody][3] >= 0.0) theta_body = 2.0*acos(quat[ibody][0]);
else theta_body = -2.0*acos(quat[ibody][0]);
orient[i][0] = lbonus[line[i]].theta - theta_body;
while (orient[i][0] <= -MY_PI) orient[i][0] += MY_2PI;
while (orient[i][0] > MY_PI) orient[i][0] -= MY_2PI;
if (orientflag == 4) orient[i][1] = orient[i][2] = orient[i][3] = 0.0;
} else if (eflags[i] & TRIANGLE) {
quatatom = tbonus[tri[i]].quat;
MathExtra::qconjugate(quat[ibody],qc);
MathExtra::quatquat(qc,quatatom,orient[i]);
MathExtra::qnormalize(orient[i]);
} else if (orientflag == 4) {
orient[i][0] = orient[i][1] = orient[i][2] = orient[i][3] = 0.0;
} else if (orientflag == 1)
orient[i][0] = 0.0;
if (eflags[i] & DIPOLE) {
MathExtra::transpose_matvec(ex_space[ibody],ey_space[ibody],
ez_space[ibody],mu[i],dorient[i]);
MathExtra::snormalize3(mu[i][3],dorient[i],dorient[i]);
} else if (dorientflag)
dorient[i][0] = dorient[i][1] = dorient[i][2] = 0.0;
}
}
// test for valid principal moments & axes
// recompute moments of inertia around new axes
// 3 diagonal moments should equal principal moments
// 3 off-diagonal moments should be 0.0
// extended particles may contribute extra terms to moments of inertia
for (ibody = 0; ibody < nbody; ibody++)
for (i = 0; i < 6; i++) sum[ibody][i] = 0.0;
for (i = 0; i < nlocal; i++) {
if (body[i] < 0) continue;
ibody = body[i];
if (rmass) massone = rmass[i];
else massone = mass[type[i]];
sum[ibody][0] += massone *
(displace[i][1]*displace[i][1] + displace[i][2]*displace[i][2]);
sum[ibody][1] += massone *
(displace[i][0]*displace[i][0] + displace[i][2]*displace[i][2]);
sum[ibody][2] += massone *
(displace[i][0]*displace[i][0] + displace[i][1]*displace[i][1]);
sum[ibody][3] -= massone * displace[i][1]*displace[i][2];
sum[ibody][4] -= massone * displace[i][0]*displace[i][2];
sum[ibody][5] -= massone * displace[i][0]*displace[i][1];
}
if (extended) {
double ivec[6];
double *shape,*inertiaatom;
double length;
for (i = 0; i < nlocal; i++) {
if (body[i] < 0) continue;
ibody = body[i];
if (rmass) massone = rmass[i];
else massone = mass[type[i]];
if (eflags[i] & SPHERE) {
sum[ibody][0] += SINERTIA*massone * radius[i]*radius[i];
sum[ibody][1] += SINERTIA*massone * radius[i]*radius[i];
sum[ibody][2] += SINERTIA*massone * radius[i]*radius[i];
} else if (eflags[i] & ELLIPSOID) {
shape = ebonus[ellipsoid[i]].shape;
MathExtra::inertia_ellipsoid(shape,orient[i],massone,ivec);
sum[ibody][0] += ivec[0];
sum[ibody][1] += ivec[1];
sum[ibody][2] += ivec[2];
sum[ibody][3] += ivec[3];
sum[ibody][4] += ivec[4];
sum[ibody][5] += ivec[5];
} else if (eflags[i] & LINE) {
length = lbonus[line[i]].length;
MathExtra::inertia_line(length,orient[i][0],massone,ivec);
sum[ibody][0] += ivec[0];
sum[ibody][1] += ivec[1];
sum[ibody][2] += ivec[2];
sum[ibody][3] += ivec[3];
sum[ibody][4] += ivec[4];
sum[ibody][5] += ivec[5];
} else if (eflags[i] & TRIANGLE) {
inertiaatom = tbonus[tri[i]].inertia;
MathExtra::inertia_triangle(inertiaatom,orient[i],massone,ivec);
sum[ibody][0] += ivec[0];
sum[ibody][1] += ivec[1];
sum[ibody][2] += ivec[2];
sum[ibody][3] += ivec[3];
sum[ibody][4] += ivec[4];
sum[ibody][5] += ivec[5];
}
}
}
MPI_Allreduce(sum[0],all[0],6*nbody,MPI_DOUBLE,MPI_SUM,world);
// error check that re-computed moments of inertia match diagonalized ones
// do not do test for bodies with params read from inpfile
double norm;
for (ibody = 0; ibody < nbody; ibody++) {
if (inpfile && inbody[ibody]) continue;
if (inertia[ibody][0] == 0.0) {
if (fabs(all[ibody][0]) > TOLERANCE)
error->all(FLERR,"Fix rigid: Bad principal moments");
} else {
if (fabs((all[ibody][0]-inertia[ibody][0])/inertia[ibody][0]) >
TOLERANCE) error->all(FLERR,"Fix rigid: Bad principal moments");
}
if (inertia[ibody][1] == 0.0) {
if (fabs(all[ibody][1]) > TOLERANCE)
error->all(FLERR,"Fix rigid: Bad principal moments");
} else {
if (fabs((all[ibody][1]-inertia[ibody][1])/inertia[ibody][1]) >
TOLERANCE) error->all(FLERR,"Fix rigid: Bad principal moments");
}
if (inertia[ibody][2] == 0.0) {
if (fabs(all[ibody][2]) > TOLERANCE)
error->all(FLERR,"Fix rigid: Bad principal moments");
} else {
if (fabs((all[ibody][2]-inertia[ibody][2])/inertia[ibody][2]) >
TOLERANCE) error->all(FLERR,"Fix rigid: Bad principal moments");
}
norm = (inertia[ibody][0] + inertia[ibody][1] + inertia[ibody][2]) / 3.0;
if (fabs(all[ibody][3]/norm) > TOLERANCE ||
fabs(all[ibody][4]/norm) > TOLERANCE ||
fabs(all[ibody][5]/norm) > TOLERANCE)
error->all(FLERR,"Fix rigid: Bad principal moments");
}
if (inpfile) memory->destroy(inbody);
}
/* ----------------------------------------------------------------------
one-time initialization of dynamic rigid body attributes
set vcm and angmom, computed explicitly from constituent particles
not done if body properites read from file, e.g. for overlapping particles
------------------------------------------------------------------------- */
void FixRigid::setup_bodies_dynamic()
{
int i,ibody;
double massone,radone;
// vcm = velocity of center-of-mass of each rigid body
// angmom = angular momentum of each rigid body
double **x = atom->x;
double **v = atom->v;
double *rmass = atom->rmass;
double *mass = atom->mass;
int *type = atom->type;
int nlocal = atom->nlocal;
double dx,dy,dz;
double unwrap[3];
for (ibody = 0; ibody < nbody; ibody++)
for (i = 0; i < 6; i++) sum[ibody][i] = 0.0;
for (i = 0; i < nlocal; i++) {
if (body[i] < 0) continue;
ibody = body[i];
if (rmass) massone = rmass[i];
else massone = mass[type[i]];
sum[ibody][0] += v[i][0] * massone;
sum[ibody][1] += v[i][1] * massone;
sum[ibody][2] += v[i][2] * massone;
domain->unmap(x[i],xcmimage[i],unwrap);
dx = unwrap[0] - xcm[ibody][0];
dy = unwrap[1] - xcm[ibody][1];
dz = unwrap[2] - xcm[ibody][2];
sum[ibody][3] += dy * massone*v[i][2] - dz * massone*v[i][1];
sum[ibody][4] += dz * massone*v[i][0] - dx * massone*v[i][2];
sum[ibody][5] += dx * massone*v[i][1] - dy * massone*v[i][0];
}
// extended particles add their rotation to angmom of body
if (extended) {
AtomVecLine::Bonus *lbonus;
if (avec_line) lbonus = avec_line->bonus;
double **omega_one = atom->omega;
double **angmom_one = atom->angmom;
double *radius = atom->radius;
int *line = atom->line;
for (i = 0; i < nlocal; i++) {
if (body[i] < 0) continue;
ibody = body[i];
if (eflags[i] & OMEGA) {
if (eflags[i] & SPHERE) {
radone = radius[i];
sum[ibody][3] += SINERTIA*rmass[i] * radone*radone * omega_one[i][0];
sum[ibody][4] += SINERTIA*rmass[i] * radone*radone * omega_one[i][1];
sum[ibody][5] += SINERTIA*rmass[i] * radone*radone * omega_one[i][2];
} else if (eflags[i] & LINE) {
radone = lbonus[line[i]].length;
sum[ibody][5] += LINERTIA*rmass[i] * radone*radone * omega_one[i][2];
}
}
if (eflags[i] & ANGMOM) {
sum[ibody][3] += angmom_one[i][0];
sum[ibody][4] += angmom_one[i][1];
sum[ibody][5] += angmom_one[i][2];
}
}
}
MPI_Allreduce(sum[0],all[0],6*nbody,MPI_DOUBLE,MPI_SUM,world);
// normalize velocity of COM
for (ibody = 0; ibody < nbody; ibody++) {
vcm[ibody][0] = all[ibody][0]/masstotal[ibody];
vcm[ibody][1] = all[ibody][1]/masstotal[ibody];
vcm[ibody][2] = all[ibody][2]/masstotal[ibody];
angmom[ibody][0] = all[ibody][3];
angmom[ibody][1] = all[ibody][4];
angmom[ibody][2] = all[ibody][5];
}
}
/* ----------------------------------------------------------------------
read per rigid body info from user-provided file
which = 0 to read everthing except 6 moments of inertia
which = 1 to read 6 moments of inertia
flag inbody = 0 for bodies whose info is read from file
nlines = # of lines of rigid body info
one line = rigid-ID mass xcm ycm zcm ixx iyy izz ixy ixz iyz
vxcm vycm vzcm lx ly lz ix iy iz
------------------------------------------------------------------------- */
void FixRigid::readfile(int which, double *vec,
double **array1, double **array2, double **array3,
imageint *ivec, int *inbody)
{
int j,nchunk,id,eofflag,xbox,ybox,zbox;
int nlines;
FILE *fp;
char *eof,*start,*next,*buf;
char line[MAXLINE];
if (me == 0) {
fp = fopen(inpfile,"r");
if (fp == NULL) {
char str[128];
snprintf(str,128,"Cannot open fix rigid inpfile %s",inpfile);
error->one(FLERR,str);
}
while (1) {
eof = fgets(line,MAXLINE,fp);
if (eof == NULL) error->one(FLERR,"Unexpected end of fix rigid file");
start = &line[strspn(line," \t\n\v\f\r")];
if (*start != '\0' && *start != '#') break;
}
sscanf(line,"%d",&nlines);
}
MPI_Bcast(&nlines,1,MPI_INT,0,world);
if (nlines == 0) error->all(FLERR,"Fix rigid file has no lines");
char *buffer = new char[CHUNK*MAXLINE];
char **values = new char*[ATTRIBUTE_PERBODY];
int nread = 0;
while (nread < nlines) {
nchunk = MIN(nlines-nread,CHUNK);
eofflag = comm->read_lines_from_file(fp,nchunk,MAXLINE,buffer);
if (eofflag) error->all(FLERR,"Unexpected end of fix rigid file");
buf = buffer;
next = strchr(buf,'\n');
*next = '\0';
int nwords = atom->count_words(buf);
*next = '\n';
if (nwords != ATTRIBUTE_PERBODY)
error->all(FLERR,"Incorrect rigid body format in fix rigid file");
// loop over lines of rigid body attributes
// tokenize the line into values
// id = rigid body ID
// use ID as-is for SINGLE, as mol-ID for MOLECULE, as-is for GROUP
// for which = 0, store all but inertia in vecs and arrays
// for which = 1, store inertia tensor array, invert 3,4,5 values to Voigt
for (int i = 0; i < nchunk; i++) {
next = strchr(buf,'\n');
values[0] = strtok(buf," \t\n\r\f");
for (j = 1; j < nwords; j++)
values[j] = strtok(NULL," \t\n\r\f");
id = atoi(values[0]);
if (rstyle == MOLECULE) {
if (id <= 0 || id > maxmol)
error->all(FLERR,"Invalid rigid body ID in fix rigid file");
id = mol2body[id];
} else id--;
if (id < 0 || id >= nbody)
error->all(FLERR,"Invalid rigid body ID in fix rigid file");
inbody[id] = 1;
if (which == 0) {
vec[id] = atof(values[1]);
array1[id][0] = atof(values[2]);
array1[id][1] = atof(values[3]);
array1[id][2] = atof(values[4]);
array2[id][0] = atof(values[11]);
array2[id][1] = atof(values[12]);
array2[id][2] = atof(values[13]);
array3[id][0] = atof(values[14]);
array3[id][1] = atof(values[15]);
array3[id][2] = atof(values[16]);
xbox = atoi(values[17]);
ybox = atoi(values[18]);
zbox = atoi(values[19]);
ivec[id] = ((imageint) (xbox + IMGMAX) & IMGMASK) |
(((imageint) (ybox + IMGMAX) & IMGMASK) << IMGBITS) |
(((imageint) (zbox + IMGMAX) & IMGMASK) << IMG2BITS);
} else {
array1[id][0] = atof(values[5]);
array1[id][1] = atof(values[6]);
array1[id][2] = atof(values[7]);
array1[id][3] = atof(values[10]);
array1[id][4] = atof(values[9]);
array1[id][5] = atof(values[8]);
}
buf = next + 1;
}
nread += nchunk;
}
if (me == 0) fclose(fp);
delete [] buffer;
delete [] values;
}
/* ----------------------------------------------------------------------
write out restart info for mass, COM, inertia tensor, image flags to file
identical format to inpfile option, so info can be read in when restarting
only proc 0 writes list of global bodies to file
------------------------------------------------------------------------- */
void FixRigid::write_restart_file(char *file)
{
if (me) return;
char outfile[128];
snprintf(outfile,128,"%s.rigid",file);
FILE *fp = fopen(outfile,"w");
if (fp == NULL) {
char str[192];
snprintf(str,192,"Cannot open fix rigid restart file %s",outfile);
error->one(FLERR,str);
}
fprintf(fp,"# fix rigid mass, COM, inertia tensor info for "
"%d bodies on timestep " BIGINT_FORMAT "\n\n",
nbody,update->ntimestep);
fprintf(fp,"%d\n",nbody);
// compute I tensor against xyz axes from diagonalized I and current quat
// Ispace = P Idiag P_transpose
// P is stored column-wise in exyz_space
int xbox,ybox,zbox;
double p[3][3],pdiag[3][3],ispace[3][3];
int id;
for (int i = 0; i < nbody; i++) {
if (rstyle == SINGLE || rstyle == GROUP) id = i;
else id = body2mol[i];
MathExtra::col2mat(ex_space[i],ey_space[i],ez_space[i],p);
MathExtra::times3_diag(p,inertia[i],pdiag);
MathExtra::times3_transpose(pdiag,p,ispace);
xbox = (imagebody[i] & IMGMASK) - IMGMAX;
ybox = (imagebody[i] >> IMGBITS & IMGMASK) - IMGMAX;
zbox = (imagebody[i] >> IMG2BITS) - IMGMAX;
fprintf(fp,"%d %-1.16e %-1.16e %-1.16e %-1.16e "
"%-1.16e %-1.16e %-1.16e %-1.16e %-1.16e %-1.16e "
"%-1.16e %-1.16e %-1.16e %-1.16e %-1.16e %-1.16e "
"%d %d %d\n",
id,masstotal[i],xcm[i][0],xcm[i][1],xcm[i][2],
ispace[0][0],ispace[1][1],ispace[2][2],
ispace[0][1],ispace[0][2],ispace[1][2],
vcm[i][0],vcm[i][1],vcm[i][2],
angmom[i][0],angmom[i][1],angmom[i][2],
xbox,ybox,zbox);
}
fclose(fp);
}
/* ----------------------------------------------------------------------
memory usage of local atom-based arrays
------------------------------------------------------------------------- */
double FixRigid::memory_usage()
{
int nmax = atom->nmax;
double bytes = nmax * sizeof(int);
bytes += nmax * sizeof(imageint);
bytes += nmax*3 * sizeof(double);
bytes += maxvatom*6 * sizeof(double); // vatom
if (extended) {
bytes += nmax * sizeof(int);
if (orientflag) bytes = nmax*orientflag * sizeof(double);
if (dorientflag) bytes = nmax*3 * sizeof(double);
}
return bytes;
}
/* ----------------------------------------------------------------------
allocate local atom-based arrays
------------------------------------------------------------------------- */
void FixRigid::grow_arrays(int nmax)
{
memory->grow(body,nmax,"rigid:body");
memory->grow(xcmimage,nmax,"rigid:xcmimage");
memory->grow(displace,nmax,3,"rigid:displace");
if (extended) {
memory->grow(eflags,nmax,"rigid:eflags");
if (orientflag) memory->grow(orient,nmax,orientflag,"rigid:orient");
if (dorientflag) memory->grow(dorient,nmax,3,"rigid:dorient");
}
// check for regrow of vatom
// must be done whether per-atom virial is accumulated on this step or not
// b/c this is only time grow_array() may be called
// need to regrow b/c vatom is calculated before and after atom migration
if (nmax > maxvatom) {
maxvatom = atom->nmax;
memory->grow(vatom,maxvatom,6,"fix:vatom");
}
}
/* ----------------------------------------------------------------------
copy values within local atom-based arrays
------------------------------------------------------------------------- */
void FixRigid::copy_arrays(int i, int j, int /*delflag*/)
{
body[j] = body[i];
xcmimage[j] = xcmimage[i];
displace[j][0] = displace[i][0];
displace[j][1] = displace[i][1];
displace[j][2] = displace[i][2];
if (extended) {
eflags[j] = eflags[i];
for (int k = 0; k < orientflag; k++)
orient[j][k] = orient[i][k];
if (dorientflag) {
dorient[j][0] = dorient[i][0];
dorient[j][1] = dorient[i][1];
dorient[j][2] = dorient[i][2];
}
}
// must also copy vatom if per-atom virial calculated on this timestep
// since vatom is calculated before and after atom migration
if (vflag_atom)
for (int k = 0; k < 6; k++)
vatom[j][k] = vatom[i][k];
}
/* ----------------------------------------------------------------------
initialize one atom's array values, called when atom is created
------------------------------------------------------------------------- */
void FixRigid::set_arrays(int i)
{
body[i] = -1;
xcmimage[i] = 0;
displace[i][0] = 0.0;
displace[i][1] = 0.0;
displace[i][2] = 0.0;
// must also zero vatom if per-atom virial calculated on this timestep
// since vatom is calculated before and after atom migration
if (vflag_atom)
for (int k = 0; k < 6; k++)
vatom[i][k] = 0.0;
}
/* ----------------------------------------------------------------------
pack values in local atom-based arrays for exchange with another proc
------------------------------------------------------------------------- */
int FixRigid::pack_exchange(int i, double *buf)
{
buf[0] = ubuf(body[i]).d;
buf[1] = ubuf(xcmimage[i]).d;
buf[2] = displace[i][0];
buf[3] = displace[i][1];
buf[4] = displace[i][2];
if (!extended) return 5;
int m = 5;
buf[m++] = eflags[i];
for (int j = 0; j < orientflag; j++)
buf[m++] = orient[i][j];
if (dorientflag) {
buf[m++] = dorient[i][0];
buf[m++] = dorient[i][1];
buf[m++] = dorient[i][2];
}
// must also pack vatom if per-atom virial calculated on this timestep
// since vatom is calculated before and after atom migration
if (vflag_atom)
for (int k = 0; k < 6; k++)
buf[m++] = vatom[i][k];
return m;
}
/* ----------------------------------------------------------------------
unpack values in local atom-based arrays from exchange with another proc
------------------------------------------------------------------------- */
int FixRigid::unpack_exchange(int nlocal, double *buf)
{
body[nlocal] = (int) ubuf(buf[0]).i;
xcmimage[nlocal] = (imageint) ubuf(buf[1]).i;
displace[nlocal][0] = buf[2];
displace[nlocal][1] = buf[3];
displace[nlocal][2] = buf[4];
if (!extended) return 5;
int m = 5;
eflags[nlocal] = static_cast<int> (buf[m++]);
for (int j = 0; j < orientflag; j++)
orient[nlocal][j] = buf[m++];
if (dorientflag) {
dorient[nlocal][0] = buf[m++];
dorient[nlocal][1] = buf[m++];
dorient[nlocal][2] = buf[m++];
}
// must also unpack vatom if per-atom virial calculated on this timestep
// since vatom is calculated before and after atom migration
if (vflag_atom)
for (int k = 0; k < 6; k++)
vatom[nlocal][k] = buf[m++];
return m;
}
/* ---------------------------------------------------------------------- */
void FixRigid::reset_dt()
{
dtv = update->dt;
dtf = 0.5 * update->dt * force->ftm2v;
dtq = 0.5 * update->dt;
}
/* ----------------------------------------------------------------------
zero linear momentum of each rigid body
set Vcm to 0.0, then reset velocities of particles via set_v()
------------------------------------------------------------------------- */
void FixRigid::zero_momentum()
{
for (int ibody = 0; ibody < nbody; ibody++)
vcm[ibody][0] = vcm[ibody][1] = vcm[ibody][2] = 0.0;
evflag = 0;
set_v();
}
/* ----------------------------------------------------------------------
zero angular momentum of each rigid body
set angmom/omega to 0.0, then reset velocities of particles via set_v()
------------------------------------------------------------------------- */
void FixRigid::zero_rotation()
{
for (int ibody = 0; ibody < nbody; ibody++) {
angmom[ibody][0] = angmom[ibody][1] = angmom[ibody][2] = 0.0;
omega[ibody][0] = omega[ibody][1] = omega[ibody][2] = 0.0;
}
evflag = 0;
set_v();
}
/* ---------------------------------------------------------------------- */
int FixRigid::modify_param(int narg, char **arg)
{
if (strcmp(arg[0],"bodyforces") == 0) {
if (narg < 2) error->all(FLERR,"Illegal fix_modify command");
if (strcmp(arg[1],"early") == 0) earlyflag = 1;
else if (strcmp(arg[1],"late") == 0) earlyflag = 0;
else error->all(FLERR,"Illegal fix_modify command");
// reset fix mask
// must do here and not in init,
// since modify.cpp::init() uses fix masks before calling fix::init()
for (int i = 0; i < modify->nfix; i++)
if (strcmp(modify->fix[i]->id,id) == 0) {
if (earlyflag) modify->fmask[i] |= POST_FORCE;
else if (!langflag) modify->fmask[i] &= ~POST_FORCE;
break;
}
return 2;
}
return 0;
}
/* ----------------------------------------------------------------------
return temperature of collection of rigid bodies
non-active DOF are removed by fflag/tflag and in tfactor
------------------------------------------------------------------------- */
double FixRigid::compute_scalar()
{
double wbody[3],rot[3][3];
double t = 0.0;
for (int i = 0; i < nbody; i++) {
t += masstotal[i] * (fflag[i][0]*vcm[i][0]*vcm[i][0] +
fflag[i][1]*vcm[i][1]*vcm[i][1] +
fflag[i][2]*vcm[i][2]*vcm[i][2]);
// wbody = angular velocity in body frame
MathExtra::quat_to_mat(quat[i],rot);
MathExtra::transpose_matvec(rot,angmom[i],wbody);
if (inertia[i][0] == 0.0) wbody[0] = 0.0;
else wbody[0] /= inertia[i][0];
if (inertia[i][1] == 0.0) wbody[1] = 0.0;
else wbody[1] /= inertia[i][1];
if (inertia[i][2] == 0.0) wbody[2] = 0.0;
else wbody[2] /= inertia[i][2];
t += tflag[i][0]*inertia[i][0]*wbody[0]*wbody[0] +
tflag[i][1]*inertia[i][1]*wbody[1]*wbody[1] +
tflag[i][2]*inertia[i][2]*wbody[2]*wbody[2];
}
t *= tfactor;
return t;
}
/* ---------------------------------------------------------------------- */
void *FixRigid::extract(const char *str, int &dim)
{
if (strcmp(str,"body") == 0) {
dim = 1;
return body;
}
if (strcmp(str,"masstotal") == 0) {
dim = 1;
return masstotal;
}
if (strcmp(str,"t_target") == 0) {
dim = 0;
return &t_target;
}
return NULL;
}
/* ----------------------------------------------------------------------
return translational KE for all rigid bodies
KE = 1/2 M Vcm^2
------------------------------------------------------------------------- */
double FixRigid::extract_ke()
{
double ke = 0.0;
for (int i = 0; i < nbody; i++)
ke += masstotal[i] *
(vcm[i][0]*vcm[i][0] + vcm[i][1]*vcm[i][1] + vcm[i][2]*vcm[i][2]);
return 0.5*ke;
}
/* ----------------------------------------------------------------------
return rotational KE for all rigid bodies
Erotational = 1/2 I wbody^2
------------------------------------------------------------------------- */
double FixRigid::extract_erotational()
{
double wbody[3],rot[3][3];
double erotate = 0.0;
for (int i = 0; i < nbody; i++) {
// wbody = angular velocity in body frame
MathExtra::quat_to_mat(quat[i],rot);
MathExtra::transpose_matvec(rot,angmom[i],wbody);
if (inertia[i][0] == 0.0) wbody[0] = 0.0;
else wbody[0] /= inertia[i][0];
if (inertia[i][1] == 0.0) wbody[1] = 0.0;
else wbody[1] /= inertia[i][1];
if (inertia[i][2] == 0.0) wbody[2] = 0.0;
else wbody[2] /= inertia[i][2];
erotate += inertia[i][0]*wbody[0]*wbody[0] +
inertia[i][1]*wbody[1]*wbody[1] + inertia[i][2]*wbody[2]*wbody[2];
}
return 0.5*erotate;
}
/* ----------------------------------------------------------------------
return attributes of a rigid body
15 values per body
xcm = 0,1,2; vcm = 3,4,5; fcm = 6,7,8; torque = 9,10,11; image = 12,13,14
------------------------------------------------------------------------- */
double FixRigid::compute_array(int i, int j)
{
if (j < 3) return xcm[i][j];
if (j < 6) return vcm[i][j-3];
if (j < 9) return fcm[i][j-6];
if (j < 12) return torque[i][j-9];
if (j == 12) return (imagebody[i] & IMGMASK) - IMGMAX;
if (j == 13) return (imagebody[i] >> IMGBITS & IMGMASK) - IMGMAX;
return (imagebody[i] >> IMG2BITS) - IMGMAX;
}
| pdebuyl/lammps | src/RIGID/fix_rigid.cpp | C++ | gpl-2.0 | 91,201 |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ResourceList.cs" company="Tygertec">
// Copyright © 2016 Ty Walls.
// All rights reserved.
// </copyright>
// <summary>
// Defines the ResourceList type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace TW.Resfit.Core
{
using System.Collections.Generic;
using System.Linq;
using TW.Resfit.Framework;
public class ResourceList : ListDecoratorBase<Resource>
{
public ResourceList()
{
}
public ResourceList(IEnumerable<Resource> resources) : this()
{
this.Items.AddRange(resources);
}
/// <summary>
/// Gets the underlying Items collection.
/// It is just a proxy for the protected Items property.
/// Its only purpose is to make the code read easier.
/// </summary>
public ICollection<Resource> Resources
{
get
{
return this.Items;
}
}
public ResourceList Clone(ResourceFilter filter = null)
{
if (filter == null)
{
filter = ResourceFilter.NoFilter;
}
var clonedList = new ResourceList();
foreach (var resource in this.Where(resource => filter.IsMatch(resource)))
{
clonedList.Add(new Resource(resource));
}
return clonedList;
}
public void Merge(ResourceList resourceListToAbsorb)
{
foreach (var resource in resourceListToAbsorb)
{
if (this.All(x => x.Key != resource.Key))
{
this.Add(new Resource(resource));
}
}
}
public ResourceList TransformSelfIntoNewList()
{
var newList = new ResourceList();
foreach (var resource in this)
{
var newResource = new Resource(resource);
foreach (var transform in resource.Transforms)
{
newResource = transform.Transform(resource);
}
if (newResource != null)
{
newList.Add(newResource);
}
}
return newList;
}
}
}
| tygerbytes/ResourceFitness | TW.Resfit.Core/ResourceList.cs | C# | gpl-2.0 | 2,524 |
package mnm.mcpackager.gui;
import java.io.File;
import javax.swing.filechooser.FileFilter;
public class JarFilter extends FileFilter {
@Override
public boolean accept(File f) {
if (f.isDirectory())
return true;
return getExtension(f).equalsIgnoreCase("jar");
}
@Override
public String getDescription() {
return "Jar Archives";
}
private String getExtension(File f) {
String ext = null;
String s = f.getName();
int i = s.lastIndexOf('.');
if (i > 0 && i < s.length() - 1)
ext = s.substring(i + 1).toLowerCase();
return ext;
}
}
| killjoy1221/MCPatcher-Repackager | src/main/java/mnm/mcpackager/gui/JarFilter.java | Java | gpl-2.0 | 656 |
<?php
/** ---------------------------------------------------------------------
* app/lib/core/BaseModel.php :
* ----------------------------------------------------------------------
* CollectiveAccess
* Open-source collections management software
* ----------------------------------------------------------------------
*
* Software by Whirl-i-Gig (http://www.whirl-i-gig.com)
* Copyright 2000-2012 Whirl-i-Gig
*
* For more information visit http://www.CollectiveAccess.org
*
* This program is free software; you may redistribute it and/or modify it under
* the terms of the provided license as published by Whirl-i-Gig
*
* CollectiveAccess is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTIES whatsoever, including any implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* This source code is free and modifiable under the terms of
* GNU General Public License. (http://www.gnu.org/copyleft/gpl.html). See
* the "license.txt" file for details, or visit the CollectiveAccess web site at
* http://www.CollectiveAccess.org
*
* @package CollectiveAccess
* @subpackage BaseModel
* @license http://www.gnu.org/copyleft/gpl.html GNU Public License version 3
*
* ----------------------------------------------------------------------
*/
/**
*
*/
# ------------------------------------------------------------------------------------
# --- Field type constants
# ------------------------------------------------------------------------------------
define("FT_NUMBER",0);
define("FT_TEXT", 1);
define("FT_TIMESTAMP", 2);
define("FT_DATETIME", 3);
define("FT_HISTORIC_DATETIME", 4);
define("FT_DATERANGE", 5);
define("FT_HISTORIC_DATERANGE", 6);
define("FT_BIT", 7);
define("FT_FILE", 8);
define("FT_MEDIA", 9);
define("FT_PASSWORD", 10);
define("FT_VARS", 11);
define("FT_TIMECODE", 12);
define("FT_DATE", 13);
define("FT_HISTORIC_DATE", 14);
define("FT_TIME", 15);
define("FT_TIMERANGE", 16);
# ------------------------------------------------------------------------------------
# --- Display type constants
# ------------------------------------------------------------------------------------
define("DT_SELECT", 0);
define("DT_LIST", 1);
define("DT_LIST_MULTIPLE", 2);
define("DT_CHECKBOXES", 3);
define("DT_RADIO_BUTTONS", 4);
define("DT_FIELD", 5);
define("DT_HIDDEN", 6);
define("DT_OMIT", 7);
define("DT_TEXT", 8);
define("DT_PASSWORD", 9);
define("DT_COLORPICKER", 10);
define("DT_TIMECODE", 12);
define("DT_COUNTRY_LIST", 13);
define("DT_STATEPROV_LIST", 14);
# ------------------------------------------------------------------------------------
# --- Access mode constants
# ------------------------------------------------------------------------------------
define("ACCESS_READ", 0);
define("ACCESS_WRITE", 1);
# ------------------------------------------------------------------------------------
# --- Text-markup constants
# ------------------------------------------------------------------------------------
define("__CA_MT_HTML__", 0);
define("__CA_MT_TEXT_ONLY__", 1);
# ------------------------------------------------------------------------------------
# --- Hierarchy type constants
# ------------------------------------------------------------------------------------
define("__CA_HIER_TYPE_SIMPLE_MONO__", 1);
define("__CA_HIER_TYPE_MULTI_MONO__", 2);
define("__CA_HIER_TYPE_ADHOC_MONO__", 3);
define("__CA_HIER_TYPE_MULTI_POLY__", 4);
# ----------------------------------------------------------------------
# --- Import classes
# ----------------------------------------------------------------------
require_once(__CA_LIB_DIR__."/core/BaseObject.php");
require_once(__CA_LIB_DIR__."/core/Error.php");
require_once(__CA_LIB_DIR__."/core/Configuration.php");
require_once(__CA_LIB_DIR__."/core/Datamodel.php");
require_once(__CA_LIB_DIR__."/core/ApplicationChangeLog.php");
require_once(__CA_LIB_DIR__."/core/Parsers/TimeExpressionParser.php");
require_once(__CA_LIB_DIR__."/core/Parsers/TimecodeParser.php");
require_once(__CA_LIB_DIR__."/core/Db.php");
require_once(__CA_LIB_DIR__."/core/Media.php");
require_once(__CA_LIB_DIR__."/core/Media/MediaVolumes.php");
require_once(__CA_LIB_DIR__."/core/File.php");
require_once(__CA_LIB_DIR__."/core/File/FileVolumes.php");
require_once(__CA_LIB_DIR__."/core/Utils/Timer.php");
require_once(__CA_LIB_DIR__."/core/Utils/Unicode.php");
require_once(__CA_LIB_DIR__."/core/Search/SearchIndexer.php");
require_once(__CA_LIB_DIR__."/core/Db/Transaction.php");
require_once(__CA_LIB_DIR__."/core/Media/MediaProcessingSettings.php");
require_once(__CA_APP_DIR__."/helpers/utilityHelpers.php");
require_once(__CA_APP_DIR__."/helpers/gisHelpers.php");
require_once(__CA_LIB_DIR__."/ca/ApplicationPluginManager.php");
require_once(__CA_LIB_DIR__."/core/Parsers/htmlpurifier/HTMLPurifier.standalone.php");
/**
* Base class for all database table classes. Implements database insert/update/delete
* functionality and a whole lot more, including automatic generation of HTML form
* widgets, layering of additional field types and data processing functionality
* (media upload fields using the Media class; date/time and date range fields
* with natural language input using the TimeExpressionParser class; serialized
* variable stores using php serialize(), automatic management of hierarchies, etc.)
* Each table in your database should have a class that extends BaseModel.
*/
class BaseModel extends BaseObject {
# --------------------------------------------------------------------------------
# --- Properties
# --------------------------------------------------------------------------------
/**
* representation of the access mode of the current instance.
* 0 (ACCESS_READ) means read-only,
* 1 (ACCESS_WRITE) characterizes a BaseModel instance that is able to write to the database.
*
* @access private
*/
private $ACCESS_MODE;
/**
* local Db object for database access
*
* @access private
*/
private $o_db;
/**
* debug mode state
*
* @access private
*/
var $debug = 0;
/**
* @access private
*/
var $_FIELD_VALUES;
/**
* @access protected
*/
protected $_FIELD_VALUE_CHANGED;
/**
* @access private
*/
var $_FIELD_VALUES_OLD;
/**
* @access private
*/
private $_FILES;
/**
* @access private
*/
private $_SET_FILES;
/**
* @access private
*/
private $_FILES_CLEAR;
/**
* object-oriented access to media volume information
*
* @access private
*/
private $_MEDIA_VOLUMES;
/**
* object-oriented access to file volume information
*
* @access private
*/
private $_FILE_VOLUMES;
/**
* if true, DATETIME fields take Unix date/times,
* not parseable date/time expressions
*
* @access private
*/
private $DIRECT_DATETIMES = 0;
/**
* local Configuration object representation
*
* @access protected
*/
protected $_CONFIG;
/**
* local Datamodel object representation
*
* @access protected
*/
protected $_DATAMODEL = null;
/**
* contains current Transaction object
*
* @access protected
*/
protected $_TRANSACTION = null;
/**
* The current locale. Used to determine which set of localized error messages to use. Default is US English ("en_us")
*
* @access private
*/
var $ops_locale = "en_us"; #
/**
* prepared change log statement (primary log entry)
*
* @access private
*/
private $opqs_change_log;
/**
* prepared change log statement (log subject entries)
*
* @access private
*/
private $opqs_change_log_subjects;
/**
* prepared statement to get change log
*
* @access private
*/
private $opqs_get_change_log;
/**
* prepared statement to get change log
*
* @access private
*/
private $opqs_get_change_log_subjects; #
/**
* array containing parsed version string from
*
* @access private
*/
private $opa_php_version; #
# --------------------------------------------------------------------------------
# --- Error handling properties
# --------------------------------------------------------------------------------
/**
* Array of error objects
*
* @access public
*/
public $errors;
/**
* If true, on error error message is printed and execution halted
*
* @access private
*/
private $error_output;
/**
* List of fields that had conflicts with existing data during last update()
* (ie. someone else had already saved to this field while the user of this instance was working)
*
* @access private
*/
private $field_conflicts;
/**
* Single instance of search indexer used by all models
*/
static public $search_indexer;
/**
* Single instance of HTML Purifier used by all models
*/
static public $html_purifier;
/**
* If set, all field values passed through BaseModel::set() are run through HTML Purifier before being stored
*/
private $opb_purify_input = false;
/**
* Array of model definitions, keyed on table name
*/
static $s_ca_models_definitions;
/**
* Constructor
* In general you should not call this constructor directly. Any table in your database
* should be represented by an extension of this class.
*
* @param int $pn_id primary key identifier of the table row represented by this object
* if omitted, an empty object is created which can be used to create a new row in the database.
* @return BaseModel
*/
public function __construct($pn_id=null) {
$vs_table_name = $this->tableName();
if (!$this->FIELDS =& BaseModel::$s_ca_models_definitions[$vs_table_name]['FIELDS']) {
die("Field definitions not found for {$vs_table_name}");
}
$this->NAME_SINGULAR =& BaseModel::$s_ca_models_definitions[$vs_table_name]['NAME_SINGULAR'];
$this->NAME_PLURAL =& BaseModel::$s_ca_models_definitions[$vs_table_name]['NAME_PLURAL'];
$this->errors = array();
$this->error_output = 0; # don't halt on error
$this->field_conflicts = array();
$this->_CONFIG = Configuration::load();
$this->_DATAMODEL = Datamodel::load();
$this->_FILES_CLEAR = array();
$this->_SET_FILES = array();
$this->_MEDIA_VOLUMES = MediaVolumes::load();
$this->_FILE_VOLUMES = FileVolumes::load();
$this->_FIELD_VALUE_CHANGED = array();
if ($vs_locale = $this->_CONFIG->get("locale")) {
$this->ops_locale = $vs_locale;
}
$this->opo_app_plugin_manager = new ApplicationPluginManager();
$this->setMode(ACCESS_READ);
if ($pn_id) { $this->load($pn_id);}
}
/**
* Get Db object
* If a transaction is pending, the Db object representation is taken from the Transaction object,
* if not, a new connection is established, stored in a local property and returned.
*
* @return Db
*/
public function getDb() {
if ($this->inTransaction()) {
$this->o_db = $this->getTransaction()->getDb();
} else {
if (!$this->o_db) {
$this->o_db = new Db();
$this->o_db->dieOnError(false);
}
}
return $this->o_db;
}
/**
* Convenience method to return application configuration object. This is the same object
* you'd get if you instantiated a Configuration() object without any parameters
*
* @return Configuration
*/
public function getAppConfig() {
return $this->_CONFIG;
}
/**
* Convenience method to return application datamodel object. This is the same object
* you'd get if you instantiated a Datamodel() object
*
* @return Configuration
*/
public function getAppDatamodel() {
return $this->_DATAMODEL;
}
/**
* Get character set from configuration file. Defaults to
* UTF8 if configuration parameter "character_set" is
* not found.
*
* @return string the character set
*/
public function getCharacterSet() {
if (!($vs_charset = $this->_CONFIG->get("character_set"))) {
$vs_charset = "UTF-8";
}
return $vs_charset;
}
# --------------------------------------------------------------------------------
# --- Transactions
# --------------------------------------------------------------------------------
/**
* Sets up local transaction property and refreshes local db property to
* reflect the db connection of that transaction. After setting it, you
* can perform common actions.
*
* @see BaseModel::getTransaction()
* @see BaseModel::inTransaction()
* @see BaseModel::removeTransaction()
*
* @param Transaction $transaction
* @return bool success state
*/
public function setTransaction(&$transaction) {
if (is_object($transaction)) {
$this->_TRANSACTION = $transaction;
$this->getDb(); // refresh $o_db property to reflect db connection of transaction
return true;
} else {
return false;
}
}
/**
* Get transaction property.
*
* @see BaseModel::setTransaction()
* @see BaseModel::inTransaction()
* @see BaseModel::removeTransaction()
*
* @return Transaction
*/
public function getTransaction() {
return isset($this->_TRANSACTION) ? $this->_TRANSACTION : null;
}
/**
* Is there a pending transaction?
*
* @return bool
*/
public function inTransaction() {
if (isset($this->_TRANSACTION)) { return ($this->_TRANSACTION) ? true : false; }
return false;
}
/**
* Remove transaction property.
*
* @param bool $ps_commit If true, the transaction is committed, if false, the transaction is rollback.
* Defaults to true.
* @return bool success state
*/
public function removeTransaction($ps_commit=true) {
if ($this->inTransaction()) {
if ($ps_commit) {
$this->_TRANSACTION->commit();
} else {
$this->_TRANSACTION->rollback();
}
unset($this->_TRANSACTION);
return true;
} else {
return false;
}
}
# --------------------------------------------------------------------------------
/**
* Sets whether BaseModel::set() input is run through HTML purifier or not
*
* @param bool $pb_purify If true, all input passed via BaseModel::set() is run through HTML Purifier prior to being stored. If false, input is stored as-is. If null or omitted, no change is made to current setting
* @return bool Returns current purification settings. If you simply want to get the current setting call BaseModel::purify without any parameters.
*/
public function purify($pb_purify=null) {
if (!is_null($pb_purify)) {
$this->opb_purify_input = (bool)$pb_purify;
}
return $this->opb_purify_input;
}
# --------------------------------------------------------------------------------
# Set/get values
# --------------------------------------------------------------------------------
/**
* Get all field values of the current row that is represented by this BaseModel object.
*
* @see BaseModel::getChangedFieldValuesArray()
* @return array associative array: field name => field value
*/
public function getFieldValuesArray() {
return $this->_FIELD_VALUES;
}
/**
* Set alls field values of the current row that is represented by this BaseModel object
* by passing an associative array as follows: field name => field value
*
* @param array $pa_values associative array: field name => field value
* @return void
*/
public function setFieldValuesArray($pa_values) {
$this->_FIELD_VALUES = $pa_values;
}
/**
* Get an associative array of the field values that changed since instantiation of
* this BaseModel object.
*
* @return array associative array: field name => field value
*/
public function getChangedFieldValuesArray() {
$va_fieldnames = array_keys($this->_FIELD_VALUES);
$va_changed_field_values_array = array();
foreach($va_fieldnames as $vs_fieldname) {
if($this->changed($vs_fieldname)) {
$va_changed_field_values_array[$vs_fieldname] = $this->_FIELD_VALUES[$vs_fieldname];
}
}
return $va_changed_field_values_array;
}
/**
* What was the original value of a field?
*
* @param string $ps_field field name
* @return mixed original field value
*/
public function getOriginalValue($ps_field) {
return $this->_FIELD_VALUES_OLD[$ps_field];
}
/**
* Check if the content of a field has changed.
*
* @param string $ps_field field name
* @return bool
*/
public function changed($ps_field) {
return isset($this->_FIELD_VALUE_CHANGED[$ps_field]) ? $this->_FIELD_VALUE_CHANGED[$ps_field] : null;
}
/**
* Force field to be considered changed
*
* @param string $ps_field field name
* @return bool Always true
*/
public function setAsChanged($ps_field) {
$this->_FIELD_VALUE_CHANGED[$ps_field] = true;
return true;
}
/**
* Returns value of primary key
*
* @param bool $vb_quoted Set to true if you want the method to return the value in quotes. Default is false.
* @return mixed value of primary key
*/
public function getPrimaryKey ($vb_quoted=false) {
if (!isset($this->_FIELD_VALUES[$this->PRIMARY_KEY])) return null;
$vm_pk = $this->_FIELD_VALUES[$this->PRIMARY_KEY];
if ($vb_quoted) {
$vm_pk = $this->quote($this->PRIMARY_KEY, $vm_pk);
}
return $vm_pk;
}
/**
* Get a field value of the table row that is represented by this object.
*
* @param string $ps_field field name
* @param array $pa_options options array; can be omitted.
* It should be an associative array of boolean (except one of the options) flags. In case that some of the options are not set, they are treated as 'false'.
* Possible options (keys) are:
* -BINARY: return field value as is
* -FILTER_HTML_SPECIAL_CHARS: convert all applicable chars to their html entities
* -DONT_PROCESS_GLOSSARY_TAGS: ?
* -CONVERT_HTML_BREAKS: similar to nl2br()
* -convertLineBreaks: same as CONVERT_HTML_BREAKS
* -GET_DIRECT_DATE: return raw date value from database if $ps_field adresses a date field, otherwise the value will be parsed using the TimeExpressionParser::getText() method
* -GET_DIRECT_TIME: return raw time value from database if $ps_field adresses a time field, otherwise the value will be parsed using the TimeExpressionParser::getText() method
* -TIMECODE_FORMAT: set return format for fields representing time ranges possible (string) values: COLON_DELIMITED, HOURS_MINUTES_SECONDS, RAW; data will be passed through floatval() by default
* -QUOTE: set return value into quotes
* -URL_ENCODE: value will be passed through urlencode()
* -ESCAPE_FOR_XML: convert <, >, &, ' and " characters for XML use
* -DONT_STRIP_SLASHES: if set to true, return value will not be passed through stripslashes()
* -template: formatting string to use for returned value; ^<fieldname> placeholder is used to represent field value in template
* -returnAsArray: if true, fields that can return multiple values [currently only <table_name>.children.<field>] will return values in an indexed array; default is false
* -returnAllLocales:
* -delimiter: if set, value is used as delimiter when fields that can return multiple fields are returned as strings; default is a single space
* -convertCodesToDisplayText: if set, id values refering to foreign keys are returned as preferred label text in the current locale
* -returnURL: if set then url is returned for media, otherwise an HTML tag for display is returned
* -dateFormat: format to return created or lastModified dates in. Valid values are iso8601 or text
*/
public function get($ps_field, $pa_options=null) {
if (!$ps_field) return null;
if (!is_array($pa_options)) { $pa_options = array();}
$vb_return_as_array = (isset($pa_options['returnAsArray'])) ? (bool)$pa_options['returnAsArray'] : false;
$vb_return_all_locales = (isset($pa_options['returnAllLocales'])) ? (bool)$pa_options['returnAllLocales'] : false;
$vs_delimiter = (isset($pa_options['delimiter'])) ? $pa_options['delimiter'] : ' ';
if ($vb_return_all_locales && !$vb_return_as_array) { $vb_return_as_array = true; }
$vn_row_id = $this->getPrimaryKey();
if ($vb_return_as_array && $vb_return_as_array) {
$vn_locale_id = ($this->hasField('locale_id')) ? $this->get('locale_id') : null;
}
$va_tmp = explode('.', $ps_field);
if (sizeof($va_tmp) > 1) {
if ($va_tmp[0] === $this->tableName()) {
//
// Return created on or last modified
//
if (in_array($va_tmp[1], array('created', 'lastModified'))) {
if ($vb_return_as_array) {
return ($va_tmp[1] == 'lastModified') ? $this->getLastChangeTimestamp() : $this->getCreationTimestamp();
} else {
$va_data = ($va_tmp[1] == 'lastModified') ? $this->getLastChangeTimestamp() : $this->getCreationTimestamp();
$vs_subfield = (isset($va_tmp[2]) && isset($va_data[$va_tmp[2]])) ? $va_tmp[2] : 'timestamp';
$vm_val = $va_data[$vs_subfield];
if ($vs_subfield == 'timestamp') {
$o_tep = new TimeExpressionParser();
$o_tep->setUnixTimestamps($vm_val, $vm_val);
$vm_val = $o_tep->getText($pa_options);
}
return $vm_val;
}
}
//
// Generalized get
//
switch(sizeof($va_tmp)) {
case 2:
// support <table_name>.<field_name> syntax
$ps_field = $va_tmp[1];
break;
default: // > 2 elements
// media field?
$va_field_info = $this->getFieldInfo($va_tmp[1]);
if (($va_field_info['FIELD_TYPE'] === FT_MEDIA) && (!isset($pa_options['returnAsArray'])) && !$pa_options['returnAsArray']) {
$o_media_settings = new MediaProcessingSettings($va_tmp[0], $va_tmp[1]);
$va_versions = $o_media_settings->getMediaTypeVersions('*');
$vs_version = $va_tmp[2];
if (!isset($va_versions[$vs_version])) {
$vs_version = array_shift(array_keys($va_versions));
}
if (isset($pa_options['returnURL']) && $pa_options['returnURL']) {
return $this->getMediaUrl($va_tmp[1], $vs_version);
} else {
return $this->getMediaTag($va_tmp[1], $vs_version);
}
}
if (($va_tmp[1] == 'parent') && ($this->isHierarchical()) && ($vn_parent_id = $this->get($this->getProperty('HIERARCHY_PARENT_ID_FLD')))) {
$t_instance = $this->getAppDatamodel()->getInstanceByTableNum($this->tableNum(), true);
if (!$t_instance->load($vn_parent_id)) {
return ($vb_return_as_array) ? array() : null;
} else {
unset($va_tmp[1]);
$va_tmp = array_values($va_tmp);
if ($vb_return_as_array) {
if ($vb_return_all_locales) {
return array(
$vn_row_id => array( // this row_id
$vn_locale_id => array( // base model fields aren't translate-able
$t_instance->get(join('.', $va_tmp))
)
)
);
} else {
return array(
$vn_row_id => $t_instance->get(join('.', $va_tmp))
);
}
} else {
return $t_instance->get(join('.', $va_tmp));
}
}
} else {
if (($va_tmp[1] == 'children') && ($this->isHierarchical())) {
unset($va_tmp[1]); // remove 'children' from field path
$va_tmp = array_values($va_tmp);
$vs_childless_path = join('.', $va_tmp);
$va_data = array();
$va_children_ids = $this->getHierarchyChildren(null, array('idsOnly' => true));
$t_instance = $this->getAppDatamodel()->getInstanceByTableNum($this->tableNum());
foreach($va_children_ids as $vn_child_id) {
if ($t_instance->load($vn_child_id)) {
if ($vb_return_as_array) {
$va_data[$vn_child_id] = array_shift($t_instance->get($vs_childless_path, array_merge($pa_options, array('returnAsArray' => $vb_return_as_array, 'returnAllLocales' => $vb_return_all_locales))));
} else {
$va_data[$vn_child_id] = $t_instance->get($vs_childless_path, array_merge($pa_options, array('returnAsArray' => false, 'returnAllLocales' => false)));
}
}
}
if ($vb_return_as_array) {
return $va_data;
} else {
return join($vs_delimiter, $va_data);
}
}
}
break;
}
} else {
// can't pull fields from other tables!
return $vb_return_as_array ? array() : null;
}
}
if (isset($pa_options["BINARY"]) && $pa_options["BINARY"]) {
return $this->_FIELD_VALUES[$ps_field];
}
if (array_key_exists($ps_field,$this->FIELDS)) {
$ps_field_type = $this->getFieldInfo($ps_field,"FIELD_TYPE");
if ($this->getFieldInfo($ps_field, 'IS_LIFESPAN')) {
$pa_options['isLifespan'] = true;
}
switch ($ps_field_type) {
case (FT_BIT):
$vs_prop = isset($this->_FIELD_VALUES[$ps_field]) ? $this->_FIELD_VALUES[$ps_field] : "";
if (isset($pa_options['convertCodesToDisplayText']) && $pa_options['convertCodesToDisplayText']) {
$vs_prop = (bool)$vs_prop ? _t('yes') : _t('no');
}
return $vs_prop;
break;
case (FT_TEXT):
case (FT_NUMBER):
case (FT_PASSWORD):
$vs_prop = isset($this->_FIELD_VALUES[$ps_field]) ? $this->_FIELD_VALUES[$ps_field] : null;
if (isset($pa_options["FILTER_HTML_SPECIAL_CHARS"]) && ($pa_options["FILTER_HTML_SPECIAL_CHARS"])) {
$vs_prop = htmlentities(html_entity_decode($vs_prop));
}
//
// Convert foreign keys and choice list values to display text is needed
//
if (isset($pa_options['convertCodesToDisplayText']) && $pa_options['convertCodesToDisplayText'] && ($vs_list_code = $this->getFieldInfo($ps_field,"LIST_CODE"))) {
$t_list = new ca_lists();
$vs_prop = $t_list->getItemFromListForDisplayByItemID($vs_list_code, $vs_prop);
} else {
if (isset($pa_options['convertCodesToDisplayText']) && $pa_options['convertCodesToDisplayText'] && ($vs_list_code = $this->getFieldInfo($ps_field,"LIST"))) {
$t_list = new ca_lists();
if (!($vs_tmp = $t_list->getItemFromListForDisplayByItemValue($vs_list_code, $vs_prop))) {
if ($vs_tmp = $this->getChoiceListValue($ps_field, $vs_prop)) {
$vs_prop = $vs_tmp;
}
} else {
$vs_prop = $vs_tmp;
}
} else {
if (isset($pa_options['convertCodesToDisplayText']) && $pa_options['convertCodesToDisplayText'] && ($ps_field === 'locale_id') && ((int)$vs_prop > 0)) {
$t_locale = new ca_locales($vs_prop);
$vs_prop = $t_locale->getName();
} else {
if (isset($pa_options['convertCodesToDisplayText']) && $pa_options['convertCodesToDisplayText'] && (is_array($va_list = $this->getFieldInfo($ps_field,"BOUNDS_CHOICE_LIST")))) {
foreach($va_list as $vs_option => $vs_value) {
if ($vs_value == $vs_prop) {
$vs_prop = $vs_option;
break;
}
}
}
}
}
}
if (
(isset($pa_options["CONVERT_HTML_BREAKS"]) && ($pa_options["CONVERT_HTML_BREAKS"]))
||
(isset($pa_options["convertLineBreaks"]) && ($pa_options["convertLineBreaks"]))
) {
$vs_prop = caConvertLineBreaks($vs_prop);
}
break;
case (FT_DATETIME):
case (FT_TIMESTAMP):
case (FT_HISTORIC_DATETIME):
case (FT_HISTORIC_DATE):
case (FT_DATE):
if (isset($pa_options["GET_DIRECT_DATE"]) && $pa_options["GET_DIRECT_DATE"]) {
$vs_prop = $this->_FIELD_VALUES[$ps_field];
} else {
$o_tep = new TimeExpressionParser();
$vn_timestamp = isset($this->_FIELD_VALUES[$ps_field]) ? $this->_FIELD_VALUES[$ps_field] : 0;
if (($ps_field_type == FT_HISTORIC_DATETIME) || ($ps_field_type == FT_HISTORIC_DATE)) {
$o_tep->setHistoricTimestamps($vn_timestamp, $vn_timestamp);
} else {
$o_tep->setUnixTimestamps($vn_timestamp, $vn_timestamp);
}
if (($ps_field_type == FT_DATE) || ($ps_field_type == FT_HISTORIC_DATE)) {
$vs_prop = $o_tep->getText(array_merge(array('timeOmit' => true), $pa_options));
} else {
$vs_prop = $o_tep->getText($pa_options);
}
}
break;
case (FT_TIME):
if (isset($pa_options["GET_DIRECT_TIME"]) && $pa_options["GET_DIRECT_TIME"]) {
$vs_prop = $this->_FIELD_VALUES[$ps_field];
} else {
$o_tep = new TimeExpressionParser();
$vn_timestamp = isset($this->_FIELD_VALUES[$ps_field]) ? $this->_FIELD_VALUES[$ps_field] : 0;
$o_tep->setTimes($vn_timestamp, $vn_timestamp);
$vs_prop = $o_tep->getText($pa_options);
}
break;
case (FT_DATERANGE):
case (FT_HISTORIC_DATERANGE):
$vs_start_field_name = $this->getFieldInfo($ps_field,"START");
$vs_end_field_name = $this->getFieldInfo($ps_field,"END");
$vn_start_date = isset($this->_FIELD_VALUES[$vs_start_field_name]) ? $this->_FIELD_VALUES[$vs_start_field_name] : null;
$vn_end_date = isset($this->_FIELD_VALUES[$vs_end_field_name]) ? $this->_FIELD_VALUES[$vs_end_field_name] : null;
if (!isset($pa_options["GET_DIRECT_DATE"]) || !$pa_options["GET_DIRECT_DATE"]) {
$o_tep = new TimeExpressionParser();
if ($ps_field_type == FT_HISTORIC_DATERANGE) {
$o_tep->setHistoricTimestamps($vn_start_date, $vn_end_date);
} else {
$o_tep->setUnixTimestamps($vn_start_date, $vn_end_date);
}
$vs_prop = $o_tep->getText($pa_options);
} else {
$vs_prop = array($vn_start_date, $vn_end_date);
}
break;
case (FT_TIMERANGE):
$vs_start_field_name = $this->getFieldInfo($ps_field,"START");
$vs_end_field_name = $this->getFieldInfo($ps_field,"END");
$vn_start_date = isset($this->_FIELD_VALUES[$vs_start_field_name]) ? $this->_FIELD_VALUES[$vs_start_field_name] : null;
$vn_end_date = isset($this->_FIELD_VALUES[$vs_end_field_name]) ? $this->_FIELD_VALUES[$vs_end_field_name] : null;
if (!isset($pa_options["GET_DIRECT_TIME"]) || !$pa_options["GET_DIRECT_TIME"]) {
$o_tep = new TimeExpressionParser();
$o_tep->setTimes($vn_start_date, $vn_end_date);
$vs_prop = $o_tep->getText($pa_options);
} else {
$vs_prop = array($vn_start_date, $vn_end_date);
}
break;
case (FT_TIMECODE):
$o_tp = new TimecodeParser();
$o_tp->setParsedValueInSeconds($this->_FIELD_VALUES[$ps_field]);
$vs_prop = $o_tp->getText(isset($pa_options["TIMECODE_FORMAT"]) ? $pa_options["TIMECODE_FORMAT"] : null);
break;
case (FT_MEDIA):
case (FT_FILE):
if (isset($pa_options["USE_MEDIA_FIELD_VALUES"]) && $pa_options["USE_MEDIA_FIELD_VALUES"]) {
$vs_prop = $this->_FIELD_VALUES[$ps_field];
} else {
$vs_prop = (isset($this->_SET_FILES[$ps_field]['tmp_name']) && $this->_SET_FILES[$ps_field]['tmp_name']) ? $this->_SET_FILES[$ps_field]['tmp_name'] : $this->_FIELD_VALUES[$ps_field];
}
break;
case (FT_VARS):
$vs_prop = (isset($this->_FIELD_VALUES[$ps_field]) && $this->_FIELD_VALUES[$ps_field]) ? $this->_FIELD_VALUES[$ps_field] : null;
break;
}
if (isset($pa_options["QUOTE"]) && $pa_options["QUOTE"])
$vs_prop = $this->quote($ps_field, $vs_prop);
} else {
$this->postError(710,_t("'%1' does not exist in this object", $ps_field),"BaseModel->get()");
return $vb_return_as_array ? array() : null;
}
if (isset($pa_options["URL_ENCODE"]) && $pa_options["URL_ENCODE"]) {
$vs_prop = urlEncode($vs_prop);
}
if (isset($pa_options["ESCAPE_FOR_XML"]) && $pa_options["ESCAPE_FOR_XML"]) {
$vs_prop = escapeForXML($vs_prop);
}
if (!(isset($pa_options["DONT_STRIP_SLASHES"]) && $pa_options["DONT_STRIP_SLASHES"])) {
if (is_string($vs_prop)) { $vs_prop = stripSlashes($vs_prop); }
}
if ((isset($pa_options["template"]) && $pa_options["template"])) {
$vs_template_with_substitution = str_replace("^".$ps_field, $vs_prop, $pa_options["template"]);
$vs_prop = str_replace("^".$this->tableName().".".$ps_field, $vs_prop, $vs_template_with_substitution);
}
if ($vb_return_as_array) {
if ($vb_return_all_locales) {
return array(
$vn_row_id => array( // this row_id
$vn_locale_id => array($vs_prop)
)
);
} else {
return array(
$vn_row_id => $vs_prop
);
}
} else {
return $vs_prop;
}
}
/**
* Set field value(s) for the table row represented by this object
*
* @param string|array string $pa_fields representation of a field name
* or array of string representations of field names
* @param mixed $pm_value value to set the given field(s) to
* @param array $pa_options associative array of options
* possible options (keys):
* when dealing with date/time fields:
* - SET_DIRECT_DATE
* - SET_DIRECT_TIME
* - SET_DIRECT_TIMES
*
* for media/files fields:
* - original_filename : (note that it is lower case) optional parameter which enables you to pass the original filename of a file, in addition to the representation in the temporary, global _FILES array;
*
* for text fields:
* - purify : if set then text input is run through HTML Purifier before being set
*/
public function set($pa_fields, $pm_value="", $pa_options=null) {
$this->errors = array();
if (!is_array($pa_fields)) {
$pa_fields = array($pa_fields => $pm_value);
}
foreach($pa_fields as $vs_field => $vm_value) {
if (array_key_exists($vs_field, $this->FIELDS)) {
$pa_fields_type = $this->getFieldInfo($vs_field,"FIELD_TYPE");
$pb_need_reload = false;
if (!$this->verifyFieldValue($vs_field, $vm_value, $pb_need_reload)) {
return false;
}
if ($pb_need_reload) { return true; } // was set to default
if ($vs_field == $this->primaryKey()) {
$vm_value = preg_replace("/[\"']/", "", $vm_value);
}
// what markup is supported for text fields?
$vs_markup_type = $this->getFieldInfo($vs_field, "MARKUP_TYPE");
// if markup is non-HTML then strip out HTML special chars for safety
if (!($vs_markup_type == __CA_MT_HTML__)) {
$vm_value = htmlspecialchars($vm_value, ENT_QUOTES, 'UTF-8');
}
$vs_cur_value = isset($this->_FIELD_VALUES[$vs_field]) ? $this->_FIELD_VALUES[$vs_field] : null;
switch ($pa_fields_type) {
case (FT_NUMBER):
if ($vs_cur_value != $vm_value) {
$this->_FIELD_VALUE_CHANGED[$vs_field] = true;
}
if (($vm_value !== "") || ($this->getFieldInfo($vs_field, "IS_NULL") && ($vm_value == ""))) {
if ($vm_value) {
$vm_orig_value = $vm_value;
$vm_value = preg_replace("/[^\d-.]+/", "", $vm_value); # strip non-numeric characters
if (!preg_match("/^[\-]{0,1}[\d.]+$/", $vm_value)) {
$this->postError(1100,_t("'%1' for %2 is not numeric", $vm_orig_value, $vs_field),"BaseModel->set()");
return "";
}
}
$this->_FIELD_VALUES[$vs_field] = $vm_value;
}
break;
case (FT_BIT):
if ($vs_cur_value != $vm_value) {
$this->_FIELD_VALUE_CHANGED[$vs_field] = true;
}
$this->_FIELD_VALUES[$vs_field] = ($vm_value ? 1 : 0);
break;
case (FT_DATETIME):
case (FT_HISTORIC_DATETIME):
case (FT_DATE):
case (FT_HISTORIC_DATE):
if (($this->DIRECT_DATETIMES) || ($pa_options["SET_DIRECT_DATE"])) {
$this->_FIELD_VALUES[$vs_field] = $vm_value;
} else {
if (!$vm_value && $this->FIELDS[$vs_field]["IS_NULL"]) {
if ($vs_cur_value) {
$this->_FIELD_VALUE_CHANGED[$vs_field] = true;
}
$this->_FIELD_VALUES[$vs_field] = null;
} else {
$o_tep= new TimeExpressionParser();
if (($pa_fields_type == FT_DATE) || ($pa_fields_type == FT_HISTORIC_DATE)) {
$va_timestamps = $o_tep->parseDate($vm_value);
} else {
$va_timestamps = $o_tep->parseDatetime($vm_value);
}
if (!$va_timestamps) {
$this->postError(1805, $o_tep->getParseErrorMessage(), 'BaseModel->set()');
return false;
}
if (($pa_fields_type == FT_HISTORIC_DATETIME) || ($pa_fields_type == FT_HISTORIC_DATE)) {
if($vs_cur_value != $va_timestamps["start"]) {
$this->_FIELD_VALUES[$vs_field] = $va_timestamps["start"];
$this->_FIELD_VALUE_CHANGED[$vs_field] = true;
}
} else {
$va_timestamps = $o_tep->getUnixTimestamps();
if ($va_timestamps[0] == -1) {
$this->postError(1830, $o_tep->getParseErrorMessage(), 'BaseModel->set()');
return false;
}
if ($vs_cur_value != $va_timestamps["start"]) {
$this->_FIELD_VALUES[$vs_field] = $va_timestamps["start"];
$this->_FIELD_VALUE_CHANGED[$vs_field] = true;
}
}
}
}
break;
case (FT_TIME):
if (($this->DIRECT_TIMES) || ($pa_options["SET_DIRECT_TIME"])) {
$this->_FIELD_VALUES[$vs_field] = $vm_value;
} else {
if (!$vm_value && $this->FIELDS[$vs_field]["IS_NULL"]) {
if ($vs_cur_value) {
$this->_FIELD_VALUE_CHANGED[$vs_field] = true;
}
$this->_FIELD_VALUES[$vs_field] = null;
} else {
$o_tep= new TimeExpressionParser();
if (!$o_tep->parseTime($vm_value)) {
$this->postError(1805, $o_tep->getParseErrorMessage(), 'BaseModel->set()');
return false;
}
$va_times = $o_tep->getTimes();
if ($vs_cur_value != $va_times['start']) {
$this->_FIELD_VALUES[$vs_field] = $va_times['start'];
$this->_FIELD_VALUE_CHANGED[$vs_field] = true;
}
}
}
break;
case (FT_TIMESTAMP):
# can't set timestamp
break;
case (FT_DATERANGE):
case (FT_HISTORIC_DATERANGE):
$vs_start_field_name = $this->getFieldInfo($vs_field,"START");
$vs_end_field_name = $this->getFieldInfo($vs_field,"END");
$vn_start_date = isset($this->_FIELD_VALUES[$vs_start_field_name]) ? $this->_FIELD_VALUES[$vs_start_field_name] : null;
$vn_end_date = isset($this->_FIELD_VALUES[$vs_end_field_name]) ? $this->_FIELD_VALUES[$vs_end_field_name] : null;
if (($this->DIRECT_DATETIMES) || ($pa_options["SET_DIRECT_DATE"])) {
if (is_array($vm_value) && (sizeof($vm_value) == 2) && ($vm_value[0] <= $vm_value[1])) {
if ($vn_start_date != $vm_value[0]) {
$this->_FIELD_VALUE_CHANGED[$vs_field] = true;
$this->_FIELD_VALUES[$vs_start_field_name] = $vm_value[0];
}
if ($vn_end_date != $vm_value[1]) {
$this->_FIELD_VALUE_CHANGED[$vs_field] = true;
$this->_FIELD_VALUES[$vs_end_field_name] = $vm_value[1];
}
} else {
$this->postError(1100,_t("Invalid direct date values"),"BaseModel->set()");
}
} else {
if (!$vm_value && $this->FIELDS[$vs_field]["IS_NULL"]) {
if ($vn_start_date || $vn_end_date) {
$this->_FIELD_VALUE_CHANGED[$vs_field] = true;
}
$this->_FIELD_VALUES[$vs_start_field_name] = null;
$this->_FIELD_VALUES[$vs_end_field_name] = null;
} else {
$o_tep = new TimeExpressionParser();
if (!$o_tep->parseDatetime($vm_value)) {
$this->postError(1805, $o_tep->getParseErrorMessage(), 'BaseModel->set()');
return false;
}
if ($pa_fields_type == FT_HISTORIC_DATERANGE) {
$va_timestamps = $o_tep->getHistoricTimestamps();
} else {
$va_timestamps = $o_tep->getUnixTimestamps();
if ($va_timestamps[0] == -1) {
$this->postError(1830, $o_tep->getParseErrorMessage(), 'BaseModel->set()');
return false;
}
}
if ($vn_start_date != $va_timestamps["start"]) {
$this->_FIELD_VALUE_CHANGED[$vs_field] = true;
$this->_FIELD_VALUES[$vs_start_field_name] = $va_timestamps["start"];
}
if ($vn_end_date != $va_timestamps["end"]) {
$this->_FIELD_VALUE_CHANGED[$vs_field] = true;
$this->_FIELD_VALUES[$vs_end_field_name] = $va_timestamps["end"];
}
}
}
break;
case (FT_TIMERANGE):
$vs_start_field_name = $this->getFieldInfo($vs_field,"START");
$vs_end_field_name = $this->getFieldInfo($vs_field,"END");
if (($this->DIRECT_TIMES) || ($pa_options["SET_DIRECT_TIMES"])) {
if (is_array($vm_value) && (sizeof($vm_value) == 2) && ($vm_value[0] <= $vm_value[1])) {
if ($this->_FIELD_VALUES[$vs_start_field_name] != $vm_value[0]) {
$this->_FIELD_VALUE_CHANGED[$vs_field] = true;
$this->_FIELD_VALUES[$vs_start_field_name] = $vm_value[0];
}
if ($this->_FIELD_VALUES[$vs_end_field_name] != $vm_value[1]) {
$this->_FIELD_VALUE_CHANGED[$vs_field] = true;
$this->_FIELD_VALUES[$vs_end_field_name] = $vm_value[1];
}
} else {
$this->postError(1100,_t("Invalid direct time values"),"BaseModel->set()");
}
} else {
if (!$vm_value && $this->FIELDS[$vs_field]["IS_NULL"]) {
if ($this->_FIELD_VALUES[$vs_start_field_name] || $this->_FIELD_VALUES[$vs_end_field_name]) {
$this->_FIELD_VALUE_CHANGED[$vs_field] = true;
}
$this->_FIELD_VALUES[$vs_start_field_name] = null;
$this->_FIELD_VALUES[$vs_end_field_name] = null;
} else {
$o_tep = new TimeExpressionParser();
if (!$o_tep->parseTime($vm_value)) {
$this->postError(1805, $o_tep->getParseErrorMessage(), 'BaseModel->set()');
return false;
}
$va_timestamps = $o_tep->getTimes();
if ($this->_FIELD_VALUES[$vs_start_field_name] != $va_timestamps["start"]) {
$this->_FIELD_VALUE_CHANGED[$vs_field] = true;
$this->_FIELD_VALUES[$vs_start_field_name] = $va_timestamps["start"];
}
if ($this->_FIELD_VALUES[$vs_end_field_name] != $va_timestamps["end"]) {
$this->_FIELD_VALUE_CHANGED[$vs_field] = true;
$this->_FIELD_VALUES[$vs_end_field_name] = $va_timestamps["end"];
}
}
}
break;
case (FT_TIMECODE):
$o_tp = new TimecodeParser();
if ($o_tp->parse($vm_value)) {
if ($o_tp->getParsedValueInSeconds() != $vs_cur_value) {
$this->_FIELD_VALUE_CHANGED[$vs_field] = true;
$this->_FIELD_VALUES[$vs_field] = $o_tp->getParsedValueInSeconds();
}
}
break;
case (FT_TEXT):
if (is_string($vm_value)) {
$vm_value = stripSlashes($vm_value);
}
if ((isset($pa_options['purify']) && ($pa_options['purify'])) || ((bool)$this->opb_purify_input) || ($this->getFieldInfo($vs_field, "PURIFY")) || ((bool)$this->getAppConfig()->get('useHTMLPurifier'))) {
if (!BaseModel::$html_purifier) { BaseModel::$html_purifier = new HTMLPurifier(); }
$vm_value = BaseModel::$html_purifier->purify((string)$vm_value);
}
if ($this->getFieldInfo($vs_field, "DISPLAY_TYPE") == DT_LIST_MULTIPLE) {
if (is_array($vm_value)) {
if (!($vs_list_multiple_delimiter = $this->getFieldInfo($vs_field, 'LIST_MULTIPLE_DELIMITER'))) { $vs_list_multiple_delimiter = ';'; }
$vs_string_value = join($vs_list_multiple_delimiter, $vm_value);
$vs_string_value = str_replace("\0", '', $vs_string_value);
if ($vs_cur_value != $vs_string_value) {
$this->_FIELD_VALUE_CHANGED[$vs_field] = true;
}
$this->_FIELD_VALUES[$vs_field] = $vs_string_value;
}
} else {
$vm_value = str_replace("\0", '', $vm_value);
if ($this->getFieldInfo($vs_field, "ENTITY_ENCODE_INPUT")) {
$vs_value_entity_encoded = htmlentities(html_entity_decode($vm_value));
if ($vs_cur_value != $vs_value_entity_encoded) {
$this->_FIELD_VALUE_CHANGED[$vs_field] = true;
}
$this->_FIELD_VALUES[$vs_field] = $vs_value_entity_encoded;
} else {
if ($this->getFieldInfo($vs_field, "URL_ENCODE_INPUT")) {
$vs_value_url_encoded = urlencode($vm_value);
if ($vs_cur_value != $vs_value_url_encoded) {
$this->_FIELD_VALUE_CHANGED[$vs_field] = true;
}
$this->_FIELD_VALUES[$vs_field] = $vs_value_url_encoded;
} else {
if ($vs_cur_value != $vm_value) {
$this->_FIELD_VALUE_CHANGED[$vs_field] = true;
}
$this->_FIELD_VALUES[$vs_field] = $vm_value;
}
}
}
break;
case (FT_PASSWORD):
if (!$vm_value) { // store blank passwords as blank, not MD5 of blank
$this->_FIELD_VALUES[$vs_field] = $vs_crypt_pw = "";
} else {
if ($this->_CONFIG->get("use_old_style_passwords")) {
$vs_crypt_pw = crypt($vm_value,substr($vm_value,0,2));
} else {
$vs_crypt_pw = md5($vm_value);
}
if (($vs_cur_value != $vm_value) && ($vs_cur_value != $vs_crypt_pw)) {
$this->_FIELD_VALUES[$vs_field] = $vs_crypt_pw;
}
if ($vs_cur_value != $vs_crypt_pw) {
$this->_FIELD_VALUE_CHANGED[$vs_field] = true;
}
}
break;
case (FT_VARS):
if (md5(print_r($vs_cur_value, true)) != md5(print_r($vm_value, true))) {
$this->_FIELD_VALUE_CHANGED[$vs_field] = true;
}
$this->_FIELD_VALUES[$vs_field] = $vm_value;
break;
case (FT_MEDIA):
case (FT_FILE):
$vb_allow_fetching_of_urls = (bool)$this->_CONFIG->get('allow_fetching_of_media_from_remote_urls');
# if there's a tmp_name is the global _FILES array
# then we'll process it in insert()/update()...
$this->_SET_FILES[$vs_field]['options'] = $pa_options;
if (caGetOSFamily() == OS_WIN32) { // fix for paths using backslashes on Windows failing in processing
$vm_value = str_replace('\\', '/', $vm_value);
}
$va_matches = null;
if (is_string($vm_value) && (file_exists($vm_value) || ($vb_allow_fetching_of_urls && isURL($vm_value)))) {
$this->_SET_FILES[$vs_field]['original_filename'] = $pa_options["original_filename"];
$this->_SET_FILES[$vs_field]['tmp_name'] = $vm_value;
$this->_FIELD_VALUE_CHANGED[$vs_field] = true;
} else {
# only return error when file name is not 'none'
# 'none' is PHP's stupid way of telling you there
# isn't a file...
if (($vm_value != "none") && ($vm_value)) {
//$this->postError(1500,_t("%1 does not exist", $vm_value),"BaseModel->set()");
}
return false;
}
break;
default:
die("Invalid field type in BaseModel->set()");
break;
}
} else {
$this->postError(710,_t("%1' does not exist in this object", $vs_field),"BaseModel->set()");
return false;
}
}
return true;
}
# ------------------------------------------------------------------
/**
*
*/
public function getValuesForExport($pa_options=null) {
$va_fields = $this->getFields();
$va_data = array();
$t_list = new ca_lists();
// get field values
foreach($va_fields as $vs_field) {
$vs_value = $this->get($this->tableName().'.'.$vs_field);
// Convert list item_id's to idnos for export
if ($vs_list_code = $this->getFieldInfo($vs_field, 'LIST_CODE')) {
$va_item = $t_list->getItemFromListByItemID($vs_list_code, $vs_value);
$vs_value = $va_item['idno'];
}
$va_data[$vs_field] = $vs_value;
}
return $va_data;
}
# --------------------------------------------------------------------------------
# BaseModel info
# --------------------------------------------------------------------------------
/**
* Returns an array containing the field names of the table.
*
* @return array field names
*/
public function getFields() {
return array_keys($this->FIELDS);
}
/**
* Returns an array containing the field names of the table as keys and their info as values.
*
* @return array field names
*/
public function getFieldsArray() {
return $this->FIELDS;
}
/**
* Returns name of primary key
*
* @return string the primary key of the table
*/
public function primaryKey() {
return $this->PRIMARY_KEY;
}
/**
* Returns name of the table
*
* @return string the name of the table
*/
public function tableName() {
return $this->TABLE;
}
/**
* Returns number of the table as defined in datamodel.conf configuration file
*
* @return int table number
*/
public function tableNum() {
return $this->_DATAMODEL->getTableNum($this->TABLE);
}
/**
* Returns number of the given field. Field numbering is defined implicitly by the order.
*
* @param string $ps_field field name
* @return int field number
*/
public function fieldNum($ps_field) {
return $this->_DATAMODEL->getFieldNum($this->TABLE, $ps_field);
}
/**
* Returns name of the given field number.
*
* @param number $pn_num field number
* @return string field name
*/
public function fieldName($pn_num) {
$va_fields = $this->getFields();
return isset($va_fields[$pn_num]) ? $va_fields[$pn_num] : null;
}
/**
* Returns name field used for arbitrary ordering of records (returns "" if none defined)
*
* @return string field name, "" if none defined
*/
public function rankField() {
return $this->RANK;
}
/**
* Returns table property
*
* @return mixed the property
*/
public function getProperty($property) {
if (isset($this->{$property})) { return $this->{$property}; }
return null;
}
/**
* Returns a string with the values taken from fields which are defined in global property LIST_FIELDS
* taking into account the global property LIST_DELIMITER. Each extension of BaseModel can define those properties.
*
* @return string
*/
public function getListFieldText() {
if (is_array($va_list_fields = $this->getProperty('LIST_FIELDS'))) {
$vs_delimiter = $this->getProperty('LIST_DELIMITER');
if ($vs_delimiter == null) { $vs_delimiter = ' '; }
$va_tmp = array();
foreach($va_list_fields as $vs_field) {
$va_tmp[] = $this->get($vs_field);
}
return join($vs_delimiter, $va_tmp);
}
return '';
}
# --------------------------------------------------------------------------------
# Access mode
# --------------------------------------------------------------------------------
/**
* Returns the current access mode.
*
* @param bool $pb_return_name If set to true, return string representations of the modes
* (i.e. 'read' or 'write'). If set to false (it is by default), returns ACCESS_READ or ACCESS_WRITE.
*
* @return int|string access mode representation
*/
public function getMode($pb_return_name=false) {
if ($pb_return_name) {
switch($this->ACCESS_MODE) {
case ACCESS_READ:
return 'read';
break;
case ACCESS_WRITE:
return 'write';
break;
default:
return '???';
break;
}
}
return $this->ACCESS_MODE;
}
/**
* Set current access mode.
*
* @param int $pn_mode access mode representation, either ACCESS_READ or ACCESS_WRITE
* @return bool either returns the access mode or false on error
*/
public function setMode($pn_mode) {
if (in_array($pn_mode, array(ACCESS_READ, ACCESS_WRITE))) {
return $this->ACCESS_MODE = $pn_mode;
}
$this->postError(700,_t("Mode:%1 is not supported by this object", $pn_mode),"BaseModel->setMode()");
return false;
}
# --------------------------------------------------------------------------------
# --- Content methods (just your standard Create, Return, Update, Delete methods)
# --------------------------------------------------------------------------------
/**
* Generic method to load content properties of object with database fields.
* After dealing with one row in the database using an extension of BaseModel
* you can use this method to make the same object represent another row, instead
* of destructing the old and constructing a new one.
*
* @param mixed $pm_id primary key value of the record to load (assuming we have no composed primary key)
* @return bool success state
*/
public function load ($pm_id=null) {
$this->clear();
if ($pm_id == null) {
//$this->postError(750,_t("Can't load record; key is blank"), "BaseModel->load()");
return false;
}
$o_db = $this->getDb();
if (!is_array($pm_id)) {
if ($this->_getFieldTypeType($this->primaryKey()) == 1) {
$pm_id = $this->quote($pm_id);
} else {
$pm_id = intval($pm_id);
}
$vs_sql = "SELECT * FROM ".$this->tableName()." WHERE ".$this->primaryKey()." = ".$pm_id;
} else {
$va_sql_wheres = array();
foreach ($pm_id as $vs_field => $vm_value) {
# support case where fieldname is in format table.fieldname
if (preg_match("/([\w_]+)\.([\w_]+)/", $vs_field, $va_matches)) {
if ($va_matches[1] != $this->tableName()) {
if ($this->_DATAMODEL->tableExists($va_matches[1])) {
$this->postError(715,_t("BaseModel '%1' cannot be accessed with this class", $matches[1]), "BaseModel->load()");
return false;
} else {
$this->postError(715, _t("BaseModel '%1' does not exist", $matches[1]), "BaseModel->load()");
return false;
}
}
$vs_field = $matches[2]; # get field name alone
}
if (!$this->hasField($vs_field)) {
$this->postError(716,_t("Field '%1' does not exist", $vs_field), "BaseModel->load()");
return false;
}
if ($this->_getFieldTypeType($vs_field) == 0) {
if (!is_numeric($vm_value) && !is_null($vm_value)) {
$vm_value = intval($vm_value);
}
} else {
$vm_value = $this->quote($vs_field, is_null($vm_value) ? '' : $vm_value);
}
if (is_null($vm_value)) {
$va_sql_wheres[] = "($vs_field IS NULL)";
} else {
if ($vm_value === '') { continue; }
$va_sql_wheres[] = "($vs_field = $vm_value)";
}
}
$vs_sql = "SELECT * FROM ".$this->tableName()." WHERE ".join(" AND ", $va_sql_wheres);
}
$qr_res = $o_db->query($vs_sql);
if ($o_db->numErrors()) {
$this->postError(250, _t('Basemodel::load SQL had an error: %1; SQL was %2', join("; ", $o_db->getErrors()), $vs_sql), 'BaseModel->load');
return false;
}
if ($qr_res->nextRow()) {
foreach($this->FIELDS as $vs_field => $va_attr) {
$vs_cur_value = isset($this->_FIELD_VALUES[$vs_field]) ? $this->_FIELD_VALUES[$vs_field] : null;
$va_row =& $qr_res->getRow();
switch($va_attr["FIELD_TYPE"]) {
case FT_DATERANGE:
case FT_HISTORIC_DATERANGE:
case FT_TIMERANGE:
$vs_start_field_name = $va_attr["START"];
$vs_end_field_name = $va_attr["END"];
$this->_FIELD_VALUES[$vs_start_field_name] = $va_row[$vs_start_field_name];
$this->_FIELD_VALUES[$vs_end_field_name] = $va_row[$vs_end_field_name];
break;
case FT_TIMESTAMP:
$this->_FIELD_VALUES[$vs_field] = $va_row[$vs_field];
break;
case FT_VARS:
case FT_FILE:
case FT_MEDIA:
if (!$vs_cur_value) {
$this->_FIELD_VALUES[$vs_field] = caUnserializeForDatabase($va_row[$vs_field]);
}
break;
default:
$this->_FIELD_VALUES[$vs_field] = $va_row[$vs_field];
break;
}
}
$this->_FIELD_VALUES_OLD = $this->_FIELD_VALUES;
$this->_FILES_CLEAR = array();
return true;
} else {
if (!is_array($pm_id)) {
$this->postError(750,_t("Invalid %1 '%2'", $this->primaryKey(), $pm_id), "BaseModel->load()");
} else {
$va_field_list = array();
foreach ($pm_id as $vs_field => $vm_value) {
$va_field_list[] = "$vs_field => $vm_value";
}
$this->postError(750,_t("No record with %1", join(", ", $va_field_list)), "BaseModel->load()");
}
return false;
}
}
/**
*
*/
private function _calcHierarchicalIndexing($pa_parent_info) {
$vs_hier_left_fld = $this->getProperty('HIERARCHY_LEFT_INDEX_FLD');
$vs_hier_right_fld = $this->getProperty('HIERARCHY_RIGHT_INDEX_FLD');
$vs_hier_id_fld = $this->getProperty('HIERARCHY_ID_FLD');
$vs_parent_fld = $this->getProperty('HIERARCHY_PARENT_ID_FLD');
$o_db = $this->getDb();
$qr_up = $o_db->query("
SELECT MAX({$vs_hier_right_fld}) maxChildRight
FROM ".$this->tableName()."
WHERE
({$vs_hier_left_fld} > ?) AND
({$vs_hier_right_fld} < ?) AND (".$this->primaryKey()." <> ?)".
($vs_hier_id_fld ? " AND ({$vs_hier_id_fld} = ".intval($pa_parent_info[$vs_hier_id_fld]).")" : '')."
", $pa_parent_info[$vs_hier_left_fld], $pa_parent_info[$vs_hier_right_fld], $pa_parent_info[$this->primaryKey()]);
if ($qr_up->nextRow()) {
if (!($vn_gap_start = $qr_up->get('maxChildRight'))) {
$vn_gap_start = $pa_parent_info[$vs_hier_left_fld];
}
$vn_gap_end = $pa_parent_info[$vs_hier_right_fld];
$vn_gap_size = ($vn_gap_end - $vn_gap_start);
if ($vn_gap_size < 0.00001) {
// rebuild hierarchical index if the current gap is not large enough to fit current record
$this->rebuildHierarchicalIndex($this->get($vs_hier_id_fld));
$pa_parent_info = $this->_getHierarchyParent($pa_parent_info[$this->primaryKey()]);
return $this->_calcHierarchicalIndexing($pa_parent_info);
}
if (($vn_scale = strlen(floor($vn_gap_size/10000))) < 1) { $vn_scale = 1; }
$vn_interval_start = $vn_gap_start + ($vn_gap_size/(pow(10, $vn_scale)));
$vn_interval_end = $vn_interval_start + ($vn_gap_size/(pow(10, $vn_scale)));
//print "--------------------------\n";
//print "GAP START={$vn_gap_start} END={$vn_gap_end} SIZE={$vn_gap_size} SCALE={$vn_scale} INC=".($vn_gap_size/(pow(10, $vn_scale)))."\n";
//print "INT START={$vn_interval_start} INT END={$vn_interval_end}\n";
//print "--------------------------\n";
return array('left' => $vn_interval_start, 'right' => $vn_interval_end);
}
return null;
}
/**
*
*/
private function _getHierarchyParent($pn_parent_id) {
$o_db = $this->getDb();
$qr_get_parent = $o_db->query("
SELECT *
FROM ".$this->tableName()."
WHERE
".$this->primaryKey()." = ?
", intval($pn_parent_id));
if($qr_get_parent->nextRow()) {
return $qr_get_parent->getRow();
}
return null;
}
/**
* Internal-use-only function for getting child record ids in a hierarchy. Unlike the public getHierarchyChildren() method
* which uses nested set hierarchical indexing to fetch all children in a single pass (and also can return more than just the id's
* of the children), _getHierarchyChildren() recursively traverses the hierarchy using parent_id field values. This makes it useful for
* getting children in situations when the hierarchical indexing may not be valid, such as when moving items between hierarchies.
*
* @access private
* @param array $pa_ids List of ids to get children for
* @return array ids of all children of specified ids. List includes the original specified ids.
*/
private function _getHierarchyChildren($pa_ids) {
if(!is_array($pa_ids)) { return null; }
if (!sizeof($pa_ids)) { return null; }
if (!($vs_parent_id_fld = $this->getProperty('HIERARCHY_PARENT_ID_FLD'))) { return null; }
foreach($pa_ids as $vn_i => $vn_v) {
$pa_ids[$vn_i] = (int)$vn_v;
}
$o_db = $this->getDb();
$qr_get_children = $o_db->query("
SELECT ".$this->primaryKey()."
FROM ".$this->tableName()."
WHERE
{$vs_parent_id_fld} IN (?)
", array($pa_ids));
$va_child_ids = $qr_get_children->getAllFieldValues($this->primaryKey());
if (($va_child_ids && is_array($va_child_ids) && sizeof($va_child_ids) > 0)) {
$va_child_ids = array_merge($va_child_ids, $this->_getHierarchyChildren($va_child_ids));
}
if (!is_array($va_child_ids)) { $va_child_ids = array(); }
$va_child_ids = array_merge($pa_ids, $va_child_ids);
return array_unique($va_child_ids, SORT_STRING);
}
/**
* Use this method to insert new record using supplied values
* (assuming that you've constructed your BaseModel object as empty record)
* @param $pa_options array optional associative array of options. Supported options include:
* dont_do_search_indexing = if set to true then no search indexing on the inserted record is performed
* @return int primary key of the new record, false on error
*/
public function insert ($pa_options=null) {
if (!is_array($pa_options)) { $pa_options = array(); }
$vb_we_set_transaction = false;
$this->clearErrors();
if ($this->getMode() == ACCESS_WRITE) {
if (!$this->inTransaction()) {
$this->setTransaction(new Transaction($this->getDb()));
$vb_we_set_transaction = true;
}
$o_db = $this->getDb();
$vs_fields = "";
$vs_values = "";
$va_media_fields = array();
$va_file_fields = array();
//
// Set any auto-set hierarchical fields (eg. HIERARCHY_LEFT_INDEX_FLD and HIERARCHY_RIGHT_INDEX_FLD indexing for all and HIERARCHY_ID_FLD for ad-hoc hierarchies) here
//
$vn_hier_left_index_value = $vn_hier_right_index_value = 0;
if ($vb_is_hierarchical = $this->isHierarchical()) {
$vn_parent_id = $this->get($this->getProperty('HIERARCHY_PARENT_ID_FLD'));
$va_parent_info = $this->_getHierarchyParent($vn_parent_id);
switch($this->getHierarchyType()) {
case __CA_HIER_TYPE_SIMPLE_MONO__: // you only need to set parent_id for this type of hierarchy
if (!$vn_parent_id) {
if ($vn_parent_id = $this->getHierarchyRootID(null)) {
$this->set($this->getProperty('HIERARCHY_PARENT_ID_FLD'), $vn_parent_id);
$va_parent_info = $this->_getHierarchyParent($vn_parent_id);
}
}
break;
case __CA_HIER_TYPE_MULTI_MONO__: // you need to set parent_id (otherwise it defaults to the hierarchy root); you only need to set hierarchy_id if you're creating a root
if (!($vn_hierarchy_id = $this->get($this->getProperty('HIERARCHY_ID_FLD')))) {
$this->set($this->getProperty('HIERARCHY_ID_FLD'), $va_parent_info[$this->getProperty('HIERARCHY_ID_FLD')]);
}
if (!$vn_parent_id) {
if ($vn_parent_id = $this->getHierarchyRootID($vn_hierarchy_id)) {
$this->set($this->getProperty('HIERARCHY_PARENT_ID_FLD'), $vn_parent_id);
$va_parent_info = $this->_getHierarchyParent($vn_parent_id);
}
}
break;
case __CA_HIER_TYPE_ADHOC_MONO__: // you need to set parent_id for this hierarchy; you never need to set hierarchy_id
if (!($vn_hierarchy_id = $this->get($this->getProperty('HIERARCHY_ID_FLD')))) {
if ($va_parent_info) {
// set hierarchy to that of parent
$this->set($this->getProperty('HIERARCHY_ID_FLD'), $va_parent_info[$this->getProperty('HIERARCHY_ID_FLD')]);
}
// if there's no parent then this is a root in which case HIERARCHY_ID_FLD should be set to the primary
// key of the row, which we'll know once we insert it (so we must set it after insert)
}
break;
case __CA_HIER_TYPE_MULTI_POLY__: // TODO: implement
break;
default:
die("Invalid hierarchy type: ".$this->getHierarchyType());
break;
}
if ($va_parent_info) {
$va_hier_indexing = $this->_calcHierarchicalIndexing($va_parent_info);
} else {
$va_hier_indexing = array('left' => 1, 'right' => pow(2,32));
}
$this->set($this->getProperty('HIERARCHY_LEFT_INDEX_FLD'), $va_hier_indexing['left']);
$this->set($this->getProperty('HIERARCHY_RIGHT_INDEX_FLD'), $va_hier_indexing['right']);
}
$va_many_to_one_relations = $this->_DATAMODEL->getManyToOneRelations($this->tableName());
foreach($this->FIELDS as $vs_field => $va_attr) {
$vs_field_type = $va_attr["FIELD_TYPE"]; # field type
$vs_field_value = $this->get($vs_field, array("TIMECODE_FORMAT" => "RAW"));
if (isset($va_attr['DONT_PROCESS_DURING_INSERT_UPDATE']) && (bool)$va_attr['DONT_PROCESS_DURING_INSERT_UPDATE']) { continue; }
# --- check bounds (value, length and choice lists)
$pb_need_reload = false;
if (!$this->verifyFieldValue($vs_field, $vs_field_value, $pb_need_reload)) {
# verifyFieldValue() posts errors so we don't have to do anything here
# No query will be run if there are errors so we don't have to worry about invalid
# values being written into the database. By not immediately bailing on an error we
# can return a list of *all* input errors to the caller; this is perfect listing all form input errors in
# a form-based user interface
}
if ($pb_need_reload) {
$vs_field_value = $this->get($vs_field, array("TIMECODE_FORMAT" => "RAW")); // reload value since verifyFieldValue() may force the value to a default
}
# --- TODO: This is MySQL dependent
# --- primary key has no place in an INSERT statement if it is identity
if ($vs_field == $this->primaryKey()) {
if (isset($va_attr["IDENTITY"]) && $va_attr["IDENTITY"]) {
if (!defined('__CA_ALLOW_SETTING_OF_PRIMARY_KEYS__') || !$vs_field_value) {
continue;
}
}
}
# --- check ->one relations
if (isset($va_many_to_one_relations[$vs_field]) && $va_many_to_one_relations[$vs_field]) {
# Nothing to verify if key is null
if (!(
(isset($va_attr["IS_NULL"]) && $va_attr["IS_NULL"]) &&
(
($vs_field_value == "") || ($vs_field_value === null)
)
)) {
if ($t_many_table = $this->_DATAMODEL->getTableInstance($va_many_to_one_relations[$vs_field]["one_table"])) {
if ($this->inTransaction()) {
$t_many_table->setTransaction($this->getTransaction());
}
$t_many_table->load($this->get($va_many_to_one_relations[$vs_field]["many_table_field"]));
}
if ($t_many_table->numErrors()) {
$this->postError(750,_t("%1 record with $vs_field = %2 does not exist", $t_many_table->tableName(), $this->get($vs_field)),"BaseModel->insert()");
}
}
}
if (isset($va_attr["IS_NULL"]) && $va_attr["IS_NULL"] && ($vs_field_value == null)) {
$vs_field_value_is_null = true;
} else {
$vs_field_value_is_null = false;
}
if ($vs_field_value_is_null) {
if (($vs_field_type == FT_DATERANGE) || ($vs_field_type == FT_HISTORIC_DATERANGE) || ($vs_field_type == FT_TIMERANGE)) {
$start_field_name = $va_attr["START"];
$end_field_name = $va_attr["END"];
$vs_fields .= "$start_field_name, $end_field_name,";
$vs_values .= "NULL, NULL,";
} else {
$vs_fields .= "$vs_field,";
$vs_values .= "NULL,";
}
} else {
switch($vs_field_type) {
# -----------------------------
case (FT_DATETIME): # date/time
case (FT_HISTORIC_DATETIME):
case (FT_DATE):
case (FT_HISTORIC_DATE):
$vs_fields .= "$vs_field,";
$v = isset($this->_FIELD_VALUES[$vs_field]) ? $this->_FIELD_VALUES[$vs_field] : null;
if ($v == '') {
$this->postError(1805, _t("Date is undefined but field %1 does not support NULL values", $vs_field),"BaseModel->insert()");
if ($vb_we_set_transaction) { $this->removeTransaction(false); }
return false;
}
if (!is_numeric($v)) {
$this->postError(1100, _t("Date is invalid for %1", $vs_field),"BaseModel->insert()");
if ($vb_we_set_transaction) { $this->removeTransaction(false); }
return false;
}
$vs_values .= $v.","; # output as is
break;
# -----------------------------
case (FT_TIME):
$vs_fields .= $vs_field.",";
$v = isset($this->_FIELD_VALUES[$vs_field]) ? $this->_FIELD_VALUES[$vs_field] : null;
if ($v == "") {
$this->postError(1805, _t("Time is undefined but field %1 does not support NULL values", $vs_field),"BaseModel->insert()");
if ($vb_we_set_transaction) { $this->removeTransaction(false); }
return false;
}
if (!is_numeric($v)) {
$this->postError(1100, _t("Time is invalid for ", $vs_field),"BaseModel->insert()");
if ($vb_we_set_transaction) { $this->removeTransaction(false); }
return false;
}
$vs_values .= $v.","; # output as is
break;
# -----------------------------
case (FT_TIMESTAMP): # insert on stamp
$vs_fields .= $vs_field.",";
$vs_values .= time().",";
break;
# -----------------------------
case (FT_DATERANGE):
case (FT_HISTORIC_DATERANGE):
$start_field_name = $va_attr["START"];
$end_field_name = $va_attr["END"];
if (($this->_FIELD_VALUES[$start_field_name] == "") || ($this->_FIELD_VALUES[$end_field_name] == "")) {
$this->postError(1805, _t("Daterange is undefined but field does not support NULL values"),"BaseModel->insert()");
if ($vb_we_set_transaction) { $this->removeTransaction(false); }
return false;
}
if (!is_numeric($this->_FIELD_VALUES[$start_field_name])) {
$this->postError(1100, _t("Starting date is invalid"),"BaseModel->insert()");
if ($vb_we_set_transaction) { $this->removeTransaction(false); }
return false;
}
if (!is_numeric($this->_FIELD_VALUES[$end_field_name])) {
$this->postError(1100,_t("Ending date is invalid"),"BaseModel->insert()");
if ($vb_we_set_transaction) { $this->removeTransaction(false); }
return false;
}
$vs_fields .= "$start_field_name, $end_field_name,";
$vs_values .= $this->_FIELD_VALUES[$start_field_name].", ".$this->_FIELD_VALUES[$end_field_name].",";
break;
# -----------------------------
case (FT_TIMERANGE):
$start_field_name = $va_attr["START"];
$end_field_name = $va_attr["END"];
if (($this->_FIELD_VALUES[$start_field_name] == "") || ($this->_FIELD_VALUES[$end_field_name] == "")) {
$this->postError(1805,_t("Time range is undefined but field does not support NULL values"),"BaseModel->insert()");
if ($vb_we_set_transaction) { $this->removeTransaction(false); }
return false;
}
if (!is_numeric($this->_FIELD_VALUES[$start_field_name])) {
$this->postError(1100,_t("Starting time is invalid"),"BaseModel->insert()");
if ($vb_we_set_transaction) { $this->removeTransaction(false); }
return false;
}
if (!is_numeric($this->_FIELD_VALUES[$end_field_name])) {
$this->postError(1100,_t("Ending time is invalid"),"BaseModel->insert()");
if ($vb_we_set_transaction) { $this->removeTransaction(false); }
return false;
}
$vs_fields .= "$start_field_name, $end_field_name,";
$vs_values .= $this->_FIELD_VALUES[$start_field_name].", ".$this->_FIELD_VALUES[$end_field_name].",";
break;
# -----------------------------
case (FT_NUMBER):
case (FT_BIT):
if (!$vb_is_hierarchical) {
if ((isset($this->RANK)) && ($vs_field == $this->RANK) && (!$this->get($this->RANK))) {
$qr_fmax = $o_db->query("SELECT MAX(".$this->RANK.") m FROM ".$this->TABLE);
$qr_fmax->nextRow();
$vs_field_value = $qr_fmax->get("m")+1;
$this->set($vs_field, $vs_field_value);
}
}
$vs_fields .= "$vs_field,";
$v = $vs_field_value;
if (!trim($v)) { $v = 0; }
if (!is_numeric($v)) {
$this->postError(1100,_t("Number is invalid for %1 [%2]", $vs_field, $v),"BaseModel->insert()");
if ($vb_we_set_transaction) { $this->removeTransaction(false); }
return false;
}
$vs_values .= $v.",";
break;
# -----------------------------
case (FT_TIMECODE):
$vs_fields .= $vs_field.",";
$v = $vs_field_value;
if (!trim($v)) { $v = 0; }
if (!is_numeric($v)) {
$this->postError(1100, _t("Timecode is invalid"),"BaseModel->insert()");
if ($vb_we_set_transaction) { $this->removeTransaction(false); }
return false;
}
$vs_values .= $v.",";
break;
# -----------------------------
case (FT_MEDIA):
$vs_fields .= $vs_field.",";
$vs_values .= "'',";
$va_media_fields[] = $vs_field;
break;
# -----------------------------
case (FT_FILE):
$vs_fields .= $vs_field.",";
$vs_values .= "'',";
$va_file_fields[] = $vs_field;
break;
# -----------------------------
case (FT_TEXT):
case (FT_PASSWORD):
$vs_fields .= $vs_field.",";
$vs_value = $this->quote($this->get($vs_field));
$vs_values .= $vs_value.",";
break;
# -----------------------------
case (FT_VARS):
$vs_fields .= $vs_field.",";
$vs_values .= $this->quote(caSerializeForDatabase($this->get($vs_field), (isset($va_attr['COMPRESS']) && $va_attr['COMPRESS']) ? true : false)).",";
break;
# -----------------------------
default:
# Should never be executed
die("$vs_field not caught in insert()");
# -----------------------------
}
}
}
if ($this->numErrors() == 0) {
$vs_fields = substr($vs_fields,0,strlen($vs_fields)-1); # remove trailing comma
$vs_values = substr($vs_values,0,strlen($vs_values)-1); # remove trailing comma
$vs_sql = "INSERT INTO ".$this->TABLE." ($vs_fields) VALUES ($vs_values)";
if ($this->debug) echo $vs_sql;
$o_db->query($vs_sql);
if ($o_db->numErrors() == 0) {
if ($this->getFieldInfo($this->primaryKey(), "IDENTITY")) {
$this->_FIELD_VALUES[$this->primaryKey()] = $o_db->getLastInsertID();
}
if ((sizeof($va_media_fields) > 0) || (sizeof($va_file_fields) > 0) || ($this->getHierarchyType() == __CA_HIER_TYPE_ADHOC_MONO__)) {
$vs_sql = "";
if (sizeof($va_media_fields) > 0) {
foreach($va_media_fields as $f) {
if($vs_msql = $this->_processMedia($f, array('delete_old_media' => false))) {
$vs_sql .= $vs_msql;
}
}
}
if (sizeof($va_file_fields) > 0) {
foreach($va_file_fields as $f) {
if($vs_msql = $this->_processFiles($f)) {
$vs_sql .= $vs_msql;
}
}
}
if($this->getHierarchyType() == __CA_HIER_TYPE_ADHOC_MONO__) { // Ad-hoc hierarchy
if (!$this->get($this->getProperty('HIERARCHY_ID_FLD'))) {
$vs_sql .= $this->getProperty('HIERARCHY_ID_FLD').' = '.$this->getPrimaryKey().' ';
}
}
if ($this->numErrors() == 0) {
$vs_sql = substr($vs_sql, 0, strlen($vs_sql) - 1);
if ($vs_sql) {
$o_db->query("UPDATE ".$this->tableName()." SET ".$vs_sql." WHERE ".$this->primaryKey()." = ?", $this->getPrimaryKey(1));
}
} else {
# media and/or file error
$o_db->query("DELETE FROM ".$this->tableName()." WHERE ".$this->primaryKey()." = ?", $this->getPrimaryKey(1));
$this->_FIELD_VALUES[$this->primaryKey()] = "";
if ($vb_we_set_transaction) { $this->removeTransaction(false); }
return false;
}
}
$this->_FILES_CLEAR = array();
$this->logChange("I");
#
# update search index
#
$vn_id = $this->getPrimaryKey();
if ((!isset($pa_options['dont_do_search_indexing']) || (!$pa_options['dont_do_search_indexing'])) && !defined('__CA_DONT_DO_SEARCH_INDEXING__')) {
$this->doSearchIndexing();
}
if ($vb_we_set_transaction) { $this->removeTransaction(true); }
$this->_FIELD_VALUE_CHANGED = array();
return $vn_id;
} else {
foreach($o_db->errors() as $o_e) {
$this->postError($o_e->getErrorNumber(), $o_e->getErrorDescription().' ['.$o_e->getErrorNumber().']', "BaseModel->insert()");
}
if ($vb_we_set_transaction) { $this->removeTransaction(false); }
return false;
}
} else {
foreach($o_db->errors() as $o_e) {
switch($vn_err_num = $o_e->getErrorNumber()) {
case 251: // violation of unique key (duplicate record)
$va_indices = $o_db->getIndices($this->tableName()); // try to get key info
if (preg_match("/for key [']{0,1}([\w]+)[']{0,1}$/", $o_e->getErrorDescription(), $va_matches)) {
$va_field_labels = array();
foreach($va_indices[$va_matches[1]]['fields'] as $vs_col_name) {
$va_tmp = $this->getFieldInfo($vs_col_name);
$va_field_labels[] = $va_tmp['LABEL'];
}
$vs_last_name = array_pop($va_field_labels);
if (sizeof($va_field_labels) > 0) {
$vs_err_desc = _t("The combination of %1 and %2 must be unique", join(', ', $va_field_labels), $vs_last_name);
} else {
$vs_err_desc = _t("The value of %1 must be unique", $vs_last_name);
}
} else {
$vs_err_desc = $o_e->getErrorDescription();
}
$this->postError($vn_err_num, $vs_err_desc, "BaseModel->insert()");
break;
default:
$this->postError($vn_err_num, $o_e->getErrorDescription().' ['.$vn_err_num.']', "BaseModel->insert()");
break;
}
}
if ($vb_we_set_transaction) { $this->removeTransaction(false); }
return false;
}
} else {
$this->postError(400, _t("Mode was %1; must be write", $this->getMode(true)),"BaseModel->insert()");
return false;
}
}
/**
* Generic method to save content properties of object to database fields
* Use this, if you've contructed your BaseModel object to represent an existing record
* if you've loaded an existing record.
*
* @param array $pa_options options array
* possible options (keys):
* dont_check_circular_references = when dealing with strict monohierarchical lists (also known as trees), you can use this option to disable checks for circuits in the graph
* update_only_media_versions = when set to an array of valid media version names, media is only processed for the specified versions
* force = if set field values are not verified prior to performing the update
* @return bool success state
*/
public function update ($pa_options=null) {
if (!is_array($pa_options)) { $pa_options = array(); }
$this->field_conflicts = array();
$this->clearErrors();
$va_rebuild_hierarchical_index = null;
if (!$this->getPrimaryKey()) {
$this->postError(765, _t("Can't do update() on new record; use insert() instead"),"BaseModel->update()");
return false;
}
if ($this->getMode() == ACCESS_WRITE) {
// do form timestamp check
if (isset($_REQUEST['form_timestamp']) && ($vn_form_timestamp = $_REQUEST['form_timestamp'])) {
$va_possible_conflicts = $this->getChangeLog(null, array('range' => array('start' => $vn_form_timestamp, 'end' => time()), 'excludeUnitID' => $this->getCurrentLoggingUnitID()));
if (sizeof($va_possible_conflicts)) {
$va_conflict_users = array();
$va_conflict_fields = array();
foreach($va_possible_conflicts as $va_conflict) {
$vs_user_desc = trim($va_conflict['fname'].' '.$va_conflict['lname']);
if ($vs_user_email = trim($va_conflict['email'])) {
$vs_user_desc .= ' ('.$vs_user_email.')';
}
if ($vs_user_desc) { $va_conflict_users[$vs_user_desc] = true; }
if(isset($va_conflict['snapshot']) && is_array($va_conflict['snapshot'])) {
foreach($va_conflict['snapshot'] as $vs_field => $vs_value) {
if ($va_conflict_fields[$vs_field]) { continue; }
$va_conflict_fields[$vs_field] = true;
}
}
}
$this->field_conflicts = array_keys($va_conflict_fields);
switch (sizeof($va_conflict_users)) {
case 0:
$this->postError(795, _t('Changes have been made since you loaded this data. Save again to overwrite the changes or cancel to keep the changes.'), "BaseModel->update()");
break;
case 1:
$this->postError(795, _t('Changes have been made since you loaded this data by %1. Save again to overwrite the changes or cancel to keep the changes.', join(', ', array_keys($va_conflict_users))), "BaseModel->update()");
break;
default:
$this->postError(795, _t('Changes have been made since you loaded this data by these users: %1. Save again to overwrite the changes or cancel to keep the changes.', join(', ', array_keys($va_conflict_users))), "BaseModel->update()");
break;
}
}
}
$vb_we_set_transaction = false;
if (!$this->inTransaction()) {
$this->setTransaction(new Transaction($this->getDb()));
$vb_we_set_transaction = true;
}
$o_db = $this->getDb();
if ($vb_is_hierarchical = $this->isHierarchical()) {
$vs_parent_id_fld = $this->getProperty('HIERARCHY_PARENT_ID_FLD');
$vs_hier_left_fld = $this->getProperty('HIERARCHY_LEFT_INDEX_FLD');
$vs_hier_right_fld = $this->getProperty('HIERARCHY_RIGHT_INDEX_FLD');
$vs_hier_id_fld = $this->getProperty('HIERARCHY_ID_FLD');
// save original left/right index values - we need them later to recalculate
// the indexing values for children of this record
$vn_orig_hier_left = $this->get($vs_hier_left_fld);
$vn_orig_hier_right = $this->get($vs_hier_right_fld);
$vn_parent_id = $this->get($vs_parent_id_fld);
if ($vb_parent_id_changed = $this->changed($vs_parent_id_fld)) {
$va_parent_info = $this->_getHierarchyParent($vn_parent_id);
if (!$pa_options['dont_check_circular_references']) {
$va_ids = $this->getHierarchyIDs($this->getPrimaryKey());
if (in_array($this->get($vs_parent_id_fld), $va_ids)) {
$this->postError(2010,_t("Cannot move %1 under its sub-record", $this->getProperty('NAME_SINGULAR')),"BaseModel->update()");
if ($vb_we_set_transaction) { $this->removeTransaction(false); }
return false;
}
}
//if (is_null($this->getOriginalValue($vs_parent_id_fld))) {
// don't allow moves of hierarchy roots - just ignore the move and keep on going with the update
// $this->set($vs_parent_id_fld, null);
// $vb_parent_id_changed = false;
//} else {
switch($this->getHierarchyType()) {
case __CA_HIER_TYPE_SIMPLE_MONO__: // you only need to set parent_id for this type of hierarchy
break;
case __CA_HIER_TYPE_MULTI_MONO__: // you need to set parent_id; you only need to set hierarchy_id if you're creating a root
if (!($vn_hierarchy_id = $this->get($this->getProperty('HIERARCHY_ID_FLD')))) {
$this->set($this->getProperty('HIERARCHY_ID_FLD'), $va_parent_info[$this->getProperty('HIERARCHY_ID_FLD')]);
}
if (!($vn_hierarchy_id = $this->get($vs_hier_id_fld))) {
$this->postError(2030, _t("Hierarchy ID must be specified for this update"), "BaseModel->update()");
if ($vb_we_set_transaction) { $this->removeTransaction(false); }
return false;
}
// Moving between hierarchies
if ($this->get($vs_hier_id_fld) != $va_parent_info[$vs_hier_id_fld]) {
$vn_hierarchy_id = $va_parent_info[$vs_hier_id_fld];
$this->set($this->getProperty('HIERARCHY_ID_FLD'), $vn_hierarchy_id);
if (is_array($va_children = $this->_getHierarchyChildren(array($this->getPrimaryKey())))) {
$va_rebuild_hierarchical_index = $va_children;
}
}
break;
case __CA_HIER_TYPE_ADHOC_MONO__: // you need to set parent_id for this hierarchy; you never need to set hierarchy_id
if ($va_parent_info) {
// set hierarchy to that of root
if (sizeof($va_ancestors = $this->getHierarchyAncestors($vn_parent_id, array('idsOnly' => true, 'includeSelf' => true)))) {
$vn_hierarchy_id = array_pop($va_ancestors);
} else {
$vn_hierarchy_id = $this->getPrimaryKey();
}
$this->set($this->getProperty('HIERARCHY_ID_FLD'), $vn_hierarchy_id);
if (is_array($va_children = $this->_getHierarchyChildren(array($this->getPrimaryKey())))) {
$va_rebuild_hierarchical_index = $va_children;
}
}
// if there's no parent then this is a root in which case HIERARCHY_ID_FLD should be set to the primary
// key of the row, which we'll know once we insert it (so we must set it after insert)
break;
case __CA_HIER_TYPE_MULTI_POLY__: // TODO: implement
break;
default:
die("Invalid hierarchy type: ".$this->getHierarchyType());
break;
}
if ($va_parent_info) {
$va_hier_indexing = $this->_calcHierarchicalIndexing($va_parent_info);
} else {
$va_hier_indexing = array('left' => 1, 'right' => pow(2,32));
}
$this->set($this->getProperty('HIERARCHY_LEFT_INDEX_FLD'), $va_hier_indexing['left']);
$this->set($this->getProperty('HIERARCHY_RIGHT_INDEX_FLD'), $va_hier_indexing['right']);
//}
}
}
$vs_sql = "UPDATE ".$this->TABLE." SET ";
$va_many_to_one_relations = $this->_DATAMODEL->getManyToOneRelations($this->tableName());
$vn_fields_that_have_been_set = 0;
foreach ($this->FIELDS as $vs_field => $va_attr) {
if (isset($va_attr['DONT_PROCESS_DURING_INSERT_UPDATE']) && (bool)$va_attr['DONT_PROCESS_DURING_INSERT_UPDATE']) { continue; }
if (isset($va_attr['IDENTITY']) && $va_attr['IDENTITY']) { continue; } // never update identity fields
$vs_field_type = isset($va_attr["FIELD_TYPE"]) ? $va_attr["FIELD_TYPE"] : null; # field type
$vn_datatype = $this->_getFieldTypeType($vs_field); # field's underlying datatype
$vs_field_value = $this->get($vs_field, array("TIMECODE_FORMAT" => "RAW"));
# --- check bounds (value, length and choice lists)
$pb_need_reload = false;
if (!isset($pa_options['force']) || !$pa_options['force']) {
if (!$this->verifyFieldValue($vs_field, $vs_field_value, $pb_need_reload)) {
# verifyFieldValue() posts errors so we don't have to do anything here
# No query will be run if there are errors so we don't have to worry about invalid
# values being written into the database. By not immediately bailing on an error we
# can return a list of *all* input errors to the caller; this is perfect listing all form input errors in
# a form-based user interface
}
}
if ($pb_need_reload) {
$vs_field_value = $this->get($vs_field, array("TIMECODE_FORMAT" => "RAW")); //
}
if (!isset($va_attr["IS_NULL"])) { $va_attr["IS_NULL"] = 0; }
if ($va_attr["IS_NULL"] && ($vs_field_value=="")) {
$vs_field_value_is_null = 1;
} else {
$vs_field_value_is_null = 0;
}
# --- check ->one relations
if (isset($va_many_to_one_relations[$vs_field]) && $va_many_to_one_relations[$vs_field]) {
# Nothing to verify if key is null
if (!(($va_attr["IS_NULL"]) && ($vs_field_value == ""))) {
if ($t_many_table = $this->_DATAMODEL->getTableInstance($va_many_to_one_relations[$vs_field]["one_table"])) {
if ($this->inTransaction()) {
$t_many_table->setTransaction($this->getTransaction());
}
$t_many_table->load($this->get($va_many_to_one_relations[$vs_field]["many_table_field"]));
}
if ($t_many_table->numErrors()) {
$this->postError(750,_t("%1 record with $vs_field = %2 does not exist", $t_many_table->tableName(), $this->get($vs_field)),"BaseModel->update()");
}
}
}
if (($vs_field_value_is_null) && (!(isset($va_attr["UPDATE_ON_UPDATE"]) && $va_attr["UPDATE_ON_UPDATE"]))) {
if (($vs_field_type == FT_DATERANGE) || ($vs_field_type == FT_HISTORIC_DATERANGE) || ($vs_field_type == FT_TIMERANGE)) {
$start_field_name = $va_attr["START"];
$end_field_name = $va_attr["END"];
$vs_sql .= "$start_field_name = NULL, $end_field_name = NULL,";
} else {
$vs_sql .= "$vs_field = NULL,";
}
$vn_fields_that_have_been_set++;
} else {
if (($vs_field_type != FT_TIMESTAMP) && !$this->changed($vs_field)) { continue; } // don't try to update fields that haven't changed -- saves time, especially for large fields like FT_VARS and FT_TEXT when text is long
switch($vs_field_type) {
# -----------------------------
case (FT_NUMBER):
case (FT_BIT):
$vm_val = isset($this->_FIELD_VALUES[$vs_field]) ? $this->_FIELD_VALUES[$vs_field] : null;
if (!trim($vm_val)) { $vm_val = 0; }
if (!is_numeric($vm_val)) {
$this->postError(1100,_t("Number is invalid for %1", $vs_field),"BaseModel->update()");
if ($vb_we_set_transaction) { $this->removeTransaction(false); }
return false;
}
$vs_sql .= "{$vs_field} = {$vm_val},";
$vn_fields_that_have_been_set++;
break;
# -----------------------------
case (FT_TEXT):
case (FT_PASSWORD):
$vm_val = isset($this->_FIELD_VALUES[$vs_field]) ? $this->_FIELD_VALUES[$vs_field] : null;
$vs_sql .= "{$vs_field} = ".$this->quote($vm_val).",";
$vn_fields_that_have_been_set++;
break;
# -----------------------------
case (FT_VARS):
$vm_val = isset($this->_FIELD_VALUES[$vs_field]) ? $this->_FIELD_VALUES[$vs_field] : null;
$vs_sql .= "{$vs_field} = ".$this->quote(caSerializeForDatabase($vm_val, ((isset($va_attr['COMPRESS']) && $va_attr['COMPRESS']) ? true : false))).",";
$vn_fields_that_have_been_set++;
break;
# -----------------------------
case (FT_DATETIME):
case (FT_HISTORIC_DATETIME):
case (FT_DATE):
case (FT_HISTORIC_DATE):
$vm_val = isset($this->_FIELD_VALUES[$vs_field]) ? $this->_FIELD_VALUES[$vs_field] : null;
if ($vm_val == "") {
$this->postError(1805,_t("Date is undefined but field does not support NULL values"),"BaseModel->update()");
if ($vb_we_set_transaction) { $this->removeTransaction(false); }
return false;
}
if (!is_numeric($vm_val)) {
$this->postError(1100,_t("Date is invalid for %1", $vs_field),"BaseModel->update()");
if ($vb_we_set_transaction) { $this->removeTransaction(false); }
return false;
}
$vs_sql .= "{$vs_field} = {$vm_val},"; # output as is
$vn_fields_that_have_been_set++;
break;
# -----------------------------
case (FT_TIME):
$vm_val = isset($this->_FIELD_VALUES[$vs_field]) ? $this->_FIELD_VALUES[$vs_field] : null;
if ($vm_val == "") {
$this->postError(1805, _t("Time is undefined but field does not support NULL values"),"BaseModel->update()");
if ($vb_we_set_transaction) { $this->removeTransaction(false); }
return false;
}
if (!is_numeric($vm_val)) {
$this->postError(1100, _t("Time is invalid for %1", $vs_field),"BaseModel->update()");
if ($vb_we_set_transaction) { $this->removeTransaction(false); }
return false;
}
$vs_sql .= "{$vs_field} = {$vm_val},"; # output as is
$vn_fields_that_have_been_set++;
break;
# -----------------------------
case (FT_TIMESTAMP):
if (isset($va_attr["UPDATE_ON_UPDATE"]) && $va_attr["UPDATE_ON_UPDATE"]) {
$vs_sql .= "{$vs_field} = ".time().",";
$vn_fields_that_have_been_set++;
}
break;
# -----------------------------
case (FT_DATERANGE):
case (FT_HISTORIC_DATERANGE):
$vn_start_field_name = $va_attr["START"];
$vn_end_field_name = $va_attr["END"];
if (($this->_FIELD_VALUES[$vn_start_field_name] == "") || ($this->_FIELD_VALUES[$vn_end_field_name] == "")) {
$this->postError(1805,_t("Daterange is undefined but field does not support NULL values"),"BaseModel->update()");
if ($vb_we_set_transaction) { $this->removeTransaction(false); }
return false;
}
if (!is_numeric($this->_FIELD_VALUES[$vn_start_field_name])) {
$this->postError(1100,_t("Starting date is invalid"),"BaseModel->update()");
if ($vb_we_set_transaction) { $this->removeTransaction(false); }
return false;
}
if (!is_numeric($this->_FIELD_VALUES[$vn_end_field_name])) {
$this->postError(1100,_t("Ending date is invalid"),"BaseModel->update()");
if ($vb_we_set_transaction) { $this->removeTransaction(false); }
return false;
}
$vs_sql .= "{$vn_start_field_name} = ".$this->_FIELD_VALUES[$vn_start_field_name].", {$vn_end_field_name} = ".$this->_FIELD_VALUES[$vn_end_field_name].",";
$vn_fields_that_have_been_set++;
break;
# -----------------------------
case (FT_TIMERANGE):
$vn_start_field_name = $va_attr["START"];
$vn_end_field_name = $va_attr["END"];
if (($this->_FIELD_VALUES[$vn_start_field_name] == "") || ($this->_FIELD_VALUES[$vn_end_field_name] == "")) {
$this->postError(1805,_t("Time range is undefined but field does not support NULL values"),"BaseModel->update()");
if ($vb_we_set_transaction) { $this->removeTransaction(false); }
return false;
}
if (!is_numeric($this->_FIELD_VALUES[$vn_start_field_name])) {
$this->postError(1100,_t("Starting time is invalid"),"BaseModel->update()");
if ($vb_we_set_transaction) { $this->removeTransaction(false); }
return false;
}
if (!is_numeric($this->_FIELD_VALUES[$vn_end_field_name])) {
$this->postError(1100,_t("Ending time is invalid"),"BaseModel->update()");
if ($vb_we_set_transaction) { $this->removeTransaction(false); }
return false;
}
$vs_sql .= "{$vn_start_field_name} = ".$this->_FIELD_VALUES[$vn_start_field_name].", {$vn_end_field_name} = ".$this->_FIELD_VALUES[$vn_end_field_name].",";
$vn_fields_that_have_been_set++;
break;
# -----------------------------
case (FT_TIMECODE):
$vm_val = isset($this->_FIELD_VALUES[$vs_field]) ? $this->_FIELD_VALUES[$vs_field] : null;
if (!trim($vm_val)) { $vm_val = 0; }
if (!is_numeric($vm_val)) {
$this->postError(1100,_t("Timecode is invalid"),"BaseModel->update()");
if ($vb_we_set_transaction) { $this->removeTransaction(false); }
return false;
}
$vs_sql .= "{$vs_field} = {$vm_val},";
$vn_fields_that_have_been_set++;
break;
# -----------------------------
case (FT_MEDIA):
$va_limit_to_versions = (isset($pa_options['update_only_media_versions']) ? $pa_options['update_only_media_versions'] : null);
if ($vs_media_sql = $this->_processMedia($vs_field, array('these_versions_only' => $va_limit_to_versions))) {
$vs_sql .= $vs_media_sql;
$vn_fields_that_have_been_set++;
} else {
if ($this->numErrors() > 0) {
if ($vb_we_set_transaction) { $this->removeTransaction(false); }
return false;
}
}
break;
# -----------------------------
case (FT_FILE):
if ($vs_file_sql = $this->_processFiles($vs_field)) {
$vs_sql .= $vs_file_sql;
$vn_fields_that_have_been_set++;
} else {
if ($this->numErrors() > 0) {
if ($vb_we_set_transaction) { $this->removeTransaction(false); }
return false;
}
}
break;
# -----------------------------
}
}
}
if ($this->numErrors() == 0) {
if ($vn_fields_that_have_been_set > 0) {
$vs_sql = substr($vs_sql,0,strlen($vs_sql)-1); # remove trailing comma
$vs_sql .= " WHERE ".$this->PRIMARY_KEY." = ".$this->getPrimaryKey(1);
if ($this->debug) echo $vs_sql;
$o_db->query($vs_sql);
if ($o_db->numErrors()) {
foreach($o_db->errors() as $o_e) {
switch($vn_err_num = $o_e->getErrorNumber()) {
case 251: // violation of unique key (duplicate record)
// try to get key info
$va_indices = $o_db->getIndices($this->tableName());
if (preg_match("/for key [']{0,1}([\w]+)[']{0,1}$/", $o_e->getErrorDescription(), $va_matches)) {
$va_field_labels = array();
foreach($va_indices[$va_matches[1]]['fields'] as $vs_col_name) {
$va_tmp = $this->getFieldInfo($vs_col_name);
$va_field_labels[] = $va_tmp['LABEL'];
}
$vs_last_name = array_pop($va_field_labels);
if (sizeof($va_field_labels) > 0) {
$vs_err_desc = "The combination of ".join(', ', $va_field_labels).' and '.$vs_last_name." must be unique";
} else {
$vs_err_desc = "The value of {$vs_last_name} must be unique";
}
} else {
$vs_err_desc = $o_e->getErrorDescription();
}
$this->postError($vn_err_num, $vs_err_desc, "BaseModel->insert()");
break;
default:
$this->postError($vn_err_num, $o_e->getErrorDescription().' ['.$vn_err_num.']', "BaseModel->update()");
break;
}
}
if ($vb_we_set_transaction) { $this->removeTransaction(false); }
return false;
} else {
if (($vb_is_hierarchical) && ($vb_parent_id_changed)) {
// recalulate left/right indexing of sub-records
$vn_interval_start = $this->get($vs_hier_left_fld);
$vn_interval_end = $this->get($vs_hier_right_fld);
if (($vn_interval_start > 0) && ($vn_interval_end > 0)) {
if ($vs_hier_id_fld) {
$vs_hier_sql = ' AND ('.$vs_hier_id_fld.' = '.$this->get($vs_hier_id_fld).')';
} else {
$vs_hier_sql = "";
}
$vn_ratio = ($vn_interval_end - $vn_interval_start)/($vn_orig_hier_right - $vn_orig_hier_left);
$vs_sql = "
UPDATE ".$this->tableName()."
SET
$vs_hier_left_fld = ($vn_interval_start + (($vs_hier_left_fld - $vn_orig_hier_left) * $vn_ratio)),
$vs_hier_right_fld = ($vn_interval_end + (($vs_hier_right_fld - $vn_orig_hier_right) * $vn_ratio))
WHERE
(".$vs_hier_left_fld." BETWEEN ".$vn_orig_hier_left." AND ".$vn_orig_hier_right.")
$vs_hier_sql
";
//print "<hr>$vs_sql<hr>";
$o_db->query($vs_sql);
if ($vn_err = $o_db->numErrors()) {
$this->postError(2030, _t("Could not update sub records in hierarchy: [%1] %2", $vs_sql, join(';', $o_db->getErrors())),"BaseModel->update()");
if ($vb_we_set_transaction) { $this->removeTransaction(false); }
return false;
}
} else {
$this->postError(2045, _t("Parent record had invalid hierarchical indexing (should not happen!)"), "BaseModel->update()");
if ($vb_we_set_transaction) { $this->removeTransaction(false); }
return false;
}
}
}
if ((!isset($pa_options['dont_do_search_indexing']) || (!$pa_options['dont_do_search_indexing'])) && !defined('__CA_DONT_DO_SEARCH_INDEXING__')) {
# update search index
$this->doSearchIndexing();
}
if (is_array($va_rebuild_hierarchical_index)) {
//$this->rebuildHierarchicalIndex($this->get($vs_hier_id_fld));
$t_instance = $this->_DATAMODEL->getInstanceByTableName($this->tableName());
foreach($va_rebuild_hierarchical_index as $vn_child_id) {
if ($t_instance->load($vn_child_id)) {
$t_instance->setMode(ACCESS_WRITE);
$t_instance->set($this->getProperty('HIERARCHY_ID_FLD'), $vn_hierarchy_id);
$t_instance->update();
if ($t_instance->numErrors()) {
$this->errors = array_merge($this->errors, $t_instance->errors);
}
}
}
}
$this->logChange("U");
$this->_FILES_CLEAR = array();
}
if ($vb_we_set_transaction) { $this->removeTransaction(true); }
$this->_FIELD_VALUE_CHANGED = array();
return true;
} else {
if ($vb_we_set_transaction) { $this->removeTransaction(false); }
return false;
}
} else {
$this->postError(400, _t("Mode was %1; must be write or admin", $this->getMode(true)),"BaseModel->update()");
return false;
}
}
public function doSearchIndexing($pa_changed_field_values_array=null, $pb_reindex_mode=false, $ps_engine=null) {
if (defined("__CA_DONT_DO_SEARCH_INDEXING__")) { return; }
if (is_null($pa_changed_field_values_array)) {
$pa_changed_field_values_array = $this->getChangedFieldValuesArray();
}
if (!BaseModel::$search_indexer) {
BaseModel::$search_indexer = new SearchIndexer($this->getDb(), $ps_engine);
}
BaseModel::$search_indexer->indexRow($this->tableNum(), $this->getPrimaryKey(), $this->getFieldValuesArray(), $pb_reindex_mode, null, $pa_changed_field_values_array, $this->_FIELD_VALUES_OLD);
}
/**
* Delete record represented by this object. Uses the Datamodel object
* to generate possible dependencies and relationships.
*
* @param bool $pb_delete_related delete stuff related to the record? pass non-zero value if you want to.
* @param array $pa_options Options for delete process. Options are:
* hard = if true records which can support "soft" delete are really deleted rather than simply being marked as deleted
* @param array $pa_fields instead of deleting the record represented by this object instance you can
* pass an array of field => value assignments which is used in a SQL-DELETE-WHERE clause.
* @param array $pa_table_list this is your possibility to pass an array of table name => true assignments
* to specify which tables to omit when deleting related stuff
*/
public function delete ($pb_delete_related=false, $pa_options=null, $pa_fields=null, $pa_table_list=null) {
if ($this->hasField('deleted') && (!isset($pa_options['hard']) || !$pa_options['hard'])) {
$this->setMode(ACCESS_WRITE);
$this->set('deleted', 1);
return $this->update(array('force' => true));
}
$this->clearErrors();
if ((!$this->getPrimaryKey()) && (!is_array($pa_fields))) { # is there a record loaded?
$this->postError(770, _t("No record loaded"),"BaseModel->delete()");
return false;
}
if (!is_array($pa_table_list)) {
$pa_table_list = array();
}
$pa_table_list[$this->tableName()] = true;
if ($this->getMode() == ACCESS_WRITE) {
$vb_we_set_transaction = false;
if (!$this->inTransaction()) {
$o_t = new Transaction($this->getDb());
$this->setTransaction($o_t);
$vb_we_set_transaction = true;
}
$o_db = $this->getDb();
if (is_array($pa_fields)) {
$vs_sql = "DELETE FROM ".$this->tableName()." WHERE ";
$vs_wheres = "";
while(list($vs_field, $vm_val) = each($pa_fields)) {
$vn_datatype = $this->_getFieldTypeType($vs_field);
switch($vn_datatype) {
# -----------------------------
case (0): # number
if ($vm_val == "") { $vm_val = 0; }
break;
# -----------------------------
case (1): # string
$vm_val = $this->quote($vm_val);
break;
# -----------------------------
}
if ($vs_wheres) {
$vs_wheres .= " AND ";
}
$vs_wheres .= "($vs_field = $vm_val)";
}
$vs_sql .= $vs_wheres;
} else {
$vs_sql = "DELETE FROM ".$this->tableName()." WHERE ".$this->primaryKey()." = ".$this->getPrimaryKey(1);
}
if ($this->isHierarchical()) {
// TODO: implement delete of children records
$vs_parent_id_fld = $this->getProperty('HIERARCHY_PARENT_ID_FLD');
$qr_res = $o_db->query("
SELECT ".$this->primaryKey()."
FROM ".$this->tableName()."
WHERE
{$vs_parent_id_fld} = ?
", $this->getPrimaryKey());
if ($qr_res->nextRow()) {
$this->postError(780, _t("Can't delete item because it has sub-records"),"BaseModel->delete()");
if ($vb_we_set_transaction) { $this->removeTransaction(false); }
return false;
}
}
#
# --- delete search index entries
#
$vn_id = $this->getPrimaryKey();
// TODO: FIX THIS ISSUE!
// NOTE: we delete the indexing here, before we actually do the
// SQL delete because the search indexer relies upon the relevant
// relationships to be intact (ie. exist) in order to properly remove the indexing for them.
//
// In particular, the incremental indexing used by the MySQL Fulltext plugin fails to properly
// update if it can't traverse the relationships it is to remove.
//
// By removing the search indexing here we run the risk of corrupting the search index if the SQL
// delete subsequently fails. Specifically, the indexing for rows that still exist in the database
// will be removed. Wrapping everything in a MySQL transaction deals with it for MySQL Fulltext, but
// other non-SQL engines (Lucene, SOLR, etc.) are still affected.
//
// At some point we need to come up with something clever to handle this. Most likely it means moving all of the actual
// analysis to startRowUnindexing() and only executing commands in commitRowUnIndexing(). For now we blithely assume that
// SQL deletes always succeed. If they don't we can always reindex. Only the indexing is affected, not the underlying data.
if(!defined('__CA_DONT_DO_SEARCH_INDEXING__')) {
if (!BaseModel::$search_indexer) {
BaseModel::$search_indexer = new SearchIndexer($this->getDb());
}
BaseModel::$search_indexer->startRowUnIndexing($this->tableNum(), $vn_id);
BaseModel::$search_indexer->commitRowUnIndexing($this->tableNum(), $vn_id);
}
# --- Check ->many and many<->many relations
$va_one_to_many_relations = $this->_DATAMODEL->getOneToManyRelations($this->tableName());
#
# Note: cascading delete code is very slow when used
# on a record with a large number of related records as
# each record in check individually for cascading deletes...
# it is possible to make this *much* faster by crafting clever-er queries
#
if (is_array($va_one_to_many_relations)) {
foreach($va_one_to_many_relations as $vs_many_table => $va_info) {
foreach($va_info as $va_relationship) {
if (isset($pa_table_list[$vs_many_table.'/'.$va_relationship["many_table_field"]]) && $pa_table_list[$vs_many_table.'/'.$va_relationship["many_table_field"]]) { continue; }
# do any records exist?
$t_related = $this->_DATAMODEL->getTableInstance($vs_many_table);
$t_related->setTransaction($this->getTransaction());
$qr_record_check = $o_db->query("
SELECT ".$t_related->primaryKey()."
FROM ".$vs_many_table."
WHERE
(".$va_relationship["many_table_field"]." = ".$this->getPrimaryKey(1).")
");
$pa_table_list[$vs_many_table.'/'.$va_relationship["many_table_field"]] = true;
//print "FOR ".$vs_many_table.'/'.$va_relationship["many_table_field"].":".$qr_record_check->numRows()."<br>\n";
if ($qr_record_check->numRows() > 0) {
if ($pb_delete_related) {
while($qr_record_check->nextRow()) {
if ($t_related->load($qr_record_check->get($t_related->primaryKey()))) {
$t_related->setMode(ACCESS_WRITE);
$t_related->delete($pb_delete_related, $pa_options, null, $pa_table_list);
if ($t_related->numErrors()) {
$this->postError(790, _t("Can't delete item because items related to it have sub-records (%1)", $vs_many_table),"BaseModel->delete()");
if ($vb_we_set_transaction) { $this->removeTransaction(false); }
return false;
}
}
}
} else {
$this->postError(780, _t("Can't delete item because it is in use (%1)", $vs_many_table),"BaseModel->delete()");
if ($vb_we_set_transaction) { $this->removeTransaction(false); }
return false;
}
}
}
}
}
# --- do deletion
if ($this->debug) echo $vs_sql;
$o_db->query($vs_sql);
if ($o_db->numErrors() > 0) {
$this->errors = $o_db->errors();
if ($vb_we_set_transaction) { $this->removeTransaction(false); }
return false;
}
# cancel and pending queued tasks against this record
$tq = new TaskQueue();
$tq->cancelPendingTasksForRow(join("/", array($this->tableName(), $vn_id)));
$this->_FILES_CLEAR = array();
# --- delete media and file field files
foreach($this->FIELDS as $f => $attr) {
switch($attr['FIELD_TYPE']) {
case FT_MEDIA:
$versions = $this->getMediaVersions($f);
foreach ($versions as $v) {
$this->_removeMedia($f, $v);
}
break;
case FT_FILE:
@unlink($this->getFilePath($f));
#--- delete conversions
#
foreach ($this->getFileConversions($f) as $vs_format => $va_file_conversion) {
@unlink($this->getFileConversionPath($f, $vs_format));
}
break;
}
}
if ($o_db->numErrors() == 0) {
//if ($vb_is_hierarchical = $this->isHierarchical()) {
//}
# clear object
$this->logChange("D");
$this->clear();
} else {
if ($vb_we_set_transaction) { $this->removeTransaction(false); }
return false;
}
if ($vb_we_set_transaction) { $this->removeTransaction(true); }
return true;
} else {
$this->postError(400, _t("Mode was %1; must be write", $this->getMode(true)),"BaseModel->delete()");
return false;
}
}
# --------------------------------------------------------------------------------
# --- Uploaded media handling
# --------------------------------------------------------------------------------
/**
* Check if media content is mirrored (depending on settings in configuration file)
*
* @return bool
*/
public function mediaIsMirrored($field, $version) {
$media_info = $this->get($field);
if (!is_array($media_info)) {
return "";
}
$vi = $this->_MEDIA_VOLUMES->getVolumeInformation($media_info[$version]["VOLUME"]);
if (!is_array($vi)) {
return "";
}
if (is_array($vi["mirrors"])) {
return true;
} else {
return false;
}
}
/**
* Get status of media mirror
*
* @param string $field field name
* @param string $version version of the media file, as defined in media_processing.conf
* @param string media mirror name, as defined in media_volumes.conf
* @return mixed media mirror status
*/
public function getMediaMirrorStatus($field, $version, $mirror="") {
$media_info = $this->get($field);
if (!is_array($media_info)) {
return "";
}
$vi = $this->_MEDIA_VOLUMES->getVolumeInformation($media_info[$version]["VOLUME"]);
if (!is_array($vi)) {
return "";
}
if ($mirror) {
return $media_info["MIRROR_STATUS"][$mirror];
} else {
return $media_info["MIRROR_STATUS"][$vi["accessUsingMirror"]];
}
}
/**
* Retry mirroring of given media field. Sets global error properties on failure.
*
* @param string $ps_field field name
* @param string $ps_version version of the media file, as defined in media_processing.conf
* @return null
*/
public function retryMediaMirror($ps_field, $ps_version) {
global $AUTH_CURRENT_USER_ID;
$va_media_info = $this->get($ps_field);
if (!is_array($va_media_info)) {
return "";
}
$va_volume_info = $this->_MEDIA_VOLUMES->getVolumeInformation($va_media_info[$ps_version]["VOLUME"]);
if (!is_array($va_volume_info)) {
return "";
}
$o_tq = new TaskQueue();
$vs_row_key = join("/", array($this->tableName(), $this->getPrimaryKey()));
$vs_entity_key = join("/", array($this->tableName(), $ps_field, $this->getPrimaryKey(), $ps_version));
foreach($va_media_info["MIRROR_STATUS"] as $vs_mirror_code => $vs_status) {
$va_mirror_info = $va_volume_info["mirrors"][$vs_mirror_code];
$vs_mirror_method = $va_mirror_info["method"];
$vs_queue = $vs_mirror_method."mirror";
switch($vs_status) {
case 'FAIL':
case 'PARTIAL':
if (!($o_tq->cancelPendingTasksForEntity($vs_entity_key))) {
//$this->postError(560, _t("Could not cancel pending tasks: %1", $this->error),"BaseModel->retryMediaMirror()");
//return false;
}
if ($o_tq->addTask(
$vs_queue,
array(
"MIRROR" => $vs_mirror_code,
"VOLUME" => $va_media_info[$ps_version]["VOLUME"],
"FIELD" => $ps_field,
"TABLE" => $this->tableName(),
"VERSION" => $ps_version,
"FILES" => array(
array(
"FILE_PATH" => $this->getMediaPath($ps_field, $ps_version),
"ABS_PATH" => $va_volume_info["absolutePath"],
"HASH" => $this->_FIELD_VALUES[$ps_field][$ps_version]["HASH"],
"FILENAME" => $this->_FIELD_VALUES[$ps_field][$ps_version]["FILENAME"]
)
),
"MIRROR_INFO" => $va_mirror_info,
"PK" => $this->primaryKey(),
"PK_VAL" => $this->getPrimaryKey()
),
array("priority" => 100, "entity_key" => $vs_entity_key, "row_key" => $vs_row_key, 'user_id' => $AUTH_CURRENT_USER_ID)))
{
$va_media_info["MIRROR_STATUS"][$vs_mirror_code] = ""; // pending
$this->setMediaInfo($ps_field, $va_media_info);
$this->setMode(ACCESS_WRITE);
$this->update();
continue;
} else {
$this->postError(100, _t("Couldn't queue mirror using '%1' for version '%2' (handler '%3')", $vs_mirror_method, $ps_version, $queue),"BaseModel->retryMediaMirror()");
}
break;
}
}
}
/**
* Returns url of media file
*
* @param string $ps_field field name
* @param string $ps_version version of the media file, as defined in media_processing.conf
* @param int $pn_page page number, defaults to 1
* @return string the url
*/
public function getMediaUrl($ps_field, $ps_version, $pn_page=1) {
$va_media_info = $this->getMediaInfo($ps_field);
if (!is_array($va_media_info)) {
return "";
}
#
# Is this version externally hosted?
#
if (isset($va_media_info[$ps_version]["EXTERNAL_URL"]) && ($va_media_info[$ps_version]["EXTERNAL_URL"])) {
return $va_media_info[$ps_version]["EXTERNAL_URL"];
}
#
# Is this version queued for processing?
#
if (isset($va_media_info[$ps_version]["QUEUED"]) && ($va_media_info[$ps_version]["QUEUED"])) {
if ($va_media_info[$ps_version]["QUEUED_ICON"]["src"]) {
return $va_media_info[$ps_version]["QUEUED_ICON"]["src"];
} else {
return "";
}
}
$va_volume_info = $this->_MEDIA_VOLUMES->getVolumeInformation($va_media_info[$ps_version]["VOLUME"]);
if (!is_array($va_volume_info)) {
return "";
}
# is this mirrored?
if (
(isset($va_volume_info["accessUsingMirror"]) && $va_volume_info["accessUsingMirror"])
&&
(
isset($va_media_info["MIRROR_STATUS"][$va_volume_info["accessUsingMirror"]])
&&
($va_media_info["MIRROR_STATUS"][$va_volume_info["accessUsingMirror"]] == "SUCCESS")
)
) {
$vs_protocol = $va_volume_info["mirrors"][$va_volume_info["accessUsingMirror"]]["accessProtocol"];
$vs_host = $va_volume_info["mirrors"][$va_volume_info["accessUsingMirror"]]["accessHostname"];
$vs_url_path = $va_volume_info["mirrors"][$va_volume_info["accessUsingMirror"]]["accessUrlPath"];
} else {
$vs_protocol = $va_volume_info["protocol"];
$vs_host = $va_volume_info["hostname"];
$vs_url_path = $va_volume_info["urlPath"];
}
if ($va_media_info[$ps_version]["FILENAME"]) {
$vs_fpath = join("/",array($vs_url_path, $va_media_info[$ps_version]["HASH"], $va_media_info[$ps_version]["MAGIC"]."_".$va_media_info[$ps_version]["FILENAME"]));
return $vs_protocol."://$vs_host".$vs_fpath;
} else {
return "";
}
}
/**
* Returns path of media file
*
* @param string $ps_field field name
* @param string $ps_version version of the media file, as defined in media_processing.conf
* @param int $pn_page page number, defaults to 1
* @return string path of the media file
*/
public function getMediaPath($ps_field, $ps_version, $pn_page=1) {
$va_media_info = $this->getMediaInfo($ps_field);
if (!is_array($va_media_info)) {
return "";
}
#
# Is this version externally hosted?
#
if (isset($va_media_info[$ps_version]["EXTERNAL_URL"]) && ($va_media_info[$ps_version]["EXTERNAL_URL"])) {
return ''; // no local path for externally hosted media
}
#
# Is this version queued for processing?
#
if (isset($va_media_info[$ps_version]["QUEUED"]) && $va_media_info[$ps_version]["QUEUED"]) {
if ($va_media_info[$ps_version]["QUEUED_ICON"]["filepath"]) {
return $va_media_info[$ps_version]["QUEUED_ICON"]["filepath"];
} else {
return "";
}
}
$va_volume_info = $this->_MEDIA_VOLUMES->getVolumeInformation($va_media_info[$ps_version]["VOLUME"]);
if (!is_array($va_volume_info)) {
return "";
}
if ($va_media_info[$ps_version]["FILENAME"]) {
return join("/",array($va_volume_info["absolutePath"], $va_media_info[$ps_version]["HASH"], $va_media_info[$ps_version]["MAGIC"]."_".$va_media_info[$ps_version]["FILENAME"]));
} else {
return "";
}
}
/**
* Returns appropriate representation of that media version in an html tag, including attributes for display
*
* @param string $field field name
* @param string $version version of the media file, as defined in media_processing.conf
* @param string $name name attribute of the img tag
* @param string $vspace vspace attribute of the img tag - note: deprecated in HTML 4.01, not supported in XHTML 1.0 Strict
* @param string $hspace hspace attribute of the img tag - note: deprecated in HTML 4.01, not supported in XHTML 1.0 Strict
* @param string $alt alt attribute of the img tag
* @param int $border border attribute of the img tag - note: deprecated in HTML 4.01, not supported in XHTML 1.0 Strict
* @param string $usemap usemap attribute of the img tag
* @param int $align align attribute of the img tag - note: deprecated in HTML 4.01, not supported in XHTML 1.0 Strict
* @return string html tag
*/
public function getMediaTag($field, $version, $pa_options=null) {
$media_info = $this->getMediaInfo($field);
if (!is_array($media_info[$version])) {
return "";
}
#
# Is this version queued for processing?
#
if (isset($media_info[$version]["QUEUED"]) && ($media_info[$version]["QUEUED"])) {
if ($media_info[$version]["QUEUED_ICON"]["src"]) {
return "<img src='".$media_info[$version]["QUEUED_ICON"]["src"]."' width='".$media_info[$version]["QUEUED_ICON"]["width"]."' height='".$media_info[$version]["QUEUED_ICON"]["height"]."' alt='".$media_info[$version]["QUEUED_ICON"]["alt"]."'>";
} else {
return $media_info[$version]["QUEUED_MESSAGE"];
}
}
$url = $this->getMediaUrl($field, $version, isset($options["page"]) ? $options["page"] : null);
$m = new Media();
$o_vol = new MediaVolumes();
$va_volume = $o_vol->getVolumeInformation($media_info[$version]['VOLUME']);
return $m->htmlTag($media_info[$version]["MIMETYPE"], $url, $media_info[$version]["PROPERTIES"], $pa_options, $va_volume);
}
/**
* Get media information for the given field
*
* @param string $field field name
* @param string $version version of the media file, as defined in media_processing.conf, can be omitted to retrieve information about all versions
* @param string $property this is your opportunity to restrict the result to a certain property for the given (field,version) pair.
* possible values are:
* -VOLUME
* -MIMETYPE
* -WIDTH
* -HEIGHT
* -PROPERTIES: returns an array with some media metadata like width, height, mimetype, etc.
* -FILENAME
* -HASH
* -MAGIC
* -EXTENSION
* -MD5
* @return mixed media information
*/
public function &getMediaInfo($field, $version="", $property="") {
$media_info = $this->get($field, array('USE_MEDIA_FIELD_VALUES' => true));
if (!is_array($media_info)) {
return "";
}
if ($version) {
if (!$property) {
return $media_info[$version];
} else {
return $media_info[$version][$property];
}
} else {
return $media_info;
}
}
/**
* Fetches media input type for the given field, e.g. "image"
*
* @param $ps_field field name
* @return string media input type
*/
public function getMediaInputType($ps_field) {
if ($va_media_info = $this->getMediaInfo($ps_field)) {
$o_media_proc_settings = new MediaProcessingSettings($this, $ps_field);
return $o_media_proc_settings->canAccept($va_media_info["INPUT"]["MIMETYPE"]);
} else {
return null;
}
}
/**
* Fetches media input type for the given field, e.g. "image" and version
*
* @param string $ps_field field name
* @param string $ps_version version
* @return string media input type
*/
public function getMediaInputTypeForVersion($ps_field, $ps_version) {
if ($va_media_info = $this->getMediaInfo($ps_field)) {
$o_media_proc_settings = new MediaProcessingSettings($this, $ps_field);
if($vs_media_type = $o_media_proc_settings->canAccept($va_media_info["INPUT"]["MIMETYPE"])) {
$va_media_type_info = $o_media_proc_settings->getMediaTypeInfo($vs_media_type);
if (isset($va_media_type_info['VERSIONS'][$ps_version])) {
if ($va_rule = $o_media_proc_settings->getMediaTransformationRule($va_media_type_info['VERSIONS'][$ps_version]['RULE'])) {
return $o_media_proc_settings->canAccept($va_rule['SET']['format']);
}
}
}
}
return null;
}
/**
* Returns default version to display for the given field based upon the currently loaded row
*
* @param string $ps_field field name
*/
public function getDefaultMediaVersion($ps_field) {
if ($va_media_info = $this->getMediaInfo($ps_field)) {
$o_media_proc_settings = new MediaProcessingSettings($this, $ps_field);
$va_type_info = $o_media_proc_settings->getMediaTypeInfo($o_media_proc_settings->canAccept($va_media_info["INPUT"]["MIMETYPE"]));
return ($va_type_info['MEDIA_VIEW_DEFAULT_VERSION']) ? $va_type_info['MEDIA_VIEW_DEFAULT_VERSION'] : array_shift($this->getMediaVersions($ps_field));
} else {
return null;
}
}
/**
* Returns default version to display as a preview for the given field based upon the currently loaded row
*
* @param string $ps_field field name
*/
public function getDefaultMediaPreviewVersion($ps_field) {
if ($va_media_info = $this->getMediaInfo($ps_field)) {
$o_media_proc_settings = new MediaProcessingSettings($this, $ps_field);
$va_type_info = $o_media_proc_settings->getMediaTypeInfo($o_media_proc_settings->canAccept($va_media_info["INPUT"]["MIMETYPE"]));
return ($va_type_info['MEDIA_PREVIEW_DEFAULT_VERSION']) ? $va_type_info['MEDIA_PREVIEW_DEFAULT_VERSION'] : array_shift($this->getMediaVersions($ps_field));
} else {
return null;
}
}
/**
* Fetches available media versions for the given field (and optional mimetype), as defined in media_processing.conf
*
* @param string $ps_field field name
* @param string $ps_mimetype optional mimetype restriction
* @return array list of available media versions
*/
public function getMediaVersions($ps_field, $ps_mimetype="") {
if (!$ps_mimetype) {
# figure out mimetype from field content
$va_media_desc = $this->get($ps_field);
if (is_array($va_media_desc)) {
unset($va_media_desc["ORIGINAL_FILENAME"]);
unset($va_media_desc["INPUT"]);
unset($va_media_desc["VOLUME"]);
return array_keys($va_media_desc);
}
} else {
$o_media_proc_settings = new MediaProcessingSettings($this, $ps_field);
if ($vs_media_type = $o_media_proc_settings->canAccept($ps_mimetype)) {
$va_version_list = $o_media_proc_settings->getMediaTypeVersions($vs_media_type);
if (is_array($va_version_list)) {
return array_keys($va_version_list);
}
}
}
return array();
}
/**
* Checks if a media version for the given field exists.
*
* @param string $ps_field field name
* @param string $ps_version string representation of the version you are asking for
* @return bool
*/
public function hasMediaVersion($ps_field, $ps_version) {
return in_array($ps_version, $this->getMediaVersions($ps_field));
}
/**
* Fetches processing settings information for the given field with respect to the given mimetype
*
* @param string $ps_field field name
* @param string $ps_mimetype mimetype
* @return array containing the information defined in media_processing.conf
*/
public function &getMediaTypeInfo($ps_field, $ps_mimetype="") {
$o_media_proc_settings = new MediaProcessingSettings($this, $ps_field);
if (!$ps_mimetype) {
# figure out mimetype from field content
$va_media_desc = $this->get($ps_field);
if ($vs_media_type = $o_media_proc_settings->canAccept($media_desc["INPUT"]["MIMETYPE"])) {
return $o_media_proc_settings->getMediaTypeInfo($vs_media_type);
}
} else {
if ($vs_media_type = $o_media_proc_settings->canAccept($ps_mimetype)) {
return $o_media_proc_settings->getMediaTypeInfo($vs_media_type);
}
}
return null;
}
/**
* Sets media information
*
* @param $field field name
* @param array $info
* @return bool success state
*/
public function setMediaInfo($field, $info) {
if(($this->getFieldInfo($field,"FIELD_TYPE")) == FT_MEDIA) {
$this->_FIELD_VALUES[$field] = $info;
$this->_FIELD_VALUE_CHANGED[$field] = 1;
return true;
}
return false;
}
/**
* Clear media
*
* @param string $field field name
* @return bool always true
*/
public function clearMedia($field) {
$this->_FILES_CLEAR[$field] = 1;
$this->_FIELD_VALUE_CHANGED[$field] = 1;
return true;
}
/**
* Generate name for media file representation.
* Makes the application die if you try to call this on a BaseModel object not representing an actual db row.
*
* @access private
* @param string $field
* @return string the media name
*/
public function _genMediaName($field) {
$pk = $this->getPrimaryKey();
if ($pk) {
return $this->TABLE."_".$field."_".$pk;
} else {
die("NO PK TO MAKE media name for $field!");
}
}
/**
* Removes media
*
* @access private
* @param string $ps_field field name
* @param string $ps_version string representation of the version (e.g. original)
* @param string $ps_dont_delete_path
* @param string $ps_dont_delete extension
* @return null
*/
public function _removeMedia($ps_field, $ps_version, $ps_dont_delete_path="", $ps_dont_delete_extension="") {
global $AUTH_CURRENT_USER_ID;
$va_media_info = $this->getMediaInfo($ps_field,$ps_version);
if (!$va_media_info) { return true; }
$vs_volume = $va_media_info["VOLUME"];
$va_volume_info = $this->_MEDIA_VOLUMES->getVolumeInformation($vs_volume);
#
# Get list of media files to delete
#
$va_files_to_delete = array();
$vs_delete_path = $va_volume_info["absolutePath"]."/".$va_media_info["HASH"]."/".$va_media_info["MAGIC"]."_".$va_media_info["FILENAME"];
if (($va_media_info["FILENAME"]) && ($vs_delete_path != $ps_dont_delete_path.".".$ps_dont_delete_extension)) {
$va_files_to_delete[] = $va_media_info["MAGIC"]."_".$va_media_info["FILENAME"];
@unlink($vs_delete_path);
}
# if media is mirrored, delete file off of mirrored server
if (is_array($va_volume_info["mirrors"]) && sizeof($va_volume_info["mirrors"]) > 0) {
$o_tq = new TaskQueue();
$vs_row_key = join("/", array($this->tableName(), $this->getPrimaryKey()));
$vs_entity_key = join("/", array($this->tableName(), $ps_field, $this->getPrimaryKey(), $ps_version));
if (!($o_tq->cancelPendingTasksForEntity($vs_entity_key))) {
$this->postError(560, _t("Could not cancel pending tasks: %1", $this->error),"BaseModel->_removeMedia()");
return false;
}
foreach ($va_volume_info["mirrors"] as $vs_mirror_code => $va_mirror_info) {
$vs_mirror_method = $va_mirror_info["method"];
$vs_queue = $vs_mirror_method."mirror";
if (!($o_tq->cancelPendingTasksForEntity($vs_entity_key))) {
$this->postError(560, _t("Could not cancel pending tasks: %1", $this->error),"BaseModel->_removeMedia()");
return false;
}
$va_tq_filelist = array();
foreach($va_files_to_delete as $vs_filename) {
$va_tq_filelist[] = array(
"HASH" => $va_media_info["HASH"],
"FILENAME" => $vs_filename
);
}
if ($o_tq->addTask(
$vs_queue,
array(
"MIRROR" => $vs_mirror_code,
"VOLUME" => $vs_volume,
"FIELD" => $f,
"TABLE" => $this->tableName(),
"DELETE" => 1,
"VERSION" => $ps_version,
"FILES" => $va_tq_filelist,
"MIRROR_INFO" => $va_mirror_info,
"PK" => $this->primaryKey(),
"PK_VAL" => $this->getPrimaryKey()
),
array("priority" => 50, "entity_key" => $vs_entity_key, "row_key" => $vs_row_key, 'user_id' => $AUTH_CURRENT_USER_ID)))
{
continue;
} else {
$this->postError(100, _t("Couldn't queue mirror using '%1' for version '%2' (handler '%3')", $vs_mirror_method, $v, $queue),"BaseModel->_removeMedia()");
}
}
}
}
/**
* perform media processing for the given field if sth. has been uploaded
*
* @access private
* @param string $ps_field field name
* @param array options
*
* Supported options:
* delete_old_media = set to zero to prevent that old media files are deleted; defaults to 1
* these_versions_only = if set to an array of valid version names, then only the specified versions are updated with the currently updated file; ignored if no media already exists
*/
public function _processMedia($ps_field, $pa_options=null) {
global $AUTH_CURRENT_USER_ID;
if(!is_array($pa_options)) { $pa_options = array(); }
if(!isset($pa_options['delete_old_media'])) { $pa_options['delete_old_media'] = true; }
if(!isset($pa_options['these_versions_only'])) { $pa_options['these_versions_only'] = null; }
$vs_sql = "";
$vn_max_execution_time = ini_get('max_execution_time');
set_time_limit(7200);
$o_tq = new TaskQueue();
$o_media_proc_settings = new MediaProcessingSettings($this, $ps_field);
# only set file if something was uploaded
# (ie. don't nuke an existing file because none
# was uploaded)
$va_field_info = $this->getFieldInfo($ps_field);
if ((isset($this->_FILES_CLEAR[$ps_field])) && ($this->_FILES_CLEAR[$ps_field])) {
//
// Clear files
//
$va_versions = $this->getMediaVersions($ps_field);
#--- delete files
foreach ($va_versions as $v) {
$this->_removeMedia($ps_field, $v);
}
$this->_FILES[$ps_field] = null;
$this->_FIELD_VALUES[$ps_field] = null;
$vs_sql = "{$ps_field} = ".$this->quote(caSerializeForDatabase($this->_FILES[$ps_field], true)).",";
} else {
//
// Process incoming files
//
$m = new Media();
// is it a URL?
$vs_url_fetched_from = null;
$vn_url_fetched_on = null;
$vb_allow_fetching_of_urls = (bool)$this->_CONFIG->get('allow_fetching_of_media_from_remote_urls');
$vb_is_fetched_file = false;
if ($vb_allow_fetching_of_urls && (bool)ini_get('allow_url_fopen') && isURL($this->_SET_FILES[$ps_field]['tmp_name'])) {
$vs_tmp_file = tempnam(__CA_APP_DIR__.'/tmp', 'caUrlCopy');
$r_incoming_fp = @fopen($this->_SET_FILES[$ps_field]['tmp_name'], 'r');
if (!$r_incoming_fp) {
$this->postError(1600, _t('Cannot open remote URL [%1] to fetch media', $this->_SET_FILES[$ps_field]['tmp_name']),"BaseModel->_processMedia()");
set_time_limit($vn_max_execution_time);
return false;
}
$r_outgoing_fp = fopen($vs_tmp_file, 'w');
if (!$r_outgoing_fp) {
$this->postError(1600, _t('Cannot open file for media fetched from URL [%1]', $this->_SET_FILES[$ps_field]['tmp_name']),"BaseModel->_processMedia()");
set_time_limit($vn_max_execution_time);
return false;
}
while(($vs_content = fgets($r_incoming_fp, 4096)) !== false) {
fwrite($r_outgoing_fp, $vs_content);
}
fclose($r_incoming_fp);
fclose($r_outgoing_fp);
$vs_url_fetched_from = $this->_SET_FILES[$ps_field]['tmp_name'];
$vn_url_fetched_on = time();
$this->_SET_FILES[$ps_field]['tmp_name'] = $vs_tmp_file;
$vb_is_fetched_file = true;
}
if (isset($this->_SET_FILES[$ps_field]['tmp_name']) && (file_exists($this->_SET_FILES[$ps_field]['tmp_name']))) {
// ImageMagick partly relies on file extensions to properly identify images (RAW images in particular)
// therefore we rename the temporary file here (using the extension of the original filename, if any)
$va_matches = array();
$vb_renamed_tmpfile = false;
preg_match("/[.]*\.([a-zA-Z0-9]+)$/",$this->_SET_FILES[$ps_field]['tmp_name'],$va_matches);
if(!isset($va_matches[1])){ // file has no extension, i.e. is probably PHP upload tmp file
$va_matches = array();
preg_match("/[.]*\.([a-zA-Z0-9]+)$/",$this->_SET_FILES[$ps_field]['original_filename'],$va_matches);
if(strlen($va_matches[1])>0){
$va_parts = explode("/",$this->_SET_FILES[$ps_field]['tmp_name']);
$vs_new_filename = sys_get_temp_dir()."/".$va_parts[sizeof($va_parts)-1].".".$va_matches[1];
if (!move_uploaded_file($this->_SET_FILES[$ps_field]['tmp_name'],$vs_new_filename)) {
rename($this->_SET_FILES[$ps_field]['tmp_name'],$vs_new_filename);
}
$this->_SET_FILES[$ps_field]['tmp_name'] = $vs_new_filename;
$vb_renamed_tmpfile = true;
}
}
$input_mimetype = $m->divineFileFormat($this->_SET_FILES[$ps_field]['tmp_name']);
if (!$input_type = $o_media_proc_settings->canAccept($input_mimetype)) {
# error - filetype not accepted by this field
$this->postError(1600, ($input_mimetype) ? _t("File type %1 not accepted by %2", $input_mimetype, $ps_field) : _t("Unknown file type not accepted by %1", $ps_field),"BaseModel->_processMedia()");
set_time_limit($vn_max_execution_time);
if ($vb_is_fetched_file) { @unlink($vs_tmp_file); }
return false;
}
# ok process file...
if (!($m->read($this->_SET_FILES[$ps_field]['tmp_name']))) {
$this->errors = array_merge($this->errors, $m->errors()); // copy into model plugin errors
//$this->postError(1600, _t("File for %1 could not be read", $ps_field),"BaseModel->_processMedia()");
set_time_limit($vn_max_execution_time);
if ($vb_is_fetched_file) { @unlink($vs_tmp_file); }
return false;
}
$media_desc = array(
"ORIGINAL_FILENAME" => $this->_SET_FILES[$ps_field]['original_filename'],
"INPUT" => array(
"MIMETYPE" => $m->get("mimetype"),
"WIDTH" => $m->get("width"),
"HEIGHT" => $m->get("height"),
"MD5" => md5_file($this->_SET_FILES[$ps_field]['tmp_name']),
"FILESIZE" => filesize($this->_SET_FILES[$ps_field]['tmp_name']),
"FETCHED_FROM" => $vs_url_fetched_from,
"FETCHED_ON" => $vn_url_fetched_on
)
);
#
# Extract metadata from file
#
$media_metadata = $m->getExtractedMetadata();
# get versions to create
$va_versions = $this->getMediaVersions($ps_field, $input_mimetype);
$error = 0;
# don't process files that are not going to be processed or converted
# we don't want to waste time opening file we're not going to do anything with
# also, we don't want to recompress JPEGs...
$media_type = $o_media_proc_settings->canAccept($input_mimetype);
$version_info = $o_media_proc_settings->getMediaTypeVersions($media_type);
$va_default_queue_settings = $o_media_proc_settings->getMediaTypeQueueSettings($media_type);
if (!($va_media_write_options = $this->_FILES[$ps_field]['options'])) {
$va_media_write_options = $this->_SET_FILES[$ps_field]['options'];
}
$va_process_these_versions_only = array();
if (isset($pa_options['these_versions_only']) && is_array($pa_options['these_versions_only']) && sizeof($pa_options['these_versions_only'])) {
$va_tmp = $this->_FIELD_VALUES[$ps_field];
foreach($pa_options['these_versions_only'] as $vs_this_version_only) {
if (in_array($vs_this_version_only, $va_versions)) {
if (is_array($this->_FIELD_VALUES[$ps_field])) {
$va_process_these_versions_only[] = $vs_this_version_only;
}
}
}
// Copy metadata for version we're not processing
if (sizeof($va_process_these_versions_only)) {
foreach (array_keys($va_tmp) as $v) {
if (!in_array($v, $va_process_these_versions_only)) {
$media_desc[$v] = $va_tmp[$v];
}
}
}
}
$va_files_to_delete = array();
$va_queued_versions = array();
$queue_enabled = (!sizeof($va_process_these_versions_only) && $this->getAppConfig()->get('queue_enabled')) ? true : false;
$vs_path_to_queue_media = null;
foreach ($va_versions as $v) {
if (sizeof($va_process_these_versions_only) && (!in_array($v, $va_process_these_versions_only))) {
// only processing certain versions... and this one isn't it so skip
continue;
}
$queue = $va_default_queue_settings['QUEUE'];
$queue_threshold = isset($version_info[$v]['QUEUE_WHEN_FILE_LARGER_THAN']) ? intval($version_info[$v]['QUEUE_WHEN_FILE_LARGER_THAN']) : (int)$va_default_queue_settings['QUEUE_WHEN_FILE_LARGER_THAN'];
$rule = isset($version_info[$v]['RULE']) ? $version_info[$v]['RULE'] : '';
$volume = isset($version_info[$v]['VOLUME']) ? $version_info[$v]['VOLUME'] : '';
# get volume
$vi = $this->_MEDIA_VOLUMES->getVolumeInformation($volume);
if (!is_array($vi)) {
print "Invalid volume '{$volume}'<br>";
exit;
}
// Send to queue it it's too big to process here
if (($queue_enabled) && ($queue) && ($queue_threshold > 0) && ($queue_threshold < (int)$media_desc["INPUT"]["FILESIZE"]) && ($va_default_queue_settings['QUEUE_USING_VERSION'] != $v)) {
$va_queued_versions[$v] = array(
'VOLUME' => $volume
);
$media_desc[$v]["QUEUED"] = $queue;
if ($version_info[$v]["QUEUED_MESSAGE"]) {
$media_desc[$v]["QUEUED_MESSAGE"] = $version_info[$v]["QUEUED_MESSAGE"];
} else {
$media_desc[$v]["QUEUED_MESSAGE"] = ($va_default_queue_settings['QUEUED_MESSAGE']) ? $va_default_queue_settings['QUEUED_MESSAGE'] : _t("Media is being processed and will be available shortly.");
}
if ($pa_options['delete_old_media']) {
$va_files_to_delete[] = array(
'field' => $ps_field,
'version' => $v
);
}
continue;
}
# get transformation rules
$rules = $o_media_proc_settings->getMediaTransformationRule($rule);
if (sizeof($rules) == 0) {
$output_mimetype = $input_mimetype;
$m->set("version", $v);
#
# don't process this media, just copy the file
#
$ext = $m->mimetype2extension($output_mimetype);
if (!$ext) {
$this->postError(1600, _t("File could not be copied for %1; can't convert mimetype '%2' to extension", $ps_field, $output_mimetype),"BaseModel->_processMedia()");
$m->cleanup();
set_time_limit($vn_max_execution_time);
if ($vb_is_fetched_file) { @unlink($vs_tmp_file); }
return false;
}
if (($dirhash = $this->_getDirectoryHash($vi["absolutePath"], $this->getPrimaryKey())) === false) {
$this->postError(1600, _t("Could not create subdirectory for uploaded file in %1. Please ask your administrator to check the permissions of your media directory.", $vi["absolutePath"]),"BaseModel->_processMedia()");
set_time_limit($vn_max_execution_time);
if ($vb_is_fetched_file) { @unlink($vs_tmp_file); }
return false;
}
if ((bool)$version_info[$v]["USE_EXTERNAL_URL_WHEN_AVAILABLE"]) {
$filepath = $this->_SET_FILES[$ps_field]['tmp_name'];
if ($pa_options['delete_old_media']) {
$va_files_to_delete[] = array(
'field' => $ps_field,
'version' => $v
);
}
$media_desc[$v] = array(
"VOLUME" => $volume,
"MIMETYPE" => $output_mimetype,
"WIDTH" => $m->get("width"),
"HEIGHT" => $m->get("height"),
"PROPERTIES" => $m->getProperties(),
"EXTERNAL_URL" => $media_desc['INPUT']['FETCHED_FROM'],
"FILENAME" => null,
"HASH" => null,
"MAGIC" => null,
"EXTENSION" => $ext,
"MD5" => md5_file($filepath)
);
} else {
$magic = rand(0,99999);
$filepath = $vi["absolutePath"]."/".$dirhash."/".$magic."_".$this->_genMediaName($ps_field)."_".$v.".".$ext;
if (!copy($this->_SET_FILES[$ps_field]['tmp_name'], $filepath)) {
$this->postError(1600, _t("File could not be copied. Ask your administrator to check permissions and file space for %1",$vi["absolutePath"]),"BaseModel->_processMedia()");
$m->cleanup();
set_time_limit($vn_max_execution_time);
if ($vb_is_fetched_file) { @unlink($vs_tmp_file); }
return false;
}
if ($v === $va_default_queue_settings['QUEUE_USING_VERSION']) {
$vs_path_to_queue_media = $filepath;
}
if ($pa_options['delete_old_media']) {
$va_files_to_delete[] = array(
'field' => $ps_field,
'version' => $v,
'dont_delete_path' => $vi["absolutePath"]."/".$dirhash."/".$magic."_".$this->_genMediaName($ps_field)."_".$v,
'dont_delete_extension' => $ext
);
}
if (is_array($vi["mirrors"]) && sizeof($vi["mirrors"]) > 0) {
$vs_entity_key = join("/", array($this->tableName(), $ps_field, $this->getPrimaryKey(), $v));
$vs_row_key = join("/", array($this->tableName(), $this->getPrimaryKey()));
foreach ($vi["mirrors"] as $vs_mirror_code => $va_mirror_info) {
$vs_mirror_method = $va_mirror_info["method"];
$vs_queue = $vs_mirror_method."mirror";
if (!($o_tq->cancelPendingTasksForEntity($vs_entity_key))) {
//$this->postError(560, _t("Could not cancel pending tasks: %1", $this->error),"BaseModel->_processMedia()");
//$m->cleanup();
//return false;
}
if ($o_tq->addTask(
$vs_queue,
array(
"MIRROR" => $vs_mirror_code,
"VOLUME" => $volume,
"FIELD" => $ps_field,
"TABLE" => $this->tableName(),
"VERSION" => $v,
"FILES" => array(
array(
"FILE_PATH" => $filepath,
"ABS_PATH" => $vi["absolutePath"],
"HASH" => $dirhash,
"FILENAME" => $magic."_".$this->_genMediaName($ps_field)."_".$v.".".$ext
)
),
"MIRROR_INFO" => $va_mirror_info,
"PK" => $this->primaryKey(),
"PK_VAL" => $this->getPrimaryKey()
),
array("priority" => 100, "entity_key" => $vs_entity_key, "row_key" => $vs_row_key, 'user_id' => $AUTH_CURRENT_USER_ID)))
{
continue;
} else {
$this->postError(100, _t("Couldn't queue mirror using '%1' for version '%2' (handler '%3')", $vs_mirror_method, $v, $queue),"BaseModel->_processMedia()");
}
}
}
$media_desc[$v] = array(
"VOLUME" => $volume,
"MIMETYPE" => $output_mimetype,
"WIDTH" => $m->get("width"),
"HEIGHT" => $m->get("height"),
"PROPERTIES" => $m->getProperties(),
"FILENAME" => $this->_genMediaName($ps_field)."_".$v.".".$ext,
"HASH" => $dirhash,
"MAGIC" => $magic,
"EXTENSION" => $ext,
"MD5" => md5_file($filepath)
);
}
} else {
$m->set("version", $v);
while(list($operation, $parameters) = each($rules)) {
if ($operation === 'SET') {
foreach($parameters as $pp => $pv) {
if ($pp == 'format') {
$output_mimetype = $pv;
} else {
$m->set($pp, $pv);
}
}
} else {
if (!($m->transform($operation, $parameters))) {
$error = 1;
$error_msg = "Couldn't do transformation '$operation'";
break(2);
}
}
}
if (!$output_mimetype) { $output_mimetype = $input_mimetype; }
if (!($ext = $m->mimetype2extension($output_mimetype))) {
$this->postError(1600, _t("File could not be processed for %1; can't convert mimetype '%2' to extension", $ps_field, $output_mimetype),"BaseModel->_processMedia()");
$m->cleanup();
set_time_limit($vn_max_execution_time);
if ($vb_is_fetched_file) { @unlink($vs_tmp_file); }
return false;
}
if (($dirhash = $this->_getDirectoryHash($vi["absolutePath"], $this->getPrimaryKey())) === false) {
$this->postError(1600, _t("Could not create subdirectory for uploaded file in %1. Please ask your administrator to check the permissions of your media directory.", $vi["absolutePath"]),"BaseModel->_processMedia()");
set_time_limit($vn_max_execution_time);
if ($vb_is_fetched_file) { @unlink($vs_tmp_file); }
return false;
}
$magic = rand(0,99999);
$filepath = $vi["absolutePath"]."/".$dirhash."/".$magic."_".$this->_genMediaName($ps_field)."_".$v;
$va_output_files = array();
if (!($vs_output_file = $m->write($filepath, $output_mimetype, $va_media_write_options))) {
$this->postError(1600,_t("Couldn't write file: %1", join("; ", $m->getErrors())),"BaseModel->_processMedia()");
$m->cleanup();
set_time_limit($vn_max_execution_time);
if ($vb_is_fetched_file) { @unlink($vs_tmp_file); }
return false;
break;
} else {
$va_output_files[] = $vs_output_file;
}
if ($v === $va_default_queue_settings['QUEUE_USING_VERSION']) {
$vs_path_to_queue_media = $vs_output_file;
}
if (($pa_options['delete_old_media']) && (!$error)) {
if($vs_old_media_path = $this->getMediaPath($ps_field, $v)) {
$va_files_to_delete[] = array(
'field' => $ps_field,
'version' => $v,
'dont_delete_path' => $filepath,
'dont_delete_extension' => $ext
);
}
}
if (is_array($vi["mirrors"]) && sizeof($vi["mirrors"]) > 0) {
$vs_entity_key = join("/", array($this->tableName(), $ps_field, $this->getPrimaryKey(), $v));
$vs_row_key = join("/", array($this->tableName(), $this->getPrimaryKey()));
foreach ($vi["mirrors"] as $vs_mirror_code => $va_mirror_info) {
$vs_mirror_method = $va_mirror_info["method"];
$vs_queue = $vs_mirror_method."mirror";
if (!($o_tq->cancelPendingTasksForEntity($vs_entity_key))) {
//$this->postError(560, _t("Could not cancel pending tasks: %1", $this->error),"BaseModel->_processMedia()");
//$m->cleanup();
//return false;
}
if ($o_tq->addTask(
$vs_queue,
array(
"MIRROR" => $vs_mirror_code,
"VOLUME" => $volume,
"FIELD" => $ps_field, "TABLE" => $this->tableName(),
"VERSION" => $v,
"FILES" => array(
array(
"FILE_PATH" => $filepath.".".$ext,
"ABS_PATH" => $vi["absolutePath"],
"HASH" => $dirhash,
"FILENAME" => $magic."_".$this->_genMediaName($ps_field)."_".$v.".".$ext
)
),
"MIRROR_INFO" => $va_mirror_info,
"PK" => $this->primaryKey(),
"PK_VAL" => $this->getPrimaryKey()
),
array("priority" => 100, "entity_key" => $vs_entity_key, "row_key" => $vs_row_key, 'user_id' => $AUTH_CURRENT_USER_ID)))
{
continue;
} else {
$this->postError(100, _t("Couldn't queue mirror using '%1' for version '%2' (handler '%3')", $vs_mirror_method, $v, $queue),"BaseModel->_processMedia()");
}
}
}
$media_desc[$v] = array(
"VOLUME" => $volume,
"MIMETYPE" => $output_mimetype,
"WIDTH" => $m->get("width"),
"HEIGHT" => $m->get("height"),
"PROPERTIES" => $m->getProperties(),
"FILENAME" => $this->_genMediaName($ps_field)."_".$v.".".$ext,
"HASH" => $dirhash,
"MAGIC" => $magic,
"EXTENSION" => $ext,
"MD5" => md5_file($vi["absolutePath"]."/".$dirhash."/".$magic."_".$this->_genMediaName($ps_field)."_".$v.".".$ext)
);
$m->reset();
}
}
if (sizeof($va_queued_versions)) {
$vs_entity_key = md5(join("/", array_merge(array($this->tableName(), $ps_field, $this->getPrimaryKey()), array_keys($va_queued_versions))));
$vs_row_key = join("/", array($this->tableName(), $this->getPrimaryKey()));
if (!($o_tq->cancelPendingTasksForEntity($vs_entity_key, $queue))) {
// TODO: log this
}
if (!($filename = $vs_path_to_queue_media)) {
// if we're not using a designated not-queued representation to generate the queued ones
// then copy the uploaded file to the tmp dir and use that
$filename = $o_tq->copyFileToQueueTmp($va_default_queue_settings['QUEUE'], $this->_SET_FILES[$ps_field]['tmp_name']);
}
if ($filename) {
if ($o_tq->addTask(
$va_default_queue_settings['QUEUE'],
array(
"TABLE" => $this->tableName(), "FIELD" => $ps_field,
"PK" => $this->primaryKey(), "PK_VAL" => $this->getPrimaryKey(),
"INPUT_MIMETYPE" => $input_mimetype,
"FILENAME" => $filename,
"VERSIONS" => $va_queued_versions,
"OPTIONS" => $va_media_write_options,
"DONT_DELETE_OLD_MEDIA" => ($filename == $vs_path_to_queue_media) ? true : false
),
array("priority" => 100, "entity_key" => $vs_entity_key, "row_key" => $vs_row_key, 'user_id' => $AUTH_CURRENT_USER_ID)))
{
if ($pa_options['delete_old_media']) {
foreach($va_queued_versions as $vs_version => $va_version_info) {
$va_files_to_delete[] = array(
'field' => $ps_field,
'version' => $vs_version
);
}
}
} else {
$this->postError(100, _t("Couldn't queue processing for version '%1' using handler '%2'", !$v, $queue),"BaseModel->_processMedia()");
}
} else {
$this->errors = $o_tq->errors;
}
} else {
// Generate preview frames for media that support that (Eg. video)
// and add them as "multifiles" assuming the current model supports that (ca_object_representations does)
if (!sizeof($va_process_these_versions_only) && ((bool)$this->_CONFIG->get('video_preview_generate_frames') || (bool)$this->_CONFIG->get('document_preview_generate_pages')) && method_exists($this, 'addFile')) {
$va_preview_frame_list = $m->writePreviews(
array(
'width' => $m->get("width"),
'height' => $m->get("height"),
'minNumberOfFrames' => $this->_CONFIG->get('video_preview_min_number_of_frames'),
'maxNumberOfFrames' => $this->_CONFIG->get('video_preview_max_number_of_frames'),
'numberOfPages' => $this->_CONFIG->get('document_preview_max_number_of_pages'),
'frameInterval' => $this->_CONFIG->get('video_preview_interval_between_frames'),
'pageInterval' => $this->_CONFIG->get('document_preview_interval_between_pages'),
'startAtTime' => $this->_CONFIG->get('video_preview_start_at'),
'endAtTime' => $this->_CONFIG->get('video_preview_end_at'),
'startAtPage' => $this->_CONFIG->get('document_preview_start_page'),
'outputDirectory' => __CA_APP_DIR__.'/tmp'
)
);
$this->removeAllFiles(); // get rid of any previously existing frames (they might be hanging around if we're editing an existing record)
if (is_array($va_preview_frame_list)) {
foreach($va_preview_frame_list as $vn_time => $vs_frame) {
$this->addFile($vs_frame, $vn_time, true); // the resource path for each frame is it's time, in seconds (may be fractional) for video, or page number for documents
@unlink($vs_frame); // clean up tmp preview frame file
}
}
}
}
if (!$error) {
#
# --- Clean up old media from versions that are not supported in the new media
#
if ($pa_options['delete_old_media']) {
foreach ($this->getMediaVersions($ps_field) as $old_version) {
if (!is_array($media_desc[$old_version])) {
$this->_removeMedia($ps_field, $old_version);
}
}
}
foreach($va_files_to_delete as $va_file_to_delete) {
$this->_removeMedia($va_file_to_delete['field'], $va_file_to_delete['version'], $va_file_to_delete['dont_delete_path'], $va_file_to_delete['dont_delete_extension']);
}
$this->_FILES[$ps_field] = $media_desc;
$this->_FIELD_VALUES[$ps_field] = $media_desc;
$vs_serialized_data = caSerializeForDatabase($this->_FILES[$ps_field], true);
$vs_sql = "$ps_field = ".$this->quote($vs_serialized_data).",";
if (($vs_metadata_field_name = $o_media_proc_settings->getMetadataFieldName()) && $this->hasField($vs_metadata_field_name)) {
$this->set($vs_metadata_field_name, $media_metadata);
$vs_sql .= " ".$vs_metadata_field_name." = ".$this->quote(caSerializeForDatabase($media_metadata, true)).",";
}
if (($vs_content_field_name = $o_media_proc_settings->getMetadataContentName()) && $this->hasField($vs_content_field_name)) {
$this->_FIELD_VALUES[$vs_content_field_name] = $this->quote($m->getExtractedText());
$vs_sql .= " ".$vs_content_field_name." = ".$this->_FIELD_VALUES[$vs_content_field_name].",";
}
} else {
# error - invalid media
$this->postError(1600, _t("File could not be processed for %1: %2", $ps_field, $error_msg),"BaseModel->_processMedia()");
# return false;
}
$m->cleanup();
if($vb_renamed_tmpfile){
@unlink($this->_SET_FILES[$ps_field]['tmp_name']);
}
} else {
if(is_array($this->_FIELD_VALUES[$ps_field])) {
$this->_FILES[$ps_field] = $this->_FIELD_VALUES[$ps_field];
$vs_sql = "$ps_field = ".$this->quote(caSerializeForDatabase($this->_FILES[$ps_field], true)).",";
}
}
$this->_SET_FILES[$ps_field] = null;
}
set_time_limit($vn_max_execution_time);
if ($vb_is_fetched_file) { @unlink($vs_tmp_file); }
return $vs_sql;
}
# --------------------------------------------------------------------------------
/**
* Fetches hash directory
*
* @access private
* @param string $basepath path
* @param int $id identifier
* @return string directory
*/
public function _getDirectoryHash ($basepath, $id) {
$n = intval($id / 100);
$dirs = array();
$l = strlen($n);
for($i=0;$i<$l; $i++) {
$dirs[] = substr($n,$i,1);
if (!file_exists($basepath."/".join("/", $dirs))) {
if (!@mkdir($basepath."/".join("/", $dirs))) {
return false;
}
}
}
return join("/", $dirs);
}
# --------------------------------------------------------------------------------
# --- Uploaded file handling
# --------------------------------------------------------------------------------
/**
* Returns url of file
*
* @access public
* @param $field field name
* @return string file url
*/
public function getFileUrl($ps_field) {
$va_file_info = $this->get($ps_field);
if (!is_array($va_file_info)) {
return null;
}
$va_volume_info = $this->_FILE_VOLUMES->getVolumeInformation($va_file_info["VOLUME"]);
if (!is_array($va_volume_info)) {
return null;
}
$vs_protocol = $va_volume_info["protocol"];
$vs_host = $va_volume_info["hostname"];
$vs_path = join("/",array($va_volume_info["urlPath"], $va_file_info["HASH"], $va_file_info["MAGIC"]."_".$va_file_info["FILENAME"]));
return $va_file_info["FILENAME"] ? "{$vs_protocol}://{$vs_host}.{$vs_path}" : "";
}
# --------------------------------------------------------------------------------
/**
* Returns path of file
*
* @access public
* @param string $field field name
* @return string path in local filesystem
*/
public function getFilePath($ps_field) {
$va_file_info = $this->get($ps_field);
if (!is_array($va_file_info)) {
return null;
}
$va_volume_info = $this->_FILE_VOLUMES->getVolumeInformation($va_file_info["VOLUME"]);
if (!is_array($va_volume_info)) {
return null;
}
return join("/",array($va_volume_info["absolutePath"], $va_file_info["HASH"], $va_file_info["MAGIC"]."_".$va_file_info["FILENAME"]));
}
# --------------------------------------------------------------------------------
/**
* Wrapper around BaseModel::get(), used to fetch information about files
*
* @access public
* @param string $field field name
* @return array file information
*/
public function &getFileInfo($ps_field) {
$va_file_info = $this->get($ps_field);
if (!is_array($va_file_info)) {
return null;
}
return $va_file_info;
}
# --------------------------------------------------------------------------------
/**
* Clear file
*
* @access public
* @param string $field field name
* @return bool always true
*/
public function clearFile($ps_field) {
$this->_FILES_CLEAR[$ps_field] = 1;
$this->_FIELD_VALUE_CHANGED[$ps_field] = 1;
return true;
}
# --------------------------------------------------------------------------------
/**
* Returns list of mimetypes of available conversions of files
*
* @access public
* @param string $ps_field field name
* @return array
*/
public function getFileConversions($ps_field) {
$va_info = $this->getFileInfo($ps_field);
if (!is_array($va_info["CONVERSIONS"])) {
return array();
}
return $va_info["CONVERSIONS"];
}
# --------------------------------------------------------------------------------
/**
* Returns file path to converted version of file
*
* @access public
* @param string $ps_field field name
* @param string $ps_format format of the converted version
* @return string file path
*/
public function getFileConversionPath($ps_field, $ps_format) {
$va_info = $this->getFileInfo($ps_field);
if (!is_array($va_info)) {
return "";
}
$vi = $this->_FILE_VOLUMES->getVolumeInformation($va_info["VOLUME"]);
if (!is_array($vi)) {
return "";
}
$va_conversions = $this->getFileConversions($ps_field);
if ($va_conversions[$ps_format]) {
return join("/",array($vi["absolutePath"], $va_info["HASH"], $va_info["MAGIC"]."_".$va_conversions[$ps_format]["FILENAME"]));
} else {
return "";
}
}
# --------------------------------------------------------------------------------
/**
* Returns url to converted version of file
*
* @access public
* @param string $ps_field field name
* @param string $ps_format format of the converted version
* @return string url
*/
public function getFileConversionUrl($ps_field, $ps_format) {
$va_info = $this->getFileInfo($ps_field);
if (!is_array($va_info)) {
return "";
}
$vi = $this->_FILE_VOLUMES->getVolumeInformation($va_info["VOLUME"]);
if (!is_array($vi)) {
return "";
}
$va_conversions = $this->getFileConversions($ps_field);
if ($va_conversions[$ps_format]) {
return $vi["protocol"]."://".join("/", array($vi["hostname"], $vi["urlPath"], $va_info["HASH"], $va_info["MAGIC"]."_".$va_conversions[$ps_format]["FILENAME"]));
} else {
return "";
}
}
# -------------------------------------------------------------------------------
/**
* Generates filenames as follows: <table>_<field>_<primary_key>
* Makes the application die if no record is loaded
*
* @access private
* @param string $field field name
* @return string file name
*/
public function _genFileName($field) {
$pk = $this->getPrimaryKey();
if ($pk) {
return $this->TABLE."_".$field."_".$pk;
} else {
die("NO PK TO MAKE file name for $field!");
}
}
# --------------------------------------------------------------------------------
/**
* Processes uploaded files (only if something was uploaded)
*
* @access private
* @param string $field field name
* @return string
*/
public function _processFiles($field) {
$vs_sql = "";
# only set file if something was uploaded
# (ie. don't nuke an existing file because none
# was uploaded)
if ((isset($this->_FILES_CLEAR[$field])) && ($this->_FILES_CLEAR[$field])) {
#--- delete file
@unlink($this->getFilePath($field));
#--- delete conversions
#
# TODO: wvWWare MSWord conversion to HTML generates untracked graphics files for embedded images... they are currently
# *not* deleted when the file and associated conversions are deleted. We will need to parse the HTML to derive the names
# of these files...
#
foreach ($this->getFileConversions($field) as $vs_format => $va_file_conversion) {
@unlink($this->getFileConversionPath($field, $vs_format));
}
$this->_FILES[$field] = "";
$this->_FIELD_VALUES[$field] = "";
$vs_sql = "$field = ".$this->quote(caSerializeForDatabase($this->_FILES[$field], true)).",";
} else {
$va_field_info = $this->getFieldInfo($field);
if ((file_exists($this->_SET_FILES[$field]['tmp_name']))) {
$ff = new File();
$mimetype = $ff->divineFileFormat($this->_SET_FILES[$field]['tmp_name'], $this->_SET_FILES[$field]['original_filename']);
if (is_array($va_field_info["FILE_FORMATS"]) && sizeof($va_field_info["FILE_FORMATS"]) > 0) {
if (!in_array($mimetype, $va_field_info["FILE_FORMATS"])) {
$this->postError(1605, _t("File is not a valid format"),"BaseModel->_processFiles()");
return false;
}
}
$vn_dangerous = 0;
if (!$mimetype) {
$mimetype = "application/octet-stream";
$vn_dangerous = 1;
}
# get volume
$vi = $this->_FILE_VOLUMES->getVolumeInformation($va_field_info["FILE_VOLUME"]);
if (!is_array($vi)) {
print "Invalid volume ".$va_field_info["FILE_VOLUME"]."<br>";
exit;
}
$properties = $ff->getProperties();
if ($properties['dangerous'] > 0) { $vn_dangerous = 1; }
if (($dirhash = $this->_getDirectoryHash($vi["absolutePath"], $this->getPrimaryKey())) === false) {
$this->postError(1600, _t("Could not create subdirectory for uploaded file in %1. Please ask your administrator to check the permissions of your media directory.", $vi["absolutePath"]),"BaseModel->_processFiles()");
return false;
}
$magic = rand(0,99999);
$va_pieces = explode("/", $this->_SET_FILES[$field]['original_filename']);
$ext = array_pop($va_tmp = explode(".", array_pop($va_pieces)));
if ($properties["dangerous"]) { $ext .= ".bin"; }
if (!$ext) $ext = "bin";
$filestem = $vi["absolutePath"]."/".$dirhash."/".$magic."_".$this->_genMediaName($field);
$filepath = $filestem.".".$ext;
$filesize = isset($properties["filesize"]) ? $properties["filesize"] : 0;
if (!$filesize) {
$properties["filesize"] = filesize($this->_SET_FILES[$field]['tmp_name']);
}
$file_desc = array(
"FILE" => 1, # signifies is file
"VOLUME" => $va_field_info["FILE_VOLUME"],
"ORIGINAL_FILENAME" => $this->_SET_FILES[$field]['original_filename'],
"MIMETYPE" => $mimetype,
"FILENAME" => $this->_genMediaName($field).".".$ext,
"HASH" => $dirhash,
"MAGIC" => $magic,
"PROPERTIES" => $properties,
"DANGEROUS" => $vn_dangerous,
"CONVERSIONS" => array(),
"MD5" => md5_file($this->_SET_FILES[$field]['tmp_name'])
);
if (!copy($this->_SET_FILES[$field]['tmp_name'], $filepath)) {
$this->postError(1600, _t("File could not be copied. Ask your administrator to check permissions and file space for %1",$vi["absolutePath"]),"BaseModel->_processFiles()");
return false;
}
# -- delete old file if its name is different from the one we just wrote (otherwise, we overwrote it)
if ($filepath != $this->getFilePath($field)) {
@unlink($this->getFilePath($field));
}
#
# -- Attempt to do file conversions
#
if (isset($va_field_info["FILE_CONVERSIONS"]) && is_array($va_field_info["FILE_CONVERSIONS"]) && (sizeof($va_field_info["FILE_CONVERSIONS"]) > 0)) {
foreach($va_field_info["FILE_CONVERSIONS"] as $vs_output_format) {
if ($va_tmp = $ff->convert($vs_output_format, $filepath,$filestem)) { # new extension is added to end of stem by conversion
$vs_file_ext = $va_tmp["extension"];
$vs_format_name = $va_tmp["format_name"];
$vs_long_format_name = $va_tmp["long_format_name"];
$file_desc["CONVERSIONS"][$vs_output_format] = array(
"MIMETYPE" => $vs_output_format,
"FILENAME" => $this->_genMediaName($field)."_conv.".$vs_file_ext,
"PROPERTIES" => array(
"filesize" => filesize($filestem."_conv.".$vs_file_ext),
"extension" => $vs_file_ext,
"format_name" => $vs_format_name,
"long_format_name" => $vs_long_format_name
)
);
}
}
}
$this->_FILES[$field] = $file_desc;
$vs_sql = "$field = ".$this->quote(caSerializeForDatabase($this->_FILES[$field], true)).",";
$this->_FIELD_VALUES[$field]= $this->_SET_FILES[$field] = $file_desc;
}
}
return $vs_sql;
}
# --------------------------------------------------------------------------------
# --- Utilities
# --------------------------------------------------------------------------------
/**
* Can be called in two ways:
* 1. Called with two arguments: returns $val quoted and escaped for use with $field.
* That is, it will only quote $val if the field type requires it.
* 2. Called with one argument: simply returns $val quoted and escaped.
*
* @access public
* @param string $field field name
* @param string $val optional field value
*/
public function "e ($field, $val=null) {
if (is_null($val)) { # just quote it!
$field = "'".$this->escapeForDatabase($field)."'";
return $field;# quote only if field needs it
} else {
if ($this->_getFieldTypeType($field) == 1) {
$val = "'".$this->escapeForDatabase($val)."'";
}
return $val;
}
}
# --------------------------------------------------------------------------------
/**
* Escapes a string for SQL use
*
* @access public
* @param string $ps_value
* @return string
*/
public function escapeForDatabase ($ps_value) {
$o_db = $this->getDb();
return $o_db->escape($ps_value);
}
# --------------------------------------------------------------------------------
/**
* Make copy of BaseModel object with all fields information intact *EXCEPT* for the
* primary key value and all media and file fields, all of which are empty.
*
* @access public
* @return BaseModel the copy
*/
public function &cloneRecord() {
$o_clone = $this;
$o_clone->set($o_clone->getPrimaryKey(), null);
foreach($o_clone->getFields() as $vs_f) {
switch($o_clone->getFieldInfo($vs_f, "FIELD_TYPE")) {
case FT_MEDIA:
$o_clone->_FIELD_VALUES[$vs_f] = "";
break;
case FT_FILE:
$o_clone->_FIELD_VALUES[$vs_f] = "";
break;
}
}
return $o_clone;
}
# --------------------------------------------------------------------------------
/**
* Clears all fields in object
*
* @access public
*/
public function clear () {
$this->clearErrors();
foreach($this->FIELDS as $field => $attr) {
if (isset($this->FIELDS[$field]['START']) && ($vs_start_fld = $this->FIELDS[$field]['START'])) {
unset($this->_FIELD_VALUES[$vs_start_fld]);
unset($this->_FIELD_VALUES[$this->FIELDS[$field]['END']]);
}
unset($this->_FIELD_VALUES[$field]);
}
}
# --------------------------------------------------------------------------------
/**
* Prints contents of all fields in object
*
* @access public
*/
public function dump () {
$this->clearErrors();
reset($this->FIELDS);
while (list($field, $attr) = each($this->FIELDS)) {
echo "$field = ".$this->_FIELD_VALUES[$field]."<BR>\n";
}
}
# --------------------------------------------------------------------------------
/**
* Returns true if field exists in this object
*
* @access public
* @param string $field field name
* @return bool
*/
public function hasField ($field) {
return (isset($this->FIELDS[$field]) && $this->FIELDS[$field]) ? 1 : 0;
}
# --------------------------------------------------------------------------------
/**
* Returns underlying datatype for given field type
* 0 = numeric, 1 = string
*
* @access private
* @param string $fieldname
* @return int
*/
public function _getFieldTypeType ($fieldname) {
switch($this->FIELDS[$fieldname]["FIELD_TYPE"]) {
case (FT_TEXT):
case (FT_MEDIA):
case (FT_FILE):
case (FT_PASSWORD):
case (FT_VARS):
return 1;
break;
case (FT_NUMBER):
case (FT_TIMESTAMP):
case (FT_DATETIME):
case (FT_TIME):
case (FT_TIMERANGE):
case (FT_HISTORIC_DATETIME):
case (FT_DATE):
case (FT_HISTORIC_DATE):
case (FT_DATERANGE):
case (FT_TIMECODE):
case (FT_HISTORIC_DATERANGE):
case (FT_BIT):
return 0;
break;
default:
print "Invalid field type in _getFieldTypeType: ". $this->FIELDS[$fieldname]["FIELD_TYPE"];
exit;
}
}
# --------------------------------------------------------------------------------
/**
* Fetches the choice list value for a given field
*
* @access public
* @param string $field field name
* @param string $value choice list name
* @return string
*/
public function getChoiceListValue($field, $value) {
$va_attr = $this->getFieldInfo($field);
$va_list = $va_attr["BOUNDS_CHOICE_LIST"];
if (isset($va_attr['LIST']) && $va_attr['LIST']) {
$t_list = new ca_lists();
if ($t_list->load(array('list_code' => $va_attr['LIST']))) {
$va_items = caExtractValuesByUserLocale($t_list->getItemsForList($va_attr['LIST']));
$va_list = array();
foreach($va_items as $vn_item_id => $va_item_info) {
$va_list[$va_item_info['name_singular']] = $va_item_info['item_value'];
}
}
}
if ($va_list) {
foreach ($va_list as $k => $v) {
if ($v == $value) {
return $k;
}
}
} else {
return;
}
}
# --------------------------------------------------------------------------------
# --- Field input verification
# --------------------------------------------------------------------------------
/**
* Does bounds checks specified for field $field on value $value.
* Returns 0 and throws an exception is it fails, returns 1 on success.
*
* @access public
* @param string $field field name
* @param string $value value
*/
public function verifyFieldValue ($field, $value, &$pb_need_reload) {
$pb_need_reload = false;
$va_attr = $this->FIELDS[$field];
if (!$va_attr) {
$this->postError(716,_t("%1 does not exist", $field),"BaseModel->verifyFieldValue()");
return false;
}
$data_type = $this->_getFieldTypeType($field);
$field_type = $this->getFieldInfo($field,"FIELD_TYPE");
if ((isset($va_attr["FILTER"]) && ($filter = $va_attr["FILTER"]))) {
if (!preg_match($filter, $value)) {
$this->postError(1102,_t("%1 is invalid", $va_attr["LABEL"]),"BaseModel->verifyFieldValue()");
return false;
}
}
if ($data_type == 0) { # number; check value
if (isset($va_attr["BOUNDS_VALUE"][0])) { $min_value = $va_attr["BOUNDS_VALUE"][0]; }
if (isset($va_attr["BOUNDS_VALUE"][1])) { $max_value = $va_attr["BOUNDS_VALUE"][1];
}
if (!($va_attr["IS_NULL"] && (!$value))) {
if ((isset($min_value)) && ($value < $min_value)) {
$this->postError(1101,_t("%1 must not be less than %2", $va_attr["LABEL"], $min_value),"BaseModel->verifyFieldValue()");
return false;
}
if ((isset($max_value)) && ($value > $max_value)) {
$this->postError(1101,_t("%1 must not be greater than %2", $va_attr["LABEL"], $max_value),"BaseModel->verifyFieldValue()");
return false;
}
}
}
if (!isset($va_attr["IS_NULL"])) { $va_attr["IS_NULL"] = 0; }
if (!($va_attr["IS_NULL"] && (!$value))) {
# check length
if (isset($va_attr["BOUNDS_LENGTH"]) && is_array($va_attr["BOUNDS_LENGTH"])) {
$min_length = $va_attr["BOUNDS_LENGTH"][0];
$max_length = $va_attr["BOUNDS_LENGTH"][1];
}
if ((isset($min_length)) && (strlen($value) < $min_length)) {
$this->postError(1102, _t("%1 must be at least %2 characters", $va_attr["LABEL"], $min_length),"BaseModel->verifyFieldValue()");
return false;
}
if ((isset($max_length)) && (strlen($value) > $max_length)) {
$this->postError(1102,_t("%1 must not be more than %2 characters long", $va_attr["LABEL"], $max_length),"BaseModel->verifyFieldValue()");
return false;
}
$va_list = isset($va_attr["BOUNDS_CHOICE_LIST"]) ? $va_attr["BOUNDS_CHOICE_LIST"] : null;
if (isset($va_attr['LIST']) && $va_attr['LIST']) {
$t_list = new ca_lists();
if ($t_list->load(array('list_code' => $va_attr['LIST']))) {
$va_items = caExtractValuesByUserLocale($t_list->getItemsForList($va_attr['LIST']));
$va_list = array();
$vs_list_default = null;
foreach($va_items as $vn_item_id => $va_item_info) {
if(is_null($vs_list_default) || (isset($va_item_info['is_default']) && $va_item_info['is_default'])) { $vs_list_default = $va_item_info['item_value']; }
$va_list[$va_item_info['name_singular']] = $va_item_info['item_value'];
}
$va_attr['DEFAULT'] = $vs_list_default;
}
}
if ((in_array($data_type, array(FT_NUMBER, FT_TEXT))) && (isset($va_list)) && (is_array($va_list)) && (count($va_list) > 0)) { # string; check choice list
if (isset($va_attr['DEFAULT']) && !strlen($value)) {
$value = $va_attr['DEFAULT'];
if (strlen($value)) {
$this->set($field, $value);
$pb_need_reload = true;
}
} // force default value if nothing is set
if (!is_array($value)) { $value = explode(":",$value); }
if (!isset($va_attr['LIST_MULTIPLE_DELIMITER']) || !($vs_list_multiple_delimiter = $va_attr['LIST_MULTIPLE_DELIMITER'])) { $vs_list_multiple_delimiter = ';'; }
foreach($value as $v) {
if ((sizeof($value) > 1) && (!$v)) continue;
if ($va_attr['DISPLAY_TYPE'] == DT_LIST_MULTIPLE) {
$va_tmp = explode($vs_list_multiple_delimiter, $v);
foreach($va_tmp as $vs_mult_item) {
if (!in_array($vs_mult_item,$va_list)) {
$this->postError(1103,_t("'%1' is not valid choice for %2", $v, $va_attr["LABEL"]),"BaseModel->verifyFieldValue()");
return false;
}
}
} else {
if (!in_array($v,$va_list)) {
$this->postError(1103, _t("'%1' is not valid choice for %2", $v, $va_attr["LABEL"]),"BaseModel->verifyFieldValue()");
return false;
}
}
}
}
}
return true;
}
# --------------------------------------------------------------------------------------------
/**
* Verifies values of each field and returns a hash keyed on field name with values set to
* and array of error messages for each field. Returns false (0) if no errors.
*
* @access public
* @return array|bool
*/
public function verifyForm() {
$this->clearErrors();
$errors = array();
$errors_found = 0;
$fields = $this->getFormFields();
$err_halt = $this->error->getHaltOnError();
$err_report = $this->error->getReportOnError();
$this->error->setErrorOutput(0);
while(list($field,$attr) = each($fields)) {
$pb_need_reload = false;
$this->verifyFieldValue ($field, $this->get($field), $pb_need_reload);
if ($errnum = $this->error->getErrorNumber()) {
$errors[$field][$errnum] = $this->error->getErrorDescription();
$errors_found++;
}
}
$this->error->setHaltOnError($err_halt);
$this->error->setReportOnError($err_report);
if ($errors_found) {
return $errors;
} else {
return false;
}
}
# --------------------------------------------------------------------------------------------
# --- Field info
# --------------------------------------------------------------------------------------------
/**
* Returns a hash with field names as keys and attributes hashes as values
* If $names_only is set, only the field names are returned in an indexed array (NOT a hash)
* Only returns fields that belong in public forms - it omits those fields with a display type of 7 ("PRIVATE")
*
* @param bool $return_all
* @param bool $names_only
* @return array
*/
public function getFormFields ($return_all = 0, $names_only = 0) {
if (($return_all) && (!$names_only)) {
return $this->FIELDS;
}
$form_fields = array();
if (!$names_only) {
foreach($this->FIELDS as $field => $attr) {
if ($return_all || ($attr["DISPLAY_TYPE"] != DT_OMIT)) {
$form_fields[$field] = $attr;
}
}
} else {
foreach($this->FIELDS as $field => $attr) {
if ($return_all || ($attr["DISPLAY_TYPE"] != DT_OMIT)) {
$form_fields[] = $field;
}
}
}
return $form_fields;
}
# --------------------------------------------------------------------------------------------
/**
* Returns (array) snapshot of the record represented by this BaseModel object
*
* @access public
* @param bool $pb_changes_only optional, just return changed fields
* @return array
*/
public function &getSnapshot($pb_changes_only=false) {
$va_field_list = $this->getFormFields(true, true);
$va_snapshot = array();
foreach($va_field_list as $vs_field) {
if (!$pb_changes_only || ($pb_changes_only && $this->changed($vs_field))) {
$va_snapshot[$vs_field] = $this->get($vs_field);
}
}
// We need to include the element_id when storing snapshots of ca_attributes and ca_attribute_values
// whether is has changed or not (actually, it shouldn't really be changing after insert in normal use)
// We need it available to assist in proper display of attributes in the change log
if (in_array($this->tableName(), array('ca_attributes', 'ca_attribute_values'))) {
$va_snapshot['element_id'] = $this->get('element_id');
$va_snapshot['attribute_id'] = $this->get('attribute_id');
}
return $va_snapshot;
}
# --------------------------------------------------------------------------------------------
/**
* Returns attributes hash for specified field
*
* @access public
* @param string $field field name
* @param string $attribute optional restriction to a single attribute
*/
public function getFieldInfo($field, $attribute = "") {
if (isset($this->FIELDS[$field])) {
$fieldinfo = $this->FIELDS[$field];
if ($attribute) {
return (isset($fieldinfo[$attribute])) ? $fieldinfo[$attribute] : "";
} else {
return $fieldinfo;
}
} else {
$this->postError(710,_t("'%1' does not exist in this object", $field),"BaseModel->getFieldInfo()");
return false;
}
}
# --------------------------------------------------------------------------------------------
/**
* Returns display label for element specified by standard "get" bundle code (eg. <table_name>.<field_name> format)
*/
public function getDisplayLabel($ps_field) {
$va_tmp = explode('.', $ps_field);
if ($va_tmp[0] == 'created') {
return _t('Creation date/time');
}
if ($va_tmp[0] == 'modified') {
return _t('Modification date/time');
}
if ($va_tmp[0] != $this->tableName()) { return null; }
if ($this->hasField($va_tmp[1])) {
return $this->getFieldInfo($va_tmp[1], 'LABEL');
}
if ($va_tmp[1] == 'created') {
return _t('Creation date/time');
}
if ($va_tmp[1] == 'lastModified') {
return _t('Last modification date/time');
}
return null;
}
# --------------------------------------------------------------------------------------------
/**
* Returns display description for element specified by standard "get" bundle code (eg. <table_name>.<bundle_name> format)
*/
public function getDisplayDescription($ps_field) {
$va_tmp = explode('.', $ps_field);
if ($va_tmp[0] == 'created') {
return _t('Date and time %1 was created', $this->getProperty('NAME_SINGULAR'));
}
if ($va_tmp[0] == 'modified') {
return _t('Date and time %1 was modified', $this->getProperty('NAME_SINGULAR'));
}
if ($va_tmp[0] != $this->tableName()) { return null; }
if ($this->hasField($va_tmp[1])) {
return $this->getFieldInfo($va_tmp[1], 'DESCRIPTION');
}
if ($va_tmp[1] == 'created') {
return _t('Date and time %1 was created', $this->getProperty('NAME_SINGULAR'));
}
if ($va_tmp[1] == 'lastModified') {
return _t('Date and time %1 was last modified', $this->getProperty('NAME_SINGULAR'));
}
return null;
}
# --------------------------------------------------------------------------------------------
/**
* Returns HTML search form input widget for bundle specified by standard "get" bundle code (eg. <table_name>.<bundle_name> format)
* This method handles generation of search form widgets for intrinsic fields in the primary table. If this method can't handle
* the bundle (because it is not an intrinsic field in the primary table...) it will return null.
*
* @param $po_request HTTPRequest
* @param $ps_field string
* @param $pa_options array
* @return string HTML text of form element. Will return null if it is not possible to generate an HTML form widget for the bundle.
*
*/
public function htmlFormElementForSearch($po_request, $ps_field, $pa_options=null) {
if (!is_array($pa_options)) { $pa_options = array(); }
if (isset($pa_options['width'])) {
if ($va_dim = caParseFormElementDimension($pa_options['width'])) {
if ($va_dim['type'] == 'pixels') {
unset($pa_options['width']);
$pa_options['maxPixelWidth'] = $va_dim['dimension'];
}
}
}
$va_tmp = explode('.', $ps_field);
if (in_array($va_tmp[0], array('created', 'modified'))) {
return caHTMLTextInput($ps_field, array(
'id' => str_replace(".", "_", $ps_field),
'width' => (isset($pa_options['width']) && ($pa_options['width'] > 0)) ? $pa_options['width'] : 30,
'height' => (isset($pa_options['height']) && ($pa_options['height'] > 0)) ? $pa_options['height'] : 1,
'value' => (isset($pa_options['values'][$ps_field]) ? $pa_options['values'][$ps_field] : ''))
);
}
if ($va_tmp[0] != $this->tableName()) { return null; }
if ($this->hasField($va_tmp[1])) {
return $this->htmlFormElement($va_tmp[1], '^ELEMENT', array_merge($pa_options, array(
'name' => $ps_field,
'id' => str_replace(".", "_", $ps_field),
'nullOption' => '-',
'value' => (isset($pa_options['values'][$ps_field]) ? $pa_options['values'][$ps_field] : ''),
'width' => (isset($pa_options['width']) && ($pa_options['width'] > 0)) ? $pa_options['width'] : 30,
'height' => (isset($pa_options['height']) && ($pa_options['height'] > 0)) ? $pa_options['height'] : 1,
'no_tooltips' => true
)));
}
return null;
}
# --------------------------------------------------------------------------------------------
/**
* Return list of fields that had conflicts with existing data during last update()
* (ie. someone else had already saved to this field while the user of this instance was working)
*
* @access public
*/
public function getFieldConflicts() {
return $this->field_conflicts;
}
# --------------------------------------------------------------------------------------------
# --- Change log
# --------------------------------------------------------------------------------------------
/**
* Log a change
*
* @access private
* @param string $ps_change_type 'I', 'U' or 'D', meaning INSERT, UPDATE or DELETE
* @param int $pn_user_id user identifier, defaults to null
*/
private function logChange($ps_change_type, $pn_user_id=null) {
$vb_is_metadata = $vb_is_metadata_value = false;
if ($this->tableName() == 'ca_attributes') {
$vb_log_changes_to_self = false;
$va_subject_config = null;
$vb_is_metadata = true;
} elseif($this->tableName() == 'ca_attribute_values') {
$vb_log_changes_to_self = false;
$va_subject_config = null;
$vb_is_metadata_value = true;
} else {
$vb_log_changes_to_self = $this->getProperty('LOG_CHANGES_TO_SELF');
$va_subject_config = $this->getProperty('LOG_CHANGES_USING_AS_SUBJECT');
}
global $AUTH_CURRENT_USER_ID;
if (!$pn_user_id) { $pn_user_id = $AUTH_CURRENT_USER_ID; }
if (!$pn_user_id) { $pn_user_id = null; }
if (!in_array($ps_change_type, array('I', 'U', 'D'))) { return false; }; // invalid change type (shouldn't happen)
if (!($vn_row_id = $this->getPrimaryKey())) { return false; } // no logging without primary key value
// get unit id (if set)
global $g_change_log_unit_id;
$vn_unit_id = $g_change_log_unit_id;
if (!$vn_unit_id) { $vn_unit_id = null; }
// get subject ids
$va_subjects = array();
if ($vb_is_metadata) {
// special case for logging attribute changes
if (($vn_id = $this->get('row_id')) > 0) {
$va_subjects[$this->get('table_num')][] = $vn_id;
}
} elseif ($vb_is_metadata_value) {
// special case for logging metadata changes
$t_attr = new ca_attributes($this->get('attribute_id'));
if (($vn_id = $t_attr->get('row_id')) > 0) {
$va_subjects[$t_attr->get('table_num')][] = $vn_id;
}
} else {
if (is_array($va_subject_config)) {
if(is_array($va_subject_config['FOREIGN_KEYS'])) {
foreach($va_subject_config['FOREIGN_KEYS'] as $vs_field) {
$va_relationships = $this->_DATAMODEL->getManyToOneRelations($this->tableName(), $vs_field);
if ($va_relationships['one_table']) {
$vn_table_num = $this->_DATAMODEL->getTableNum($va_relationships['one_table']);
if (!isset($va_subjects[$vn_table_num]) || !is_array($va_subjects[$vn_table_num])) { $va_subjects[$vn_table_num] = array(); }
if (($vn_id = $this->get($vs_field)) > 0) {
$va_subjects[$vn_table_num][] = $vn_id;
}
}
}
}
if(is_array($va_subject_config['RELATED_TABLES'])) {
if (!isset($o_db) || !$o_db) {
$o_db = new Db();
$o_db->dieOnError(false);
}
foreach($va_subject_config['RELATED_TABLES'] as $vs_dest_table => $va_path_to_dest) {
$t_dest = $this->_DATAMODEL->getTableInstance($vs_dest_table);
if (!$t_dest) { continue; }
$vn_dest_table_num = $t_dest->tableNum();
$vs_dest_primary_key = $t_dest->primaryKey();
$va_path_to_dest[] = $vs_dest_table;
$vs_cur_table = $this->tableName();
$vs_sql = "SELECT ".$vs_dest_table.".".$vs_dest_primary_key." FROM ".$this->tableName()."\n";
foreach($va_path_to_dest as $vs_ltable) {
$va_relations = $this->_DATAMODEL->getRelationships($vs_cur_table, $vs_ltable);
$vs_sql .= "INNER JOIN $vs_ltable ON $vs_cur_table.".$va_relations[$vs_cur_table][$vs_ltable][0][0]." = $vs_ltable.".$va_relations[$vs_cur_table][$vs_ltable][0][1]."\n";
$vs_cur_table = $vs_ltable;
}
$vs_sql .= "WHERE ".$this->tableName().".".$this->primaryKey()." = ".$this->getPrimaryKey();
if ($qr_subjects = $o_db->query($vs_sql)) {
if (!isset($va_subjects[$vn_dest_table_num]) || !is_array($va_subjects[$vn_dest_table_num])) { $va_subjects[$vn_dest_table_num] = array(); }
while($qr_subjects->nextRow()) {
if (($vn_id = $qr_subjects->get($vs_dest_primary_key)) > 0) {
$va_subjects[$vn_dest_table_num][] = $vn_id;
}
}
} else {
print "<hr>Error in subject logging: ";
print "<br>$vs_sql<hr>\n";
}
}
}
}
}
if (!sizeof($va_subjects) && !$vb_log_changes_to_self) { return true; }
if (!$this->opqs_change_log) {
$o_db = $this->getDb();
$o_db->dieOnError(false);
$vs_change_log_database = '';
if ($vs_change_log_database = $this->_CONFIG->get("change_log_database")) {
$vs_change_log_database .= ".";
}
if (!($this->opqs_change_log = $o_db->prepare("
INSERT INTO ".$vs_change_log_database."ca_change_log
(
log_datetime, user_id, unit_id, changetype,
logged_table_num, logged_row_id
)
VALUES
(?, ?, ?, ?, ?, ?)
"))) {
// prepare failed - shouldn't happen
return false;
}
if (!($this->opqs_change_log_snapshot = $o_db->prepare("
INSERT INTO ".$vs_change_log_database."ca_change_log_snapshots
(
log_id, snapshot
)
VALUES
(?, ?)
"))) {
// prepare failed - shouldn't happen
return false;
}
if (!($this->opqs_change_log_subjects = $o_db->prepare("
INSERT INTO ".$vs_change_log_database."ca_change_log_subjects
(
log_id, subject_table_num, subject_row_id
)
VALUES
(?, ?, ?)
"))) {
// prepare failed - shouldn't happen
return false;
}
}
// get snapshot of changes made to record
$va_snapshot = $this->getSnapshot(($ps_change_type === 'U') ? true : false);
$vs_snapshot = caSerializeForDatabase($va_snapshot, true);
if (!(($ps_change_type == 'U') && (!sizeof($va_snapshot)))) {
// Create primary log entry
$this->opqs_change_log->execute(
time(), $pn_user_id, $vn_unit_id, $ps_change_type,
$this->tableNum(), $vn_row_id
);
$vn_log_id = $this->opqs_change_log->getLastInsertID();
$this->opqs_change_log_snapshot->execute(
$vn_log_id, $vs_snapshot
);
foreach($va_subjects as $vn_subject_table_num => $va_subject_ids) {
foreach($va_subject_ids as $vn_subject_row_id) {
$this->opqs_change_log_subjects->execute($vn_log_id, $vn_subject_table_num, $vn_subject_row_id);
}
}
}
}
# --------------------------------------------------------------------------------------------
/**
* Get change log for the current record represented by this BaseModel object, or for another specified row.
*
* @access public
* @param int $pn_row_id Return change log for row with specified primary key id. If omitted currently loaded record is used.
* @param array $pa_options Array of options. Valid options are:
* range = optional range to restrict returned entries to. Should be array with 0th key set to start and 1st key set to end of range. Both values should be Unix timestamps. You can also use 'start' and 'end' as keys if desired.
* limit = maximum number of entries returned. Omit or set to zero for no limit. [default=all]
* forTable = if true only return changes made directly to the current table (ie. omit changes to related records that impact this record [default=false]
* excludeUnitID = if set, log records with the specific unit_id are not returned [default=not set]
* changeType = if set to I, U or D, will limit change log to inserts, updates or deletes respectively. If not set all types are returned.
* @return array Change log data
*/
public function getChangeLog($pn_row_id=null, $pa_options=null) {
$pa_datetime_range = (isset($pa_options['range']) && is_array($pa_options['range'])) ? $pa_options['range'] : null;
$pn_max_num_entries_returned = (isset($pa_options['limit']) && (int)$pa_options['limit']) ? (int)$pa_options['limit'] : 0;
$pb_for_table = (isset($pa_options['forTable'])) ? (bool)$pa_options['forTable'] : false;
$ps_exclude_unit_id = (isset($pa_options['excludeUnitID']) && $pa_options['excludeUnitID']) ? $pa_options['excludeUnitID'] : null;
$ps_change_type = (isset($pa_options['changeType']) && in_array($pa_options['changeType'], array('I', 'U', 'D'))) ? $pa_options['changeType'] : null;
$vs_daterange_sql = '';
if ($pa_datetime_range) {
$vn_start = $vn_end = null;
if (isset($pa_datetime_range[0])) {
$vn_start = (int)$pa_datetime_range[0];
} else {
if (isset($pa_datetime_range['start'])) {
$vn_start = (int)$pa_datetime_range['start'];
}
}
if (isset($pa_datetime_range[1])) {
$vn_end = (int)$pa_datetime_range[1];
} else {
if (isset($pa_datetime_range['end'])) {
$vn_end = (int)$pa_datetime_range['end'];
}
}
if ($vn_start <= 0) { $vn_start = time() - 3600; }
if (!$vn_end <= 0) { $vn_end = time(); }
if ($vn_end < $vn_start) { $vn_end = $vn_start; }
if (!$pn_row_id) {
if (!($pn_row_id = $this->getPrimaryKey())) {
return array();
}
}
$vs_daterange_sql = " AND (wcl.log_datetime > ? AND wcl.log_datetime < ?)";
}
if (!$this->opqs_get_change_log) {
$vs_change_log_database = '';
if ($vs_change_log_database = $this->_CONFIG->get("change_log_database")) {
$vs_change_log_database .= ".";
}
$o_db = $this->getDb();
if ($pb_for_table) {
if (!($this->opqs_get_change_log = $o_db->prepare("
SELECT DISTINCT
wcl.log_id, wcl.log_datetime log_datetime, wcl.user_id, wcl.changetype, wcl.logged_table_num, wcl.logged_row_id,
wclsnap.snapshot, wcl.unit_id, wu.email, wu.fname, wu.lname
FROM ca_change_log wcl
INNER JOIN ca_change_log_snapshots AS wclsnap ON wclsnap.log_id = wcl.log_id
LEFT JOIN ca_change_log_subjects AS wcls ON wcl.log_id = wcls.log_id
LEFT JOIN ca_users AS wu ON wcl.user_id = wu.user_id
WHERE
(
(wcl.logged_table_num = ".((int)$this->tableNum()).") AND ".(($ps_change_type) ? "(wcl.changetype = '".$ps_change_type."') AND " : "")."
(wcl.logged_row_id = ?)
)
{$vs_daterange_sql}
ORDER BY log_datetime
"))) {
# should not happen
return false;
}
} else {
if (!($this->opqs_get_change_log = $o_db->prepare("
SELECT DISTINCT
wcl.log_id, wcl.log_datetime log_datetime, wcl.user_id, wcl.changetype, wcl.logged_table_num, wcl.logged_row_id,
wclsnap.snapshot, wcl.unit_id, wu.email, wu.fname, wu.lname
FROM ca_change_log wcl
INNER JOIN ca_change_log_snapshots AS wclsnap ON wclsnap.log_id = wcl.log_id
LEFT JOIN ca_change_log_subjects AS wcls ON wcl.log_id = wcls.log_id
LEFT JOIN ca_users AS wu ON wcl.user_id = wu.user_id
WHERE
(
(wcl.logged_table_num = ".((int)$this->tableNum()).") AND ".(($ps_change_type) ? "(wcl.changetype = '".$ps_change_type."') AND " : "")."
(wcl.logged_row_id = ?)
)
{$vs_daterange_sql}
UNION
SELECT DISTINCT
wcl.log_id, wcl.log_datetime, wcl.user_id, wcl.changetype, wcl.logged_table_num, wcl.logged_row_id,
wclsnap.snapshot, wcl.unit_id, wu.email, wu.fname, wu.lname
FROM ca_change_log wcl
INNER JOIN ca_change_log_snapshots AS wclsnap ON wclsnap.log_id = wcl.log_id
LEFT JOIN ca_change_log_subjects AS wcls ON wcl.log_id = wcls.log_id
LEFT JOIN ca_users AS wu ON wcl.user_id = wu.user_id
WHERE
(
(wcls.subject_table_num = ".((int)$this->tableNum()).") AND ".(($ps_change_type) ? "(wcl.changetype = '".$ps_change_type."') AND " : "")."
(wcls.subject_row_id = ?)
)
{$vs_daterange_sql}
ORDER BY log_datetime
"))) {
# should not happen
return false;
}
}
if ($pn_max_num_entries_returned > 0) {
$this->opqs_get_change_log->setLimit($pn_max_num_entries_returned);
}
}
// get directly logged records
$va_log = array();
if ($pb_for_table) {
$qr_log = $this->opqs_get_change_log->execute($vs_daterange_sql ? array((int)$pn_row_id, (int)$vn_start, (int)$vn_end) : array((int)$pn_row_id));
} else {
$qr_log = $this->opqs_get_change_log->execute($vs_daterange_sql ? array((int)$pn_row_id, (int)$vn_start, (int)$vn_end, (int)$pn_row_id, (int)$vn_start, (int)$vn_end) : array((int)$pn_row_id, (int)$pn_row_id));
}
while($qr_log->nextRow()) {
if ($ps_exclude_unit_id && ($ps_exclude_unit_id == $qr_log->get('unit_id'))) { continue; }
$va_log[] = $qr_log->getRow();
$va_log[sizeof($va_log)-1]['snapshot'] = caUnserializeForDatabase($va_log[sizeof($va_log)-1]['snapshot']);
}
return $va_log;
}
# --------------------------------------------------------------------------------------------
/**
* Get list of users (containing username, user id, forename, last name and email adress) who changed something
* in a) this record (if the parameter is omitted) or b) the whole table (if the parameter is set).
*
* @access public
* @param bool $pb_for_table
* @return array
*/
public function getChangeLogUsers($pb_for_table=false) {
$o_db = $this->getDb();
if ($pb_for_table) {
$qr_users = $o_db->query("
SELECT DISTINCT wu.user_id, wu.user_name, wu.fname, wu.lname, wu.email
FROM ca_users wu
INNER JOIN ca_change_log AS wcl ON wcl.user_id = wu.user_id
LEFT JOIN ca_change_log_subjects AS wcls ON wcl.log_id = wcls.log_id
WHERE
((wcls.subject_table_num = ?) OR (wcl.logged_table_num = ?))
ORDER BY wu.lname, wu.fname
", $this->tableNum(), $this->tableNum());
} else {
$qr_users = $o_db->query("
SELECT DISTINCT wu.user_id, wu.user_name, wu.fname, wu.lname, wu.email
FROM ca_users wu
INNER JOIN ca_change_log AS wcl ON wcl.user_id = wu.user_id
LEFT JOIN ca_change_log_subjects AS wcls ON wcl.log_id = wcls.log_id
WHERE
((wcls.subject_table_num = ?) OR (wcl.logged_table_num = ?))
AND
((wcl.logged_row_id = ?) OR (wcls.subject_row_id = ?))
ORDER BY wu.lname, wu.fname
", $this->tableNum(), $this->tableNum(), $this->getPrimaryKey(), $this->getPrimaryKey());
}
$va_users = array();
while($qr_users->nextRow()) {
$vs_user_name = $qr_users->get('user_name');
$va_users[$vs_user_name] = array(
'user_name' => $vs_user_name,
'user_id' => $qr_users->get('user_id'),
'fname' => $qr_users->get('fname'),
'lname' => $qr_users->get('lname'),
'email' => $qr_users->get('email')
);
}
return $va_users;
}
# --------------------------------------------------------------------------------------------
/**
* Returns information about the creation currently loaded row
*
* @param int $pn_row_id If set information is returned about the specified row instead of the currently loaded one.
* @param array $pa_options Array of options. Supported options are:
* timestampOnly = if set to true an integer Unix timestamp for the date/time of creation is returned. If false (default) then an array is returned with timestamp and user information about the creation.
* @return mixed An array detailing the date/time and creator of the row. Array includes the user_id, fname, lname and email of the user who executed the change as well as an integer Unix-style timestamp. If the timestampOnly option is set then only the timestamp is returned.
*/
public function getCreationTimestamp($pn_row_id=null, $pa_options=null) {
if (!($vn_row_id = $pn_row_id)) {
if (!($vn_row_id = $this->getPrimaryKey())) { return null; }
}
$o_db = $this->getDb();
$qr_res = $o_db->query("
SELECT wcl.log_datetime, wu.user_id, wu.fname, wu.lname, wu.email
FROM ca_change_log wcl
LEFT JOIN ca_users AS wu ON wcl.user_id = wu.user_id
WHERE
(wcl.logged_table_num = ?) AND (wcl.logged_row_id = ?) AND(wcl.changetype = 'I')",
$this->tableNum(), $vn_row_id);
if ($qr_res->nextRow()) {
if (isset($pa_options['timestampOnly']) && $pa_options['timestampOnly']) {
return $qr_res->get('log_datetime');
}
return array(
'user_id' => $qr_res->get('user_id'),
'fname' => $qr_res->get('fname'),
'lname' => $qr_res->get('lname'),
'email' => $qr_res->get('email'),
'timestamp' => $qr_res->get('log_datetime')
);
}
return null;
}
# --------------------------------------------------------------------------------------------
/**
* Returns information about the last change made to the currently loaded row
*
* @param int $pn_row_id If set information is returned about the specified row instead of the currently loaded one.
* @param array $pa_options Array of options. Supported options are:
* timestampOnly = if set to true an integer Unix timestamp for the last change is returned. If false (default) then an array is returned with timestamp and user information about the change.
* @return mixed An array detailing the date/time and initiator of the last change. Array includes the user_id, fname, lname and email of the user who executed the change as well as an integer Unix-style timestamp. If the timestampOnly option is set then only the timestamp is returned.
*/
public function getLastChangeTimestamp($pn_row_id=null, $pa_options=null) {
if (!($vn_row_id = $pn_row_id)) {
if (!($vn_row_id = $this->getPrimaryKey())) { return null; }
}
$o_db = $this->getDb();
$qr_res = $o_db->query("
SELECT wcl.log_datetime, wu.user_id, wu.fname, wu.lname, wu.email
FROM ca_change_log wcl
LEFT JOIN ca_users AS wu ON wcl.user_id = wu.user_id
INNER JOIN ca_change_log_subjects AS wcls ON wcl.log_id = wcls.log_id
WHERE
(wcls.subject_table_num = ?)
AND
(wcls.subject_row_id = ?)
AND
(wcl.changetype IN ('I', 'U'))
ORDER BY wcl.log_datetime DESC LIMIT 1",
$this->tableNum(), $vn_row_id);
$vn_last_change_timestamp = 0;
$va_last_change_info = null;
if ($qr_res->nextRow()) {
$vn_last_change_timestamp = $qr_res->get('log_datetime');
$va_last_change_info = array(
'user_id' => $qr_res->get('user_id'),
'fname' => $qr_res->get('fname'),
'lname' => $qr_res->get('lname'),
'email' => $qr_res->get('email'),
'timestamp' => $qr_res->get('log_datetime')
);
}
$qr_res = $o_db->query("
SELECT wcl.log_datetime, wu.user_id, wu.fname, wu.lname, wu.email
FROM ca_change_log wcl
LEFT JOIN ca_users AS wu ON wcl.user_id = wu.user_id
WHERE
(wcl.logged_table_num = ?)
AND
(wcl.logged_row_id = ?)
AND
(wcl.changetype IN ('I', 'U'))
ORDER BY wcl.log_datetime DESC LIMIT 1",
$this->tableNum(), $vn_row_id);
if ($qr_res->nextRow()) {
if ($qr_res->get('log_datetime') > $vn_last_change_timestamp) {
$vn_last_change_timestamp = $qr_res->get('log_datetime');
$va_last_change_info = array(
'user_id' => $qr_res->get('user_id'),
'fname' => $qr_res->get('fname'),
'lname' => $qr_res->get('lname'),
'email' => $qr_res->get('email'),
'timestamp' => $qr_res->get('log_datetime')
);
}
}
if ($vn_last_change_timestamp > 0) {
if (isset($pa_options['timestampOnly']) && $pa_options['timestampOnly']) {
return $vn_last_change_timestamp;
}
return $va_last_change_info;
}
return null;
}
# --------------------------------------------------------------------------------------------
# --- Hierarchical functions
# --------------------------------------------------------------------------------------------
/**
* Are we dealing with a hierarchical structure in this table?
*
* @access public
* @return bool
*/
public function isHierarchical() {
return (!is_null($this->getProperty("HIERARCHY_TYPE"))) ? true : false;
}
# --------------------------------------------------------------------------------------------
/**
* What type of hierarchical structure is used by this table?
*
* @access public
* @return int (__CA_HIER_*__ constant)
*/
public function getHierarchyType() {
return $this->getProperty("HIERARCHY_TYPE");
}
# --------------------------------------------------------------------------------------------
/**
* Fetches primary key of the hierarchy root.
* DOES NOT CREATE ROOT - YOU HAVE TO DO THAT YOURSELF (this differs from previous versions of these libraries).
*
* @param int $pn_hierarchy_id optional, points to record in related table containing hierarchy description
* @return int root id
*/
public function getHierarchyRootID($pn_hierarchy_id=null) {
$vn_root_id = null;
$o_db = $this->getDb();
switch($this->getHierarchyType()) {
# ------------------------------------------------------------------
case __CA_HIER_TYPE_SIMPLE_MONO__:
// For simple "table is one big hierarchy" setups all you need
// to do is look for the row where parent_id is NULL
$qr_res = $o_db->query("
SELECT ".$this->primaryKey()."
FROM ".$this->tableName()."
WHERE
(".$this->getProperty('HIERARCHY_PARENT_ID_FLD')." IS NULL)
");
if ($qr_res->nextRow()) {
$vn_root_id = $qr_res->get($this->primaryKey());
}
break;
# ------------------------------------------------------------------
case __CA_HIER_TYPE_MULTI_MONO__:
// For tables that house multiple hierarchies defined in a second table
// you need to look for the row where parent_id IS NULL and hierarchy_id = the value
// passed in $pn_hierarchy_id
if (!$pn_hierarchy_id) { // if hierarchy_id is not explicitly set use the value in the currently loaded row
$pn_hierarchy_id = $this->get($this->getProperty('HIERARCHY_PARENT_ID_FLD'));
}
$qr_res = $o_db->query("
SELECT ".$this->primaryKey()."
FROM ".$this->tableName()."
WHERE
(".$this->getProperty('HIERARCHY_PARENT_ID_FLD')." IS NULL)
AND
(".$this->getProperty('HIERARCHY_ID_FLD')." = ?)
", (int)$pn_hierarchy_id);
if ($qr_res->nextRow()) {
$vn_root_id = $qr_res->get($this->primaryKey());
}
break;
# ------------------------------------------------------------------
case __CA_HIER_TYPE_ADHOC_MONO__:
// For ad-hoc hierarchies you just return the hierarchy_id value
if (!$pn_hierarchy_id) { // if hierarchy_id is not explicitly set use the value in the currently loaded row
$pn_hierarchy_id = $this->get($this->getProperty('HIERARCHY_ID_FLD'));
}
$vn_root_id = $pn_hierarchy_id;
break;
# ------------------------------------------------------------------
case __CA_HIER_TYPE_MULTI_POLY__:
// TODO: implement this
break;
# ------------------------------------------------------------------
default:
die("Invalid hierarchy type: ".$this->getHierarchyType());
break;
# ------------------------------------------------------------------
}
return $vn_root_id;
}
# --------------------------------------------------------------------------------------------
/**
* Fetch a DbResult representation of the whole hierarchy
*
* @access public
* @param int $pn_id optional, id of record to be treated as root
* @param array $pa_options
* returnDeleted = return deleted records in list (def. false)
* additionalTableToJoin: name of table to join to hierarchical table (and return fields from); only fields related many-to-one are currently supported
*
* @return DbResult
*/
public function &getHierarchy($pn_id=null, $pa_options=null) {
if (!is_array($pa_options)) { $pa_options = array(); }
$vs_table_name = $this->tableName();
if ($this->isHierarchical()) {
$vs_hier_left_fld = $this->getProperty("HIERARCHY_LEFT_INDEX_FLD");
$vs_hier_right_fld = $this->getProperty("HIERARCHY_RIGHT_INDEX_FLD");
$vs_hier_parent_id_fld = $this->getProperty("HIERARCHY_PARENT_ID_FLD");
$vs_hier_id_fld = $this->getProperty("HIERARCHY_ID_FLD");
$vs_hier_id_table = $this->getProperty("HIERARCHY_DEFINITION_TABLE");
if (!$pn_id) {
if (!($pn_id = $this->getHierarchyRootID($this->get($vs_hier_id_fld)))) {
return null;
}
}
$vn_hierarchy_id = $this->get($vs_hier_id_fld);
$vs_hier_id_sql = "";
if ($vn_hierarchy_id) {
// TODO: verify hierarchy_id exists
$vs_hier_id_sql = " AND (".$vs_hier_id_fld." = ".$vn_hierarchy_id.")";
}
$o_db = $this->getDb();
$qr_root = $o_db->query("
SELECT $vs_hier_left_fld, $vs_hier_right_fld ".(($this->hasField($vs_hier_id_fld)) ? ", $vs_hier_id_fld" : "")."
FROM ".$this->tableName()."
WHERE
(".$this->primaryKey()." = ?)
", intval($pn_id));
if ($o_db->numErrors()) {
$this->errors = array_merge($this->errors, $o_db->errors());
return null;
} else {
if ($qr_root->nextRow()) {
$va_count = array();
if (($this->hasField($vs_hier_id_fld)) && (!($vn_hierarchy_id = $this->get($vs_hier_id_fld))) && (!($vn_hierarchy_id = $qr_root->get($vs_hier_id_fld)))) {
$this->postError(2030, _t("Hierarchy ID must be specified"), "Table->getHierarchy()");
return false;
}
$vs_table_name = $this->tableName();
$vs_hier_id_sql = "";
if ($vn_hierarchy_id) {
$vs_hier_id_sql = " AND ({$vs_table_name}.{$vs_hier_id_fld} = {$vn_hierarchy_id})";
}
$va_sql_joins = array();
if (isset($pa_options['additionalTableToJoin']) && ($pa_options['additionalTableToJoin'])){
$ps_additional_table_to_join = $pa_options['additionalTableToJoin'];
// what kind of join are we doing for the additional table? LEFT or INNER? (default=INNER)
$ps_additional_table_join_type = 'INNER';
if (isset($pa_options['additionalTableJoinType']) && ($pa_options['additionalTableJoinType'] === 'LEFT')) {
$ps_additional_table_join_type = 'LEFT';
}
if (is_array($va_rel = $this->getAppDatamodel()->getOneToManyRelations($this->tableName(), $ps_additional_table_to_join))) {
// one-many rel
$va_sql_joins[] = "{$ps_additional_table_join_type} JOIN {$ps_additional_table_to_join} ON ".$this->tableName().'.'.$va_rel['one_table_field']." = {$ps_additional_table_to_join}.".$va_rel['many_table_field'];
} else {
// TODO: handle many-many cases
}
// are there any SQL WHERE criteria for the additional table?
$va_additional_table_wheres = null;
if (isset($pa_options['additionalTableWheres']) && is_array($pa_options['additionalTableWheres'])) {
$va_additional_table_wheres = $pa_options['additionalTableWheres'];
}
$vs_additional_wheres = '';
if (is_array($va_additional_table_wheres) && (sizeof($va_additional_table_wheres) > 0)) {
$vs_additional_wheres = ' AND ('.join(' AND ', $va_additional_table_wheres).') ';
}
}
$vs_deleted_sql = '';
if ($this->hasField('deleted') && (!isset($pa_options['returnDeleted']) || (!$pa_options['returnDeleted']))) {
$vs_deleted_sql = " AND ({$vs_table_name}.deleted = 0)";
}
$vs_sql_joins = join("\n", $va_sql_joins);
$vs_sql = "
SELECT *
FROM {$vs_table_name}
{$vs_sql_joins}
WHERE
({$vs_table_name}.{$vs_hier_left_fld} BETWEEN ".$qr_root->get($vs_hier_left_fld)." AND ".$qr_root->get($vs_hier_right_fld).")
{$vs_hier_id_sql}
{$vs_deleted_sql}
{$vs_additional_wheres}
ORDER BY
{$vs_table_name}.{$vs_hier_left_fld}
";
//print $vs_sql;
$qr_hier = $o_db->query($vs_sql);
if ($o_db->numErrors()) {
$this->errors = array_merge($this->errors, $o_db->errors());
return null;
} else {
return $qr_hier;
}
} else {
return null;
}
}
} else {
return null;
}
}
# --------------------------------------------------------------------------------------------
/**
* Get the hierarchy in list form
*
* @param int $pn_id
* @param array $pa_options
*
* additionalTableToJoin: name of table to join to hierarchical table (and return fields from); only fields related many-to-one are currently supported
* idsOnly: if true, only the primary key id values of the chidlren records are returned
* returnDeleted = return deleted records in list (def. false)
* maxLevels =
* dontIncludeRoot =
*
* @return array
*/
public function &getHierarchyAsList($pn_id=null, $pa_options=null) {
$pb_ids_only = (isset($pa_options['idsOnly']) && $pa_options['idsOnly']) ? true : false;
$pn_max_levels = isset($pa_options['maxLevels']) ? intval($pa_options['maxLevels']) : null;
$ps_additional_table_to_join = isset($pa_options['additionalTableToJoin']) ? $pa_options['additionalTableToJoin'] : null;
$pb_dont_include_root = (isset($pa_options['dontIncludeRoot']) && $pa_options['dontIncludeRoot']) ? true : false;
if ($qr_hier = $this->getHierarchy($pn_id, $pa_options)) {
$vs_hier_right_fld = $this->getProperty("HIERARCHY_RIGHT_INDEX_FLD");
$va_indent_stack = array();
$va_hier = array();
$vn_cur_level = -1;
$va_omit_stack = array();
$vn_root_id = $pn_id;
while($qr_hier->nextRow()) {
$vn_row_id = $qr_hier->get($this->primaryKey());
if (is_null($vn_root_id)) { $vn_root_id = $vn_row_id; }
if ($pb_dont_include_root && ($vn_row_id == $vn_root_id)) { continue; } // skip root if desired
$vn_r = $qr_hier->get($vs_hier_right_fld);
$vn_c = sizeof($va_indent_stack);
if($vn_c > 0) {
while (($vn_c) && ($va_indent_stack[$vn_c - 1] <= $vn_r)){
array_pop($va_indent_stack);
$vn_c = sizeof($va_indent_stack);
}
}
if($vn_cur_level != sizeof($va_indent_stack)) {
if ($vn_cur_level > sizeof($va_indent_stack)) {
$va_omit_stack = array();
}
$vn_cur_level = intval(sizeof($va_indent_stack));
}
if (is_null($pn_max_levels) || ($vn_cur_level < $pn_max_levels)) {
$va_field_values = $qr_hier->getRow();
foreach($va_field_values as $vs_key => $vs_val) {
$va_field_values[$vs_key] = stripSlashes($vs_val);
}
if ($pb_ids_only) {
$va_hier[] = $vn_row_id;
} else {
$va_node = array(
"NODE" => $va_field_values,
"LEVEL" => $vn_cur_level
);
$va_hier[] = $va_node;
}
}
$va_indent_stack[] = $vn_r;
}
return $va_hier;
} else {
return null;
}
}
# --------------------------------------------------------------------------------------------
/**
* Returns a list of primary keys comprising all child rows
*
* @param int $pn_id node to start from - default is the hierarchy root
* @return array id list
*/
public function &getHierarchyIDs($pn_id=null, $pa_options=null) {
if ($qr_hier = $this->getHierarchy($pn_id, $pa_options)) {
$va_ids = array();
$vs_pk = $this->primaryKey();
while($qr_hier->nextRow()) {
$va_ids[] = $qr_hier->get($vs_pk);
}
return $va_ids;
} else {
return null;
}
}
# --------------------------------------------------------------------------------------------
/**
* Get *direct* child records for currently loaded record or one specified by $pn_id
* Note that this only returns direct children, *NOT* children of children and further descendents
* If you need to get a chunk of the hierarchy use getHierarchy()
*
* @access public
* @param int optional, primary key value of a record.
* Use this if you want to know the children of a record different than $this
* @param array, optional associative array of options. Valid keys for the array are:
* additionalTableToJoin: name of table to join to hierarchical table (and return fields from); only fields related many-to-one are currently supported
* returnChildCounts: if true, the number of children under each returned child is calculated and returned in the result set under the column name 'child_count'. Note that this count is always at least 1, even if there are no children. The 'has_children' column will be null if the row has, in fact no children, or non-null if it does have children. You should check 'has_children' before using 'child_count' and disregard 'child_count' if 'has_children' is null.
* returnDeleted = return deleted records in list (def. false)
* @return DbResult
*/
public function &getHierarchyChildrenAsQuery($pn_id=null, $pa_options=null) {
$o_db = $this->getDb();
$vs_table_name = $this->tableName();
// return counts of child records for each child found?
$pb_return_child_counts = isset($pa_options['returnChildCounts']) ? true : false;
$va_additional_table_wheres = array();
$va_additional_table_select_fields = array();
// additional table to join into query?
$ps_additional_table_to_join = isset($pa_options['additionalTableToJoin']) ? $pa_options['additionalTableToJoin'] : null;
if ($ps_additional_table_to_join) {
// what kind of join are we doing for the additional table? LEFT or INNER? (default=INNER)
$ps_additional_table_join_type = 'INNER';
if (isset($pa_options['additionalTableJoinType']) && ($pa_options['additionalTableJoinType'] === 'LEFT')) {
$ps_additional_table_join_type = 'LEFT';
}
// what fields from the additional table are we going to return?
if (isset($pa_options['additionalTableSelectFields']) && is_array($pa_options['additionalTableSelectFields'])) {
foreach($pa_options['additionalTableSelectFields'] as $vs_fld) {
$va_additional_table_select_fields[] = "{$ps_additional_table_to_join}.{$vs_fld}";
}
}
// are there any SQL WHERE criteria for the additional table?
if (isset($pa_options['additionalTableWheres']) && is_array($pa_options['additionalTableWheres'])) {
$va_additional_table_wheres = $pa_options['additionalTableWheres'];
}
}
if ($this->hasField('deleted') && (!isset($pa_options['returnDeleted']) || (!$pa_options['returnDeleted']))) {
$va_additional_table_wheres[] = "({$vs_table_name}.deleted = 0)";
}
if ($this->isHierarchical()) {
if (!$pn_id) {
if (!($pn_id = $this->getPrimaryKey())) {
return null;
}
}
$va_sql_joins = array();
$vs_additional_table_to_join_group_by = '';
if ($ps_additional_table_to_join){
if (is_array($va_rel = $this->getAppDatamodel()->getOneToManyRelations($this->tableName(), $ps_additional_table_to_join))) {
// one-many rel
$va_sql_joins[] = $ps_additional_table_join_type." JOIN {$ps_additional_table_to_join} ON ".$this->tableName().'.'.$va_rel['one_table_field']." = {$ps_additional_table_to_join}.".$va_rel['many_table_field'];
} else {
// TODO: handle many-many cases
}
$t_additional_table_to_join = $this->_DATAMODEL->getTableInstance($ps_additional_table_to_join);
$vs_additional_table_to_join_group_by = ', '.$ps_additional_table_to_join.'.'.$t_additional_table_to_join->primaryKey();
}
$vs_sql_joins = join("\n", $va_sql_joins);
$vs_hier_parent_id_fld = $this->getProperty("HIERARCHY_PARENT_ID_FLD");
if ($vs_rank_fld = $this->getProperty('RANK')) {
$vs_order_by = $this->tableName().'.'.$vs_rank_fld;
} else {
$vs_order_by = $this->tableName().".".$this->primaryKey();
}
if ($pb_return_child_counts) {
$qr_hier = $o_db->query("
SELECT ".$this->tableName().".* ".(sizeof($va_additional_table_select_fields) ? ', '.join(', ', $va_additional_table_select_fields) : '').", count(*) child_count, p2.".$this->primaryKey()." has_children
FROM ".$this->tableName()."
{$vs_sql_joins}
LEFT JOIN ".$this->tableName()." AS p2 ON p2.".$vs_hier_parent_id_fld." = ".$this->tableName().".".$this->primaryKey()."
WHERE
(".$this->tableName().".{$vs_hier_parent_id_fld} = ?) ".((sizeof($va_additional_table_wheres) > 0) ? ' AND '.join(' AND ', $va_additional_table_wheres) : '')."
GROUP BY
".$this->tableName().".".$this->primaryKey()." {$vs_additional_table_to_join_group_by}
ORDER BY
".$vs_order_by."
", $pn_id);
} else {
$qr_hier = $o_db->query("
SELECT ".$this->tableName().".* ".(sizeof($va_additional_table_select_fields) ? ', '.join(', ', $va_additional_table_select_fields) : '')."
FROM ".$this->tableName()."
{$vs_sql_joins}
WHERE
(".$this->tableName().".{$vs_hier_parent_id_fld} = ?) ".((sizeof($va_additional_table_wheres) > 0) ? ' AND '.join(' AND ', $va_additional_table_wheres) : '')."
ORDER BY
".$vs_order_by."
", $pn_id);
}
if ($o_db->numErrors()) {
$this->errors = array_merge($this->errors, $o_db->errors());
return null;
} else {
return $qr_hier;
}
} else {
return null;
}
}
# --------------------------------------------------------------------------------------------
/**
* Get *direct* child records for currently loaded record or one specified by $pn_id
* Note that this only returns direct children, *NOT* children of children and further descendents
* If you need to get a chunk of the hierarchy use getHierarchy().
*
* Results are returned as an array with either associative array values for each child record, or if the
* idsOnly option is set, then the primary key values.
*
* @access public
* @param int optional, primary key value of a record.
* Use this if you want to know the children of a record different than $this
* @param array, optional associative array of options. Valid keys for the array are:
* additionalTableToJoin: name of table to join to hierarchical table (and return fields from); only fields related many-to-one are currently supported
* returnChildCounts: if true, the number of children under each returned child is calculated and returned in the result set under the column name 'child_count'. Note that this count is always at least 1, even if there are no children. The 'has_children' column will be null if the row has, in fact no children, or non-null if it does have children. You should check 'has_children' before using 'child_count' and disregard 'child_count' if 'has_children' is null.
* idsOnly: if true, only the primary key id values of the chidlren records are returned
* returnDeleted = return deleted records in list (def. false)
* @return array
*/
public function getHierarchyChildren($pn_id=null, $pa_options=null) {
$pb_ids_only = (isset($pa_options['idsOnly']) && $pa_options['idsOnly']) ? true : false;
if (!$pn_id) { $pn_id = $this->getPrimaryKey(); }
if (!$pn_id) { return null; }
$qr_children = $this->getHierarchyChildrenAsQuery($pn_id, $pa_options);
$va_children = array();
$vs_pk = $this->primaryKey();
while($qr_children->nextRow()) {
if ($pb_ids_only) {
$va_row = $qr_children->getRow();
$va_children[] = $va_row[$vs_pk];
} else {
$va_children[] = $qr_children->getRow();
}
}
return $va_children;
}
# --------------------------------------------------------------------------------------------
/**
* Get "siblings" records - records with the same parent - as the currently loaded record
* or the record with its primary key = $pn_id
*
* Results are returned as an array with either associative array values for each sibling record, or if the
* idsOnly option is set, then the primary key values.
*
* @access public
* @param int optional, primary key value of a record.
* Use this if you want to know the siblings of a record different than $this
* @param array, optional associative array of options. Valid keys for the array are:
* additionalTableToJoin: name of table to join to hierarchical table (and return fields from); only fields related many-to-one are currently supported
* returnChildCounts: if true, the number of children under each returned sibling is calculated and returned in the result set under the column name 'sibling_count'.d
* idsOnly: if true, only the primary key id values of the chidlren records are returned
* returnDeleted = return deleted records in list (def. false)
* @return array
*/
public function &getHierarchySiblings($pn_id=null, $pa_options=null) {
$pb_ids_only = (isset($pa_options['idsOnly']) && $pa_options['idsOnly']) ? true : false;
if (!$pn_id) { $pn_id = $this->getPrimaryKey(); }
if (!$pn_id) { return null; }
$vs_table_name = $this->tableName();
$va_additional_table_wheres = array($this->primaryKey()." = ?");
if ($this->hasField('deleted') && (!isset($pa_options['returnDeleted']) || (!$pa_options['returnDeleted']))) {
$va_additional_table_wheres[] = "({$vs_table_name}.deleted = 0)";
}
// convert id into parent_id - get the children of the parent is equivalent to getting the siblings for the id
if ($qr_parent = $this->getDb()->query("
SELECT ".$this->getProperty('HIERARCHY_PARENT_ID_FLD')."
FROM ".$this->tableName()."
WHERE ".join(' AND ', $va_additional_table_wheres), (int)$pn_id)) {
if ($qr_parent->nextRow()) {
$pn_id = $qr_parent->get($this->getProperty('HIERARCHY_PARENT_ID_FLD'));
} else {
$this->postError(250, _t('Could not get parent_id to load siblings by: %1', join(';', $this->getDb()->getErrors())), 'BaseModel->getHierarchySiblings');
return false;
}
} else {
$this->postError(250, _t('Could not get hierarchy siblings: %1', join(';', $this->getDb()->getErrors())), 'BaseModel->getHierarchySiblings');
return false;
}
if (!$pn_id) { return array(); }
$qr_children = $this->getHierarchyChildrenAsQuery($pn_id, $pa_options);
$va_siblings = array();
$vs_pk = $this->primaryKey();
while($qr_children->nextRow()) {
if ($pb_ids_only) {
$va_row = $qr_children->getRow();
$va_siblings[] = $va_row[$vs_pk];
} else {
$va_siblings[] = $qr_children->getRow();
}
}
return $va_siblings;
}
# --------------------------------------------------------------------------------------------
/**
* Get hierarchy ancestors
*
* @access public
* @param int optional, primary key value of a record.
* Use this if you want to know the ancestors of a record different than $this
* @param array optional, options
* idsOnly = just return the ids of the ancestors (def. false)
* includeSelf = include this record (def. false)
* additionalTableToJoin = name of additonal table data to return
* returnDeleted = return deleted records in list (def. false)
* @return array
*/
public function &getHierarchyAncestors($pn_id=null, $pa_options=null) {
$pb_include_self = (isset($pa_options['includeSelf']) && $pa_options['includeSelf']) ? true : false;
$pb_ids_only = (isset($pa_options['idsOnly']) && $pa_options['idsOnly']) ? true : false;
$vs_table_name = $this->tableName();
$va_additional_table_select_fields = array();
$va_additional_table_wheres = array();
// additional table to join into query?
$ps_additional_table_to_join = isset($pa_options['additionalTableToJoin']) ? $pa_options['additionalTableToJoin'] : null;
if ($ps_additional_table_to_join) {
// what kind of join are we doing for the additional table? LEFT or INNER? (default=INNER)
$ps_additional_table_join_type = 'INNER';
if (isset($pa_options['additionalTableJoinType']) && ($pa_options['additionalTableJoinType'] === 'LEFT')) {
$ps_additional_table_join_type = 'LEFT';
}
// what fields from the additional table are we going to return?
if (isset($pa_options['additionalTableSelectFields']) && is_array($pa_options['additionalTableSelectFields'])) {
foreach($pa_options['additionalTableSelectFields'] as $vs_fld) {
$va_additional_table_select_fields[] = "{$ps_additional_table_to_join}.{$vs_fld}";
}
}
// are there any SQL WHERE criteria for the additional table?
if (isset($pa_options['additionalTableWheres']) && is_array($pa_options['additionalTableWheres'])) {
$va_additional_table_wheres = $pa_options['additionalTableWheres'];
}
}
if ($this->hasField('deleted') && (!isset($pa_options['returnDeleted']) || (!$pa_options['returnDeleted']))) {
$va_additional_table_wheres[] = "({$vs_table_name}.deleted = 0)";
}
if ($this->isHierarchical()) {
if (!$pn_id) {
if (!($pn_id = $this->getPrimaryKey())) {
return null;
}
}
$vs_hier_left_fld = $this->getProperty("HIERARCHY_LEFT_INDEX_FLD");
$vs_hier_right_fld = $this->getProperty("HIERARCHY_RIGHT_INDEX_FLD");
$vs_hier_id_fld = $this->getProperty("HIERARCHY_ID_FLD");
$vs_hier_id_table = $this->getProperty("HIERARCHY_DEFINITION_TABLE");
$vs_hier_parent_id_fld = $this->getProperty("HIERARCHY_PARENT_ID_FLD");
$va_sql_joins = array();
if ($ps_additional_table_to_join){
$va_path = $this->getAppDatamodel()->getPath($vs_table_name, $ps_additional_table_to_join);
switch(sizeof($va_path)) {
case 2:
$va_rels = $this->getAppDatamodel()->getRelationships($vs_table_name, $ps_additional_table_to_join);
$va_sql_joins[] = $ps_additional_table_join_type." JOIN {$ps_additional_table_to_join} ON ".$vs_table_name.'.'.$va_rels[$ps_additional_table_to_join][$vs_table_name][0][1]." = {$ps_additional_table_to_join}.".$va_rels[$ps_additional_table_to_join][$vs_table_name][0][0];
break;
case 3:
// TODO: handle many-many cases
break;
}
}
$vs_sql_joins = join("\n", $va_sql_joins);
$o_db = $this->getDb();
$qr_root = $o_db->query("
SELECT {$vs_table_name}.* ".(sizeof($va_additional_table_select_fields) ? ', '.join(', ', $va_additional_table_select_fields) : '')."
FROM {$vs_table_name}
{$vs_sql_joins}
WHERE
({$vs_table_name}.".$this->primaryKey()." = ?) ".((sizeof($va_additional_table_wheres) > 0) ? ' AND '.join(' AND ', $va_additional_table_wheres) : '')."
", intval($pn_id));
if ($o_db->numErrors()) {
$this->errors = array_merge($this->errors, $o_db->errors());
return null;
} else {
if ($qr_root->numRows()) {
$va_ancestors = array();
$vn_parent_id = null;
$vn_level = 0;
if ($pb_include_self) {
while ($qr_root->nextRow()) {
if (!$vn_parent_id) { $vn_parent_id = $qr_root->get($vs_hier_parent_id_fld); }
if ($pb_ids_only) {
$va_ancestors[] = $qr_root->get($this->primaryKey());
} else {
$va_ancestors[] = array(
"NODE" => $qr_root->getRow(),
"LEVEL" => $vn_level
);
}
$vn_level++;
}
} else {
$qr_root->nextRow();
$vn_parent_id = $qr_root->get($vs_hier_parent_id_fld);
}
if($vn_parent_id) {
do {
$vs_sql = "
SELECT {$vs_table_name}.* ".(sizeof($va_additional_table_select_fields) ? ', '.join(', ', $va_additional_table_select_fields) : '')."
FROM {$vs_table_name}
{$vs_sql_joins}
WHERE ({$vs_table_name}.".$this->primaryKey()." = ?) ".((sizeof($va_additional_table_wheres) > 0) ? ' AND '.join(' AND ', $va_additional_table_wheres) : '')."
";
$qr_hier = $o_db->query($vs_sql, $vn_parent_id);
$vn_parent_id = null;
while ($qr_hier->nextRow()) {
if (!$vn_parent_id) { $vn_parent_id = $qr_hier->get($vs_hier_parent_id_fld); }
if ($pb_ids_only) {
$va_ancestors[] = $qr_hier->get($this->primaryKey());
} else {
$va_ancestors[] = array(
"NODE" => $qr_hier->getRow(),
"LEVEL" => $vn_level
);
}
}
$vn_level++;
} while($vn_parent_id);
return $va_ancestors;
} else {
return $va_ancestors;
}
} else {
return null;
}
}
} else {
return null;
}
}
# --------------------------------------------------------------------------------------------
public function rebuildAllHierarchicalIndexes() {
$vs_hier_left_fld = $this->getProperty("HIERARCHY_LEFT_INDEX_FLD");
$vs_hier_right_fld = $this->getProperty("HIERARCHY_RIGHT_INDEX_FLD");
$vs_hier_id_fld = $this->getProperty("HIERARCHY_ID_FLD");
$vs_hier_id_table = $this->getProperty("HIERARCHY_DEFINITION_TABLE");
$vs_hier_parent_id_fld = $this->getProperty("HIERARCHY_PARENT_ID_FLD");
if (!$vs_hier_id_fld) { return false; }
$o_db = $this->getDb();
$qr_hier_ids = $o_db->query("
SELECT DISTINCT ".$vs_hier_id_fld."
FROM ".$this->tableName()."
");
while($qr_hier_ids->nextRow()) {
$this->rebuildHierarchicalIndex($qr_hier_ids->get($vs_hier_id_fld));
}
return true;
}
# --------------------------------------------------------------------------------------------
public function rebuildHierarchicalIndex($pn_hierarchy_id=null) {
if ($this->isHierarchical()) {
$vb_we_set_transaction = false;
if (!$this->inTransaction()) {
$this->setTransaction(new Transaction($this->getDb()));
$vb_we_set_transaction = true;
}
if ($vn_root_id = $this->getHierarchyRootID($pn_hierarchy_id)) {
$this->_rebuildHierarchicalIndex($vn_root_id, 1);
if ($vb_we_set_transaction) { $this->removeTransaction(true);}
return true;
} else {
if ($vb_we_set_transaction) { $this->removeTransaction(false);}
return null;
}
} else {
return null;
}
}
# --------------------------------------------------------------------------------------------
private function _rebuildHierarchicalIndex($pn_parent_id, $pn_hier_left) {
$vs_hier_parent_id_fld = $this->getProperty("HIERARCHY_PARENT_ID_FLD");
$vs_hier_left_fld = $this->getProperty("HIERARCHY_LEFT_INDEX_FLD");
$vs_hier_right_fld = $this->getProperty("HIERARCHY_RIGHT_INDEX_FLD");
$vs_hier_id_fld = $this->getProperty("HIERARCHY_ID_FLD");
$vs_hier_id_table = $this->getProperty("HIERARCHY_DEFINITION_TABLE");
$vn_hier_right = $pn_hier_left + 100;
$vs_pk = $this->primaryKey();
$o_db = $this->getDb();
if (is_null($pn_parent_id)) {
$vs_sql = "
SELECT *
FROM ".$this->tableName()."
WHERE
(".$vs_hier_parent_id_fld." IS NULL)
";
} else {
$vs_sql = "
SELECT *
FROM ".$this->tableName()."
WHERE
(".$vs_hier_parent_id_fld." = ".intval($pn_parent_id).")
";
}
$qr_level = $o_db->query($vs_sql);
if ($o_db->numErrors()) {
$this->errors = array_merge($this->errors, $o_db->errors());
return null;
} else {
while($qr_level->nextRow()) {
$vn_hier_right = $this->_rebuildHierarchicalIndex($qr_level->get($vs_pk), $vn_hier_right);
}
$qr_up = $o_db->query("
UPDATE ".$this->tableName()."
SET ".$vs_hier_left_fld." = ".intval($pn_hier_left).", ".$vs_hier_right_fld." = ".intval($vn_hier_right)."
WHERE
(".$vs_pk." = ?)
", intval($pn_parent_id));
if ($o_db->numErrors()) {
$this->errors = array_merge($this->errors, $o_db->errors());
return null;
} else {
return $vn_hier_right + 100;
}
}
}
# --------------------------------------------------------------------------------------------
/**
* HTML Form element generation
* Optional name parameter allows you to generate a form element for a field but give it a
* name different from the field name
*
* @param string $ps_field field name
* @param string $ps_format field format
* @param array $pa_options additional options
* TODO: document them.
*/
public function htmlFormElement($ps_field, $ps_format=null, $pa_options=null) {
$o_db = $this->getDb();
// init options
if (!is_array($pa_options)) {
$pa_options = array();
}
foreach (array(
'display_form_field_tips', 'classname', 'maxOptionLength', 'textAreaTagName', 'display_use_count',
'display_omit_items__with_zero_count', 'display_use_count_filters', 'display_use_count_filters',
'selection', 'name', 'value', 'dont_show_null_value', 'size', 'multiple', 'show_text_field_for_vars',
'nullOption', 'empty_message', 'displayMessageForFieldValues', 'DISPLAY_FIELD', 'WHERE',
'select_item_text', 'hide_select_if_only_one_option', 'field_errors', 'display_form_field_tips', 'form_name',
'no_tooltips', 'tooltip_namespace', 'extraLabelText', 'width', 'height', 'label', 'list_code', 'hide_select_if_no_options', 'id',
'lookup_url', 'progress_indicator', 'error_icon', 'maxPixelWidth', 'displayMediaVersion', 'FIELD_TYPE', 'DISPLAY_TYPE', 'choiceList',
'readonly'
)
as $vs_key) {
if(!isset($pa_options[$vs_key])) { $pa_options[$vs_key] = null; }
}
$va_attr = $this->getFieldInfo($ps_field);
foreach (array(
'DISPLAY_WIDTH', 'DISPLAY_USE_COUNT', 'DISPLAY_SHOW_COUNT', 'DISPLAY_OMIT_ITEMS_WITH_ZERO_COUNT',
'DISPLAY_TYPE', 'IS_NULL', 'DEFAULT_ON_NULL', 'DEFAULT', 'LIST_MULTIPLE_DELIMITER', 'FIELD_TYPE',
'LIST_CODE', 'DISPLAY_FIELD', 'WHERE', 'DISPLAY_WHERE', 'DISPLAY_ORDERBY', 'LIST',
'BOUNDS_CHOICE_LIST', 'BOUNDS_LENGTH', 'DISPLAY_DESCRIPTION', 'LABEL', 'DESCRIPTION',
'SUB_LABEL', 'SUB_DESCRIPTION', 'MAX_PIXEL_WIDTH'
)
as $vs_key) {
if(!isset($va_attr[$vs_key])) { $va_attr[$vs_key] = null; }
}
if (isset($pa_options['FIELD_TYPE'])) {
$va_attr['FIELD_TYPE'] = $pa_options['FIELD_TYPE'];
}
if (isset($pa_options['DISPLAY_TYPE'])) {
$va_attr['DISPLAY_TYPE'] = $pa_options['DISPLAY_TYPE'];
}
$vn_display_width = (isset($pa_options['width']) && ($pa_options['width'] > 0)) ? $pa_options['width'] : $va_attr["DISPLAY_WIDTH"];
$vn_display_height = (isset($pa_options['height']) && ($pa_options['height'] > 0)) ? $pa_options['height'] : $va_attr["DISPLAY_HEIGHT"];
$va_parsed_width = caParseFormElementDimension($vn_display_width);
$va_parsed_height = caParseFormElementDimension($vn_display_height);
$va_dim_styles = array();
if ($va_parsed_width['type'] == 'pixels') {
$va_dim_styles[] = "width: ".$va_parsed_width['dimension']."px;";
}
if ($va_parsed_height['type'] == 'pixels') {
$va_dim_styles[] = "height: ".$va_parsed_height['dimension']."px;";
}
if ($vn_max_pixel_width) {
$va_dim_styles[] = "max-width: {$vn_max_pixel_width}px;";
}
$vs_dim_style = trim(join(" ", $va_dim_styles));
$vs_field_label = (isset($pa_options['label']) && (strlen($pa_options['label']) > 0)) ? $pa_options['label'] : $va_attr["LABEL"];
$vs_errors = '';
// TODO: PULL THIS FROM A CONFIG FILE
$pa_options["display_form_field_tips"] = true;
if (isset($pa_options['classname'])) {
$vs_css_class_attr = ' class="'.$pa_options['classname'].'" ';
} else {
$vs_css_class_attr = '';
}
if (!isset($pa_options['id'])) { $pa_options['id'] = $pa_options['name']; }
if (!isset($pa_options['id'])) { $pa_options['id'] = $ps_field; }
if (!isset($pa_options['maxPixelWidth']) || ((int)$pa_options['maxPixelWidth'] <= 0)) { $vn_max_pixel_width = $va_attr['MAX_PIXEL_WIDTH']; } else { $vn_max_pixel_width = (int)$pa_options['maxPixelWidth']; }
if ($vn_max_pixel_width <= 0) { $vn_max_pixel_width = null; }
if (!isset($pa_options["maxOptionLength"]) && isset($vn_display_width)) {
$pa_options["maxOptionLength"] = isset($vn_display_width) ? $vn_display_width : null;
}
$vs_text_area_tag_name = 'textarea';
if (isset($pa_options["textAreaTagName"]) && $pa_options['textAreaTagName']) {
$vs_text_area_tag_name = isset($pa_options['textAreaTagName']) ? $pa_options['textAreaTagName'] : null;
}
if (!isset($va_attr["DISPLAY_USE_COUNT"]) || !($vs_display_use_count = $va_attr["DISPLAY_USE_COUNT"])) {
$vs_display_use_count = isset($pa_options["display_use_count"]) ? $pa_options["display_use_count"] : null;
}
if (!isset($va_attr["DISPLAY_SHOW_COUNT"]) || !($vb_display_show_count = (boolean)$va_attr["DISPLAY_SHOW_COUNT"])) {
$vb_display_show_count = isset($pa_options["display_show_count"]) ? (boolean)$pa_options["display_show_count"] : null;
}
if (!isset($va_attr["DISPLAY_OMIT_ITEMS_WITH_ZERO_COUNT"]) || !($vb_display_omit_items__with_zero_count = (boolean)$va_attr["DISPLAY_OMIT_ITEMS_WITH_ZERO_COUNT"])) {
$vb_display_omit_items__with_zero_count = isset($pa_options["display_omit_items__with_zero_count"]) ? (boolean)$pa_options["display_omit_items__with_zero_count"] : null;
}
if (!isset($va_attr["DISPLAY_OMIT_ITEMS_WITH_ZERO_COUNT"]) || !($va_display_use_count_filters = $va_attr["DISPLAY_USE_COUNT_FILTERS"])) {
$va_display_use_count_filters = isset($pa_options["display_use_count_filters"]) ? $pa_options["display_use_count_filters"] : null;
}
if (!isset($va_display_use_count_filters) || !is_array($va_display_use_count_filters)) { $va_display_use_count_filters = null; }
if (isset($pa_options["selection"]) && is_array($pa_options["selection"])) {
$va_selection = isset($pa_options["selection"]) ? $pa_options["selection"] : null;
} else {
$va_selection = array();
}
if (isset($pa_options["choiceList"]) && is_array($pa_options["choiceList"])) {
$va_attr["BOUNDS_CHOICE_LIST"] = $pa_options["choiceList"];
}
$vs_element = $vs_subelement = "";
if ($va_attr) {
# --- Skip omitted fields completely
if ($va_attr["DISPLAY_TYPE"] == DT_OMIT) {
return "";
}
if (!isset($pa_options["name"]) || !$pa_options["name"]) {
$pa_options["name"] = htmlspecialchars($ps_field, ENT_QUOTES, 'UTF-8');
}
$va_js = array();
$va_handlers = array("onclick", "onchange", "onkeypress", "onkeydown", "onkeyup");
foreach($va_handlers as $vs_handler) {
if (isset($pa_options[$vs_handler]) && $pa_options[$vs_handler]) {
$va_js[] = "$vs_handler='".($pa_options[$vs_handler])."'";
}
}
$vs_js = join(" ", $va_js);
if (!isset($pa_options["value"])) { // allow field value to be overriden with value from options array
$vm_field_value = $this->get($ps_field, $pa_options);
} else {
$vm_field_value = $pa_options["value"];
}
$vm_raw_field_value = $vm_field_value;
$vb_is_null = isset($va_attr["IS_NULL"]) ? $va_attr["IS_NULL"] : false;
if (isset($pa_options['dont_show_null_value']) && $pa_options['dont_show_null_value']) { $vb_is_null = false; }
if (
(!is_array($vm_field_value) && (strlen($vm_field_value) == 0)) &&
(
(!isset($vb_is_null) || (!$vb_is_null)) ||
((isset($va_attr["DEFAULT_ON_NULL"]) ? $va_attr["DEFAULT_ON_NULL"] : 0))
)
) {
$vm_field_value = isset($va_attr["DEFAULT"]) ? $va_attr["DEFAULT"] : "";
}
# --- Return hidden fields
if ($va_attr["DISPLAY_TYPE"] == DT_HIDDEN) {
return '<input type="hidden" name="'.$pa_options["name"].'" value="'.$this->escapeHTML($vm_field_value).'"/>';
}
if (isset($pa_options["size"]) && ($pa_options["size"] > 0)) {
$ps_size = " size='".$pa_options["size"]."'";
} else{
if ((($va_attr["DISPLAY_TYPE"] == DT_LIST_MULTIPLE) || ($va_attr["DISPLAY_TYPE"] == DT_LIST)) && ($vn_display_height > 1)) {
$ps_size = " size='".$vn_display_height."'";
} else {
$ps_size = '';
}
}
$vs_multiple_name_extension = '';
if ($vs_is_multiple = ((isset($pa_options["multiple"]) && $pa_options["multiple"]) || ($va_attr["DISPLAY_TYPE"] == DT_LIST_MULTIPLE) ? "multiple='1'" : "")) {
$vs_multiple_name_extension = '[]';
if (!($vs_list_multiple_delimiter = $va_attr['LIST_MULTIPLE_DELIMITER'])) { $vs_list_multiple_delimiter = ';'; }
$va_selection = array_merge($va_selection, explode($vs_list_multiple_delimiter, $vm_field_value));
}
# --- Return form element
switch($va_attr["FIELD_TYPE"]) {
# ----------------------------
case(FT_NUMBER):
case(FT_TEXT):
case(FT_VARS):
if ($va_attr["FIELD_TYPE"] == FT_VARS) {
if (!$pa_options['show_text_field_for_vars']) {
break;
}
if (!is_string($vm_field_value) && !is_numeric($vm_field_value)) { $vm_value = ''; }
}
if ($va_attr['DISPLAY_TYPE'] == DT_COUNTRY_LIST) {
$vs_element = caHTMLSelect($ps_field, caGetCountryList(), array('id' => $ps_field), array('value' => $vm_field_value));
if ($va_attr['STATEPROV_FIELD']) {
$vs_element .="<script type='text/javascript'>\n";
$vs_element .= "var caStatesByCountryList = ".json_encode(caGetStateList()).";\n";
$vs_element .= "
jQuery('#{$ps_field}').click({countryID: '{$ps_field}', stateProvID: '".$va_attr['STATEPROV_FIELD']."', value: '".addslashes($this->get($va_attr['STATEPROV_FIELD']))."', statesByCountryList: caStatesByCountryList}, caUI.utils.updateStateProvinceForCountry);
jQuery(document).ready(function() {
caUI.utils.updateStateProvinceForCountry({data: {countryID: '{$ps_field}', stateProvID: '".$va_attr['STATEPROV_FIELD']."', value: '".addslashes($this->get($va_attr['STATEPROV_FIELD']))."', statesByCountryList: caStatesByCountryList}});
});
";
$vs_element .="</script>\n";
}
break;
}
if ($va_attr['DISPLAY_TYPE'] == DT_STATEPROV_LIST) {
$vs_element = caHTMLSelect($ps_field.'_select', array(), array('id' => $ps_field.'_select'), array('value' => $vm_field_value));
$vs_element .= caHTMLTextInput($ps_field.'_name', array('id' => $ps_field.'_text', 'value' => $vm_field_value));
break;
}
if (($vn_display_width > 0) && (in_array($va_attr["DISPLAY_TYPE"], array(DT_SELECT, DT_LIST, DT_LIST_MULTIPLE)))) {
#
# Generate auto generated <select> (from foreign key, from ca_lists or from field-defined choice list)
#
# TODO: CLEAN UP THIS CODE, RUNNING VARIOUS STAGES THROUGH HELPER FUNCTIONS; ALSO FORMALIZE AND DOCUMENT VARIOUS OPTIONS
// -----
// from ca_lists
// -----
if(!($vs_list_code = $pa_options['list_code'])) {
if(isset($va_attr['LIST_CODE']) && $va_attr['LIST_CODE']) {
$vs_list_code = $va_attr['LIST_CODE'];
}
}
if ($vs_list_code) {
$va_many_to_one_relations = $this->_DATAMODEL->getManyToOneRelations($this->tableName());
if ($va_many_to_one_relations[$ps_field]) {
$vs_key = 'item_id';
} else {
$vs_key = 'item_value';
}
$vs_null_option = null;
if (!$pa_options["nullOption"] && $vb_is_null) {
$vs_null_option = "- NONE -";
} else {
if ($pa_options["nullOption"]) {
$vs_null_option = $pa_options["nullOption"];
}
}
$t_list = new ca_lists();
$va_list_attrs = array( 'id' => $pa_options['id']);
if ($vn_max_pixel_width) { $va_list_attrs['style'] = $vs_width_style; }
// NOTE: "raw" field value (value passed into method, before the model default value is applied) is used so as to allow the list default to be used if needed
$vs_element = $t_list->getListAsHTMLFormElement($vs_list_code, $pa_options["name"].$vs_multiple_name_extension, $va_list_attrs, array('value' => $vm_raw_field_value, 'key' => $vs_key, 'nullOption' => $vs_null_option, 'readonly' => $pa_options['readonly']));
if (isset($pa_options['hide_select_if_no_options']) && $pa_options['hide_select_if_no_options'] && (!$vs_element)) {
$vs_element = "";
$ps_format = '^ERRORS^ELEMENT';
}
} else {
// -----
// from related table
// -----
$va_many_to_one_relations = $this->_DATAMODEL->getManyToOneRelations($this->tableName());
if (isset($va_many_to_one_relations[$ps_field]) && $va_many_to_one_relations[$ps_field]) {
#
# Use foreign key to populate <select>
#
$o_one_table = $this->_DATAMODEL->getTableInstance($va_many_to_one_relations[$ps_field]["one_table"]);
$vs_one_table_primary_key = $o_one_table->primaryKey();
if ($o_one_table->isHierarchical()) {
#
# Hierarchical <select>
#
$va_hier = $o_one_table->getHierarchyAsList(0, $vs_display_use_count, $va_display_use_count_filters, $vb_display_omit_items__with_zero_count);
$va_display_fields = $va_attr["DISPLAY_FIELD"];
if (!in_array($vs_one_table_primary_key, $va_display_fields)) {
$va_display_fields[] = $o_one_table->tableName().".".$vs_one_table_primary_key;
}
if (!is_array($va_display_fields) || sizeof($va_display_fields) < 1) {
$va_display_fields = array("*");
}
$vs_hier_parent_id_fld = $o_one_table->getProperty("HIER_PARENT_ID_FLD");
$va_options = array();
if ($pa_options["nullOption"]) {
$va_options[""] = array($pa_options["nullOption"]);
}
$va_suboptions = array();
$va_suboption_values = array();
$vn_selected = 0;
$vm_cur_top_level_val = null;
$vm_selected_top_level_val = null;
foreach($va_hier as $va_option) {
if (!$va_option["NODE"][$vs_hier_parent_id_fld]) { continue; }
$vn_val = $va_option["NODE"][$o_one_table->primaryKey()];
$vs_selected = ($vn_val == $vm_field_value) ? 'selected="1"' : "";
$vn_indent = $va_option["LEVEL"] - 1;
$va_display_data = array();
foreach ($va_display_fields as $vs_fld) {
$va_bits = explode(".", $vs_fld);
if ($va_bits[1] != $vs_one_table_primary_key) {
$va_display_data[] = $va_option["NODE"][$va_bits[1]];
}
}
$vs_option_label = join(" ", $va_display_data);
$va_options[$vn_val] = array($vs_option_label, $vn_indent, $va_option["HITS"], $va_option['NODE']);
}
if (sizeof($va_options) == 0) {
$vs_element = isset($pa_options['empty_message']) ? $pa_options['empty_message'] : 'No options available';
} else {
$vs_element = "<select name='".$pa_options["name"].$vs_multiple_name_extension."' ".$vs_js." ".$vs_is_multiple." ".$ps_size." id='".$pa_options["id"].$vs_multiple_name_extension."' {$vs_css_class_attr} style='{$vs_dim_style}'".($pa_options['readonly'] ? ' disabled="disabled" ' : '').">\n";
if (!$pa_options["nullOption"] && $vb_is_null) {
$vs_element .= "<option value=''>- NONE -</option>\n";
} else {
if ($pa_options["nullOption"]) {
$vs_element .= "<option value=''>".$pa_options["nullOption"]."</option>\n";
}
}
foreach($va_options as $vn_val => $va_option_info) {
$vs_selected = (($vn_val == $vm_field_value) || in_array($vn_val, $va_selection)) ? "selected='selected'" : "";
$vs_element .= "<option value='".$vn_val."' $vs_selected>";
$vn_indent = ($va_option_info[1]) * 2;
$vs_indent = "";
if ($vn_indent > 0) {
$vs_indent = str_repeat(" ", ($vn_indent - 1) * 2)." ";
$vn_indent++;
}
$vs_option_text = $va_option_info[0];
$vs_use_count = "";
if($vs_display_use_count && $vb_display_show_count&& ($vn_val != "")) {
$vs_use_count = " (".intval($va_option_info[2]).")";
}
$vs_display_message = '';
if (is_array($pa_options['displayMessageForFieldValues'])) {
foreach($pa_options['displayMessageForFieldValues'] as $vs_df => $va_df_vals) {
if ((isset($va_option_info[3][$vs_df])) && is_array($va_df_vals)) {
$vs_tmp = $va_option_info[3][$vs_df];
if (isset($va_df_vals[$vs_tmp])) {
$vs_display_message = ' '.$va_df_vals[$vs_tmp];
}
}
}
}
if (
($pa_options["maxOptionLength"]) &&
(strlen($vs_option_text) + strlen($vs_use_count) + $vn_indent > $pa_options["maxOptionLength"])
) {
if (($vn_strlen = $pa_options["maxOptionLength"] - strlen($vs_indent) - strlen($vs_use_count) - 3) < $pa_options["maxOptionLength"]) {
$vn_strlen = $pa_options["maxOptionLength"];
}
$vs_option_text = unicode_substr($vs_option_text, 0, $vn_strlen)."...";
}
$vs_element .= $vs_indent.$vs_option_text.$vs_use_count.$vs_display_message."</option>\n";
}
$vs_element .= "</select>\n";
}
} else {
#
# "Flat" <select>
#
if (!is_array($va_display_fields = $pa_options["DISPLAY_FIELD"])) { $va_display_fields = $va_attr["DISPLAY_FIELD"]; }
if (!is_array($va_display_fields)) {
return "Configuration error: DISPLAY_FIELD directive for field '$ps_field' must be an array of field names in the format tablename.fieldname";
}
if (!in_array($vs_one_table_primary_key, $va_display_fields)) {
$va_display_fields[] = $o_one_table->tableName().".".$vs_one_table_primary_key;
}
if (!is_array($va_display_fields) || sizeof($va_display_fields) < 1) {
$va_display_fields = array("*");
}
$vs_sql = "
SELECT *
FROM ".$va_many_to_one_relations[$ps_field]["one_table"]."
";
if (isset($pa_options["WHERE"]) && (is_array($pa_options["WHERE"]) && ($vs_where = join(" AND ",$pa_options["WHERE"]))) || ((is_array($va_attr["DISPLAY_WHERE"])) && ($vs_where = join(" AND ",$va_attr["DISPLAY_WHERE"])))) {
$vs_sql .= " WHERE $vs_where ";
}
if ((isset($va_attr["DISPLAY_ORDERBY"])) && ($va_attr["DISPLAY_ORDERBY"]) && ($vs_orderby = join(",",$va_attr["DISPLAY_ORDERBY"]))) {
$vs_sql .= " ORDER BY $vs_orderby ";
}
$qr_res = $o_db->query($vs_sql);
if ($o_db->numErrors()) {
$vs_element = "Error creating menu: ".join(';', $o_db->getErrors());
break;
}
$va_opts = array();
if (isset($pa_options["nullOption"]) && $pa_options["nullOption"]) {
$va_opts[$pa_options["nullOption"]] = array($pa_options["nullOption"], null);
} else {
if ($vb_is_null) {
$va_opts["- NONE -"] = array("- NONE -", null);
}
}
if ($pa_options["select_item_text"]) {
$va_opts[$pa_options["select_item_text"]] = array($pa_options["select_item_text"], null);
}
$va_fields = array();
foreach($va_display_fields as $vs_field) {
$va_tmp = explode(".", $vs_field);
$va_fields[] = $va_tmp[1];
}
while ($qr_res->nextRow()) {
$vs_display = "";
foreach($va_fields as $vs_field) {
if ($vs_field != $vs_one_table_primary_key) {
$vs_display .= $qr_res->get($vs_field). " ";
}
}
$va_opts[] = array($vs_display, $qr_res->get($vs_one_table_primary_key), $qr_res->getRow());
}
if (sizeof($va_opts) == 0) {
$vs_element = isset($pa_options['empty_message']) ? $pa_options['empty_message'] : 'No options available';
} else {
if (isset($pa_options['hide_select_if_only_one_option']) && $pa_options['hide_select_if_only_one_option'] && (sizeof($va_opts) == 1)) {
$vs_element = "<input type='hidden' name='".$pa_options["name"]."' ".$vs_js." ".$ps_size." id='".$pa_options["id"]."' value='".($vm_field_value ? $vm_field_value : $va_opts[0][1])."' {$vs_css_class_attr}/>";
$ps_format = '^ERRORS^ELEMENT';
} else {
$vs_element = "<select name='".$pa_options["name"].$vs_multiple_name_extension."' ".$vs_js." ".$vs_is_multiple." ".$ps_size." id='".$pa_options["id"].$vs_multiple_name_extension."' {$vs_css_class_attr} style='{$vs_dim_style}'".($pa_options['readonly'] ? ' disabled="disabled" ' : '').">\n";
foreach ($va_opts as $va_opt) {
$vs_option_text = $va_opt[0];
$vs_value = $va_opt[1];
$vs_selected = (($vs_value == $vm_field_value) || in_array($vs_value, $va_selection)) ? "selected='selected'" : "";
$vs_use_count = "";
if ($vs_display_use_count && $vb_display_show_count && ($vs_value != "")) {
$vs_use_count = "(".intval($va_option_info[2]).")";
}
if (
($pa_options["maxOptionLength"]) &&
(strlen($vs_option_text) + strlen($vs_use_count) > $pa_options["maxOptionLength"])
) {
$vs_option_text = unicode_substr($vs_option_text,0, $pa_options["maxOptionLength"] - 3 - strlen($vs_use_count))."...";
}
$vs_display_message = '';
if (is_array($pa_options['displayMessageForFieldValues'])) {
foreach($pa_options['displayMessageForFieldValues'] as $vs_df => $va_df_vals) {
if ((isset($va_opt[2][$vs_df])) && is_array($va_df_vals)) {
$vs_tmp = $va_opt[2][$vs_df];
if (isset($va_df_vals[$vs_tmp])) {
$vs_display_message = ' '.$va_df_vals[$vs_tmp];
}
}
}
}
$vs_element.= "<option value='$vs_value' $vs_selected>";
$vs_element .= $vs_option_text.$vs_use_count.$vs_display_message;
$vs_element .= "</option>\n";
}
$vs_element .= "</select>\n";
}
}
}
} else {
#
# choice list
#
$vs_element = '';
// if 'LIST' is set try to stock over choice list with the contents of the list
if (isset($va_attr['LIST']) && $va_attr['LIST']) {
// NOTE: "raw" field value (value passed into method, before the model default value is applied) is used so as to allow the list default to be used if needed
$vs_element = ca_lists::getListAsHTMLFormElement($va_attr['LIST'], $pa_options["name"].$vs_multiple_name_extension, array('class' => $pa_options['classname'], 'id' => $pa_options['id']), array('key' => 'item_value', 'value' => $vm_raw_field_value, 'nullOption' => $pa_options['nullOption'], 'readonly' => $pa_options['readonly']));
}
if (!$vs_element && (isset($va_attr["BOUNDS_CHOICE_LIST"]) && is_array($va_attr["BOUNDS_CHOICE_LIST"]))) {
if (sizeof($va_attr["BOUNDS_CHOICE_LIST"]) == 0) {
$vs_element = isset($pa_options['empty_message']) ? $pa_options['empty_message'] : 'No options available';
} else {
$vs_element = "<select name='".$pa_options["name"].$vs_multiple_name_extension."' ".$vs_js." ".$vs_is_multiple." ".$ps_size." id='".$pa_options['id'].$vs_multiple_name_extension."' {$vs_css_class_attr} style='{$vs_dim_style}'".($pa_options['readonly'] ? ' disabled="disabled" ' : '').">\n";
if ($pa_options["select_item_text"]) {
$vs_element.= "<option value=''>".$this->escapeHTML($pa_options["select_item_text"])."</option>\n";
}
if (!$pa_options["nullOption"] && $vb_is_null) {
$vs_element .= "<option value=''>- NONE -</option>\n";
} else {
if ($pa_options["nullOption"]) {
$vs_element .= "<option value=''>".$pa_options["nullOption"]."</option>\n";
}
}
foreach($va_attr["BOUNDS_CHOICE_LIST"] as $vs_option => $vs_value) {
$vs_selected = ((strval($vs_value) === strval($vm_field_value)) || in_array($vs_value, $va_selection)) ? "selected='selected'" : "";
if (($pa_options["maxOptionLength"]) && (strlen($vs_option) > $pa_options["maxOptionLength"])) {
$vs_option = unicode_substr($vs_option, 0, $pa_options["maxOptionLength"] - 3)."...";
}
$vs_element.= "<option value='$vs_value' $vs_selected>".$this->escapeHTML($vs_option)."</option>\n";
}
$vs_element .= "</select>\n";
}
}
}
}
} else {
if ($va_attr["DISPLAY_TYPE"] === DT_COLORPICKER) { // COLORPICKER
$vs_element = '<input name="'.$pa_options["name"].'" type="hidden" size="'.($pa_options['size'] ? $pa_options['size'] : $vn_display_width).'" value="'.$this->escapeHTML($vm_field_value).'" '.$vs_js.' id=\''.$pa_options["id"]."' style='{$vs_dim_style}'/>\n";
$vs_element .= '<div id="'.$pa_options["id"].'_colorchip" class="colorpicker_chip" style="background-color: #'.$vm_field_value.'"><!-- empty --></div>';
$vs_element .= "<script type='text/javascript'>jQuery(document).ready(function() { jQuery('#".$pa_options["name"]."_colorchip').ColorPicker({
onShow: function (colpkr) {
jQuery(colpkr).fadeIn(500);
return false;
},
onHide: function (colpkr) {
jQuery(colpkr).fadeOut(500);
return false;
},
onChange: function (hsb, hex, rgb) {
jQuery('#".$pa_options["name"]."').val(hex);
jQuery('#".$pa_options["name"]."_colorchip').css('backgroundColor', '#' + hex);
},
color: jQuery('#".$pa_options["name"]."').val()
})}); </script>\n";
if (method_exists('JavascriptLoadManager', 'register')) {
JavascriptLoadManager::register('jquery', 'colorpicker');
}
} else {
# normal controls: all non-DT_SELECT display types are returned as DT_FIELD's. We could generate
# radio-button controls for foreign key and choice lists, but we don't bother because it's never
# really necessary.
if ($vn_display_height > 1) {
$vs_element = '<'.$vs_text_area_tag_name.' name="'.$pa_options["name"].'" rows="'.$vn_display_height.'" cols="'.$vn_display_width.'"'.($pa_options['readonly'] ? ' readonly="readonly" ' : '').' wrap="soft" '.$vs_js.' id=\''.$pa_options["id"]."' style='{$vs_dim_style}' ".$vs_css_class_attr.">".$this->escapeHTML($vm_field_value).'</'.$vs_text_area_tag_name.'>'."\n";
} else {
$vs_element = '<input name="'.$pa_options["name"].'" type="text" size="'.($pa_options['size'] ? $pa_options['size'] : $vn_display_width).'"'.($pa_options['readonly'] ? ' readonly="readonly" ' : '').' value="'.$this->escapeHTML($vm_field_value).'" '.$vs_js.' id=\''.$pa_options["id"]."' {$vs_css_class_attr} style='{$vs_dim_style}'/>\n";
}
if (isset($va_attr['UNIQUE_WITHIN']) && is_array($va_attr['UNIQUE_WITHIN'])) {
$va_within_fields = array();
foreach($va_attr['UNIQUE_WITHIN'] as $vs_within_field) {
$va_within_fields[$vs_within_field] = $this->get($vs_within_field);
}
$vs_element .= "<span id='".$pa_options["id"].'_uniqueness_status'."'></span>";
$vs_element .= "<script type='text/javascript'>
caUI.initUniquenessChecker({
errorIcon: '".$pa_options['error_icon']."',
processIndicator: '".$pa_options['progress_indicator']."',
statusID: '".$pa_options["id"]."_uniqueness_status',
lookupUrl: '".$pa_options['lookup_url']."',
formElementID: '".$pa_options["id"]."',
row_id: ".intval($this->getPrimaryKey()).",
table_num: ".$this->tableNum().",
field: '".$ps_field."',
withinFields: ".json_encode($va_within_fields).",
alreadyInUseMessage: '".addslashes(_t('Value must be unique. Please try another.'))."'
});
</script>";
}
}
}
break;
# ----------------------------
case (FT_TIMESTAMP):
if ($this->get($ps_field)) { # is timestamp set?
$vs_element = $this->escapeHTML($vm_field_value); # return printed date
} else {
$vs_element = "[Not set]"; # return text instead of 1969 date
}
break;
# ----------------------------
case (FT_DATETIME):
case (FT_HISTORIC_DATETIME):
case (FT_DATE):
case (FT_HISTORIC_DATE):
if (!$vm_field_value) {
$vm_field_value = $pa_options['value'];
}
switch($va_attr["DISPLAY_TYPE"]) {
case DT_TEXT:
$vs_element = $vm_field_value ? $vm_field_value : "[Not set]";
break;
default:
$vn_max_length = $va_attr["BOUNDS_LENGTH"][1];
$vs_max_length = '';
if ($vn_max_length > 0) $vs_max_length = 'maxlength="'.$vn_max_length.'"';
if ($vn_display_height > 1) {
$vs_element = '<'.$vs_text_area_tag_name.' name="'.$pa_options["name"].'" rows="'.$vn_display_height.'" cols="'.$vn_display_width.'" wrap="soft" '.$vs_js.' '.$vs_css_class_attr." style='{$vs_dim_style}'".($pa_options['readonly'] ? ' readonly="readonly" ' : '').">".$this->escapeHTML($vm_field_value).'</'.$vs_text_area_tag_name.'>';
} else {
$vs_element = '<input type="text" name="'.$pa_options["name"].'" value="'.$this->escapeHTML($vm_field_value)."\" size='{$vn_display_width}' {$vs_max_length} {$vs_js} {$vs_css_class_attr} style='{$vs_dim_style}'".($pa_options['readonly'] ? ' readonly="readonly" ' : '')."/>";
}
break;
}
break;
# ----------------------------
case(FT_TIME):
if (!$this->get($ps_field)) {
$vm_field_value = "";
}
switch($va_attr["DISPLAY_TYPE"]) {
case DT_TEXT:
$vs_element = $vm_field_value ? $vm_field_value : "[Not set]";
break;
default:
$vn_max_length = $va_attr["BOUNDS_LENGTH"][1];
$vs_max_length = '';
if ($vn_max_length > 0) $vs_max_length = 'maxlength="'.$vn_max_length.'"';
if ($vn_display_height > 1) {
$vs_element = '<'.$vs_text_area_tag_name.' name="'.$pa_options["name"].'" rows="'.$vn_display_height.'" cols="'.$vn_display_width.'" wrap="soft" '.$vs_js.' '.$vs_css_class_attr." style='{$vs_dim_style}'".($pa_options['readonly'] ? ' readonly="readonly" ' : '').">".$this->escapeHTML($vm_field_value).'</'.$vs_text_area_tag_name.'>';
} else {
$vs_element = '<input type="text" name="'.$pa_options["name"].'" value="'.$this->escapeHTML($vm_field_value)."\" size='{$vn_display_width}' {$vs_max_length} {$vs_js} {$vs_css_class_attr}' style='{$vs_dim_style}'".($pa_options['readonly'] ? ' readonly="readonly" ' : '')."/>";
}
break;
}
break;
# ----------------------------
case(FT_DATERANGE):
case(FT_HISTORIC_DATERANGE):
switch($va_attr["DISPLAY_TYPE"]) {
case DT_TEXT:
$vs_element = $vm_field_value ? $vm_field_value : "[Not set]";
break;
default:
$vn_max_length = $va_attr["BOUNDS_LENGTH"][1];
$vs_max_length = '';
if ($vn_max_length > 0) $vs_max_length = 'maxlength="'.$vn_max_length.'"';
if ($vn_display_height > 1) {
$vs_element = '<'.$vs_text_area_tag_name.' name="'.$pa_options["name"].'" rows="'.$vn_display_height.'" cols="'.$vn_display_width.'" wrap="soft" '.$vs_js.' '.$vs_css_class_attr." style='{$vs_dim_style}'".($pa_options['readonly'] ? ' readonly="readonly" ' : '').">".$this->escapeHTML($vm_field_value).'</'.$vs_text_area_tag_name.'>';
} else {
$vs_element = '<input type="text" name="'.$pa_options["name"].'" value="'.$this->escapeHTML($vm_field_value)."\" size='{$vn_display_width}' {$vn_max_length} {$vs_js} {$vs_css_class_attr} style='{$vs_dim_style}'".($pa_options['readonly'] ? ' readonly="readonly" ' : '')."/>";
}
break;
}
break;
# ----------------------------
case (FT_TIMERANGE):
switch($va_attr["DISPLAY_TYPE"]) {
case DT_TEXT:
$vs_element = $vm_field_value ? $vm_field_value : "[Not set]";
break;
default:
$vn_max_length = $va_attr["BOUNDS_LENGTH"][1];
$vs_max_length = '';
if ($vn_max_length > 0) $vs_max_length = 'maxlength="'.$vn_max_length.'"';
if ($vn_display_height > 1) {
$vs_element = '<'.$vs_text_area_tag_name.' name="'.$pa_options["name"].'" rows="'.$vn_display_height.'" cols="'.$vn_display_width.'" wrap="soft" '.$vs_js.' '.$vs_css_class_attr." style='{$vs_dim_style}'".($pa_options['readonly'] ? ' readonly="readonly" ' : '').">".$this->escapeHTML($vm_field_value).'</'.$vs_text_area_tag_name.'>';
} else {
$vs_element = '<input type="text" name="'.$pa_options["name"].'" value="'.$this->escapeHTML($vm_field_value)."\" size='{$vn_display_width}' {$vs_max_length} {$vs_js} {$vs_css_class_attr} style='{$vs_dim_style}'".($pa_options['readonly'] ? ' readonly="readonly" ' : '')."/>";
}
break;
}
break;
# ----------------------------
case(FT_TIMECODE):
$o_tp = new TimecodeParser();
$o_tp->setParsedValueInSeconds($vm_field_value);
$vs_timecode = $o_tp->getText("COLON_DELIMITED", array("BLANK_ON_ZERO" => true));
$vn_max_length = $va_attr["BOUNDS_LENGTH"][1];
$vs_max_length = '';
if ($vn_max_length > 0) $vs_max_length = 'maxlength="'.$vn_max_length.'"';
if ($vn_display_height > 1) {
$vs_element = '<'.$vs_text_area_tag_name.' name="'.$pa_options["name"].'" rows="'.$vn_display_height.'" cols="'.$vn_display_width.'" wrap="soft" '.$vs_js.' '.$vs_css_class_attr." style='{$vs_dim_style}'".($pa_options['readonly'] ? ' readonly="readonly" ' : '').">".$this->escapeHTML($vs_timecode).'</'.$vs_text_area_tag_name.'>';
} else {
$vs_element = '<input type="text" NAME="'.$pa_options["name"].'" value="'.$this->escapeHTML($vs_timecode)."\" size='{$vn_display_width}' {$vs_max_length} {$vs_js} {$vs_css_class_attr} style='{$vs_dim_style}'".($pa_options['readonly'] ? ' readonly="readonly" ' : '')."/>";
}
break;
# ----------------------------
case(FT_MEDIA):
case(FT_FILE):
$vs_element = '<input type="file" name="'.$pa_options["name"].'" '.$vs_js.'/>';
// show current media icon
if ($vs_version = (array_key_exists('displayMediaVersion', $pa_options)) ? $pa_options['displayMediaVersion'] : 'icon') {
$va_valid_versions = $this->getMediaVersions($ps_field);
if (!in_array($vs_version, $va_valid_versions)) {
$vs_version = $va_valid_versions[0];
}
if ($vs_tag = $this->getMediaTag($ps_field, $vs_version)) { $vs_element .= $vs_tag; }
}
break;
# ----------------------------
case(FT_PASSWORD):
$vn_max_length = $va_attr["BOUNDS_LENGTH"][1];
$vs_max_length = '';
if ($vn_max_length > 0) $vs_max_length = 'maxlength="'.$vn_max_length.'"';
$vs_element = '<input type="password" name="'.$pa_options["name"].'" value="'.$this->escapeHTML($vm_field_value).'" size="'.$vn_display_width.'" '.$vs_max_length.' '.$vs_js.' autocomplete="off" '.$vs_css_class_attr." style='{$vs_dim_style}'".($pa_options['readonly'] ? ' readonly="readonly" ' : '')."/>";
break;
# ----------------------------
case(FT_BIT):
switch($va_attr["DISPLAY_TYPE"]) {
case (DT_FIELD):
$vs_element = '<input type="text" name="'.$pa_options["name"]."\" value='{$vm_field_value}' maxlength='1' size='2' {$vs_js} style='{$vs_dim_style}'".($pa_options['readonly'] ? ' readonly="readonly" ' : '')."/>";
break;
case (DT_SELECT):
$vs_element = "<select name='".$pa_options["name"]."' ".$vs_js." id='".$pa_options["id"]."' {$vs_css_class_attr} style='{$vs_dim_style}'".($pa_options['readonly'] ? ' disabled="disabled" ' : '').">\n";
foreach(array("Yes" => 1, "No" => 0) as $vs_option => $vs_value) {
$vs_selected = ($vs_value == $vm_field_value) ? "selected='selected'" : "";
$vs_element.= "<option value='$vs_value' {$vs_selected}".($pa_options['readonly'] ? ' disabled="disabled" ' : '').">$vs_option</option>\n";
}
$vs_element .= "</select>\n";
break;
case (DT_CHECKBOXES):
$vs_element = '<input type="checkbox" name="'.$pa_options["name"].'" value="1" '.($vm_field_value ? 'checked="1"' : '').' '.$vs_js.($pa_options['readonly'] ? ' disabled="disabled" ' : '').' id="'.$pa_options["id"].'"/>';
break;
case (DT_RADIO_BUTTONS):
$vs_element = 'Radio buttons not supported for bit-type fields';
break;
}
break;
# ----------------------------
}
# Apply format
$vs_formatting = "";
if (isset($pa_options['field_errors']) && is_array($pa_options['field_errors']) && sizeof($pa_options['field_errors'])) {
$va_field_errors = array();
foreach($pa_options['field_errors'] as $o_e) {
$va_field_errors[] = $o_e->getErrorDescription();
}
$vs_errors = join('; ', $va_field_errors);
} else {
$vs_errors = '';
}
if (is_null($ps_format)) {
if (isset($pa_options['field_errors']) && is_array($pa_options['field_errors']) && sizeof($pa_options['field_errors'])) {
$ps_format = $this->_CONFIG->get('form_element_error_display_format');
} else {
$ps_format = $this->_CONFIG->get('form_element_display_format');
}
}
if ($ps_format != '') {
$ps_formatted_element = $ps_format;
$ps_formatted_element = str_replace("^ELEMENT", $vs_element, $ps_formatted_element);
if ($vs_subelement) {
$ps_formatted_element = str_replace("^SUB_ELEMENT", $vs_subelement, $ps_formatted_element);
}
$vb_fl_display_form_field_tips = false;
if (
$pa_options["display_form_field_tips"] ||
(!isset($pa_options["display_form_field_tips"]) && $va_attr["DISPLAY_DESCRIPTION"]) ||
(!isset($pa_options["display_form_field_tips"]) && !isset($va_attr["DISPLAY_DESCRIPTION"]) && $vb_fl_display_form_field_tips)
) {
if (preg_match("/\^DESCRIPTION/", $ps_formatted_element)) {
$ps_formatted_element = str_replace("^LABEL",$vs_field_label, $ps_formatted_element);
$ps_formatted_element = str_replace("^DESCRIPTION",$va_attr["DESCRIPTION"], $ps_formatted_element);
} else {
// no explicit placement of description text, so...
$vs_field_id = '_'.$this->tableName().'_'.$this->getPrimaryKey().'_'.$pa_options["name"].'_'.$pa_options['form_name'];
$ps_formatted_element = str_replace("^LABEL",'<span id="'.$vs_field_id.'">'.$vs_field_label.'</span>', $ps_formatted_element);
if (!isset($pa_options['no_tooltips']) || !$pa_options['no_tooltips']) {
TooltipManager::add('#'.$vs_field_id, "<h3>{$vs_field_label}</h3>".$va_attr["DESCRIPTION"], $pa_options['tooltip_namespace']);
}
}
if (!isset($va_attr["SUB_LABEL"])) { $va_attr["SUB_LABEL"] = ''; }
if (!isset($va_attr["SUB_DESCRIPTION"])) { $va_attr["SUB_DESCRIPTION"] = ''; }
if (preg_match("/\^SUB_DESCRIPTION/", $ps_formatted_element)) {
$ps_formatted_element = str_replace("^SUB_LABEL",$va_attr["SUB_LABEL"], $ps_formatted_element);
$ps_formatted_element = str_replace("^SUB_DESCRIPTION", $va_attr["SUB_DESCRIPTION"], $ps_formatted_element);
} else {
// no explicit placement of description text, so...
// ... make label text itself rollover for description text because no icon was specified
$ps_formatted_element = str_replace("^SUB_LABEL",$va_attr["SUB_LABEL"], $ps_formatted_element);
}
} else {
$ps_formatted_element = str_replace("^LABEL", $vs_field_label, $ps_formatted_element);
$ps_formatted_element = str_replace("^DESCRIPTION", "", $ps_formatted_element);
if ($vs_subelement) {
$ps_formatted_element = str_replace("^SUB_LABEL", $va_attr["SUB_LABEL"], $ps_formatted_element);
$ps_formatted_element = str_replace("^SUB_DESCRIPTION", "", $ps_formatted_element);
}
}
$ps_formatted_element = str_replace("^ERRORS", $vs_errors, $ps_formatted_element);
$ps_formatted_element = str_replace("^EXTRA", isset($pa_options['extraLabelText']) ? $pa_options['extraLabelText'] : '', $ps_formatted_element);
$vs_element = $ps_formatted_element;
} else {
$vs_element .= "<br/>".$vs_subelement;
}
return $vs_element;
} else {
$this->postError(716,_t("'%1' does not exist in this object", $ps_field),"BaseModel->formElement()");
return "";
}
return "";
}
# --------------------------------------------------------------------------------------------
/**
* Get list name
*
* @access public
* @return string
*/
public function getListName() {
if (is_array($va_display_fields = $this->getProperty('LIST_FIELDS'))) {
$va_tmp = array();
$vs_delimiter = $this->getProperty('LIST_DELIMITER');
foreach($va_display_fields as $vs_display_field) {
$va_tmp[] = $this->get($vs_display_field);
}
return join($vs_delimiter, $va_tmp);
}
return null;
}
# --------------------------------------------------------------------------------------------
/**
* Modifies text for HTML use (i.e. passing it through stripslashes and htmlspecialchars)
*
* @param string $ps_text
* @return string
*/
public function escapeHTML($ps_text) {
$opa_php_version = caGetPHPVersion();
if ($opa_php_version['versionInt'] >= 50203) {
$ps_text = htmlspecialchars(stripslashes($ps_text), ENT_QUOTES, $this->getCharacterSet(), false);
} else {
$ps_text = htmlspecialchars(stripslashes($ps_text), ENT_QUOTES, $this->getCharacterSet());
}
return str_replace("&#", "&#", $ps_text);
}
# --------------------------------------------------------------------------------------------
/**
* Returns list of names of fields that must be defined
*/
public function getMandatoryFields() {
$va_fields = $this->getFormFields(true);
$va_many_to_one_relations = $this->_DATAMODEL->getManyToOneRelations($this->tableName());
$va_mandatory_fields = array();
foreach($va_fields as $vs_field => $va_info) {
if (isset($va_info['IDENTITY']) && $va_info['IDENTITY']) { continue;}
if ((isset($va_many_to_one_relations[$vs_field]) && $va_many_to_one_relations[$vs_field]) && (!isset($va_info['IS_NULL']) || !$va_info['IS_NULL'])) {
$va_mandatory_fields[] = $vs_field;
continue;
}
if (isset($va_info['BOUNDS_LENGTH']) && is_array($va_info['BOUNDS_LENGTH'])) {
if ($va_info['BOUNDS_LENGTH'][0] > 0) {
$va_mandatory_fields[] = $vs_field;
continue;
}
}
}
return $va_mandatory_fields;
}
# --------------------------------------------------------------------------------------------
/**
* Returns a list_code for a list in the ca_lists table that is used for the specified field
* Return null if the field has no list associated with it
*/
public function getFieldListCode($ps_field) {
$va_field_info = $this->getFieldInfo($ps_field);
return ($vs_list_code = $va_field_info['LIST_CODE']) ? $vs_list_code : null;
}
# --------------------------------------------------------------------------------------------
/**
* Return list of items specified for the given field.
*
* @param string $ps_field The name of the field
* @param string $ps_list_code Optional list code or list_id to force return of, overriding the list configured in the model
* @return array A list of items, filtered on the current user locale; the format is the same as that returned by ca_lists::getItemsForList()
*/
public function getFieldList($ps_field, $ps_list_code=null) {
$t_list = new ca_lists();
return caExtractValuesByUserLocale($t_list->getItemsForList($ps_list_code ? $ps_list_code : $this->getFieldListCode($ps_field)));
}
# --------------------------------------------------------------------------------------------
/**
* Creates a relationship between the currently loaded row and the specified row.
*
* @param mixed $pm_rel_table_name_or_num Table name (eg. "ca_entities") or number as defined in datamodel.conf of table containing row to creation relationship to.
* @param int $pn_rel_id primary key value of row to creation relationship to.
* @param mixed $pm_type_id Relationship type type_code or type_id, as defined in the ca_relationship_types table. This is required for all relationships that use relationship types. This includes all of the most common types of relationships.
* @param string $ps_effective_date Optional date expression to qualify relation with. Any expression that the TimeExpressionParser can handle is supported here.
* @param string $ps_source_info Text field for storing information about source of relationship. Not currently used.
* @param string $ps_direction Optional direction specification for self-relationships (relationships linking two rows in the same table). Valid values are 'ltor' (left-to-right) and 'rtol' (right-to-left); the direction determines which "side" of the relationship the currently loaded row is on: 'ltor' puts the current row on the left side. For many self-relations the direction determines the nature and display text for the relationship.
* @return boolean True on success, false on error.
*/
public function addRelationship($pm_rel_table_name_or_num, $pn_rel_id, $pm_type_id=null, $ps_effective_date=null, $ps_source_info=null, $ps_direction=null, $pn_rank=null) {
if(!($va_rel_info = $this->_getRelationshipInfo($pm_rel_table_name_or_num))) {
$this->postError(1240, _t('Related table specification "%1" is not valid', $pm_rel_table_name_or_num), 'BaseModel->addRelationship()');
return false;
}
$t_item_rel = $va_rel_info['t_item_rel'];
if ($pm_type_id && !is_numeric($pm_type_id)) {
$t_rel_type = new ca_relationship_types();
if ($vs_linking_table = $t_rel_type->getRelationshipTypeTable($this->tableName(), $t_item_rel->tableName())) {
$pn_type_id = $t_rel_type->getRelationshipTypeID($vs_linking_table, $pm_type_id);
}
} else {
$pn_type_id = $pm_type_id;
}
if ($va_rel_info['related_table_name'] == $this->tableName()) {
// is self relation
$t_item_rel->setMode(ACCESS_WRITE);
// is self relationship
if ($ps_direction == 'rtol') {
$t_item_rel->set($t_item_rel->getRightTableFieldName(), $this->getPrimaryKey());
$t_item_rel->set($t_item_rel->getLeftTableFieldName(), $pn_rel_id);
} else {
// default is left-to-right
$t_item_rel->set($t_item_rel->getLeftTableFieldName(), $this->getPrimaryKey());
$t_item_rel->set($t_item_rel->getRightTableFieldName(), $pn_rel_id);
}
$t_item_rel->set($t_item_rel->getTypeFieldName(), $pn_type_id); // TODO: verify type_id based upon type_id's of each end of the relationship
if(!is_null($ps_effective_date)){ $t_item_rel->set('effective_date', $ps_effective_date); }
if(!is_null($ps_source_info)){ $t_item_rel->set("source_info",$ps_source_info); }
$t_item_rel->insert();
if ($t_item_rel->numErrors()) {
$this->errors = $t_item_rel->errors;
return false;
}
} else {
switch(sizeof($va_rel_info['path'])) {
case 3: // many-to-many relationship
$t_rel = $this->getAppDatamodel()->getTableInstance($va_rel_info['related_table_name']);
$t_item_rel->setMode(ACCESS_WRITE);
$vs_left_table = $t_item_rel->getLeftTableName();
$vs_right_table = $t_item_rel->getRightTableName();
if ($this->tableName() == $vs_left_table) {
// is lefty
$t_item_rel->set($t_item_rel->getLeftTableFieldName(), $this->getPrimaryKey());
$t_item_rel->set($t_item_rel->getRightTableFieldName(), $pn_rel_id);
} else {
// is righty
$t_item_rel->set($t_item_rel->getRightTableFieldName(), $this->getPrimaryKey());
$t_item_rel->set($t_item_rel->getLeftTableFieldName(), $pn_rel_id);
}
$t_item_rel->set('rank', $pn_rank);
$t_item_rel->set($t_item_rel->getTypeFieldName(), $pn_type_id); // TODO: verify type_id based upon type_id's of each end of the relationship
if(!is_null($ps_effective_date)){ $t_item_rel->set('effective_date', $ps_effective_date); }
if(!is_null($ps_source_info)){ $t_item_rel->set("source_info",$ps_source_info); }
$t_item_rel->insert();
if ($t_item_rel->numErrors()) {
$this->errors = $t_item_rel->errors;
return false;
}
case 2: // many-to-one relationship
if ($this->tableName() == $va_rel_info['rel_keys']['one_table']) {
if ($t_item_rel->load($pn_rel_id)) {
$t_item_rel->setMode(ACCESS_WRITE);
$t_item_rel->set($va_rel_info['rel_keys']['many_table_field'], $this->getPrimaryKey());
$t_item_rel->update();
if ($t_item_rel->numErrors()) {
$this->errors = $t_item_rel->errors;
return false;
}
} else {
$t_item_rel->setMode(ACCESS_WRITE);
$t_item_rel->set($t_item_rel->getLeftTableFieldName(), $this->getPrimaryKey());
$t_item_rel->set($t_item_rel->getRightTableFieldName(), $pn_rel_id);
$t_item_rel->set($t_item_rel->getTypeFieldName(), $pn_type_id);
$t_item_rel->insert();
if ($t_item_rel->numErrors()) {
$this->errors = $t_item_rel->errors;
return false;
}
}
} else {
$this->setMode(ACCESS_WRITE);
$this->set($va_rel_info['rel_keys']['many_table_field'], $pn_rel_id);
$this->update();
if ($this->numErrors()) {
return false;
}
}
break;
default:
return false;
break;
}
}
return true;
}
# --------------------------------------------------------------------------------------------
/**
* Edits the data in an existing relationship between the currently loaded row and the specified row.
*
* @param mixed $pm_rel_table_name_or_num Table name (eg. "ca_entities") or number as defined in datamodel.conf of table containing row to create relationships to.
* @param int $pn_relation_id primary key value of the relation to edit.
* @param int $pn_rel_id primary key value of row to creation relationship to.
* @param mixed $pm_type_id Relationship type type_code or type_id, as defined in the ca_relationship_types table. This is required for all relationships that use relationship types. This includes all of the most common types of relationships.
* @param string $ps_effective_date Optional date expression to qualify relation with. Any expression that the TimeExpressionParser can handle is supported here.
* @param string $ps_source_info Text field for storing information about source of relationship. Not currently used.
* @param string $ps_direction Optional direction specification for self-relationships (relationships linking two rows in the same table). Valid values are 'ltor' (left-to-right) and 'rtol' (right-to-left); the direction determines which "side" of the relationship the currently loaded row is on: 'ltor' puts the current row on the left side. For many self-relations the direction determines the nature and display text for the relationship.
* @return boolean True on success, false on error.
*/
public function editRelationship($pm_rel_table_name_or_num, $pn_relation_id, $pn_rel_id, $pm_type_id=null, $ps_effective_date=null, $pa_source_info=null, $ps_direction=null, $pn_rank=null) {
if(!($va_rel_info = $this->_getRelationshipInfo($pm_rel_table_name_or_num))) {
$this->postError(1240, _t('Related table specification "%1" is not valid', $pm_rel_table_name_or_num), 'BaseModel->editRelationship()');
return false;
}
$t_item_rel = $va_rel_info['t_item_rel'];
if ($pm_type_id && !is_numeric($pm_type_id)) {
$t_rel_type = new ca_relationship_types();
if ($vs_linking_table = $t_rel_type->getRelationshipTypeTable($this->tableName(), $t_item_rel->tableName())) {
$pn_type_id = $t_rel_type->getRelationshipTypeID($vs_linking_table, $pm_type_id);
}
} else {
$pn_type_id = $pm_type_id;
}
if ($va_rel_info['related_table_name'] == $this->tableName()) {
// is self relation
if ($t_item_rel->load($pn_relation_id)) {
$t_item_rel->setMode(ACCESS_WRITE);
if ($ps_direction == 'rtol') {
$t_item_rel->set($t_item_rel->getRightTableFieldName(), $this->getPrimaryKey());
$t_item_rel->set($t_item_rel->getLeftTableFieldName(), $pn_rel_id);
} else {
// default is left-to-right
$t_item_rel->set($t_item_rel->getLeftTableFieldName(), $this->getPrimaryKey());
$t_item_rel->set($t_item_rel->getRightTableFieldName(), $pn_rel_id);
}
$t_item_rel->set('rank', $pn_rank);
$t_item_rel->set($t_item_rel->getTypeFieldName(), $pn_type_id); // TODO: verify type_id based upon type_id's of each end of the relationship
if(!is_null($ps_effective_date)){ $t_item_rel->set('effective_date', $ps_effective_date); }
if(!is_null($ps_source_info)){ $t_item_rel->set("source_info",$ps_source_info); }
$t_item_rel->update();
if ($t_item_rel->numErrors()) {
$this->errors = $t_item_rel->errors;
return false;
}
}
} else {
switch(sizeof($va_rel_info['path'])) {
case 3: // many-to-many relationship
if ($t_item_rel->load($pn_relation_id)) {
$t_item_rel->setMode(ACCESS_WRITE);
$vs_left_table = $t_item_rel->getLeftTableName();
$vs_right_table = $t_item_rel->getRightTableName();
if ($this->tableName() == $vs_left_table) {
// is lefty
$t_item_rel->set($t_item_rel->getLeftTableFieldName(), $this->getPrimaryKey());
$t_item_rel->set($t_item_rel->getRightTableFieldName(), $pn_rel_id);
} else {
// is righty
$t_item_rel->set($t_item_rel->getRightTableFieldName(), $this->getPrimaryKey());
$t_item_rel->set($t_item_rel->getLeftTableFieldName(), $pn_rel_id);
}
$t_item_rel->set('rank', $pn_rank);
$t_item_rel->set($t_item_rel->getTypeFieldName(), $pn_type_id); // TODO: verify type_id based upon type_id's of each end of the relationship
if(!is_null($ps_effective_date)){ $t_item_rel->set('effective_date', $ps_effective_date); }
if(!is_null($ps_source_info)){ $t_item_rel->set("source_info",$ps_source_info); }
$t_item_rel->update();
if ($t_item_rel->numErrors()) {
$this->errors = $t_item_rel->errors;
return false;
}
return true;
}
case 2: // many-to-one relations
if ($this->tableName() == $va_rel_info['rel_keys']['one_table']) {
if ($t_item_rel->load($pn_relation_id)) {
$t_item_rel->setMode(ACCESS_WRITE);
$t_item_rel->set($va_rel_info['rel_keys']['many_table_field'], null);
$t_item_rel->update();
if ($t_item_rel->numErrors()) {
$this->errors = $t_item_rel->errors;
return false;
}
}
if ($t_item_rel->load($pn_rel_id)) {
$t_item_rel->setMode(ACCESS_WRITE);
$t_item_rel->set($va_rel_info['rel_keys']['many_table_field'], $this->getPrimaryKey());
$t_item_rel->update();
if ($t_item_rel->numErrors()) {
$this->errors = $t_item_rel->errors;
return false;
}
}
} else {
$this->setMode(ACCESS_WRITE);
$this->set($va_rel_info['rel_keys']['many_table_field'], $pn_rel_id);
$this->update();
if ($this->numErrors()) {
return false;
}
}
break;
default:
return false;
break;
}
}
return false;
}
# --------------------------------------------------------------------------------------------
/**
* Removes the specified relationship
*
* @param mixed $pm_rel_table_name_or_num Table name (eg. "ca_entities") or number as defined in datamodel.conf of table containing row to edit relationships to.
* @param int $pn_relation_id primary key value of the relation to remove.
* @return boolean True on success, false on error.
*/
public function removeRelationship($pm_rel_table_name_or_num, $pn_relation_id) {
if(!($va_rel_info = $this->_getRelationshipInfo($pm_rel_table_name_or_num))) {
$this->postError(1240, _t('Related table specification "%1" is not valid', $pm_rel_table_name_or_num), 'BaseModel->removeRelationship()');
return false;
}
$t_item_rel = $va_rel_info['t_item_rel'];
if ($va_rel_info['related_table_name'] == $this->tableName()) {
if ($t_item_rel->load($pn_relation_id)) {
$t_item_rel->setMode(ACCESS_WRITE);
$t_item_rel->delete();
if ($t_item_rel->numErrors()) {
$this->errors = $t_item_rel->errors;
return false;
}
return true;
}
} else {
switch(sizeof($va_rel_info['path'])) {
case 3: // many-to-one relationship
if ($t_item_rel->load($pn_relation_id)) {
$t_item_rel->setMode(ACCESS_WRITE);
$t_item_rel->delete();
if ($t_item_rel->numErrors()) {
$this->errors = $t_item_rel->errors;
return false;
}
return true;
}
case 2:
if ($this->tableName() == $va_rel_info['rel_keys']['one_table']) {
if ($t_item_rel->load($pn_relation_id)) {
$t_item_rel->setMode(ACCESS_WRITE);
$t_item_rel->set($va_rel_info['rel_keys']['many_table_field'], null);
$t_item_rel->update();
if ($t_item_rel->numErrors()) {
$this->errors = $t_item_rel->errors;
return false;
}
}
} else {
$this->setMode(ACCESS_WRITE);
$this->set($va_rel_info['rel_keys']['many_table_field'], null);
$this->update();
if ($this->numErrors()) {
return false;
}
}
break;
default:
return false;
break;
}
}
return false;
}
# --------------------------------------------------------------------------------------------
/**
* Remove all relations with the specified table from the currently loaded row
*
* @param mixed $pm_rel_table_name_or_num Table name (eg. "ca_entities") or number as defined in datamodel.conf of table containing row to removes relationships to.
* @return boolean True on success, false on error
*/
public function removeRelationships($pm_rel_table_name_or_num) {
if (!($vn_row_id = $this->getPrimaryKey())) { return null; }
if(!($va_rel_info = $this->_getRelationshipInfo($pm_rel_table_name_or_num))) { return null; }
$t_item_rel = $va_rel_info['t_item_rel'];
$o_db = $this->getDb();
if ($t_item_rel->tableName() == $this->getSelfRelationTableName()) {
$qr_res = $o_db->query("
SELECT relation_id FROM ".$t_item_rel->tableName()."
WHERE ".$t_item_rel->getLeftTableFieldName()." = ? OR ".$t_item_rel->getRightTableFieldName()." = ?
", (int)$vn_row_id, (int)$vn_row_id);
while($qr_res->nextRow()) {
if (!$this->removeRelationship($pm_rel_table_name_or_num, $qr_res->get('relation_id'))) {
return false;
}
}
} else {
$qr_res = $o_db->query("
SELECT relation_id FROM ".$t_item_rel->tableName()." WHERE ".$this->primaryKey()." = ?
", (int)$vn_row_id);
while($qr_res->nextRow()) {
if (!$this->removeRelationship($pm_rel_table_name_or_num, $qr_res->get('relation_id'))) {
return false;
}
}
}
return true;
}
# --------------------------------------------------------------------------------------------
/**
*
*/
public function getRelationshipInstance($pm_rel_table_name_or_num) {
if ($va_rel_info = $this->_getRelationshipInfo($pm_rel_table_name_or_num)) {
return $va_rel_info['t_item_rel'];
}
return null;
}
# --------------------------------------------------------------------------------------------
/**
* Moves relationships from currently loaded row to another row specified by $pn_row_id. The existing relationship
* rows are simply re-pointed to the new row, so this is a relatively fast operation. Note that this method does not copy
* relationships, it moves them. After the operation completes no relationships to the specified related table will exist for the current row.
*
* @param mixed $pm_rel_table_name_or_num The table name or number of the related table. Only relationships pointing to this table will be moved.
* @param int $pn_to_id The primary key value of the row to move the relationships to.
* @param array $pa_options Array of options. No options are currently supported.
*
* @return int Number of relationships moved, or null on error. Note that you should carefully test the return value for null-ness rather than false-ness, since zero is a valid return value in cases where no relationships need to be moved.
*/
public function moveRelationships($pm_rel_table_name_or_num, $pn_to_id, $pa_options=null) {
if (!($vn_row_id = $this->getPrimaryKey())) { return null; }
if(!($va_rel_info = $this->_getRelationshipInfo($pm_rel_table_name_or_num))) { return null; }
$t_item_rel = $va_rel_info['t_item_rel']; // linking table
$o_db = $this->getDb();
$vs_item_pk = $this->primaryKey();
if (!($t_rel_item = $this->getAppDatamodel()->getTableInstance($va_rel_info['related_table_name']))) { // related item
return null;
}
$va_to_reindex_relations = array();
if ($t_item_rel->tableName() == $this->getSelfRelationTableName()) {
$qr_res = $o_db->query("
SELECT * FROM ".$t_item_rel->tableName()."
WHERE ".$t_item_rel->getLeftTableFieldName()." = ? OR ".$t_item_rel->getRightTableFieldName()." = ?
", (int)$vn_row_id, (int)$vn_row_id);
if ($o_db->numErrors()) { $this->errors = $o_db->errors; return null; }
while($qr_res->nextRow()) {
$va_to_reindex_relations[(int)$qr_res->get('relation_id')] = $qr_res->getRow();
}
if (!sizeof($va_to_reindex_relations)) { return 0; }
$o_db->query("
UPDATE ".$t_item_rel->tableName()." SET ".$t_item_rel->getLeftTableFieldName()." = ? WHERE ".$t_item_rel->getLeftTableFieldName()." = ?
", (int)$pn_to_id, (int)$vn_row_id);
if ($o_db->numErrors()) { $this->errors = $o_db->errors; return null; }
$o_db->query("
UPDATE ".$t_item_rel->tableName()." SET ".$t_item_rel->getRightTableFieldName()." = ? WHERE ".$t_item_rel->getRightTableFieldName()." = ?
", (int)$pn_to_id, (int)$vn_row_id);
if ($o_db->numErrors()) { $this->errors = $o_db->errors; return null; }
} else {
$qr_res = $o_db->query("
SELECT * FROM ".$t_item_rel->tableName()." WHERE {$vs_item_pk} = ?
", (int)$vn_row_id);
if ($o_db->numErrors()) { $this->errors = $o_db->errors; return null; }
while($qr_res->nextRow()) {
$va_to_reindex_relations[(int)$qr_res->get('relation_id')] = $qr_res->getRow();
}
if (!sizeof($va_to_reindex_relations)) { return 0; }
$o_db->query("
UPDATE ".$t_item_rel->tableName()." SET {$vs_item_pk} = ? WHERE {$vs_item_pk} = ?
", (int)$pn_to_id, (int)$vn_row_id);
if ($o_db->numErrors()) { $this->errors = $o_db->errors; return null; }
}
$vn_rel_table_num = $t_item_rel->tableNum();
// Reindex modified relationships
if (!BaseModel::$search_indexer) {
BaseModel::$search_indexer = new SearchIndexer($this->getDb());
}
foreach($va_to_reindex_relations as $vn_relation_id => $va_row) {
BaseModel::$search_indexer->indexRow($vn_rel_table_num, $vn_relation_id, $va_row, false, null, array($vs_item_pk => true));
}
return sizeof($va_to_reindex_relations);
}
# --------------------------------------------------------------------------------------------
/**
* Copies relationships from currently loaded row to another row specified by $pn_row_id. If you want to transfer relationships
* from one row to another use moveRelationships() which is much faster than copying and then deleting relationships.
*
* @see moveRelationships()
*
* @param mixed $pm_rel_table_name_or_num The table name or number of the related table. Only relationships pointing to this table will be moved.
* @param int $pn_to_id The primary key value of the row to move the relationships to.
* @param array $pa_options Array of options. No options are currently supported.
*
* @return int Number of relationships copied, or null on error. Note that you should carefully test the return value for null-ness rather than false-ness, since zero is a valid return value in cases where no relationships were available to be copied.
*/
public function copyRelationships($pm_rel_table_name_or_num, $pn_to_id, $pa_options=null) {
if (!($vn_row_id = $this->getPrimaryKey())) { return null; }
if(!($va_rel_info = $this->_getRelationshipInfo($pm_rel_table_name_or_num))) { return null; }
$t_item_rel = $va_rel_info['t_item_rel']; // linking table
if ($this->inTransaction()) { $t_item_rel->setTransaction($this->getTransaction()); }
$o_db = $this->getDb();
$vs_item_pk = $this->primaryKey();
if (!($t_rel_item = $this->getAppDatamodel()->getTableInstance($va_rel_info['related_table_name']))) { // related item
return null;
}
$va_to_reindex_relations = array();
if ($t_item_rel->tableName() == $this->getSelfRelationTableName()) {
$vs_left_field_name = $t_item_rel->getLeftTableFieldName();
$vs_right_field_name = $t_item_rel->getRightTableFieldName();
$qr_res = $o_db->query("
SELECT * FROM ".$t_item_rel->tableName()."
WHERE {$vs_left_field_name} = ? OR {$vs_right_field_name} = ?
", (int)$vn_row_id, (int)$vn_row_id);
if ($o_db->numErrors()) { $this->errors = $o_db->errors; return null; }
while($qr_res->nextRow()) {
$va_to_reindex_relations[(int)$qr_res->get('relation_id')] = $qr_res->getRow();
}
if (!sizeof($va_to_reindex_relations)) { return 0; }
$va_new_relations = array();
foreach($va_to_reindex_relations as $vn_relation_id => $va_row) {
$t_item_rel->setMode(ACCESS_WRITE);
unset($va_row[$vs_rel_pk]);
if ($va_row[$vs_left_field_name] == $vn_row_id) {
$va_row[$vs_left_field_name] = $pn_to_id;
} else {
$va_row[$vs_right_field_name] = $pn_to_id;
}
$t_item_rel->set($va_row);
$t_item_rel->insert();
if ($t_item_rel->numErrors()) {
$this->errors = $t_item_rel->errors; return null;
}
$va_new_relations[$t_item_rel->getPrimaryKey()] = $va_row;
}
} else {
$qr_res = $o_db->query("
SELECT * FROM ".$t_item_rel->tableName()." WHERE {$vs_item_pk} = ?
", (int)$vn_row_id);
if ($o_db->numErrors()) { $this->errors = $o_db->errors; return null; }
while($qr_res->nextRow()) {
$va_to_reindex_relations[(int)$qr_res->get('relation_id')] = $qr_res->getRow();
}
if (!sizeof($va_to_reindex_relations)) { return 0; }
$vs_pk = $this->primaryKey();
$vs_rel_pk = $t_item_rel->primaryKey();
$va_new_relations = array();
foreach($va_to_reindex_relations as $vn_relation_id => $va_row) {
$t_item_rel->setMode(ACCESS_WRITE);
unset($va_row[$vs_rel_pk]);
$va_row[$vs_item_pk] = $pn_to_id;
$t_item_rel->set($va_row);
$t_item_rel->insert();
if ($t_item_rel->numErrors()) {
$this->errors = $t_item_rel->errors; return null;
}
$va_new_relations[$t_item_rel->getPrimaryKey()] = $va_row;
}
}
$vn_rel_table_num = $t_item_rel->tableNum();
// Reindex modified relationships
if (!BaseModel::$search_indexer) {
BaseModel::$search_indexer = new SearchIndexer($this->getDb());
}
foreach($va_new_relations as $vn_relation_id => $va_row) {
BaseModel::$search_indexer->indexRow($vn_rel_table_num, $vn_relation_id, $va_row, false, null, array($vs_item_pk => true));
}
return sizeof($va_new_relations);
}
# --------------------------------------------------------------------------------------------
/**
*
*/
private function _getRelationshipInfo($pm_rel_table_name_or_num) {
if (is_numeric($pm_rel_table_name_or_num)) {
$vs_related_table_name = $this->getAppDataModel()->getTableName($pm_rel_table_name_or_num);
} else {
$vs_related_table_name = $pm_rel_table_name_or_num;
}
$va_rel_keys = array();
if ($this->tableName() == $vs_related_table_name) {
// self relations
if ($vs_self_relation_table = $this->getSelfRelationTableName()) {
$t_item_rel = $this->getAppDatamodel()->getTableInstance($vs_self_relation_table);
} else {
return null;
}
} else {
$va_path = array_keys($this->getAppDatamodel()->getPath($this->tableName(), $vs_related_table_name));
switch(sizeof($va_path)) {
case 3:
$t_item_rel = $this->getAppDatamodel()->getTableInstance($va_path[1]);
break;
case 2:
$t_item_rel = $this->getAppDatamodel()->getTableInstance($va_path[1]);
if (!sizeof($va_rel_keys = $this->_DATAMODEL->getOneToManyRelations($this->tableName(), $va_path[1]))) {
$va_rel_keys = $this->_DATAMODEL->getOneToManyRelations($va_path[1], $this->tableName());
}
break;
default:
// bad related table
return null;
break;
}
}
return array(
'related_table_name' => $vs_related_table_name,
'path' => $va_path,
'rel_keys' => $va_rel_keys,
't_item_rel' => $t_item_rel
);
}
# --------------------------------------------------------------------------------------------
/**
*
*/
public function getDefaultLocaleList() {
global $g_ui_locale_id;
$va_locale_dedup = array();
if ($g_ui_locale_id) {
$va_locale_dedup[$g_ui_locale_id] = true;
}
$t_locale = new ca_locales();
$va_locales = $t_locale->getLocaleList();
if (is_array($va_locale_defaults = $this->getAppConfig()->getList('locale_defaults'))) {
foreach($va_locale_defaults as $vs_locale_default) {
$va_locale_dedup[$va_locales[$vs_locale_default]] = true;
}
}
foreach($va_locales as $vn_locale_id => $vs_locale_code) {
$va_locale_dedup[$vn_locale_id] = true;
}
return array_keys($va_locale_dedup);
}
# --------------------------------------------------------------------------------------------
/**
* Returns name of self relation table (table that links two rows in this table) or NULL if no table exists
*
* @return string Name of table or null if no table is defined.
*/
public function getSelfRelationTableName() {
if (isset($this->SELF_RELATION_TABLE_NAME)) {
return $this->SELF_RELATION_TABLE_NAME;
}
return null;
}
# --------------------------------------------------------------------------------------------
# User tagging
# --------------------------------------------------------------------------------------------
/**
* Adds a tag to currently loaded row. Returns null if no row is loaded. Otherwise returns true
* if tag was successfully added, false if an error occurred in which case the errors will be available
* via the model's standard error methods (getErrors() and friends.
*
* Most of the parameters are optional with the exception of $ps_tag - the text of the tag. Note that
* tag text is monolingual; if you want to do multilingual tags then you must add multiple tags.
*
* The parameters are:
*
* @param $ps_tag [string] Text of the tag (mandatory)
* @param $pn_user_id [integer] A valid ca_users.user_id indicating the user who added the tag; is null for tags from non-logged-in users (optional - default is null)
* @param $pn_locale_id [integer] A valid ca_locales.locale_id indicating the language of the comment. If omitted or left null then the value in the global $g_ui_locale_id variable is used. If $g_ui_locale_id is not set and $pn_locale_id is not set then an error will occur (optional - default is to use $g_ui_locale_id)
* @param $pn_access [integer] Determines public visibility of tag; if set to 0 then tag is not visible to public; if set to 1 tag is visible (optional - default is 0)
* @param $pn_moderator [integer] A valid ca_users.user_id value indicating who moderated the tag; if omitted or set to null then moderation status will not be set unless app.conf setting dont_moderate_comments = 1 (optional - default is null)
* @param array $pa_options Array of options. Supported options are:
* purify = if true, comment, name and email are run through HTMLPurifier before being stored in the database. Default is true.
*/
public function addTag($ps_tag, $pn_user_id=null, $pn_locale_id=null, $pn_access=0, $pn_moderator=null, $pa_options=null) {
global $g_ui_locale_id;
if (!($vn_row_id = $this->getPrimaryKey())) { return null; }
if (!$pn_locale_id) { $pn_locale_id = $g_ui_locale_id; }
if (!$pn_locale_id) {
$this->postErrors(2830, _t('No locale was set for tag'), 'BaseModel->addTag()');
return false;
}
if(!isset($pa_options['purify'])) { $pa_options['purify'] = true; }
if ((bool)$pa_options['purify']) {
$o_purifier = new HTMLPurifier();
$ps_tag = $o_purifier->purify($ps_tag);
}
$t_tag = new ca_item_tags();
if (!$t_tag->load(array('tag' => $ps_tag, 'locale_id' => $pn_locale_id))) {
// create new new
$t_tag->setMode(ACCESS_WRITE);
$t_tag->set('tag', $ps_tag);
$t_tag->set('locale_id', $pn_locale_id);
$vn_tag_id = $t_tag->insert();
if ($t_tag->numErrors()) {
$this->errors = $t_tag->errors;
return false;
}
} else {
$vn_tag_id = $t_tag->getPrimaryKey();
}
$t_ixt = new ca_items_x_tags();
$t_ixt->setMode(ACCESS_WRITE);
$t_ixt->set('table_num', $this->tableNum());
$t_ixt->set('row_id', $this->getPrimaryKey());
$t_ixt->set('user_id', $pn_user_id);
$t_ixt->set('tag_id', $vn_tag_id);
$t_ixt->set('access', $pn_access);
if (!is_null($pn_moderator)) {
$t_ixt->set('moderated_by_user_id', $pn_moderator);
$t_ixt->set('moderated_on', 'now');
}elseif($this->_CONFIG->get("dont_moderate_comments")){
$t_ixt->set('moderated_on', 'now');
}
$t_ixt->insert();
if ($t_ixt->numErrors()) {
$this->errors = $t_ixt->errors;
return false;
}
return true;
}
# --------------------------------------------------------------------------------------------
/**
* Changed the access value for an existing tag. Returns null if no row is loaded. Otherwise returns true
* if tag access setting was successfully changed, false if an error occurred in which case the errors will be available
* via the model's standard error methods (getErrors() and friends.
*
* If $pn_user_id is set then only tag relations created by the specified user can be modified. Attempts to modify
* tags created by users other than the one specified in $pn_user_id will return false and post an error.
*
* Most of the parameters are optional with the exception of $ps_tag - the text of the tag. Note that
* tag text is monolingual; if you want to do multilingual tags then you must add multiple tags.
*
* The parameters are:
*
* @param $pn_relation_id [integer] A valid ca_items_x_tags.relation_id value specifying the tag relation to modify (mandatory)
* @param $pn_access [integer] Determines public visibility of tag; if set to 0 then tag is not visible to public; if set to 1 tag is visible (optional - default is 0)
* @param $pn_moderator [integer] A valid ca_users.user_id value indicating who moderated the tag; if omitted or set to null then moderation status will not be set (optional - default is null)
* @param $pn_user_id [integer] A valid ca_users.user_id valid; if set only tag relations created by the specified user will be modifed (optional - default is null)
*/
public function changeTagAccess($pn_relation_id, $pn_access=0, $pn_moderator=null, $pn_user_id=null) {
if (!($vn_row_id = $this->getPrimaryKey())) { return null; }
$t_ixt = new ca_items_x_tags($pn_relation_id);
if (!$t_ixt->getPrimaryKey()) {
$this->postError(2800, _t('Tag relation id is invalid'), 'BaseModel->changeTagAccess()');
return false;
}
if (
($t_ixt->get('table_num') != $this->tableNum()) ||
($t_ixt->get('row_id') != $vn_row_id)
) {
$this->postError(2810, _t('Tag is not part of the current row'), 'BaseModel->changeTagAccess()');
return false;
}
if ($pn_user_id) {
if ($t_ixt->get('user_id') != $pn_user_id) {
$this->postError(2820, _t('Tag was not created by specified user'), 'BaseModel->changeTagAccess()');
return false;
}
}
$t_ixt->setMode(ACCESS_WRITE);
$t_ixt->set('access', $pn_access);
if (!is_null($pn_moderator)) {
$t_ixt->set('moderated_by_user_id', $pn_moderator);
$t_ixt->set('moderated_on', 'now');
}
$t_ixt->update();
if ($t_ixt->numErrors()) {
$this->errors = $t_ixt->errors;
return false;
}
return true;
}
# --------------------------------------------------------------------------------------------
/**
* Deletes the tag relation specified by $pn_relation_id (a ca_items_x_tags.relation_id value) from the currently loaded row. Will only delete
* tags attached to the currently loaded row. If you attempt to delete a ca_items_x_tags.relation_id not attached to the current row
* removeTag() will return false and post an error. If you attempt to call removeTag() with no row loaded null will be returned.
* If $pn_user_id is specified then only tags created by the specified user will be deleted; if the tag being
* deleted is not created by the user then false is returned and an error posted.
*
* @param $pn_relation_id [integer] a valid ca_items_x_tags.relation_id to be removed; must be related to the currently loaded row (mandatory)
* @param $pn_user_id [integer] a valid ca_users.user_id value; if specified then only tag relations added by the specified user will be deleted (optional - default is null)
*/
public function removeTag($pn_relation_id, $pn_user_id=null) {
if (!($vn_row_id = $this->getPrimaryKey())) { return null; }
$t_ixt = new ca_items_x_tags($pn_relation_id);
if (!$t_ixt->getPrimaryKey()) {
$this->postError(2800, _t('Tag relation id is invalid'), 'BaseModel->removeTag()');
return false;
}
if (
($t_ixt->get('table_num') != $this->tableNum()) ||
($t_ixt->get('row_id') != $vn_row_id)
) {
$this->postError(2810, _t('Tag is not part of the current row'), 'BaseModel->removeTag()');
return false;
}
if ($pn_user_id) {
if ($t_ixt->get('user_id') != $pn_user_id) {
$this->postError(2820, _t('Tag was not created by specified user'), 'BaseModel->removeTag()');
return false;
}
}
$t_ixt->setMode(ACCESS_WRITE);
$t_ixt->delete();
if ($t_ixt->numErrors()) {
$this->errors = $t_ixt->errors;
return false;
}
return true;
}
# --------------------------------------------------------------------------------------------
/**
* Removes all tags associated with the currently loaded row. Will return null if no row is currently loaded.
* If the optional $ps_user_id parameter is passed then only tags added by the specified user will be removed.
*
* @param $pn_user_id [integer] A valid ca_users.user_id value. If specified, only tags added by the specified user will be removed. (optional - default is null)
*/
public function removeAllTags($pn_user_id=null) {
if (!($vn_row_id = $this->getPrimaryKey())) { return null; }
$va_tags = $this->getTags($pn_user_id);
foreach($va_tags as $va_tag) {
if (!$this->removeTag($va_tag['tag_id'], $pn_user_id)) {
return false;
}
}
return true;
}
# --------------------------------------------------------------------------------------------
/**
* Returns all tags associated with the currently loaded row. Will return null if not row is currently loaded.
* If the optional $ps_user_id parameter is passed then only tags created by the specified user will be returned.
* If the optional $pb_moderation_status parameter is passed then only tags matching the criteria will be returned:
* Passing $pb_moderation_status = TRUE will cause only moderated tags to be returned
* Passing $pb_moderation_status = FALSE will cause only unmoderated tags to be returned
* If you want both moderated and unmoderated tags to be returned then omit the parameter or pass a null value
*
* @param $pn_user_id [integer] A valid ca_users.user_id value. If specified, only tags added by the specified user will be returned. (optional - default is null)
* @param $pn_moderation_status [boolean] To return only unmoderated tags set to FALSE; to return only moderated tags set to TRUE; to return all tags set to null or omit
*/
public function getTags($pn_user_id=null, $pb_moderation_status=null, $pn_row_id=null) {
if (!($vn_row_id = $pn_row_id)) {
if (!($vn_row_id = $this->getPrimaryKey())) { return null; }
}
$o_db = $this->getDb();
$vs_user_sql = ($pn_user_id) ? ' AND (cixt.user_id = '.intval($pn_user_id).')' : '';
$vs_moderation_sql = '';
if (!is_null($pb_moderation_status)) {
$vs_moderation_sql = ($pb_moderation_status) ? ' AND (cixt.moderated_on IS NOT NULL)' : ' AND (cixt.moderated_on IS NULL)';
}
$qr_comments = $o_db->query("
SELECT *
FROM ca_item_tags cit
INNER JOIN ca_items_x_tags AS cixt ON cit.tag_id = cixt.tag_id
WHERE
(cixt.table_num = ?) AND (cixt.row_id = ?) {$vs_user_sql} {$vs_moderation_sql}
", $this->tableNum(), $vn_row_id);
return $qr_comments->getAllRows();
}
# --------------------------------------------------------------------------------------------
# User commenting
# --------------------------------------------------------------------------------------------
/**
* Adds a comment to currently loaded row. Returns null if no row is loaded. Otherwise returns true
* if comment was successfully added, false if an error occurred in which case the errors will be available
* via the model's standard error methods (getErrors() and friends.
*
* Most of the parameters are optional with the exception of $ps_comment - the text of the comment. Note that
* comment text is monolingual; if you want to do multilingual comments (which aren't really comments then, are they?) then
* you should add multiple comments.
*
* @param $ps_comment [string] Text of the comment (mandatory)
* @param $pn_rating [integer] A number between 1 and 5 indicating the user's rating of the row; larger is better (optional - default is null)
* @param $pn_user_id [integer] A valid ca_users.user_id indicating the user who posted the comment; is null for comments from non-logged-in users (optional - default is null)
* @param $pn_locale_id [integer] A valid ca_locales.locale_id indicating the language of the comment. If omitted or left null then the value in the global $g_ui_locale_id variable is used. If $g_ui_locale_id is not set and $pn_locale_id is not set then an error will occur (optional - default is to use $g_ui_locale_id)
* @param $ps_name [string] Name of user posting comment. Only needs to be set if $pn_user_id is *not* set; used to identify comments posted by non-logged-in users (optional - default is null)
* @param $ps_email [string] E-mail address of user posting comment. Only needs to be set if $pn_user_id is *not* set; used to identify comments posted by non-logged-in users (optional - default is null)
* @param $pn_access [integer] Determines public visibility of comments; if set to 0 then comment is not visible to public; if set to 1 comment is visible (optional - default is 0)
* @param $pn_moderator [integer] A valid ca_users.user_id value indicating who moderated the comment; if omitted or set to null then moderation status will not be set unless app.conf setting dont_moderate_comments = 1 (optional - default is null)
* @param array $pa_options Array of options. Supported options are:
* purify = if true, comment, name and email are run through HTMLPurifier before being stored in the database. Default is true.
* media1_original_filename = original file name to set for comment "media1"
* media2_original_filename = original file name to set for comment "media2"
* media3_original_filename = original file name to set for comment "media3"
* media4_original_filename = original file name to set for comment "media4"
*/
public function addComment($ps_comment, $pn_rating=null, $pn_user_id=null, $pn_locale_id=null, $ps_name=null, $ps_email=null, $pn_access=0, $pn_moderator=null, $pa_options=null, $ps_media1=null, $ps_media2=null, $ps_media3=null, $ps_media4=null) {
global $g_ui_locale_id;
if (!($vn_row_id = $this->getPrimaryKey())) { return null; }
if (!$pn_locale_id) { $pn_locale_id = $g_ui_locale_id; }
if(!isset($pa_options['purify'])) { $pa_options['purify'] = true; }
if ((bool)$pa_options['purify']) {
$o_purifier = new HTMLPurifier();
$ps_comment = $o_purifier->purify($ps_comment);
$ps_name = $o_purifier->purify($ps_name);
$ps_email = $o_purifier->purify($ps_email);
}
$t_comment = new ca_item_comments();
$t_comment->setMode(ACCESS_WRITE);
$t_comment->set('table_num', $this->tableNum());
$t_comment->set('row_id', $vn_row_id);
$t_comment->set('user_id', $pn_user_id);
$t_comment->set('locale_id', $pn_locale_id);
$t_comment->set('comment', $ps_comment);
$t_comment->set('rating', $pn_rating);
$t_comment->set('email', $ps_email);
$t_comment->set('name', $ps_name);
$t_comment->set('access', $pn_access);
$t_comment->set('media1', $ps_media1, array('original_filename' => $pa_options['media1_original_filename']));
$t_comment->set('media2', $ps_media2, array('original_filename' => $pa_options['media2_original_filename']));
$t_comment->set('media3', $ps_media3, array('original_filename' => $pa_options['media3_original_filename']));
$t_comment->set('media4', $ps_media4, array('original_filename' => $pa_options['media4_original_filename']));
if (!is_null($pn_moderator)) {
$t_comment->set('moderated_by_user_id', $pn_moderator);
$t_comment->set('moderated_on', 'now');
}elseif($this->_CONFIG->get("dont_moderate_comments")){
$t_comment->set('moderated_on', 'now');
}
$t_comment->insert();
if ($t_comment->numErrors()) {
$this->errors = $t_comment->errors;
return false;
}
return true;
}
# --------------------------------------------------------------------------------------------
/**
* Edits an existing comment as specified by $pn_comment_id. Will only edit comments that are attached to the
* currently loaded row. If called with no row loaded editComment() will return null. If you attempt to modify
* a comment not associated with the currently loaded row editComment() will return false and post an error.
* Note that all parameters are mandatory in the sense that the value passed (or the default value if not passed)
* will be written into the comment. For example, if you don't bother passing $ps_name then it will be set to null, even
* if there's an existing name value in the field. The only exception is $pn_locale_id; if set to null or omitted then
* editComment() will attempt to use the locale value in the global $g_ui_locale_id variable. If this is not set then
* an error will be posted and editComment() will return false.
*
* @param $pn_comment_id [integer] a valid comment_id to be edited; must be related to the currently loaded row (mandatory)
* @param $ps_comment [string] the text of the comment (mandatory)
* @param $pn_rating [integer] a number between 1 and 5 indicating the user's rating of the row; higher is better (optional - default is null)
* @param $pn_user_id [integer] A valid ca_users.user_id indicating the user who posted the comment; is null for comments from non-logged-in users (optional - default is null)
* @param $pn_locale_id [integer] A valid ca_locales.locale_id indicating the language of the comment. If omitted or left null then the value in the global $g_ui_locale_id variable is used. If $g_ui_locale_id is not set and $pn_locale_id is not set then an error will occur (optional - default is to use $g_ui_locale_id)
* @param $ps_name [string] Name of user posting comment. Only needs to be set if $pn_user_id is *not* set; used to identify comments posted by non-logged-in users (optional - default is null)
* @param $ps_email [string] E-mail address of user posting comment. Only needs to be set if $pn_user_id is *not* set; used to identify comments posted by non-logged-in users (optional - default is null)
* @param $pn_access [integer] Determines public visibility of comments; if set to 0 then comment is not visible to public; if set to 1 comment is visible (optional - default is 0)
* @param $pn_moderator [integer] A valid ca_users.user_id value indicating who moderated the comment; if omitted or set to null then moderation status will not be set (optional - default is null)
* @param array $pa_options Array of options. Supported options are:
* purify = if true, comment, name and email are run through HTMLPurifier before being stored in the database. Default is true.
* media1_original_filename = original file name to set for comment "media1"
* media2_original_filename = original file name to set for comment "media2"
* media3_original_filename = original file name to set for comment "media3"
* media4_original_filename = original file name to set for comment "media4"
*/
public function editComment($pn_comment_id, $ps_comment, $pn_rating=null, $pn_user_id=null, $pn_locale_id=null, $ps_name=null, $ps_email=null, $pn_access=null, $pn_moderator=null, $pa_options=null, $ps_media1=null, $ps_media2=null, $ps_media3=null, $ps_media4=null) {
global $g_ui_locale_id;
if (!($vn_row_id = $this->getPrimaryKey())) { return null; }
if (!$pn_locale_id) { $pn_locale_id = $g_ui_locale_id; }
$t_comment = new ca_item_comments($pn_comment_id);
if (!$t_comment->getPrimaryKey()) {
$this->postError(2800, _t('Comment id is invalid'), 'BaseModel->editComment()');
return false;
}
if (
($t_comment->get('table_num') != $this->tableNum()) ||
($t_comment->get('row_id') != $vn_row_id)
) {
$this->postError(2810, _t('Comment is not part of the current row'), 'BaseModel->editComment()');
return false;
}
if(!isset($pa_options['purify'])) { $pa_options['purify'] = true; }
if ((bool)$pa_options['purify']) {
$o_purifier = new HTMLPurifier();
$ps_comment = $o_purifier->purify($ps_comment);
$ps_name = $o_purifier->purify($ps_name);
$ps_email = $o_purifier->purify($ps_email);
}
$t_comment->setMode(ACCESS_WRITE);
$t_comment->set('comment', $ps_comment);
$t_comment->set('rating', $pn_rating);
$t_comment->set('user_id', $pn_user_id);
$t_comment->set('name', $ps_name);
$t_comment->set('email', $ps_email);
$t_comment->set('media1', $ps_media1, array('original_filename' => $pa_options['media1_original_filename']));
$t_comment->set('media2', $ps_media2, array('original_filename' => $pa_options['media2_original_filename']));
$t_comment->set('media3', $ps_media3, array('original_filename' => $pa_options['media3_original_filename']));
$t_comment->set('media4', $ps_media4, array('original_filename' => $pa_options['media4_original_filename']));
if (!is_null($pn_moderator)) {
$t_comment->set('moderated_by_user_id', $pn_moderator);
$t_comment->set('moderated_on', 'now');
}
if (!is_null($pn_locale_id)) { $t_comment->set('locale_id', $pn_locale_id); }
$t_comment->update();
if ($t_comment->numErrors()) {
$this->errors = $t_comment->errors;
return false;
}
return true;
}
# --------------------------------------------------------------------------------------------
/**
* Permanently deletes the comment specified by $pn_comment_id. Will only delete comments attached to the
* currently loaded row. If you attempt to delete a comment_id not attached to the current row removeComment()
* will return false and post an error. If you attempt to call removeComment() with no row loaded null will be returned.
* If $pn_user_id is specified then only comments created by the specified user will be deleted; if the comment being
* deleted is not created by the user then false is returned and an error posted.
*
* @param $pn_comment_id [integer] a valid comment_id to be removed; must be related to the currently loaded row (mandatory)
* @param $pn_user_id [integer] a valid ca_users.user_id value; if specified then only comments by the specified user will be deleted (optional - default is null)
*/
public function removeComment($pn_comment_id, $pn_user_id=null) {
if (!($vn_row_id = $this->getPrimaryKey())) { return null; }
$t_comment = new ca_item_comments($pn_comment_id);
if (!$t_comment->getPrimaryKey()) {
$this->postError(2800, _t('Comment id is invalid'), 'BaseModel->removeComment()');
return false;
}
if (
($t_comment->get('table_num') != $this->tableNum()) ||
($t_comment->get('row_id') != $vn_row_id)
) {
$this->postError(2810, _t('Comment is not part of the current row'), 'BaseModel->removeComment()');
return false;
}
if ($pn_user_id) {
if ($t_comment->get('user_id') != $pn_user_id) {
$this->postError(2820, _t('Comment was not created by specified user'), 'BaseModel->removeComment()');
return false;
}
}
$t_comment->setMode(ACCESS_WRITE);
$t_comment->delete();
if ($t_comment->numErrors()) {
$this->errors = $t_comment->errors;
return false;
}
return true;
}
# --------------------------------------------------------------------------------------------
/**
* Removes all comments associated with the currently loaded row. Will return null if no row is currently loaded.
* If the optional $ps_user_id parameter is passed then only comments created by the specified user will be removed.
*
* @param $pn_user_id [integer] A valid ca_users.user_id value. If specified, only comments by the specified user will be removed. (optional - default is null)
*/
public function removeAllComments($pn_user_id=null) {
if (!($vn_row_id = $this->getPrimaryKey())) { return null; }
$va_comments = $this->getComments($pn_user_id);
foreach($va_comments as $va_comment) {
if (!$this->removeComment($va_comment['comment_id'], $pn_user_id)) {
return false;
}
}
return true;
}
# --------------------------------------------------------------------------------------------
/**
* Returns all comments associated with the currently loaded row. Will return null if not row is currently loaded.
* If the optional $ps_user_id parameter is passed then only comments created by the specified user will be returned.
* If the optional $pb_moderation_status parameter is passed then only comments matching the criteria will be returned:
* Passing $pb_moderation_status = TRUE will cause only moderated comments to be returned
* Passing $pb_moderation_status = FALSE will cause only unmoderated comments to be returned
* If you want both moderated and unmoderated comments to be returned then omit the parameter or pass a null value
*
* @param $pn_user_id [integer] A valid ca_users.user_id value. If specified, only comments by the specified user will be returned. (optional - default is null)
* @param $pn_moderation_status [boolean] To return only unmoderated comments set to FALSE; to return only moderated comments set to TRUE; to return all comments set to null or omit
*/
public function getComments($pn_user_id=null, $pb_moderation_status=null) {
if (!($vn_row_id = $this->getPrimaryKey())) { return null; }
$o_db = $this->getDb();
$vs_user_sql = ($pn_user_id) ? ' AND (user_id = '.intval($pn_user_id).')' : '';
$vs_moderation_sql = '';
if (!is_null($pb_moderation_status)) {
$vs_moderation_sql = ($pb_moderation_status) ? ' AND (ca_item_comments.moderated_on IS NOT NULL)' : ' AND (ca_item_comments.moderated_on IS NULL)';
}
$qr_comments = $o_db->query("
SELECT *
FROM ca_item_comments
WHERE
(table_num = ?) AND (row_id = ?) {$vs_user_sql} {$vs_moderation_sql}
", $this->tableNum(), $vn_row_id);
$va_comments = array();
while($qr_comments->nextRow()){
$va_comments[$qr_comments->get("comment_id")] = $qr_comments->getRow();
foreach(array("media1", "media2", "media3", "media4") as $vs_media_field){
$va_media_versions = array();
$va_media_versions = $qr_comments->getMediaVersions($vs_media_field);
$va_media = array();
if(is_array($va_media_versions) && (sizeof($va_media_versions) > 0)){
foreach($va_media_versions as $vs_version){
$va_image_info = array();
$va_image_info = $qr_comments->getMediaInfo($vs_media_field, $vs_version);
$va_image_info["TAG"] = $qr_comments->getMediaTag($vs_media_field, $vs_version);
$va_image_info["URL"] = $qr_comments->getMediaUrl($vs_media_field, $vs_version);
$va_media[$vs_version] = $va_image_info;
}
$va_comments[$qr_comments->get("comment_id")][$vs_media_field] = $va_media;
}
}
}
return $va_comments;
}
# --------------------------------------------------------------------------------------------
/**
* Returns average user rating of item
*/
public function getAverageRating($pb_moderation_status=true) {
if (!($vn_row_id = $this->getPrimaryKey())) { return null; }
$vs_moderation_sql = '';
if (!is_null($pb_moderation_status)) {
$vs_moderation_sql = ($pb_moderation_status) ? ' AND (ca_item_comments.moderated_on IS NOT NULL)' : ' AND (ca_item_comments.moderated_on IS NULL)';
}
$o_db = $this->getDb();
$qr_comments = $o_db->query("
SELECT avg(rating) r
FROM ca_item_comments
WHERE
(table_num = ?) AND (row_id = ?) {$vs_moderation_sql}
", $this->tableNum(), $vn_row_id);
if ($qr_comments->nextRow()) {
return round($qr_comments->get('r'));
} else {
return null;
}
}
# --------------------------------------------------------------------------------------------
/**
* Returns number of user ratings for item
*/
public function getNumRatings($pb_moderation_status=true) {
if (!($vn_row_id = $this->getPrimaryKey())) { return null; }
$vs_moderation_sql = '';
if (!is_null($pb_moderation_status)) {
$vs_moderation_sql = ($pb_moderation_status) ? ' AND (ca_item_comments.moderated_on IS NOT NULL)' : ' AND (ca_item_comments.moderated_on IS NULL)';
}
$o_db = $this->getDb();
$qr_ratings = $o_db->query("
SELECT count(*) c
FROM ca_item_comments
WHERE
(rating > 0) AND (table_num = ?) AND (row_id = ?) {$vs_moderation_sql}
", $this->tableNum(), $vn_row_id);
if ($qr_ratings->nextRow()) {
return round($qr_ratings->get('c'));
} else {
return null;
}
}
# --------------------------------------------------------------------------------------------
/**
* Return the highest rated item(s)
* Return an array of primary key values
*/
public function getHighestRated($pb_moderation_status=true, $pn_num_to_return=1, $va_access_values = array()) {
$vs_moderation_sql = '';
if (!is_null($pb_moderation_status)) {
$vs_moderation_sql = ($pb_moderation_status) ? ' AND (ca_item_comments.moderated_on IS NOT NULL)' : ' AND (ca_item_comments.moderated_on IS NULL)';
}
$vs_access_join = "";
$vs_access_where = "";
$vs_table_name = $this->tableName();
$vs_primary_key = $this->primaryKey();
if (isset($va_access_values) && is_array($va_access_values) && sizeof($va_access_values) && $this->hasField('access')) {
if ($vs_table_name && $vs_primary_key) {
$vs_access_join = 'INNER JOIN '.$vs_table_name.' as rel ON rel.'.$vs_primary_key." = ca_item_comments.row_id ";
$vs_access_where = ' AND rel.access IN ('.join(',', $va_access_values).')';
}
}
$vs_deleted_sql = '';
if ($this->hasField('deleted')) {
$vs_deleted_sql = " AND (rel.deleted = 0) ";
}
if ($vs_deleted_sql || $vs_access_where) {
$vs_access_join = 'INNER JOIN '.$vs_table_name.' as rel ON rel.'.$vs_primary_key." = ca_item_comments.row_id ";
}
$o_db = $this->getDb();
$qr_comments = $o_db->query($x="
SELECT ca_item_comments.row_id
FROM ca_item_comments
{$vs_access_join}
WHERE
(ca_item_comments.table_num = ?)
{$vs_moderation_sql}
{$vs_access_where}
{$vs_deleted_sql}
GROUP BY
ca_item_comments.row_id
ORDER BY
avg(ca_item_comments.rating) DESC, MAX(ca_item_comments.created_on) DESC
LIMIT {$pn_num_to_return}
", $this->tableNum());
$va_row_ids = array();
while ($qr_comments->nextRow()) {
$va_row_ids[] = $qr_comments->get('row_id');
}
return $va_row_ids;
}
# --------------------------------------------------------------------------------------------
/**
* Return the number of ratings
* Return an integer count
*/
public function getRatingsCount($pb_moderation_status=true) {
if (!($vn_row_id = $this->getPrimaryKey())) { return null; }
$vs_moderation_sql = '';
if (!is_null($pb_moderation_status)) {
$vs_moderation_sql = ($pb_moderation_status) ? ' AND (ca_item_comments.moderated_on IS NOT NULL)' : ' AND (ca_item_comments.moderated_on IS NULL)';
}
$o_db = $this->getDb();
$qr_comments = $o_db->query("
SELECT count(*) c
FROM ca_item_comments
WHERE
(ca_item_comments.table_num = ?) AND (ca_item_comments.row_id = ?)
{$vs_moderation_sql}
", $this->tableNum(), $vn_row_id);
if ($qr_comments->nextRow()) {
return $qr_comments->get('c');
}
return 0;
}
# --------------------------------------------------------------------------------------------
/**
* Increments the view count for this item
*
* @param int $pn_user_id User_id of user viewing item. Omit of set null if user is not logged in.
*
* @return bool True on success, false on error.
*/
public function registerItemView($pn_user_id=null) {
global $g_ui_locale_id;
if (!($vn_row_id = $this->getPrimaryKey())) { return null; }
if (!$pn_locale_id) { $pn_locale_id = $g_ui_locale_id; }
$vn_table_num = $this->tableNum();
$t_view = new ca_item_views();
$t_view->setMode(ACCESS_WRITE);
$t_view->set('table_num', $vn_table_num);
$t_view->set('row_id', $vn_row_id);
$t_view->set('user_id', $pn_user_id);
$t_view->set('locale_id', $pn_locale_id);
$t_view->insert();
if ($t_view->numErrors()) {
$this->errors = $t_view->errors;
return false;
}
$o_db = $this->getDb();
// increment count
$qr_res = $o_db->query("
SELECT *
FROM ca_item_view_counts
WHERE table_num = ? AND row_id = ?
", $vn_table_num, $vn_row_id);
if ($qr_res->nextRow()) {
$o_db->query("
UPDATE ca_item_view_counts
SET view_count = view_count + 1
WHERE table_num = ? AND row_id = ?
", $vn_table_num, $vn_row_id);
} else {
$o_db->query("
INSERT INTO ca_item_view_counts
(table_num, row_id, view_count)
VALUES
(?, ?, 1)
", $vn_table_num, $vn_row_id);
}
$o_cache = caGetCacheObject("caRecentlyViewedCache");
if (!is_array($va_recently_viewed_list = $o_cache->load('recentlyViewed'))) {
$va_recently_viewed_list = array();
}
if (!is_array($va_recently_viewed_list[$vn_table_num])) {
$va_recently_viewed_list[$vn_table_num] = array();
}
while(sizeof($va_recently_viewed_list[$vn_table_num]) > 100) {
array_pop($va_recently_viewed_list[$vn_table_num]);
}
if (!in_array($vn_row_id, $va_recently_viewed_list[$vn_table_num])) {
array_unshift($va_recently_viewed_list[$vn_table_num], $vn_row_id);
}
$o_cache->save($va_recently_viewed_list, 'recentlyViewed');
return true;
}
# --------------------------------------------------------------------------------------------
/**
* Clears view count for the currently loaded row
*
* @param int $pn_user_id If set, only views from the specified user are cleared
* @return bool True on success, false on error
*/
public function clearItemViewCount($pn_user_id=null) {
if (!($vn_row_id = $this->getPrimaryKey())) { return null; }
$o_db = $this->getDb();
$vs_user_sql = '';
if ($pn_user_id) {
$vs_user_sql = " AND user_id = ".intval($pn_user_id);
}
$qr_res = $o_db->query("
DELETE FROM ca_item_views
WHERE table_num = ? AND row_id = ? {$vs_user_sql}
", $this->tableNum(), $vn_row_id);
$qr_res = $o_db->query("
UPDATE ca_item_view_counts
SET view_count = 0
WHERE table_num = ? AND row_id = ? {$vs_user_sql}
", $this->tableNum(), $vn_row_id);
return $o_db->numErrors() ? false : true;
}
# --------------------------------------------------------------------------------------------
/**
* Get view list for currently loaded row.
*
* @param int $pn_user_id If set, only views from the specified user are returned
* @param array $pa_options Supported options are:
* restrictToTypes = array of type names or type_ids to restrict to
* hasRepresentations = if set when model is for ca_objects views are only returned when the object has at least one representation
* checkAccess = an array of access values to filter only. Views will only be returned if the item's access setting is in the array.
* @return bool True on success, false on error
*/
public function getViewList($pn_user_id=null, $pa_options=null) {
if (!($vn_row_id = $this->getPrimaryKey())) { return null; }
$o_db = $this->getDb();
$vs_limit_sql = '';
if ($pn_limit > 0) {
$vs_limit_sql = "LIMIT ".intval($pn_limit);
}
$va_wheres = array('(civc.table_num = ?)');
if (is_array($pa_options['checkAccess']) && sizeof($pa_options['checkAccess']) && ($this->hasField('access'))) {
$va_wheres[] = 't.access IN ('.join(',', $pa_options['checkAccess']).')';
}
if (method_exists($this, 'getTypeFieldName') && ($vs_type_field_name = $this->getTypeFieldName())) {
$va_types = caMergeTypeRestrictionLists($this, $pa_options);
if (is_array($va_types) && sizeof($va_types)) {
$va_wheres[] = 't.'.$vs_type_field_name.' IN ('.join(',', $va_types).')';
}
}
$vs_join_sql = '';
if (isset($pa_options['hasRepresentations']) && $pa_options['hasRepresentations'] && ($this->tableName() == 'ca_objects')) {
$vs_join_sql = ' INNER JOIN ca_objects_x_object_representations ON ca_objects_x_object_representations.object_id = t.object_id';
$va_wheres[] = 'ca_objects_x_object_representations.is_primary = 1';
}
if ($pn_user_id) {
$va_wheres[] = "civ.user_id = ".intval($pn_user_id);
}
if ($vs_where_sql = join(' AND ', $va_wheres)) {
$vs_where_sql = ' WHERE '.$vs_where_sql;
}
$qr_res = $o_db->query("
SELECT t.*, count(*) cnt
FROM ".$this->tableName()." t
INNER JOIN ca_item_views AS civ ON civ.row_id = t.".$this->primaryKey()."
WHERE
civ.table_num = ? AND row_id = ? {$vs_user_sql} {$vs_access_sql}
GROUP BY
civ.row_id
ORDER BY
cnt DESC
{$vs_limit_sql}
", $this->tableNum(), $vn_row_id);
$va_items = array();
while($qr_res->nextRow()) {
$va_items[] = $qr_res->getRow();
}
return $va_items;
}
# --------------------------------------------------------------------------------------------
/**
* Returns a list of the items with the most views.
*
* @param int $pn_limit Limit list to the specified number of items. Defaults to 10 if not specified.
* @param array $pa_options Supported options are:
* restrictToTypes = array of type names or type_ids to restrict to. Only items with a type_id in the list will be returned.
* hasRepresentations = if set when model is for ca_objects views are only returned when the object has at least one representation.
* checkAccess = an array of access values to filter only. Items will only be returned if the item's access setting is in the array.
* @return bool True on success, false on error
*/
public function getMostViewedItems($pn_limit=10, $pa_options=null) {
$o_db = $this->getDb();
$vs_limit_sql = '';
if ($pn_limit > 0) {
$vs_limit_sql = "LIMIT ".intval($pn_limit);
}
$va_wheres = array('(civc.table_num = '.intval($this->tableNum()).')');
if (is_array($pa_options['checkAccess']) && sizeof($pa_options['checkAccess']) && ($this->hasField('access'))) {
$va_wheres[] = 't.access IN ('.join(',', $pa_options['checkAccess']).')';
}
if (method_exists($this, 'getTypeFieldName') && ($vs_type_field_name = $this->getTypeFieldName())) {
$va_types = caMergeTypeRestrictionLists($this, $pa_options);
if (is_array($va_types) && sizeof($va_types)) {
$va_wheres[] = 't.'.$vs_type_field_name.' IN ('.join(',', $va_types).')';
}
}
$vs_join_sql = '';
if (isset($pa_options['hasRepresentations']) && $pa_options['hasRepresentations'] && ($this->tableName() == 'ca_objects')) {
$vs_join_sql = ' INNER JOIN ca_objects_x_object_representations ON ca_objects_x_object_representations.object_id = t.object_id';
$va_wheres[] = 'ca_objects_x_object_representations.is_primary = 1';
}
if ($this->hasField('deleted')) {
$va_wheres[] = "(t.deleted = 0)";
}
if ($vs_where_sql = join(' AND ', $va_wheres)) {
$vs_where_sql = ' WHERE '.$vs_where_sql;
}
$qr_res = $o_db->query("
SELECT t.*, civc.view_count cnt
FROM ".$this->tableName()." t
INNER JOIN ca_item_view_counts AS civc ON civc.row_id = t.".$this->primaryKey()."
{$vs_join_sql}
{$vs_where_sql}
ORDER BY
civc.view_count DESC
{$vs_limit_sql}
");
$va_most_viewed_items = array();
while($qr_res->nextRow()) {
$va_most_viewed_items[$qr_res->get($this->primaryKey())] = $qr_res->getRow();
}
return $va_most_viewed_items;
}
# --------------------------------------------------------------------------------------------
/**
* Returns the most recently viewed items, up to a maximum of $pn_limit (default is 10)
* Note that the limit is just that – a limit. getRecentlyViewedItems() may return fewer
* than the limit either because there fewer viewed items than your limit or because fetching
* additional views would take too long. (To ensure adequate performance getRecentlyViewedItems() uses a cache of
* recent views. If there is no cache available it will query the database to look at the most recent (4 x your limit) viewings.
* If there are many views of the same item in that group then it is possible that fewer items than your limit will be returned)
*
* @param int $pn_limit The maximum number of items to return. Default is 10.
* @param array $pa_options Supported options are:
* restrictToTypes = array of type names or type_ids to restrict to. Only items with a type_id in the list will be returned.
* checkAccess = array of access values to filter results by; if defined only items with the specified access code(s) are returned
* hasRepresentations = if set to a non-zero (boolean true) value only items with representations will be returned
* dontUseCache = if set to true, forces list to be generated from database; default is false.
* @return array List of primary key values for recently viewed items.
*/
public function getRecentlyViewedItems($pn_limit=10, $pa_options=null) {
if (!isset($pa_options['dontUseCache']) || !$pa_options['dontUseCache']) {
$o_cache = caGetCacheObject("caRecentlyViewedCache");
$va_recently_viewed_items = $o_cache->load('recentlyViewed');
$vn_table_num = $this->tableNum();
if(is_array($va_recently_viewed_items) && is_array($va_recently_viewed_items[$vn_table_num])) {
if(sizeof($va_recently_viewed_items[$vn_table_num]) > $pn_limit) {
$va_recently_viewed_items[$vn_table_num] = array_slice($va_recently_viewed_items[$vn_table_num], 0, $pn_limit);
}
return $va_recently_viewed_items[$vn_table_num];
}
}
$o_db = $this->getDb();
$vs_limit_sql = '';
if ($pn_limit > 0) {
$vs_limit_sql = "LIMIT ".(intval($pn_limit) * 4);
}
$va_wheres = array('(civ.table_num = '.intval($this->tableNum()).')');
if (is_array($pa_options['checkAccess']) && sizeof($pa_options['checkAccess']) && ($this->hasField('access'))) {
$va_wheres[] = 't.access IN ('.join(',', $pa_options['checkAccess']).')';
}
if (method_exists($this, 'getTypeFieldName') && ($vs_type_field_name = $this->getTypeFieldName())) {
$va_types = caMergeTypeRestrictionLists($this, $pa_options);
if (is_array($va_types) && sizeof($va_types)) {
$va_wheres[] = 't.'.$vs_type_field_name.' IN ('.join(',', $va_types).')';
}
}
$vs_join_sql = '';
if (isset($pa_options['hasRepresentations']) && $pa_options['hasRepresentations'] && ($this->tableName() == 'ca_objects')) {
$vs_join_sql = ' INNER JOIN ca_objects_x_object_representations ON ca_objects_x_object_representations.object_id = t.object_id';
$va_wheres[] = 'ca_objects_x_object_representations.is_primary = 1';
}
if ($this->hasField('deleted')) {
$va_wheres[] = "(t.deleted = 0)";
}
if ($vs_where_sql = join(' AND ', $va_wheres)) {
$vs_where_sql = ' WHERE '.$vs_where_sql;
}
$qr_res = $o_db->query($vs_sql = "
SELECT t.".$this->primaryKey()."
FROM ".$this->tableName()." t
INNER JOIN ca_item_views AS civ ON civ.row_id = t.".$this->primaryKey()."
{$vs_join_sql}
{$vs_where_sql}
ORDER BY
civ.view_id DESC
{$vs_limit_sql}
");
$va_recently_viewed_items = array();
$vn_c = 0;
while($qr_res->nextRow() && ($vn_c < $pn_limit)) {
if (!isset($va_recently_viewed_items[$vn_id = $qr_res->get($this->primaryKey())])) {
$va_recently_viewed_items[$vn_id] = true;
$vn_c++;
}
}
return array_keys($va_recently_viewed_items);
}
# --------------------------------------------------------------------------------------------
/**
* Returns a list of items recently added to the database.
*
* @param int $pn_limit Limit list to the specified number of items. Defaults to 10 if not specified.
* @param array $pa_options Supported options are:
* restrictToTypes = array of type names or type_ids to restrict to. Only items with a type_id in the list will be returned.
* hasRepresentations = if set when model is for ca_objects views are only returned when the object has at least one representation.
* checkAccess = an array of access values to filter only. Items will only be returned if the item's access setting is in the array.
* @return bool True on success, false on error
*/
public function getRecentlyAddedItems($pn_limit=10, $pa_options=null) {
$o_db = $this->getDb();
$vs_limit_sql = '';
if ($pn_limit > 0) {
$vs_limit_sql = "LIMIT ".intval($pn_limit);
}
$va_wheres = array();
if (is_array($pa_options['checkAccess']) && sizeof($pa_options['checkAccess']) && ($this->hasField('access'))) {
$va_wheres[] = 't.access IN ('.join(',', $pa_options['checkAccess']).')';
}
if (method_exists($this, 'getTypeFieldName') && ($vs_type_field_name = $this->getTypeFieldName())) {
$va_types = caMergeTypeRestrictionLists($this, $pa_options);
if (is_array($va_types) && sizeof($va_types)) {
$va_wheres[] = 't.'.$vs_type_field_name.' IN ('.join(',', $va_types).')';
}
}
$vs_join_sql = '';
if (isset($pa_options['hasRepresentations']) && $pa_options['hasRepresentations'] && ($this->tableName() == 'ca_objects')) {
$vs_join_sql = ' INNER JOIN ca_objects_x_object_representations ON ca_objects_x_object_representations.object_id = t.object_id';
$va_wheres[] = 'ca_objects_x_object_representations.is_primary = 1';
if (is_array($pa_options['checkAccess']) && sizeof($pa_options['checkAccess'])) {
$vs_join_sql .= ' INNER JOIN ca_object_representations ON ca_object_representations.representation_id = ca_objects_x_object_representations.representation_id';
$va_wheres[] = 'ca_object_representations.access IN ('.join(',', $pa_options['checkAccess']).')';
}
}
$vs_deleted_sql = '';
if ($this->hasField('deleted')) {
$va_wheres[] = "(t.deleted = 0)";
}
if ($vs_where_sql = join(' AND ', $va_wheres)) {
$vs_where_sql = " WHERE {$vs_where_sql}";
}
$vs_primary_key = $this->primaryKey();
$qr_res = $o_db->query("
SELECT t.*
FROM ".$this->tableName()." t
{$vs_join_sql}
{$vs_where_sql}
ORDER BY
t.".$vs_primary_key." DESC
{$vs_limit_sql}
");
$va_recently_added_items = array();
while($qr_res->nextRow()) {
$va_recently_added_items[$qr_res->get($this->primaryKey())] = $qr_res->getRow();
}
return $va_recently_added_items;
}
# --------------------------------------------------------------------------------------------
/**
* Return set of random rows (up to $pn_limit) subject to access restriction in $pn_access
* Set $pn_access to null or omit to return items regardless of access control status
*
* @param int $pn_limit Limit list to the specified number of items. Defaults to 10 if not specified.
* @param array $pa_options Supported options are:
* restrictToTypes = array of type names or type_ids to restrict to. Only items with a type_id in the list will be returned.
* hasRepresentations = if set when model is for ca_objects views are only returned when the object has at least one representation.
* checkAccess = an array of access values to filter only. Items will only be returned if the item's access setting is in the array.
* @return bool True on success, false on error
*/
public function getRandomItems($pn_limit=10, $pa_options=null) {
$o_db = $this->getDb();
$vs_limit_sql = '';
if ($pn_limit > 0) {
$vs_limit_sql = "LIMIT ".intval($pn_limit);
}
$vs_primary_key = $this->primaryKey();
$vs_table_name = $this->tableName();
$va_wheres = array();
if (is_array($pa_options['checkAccess']) && sizeof($pa_options['checkAccess']) && ($this->hasField('access'))) {
$va_wheres[] = $vs_table_name.'.access IN ('.join(',', $pa_options['checkAccess']).')';
}
if (method_exists($this, 'getTypeFieldName') && ($vs_type_field_name = $this->getTypeFieldName())) {
$va_types = caMergeTypeRestrictionLists($this, $pa_options);
if (is_array($va_types) && sizeof($va_types)) {
$va_wheres[] = $vs_table_name.'.'.$vs_type_field_name.' IN ('.join(',', $va_types).')';
}
}
$vs_join_sql = '';
if (isset($pa_options['hasRepresentations']) && $pa_options['hasRepresentations'] && ($this->tableName() == 'ca_objects')) {
$vs_join_sql = ' INNER JOIN ca_objects_x_object_representations ON ca_objects_x_object_representations.object_id = '.$vs_table_name.'.object_id';
}
if ($this->hasField('deleted')) {
$va_wheres[] = "{$vs_table_name}.deleted = 0";
}
$vs_sql = "
SELECT {$vs_table_name}.*
FROM (
SELECT {$vs_table_name}.{$vs_primary_key} FROM {$vs_table_name}
{$vs_join_sql}
".(sizeof($va_wheres) ? " WHERE " : "").join(" AND ", $va_wheres)."
ORDER BY RAND()
{$vs_limit_sql}
) AS random_items
INNER JOIN {$vs_table_name} ON {$vs_table_name}.{$vs_primary_key} = random_items.{$vs_primary_key}
{$vs_deleted_sql}
";
$qr_res = $o_db->query($vs_sql);
$va_random_items = array();
while($qr_res->nextRow()) {
$va_random_items[$qr_res->get($this->primaryKey())] = $qr_res->getRow();
}
return $va_random_items;
}
# --------------------------------------------------------------------------------------------
# Change log display
# --------------------------------------------------------------------------------------------
/**
* Returns change log for currently loaded row in displayable HTML format
*/
public function getChangeLogForDisplay($ps_css_id=null) {
$o_log = new ApplicationChangeLog();
return $o_log->getChangeLogForRowForDisplay($this, $ps_css_id);
}
# --------------------------------------------------------------------------------------------
#
# --------------------------------------------------------------------------------------------
/**
*
*/
static public function getLoggingUnitID() {
return md5(getmypid().microtime());
}
# --------------------------------------------------------------------------------------------
/**
*
*/
static public function getCurrentLoggingUnitID() {
global $g_change_log_unit_id;
return $g_change_log_unit_id;
}
# --------------------------------------------------------------------------------------------
/**
*
*/
static public function setChangeLogUnitID() {
global $g_change_log_unit_id;
if (!$g_change_log_unit_id) {
$g_change_log_unit_id = BaseModel::getLoggingUnitID();
return true;
}
return false;
}
# --------------------------------------------------------------------------------------------
/**
*
*/
static public function unsetChangeLogUnitID() {
global $g_change_log_unit_id;
$g_change_log_unit_id = null;
return true;
}
# --------------------------------------------------------------------------------------------
/**
* Returns number of records in table, filtering out those marked as deleted or those not meeting the specific access critera
*
* @param array $pa_access An option array of record-level access values to filter on. If omitted no filtering on access values is done.
* @return int Number of records, or null if an error occurred.
*/
public function getCount($pa_access=null) {
$o_db = new Db();
$va_wheres = array();
if (is_array($pa_access) && sizeof($pa_access) && $this->hasField('access')) {
$va_wheres[] = "(access IN (".join(',', $pa_access)."))";
}
if($this->hasField('deleted')) {
$va_wheres[] = '(deleted = 0)';
}
$vs_where_sql = join(" AND ", $va_wheres);
$qr_res = $o_db->query("
SELECT count(*) c
FROM ".$this->tableName()."
".(sizeof($va_wheres) ? ' WHERE ' : '')."
{$vs_where_sql}
");
if ($qr_res->nextRow()) {
return (int)$qr_res->get('c');
}
return null;
}
# --------------------------------------------------------------------------------------------
/**
* Sets selected attribute of field in model to new value, overriding the value coded into the model for ** the duration of the current request**
* This is useful in some unusual situations where you need to have a field behave differently than normal
* without making permanent changes to the model. Don't use this unless you know what you're doing.
*
* @param string $ps_field The field
* @param string $ps_attribute The attribute of the field
* @param string $ps_value The value to set the attribute to
* @return bool True if attribute was set, false if set failed because the field or attribute don't exist.
*/
public function setFieldAttribute($ps_field, $ps_attribute, $ps_value) {
if(isset($this->FIELDS[$ps_field][$ps_attribute])) {
$this->FIELDS[$ps_field][$ps_attribute] = $ps_value;
return true;
}
return false;
}
# --------------------------------------------------------------------------------------------
/**
* Destructor
*/
public function __destruct() {
//print "Destruct ".$this->tableName()."\n";
//print (memory_get_usage()/1024)." used in ".$this->tableName()." destructor\n";
unset($this->o_db);
unset($this->_CONFIG);
unset($this->_DATAMODEL);
unset($this->_MEDIA_VOLUMES);
unset($this->_FILE_VOLUMES);
unset($this->opo_app_plugin_manager);
unset($this->_TRANSACTION);
parent::__destruct();
}
# --------------------------------------------------------------------------------------------
}
// includes for which BaseModel must already be defined
require_once(__CA_LIB_DIR__."/core/TaskQueue.php");
require_once(__CA_APP_DIR__.'/models/ca_lists.php');
require_once(__CA_APP_DIR__.'/models/ca_locales.php');
require_once(__CA_APP_DIR__.'/models/ca_item_tags.php');
require_once(__CA_APP_DIR__.'/models/ca_items_x_tags.php');
require_once(__CA_APP_DIR__.'/models/ca_item_comments.php');
require_once(__CA_APP_DIR__.'/models/ca_item_views.php');
?>
| avpreserve/nfai | admin/app/lib/core/BaseModel.php | PHP | gpl-2.0 | 355,871 |
/****************************************************************
* This file is distributed under the following license:
*
* Copyright (C) 2010, Bernd Stramm
*
* 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 2
* 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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
****************************************************************/
#include <QRegExp>
#include <QString>
#include <QStringList>
#include "shortener.h"
#include "network-if.h"
namespace chronicon {
Shortener::Shortener (QObject *parent)
:QObject (parent),
network (0)
{
}
void
Shortener::SetNetwork (NetworkIF * net)
{
network = net;
connect (network, SIGNAL (ShortenReply (QUuid, QString, QString, bool)),
this, SLOT (CatchShortening (QUuid, QString, QString, bool)));
}
void
Shortener::ShortenHttp (QString status, bool & wait)
{
if (network == 0) {
emit DoneShortening (status);
return;
}
QRegExp regular ("(https?://)(\\S*)");
status.append (" ");
QStringList linkList;
QStringList wholeList;
int where (0), offset(0), lenSub(0);
QString link, beforeLink;
while ((where = regular.indexIn (status,offset)) > 0) {
lenSub = regular.matchedLength();
beforeLink = status.mid (offset, where - offset);
link = regular.cap(0);
if ((!link.contains ("bit.ly"))
&& (!link.contains ("twitpic.com"))
&& (link.length() > QString("http://bit.ly/12345678").length())) {
linkList << link;
}
wholeList << beforeLink;
wholeList << link;
offset = where + lenSub;
}
wholeList << status.mid (offset, -1);
shortenTag = QUuid::createUuid();
if (linkList.isEmpty ()) {
wait = false;
} else {
messageParts[shortenTag] = wholeList;
linkParts [shortenTag] = linkList;
network->ShortenHttp (shortenTag,linkList);
wait = true;
}
}
void
Shortener::CatchShortening (QUuid tag, QString shortUrl, QString longUrl, bool good)
{
/// replace the longUrl with shortUrl in the messageParts[tag]
// remove the longUrl from the linkParts[tag]
// if the linkParts[tag] is empty, we have replaced all the links
// so send append all the messageParts[tag] and finish the message
if (messageParts.find(tag) == messageParts.end()) {
return; // extra, perhaps duplicates in original, or not for me
}
if (linkParts.find(tag) == linkParts.end()) {
return;
}
QStringList::iterator chase;
for (chase = messageParts[tag].begin();
chase != messageParts[tag].end();
chase++) {
if (*chase == longUrl) {
*chase = shortUrl;
}
}
linkParts[tag].removeAll (longUrl);
if (linkParts[tag].isEmpty()) {
QString message = messageParts[tag].join (QString());
emit DoneShortening (message);
messageParts.erase (tag);
}
}
} // namespace
| berndhs/chronicon | chronicon/src/shortener.cpp | C++ | gpl-2.0 | 3,400 |
<?php // $Id$
require_once("../../config.php");
require_once("lib.php");
require_once($CFG->libdir.'/gradelib.php');
$id = required_param('id', PARAM_INT); // course
if (! $course = get_record("course", "id", $id)) {
error("Course ID is incorrect");
}
require_course_login($course);
add_to_log($course->id, "assignment", "view all", "index.php?id=$course->id", "");
$strassignments = get_string("modulenameplural", "assignment");
$strassignment = get_string("modulename", "assignment");
$strassignmenttype = get_string("assignmenttype", "assignment");
$strweek = get_string("week");
$strtopic = get_string("topic");
$strname = get_string("name");
$strduedate = get_string("duedate", "assignment");
$strsubmitted = get_string("submitted", "assignment");
$strgrade = get_string("grade");
$navlinks = array();
$navlinks[] = array('name' => $strassignments, 'link' => '', 'type' => 'activity');
$navigation = build_navigation($navlinks);
print_header_simple($strassignments, "", $navigation, "", "", true, "", navmenu($course));
if (!$cms = get_coursemodules_in_course('assignment', $course->id, 'm.assignmenttype, m.timedue')) {
notice(get_string('noassignments', 'assignment'), "../../course/view.php?id=$course->id");
die;
}
$timenow = time();
$table = new object;
if ($course->format == "weeks") {
$table->head = array ($strweek, $strname, $strassignmenttype, $strduedate, $strsubmitted, $strgrade);
$table->align = array ("center", "left", "left", "left", "right");
} else if ($course->format == "topics") {
$table->head = array ($strtopic, $strname, $strassignmenttype, $strduedate, $strsubmitted, $strgrade);
$table->align = array ("center", "left", "left", "left", "right");
} else {
$table->head = array ($strname, $strassignmenttype, $strduedate, $strsubmitted, $strgrade);
$table->align = array ("left", "left", "left", "right");
}
$currentsection = "";
$types = assignment_types();
$modinfo = get_fast_modinfo($course);
foreach ($modinfo->instances['assignment'] as $cm) {
if (!$cm->uservisible) {
continue;
}
$cm->timedue = $cms[$cm->id]->timedue;
$cm->assignmenttype = $cms[$cm->id]->assignmenttype;
$cm->idnumber = get_field('course_modules', 'idnumber', 'id', $cm->id); //hack
//Show dimmed if the mod is hidden
$class = $cm->visible ? '' : 'class="dimmed"';
$link = "<a $class href=\"view.php?id=$cm->id\">".format_string($cm->name)."</a>";
$printsection = "";
if ($cm->sectionnum !== $currentsection) {
if ($cm->sectionnum) {
$printsection = $cm->sectionnum;
}
if ($currentsection !== "") {
$table->data[] = 'hr';
}
$currentsection = $cm->sectionnum;
}
if (!file_exists($CFG->dirroot.'/mod/assignment/type/'.$cm->assignmenttype.'/assignment.class.php')) {
continue;
}
require_once ($CFG->dirroot.'/mod/assignment/type/'.$cm->assignmenttype.'/assignment.class.php');
$assignmentclass = 'assignment_'.$cm->assignmenttype;
$assignmentinstance = new $assignmentclass($cm->id, NULL, $cm, $course);
$submitted = $assignmentinstance->submittedlink(true);
$grading_info = grade_get_grades($course->id, 'mod', 'assignment', $cm->instance, $USER->id);
if (isset($grading_info->items[0]) && !$grading_info->items[0]->grades[$USER->id]->hidden ) {
$grade = $grading_info->items[0]->grades[$USER->id]->str_grade;
}
else {
$grade = '-';
}
$type = $types[$cm->assignmenttype];
$due = $cm->timedue ? userdate($cm->timedue) : '-';
if ($course->format == "weeks" or $course->format == "topics") {
$table->data[] = array ($printsection, $link, $type, $due, $submitted, $grade);
} else {
$table->data[] = array ($link, $type, $due, $submitted, $grade);
}
}
echo "<br />";
print_table($table);
print_footer($course);
?>
| IOC/moodle19 | mod/assignment/index.php | PHP | gpl-2.0 | 4,258 |
void RedboxFactory::add (Addr addr, ActionType t)
{
switch (t)
{
case ActionType::RD8 :
return add_read (addr, 1);
case ActionType::RD16 :
return add_read (addr, 2);
case ActionType::RD32 :
return add_read (addr, 4);
case ActionType::RD64 :
return add_read (addr, 8);
case ActionType::WR8 :
return add_write (addr, 1);
case ActionType::WR16 :
return add_write (addr, 2);
case ActionType::WR32 :
return add_write (addr, 4);
case ActionType::WR64 :
return add_write (addr, 8);
default :
SHOW (t, "d");
ASSERT (0);
}
}
void RedboxFactory::add_read (Addr addr, unsigned size)
{
ASSERT (size);
read_regions.emplace_back (addr, size);
}
void RedboxFactory::add_write (Addr addr, unsigned size)
{
ASSERT (size);
write_regions.emplace_back (addr, size);
}
void RedboxFactory::clear ()
{
read_regions.clear ();
write_regions.clear ();
}
Redbox *RedboxFactory::create ()
{
Redbox *b;
// Special case: we return a null pointer if both memory pools are empty.
// In this case the event will continue being labelled by a null pointer
// rather than a pointer to a Redbox. This is useful during the data race
// detection in DataRaceAnalysis::find_data_races(), because that way we
// don't even need to look inside of the red box to see if it has events, the
// event will straightfowardly be discarde for DR detection
if (read_regions.empty() and write_regions.empty()) return nullptr;
// allocate a new Redbox and keep the pointer to it, we are the container
b = new Redbox ();
boxes.push_back (b);
// compress the lists of memory areas
compress (read_regions);
compress (write_regions);
// copy them to the new redbox
b->readpool = read_regions;
b->writepool = write_regions;
#ifdef CONFIG_DEBUG
if (verb_debug) b->dump ();
// this will assert that the memory pools are a sorted sequence of disjoint
// memory areas
b->readpool.assertt ();
b->writepool.assertt ();
#endif
// restart the internal arrays
read_regions.clear ();
write_regions.clear ();
ASSERT (empty());
return b;
}
void RedboxFactory::compress (MemoryPool::Container ®ions)
{
unsigned i, j;
size_t s;
// nothing to do if we have no regions; code below assumes we have at least 1
if (regions.empty ()) return;
// sort the memory regions by increasing value of lower bound
struct compare {
bool operator() (const MemoryRegion<Addr> &a, const MemoryRegion<Addr> &b)
{
return a.lower < b.lower;
}
} cmp;
std::sort (regions.begin(), regions.end(), cmp);
// compress regions
s = regions.size ();
breakme ();
for (i = 0, j = 1; j < s; ++j)
{
ASSERT (i < j);
ASSERT (regions[i].lower <= regions[j].lower);
// if the next region's lower bound is below i's region upper bound, we can
// extend i's range
if (regions[i].upper >= regions[j].lower)
{
regions[i].upper = std::max (regions[i].upper, regions[j].upper);
}
else
{
// otherwise there is a gap betwen interval i and interval j, so we
// need to create a new interval at offset i+1, only if i+1 != j
++i;
if (i != j)
{
// copy j into i
regions[i] = regions[j];
}
}
}
DEBUG ("redbox-factory: compressed %zu regions into %u", regions.size(), i+1);
regions.resize (i + 1);
}
| cesaro/dpu | src/redbox-factory.hpp | C++ | gpl-2.0 | 3,512 |
/*
* =====================================================================================
*
* Filename: bmp_pixmap_fill.cpp
*
* Description: Fill the whole bmp with one color.
*
* Version: 1.0
* Created: 2009年04月11日 16时45分26秒
* Revision: none
* Compiler: gcc
*
* Author: Xu Lijian (ivenvd), ivenvd@gmail.com
* Company: CUGB, China
*
* =====================================================================================
*/
#include "bmp_pixmap.h"
/*
*--------------------------------------------------------------------------------------
* Class: BmpPixmap
* Method: fill
* Description: Fill the whole bmp with one color.
*--------------------------------------------------------------------------------------
*/
BmpPixmap &
BmpPixmap::fill (const BmpPixel &pixel)
{
BmpPixmap *temp = new BmpPixmap (*this);
for (i = 0; i < height; i++) {
for (j = 0; j < width; j++) {
*temp->pdata [i][j] = pixel;
}
}
return *temp;
} /* ----- end of method BmpPixmap::fill ----- */
BmpPixmap &
BmpPixmap::fill (Byte b, Byte g, Byte r)
{
BmpPixmap *temp = new BmpPixmap (*this);
for (i = 0; i < height; i++) {
for (j = 0; j < width; j++) {
temp->pdata [i][j]->set (b, g, r);
}
}
return *temp;
} /* ----- end of method BmpPixmap::fill ----- */
| iven/dip | src/bmp_pixmap/bmp_pixmap_fill.cpp | C++ | gpl-2.0 | 1,440 |
'use strict';
angular.module('eshttp')
.filter('unixtostr', function() {
return function(str){
var dt;
dt = Date.create(str * 1000).format('{yyyy}-{MM}-{dd} {HH}:{mm}:{ss}');
if (dt == "Invalid Date") {
return 'N/A';
} else {
return dt;
}
};
});
| fangli/eshttp | eshttp_webmanager/cloudconfig/static/filters/unixtostr.js | JavaScript | gpl-2.0 | 323 |
<?php
/*
* This file is part of PHPExifTool.
*
* (c) 2012 Romain Neutron <imprec@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPExiftool\Driver\Tag\Microsoft;
use PHPExiftool\Driver\AbstractTag;
class Duration extends AbstractTag
{
protected $Id = 'mixed';
protected $Name = 'Duration';
protected $FullName = 'Microsoft::Xtra';
protected $GroupName = 'Microsoft';
protected $g0 = 'QuickTime';
protected $g1 = 'Microsoft';
protected $g2 = 'Video';
protected $Type = '?';
protected $Writable = false;
protected $Description = 'Duration';
}
| Droces/casabio | vendor/phpexiftool/phpexiftool/lib/PHPExiftool/Driver/Tag/Microsoft/Duration.php | PHP | gpl-2.0 | 707 |
/*
Copyright (c) 2003-2021, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
CKEDITOR.plugins.setLang( 'colordialog', 'en-gb', {
clear: 'Clear',
highlight: 'Highlight',
options: 'Colour Options',
selected: 'Selected Colour',
title: 'Select colour'
} );
| WBCE/WebsiteBaker_CommunityEdition | wbce/modules/ckeditor/ckeditor/plugins/colordialog/lang/en-gb.js | JavaScript | gpl-2.0 | 344 |
<?php
if(!defined('kernel_entry') || !kernel_entry) die('Not A Valid Entry Point');
require_once('include/data/cls_table_view_base.php');
class cls_view_drupal_registry_d855ab16_bba7_43de_b448_7e9b9d78edec extends cls_table_view_base
{
private $p_column_definitions = null;
function __construct()
{
$a = func_get_args();
$i = func_num_args();
if (method_exists($this,$f="__construct".$i))
{
call_user_func_array(array($this,$f),$a);
}
}
public function query($search_values,$limit,$offset)
{
require_once('include/data/table_factory/cls_table_factory.php');
$common_drupal_registry = cls_table_factory::get_common_drupal_registry();
$array_drupal_registry = $common_drupal_registry->get_drupal_registrys($this->get_db_manager(),$this->get_application(),$search_values,$limit,$offset,false);
$result_array = array();
foreach($array_drupal_registry as $drupal_registry)
{
$drupal_registry_id = $drupal_registry->get_id();
$result_array[$drupal_registry_id]['drupal_registry.name'] = $drupal_registry->get_name();
$result_array[$drupal_registry_id]['drupal_registry.type'] = $drupal_registry->get_type();
$result_array[$drupal_registry_id]['drupal_registry.filename'] = $drupal_registry->get_filename();
$result_array[$drupal_registry_id]['drupal_registry.module'] = $drupal_registry->get_module();
$result_array[$drupal_registry_id]['drupal_registry.weight'] = $drupal_registry->get_weight();
$result_array[$drupal_registry_id]['drupal_registry.id'] = $drupal_registry->get_id();
}
return $result_array;
}
public function get_column_definitions()
{
if (!is_null($this->p_column_definitions)) return $this->p_column_definitions;
{
$this->p_column_definitions = array();
$this->p_column_definitions['drupal_registry.name']['type'] = 'varchar';
$this->p_column_definitions['drupal_registry.type']['type'] = 'varchar';
$this->p_column_definitions['drupal_registry.filename']['type'] = 'varchar';
$this->p_column_definitions['drupal_registry.module']['type'] = 'varchar';
$this->p_column_definitions['drupal_registry.weight']['type'] = 'int4';
$this->p_column_definitions['drupal_registry.id']['type'] = 'uuid';
}
return $this->p_column_definitions;
}
}
?>
| dl4gbe/kernel | include/data/table_views/cls_view_drupal_registry_d855ab16_bba7_43de_b448_7e9b9d78edec.php | PHP | gpl-2.0 | 2,247 |
//--------------------------------------------------------------------------
// Copyright (C) 2015-2016 Cisco and/or its affiliates. All rights reserved.
//
// This program is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License Version 2 as published
// by the Free Software Foundation. You may not use, modify or distribute
// this program under any other version of the GNU General Public License.
//
// 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, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//--------------------------------------------------------------------------
// rule_profiler.cc author Joel Cornett <jocornet@cisco.com>
#include "rule_profiler.h"
#if HAVE_CONFIG_H
#include "config.h"
#endif
#include <algorithm>
#include <functional>
#include <iostream>
#include <sstream>
#include <vector>
#include "detection/detection_options.h"
#include "detection/treenodes.h"
#include "hash/sfghash.h"
#include "main/snort_config.h"
#include "main/thread_config.h"
#include "parser/parser.h"
#include "target_based/snort_protocols.h"
#include "profiler_printer.h"
#include "profiler_stats_table.h"
#include "rule_profiler_defs.h"
#ifdef UNIT_TEST
#include "catch/catch.hpp"
#endif
#define s_rule_table_title "Rule Profile Statistics"
static inline OtnState& operator+=(OtnState& lhs, const OtnState& rhs)
{
lhs.elapsed += rhs.elapsed;
lhs.elapsed_match += rhs.elapsed_match;
lhs.checks += rhs.checks;
lhs.matches += rhs.matches;
lhs.alerts += rhs.alerts;
return lhs;
}
namespace rule_stats
{
static const StatsTable::Field fields[] =
{
{ "#", 5, '\0', 0, std::ios_base::left },
{ "gid", 6, '\0', 0, std::ios_base::fmtflags() },
{ "sid", 6, '\0', 0, std::ios_base::fmtflags() },
{ "rev", 4, '\0', 0, std::ios_base::fmtflags() },
{ "checks", 7, '\0', 0, std::ios_base::fmtflags() },
{ "matches", 8, '\0', 0, std::ios_base::fmtflags() },
{ "alerts", 7, '\0', 0, std::ios_base::fmtflags() },
{ "time (us)", 10, '\0', 0, std::ios_base::fmtflags() },
{ "avg/check", 10, '\0', 1, std::ios_base::fmtflags() },
{ "avg/match", 10, '\0', 1, std::ios_base::fmtflags() },
{ "avg/non-match", 14, '\0', 1, std::ios_base::fmtflags() },
{ "timeouts", 9, '\0', 0, std::ios_base::fmtflags() },
{ "suspends", 9, '\0', 0, std::ios_base::fmtflags() },
{ nullptr, 0, '\0', 0, std::ios_base::fmtflags() }
};
struct View
{
OtnState state;
SigInfo sig_info;
hr_duration elapsed() const
{ return state.elapsed; }
hr_duration elapsed_match() const
{ return state.elapsed_match; }
hr_duration elapsed_no_match() const
{ return elapsed() - elapsed_match(); }
uint64_t checks() const
{ return state.checks; }
uint64_t matches() const
{ return state.matches; }
uint64_t no_matches() const
{ return checks() - matches(); }
uint64_t alerts() const
{ return state.alerts; }
uint64_t timeouts() const
{ return state.latency_timeouts; }
uint64_t suspends() const
{ return state.latency_suspends; }
hr_duration time_per(hr_duration d, uint64_t v) const
{
if ( v == 0 )
return 0_ticks;
return hr_duration(d.count() / v);
}
hr_duration avg_match() const
{ return time_per(elapsed_match(), matches()); }
hr_duration avg_no_match() const
{ return time_per(elapsed_no_match(), no_matches()); }
hr_duration avg_check() const
{ return time_per(elapsed(), checks()); }
View(const OtnState& otn_state, const SigInfo* si = nullptr) :
state(otn_state)
{
if ( si )
// FIXIT-L J does sig_info need to be initialized otherwise?
sig_info = *si;
}
};
static const ProfilerSorter<View> sorters[] =
{
{ "", nullptr },
{
"checks",
[](const View& lhs, const View& rhs)
{ return lhs.checks() >= rhs.checks(); }
},
{
"avg_check",
[](const View& lhs, const View& rhs)
{ return lhs.avg_check() >= rhs.avg_check(); }
},
{
"total_time",
[](const View& lhs, const View& rhs)
{ return lhs.elapsed().count() >= rhs.elapsed().count(); }
},
{
"matches",
[](const View& lhs, const View& rhs)
{ return lhs.matches() >= rhs.matches(); }
},
{
"no_matches",
[](const View& lhs, const View& rhs)
{ return lhs.no_matches() >= rhs.no_matches(); }
},
{
"avg_match",
[](const View& lhs, const View& rhs)
{ return lhs.avg_match() >= rhs.avg_match(); }
},
{
"avg_no_match",
[](const View& lhs, const View& rhs)
{ return lhs.avg_no_match() >= rhs.avg_no_match(); }
}
};
static void consolidate_otn_states(OtnState* states)
{
for ( unsigned i = 1; i < ThreadConfig::get_instance_max(); ++i )
states[0] += states[i];
}
static std::vector<View> build_entries()
{
assert(snort_conf);
detection_option_tree_update_otn_stats(snort_conf->detection_option_tree_hash_table);
auto* otn_map = snort_conf->otn_map;
std::vector<View> entries;
for ( auto* h = sfghash_findfirst(otn_map); h; h = sfghash_findnext(otn_map) )
{
auto* otn = static_cast<OptTreeNode*>(h->data);
assert(otn);
auto* states = otn->state;
consolidate_otn_states(states);
auto& state = states[0];
if ( !state )
continue;
// FIXIT-L J should we assert(otn->sigInfo)?
entries.emplace_back(state, &otn->sigInfo);
}
return entries;
}
// FIXIT-L J logic duplicated from ProfilerPrinter
static void print_single_entry(const View& v, unsigned n)
{
using std::chrono::duration_cast;
using std::chrono::microseconds;
std::ostringstream ss;
{
StatsTable table(fields, ss);
table << StatsTable::ROW;
table << n; // #
table << v.sig_info.generator; // gid
table << v.sig_info.id; // sid
table << v.sig_info.rev; // rev
table << v.checks(); // checks
table << v.matches(); // matches
table << v.alerts(); // alerts
table << duration_cast<microseconds>(v.elapsed()).count(); // time
table << duration_cast<microseconds>(v.avg_check()).count(); // avg/check
table << duration_cast<microseconds>(v.avg_match()).count(); // avg/match
table << duration_cast<microseconds>(v.avg_no_match()).count(); // avg/non-match
table << v.timeouts();
table << v.suspends();
}
LogMessage("%s", ss.str().c_str());
}
// FIXIT-L J logic duplicated from ProfilerPrinter
static void print_entries(std::vector<View>& entries, ProfilerSorter<View> sort, unsigned count)
{
std::ostringstream ss;
{
StatsTable table(fields, ss);
table << StatsTable::SEP;
table << s_rule_table_title;
if ( count )
table << " (worst " << count;
else
table << " (all";
if ( sort )
table << ", sorted by " << sort.name;
table << ")\n";
table << StatsTable::HEADER;
}
LogMessage("%s", ss.str().c_str());
if ( !count || count > entries.size() )
count = entries.size();
if ( sort )
std::partial_sort(entries.begin(), entries.begin() + count, entries.end(), sort);
for ( unsigned i = 0; i < count; ++i )
print_single_entry(entries[i], i + 1);
}
}
void show_rule_profiler_stats(const RuleProfilerConfig& config)
{
if ( !config.show )
return;
auto entries = rule_stats::build_entries();
// if there aren't any eval'd rules, don't sort or print
if ( entries.empty() )
return;
auto sort = rule_stats::sorters[config.sort];
// FIXIT-L J do we eventually want to be able print rule totals, too?
print_entries(entries, sort, config.count);
}
void reset_rule_profiler_stats()
{
assert(snort_conf);
auto* otn_map = snort_conf->otn_map;
for ( auto* h = sfghash_findfirst(otn_map); h; h = sfghash_findnext(otn_map) )
{
auto* otn = static_cast<OptTreeNode*>(h->data);
assert(otn);
auto* rtn = getRtnFromOtn(otn);
if ( !rtn || !is_network_protocol(rtn->proto) )
continue;
for ( unsigned i = 0; i < ThreadConfig::get_instance_max(); ++i )
{
auto& state = otn->state[i];
state = OtnState();
}
}
}
void RuleContext::stop(bool match)
{
if ( finished )
return;
finished = true;
stats.update(sw.get(), match);
}
#ifdef UNIT_TEST
namespace
{
using RuleEntryVector = std::vector<rule_stats::View>;
using RuleStatsVector = std::vector<OtnState>;
} // anonymous namespace
static inline bool operator==(const RuleEntryVector& lhs, const RuleStatsVector& rhs)
{
if ( lhs.size() != rhs.size() )
return false;
for ( unsigned i = 0; i < lhs.size(); ++i )
if ( lhs[i].state != rhs[i] )
return false;
return true;
}
static inline OtnState make_otn_state(
hr_duration elapsed, hr_duration elapsed_match,
uint64_t checks, uint64_t matches)
{
OtnState state;
state.elapsed = elapsed;
state.elapsed_match = elapsed_match;
state.checks = checks;
state.matches = matches;
return state;
}
static inline rule_stats::View make_rule_entry(
hr_duration elapsed, hr_duration elapsed_match,
uint64_t checks, uint64_t matches)
{
return {
make_otn_state(elapsed, elapsed_match, checks, matches),
nullptr
};
}
static void avoid_optimization()
{ for ( int i = 0; i < 1024; ++i ); }
TEST_CASE( "otn state", "[profiler][rule_profiler]" )
{
OtnState state_a;
state_a.elapsed = 1_ticks;
state_a.elapsed_match = 2_ticks;
state_a.elapsed_no_match = 2_ticks;
state_a.checks = 1;
state_a.matches = 2;
state_a.noalerts = 3;
state_a.alerts = 4;
SECTION( "incremental addition" )
{
OtnState state_b;
state_b.elapsed = 4_ticks;
state_b.elapsed_match = 5_ticks;
state_b.elapsed_no_match = 6_ticks;
state_b.checks = 5;
state_b.matches = 6;
state_b.noalerts = 7;
state_b.alerts = 8;
state_a += state_b;
CHECK( state_a.elapsed == 5_ticks );
CHECK( state_a.elapsed_match == 7_ticks );
CHECK( state_a.checks == 6 );
CHECK( state_a.matches == 8 );
CHECK( state_a.alerts == 12 );
}
SECTION( "reset" )
{
state_a = OtnState();
CHECK( state_a.elapsed == 0_ticks );
CHECK( state_a.elapsed_match == 0_ticks );
CHECK( state_a.checks == 0 );
CHECK( state_a.matches == 0 );
CHECK( state_a.alerts == 0 );
}
SECTION( "bool()" )
{
CHECK( state_a );
OtnState state_c = OtnState();
CHECK_FALSE( state_c );
state_c.elapsed = 1_ticks;
CHECK( state_c );
state_c.elapsed = 0_ticks;
state_c.checks = 1;
CHECK( state_c );
}
}
TEST_CASE( "rule entry", "[profiler][rule_profiler]" )
{
SigInfo sig_info;
auto entry = make_rule_entry(3_ticks, 2_ticks, 3, 2);
entry.state.alerts = 77;
entry.state.latency_timeouts = 5;
entry.state.latency_suspends = 2;
SECTION( "copy assignment" )
{
auto copy = entry;
CHECK( copy.sig_info.generator == entry.sig_info.generator );
CHECK( copy.sig_info.id == entry.sig_info.id );
CHECK( copy.sig_info.rev == entry.sig_info.rev );
CHECK( copy.state == entry.state );
}
SECTION( "copy construction" )
{
rule_stats::View copy(entry);
CHECK( copy.sig_info.generator == entry.sig_info.generator );
CHECK( copy.sig_info.id == entry.sig_info.id );
CHECK( copy.sig_info.rev == entry.sig_info.rev );
CHECK( copy.state == entry.state );
}
SECTION( "elapsed" )
{
CHECK( entry.elapsed() == 3_ticks );
}
SECTION( "elapsed_match" )
{
CHECK( entry.elapsed_match() == 2_ticks );
}
SECTION( "elapsed_no_match" )
{
CHECK( entry.elapsed_no_match() == 1_ticks );
}
SECTION( "checks" )
{
CHECK( entry.checks() == 3 );
}
SECTION( "matches" )
{
CHECK( entry.matches() == 2 );
}
SECTION( "no_matches" )
{
CHECK( entry.no_matches() == 1 );
}
SECTION( "alerts" )
{
CHECK( entry.alerts() == 77 );
}
SECTION( "timeouts" )
{
CHECK( entry.timeouts() == 5 );
}
SECTION( "suspends" )
{
CHECK( entry.suspends() == 2 );
}
SECTION( "avg_match" )
{
auto ticks = entry.avg_match();
INFO( ticks.count() << " == " << (1_ticks).count() );
CHECK( ticks == 1_ticks );
}
SECTION( "avg_no_match" )
{
auto ticks = entry.avg_no_match();
INFO( ticks.count() << " == " << (1_ticks).count() );
CHECK( ticks == 1_ticks );
}
SECTION( "avg_check" )
{
auto ticks = entry.avg_check();
INFO( ticks.count() << " == " << (1_ticks).count() );
CHECK( ticks == 1_ticks );
}
}
TEST_CASE( "rule profiler sorting", "[profiler][rule_profiler]" )
{
using Sort = RuleProfilerConfig::Sort;
SECTION( "checks" )
{
RuleEntryVector entries {
make_rule_entry(0_ticks, 0_ticks, 0, 0),
make_rule_entry(0_ticks, 0_ticks, 1, 0),
make_rule_entry(0_ticks, 0_ticks, 2, 0)
};
RuleStatsVector expected {
make_otn_state(0_ticks, 0_ticks, 2, 0),
make_otn_state(0_ticks, 0_ticks, 1, 0),
make_otn_state(0_ticks, 0_ticks, 0, 0)
};
const auto& sorter = rule_stats::sorters[Sort::SORT_CHECKS];
std::partial_sort(entries.begin(), entries.end(), entries.end(), sorter);
CHECK( entries == expected );
}
SECTION( "avg_check" )
{
RuleEntryVector entries {
make_rule_entry(2_ticks, 0_ticks, 2, 0),
make_rule_entry(8_ticks, 0_ticks, 4, 0),
make_rule_entry(4_ticks, 0_ticks, 1, 0)
};
RuleStatsVector expected {
make_otn_state(4_ticks, 0_ticks, 1, 0),
make_otn_state(8_ticks, 0_ticks, 4, 0),
make_otn_state(2_ticks, 0_ticks, 2, 0)
};
const auto& sorter = rule_stats::sorters[Sort::SORT_AVG_CHECK];
std::partial_sort(entries.begin(), entries.end(), entries.end(), sorter);
CHECK( entries == expected );
}
SECTION( "total_time" )
{
RuleEntryVector entries {
make_rule_entry(0_ticks, 0_ticks, 0, 0),
make_rule_entry(1_ticks, 0_ticks, 0, 0),
make_rule_entry(2_ticks, 0_ticks, 0, 0)
};
RuleStatsVector expected {
make_otn_state(2_ticks, 0_ticks, 0, 0),
make_otn_state(1_ticks, 0_ticks, 0, 0),
make_otn_state(0_ticks, 0_ticks, 0, 0)
};
const auto& sorter = rule_stats::sorters[Sort::SORT_TOTAL_TIME];
std::partial_sort(entries.begin(), entries.end(), entries.end(), sorter);
CHECK( entries == expected );
}
SECTION( "matches" )
{
RuleEntryVector entries {
make_rule_entry(0_ticks, 0_ticks, 0, 0),
make_rule_entry(0_ticks, 0_ticks, 0, 1),
make_rule_entry(0_ticks, 0_ticks, 0, 2)
};
RuleStatsVector expected {
make_otn_state(0_ticks, 0_ticks, 0, 2),
make_otn_state(0_ticks, 0_ticks, 0, 1),
make_otn_state(0_ticks, 0_ticks, 0, 0)
};
const auto& sorter = rule_stats::sorters[Sort::SORT_MATCHES];
std::partial_sort(entries.begin(), entries.end(), entries.end(), sorter);
CHECK( entries == expected );
}
SECTION( "no matches" )
{
RuleEntryVector entries {
make_rule_entry(0_ticks, 0_ticks, 4, 3),
make_rule_entry(0_ticks, 0_ticks, 3, 1),
make_rule_entry(0_ticks, 0_ticks, 4, 1)
};
RuleStatsVector expected {
make_otn_state(0_ticks, 0_ticks, 4, 1),
make_otn_state(0_ticks, 0_ticks, 3, 1),
make_otn_state(0_ticks, 0_ticks, 4, 3)
};
const auto& sorter = rule_stats::sorters[Sort::SORT_NO_MATCHES];
std::partial_sort(entries.begin(), entries.end(), entries.end(), sorter);
CHECK( entries == expected );
}
SECTION( "avg match" )
{
RuleEntryVector entries {
make_rule_entry(4_ticks, 0_ticks, 0, 2),
make_rule_entry(6_ticks, 0_ticks, 0, 2),
make_rule_entry(8_ticks, 0_ticks, 0, 2)
};
RuleStatsVector expected {
make_otn_state(8_ticks, 0_ticks, 0, 2),
make_otn_state(6_ticks, 0_ticks, 0, 2),
make_otn_state(4_ticks, 0_ticks, 0, 2)
};
const auto& sorter = rule_stats::sorters[Sort::SORT_AVG_MATCH];
std::partial_sort(entries.begin(), entries.end(), entries.end(), sorter);
CHECK( entries == expected );
}
SECTION( "avg no match" )
{
RuleEntryVector entries {
make_rule_entry(4_ticks, 0_ticks, 6, 2),
make_rule_entry(6_ticks, 0_ticks, 5, 2),
make_rule_entry(8_ticks, 0_ticks, 2, 0)
};
RuleStatsVector expected {
make_otn_state(8_ticks, 0_ticks, 2, 0),
make_otn_state(6_ticks, 0_ticks, 5, 2),
make_otn_state(4_ticks, 0_ticks, 6, 2)
};
const auto& sorter = rule_stats::sorters[Sort::SORT_AVG_NO_MATCH];
std::partial_sort(entries.begin(), entries.end(), entries.end(), sorter);
CHECK( entries == expected );
}
}
TEST_CASE( "rule profiler time context", "[profiler][rule_profiler]" )
{
dot_node_state_t stats;
stats.elapsed = 0_ticks;
stats.checks = 0;
stats.elapsed_match = 0_ticks;
SECTION( "automatically updates stats" )
{
{
RuleContext ctx(stats);
avoid_optimization();
}
INFO( "elapsed: " << stats.elapsed.count() );
CHECK( stats.elapsed > 0_ticks );
CHECK( stats.checks == 1 );
INFO( "elapsed_match: " << stats.elapsed_match.count() );
CHECK( stats.elapsed_match == 0_ticks );
}
SECTION( "explicitly calling stop" )
{
dot_node_state_t save;
SECTION( "stop(true)" )
{
{
RuleContext ctx(stats);
avoid_optimization();
ctx.stop(true);
INFO( "elapsed: " << stats.elapsed.count() );
CHECK( stats.elapsed > 0_ticks );
CHECK( stats.checks == 1 );
CHECK( stats.elapsed_match == stats.elapsed );
save = stats;
}
}
SECTION( "stop(false)" )
{
{
RuleContext ctx(stats);
avoid_optimization();
ctx.stop(false);
INFO( "elapsed: " << stats.elapsed.count() );
CHECK( stats.elapsed > 0_ticks );
CHECK( stats.checks == 1 );
CHECK( stats.elapsed_match == 0_ticks );
save = stats;
}
}
INFO( "elapsed: " << stats.elapsed.count() );
CHECK( stats.elapsed == save.elapsed );
CHECK( stats.elapsed_match == save.elapsed_match );
CHECK( stats.checks == save.checks );
}
}
#endif
| Ghorbani-Roozbahan-Gholipoor-Dashti/Snort | src/profiler/rule_profiler.cc | C++ | gpl-2.0 | 19,967 |
// Copyright (C) 2015 Dave Griffiths
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
// messy scheme interface
#include <unistd.h>
#include <sys/time.h>
#include <time.h>
#include "scheme.h"
#include "scheme-private.h"
///// starwisp stuff //////////////////////////
#ifdef ANDROID_NDK
#include <android/log.h>
#endif
#include "engine/engine.h"
#include "engine/shader.h"
#include "core/geometry.h"
#include "core/osc.h"
#include "fluxa/graph.h"
#include "fluxa/time.h"
#include "audio.h"
graph *m_audio_graph = NULL;
audio_device *m_audio_device = NULL;
char *starwisp_data = NULL;
#ifdef USE_SQLITE
#include "core/db_container.h"
db_container the_db_container;
#include "core/idmap.h"
idmap the_idmap;
#endif
pointer scheme_interface(scheme *sc, enum scheme_opcodes op) {
switch (op) {
///////////// FLUXUS
case OP_ALOG:
#ifdef ANDROID_NDK
__android_log_print(ANDROID_LOG_INFO, "starwisp", string_value(car(sc->args)));
#endif
s_return(sc,sc->F);
case OP_SEND:
if (is_string(car(sc->args))) {
if (starwisp_data!=NULL) {
#ifdef ANDROID_NDK
__android_log_print(ANDROID_LOG_INFO, "starwisp", "deleting starwisp data: something is wrong!");
#endif
free(starwisp_data);
}
starwisp_data=strdup(string_value(car(sc->args)));
}
s_return(sc,sc->F);
case OP_OPEN_DB: {
#ifdef USE_SQLITE
if (is_string(car(sc->args))) {
the_db_container.add(string_value(car(sc->args)),
new db(string_value(car(sc->args))));
s_return(sc,sc->T);
}
#endif
s_return(sc,sc->F);
}
case OP_EXEC_DB: {
#ifdef USE_SQLITE
if (is_string(car(sc->args)) &&
is_string(cadr(sc->args))) {
db *d=the_db_container.get(string_value(car(sc->args)));
if (d!=NULL)
{
s_return(sc,db_exec(sc,d));
}
}
#endif
s_return(sc,sc->F);
}
case OP_INSERT_DB: {
#ifdef USE_SQLITE
if (is_string(car(sc->args)) &&
is_string(cadr(sc->args))) {
db *d=the_db_container.get(string_value(car(sc->args)));
if (d!=NULL)
{
db_exec(sc,d);
s_return(sc,mk_integer(sc,d->last_rowid()));
}
}
#endif
s_return(sc,sc->F);
}
/* case OP_INSERT_BLOB_DB: {
#ifndef FLX_RPI
if (is_string(car(sc->args)) &&
is_string(caddr(sc->args)) &&
is_string(cadddr(sc->args)) &&
is_string(caddddr(sc->args)) &&
is_string(cadddddr(sc->args))) {
db *d=the_db_container.get(string_value(car(sc->args)));
if (d!=NULL)
{
db_exec(sc,d);
s_return(sc,mk_integer(sc,d->last_rowid()));
}
}
#endif
s_return(sc,sc->F);
} */
case OP_STATUS_DB: {
#ifdef USE_SQLITE
if (is_string(car(sc->args))) {
s_return(sc,mk_string(sc,the_db_container.status()));
}
#endif
s_return(sc,sc->F);
}
case OP_TIME: {
timeval t;
// stop valgrind complaining
t.tv_sec=0;
t.tv_usec=0;
gettimeofday(&t,NULL);
s_return(sc,cons(sc,mk_integer(sc,t.tv_sec),
cons(sc,mk_integer(sc,t.tv_usec),sc->NIL)));
}
case OP_NTP_TIME: {
spiralcore::time t;
t.set_to_now();
s_return(sc,cons(sc,mk_integer(sc,t.seconds),
cons(sc,mk_integer(sc,t.fraction),sc->NIL)));
}
case OP_NTP_TIME_ADD: {
spiralcore::time t(ivalue(car(car(sc->args))),
ivalue(cadr(car(sc->args))));
t+=rvalue(cadr(sc->args));
s_return(sc,cons(sc,mk_integer(sc,t.seconds),
cons(sc,mk_integer(sc,t.fraction),sc->NIL)));
}
case OP_NTP_TIME_DIFF: {
spiralcore::time t(ivalue(car(car(sc->args))),
ivalue(cadr(car(sc->args))));
spiralcore::time t2(ivalue(car(cadr(sc->args))),
ivalue(cadr(cadr(sc->args))));
s_return(sc,mk_real(sc,t.get_difference(t2)));
}
case OP_NTP_TIME_GTR: {
spiralcore::time t(ivalue(car(car(sc->args))),
ivalue(cadr(car(sc->args))));
spiralcore::time t2(ivalue(car(cadr(sc->args))),
ivalue(cadr(cadr(sc->args))));
if (t>t2) s_return(sc,sc->T);
else s_return(sc,sc->F);
}
case OP_DATETIME: {
timeval t;
// stop valgrind complaining
t.tv_sec=0;
t.tv_usec=0;
gettimeofday(&t,NULL);
struct tm *now = gmtime((time_t *)&t.tv_sec);
/* note: now->tm_year is the number of years SINCE 1900. On the year 2000, this
will be 100 not 0. Do a man gmtime for more information */
s_return(sc,cons(sc,mk_integer(sc,now->tm_year + 1900),
cons(sc,mk_integer(sc,now->tm_mon + 1),
cons(sc,mk_integer(sc,now->tm_mday),
cons(sc,mk_integer(sc,now->tm_hour),
cons(sc,mk_integer(sc,now->tm_min),
cons(sc,mk_integer(sc,now->tm_sec), sc->NIL)))))));
}
#ifdef USE_SQLITE
case OP_ID_MAP_ADD: {
the_idmap.add(
string_value(car(sc->args)),
ivalue(cadr(sc->args)));
s_return(sc,sc->F);
}
case OP_ID_MAP_GET: {
s_return(
sc,mk_integer(sc,the_idmap.get(
string_value(car(sc->args)))));
}
#endif
//////////////////// fluxa /////////////////////////////////////////
case OP_SYNTH_INIT: {
// name,buf,sr,synths
m_audio_device = new audio_device(string_value(car(sc->args)),
ivalue(cadr(sc->args)),
ivalue(caddr(sc->args)),
ivalue(cadddr(sc->args)));
m_audio_graph = new graph(ivalue(caddddr(sc->args)),ivalue(caddr(sc->args)));
m_audio_device->start_graph(m_audio_graph);
s_return(sc,sc->F);
} break;
case OP_AUDIO_CHECK: {
m_audio_device->check_audio();
s_return(sc,sc->F);
} break;
case OP_SYNTH_RECORD: {
m_audio_device->start_recording(string_value(car(sc->args)));
s_return(sc,sc->F);
} break;
case OP_AUDIO_EQ: {
m_audio_device->m_left_eq.set_low(rvalue(car(sc->args)));
m_audio_device->m_right_eq.set_low(rvalue(car(sc->args)));
m_audio_device->m_left_eq.set_mid(rvalue(cadr(sc->args)));
m_audio_device->m_right_eq.set_mid(rvalue(cadr(sc->args)));
m_audio_device->m_left_eq.set_high(rvalue(caddr(sc->args)));
m_audio_device->m_right_eq.set_high(rvalue(caddr(sc->args)));
s_return(sc,sc->F);
} break;
case OP_AUDIO_COMP: {
m_audio_device->m_left_comp.set_attack(rvalue(car(sc->args)));
m_audio_device->m_right_comp.set_attack(rvalue(car(sc->args)));
m_audio_device->m_left_comp.set_release(rvalue(cadr(sc->args)));
m_audio_device->m_right_comp.set_release(rvalue(cadr(sc->args)));
m_audio_device->m_left_comp.set_threshold(rvalue(caddr(sc->args)));
m_audio_device->m_right_comp.set_threshold(rvalue(caddr(sc->args)));
m_audio_device->m_left_comp.set_slope(rvalue(cadddr(sc->args)));
m_audio_device->m_right_comp.set_slope(rvalue(cadddr(sc->args)));
s_return(sc,sc->F);
} break;
case OP_SYNTH_CRT: {
m_audio_graph
->create(ivalue(car(sc->args)),
(graph::node_type)(ivalue(cadr(sc->args))),
rvalue(caddr(sc->args)));
s_return(sc,sc->F);
} break;
case OP_SYNTH_CON: {
m_audio_graph
->connect(ivalue(car(sc->args)),
ivalue(cadr(sc->args)),
ivalue(caddr(sc->args)));
s_return(sc,sc->F);
} break;
case OP_SYNTH_PLY: {
m_audio_graph
->play(ivalue(car(sc->args)),
ivalue(cadr(sc->args)),
ivalue(caddr(sc->args)),
rvalue(cadddr(sc->args)));
s_return(sc,sc->F);
} break;
case OP_SLEEP: {
usleep(ivalue(car(sc->args)));
s_return(sc,sc->F);
} break;
case OP_FMOD: {
s_return(sc,mk_real(sc,fmod(rvalue(car(sc->args)),rvalue(cadr(sc->args)))));
} break;
case OP_OSC_SEND: {
const char *url=string_value(car(sc->args));
const char *name=string_value(cadr(sc->args));
const char *types=string_value(caddr(sc->args));
pointer data=cadddr(sc->args);
// figure out size of the data packet
u32 data_size=0;
for (u32 i=0; i<strlen(types); ++i) {
switch(types[i]) {
case 'f': data_size+=sizeof(float); break;
case 'i': data_size+=sizeof(int); break;
case 'l': data_size+=sizeof(long long); break;
case 's': data_size+=strlen(string_value(list_ref(sc,data,i)))+1; break;
}
}
// build data packet
char *packet = new char[data_size];
u32 data_pos=0;
for (u32 i=0; i<strlen(types); ++i) {
switch(types[i]) {
case 'f': {
float v=rvalue(list_ref(sc,data,i));
memcpy(packet+data_pos,&v,sizeof(float));
data_pos+=sizeof(float);
} break;
case 'i': {
int v=ivalue(list_ref(sc,data,i));
memcpy(packet+data_pos,&v,sizeof(int));
data_pos+=sizeof(int);
} break;
case 'l':
/*float v=ivalue(list_ref(sc,data,i));
memcpy(packet+data_pos,&v,sizeof(float));
data_pos+=sizeof(long long); */
break;
case 's': {
char *str=string_value(list_ref(sc,data,i));
memcpy(packet+data_pos,str,strlen(str));
data_pos+=strlen(string_value(list_ref(sc,data,i)));
packet[data_pos]=0; // null terminator
data_pos++;
} break;
}
}
network_osc::send(url,name,types,packet,data_size);
delete[] packet;
s_return(sc,sc->F);
} break;
//////////////////// fluxus /////////////////////////////////////////
case OP_PUSH:
engine::get()->push(); s_return(sc,sc->F);
case OP_POP:
engine::get()->pop(); s_return(sc,sc->F);
case OP_GRAB:
engine::get()->grab(ivalue(car(sc->args))); s_return(sc,sc->F);
case OP_UNGRAB:
engine::get()->ungrab(); s_return(sc,sc->F);
case OP_PARENT:
engine::get()->parent(ivalue(car(sc->args))); s_return(sc,sc->F);
case OP_LOCK_CAMERA:
engine::get()->lock_camera(ivalue(car(sc->args))); s_return(sc,sc->F);
case OP_IDENTITY:
engine::get()->identity(); s_return(sc,sc->F);
case OP_TRANSLATE:
engine::get()->translate(rvalue(vector_elem(car(sc->args),0)),
rvalue(vector_elem(car(sc->args),1)),
rvalue(vector_elem(car(sc->args),2)));
s_return(sc,sc->F);
case OP_SCALE:
if (!is_vector(car(sc->args))) // uniform scale with one arg
{
engine::get()->scale(rvalue(car(sc->args)),
rvalue(car(sc->args)),
rvalue(car(sc->args)));
} else {
engine::get()->scale(rvalue(vector_elem(car(sc->args),0)),
rvalue(vector_elem(car(sc->args),1)),
rvalue(vector_elem(car(sc->args),2)));
}
s_return(sc,sc->F);
case OP_ROTATE:
engine::get()->rotate(rvalue(vector_elem(car(sc->args),0)),
rvalue(vector_elem(car(sc->args),1)),
rvalue(vector_elem(car(sc->args),2)));
s_return(sc,sc->F);
case OP_AIM:
engine::get()->aim(rvalue(vector_elem(car(sc->args),0)),
rvalue(vector_elem(car(sc->args),1)),
rvalue(vector_elem(car(sc->args),2)),
rvalue(vector_elem(cadr(sc->args),0)),
rvalue(vector_elem(cadr(sc->args),1)),
rvalue(vector_elem(cadr(sc->args),2)));
s_return(sc,sc->F);
case OP_CONCAT:
{
mat44 t = mat44(rvalue(vector_elem(car(sc->args),0)),
rvalue(vector_elem(car(sc->args),1)),
rvalue(vector_elem(car(sc->args),2)),
rvalue(vector_elem(car(sc->args),3)),
rvalue(vector_elem(car(sc->args),4)),
rvalue(vector_elem(car(sc->args),5)),
rvalue(vector_elem(car(sc->args),6)),
rvalue(vector_elem(car(sc->args),7)),
rvalue(vector_elem(car(sc->args),8)),
rvalue(vector_elem(car(sc->args),9)),
rvalue(vector_elem(car(sc->args),10)),
rvalue(vector_elem(car(sc->args),11)),
rvalue(vector_elem(car(sc->args),12)),
rvalue(vector_elem(car(sc->args),13)),
rvalue(vector_elem(car(sc->args),14)),
rvalue(vector_elem(car(sc->args),15)));
t.transpose();
engine::get()->concat(t);
s_return(sc,sc->F);
}
case OP_COLOUR:
engine::get()->colour(rvalue(vector_elem(car(sc->args),0)),
rvalue(vector_elem(car(sc->args),1)),
rvalue(vector_elem(car(sc->args),2)),
rvalue(vector_elem(car(sc->args),3)));
s_return(sc,sc->F);
case OP_HINT:
{
u32 h=ivalue(car(sc->args));
switch (h)
{
case 0: engine::get()->hint(HINT_NONE); break; //???
case 1: engine::get()->hint(HINT_SOLID); break;
case 2: engine::get()->hint(HINT_WIRE); break;
case 3: engine::get()->hint(HINT_NORMAL); break;
case 4: engine::get()->hint(HINT_POINTS); break;
case 5: engine::get()->hint(HINT_AALIAS); break;
case 6: engine::get()->hint(HINT_BOUND); break;
case 7: engine::get()->hint(HINT_UNLIT); break;
case 8: engine::get()->hint(HINT_VERTCOLS); break;
case 9: engine::get()->hint(HINT_ORIGIN); break;
case 10: engine::get()->hint(HINT_CAST_SHADOW); break;
case 11: engine::get()->hint(HINT_IGNORE_DEPTH); break;
case 12: engine::get()->hint(HINT_DEPTH_SORT); break;
case 13: engine::get()->hint(HINT_LAZY_PARENT); break;
case 14: engine::get()->hint(HINT_CULL_CCW); break;
case 15: engine::get()->hint(HINT_WIRE_STIPPLED); break;
case 16: engine::get()->hint(HINT_SPHERE_MAP); break;
case 17: engine::get()->hint(HINT_FRUSTUM_CULL); break;
case 18: engine::get()->hint(HINT_NORMALISE); break;
case 19: engine::get()->hint(HINT_NOBLEND); break;
case 20: engine::get()->hint(HINT_NOZWRITE); break;
}
s_return(sc,sc->F);
}
case OP_DESTROY:
engine::get()->destroy(rvalue(car(sc->args)));
s_return(sc,sc->F);
case OP_LINE_WIDTH:
engine::get()->line_width(rvalue(car(sc->args)));
s_return(sc,sc->F);
case OP_TEXTURE:
engine::get()->texture(rvalue(car(sc->args)));
s_return(sc,sc->F);
case OP_SHADER:
engine::get()->set_shader(string_value(car(sc->args)),
string_value(cadr(sc->args)));
s_return(sc,sc->F);
case OP_SHADER_SET: {
shader *shader = engine::get()->get_current_shader();
shader->apply();
char *name = string_value(car(sc->args));
pointer arg=cadr(sc->args);
if (is_vector(arg)) {
switch (ivalue(arg)) {
case 3: {
vec3 vec(rvalue(vector_elem(arg,0)),
rvalue(vector_elem(arg,1)),
rvalue(vector_elem(arg,2)));
shader->set_vector(name,vec);
} break;
case 16: {
mat44 mat(rvalue(vector_elem(arg,0)),
rvalue(vector_elem(arg,1)),
rvalue(vector_elem(arg,2)),
rvalue(vector_elem(arg,3)),
rvalue(vector_elem(arg,4)),
rvalue(vector_elem(arg,5)),
rvalue(vector_elem(arg,6)),
rvalue(vector_elem(arg,7)),
rvalue(vector_elem(arg,8)),
rvalue(vector_elem(arg,9)),
rvalue(vector_elem(arg,10)),
rvalue(vector_elem(arg,11)),
rvalue(vector_elem(arg,12)),
rvalue(vector_elem(arg,13)),
rvalue(vector_elem(arg,14)),
rvalue(vector_elem(arg,15)));
shader->set_matrix(name,mat);
} break;
}
} else {
if (is_number(arg)) {
if (num_is_integer(arg))
{
shader->set_int(name,ivalue(arg));
}
else
{
shader->set_float(name,rvalue(arg));
}
}
}
shader->unapply();
s_return(sc,sc->F);
}
case OP_LOAD_TEXTURE:
s_return(sc,mk_integer(sc,engine::get()->get_texture(string_value(car(sc->args)))));
case OP_DRAW_INSTANCE:
engine::get()->draw_instance(ivalue(car(sc->args)));
s_return(sc,sc->F);
case OP_BUILD_CUBE:
s_return(sc,mk_integer(sc,engine::get()->build_cube()));
case OP_LOAD_OBJ:
s_return(sc,mk_integer(sc,engine::get()->load_obj(string_value(car(sc->args)))));
case OP_RAW_OBJ:
s_return(sc,mk_integer(sc,engine::get()->raw_obj(string_value(car(sc->args)))));
case OP_BUILD_TEXT:
s_return(sc,mk_integer(sc,engine::get()->build_text(
string_value(car(sc->args)))));
case OP_BUILD_JELLYFISH:
s_return(sc,mk_integer(sc,engine::get()->build_jellyfish(ivalue(car(sc->args)))));
case OP_BUILD_INSTANCE:
s_return(sc,mk_integer(sc,engine::get()->build_instance(ivalue(car(sc->args)))));
case OP_BUILD_POLYGONS:
s_return(sc,mk_integer(sc,engine::get()->build_polygons(
ivalue(car(sc->args)),
ivalue(cadr(sc->args))
)));
case OP_GET_TRANSFORM:
{
flx_real *m=&(engine::get()->get_transform()->m[0][0]);
pointer v=mk_vector(sc,16);
int i=0;
for (i=0; i<16; i++)
{
set_vector_elem(v,i,mk_real(sc,m[i]));
}
s_return(sc,v);
}
case OP_GET_GLOBAL_TRANSFORM:
{
mat44 mat=engine::get()->get_global_transform();
flx_real *m=&(mat.m[0][0]);
pointer v=mk_vector(sc,16);
int i=0;
for (i=0; i<16; i++)
{
set_vector_elem(v,i,mk_real(sc,m[i]));
}
s_return(sc,v);
}
case OP_GET_CAMERA_TRANSFORM:
{
flx_real *m=&(engine::get()->get_camera_transform()->m[0][0]);
pointer v=mk_vector(sc,16);
int i=0;
for (i=0; i<16; i++)
{
set_vector_elem(v,i,mk_real(sc,m[i]));
}
s_return(sc,v);
}
case OP_GET_SCREEN_SIZE:
{
unsigned int *s=engine::get()->get_screensize();
pointer v=mk_vector(sc,2);
set_vector_elem(v,0,mk_real(sc,s[0]));
set_vector_elem(v,1,mk_real(sc,s[1]));
s_return(sc,v);
}
case OP_APPLY_TRANSFORM:
engine::get()->apply_transform(); s_return(sc,sc->F);
case OP_CLEAR:
engine::get()->clear(); s_return(sc,sc->F);
case OP_CLEAR_COLOUR:
engine::get()->clear_colour(rvalue(vector_elem(car(sc->args),0)),
rvalue(vector_elem(car(sc->args),1)),
rvalue(vector_elem(car(sc->args),2)),
rvalue(vector_elem(car(sc->args),3)));
s_return(sc,sc->F);
case OP_PDATA_SIZE:
s_return(sc,mk_integer(sc,engine::get()->pdata_size()));
case OP_PDATA_ADD:
engine::get()->pdata_add(string_value(car(sc->args)));
s_return(sc,sc->F);
case OP_PDATA_REF:
{
vec3* vec=engine::get()->pdata_get(string_value(car(sc->args)),
ivalue(cadr(sc->args)));
pointer v=mk_vector(sc,3);
if (vec)
{
set_vector_elem(v,0,mk_real(sc,vec->x));
set_vector_elem(v,1,mk_real(sc,vec->y));
set_vector_elem(v,2,mk_real(sc,vec->z));
}
s_return(sc,v);
}
case OP_PDATA_SET:
{
vec3 vec(rvalue(vector_elem(caddr(sc->args),0)),
rvalue(vector_elem(caddr(sc->args),1)),
rvalue(vector_elem(caddr(sc->args),2)));
engine::get()->pdata_set(string_value(car(sc->args)),
ivalue(cadr(sc->args)),
vec);
s_return(sc,sc->F);
}
case OP_SET_TEXT:
{
engine::get()->text_set(string_value(car(sc->args)));
s_return(sc,sc->F);
}
case OP_TEXT_PARAMS:
{
engine::get()->text_params(string_value(list_ref(sc,sc->args,0)),
rvalue(list_ref(sc,sc->args,1)),
rvalue(list_ref(sc,sc->args,2)),
ivalue(list_ref(sc,sc->args,3)),
ivalue(list_ref(sc,sc->args,4)),
rvalue(list_ref(sc,sc->args,5)),
rvalue(list_ref(sc,sc->args,6)),
rvalue(list_ref(sc,sc->args,7)),
rvalue(list_ref(sc,sc->args,8)),
rvalue(list_ref(sc,sc->args,9)),
rvalue(list_ref(sc,sc->args,10)));
s_return(sc,sc->F);
}
case OP_RECALC_BB:
{
engine::get()->recalc_bb();
s_return(sc,sc->F);
}
case OP_BB_POINT_INTERSECT:
{
vec3 pvec(rvalue(vector_elem(car(sc->args),0)),
rvalue(vector_elem(car(sc->args),1)),
rvalue(vector_elem(car(sc->args),2)));
s_return(sc,mk_integer(sc,engine::get()->bb_point_intersect(pvec,rvalue(cadr(sc->args)))));
}
case OP_GEO_LINE_INTERSECT:
{
vec3 svec(rvalue(vector_elem(car(sc->args),0)),
rvalue(vector_elem(car(sc->args),1)),
rvalue(vector_elem(car(sc->args),2)));
vec3 evec(rvalue(vector_elem(cadr(sc->args),0)),
rvalue(vector_elem(cadr(sc->args),1)),
rvalue(vector_elem(cadr(sc->args),2)));
bb::list *points=engine::get()->geo_line_intersect(svec,evec);
if (points!=NULL)
{
pointer list=sc->NIL;
intersect_point *p=static_cast<intersect_point*>(points->m_head);
while (p!=NULL)
{
list=cons(sc,mk_real(sc,p->m_t),list);
pointer blend=sc->NIL;
intersect_point::blend *b=
static_cast<intersect_point::blend*>
(p->m_blends.m_head);
while (b!=NULL)
{
pointer v=mk_vector(sc,3);
set_vector_elem(v,0,mk_real(sc,b->m_blend.x));
set_vector_elem(v,1,mk_real(sc,b->m_blend.y));
set_vector_elem(v,2,mk_real(sc,b->m_blend.z));
pointer l=sc->NIL;
l=cons(sc,mk_string(sc,b->m_name),v);
blend=cons(sc,l,blend);
b=static_cast<intersect_point::blend*>(b->m_next);
}
list=cons(sc,blend,list);
p=static_cast<intersect_point*>(p->m_next);
}
s_return(sc,list);
}
s_return(sc,sc->F);
}
case OP_GET_LINE_INTERSECT:
{
vec3 svec(rvalue(vector_elem(car(sc->args),0)),
rvalue(vector_elem(car(sc->args),1)),
rvalue(vector_elem(car(sc->args),2)));
vec3 evec(rvalue(vector_elem(cadr(sc->args),0)),
rvalue(vector_elem(cadr(sc->args),1)),
rvalue(vector_elem(cadr(sc->args),2)));
s_return(sc,mk_integer(sc,engine::get()->get_line_intersect(svec,evec)));
}
case OP_MINVERSE:
{
mat44 inm;
int i=0;
for (i=0; i<16; i++)
{
inm.arr()[i]=rvalue(vector_elem(car(sc->args),i));
}
inm=inm.inverse();
pointer v=mk_vector(sc,16);
for (i=0; i<16; i++)
{
set_vector_elem(v,i,mk_real(sc,inm.arr()[i]));
}
s_return(sc,v);
}
case OP_BITWISE_IOR:
{
s_return(sc,mk_integer(sc,
ivalue(car(sc->args))|
ivalue(cadr(sc->args))|
ivalue(caddr(sc->args))
));
}
case OP_BLEND_MODE:
{
u32 src = GL_SRC_ALPHA;
u32 dst = GL_ONE_MINUS_SRC_ALPHA;
u32 s = ivalue(car(sc->args));
u32 d = ivalue(cadr(sc->args));
if (s==0) src=GL_ZERO;
else if (s==1) src=GL_ONE;
else if (s==2) src=GL_DST_COLOR;
else if (s==3) src=GL_ONE_MINUS_DST_COLOR;
else if (s==4) src=GL_SRC_ALPHA;
else if (s==5) src=GL_ONE_MINUS_SRC_ALPHA;
else if (s==6) src=GL_DST_ALPHA;
else if (s==7) src=GL_ONE_MINUS_DST_ALPHA;
else if (s==8) src=GL_SRC_ALPHA_SATURATE;
if (d==0) dst=GL_ZERO;
else if (d==1) dst=GL_ONE;
else if (d==9) dst=GL_SRC_COLOR;
else if (d==10) dst=GL_ONE_MINUS_SRC_COLOR;
else if (d==4) dst=GL_SRC_ALPHA;
else if (d==5) dst=GL_ONE_MINUS_SRC_ALPHA;
else if (d==6) dst=GL_DST_ALPHA;
else if (d==7) dst=GL_ONE_MINUS_DST_ALPHA;
engine::get()->blend_mode(src,dst);
s_return(sc,sc->F);
}
default:
snprintf(sc->strbuff,STRBUFFSIZE,"%d: illegal operator", sc->op);
Error_0(sc,sc->strbuff);
}
////////////////////
}
| nebogeo/jellyfish | src/scheme/interface.cpp | C++ | gpl-2.0 | 22,783 |
#include "TreeFactory.h"
#include "RobotFactory.h"
#include "Robot.h"
#include "kinematic/Tree.h"
#include "kinematic/Enums.h"
#include <vector>
#include <list>
using namespace matrices;
using namespace manip_core::enums;
using namespace manip_core::enums::robot;
namespace factories
{
const Vector3 unitx(1, 0, 0);
const Vector3 unity(0, 1, 0);
const Vector3 unitz(0, 0, 1);
const Vector3 unit1(sqrt(14.0)/8.0, 1.0/8.0, 7.0/8.0);
const Vector3 zero(0,0,0);
struct RobotFactoryPimpl{
RobotFactoryPimpl()
{
// NOTHING
}
~RobotFactoryPimpl()
{
// NOTHING
}
// TODO Joint that do not move
Robot* CreateHuman(const Matrix4& robotBasis) const
{
Robot* res = new Robot(robotBasis, treeFact_.CreateTree( HumanTorso, Vector3(0.0, 0., 0), 4), manip_core::enums::robot::Human);
Tree* rightLeg = treeFact_.CreateTree( RightLeg, Vector3(0.0, -0.2, 0.1), 0);
Tree* leftLeg = treeFact_.CreateTree( LeftLeg, Vector3(0.0, 0.2 , 0.1), 1);
Tree* rightArm = treeFact_.CreateTree( RightArm, Vector3(0.0, -0.4, 1.3), 2);
Tree* leftArm = treeFact_.CreateTree( LeftArm, Vector3(0.0, 0.4, 1.3), 3);
//rightArm->SetBoundaryRadius(rightArm->GetBoundaryRadius() * 8 / 10 );
//leftArm->SetBoundaryRadius(leftArm->GetBoundaryRadius() * 8 / 10 );
res->AddTree(rightLeg, matrices::Vector3(0,0,0), 0);
res->AddTree(leftLeg, matrices::Vector3(0,0,0), 0);
res->AddTree(rightArm, matrices::Vector3(0,0,1.2), 1);
res->AddTree(leftArm, matrices::Vector3(0,0,1.2), 1);
/*rightLeg->LockTarget(rightLeg->GetTarget());
leftLeg->LockTarget(leftLeg->GetTarget());*/
//rightLeg->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightLeg->GetPosition() + Vector3( -0.3, 0, -1.6)));
//leftLeg ->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), leftLeg->GetPosition() + Vector3( 0.3, 0, -1.4)));
return res;
}
Robot* CreateHumanEscalade(const Matrix4& robotBasis) const
{
Robot* res = new Robot(robotBasis, treeFact_.CreateTree( HumanTorso, Vector3(0.0, 0., 0), 4), manip_core::enums::robot::HumanEscalade);
Tree* rightLeg = treeFact_.CreateTree( RightLegEscalade, Vector3(0.0, -0.2, 0.1), 0);
Tree* leftLeg = treeFact_.CreateTree( LeftLegEscalade, Vector3(0.0, 0.2 , 0.1), 1);
Tree* rightArm = treeFact_.CreateTree( RightArmEscalade, Vector3(0.0, -0.4, 1.3), 2);
Tree* leftArm = treeFact_.CreateTree( LeftArmEscalade, Vector3(0.0, 0.4, 1.3), 3);
//rightArm->SetBoundaryRadius(rightArm->GetBoundaryRadius() * 8 / 10 );
//leftArm->SetBoundaryRadius(leftArm->GetBoundaryRadius() * 8 / 10 );
res->AddTree(rightLeg, matrices::Vector3(0,0,0), 0);
res->AddTree(leftLeg, matrices::Vector3(0,0,0), 0);
res->AddTree(rightArm, matrices::Vector3(0,0,1.2), 1);
res->AddTree(leftArm, matrices::Vector3(0,0,1.2), 1);
/*rightLeg->LockTarget(rightLeg->GetTarget());
leftLeg->LockTarget(leftLeg->GetTarget());*/
//rightLeg->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightLeg->GetPosition() + Vector3( -0.3, 0, -1.6)));
//leftLeg ->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), leftLeg->GetPosition() + Vector3( 0.3, 0, -1.4)));
return res;
}
Robot* CreateHumanCanap(const Matrix4& robotBasis) const
{
Robot* res = new Robot(robotBasis, treeFact_.CreateTree( HumanTorso, Vector3(0.0, 0., 0), 4), manip_core::enums::robot::HumanCanap);
Tree* rightLeg = treeFact_.CreateTree( RightLegCanap, Vector3(0.0, -0.2, 0.1), 0);
Tree* leftLeg = treeFact_.CreateTree( LeftLegCanap, Vector3(0.0, 0.2 , 0.1), 1);
Tree* rightArm = treeFact_.CreateTree( RightArmCanap, Vector3(0.0, -0.4, 1.3), 2);
Tree* leftArm = treeFact_.CreateTree( LeftArmCanap, Vector3(0.0, 0.4, 1.3), 3);
//rightArm->SetBoundaryRadius(rightArm->GetBoundaryRadius() * 8 / 10 );
//leftArm->SetBoundaryRadius(leftArm->GetBoundaryRadius() * 8 / 10 );
res->AddTree(rightLeg, matrices::Vector3(0,0,0), 0);
res->AddTree(leftLeg, matrices::Vector3(0,0,0), 0);
res->AddTree(rightArm, matrices::Vector3(0,0,1.2), 1);
res->AddTree(leftArm, matrices::Vector3(0,0,1.2), 1);
/*rightLeg->LockTarget(rightLeg->GetTarget());
leftLeg->LockTarget(leftLeg->GetTarget());*/
//rightLeg->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightLeg->GetPosition() + Vector3( -0.3, 0, -1.6)));
//leftLeg ->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), leftLeg->GetPosition() + Vector3( 0.3, 0, -1.4)));
return res;
}
Robot* CreateHumanCrouch(const Matrix4& robotBasis) const
{
Robot* res = new Robot(robotBasis, treeFact_.CreateTree( HumanTorsoCrouch, Vector3(0.0, 0., 0), 4), manip_core::enums::robot::Human);
Tree* rightLeg = treeFact_.CreateTree( RightLegCrouch, Vector3(0.1, -0.2, 0.), 0);
Tree* leftLeg = treeFact_.CreateTree( LeftLegCrouch, Vector3(0.1, 0.2 , 0.), 1);
Tree* rightArm = treeFact_.CreateTree( RightArmCrouch, Vector3(1.3, -0.4, 0.), 2);
Tree* leftArm = treeFact_.CreateTree( LeftArmCrouch, Vector3(1.3, 0.4, 0.), 3);
//rightArm->SetBoundaryRadius(rightArm->GetBoundaryRadius() * 8 / 10 );
//leftArm->SetBoundaryRadius(leftArm->GetBoundaryRadius() * 8 / 10 );
res->AddTree(rightLeg, matrices::Vector3(0,0,0), 0);
res->AddTree(leftLeg, matrices::Vector3(0,0,0), 0);
res->AddTree(rightArm, matrices::Vector3(1.2,0,0), 1);
res->AddTree(leftArm, matrices::Vector3(1.2,0,0), 1);
/*rightLeg->LockTarget(rightLeg->GetTarget());
leftLeg->LockTarget(leftLeg->GetTarget());*/
//rightLeg->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightLeg->GetPosition() + Vector3( -0.3, 0, -1.6)));
//leftLeg ->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), leftLeg->GetPosition() + Vector3( 0.3, 0, -1.4)));
return res;
}
Robot* CreateHumanCrouch180(const Matrix4& robotBasis) const
{
Robot* res = new Robot(robotBasis, treeFact_.CreateTree( HumanTorsoCrouch180, Vector3(0, 0., 0), 4), manip_core::enums::robot::Human);
Tree* rightLeg = treeFact_.CreateTree( RightLegCrouch180, Vector3(0.1, -0.2, 0.), 0);
Tree* leftLeg = treeFact_.CreateTree( LeftLegCrouch180, Vector3(0.1, 0.2 , 0.), 1);
Tree* rightArm = treeFact_.CreateTree( RightArmCrouch180, Vector3(1.3, -0.4, 0.), 2);
Tree* leftArm = treeFact_.CreateTree( LeftArmCrouch180, Vector3(1.3, 0.4, 0.), 3);
//rightArm->SetBoundaryRadius(rightArm->GetBoundaryRadius() * 8 / 10 );
//leftArm->SetBoundaryRadius(leftArm->GetBoundaryRadius() * 8 / 10 );
res->AddTree(rightLeg, matrices::Vector3(0,0,0), 0);
res->AddTree(leftLeg, matrices::Vector3(0,0,0), 0);
res->AddTree(rightArm, matrices::Vector3(1.2,0,0), 1);
res->AddTree(leftArm, matrices::Vector3(1.2,0,0), 1);
/*rightLeg->LockTarget(rightLeg->GetTarget());
leftLeg->LockTarget(leftLeg->GetTarget());*/
//rightLeg->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightLeg->GetPosition() + Vector3( -0.3, 0, -1.6)));
//leftLeg ->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), leftLeg->GetPosition() + Vector3( 0.3, 0, -1.4)));
return res;
}
Robot* CreateHumanWalk(const Matrix4& robotBasis) const
{
Robot* res = new Robot(robotBasis, treeFact_.CreateTree( HumanTorso, Vector3(0.0, 0., 0), 4), manip_core::enums::robot::HumanWalk);
Tree* rightLeg = treeFact_.CreateTree( RightLegWalk, Vector3(0.0, -0.2, 0.1), 0);
Tree* leftLeg = treeFact_.CreateTree( LeftLegWalk, Vector3(0.0, 0.2 , 0.1), 1);
Tree* rightArm = treeFact_.CreateTree( RightArm, Vector3(0.0, -0.4, 1.3), 2);
Tree* leftArm = treeFact_.CreateTree( LeftArm, Vector3(0.0, 0.4, 1.3), 3);
res->AddTree(rightLeg, matrices::Vector3(0,0,0), 0);
res->AddTree(leftLeg, matrices::Vector3(0,0,0), 0);
res->AddTree(rightArm, matrices::Vector3(0,0,1.2), 1);
res->AddTree(leftArm, matrices::Vector3(0,0,1.2), 1);
/*rightLeg->LockTarget(rightLeg->GetTarget());
leftLeg->LockTarget(leftLeg->GetTarget());*/
//rightLeg->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightLeg->GetPosition() + Vector3( -0.3, 0, -1.6)));
//leftLeg ->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), leftLeg->GetPosition() + Vector3( 0.3, 0, -1.4)));
return res;
}
Robot* CreateHumanEllipse(const Matrix4& robotBasis) const
{
Robot* res = new Robot(robotBasis, treeFact_.CreateTree( HumanTorso, Vector3(0.0, 0., 0), 1), manip_core::enums::robot::HumanEllipse);
//Tree* rightLeg = treeFact_.CreateTree( RightLegWalk, Vector3(0.0, -0.2, 0.1), 0);
//Tree* leftLeg = treeFact_.CreateTree( LeftLegWalk, Vector3(0.0, 0.2 , 0.1), 1);
Tree* rightArm = treeFact_.CreateTree( RightArmEllipse, Vector3(0.0, -0.4, 1.3), 0);
//Tree* leftArm = treeFact_.CreateTree( LeftArm, Vector3(0.0, 0.4, 1.3), 3);
/*res->AddTree(rightLeg, matrices::Vector3(0,0,0), 0);
res->AddTree(leftLeg, matrices::Vector3(0,0,0), 0);*/
res->AddTree(rightArm, matrices::Vector3(0,0,1.2), 0);
//res->AddTree(leftArm, matrices::Vector3(0,0,1.2), 1);
/*rightLeg->LockTarget(rightLeg->GetTarget());
leftLeg->LockTarget(leftLeg->GetTarget());*/
//rightLeg->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightLeg->GetPosition() + Vector3( -0.3, 0, -1.6)));
//leftLeg ->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), leftLeg->GetPosition() + Vector3( 0.3, 0, -1.4)));
return res;
}
Robot* CreateQuadruped(const Matrix4& robotBasis) const
{
// TODO Remove order neccessity to create ids ...
Robot* res = new Robot(robotBasis, treeFact_.CreateTree( QuadrupedTorso, Vector3(0.0, 0., 0.0), 4), manip_core::enums::robot::Quadruped);
factories::TreeFactory factory;
Tree* rightLeg = treeFact_.CreateTree( QuadrupedLegRight, Vector3(-1.2, -0.25, -0.1), 0);
Tree* leftLeg = treeFact_.CreateTree( QuadrupedLegLeft, Vector3(-1.2, 0.25 , -0.1), 1);
Tree* leftArm = treeFact_.CreateTree( QuadrupedLegLeft, Vector3(0.3, 0.25 , -0.1), 2);
Tree* rightArm = treeFact_.CreateTree( QuadrupedLegRight, Vector3(0.3, -0.25, -0.1), 3);
res->AddTree(rightLeg, matrices::Vector3(-1.2,0,0), 0);
res->AddTree(leftLeg, matrices::Vector3(-1.2,0,0), 0);
res->AddTree(leftArm, matrices::Vector3(0.3,0,0), 1);
res->AddTree(rightArm, matrices::Vector3(0.3,0,0), 1);
/*rightLeg->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightLeg->GetPosition() + Vector3(-0.3, 0, -1.3)));
leftLeg ->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), leftLeg->GetPosition() + Vector3( 0.5, 0, -1.3)));
rightArm->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightArm->GetPosition() + Vector3( 0.3, 0, -1.3)));*/
rightLeg->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightLeg->GetPosition() + Vector3( -0.3, 0, -1.4)));
leftLeg ->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), leftLeg->GetPosition() + Vector3( 0.3, 0, -1.4)));
rightArm->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightArm->GetPosition() + Vector3( 0.4, 0, -1.4)));
leftArm->LockTarget (matrix4TimesVect3(res->ToWorldCoordinates(), leftArm->GetPosition() + Vector3( -0.4, 0, -1.4)));
return res;
}
Robot* CreateQuadrupedDown(const Matrix4& robotBasis) const
{
// TODO Remove order neccessity to create ids ...
Robot* res = new Robot(robotBasis, treeFact_.CreateTree( QuadrupedTorso, Vector3(0.0, 0., 0.0), 4), manip_core::enums::robot::Quadruped);
factories::TreeFactory factory;
Tree* rightLeg = treeFact_.CreateTree( QuadrupedLegDownRight, Vector3(0.0, -0.25, -0.1), 0);
Tree* leftLeg = treeFact_.CreateTree( QuadrupedLegDownLeft, Vector3(0.0, 0.25 , -0.1), 1);
Tree* leftArm = treeFact_.CreateTree( QuadrupedLegDownLeft, Vector3(1.5, 0.25 , -0.1), 2);
Tree* rightArm = treeFact_.CreateTree( QuadrupedLegDownRight, Vector3(1.5, -0.25, -0.1), 3);
res->AddTree(rightLeg, matrices::Vector3(0,0,0), 0);
res->AddTree(leftLeg, matrices::Vector3(0,0,0), 0);
res->AddTree(leftArm, matrices::Vector3(1.5,0,0), 1);
res->AddTree(rightArm, matrices::Vector3(1.5,0,0), 1);
/*rightLeg->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightLeg->GetPosition() + Vector3(-0.3, 0, -1.3)));
leftLeg ->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), leftLeg->GetPosition() + Vector3( 0.5, 0, -1.3)));
rightArm->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightArm->GetPosition() + Vector3( 0.3, 0, -1.3)));*/
rightLeg->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightLeg->GetPosition() + Vector3( -0.3, 0, -1.4)));
leftLeg ->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), leftLeg->GetPosition() + Vector3( 0.3, 0, -1.4)));
rightArm->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightArm->GetPosition() + Vector3( 0.4, 0, -1.4)));
leftArm->LockTarget (matrix4TimesVect3(res->ToWorldCoordinates(), leftArm->GetPosition() + Vector3( -0.4, 0, -1.4)));
return res;
}
Robot* CreateSpider(const Matrix4& robotBasis) const
{
// TODO Remove order neccessity to create ids ...
Robot* res = new Robot(robotBasis, treeFact_.CreateTree( SpiderTorso, Vector3(0.0, 0., 0.0), 8), manip_core::enums::robot::Spider);
factories::TreeFactory factory;
Vector3 zeroAngle(0.25, 0, 0);
Tree* t1 = treeFact_.CreateTree( SpiderLeg, zeroAngle, 0);
Tree* t2 = treeFact_.CreateTree( SpiderLeg, zeroAngle, 1);
Tree* t3 = treeFact_.CreateTree( SpiderLeg, zeroAngle, 2);
Tree* t4 = treeFact_.CreateTree( SpiderLeg, zeroAngle, 3);
Tree* t5 = treeFact_.CreateTree( SpiderLeg, zeroAngle, 4);
Tree* t6 = treeFact_.CreateTree( SpiderLeg, zeroAngle, 5);
Tree* t7 = treeFact_.CreateTree( SpiderLeg, zeroAngle, 6);
Tree* t8 = treeFact_.CreateTree( SpiderLeg, zeroAngle, 7);
matrices::Vector3 position(0,0,0);
res->AddTree(t1,position, 1);
res->AddTree(t2,position, 1);
res->AddTree(t3,position, 1);
res->AddTree(t4,position, 1);
res->AddTree(t5,position, 1);
res->AddTree(t6,position, 1);
res->AddTree(t7,position, 1);
res->AddTree(t8,position, 1);
/*rightLeg->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightLeg->GetPosition() + Vector3(-0.3, 0, -1.3)));
leftLeg ->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), leftLeg->GetPosition() + Vector3( 0.5, 0, -1.3)));
rightArm->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightArm->GetPosition() + Vector3( 0.3, 0, -1.3)));*/
/*rightLeg->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightLeg->GetPosition() + Vector3( -0.3, 0, -1.4)));
leftLeg ->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), leftLeg->GetPosition() + Vector3( 0.3, 0, -1.4)));
rightArm->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightArm->GetPosition() + Vector3( 0.4, 0, -1.4)));
leftArm->LockTarget (matrix4TimesVect3(res->ToWorldCoordinates(), leftArm->GetPosition() + Vector3( -0.4, 0, -1.4)));*/
return res;
}
Robot* CreateSpiderRace(const Matrix4& robotBasis) const
{
// TODO Remove order neccessity to create ids ...
Robot* res = new Robot(robotBasis, treeFact_.CreateTree( SpiderTorsoRace, Vector3(0.0, 0., 0.0), 4), manip_core::enums::robot::SpiderRace);
factories::TreeFactory factory;
Vector3 zeroAngle(0.25, 0, 0);
Tree* t1 = treeFact_.CreateTree( SpiderLegRace, zeroAngle, 0);
Tree* t2 = treeFact_.CreateTree( SpiderLegRace, zeroAngle, 1);
Tree* t3 = treeFact_.CreateTree( SpiderLegRace, zeroAngle, 2);
Tree* t4 = treeFact_.CreateTree( SpiderLegRace, zeroAngle, 3);
matrices::Vector3 position(0,0,0);
res->AddTree(t1,position, 1);
res->AddTree(t2,position, 1);
res->AddTree(t3,position, 1);
res->AddTree(t4,position, 1);
return res;
}
Robot* CreateSpiderSix(const Matrix4& robotBasis) const
{
// TODO Remove order neccessity to create ids ...
Robot* res = new Robot(robotBasis, treeFact_.CreateTree( SpiderTorsoRace, Vector3(0.0, 0., 0.0), 4), manip_core::enums::robot::SpiderSix);
factories::TreeFactory factory;
Vector3 zeroAngle(0.25, 0, 0);
Tree* t1 = treeFact_.CreateTree( SpiderLegSix, zeroAngle, 0);
Tree* t2 = treeFact_.CreateTree( SpiderLegSix, zeroAngle, 1);
Tree* t3 = treeFact_.CreateTree( SpiderLegSix, zeroAngle, 2);
Tree* t4 = treeFact_.CreateTree( SpiderLegSix, zeroAngle, 3);
Tree* t5 = treeFact_.CreateTree( SpiderLegSix, zeroAngle, 4);
Tree* t6 = treeFact_.CreateTree( SpiderLegSix, zeroAngle, 5);
matrices::Vector3 position(0,0,0);
res->AddTree(t1,position, 1);
res->AddTree(t2,position, 1);
res->AddTree(t3,position, 1);
res->AddTree(t4,position, 1);
res->AddTree(t5,position, 1);
res->AddTree(t6,position, 1);
return res;
}
TreeFactory treeFact_;
};
}
using namespace factories;
RobotFactory::RobotFactory()
: pImpl_(new RobotFactoryPimpl())
{
// NOTHING
}
RobotFactory::~RobotFactory()
{
// NOTHING
}
Robot* RobotFactory::CreateRobot(const eRobots robots, const Matrix4& robotBasis) const
{
switch (robots)
{
case Human:
{
return pImpl_->CreateHuman(robotBasis);
}
case HumanWalk:
{
return pImpl_->CreateHumanWalk(robotBasis);
}
case HumanEscalade:
{
return pImpl_->CreateHumanEscalade(robotBasis);
}
case HumanCanap:
{
return pImpl_->CreateHumanCanap(robotBasis);
}
case HumanEllipse:
{
return pImpl_->CreateHumanEllipse(robotBasis);
}
case Quadruped:
{
return pImpl_->CreateQuadruped(robotBasis);
}
case QuadrupedDown:
{
return pImpl_->CreateQuadrupedDown(robotBasis);
}
case Spider:
{
return pImpl_->CreateSpider(robotBasis);
}
case SpiderSix:
{
return pImpl_->CreateSpiderSix(robotBasis);
}
case SpiderRace:
{
return pImpl_->CreateSpiderRace(robotBasis);
}
case HumanCrouch:
{
return pImpl_->CreateHumanCrouch(robotBasis);
}
case HumanCrouch180:
{
return pImpl_->CreateHumanCrouch180(robotBasis);
}
default:
throw(std::exception());
}
}
/*
bool IsSpine(const joint_def_t* root)
{
const std::string headTag("head");
std::string taf(root->tag);
return (root->nbChildren_ == 0) ? (taf == headTag) : IsSpine(root->children[0]);
}
const joint_def_t* RetrieveSpine(std::list<const joint_def_t*>& trees)
{
for(std::list<const joint_def_t*>::const_iterator it = trees.begin(); it!= trees.end(); ++it)
{
if(IsSpine(*it))
{
const joint_def_t* res = (*it);
trees.remove(*it);
return res;
}
}
return 0;
}
void GetTrees(const joint_def_t* root, std::list<const joint_def_t*>& trees)
{
if(root->is_simple() && !root->is_locked())
{
trees.push_back(root);
}
else
{
for(unsigned int i = 0; i < root->nbChildren_; ++i)
{
GetTrees(root->children[i], trees);
}
}
}
#include "Pi.h"
#include "kinematic/Com.h"
#include "kinematic/Joint.h"
#include "kinematic/Tree.h"
Joint* GetLast(Tree* tree)
{
Joint* j = tree->GetRoot();
while(j)
{
if(j->pChild_) j = j->pChild_;
else return j;
}
return 0;
}
void ReadOneJointDef(matrices::Vector3 root, const joint_def_t* jointDef, Tree* tree, const ComFactory& comFact_)
{
const Vector3 unitx(1, 0, 0);
const Vector3 unity(0, 1, 0);
const Vector3 unitz(0, 0, 1);
const Vector3 vectors []= {unitx, unity, unitz};
Joint* previous = GetLast(tree);
matrices::Vector3 attach(jointDef->offset[0], jointDef->offset[1], jointDef->offset[2]);
attach += root;
bool lastIsEffector = jointDef->nbChildren_ == 0;
for(int i = 0; i < 3; ++ i)
{
Joint* j = new Joint(attach, vectors[i], (lastIsEffector && i == 2) ? EFFECTOR : JOINT, comFact_.CreateCom(None)
, RADIAN(jointDef->minAngleValues[i]), RADIAN(jointDef->maxAngleValues[i]), RADIAN(jointDef->defaultAngleValues[i]),
rotation::eRotation(i));
if(previous)
{
tree->InsertChild(previous, j);
}
else
{
tree->InsertRoot(j);
}
previous = j;
}
if(!lastIsEffector)
ReadOneJointDef(attach, jointDef->children[0], tree, comFact_);
}
Tree* MakeTree(const joint_def_t* root, unsigned int& id)
{
assert(root->is_simple());
const ComFactory comFact;
Tree* tree = new Tree(id++);
const joint_def_t* current_joint = root;
matrices::Vector3 attach(0,0,0);
ReadOneJointDef(attach, root, tree, comFact);
return tree;
}
Robot* RobotFactory::CreateRobot(const joint_def_t& joint, const Matrix4& robotBasis) const
{
std::list<const joint_def_t*> trees;
GetTrees(&joint, trees);
const joint_def_t * spine = RetrieveSpine(trees);
unsigned int id = 0; unsigned int torsoIndex = trees.size();
Robot* res = new Robot(robotBasis, MakeTree(spine, torsoIndex));
for(std::list<const joint_def_t*>::const_iterator it = trees.begin(); it!= trees.end(); ++it)
{
matrices::Vector3 offset((*it)->offset[0], (*it)->offset[1], (*it)->offset[2]);
res->AddTree( MakeTree((*it), id), offset, 0); // TODO find good column joint for rendering
}
return res;
}*/
| heyang123/ManipulabilitySampleTestapp | src/manipulability_core/kinematic/RobotFactory.cpp | C++ | gpl-2.0 | 20,561 |
<!DOCTYPE html>
<html lang="en">
<head>
<?php //////////////////////////////////////////////////////
///Copyright 2015 Luna Claudio,Rebolloso Leandro.///
////////////////////////////////////////////////////
//
//This file is part of ARSoftware.
//ARSoftware 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 2
//of the License, or (at your option) any later version.
//
//ARSoftware 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, write to the Free Software
//Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
?>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>ARSoftware</title>
<?php
include_once($_SERVER["DOCUMENT_ROOT"]."/arsoftware/utiles/headerAdmin.php");
include_once($docRootSitio."modelo/Administrador.php");
#Paginación
$limit=15;
if(is_numeric($_GET['pagina']) && $_GET['pagina']>=1){
$offset = ($_GET['pagina']-1) * $limit;
}
else{
$offset=0;
}
#Orden por defecto
if(!isset($_GET['campoOrder']) && !isset($_GET['order']) ){
$order = "DESC";
}
else{
$campoOrder = $_GET['campoOrder'];
$order = $_GET['order'];
}
#incluyo clases
include_once($docRootSitio."modelo/Marca.php");
#nuevo objeto
$mar1 = new Marca();
$adm1 = new Administrador();
$usuario = $_SESSION["nombreUsuario"];
$mar1->setNombreUsuario($usuario);
$_marcas = $mar1->listarMarcas($offset,$limit,$campoOrder,$order);
$_nombre = $adm1->listarAdministradorins2($usuario);
#getCantRegistros
$cantRegistros = $mar1->getCantRegistros();
$cantPaginas = ceil($cantRegistros/$limit);
?>
<!-- Bootstrap Core CSS -->
<link href="<?php echo $httpHostSitio?>plantilla/css/bootstrap.min.css" rel="stylesheet">
<!-- Custom CSS -->
<link href="<?php echo $httpHostSitio?>plantilla/css/sb-admin.css" rel="stylesheet">
<!-- Morris Charts CSS -->
<link href="<?php echo $httpHostSitio?>plantilla/css/plugins/morris.css" rel="stylesheet">
<!-- Custom Fonts -->
<link href="<?php echo $httpHostSitio?>plantilla/font-awesome-4.1.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<script src="<?php echo $httpHostSitio?>jquery/jquery-1.11.1.js"></script>
<script src="<?php echo $httpHostSitio?>plantilla/js/bootstrap.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div id="wrapper">
<!-- Navigation -->
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<div onclick="location = ('<?php echo $httpHostSitio?>modulos/back-end/administradores/principalAdministradorAR.php')"; style="height: 52px; width:225px; max-width: 100%; background: #FFFFFF; background-image: url(<?php echo $httpHostSitio?>plantilla/imagenes/logotipoe.png);"></div>
</div>
<ul class="nav navbar-right top-nav">
<li class="dropdown">
<a href="principalAdministrador.php" class="dropdown-toggle" data-toggle="dropdown"><i class="fa fa-user"></i> <?php echo $_nombre['nombre'].' '.$_nombre['apellido']?> <b class="caret"></b></a>
<ul class="dropdown-menu">
<li>
<a href="<?php echo $httpHostSitio?>utiles/ctrlLogout.php"><i class="fa fa-fw fa-power-off"></i> Salir</a>
</li>
</ul>
</li>
</ul>
<!-- Sidebar Menu Items - These collapse to the responsive navigation menu on small screens -->
<div class="collapse navbar-collapse navbar-ex1-collapse">
<?php include_once($docRootSitio."utiles/menuAdministradorAR.php");?>
</div>
<!-- /.navbar-collapse -->
</nav>
<div id="page-wrapper">
<div class="container-fluid">
</div>
<!-- /.container-fluid ------------------------------------------------------------------------------------------------------>
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">
Marcas Netbooks
</h1>
<ol class="breadcrumb">
<li class="active">
<i class="fa fa-dashboard"></i> Marcas Netbooks
</li>
</ol>
</div>
</div>
<?php if($_GET['insert']==1){?>
<div class="alert alert-success">
<strong>La Marca Se Agrego Exitosamente.</strong>
</div>
<?php }?>
<?php if($_GET['update']==1){?>
<div class="alert alert-success">
<strong>La Marca Se Modificó Exitosamente.</strong>
</div>
<?php }?>
<?php if($_GET['delete']==1){?>
<div class="alert alert-success">
<strong>La Marca Se Elimino Exitosamente.</strong>
</div>
<?php }?>
<p>
<button type="button" class="btn btn-primary" onclick="location = ('<?php echo $httpHostSitio?>modulos/back-end/netescuela/listarNetbooks.php')" > Remanente Netbook</button>
<button type="button" class="btn btn-success" onclick="location = ('<?php echo $httpHostSitio?>modulos/back-end/prestamo/listarPrestamos.php')" > Prestamos Netbook</button>
<button type="button" class="btn btn-warning" onclick="location = ('<?php echo $httpHostSitio?>modulos/back-end/marcas/listarMarcas.php')" > Marcas Netbooks</button>
<button type="button" class="btn btn-danger" onclick="location = ('<?php echo $httpHostSitio?>modulos/back-end/marcas/agregarMarca.php')" > Agregar Marca Netbooks</button>
</p>
<?php
if(!isset($_GET['order']) || $_GET['order']=="DESC"){
$order = "ASC";
}
else{
$order = "DESC";
}
if(count($_marcas)){?>
<table class="table table-bordered table-hover table-striped">
<tr>
<td>
<center><b>Nombre</b></center>
</td>
<td>
<center><b>Acciones</b></center>
</td>
</tr>
<?php for($i=1;$i<=count($_marcas);$i++){
if($i%2==0){
$class="class='alt'";
$classTh="class='specalt'";
}
else{
$class="";
$classTh="class='spec'";
}
?>
<tr>
<td>
<center><?php echo $_marcas[$i]['nombre']?></center>
</td>
<td>
<div id="celdaAcciones">
<center><form method="post" action="modificarMarca.php">
<input type="hidden" name="Marca" value="<?php echo $_marcas[$i]['id']?>">
<input type="submit" value="Editar" class="btn btn-primary">
</form></center>
</div>
<div id="celdaAcciones">
<center><form method="post" action="eliminarMarca.php">
<input type="hidden" name="Marca" value="<?php echo $_marcas[$i]['id']?>">
<input type="submit" value="Eliminar" class="btn btn-success" onclick="return confirm('¿Está seguro que desea eliminar la siguiente marca <?php echo $_marcas[$i]['nombre']?>?');">
</form></center>
</div>
</td>
</tr>
<?php }?>
</table>
<div id="paginacion">
<?php
if(!is_numeric($_GET['pagina']) || $_GET['pagina']<=1){
$_GET['pagina'] = 1;
}
else{
$paginaAnterior=$_GET['pagina']-1;
if(isset($_GET['campoOrder']) && isset($_GET['order'])){
$campoOrder = $_GET['campoOrder'];+
$order = $_GET['order'];
$criteriosOrder = "&campoOrder=$campoOrder&order=$order";
}
?>
<a href="listarMarcas.php?pagina=<?php echo $paginaAnterior?><?php echo $criteriosOrder?>">Anterior</a>
<?php }?>
Página <?php echo $_GET['pagina']?>/<?php echo $cantPaginas?> de <?php echo $cantRegistros?> registros
<?php if($_GET['pagina']<$cantPaginas){
$paginaSiguiente=$_GET['pagina']+1;
if(isset($_GET['campoOrder']) && isset($_GET['order'])){
$campoOrder = $_GET['campoOrder'];+
$order = $_GET['order'];
$criteriosOrder = "&campoOrder=$campoOrder&order=$order";
}
?>
<a href="listarMarcas.php?pagina=<?php echo $paginaSiguiente?><?php echo $criteriosOrder?>">Siguiente</a>
<?php }?>
</div>
<?php }
else{?>
<div class="alert alert-info">
<center><strong>Aviso! </strong> No existen marcas de netbooks cargadas.</center>
</div>
<?php }?>
</div><!-- Fin container-fluid ------------------------------------------------------------------------------------------------------>
<!-- /#page-wrapper -->
<!-- /#wrapper -->
<!-- jQuery Version 1.11.0 -->
<script src="js/jquery-1.11.0.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="js/bootstrap.min.js"></script>
<!-- Morris Charts JavaScript -->
<script src="js/plugins/morris/raphael.min.js"></script>
<script src="js/plugins/morris/morris.min.js"></script>
<script src="js/plugins/morris/morris-data.js"></script>
</body>
</html>
| claudioLuna/arsoftware | modulos/back-end/marcas/listarMarcas.php | PHP | gpl-2.0 | 10,483 |
/* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */
/*
Rosegarden
A MIDI and audio sequencer and musical notation editor.
Copyright 2000-2018 the Rosegarden development team.
Other copyrights also apply to some parts of this work. Please
see the AUTHORS file and individual file headers for details.
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 2 of the
License, or (at your option) any later version. See the file
COPYING included with this distribution for more information.
*/
#define RG_MODULE_STRING "[TrackButtons]"
#include "TrackButtons.h"
#include "TrackLabel.h"
#include "TrackVUMeter.h"
#include "misc/Debug.h"
#include "misc/Strings.h"
#include "base/AudioPluginInstance.h"
#include "base/Composition.h"
#include "base/Device.h"
#include "base/Instrument.h"
#include "base/InstrumentStaticSignals.h"
#include "base/MidiProgram.h"
#include "base/Studio.h"
#include "base/Track.h"
#include "commands/segment/RenameTrackCommand.h"
#include "document/RosegardenDocument.h"
#include "document/CommandHistory.h"
#include "gui/application/RosegardenMainWindow.h"
#include "gui/general/GUIPalette.h"
#include "gui/general/IconLoader.h"
#include "gui/seqmanager/SequenceManager.h"
#include "gui/widgets/LedButton.h"
#include "sound/AudioFileManager.h"
#include "sound/ControlBlock.h"
#include "sound/PluginIdentifier.h"
#include "sequencer/RosegardenSequencer.h"
#include <QApplication>
#include <QLayout>
#include <QMessageBox>
#include <QCursor>
#include <QFrame>
#include <QIcon>
#include <QLabel>
#include <QObject>
#include <QPixmap>
#include <QMenu>
#include <QSignalMapper>
#include <QString>
#include <QTimer>
#include <QWidget>
#include <QStackedWidget>
#include <QToolTip>
namespace Rosegarden
{
// Constants
const int TrackButtons::m_borderGap = 1;
const int TrackButtons::m_buttonGap = 8;
const int TrackButtons::m_vuWidth = 20;
const int TrackButtons::m_vuSpacing = 2;
TrackButtons::TrackButtons(RosegardenDocument* doc,
int trackCellHeight,
int trackLabelWidth,
bool showTrackLabels,
int overallHeight,
QWidget* parent) :
QFrame(parent),
m_doc(doc),
m_layout(new QVBoxLayout(this)),
m_recordSigMapper(new QSignalMapper(this)),
m_muteSigMapper(new QSignalMapper(this)),
m_soloSigMapper(new QSignalMapper(this)),
m_clickedSigMapper(new QSignalMapper(this)),
m_instListSigMapper(new QSignalMapper(this)),
m_tracks(doc->getComposition().getNbTracks()),
// m_offset(4),
m_cellSize(trackCellHeight),
m_trackLabelWidth(trackLabelWidth),
m_popupTrackPos(0),
m_lastSelected(-1)
{
setFrameStyle(Plain);
QPalette pal = palette();
pal.setColor(backgroundRole(), QColor(0xDD, 0xDD, 0xDD));
pal.setColor(foregroundRole(), Qt::black);
setPalette(pal);
// when we create the widget, what are we looking at?
if (showTrackLabels) {
m_labelDisplayMode = TrackLabel::ShowTrack;
} else {
m_labelDisplayMode = TrackLabel::ShowInstrument;
}
m_layout->setMargin(0);
// Set the spacing between vertical elements
m_layout->setSpacing(m_borderGap);
// Now draw the buttons and labels and meters
//
makeButtons();
m_layout->addStretch(20);
connect(m_recordSigMapper, SIGNAL(mapped(int)),
this, SLOT(slotToggleRecord(int)));
connect(m_muteSigMapper, SIGNAL(mapped(int)),
this, SLOT(slotToggleMute(int)));
connect(m_soloSigMapper, SIGNAL(mapped(int)),
this, SLOT(slotToggleSolo(int)));
// connect signal mappers
connect(m_instListSigMapper, SIGNAL(mapped(int)),
this, SLOT(slotInstrumentMenu(int)));
connect(m_clickedSigMapper, SIGNAL(mapped(int)),
this, SLOT(slotTrackSelected(int)));
// We have to force the height for the moment
//
setMinimumHeight(overallHeight);
m_doc->getComposition().addObserver(this);
// We do not care about documentChanged() because if the
// document is changing, we are going away. A new TrackButtons
// is created for each new document.
//connect(RosegardenMainWindow::self(),
// SIGNAL(documentChanged(RosegardenDocument *)),
// SLOT(slotNewDocument(RosegardenDocument *)));
}
TrackButtons::~TrackButtons() {
// CRASH! Probably m_doc is gone...
// Probably don't need to disconnect as we only go away when the
// doc and composition do. shared_ptr would help here.
// m_doc->getComposition().removeObserver(this);
}
void
TrackButtons::updateUI(Track *track)
{
if (!track)
return;
int pos = track->getPosition();
if (pos < 0 || pos >= m_tracks)
return;
// *** Archive Background
QFrame *hbox = m_trackHBoxes.at(pos);
if (track->isArchived()) {
// Go with the dark gray background.
QPalette palette = hbox->palette();
palette.setColor(hbox->backgroundRole(), QColor(0x88, 0x88, 0x88));
hbox->setPalette(palette);
} else {
// Go with the parent's background color.
QColor parentBackground = palette().color(backgroundRole());
QPalette palette = hbox->palette();
palette.setColor(hbox->backgroundRole(), parentBackground);
hbox->setPalette(palette);
}
// *** Mute LED
if (track->isMuted()) {
m_muteLeds[pos]->off();
} else {
m_muteLeds[pos]->on();
}
// *** Record LED
Instrument *ins =
m_doc->getStudio().getInstrumentById(track->getInstrument());
m_recordLeds[pos]->setColor(getRecordLedColour(ins));
// Note: setRecord() used to be used to do this. But that would
// set the track in the composition to record as well as setting
// the button on the UI. This seems better and works fine.
bool recording =
m_doc->getComposition().isTrackRecording(track->getId());
setRecordButton(pos, recording);
// *** Solo LED
// ??? An Led::setState(bool) would be handy.
m_soloLeds[pos]->setState(track->isSolo() ? Led::On : Led::Off);
// *** Track Label
TrackLabel *label = m_trackLabels[pos];
if (!label)
return;
// In case the tracks have been moved around, update the mapping.
label->setId(track->getId());
setButtonMapping(label, track->getId());
label->setPosition(pos);
if (track->getLabel() == "") {
if (ins && ins->getType() == Instrument::Audio) {
label->setTrackName(tr("<untitled audio>"));
} else {
label->setTrackName(tr("<untitled>"));
}
} else {
label->setTrackName(strtoqstr(track->getLabel()));
label->setShortName(strtoqstr(track->getShortLabel()));
}
initInstrumentNames(ins, label);
label->updateLabel();
}
void
TrackButtons::makeButtons()
{
if (!m_doc)
return;
//RG_DEBUG << "makeButtons()";
// Create a horizontal box filled with widgets for each track
for (int i = 0; i < m_tracks; ++i) {
Track *track = m_doc->getComposition().getTrackByPosition(i);
if (!track)
continue;
QFrame *trackHBox = makeButton(track);
if (trackHBox) {
trackHBox->setObjectName("TrackButtonFrame");
m_layout->addWidget(trackHBox);
m_trackHBoxes.push_back(trackHBox);
}
}
populateButtons();
}
void
TrackButtons::setButtonMapping(TrackLabel* trackLabel, TrackId trackId)
{
m_clickedSigMapper->setMapping(trackLabel, trackId);
m_instListSigMapper->setMapping(trackLabel, trackId);
}
void
TrackButtons::initInstrumentNames(Instrument *ins, TrackLabel *label)
{
if (!label)
return;
if (ins) {
label->setPresentationName(ins->getLocalizedPresentationName());
if (ins->sendsProgramChange()) {
label->setProgramChangeName(
QObject::tr(ins->getProgramName().c_str()));
} else {
label->setProgramChangeName("");
}
} else {
label->setPresentationName(tr("<no instrument>"));
}
}
void
TrackButtons::populateButtons()
{
//RG_DEBUG << "populateButtons()";
// For each track, copy info from Track object to the widgets
for (int i = 0; i < m_tracks; ++i) {
Track *track = m_doc->getComposition().getTrackByPosition(i);
if (!track)
continue;
updateUI(track);
}
}
void
TrackButtons::slotToggleMute(int pos)
{
//RG_DEBUG << "TrackButtons::slotToggleMute( position =" << pos << ")";
if (!m_doc)
return;
if (pos < 0 || pos >= m_tracks)
return;
Composition &comp = m_doc->getComposition();
Track *track = comp.getTrackByPosition(pos);
if (!track)
return;
// Toggle the mute state
track->setMuted(!track->isMuted());
// Notify observers
comp.notifyTrackChanged(track);
m_doc->slotDocumentModified();
}
void TrackButtons::toggleSolo()
{
if (!m_doc)
return;
Composition &comp = m_doc->getComposition();
int pos = comp.getTrackPositionById(comp.getSelectedTrack());
if (pos == -1)
return;
slotToggleSolo(pos);
}
void
TrackButtons::slotToggleSolo(int pos)
{
//RG_DEBUG << "slotToggleSolo( position =" << pos << ")";
if (!m_doc)
return;
if (pos < 0 || pos >= m_tracks)
return;
Composition &comp = m_doc->getComposition();
Track *track = comp.getTrackByPosition(pos);
if (!track)
return;
bool state = !track->isSolo();
// If we're setting solo on this track and shift isn't being held down,
// clear solo on all tracks (canceling mode). If shift is being held
// down, multiple tracks can be put into solo (latching mode).
if (state &&
QApplication::keyboardModifiers() != Qt::ShiftModifier) {
// For each track
for (int i = 0; i < m_tracks; ++i) {
// Except the one that is being toggled.
if (i == pos)
continue;
Track *track2 = comp.getTrackByPosition(i);
if (!track2)
continue;
if (track2->isSolo()) {
// Clear solo
track2->setSolo(false);
comp.notifyTrackChanged(track2);
}
}
}
// Toggle the solo state
track->setSolo(state);
// Notify observers
comp.notifyTrackChanged(track);
m_doc->slotDocumentModified();
}
void
TrackButtons::removeButtons(int position)
{
//RG_DEBUG << "removeButtons() - deleting track button at position:" << position;
if (position < 0 || position >= m_tracks) {
RG_DEBUG << "%%%%%%%%% BIG PROBLEM : TrackButtons::removeButtons() was passed a non-existing index\n";
return;
}
std::vector<TrackLabel*>::iterator tit = m_trackLabels.begin();
tit += position;
m_trackLabels.erase(tit);
std::vector<TrackVUMeter*>::iterator vit = m_trackMeters.begin();
vit += position;
m_trackMeters.erase(vit);
std::vector<LedButton*>::iterator mit = m_muteLeds.begin();
mit += position;
m_muteLeds.erase(mit);
mit = m_recordLeds.begin();
mit += position;
m_recordLeds.erase(mit);
m_soloLeds.erase(m_soloLeds.begin() + position);
// Delete all child widgets (button, led, label...)
delete m_trackHBoxes[position];
m_trackHBoxes[position] = nullptr;
std::vector<QFrame*>::iterator it = m_trackHBoxes.begin();
it += position;
m_trackHBoxes.erase(it);
}
void
TrackButtons::slotUpdateTracks()
{
//RG_DEBUG << "slotUpdateTracks()";
#if 0
static QTime t;
RG_DEBUG << " elapsed: " << t.restart();
#endif
if (!m_doc)
return;
Composition &comp = m_doc->getComposition();
const int newNbTracks = comp.getNbTracks();
if (newNbTracks < 0) {
RG_WARNING << "slotUpdateTracks(): WARNING: New number of tracks was negative:" << newNbTracks;
return;
}
//RG_DEBUG << "TrackButtons::slotUpdateTracks > newNbTracks = " << newNbTracks;
// If a track or tracks were deleted
if (newNbTracks < m_tracks) {
// For each deleted track, remove a button from the end.
for (int i = m_tracks; i > newNbTracks; --i)
removeButtons(i - 1);
} else if (newNbTracks > m_tracks) { // if added
// For each added track
for (int i = m_tracks; i < newNbTracks; ++i) {
Track *track = m_doc->getComposition().getTrackByPosition(i);
if (track) {
// Make a new button
QFrame *trackHBox = makeButton(track);
if (trackHBox) {
trackHBox->show();
// Add the new button to the layout.
m_layout->insertWidget(i, trackHBox);
m_trackHBoxes.push_back(trackHBox);
}
} else
RG_DEBUG << "TrackButtons::slotUpdateTracks - can't find TrackId for position " << i;
}
}
m_tracks = newNbTracks;
if (m_tracks != (int)m_trackHBoxes.size())
RG_DEBUG << "WARNING TrackButtons::slotUpdateTracks(): m_trackHBoxes.size() != m_tracks";
if (m_tracks != (int)m_trackLabels.size())
RG_DEBUG << "WARNING TrackButtons::slotUpdateTracks(): m_trackLabels.size() != m_tracks";
// For each track
for (int i = 0; i < m_tracks; ++i) {
Track *track = comp.getTrackByPosition(i);
if (!track)
continue;
// *** Set Track Size ***
// Track height can change when the user moves segments around and
// they overlap.
m_trackHBoxes[i]->setMinimumSize(labelWidth(), trackHeight(track->getId()));
m_trackHBoxes[i]->setFixedHeight(trackHeight(track->getId()));
}
populateButtons();
// This is necessary to update the widgets's sizeHint to reflect any change in child widget sizes
// Make the TrackButtons QFrame big enough to hold all the track buttons.
// Some may have grown taller due to segments that overlap.
// Note: This appears to no longer be needed. But it doesn't hurt.
adjustSize();
}
void
TrackButtons::slotToggleRecord(int position)
{
//RG_DEBUG << "TrackButtons::slotToggleRecord(" << position << ")";
if (position < 0 || position >= m_tracks)
return;
if (!m_doc)
return;
Composition &comp = m_doc->getComposition();
Track *track = comp.getTrackByPosition(position);
if (!track)
return;
// Toggle
bool state = !comp.isTrackRecording(track->getId());
// Update the Track
comp.setTrackRecording(track->getId(), state);
comp.notifyTrackChanged(track);
m_doc->checkAudioPath(track);
}
void
TrackButtons::setRecordButton(int position, bool record)
{
if (position < 0 || position >= m_tracks)
return;
m_recordLeds[position]->setState(record ? Led::On : Led::Off);
}
void
TrackButtons::selectTrack(int position)
{
if (position < 0 || position >= m_tracks)
return;
// No sense doing anything if the selection isn't changing
if (position == m_lastSelected)
return;
// Unselect the previously selected
if (m_lastSelected >= 0 && m_lastSelected < m_tracks) {
m_trackLabels[m_lastSelected]->setSelected(false);
}
// Select the newly selected
m_trackLabels[position]->setSelected(true);
m_lastSelected = position;
}
#if 0
// unused
std::vector<int>
TrackButtons::getHighlightedTracks()
{
std::vector<int> retList;
for (int i = 0; i < m_trackLabels.size(); ++i) {
if (m_trackLabels[i]->isSelected())
retList.push_back(i);
}
return retList;
}
#endif
void
TrackButtons::slotRenameTrack(QString longLabel, QString shortLabel, TrackId trackId)
{
if (!m_doc) return;
Track *track = m_doc->getComposition().getTrackById(trackId);
if (!track) return;
TrackLabel *label = m_trackLabels[track->getPosition()];
// If neither label is changing, skip it
if (label->getTrackName() == longLabel &&
QString::fromStdString(track->getShortLabel()) == shortLabel) return;
// Rename the track
CommandHistory::getInstance()->addCommand(
new RenameTrackCommand(&m_doc->getComposition(),
trackId,
longLabel,
shortLabel));
}
void
TrackButtons::slotSetTrackMeter(float value, int position)
{
if (position < 0 || position >= m_tracks)
return;
m_trackMeters[position]->setLevel(value);
}
void
TrackButtons::slotSetMetersByInstrument(float value,
InstrumentId id)
{
Composition &comp = m_doc->getComposition();
for (int i = 0; i < m_tracks; ++i) {
Track *track = comp.getTrackByPosition(i);
if (track && track->getInstrument() == id) {
m_trackMeters[i]->setLevel(value);
}
}
}
void
TrackButtons::slotInstrumentMenu(int trackId)
{
//RG_DEBUG << "TrackButtons::slotInstrumentMenu( trackId =" << trackId << ")";
Composition &comp = m_doc->getComposition();
const int position = comp.getTrackById(trackId)->getPosition();
Track *track = comp.getTrackByPosition(position);
Instrument *instrument = nullptr;
if (track != nullptr) {
instrument = m_doc->getStudio().getInstrumentById(
track->getInstrument());
}
// *** Force The Track Label To Show The Presentation Name ***
// E.g. "General MIDI Device #1"
m_trackLabels[position]->forcePresentationName(true);
m_trackLabels[position]->updateLabel();
// *** Launch The Popup ***
// Yes, well as we might've changed the Device name in the
// Device/Bank dialog then we reload the whole menu here.
QMenu instrumentPopup(this);
populateInstrumentPopup(instrument, &instrumentPopup);
// Store the popup item position for slotInstrumentSelected().
m_popupTrackPos = position;
instrumentPopup.exec(QCursor::pos());
// *** Restore The Track Label ***
// Turn off the presentation name
m_trackLabels[position]->forcePresentationName(false);
m_trackLabels[position]->updateLabel();
}
// ??? Break this stuff off into an InstrumentPopup class. This class is too
// big.
void
TrackButtons::populateInstrumentPopup(Instrument *thisTrackInstr, QMenu* instrumentPopup)
{
// pixmaps for icons to show connection states as variously colored boxes
// ??? Factor out the icon-related stuff to make this routine clearer.
// getIcon(Instrument *) would be ideal, but might not be easy.
// getIcon(Device *) would also be needed.
static QPixmap connectedPixmap, unconnectedPixmap,
connectedUsedPixmap, unconnectedUsedPixmap,
connectedSelectedPixmap, unconnectedSelectedPixmap;
static bool havePixmaps = false;
if (!havePixmaps) {
IconLoader il;
connectedPixmap = il.loadPixmap("connected");
connectedUsedPixmap = il.loadPixmap("connected-used");
connectedSelectedPixmap = il.loadPixmap("connected-selected");
unconnectedPixmap = il.loadPixmap("unconnected");
unconnectedUsedPixmap = il.loadPixmap("unconnected-used");
unconnectedSelectedPixmap = il.loadPixmap("unconnected-selected");
havePixmaps = true;
}
Composition &comp = m_doc->getComposition();
// clear the popup
instrumentPopup->clear();
QMenu *currentSubMenu = nullptr;
// position index
int count = 0;
int currentDevId = -1;
// Get the list
Studio &studio = m_doc->getStudio();
InstrumentList list = studio.getPresentationInstruments();
// For each instrument
for (InstrumentList::iterator it = list.begin(); it != list.end(); ++it) {
if (!(*it)) continue; // sanity check
// get the Localized instrument name, with the string hackery performed
// in Instrument
QString iname((*it)->getLocalizedPresentationName());
// translate the program name
//
// Note we are converting the string from std to Q back to std then to
// C. This is obviously ridiculous, but the fact that we have programName
// here at all makes me think it exists as some kind of necessary hack
// to coax tr() into behaving nicely. I decided to change it as little
// as possible to get it to compile, and not refactor this down to the
// simplest way to call tr() on a C string.
QString programName(strtoqstr((*it)->getProgramName()));
programName = QObject::tr(programName.toStdString().c_str());
Device *device = (*it)->getDevice();
DeviceId devId = device->getId();
bool connectedIcon = false;
// Determine the proper program name and whether it is connected
if ((*it)->getType() == Instrument::SoftSynth) {
programName = "";
AudioPluginInstance *plugin =
(*it)->getPlugin(Instrument::SYNTH_PLUGIN_POSITION);
if (plugin) {
// we don't translate any plugin program names or other texts
programName = strtoqstr(plugin->getDisplayName());
connectedIcon = (plugin->getIdentifier() != "");
}
} else if ((*it)->getType() == Instrument::Audio) {
connectedIcon = true;
} else {
QString conn = RosegardenSequencer::getInstance()->
getConnection(devId);
connectedIcon = (conn != "");
}
// These two are for selecting the correct icon to display.
bool instrUsedByMe = false;
bool instrUsedByAnyone = false;
if (thisTrackInstr && thisTrackInstr->getId() == (*it)->getId()) {
instrUsedByMe = true;
instrUsedByAnyone = true;
}
// If we have switched to a new device, we'll create a new submenu
if (devId != (DeviceId)(currentDevId)) {
currentDevId = int(devId);
// For selecting the correct icon to display.
bool deviceUsedByAnyone = false;
if (instrUsedByMe)
deviceUsedByAnyone = true;
else {
for (Composition::trackcontainer::iterator tit =
comp.getTracks().begin();
tit != comp.getTracks().end(); ++tit) {
if (tit->second->getInstrument() == (*it)->getId()) {
instrUsedByAnyone = true;
deviceUsedByAnyone = true;
break;
}
Instrument *instr =
studio.getInstrumentById(tit->second->getInstrument());
if (instr && (instr->getDevice()->getId() == devId)) {
deviceUsedByAnyone = true;
}
}
}
QIcon icon
(connectedIcon ?
(deviceUsedByAnyone ?
connectedUsedPixmap : connectedPixmap) :
(deviceUsedByAnyone ?
unconnectedUsedPixmap : unconnectedPixmap));
// Create a submenu for this device
QMenu *subMenu = new QMenu(instrumentPopup);
subMenu->setMouseTracking(true);
subMenu->setIcon(icon);
// Not needed so long as AA_DontShowIconsInMenus is false.
//subMenu->menuAction()->setIconVisibleInMenu(true);
// Menu title
QString deviceName = QObject::tr(device->getName().c_str());
subMenu->setTitle(deviceName);
// QObject name
subMenu->setObjectName(deviceName);
// Add the submenu to the popup menu
instrumentPopup->addMenu(subMenu);
// Connect the submenu to slotInstrumentSelected()
connect(subMenu, SIGNAL(triggered(QAction*)),
this, SLOT(slotInstrumentSelected(QAction*)));
currentSubMenu = subMenu;
} else if (!instrUsedByMe) {
// Search the tracks to see if anyone else is using this
// instrument
for (Composition::trackcontainer::iterator tit =
comp.getTracks().begin();
tit != comp.getTracks().end(); ++tit) {
if (tit->second->getInstrument() == (*it)->getId()) {
instrUsedByAnyone = true;
break;
}
}
}
QIcon icon
(connectedIcon ?
(instrUsedByAnyone ?
instrUsedByMe ?
connectedSelectedPixmap :
connectedUsedPixmap : connectedPixmap) :
(instrUsedByAnyone ?
instrUsedByMe ?
unconnectedSelectedPixmap :
unconnectedUsedPixmap : unconnectedPixmap));
// Create an action for this instrument
QAction* action = new QAction(instrumentPopup);
action->setIcon(icon);
// Not needed so long as AA_DontShowIconsInMenus is false.
//action->setIconVisibleInMenu(true);
// Action text
if (programName != "") iname += " (" + programName + ")";
action->setText(iname);
// Item index used to find the proper instrument once the user makes
// a selection from the menu.
action->setData(QVariant(count));
// QObject object name.
action->setObjectName(iname + QString(count));
// Add the action to the current submenu
if (currentSubMenu)
currentSubMenu->addAction(action);
// Next item index
count++;
}
}
void
TrackButtons::slotInstrumentSelected(QAction* action)
{
// The action data field has the instrument index.
slotInstrumentSelected(action->data().toInt());
}
void
TrackButtons::selectInstrument(Track *track, Instrument *instrument)
{
// Inform the rest of the system of the instrument change.
// ??? This routine needs to go for two reasons:
//
// 1. TrackParameterBox calls this. UI to UI connections should be
// avoided. It would be better to copy/paste this over to TPB
// to avoid the connection. But then we have double-maintenance.
// See reason 2.
//
// 2. The UI shouldn't know so much about the other objects in the
// system. The following updates should be done by their
// respective objects.
//
// A "TrackStaticSignals::instrumentChanged(Track *, Instrument *)"
// notification is probably the best way to get rid of this routine.
// It could be emitted from Track::setInstrument(). Normally emitting
// from setters is bad, but in this case, it is necessary. We need
// to know about every single change when it occurs.
// Then ControlBlockSignalHandler (new class to avoid deriving
// ControlBlock from QObject), InstrumentSignalHandler (new class to
// handle signals for all Instrument instances), and
// SequenceManager (already derives from QObject, might want to
// consider a new SequenceManagerSignalHandler to avoid additional
// dependency on QObject) can connect and do what needs to be done in
// response. Rationale for this over doc modified is that we
// can't simply refresh everything (Instrument::sendChannelSetup()
// sends out data), and it is expensive to detect what has actually
// changed (we would have to cache the Track->Instrument mapping and
// check it for changes).
const TrackId trackId = track->getId();
// *** ControlBlock
ControlBlock::getInstance()->
setInstrumentForTrack(trackId, instrument->getId());
// *** Send out BS/PC
// Make sure the Device is in sync with the Instrument's settings.
instrument->sendChannelSetup();
// *** SequenceManager
// In case the sequencer is currently playing, we need to regenerate
// all the events with the new channel number.
Composition &comp = m_doc->getComposition();
SequenceManager *sequenceManager = m_doc->getSequenceManager();
// For each segment in the composition
for (Composition::iterator i = comp.begin();
i != comp.end();
++i) {
Segment *segment = (*i);
// If this Segment is on this Track, let SequenceManager know
// that the Instrument has changed.
// Segments on this track are now playing on a new
// instrument, so they're no longer ready (making them
// ready is done just-in-time elsewhere), nor is thru
// channel ready.
if (segment->getTrack() == trackId)
sequenceManager->segmentInstrumentChanged(segment);
}
}
void
TrackButtons::slotInstrumentSelected(int instrumentIndex)
{
//RG_DEBUG << "slotInstrumentSelected(): instrumentIndex =" << instrumentIndex;
Instrument *instrument =
m_doc->getStudio().getInstrumentFromList(instrumentIndex);
//RG_DEBUG << "slotInstrumentSelected(): instrument " << inst;
if (!instrument) {
RG_WARNING << "slotInstrumentSelected(): WARNING: Can't find Instrument";
return;
}
Composition &comp = m_doc->getComposition();
Track *track = comp.getTrackByPosition(m_popupTrackPos);
if (!track) {
RG_WARNING << "slotInstrumentSelected(): WARNING: Can't find Track";
return;
}
// No change? Bail.
if (instrument->getId() == track->getInstrument())
return;
// Select the new instrument for the track.
// ??? This sends a trackChanged() notification. It shouldn't. We should
// send one here.
track->setInstrument(instrument->getId());
// ??? This is what we should do.
//comp.notifyTrackChanged(track);
m_doc->slotDocumentModified();
// Notify IPB, ControlBlock, and SequenceManager.
selectInstrument(track, instrument);
}
void
TrackButtons::changeLabelDisplayMode(TrackLabel::DisplayMode mode)
{
// Set new mode
m_labelDisplayMode = mode;
// For each track, set the display mode and update.
for (int i = 0; i < m_tracks; i++) {
m_trackLabels[i]->setDisplayMode(mode);
m_trackLabels[i]->updateLabel();
}
}
void
TrackButtons::slotSynchroniseWithComposition()
{
//RG_DEBUG << "slotSynchroniseWithComposition()";
Composition &comp = m_doc->getComposition();
for (int i = 0; i < m_tracks; i++) {
updateUI(comp.getTrackByPosition(i));
}
}
#if 0
void
TrackButtons::slotLabelSelected(int position)
{
Track *track =
m_doc->getComposition().getTrackByPosition(position);
if (track) {
emit trackSelected(track->getId());
}
}
#endif
void
TrackButtons::slotTPBInstrumentSelected(TrackId trackId, int instrumentIndex)
{
//RG_DEBUG << "TrackButtons::slotTPBInstrumentSelected( trackId =" << trackId << ", instrumentIndex =" << instrumentIndex << ")";
// Set the position for slotInstrumentSelected().
// ??? This isn't good. Should have a selectTrack() that takes the
// track position and the instrument index. slotInstrumentSelected()
// could call it.
m_popupTrackPos =
m_doc->getComposition().getTrackById(trackId)->getPosition();
slotInstrumentSelected(instrumentIndex);
}
int
TrackButtons::labelWidth()
{
return m_trackLabelWidth -
((m_cellSize - m_buttonGap) * 2 + m_vuSpacing * 2 + m_vuWidth);
}
int
TrackButtons::trackHeight(TrackId trackId)
{
int multiple = m_doc->
getComposition().getMaxContemporaneousSegmentsOnTrack(trackId);
if (multiple == 0)
multiple = 1;
return m_cellSize * multiple - m_borderGap;
}
QFrame*
TrackButtons::makeButton(Track *track)
{
if (track == nullptr) return nullptr;
TrackId trackId = track->getId();
// *** Horizontal Box ***
QFrame *trackHBox = new QFrame(this);
QHBoxLayout *hblayout = new QHBoxLayout(trackHBox);
trackHBox->setLayout(hblayout);
hblayout->setMargin(0);
hblayout->setSpacing(0);
trackHBox->setMinimumSize(labelWidth(), trackHeight(trackId));
trackHBox->setFixedHeight(trackHeight(trackId));
trackHBox->setFrameShape(QFrame::StyledPanel);
trackHBox->setFrameShadow(QFrame::Raised);
// We will be changing the background color, so turn on auto-fill.
trackHBox->setAutoFillBackground(true);
// Insert a little gap
hblayout->addSpacing(m_vuSpacing);
// *** VU Meter ***
TrackVUMeter *vuMeter = new TrackVUMeter(trackHBox,
VUMeter::PeakHold,
m_vuWidth,
m_buttonGap,
track->getPosition());
m_trackMeters.push_back(vuMeter);
hblayout->addWidget(vuMeter);
// Insert a little gap
hblayout->addSpacing(m_vuSpacing);
// *** Mute LED ***
LedButton *mute = new LedButton(
GUIPalette::getColour(GUIPalette::MuteTrackLED), trackHBox);
mute->setToolTip(tr("Mute track"));
hblayout->addWidget(mute);
connect(mute, SIGNAL(stateChanged(bool)),
m_muteSigMapper, SLOT(map()));
m_muteSigMapper->setMapping(mute, track->getPosition());
m_muteLeds.push_back(mute);
mute->setFixedSize(m_cellSize - m_buttonGap, m_cellSize - m_buttonGap);
// *** Record LED ***
Rosegarden::Instrument *ins =
m_doc->getStudio().getInstrumentById(track->getInstrument());
LedButton *record = new LedButton(getRecordLedColour(ins), trackHBox);
record->setToolTip(tr("Record on this track"));
hblayout->addWidget(record);
connect(record, SIGNAL(stateChanged(bool)),
m_recordSigMapper, SLOT(map()));
m_recordSigMapper->setMapping(record, track->getPosition());
m_recordLeds.push_back(record);
record->setFixedSize(m_cellSize - m_buttonGap, m_cellSize - m_buttonGap);
// *** Solo LED ***
LedButton *solo = new LedButton(
GUIPalette::getColour(GUIPalette::SoloTrackLED), trackHBox);
solo->setToolTip(tr("Solo track"));
hblayout->addWidget(solo);
connect(solo, SIGNAL(stateChanged(bool)),
m_soloSigMapper, SLOT(map()));
m_soloSigMapper->setMapping(solo, track->getPosition());
m_soloLeds.push_back(solo);
solo->setFixedSize(m_cellSize - m_buttonGap, m_cellSize - m_buttonGap);
// *** Track Label ***
TrackLabel *trackLabel =
new TrackLabel(trackId, track->getPosition(), trackHBox);
hblayout->addWidget(trackLabel);
hblayout->addSpacing(m_vuSpacing);
trackLabel->setDisplayMode(m_labelDisplayMode);
trackLabel->setFixedSize(labelWidth(), m_cellSize - m_buttonGap);
trackLabel->setFixedHeight(m_cellSize - m_buttonGap);
trackLabel->setIndent(7);
connect(trackLabel, &TrackLabel::renameTrack,
this, &TrackButtons::slotRenameTrack);
m_trackLabels.push_back(trackLabel);
// Connect it
setButtonMapping(trackLabel, trackId);
connect(trackLabel, SIGNAL(changeToInstrumentList()),
m_instListSigMapper, SLOT(map()));
connect(trackLabel, SIGNAL(clicked()),
m_clickedSigMapper, SLOT(map()));
return trackHBox;
}
QColor
TrackButtons::getRecordLedColour(Instrument *ins)
{
if (!ins) return Qt::white;
switch (ins->getType()) {
case Instrument::Audio:
return GUIPalette::getColour(GUIPalette::RecordAudioTrackLED);
case Instrument::SoftSynth:
return GUIPalette::getColour(GUIPalette::RecordSoftSynthTrackLED);
case Instrument::Midi:
return GUIPalette::getColour(GUIPalette::RecordMIDITrackLED);
case Instrument::InvalidInstrument:
default:
RG_DEBUG << "TrackButtons::slotUpdateTracks() - invalid instrument type, this is probably a BUG!";
return Qt::green;
}
}
void
TrackButtons::tracksAdded(const Composition *, std::vector<TrackId> &/*trackIds*/)
{
//RG_DEBUG << "TrackButtons::tracksAdded()";
// ??? This is a bit heavy-handed as it just adds a track button, then
// recreates all the track buttons. We might be able to just add the
// one that is needed.
slotUpdateTracks();
}
void
TrackButtons::trackChanged(const Composition *, Track* track)
{
//RG_DEBUG << "trackChanged()";
//RG_DEBUG << " Position:" << track->getPosition();
//RG_DEBUG << " Armed:" << track->isArmed();
updateUI(track);
}
void
TrackButtons::tracksDeleted(const Composition *, std::vector<TrackId> &/*trackIds*/)
{
//RG_DEBUG << "TrackButtons::tracksDeleted()";
// ??? This is a bit heavy-handed as it just deletes a track button,
// then recreates all the track buttons. We might be able to just
// delete the one that is going away.
slotUpdateTracks();
}
void
TrackButtons::trackSelectionChanged(const Composition *, TrackId trackId)
{
//RG_DEBUG << "TrackButtons::trackSelectionChanged()" << trackId;
Track *track = m_doc->getComposition().getTrackById(trackId);
selectTrack(track->getPosition());
}
void
TrackButtons::segmentRemoved(const Composition *, Segment *)
{
// If recording causes the track heights to change, this makes sure
// they go back if needed when recording stops.
slotUpdateTracks();
}
void
TrackButtons::slotTrackSelected(int trackId)
{
// Select the track.
m_doc->getComposition().setSelectedTrack(trackId);
// Old notification mechanism
// ??? This should be replaced with emitDocumentModified() below.
m_doc->getComposition().notifyTrackSelectionChanged(trackId);
// Older mechanism. Keeping this until we can completely replace it
// with emitDocumentModified() below.
emit trackSelected(trackId);
// New notification mechanism.
// This should replace all others.
m_doc->emitDocumentModified();
}
void
TrackButtons::slotDocumentModified(bool)
{
// Full and immediate update.
// ??? Note that updates probably happen elsewhere. This will result
// in duplicate updates. All other updates should be removed and
// this should be the only update.
slotUpdateTracks();
}
}
| bownie/RosegardenW | gui/editors/segment/TrackButtons.cpp | C++ | gpl-2.0 | 38,763 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Navigation;
namespace SupCarLocator.ViewModel
{
class PageViewModelBase : BaseViewModel
{
protected NavigationContext NavigationContext;
protected NavigationService NavigationService;
public virtual void OnNavigatedTo(NavigationContext navigationContext, NavigationService navigationService)
{
NavigationContext = navigationContext;
NavigationService = navigationService;
}
}
}
| Dioud/SupCarLocator | SupCarLocator/SupCarLocator/ViewModel/PageViewModelBase.cs | C# | gpl-2.0 | 605 |
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.6 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2015 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2015
*
* Generated from xml/schema/CRM/Contribute/Premium.xml
* DO NOT EDIT. Generated by CRM_Core_CodeGen
*/
require_once 'CRM/Core/DAO.php';
require_once 'CRM/Utils/Type.php';
class CRM_Contribute_DAO_Premium extends CRM_Core_DAO {
/**
* static instance to hold the table name
*
* @var string
*/
static $_tableName = 'civicrm_premiums';
/**
* static instance to hold the field values
*
* @var array
*/
static $_fields = null;
/**
* static instance to hold the keys used in $_fields for each field.
*
* @var array
*/
static $_fieldKeys = null;
/**
* static instance to hold the FK relationships
*
* @var string
*/
static $_links = null;
/**
* static instance to hold the values that can
* be imported
*
* @var array
*/
static $_import = null;
/**
* static instance to hold the values that can
* be exported
*
* @var array
*/
static $_export = null;
/**
* static value to see if we should log any modifications to
* this table in the civicrm_log table
*
* @var boolean
*/
static $_log = true;
/**
*
* @var int unsigned
*/
public $id;
/**
* Joins these premium settings to another object. Always civicrm_contribution_page for now.
*
* @var string
*/
public $entity_table;
/**
*
* @var int unsigned
*/
public $entity_id;
/**
* Is the Premiums feature enabled for this page?
*
* @var boolean
*/
public $premiums_active;
/**
* Title for Premiums section.
*
* @var string
*/
public $premiums_intro_title;
/**
* Displayed in <div> at top of Premiums section of page. Text and HTML allowed.
*
* @var text
*/
public $premiums_intro_text;
/**
* This email address is included in receipts if it is populated and a premium has been selected.
*
* @var string
*/
public $premiums_contact_email;
/**
* This phone number is included in receipts if it is populated and a premium has been selected.
*
* @var string
*/
public $premiums_contact_phone;
/**
* Boolean. Should we automatically display minimum contribution amount text after the premium descriptions.
*
* @var boolean
*/
public $premiums_display_min_contribution;
/**
* Label displayed for No Thank-you option in premiums block (e.g. No thank you)
*
* @var string
*/
public $premiums_nothankyou_label;
/**
*
* @var int unsigned
*/
public $premiums_nothankyou_position;
/**
* class constructor
*
* @return civicrm_premiums
*/
function __construct() {
$this->__table = 'civicrm_premiums';
parent::__construct();
}
/**
* Returns foreign keys and entity references
*
* @return array
* [CRM_Core_Reference_Interface]
*/
static function getReferenceColumns() {
if (!self::$_links) {
self::$_links = static ::createReferenceColumns(__CLASS__);
self::$_links[] = new CRM_Core_Reference_Dynamic(self::getTableName() , 'entity_id', NULL, 'id', 'entity_table');
}
return self::$_links;
}
/**
* Returns all the column names of this table
*
* @return array
*/
static function &fields() {
if (!(self::$_fields)) {
self::$_fields = array(
'id' => array(
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Premium ID') ,
'required' => true,
) ,
'entity_table' => array(
'name' => 'entity_table',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Premium Entity') ,
'description' => 'Joins these premium settings to another object. Always civicrm_contribution_page for now.',
'required' => true,
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
) ,
'entity_id' => array(
'name' => 'entity_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Premium entity ID') ,
'required' => true,
) ,
'premiums_active' => array(
'name' => 'premiums_active',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Is Premium Active?') ,
'description' => 'Is the Premiums feature enabled for this page?',
'required' => true,
) ,
'premiums_intro_title' => array(
'name' => 'premiums_intro_title',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Title for Premiums section') ,
'description' => 'Title for Premiums section.',
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
) ,
'premiums_intro_text' => array(
'name' => 'premiums_intro_text',
'type' => CRM_Utils_Type::T_TEXT,
'title' => ts('Premium Introductory Text') ,
'description' => 'Displayed in <div> at top of Premiums section of page. Text and HTML allowed.',
) ,
'premiums_contact_email' => array(
'name' => 'premiums_contact_email',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Premium Contact Email') ,
'description' => 'This email address is included in receipts if it is populated and a premium has been selected.',
'maxlength' => 100,
'size' => CRM_Utils_Type::HUGE,
) ,
'premiums_contact_phone' => array(
'name' => 'premiums_contact_phone',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Premiums Contact Phone') ,
'description' => 'This phone number is included in receipts if it is populated and a premium has been selected.',
'maxlength' => 50,
'size' => CRM_Utils_Type::BIG,
) ,
'premiums_display_min_contribution' => array(
'name' => 'premiums_display_min_contribution',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Display Minimum Contribution?') ,
'description' => 'Boolean. Should we automatically display minimum contribution amount text after the premium descriptions.',
'required' => true,
) ,
'premiums_nothankyou_label' => array(
'name' => 'premiums_nothankyou_label',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('No Thank-you Text') ,
'description' => 'Label displayed for No Thank-you option in premiums block (e.g. No thank you)',
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
) ,
'premiums_nothankyou_position' => array(
'name' => 'premiums_nothankyou_position',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('No Thank-you Position') ,
'default' => '1',
) ,
);
}
return self::$_fields;
}
/**
* Returns an array containing, for each field, the arary key used for that
* field in self::$_fields.
*
* @return array
*/
static function &fieldKeys() {
if (!(self::$_fieldKeys)) {
self::$_fieldKeys = array(
'id' => 'id',
'entity_table' => 'entity_table',
'entity_id' => 'entity_id',
'premiums_active' => 'premiums_active',
'premiums_intro_title' => 'premiums_intro_title',
'premiums_intro_text' => 'premiums_intro_text',
'premiums_contact_email' => 'premiums_contact_email',
'premiums_contact_phone' => 'premiums_contact_phone',
'premiums_display_min_contribution' => 'premiums_display_min_contribution',
'premiums_nothankyou_label' => 'premiums_nothankyou_label',
'premiums_nothankyou_position' => 'premiums_nothankyou_position',
);
}
return self::$_fieldKeys;
}
/**
* Returns the names of this table
*
* @return string
*/
static function getTableName() {
return CRM_Core_DAO::getLocaleTableName(self::$_tableName);
}
/**
* Returns if this table needs to be logged
*
* @return boolean
*/
function getLog() {
return self::$_log;
}
/**
* Returns the list of fields that can be imported
*
* @param bool $prefix
*
* @return array
*/
static function &import($prefix = false) {
if (!(self::$_import)) {
self::$_import = array();
$fields = self::fields();
foreach($fields as $name => $field) {
if (CRM_Utils_Array::value('import', $field)) {
if ($prefix) {
self::$_import['premiums'] = & $fields[$name];
} else {
self::$_import[$name] = & $fields[$name];
}
}
}
}
return self::$_import;
}
/**
* Returns the list of fields that can be exported
*
* @param bool $prefix
*
* @return array
*/
static function &export($prefix = false) {
if (!(self::$_export)) {
self::$_export = array();
$fields = self::fields();
foreach($fields as $name => $field) {
if (CRM_Utils_Array::value('export', $field)) {
if ($prefix) {
self::$_export['premiums'] = & $fields[$name];
} else {
self::$_export[$name] = & $fields[$name];
}
}
}
}
return self::$_export;
}
}
| eastoncat/cm.eastoncat | sites/all/modules/contrib/civicrm/CRM/Contribute/DAO/Premium.php | PHP | gpl-2.0 | 10,862 |
<?php
/**
* EXHIBIT A. Common Public Attribution License Version 1.0
* The contents of this file are subject to the Common Public Attribution License Version 1.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.oxwall.org/license. The License is based on the Mozilla Public License Version 1.1
* but Sections 14 and 15 have been added to cover use of software over a computer network and provide for
* limited attribution for the Original Developer. In addition, Exhibit A has been modified to be consistent
* with Exhibit B. 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 Oxwall software.
* The Initial Developer of the Original Code is Oxwall Foundation (http://www.oxwall.org/foundation).
* All portions of the code written by Oxwall Foundation are Copyright (c) 2011. All Rights Reserved.
* EXHIBIT B. Attribution Information
* Attribution Copyright Notice: Copyright 2011 Oxwall Foundation. All rights reserved.
* Attribution Phrase (not exceeding 10 words): Powered by Oxwall community software
* Attribution URL: http://www.oxwall.org/
* Graphic Image as provided in the Covered Code.
* Display of Attribution Information is required in Larger Works which are defined in the CPAL as a work
* which combines Covered Code or portions thereof with code not governed by the terms of the CPAL.
*/
/**
* Collector event
*
* @author Sergey Kambalin <greyexpert@gmail.com>
* @package ow_system_plugins.base.bol
* @since 1.0
*/
class BASE_CLASS_EventCollector extends OW_Event
{
public function __construct( $name, $params = array() )
{
parent::__construct($name, $params);
$this->data = array();
}
public function add( $item )
{
$this->data[] = $item;
}
public function setData( $data )
{
throw new LogicException("Can't set data in collector event `" . $this->getName() . "`!");
}
} | locthdev/shopthoitrang-oxwall | ow_system_plugins/base/classes/event_collector.php | PHP | gpl-2.0 | 2,181 |
package org.mo.game.editor.face.apl.logic.report;
import org.mo.jfa.common.page.FAbstractFormPage;
public class FWebReportPage
extends FAbstractFormPage{
private static final long serialVersionUID = 1L;
private String _tempName;
public String getTempName(){
return _tempName;
}
public void setTempName(String tempName){
_tempName = tempName;
}
}
| favedit/MoPlatform | mo-gm-develop/src/editor-face/org/mo/game/editor/face/apl/logic/report/FWebReportPage.java | Java | gpl-2.0 | 389 |
import xml.etree.ElementTree as ET
import requests
from flask import Flask
import batalha
import pokemon
import ataque
class Cliente:
def __init__(self, execute = False, ip = '127.0.0.1', port = 5000, npc = False):
self.ip = ip
self.port = port
self.npc = npc
if (execute):
self.iniciaBatalha()
def writeXML(self, pkmn):
#Escreve um XML a partir de um pokemon
root = ET.Element('battle_state')
ET.SubElement(root, "pokemon")
poke = root.find('pokemon')
ET.SubElement(poke, "name")
poke.find('name').text = pkmn.getNome()
ET.SubElement(poke, "level")
poke.find('level').text = str(pkmn.getLvl())
ET.SubElement(poke, "attributes")
poke_att = poke.find('attributes')
ET.SubElement(poke_att, "health")
poke_att.find('health').text = str(pkmn.getHp())
ET.SubElement(poke_att, "attack")
poke_att.find('attack').text = str(pkmn.getAtk())
ET.SubElement(poke_att, "defense")
poke_att.find('defense').text = str(pkmn.getDefe())
ET.SubElement(poke_att, "speed")
poke_att.find('speed').text = str(pkmn.getSpd())
ET.SubElement(poke_att, "special")
poke_att.find('special').text = str(pkmn.getSpc())
ET.SubElement(poke, "type")
ET.SubElement(poke, "type")
tipos = poke.findall('type')
tipos[0].text = str(pkmn.getTyp1())
tipos[1].text = str(pkmn.getTyp2())
for i in range(0, 4):
atk = pkmn.getAtks(i)
if (atk is not None):
ET.SubElement(poke, "attacks")
poke_atk = poke.findall('attacks')
ET.SubElement(poke_atk[-1], "id")
poke_atk[-1].find('id').text = str(i + 1)
ET.SubElement(poke_atk[-1], "name")
poke_atk[-1].find('name').text = atk.getNome()
ET.SubElement(poke_atk[-1], "type")
poke_atk[-1].find('type').text = str(atk.getTyp())
ET.SubElement(poke_atk[-1], "power")
poke_atk[-1].find('power').text = str(atk.getPwr())
ET.SubElement(poke_atk[-1], "accuracy")
poke_atk[-1].find('accuracy').text = str(atk.getAcu())
ET.SubElement(poke_atk[-1], "power_points")
poke_atk[-1].find('power_points').text = str(atk.getPpAtual())
s = ET.tostring(root)
return s
def iniciaBatalha(self):
pkmn = pokemon.Pokemon()
xml = self.writeXML(pkmn)
try:
self.battle_state = requests.post('http://{}:{}/battle/'.format(self.ip, self.port), data = xml).text
except requests.exceptions.ConnectionError:
print("Não foi possível conectar ao servidor.")
return None
pkmn2 = pokemon.lePokemonXML(1, self.battle_state)
self.batalha = batalha.Batalha([pkmn, pkmn2])
if (self.npc):
self.batalha.pkmn[0].npc = True
print("Eu sou um NPC")
self.batalha.turno = 0
self.batalha.display.showPokemon(self.batalha.pkmn[0])
self.batalha.display.showPokemon(self.batalha.pkmn[1])
return self.atualizaBatalha()
def atualizaBatalha(self):
self.batalha.AlternaTurno()
root = ET.fromstring(self.battle_state)
for i in range(0,2):
pkmnXML = root[i]
atksXML = root[i].findall('attacks')
pkmn = self.batalha.pkmn[i]
pkmn.setHpAtual(int(pkmnXML.find('attributes').find('health').text))
self.batalha.showStatus()
if (not self.batalha.isOver()):
self.batalha.AlternaTurno()
if (self.batalha.pkmn[self.batalha.turno].npc):
id = self.batalha.EscolheAtaqueInteligente()
else:
id = self.batalha.EscolheAtaque()
self.batalha.pkmn[0].getAtks(id).decreasePp()
if (id == 4):
self.battle_state = requests.post('http://{}:{}/battle/attack/{}'.format(self.ip, self.port, 0)).text
else:
self.battle_state = requests.post('http://{}:{}/battle/attack/{}'.format(self.ip, self.port, id + 1)).text
self.simulaAtaque(id)
self.atualizaBatalha()
else:
self.batalha.showResults()
return 'FIM'
def sendShutdownSignal(self):
requests.post('http://{}:{}/shutdown'.format(self.ip, self.port))
def simulaAtaque(self, idCliente):
disp = self.batalha.display
root = ET.fromstring(self.battle_state)
pkmnCXML = root[0]
pkmnC = self.batalha.pkmn[0]
pkmnSXML = root[1]
pkmnS = self.batalha.pkmn[1]
atksXML = pkmnSXML.findall('attacks')
idServidor = self.descobreAtaqueUsado(atksXML, pkmnS)
if (int(pkmnSXML.find('attributes').find('health').text) > 0):
if (idCliente != 4):
if (idServidor != 4):
dmg = pkmnS.getHpAtual() - int(pkmnSXML.find('attributes').find('health').text)
if (dmg == 0):
disp.miss(pkmnC, pkmnS, pkmnC.getAtks(idCliente))
else:
disp.hit(pkmnC, pkmnS, pkmnC.getAtks(idCliente), dmg)
dmg = pkmnC.getHpAtual() - int(pkmnCXML.find('attributes').find('health').text)
if (dmg == 0):
disp.miss(pkmnS, pkmnC, pkmnS.getAtks(idServidor))
else:
disp.hit(pkmnS, pkmnC, pkmnS.getAtks(idServidor), dmg)
else:
dmgStruggle = pkmnC.getHpAtual() - int(pkmnCXML.find('attributes').find('health').text)
dmg = pkmnS.getHpAtual() - int(pkmnSXML.find('attributes').find('health').text) + round(dmgStruggle / 2, 0)
if (dmg == 0):
disp.miss(pkmnC, pkmnS, pkmnC.getAtks(idCliente))
else:
disp.hit(pkmnC, pkmnS, pkmnC.getAtks(idCliente), dmg)
disp.hit(pkmnS, pkmnC, pkmnS.getAtks(idServidor), dmgStruggle)
disp.hitSelf(pkmnS, round(dmgStruggle / 2, 0))
else:
if (idServidor != 4):
dmgStruggle = pkmnS.getHpAtual() - int(pkmnSXML.find('attributes').find('health').text)
disp.hit(pkmnC, pkmnS, pkmnC.getAtks(idCliente), dmgStruggle)
disp.hitSelf(pkmnC, round(dmgStruggle / 2, 0))
dmg = pkmnC.getHpAtual() - int(pkmnCXML.find('attributes').find('health').text) + round(dmgStruggle / 2, 0)
if (dmg == 0):
disp.miss(pkmnS, pkmnC, pkmnS.getAtks(idServidor))
else:
disp.hit(pkmnS, pkmnC, pkmnS.getAtks(idServidor), dmg)
else:
print('Ambos usam e se machucam com Struggle!')
else:
if (idCliente != 4):
dmg = pkmnS.getHpAtual() - int(pkmnSXML.find('attributes').find('health').text)
if (dmg == 0):
disp.miss(pkmnC, pkmnS, pkmnC.getAtks(idCliente))
else:
disp.hit(pkmnC, pkmnS, pkmnC.getAtks(idCliente), dmg)
else:
dmgStruggle = pkmnC.getHpAtual() - int(pkmnCXML.find('attributes').find('health').text)
disp.hit(pkmnC, pkmnS, pkmnC.getAtks(idServidor), dmgStruggle * 2)
disp.hitSelf(pkmnC, round(dmgStruggle, 0))
def descobreAtaqueUsado(self, atksXML, pkmn):
for i in range(0, len(atksXML)):
id = int(atksXML[i].find('id').text) - 1
ppXML = int(atksXML[i].find('power_points').text)
pp = pkmn.getAtks(id).getPpAtual()
if (pp != ppXML):
pkmn.getAtks(id).decreasePp()
return id
return id
| QuartetoFantastico/projetoPokemon | cliente.py | Python | gpl-2.0 | 6,564 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Net;
using System.Collections;
using System.Web;
using System.Xml;
using System.Reflection;
using Microsoft.Win32;
using System.Globalization;
using Microsoft.FlightSimulator.SimConnect;
using System.Runtime.InteropServices;
namespace FSX_Google_Earth_Tracker
{
public partial class Form1 : Form
{
#region Global Variables
bool bErrorOnLoad = false;
Form2 frmAdd = new Form2();
String szAppPath = "";
//String szCommonPath = "";
String szUserAppPath = "";
String szFilePathPub = "";
String szFilePathData = "";
String szServerPath = "";
IPAddress[] ipalLocal1 = null;
IPAddress[] ipalLocal2 = null;
System.Object lockIPAddressList = new System.Object();
string /* szPathGE , */ szPathFSX;
const string szRegKeyRun = "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run";
//const int iOnlineVersionCheckRawDataLength = 64;
//WebRequest wrOnlineVersionCheck;
//WebResponse wrespOnlineVersionCheck;
//private byte[] bOnlineVersionCheckRawData = new byte[iOnlineVersionCheckRawDataLength];
//String szOnlineVersionCheckData = "";
XmlTextReader xmlrSeetingsFile;
XmlTextWriter xmlwSeetingsFile;
XmlDocument xmldSettings;
GlobalFixConfiguration gconffixCurrent = new GlobalFixConfiguration();
GlobalChangingConfiguration gconfchCurrent;
System.Object lockChConf = new System.Object();
bool bClose = false;
bool bConnected = false;
//bool bServerUp = false;
bool bRestartRequired = false;
const int WM_USER_SIMCONNECT = 0x0402;
SimConnect simconnect = null;
Icon icActive, icDisabled, icReceive;
Image imgAtcLabel;
HttpListener listener;
System.Object lockListenerControl = new System.Object();
uint uiUserAircraftID = 0;
bool bUserAircraftIDSet = false;
System.Object lockUserAircraftID = new System.Object();
StructBasicMovingSceneryObject suadCurrent;
System.Object lockKmlUserAircraft = new System.Object();
String szKmlUserAircraftPath = "";
System.Object lockKmlUserPath = new System.Object();
PathPosition ppPos1, ppPos2;
String szKmlUserPrediction = "";
List<PathPositionStored> listKmlPredictionPoints;
System.Object lockKmlUserPrediction = new System.Object();
System.Object lockKmlPredictionPoints = new System.Object();
DataRequestReturn drrAIPlanes;
System.Object lockDrrAiPlanes = new System.Object();
DataRequestReturn drrAIHelicopters;
System.Object lockDrrAiHelicopters = new System.Object();
DataRequestReturn drrAIBoats;
System.Object lockDrrAiBoats = new System.Object();
DataRequestReturn drrAIGround;
System.Object lockDrrAiGround = new System.Object();
List<ObjectImage> listIconsGE;
List<ObjectImage> listImgUnitsAir, listImgUnitsWater, listImgUnitsGround;
//List<FlightPlan> listFlightPlans;
//System.Object lockFlightPlanList = new System.Object();
byte[] imgNoImage;
#endregion
#region Structs & Enums
enum DEFINITIONS
{
StructBasicMovingSceneryObject,
};
enum DATA_REQUESTS
{
REQUEST_USER_AIRCRAFT,
REQUEST_USER_PATH,
REQUEST_USER_PREDICTION,
REQUEST_AI_HELICOPTER,
REQUEST_AI_PLANE,
REQUEST_AI_BOAT,
REQUEST_AI_GROUND
};
enum KML_FILES
{
REQUEST_USER_AIRCRAFT,
REQUEST_USER_PATH,
REQUEST_USER_PREDICTION,
REQUEST_AI_HELICOPTER,
REQUEST_AI_PLANE,
REQUEST_AI_BOAT,
REQUEST_AI_GROUND,
REQUEST_FLIGHT_PLANS
};
enum KML_ACCESS_MODES
{
MODE_SERVER,
MODE_FILE_LOCAL,
MODE_FILE_USERDEFINED
};
enum KML_IMAGE_TYPES
{
AIRCRAFT,
WATER,
GROUND
};
enum KML_ICON_TYPES
{
USER_AIRCRAFT_POSITION,
USER_PREDICTION_POINT,
AI_AIRCRAFT_PREDICTION_POINT,
AI_HELICOPTER_PREDICTION_POINT,
AI_BOAT_PREDICTION_POINT,
AI_GROUND_PREDICTION_POINT,
AI_AIRCRAFT,
AI_HELICOPTER,
AI_BOAT,
AI_GROUND_UNIT,
PLAN_VOR,
PLAN_NDB,
PLAN_USER,
PLAN_PORT,
PLAN_INTER,
ATC_LABEL,
UNKNOWN
};
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
struct StructBasicMovingSceneryObject
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
public String szTitle;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public String szATCType;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public String szATCModel;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public String szATCID;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 64)]
public String szATCAirline;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public String szATCFlightNumber;
public double dLatitude;
public double dLongitude;
public double dAltitude;
public double dSpeed;
public double dVSpeed;
//public double dSpeedX;
//public double dSpeedY;
//public double dSpeedZ;
public double dTime;
};
struct DataRequestReturn
{
public List<DataRequestReturnObject> listFirst;
public List<DataRequestReturnObject> listSecond;
public uint uiLastEntryNumber;
public uint uiCurrentDataSet;
public bool bClearOnNextRun;
};
struct DataRequestReturnObject
{
public uint uiObjectID;
public StructBasicMovingSceneryObject bmsoObject;
public String szCoursePrediction;
public PathPositionStored[] ppsPredictionPoints;
}
struct PathPosition
{
public bool bInitialized;
public double dLat;
public double dLong;
public double dAlt;
public double dTime;
}
struct PathPositionStored
{
public double dLat;
public double dLong;
public double dAlt;
public double dTime;
}
struct ObjectImage
{
public String szTitle;
public String szPath;
public byte[] bData;
};
class GlobalFixConfiguration
{
public bool bLoadKMLFile;
//public bool bCheckForUpdates;
public long iServerPort;
public uint uiServerAccessLevel;
public String szUserdefinedPath;
public bool bQueryUserAircraft;
public long iTimerUserAircraft;
public bool bQueryUserPath;
public long iTimerUserPath;
public bool bUserPathPrediction;
public long iTimerUserPathPrediction;
public double[] dPredictionTimes;
public bool bQueryAIObjects;
public bool bQueryAIAircrafts;
public long iTimerAIAircrafts;
public long iRangeAIAircrafts;
public bool bPredictAIAircrafts;
public bool bPredictPointsAIAircrafts;
public bool bQueryAIHelicopters;
public long iTimerAIHelicopters;
public long iRangeAIHelicopters;
public bool bPredictAIHelicopters;
public bool bPredictPointsAIHelicopters;
public bool bQueryAIBoats;
public long iTimerAIBoats;
public long iRangeAIBoats;
public bool bPredictAIBoats;
public bool bPredictPointsAIBoats;
public bool bQueryAIGroundUnits;
public long iTimerAIGroundUnits;
public long iRangeAIGroundUnits;
public bool bPredictAIGroundUnits;
public bool bPredictPointsAIGroundUnits;
public long iUpdateGEUserAircraft;
public long iUpdateGEUserPath;
public long iUpdateGEUserPrediction;
public long iUpdateGEAIAircrafts;
public long iUpdateGEAIHelicopters;
public long iUpdateGEAIBoats;
public long iUpdateGEAIGroundUnits;
public bool bFsxConnectionIsLocal;
public String szFsxConnectionProtocol;
public String szFsxConnectionHost;
public String szFsxConnectionPort;
public bool bExitOnFsxExit;
private Object lock_utUnits = new Object();
private UnitType priv_utUnits;
public UnitType utUnits
{
get
{
lock (lock_utUnits)
{
return priv_utUnits;
}
}
set
{
lock (lock_utUnits)
{
priv_utUnits = value;
}
}
}
//public bool bLoadFlightPlans;
};
struct GlobalChangingConfiguration
{
public bool bEnabled;
public bool bShowBalloons;
};
struct ListBoxPredictionTimesItem
{
public double dTime;
public override String ToString()
{
if (dTime < 60)
return "ETA " + dTime + " sec";
else if (dTime < 3600)
return "ETA " + Math.Round(dTime / 60.0, 1) + " min";
else
return "ETA " + Math.Round(dTime / 3600.0, 2) + " hrs";
}
}
enum UnitType
{
METERS,
FEET
};
//struct ListViewFlightPlansItem
//{
// public String szName;
// public int iID;
// public override String ToString()
// {
// return szName.ToString();
// }
//}
//struct FlightPlan
//{
// public int uiID;
// public String szName;
// public XmlDocument xmldPlan;
//}
#endregion
#region Form Functions
public Form1()
{
//As this method doesn't start any other threads we don't need to lock anything here (especially not the config file xml document)
InitializeComponent();
Text = AssemblyTitle;
thrConnect = new Thread(new ThreadStart(openConnectionThreadFunction));
text = Text;
// Set data for the about page
this.labelProductName.Text = AssemblyProduct;
this.labelVersion.Text = String.Format("Version {0}", AssemblyVersion);
this.labelCopyright.Text = AssemblyCopyright;
this.labelCompanyName.Text = AssemblyCompany;
// Set file path
#if DEBUG
szAppPath = Application.StartupPath + "\\..\\..";
szUserAppPath = szAppPath + "\\AppData\\" + AssemblyVersion;
#else
szAppPath = Application.StartupPath;
szUserAppPath = Application.UserAppDataPath;
#endif
szFilePathPub = szAppPath + "\\pub";
szFilePathData = szAppPath + "\\data";
// Check if config file for current user exists
if (!File.Exists(szUserAppPath + "\\settings.cfg"))
{
if (!Directory.Exists(szUserAppPath))
Directory.CreateDirectory(szUserAppPath);
File.Copy(szAppPath + "\\data\\settings.default", szUserAppPath + "\\settings.cfg");
File.SetAttributes(szUserAppPath + "\\settings.cfg", FileAttributes.Normal);
}
// Load config file into memory
xmlrSeetingsFile = new XmlTextReader(szUserAppPath + "\\settings.cfg");
xmldSettings = new XmlDocument();
xmldSettings.PreserveWhitespace = true;
xmldSettings.Load(xmlrSeetingsFile);
xmlrSeetingsFile.Close();
xmlrSeetingsFile = null;
// Make sure we have a config file for the right version
// (future version should contain better checks and update from old config files to new version)
String szConfigVersion = "";
bool bUpdate = false;
try
{
szConfigVersion = xmldSettings["fsxget"]["settings"].Attributes["version"].Value;
}
catch
{
bUpdate = true;
}
if (bUpdate || !szConfigVersion.Equals(ProductVersion.ToLower()))
{
try
{
File.SetAttributes(szUserAppPath + "\\settings.cfg", FileAttributes.Normal);
File.Delete(szUserAppPath + "\\settings.cfg");
File.Copy(szAppPath + "\\data\\settings.default", szUserAppPath + "\\settings.cfg");
File.SetAttributes(szUserAppPath + "\\settings.cfg", FileAttributes.Normal);
xmlrSeetingsFile = new XmlTextReader(szUserAppPath + "\\settings.cfg");
xmldSettings = new XmlDocument();
xmldSettings.PreserveWhitespace = true;
xmldSettings.Load(xmlrSeetingsFile);
xmlrSeetingsFile.Close();
xmlrSeetingsFile = null;
xmldSettings["fsxget"]["settings"].Attributes["version"].Value = ProductVersion;
}
catch
{
MessageBox.Show("The config file for this program cannot be updated. Aborting!", Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
bErrorOnLoad = true;
return;
}
}
// Mirror values we need from config file in memory to variables
try
{
ConfigMirrorToVariables();
}
catch
{
MessageBox.Show("The config file for this program contains errors. Aborting!", Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
bErrorOnLoad = true;
return;
}
// Write SimConnect configuration file
try { File.Delete(szAppPath + "\\SimConnect.cfg"); }
catch { }
if (!gconffixCurrent.bFsxConnectionIsLocal)
{
try
{
StreamWriter swSimConnectCfg = File.CreateText(szAppPath + "\\SimConnect.cfg");
swSimConnectCfg.WriteLine("; FSXGET SimConnect client configuration");
swSimConnectCfg.WriteLine();
swSimConnectCfg.WriteLine("[SimConnect]");
swSimConnectCfg.WriteLine("Protocol=" + gconffixCurrent.szFsxConnectionProtocol);
swSimConnectCfg.WriteLine("Address=" + gconffixCurrent.szFsxConnectionHost);
swSimConnectCfg.WriteLine("Port=" + gconffixCurrent.szFsxConnectionPort);
swSimConnectCfg.WriteLine();
swSimConnectCfg.Flush();
swSimConnectCfg.Close();
swSimConnectCfg.Dispose();
}
catch
{
MessageBox.Show("The SimConnect client configuration file could not be written. Aborting!", Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
bErrorOnLoad = true;
return;
}
}
// Update the notification icon context menu
lock (lockChConf)
{
enableTrackerToolStripMenuItem.Checked = gconfchCurrent.bEnabled;
showBalloonTipsToolStripMenuItem.Checked = gconfchCurrent.bShowBalloons;
}
// Set timer intervals
timerFSXConnect.Interval = 1500;
timerQueryUserAircraft.Interval = (int)gconffixCurrent.iTimerUserAircraft;
timerQueryUserPath.Interval = (int)gconffixCurrent.iTimerUserPath;
timerUserPrediction.Interval = (int)gconffixCurrent.iTimerUserPathPrediction;
timerQueryAIAircrafts.Interval = (int)gconffixCurrent.iTimerAIAircrafts;
timerQueryAIHelicopters.Interval = (int)gconffixCurrent.iTimerAIHelicopters;
timerQueryAIBoats.Interval = (int)gconffixCurrent.iTimerAIBoats;
timerQueryAIGroundUnits.Interval = (int)gconffixCurrent.iTimerAIGroundUnits;
timerIPAddressRefresh.Interval = 10000;
// Set server settings
szServerPath = "http://+:" + gconffixCurrent.iServerPort.ToString();
listener = new HttpListener();
listener.Prefixes.Add(szServerPath + "/");
// Lookup (in the config file) and load program icons, google earth pins and object images
try
{
// notification icons
for (XmlNode xmlnTemp = xmldSettings["fsxget"]["gfx"]["program"]["icons"].FirstChild; xmlnTemp != null; xmlnTemp = xmlnTemp.NextSibling)
{
if (xmlnTemp.NodeType == XmlNodeType.Whitespace)
continue;
if (xmlnTemp.Attributes["Name"].Value == "Taskbar - Enabled")
icActive = new Icon(szFilePathData + xmlnTemp.Attributes["Img"].Value);
else if (xmlnTemp.Attributes["Name"].Value == "Taskbar - Disabled")
icDisabled = new Icon(szFilePathData + xmlnTemp.Attributes["Img"].Value);
else if (xmlnTemp.Attributes["Name"].Value == "Taskbar - Connected")
icReceive = new Icon(szFilePathData + xmlnTemp.Attributes["Img"].Value);
}
notifyIconMain.Icon = icDisabled;
notifyIconMain.Text = this.Text;
notifyIconMain.Visible = true;
// google earth icons
listIconsGE = new List<ObjectImage>(xmldSettings["fsxget"]["gfx"]["ge"]["icons"].ChildNodes.Count);
for (XmlNode xmlnTemp = xmldSettings["fsxget"]["gfx"]["ge"]["icons"].FirstChild; xmlnTemp != null; xmlnTemp = xmlnTemp.NextSibling)
{
if (xmlnTemp.NodeType == XmlNodeType.Whitespace)
continue;
ObjectImage imgTemp = new ObjectImage();
imgTemp.szTitle = xmlnTemp.Attributes["Name"].Value;
imgTemp.bData = File.ReadAllBytes(szFilePathPub + xmlnTemp.Attributes["Img"].Value);
listIconsGE.Add(imgTemp);
}
// no-image image
imgNoImage = File.ReadAllBytes(szFilePathPub + xmldSettings["fsxget"]["gfx"]["scenery"]["noimage"].Attributes["Img"].Value);
// ATC label base image
imgAtcLabel = Image.FromFile(szFilePathData + xmldSettings["fsxget"]["gfx"]["ge"]["atclabel"].Attributes["Img"].Value);
// object images
listImgUnitsAir = new List<ObjectImage>(xmldSettings["fsxget"]["gfx"]["scenery"]["air"].ChildNodes.Count);
for (XmlNode xmlnTemp = xmldSettings["fsxget"]["gfx"]["scenery"]["air"].FirstChild; xmlnTemp != null; xmlnTemp = xmlnTemp.NextSibling)
{
if (xmlnTemp.NodeType == XmlNodeType.Whitespace)
continue;
ObjectImage imgTemp = new ObjectImage();
imgTemp.szTitle = xmlnTemp.Attributes["Name"].Value;
imgTemp.szPath = xmlnTemp.Attributes["Img"].Value;
imgTemp.bData = File.ReadAllBytes(szFilePathPub + xmlnTemp.Attributes["Img"].Value);
listImgUnitsAir.Add(imgTemp);
}
listImgUnitsWater = new List<ObjectImage>(xmldSettings["fsxget"]["gfx"]["scenery"]["water"].ChildNodes.Count);
for (XmlNode xmlnTemp = xmldSettings["fsxget"]["gfx"]["scenery"]["water"].FirstChild; xmlnTemp != null; xmlnTemp = xmlnTemp.NextSibling)
{
if (xmlnTemp.NodeType == XmlNodeType.Whitespace)
continue;
ObjectImage imgTemp = new ObjectImage();
imgTemp.szTitle = xmlnTemp.Attributes["Name"].Value;
imgTemp.szPath = xmlnTemp.Attributes["Img"].Value;
imgTemp.bData = File.ReadAllBytes(szFilePathPub + xmlnTemp.Attributes["Img"].Value);
listImgUnitsWater.Add(imgTemp);
}
listImgUnitsGround = new List<ObjectImage>(xmldSettings["fsxget"]["gfx"]["scenery"]["ground"].ChildNodes.Count);
for (XmlNode xmlnTemp = xmldSettings["fsxget"]["gfx"]["scenery"]["ground"].FirstChild; xmlnTemp != null; xmlnTemp = xmlnTemp.NextSibling)
{
if (xmlnTemp.NodeType == XmlNodeType.Whitespace)
continue;
ObjectImage imgTemp = new ObjectImage();
imgTemp.szTitle = xmlnTemp.Attributes["Name"].Value;
imgTemp.szPath = xmlnTemp.Attributes["Img"].Value;
imgTemp.bData = File.ReadAllBytes(szFilePathPub + xmlnTemp.Attributes["Img"].Value);
listImgUnitsWater.Add(imgTemp);
}
}
catch
{
MessageBox.Show("Could not load all graphics files probably due to errors in the config file. Aborting!", Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
bErrorOnLoad = true;
return;
}
// Initialize some variables
clearDrrStructure(ref drrAIPlanes);
clearDrrStructure(ref drrAIHelicopters);
clearDrrStructure(ref drrAIBoats);
clearDrrStructure(ref drrAIGround);
clearPPStructure(ref ppPos1);
clearPPStructure(ref ppPos2);
//listFlightPlans = new List<FlightPlan>();
listKmlPredictionPoints = new List<PathPositionStored>(gconffixCurrent.dPredictionTimes.GetLength(0));
// Test drive the following function which loads data from the config file, as it will be used regularly later on
try
{
ConfigMirrorToForm();
}
catch
{
MessageBox.Show("The config file for this program contains errors. Aborting!", Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
bErrorOnLoad = true;
return;
}
// Load FSX and Google Earth path from registry
const string szRegKeyFSX = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Microsoft Games\\flight simulator\\10.0";
//const string szRegKeyGE = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Google\\Google Earth Plus";
//const string szRegKeyGE2 = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Google\\Google Earth Pro";
//szPathGE = (string)Registry.GetValue(szRegKeyGE, "InstallDir", "");
//if (szPathGE == "")
// szPathGE = (string)Registry.GetValue(szRegKeyGE2, "InstallDir", "");
szPathFSX = (string)Registry.GetValue(szRegKeyFSX, "SetupPath", "");
//if (szPathGE != "")
//{
// szPathGE += "\\googleearth.exe";
// if (File.Exists(szPathGE))
// runGoogleEarthToolStripMenuItem.Enabled = true;
// else
// runGoogleEarthToolStripMenuItem.Enabled = false;
//}
//else
// runGoogleEarthToolStripMenuItem.Enabled = false;
runGoogleEarthToolStripMenuItem.Enabled = true;
if (szPathFSX != "")
{
szPathFSX += "fsx.exe";
if (File.Exists(szPathFSX))
runMicrosoftFlightSimulatorXToolStripMenuItem.Enabled = true;
else
runMicrosoftFlightSimulatorXToolStripMenuItem.Enabled = false;
}
else
runMicrosoftFlightSimulatorXToolStripMenuItem.Enabled = false;
// Write Google Earth startup KML file
String szTempKMLFile = "";
String szTempKMLFileStatic = "";
if (CompileKMLStartUpFileDynamic("localhost", ref szTempKMLFile) && CompileKMLStartUpFileStatic("localhost", ref szTempKMLFileStatic))
{
try
{
if (!Directory.Exists(szUserAppPath + "\\pub"))
Directory.CreateDirectory(szUserAppPath + "\\pub");
File.WriteAllText(szUserAppPath + "\\pub\\fsxgetd.kml", szTempKMLFile);
File.WriteAllText(szUserAppPath + "\\pub\\fsxgets.kml", szTempKMLFileStatic);
}
catch
{
MessageBox.Show("Could not write KML file for google earth. Aborting!", Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
bErrorOnLoad = true;
return;
}
}
else
{
MessageBox.Show("Could not write KML file for google earth. Aborting!", Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
bErrorOnLoad = true;
return;
}
// Init some never-changing form fields
textBoxLocalPubPath.Text = szFilePathPub;
// Load flight plans
//if (gconffixCurrent.bLoadFlightPlans)
// LoadFlightPlans();
// Online Update Check
//if (gconffixCurrent.bCheckForUpdates)
// checkForProgramUpdate();
}
private void Form1_Load(object sender, EventArgs e)
{
if (bErrorOnLoad)
return;
}
private void Form1_Shown(object sender, EventArgs e)
{
if (bErrorOnLoad)
{
bClose = true;
Close();
}
else
{
Hide();
lock (lockListenerControl)
{
listener.Start();
listener.BeginGetContext(new AsyncCallback(ListenerCallback), listener);
//bServerUp = true;
}
globalConnect();
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (!bClose)
{
e.Cancel = true;
safeHideMainDialog();
}
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
if (bErrorOnLoad)
return;
notifyIconMain.ContextMenuStrip = null;
// Save xml document in memory to config file on disc
xmlwSeetingsFile = new XmlTextWriter(szUserAppPath + "\\settings.cfg", null);
xmldSettings.PreserveWhitespace = true;
xmldSettings.Save(xmlwSeetingsFile);
xmlwSeetingsFile.Flush();
xmlwSeetingsFile.Close();
xmldSettings = null;
// Disconnect with FSX
lock (lockChConf)
{
gconfchCurrent.bEnabled = false;
}
globalDisconnect();
// Stop server
lock (lockListenerControl)
{
//bServerUp = false;
listener.Stop();
listener.Abort();
timerIPAddressRefresh.Stop();
}
// Delete temporary KML file
if (File.Exists(szFilePathPub + "\\fsxget.kml"))
{
try
{
File.Delete(szFilePathPub + "\\fsxget.kml");
}
catch { }
}
if (File.Exists(szAppPath + "\\SimConnect.cfg"))
{
try
{
File.Delete(szAppPath + "\\SimConnect.cfg");
}
catch { }
}
}
protected override void DefWndProc(ref Message m)
{
if (m.Msg == WM_USER_SIMCONNECT)
{
if (simconnect != null)
{
try
{
simconnect.ReceiveMessage();
}
catch
{
#if DEBUG
safeShowBalloonTip(3, "Error", "Error receiving data from FSX!", ToolTipIcon.Error);
#endif
}
}
}
else
base.DefWndProc(ref m);
}
#endregion
#region FSX Connection
Object lock_ConnectThread = new Object();
String text;
public void openConnectionThreadFunction()
{
while (simconnect == null)
{
try
{
simconnect = new SimConnect(text, IntPtr.Zero, WM_USER_SIMCONNECT, null, 0);
}
catch { }
if (simconnect == null)
Thread.Sleep(2000);
}
}
private bool openConnection()
{
if (thrConnect.ThreadState == ThreadState.Unstarted)
{
thrConnect.Start();
return false;
}
else if (thrConnect.ThreadState == ThreadState.Stopped)
{
if (simconnect != null)
{
try
{
simconnect.Dispose();
simconnect = null;
simconnect = new SimConnect(Text, this.Handle, WM_USER_SIMCONNECT, null, 0);
}
catch
{
return false;
}
if (initDataRequest())
return true;
else
{
simconnect = null;
return false;
}
}
else
{
thrConnect = new Thread(new ThreadStart(openConnectionThreadFunction));
thrConnect.Start();
return false;
}
}
else
return false;
}
private void closeConnection()
{
if (simconnect != null)
{
simconnect.Dispose();
simconnect = null;
}
}
private bool initDataRequest()
{
try
{
// listen to connect and quit msgs
simconnect.OnRecvOpen += new SimConnect.RecvOpenEventHandler(simconnect_OnRecvOpen);
simconnect.OnRecvQuit += new SimConnect.RecvQuitEventHandler(simconnect_OnRecvQuit);
// listen to exceptions
simconnect.OnRecvException += new SimConnect.RecvExceptionEventHandler(simconnect_OnRecvException);
// define a data structure
simconnect.AddToDataDefinition(DEFINITIONS.StructBasicMovingSceneryObject, "Title", null, SIMCONNECT_DATATYPE.STRING256, 0.0f, SimConnect.SIMCONNECT_UNUSED);
simconnect.AddToDataDefinition(DEFINITIONS.StructBasicMovingSceneryObject, "ATC Type", null, SIMCONNECT_DATATYPE.STRING32, 0.0f, SimConnect.SIMCONNECT_UNUSED);
simconnect.AddToDataDefinition(DEFINITIONS.StructBasicMovingSceneryObject, "ATC Model", null, SIMCONNECT_DATATYPE.STRING32, 0.0f, SimConnect.SIMCONNECT_UNUSED);
simconnect.AddToDataDefinition(DEFINITIONS.StructBasicMovingSceneryObject, "ATC ID", null, SIMCONNECT_DATATYPE.STRING32, 0.0f, SimConnect.SIMCONNECT_UNUSED);
simconnect.AddToDataDefinition(DEFINITIONS.StructBasicMovingSceneryObject, "ATC Airline", null, SIMCONNECT_DATATYPE.STRING64, 0.0f, SimConnect.SIMCONNECT_UNUSED);
simconnect.AddToDataDefinition(DEFINITIONS.StructBasicMovingSceneryObject, "ATC Flight Number", null, SIMCONNECT_DATATYPE.STRING32, 0.0f, SimConnect.SIMCONNECT_UNUSED);
simconnect.AddToDataDefinition(DEFINITIONS.StructBasicMovingSceneryObject, "Plane Latitude", "degrees", SIMCONNECT_DATATYPE.FLOAT64, 0.0f, SimConnect.SIMCONNECT_UNUSED);
simconnect.AddToDataDefinition(DEFINITIONS.StructBasicMovingSceneryObject, "Plane Longitude", "degrees", SIMCONNECT_DATATYPE.FLOAT64, 0.0f, SimConnect.SIMCONNECT_UNUSED);
simconnect.AddToDataDefinition(DEFINITIONS.StructBasicMovingSceneryObject, "Plane Altitude", "meters", SIMCONNECT_DATATYPE.FLOAT64, 0.0f, SimConnect.SIMCONNECT_UNUSED);
simconnect.AddToDataDefinition(DEFINITIONS.StructBasicMovingSceneryObject, "Ground Velocity", "knots", SIMCONNECT_DATATYPE.FLOAT64, 0.0f, SimConnect.SIMCONNECT_UNUSED);
simconnect.AddToDataDefinition(DEFINITIONS.StructBasicMovingSceneryObject, "Velocity World Y", "meter per second", SIMCONNECT_DATATYPE.FLOAT64, 0.0f, SimConnect.SIMCONNECT_UNUSED);
//simconnect.AddToDataDefinition(DEFINITIONS.StructBasicMovingSceneryObject, "Velocity World X", "meter per second", SIMCONNECT_DATATYPE.FLOAT64, 0.0f, SimConnect.SIMCONNECT_UNUSED);
//simconnect.AddToDataDefinition(DEFINITIONS.StructBasicMovingSceneryObject, "Velocity World Y", "meter per second", SIMCONNECT_DATATYPE.FLOAT64, 0.0f, SimConnect.SIMCONNECT_UNUSED);
//simconnect.AddToDataDefinition(DEFINITIONS.StructBasicMovingSceneryObject, "Velocity World Z", "meter per second", SIMCONNECT_DATATYPE.FLOAT64, 0.0f, SimConnect.SIMCONNECT_UNUSED);
simconnect.AddToDataDefinition(DEFINITIONS.StructBasicMovingSceneryObject, "Absolute Time", "seconds", SIMCONNECT_DATATYPE.FLOAT64, 0.0f, SimConnect.SIMCONNECT_UNUSED);
// IMPORTANT: register it with the simconnect managed wrapper marshaller
// if you skip this step, you will only receive a uint in the .dwData field.
simconnect.RegisterDataDefineStruct<StructBasicMovingSceneryObject>(DEFINITIONS.StructBasicMovingSceneryObject);
// catch a simobject data request
simconnect.OnRecvSimobjectDataBytype += new SimConnect.RecvSimobjectDataBytypeEventHandler(simconnect_OnRecvSimobjectDataBytype);
return true;
}
catch (COMException ex)
{
safeShowBalloonTip(3000, Text, "FSX Exception!\n\n" + ex.Message, ToolTipIcon.Error);
return false;
}
}
void simconnect_OnRecvOpen(SimConnect sender, SIMCONNECT_RECV_OPEN data)
{
lock (lockUserAircraftID)
{
bUserAircraftIDSet = false;
}
if (gconffixCurrent.bQueryUserAircraft)
timerQueryUserAircraft.Start();
if (gconffixCurrent.bQueryUserPath)
timerQueryUserPath.Start();
if (gconffixCurrent.bUserPathPrediction)
timerUserPrediction.Start();
if (gconffixCurrent.bQueryAIObjects)
{
if (gconffixCurrent.bQueryAIAircrafts)
timerQueryAIAircrafts.Start();
if (gconffixCurrent.bQueryAIHelicopters)
timerQueryAIHelicopters.Start();
if (gconffixCurrent.bQueryAIBoats)
timerQueryAIBoats.Start();
if (gconffixCurrent.bQueryAIGroundUnits)
timerQueryAIGroundUnits.Start();
}
timerIPAddressRefresh_Tick(null, null);
timerIPAddressRefresh.Start();
}
void simconnect_OnRecvQuit(SimConnect sender, SIMCONNECT_RECV data)
{
globalDisconnect();
if (gconffixCurrent.bExitOnFsxExit && isFsxStartActivated())
{
bClose = true;
Close();
}
}
void simconnect_OnRecvException(SimConnect sender, SIMCONNECT_RECV_EXCEPTION data)
{
safeShowBalloonTip(3000, Text, "FSX Exception!", ToolTipIcon.Error);
}
void simconnect_OnRecvSimobjectDataBytype(SimConnect sender, SIMCONNECT_RECV_SIMOBJECT_DATA_BYTYPE data)
{
if (data.dwentrynumber == 0 && data.dwoutof == 0)
return;
DataRequestReturnObject drroTemp;
drroTemp.bmsoObject = (StructBasicMovingSceneryObject)data.dwData[0];
drroTemp.uiObjectID = data.dwObjectID;
drroTemp.szCoursePrediction = "";
drroTemp.ppsPredictionPoints = null;
switch ((DATA_REQUESTS)data.dwRequestID)
{
case DATA_REQUESTS.REQUEST_USER_AIRCRAFT:
case DATA_REQUESTS.REQUEST_USER_PATH:
case DATA_REQUESTS.REQUEST_USER_PREDICTION:
lock (lockUserAircraftID)
{
bUserAircraftIDSet = true;
uiUserAircraftID = drroTemp.uiObjectID;
}
switch ((DATA_REQUESTS)data.dwRequestID)
{
case DATA_REQUESTS.REQUEST_USER_AIRCRAFT:
lock (lockKmlUserAircraft)
{
suadCurrent = drroTemp.bmsoObject;
}
break;
case DATA_REQUESTS.REQUEST_USER_PATH:
lock (lockKmlUserPath)
{
szKmlUserAircraftPath += drroTemp.bmsoObject.dLongitude.ToString().Replace(",", ".") + "," + drroTemp.bmsoObject.dLatitude.ToString().Replace(",", ".") + "," + drroTemp.bmsoObject.dAltitude.ToString().Replace(",", ".") + "\n";
}
break;
case DATA_REQUESTS.REQUEST_USER_PREDICTION:
lock (lockKmlPredictionPoints)
{
if (!ppPos1.bInitialized)
{
ppPos1.dLong = drroTemp.bmsoObject.dLongitude;
ppPos1.dLat = drroTemp.bmsoObject.dLatitude;
ppPos1.dAlt = drroTemp.bmsoObject.dAltitude;
ppPos1.dTime = drroTemp.bmsoObject.dTime;
ppPos1.bInitialized = true;
return;
}
else
{
if (!ppPos2.bInitialized)
{
ppPos2.dLong = drroTemp.bmsoObject.dLongitude;
ppPos2.dLat = drroTemp.bmsoObject.dLatitude;
ppPos2.dAlt = drroTemp.bmsoObject.dAltitude;
ppPos2.dTime = drroTemp.bmsoObject.dTime;
ppPos2.bInitialized = true;
}
else
{
ppPos1 = ppPos2;
ppPos2.dLong = drroTemp.bmsoObject.dLongitude;
ppPos2.dLat = drroTemp.bmsoObject.dLatitude;
ppPos2.dAlt = drroTemp.bmsoObject.dAltitude;
ppPos2.dTime = drroTemp.bmsoObject.dTime;
//ppPos2.bInitialized = true;
}
}
if (ppPos1.dTime != ppPos2.dTime && ppPos1.bInitialized && ppPos2.bInitialized)
{
lock (lockKmlUserPrediction)
{
szKmlUserPrediction = drroTemp.bmsoObject.dLongitude.ToString().Replace(",", ".") + "," + drroTemp.bmsoObject.dLatitude.ToString().Replace(",", ".") + "," + drroTemp.bmsoObject.dAltitude.ToString().Replace(",", ".") + "\n";
listKmlPredictionPoints.Clear();
for (uint n = 0; n < gconffixCurrent.dPredictionTimes.GetLength(0); n++)
{
double dLongNew = 0.0, dLatNew = 0.0, dAltNew = 0.0;
calcPositionByTime(ref ppPos1, ref ppPos2, gconffixCurrent.dPredictionTimes[n], ref dLatNew, ref dLongNew, ref dAltNew);
PathPositionStored ppsTemp;
ppsTemp.dLat = dLatNew;
ppsTemp.dLong = dLongNew;
ppsTemp.dAlt = dAltNew;
ppsTemp.dTime = gconffixCurrent.dPredictionTimes[n];
listKmlPredictionPoints.Add(ppsTemp);
szKmlUserPrediction += dLongNew.ToString().Replace(",", ".") + "," + dLatNew.ToString().Replace(",", ".") + "," + dAltNew.ToString().Replace(",", ".") + "\n";
}
}
}
}
break;
}
break;
case DATA_REQUESTS.REQUEST_AI_PLANE:
case DATA_REQUESTS.REQUEST_AI_HELICOPTER:
case DATA_REQUESTS.REQUEST_AI_BOAT:
case DATA_REQUESTS.REQUEST_AI_GROUND:
lock (lockUserAircraftID)
{
if (bUserAircraftIDSet && (drroTemp.uiObjectID == uiUserAircraftID))
return;
}
switch ((DATA_REQUESTS)data.dwRequestID)
{
case DATA_REQUESTS.REQUEST_AI_PLANE:
processDataRequestResultAlternatingly(data.dwentrynumber, data.dwoutof, ref drrAIPlanes, ref lockDrrAiPlanes, ref drroTemp, gconffixCurrent.bPredictAIAircrafts, gconffixCurrent.bPredictPointsAIAircrafts);
break;
case DATA_REQUESTS.REQUEST_AI_HELICOPTER:
processDataRequestResultAlternatingly(data.dwentrynumber, data.dwoutof, ref drrAIHelicopters, ref lockDrrAiHelicopters, ref drroTemp, gconffixCurrent.bPredictAIHelicopters, gconffixCurrent.bPredictPointsAIHelicopters);
break;
case DATA_REQUESTS.REQUEST_AI_BOAT:
processDataRequestResultAlternatingly(data.dwentrynumber, data.dwoutof, ref drrAIBoats, ref lockDrrAiBoats, ref drroTemp, gconffixCurrent.bPredictAIBoats, gconffixCurrent.bPredictPointsAIBoats);
break;
case DATA_REQUESTS.REQUEST_AI_GROUND:
processDataRequestResultAlternatingly(data.dwentrynumber, data.dwoutof, ref drrAIGround, ref lockDrrAiGround, ref drroTemp, gconffixCurrent.bPredictAIGroundUnits, gconffixCurrent.bPredictPointsAIGroundUnits);
break;
}
break;
default:
#if DEBUG
safeShowBalloonTip(3000, Text, "Received unknown data from FSX!", ToolTipIcon.Warning);
#endif
break;
}
}
Thread thrConnect;
private void globalConnect()
{
lock (lockChConf)
{
if (!gconfchCurrent.bEnabled)
return;
}
notifyIconMain.Icon = icActive;
notifyIconMain.Text = Text + "(Waiting for connection...)";
if (bConnected)
return;
lock (lockKmlUserAircraft)
{
szKmlUserAircraftPath = "";
uiUserAircraftID = 0;
}
if (!timerFSXConnect.Enabled)
timerFSXConnect.Start();
}
private void globalDisconnect()
{
if (bConnected)
{
bConnected = false;
// Stop all query timers
timerQueryUserAircraft.Stop();
timerQueryUserPath.Stop();
timerUserPrediction.Stop();
timerQueryAIAircrafts.Stop();
timerQueryAIHelicopters.Stop();
timerQueryAIBoats.Stop();
timerQueryAIGroundUnits.Stop();
closeConnection();
lock (lockChConf)
{
if (gconfchCurrent.bEnabled)
safeShowBalloonTip(1000, Text, "Disconnected from FSX!", ToolTipIcon.Info);
}
}
lock (lockChConf)
{
if (gconfchCurrent.bEnabled)
{
if (!timerFSXConnect.Enabled)
{
timerFSXConnect.Start();
notifyIconMain.Icon = icActive;
notifyIconMain.Text = Text + "(Waiting for connection...)";
}
}
else
{
if (timerFSXConnect.Enabled)
{
timerFSXConnect.Stop();
thrConnect.Abort();
if (thrConnect.ThreadState != ThreadState.Unstarted)
thrConnect.Join();
closeConnection();
}
notifyIconMain.Icon = icDisabled;
notifyIconMain.Text = Text + "(Disabled)";
}
}
}
#endregion
#region Helper Functions
#region Old Version
//void processDataRequestResultAlternatingly(uint entryNumber, uint entriesCount, ref DataRequestReturn currentRequestStructure, ref object relatedLock, ref StructBasicMovingSceneryObject receivedData, ref String processedData)
//{
// lock (relatedLock)
// {
// if (entryNumber <= currentRequestStructure.uiLastEntryNumber)
// {
// if (currentRequestStructure.uiCurrentDataSet == 1)
// {
// currentRequestStructure.szData2 = "";
// currentRequestStructure.uiCurrentDataSet = 2;
// }
// else
// {
// currentRequestStructure.szData1 = "";
// currentRequestStructure.uiCurrentDataSet = 1;
// }
// }
// currentRequestStructure.uiLastEntryNumber = entryNumber;
// if (currentRequestStructure.uiCurrentDataSet == 1)
// currentRequestStructure.szData1 += processedData;
// else
// currentRequestStructure.szData2 += processedData;
// if (entryNumber == entriesCount)
// {
// if (currentRequestStructure.uiCurrentDataSet == 1)
// {
// currentRequestStructure.szData2 = "";
// currentRequestStructure.uiCurrentDataSet = 2;
// }
// else
// {
// currentRequestStructure.szData1 = "";
// currentRequestStructure.uiCurrentDataSet = 1;
// }
// currentRequestStructure.uiLastEntryNumber = 0;
// }
// }
//}
#endregion
void processDataRequestResultAlternatingly(uint entryNumber, uint entriesCount, ref DataRequestReturn currentRequestStructure, ref object relatedLock, ref DataRequestReturnObject receivedData, bool bCoursePrediction, bool bPredictionPoints)
{
lock (relatedLock)
{
// In case last data request return aborted unnormally and we're dealing with a new result, switch lists
if (entryNumber <= currentRequestStructure.uiLastEntryNumber)
{
if (currentRequestStructure.uiCurrentDataSet == 1)
currentRequestStructure.uiCurrentDataSet = 2;
else
currentRequestStructure.uiCurrentDataSet = 1;
}
List<DataRequestReturnObject> listCurrent = currentRequestStructure.uiCurrentDataSet == 1 ? currentRequestStructure.listFirst : currentRequestStructure.listSecond;
List<DataRequestReturnObject> listOld = currentRequestStructure.uiCurrentDataSet == 1 ? currentRequestStructure.listSecond : currentRequestStructure.listFirst;
// In case we have switched lists, clear new list and resize if necessary
if (currentRequestStructure.bClearOnNextRun)
{
currentRequestStructure.bClearOnNextRun = false;
listCurrent.Clear();
if (listCurrent.Capacity < entriesCount)
listCurrent.Capacity = (int)((double)entriesCount * 1.1);
}
// Calculate course prediction
if (bCoursePrediction)
{
foreach (DataRequestReturnObject drroTemp in listOld)
{
if (drroTemp.uiObjectID == receivedData.uiObjectID)
{
if (drroTemp.bmsoObject.dTime != receivedData.bmsoObject.dTime)
{
if (bPredictionPoints)
receivedData.ppsPredictionPoints = new PathPositionStored[gconffixCurrent.dPredictionTimes.GetLength(0)];
receivedData.szCoursePrediction = receivedData.bmsoObject.dLongitude.ToString().Replace(",", ".") + "," + receivedData.bmsoObject.dLatitude.ToString().Replace(",", ".") + "," + receivedData.bmsoObject.dAltitude.ToString().Replace(",", ".") + "\n";
for (uint n = 0; n < gconffixCurrent.dPredictionTimes.GetLength(0); n++)
{
PathPosition ppOld, ppCurrent;
double dLongNew = 0.0, dLatNew = 0.0, dAltNew = 0.0;
ppOld.bInitialized = true;
ppOld.dLat = drroTemp.bmsoObject.dLatitude;
ppOld.dLong = drroTemp.bmsoObject.dLongitude;
ppOld.dAlt = drroTemp.bmsoObject.dAltitude;
ppOld.dTime = drroTemp.bmsoObject.dTime;
ppCurrent.bInitialized = true;
ppCurrent.dLat = receivedData.bmsoObject.dLatitude;
ppCurrent.dLong = receivedData.bmsoObject.dLongitude;
ppCurrent.dAlt = receivedData.bmsoObject.dAltitude;
ppCurrent.dTime = receivedData.bmsoObject.dTime;
calcPositionByTime(ref ppOld, ref ppCurrent, gconffixCurrent.dPredictionTimes[n], ref dLatNew, ref dLongNew, ref dAltNew);
receivedData.szCoursePrediction += dLongNew.ToString().Replace(",", ".") + "," + dLatNew.ToString().Replace(",", ".") + "," + dAltNew.ToString().Replace(",", ".") + "\n";
if (bPredictionPoints)
{
PathPositionStored ppsTemp;
ppsTemp.dLat = dLatNew;
ppsTemp.dLong = dLongNew;
ppsTemp.dAlt = dAltNew;
ppsTemp.dTime = gconffixCurrent.dPredictionTimes[n];
receivedData.ppsPredictionPoints[n] = ppsTemp;
}
}
}
else
{
receivedData.szCoursePrediction = drroTemp.szCoursePrediction;
receivedData.ppsPredictionPoints = drroTemp.ppsPredictionPoints;
}
break;
}
}
}
// Set current entry number
currentRequestStructure.uiLastEntryNumber = entryNumber;
// Insert new data into the list
if (currentRequestStructure.uiCurrentDataSet == 1)
currentRequestStructure.listFirst.Add(receivedData);
else
currentRequestStructure.listSecond.Add(receivedData);
// If this is the last entry from the current return, switch lists, so that http server can work with the just completed list
if (entryNumber == entriesCount)
{
if (currentRequestStructure.uiCurrentDataSet == 1)
currentRequestStructure.uiCurrentDataSet = 2;
else
currentRequestStructure.uiCurrentDataSet = 1;
currentRequestStructure.uiLastEntryNumber = 0;
currentRequestStructure.bClearOnNextRun = true;
}
}
}
private List<DataRequestReturnObject> GetCurrentList(ref DataRequestReturn drrnCurrent)
{
if (drrnCurrent.uiCurrentDataSet == 1)
return drrnCurrent.listSecond;
else
return drrnCurrent.listFirst;
}
private void safeShowBalloonTip(int timeout, String tipTitle, String tipText, ToolTipIcon tipIcon)
{
lock (lockChConf)
{
if (!gconfchCurrent.bShowBalloons)
return;
}
notifyIconMain.ShowBalloonTip(timeout, tipTitle, tipText, tipIcon);
}
private void safeShowMainDialog(int iTab)
{
notifyIconMain.ContextMenuStrip = null;
ConfigMirrorToForm();
// Check startup options
if (isAutoStartActivated())
radioButton8.Checked = true;
else if (isFsxStartActivated() && szPathFSX != "")
radioButton9.Checked = true;
else
radioButton10.Checked = true;
if (szPathFSX == "")
radioButton9.Enabled = false;
bRestartRequired = false;
tabControl1.SelectedIndex = iTab;
Show();
}
private void safeHideMainDialog()
{
notifyIconMain.ContextMenuStrip = contextMenuStripNotifyIcon;
Hide();
}
private void clearDrrStructure(ref DataRequestReturn drrToClear)
{
if (drrToClear.listFirst == null)
drrToClear.listFirst = new List<DataRequestReturnObject>();
if (drrToClear.listSecond == null)
drrToClear.listSecond = new List<DataRequestReturnObject>();
drrToClear.listFirst.Clear();
drrToClear.listSecond.Clear();
drrToClear.uiLastEntryNumber = 0;
drrToClear.uiCurrentDataSet = 1;
drrToClear.bClearOnNextRun = true;
}
private void clearPPStructure(ref PathPosition ppToClear)
{
ppToClear.bInitialized = false;
ppToClear.dAlt = ppToClear.dLong = ppToClear.dAlt = 0.0;
}
private bool IsLocalHostIP(IPAddress ipaRequest)
{
lock (lockIPAddressList)
{
if (ipalLocal1 != null)
{
foreach (IPAddress ipaTemp in ipalLocal1)
{
if (ipaTemp.Equals(ipaRequest))
return true;
}
}
if (ipalLocal2 != null)
{
foreach (IPAddress ipaTemp in ipalLocal2)
{
if (ipaTemp.Equals(ipaRequest))
return true;
}
}
}
return false;
}
private bool CompileKMLStartUpFileDynamic(String szIPAddress, ref String szResult)
{
try
{
string szTempKMLFile = File.ReadAllText(szFilePathData + "\\fsxget.template");
szTempKMLFile = szTempKMLFile.Replace("%FSXU%", gconffixCurrent.bQueryUserAircraft ? File.ReadAllText(szFilePathData + "\\fsxget-fsxu.part") : "");
szTempKMLFile = szTempKMLFile.Replace("%FSXP%", gconffixCurrent.bQueryUserPath ? File.ReadAllText(szFilePathData + "\\fsxget-fsxp.part") : "");
szTempKMLFile = szTempKMLFile.Replace("%FSXPRE%", gconffixCurrent.bUserPathPrediction ? File.ReadAllText(szFilePathData + "\\fsxget-fsxpre.part") : "");
szTempKMLFile = szTempKMLFile.Replace("%FSXAIP%", gconffixCurrent.bQueryAIAircrafts ? File.ReadAllText(szFilePathData + "\\fsxget-fsxaip.part") : "");
szTempKMLFile = szTempKMLFile.Replace("%FSXAIH%", gconffixCurrent.bQueryAIHelicopters ? File.ReadAllText(szFilePathData + "\\fsxget-fsxaih.part") : "");
szTempKMLFile = szTempKMLFile.Replace("%FSXAIB%", gconffixCurrent.bQueryAIBoats ? File.ReadAllText(szFilePathData + "\\fsxget-fsxaib.part") : "");
szTempKMLFile = szTempKMLFile.Replace("%FSXAIG%", gconffixCurrent.bQueryAIGroundUnits ? File.ReadAllText(szFilePathData + "\\fsxget-fsxaig.part") : "");
//szTempKMLFile = szTempKMLFile.Replace("%FSXFLIGHTPLAN%", gconffixCurrent.bLoadFlightPlans ? File.ReadAllText(szFilePathData + "\\fsxget-fsxflightplan.part") : "");
szTempKMLFile = szTempKMLFile.Replace("%PATH%", "http://" + szIPAddress + ":" + gconffixCurrent.iServerPort.ToString());
szResult = szTempKMLFile;
return true;
}
catch
{
return false;
}
}
private bool CompileKMLStartUpFileStatic(String szIPAddress, ref String szResult)
{
try
{
string szTempKMLFile = File.ReadAllText(szFilePathData + "\\fsxgets.template");
//szTempKMLFile = szTempKMLFile.Replace("%FSXU%", "");
//szTempKMLFile = szTempKMLFile.Replace("%FSXP%", "");
//szTempKMLFile = szTempKMLFile.Replace("%FSXPRE%", "");
//szTempKMLFile = szTempKMLFile.Replace("%FSXAIP%", "");
//szTempKMLFile = szTempKMLFile.Replace("%FSXAIH%", "");
//szTempKMLFile = szTempKMLFile.Replace("%FSXAIB%", "");
//szTempKMLFile = szTempKMLFile.Replace("%FSXAIG%", "");
//szTempKMLFile = szTempKMLFile.Replace("%FSXFLIGHTPLAN%", gconffixCurrent.bLoadFlightPlans ? File.ReadAllText(szFilePathData + "\\fsxget-fsxflightplan.part") : "");
//szTempKMLFile = szTempKMLFile.Replace("%PATH%", "http://" + szIPAddress + ":" + gconffixCurrent.iServerPort.ToString());
szResult = szTempKMLFile;
return true;
}
catch
{
return false;
}
}
private void UpdateCheckBoxStates()
{
checkBoxQueryAIObjects_CheckedChanged(null, null);
radioButton7_CheckedChanged(null, null);
radioButton6_CheckedChanged(null, null);
radioButton8_CheckedChanged(null, null);
radioButton9_CheckedChanged(null, null);
radioButton10_CheckedChanged(null, null);
}
private void UpdateButtonStates()
{
if (listBoxPathPrediction.SelectedItems.Count == 1)
button2.Enabled = true;
else
button2.Enabled = false;
}
private double ConvertDegToDouble(String szDeg)
{
String szTemp = szDeg;
szTemp = szTemp.Replace("N", "+");
szTemp = szTemp.Replace("S", "-");
szTemp = szTemp.Replace("E", "+");
szTemp = szTemp.Replace("W", "-");
szTemp = szTemp.Replace(" ", "");
szTemp = szTemp.Replace("\"", "");
szTemp = szTemp.Replace("'", "/");
szTemp = szTemp.Replace("°", "/");
char[] szSeperator = { '/' };
String[] szParts = szTemp.Split(szSeperator);
if (szParts.GetLength(0) != 3)
{
throw new System.Exception("Wrong coordinate format!");
}
double d1 = System.Double.Parse(szParts[0], System.Globalization.NumberFormatInfo.InvariantInfo);
int iSign = Math.Sign(d1);
d1 = Math.Abs(d1);
double d2 = System.Double.Parse(szParts[1], System.Globalization.NumberFormatInfo.InvariantInfo);
double d3 = System.Double.Parse(szParts[2], System.Globalization.NumberFormatInfo.InvariantInfo);
return iSign * (d1 + (d2 * 60.0 + d3) / 3600.0);
}
private bool isAutoStartActivated()
{
string szRun = (string)Registry.GetValue(szRegKeyRun, AssemblyTitle, "");
return (szRun.ToLower() == Application.ExecutablePath.ToLower());
}
private bool AutoStartActivate()
{
try
{
Registry.SetValue(szRegKeyRun, AssemblyTitle, Application.ExecutablePath);
}
catch
{
return false;
}
return true;
}
private bool AutoStartDeactivate()
{
try
{
RegistryKey regkTemp = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Run", true);
regkTemp.DeleteValue(AssemblyTitle);
}
catch
{
return false;
}
return true;
}
private bool isFsxStartActivated()
{
String szAppDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Microsoft\\FSX";
if (File.Exists(szAppDataFolder + "\\EXE.xml"))
{
XmlTextReader xmlrFsxFile = new XmlTextReader(szAppDataFolder + "\\EXE.xml");
XmlDocument xmldSettings = new XmlDocument();
try
{
xmldSettings.Load(xmlrFsxFile);
}
catch
{
xmlrFsxFile.Close();
xmlrFsxFile = null;
return false;
}
xmlrFsxFile.Close();
xmlrFsxFile = null;
try
{
for (XmlNode xmlnTemp = xmldSettings["SimBase.Document"].FirstChild; xmlnTemp != null; xmlnTemp = xmlnTemp.NextSibling)
{
if (xmlnTemp.Name.ToLower() == "launch.addon")
{
try
{
if (Path.GetFullPath(xmlnTemp["Path"].InnerText).ToLower() == (Path.GetFullPath(szAppPath) + "\\starter.exe").ToLower())
return true;
}
catch { }
}
}
return false;
}
catch
{
return false;
}
}
else
return false;
}
private bool FsxStartActivate()
{
String szAppDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Microsoft\\FSX";
if (File.Exists(szAppDataFolder + "\\EXE.xml"))
{
bool bLoadError = false;
XmlTextReader xmlrFsxFile = new XmlTextReader(szAppDataFolder + "\\EXE.xml");
XmlDocument xmldSettings = new XmlDocument();
try
{
xmldSettings.Load(xmlrFsxFile);
}
catch
{
bLoadError = true;
}
xmlrFsxFile.Close();
xmlrFsxFile = null;
// TODO: One could improve this function not just replacing the document if ["SimBase.Document"] doesn't exist,
// but just find and use the document's root element whatever it may be called. This would increase compatibility
// with future FS version. (Same should be done for other functions dealing with this document)
if (bLoadError || xmldSettings["SimBase.Document"] == null)
{
try
{
File.Delete(szAppDataFolder + "\\EXE.xml");
return FsxStartActivate();
}
catch
{
return false;
}
}
else
{
if (xmldSettings["SimBase.Document"]["Disabled"] == null)
{
XmlNode nodeTemp = xmldSettings.CreateElement("Disabled");
nodeTemp.InnerText = "False";
xmldSettings["SimBase.Document"].AppendChild(nodeTemp);
}
else if (xmldSettings["SimBase.Document"]["Disabled"].InnerText.ToLower() == "true")
xmldSettings["SimBase.Document"]["Disabled"].InnerText = "False";
xmlrFsxFile = new XmlTextReader(szAppPath + "\\data\\EXE.xml");
XmlDocument xmldTemplate = new XmlDocument();
xmldTemplate.Load(xmlrFsxFile);
xmlrFsxFile.Close();
xmlrFsxFile = null;
XmlNode nodeFsxget = xmldTemplate["SimBase.Document"]["Launch.Addon"];
XmlNode nodeTemp2 = xmldSettings.CreateElement(nodeFsxget.Name);
nodeTemp2.InnerXml = nodeFsxget.InnerXml.Replace("%PATH%", Path.GetFullPath(szAppPath) + "\\starter.exe");
xmldSettings["SimBase.Document"].AppendChild(nodeTemp2);
try
{
File.Delete(szAppDataFolder + "\\EXE.xml");
xmldSettings.Save(szAppDataFolder + "\\EXE.xml");
return true;
}
catch
{
return false;
}
}
}
else
{
try
{
StreamWriter swFsxFile = File.CreateText(szAppDataFolder + "\\EXE.xml");
StreamReader srFsxFileTemplate = File.OpenText(szAppPath + "\\data\\EXE.xml");
swFsxFile.Write(srFsxFileTemplate.ReadToEnd().Replace("%PATH%", Path.GetFullPath(szAppPath) + "\\starter.exe"));
swFsxFile.Flush();
swFsxFile.Close();
swFsxFile.Dispose();
srFsxFileTemplate.Close();
srFsxFileTemplate.Dispose();
return true;
}
catch
{
return false;
}
}
}
private bool FsxStartDeactivate()
{
String szAppDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Microsoft\\FSX";
if (File.Exists(szAppDataFolder + "\\EXE.xml"))
{
XmlTextReader xmlrFsxFile = new XmlTextReader(szAppDataFolder + "\\EXE.xml");
XmlDocument xmldSettings = new XmlDocument();
xmldSettings.Load(xmlrFsxFile);
xmlrFsxFile.Close();
xmlrFsxFile = null;
try
{
bool bChanges = false;
for (XmlNode xmlnTemp = xmldSettings["SimBase.Document"].FirstChild; xmlnTemp != null; xmlnTemp = xmlnTemp.NextSibling)
{
if (xmlnTemp.Name.ToLower() == "launch.addon")
{
if (xmlnTemp["Path"] != null)
{
if (Path.GetFullPath(xmlnTemp["Path"].InnerText).ToLower() == (Path.GetFullPath(szAppPath) + "\\starter.exe").ToLower())
{
xmldSettings["SimBase.Document"].RemoveChild(xmlnTemp);
bChanges = true;
}
}
}
}
if (bChanges)
{
try
{
File.Delete(szAppDataFolder + "\\EXE.xml");
xmldSettings.Save(szAppDataFolder + "\\EXE.xml");
}
catch
{
return false;
}
}
return true;
}
catch
{
return true;
}
}
else
return true;
}
private double getValueInUnit(double dValueInMeters, UnitType Unit)
{
switch (Unit)
{
case UnitType.METERS:
return dValueInMeters;
case UnitType.FEET:
return dValueInMeters * 3.2808399;
default:
throw new Exception("Unknown unit type");
}
}
private double getValueInCurrentUnit(double dValueInMeters)
{
return getValueInUnit(dValueInMeters, gconffixCurrent.utUnits);
}
private String getCurrentUnitNameShort()
{
switch (gconffixCurrent.utUnits)
{
case UnitType.METERS:
return "m";
case UnitType.FEET:
return "ft";
default:
return "--";
}
}
private String getCurrentUnitName()
{
switch (gconffixCurrent.utUnits)
{
case UnitType.METERS:
return "Meters";
case UnitType.FEET:
return "Feet";
default:
return "Unknown Unit";
}
}
private void RestartApp()
{
Program.bRestart = true;
bClose = true;
Close();
}
protected static byte[] BitmapToPngBytes(Bitmap bmp)
{
byte[] bufferPng = null;
if (bmp != null)
{
byte[] buffer = new byte[1024 + bmp.Height * bmp.Width * 4];
MemoryStream s = new MemoryStream(buffer);
bmp.Save(s, System.Drawing.Imaging.ImageFormat.Png);
int nSize = (int)s.Position;
s.Close();
bufferPng = new byte[nSize];
for (int i = 0; i < nSize; i++)
bufferPng[i] = buffer[i];
}
return bufferPng;
}
#endregion
#region Calucaltion
private void calcPositionByTime(ref PathPosition ppOld, ref PathPosition ppNew, double dSeconds, ref double dResultLat, ref double dResultLong, ref double dResultAlt)
{
double dTimeElapsed = ppNew.dTime - ppOld.dTime;
double dScale = dSeconds / dTimeElapsed;
dResultLat = ppNew.dLat + dScale * (ppNew.dLat - ppOld.dLat);
dResultLong = ppNew.dLong + dScale * (ppNew.dLong - ppOld.dLong);
dResultAlt = ppNew.dAlt + dScale * (ppNew.dAlt - ppOld.dAlt);
}
#region Old Calculation
//private void calcPositionByTime(double dLong, double dLat, double dAlt, double dSpeedX, double dSpeedY, double dSpeedZ, double dSeconds, ref double dResultLat, ref double dResultLong, ref double dResultAlt)
//{
// const double dRadEarth = 6371000.8;
// dResultLat = dLat + dSpeedZ * dSeconds / 1852.0;
// dResultAlt = dAlt + dSpeedY * dSeconds;
// double dLatMiddle = dLat + (dSpeedZ * dSeconds / 1852.0 / 2.0);
// dResultLong = dLong + (dSpeedX * dSeconds / (2.0 * Math.PI * dRadEarth / 360.0 * Math.Cos(dLatMiddle * Math.PI / 180.0)));
// //double dNewPosX = dSpeedX * dSeconds;
// //double dNewPosY = dSpeedY * dSeconds;
// //double dNewPosZ = dSpeedZ * dSeconds;
// //double dCosAngle = (dNewPosY * 1.0 + dNewPosZ * 0.0) / (Math.Sqrt(Math.Pow(dNewPosY, 2.0) + Math.Pow(dNewPosZ, 2.0)) * Math.Sqrt(Math.Pow(0.0, 2.0) + Math.Pow(1.0, 2.0)));
// //dResultLat = dLat + Math.Acos(dCosAngle / 180.0 * Math.PI);
// //// East-West-Position
// //dCosAngle = (dNewPosX * 1.0 + dNewPosY * 0.0) / (Math.Sqrt(Math.Pow(dNewPosX, 2.0) + Math.Pow(dNewPosY, 2.0)) * Math.Sqrt(Math.Pow(1.0, 2.0) + Math.Pow(0.0, 2.0)));
// //dResultLong = dLong + Math.Acos(dCosAngle / 180.0 * Math.PI);
// //// Altitude
// //dResultAlt = dAlt + Math.Sqrt(Math.Pow(dNewPosX, 2.0) + Math.Pow(dNewPosY, 2.0) + Math.Pow(dNewPosZ, 2.0));
// //const double dRadEarth = 6371000.8;
// ////x' = cos(theta)*x - sin(theta)*y
// ////y' = sin(theta)*x + cos(theta)*y
// //// Calculate North-South-Position
// //double dTempX = dAlt + dRadEarth;
// //double dTempY = 0.0;
// //double dPosY = Math.Cos(dLat) * dTempX - Math.Sin(dLat) * dTempY;
// //double dPosZ = Math.Sin(dLat) * dTempX - Math.Cos(dLat) * dTempY;
// //// Calculate East-West-Position
// //dTempX = dAlt + dRadEarth;
// //dTempY = 0;
// //double dPosX = Math.Cos(dLong) * dTempX - Math.Sin(dLong) * dTempY;
// ////dPosZ = Math.Sin(dLat) * dTempX - Math.Cos(dLat) * dTempY;
// //// Normalize
// //double dLength = Math.Sqrt(Math.Pow(dPosX, 2.0) + Math.Pow(dPosY, 2.0) + Math.Pow(dPosZ, 2.0));
// //dPosX = dPosX / dLength * (dAlt + dRadEarth);
// //dPosY = dPosY / dLength * (dAlt + dRadEarth);
// //dPosZ = dPosZ / dLength * (dAlt + dRadEarth);
// //double dTest = Math.Sqrt(Math.Pow(dPosX, 2.0) + Math.Pow(dPosY, 2.0) + Math.Pow(dPosZ, 2.0)) - dRadEarth;
// //// Calculate position after given time
// //double dNewPosX = dPosX + dSpeedX * dSeconds;
// //double dNewPosY = dPosY + dSpeedY * dSeconds;
// //double dNewPosZ = dPosZ + dSpeedZ * dSeconds;
// //// Now again translate into lat-long-coordinates
// //// North-South-Position
// //double dCosAngle = (dNewPosY * dPosY + dNewPosZ * dPosZ) / (Math.Sqrt(Math.Pow(dNewPosY, 2.0) + Math.Pow(dNewPosZ, 2.0)) * Math.Sqrt(Math.Pow(dPosY, 2.0) + Math.Pow(dPosZ, 2.0)));
// //dResultLat = dLat + Math.Acos(dCosAngle / 180.0 * Math.PI);
// //// East-West-Position
// //dCosAngle = (dNewPosX * dPosX + dNewPosY * dPosY) / (Math.Sqrt(Math.Pow(dNewPosX, 2.0) + Math.Pow(dNewPosY, 2.0)) * Math.Sqrt(Math.Pow(dPosX, 2.0) + Math.Pow(dPosY, 2.0)));
// //dResultLong = dLong + Math.Acos(dCosAngle / 180.0 * Math.PI);
// //// Altitude
// //dResultAlt = Math.Sqrt(Math.Pow(dNewPosX, 2.0) + Math.Pow(dNewPosY, 2.0) + Math.Pow(dNewPosZ, 2.0)) - dRadEarth;
//}
#endregion
#endregion
#region Server
public void ListenerCallback(IAsyncResult result)
{
lock (lockListenerControl)
{
HttpListener listener = (HttpListener)result.AsyncState;
if (!listener.IsListening)
return;
HttpListenerContext context = listener.EndGetContext(result);
HttpListenerRequest request = context.Request;
HttpListenerResponse response = context.Response;
// This code using the objects IsLocal property doesn't work for some reason ...
//if (gconffixCurrent.uiServerAccessLevel == 0 && !request.IsLocal)
//{
// response.Abort();
// return;
//}
// ... so I'm using my own code.
if (gconffixCurrent.uiServerAccessLevel == 0 && !IsLocalHostIP(request.RemoteEndPoint.Address))
{
response.Abort();
return;
}
byte[] buffer = System.Text.Encoding.UTF8.GetBytes("");
String szHeader = "";
bool bContentSet = false;
if (request.Url.PathAndQuery.ToLower().StartsWith("/gfx/scenery/air/"))
{
String szTemp = request.Url.PathAndQuery.Substring(17);
if (szTemp.Length >= 4)
{
// Cut the .png suffix from the url
szTemp = szTemp.Substring(0, szTemp.Length - 4);
foreach (ObjectImage aimgCurrent in listImgUnitsAir)
{
String szTemp2 = HttpUtility.UrlDecode(szTemp);
if (aimgCurrent.szTitle.ToLower() == HttpUtility.UrlDecode(szTemp).ToLower())
{
buffer = aimgCurrent.bData;
szHeader = "image/png";
bContentSet = true;
break;
}
}
if (!bContentSet)
{
buffer = imgNoImage;
szHeader = "image/png";
bContentSet = true;
}
}
}
else if (request.Url.PathAndQuery.ToLower().StartsWith("/gfx/scenery/water/"))
{
String szTemp = request.Url.PathAndQuery.Substring(19);
if (szTemp.Length >= 4)
{
// Cut the .png suffix from the url
szTemp = szTemp.Substring(0, szTemp.Length - 4);
foreach (ObjectImage aimgCurrent in listImgUnitsWater)
{
String szTemp2 = HttpUtility.UrlDecode(szTemp);
if (aimgCurrent.szTitle.ToLower() == HttpUtility.UrlDecode(szTemp).ToLower())
{
buffer = aimgCurrent.bData;
szHeader = "image/png";
bContentSet = true;
break;
}
}
if (!bContentSet)
{
buffer = imgNoImage;
szHeader = "image/png";
bContentSet = true;
}
}
}
else if (request.Url.PathAndQuery.ToLower().StartsWith("/gfx/scenery/ground/"))
{
String szTemp = request.Url.PathAndQuery.Substring(20);
if (szTemp.Length >= 4)
{
// Cut the .png suffix from the url
szTemp = szTemp.Substring(0, szTemp.Length - 4);
foreach (ObjectImage aimgCurrent in listImgUnitsGround)
{
String szTemp2 = HttpUtility.UrlDecode(szTemp);
if (aimgCurrent.szTitle.ToLower() == HttpUtility.UrlDecode(szTemp).ToLower())
{
buffer = aimgCurrent.bData;
szHeader = "image/png";
bContentSet = true;
break;
}
}
if (!bContentSet)
{
buffer = imgNoImage;
szHeader = "image/png";
bContentSet = true;
}
}
}
else if (request.Url.PathAndQuery.ToLower().StartsWith("/gfx/ge/icons/"))
{
String szTemp = request.Url.PathAndQuery.Substring(14);
if (szTemp.Length >= 4)
{
// Cut the .png suffix from the url
szTemp = szTemp.Substring(0, szTemp.Length - 4);
buffer = null;
foreach (ObjectImage oimgTemp in listIconsGE)
{
if (oimgTemp.szTitle.ToLower() == szTemp.ToLower())
{
szHeader = "image/png";
buffer = oimgTemp.bData;
bContentSet = true;
break;
}
}
if (!bContentSet)
{
buffer = imgNoImage;
szHeader = "image/png";
bContentSet = true;
}
}
}
else if (request.Url.PathAndQuery.ToLower() == "/fsxu.kml")
{
bContentSet = true;
szHeader = "application/vnd.google-earth.kml+xml";
buffer = System.Text.Encoding.UTF8.GetBytes(KmlGenFile(KML_FILES.REQUEST_USER_AIRCRAFT, KML_ACCESS_MODES.MODE_SERVER, true, (uint)gconffixCurrent.iUpdateGEUserAircraft, request.UserHostName));
}
else if (request.Url.PathAndQuery.ToLower() == "/fsxp.kml")
{
bContentSet = true;
szHeader = "application/vnd.google-earth.kml+xml";
buffer = System.Text.Encoding.UTF8.GetBytes(KmlGenFile(KML_FILES.REQUEST_USER_PATH, KML_ACCESS_MODES.MODE_SERVER, true, (uint)gconffixCurrent.iUpdateGEUserPath, request.UserHostName));
}
else if (request.Url.PathAndQuery.ToLower() == "/fsxpre.kml")
{
bContentSet = true;
szHeader = "application/vnd.google-earth.kml+xml";
buffer = System.Text.Encoding.UTF8.GetBytes(KmlGenFile(KML_FILES.REQUEST_USER_PREDICTION, KML_ACCESS_MODES.MODE_SERVER, true, (uint)gconffixCurrent.iUpdateGEUserPrediction, request.UserHostName));
}
else if (request.Url.PathAndQuery.ToLower() == "/fsxaip.kml")
{
bContentSet = true;
szHeader = "application/vnd.google-earth.kml+xml";
buffer = System.Text.Encoding.UTF8.GetBytes(KmlGenFile(KML_FILES.REQUEST_AI_PLANE, KML_ACCESS_MODES.MODE_SERVER, true, (uint)gconffixCurrent.iUpdateGEAIAircrafts, request.UserHostName));
}
else if (request.Url.PathAndQuery.ToLower() == "/fsxaih.kml")
{
bContentSet = true;
szHeader = "application/vnd.google-earth.kml+xml";
buffer = System.Text.Encoding.UTF8.GetBytes(KmlGenFile(KML_FILES.REQUEST_AI_HELICOPTER, KML_ACCESS_MODES.MODE_SERVER, true, (uint)gconffixCurrent.iUpdateGEAIHelicopters, request.UserHostName));
}
else if (request.Url.PathAndQuery.ToLower() == "/fsxaib.kml")
{
bContentSet = true;
szHeader = "application/vnd.google-earth.kml+xml";
buffer = System.Text.Encoding.UTF8.GetBytes(KmlGenFile(KML_FILES.REQUEST_AI_BOAT, KML_ACCESS_MODES.MODE_SERVER, true, (uint)gconffixCurrent.iUpdateGEAIBoats, request.UserHostName));
}
else if (request.Url.PathAndQuery.ToLower() == "/fsxaig.kml")
{
bContentSet = true;
szHeader = "application/vnd.google-earth.kml+xml";
buffer = System.Text.Encoding.UTF8.GetBytes(KmlGenFile(KML_FILES.REQUEST_AI_GROUND, KML_ACCESS_MODES.MODE_SERVER, true, (uint)gconffixCurrent.iUpdateGEAIGroundUnits, request.UserHostName));
}
else if (request.Url.PathAndQuery.ToLower() == "/fsxflightplans.kml")
{
bContentSet = true;
szHeader = "application/vnd.google-earth.kml+xml";
buffer = System.Text.Encoding.UTF8.GetBytes(KmlGenFile(KML_FILES.REQUEST_FLIGHT_PLANS, KML_ACCESS_MODES.MODE_SERVER, false, 0, request.UserHostName));
}
else if (request.Url.AbsolutePath.ToLower() == "/gfx/ge/label.png")
{
bContentSet = true;
szHeader = "image/png";
buffer = KmlGenAtcLabel(request.QueryString["code"], request.QueryString["fl"], request.QueryString["aircraft"], request.QueryString["speed"], request.QueryString["vspeed"]);
}
else
bContentSet = false;
if (bContentSet)
{
response.AddHeader("Content-type", szHeader);
response.ContentLength64 = buffer.Length;
System.IO.Stream output = response.OutputStream;
output.Write(buffer, 0, buffer.Length);
output.Close();
}
else
{
response.StatusCode = 404;
response.Close();
}
listener.BeginGetContext(new AsyncCallback(ListenerCallback), listener);
}
}
private String KmlGenFile(KML_FILES kmlfWanted, KML_ACCESS_MODES AccessMode, bool bExpires, uint uiSeconds, String szSever)
{
String szTemp = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><kml xmlns=\"http://earth.google.com/kml/2.1\">" +
KmlGetExpireString(bExpires, uiSeconds) +
"<Document>";
switch (kmlfWanted)
{
case KML_FILES.REQUEST_USER_AIRCRAFT:
szTemp += KmlGenUserPosition(AccessMode, szSever);
break;
case KML_FILES.REQUEST_USER_PATH:
szTemp += KmlGenUserPath(AccessMode, szSever);
break;
case KML_FILES.REQUEST_USER_PREDICTION:
szTemp += KmlGenUserPrediction(AccessMode, szSever);
break;
case KML_FILES.REQUEST_AI_PLANE:
szTemp += KmlGenAIAircraft(AccessMode, szSever);
break;
case KML_FILES.REQUEST_AI_HELICOPTER:
szTemp += KmlGenAIHelicopter(AccessMode, szSever);
break;
case KML_FILES.REQUEST_AI_BOAT:
szTemp += KmlGenAIBoat(AccessMode, szSever);
break;
case KML_FILES.REQUEST_AI_GROUND:
szTemp += KmlGenAIGroundUnit(AccessMode, szSever);
break;
//case KML_FILES.REQUEST_FLIGHT_PLANS:
// szTemp += KmlGenFlightPlans(AccessMode, szSever);
// break;
default:
break;
}
szTemp += "</Document></kml>";
return szTemp;
}
private String KmlGetExpireString(bool bExpires, uint uiSeconds)
{
if (!bExpires)
return "";
DateTime date = DateTime.Now;
date = date.AddSeconds(uiSeconds);
date = date.ToUniversalTime();
return "<NetworkLinkControl><expires>" + date.ToString("yyyy") + "-" + date.ToString("MM") + "-" + date.ToString("dd") + "T" + date.ToString("HH") + ":" + date.ToString("mm") + ":" + date.ToString("ss") + "Z" + "</expires></NetworkLinkControl>";
}
private String KmlGetImageLink(KML_ACCESS_MODES AccessMode, KML_IMAGE_TYPES ImageType, String szTitle, String szServer)
{
if (AccessMode == KML_ACCESS_MODES.MODE_SERVER)
{
String szPrefix = "";
switch (ImageType)
{
case KML_IMAGE_TYPES.AIRCRAFT:
szPrefix = "/gfx/scenery/air/";
break;
case KML_IMAGE_TYPES.WATER:
szPrefix = "/gfx/scenery/water/";
break;
case KML_IMAGE_TYPES.GROUND:
szPrefix = "/gfx/scenery/ground/";
break;
}
return "http://" + szServer + szPrefix + szTitle + ".png";
}
else
{
List<ObjectImage> listTemp;
switch (ImageType)
{
case KML_IMAGE_TYPES.AIRCRAFT:
listTemp = listImgUnitsAir;
break;
case KML_IMAGE_TYPES.WATER:
listTemp = listImgUnitsWater;
break;
case KML_IMAGE_TYPES.GROUND:
listTemp = listImgUnitsGround;
break;
default:
return "";
}
foreach (ObjectImage oimgTemp in listTemp)
{
if (oimgTemp.szTitle.ToLower() == szTitle.ToLower())
{
if (AccessMode == KML_ACCESS_MODES.MODE_FILE_LOCAL)
return szFilePathPub + oimgTemp.szPath;
else if (AccessMode == KML_ACCESS_MODES.MODE_FILE_USERDEFINED)
return gconffixCurrent.szUserdefinedPath + oimgTemp.szPath;
}
}
return "";
}
}
private String KmlGetIconLink(KML_ACCESS_MODES AccessMode, KML_ICON_TYPES IconType, String szServer)
{
String szIcon = "";
switch (IconType)
{
case KML_ICON_TYPES.USER_AIRCRAFT_POSITION:
szIcon = "fsxu";
break;
case KML_ICON_TYPES.USER_PREDICTION_POINT:
szIcon = "fsxpm";
break;
case KML_ICON_TYPES.AI_AIRCRAFT:
szIcon = "fsxaip";
break;
case KML_ICON_TYPES.AI_HELICOPTER:
szIcon = "fsxaih";
break;
case KML_ICON_TYPES.AI_BOAT:
szIcon = "fsxaib";
break;
case KML_ICON_TYPES.AI_GROUND_UNIT:
szIcon = "fsxaig";
break;
case KML_ICON_TYPES.AI_AIRCRAFT_PREDICTION_POINT:
szIcon = "fsxaippp";
break;
case KML_ICON_TYPES.AI_HELICOPTER_PREDICTION_POINT:
szIcon = "fsxaihpp";
break;
case KML_ICON_TYPES.AI_BOAT_PREDICTION_POINT:
szIcon = "fsxaibpp";
break;
case KML_ICON_TYPES.AI_GROUND_PREDICTION_POINT:
szIcon = "fsxaigpp";
break;
case KML_ICON_TYPES.PLAN_INTER:
szIcon = "plan-inter";
break;
case KML_ICON_TYPES.PLAN_NDB:
szIcon = "plan-ndb";
break;
case KML_ICON_TYPES.PLAN_PORT:
szIcon = "plan-port";
break;
case KML_ICON_TYPES.PLAN_USER:
szIcon = "plan-user";
break;
case KML_ICON_TYPES.PLAN_VOR:
szIcon = "plan-vor";
break;
case KML_ICON_TYPES.ATC_LABEL:
return "http://" + szServer + "/gfx/ge/label.png";
}
if (AccessMode == KML_ACCESS_MODES.MODE_SERVER)
{
return "http://" + szServer + "/gfx/ge/icons/" + szIcon + ".png";
}
else
{
foreach (ObjectImage oimgTemp in listIconsGE)
{
if (oimgTemp.szTitle.ToLower() == szIcon.ToLower())
{
if (AccessMode == KML_ACCESS_MODES.MODE_FILE_LOCAL)
return szFilePathPub + oimgTemp.szPath;
else if (AccessMode == KML_ACCESS_MODES.MODE_FILE_USERDEFINED)
return gconffixCurrent.szUserdefinedPath + oimgTemp.szPath;
}
}
return "";
}
}
private String KmlGenETAPoints(ref PathPositionStored[] ppsCurrent, bool bGenerate, KML_ACCESS_MODES AccessMode, KML_ICON_TYPES Icon, String szServer)
{
if (ppsCurrent == null)
return "";
if (bGenerate)
{
String szTemp = "<Folder><name>ETA Points</name>";
for (uint n = 0; n < ppsCurrent.GetLength(0); n++)
szTemp += "<Placemark>" +
"<name>ETA " + ((ppsCurrent[n].dTime < 60.0) ? (((int)ppsCurrent[n].dTime).ToString() + " sec") : (ppsCurrent[n].dTime / 60.0 + " min")) + "</name><visibility>1</visibility><open>0</open>" +
"<description><![CDATA[Esitmated Position]]></description>" +
"<Style>" +
"<IconStyle><Icon><href>" + KmlGetIconLink(AccessMode, Icon, szServer) + "</href></Icon><scale>0.2</scale></IconStyle>" +
"<LabelStyle><scale>0.4</scale></LabelStyle>" +
"</Style>" +
"<Point><altitudeMode>absolute</altitudeMode><coordinates>" + ppsCurrent[n].dLong.ToString().Replace(",", ".") + "," + ppsCurrent[n].dLat.ToString().Replace(",", ".") + "," + ppsCurrent[n].dAlt.ToString().Replace(",", ".") + "</coordinates><extrude>1</extrude></Point></Placemark>";
return szTemp + "</Folder>";
}
else
return "";
}
private String KmlGenUserPosition(KML_ACCESS_MODES AccessMode, String szServer)
{
lock (lockKmlUserAircraft)
{
return "<Placemark>" +
"<name>User Aircraft Position</name><visibility>1</visibility><open>0</open>" +
"<description><![CDATA[Microsoft Flight Simulator X - User Aircraft<br> <br>" +
"<b>Title:</b> " + suadCurrent.szTitle + "<br> <br>" +
"<b>Type:</b> " + suadCurrent.szATCType + "<br>" +
"<b>Model:</b> " + suadCurrent.szATCModel + "<br> <br>" +
"<b>Identification:</b> " + suadCurrent.szATCID + "<br> <br>" +
"<b>Flight Number:</b> " + suadCurrent.szATCFlightNumber + "<br>" +
"<b>Airline:</b> " + suadCurrent.szATCAirline + "<br> <br>" +
"<b>Altitude:</b> " + ((int)getValueInCurrentUnit(suadCurrent.dAltitude)).ToString().Replace(",", ".") + " " + getCurrentUnitNameShort() + "<br> <br>" +
"<center><img src=\"" + KmlGetImageLink(AccessMode, KML_IMAGE_TYPES.AIRCRAFT, suadCurrent.szTitle, szServer) + "\"></center>]]></description>" +
"<Snippet>" + suadCurrent.szATCType + " " + suadCurrent.szATCModel + " (" + suadCurrent.szTitle + "), " + suadCurrent.szATCID + "\nAltitude: " + ((int)getValueInCurrentUnit(suadCurrent.dAltitude)).ToString().Replace(",", ".") + " " + getCurrentUnitNameShort() + "</Snippet>" +
"<Style>" +
"<IconStyle><Icon><href>" + KmlGetIconLink(AccessMode, KML_ICON_TYPES.USER_AIRCRAFT_POSITION, szServer) + "</href></Icon><scale>0.8</scale></IconStyle>" +
"<LabelStyle><scale>1.0</scale></LabelStyle>" +
"</Style>" +
"<Point><altitudeMode>absolute</altitudeMode><coordinates>" + suadCurrent.dLongitude.ToString().Replace(",", ".") + "," + suadCurrent.dLatitude.ToString().Replace(",", ".") + "," + suadCurrent.dAltitude.ToString().Replace(",", ".") + "</coordinates><extrude>1</extrude></Point></Placemark>";
}
}
private String KmlGenUserPath(KML_ACCESS_MODES AccessMode, String szServer)
{
lock (lockKmlUserPath)
{
return "<Placemark><name>User Aircraft Path</name><description>Path of the user aircraft since tracking started.</description><visibility>1</visibility><open>0</open><Style><LineStyle><color>9fffffff</color><width>2</width></LineStyle></Style><LineString><altitudeMode>absolute</altitudeMode><coordinates>" + szKmlUserAircraftPath + "</coordinates></LineString></Placemark>";
}
}
private String KmlGenUserPrediction(KML_ACCESS_MODES AccessMode, String szServer)
{
String szTemp = "";
lock (lockKmlUserPrediction)
{
szTemp = "<Placemark><name>User Aircraft Path Prediction</name><description>Path prediction of the user aircraft.</description><visibility>1</visibility><open>0</open><Style><LineStyle><color>9f00ffff</color><width>2</width></LineStyle></Style><LineString><altitudeMode>absolute</altitudeMode><coordinates>" + szKmlUserPrediction + "</coordinates></LineString></Placemark>" +
"<Folder><name>ETA Points</name>";
foreach (PathPositionStored ppsTemp in listKmlPredictionPoints)
{
szTemp += "<Placemark>" +
"<name>ETA " + ((ppsTemp.dTime < 60.0) ? (((int)ppsTemp.dTime).ToString() + " sec") : (ppsTemp.dTime / 60.0 + " min")) + "</name><visibility>1</visibility><open>0</open>" +
"<description><![CDATA[Esitmated Position]]></description>" +
"<Style>" +
"<IconStyle><Icon><href>" + KmlGetIconLink(AccessMode, KML_ICON_TYPES.USER_PREDICTION_POINT, szServer) + "</href></Icon><scale>0.2</scale></IconStyle>" +
"<LabelStyle><scale>0.4</scale></LabelStyle>" +
"</Style>" +
"<Point><altitudeMode>absolute</altitudeMode><coordinates>" + ppsTemp.dLong.ToString().Replace(",", ".") + "," + ppsTemp.dLat.ToString().Replace(",", ".") + "," + ppsTemp.dAlt.ToString().Replace(",", ".") + "</coordinates><extrude>1</extrude></Point></Placemark>";
}
}
return szTemp + "</Folder>";
}
private String KmlGenAIAircraft(KML_ACCESS_MODES AccessMode, String szServer)
{
String szTemp = "<Folder><name>Aircraft Positions</name>";
lock (lockDrrAiPlanes)
{
List<DataRequestReturnObject> listTemp = GetCurrentList(ref drrAIPlanes);
foreach (DataRequestReturnObject bmsoTemp in listTemp)
{
//szTemp += "<Placemark>" +
// "<name>" + bmsoTemp.bmsoObject.szATCType + " " + bmsoTemp.bmsoObject.szATCModel + " (" + bmsoTemp.bmsoObject.szATCID + ")</name><visibility>1</visibility><open>0</open>" +
// "<description><![CDATA[Microsoft Flight Simulator X - AI Plane<br> <br>" +
// "<b>Title:</b> " + bmsoTemp.bmsoObject.szTitle + "<br> <br>" +
// "<b>Type:</b> " + bmsoTemp.bmsoObject.szATCType + "<br>" +
// "<b>Model:</b> " + bmsoTemp.bmsoObject.szATCModel + "<br> <br>" +
// "<b>Identification:</b> " + bmsoTemp.bmsoObject.szATCID + "<br> <br>" +
// "<b>Flight Number:</b> " + bmsoTemp.bmsoObject.szATCFlightNumber + "<br>" +
// "<b>Airline:</b> " + bmsoTemp.bmsoObject.szATCAirline + "<br> <br>" +
// "<b>Altitude:</b> " + ((int)getValueInCurrentUnit(bmsoTemp.bmsoObject.dAltitude)).ToString().Replace(",", ".") + " " + getCurrentUnitNameShort() + "<br> <br>" +
// "<center><img src=\"" + KmlGetImageLink(AccessMode, KML_IMAGE_TYPES.AIRCRAFT, bmsoTemp.bmsoObject.szTitle, szServer) + "\"></center>]]></description>" +
// "<Snippet>" + bmsoTemp.bmsoObject.szTitle + "\nAltitude: " + ((int)getValueInCurrentUnit(bmsoTemp.bmsoObject.dAltitude)).ToString().Replace(",", ".") + " " + getCurrentUnitNameShort() + "</Snippet>" +
// "<Style>" +
// "<IconStyle><Icon><href>" + KmlGetIconLink(AccessMode, KML_ICON_TYPES.AI_AIRCRAFT, szServer) + "</href></Icon><scale>0.6</scale></IconStyle>" +
// "<LabelStyle><scale>0.6</scale></LabelStyle>" +
// "</Style>" +
// "<Point><altitudeMode>absolute</altitudeMode><coordinates>" + bmsoTemp.bmsoObject.dLongitude.ToString().Replace(",", ".") + "," + bmsoTemp.bmsoObject.dLatitude.ToString().Replace(",", ".") + "," + bmsoTemp.bmsoObject.dAltitude.ToString().Replace(",", ".") + "</coordinates><extrude>1</extrude></Point></Placemark>";
int FL = (int)Math.Round(getValueInUnit(bmsoTemp.bmsoObject.dAltitude, UnitType.FEET) / 100.0, 0);
int FLRound = FL - (FL % 10);
szTemp += "<Placemark>" +
"<name>" + bmsoTemp.bmsoObject.szATCType + " " + bmsoTemp.bmsoObject.szATCModel + " (" + bmsoTemp.bmsoObject.szATCID + ")</name><visibility>1</visibility><open>0</open>" +
"<description><![CDATA[Microsoft Flight Simulator X - AI Plane<br> <br>" +
"<b>Title:</b> " + bmsoTemp.bmsoObject.szTitle + "<br> <br>" +
"<b>Type:</b> " + bmsoTemp.bmsoObject.szATCType + "<br>" +
"<b>Model:</b> " + bmsoTemp.bmsoObject.szATCModel + "<br> <br>" +
"<b>Identification:</b> " + bmsoTemp.bmsoObject.szATCID + "<br> <br>" +
"<b>Flight Number:</b> " + bmsoTemp.bmsoObject.szATCFlightNumber + "<br>" +
"<b>Airline:</b> " + bmsoTemp.bmsoObject.szATCAirline + "<br> <br>" +
"<b>Altitude:</b> " + ((int)getValueInCurrentUnit(bmsoTemp.bmsoObject.dAltitude)).ToString().Replace(",", ".") + " " + getCurrentUnitNameShort() + "<br> <br>" +
"<center><img src=\"" + KmlGetImageLink(AccessMode, KML_IMAGE_TYPES.AIRCRAFT, bmsoTemp.bmsoObject.szTitle, szServer) + "\"></center>]]></description>" +
"<Snippet>" + bmsoTemp.bmsoObject.szTitle + "\nAltitude: " + ((int)getValueInCurrentUnit(bmsoTemp.bmsoObject.dAltitude)).ToString().Replace(",", ".") + " " + getCurrentUnitNameShort() + "</Snippet>" +
"<Style>" +
"<IconStyle><Icon><href>" + KmlGetIconLink(AccessMode, KML_ICON_TYPES.ATC_LABEL, szServer) + "?code=" + bmsoTemp.bmsoObject.szATCID + "&fl=FL" + FLRound.ToString() + "&speed=" + Math.Round(bmsoTemp.bmsoObject.dSpeed, 0).ToString() + " kn&vspeed=" + (bmsoTemp.bmsoObject.dVSpeed > 0.0 ? "%2F%5C" : (bmsoTemp.bmsoObject.dVSpeed == 0.0 ? "-" : "%5C%2F")) + "&aircraft=" + bmsoTemp.bmsoObject.szATCModel + "</href></Icon><scale>2.5</scale> <hotSpot x=\"30\" y=\"50\" xunits=\"pixels\" yunits=\"pixels\"/></IconStyle>" +
"<LabelStyle><scale>0.6</scale></LabelStyle>" +
"</Style>" +
"<Point><altitudeMode>absolute</altitudeMode><coordinates>" + bmsoTemp.bmsoObject.dLongitude.ToString().Replace(",", ".") + "," + bmsoTemp.bmsoObject.dLatitude.ToString().Replace(",", ".") + "," + bmsoTemp.bmsoObject.dAltitude.ToString().Replace(",", ".") + "</coordinates><extrude>1</extrude></Point></Placemark>";
}
szTemp += "</Folder>";
if (gconffixCurrent.bPredictAIAircrafts)
{
szTemp += "<Folder><name>Aircraft Courses</name>";
foreach (DataRequestReturnObject bmsoTemp in listTemp)
{
if (bmsoTemp.szCoursePrediction == "")
continue;
szTemp += "<Placemark><name>" + bmsoTemp.bmsoObject.szATCType + " " + bmsoTemp.bmsoObject.szATCModel + " (" + bmsoTemp.bmsoObject.szATCID + ")</name><description>Course prediction of the aircraft.</description><visibility>1</visibility><open>0</open><Style><LineStyle><color>9fd20091</color><width>2</width></LineStyle></Style><LineString><altitudeMode>absolute</altitudeMode><coordinates>" + bmsoTemp.szCoursePrediction + "</coordinates></LineString></Placemark>";
PathPositionStored[] ppsTemp = bmsoTemp.ppsPredictionPoints;
szTemp += KmlGenETAPoints(ref ppsTemp, gconffixCurrent.bPredictPointsAIAircrafts, AccessMode, KML_ICON_TYPES.AI_AIRCRAFT_PREDICTION_POINT, szServer);
}
szTemp += "</Folder>";
}
}
return szTemp;
}
private String KmlGenAIHelicopter(KML_ACCESS_MODES AccessMode, String szServer)
{
String szTemp = "<Folder><name>Helicopter Positions</name>";
lock (lockDrrAiHelicopters)
{
List<DataRequestReturnObject> listTemp = GetCurrentList(ref drrAIHelicopters);
foreach (DataRequestReturnObject bmsoTemp in listTemp)
{
szTemp += "<Placemark>" +
"<name>" + bmsoTemp.bmsoObject.szATCType + " " + bmsoTemp.bmsoObject.szATCModel + " (" + bmsoTemp.bmsoObject.szATCID + ")</name><visibility>1</visibility><open>0</open>" +
"<description><![CDATA[Microsoft Flight Simulator X - AI Helicopter<br> <br>" +
"<b>Title:</b> " + bmsoTemp.bmsoObject.szTitle + "<br> <br>" +
"<b>Type:</b> " + bmsoTemp.bmsoObject.szATCType + "<br>" +
"<b>Model:</b> " + bmsoTemp.bmsoObject.szATCModel + "<br> <br>" +
"<b>Identification:</b> " + bmsoTemp.bmsoObject.szATCID + "<br> <br>" +
"<b>Flight Number:</b> " + bmsoTemp.bmsoObject.szATCFlightNumber + "<br>" +
"<b>Airline:</b> " + bmsoTemp.bmsoObject.szATCAirline + "<br> <br>" +
"<b>Altitude:</b> " + ((int)getValueInCurrentUnit(bmsoTemp.bmsoObject.dAltitude)).ToString().Replace(",", ".") + " " + getCurrentUnitNameShort() + "<br> <br>" +
"<center><img src=\"" + KmlGetImageLink(AccessMode, KML_IMAGE_TYPES.AIRCRAFT, bmsoTemp.bmsoObject.szTitle, szServer) + "\"></center>]]></description>" +
"<Snippet>" + bmsoTemp.bmsoObject.szTitle + "\nAltitude: " + ((int)getValueInCurrentUnit(bmsoTemp.bmsoObject.dAltitude)).ToString().Replace(",", ".") + " " + getCurrentUnitNameShort() + "</Snippet>" +
"<Style>" +
"<IconStyle><Icon><href>" + KmlGetIconLink(AccessMode, KML_ICON_TYPES.AI_HELICOPTER, szServer) + "</href></Icon><scale>0.6</scale></IconStyle>" +
"<LabelStyle><scale>0.6</scale></LabelStyle>" +
"</Style>" +
"<Point><altitudeMode>absolute</altitudeMode><coordinates>" + bmsoTemp.bmsoObject.dLongitude.ToString().Replace(",", ".") + "," + bmsoTemp.bmsoObject.dLatitude.ToString().Replace(",", ".") + "," + bmsoTemp.bmsoObject.dAltitude.ToString().Replace(",", ".") + "</coordinates><extrude>1</extrude></Point></Placemark>";
}
szTemp += "</Folder>";
if (gconffixCurrent.bPredictAIHelicopters)
{
szTemp += "<Folder><name>Helicopter Courses</name>";
foreach (DataRequestReturnObject bmsoTemp in listTemp)
{
if (bmsoTemp.szCoursePrediction == "")
continue;
szTemp += "<Placemark><name>" + bmsoTemp.bmsoObject.szATCType + " " + bmsoTemp.bmsoObject.szATCModel + " (" + bmsoTemp.bmsoObject.szATCID + ")</name><description>Course prediction of the helicopter.</description><visibility>1</visibility><open>0</open><Style><LineStyle><color>9fd20091</color><width>2</width></LineStyle></Style><LineString><altitudeMode>absolute</altitudeMode><coordinates>" + bmsoTemp.szCoursePrediction + "</coordinates></LineString></Placemark>";
PathPositionStored[] ppsTemp = bmsoTemp.ppsPredictionPoints;
szTemp += KmlGenETAPoints(ref ppsTemp, gconffixCurrent.bPredictPointsAIHelicopters, AccessMode, KML_ICON_TYPES.AI_HELICOPTER_PREDICTION_POINT, szServer);
}
szTemp += "</Folder>";
}
}
return szTemp;
}
private String KmlGenAIBoat(KML_ACCESS_MODES AccessMode, String szServer)
{
String szTemp = "<Folder><name>Boat Positions</name>";
lock (lockDrrAiBoats)
{
List<DataRequestReturnObject> listTemp = GetCurrentList(ref drrAIBoats);
foreach (DataRequestReturnObject bmsoTemp in listTemp)
{
szTemp += "<Placemark>" +
"<name>" + bmsoTemp.bmsoObject.szTitle + "</name><visibility>1</visibility><open>0</open>" +
"<description><![CDATA[Microsoft Flight Simulator X - AI Boat<br> <br>" +
"<b>Title:</b> " + bmsoTemp.bmsoObject.szTitle + "<br> <br>" +
"<b>Altitude:</b> " + ((int)getValueInCurrentUnit(bmsoTemp.bmsoObject.dAltitude)).ToString().Replace(",", ".") + " " + getCurrentUnitNameShort() + "<br> <br>" +
"<center><img src=\"" + KmlGetImageLink(AccessMode, KML_IMAGE_TYPES.WATER, bmsoTemp.bmsoObject.szTitle, szServer) + "\"></center>]]></description>" +
"<Snippet>Altitude: " + ((int)getValueInCurrentUnit(bmsoTemp.bmsoObject.dAltitude)).ToString().Replace(",", ".") + " " + getCurrentUnitNameShort() + "</Snippet>" +
"<Style>" +
"<IconStyle><Icon><href>" + KmlGetIconLink(AccessMode, KML_ICON_TYPES.AI_BOAT, szServer) + "</href></Icon><scale>0.6</scale></IconStyle>" +
"<LabelStyle><scale>0.6</scale></LabelStyle>" +
"</Style>" +
"<Point><altitudeMode>absolute</altitudeMode><coordinates>" + bmsoTemp.bmsoObject.dLongitude.ToString().Replace(",", ".") + "," + bmsoTemp.bmsoObject.dLatitude.ToString().Replace(",", ".") + "," + bmsoTemp.bmsoObject.dAltitude.ToString().Replace(",", ".") + "</coordinates><extrude>1</extrude></Point></Placemark>";
}
szTemp += "</Folder>";
if (gconffixCurrent.bPredictAIBoats)
{
szTemp += "<Folder><name>Boat Courses</name>";
foreach (DataRequestReturnObject bmsoTemp in listTemp)
{
if (bmsoTemp.szCoursePrediction == "")
continue;
szTemp += "<Placemark><name>" + bmsoTemp.bmsoObject.szTitle + "</name><description>Course prediction of the boat.</description><visibility>1</visibility><open>0</open><Style><LineStyle><color>9f00b545</color><width>2</width></LineStyle></Style><LineString><altitudeMode>absolute</altitudeMode><coordinates>" + bmsoTemp.szCoursePrediction + "</coordinates></LineString></Placemark>";
PathPositionStored[] ppsTemp = bmsoTemp.ppsPredictionPoints;
szTemp += KmlGenETAPoints(ref ppsTemp, gconffixCurrent.bPredictPointsAIBoats, AccessMode, KML_ICON_TYPES.AI_BOAT_PREDICTION_POINT, szServer);
}
szTemp += "</Folder>";
}
}
return szTemp;
}
private String KmlGenAIGroundUnit(KML_ACCESS_MODES AccessMode, String szServer)
{
String szTemp = "<Folder><name>Ground Vehicle Positions</name>";
lock (lockDrrAiGround)
{
List<DataRequestReturnObject> listTemp = GetCurrentList(ref drrAIGround);
foreach (DataRequestReturnObject bmsoTemp in listTemp)
{
szTemp += "<Placemark>" +
"<name>" + bmsoTemp.bmsoObject.szTitle + "</name><visibility>1</visibility><open>0</open>" +
"<description><![CDATA[Microsoft Flight Simulator X - AI Vehicle<br> <br>" +
"<b>Title:</b> " + bmsoTemp.bmsoObject.szTitle + "<br> <br>" +
"<b>Altitude:</b> " + ((int)getValueInCurrentUnit(bmsoTemp.bmsoObject.dAltitude)).ToString().Replace(",", ".") + " " + getCurrentUnitNameShort() + "<br> <br>" +
"<center><img src=\"" + KmlGetImageLink(AccessMode, KML_IMAGE_TYPES.GROUND, bmsoTemp.bmsoObject.szTitle, szServer) + "\"></center>]]></description>" +
"<Snippet>Altitude: " + ((int)getValueInCurrentUnit(bmsoTemp.bmsoObject.dAltitude)).ToString().Replace(",", ".") + " " + getCurrentUnitNameShort() + "</Snippet>" +
"<Style>" +
"<IconStyle><Icon><href>" + KmlGetIconLink(AccessMode, KML_ICON_TYPES.AI_GROUND_UNIT, szServer) + "</href></Icon><scale>0.6</scale></IconStyle>" +
"<LabelStyle><scale>0.6</scale></LabelStyle>" +
"</Style>" +
"<Point><altitudeMode>absolute</altitudeMode><coordinates>" + bmsoTemp.bmsoObject.dLongitude.ToString().Replace(",", ".") + "," + bmsoTemp.bmsoObject.dLatitude.ToString().Replace(",", ".") + "," + bmsoTemp.bmsoObject.dAltitude.ToString().Replace(",", ".") + "</coordinates><extrude>1</extrude></Point></Placemark>";
}
szTemp += "</Folder>";
if (gconffixCurrent.bPredictAIGroundUnits)
{
szTemp += "<Folder><name>Ground Vehicle Courses</name>";
foreach (DataRequestReturnObject bmsoTemp in listTemp)
{
if (bmsoTemp.szCoursePrediction == "")
continue;
szTemp += "<Placemark><name>" + bmsoTemp.bmsoObject.szTitle + "</name><description>Course prediction of the ground vehicle.</description><visibility>1</visibility><open>0</open><Style><LineStyle><color>9f00b545</color><width>2</width></LineStyle></Style><LineString><altitudeMode>absolute</altitudeMode><coordinates>" + bmsoTemp.szCoursePrediction + "</coordinates></LineString></Placemark>";
PathPositionStored[] ppsTemp = bmsoTemp.ppsPredictionPoints;
szTemp += KmlGenETAPoints(ref ppsTemp, gconffixCurrent.bPredictPointsAIGroundUnits, AccessMode, KML_ICON_TYPES.AI_GROUND_PREDICTION_POINT, szServer);
}
szTemp += "</Folder>";
}
}
return szTemp;
}
private byte[] KmlGenAtcLabel(String CallSign, String FL, String Aircraft, String Speed, String VerticalSpeed)
{
Bitmap bmp = new Bitmap(imgAtcLabel);
Graphics g = Graphics.FromImage(bmp);
Pen pen = new Pen(Color.FromArgb(81, 255, 147));
Brush brush = new SolidBrush(Color.FromArgb(81, 255, 147));
Font font = new Font("Courier New", 10, FontStyle.Bold);
Font font_small = new Font("Courier New", 6, FontStyle.Bold);
float fX = 72;
float fY = 13;
g.DrawString(CallSign, font, brush, new PointF(fX, fY));
fY += g.MeasureString(CallSign, font).Height;
g.DrawString(FL + " " + VerticalSpeed, font, brush, new PointF(fX, fY));
fY += g.MeasureString(FL + " " + VerticalSpeed, font).Height;
g.DrawString(Aircraft, font, brush, new PointF(fX, fY));
return BitmapToPngBytes(bmp);
}
//private String KmlGenFlightPlans(KML_ACCESS_MODES AccessMode, String szServer)
//{
// String szTemp = "";
// lock (lockFlightPlanList)
// {
// foreach (FlightPlan fpTemp in listFlightPlans)
// {
// XmlDocument xmldTemp = fpTemp.xmldPlan;
// String szTempInner = "";
// String szTempWaypoints = "";
// String szPath = "";
// try
// {
// for (XmlNode xmlnTemp = xmldTemp["SimBase.Document"]["FlightPlan.FlightPlan"].FirstChild; xmlnTemp != null; xmlnTemp = xmlnTemp.NextSibling)
// {
// if (xmlnTemp.Name.ToLower() != "atcwaypoint")
// continue;
// KML_ICON_TYPES iconType;
// String szType = xmlnTemp["ATCWaypointType"].InnerText.ToLower();
// if (szType == "intersection")
// iconType = KML_ICON_TYPES.PLAN_INTER;
// else if (szType == "ndb")
// iconType = KML_ICON_TYPES.PLAN_NDB;
// else if (szType == "vor")
// iconType = KML_ICON_TYPES.PLAN_VOR;
// else if (szType == "user")
// iconType = KML_ICON_TYPES.PLAN_USER;
// else if (szType == "airport")
// iconType = KML_ICON_TYPES.PLAN_PORT;
// else
// iconType = KML_ICON_TYPES.UNKNOWN;
// char[] szSeperator = { ',' };
// String[] szCoordinates = xmlnTemp["WorldPosition"].InnerText.Split(szSeperator);
// if (szCoordinates.GetLength(0) != 3)
// throw new System.Exception("Invalid position value");
// String szAirway = "", szICAOIdent = "", szICAORegion = "";
// if (xmlnTemp["ATCAirway"] != null)
// szAirway = xmlnTemp["ATCAirway"].InnerText;
// if (xmlnTemp["ICAO"] != null)
// {
// if (xmlnTemp["ICAO"]["ICAOIdent"] != null)
// szICAOIdent = xmlnTemp["ICAO"]["ICAOIdent"].InnerText;
// if (xmlnTemp["ICAO"]["ICAORegion"] != null)
// szICAORegion = xmlnTemp["ICAO"]["ICAORegion"].InnerText;
// }
// double dCurrentLong = ConvertDegToDouble(szCoordinates[1]);
// double dCurrentLat = ConvertDegToDouble(szCoordinates[0]);
// double dCurrentAlt = System.Double.Parse(szCoordinates[2]);
// szTempWaypoints += "<Placemark>" +
// "<name>" + xmlnTemp["ATCWaypointType"].InnerText + " (" + xmlnTemp.Attributes["id"].Value + ")</name><visibility>1</visibility><open>0</open>" +
// "<description><![CDATA[Flight Plane Element<br> <br>" +
// "<b>Waypoint Type:</b> " + xmlnTemp["ATCWaypointType"].InnerText + "<br> <br>" +
// (szAirway != "" ? "<b>ATC Airway:</b> " + szAirway + "<br> <br>" : "") +
// (szICAOIdent != "" ? "<b>ICAO Identification:</b> " + szICAOIdent + "<br>" : "") +
// (szICAORegion != "" ? "<b>ICAO Region:</b> " + szICAORegion : "") +
// "]]></description>" +
// "<Snippet>Waypoint Type: " + xmlnTemp["ATCWaypointType"].InnerText + (szAirway != "" ? "\nAirway: " + szAirway : "") + "</Snippet>" +
// "<Style>" +
// "<IconStyle><Icon><href>" + KmlGetIconLink(AccessMode, iconType, szServer) + "</href></Icon><scale>1.0</scale></IconStyle>" +
// "<LabelStyle><scale>0.6</scale></LabelStyle>" +
// "</Style>" +
// "<Point><altitudeMode>clampToGround</altitudeMode><coordinates>" + dCurrentLong.ToString().Replace(",", ".") + "," + dCurrentLat.ToString().Replace(",", ".") + "," + dCurrentAlt.ToString().Replace(",", ".") + "</coordinates><extrude>1</extrude></Point></Placemark>";
// szPath += dCurrentLong.ToString().Replace(",", ".") + "," + dCurrentLat.ToString().Replace(",", ".") + "," + dCurrentAlt.ToString().Replace(",", ".") + "\n";
// }
// szTempInner = "<Folder><open>0</open>" +
// "<name>" + (xmldTemp["SimBase.Document"]["FlightPlan.FlightPlan"]["Title"] != null ? xmldTemp["SimBase.Document"]["FlightPlan.FlightPlan"]["Title"].InnerText : "n/a") + "</name>" +
// "<description><![CDATA[" +
// "Type: " + (xmldTemp["SimBase.Document"]["FlightPlan.FlightPlan"]["FPType"] != null ? xmldTemp["SimBase.Document"]["FlightPlan.FlightPlan"]["FPType"].InnerText : "n/a") + " (" + (xmldTemp["SimBase.Document"]["FlightPlan.FlightPlan"]["RouteType"] != null ? xmldTemp["SimBase.Document"]["FlightPlan.FlightPlan"]["RouteType"].InnerText : "n/a") + ")<br>" +
// "Flight from " + (xmldTemp["SimBase.Document"]["FlightPlan.FlightPlan"]["DepartureName"] != null ? xmldTemp["SimBase.Document"]["FlightPlan.FlightPlan"]["DepartureName"].InnerText : "n/a") + " to " + (xmldTemp["SimBase.Document"]["FlightPlan.FlightPlan"]["DestinationName"] != null ? xmldTemp["SimBase.Document"]["FlightPlan.FlightPlan"]["DestinationName"].InnerText : "n/a") + ".<br> <br>" +
// "Altitude: " + (xmldTemp["SimBase.Document"]["FlightPlan.FlightPlan"]["CruisingAlt"] != null ? xmldTemp["SimBase.Document"]["FlightPlan.FlightPlan"]["CruisingAlt"].InnerText : "n/a") +
// "]]></description>" +
// "<Placemark><name>Path</name><Style><LineStyle><color>9f1ab6ff</color><width>2</width></LineStyle></Style><LineString><tessellate>1</tessellate><altitudeMode>clampToGround</altitudeMode><coordinates>" + szPath + "</coordinates></LineString></Placemark>" +
// "<Folder><open>0</open><name>Waypoints</name>" + szTempWaypoints + "</Folder>" +
// "</Folder>";
// }
// catch
// {
// szTemp += "<Folder><name>Invalid Flight Plan</name><snippet>Error loading flight plan.</snippet></Folder>";
// continue;
// }
// szTemp += szTempInner;
// }
// }
// return szTemp;
//}
#endregion
#region Update Check
// private void checkForProgramUpdate()
// {
// try
// {
// szOnlineVersionCheckData = "";
// wrOnlineVersionCheck = WebRequest.Create("http://juergentreml.online.de/fsxget/provide/version.txt");
// wrOnlineVersionCheck.BeginGetResponse(new AsyncCallback(RespCallback), wrOnlineVersionCheck);
// }
// catch
// {
//#if DEBUG
// notifyIconMain.ShowBalloonTip(5, Text, "Couldn't check for program update online!", ToolTipIcon.Warning);
//#endif
// }
// }
// private void RespCallback(IAsyncResult asynchronousResult)
// {
// try
// {
// WebRequest myWebRequest = (WebRequest)asynchronousResult.AsyncState;
// wrespOnlineVersionCheck = myWebRequest.EndGetResponse(asynchronousResult);
// Stream responseStream = wrespOnlineVersionCheck.GetResponseStream();
// responseStream.BeginRead(bOnlineVersionCheckRawData, 0, iOnlineVersionCheckRawDataLength, new AsyncCallback(ReadCallBack), responseStream);
// }
// catch
// {
//#if DEBUG
// notifyIconMain.ShowBalloonTip(5, Text, "Couldn't check for program update online!", ToolTipIcon.Warning);
//#endif
// }
// }
// private void ReadCallBack(IAsyncResult asyncResult)
// {
// try
// {
// Stream responseStream = (Stream)asyncResult.AsyncState;
// int iRead = responseStream.EndRead(asyncResult);
// if (iRead > 0)
// {
// szOnlineVersionCheckData += Encoding.ASCII.GetString(bOnlineVersionCheckRawData, 0, iRead);
// responseStream.BeginRead(bOnlineVersionCheckRawData, 0, iOnlineVersionCheckRawDataLength, new AsyncCallback(ReadCallBack), responseStream);
// }
// else
// {
// responseStream.Close();
// wrespOnlineVersionCheck.Close();
// char[] szSeperator = { '.' };
// String[] szVersionLocal = Application.ProductVersion.Split(szSeperator);
// String[] szVersionOnline = szOnlineVersionCheckData.Split(szSeperator);
// for (int i = 0; i < Math.Min(szVersionLocal.GetLength(0), szVersionOnline.GetLength(0)); i++)
// {
// if (Int64.Parse(szVersionOnline[i]) > Int64.Parse(szVersionLocal[i]))
// {
// notifyIconMain.ShowBalloonTip(30, Text, "A new program version is available!\n\nLatest Version:\t" + szOnlineVersionCheckData + "\nYour Version:\t" + Application.ProductVersion, ToolTipIcon.Info);
// break;
// }
// else if (Int64.Parse(szVersionOnline[i]) < Int64.Parse(szVersionLocal[i]))
// break;
// }
// }
// }
// catch
// {
//#if DEBUG
// notifyIconMain.ShowBalloonTip(5, Text, "Couldn't check for program update online!", ToolTipIcon.Warning);
//#endif
// }
// }
#endregion
#region Timers
private void timerFSXConnect_Tick(object sender, EventArgs e)
{
if (openConnection())
{
timerFSXConnect.Stop();
bConnected = true;
notifyIconMain.Icon = icReceive;
notifyIconMain.Text = Text + "(Waiting for connection...)";
safeShowBalloonTip(1000, Text, "Connected to FSX!", ToolTipIcon.Info);
}
}
private void timerIPAddressRefresh_Tick(object sender, EventArgs e)
{
IPHostEntry ipheLocalhost1 = Dns.GetHostEntry(Dns.GetHostName());
IPHostEntry ipheLocalhost2 = Dns.GetHostEntry("localhost");
lock (lockIPAddressList)
{
ipalLocal1 = ipheLocalhost1.AddressList;
ipalLocal2 = ipheLocalhost2.AddressList;
}
}
private void timerQueryUserAircraft_Tick(object sender, EventArgs e)
{
simconnect.RequestDataOnSimObjectType(DATA_REQUESTS.REQUEST_USER_AIRCRAFT, DEFINITIONS.StructBasicMovingSceneryObject, 0, SIMCONNECT_SIMOBJECT_TYPE.USER);
}
private void timerQueryUserPath_Tick(object sender, EventArgs e)
{
simconnect.RequestDataOnSimObjectType(DATA_REQUESTS.REQUEST_USER_PATH, DEFINITIONS.StructBasicMovingSceneryObject, 0, SIMCONNECT_SIMOBJECT_TYPE.USER);
}
private void timerUserPrediction_Tick(object sender, EventArgs e)
{
simconnect.RequestDataOnSimObjectType(DATA_REQUESTS.REQUEST_USER_PREDICTION, DEFINITIONS.StructBasicMovingSceneryObject, 0, SIMCONNECT_SIMOBJECT_TYPE.USER);
}
private void timerQueryAIAircrafts_Tick(object sender, EventArgs e)
{
simconnect.RequestDataOnSimObjectType(DATA_REQUESTS.REQUEST_AI_PLANE, DEFINITIONS.StructBasicMovingSceneryObject, (uint)gconffixCurrent.iRangeAIAircrafts, SIMCONNECT_SIMOBJECT_TYPE.AIRCRAFT);
}
private void timerQueryAIHelicopters_Tick(object sender, EventArgs e)
{
simconnect.RequestDataOnSimObjectType(DATA_REQUESTS.REQUEST_AI_HELICOPTER, DEFINITIONS.StructBasicMovingSceneryObject, (uint)gconffixCurrent.iRangeAIHelicopters, SIMCONNECT_SIMOBJECT_TYPE.HELICOPTER);
}
private void timerQueryAIBoats_Tick(object sender, EventArgs e)
{
simconnect.RequestDataOnSimObjectType(DATA_REQUESTS.REQUEST_AI_BOAT, DEFINITIONS.StructBasicMovingSceneryObject, (uint)gconffixCurrent.iRangeAIBoats, SIMCONNECT_SIMOBJECT_TYPE.BOAT);
}
private void timerQueryAIGroundUnits_Tick(object sender, EventArgs e)
{
simconnect.RequestDataOnSimObjectType(DATA_REQUESTS.REQUEST_AI_GROUND, DEFINITIONS.StructBasicMovingSceneryObject, (uint)gconffixCurrent.iRangeAIGroundUnits, SIMCONNECT_SIMOBJECT_TYPE.GROUND);
}
#endregion
#region Config File Read & Write
private void ConfigMirrorToVariables()
{
gconffixCurrent.bExitOnFsxExit = (xmldSettings["fsxget"]["settings"]["options"]["general"]["application-startup"].Attributes["Exit"].Value.ToLower() == "true");
lock (lockChConf)
{
gconfchCurrent.bEnabled = (xmldSettings["fsxget"]["settings"]["options"]["general"]["enable-on-startup"].Attributes["Enabled"].Value == "1");
gconfchCurrent.bShowBalloons = (xmldSettings["fsxget"]["settings"]["options"]["general"]["show-balloon-tips"].Attributes["Enabled"].Value == "1");
}
gconffixCurrent.bLoadKMLFile = (xmldSettings["fsxget"]["settings"]["options"]["general"]["load-kml-file"].Attributes["Enabled"].Value == "1");
//gconffixCurrent.bCheckForUpdates = (xmldSettings["fsxget"]["settings"]["options"]["general"]["update-check"].Attributes["Enabled"].Value == "1");
gconffixCurrent.iTimerUserAircraft = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-user-aircraft"].Attributes["Interval"].Value);
gconffixCurrent.bQueryUserAircraft = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-user-aircraft"].Attributes["Enabled"].Value == "1");
gconffixCurrent.iTimerUserPath = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-user-path"].Attributes["Interval"].Value);
gconffixCurrent.bQueryUserPath = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-user-path"].Attributes["Enabled"].Value == "1");
gconffixCurrent.iTimerUserPathPrediction = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["user-path-prediction"].Attributes["Interval"].Value);
gconffixCurrent.bUserPathPrediction = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["user-path-prediction"].Attributes["Enabled"].Value == "1");
int iCount = 0;
for (XmlNode xmlnTemp = xmldSettings["fsxget"]["settings"]["options"]["fsx"]["user-path-prediction"].FirstChild; xmlnTemp != null; xmlnTemp = xmlnTemp.NextSibling)
{
if (xmlnTemp.Name == "prediction-point")
iCount++;
}
gconffixCurrent.dPredictionTimes = new double[iCount];
iCount = 0;
for (XmlNode xmlnTemp = xmldSettings["fsxget"]["settings"]["options"]["fsx"]["user-path-prediction"].FirstChild; xmlnTemp != null; xmlnTemp = xmlnTemp.NextSibling)
{
if (xmlnTemp.Name == "prediction-point")
{
gconffixCurrent.dPredictionTimes[iCount] = System.Int64.Parse(xmlnTemp.Attributes["Time"].Value);
iCount++;
}
}
gconffixCurrent.iTimerAIAircrafts = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-aircrafts"].Attributes["Interval"].Value);
gconffixCurrent.iRangeAIAircrafts = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-aircrafts"].Attributes["Range"].Value);
gconffixCurrent.bQueryAIAircrafts = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-aircrafts"].Attributes["Enabled"].Value == "1");
gconffixCurrent.bPredictAIAircrafts = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-aircrafts"].Attributes["Prediction"].Value == "1");
gconffixCurrent.bPredictPointsAIAircrafts = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-aircrafts"].Attributes["PredictionPoints"].Value == "1");
gconffixCurrent.iTimerAIHelicopters = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-helicopters"].Attributes["Interval"].Value);
gconffixCurrent.iRangeAIHelicopters = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-helicopters"].Attributes["Range"].Value);
gconffixCurrent.bQueryAIHelicopters = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-helicopters"].Attributes["Enabled"].Value == "1");
gconffixCurrent.bPredictAIHelicopters = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-helicopters"].Attributes["Prediction"].Value == "1");
gconffixCurrent.bPredictPointsAIHelicopters = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-helicopters"].Attributes["PredictionPoints"].Value == "1");
gconffixCurrent.iTimerAIBoats = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-boats"].Attributes["Interval"].Value);
gconffixCurrent.iRangeAIBoats = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-boats"].Attributes["Range"].Value);
gconffixCurrent.bQueryAIBoats = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-boats"].Attributes["Enabled"].Value == "1");
gconffixCurrent.bPredictAIBoats = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-boats"].Attributes["Prediction"].Value == "1");
gconffixCurrent.bPredictPointsAIBoats = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-boats"].Attributes["PredictionPoints"].Value == "1");
gconffixCurrent.iTimerAIGroundUnits = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-ground-units"].Attributes["Interval"].Value);
gconffixCurrent.iRangeAIGroundUnits = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-ground-units"].Attributes["Range"].Value);
gconffixCurrent.bQueryAIGroundUnits = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-ground-units"].Attributes["Enabled"].Value == "1");
gconffixCurrent.bPredictAIGroundUnits = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-ground-units"].Attributes["Prediction"].Value == "1");
gconffixCurrent.bPredictPointsAIGroundUnits = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-ground-units"].Attributes["PredictionPoints"].Value == "1");
gconffixCurrent.bQueryAIObjects = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"].Attributes["Enabled"].Value == "1");
gconffixCurrent.iUpdateGEUserAircraft = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["user-aircraft"].Attributes["Interval"].Value);
gconffixCurrent.iUpdateGEUserPath = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["user-path"].Attributes["Interval"].Value);
gconffixCurrent.iUpdateGEUserPrediction = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["user-path-prediction"].Attributes["Interval"].Value);
gconffixCurrent.iUpdateGEAIAircrafts = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["ai-aircrafts"].Attributes["Interval"].Value);
gconffixCurrent.iUpdateGEAIHelicopters = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["ai-helicopters"].Attributes["Interval"].Value);
gconffixCurrent.iUpdateGEAIBoats = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["ai-boats"].Attributes["Interval"].Value);
gconffixCurrent.iUpdateGEAIGroundUnits = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["ai-ground-units"].Attributes["Interval"].Value);
gconffixCurrent.iServerPort = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["server-settings"]["port"].Attributes["Value"].Value);
gconffixCurrent.uiServerAccessLevel = (uint)System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["server-settings"]["access-level"].Attributes["Value"].Value);
gconffixCurrent.bFsxConnectionIsLocal = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["connection"].Attributes["Local"].Value.ToLower() == "true");
gconffixCurrent.szFsxConnectionHost = xmldSettings["fsxget"]["settings"]["options"]["fsx"]["connection"].Attributes["Host"].Value;
gconffixCurrent.szFsxConnectionPort = xmldSettings["fsxget"]["settings"]["options"]["fsx"]["connection"].Attributes["Port"].Value;
gconffixCurrent.szFsxConnectionProtocol = xmldSettings["fsxget"]["settings"]["options"]["fsx"]["connection"].Attributes["Protocol"].Value;
//gconffixCurrent.bLoadFlightPlans = (xmldSettings["fsxget"]["settings"]["options"]["flightplans"].Attributes["Enabled"].Value == "1");
gconffixCurrent.utUnits = (UnitType)System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["units"].InnerText);
gconffixCurrent.szUserdefinedPath = "";
}
private void ConfigMirrorToForm()
{
checkBox1.Checked = (xmldSettings["fsxget"]["settings"]["options"]["general"]["application-startup"].Attributes["Exit"].Value.ToLower() == "true");
checkEnableOnStartup.Checked = (xmldSettings["fsxget"]["settings"]["options"]["general"]["enable-on-startup"].Attributes["Enabled"].Value == "1");
checkShowInfoBalloons.Checked = (xmldSettings["fsxget"]["settings"]["options"]["general"]["show-balloon-tips"].Attributes["Enabled"].Value == "1");
checkBoxLoadKMLFile.Checked = (xmldSettings["fsxget"]["settings"]["options"]["general"]["load-kml-file"].Attributes["Enabled"].Value == "1");
//checkBoxUpdateCheck.Checked = (xmldSettings["fsxget"]["settings"]["options"]["general"]["update-check"].Attributes["Enabled"].Value == "1");
numericUpDownQueryUserAircraft.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-user-aircraft"].Attributes["Interval"].Value);
checkQueryUserAircraft.Checked = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-user-aircraft"].Attributes["Enabled"].Value == "1");
numericUpDownQueryUserPath.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-user-path"].Attributes["Interval"].Value);
checkQueryUserPath.Checked = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-user-path"].Attributes["Enabled"].Value == "1");
numericUpDownUserPathPrediction.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["user-path-prediction"].Attributes["Interval"].Value);
checkBoxUserPathPrediction.Checked = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["user-path-prediction"].Attributes["Enabled"].Value == "1");
listBoxPathPrediction.Items.Clear();
for (XmlNode xmlnTemp = xmldSettings["fsxget"]["settings"]["options"]["fsx"]["user-path-prediction"].FirstChild; xmlnTemp != null; xmlnTemp = xmlnTemp.NextSibling)
{
if (xmlnTemp.Name == "prediction-point")
{
ListBoxPredictionTimesItem lbptiTemp = new ListBoxPredictionTimesItem();
lbptiTemp.dTime = System.Int64.Parse(xmlnTemp.Attributes["Time"].Value);
bool bInserted = false;
for (int n = 0; n < listBoxPathPrediction.Items.Count; n++)
{
if (((ListBoxPredictionTimesItem)listBoxPathPrediction.Items[n]).dTime > lbptiTemp.dTime)
{
listBoxPathPrediction.Items.Insert(n, lbptiTemp);
bInserted = true;
break;
}
}
if (!bInserted)
listBoxPathPrediction.Items.Add(lbptiTemp);
}
}
numericUpDownQueryAIAircraftsInterval.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-aircrafts"].Attributes["Interval"].Value);
numericUpDownQueryAIAircraftsRadius.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-aircrafts"].Attributes["Range"].Value);
checkBoxAIAircraftsPredictPoints.Checked = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-aircrafts"].Attributes["PredictionPoints"].Value == "1");
checkBoxAIAircraftsPredict.Checked = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-aircrafts"].Attributes["Prediction"].Value == "1");
checkBoxAIAircraftsPredict_CheckedChanged(null, null);
checkBoxQueryAIAircrafts.Checked = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-aircrafts"].Attributes["Enabled"].Value == "1");
checkBoxQueryAIAircrafts_CheckedChanged(null, null);
numericUpDownQueryAIHelicoptersInterval.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-helicopters"].Attributes["Interval"].Value);
numericUpDownQueryAIHelicoptersRadius.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-helicopters"].Attributes["Range"].Value);
checkBoxAIHelicoptersPredictPoints.Checked = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-helicopters"].Attributes["PredictionPoints"].Value == "1");
checkBoxAIHelicoptersPredict.Checked = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-helicopters"].Attributes["Prediction"].Value == "1");
checkBoxAIHelicoptersPredict_CheckedChanged(null, null);
checkBoxQueryAIHelicopters.Checked = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-helicopters"].Attributes["Enabled"].Value == "1");
checkBoxQueryAIHelicopters_CheckedChanged(null, null);
numericUpDownQueryAIBoatsInterval.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-boats"].Attributes["Interval"].Value);
numericUpDownQueryAIBoatsRadius.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-boats"].Attributes["Range"].Value);
checkBoxAIBoatsPredictPoints.Checked = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-boats"].Attributes["PredictionPoints"].Value == "1");
checkBoxAIBoatsPredict.Checked = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-boats"].Attributes["Prediction"].Value == "1");
checkBoxAIBoatsPredict_CheckedChanged(null, null);
checkBoxQueryAIBoats.Checked = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-boats"].Attributes["Enabled"].Value == "1");
checkBoxQueryAIBoats_CheckedChanged(null, null);
numericUpDownQueryAIGroudUnitsInterval.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-ground-units"].Attributes["Interval"].Value);
numericUpDownQueryAIGroudUnitsRadius.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-ground-units"].Attributes["Range"].Value);
checkBoxAIGroundPredictPoints.Checked = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-ground-units"].Attributes["PredictionPoints"].Value == "1");
checkBoxAIGroundPredict.Checked = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-ground-units"].Attributes["Prediction"].Value == "1");
checkBoxAIGroundPredict_CheckedChanged(null, null);
checkBoxQueryAIGroudUnits.Checked = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-ground-units"].Attributes["Enabled"].Value == "1");
checkBoxQueryAIGroudUnits_CheckedChanged(null, null);
checkBoxQueryAIObjects.Checked = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"].Attributes["Enabled"].Value == "1");
numericUpDownRefreshUserAircraft.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["user-aircraft"].Attributes["Interval"].Value);
numericUpDownRefreshUserPath.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["user-path"].Attributes["Interval"].Value);
numericUpDownRefreshUserPrediction.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["user-path-prediction"].Attributes["Interval"].Value);
numericUpDownRefreshAIAircrafts.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["ai-aircrafts"].Attributes["Interval"].Value);
numericUpDownRefreshAIHelicopter.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["ai-helicopters"].Attributes["Interval"].Value);
numericUpDownRefreshAIBoats.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["ai-boats"].Attributes["Interval"].Value);
numericUpDownRefreshAIGroundUnits.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["ai-ground-units"].Attributes["Interval"].Value);
numericUpDownServerPort.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["server-settings"]["port"].Attributes["Value"].Value);
if (System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["server-settings"]["access-level"].Attributes["Value"].Value) == 1)
radioButtonAccessRemote.Checked = true;
else
radioButtonAccessLocalOnly.Checked = true;
//checkBoxLoadFlightPlans.Checked = (xmldSettings["fsxget"]["settings"]["options"]["flightplans"].Attributes["Enabled"].Value == "1");
//listViewFlightPlans.Items.Clear();
//int iCount = 0;
//for (XmlNode xmlnTemp = xmldSettings["fsxget"]["settings"]["options"]["flightplans"].FirstChild; xmlnTemp != null; xmlnTemp = xmlnTemp.NextSibling)
//{
// ListViewItem lviTemp = listViewFlightPlans.Items.Insert(iCount, xmlnTemp.Attributes["Name"].Value);
// lviTemp.Checked = (xmlnTemp.Attributes["Show"].Value == "1" ? true : false);
// lviTemp.SubItems.Add(xmlnTemp.Attributes["File"].Value);
// iCount++;
//}
radioButton7.Checked = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["connection"].Attributes["Local"].Value.ToLower() == "true");
radioButton6.Checked = !radioButton7.Checked;
textBox1.Text = xmldSettings["fsxget"]["settings"]["options"]["fsx"]["connection"].Attributes["Host"].Value;
textBox3.Text = xmldSettings["fsxget"]["settings"]["options"]["fsx"]["connection"].Attributes["Port"].Value;
comboBox1.SelectedIndex = comboBox1.FindString(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["connection"].Attributes["Protocol"].Value);
comboBox2.SelectedIndex = int.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["units"].InnerText);
UpdateCheckBoxStates();
UpdateButtonStates();
}
private void ConfigRetrieveFromForm()
{
xmldSettings["fsxget"]["settings"]["options"]["general"]["application-startup"].Attributes["Exit"].Value = checkBox1.Checked ? "True" : "False";
xmldSettings["fsxget"]["settings"]["options"]["general"]["enable-on-startup"].Attributes["Enabled"].Value = checkEnableOnStartup.Checked ? "1" : "0";
xmldSettings["fsxget"]["settings"]["options"]["general"]["show-balloon-tips"].Attributes["Enabled"].Value = checkShowInfoBalloons.Checked ? "1" : "0";
xmldSettings["fsxget"]["settings"]["options"]["general"]["load-kml-file"].Attributes["Enabled"].Value = checkBoxLoadKMLFile.Checked ? "1" : "0";
//xmldSettings["fsxget"]["settings"]["options"]["general"]["update-check"].Attributes["Enabled"].Value = checkBoxUpdateCheck.Checked ? "1" : "0";
xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-user-aircraft"].Attributes["Interval"].Value = numericUpDownQueryUserAircraft.Value.ToString();
xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-user-aircraft"].Attributes["Enabled"].Value = checkQueryUserAircraft.Checked ? "1" : "0";
xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-user-path"].Attributes["Interval"].Value = numericUpDownQueryUserPath.Value.ToString();
xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-user-path"].Attributes["Enabled"].Value = checkQueryUserPath.Checked ? "1" : "0";
xmldSettings["fsxget"]["settings"]["options"]["fsx"]["user-path-prediction"].Attributes["Interval"].Value = numericUpDownUserPathPrediction.Value.ToString();
xmldSettings["fsxget"]["settings"]["options"]["fsx"]["user-path-prediction"].Attributes["Enabled"].Value = checkBoxUserPathPrediction.Checked ? "1" : "0";
XmlNode xmlnTempLoop = xmldSettings["fsxget"]["settings"]["options"]["fsx"]["user-path-prediction"].FirstChild;
while (xmlnTempLoop != null)
{
XmlNode xmlnDelete = xmlnTempLoop;
xmlnTempLoop = xmlnTempLoop.NextSibling;
xmldSettings["fsxget"]["settings"]["options"]["fsx"]["user-path-prediction"].RemoveChild(xmlnDelete);
}
for (int n = 0; n < listBoxPathPrediction.Items.Count; n++)
{
XmlNode xmlnTemp = xmldSettings.CreateElement("prediction-point");
XmlAttribute xmlaTemp = xmldSettings.CreateAttribute("Time");
xmlaTemp.Value = ((ListBoxPredictionTimesItem)listBoxPathPrediction.Items[n]).dTime.ToString();
xmlnTemp.Attributes.Append(xmlaTemp);
xmldSettings["fsxget"]["settings"]["options"]["fsx"]["user-path-prediction"].AppendChild(xmlnTemp);
}
xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-aircrafts"].Attributes["Interval"].Value = numericUpDownQueryAIAircraftsInterval.Value.ToString();
xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-aircrafts"].Attributes["Range"].Value = numericUpDownQueryAIAircraftsRadius.Value.ToString();
xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-aircrafts"].Attributes["Enabled"].Value = checkBoxQueryAIAircrafts.Checked ? "1" : "0";
xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-aircrafts"].Attributes["Prediction"].Value = checkBoxAIAircraftsPredict.Checked ? "1" : "0";
xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-aircrafts"].Attributes["PredictionPoints"].Value = checkBoxAIAircraftsPredictPoints.Checked ? "1" : "0";
xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-helicopters"].Attributes["Interval"].Value = numericUpDownQueryAIHelicoptersInterval.Value.ToString();
xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-helicopters"].Attributes["Range"].Value = numericUpDownQueryAIHelicoptersRadius.Value.ToString();
xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-helicopters"].Attributes["Enabled"].Value = checkBoxQueryAIHelicopters.Checked ? "1" : "0";
xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-helicopters"].Attributes["Prediction"].Value = checkBoxAIHelicoptersPredict.Checked ? "1" : "0";
xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-helicopters"].Attributes["PredictionPoints"].Value = checkBoxAIHelicoptersPredictPoints.Checked ? "1" : "0";
xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-boats"].Attributes["Interval"].Value = numericUpDownQueryAIBoatsInterval.Value.ToString();
xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-boats"].Attributes["Range"].Value = numericUpDownQueryAIBoatsRadius.Value.ToString();
xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-boats"].Attributes["Enabled"].Value = checkBoxQueryAIBoats.Checked ? "1" : "0";
xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-boats"].Attributes["Prediction"].Value = checkBoxAIBoatsPredict.Checked ? "1" : "0";
xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-boats"].Attributes["PredictionPoints"].Value = checkBoxAIBoatsPredictPoints.Checked ? "1" : "0";
xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-ground-units"].Attributes["Interval"].Value = numericUpDownQueryAIGroudUnitsInterval.Value.ToString();
xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-ground-units"].Attributes["Range"].Value = numericUpDownQueryAIGroudUnitsRadius.Value.ToString();
xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-ground-units"].Attributes["Enabled"].Value = checkBoxQueryAIGroudUnits.Checked ? "1" : "0";
xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-ground-units"].Attributes["Prediction"].Value = checkBoxAIGroundPredict.Checked ? "1" : "0";
xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-ground-units"].Attributes["PredictionPoints"].Value = checkBoxAIGroundPredictPoints.Checked ? "1" : "0";
xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"].Attributes["Enabled"].Value = checkBoxQueryAIObjects.Checked ? "1" : "0";
xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["user-aircraft"].Attributes["Interval"].Value = numericUpDownRefreshUserAircraft.Value.ToString();
xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["user-path"].Attributes["Interval"].Value = numericUpDownRefreshUserPath.Value.ToString();
xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["user-path-prediction"].Attributes["Interval"].Value = numericUpDownRefreshUserPrediction.Value.ToString();
xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["ai-aircrafts"].Attributes["Interval"].Value = numericUpDownRefreshAIAircrafts.Value.ToString();
xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["ai-helicopters"].Attributes["Interval"].Value = numericUpDownRefreshAIHelicopter.Value.ToString();
xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["ai-boats"].Attributes["Interval"].Value = numericUpDownRefreshAIBoats.Value.ToString();
xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["ai-ground-units"].Attributes["Interval"].Value = numericUpDownRefreshAIGroundUnits.Value.ToString();
xmldSettings["fsxget"]["settings"]["options"]["ge"]["server-settings"]["port"].Attributes["Value"].Value = numericUpDownServerPort.Value.ToString();
if (radioButtonAccessRemote.Checked)
xmldSettings["fsxget"]["settings"]["options"]["ge"]["server-settings"]["access-level"].Attributes["Value"].Value = "1";
else
xmldSettings["fsxget"]["settings"]["options"]["ge"]["server-settings"]["access-level"].Attributes["Value"].Value = "0";
xmldSettings["fsxget"]["settings"]["options"]["fsx"]["connection"].Attributes["Local"].Value = radioButton7.Checked ? "True" : "False";
xmldSettings["fsxget"]["settings"]["options"]["fsx"]["connection"].Attributes["Protocol"].Value = comboBox1.SelectedItem.ToString();
xmldSettings["fsxget"]["settings"]["options"]["fsx"]["connection"].Attributes["Host"].Value = textBox1.Text;
xmldSettings["fsxget"]["settings"]["options"]["fsx"]["connection"].Attributes["Port"].Value = textBox3.Text;
xmldSettings["fsxget"]["settings"]["options"]["ge"]["units"].InnerXml = comboBox2.SelectedIndex.ToString();
//xmldSettings["fsxget"]["settings"]["options"]["flightplans"].Attributes["Enabled"].Value = checkBoxLoadFlightPlans.Checked ? "1" : "0";
}
//private void LoadFlightPlans()
//{
// bool bError = false;
// FlightPlan fpTemp;
// XmlDocument xmldTemp = new XmlDocument();
// try
// {
// int iCount = 0;
// fpTemp.szName = "";
// fpTemp.uiID = 0;
// fpTemp.xmldPlan = null;
// for (XmlNode xmlnTemp = xmldSettings["fsxget"]["settings"]["options"]["flightplans"].FirstChild; xmlnTemp != null; xmlnTemp = xmlnTemp.NextSibling)
// {
// try
// {
// if (xmlnTemp.Attributes["Show"].Value == "0")
// continue;
// XmlReader xmlrTemp = new XmlTextReader(xmlnTemp.Attributes["File"].Value);
// fpTemp.uiID = iCount;
// fpTemp.xmldPlan = new XmlDocument();
// fpTemp.xmldPlan.Load(xmlrTemp);
// xmlrTemp.Close();
// xmlrTemp = null;
// }
// catch
// {
// bError = true;
// continue;
// }
// lock (lockFlightPlanList)
// {
// listFlightPlans.Add(fpTemp);
// }
// iCount++;
// }
// }
// catch
// {
// MessageBox.Show("Could not read flight plan list from settings file! No flight plans will be loaded.", Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
// }
// if (bError)
// MessageBox.Show("There were errors loading some of the flight plans! These flight plans will not be shown.\n\nThis problem might be due to incorrect or no longer existing flight plan files.\nPlease remove them from the flight plan list in the options dialog.", Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
//}
#endregion
#region Assembly Attribute Accessors
public string AssemblyTitle
{
get
{
// Get all Title attributes on this assembly
object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyTitleAttribute), false);
// If there is at least one Title attribute
if (attributes.Length > 0)
{
// Select the first one
AssemblyTitleAttribute titleAttribute = (AssemblyTitleAttribute)attributes[0];
// If it is not an empty string, return it
if (titleAttribute.Title != "")
return titleAttribute.Title;
}
// If there was no Title attribute, or if the Title attribute was the empty string, return the .exe name
return System.IO.Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().CodeBase);
}
}
public string AssemblyVersion
{
get
{
return Assembly.GetExecutingAssembly().GetName().Version.ToString();
}
}
public string AssemblyDescription
{
get
{
// Get all Description attributes on this assembly
object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyDescriptionAttribute), false);
// If there aren't any Description attributes, return an empty string
if (attributes.Length == 0)
return "";
// If there is a Description attribute, return its value
return ((AssemblyDescriptionAttribute)attributes[0]).Description;
}
}
public string AssemblyProduct
{
get
{
// Get all Product attributes on this assembly
object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyProductAttribute), false);
// If there aren't any Product attributes, return an empty string
if (attributes.Length == 0)
return "";
// If there is a Product attribute, return its value
return ((AssemblyProductAttribute)attributes[0]).Product;
}
}
public string AssemblyCopyright
{
get
{
// Get all Copyright attributes on this assembly
object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false);
// If there aren't any Copyright attributes, return an empty string
if (attributes.Length == 0)
return "";
// If there is a Copyright attribute, return its value
return ((AssemblyCopyrightAttribute)attributes[0]).Copyright;
}
}
public string AssemblyCompany
{
get
{
// Get all Company attributes on this assembly
object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCompanyAttribute), false);
// If there aren't any Company attributes, return an empty string
if (attributes.Length == 0)
return "";
// If there is a Company attribute, return its value
return ((AssemblyCompanyAttribute)attributes[0]).Company;
}
}
#endregion
#region User Interface Handlers
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
bClose = true;
Close();
}
private void optionsToolStripMenuItem_Click(object sender, EventArgs e)
{
safeShowMainDialog(0);
}
private void enableTrackerToolStripMenuItem_Click(object sender, EventArgs e)
{
bool bTemp = enableTrackerToolStripMenuItem.Checked;
lock (lockChConf)
{
if (bTemp != gconfchCurrent.bEnabled)
{
gconfchCurrent.bEnabled = bTemp;
if (gconfchCurrent.bEnabled)
globalConnect();
else
globalDisconnect();
}
}
}
private void showBalloonTipsToolStripMenuItem_Click(object sender, EventArgs e)
{
lock (lockChConf)
{
gconfchCurrent.bShowBalloons = showBalloonTipsToolStripMenuItem.Checked;
}
// This call is safe as the existence of this key has been checked by calling configMirrorToForm at startup.
xmldSettings["fsxget"]["settings"]["options"]["general"]["show-balloon-tips"].Attributes["Enabled"].Value = showBalloonTipsToolStripMenuItem.Checked ? "1" : "0";
}
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
safeShowMainDialog(5);
}
private void clearUserAircraftPathToolStripMenuItem_Click(object sender, EventArgs e)
{
lock (lockKmlUserPath)
{
szKmlUserAircraftPath = "";
}
lock (lockKmlUserPrediction)
{
szKmlUserPrediction = "";
listKmlPredictionPoints.Clear();
}
lock (lockKmlPredictionPoints)
{
clearPPStructure(ref ppPos1);
clearPPStructure(ref ppPos2);
}
}
private void runMicrosoftFlightSimulatorXToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
System.Diagnostics.Process.Start(szPathFSX);
}
catch
{
MessageBox.Show("An error occured while trying to start Microsoft Flight Simulator X.", Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
private void runGoogleEarthToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
lock (lockListenerControl)
{
if (gconffixCurrent.bLoadKMLFile && bConnected)
System.Diagnostics.Process.Start(szUserAppPath + "\\pub\\fsxgetd.kml");
else
System.Diagnostics.Process.Start(szUserAppPath + "\\pub\\fsxgets.kml");
}
}
catch
{
MessageBox.Show("An error occured while trying to start Google Earth.", Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
{
if (notifyIconMain.ContextMenuStrip == null)
this.Activate();
}
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
try
{
linkLabel1.LinkVisited = true;
System.Diagnostics.Process.Start("http://www.juergentreml.de/fsxget/");
}
catch
{
MessageBox.Show("Unable to open http://www.juergentreml.de/fsxget/!");
}
}
private void checkBoxQueryAIObjects_CheckedChanged(object sender, EventArgs e)
{
checkBoxQueryAIAircrafts.Enabled = checkBoxQueryAIBoats.Enabled = checkBoxQueryAIGroudUnits.Enabled = checkBoxQueryAIHelicopters.Enabled = checkBoxQueryAIObjects.Checked;
bRestartRequired = true;
}
private void checkBoxQueryAIAircrafts_CheckedChanged(object sender, EventArgs e)
{
checkBoxQueryAIAircrafts_EnabledChanged(null, null);
bRestartRequired = true;
}
private void checkBoxQueryAIAircrafts_EnabledChanged(object sender, EventArgs e)
{
checkBoxAIAircraftsPredict.Enabled = numericUpDownQueryAIAircraftsInterval.Enabled = numericUpDownQueryAIAircraftsRadius.Enabled = (checkBoxQueryAIAircrafts.Enabled & checkBoxQueryAIAircrafts.Checked);
}
private void checkBoxQueryAIHelicopters_CheckedChanged(object sender, EventArgs e)
{
checkBoxQueryAIHelicopters_EnabledChanged(null, null);
bRestartRequired = true;
}
private void checkBoxQueryAIHelicopters_EnabledChanged(object sender, EventArgs e)
{
checkBoxAIHelicoptersPredict.Enabled = numericUpDownQueryAIHelicoptersInterval.Enabled = numericUpDownQueryAIHelicoptersRadius.Enabled = (checkBoxQueryAIHelicopters.Enabled & checkBoxQueryAIHelicopters.Checked);
}
private void checkBoxQueryAIBoats_CheckedChanged(object sender, EventArgs e)
{
checkBoxQueryAIBoats_EnabledChanged(null, null);
bRestartRequired = true;
}
private void checkBoxQueryAIBoats_EnabledChanged(object sender, EventArgs e)
{
checkBoxAIBoatsPredict.Enabled = numericUpDownQueryAIBoatsInterval.Enabled = numericUpDownQueryAIBoatsRadius.Enabled = (checkBoxQueryAIBoats.Enabled & checkBoxQueryAIBoats.Checked);
}
private void checkBoxQueryAIGroudUnits_CheckedChanged(object sender, EventArgs e)
{
checkBoxQueryAIGroudUnits_EnabledChanged(null, null);
bRestartRequired = true;
}
private void checkBoxQueryAIGroudUnits_EnabledChanged(object sender, EventArgs e)
{
checkBoxAIGroundPredict.Enabled = numericUpDownQueryAIGroudUnitsInterval.Enabled = numericUpDownQueryAIGroudUnitsRadius.Enabled = (checkBoxQueryAIGroudUnits.Enabled & checkBoxQueryAIGroudUnits.Checked);
}
private void checkQueryUserAircraft_CheckedChanged(object sender, EventArgs e)
{
numericUpDownQueryUserAircraft.Enabled = checkQueryUserAircraft.Checked;
bRestartRequired = true;
}
private void checkQueryUserPath_CheckedChanged(object sender, EventArgs e)
{
numericUpDownQueryUserPath.Enabled = checkQueryUserPath.Checked;
bRestartRequired = true;
}
private void buttonOK_Click(object sender, EventArgs e)
{
// Set startup options if necessary
if (radioButton8.Checked)
{
if (!isAutoStartActivated())
if (!AutoStartActivate())
MessageBox.Show("Couldn't change autorun value in registry!", AssemblyTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning);
if (isFsxStartActivated())
if (!FsxStartDeactivate())
MessageBox.Show("Couldn't change FSX startup options!", AssemblyTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else if (radioButton9.Checked)
{
if (!isFsxStartActivated())
if (!FsxStartActivate())
MessageBox.Show("Couldn't change FSX startup options!", AssemblyTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning);
if (isAutoStartActivated())
if (!AutoStartDeactivate())
MessageBox.Show("Couldn't change autorun value in registry!", AssemblyTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else
{
if (isFsxStartActivated())
if (!FsxStartDeactivate())
MessageBox.Show("Couldn't change FSX startup options!", AssemblyTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning);
if (isAutoStartActivated())
if (!AutoStartDeactivate())
MessageBox.Show("Couldn't change autorun value in registry!", AssemblyTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
//string szRun = (string)Registry.GetValue(szRegKeyRun, AssemblyTitle, "");
ConfigRetrieveFromForm();
showBalloonTipsToolStripMenuItem.Checked = checkShowInfoBalloons.Checked;
notifyIconMain.ContextMenuStrip = contextMenuStripNotifyIcon;
gconffixCurrent.utUnits = (UnitType)comboBox2.SelectedIndex;
if (bRestartRequired)
if (MessageBox.Show("Some of the changes you made require a restart. Do you want to restart " + Text + " now for those changes to take effect.", Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
RestartApp();
Hide();
}
private void buttonCancel_Click(object sender, EventArgs e)
{
safeHideMainDialog();
}
private void numericUpDownQueryUserAircraft_ValueChanged(object sender, EventArgs e)
{
bRestartRequired = true;
}
private void numericUpDownQueryUserPath_ValueChanged(object sender, EventArgs e)
{
bRestartRequired = true;
}
private void numericUpDownQueryAIAircraftsInterval_ValueChanged(object sender, EventArgs e)
{
bRestartRequired = true;
}
private void numericUpDownQueryAIHelicoptersInterval_ValueChanged(object sender, EventArgs e)
{
bRestartRequired = true;
}
private void numericUpDownQueryAIBoatsInterval_ValueChanged(object sender, EventArgs e)
{
bRestartRequired = true;
}
private void numericUpDownQueryAIGroudUnitsInterval_ValueChanged(object sender, EventArgs e)
{
bRestartRequired = true;
}
private void numericUpDownQueryAIAircraftsRadius_ValueChanged(object sender, EventArgs e)
{
bRestartRequired = true;
}
private void numericUpDownQueryAIHelicoptersRadius_ValueChanged(object sender, EventArgs e)
{
bRestartRequired = true;
}
private void numericUpDownQueryAIBoatsRadius_ValueChanged(object sender, EventArgs e)
{
bRestartRequired = true;
}
private void numericUpDownQueryAIGroudUnitsRadius_ValueChanged(object sender, EventArgs e)
{
bRestartRequired = true;
}
private void numericUpDownRefreshUserAircraft_ValueChanged(object sender, EventArgs e)
{
bRestartRequired = true;
}
private void numericUpDownRefreshUserPath_ValueChanged(object sender, EventArgs e)
{
bRestartRequired = true;
}
private void numericUpDownRefreshAIAircrafts_ValueChanged(object sender, EventArgs e)
{
bRestartRequired = true;
}
private void numericUpDownRefreshAIHelicopter_ValueChanged(object sender, EventArgs e)
{
bRestartRequired = true;
}
private void numericUpDownRefreshAIBoats_ValueChanged(object sender, EventArgs e)
{
bRestartRequired = true;
}
private void numericUpDownRefreshAIGroundUnits_ValueChanged(object sender, EventArgs e)
{
bRestartRequired = true;
}
private void numericUpDownServerPort_ValueChanged(object sender, EventArgs e)
{
bRestartRequired = true;
}
private void checkBoxLoadKMLFile_CheckedChanged(object sender, EventArgs e)
{
gconffixCurrent.bLoadKMLFile = checkBoxLoadKMLFile.Checked;
}
private void checkBoxUserPathPrediction_CheckedChanged(object sender, EventArgs e)
{
numericUpDownUserPathPrediction.Enabled = checkBoxUserPathPrediction.Checked;
bRestartRequired = true;
}
private void numericUpDownUserPathPrediction_ValueChanged(object sender, EventArgs e)
{
bRestartRequired = true;
}
private void numericUpDownRefreshUserPrediction_ValueChanged(object sender, EventArgs e)
{
bRestartRequired = true;
}
private void checkBoxSaveLog_CheckedChanged(object sender, EventArgs e)
{
checkBoxSubFoldersForLog.Enabled = (checkBoxSaveLog.Checked);
}
private void radioButtonAccessLocalOnly_CheckedChanged(object sender, EventArgs e)
{
bRestartRequired = true;
}
private void radioButtonAccessRemote_CheckedChanged(object sender, EventArgs e)
{
bRestartRequired = true;
}
private void checkBoxAIAircraftsPredict_CheckedChanged(object sender, EventArgs e)
{
checkBoxAIAircraftsPredict_EnabledChanged(null, null);
bRestartRequired = true;
}
private void checkBoxAIAircraftsPredict_EnabledChanged(object sender, EventArgs e)
{
checkBoxAIAircraftsPredictPoints.Enabled = (checkBoxAIAircraftsPredict.Enabled & checkBoxAIAircraftsPredict.Checked);
}
private void checkBoxAIHelicoptersPredict_CheckedChanged(object sender, EventArgs e)
{
checkBoxAIHelicoptersPredict_EnabledChanged(null, null);
bRestartRequired = true;
}
private void checkBoxAIHelicoptersPredict_EnabledChanged(object sender, EventArgs e)
{
checkBoxAIHelicoptersPredictPoints.Enabled = (checkBoxAIHelicoptersPredict.Enabled & checkBoxAIHelicoptersPredict.Checked);
}
private void checkBoxAIBoatsPredict_CheckedChanged(object sender, EventArgs e)
{
checkBoxAIBoatsPredict_EnabledChanged(null, null);
bRestartRequired = true;
}
private void checkBoxAIBoatsPredict_EnabledChanged(object sender, EventArgs e)
{
checkBoxAIBoatsPredictPoints.Enabled = (checkBoxAIBoatsPredict.Enabled & checkBoxAIBoatsPredict.Checked);
}
private void checkBoxAIGroundPredict_CheckedChanged(object sender, EventArgs e)
{
checkBoxAIGroundPredict_EnabledChanged(null, null);
bRestartRequired = true;
}
private void checkBoxAIGroundPredict_EnabledChanged(object sender, EventArgs e)
{
checkBoxAIGroundPredictPoints.Enabled = (checkBoxAIGroundPredict.Enabled & checkBoxAIGroundPredict.Checked);
}
private void checkBoxAIAircraftsPredictPoints_CheckedChanged(object sender, EventArgs e)
{
bRestartRequired = true;
}
private void checkBoxAIHelicoptersPredictPoints_CheckedChanged(object sender, EventArgs e)
{
bRestartRequired = true;
}
private void checkBoxAIBoatsPredictPoints_CheckedChanged(object sender, EventArgs e)
{
bRestartRequired = true;
}
private void checkBoxAIGroundPredictPoints_CheckedChanged(object sender, EventArgs e)
{
bRestartRequired = true;
}
private void createGoogleEarthKMLFileToolStripMenuItem_DropDownIPClick(object sender, EventArgs e)
{
String szTemp = sender.ToString();
if (szTemp.Length < 7)
return;
szTemp = szTemp.Substring(7);
String szKMLFile = "";
if (CompileKMLStartUpFileDynamic(szTemp, ref szKMLFile))
{
safeShowMainDialog(0);
if (saveFileDialogKMLFile.ShowDialog() == DialogResult.OK)
{
try
{
File.WriteAllText(saveFileDialogKMLFile.FileName, szKMLFile);
}
catch
{
MessageBox.Show("Could not save KML file!", Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
safeHideMainDialog();
}
}
private void contextMenuStripNotifyIcon_Opening(object sender, CancelEventArgs e)
{
createGoogleEarthKMLFileToolStripMenuItem.DropDown.Items.Clear();
lock (lockIPAddressList)
{
bool bAddressFound = false;
if (ipalLocal1 != null)
{
foreach (IPAddress ipaTemp in ipalLocal1)
{
bAddressFound = true;
createGoogleEarthKMLFileToolStripMenuItem.DropDown.Items.Add("For IP " + ipaTemp.ToString(), null, createGoogleEarthKMLFileToolStripMenuItem_DropDownIPClick);
}
}
if (ipalLocal2 != null)
{
foreach (IPAddress ipaTemp in ipalLocal2)
{
bAddressFound = true;
createGoogleEarthKMLFileToolStripMenuItem.DropDown.Items.Add("For IP " + ipaTemp.ToString(), null, createGoogleEarthKMLFileToolStripMenuItem_DropDownIPClick);
}
}
if (!bAddressFound)
createGoogleEarthKMLFileToolStripMenuItem.Enabled = false;
else
createGoogleEarthKMLFileToolStripMenuItem.Enabled = true;
}
}
private void button3_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Are you sure you want to remove the selected items?", Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
//foreach (ListViewItem lviTemp in listViewFlightPlans.SelectedItems)
//{
// listViewFlightPlans.Items.Remove(lviTemp);
//}
}
}
private void radioButton7_CheckedChanged(object sender, EventArgs e)
{
comboBox1.Enabled = textBox1.Enabled = textBox3.Enabled = !radioButton7.Checked;
bRestartRequired = true;
}
private void radioButton6_CheckedChanged(object sender, EventArgs e)
{
comboBox1.Enabled = textBox1.Enabled = textBox3.Enabled = radioButton6.Checked;
bRestartRequired = true;
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
bRestartRequired = true;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
bRestartRequired = true;
}
private void textBox3_TextChanged(object sender, EventArgs e)
{
bRestartRequired = true;
}
private void radioButton10_CheckedChanged(object sender, EventArgs e)
{
if (radioButton10.Checked)
radioButton8.Checked = radioButton9.Checked = checkBox1.Enabled = false;
}
private void radioButton9_CheckedChanged(object sender, EventArgs e)
{
checkBox1.Enabled = radioButton9.Checked;
}
private void radioButton8_CheckedChanged(object sender, EventArgs e)
{
if (radioButton10.Checked)
radioButton8.Checked = radioButton9.Checked = checkBox1.Enabled = false;
}
private void checkEnableOnStartup_CheckedChanged(object sender, EventArgs e)
{
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
gconffixCurrent.bExitOnFsxExit = checkBox1.Checked;
}
private void checkShowInfoBalloons_CheckedChanged(object sender, EventArgs e)
{
}
private void listBoxPathPrediction_SelectedIndexChanged(object sender, EventArgs e)
{
UpdateButtonStates();
}
private void button2_Click(object sender, EventArgs e)
{
if (listBoxPathPrediction.SelectedItems.Count == 1)
{
int iIndex = listBoxPathPrediction.SelectedIndex;
listBoxPathPrediction.Items.RemoveAt(iIndex);
if (listBoxPathPrediction.SelectedItems.Count == 0)
{
if (listBoxPathPrediction.Items.Count > iIndex)
listBoxPathPrediction.SelectedIndex = iIndex;
else if (listBoxPathPrediction.Items.Count > 0)
listBoxPathPrediction.SelectedIndex = listBoxPathPrediction.Items.Count - 1;
}
bRestartRequired = true;
}
}
private void button1_Click(object sender, EventArgs e)
{
int iSeconds;
if (frmAdd.ShowDialog(out iSeconds) == DialogResult.Cancel)
return;
ListBoxPredictionTimesItem lbptiTemp = new ListBoxPredictionTimesItem();
lbptiTemp.dTime = iSeconds;
bool bInserted = false;
for (int n = 0; n < listBoxPathPrediction.Items.Count; n++)
{
if (((ListBoxPredictionTimesItem)listBoxPathPrediction.Items[n]).dTime > lbptiTemp.dTime)
{
listBoxPathPrediction.Items.Insert(n, lbptiTemp);
bInserted = true;
break;
}
}
if (!bInserted)
listBoxPathPrediction.Items.Add(lbptiTemp);
bRestartRequired = true;
}
#endregion
}
}
| jtreml/fsxget | FSX Google Earth Tracker/Form1.cs | C# | gpl-2.0 | 158,843 |
<?php
/**
* Created by PhpStorm.
* User: Anh Tuan
* Date: 7/24/14
* Time: 3:45 PM
*/
global $theme_options_data;
$logo_id = $theme_options_data['thim_logo'];
// The value may be a URL to the image (for the default parameter)
// or an attachment ID to the selected image.
$logo_src = $logo_id; // For the default value
if ( is_numeric( $logo_id ) ) {
$imageAttachment = wp_get_attachment_image_src( $logo_id, 'full' );
$logo_src = $imageAttachment[0];
}
$sticky_logo_id = $theme_options_data['thim_sticky_logo'];
// The value may be a URL to the image (for the default parameter)
// or an attachment ID to the selected image.
$sticky_logo_src = $sticky_logo_id; // For the default value
if ( is_numeric( $sticky_logo_id ) ) {
$imageAttachment = wp_get_attachment_image_src( $sticky_logo_id, 'full' );
$sticky_logo_src = $imageAttachment[0];
}
?>
<?php
if ( isset( $theme_options_data['thim_header_position'] ) && $theme_options_data['thim_header_position'] == 'header_after_slider' && is_active_sidebar( 'banner_header' ) ) {
dynamic_sidebar( 'banner_header' );
}
?>
<header id="masthead" class="site-header <?php if ( isset( $theme_options_data['thim_header_position'] ) && $theme_options_data['thim_header_position'] <> '' ) {
echo $theme_options_data['thim_header_position'];
}
if ( isset( $theme_options_data['thim_config_height_sticky'] ) && $theme_options_data['thim_config_height_sticky'] <> '' ) {
echo ' ' . $theme_options_data['thim_config_height_sticky'];
}
if ( isset( $theme_options_data['thim_config_att_sticky'] ) && $theme_options_data['thim_config_att_sticky'] <> '' ) {
echo ' ' . $theme_options_data['thim_config_att_sticky'];
} ?>" role="banner">
<?php if ( isset( $theme_options_data['thim_header_layout'] ) && $theme_options_data['thim_header_layout'] == 'boxed' ) {
echo "<div class=\"container header_boxed\">";
}
?>
<?php
$width_topsidebar_left = 5;
if ( isset( $theme_options_data['width_left_top_sidebar'] ) ) {
$width_topsidebar_left = $theme_options_data['width_left_top_sidebar'];
}
$width_topsidebar_right = 12 - $width_topsidebar_left;
if ( isset( $theme_options_data['thim_topbar_show'] ) && $theme_options_data['thim_topbar_show'] == '1' ) {
?>
<?php if ( ( is_active_sidebar( 'top_right_sidebar' ) ) || ( is_active_sidebar( 'top_left_sidebar' ) ) ) : ?>
<div class="top-header">
<?php if ( isset( $theme_options_data['thim_header_layout'] ) && $theme_options_data['thim_header_layout'] == 'wide' ) {
echo "<div class=\"container\"><div class=\"row\">";
}
?>
<?php if ( is_active_sidebar( 'top_left_sidebar' ) ) : ?>
<div class="col-sm-<?php echo $width_topsidebar_left; ?> top_left">
<ul class="top-left-menu">
<?php dynamic_sidebar( 'top_left_sidebar' ); ?>
</ul>
</div><!-- col-sm-6 -->
<?php endif; ?>
<?php if ( is_active_sidebar( 'top_right_sidebar' ) ) : ?>
<div class="col-sm-<?php echo $width_topsidebar_right; ?> top_right">
<ul class="top-right-menu">
<?php dynamic_sidebar( 'top_right_sidebar' ); ?>
</ul>
</div><!-- col-sm-6 -->
<?php endif; ?>
<?php if ( isset( $theme_options_data['thim_header_layout'] ) && $theme_options_data['thim_header_layout'] == 'wide' ) {
echo "</div></div>";
}
?>
</div><!--End/div.top-->
<?php
endif;
}
?>
<?php
$width_logo = 3;
if ( isset( $theme_options_data['thim_column_logo'] ) ) {
$width_logo = $theme_options_data['thim_column_logo'];
}
$width_menu = 12 - $width_logo;
?>
<div class="wapper_logo">
<div class="container tm-table">
<?php if ( is_active_sidebar( 'header_left' ) ) : ?>
<div class="table_cell">
<div class="header_left">
<?php dynamic_sidebar( 'header_left' ); ?>
</div>
</div><!-- col-sm-6 -->
<?php endif; ?>
<div class="menu-mobile-effect navbar-toggle" data-effect="mobile-effect">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</div>
<div class="table_cell table_cell-center sm-logo">
<?php if ( is_single() ) {
echo '<h2 class="header_logo">';
} else {
echo '<h1 class="header_logo">';
} ?>
<a href="<?php echo esc_url( home_url( '/' ) ); ?>" title="<?php echo esc_attr( get_bloginfo( 'name', 'display' ) ); ?> - <?php bloginfo( 'description' ); ?>" rel="home">
<?php
if ( isset( $logo_src ) && $logo_src ) {
$aloxo_logo_size = @getimagesize( $logo_src );
$width = $aloxo_logo_size[0];
$height = $aloxo_logo_size[1];
$site_title = esc_attr( get_bloginfo( 'name', 'display' ) );
echo '<img src="' . $logo_src . '" alt="' . $site_title . '" width="' . $width . '" height="' . $height . '" />';
} else {
bloginfo( 'name' );
} ?>
</a>
<?php if ( is_single() ) {
echo '</h2>';
} else {
echo '</h1>';
} ?>
</div>
<?php if ( is_active_sidebar( 'header_right' ) ) : ?>
<div class="table_cell right_header">
<div class="header_right">
<?php dynamic_sidebar( 'header_right' ); ?>
</div>
</div><!-- col-sm-6 -->
<?php endif; ?>
<div id="header-search-form-input" class="main-header-search-form-input">
<form role="search" method="get" action="<?php echo get_site_url(); ?>">
<input type="text" value="" name="s" id="s" placeholder="<?php echo __( 'Search the site or press ESC to cancel.', 'aloxo' ); ?>" class="form-control ob-search-input" autocomplete="off" />
<span class="header-search-close"><i class="fa fa-times"></i></span>
</form>
<ul class="ob_list_search">
</ul>
</div>
</div>
<!--end container tm-table-->
</div>
<!--end wapper-logo-->
<div class="navigation affix-top" <?php if ( isset( $theme_options_data['thim_header_sticky'] ) && $theme_options_data['thim_header_sticky'] == 1 ) {
echo 'data-spy="affix" data-offset-top="' . $theme_options_data['thim_header_height_sticky'] . '" ';
} ?>>
<!-- <div class="main-menu"> -->
<div class="container tm-table">
<div class="col-sm-<?php echo $width_logo ?> table_cell sm-logo-affix">
<?php
echo '<h2 class="header_logo">';
?>
<a href="<?php echo esc_url( home_url( '/' ) ); ?>" title="<?php echo esc_attr( get_bloginfo( 'name', 'display' ) ); ?> - <?php bloginfo( 'description' ); ?>" rel="home">
<?php
if ( isset( $sticky_logo_src ) ) {
if ( $sticky_logo_src ) {
$aloxo_logo_size = @getimagesize( $sticky_logo_src );
$width = $aloxo_logo_size[0];
$height = $aloxo_logo_size[1];
$site_title = esc_attr( get_bloginfo( 'name', 'display' ) );
echo '<img src="' . $sticky_logo_src . '" alt="' . $site_title . '" width="' . $width . '" height="' . $height . '" />';
} else {
$aloxo_logo_size = @getimagesize( $logo_src );
$width = $aloxo_logo_size[0];
$height = $aloxo_logo_size[1];
$site_title = esc_attr( get_bloginfo( 'name', 'display' ) );
echo '<img src="' . $logo_src . '" alt="' . $site_title . '" width="' . $width . '" height="' . $height . '" />';
}
}
?>
</a>
<?php
echo '</h2>';
?>
</div>
<nav class="col-sm-<?php echo $width_menu ?> table_cell" role="navigation">
<?php get_template_part( 'inc/header/main_menu' ); ?>
</nav>
</div>
<!-- </div> -->
</div>
<?php if ( isset( $theme_options_data['thim_header_layout'] ) && $theme_options_data['thim_header_layout'] == 'boxed' ) {
echo "</div>";
}
?>
</header>
| yogaValdlabs/shopingchart | wp-content/themes/aloxo/inc/header/header_3.php | PHP | gpl-2.0 | 7,564 |
# attack_csrf.rb
# model of a cross-site request forgery attack
require 'sdsl/view.rb'
u = mod :User do
stores set(:intentsA, :URI)
invokes(:visitA,
# user only types dest address that he/she intends to visit
:when => [:intentsA.contains(o.destA)])
end
goodServer = mod :TrustedServer do
stores :cookies, :Op, :Cookie
stores :addrA, :Hostname
stores set(:protected, :Op)
creates :DOM
creates :Cookie
exports(:httpReqA,
:args => [item(:cookie, :Cookie),
item(:addrA, :URI)],
# if op is protected, only accept when it provides a valid cookie
:when => [implies(:protected.contains(o),
o.cookie.eq(:cookies[o]))])
invokes(:httpRespA,
:when => [triggeredBy :httpReqA])
end
badServer = mod :MaliciousServer do
stores :addrA, :Hostname
creates :DOM
exports(:httpReqA2,
:args => [item(:cookie, :Cookie),
item(:addrA, :URI)])
invokes(:httpRespA,
:when => [triggeredBy :httpReqA2])
end
goodClient = mod :Client do
stores :cookies, :URI, :Cookie
exports(:visitA,
:args => [item(:destA, :URI)])
exports(:httpRespA,
:args => [item(:dom, :DOM),
item(:addrA, :URI)])
invokes([:httpReqA, :httpReqA2],
:when => [
# req always contains any associated cookie
implies(some(:cookies[o.addrA]),
o.cookie.eq(:cookies[o.addrA])),
disj(
# sends a http request only when
# the user initiates a connection
conj(triggeredBy(:visitA),
o.addrA.eq(trig.destA)),
# or in response to a src tag
conjs([triggeredBy(:httpRespA),
trig.dom.tags.src.contains(o.addrA)]
))
])
end
dom = datatype :DOM do
field set(:tags, :HTMLTag)
extends :Payload
end
addr = datatype :Addr do end
uri = datatype :URI do
field item(:addr, :Addr)
field set(:vals, :Payload)
end
imgTag = datatype :ImgTag do
field item(:src, :URI)
extends :HTMLTag
end
tag = datatype :HTMLTag do setAbstract end
cookie = datatype :Cookie do extends :Payload end
otherPayload = datatype :OtherPayload do extends :Payload end
payload = datatype :Payload do setAbstract end
VIEW_CSRF = view :AttackCSRF do
modules u, goodServer, badServer, goodClient
trusted goodServer, goodClient, u
data uri, :Hostname, cookie, otherPayload, payload, dom, tag, imgTag, addr
end
drawView VIEW_CSRF, "csrf.dot"
dumpAlloy VIEW_CSRF, "csrf.als"
# puts goodServer
# puts badServer
# puts goodClient
# writeDot mods
| kyessenov/poirot | lib/sdsl/case_studies/attack_csrf.rb | Ruby | gpl-2.0 | 2,814 |
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Log
* @subpackage Writer
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Syslog.php 23574 2010-12-23 22:58:44Z ramon $
*/
/** Zend_Log */
require_once 'Zend/Log.php';
/** Zend_Log_Writer_Abstract */
require_once 'Zend/Log/Writer/Abstract.php';
/**
* Writes log messages to syslog
*
* @category Zend
* @package Zend_Log
* @subpackage Writer
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Log_Writer_Syslog extends Zend_Log_Writer_Abstract
{
/**
* Maps Zend_Log priorities to PHP's syslog priorities
*
* @var array
*/
protected $_priorities = array(
Zend_Log::EMERG => LOG_EMERG,
Zend_Log::ALERT => LOG_ALERT,
Zend_Log::CRIT => LOG_CRIT,
Zend_Log::ERR => LOG_ERR,
Zend_Log::WARN => LOG_WARNING,
Zend_Log::NOTICE => LOG_NOTICE,
Zend_Log::INFO => LOG_INFO,
Zend_Log::DEBUG => LOG_DEBUG,
);
/**
* The default log priority - for unmapped custom priorities
*
* @var string
*/
protected $_defaultPriority = LOG_NOTICE;
/**
* Last application name set by a syslog-writer instance
*
* @var string
*/
protected static $_lastApplication;
/**
* Last facility name set by a syslog-writer instance
*
* @var string
*/
protected static $_lastFacility;
/**
* Application name used by this syslog-writer instance
*
* @var string
*/
protected $_application = 'Zend_Log';
/**
* Facility used by this syslog-writer instance
*
* @var int
*/
protected $_facility = LOG_USER;
/**
* Types of program available to logging of message
*
* @var array
*/
protected $_validFacilities = array();
/**
* Class constructor
*
* @param array $params Array of options; may include "application" and "facility" keys
* @return void
*/
public function __construct(array $params = array())
{
if (isset($params['application'])) {
$this->_application = $params['application'];
}
$runInitializeSyslog = true;
if (isset($params['facility'])) {
$this->setFacility($params['facility']);
$runInitializeSyslog = false;
}
if ($runInitializeSyslog) {
$this->_initializeSyslog();
}
}
/**
* Create a new instance of Zend_Log_Writer_Syslog
*
* @param array|Zend_Config $config
* @return Zend_Log_Writer_Syslog
*/
static public function factory($config)
{
return new self(self::_parseConfig($config));
}
/**
* Initialize values facilities
*
* @return void
*/
protected function _initializeValidFacilities()
{
$constants = array(
'LOG_AUTH',
'LOG_AUTHPRIV',
'LOG_CRON',
'LOG_DAEMON',
'LOG_KERN',
'LOG_LOCAL0',
'LOG_LOCAL1',
'LOG_LOCAL2',
'LOG_LOCAL3',
'LOG_LOCAL4',
'LOG_LOCAL5',
'LOG_LOCAL6',
'LOG_LOCAL7',
'LOG_LPR',
'LOG_MAIL',
'LOG_NEWS',
'LOG_SYSLOG',
'LOG_USER',
'LOG_UUCP'
);
foreach ($constants as $constant) {
if (defined($constant)) {
$this->_validFacilities[] = constant($constant);
}
}
}
/**
* Initialize syslog / set application name and facility
*
* @return void
*/
protected function _initializeSyslog()
{
self::$_lastApplication = $this->_application;
self::$_lastFacility = $this->_facility;
openlog($this->_application, LOG_PID, $this->_facility);
}
/**
* Set syslog facility
*
* @param int $facility Syslog facility
* @return Zend_Log_Writer_Syslog
* @throws Zend_Log_Exception for invalid log facility
*/
public function setFacility($facility)
{
if ($this->_facility === $facility) {
return $this;
}
if (!count($this->_validFacilities)) {
$this->_initializeValidFacilities();
}
if (!in_array($facility, $this->_validFacilities)) {
require_once 'Zend/Log/Exception.php';
throw new Zend_Log_Exception('Invalid log facility provided; please see http://php.net/openlog for a list of valid facility values');
}
if ('WIN' == strtoupper(substr(PHP_OS, 0, 3))
&& ($facility !== LOG_USER)
) {
require_once 'Zend/Log/Exception.php';
throw new Zend_Log_Exception('Only LOG_USER is a valid log facility on Windows');
}
$this->_facility = $facility;
$this->_initializeSyslog();
return $this;
}
/**
* Set application name
*
* @param string $application Application name
* @return Zend_Log_Writer_Syslog
*/
public function setApplicationName($application)
{
if ($this->_application === $application) {
return $this;
}
$this->_application = $application;
$this->_initializeSyslog();
return $this;
}
/**
* Close syslog.
*
* @return void
*/
public function shutdown()
{
closelog();
}
/**
* Write a message to syslog.
*
* @param array $event event data
* @return void
*/
protected function _write($event)
{
if (array_key_exists($event['priority'], $this->_priorities)) {
$priority = $this->_priorities[$event['priority']];
} else {
$priority = $this->_defaultPriority;
}
if ($this->_application !== self::$_lastApplication
|| $this->_facility !== self::$_lastFacility)
{
$this->_initializeSyslog();
}
$message = $event['message'];
if ($this->_formatter instanceof Zend_Log_Formatter_Interface) {
$message = $this->_formatter->format($event);
}
syslog($priority, $message);
}
}
| rakesh-sankar/PHP-Framework-Benchmark | zend-1.11.2/library/Zend/Log/Writer/Syslog.php | PHP | gpl-2.0 | 6,950 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using SirenOfShame.Lib;
using SirenOfShame.Lib.Watcher;
using log4net;
namespace GoServices
{
public class GoBuildStatus : BuildStatus
{
private readonly IEnumerable<XElement> _pipeline;
private static readonly ILog _log = MyLogManager.GetLogger(typeof(GoBuildStatus));
public GoBuildStatus(IEnumerable<XElement> pipeline)
{
_pipeline = pipeline;
Name = GetPipelineName();
BuildDefinitionId = GetPipelineName();
BuildStatusEnum = GetBuildStatus();
BuildId = GetBuildId();
LocalStartTime = GetLocalStartTime();
Url = GetUrl();
if (BuildStatusEnum == BuildStatusEnum.Broken)
{
RequestedBy = GetRequestedBy();
}
}
private string GetPipelineName()
{
return _pipeline.First().Attribute("name").Value.Split(' ').First();
}
private BuildStatusEnum GetBuildStatus()
{
if (_pipeline.Select(x => x.Attribute("activity").Value).Any(a => a == "Building"))
{
return BuildStatusEnum.InProgress;
}
if (_pipeline.Select(x => x.Attribute("activity").Value).Any(a => a == "Sleeping") &&
_pipeline.Select(x => x.Attribute("lastBuildStatus").Value).All(s => s == "Success"))
{
return BuildStatusEnum.Working;
}
if (_pipeline.Select(x => x.Attribute("activity").Value).Any(a => a == "Sleeping") &&
_pipeline.Select(x => x.Attribute("lastBuildStatus").Value).Any(s => s == "Failure"))
{
return BuildStatusEnum.Broken;
}
return BuildStatusEnum.Unknown;
}
private string GetBuildId()
{
return _pipeline.First().Attribute("lastBuildLabel").Value;
}
private DateTime GetLocalStartTime()
{
return Convert.ToDateTime(_pipeline.First().Attribute("lastBuildTime").Value);
}
private string GetUrl()
{
return _pipeline.First().Attribute("webUrl").Value;
}
private string GetRequestedBy()
{
var failedStage = _pipeline.FirstOrDefault(x => x.Element("messages") != null &&
x.Element("messages").Element("message") != null);
try
{
return failedStage != null
? failedStage.Element("messages").Element("message").Attribute("text").Value
: string.Empty;
}
catch (Exception)
{
return string.Empty;
}
}
}
}
| MikeMangialardi/SirenOfShame-WithGoPlugin | GoServices/GoBuildStatus.cs | C# | gpl-2.0 | 2,921 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package ch.quantasy.iot.mqtt.tinkerforge.device.deviceHandler.IMU.status;
import ch.quantasy.iot.mqtt.base.AHandler;
import ch.quantasy.iot.mqtt.base.message.AStatus;
import ch.quantasy.iot.mqtt.tinkerforge.device.deviceHandler.IMU.IMU;
import org.eclipse.paho.client.mqttv3.MqttAsyncClient;
/**
*
* @author Reto E. Koenig <reto.koenig@bfh.ch>
*/
public class AllDataPeriodStatus extends AStatus {
public AllDataPeriodStatus(AHandler deviceHandler, String statusTopic, MqttAsyncClient mqttClient) {
super(deviceHandler, statusTopic, "allData", mqttClient);
super.addDescription(IMU.PERIOD, Long.class, "JSON", "0", "..", "" + Long.MAX_VALUE);
}
}
| knr1/ch.bfh.mobicomp | ch.quantasy.iot.gateway.tinkerforge/src/main/java/ch/quantasy/iot/mqtt/tinkerforge/device/deviceHandler/IMU/status/AllDataPeriodStatus.java | Java | gpl-2.0 | 848 |
package com.karniyarik.common.util;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import org.apache.commons.lang.StringUtils;
import com.karniyarik.common.KarniyarikRepository;
import com.karniyarik.common.config.system.DeploymentConfig;
import com.karniyarik.common.config.system.WebConfig;
public class IndexMergeUtil
{
public static final String SITE_NAME_PARAMETER = "s";
public static final void callMergeSiteIndex(String siteName) throws Throwable
{
callMergeSiteIndex(siteName, false);
}
public static final void callMergeSiteIndex(String siteName, boolean reduceBoost) throws Throwable
{
WebConfig webConfig = KarniyarikRepository.getInstance().getConfig().getConfigurationBundle().getWebConfig();
DeploymentConfig config = KarniyarikRepository.getInstance().getConfig().getConfigurationBundle().getDeploymentConfig();
//String url = "http://www.karniyarik.com";
String url = config.getMasterWebUrl();
URL servletURL = null;
URLConnection connection = null;
InputStream is = null;
String tail = webConfig.getMergeIndexServlet() + "?" + SITE_NAME_PARAMETER + "=" + siteName;
if (StringUtils.isNotBlank(url))
{
if(!tail.startsWith("/") && !url.endsWith("/"))
{
url += "/";
}
url += tail;
if(reduceBoost)
{
url += "&rb=true";
}
servletURL = new URL(url);
connection = servletURL.openConnection();
connection.connect();
is = connection.getInputStream();
is.close();
}
servletURL = null;
connection = null;
is = null;
tail = null;
}
public static void callReduceSiteIndex(String siteName) throws Throwable{
callMergeSiteIndex(siteName, true);
}
public static void main(String[] args) throws Throwable{
String[] sites = new String[]{
"hataystore",
"damakzevki", "robertopirlanta", "bebekken", "elektrikmalzemem", "starsexshop", "altinsarrafi", "budatoys", "taffybaby", "medikalcim", "beyazdepo", "tasarimbookshop", "boviza",
"evdepo", "bonnyfood", "beyazkutu", "koctas", "bizimmarket", "narbebe", "gonayakkabi", "tgrtpazarlama", "pasabahce", "vatanbilgisayar", "egerate-store", "dr", "hipernex", "ensarshop",
"yesil", "dealextreme", "petsrus", "otoyedekparcaburada", "elektrikdeposu", "alisveris", "radikalteknoloji", "ekopasaj", "strawberrynet", "yenisayfa", "adresimegelsin",
"juenpetmarket", "nadirkitap"};
for(String site: sites)
{
System.out.println(site);
callMergeSiteIndex(site);
Thread.sleep(10000);
}
}
}
| Karniyarik/karniyarik | karniyarik-common/src/main/java/com/karniyarik/common/util/IndexMergeUtil.java | Java | gpl-2.0 | 2,586 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using Newtonsoft.Json;
namespace lit
{
class HttpTransferModule : ITransferModule
{
public const string ConnectionRequest = "subscribe";
public const string StatusRequest = "getstatus";
public const string StatusReport = "status";
private List<string> connections = new List<string>();
private IDictionary<string, string> myRecord;
private readonly HttpListener myListener = new HttpListener();
public List<string> Prefixes { get; set; }
public HttpTransferModule(IConfiguration configuration)
{
if (!HttpListener.IsSupported)
{
throw new NotSupportedException("Needs Windows XP SP2, Server 2003 or later.");
}
// URI prefixes are required, for example
// "http://localhost:8080/index/".
if (string.IsNullOrEmpty(configuration.Transfer.Prefix))
{
throw new ArgumentException("Prefix");
}
Console.WriteLine("using prefix {0}", configuration.Transfer.Prefix);
myListener.Prefixes.Add(configuration.Transfer.Prefix);
}
public void Start()
{
myListener.Start();
ThreadPool.QueueUserWorkItem((o) =>
{
Console.WriteLine("Webserver is running...");
try
{
while (myListener.IsListening)
{
ThreadPool.QueueUserWorkItem((c) =>
{
var ctx = c as HttpListenerContext;
try
{
var simpleResponse = Response(ctx.Request);
var buf = Encoding.UTF8.GetBytes(simpleResponse.Content);
ctx.Response.ContentLength64 = buf.Length;
ctx.Response.OutputStream.Write(buf, 0, buf.Length);
ctx.Response.StatusCode = (int)simpleResponse.StatusCode;
}
catch { } // suppress any exceptions
finally
{
// always close the stream
ctx.Response.OutputStream.Close();
}
}, myListener.GetContext());
}
}
catch { } // suppress any exceptions
});
}
public void ReceiveChanges(IDictionary<string, string> record)
{
myRecord = record;
Console.WriteLine(string.Join(", ",
new List<string>() { "TimeStamp", "Build", "Assembly", "TC", "Status" }.Select(f => record.ContainsKey(f) ? record[f] : "")));
}
public void Stop()
{
myListener.Stop();
myListener.Close();
}
public void Dispose()
{
Stop();
}
private HttpSimpleResponse Response(HttpListenerRequest httpRequest)
{
if (null == httpRequest)
{
return new HttpSimpleResponse(HttpStatusCode.BadRequest, "null");
}
var request = httpRequest.Url.LocalPath.Trim('/');
var client = httpRequest.RemoteEndPoint.Address.ToString();
Console.WriteLine("http {0} request received from {1}: {2}", httpRequest.HttpMethod, client, request);
switch (request)
{
case ConnectionRequest:
if (connections.All(c => c != client))
{
connections.Add(client);
Console.WriteLine("connection request accepted from {0}", client);
}
return new HttpSimpleResponse(HttpStatusCode.OK, RecordAsJson);
case StatusRequest:
return new HttpSimpleResponse(HttpStatusCode.OK, RecordAsJson);
default:
return new HttpSimpleResponse(HttpStatusCode.BadRequest, "he?!");
}
}
private string RecordAsJson
{
get
{
return JsonConvert.SerializeObject(myRecord, typeof(Dictionary<string, string>), Formatting.None,
new JsonSerializerSettings()
{
NullValueHandling = NullValueHandling.Ignore,
DefaultValueHandling = DefaultValueHandling.Ignore,
});
}
}
}
}
| klapantius/lit | lit/Transfer/HttpTransferModule.cs | C# | gpl-2.0 | 4,828 |
// This file is part of par2cmdline (a PAR 2.0 compatible file verification and
// repair tool). See http://parchive.sourceforge.net for details of PAR 2.0.
//
// Copyright (c) 2003 Peter Brian Clements
//
// par2cmdline 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 2 of the License, or
// (at your option) any later version.
//
// par2cmdline 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// 11/1/05 gmilow - Modified
#include "stdafx.h"
#include "par2cmdline.h"
#ifdef _MSC_VER
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
#endif
// Construct the creator packet.
// The only external information required to complete construction is
// the set_id_hash (which is normally computed from information in the
// main packet).
bool CreatorPacket::Create(const MD5Hash &setid)
{
string creator = "Created by PACKAGE version VERSION .";
// Allocate a packet just large enough for creator name
CREATORPACKET *packet = (CREATORPACKET *)AllocatePacket(sizeof(*packet) + (~3 & (3+(u32)creator.size())));
// Fill in the details the we know
packet->header.magic = packet_magic;
packet->header.length = packetlength;
//packet->header.hash; // Compute shortly
packet->header.setid = setid;
packet->header.type = creatorpacket_type;
// Copy the creator description into the packet
memcpy(packet->client, creator.c_str(), creator.size());
// Compute the packet hash
MD5Context packetcontext;
packetcontext.Update(&packet->header.setid, packetlength - offsetof(PACKET_HEADER, setid));
packetcontext.Final(packet->header.hash);
return true;
}
// Load the packet from disk.
bool CreatorPacket::Load(DiskFile *diskfile, u64 offset, PACKET_HEADER &header)
{
// Is the packet long enough
if (header.length <= sizeof(CREATORPACKET))
{
return false;
}
// Is the packet too large (what is the longest reasonable creator description)
if (header.length - sizeof(CREATORPACKET) > 100000)
{
return false;
}
// Allocate the packet (with a little extra so we will have NULLs after the description)
CREATORPACKET *packet = (CREATORPACKET *)AllocatePacket((size_t)header.length, 4);
packet->header = header;
// Load the rest of the packet from disk
return diskfile->Read(offset + sizeof(PACKET_HEADER),
packet->client,
(size_t)packet->header.length - sizeof(PACKET_HEADER));
}
| milowg/Par-N-Rar | par2-cmdline/creatorpacket.cpp | C++ | gpl-2.0 | 2,972 |
/*
* Copyright (C) 2005-2011 MaNGOS <http://getmangos.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 2 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "Common.h"
#include "Log.h"
#include "ObjectMgr.h"
#include "SpellMgr.h"
#include "Player.h"
#include "Unit.h"
#include "Spell.h"
#include "SpellAuras.h"
#include "Totem.h"
#include "Creature.h"
#include "Formulas.h"
#include "CreatureAI.h"
#include "Util.h"
pAuraProcHandler AuraProcHandler[TOTAL_AURAS]=
{
&Unit::HandleNULLProc, // 0 SPELL_AURA_NONE
&Unit::HandleNULLProc, // 1 SPELL_AURA_BIND_SIGHT
&Unit::HandleNULLProc, // 2 SPELL_AURA_MOD_POSSESS
&Unit::HandleNULLProc, // 3 SPELL_AURA_PERIODIC_DAMAGE
&Unit::HandleDummyAuraProc, // 4 SPELL_AURA_DUMMY
&Unit::HandleRemoveByDamageProc, // 5 SPELL_AURA_MOD_CONFUSE
&Unit::HandleNULLProc, // 6 SPELL_AURA_MOD_CHARM
&Unit::HandleRemoveByDamageChanceProc, // 7 SPELL_AURA_MOD_FEAR
&Unit::HandleNULLProc, // 8 SPELL_AURA_PERIODIC_HEAL
&Unit::HandleNULLProc, // 9 SPELL_AURA_MOD_ATTACKSPEED
&Unit::HandleNULLProc, // 10 SPELL_AURA_MOD_THREAT
&Unit::HandleNULLProc, // 11 SPELL_AURA_MOD_TAUNT
&Unit::HandleNULLProc, // 12 SPELL_AURA_MOD_STUN
&Unit::HandleNULLProc, // 13 SPELL_AURA_MOD_DAMAGE_DONE
&Unit::HandleNULLProc, // 14 SPELL_AURA_MOD_DAMAGE_TAKEN
&Unit::HandleNULLProc, // 15 SPELL_AURA_DAMAGE_SHIELD
&Unit::HandleRemoveByDamageProc, // 16 SPELL_AURA_MOD_STEALTH
&Unit::HandleNULLProc, // 17 SPELL_AURA_MOD_STEALTH_DETECT
&Unit::HandleRemoveByDamageProc, // 18 SPELL_AURA_MOD_INVISIBILITY
&Unit::HandleNULLProc, // 19 SPELL_AURA_MOD_INVISIBILITY_DETECTION
&Unit::HandleNULLProc, // 20 SPELL_AURA_OBS_MOD_HEALTH
&Unit::HandleNULLProc, // 21 SPELL_AURA_OBS_MOD_MANA
&Unit::HandleNULLProc, // 22 SPELL_AURA_MOD_RESISTANCE
&Unit::HandleNULLProc, // 23 SPELL_AURA_PERIODIC_TRIGGER_SPELL
&Unit::HandleNULLProc, // 24 SPELL_AURA_PERIODIC_ENERGIZE
&Unit::HandleNULLProc, // 25 SPELL_AURA_MOD_PACIFY
&Unit::HandleRemoveByDamageChanceProc, // 26 SPELL_AURA_MOD_ROOT
&Unit::HandleNULLProc, // 27 SPELL_AURA_MOD_SILENCE
&Unit::HandleNULLProc, // 28 SPELL_AURA_REFLECT_SPELLS
&Unit::HandleNULLProc, // 29 SPELL_AURA_MOD_STAT
&Unit::HandleNULLProc, // 30 SPELL_AURA_MOD_SKILL
&Unit::HandleNULLProc, // 31 SPELL_AURA_MOD_INCREASE_SPEED
&Unit::HandleNULLProc, // 32 SPELL_AURA_MOD_INCREASE_MOUNTED_SPEED
&Unit::HandleNULLProc, // 33 SPELL_AURA_MOD_DECREASE_SPEED
&Unit::HandleNULLProc, // 34 SPELL_AURA_MOD_INCREASE_HEALTH
&Unit::HandleNULLProc, // 35 SPELL_AURA_MOD_INCREASE_ENERGY
&Unit::HandleNULLProc, // 36 SPELL_AURA_MOD_SHAPESHIFT
&Unit::HandleNULLProc, // 37 SPELL_AURA_EFFECT_IMMUNITY
&Unit::HandleNULLProc, // 38 SPELL_AURA_STATE_IMMUNITY
&Unit::HandleNULLProc, // 39 SPELL_AURA_SCHOOL_IMMUNITY
&Unit::HandleNULLProc, // 40 SPELL_AURA_DAMAGE_IMMUNITY
&Unit::HandleNULLProc, // 41 SPELL_AURA_DISPEL_IMMUNITY
&Unit::HandleProcTriggerSpellAuraProc, // 42 SPELL_AURA_PROC_TRIGGER_SPELL
&Unit::HandleProcTriggerDamageAuraProc, // 43 SPELL_AURA_PROC_TRIGGER_DAMAGE
&Unit::HandleNULLProc, // 44 SPELL_AURA_TRACK_CREATURES
&Unit::HandleNULLProc, // 45 SPELL_AURA_TRACK_RESOURCES
&Unit::HandleNULLProc, // 46 SPELL_AURA_46 (used in test spells 54054 and 54058, and spell 48050) (3.0.8a-3.2.2a)
&Unit::HandleNULLProc, // 47 SPELL_AURA_MOD_PARRY_PERCENT
&Unit::HandleNULLProc, // 48 SPELL_AURA_48 spell Napalm (area damage spell with additional delayed damage effect)
&Unit::HandleNULLProc, // 49 SPELL_AURA_MOD_DODGE_PERCENT
&Unit::HandleNULLProc, // 50 SPELL_AURA_MOD_CRITICAL_HEALING_AMOUNT
&Unit::HandleNULLProc, // 51 SPELL_AURA_MOD_BLOCK_PERCENT
&Unit::HandleNULLProc, // 52 SPELL_AURA_MOD_CRIT_PERCENT
&Unit::HandleNULLProc, // 53 SPELL_AURA_PERIODIC_LEECH
&Unit::HandleNULLProc, // 54 SPELL_AURA_MOD_HIT_CHANCE
&Unit::HandleNULLProc, // 55 SPELL_AURA_MOD_SPELL_HIT_CHANCE
&Unit::HandleNULLProc, // 56 SPELL_AURA_TRANSFORM
&Unit::HandleSpellCritChanceAuraProc, // 57 SPELL_AURA_MOD_SPELL_CRIT_CHANCE
&Unit::HandleNULLProc, // 58 SPELL_AURA_MOD_INCREASE_SWIM_SPEED
&Unit::HandleNULLProc, // 59 SPELL_AURA_MOD_DAMAGE_DONE_CREATURE
&Unit::HandleRemoveByDamageChanceProc, // 60 SPELL_AURA_MOD_PACIFY_SILENCE
&Unit::HandleNULLProc, // 61 SPELL_AURA_MOD_SCALE
&Unit::HandleNULLProc, // 62 SPELL_AURA_PERIODIC_HEALTH_FUNNEL
&Unit::HandleNULLProc, // 63 unused (3.0.8a-3.2.2a) old SPELL_AURA_PERIODIC_MANA_FUNNEL
&Unit::HandleNULLProc, // 64 SPELL_AURA_PERIODIC_MANA_LEECH
&Unit::HandleModCastingSpeedNotStackAuraProc, // 65 SPELL_AURA_MOD_CASTING_SPEED_NOT_STACK
&Unit::HandleNULLProc, // 66 SPELL_AURA_FEIGN_DEATH
&Unit::HandleNULLProc, // 67 SPELL_AURA_MOD_DISARM
&Unit::HandleNULLProc, // 68 SPELL_AURA_MOD_STALKED
&Unit::HandleNULLProc, // 69 SPELL_AURA_SCHOOL_ABSORB
&Unit::HandleNULLProc, // 70 SPELL_AURA_EXTRA_ATTACKS Useless, used by only one spell 41560 that has only visual effect (3.2.2a)
&Unit::HandleNULLProc, // 71 SPELL_AURA_MOD_SPELL_CRIT_CHANCE_SCHOOL
&Unit::HandleModPowerCostSchoolAuraProc, // 72 SPELL_AURA_MOD_POWER_COST_SCHOOL_PCT
&Unit::HandleModPowerCostSchoolAuraProc, // 73 SPELL_AURA_MOD_POWER_COST_SCHOOL
&Unit::HandleReflectSpellsSchoolAuraProc, // 74 SPELL_AURA_REFLECT_SPELLS_SCHOOL
&Unit::HandleNULLProc, // 75 SPELL_AURA_MOD_LANGUAGE
&Unit::HandleNULLProc, // 76 SPELL_AURA_FAR_SIGHT
&Unit::HandleMechanicImmuneResistanceAuraProc, // 77 SPELL_AURA_MECHANIC_IMMUNITY
&Unit::HandleNULLProc, // 78 SPELL_AURA_MOUNTED
&Unit::HandleModDamagePercentDoneAuraProc, // 79 SPELL_AURA_MOD_DAMAGE_PERCENT_DONE
&Unit::HandleNULLProc, // 80 SPELL_AURA_MOD_PERCENT_STAT
&Unit::HandleNULLProc, // 81 SPELL_AURA_SPLIT_DAMAGE_PCT
&Unit::HandleNULLProc, // 82 SPELL_AURA_WATER_BREATHING
&Unit::HandleNULLProc, // 83 SPELL_AURA_MOD_BASE_RESISTANCE
&Unit::HandleNULLProc, // 84 SPELL_AURA_MOD_REGEN
&Unit::HandleCantTrigger, // 85 SPELL_AURA_MOD_POWER_REGEN
&Unit::HandleNULLProc, // 86 SPELL_AURA_CHANNEL_DEATH_ITEM
&Unit::HandleNULLProc, // 87 SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN
&Unit::HandleNULLProc, // 88 SPELL_AURA_MOD_HEALTH_REGEN_PERCENT
&Unit::HandleNULLProc, // 89 SPELL_AURA_PERIODIC_DAMAGE_PERCENT
&Unit::HandleNULLProc, // 90 unused (3.0.8a-3.2.2a) old SPELL_AURA_MOD_RESIST_CHANCE
&Unit::HandleNULLProc, // 91 SPELL_AURA_MOD_DETECT_RANGE
&Unit::HandleNULLProc, // 92 SPELL_AURA_PREVENTS_FLEEING
&Unit::HandleNULLProc, // 93 SPELL_AURA_MOD_UNATTACKABLE
&Unit::HandleNULLProc, // 94 SPELL_AURA_INTERRUPT_REGEN
&Unit::HandleNULLProc, // 95 SPELL_AURA_GHOST
&Unit::HandleNULLProc, // 96 SPELL_AURA_SPELL_MAGNET
&Unit::HandleNULLProc, // 97 SPELL_AURA_MANA_SHIELD
&Unit::HandleNULLProc, // 98 SPELL_AURA_MOD_SKILL_TALENT
&Unit::HandleNULLProc, // 99 SPELL_AURA_MOD_ATTACK_POWER
&Unit::HandleNULLProc, //100 SPELL_AURA_AURAS_VISIBLE obsolete 3.x? all player can see all auras now, but still have 2 spells including GM-spell (1852,2855)
&Unit::HandleNULLProc, //101 SPELL_AURA_MOD_RESISTANCE_PCT
&Unit::HandleNULLProc, //102 SPELL_AURA_MOD_MELEE_ATTACK_POWER_VERSUS
&Unit::HandleNULLProc, //103 SPELL_AURA_MOD_TOTAL_THREAT
&Unit::HandleNULLProc, //104 SPELL_AURA_WATER_WALK
&Unit::HandleNULLProc, //105 SPELL_AURA_FEATHER_FALL
&Unit::HandleNULLProc, //106 SPELL_AURA_HOVER
&Unit::HandleAddFlatModifierAuraProc, //107 SPELL_AURA_ADD_FLAT_MODIFIER
&Unit::HandleAddPctModifierAuraProc, //108 SPELL_AURA_ADD_PCT_MODIFIER
&Unit::HandleNULLProc, //109 SPELL_AURA_ADD_TARGET_TRIGGER
&Unit::HandleNULLProc, //110 SPELL_AURA_MOD_POWER_REGEN_PERCENT
&Unit::HandleNULLProc, //111 SPELL_AURA_ADD_CASTER_HIT_TRIGGER
&Unit::HandleOverrideClassScriptAuraProc, //112 SPELL_AURA_OVERRIDE_CLASS_SCRIPTS
&Unit::HandleNULLProc, //113 SPELL_AURA_MOD_RANGED_DAMAGE_TAKEN
&Unit::HandleNULLProc, //114 SPELL_AURA_MOD_RANGED_DAMAGE_TAKEN_PCT
&Unit::HandleNULLProc, //115 SPELL_AURA_MOD_HEALING
&Unit::HandleNULLProc, //116 SPELL_AURA_MOD_REGEN_DURING_COMBAT
&Unit::HandleMechanicImmuneResistanceAuraProc, //117 SPELL_AURA_MOD_MECHANIC_RESISTANCE
&Unit::HandleNULLProc, //118 SPELL_AURA_MOD_HEALING_PCT
&Unit::HandleNULLProc, //119 unused (3.0.8a-3.2.2a) old SPELL_AURA_SHARE_PET_TRACKING
&Unit::HandleNULLProc, //120 SPELL_AURA_UNTRACKABLE
&Unit::HandleNULLProc, //121 SPELL_AURA_EMPATHY
&Unit::HandleNULLProc, //122 SPELL_AURA_MOD_OFFHAND_DAMAGE_PCT
&Unit::HandleNULLProc, //123 SPELL_AURA_MOD_TARGET_RESISTANCE
&Unit::HandleNULLProc, //124 SPELL_AURA_MOD_RANGED_ATTACK_POWER
&Unit::HandleNULLProc, //125 SPELL_AURA_MOD_MELEE_DAMAGE_TAKEN
&Unit::HandleNULLProc, //126 SPELL_AURA_MOD_MELEE_DAMAGE_TAKEN_PCT
&Unit::HandleNULLProc, //127 SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS
&Unit::HandleNULLProc, //128 SPELL_AURA_MOD_POSSESS_PET
&Unit::HandleNULLProc, //129 SPELL_AURA_MOD_SPEED_ALWAYS
&Unit::HandleNULLProc, //130 SPELL_AURA_MOD_MOUNTED_SPEED_ALWAYS
&Unit::HandleNULLProc, //131 SPELL_AURA_MOD_RANGED_ATTACK_POWER_VERSUS
&Unit::HandleNULLProc, //132 SPELL_AURA_MOD_INCREASE_ENERGY_PERCENT
&Unit::HandleNULLProc, //133 SPELL_AURA_MOD_INCREASE_HEALTH_PERCENT
&Unit::HandleNULLProc, //134 SPELL_AURA_MOD_MANA_REGEN_INTERRUPT
&Unit::HandleNULLProc, //135 SPELL_AURA_MOD_HEALING_DONE
&Unit::HandleNULLProc, //136 SPELL_AURA_MOD_HEALING_DONE_PERCENT
&Unit::HandleNULLProc, //137 SPELL_AURA_MOD_TOTAL_STAT_PERCENTAGE
&Unit::HandleHasteAuraProc, //138 SPELL_AURA_MOD_MELEE_HASTE
&Unit::HandleNULLProc, //139 SPELL_AURA_FORCE_REACTION
&Unit::HandleNULLProc, //140 SPELL_AURA_MOD_RANGED_HASTE
&Unit::HandleNULLProc, //141 SPELL_AURA_MOD_RANGED_AMMO_HASTE
&Unit::HandleNULLProc, //142 SPELL_AURA_MOD_BASE_RESISTANCE_PCT
&Unit::HandleNULLProc, //143 SPELL_AURA_MOD_RESISTANCE_EXCLUSIVE
&Unit::HandleNULLProc, //144 SPELL_AURA_SAFE_FALL
&Unit::HandleNULLProc, //145 SPELL_AURA_MOD_PET_TALENT_POINTS
&Unit::HandleNULLProc, //146 SPELL_AURA_ALLOW_TAME_PET_TYPE
&Unit::HandleNULLProc, //147 SPELL_AURA_MECHANIC_IMMUNITY_MASK
&Unit::HandleNULLProc, //148 SPELL_AURA_RETAIN_COMBO_POINTS
&Unit::HandleCantTrigger, //149 SPELL_AURA_REDUCE_PUSHBACK
&Unit::HandleNULLProc, //150 SPELL_AURA_MOD_SHIELD_BLOCKVALUE_PCT
&Unit::HandleNULLProc, //151 SPELL_AURA_TRACK_STEALTHED
&Unit::HandleNULLProc, //152 SPELL_AURA_MOD_DETECTED_RANGE
&Unit::HandleNULLProc, //153 SPELL_AURA_SPLIT_DAMAGE_FLAT
&Unit::HandleNULLProc, //154 SPELL_AURA_MOD_STEALTH_LEVEL
&Unit::HandleNULLProc, //155 SPELL_AURA_MOD_WATER_BREATHING
&Unit::HandleNULLProc, //156 SPELL_AURA_MOD_REPUTATION_GAIN
&Unit::HandleNULLProc, //157 SPELL_AURA_PET_DAMAGE_MULTI (single test like spell 20782, also single for 214 aura)
&Unit::HandleNULLProc, //158 SPELL_AURA_MOD_SHIELD_BLOCKVALUE
&Unit::HandleNULLProc, //159 SPELL_AURA_NO_PVP_CREDIT
&Unit::HandleNULLProc, //160 SPELL_AURA_MOD_AOE_AVOIDANCE
&Unit::HandleNULLProc, //161 SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT
&Unit::HandleNULLProc, //162 SPELL_AURA_POWER_BURN_MANA
&Unit::HandleNULLProc, //163 SPELL_AURA_MOD_CRIT_DAMAGE_BONUS
&Unit::HandleNULLProc, //164 unused (3.0.8a-3.2.2a), only one test spell 10654
&Unit::HandleNULLProc, //165 SPELL_AURA_MELEE_ATTACK_POWER_ATTACKER_BONUS
&Unit::HandleNULLProc, //166 SPELL_AURA_MOD_ATTACK_POWER_PCT
&Unit::HandleNULLProc, //167 SPELL_AURA_MOD_RANGED_ATTACK_POWER_PCT
&Unit::HandleNULLProc, //168 SPELL_AURA_MOD_DAMAGE_DONE_VERSUS
&Unit::HandleNULLProc, //169 SPELL_AURA_MOD_CRIT_PERCENT_VERSUS
&Unit::HandleNULLProc, //170 SPELL_AURA_DETECT_AMORE different spells that ignore transformation effects
&Unit::HandleNULLProc, //171 SPELL_AURA_MOD_SPEED_NOT_STACK
&Unit::HandleNULLProc, //172 SPELL_AURA_MOD_MOUNTED_SPEED_NOT_STACK
&Unit::HandleNULLProc, //173 unused (3.0.8a-3.2.2a) no spells, old SPELL_AURA_ALLOW_CHAMPION_SPELLS only for Proclaim Champion spell
&Unit::HandleNULLProc, //174 SPELL_AURA_MOD_SPELL_DAMAGE_OF_STAT_PERCENT
&Unit::HandleNULLProc, //175 SPELL_AURA_MOD_SPELL_HEALING_OF_STAT_PERCENT
&Unit::HandleNULLProc, //176 SPELL_AURA_SPIRIT_OF_REDEMPTION only for Spirit of Redemption spell, die at aura end
&Unit::HandleNULLProc, //177 SPELL_AURA_AOE_CHARM (22 spells)
&Unit::HandleNULLProc, //178 SPELL_AURA_MOD_DEBUFF_RESISTANCE
&Unit::HandleNULLProc, //179 SPELL_AURA_MOD_ATTACKER_SPELL_CRIT_CHANCE
&Unit::HandleNULLProc, //180 SPELL_AURA_MOD_FLAT_SPELL_DAMAGE_VERSUS
&Unit::HandleNULLProc, //181 unused (3.0.8a-3.2.2a) old SPELL_AURA_MOD_FLAT_SPELL_CRIT_DAMAGE_VERSUS
&Unit::HandleNULLProc, //182 SPELL_AURA_MOD_RESISTANCE_OF_STAT_PERCENT
&Unit::HandleNULLProc, //183 SPELL_AURA_MOD_CRITICAL_THREAT only used in 28746
&Unit::HandleNULLProc, //184 SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE
&Unit::HandleNULLProc, //185 SPELL_AURA_MOD_ATTACKER_RANGED_HIT_CHANCE
&Unit::HandleNULLProc, //186 SPELL_AURA_MOD_ATTACKER_SPELL_HIT_CHANCE
&Unit::HandleNULLProc, //187 SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_CHANCE
&Unit::HandleNULLProc, //188 SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_CHANCE
&Unit::HandleModRating, //189 SPELL_AURA_MOD_RATING
&Unit::HandleNULLProc, //190 SPELL_AURA_MOD_FACTION_REPUTATION_GAIN
&Unit::HandleNULLProc, //191 SPELL_AURA_USE_NORMAL_MOVEMENT_SPEED
&Unit::HandleNULLProc, //192 SPELL_AURA_HASTE_MELEE
&Unit::HandleNULLProc, //193 SPELL_AURA_HASTE_ALL (in fact combat (any type attack) speed pct)
&Unit::HandleNULLProc, //194 SPELL_AURA_MOD_IGNORE_ABSORB_SCHOOL
&Unit::HandleNULLProc, //195 SPELL_AURA_MOD_IGNORE_ABSORB_FOR_SPELL
&Unit::HandleNULLProc, //196 SPELL_AURA_MOD_COOLDOWN (single spell 24818 in 3.2.2a)
&Unit::HandleNULLProc, //197 SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCEe
&Unit::HandleNULLProc, //198 unused (3.0.8a-3.2.2a) old SPELL_AURA_MOD_ALL_WEAPON_SKILLS
&Unit::HandleNULLProc, //199 SPELL_AURA_MOD_INCREASES_SPELL_PCT_TO_HIT
&Unit::HandleNULLProc, //200 SPELL_AURA_MOD_KILL_XP_PCT
&Unit::HandleNULLProc, //201 SPELL_AURA_FLY this aura enable flight mode...
&Unit::HandleNULLProc, //202 SPELL_AURA_CANNOT_BE_DODGED
&Unit::HandleNULLProc, //203 SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE
&Unit::HandleNULLProc, //204 SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE
&Unit::HandleNULLProc, //205 SPELL_AURA_MOD_ATTACKER_SPELL_CRIT_DAMAGE
&Unit::HandleNULLProc, //206 SPELL_AURA_MOD_FLIGHT_SPEED
&Unit::HandleNULLProc, //207 SPELL_AURA_MOD_FLIGHT_SPEED_MOUNTED
&Unit::HandleNULLProc, //208 SPELL_AURA_MOD_FLIGHT_SPEED_STACKING
&Unit::HandleNULLProc, //209 SPELL_AURA_MOD_FLIGHT_SPEED_MOUNTED_STACKING
&Unit::HandleNULLProc, //210 SPELL_AURA_MOD_FLIGHT_SPEED_NOT_STACKING
&Unit::HandleNULLProc, //211 SPELL_AURA_MOD_FLIGHT_SPEED_MOUNTED_NOT_STACKING
&Unit::HandleNULLProc, //212 SPELL_AURA_MOD_RANGED_ATTACK_POWER_OF_STAT_PERCENT
&Unit::HandleNULLProc, //213 SPELL_AURA_MOD_RAGE_FROM_DAMAGE_DEALT implemented in Player::RewardRage
&Unit::HandleNULLProc, //214 Tamed Pet Passive (single test like spell 20782, also single for 157 aura)
&Unit::HandleNULLProc, //215 SPELL_AURA_ARENA_PREPARATION
&Unit::HandleNULLProc, //216 SPELL_AURA_HASTE_SPELLS
&Unit::HandleNULLProc, //217 unused (3.0.8a-3.2.2a)
&Unit::HandleNULLProc, //218 SPELL_AURA_HASTE_RANGED
&Unit::HandleNULLProc, //219 SPELL_AURA_MOD_MANA_REGEN_FROM_STAT
&Unit::HandleNULLProc, //220 SPELL_AURA_MOD_RATING_FROM_STAT
&Unit::HandleNULLProc, //221 ignored
&Unit::HandleNULLProc, //222 unused (3.0.8a-3.2.2a) only for spell 44586 that not used in real spell cast
&Unit::HandleNULLProc, //223 dummy code (cast damage spell to attacker) and another dymmy (jump to another nearby raid member)
&Unit::HandleNULLProc, //224 unused (3.0.8a-3.2.2a)
&Unit::HandleMendingAuraProc, //225 SPELL_AURA_PRAYER_OF_MENDING
&Unit::HandlePeriodicDummyAuraProc, //226 SPELL_AURA_PERIODIC_DUMMY
&Unit::HandleNULLProc, //227 SPELL_AURA_PERIODIC_TRIGGER_SPELL_WITH_VALUE
&Unit::HandleNULLProc, //228 SPELL_AURA_DETECT_STEALTH
&Unit::HandleNULLProc, //229 SPELL_AURA_MOD_AOE_DAMAGE_AVOIDANCE
&Unit::HandleNULLProc, //230 Commanding Shout
&Unit::HandleProcTriggerSpellAuraProc, //231 SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE
&Unit::HandleNULLProc, //232 SPELL_AURA_MECHANIC_DURATION_MOD
&Unit::HandleNULLProc, //233 set model id to the one of the creature with id m_modifier.m_miscvalue
&Unit::HandleNULLProc, //234 SPELL_AURA_MECHANIC_DURATION_MOD_NOT_STACK
&Unit::HandleNULLProc, //235 SPELL_AURA_MOD_DISPEL_RESIST
&Unit::HandleNULLProc, //236 SPELL_AURA_CONTROL_VEHICLE
&Unit::HandleNULLProc, //237 SPELL_AURA_MOD_SPELL_DAMAGE_OF_ATTACK_POWER
&Unit::HandleNULLProc, //238 SPELL_AURA_MOD_SPELL_HEALING_OF_ATTACK_POWER
&Unit::HandleNULLProc, //239 SPELL_AURA_MOD_SCALE_2 only in Noggenfogger Elixir (16595) before 2.3.0 aura 61
&Unit::HandleNULLProc, //240 SPELL_AURA_MOD_EXPERTISE
&Unit::HandleNULLProc, //241 Forces the player to move forward
&Unit::HandleNULLProc, //242 SPELL_AURA_MOD_SPELL_DAMAGE_FROM_HEALING (only 2 test spels in 3.2.2a)
&Unit::HandleNULLProc, //243 faction reaction override spells
&Unit::HandleNULLProc, //244 SPELL_AURA_COMPREHEND_LANGUAGE
&Unit::HandleNULLProc, //245 SPELL_AURA_MOD_DURATION_OF_MAGIC_EFFECTS
&Unit::HandleNULLProc, //246 SPELL_AURA_MOD_DURATION_OF_EFFECTS_BY_DISPEL
&Unit::HandleNULLProc, //247 target to become a clone of the caster
&Unit::HandleNULLProc, //248 SPELL_AURA_MOD_COMBAT_RESULT_CHANCE
&Unit::HandleNULLProc, //249 SPELL_AURA_CONVERT_RUNE
&Unit::HandleNULLProc, //250 SPELL_AURA_MOD_INCREASE_HEALTH_2
&Unit::HandleNULLProc, //251 SPELL_AURA_MOD_ENEMY_DODGE
&Unit::HandleNULLProc, //252 SPELL_AURA_SLOW_ALL
&Unit::HandleNULLProc, //253 SPELL_AURA_MOD_BLOCK_CRIT_CHANCE
&Unit::HandleNULLProc, //254 SPELL_AURA_MOD_DISARM_SHIELD disarm Shield
&Unit::HandleNULLProc, //255 SPELL_AURA_MOD_MECHANIC_DAMAGE_TAKEN_PERCENT
&Unit::HandleNULLProc, //256 SPELL_AURA_NO_REAGENT_USE Use SpellClassMask for spell select
&Unit::HandleNULLProc, //257 SPELL_AURA_MOD_TARGET_RESIST_BY_SPELL_CLASS Use SpellClassMask for spell select
&Unit::HandleNULLProc, //258 SPELL_AURA_MOD_SPELL_VISUAL
&Unit::HandleNULLProc, //259 corrupt healing over time spell
&Unit::HandleNULLProc, //260 SPELL_AURA_SCREEN_EFFECT (miscvalue = id in ScreenEffect.dbc) not required any code
&Unit::HandleNULLProc, //261 SPELL_AURA_PHASE undetectable invisibility?
&Unit::HandleNULLProc, //262 SPELL_AURA_IGNORE_UNIT_STATE
&Unit::HandleNULLProc, //263 SPELL_AURA_ALLOW_ONLY_ABILITY player can use only abilities set in SpellClassMask
&Unit::HandleNULLProc, //264 unused (3.0.8a-3.2.2a)
&Unit::HandleNULLProc, //265 unused (3.0.8a-3.2.2a)
&Unit::HandleNULLProc, //266 unused (3.0.8a-3.2.2a)
&Unit::HandleNULLProc, //267 SPELL_AURA_MOD_IMMUNE_AURA_APPLY_SCHOOL
&Unit::HandleNULLProc, //268 SPELL_AURA_MOD_ATTACK_POWER_OF_STAT_PERCENT
&Unit::HandleNULLProc, //269 SPELL_AURA_MOD_IGNORE_DAMAGE_REDUCTION_SCHOOL
&Unit::HandleNULLProc, //270 SPELL_AURA_MOD_IGNORE_TARGET_RESIST (unused in 3.2.2a)
&Unit::HandleModDamageFromCasterAuraProc, //271 SPELL_AURA_MOD_DAMAGE_FROM_CASTER
&Unit::HandleNULLProc, //272 SPELL_AURA_MAELSTROM_WEAPON (unclear use for aura, it used in (3.2.2a...3.3.0) in single spell 53817 that spellmode stacked and charged spell expected to be drop as stack
&Unit::HandleNULLProc, //273 SPELL_AURA_X_RAY (client side implementation)
&Unit::HandleNULLProc, //274 proc free shot?
&Unit::HandleNULLProc, //275 SPELL_AURA_MOD_IGNORE_SHAPESHIFT Use SpellClassMask for spell select
&Unit::HandleNULLProc, //276 mod damage % mechanic?
&Unit::HandleNULLProc, //277 SPELL_AURA_MOD_MAX_AFFECTED_TARGETS Use SpellClassMask for spell select
&Unit::HandleNULLProc, //278 SPELL_AURA_MOD_DISARM_RANGED disarm ranged weapon
&Unit::HandleNULLProc, //279 visual effects? 58836 and 57507
&Unit::HandleNULLProc, //280 SPELL_AURA_MOD_TARGET_ARMOR_PCT
&Unit::HandleNULLProc, //281 SPELL_AURA_MOD_HONOR_GAIN
&Unit::HandleNULLProc, //282 SPELL_AURA_INCREASE_BASE_HEALTH_PERCENT
&Unit::HandleNULLProc, //283 SPELL_AURA_MOD_HEALING_RECEIVED
&Unit::HandleNULLProc, //284 51 spells
&Unit::HandleNULLProc, //285 SPELL_AURA_MOD_ATTACK_POWER_OF_ARMOR
&Unit::HandleNULLProc, //286 SPELL_AURA_ABILITY_PERIODIC_CRIT
&Unit::HandleNULLProc, //287 SPELL_AURA_DEFLECT_SPELLS
&Unit::HandleNULLProc, //288 increase parry/deflect, prevent attack (single spell used 67801)
&Unit::HandleNULLProc, //289 unused (3.2.2a)
&Unit::HandleNULLProc, //290 SPELL_AURA_MOD_ALL_CRIT_CHANCE
&Unit::HandleNULLProc, //291 SPELL_AURA_MOD_QUEST_XP_PCT
&Unit::HandleNULLProc, //292 call stabled pet
&Unit::HandleNULLProc, //293 3 spells
&Unit::HandleNULLProc, //294 2 spells, possible prevent mana regen
&Unit::HandleNULLProc, //295 unused (3.2.2a)
&Unit::HandleNULLProc, //296 2 spells
&Unit::HandleNULLProc, //297 1 spell (counter spell school?)
&Unit::HandleNULLProc, //298 unused (3.2.2a)
&Unit::HandleNULLProc, //299 unused (3.2.2a)
&Unit::HandleNULLProc, //300 3 spells (share damage?)
&Unit::HandleNULLProc, //301 5 spells
&Unit::HandleNULLProc, //302 unused (3.2.2a)
&Unit::HandleNULLProc, //303 17 spells
&Unit::HandleNULLProc, //304 2 spells (alcohol effect?)
&Unit::HandleNULLProc, //305 SPELL_AURA_MOD_MINIMUM_SPEED
&Unit::HandleNULLProc, //306 1 spell
&Unit::HandleNULLProc, //307 absorb healing?
&Unit::HandleNULLProc, //308 new aura for hunter traps
&Unit::HandleNULLProc, //309 absorb healing?
&Unit::HandleNULLProc, //310 pet avoidance passive?
&Unit::HandleNULLProc, //311 0 spells in 3.3
&Unit::HandleNULLProc, //312 0 spells in 3.3
&Unit::HandleNULLProc, //313 0 spells in 3.3
&Unit::HandleNULLProc, //314 1 test spell (reduce duration of silince/magic)
&Unit::HandleNULLProc, //315 underwater walking
&Unit::HandleNULLProc //316 makes haste affect HOT/DOT ticks
};
bool Unit::IsTriggeredAtSpellProcEvent(Unit *pVictim, SpellAuraHolder* holder, SpellEntry const* procSpell, uint32 procFlag, uint32 procExtra, WeaponAttackType attType, bool isVictim, SpellProcEventEntry const*& spellProcEvent )
{
SpellEntry const* spellProto = holder->GetSpellProto ();
// Get proc Event Entry
spellProcEvent = sSpellMgr.GetSpellProcEvent(spellProto->Id);
// Get EventProcFlag
uint32 EventProcFlag;
if (spellProcEvent && spellProcEvent->procFlags) // if exist get custom spellProcEvent->procFlags
EventProcFlag = spellProcEvent->procFlags;
else
EventProcFlag = spellProto->procFlags; // else get from spell proto
// Continue if no trigger exist
if (!EventProcFlag)
return false;
// Check spellProcEvent data requirements
if(!SpellMgr::IsSpellProcEventCanTriggeredBy(spellProcEvent, EventProcFlag, procSpell, procFlag, procExtra))
return false;
// In most cases req get honor or XP from kill
if (EventProcFlag & PROC_FLAG_KILL && GetTypeId() == TYPEID_PLAYER)
{
bool allow = ((Player*)this)->isHonorOrXPTarget(pVictim);
// Shadow Word: Death - can trigger from every kill
if (holder->GetId() == 32409)
allow = true;
if (!allow)
return false;
}
// Aura added by spell can`t trigger from self (prevent drop charges/do triggers)
// But except periodic triggers (can triggered from self)
if(procSpell && procSpell->Id == spellProto->Id && !(spellProto->procFlags & PROC_FLAG_ON_TAKE_PERIODIC))
return false;
// Check if current equipment allows aura to proc
if(!isVictim && GetTypeId() == TYPEID_PLAYER)
{
if(spellProto->EquippedItemClass == ITEM_CLASS_WEAPON)
{
Item *item = NULL;
if(attType == BASE_ATTACK)
item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND);
else if (attType == OFF_ATTACK)
item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
else
item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED);
if(!item || item->IsBroken() || item->GetProto()->Class != ITEM_CLASS_WEAPON || !((1<<item->GetProto()->SubClass) & spellProto->EquippedItemSubClassMask))
return false;
}
else if(spellProto->EquippedItemClass == ITEM_CLASS_ARMOR)
{
// Check if player is wearing shield
Item *item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
if(!item || item->IsBroken() || !CanUseEquippedWeapon(OFF_ATTACK) || item->GetProto()->Class != ITEM_CLASS_ARMOR || !((1<<item->GetProto()->SubClass) & spellProto->EquippedItemSubClassMask))
return false;
}
}
// Get chance from spell
float chance = (float)spellProto->procChance;
// If in spellProcEvent exist custom chance, chance = spellProcEvent->customChance;
if(spellProcEvent && spellProcEvent->customChance)
chance = spellProcEvent->customChance;
// If PPM exist calculate chance from PPM
if(!isVictim && spellProcEvent && spellProcEvent->ppmRate != 0)
{
uint32 WeaponSpeed = GetAttackTime(attType);
chance = GetPPMProcChance(WeaponSpeed, spellProcEvent->ppmRate);
}
// Apply chance modifier aura
if(Player* modOwner = GetSpellModOwner())
{
modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_CHANCE_OF_SUCCESS,chance);
modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_FREQUENCY_OF_SUCCESS,chance);
}
return roll_chance_f(chance);
}
SpellAuraProcResult Unit::HandleHasteAuraProc(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const * /*procSpell*/, uint32 /*procFlag*/, uint32 /*procEx*/, uint32 cooldown)
{
SpellEntry const *hasteSpell = triggeredByAura->GetSpellProto();
Item* castItem = !triggeredByAura->GetCastItemGuid().IsEmpty() && GetTypeId()==TYPEID_PLAYER
? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGuid()) : NULL;
uint32 triggered_spell_id = 0;
Unit* target = pVictim;
int32 basepoints0 = 0;
switch(hasteSpell->SpellFamilyName)
{
case SPELLFAMILY_ROGUE:
{
switch(hasteSpell->Id)
{
// Blade Flurry
case 13877:
case 33735:
{
target = SelectRandomUnfriendlyTarget(pVictim);
if(!target)
return SPELL_AURA_PROC_FAILED;
basepoints0 = damage;
triggered_spell_id = 22482;
break;
}
}
break;
}
}
// processed charge only counting case
if(!triggered_spell_id)
return SPELL_AURA_PROC_OK;
SpellEntry const* triggerEntry = sSpellStore.LookupEntry(triggered_spell_id);
if(!triggerEntry)
{
sLog.outError("Unit::HandleHasteAuraProc: Spell %u have nonexistent triggered spell %u",hasteSpell->Id,triggered_spell_id);
return SPELL_AURA_PROC_FAILED;
}
// default case
if (!target || (target != this && !target->isAlive()))
return SPELL_AURA_PROC_FAILED;
if (cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(triggered_spell_id))
return SPELL_AURA_PROC_FAILED;
if (basepoints0)
CastCustomSpell(target,triggered_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
else
CastSpell(target,triggered_spell_id,true,castItem,triggeredByAura);
if (cooldown && GetTypeId()==TYPEID_PLAYER)
((Player*)this)->AddSpellCooldown(triggered_spell_id,0,time(NULL) + cooldown);
return SPELL_AURA_PROC_OK;
}
SpellAuraProcResult Unit::HandleSpellCritChanceAuraProc(Unit *pVictim, uint32 /*damage*/, Aura* triggeredByAura, SpellEntry const * procSpell, uint32 /*procFlag*/, uint32 /*procEx*/, uint32 cooldown)
{
if (!procSpell)
return SPELL_AURA_PROC_FAILED;
SpellEntry const *triggeredByAuraSpell = triggeredByAura->GetSpellProto();
Item* castItem = !triggeredByAura->GetCastItemGuid().IsEmpty() && GetTypeId()==TYPEID_PLAYER
? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGuid()) : NULL;
uint32 triggered_spell_id = 0;
Unit* target = pVictim;
int32 basepoints0 = 0;
switch(triggeredByAuraSpell->SpellFamilyName)
{
case SPELLFAMILY_MAGE:
{
switch(triggeredByAuraSpell->Id)
{
// Focus Magic
case 54646:
{
Unit* caster = triggeredByAura->GetCaster();
if (!caster)
return SPELL_AURA_PROC_FAILED;
triggered_spell_id = 54648;
target = caster;
break;
}
}
}
}
// processed charge only counting case
if (!triggered_spell_id)
return SPELL_AURA_PROC_OK;
SpellEntry const* triggerEntry = sSpellStore.LookupEntry(triggered_spell_id);
if(!triggerEntry)
{
sLog.outError("Unit::HandleHasteAuraProc: Spell %u have nonexistent triggered spell %u",triggeredByAuraSpell->Id,triggered_spell_id);
return SPELL_AURA_PROC_FAILED;
}
// default case
if (!target || (target != this && !target->isAlive()))
return SPELL_AURA_PROC_FAILED;
if (cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(triggered_spell_id))
return SPELL_AURA_PROC_FAILED;
if (basepoints0)
CastCustomSpell(target,triggered_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
else
CastSpell(target,triggered_spell_id,true,castItem,triggeredByAura);
if (cooldown && GetTypeId()==TYPEID_PLAYER)
((Player*)this)->AddSpellCooldown(triggered_spell_id,0,time(NULL) + cooldown);
return SPELL_AURA_PROC_OK;
}
SpellAuraProcResult Unit::HandleDummyAuraProc(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const * procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown)
{
SpellEntry const *dummySpell = triggeredByAura->GetSpellProto ();
SpellEffectIndex effIndex = triggeredByAura->GetEffIndex();
int32 triggerAmount = triggeredByAura->GetModifier()->m_amount;
Item* castItem = !triggeredByAura->GetCastItemGuid().IsEmpty() && GetTypeId()==TYPEID_PLAYER
? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGuid()) : NULL;
// some dummy spells have trigger spell in spell data already (from 3.0.3)
uint32 triggered_spell_id = dummySpell->EffectApplyAuraName[effIndex] == SPELL_AURA_DUMMY ? dummySpell->EffectTriggerSpell[effIndex] : 0;
Unit* target = pVictim;
int32 basepoints[MAX_EFFECT_INDEX] = {0, 0, 0};
ObjectGuid originalCaster = ObjectGuid();
switch(dummySpell->SpellFamilyName)
{
case SPELLFAMILY_GENERIC:
{
switch (dummySpell->Id)
{
// Eye for an Eye
case 9799:
case 25988:
{
// return damage % to attacker but < 50% own total health
basepoints[0] = triggerAmount*int32(damage)/100;
if (basepoints[0] > (int32)GetMaxHealth()/2)
basepoints[0] = (int32)GetMaxHealth()/2;
triggered_spell_id = 25997;
break;
}
// Sweeping Strikes (NPC spells may be)
case 18765:
case 35429:
{
// prevent chain of triggered spell from same triggered spell
if (procSpell && procSpell->Id == 26654)
return SPELL_AURA_PROC_FAILED;
target = SelectRandomUnfriendlyTarget(pVictim);
if(!target)
return SPELL_AURA_PROC_FAILED;
triggered_spell_id = 26654;
break;
}
// Twisted Reflection (boss spell)
case 21063:
triggered_spell_id = 21064;
break;
// Unstable Power
case 24658:
{
if (!procSpell || procSpell->Id == 24659)
return SPELL_AURA_PROC_FAILED;
// Need remove one 24659 aura
RemoveAuraHolderFromStack(24659);
return SPELL_AURA_PROC_OK;
}
// Restless Strength
case 24661:
{
// Need remove one 24662 aura
RemoveAuraHolderFromStack(24662);
return SPELL_AURA_PROC_OK;
}
// Adaptive Warding (Frostfire Regalia set)
case 28764:
{
if(!procSpell)
return SPELL_AURA_PROC_FAILED;
// find Mage Armor
bool found = false;
AuraList const& mRegenInterupt = GetAurasByType(SPELL_AURA_MOD_MANA_REGEN_INTERRUPT);
for(AuraList::const_iterator iter = mRegenInterupt.begin(); iter != mRegenInterupt.end(); ++iter)
{
if(SpellEntry const* iterSpellProto = (*iter)->GetSpellProto())
{
if(iterSpellProto->SpellFamilyName==SPELLFAMILY_MAGE && (iterSpellProto->SpellFamilyFlags & UI64LIT(0x10000000)))
{
found=true;
break;
}
}
}
if(!found)
return SPELL_AURA_PROC_FAILED;
switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell)))
{
case SPELL_SCHOOL_NORMAL:
case SPELL_SCHOOL_HOLY:
return SPELL_AURA_PROC_FAILED; // ignored
case SPELL_SCHOOL_FIRE: triggered_spell_id = 28765; break;
case SPELL_SCHOOL_NATURE: triggered_spell_id = 28768; break;
case SPELL_SCHOOL_FROST: triggered_spell_id = 28766; break;
case SPELL_SCHOOL_SHADOW: triggered_spell_id = 28769; break;
case SPELL_SCHOOL_ARCANE: triggered_spell_id = 28770; break;
default:
return SPELL_AURA_PROC_FAILED;
}
target = this;
break;
}
// Obsidian Armor (Justice Bearer`s Pauldrons shoulder)
case 27539:
{
if(!procSpell)
return SPELL_AURA_PROC_FAILED;
switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell)))
{
case SPELL_SCHOOL_NORMAL:
return SPELL_AURA_PROC_FAILED; // ignore
case SPELL_SCHOOL_HOLY: triggered_spell_id = 27536; break;
case SPELL_SCHOOL_FIRE: triggered_spell_id = 27533; break;
case SPELL_SCHOOL_NATURE: triggered_spell_id = 27538; break;
case SPELL_SCHOOL_FROST: triggered_spell_id = 27534; break;
case SPELL_SCHOOL_SHADOW: triggered_spell_id = 27535; break;
case SPELL_SCHOOL_ARCANE: triggered_spell_id = 27540; break;
default:
return SPELL_AURA_PROC_FAILED;
}
target = this;
break;
}
// Mana Leech (Passive) (Priest Pet Aura)
case 28305:
{
// Cast on owner
target = GetOwner();
if(!target)
return SPELL_AURA_PROC_FAILED;
triggered_spell_id = 34650;
break;
}
// Divine purpose
case 31871:
case 31872:
{
// Roll chance
if (!roll_chance_i(triggerAmount))
return SPELL_AURA_PROC_FAILED;
// Remove any stun effect on target
SpellAuraHolderMap& Auras = pVictim->GetSpellAuraHolderMap();
for(SpellAuraHolderMap::const_iterator iter = Auras.begin(); iter != Auras.end();)
{
SpellEntry const *spell = iter->second->GetSpellProto();
if( spell->Mechanic == MECHANIC_STUN ||
iter->second->HasMechanic(MECHANIC_STUN))
{
pVictim->RemoveAurasDueToSpell(spell->Id);
iter = Auras.begin();
}
else
++iter;
}
return SPELL_AURA_PROC_OK;
}
// Mark of Malice
case 33493:
{
// Cast finish spell at last charge
if (triggeredByAura->GetHolder()->GetAuraCharges() > 1)
return SPELL_AURA_PROC_FAILED;
target = this;
triggered_spell_id = 33494;
break;
}
// Vampiric Aura (boss spell)
case 38196:
{
basepoints[0] = 3 * damage; // 300%
if (basepoints[0] < 0)
return SPELL_AURA_PROC_FAILED;
triggered_spell_id = 31285;
target = this;
break;
}
// Aura of Madness (Darkmoon Card: Madness trinket)
//=====================================================
// 39511 Sociopath: +35 strength (Paladin, Rogue, Druid, Warrior)
// 40997 Delusional: +70 attack power (Rogue, Hunter, Paladin, Warrior, Druid)
// 40998 Kleptomania: +35 agility (Warrior, Rogue, Paladin, Hunter, Druid)
// 40999 Megalomania: +41 damage/healing (Druid, Shaman, Priest, Warlock, Mage, Paladin)
// 41002 Paranoia: +35 spell/melee/ranged crit strike rating (All classes)
// 41005 Manic: +35 haste (spell, melee and ranged) (All classes)
// 41009 Narcissism: +35 intellect (Druid, Shaman, Priest, Warlock, Mage, Paladin, Hunter)
// 41011 Martyr Complex: +35 stamina (All classes)
// 41406 Dementia: Every 5 seconds either gives you +5% damage/healing. (Druid, Shaman, Priest, Warlock, Mage, Paladin)
// 41409 Dementia: Every 5 seconds either gives you -5% damage/healing. (Druid, Shaman, Priest, Warlock, Mage, Paladin)
case 39446:
{
if(GetTypeId() != TYPEID_PLAYER)
return SPELL_AURA_PROC_FAILED;
// Select class defined buff
switch (getClass())
{
case CLASS_PALADIN: // 39511,40997,40998,40999,41002,41005,41009,41011,41409
case CLASS_DRUID: // 39511,40997,40998,40999,41002,41005,41009,41011,41409
{
uint32 RandomSpell[]={39511,40997,40998,40999,41002,41005,41009,41011,41409};
triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
break;
}
case CLASS_ROGUE: // 39511,40997,40998,41002,41005,41011
case CLASS_WARRIOR: // 39511,40997,40998,41002,41005,41011
{
uint32 RandomSpell[]={39511,40997,40998,41002,41005,41011};
triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
break;
}
case CLASS_PRIEST: // 40999,41002,41005,41009,41011,41406,41409
case CLASS_SHAMAN: // 40999,41002,41005,41009,41011,41406,41409
case CLASS_MAGE: // 40999,41002,41005,41009,41011,41406,41409
case CLASS_WARLOCK: // 40999,41002,41005,41009,41011,41406,41409
{
uint32 RandomSpell[]={40999,41002,41005,41009,41011,41406,41409};
triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
break;
}
case CLASS_HUNTER: // 40997,40999,41002,41005,41009,41011,41406,41409
{
uint32 RandomSpell[]={40997,40999,41002,41005,41009,41011,41406,41409};
triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
break;
}
default:
return SPELL_AURA_PROC_FAILED;
}
target = this;
if (roll_chance_i(10))
((Player*)this)->Say("This is Madness!", LANG_UNIVERSAL);
break;
}
// Sunwell Exalted Caster Neck (Shattered Sun Pendant of Acumen neck)
// cast 45479 Light's Wrath if Exalted by Aldor
// cast 45429 Arcane Bolt if Exalted by Scryers
case 45481:
{
if(GetTypeId() != TYPEID_PLAYER)
return SPELL_AURA_PROC_FAILED;
// Get Aldor reputation rank
if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
{
target = this;
triggered_spell_id = 45479;
break;
}
// Get Scryers reputation rank
if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
{
// triggered at positive/self casts also, current attack target used then
if(IsFriendlyTo(target))
{
target = getVictim();
if(!target)
{
target = ObjectAccessor::GetUnit(*this,((Player *)this)->GetSelectionGuid());
if(!target)
return SPELL_AURA_PROC_FAILED;
}
if(IsFriendlyTo(target))
return SPELL_AURA_PROC_FAILED;
}
triggered_spell_id = 45429;
break;
}
return SPELL_AURA_PROC_FAILED;
}
// Sunwell Exalted Melee Neck (Shattered Sun Pendant of Might neck)
// cast 45480 Light's Strength if Exalted by Aldor
// cast 45428 Arcane Strike if Exalted by Scryers
case 45482:
{
if(GetTypeId() != TYPEID_PLAYER)
return SPELL_AURA_PROC_FAILED;
// Get Aldor reputation rank
if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
{
target = this;
triggered_spell_id = 45480;
break;
}
// Get Scryers reputation rank
if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
{
triggered_spell_id = 45428;
break;
}
return SPELL_AURA_PROC_FAILED;
}
// Sunwell Exalted Tank Neck (Shattered Sun Pendant of Resolve neck)
// cast 45431 Arcane Insight if Exalted by Aldor
// cast 45432 Light's Ward if Exalted by Scryers
case 45483:
{
if(GetTypeId() != TYPEID_PLAYER)
return SPELL_AURA_PROC_FAILED;
// Get Aldor reputation rank
if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
{
target = this;
triggered_spell_id = 45432;
break;
}
// Get Scryers reputation rank
if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
{
target = this;
triggered_spell_id = 45431;
break;
}
return SPELL_AURA_PROC_FAILED;
}
// Sunwell Exalted Healer Neck (Shattered Sun Pendant of Restoration neck)
// cast 45478 Light's Salvation if Exalted by Aldor
// cast 45430 Arcane Surge if Exalted by Scryers
case 45484:
{
if(GetTypeId() != TYPEID_PLAYER)
return SPELL_AURA_PROC_FAILED;
// Get Aldor reputation rank
if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
{
target = this;
triggered_spell_id = 45478;
break;
}
// Get Scryers reputation rank
if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
{
triggered_spell_id = 45430;
break;
}
return SPELL_AURA_PROC_FAILED;
}
/*
// Sunwell Exalted Caster Neck (??? neck)
// cast ??? Light's Wrath if Exalted by Aldor
// cast ??? Arcane Bolt if Exalted by Scryers*/
case 46569:
return SPELL_AURA_PROC_FAILED; // old unused version
// Living Seed
case 48504:
{
triggered_spell_id = 48503;
basepoints[0] = triggerAmount;
target = this;
break;
}
// Health Leech (used by Bloodworms)
case 50453:
{
Unit *owner = GetOwner();
if (!owner)
return SPELL_AURA_PROC_FAILED;
triggered_spell_id = 50454;
basepoints[0] = int32(damage*1.69);
target = owner;
break;
}
// Vampiric Touch (generic, used by some boss)
case 52723:
case 60501:
{
triggered_spell_id = 52724;
basepoints[0] = damage / 2;
target = this;
break;
}
// Shadowfiend Death (Gain mana if pet dies with Glyph of Shadowfiend)
case 57989:
{
Unit *owner = GetOwner();
if (!owner || owner->GetTypeId() != TYPEID_PLAYER)
return SPELL_AURA_PROC_FAILED;
// Glyph of Shadowfiend (need cast as self cast for owner, no hidden cooldown)
owner->CastSpell(owner,58227,true,castItem,triggeredByAura);
return SPELL_AURA_PROC_OK;
}
// Kill Command, pet aura
case 58914:
{
// also decrease owner buff stack
if (Unit* owner = GetOwner())
owner->RemoveAuraHolderFromStack(34027);
// Remove only single aura from stack
if (triggeredByAura->GetStackAmount() > 1 && !triggeredByAura->GetHolder()->ModStackAmount(-1))
return SPELL_AURA_PROC_CANT_TRIGGER;
}
// Glyph of Life Tap
case 63320:
triggered_spell_id = 63321;
break;
// Shiny Shard of the Scale - Equip Effect
case 69739:
// Cauterizing Heal or Searing Flame
triggered_spell_id = (procFlag & PROC_FLAG_SUCCESSFUL_POSITIVE_SPELL) ? 69734 : 69730;
break;
// Purified Shard of the Scale - Equip Effect
case 69755:
// Cauterizing Heal or Searing Flame
triggered_spell_id = (procFlag & PROC_FLAG_SUCCESSFUL_POSITIVE_SPELL) ? 69733 : 69729;
break;
case 70871:
// Soul of Blood qween
triggered_spell_id = 70872;
basepoints[0] = int32(triggerAmount* damage /100);
if (basepoints[0] < 0)
return SPELL_AURA_PROC_FAILED;
break;
// Glyph of Shadowflame
case 63310:
{
triggered_spell_id = 63311;
break;
}
// Item - Shadowmourne Legendary
case 71903:
{
if (!roll_chance_i(triggerAmount))
return SPELL_AURA_PROC_FAILED;
triggered_spell_id = 71905; // Soul Fragment
SpellAuraHolder *aurHolder = GetSpellAuraHolder(triggered_spell_id);
// will added first to stack
if (!aurHolder)
CastSpell(this, 72521, true); // Shadowmourne Visual Low
// half stack
else if (aurHolder->GetStackAmount() + 1 == 6)
CastSpell(this, 72523, true); // Shadowmourne Visual High
// full stack
else if (aurHolder->GetStackAmount() + 1 >= aurHolder->GetSpellProto()->StackAmount)
{
RemoveAurasDueToSpell(triggered_spell_id);
CastSpell(this, 71904, true); // Chaos Bane
return SPELL_AURA_PROC_OK;
}
break;
}
// Deathbringer's Will (Item - Icecrown 25 Normal Melee Trinket)
//=====================================================
// 71492 Speed of the Vrykul: +600 haste rating (Death Knight, Druid, Paladin, Rogue, Warrior, Shaman)
// 71485 Agility of the Vrykul: +600 agility (Druid, Hunter, Rogue, Shaman)
// 71486 Power of the Taunka: +1200 attack power (Hunter, Rogue, Shaman)
// 71484 Strength of the Taunka: +600 strength (Death Knight, Druid, Paladin, Warrior)
// 71491 Aim of the Iron Dwarves: +600 critical strike rating (Death Knight, Hunter, Paladin, Warrior)
case 71519:
{
if(GetTypeId() != TYPEID_PLAYER)
return SPELL_AURA_PROC_FAILED;
if(HasAura(71491) || HasAura(71484) || HasAura(71492) || HasAura(71486) || HasAura(71485))
return SPELL_AURA_PROC_FAILED;
// Select class defined buff
switch (getClass())
{
case CLASS_PALADIN:
{
uint32 RandomSpell[]={71492,71484,71491};
triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
break;
}
case CLASS_DRUID:
{
uint32 RandomSpell[]={71492,71485,71484};
triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
break;
}
case CLASS_ROGUE:
{
uint32 RandomSpell[]={71492,71485,71486};
triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
break;
}
case CLASS_WARRIOR:
{
uint32 RandomSpell[]={71492,71484,71491};
triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
break;
}
case CLASS_SHAMAN:
{
uint32 RandomSpell[]={71485,71486,71492};
triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
break;
}
case CLASS_HUNTER:
{
uint32 RandomSpell[]={71485,71486,71491};
triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
break;
}
case CLASS_DEATH_KNIGHT:
{
uint32 RandomSpell[]={71484,71492,71491};
triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
break;
}
default:
return SPELL_AURA_PROC_FAILED;
}
break;
}
// Deathbringer's Will (Item - Icecrown 25 Heroic Melee Trinket)
//=====================================================
// 71560 Speed of the Vrykul: +700 haste rating (Death Knight, Druid, Paladin, Rogue, Warrior, Shaman)
// 71556 Agility of the Vrykul: +700 agility (Druid, Hunter, Rogue, Shaman)
// 71558 Power of the Taunka: +1400 attack power (Hunter, Rogue, Shaman)
// 71561 Strength of the Taunka: +700 strength (Death Knight, Druid, Paladin, Warrior)
// 71559 Aim of the Iron Dwarves: +700 critical strike rating (Death Knight, Hunter, Paladin, Warrior)
case 71562:
{
if(GetTypeId() != TYPEID_PLAYER)
return SPELL_AURA_PROC_FAILED;
if(HasAura(71559) || HasAura(71561) || HasAura(71560) || HasAura(71556) || HasAura(71558))
return SPELL_AURA_PROC_FAILED;
// Select class defined buff
switch (getClass())
{
case CLASS_PALADIN:
{
uint32 RandomSpell[]={71560,71561,71559};
triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
break;
}
case CLASS_DRUID:
{
uint32 RandomSpell[]={71560,71556,71561};
triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
break;
}
case CLASS_ROGUE:
{
uint32 RandomSpell[]={71560,71556,71558,};
triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
break;
}
case CLASS_WARRIOR:
{
uint32 RandomSpell[]={71560,71561,71559,};
triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
break;
}
case CLASS_SHAMAN:
{
uint32 RandomSpell[]={71556,71558,71560};
triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
break;
}
case CLASS_HUNTER:
{
uint32 RandomSpell[]={71556,71558,71559};
triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
break;
}
case CLASS_DEATH_KNIGHT:
{
uint32 RandomSpell[]={71561,71560,71559};
triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
break;
}
default:
return SPELL_AURA_PROC_FAILED;
}
break;
}
// Necrotic Touch item 50692
case 71875:
case 71877:
{
basepoints[0] = damage * triggerAmount / 100;
target = pVictim;
triggered_spell_id = 71879;
break;
}
}
break;
}
case SPELLFAMILY_MAGE:
{
// Magic Absorption
if (dummySpell->SpellIconID == 459) // only this spell have SpellIconID == 459 and dummy aura
{
if (getPowerType() != POWER_MANA)
return SPELL_AURA_PROC_FAILED;
// mana reward
basepoints[0] = (triggerAmount * GetMaxPower(POWER_MANA) / 100);
target = this;
triggered_spell_id = 29442;
break;
}
// Master of Elements
if (dummySpell->SpellIconID == 1920)
{
if(!procSpell)
return SPELL_AURA_PROC_FAILED;
// mana cost save
int32 cost = procSpell->manaCost + procSpell->ManaCostPercentage * GetCreateMana() / 100;
basepoints[0] = cost * triggerAmount/100;
if (basepoints[0] <=0)
return SPELL_AURA_PROC_FAILED;
target = this;
triggered_spell_id = 29077;
break;
}
// Arcane Potency
if (dummySpell->SpellIconID == 2120)
{
if(!procSpell || procSpell->Id == 44401)
return SPELL_AURA_PROC_FAILED;
target = this;
switch (dummySpell->Id)
{
case 31571: triggered_spell_id = 57529; break;
case 31572: triggered_spell_id = 57531; break;
default:
sLog.outError("Unit::HandleDummyAuraProc: non handled spell id: %u",dummySpell->Id);
return SPELL_AURA_PROC_FAILED;
}
break;
}
// Hot Streak
if (dummySpell->SpellIconID == 2999)
{
if (effIndex != EFFECT_INDEX_0)
return SPELL_AURA_PROC_OK;
Aura *counter = GetAura(triggeredByAura->GetId(), EFFECT_INDEX_1);
if (!counter)
return SPELL_AURA_PROC_OK;
// Count spell criticals in a row in second aura
Modifier *mod = counter->GetModifier();
if (procEx & PROC_EX_CRITICAL_HIT)
{
mod->m_amount *=2;
if (mod->m_amount < 100) // not enough
return SPELL_AURA_PROC_OK;
// Critical counted -> roll chance
if (roll_chance_i(triggerAmount))
CastSpell(this, 48108, true, castItem, triggeredByAura);
}
mod->m_amount = 25;
return SPELL_AURA_PROC_OK;
}
// Burnout
if (dummySpell->SpellIconID == 2998)
{
if(!procSpell)
return SPELL_AURA_PROC_FAILED;
int32 cost = procSpell->manaCost + procSpell->ManaCostPercentage * GetCreateMana() / 100;
basepoints[0] = cost * triggerAmount/100;
if (basepoints[0] <=0)
return SPELL_AURA_PROC_FAILED;
triggered_spell_id = 44450;
target = this;
break;
}
// Incanter's Regalia set (add trigger chance to Mana Shield)
if (dummySpell->SpellFamilyFlags & UI64LIT(0x0000000000008000))
{
if (GetTypeId() != TYPEID_PLAYER)
return SPELL_AURA_PROC_FAILED;
target = this;
triggered_spell_id = 37436;
break;
}
switch(dummySpell->Id)
{
// Ignite
case 11119:
case 11120:
case 12846:
case 12847:
case 12848:
{
switch (dummySpell->Id)
{
case 11119: basepoints[0] = int32(0.04f*damage); break;
case 11120: basepoints[0] = int32(0.08f*damage); break;
case 12846: basepoints[0] = int32(0.12f*damage); break;
case 12847: basepoints[0] = int32(0.16f*damage); break;
case 12848: basepoints[0] = int32(0.20f*damage); break;
default:
sLog.outError("Unit::HandleDummyAuraProc: non handled spell id: %u (IG)",dummySpell->Id);
return SPELL_AURA_PROC_FAILED;
}
triggered_spell_id = 12654;
break;
}
// Empowered Fire (mana regen)
case 12654:
{
Unit* caster = triggeredByAura->GetCaster();
// it should not be triggered from other ignites
if (caster && pVictim && caster->GetGUID() == pVictim->GetGUID())
{
Unit::AuraList const& auras = caster->GetAurasByType(SPELL_AURA_ADD_FLAT_MODIFIER);
for (Unit::AuraList::const_iterator i = auras.begin(); i != auras.end(); i++)
{
switch((*i)->GetId())
{
case 31656:
case 31657:
case 31658:
{
if(roll_chance_i(int32((*i)->GetSpellProto()->procChance)))
{
caster->CastSpell(caster, 67545, true);
return SPELL_AURA_PROC_OK;
}
else
return SPELL_AURA_PROC_FAILED;
}
}
}
}
return SPELL_AURA_PROC_FAILED;
}
// Arcane Blast proc-off only from arcane school and not from self
case 36032:
{
if(procSpell->EffectTriggerSpell[1] == 36032 || GetSpellSchoolMask(procSpell) != SPELL_SCHOOL_MASK_ARCANE)
return SPELL_AURA_PROC_FAILED;
}
// Glyph of Ice Block
case 56372:
{
if (GetTypeId() != TYPEID_PLAYER)
return SPELL_AURA_PROC_FAILED;
// not 100% safe with client version switches but for 3.1.3 no spells with cooldown that can have mage player except Frost Nova.
((Player*)this)->RemoveSpellCategoryCooldown(35, true);
return SPELL_AURA_PROC_OK;
}
// Glyph of Icy Veins
case 56374:
{
Unit::AuraList const& hasteAuras = GetAurasByType(SPELL_AURA_MOD_CASTING_SPEED_NOT_STACK);
for(Unit::AuraList::const_iterator i = hasteAuras.begin(); i != hasteAuras.end();)
{
if (!IsPositiveSpell((*i)->GetId()))
{
RemoveAurasDueToSpell((*i)->GetId());
i = hasteAuras.begin();
}
else
++i;
}
RemoveSpellsCausingAura(SPELL_AURA_HASTE_SPELLS);
RemoveSpellsCausingAura(SPELL_AURA_MOD_DECREASE_SPEED);
return SPELL_AURA_PROC_OK;
}
// Glyph of Polymorph
case 56375:
{
if (!pVictim || !pVictim->isAlive())
return SPELL_AURA_PROC_FAILED;
pVictim->RemoveSpellsCausingAura(SPELL_AURA_PERIODIC_DAMAGE);
pVictim->RemoveSpellsCausingAura(SPELL_AURA_PERIODIC_DAMAGE_PERCENT);
pVictim->RemoveSpellsCausingAura(SPELL_AURA_PERIODIC_LEECH);
return SPELL_AURA_PROC_OK;
}
// Blessing of Ancient Kings
case 64411:
{
// for DOT procs
if (!IsPositiveSpell(procSpell->Id))
return SPELL_AURA_PROC_FAILED;
triggered_spell_id = 64413;
basepoints[0] = damage * 15 / 100;
break;
}
}
break;
}
case SPELLFAMILY_WARRIOR:
{
// Retaliation
if (dummySpell->SpellFamilyFlags == UI64LIT(0x0000000800000000))
{
// check attack comes not from behind
if (!HasInArc(M_PI_F, pVictim))
return SPELL_AURA_PROC_FAILED;
triggered_spell_id = 22858;
break;
}
// Second Wind
if (dummySpell->SpellIconID == 1697)
{
// only for spells and hit/crit (trigger start always) and not start from self casted spells (5530 Mace Stun Effect for example)
if (procSpell == 0 || !(procEx & (PROC_EX_NORMAL_HIT|PROC_EX_CRITICAL_HIT)) || this == pVictim)
return SPELL_AURA_PROC_FAILED;
// Need stun or root mechanic
if (!(GetAllSpellMechanicMask(procSpell) & IMMUNE_TO_ROOT_AND_STUN_MASK))
return SPELL_AURA_PROC_FAILED;
switch (dummySpell->Id)
{
case 29838: triggered_spell_id=29842; break;
case 29834: triggered_spell_id=29841; break;
case 42770: triggered_spell_id=42771; break;
default:
sLog.outError("Unit::HandleDummyAuraProc: non handled spell id: %u (SW)",dummySpell->Id);
return SPELL_AURA_PROC_FAILED;
}
target = this;
break;
}
// Damage Shield
if (dummySpell->SpellIconID == 3214)
{
triggered_spell_id = 59653;
basepoints[0] = GetShieldBlockValue() * triggerAmount / 100;
break;
}
// Sweeping Strikes
if (dummySpell->Id == 12328)
{
// prevent chain of triggered spell from same triggered spell
if(procSpell && procSpell->Id == 26654)
return SPELL_AURA_PROC_FAILED;
target = SelectRandomUnfriendlyTarget(pVictim);
if(!target)
return SPELL_AURA_PROC_FAILED;
triggered_spell_id = 26654;
break;
}
// Glyph of Sunder Armor
if (dummySpell->Id == 58387)
{
if (!procSpell)
return SPELL_AURA_PROC_FAILED;
target = SelectRandomUnfriendlyTarget(pVictim);
if (!target)
return SPELL_AURA_PROC_FAILED;
triggered_spell_id = 58567;
break;
}
break;
}
case SPELLFAMILY_WARLOCK:
{
// Seed of Corruption
if (dummySpell->SpellFamilyFlags & UI64LIT(0x0000001000000000))
{
Modifier* mod = triggeredByAura->GetModifier();
// if damage is more than need or target die from damage deal finish spell
if( mod->m_amount <= (int32)damage || GetHealth() <= damage )
{
// remember guid before aura delete
ObjectGuid casterGuid = triggeredByAura->GetCasterGuid();
// Remove aura (before cast for prevent infinite loop handlers)
RemoveAurasDueToSpell(triggeredByAura->GetId());
// Cast finish spell (triggeredByAura already not exist!)
CastSpell(this, 27285, true, castItem, NULL, casterGuid);
return SPELL_AURA_PROC_OK; // no hidden cooldown
}
// Damage counting
mod->m_amount-=damage;
return SPELL_AURA_PROC_OK;
}
// Seed of Corruption (Mobs cast) - no die req
if (dummySpell->SpellFamilyFlags == UI64LIT(0x0) && dummySpell->SpellIconID == 1932)
{
Modifier* mod = triggeredByAura->GetModifier();
// if damage is more than need deal finish spell
if( mod->m_amount <= (int32)damage )
{
// remember guid before aura delete
ObjectGuid casterGuid = triggeredByAura->GetCasterGuid();
// Remove aura (before cast for prevent infinite loop handlers)
RemoveAurasDueToSpell(triggeredByAura->GetId());
// Cast finish spell (triggeredByAura already not exist!)
CastSpell(this, 32865, true, castItem, NULL, casterGuid);
return SPELL_AURA_PROC_OK; // no hidden cooldown
}
// Damage counting
mod->m_amount-=damage;
return SPELL_AURA_PROC_OK;
}
// Fel Synergy
if (dummySpell->SpellIconID == 3222)
{
target = GetPet();
if (!target)
return SPELL_AURA_PROC_FAILED;
basepoints[0] = damage * triggerAmount / 100;
triggered_spell_id = 54181;
break;
}
switch(dummySpell->Id)
{
// Nightfall & Glyph of Corruption
case 18094:
case 18095:
case 56218:
{
target = this;
triggered_spell_id = 17941;
break;
}
//Soul Leech
case 30293:
case 30295:
case 30296:
{
// health
basepoints[0] = int32(damage*triggerAmount/100);
target = this;
triggered_spell_id = 30294;
// check for Improved Soul Leech
AuraList const& pDummyAuras = GetAurasByType(SPELL_AURA_DUMMY);
for (AuraList::const_iterator itr = pDummyAuras.begin(); itr != pDummyAuras.end(); ++itr)
{
SpellEntry const* spellInfo = (*itr)->GetSpellProto();
if (spellInfo->SpellFamilyName != SPELLFAMILY_WARLOCK || (*itr)->GetSpellProto()->SpellIconID != 3176)
continue;
if ((*itr)->GetEffIndex() == SpellEffectIndex(0))
{
// energize Proc pet (implicit target is pet)
CastCustomSpell(this, 59118, &((*itr)->GetModifier()->m_amount), NULL, NULL, true, NULL, (*itr));
// energize Proc master
CastCustomSpell(this, 59117, &((*itr)->GetModifier()->m_amount), NULL, NULL, true, NULL, (*itr));
}
else if (roll_chance_i((*itr)->GetModifier()->m_amount))
{
// Replenishment proc
CastSpell(this, 57669, true, NULL, (*itr));
}
}
break;
}
// Shadowflame (Voidheart Raiment set bonus)
case 37377:
{
triggered_spell_id = 37379;
break;
}
// Pet Healing (Corruptor Raiment or Rift Stalker Armor)
case 37381:
{
target = GetPet();
if (!target)
return SPELL_AURA_PROC_FAILED;
// heal amount
basepoints[0] = damage * triggerAmount/100;
triggered_spell_id = 37382;
break;
}
// Shadowflame Hellfire (Voidheart Raiment set bonus)
case 39437:
{
triggered_spell_id = 37378;
break;
}
// Siphon Life
case 63108:
{
// Glyph of Siphon Life
if (Aura *aur = GetAura(56216, EFFECT_INDEX_0))
triggerAmount += triggerAmount * aur->GetModifier()->m_amount / 100;
basepoints[0] = int32(damage * triggerAmount / 100);
triggered_spell_id = 63106;
break;
}
}
break;
}
case SPELLFAMILY_PRIEST:
{
// Vampiric Touch
if (dummySpell->SpellFamilyFlags & UI64LIT(0x0000040000000000))
{
if (!pVictim || !pVictim->isAlive())
return SPELL_AURA_PROC_FAILED;
// pVictim is caster of aura
if (triggeredByAura->GetCasterGuid() != pVictim->GetObjectGuid())
return SPELL_AURA_PROC_FAILED;
// Energize 0.25% of max. mana
pVictim->CastSpell(pVictim, 57669, true, castItem, triggeredByAura);
return SPELL_AURA_PROC_OK; // no hidden cooldown
}
switch(dummySpell->SpellIconID)
{
// Improved Shadowform
case 217:
{
if(!roll_chance_i(triggerAmount))
return SPELL_AURA_PROC_FAILED;
RemoveSpellsCausingAura(SPELL_AURA_MOD_ROOT);
RemoveSpellsCausingAura(SPELL_AURA_MOD_DECREASE_SPEED);
break;
}
// Divine Aegis
case 2820:
{
if(!pVictim || !pVictim->isAlive())
return SPELL_AURA_PROC_FAILED;
// find Divine Aegis on the target and get absorb amount
Aura* DivineAegis = pVictim->GetAura(47753,EFFECT_INDEX_0);
if (DivineAegis)
basepoints[0] = DivineAegis->GetModifier()->m_amount;
basepoints[0] += damage * triggerAmount/100;
// limit absorb amount
int32 levelbonus = pVictim->getLevel()*125;
if (basepoints[0] > levelbonus)
basepoints[0] = levelbonus;
triggered_spell_id = 47753;
break;
}
// Empowered Renew
case 3021:
{
if (!procSpell)
return SPELL_AURA_PROC_FAILED;
// Renew
Aura* healingAura = pVictim->GetAura(SPELL_AURA_PERIODIC_HEAL, SPELLFAMILY_PRIEST, UI64LIT(0x40), 0, GetGUID());
if (!healingAura)
return SPELL_AURA_PROC_FAILED;
int32 healingfromticks = healingAura->GetModifier()->m_amount * GetSpellAuraMaxTicks(procSpell);
basepoints[0] = healingfromticks * triggerAmount / 100;
triggered_spell_id = 63544;
break;
}
// Improved Devouring Plague
case 3790:
{
if (!procSpell)
return SPELL_AURA_PROC_FAILED;
Aura* leachAura = pVictim->GetAura(SPELL_AURA_PERIODIC_LEECH, SPELLFAMILY_PRIEST, UI64LIT(0x02000000), 0, GetGUID());
if (!leachAura)
return SPELL_AURA_PROC_FAILED;
int32 damagefromticks = leachAura->GetModifier()->m_amount * GetSpellAuraMaxTicks(procSpell);
basepoints[0] = damagefromticks * triggerAmount / 100;
triggered_spell_id = 63675;
break;
}
}
switch(dummySpell->Id)
{
// Vampiric Embrace
case 15286:
{
// Return if self damage
if (this == pVictim)
return SPELL_AURA_PROC_FAILED;
// Heal amount - Self/Team
int32 team = triggerAmount*damage/500;
int32 self = triggerAmount*damage/100 - team;
CastCustomSpell(this,15290,&team,&self,NULL,true,castItem,triggeredByAura);
return SPELL_AURA_PROC_OK; // no hidden cooldown
}
// Priest Tier 6 Trinket (Ashtongue Talisman of Acumen)
case 40438:
{
// Shadow Word: Pain
if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000008000))
triggered_spell_id = 40441;
// Renew
else if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000010))
triggered_spell_id = 40440;
else
return SPELL_AURA_PROC_FAILED;
target = this;
break;
}
// Oracle Healing Bonus ("Garments of the Oracle" set)
case 26169:
{
// heal amount
basepoints[0] = int32(damage * 10/100);
target = this;
triggered_spell_id = 26170;
break;
}
// Frozen Shadoweave (Shadow's Embrace set) warning! its not only priest set
case 39372:
{
if(!procSpell || (GetSpellSchoolMask(procSpell) & (SPELL_SCHOOL_MASK_FROST | SPELL_SCHOOL_MASK_SHADOW))==0 )
return SPELL_AURA_PROC_FAILED;
// heal amount
basepoints[0] = damage * triggerAmount/100;
target = this;
triggered_spell_id = 39373;
break;
}
// Greater Heal (Vestments of Faith (Priest Tier 3) - 4 pieces bonus)
case 28809:
{
triggered_spell_id = 28810;
break;
}
// Glyph of Dispel Magic
case 55677:
{
if(!target->IsFriendlyTo(this))
return SPELL_AURA_PROC_FAILED;
if (target->GetTypeId() == TYPEID_PLAYER)
basepoints[0] = int32(target->GetMaxHealth() * triggerAmount / 100);
else if (Unit* caster = triggeredByAura->GetCaster())
basepoints[0] = int32(caster->GetMaxHealth() * triggerAmount / 100);
// triggered_spell_id in spell data
break;
}
// Item - Priest T10 Healer 4P Bonus
case 70799:
{
if (GetTypeId() != TYPEID_PLAYER)
return SPELL_AURA_PROC_FAILED;
// Circle of Healing
((Player*)this)->RemoveSpellCategoryCooldown(1204, true);
// Penance
((Player*)this)->RemoveSpellCategoryCooldown(1230, true);
return SPELL_AURA_PROC_OK;
}
// Glyph of Prayer of Healing
case 55680:
{
basepoints[0] = int32(damage * triggerAmount / 200); // 10% each tick
triggered_spell_id = 56161;
break;
}
}
break;
}
case SPELLFAMILY_DRUID:
{
switch(dummySpell->Id)
{
// Leader of the Pack
case 24932:
{
// dummy m_amount store health percent (!=0 if Improved Leader of the Pack applied)
int32 heal_percent = triggeredByAura->GetModifier()->m_amount;
if (!heal_percent)
return SPELL_AURA_PROC_FAILED;
// check explicitly only to prevent mana cast when halth cast cooldown
if (cooldown && ((Player*)this)->HasSpellCooldown(34299))
return SPELL_AURA_PROC_FAILED;
// health
triggered_spell_id = 34299;
basepoints[0] = GetMaxHealth() * heal_percent / 100;
target = this;
// mana to caster
if (triggeredByAura->GetCasterGuid() == GetObjectGuid())
{
if (SpellEntry const* manaCastEntry = sSpellStore.LookupEntry(60889))
{
int32 mana_percent = manaCastEntry->CalculateSimpleValue(EFFECT_INDEX_0) * heal_percent;
CastCustomSpell(this, manaCastEntry, &mana_percent, NULL, NULL, true, castItem, triggeredByAura);
}
}
break;
}
// Healing Touch (Dreamwalker Raiment set)
case 28719:
{
// mana back
basepoints[0] = int32(procSpell->manaCost * 30 / 100);
target = this;
triggered_spell_id = 28742;
break;
}
// Healing Touch Refund (Idol of Longevity trinket)
case 28847:
{
target = this;
triggered_spell_id = 28848;
break;
}
// Mana Restore (Malorne Raiment set / Malorne Regalia set)
case 37288:
case 37295:
{
target = this;
triggered_spell_id = 37238;
break;
}
// Druid Tier 6 Trinket
case 40442:
{
float chance;
// Starfire
if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000004))
{
triggered_spell_id = 40445;
chance = 25.0f;
}
// Rejuvenation
else if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000010))
{
triggered_spell_id = 40446;
chance = 25.0f;
}
// Mangle (Bear) and Mangle (Cat)
else if (procSpell->SpellFamilyFlags & UI64LIT(0x0000044000000000))
{
triggered_spell_id = 40452;
chance = 40.0f;
}
else
return SPELL_AURA_PROC_FAILED;
if (!roll_chance_f(chance))
return SPELL_AURA_PROC_FAILED;
target = this;
break;
}
// Maim Interrupt
case 44835:
{
// Deadly Interrupt Effect
triggered_spell_id = 32747;
break;
}
// Glyph of Starfire
case 54845:
{
triggered_spell_id = 54846;
break;
}
// Glyph of Shred
case 54815:
{
triggered_spell_id = 63974;
break;
}
// Glyph of Rejuvenation
case 54754:
{
// less 50% health
if (pVictim->GetMaxHealth() < 2 * pVictim->GetHealth())
return SPELL_AURA_PROC_FAILED;
basepoints[0] = triggerAmount * damage / 100;
triggered_spell_id = 54755;
break;
}
// Glyph of Rake
case 54821:
{
triggered_spell_id = 54820;
break;
}
// Item - Druid T10 Restoration 4P Bonus (Rejuvenation)
case 70664:
{
if (!procSpell || GetTypeId() != TYPEID_PLAYER)
return SPELL_AURA_PROC_FAILED;
float radius;
if (procSpell->EffectRadiusIndex[EFFECT_INDEX_0])
radius = GetSpellRadius(sSpellRadiusStore.LookupEntry(procSpell->EffectRadiusIndex[EFFECT_INDEX_0]));
else
radius = GetSpellMaxRange(sSpellRangeStore.LookupEntry(procSpell->rangeIndex));
((Player*)this)->ApplySpellMod(procSpell->Id, SPELLMOD_RADIUS, radius,NULL);
Unit *second = pVictim->SelectRandomFriendlyTarget(pVictim, radius);
if (!second)
return SPELL_AURA_PROC_FAILED;
pVictim->CastSpell(second, procSpell, true, NULL, triggeredByAura, GetGUID());
return SPELL_AURA_PROC_OK;
}
// Item - Druid T10 Balance 4P Bonus
case 70723:
{
basepoints[0] = int32( triggerAmount * damage / 100 );
basepoints[0] = int32( basepoints[0] / 2);
triggered_spell_id = 71023;
break;
}
}
// King of the Jungle
if (dummySpell->SpellIconID == 2850)
{
switch (effIndex)
{
case EFFECT_INDEX_0: // Enrage (bear)
{
// note : aura removal is done in SpellAuraHolder::HandleSpellSpecificBoosts
basepoints[0] = triggerAmount;
triggered_spell_id = 51185;
break;
}
case EFFECT_INDEX_1: // Tiger's Fury (cat)
{
basepoints[0] = triggerAmount;
triggered_spell_id = 51178;
break;
}
default:
return SPELL_AURA_PROC_FAILED;
}
}
// Eclipse
else if (dummySpell->SpellIconID == 2856)
{
if (!procSpell)
return SPELL_AURA_PROC_FAILED;
// Wrath crit
if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000001))
{
if (HasAura(48517))
return SPELL_AURA_PROC_FAILED;
if (!roll_chance_i(60))
return SPELL_AURA_PROC_FAILED;
triggered_spell_id = 48518;
target = this;
break;
}
// Starfire crit
if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000004))
{
if (HasAura(48518))
return SPELL_AURA_PROC_FAILED;
triggered_spell_id = 48517;
target = this;
break;
}
return SPELL_AURA_PROC_FAILED;
}
// Living Seed
else if (dummySpell->SpellIconID == 2860)
{
triggered_spell_id = 48504;
basepoints[0] = triggerAmount * damage / 100;
break;
}
break;
}
case SPELLFAMILY_ROGUE:
{
switch(dummySpell->Id)
{
// Clean Escape
case 23582:
// triggered spell have same masks and etc with main Vanish spell
if (!procSpell || procSpell->Effect[EFFECT_INDEX_0] == SPELL_EFFECT_NONE)
return SPELL_AURA_PROC_FAILED;
triggered_spell_id = 23583;
break;
// Deadly Throw Interrupt
case 32748:
{
// Prevent cast Deadly Throw Interrupt on self from last effect (apply dummy) of Deadly Throw
if (this == pVictim)
return SPELL_AURA_PROC_FAILED;
triggered_spell_id = 32747;
break;
}
// Glyph of Backstab
case 56800:
{
if (Aura* aura = target->GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_ROGUE, UI64LIT(0x00100000), 0, GetGUID()))
{
uint32 countMin = aura->GetAuraMaxDuration();
uint32 countMax = GetSpellMaxDuration(aura->GetSpellProto());
countMax += 3 * triggerAmount * 1000;
countMax += HasAura(56801) ? 4000 : 0;
if (countMin < countMax)
{
aura->SetAuraDuration(aura->GetAuraDuration() + triggerAmount * 1000);
aura->SetAuraMaxDuration(countMin + triggerAmount * 1000);
aura->GetHolder()->SendAuraUpdate(false);
return SPELL_AURA_PROC_OK;
}
}
return SPELL_AURA_PROC_FAILED;
}
// Tricks of the trade
case 57934:
{
triggered_spell_id = 57933; // Tricks of the Trade, increased damage buff
target = getHostileRefManager().GetThreatRedirectionTarget();
if (!target)
return SPELL_AURA_PROC_FAILED;
CastSpell(this, 59628, true); // Tricks of the Trade (caster timer)
break;
}
}
// Cut to the Chase
if (dummySpell->SpellIconID == 2909)
{
// "refresh your Slice and Dice duration to its 5 combo point maximum"
// lookup Slice and Dice
AuraList const& sd = GetAurasByType(SPELL_AURA_MOD_MELEE_HASTE);
for(AuraList::const_iterator itr = sd.begin(); itr != sd.end(); ++itr)
{
SpellEntry const *spellProto = (*itr)->GetSpellProto();
if (spellProto->SpellFamilyName == SPELLFAMILY_ROGUE &&
(spellProto->SpellFamilyFlags & UI64LIT(0x0000000000040000)))
{
int32 duration = GetSpellMaxDuration(spellProto);
if(GetTypeId() == TYPEID_PLAYER)
static_cast<Player*>(this)->ApplySpellMod(spellProto->Id, SPELLMOD_DURATION, duration);
(*itr)->SetAuraMaxDuration(duration);
(*itr)->GetHolder()->RefreshHolder();
return SPELL_AURA_PROC_OK;
}
}
return SPELL_AURA_PROC_FAILED;
}
// Deadly Brew
if (dummySpell->SpellIconID == 2963)
{
triggered_spell_id = 44289;
break;
}
// Quick Recovery
if (dummySpell->SpellIconID == 2116)
{
if(!procSpell)
return SPELL_AURA_PROC_FAILED;
//do not proc from spells that do not need combo points
if(!NeedsComboPoints(procSpell))
return SPELL_AURA_PROC_FAILED;
// energy cost save
basepoints[0] = procSpell->manaCost * triggerAmount/100;
if (basepoints[0] <= 0)
return SPELL_AURA_PROC_FAILED;
target = this;
triggered_spell_id = 31663;
break;
}
break;
}
case SPELLFAMILY_HUNTER:
{
// Thrill of the Hunt
if (dummySpell->SpellIconID == 2236)
{
if (!procSpell)
return SPELL_AURA_PROC_FAILED;
// mana cost save
int32 mana = procSpell->manaCost + procSpell->ManaCostPercentage * GetCreateMana() / 100;
basepoints[0] = mana * 40/100;
if (basepoints[0] <= 0)
return SPELL_AURA_PROC_FAILED;
target = this;
triggered_spell_id = 34720;
break;
}
// Hunting Party
if (dummySpell->SpellIconID == 3406)
{
triggered_spell_id = 57669;
target = this;
break;
}
// Lock and Load
if ( dummySpell->SpellIconID == 3579 )
{
// Proc only from periodic (from trap activation proc another aura of this spell)
if (!(procFlag & PROC_FLAG_ON_DO_PERIODIC) || !roll_chance_i(triggerAmount))
return SPELL_AURA_PROC_FAILED;
triggered_spell_id = 56453;
target = this;
break;
}
// Rapid Recuperation
if ( dummySpell->SpellIconID == 3560 )
{
// This effect only from Rapid Killing (mana regen)
if (!(procSpell->SpellFamilyFlags & UI64LIT(0x0100000000000000)))
return SPELL_AURA_PROC_FAILED;
target = this;
switch(dummySpell->Id)
{
case 53228: // Rank 1
triggered_spell_id = 56654;
break;
case 53232: // Rank 2
triggered_spell_id = 58882;
break;
}
break;
}
// Glyph of Mend Pet
if(dummySpell->Id == 57870)
{
pVictim->CastSpell(pVictim, 57894, true, NULL, NULL, GetGUID());
return SPELL_AURA_PROC_OK;
}
// Misdirection
else if(dummySpell->Id == 34477)
{
triggered_spell_id = 35079; // 4 sec buff on self
target = this;
break;
}
// Guard Dog
else if (dummySpell->SpellIconID == 201 && procSpell->SpellIconID == 201)
{
triggered_spell_id = 54445;
target = this;
if (pVictim)
pVictim->AddThreat(this,procSpell->EffectBasePoints[0] * triggerAmount / 100.0f);
break;
}
break;
}
case SPELLFAMILY_PALADIN:
{
// Seal of Righteousness - melee proc dummy (addition ${$MWS*(0.022*$AP+0.044*$SPH)} damage)
if ((dummySpell->SpellFamilyFlags & UI64LIT(0x000000008000000)) && effIndex == EFFECT_INDEX_0)
{
triggered_spell_id = 25742;
float ap = GetTotalAttackPowerValue(BASE_ATTACK);
int32 holy = SpellBaseDamageBonusDone(SPELL_SCHOOL_MASK_HOLY);
if (holy < 0)
holy = 0;
basepoints[0] = GetAttackTime(BASE_ATTACK) * int32(ap*0.022f + 0.044f * holy) / 1000;
break;
}
// Righteous Vengeance
if (dummySpell->SpellIconID == 3025)
{
// 4 damage tick
basepoints[0] = triggerAmount*damage/400;
triggered_spell_id = 61840;
break;
}
// Sheath of Light
if (dummySpell->SpellIconID == 3030)
{
// 4 healing tick
basepoints[0] = triggerAmount*damage/400;
triggered_spell_id = 54203;
break;
}
switch(dummySpell->Id)
{
// Judgement of Light
case 20185:
{
if (pVictim == this)
return SPELL_AURA_PROC_FAILED;
basepoints[0] = int32( pVictim->GetMaxHealth() * triggeredByAura->GetModifier()->m_amount / 100 );
pVictim->CastCustomSpell(pVictim, 20267, &basepoints[0], NULL, NULL, true, NULL, triggeredByAura);
return SPELL_AURA_PROC_OK;
}
// Judgement of Wisdom
case 20186:
{
if (pVictim->getPowerType() == POWER_MANA)
{
// 2% of maximum base mana
basepoints[0] = int32(pVictim->GetCreateMana() * 2 / 100);
pVictim->CastCustomSpell(pVictim, 20268, &basepoints[0], NULL, NULL, true, NULL, triggeredByAura);
}
return SPELL_AURA_PROC_OK;
}
// Heart of the Crusader (Rank 1)
case 20335:
triggered_spell_id = 21183;
break;
// Heart of the Crusader (Rank 2)
case 20336:
triggered_spell_id = 54498;
break;
// Heart of the Crusader (Rank 3)
case 20337:
triggered_spell_id = 54499;
break;
case 20911: // Blessing of Sanctuary
case 25899: // Greater Blessing of Sanctuary
{
target = this;
switch (target->getPowerType())
{
case POWER_MANA:
triggered_spell_id = 57319;
break;
default:
return SPELL_AURA_PROC_FAILED;
}
break;
}
// Holy Power (Redemption Armor set)
case 28789:
{
if(!pVictim)
return SPELL_AURA_PROC_FAILED;
// Set class defined buff
switch (pVictim->getClass())
{
case CLASS_PALADIN:
case CLASS_PRIEST:
case CLASS_SHAMAN:
case CLASS_DRUID:
triggered_spell_id = 28795; // Increases the friendly target's mana regeneration by $s1 per 5 sec. for $d.
break;
case CLASS_MAGE:
case CLASS_WARLOCK:
triggered_spell_id = 28793; // Increases the friendly target's spell damage and healing by up to $s1 for $d.
break;
case CLASS_HUNTER:
case CLASS_ROGUE:
triggered_spell_id = 28791; // Increases the friendly target's attack power by $s1 for $d.
break;
case CLASS_WARRIOR:
triggered_spell_id = 28790; // Increases the friendly target's armor
break;
default:
return SPELL_AURA_PROC_FAILED;
}
break;
}
// Spiritual Attunement
case 31785:
case 33776:
{
// if healed by another unit (pVictim)
if (this == pVictim)
return SPELL_AURA_PROC_FAILED;
// dont count overhealing
uint32 diff = GetMaxHealth()-GetHealth();
if (!diff)
return SPELL_AURA_PROC_FAILED;
if (damage > diff)
basepoints[0] = triggerAmount*diff/100;
else
basepoints[0] = triggerAmount*damage/100;
target = this;
triggered_spell_id = 31786;
break;
}
// Seal of Vengeance (damage calc on apply aura)
case 31801:
{
if (effIndex != EFFECT_INDEX_0) // effect 1,2 used by seal unleashing code
return SPELL_AURA_PROC_FAILED;
// At melee attack or Hammer of the Righteous spell damage considered as melee attack
if ((procFlag & PROC_FLAG_SUCCESSFUL_MELEE_HIT) || (procSpell && procSpell->Id == 53595) )
triggered_spell_id = 31803; // Holy Vengeance
// Add 5-stack effect from Holy Vengeance
uint32 stacks = 0;
AuraList const& auras = target->GetAurasByType(SPELL_AURA_PERIODIC_DAMAGE);
for(AuraList::const_iterator itr = auras.begin(); itr!=auras.end(); ++itr)
{
if (((*itr)->GetId() == 31803) && (*itr)->GetCasterGuid() == GetObjectGuid())
{
stacks = (*itr)->GetStackAmount();
break;
}
}
if (stacks >= 5)
CastSpell(target,42463,true,NULL,triggeredByAura);
break;
}
// Judgements of the Wise
case 31876:
case 31877:
case 31878:
// triggered only at casted Judgement spells, not at additional Judgement effects
if(!procSpell || procSpell->Category != 1210)
return SPELL_AURA_PROC_FAILED;
target = this;
triggered_spell_id = 31930;
// Replenishment
CastSpell(this, 57669, true, NULL, triggeredByAura);
break;
// Paladin Tier 6 Trinket (Ashtongue Talisman of Zeal)
case 40470:
{
if (!procSpell)
return SPELL_AURA_PROC_FAILED;
float chance;
// Flash of light/Holy light
if (procSpell->SpellFamilyFlags & UI64LIT(0x00000000C0000000))
{
triggered_spell_id = 40471;
chance = 15.0f;
}
// Judgement (any)
else if (GetSpellSpecific(procSpell->Id)==SPELL_JUDGEMENT)
{
triggered_spell_id = 40472;
chance = 50.0f;
}
else
return SPELL_AURA_PROC_FAILED;
if (!roll_chance_f(chance))
return SPELL_AURA_PROC_FAILED;
break;
}
// Light's Beacon (heal target area aura)
case 53651:
{
// not do bonus heal for explicit beacon focus healing
if (GetObjectGuid() == triggeredByAura->GetCasterGuid())
return SPELL_AURA_PROC_FAILED;
// beacon
Unit* beacon = triggeredByAura->GetCaster();
if (!beacon)
return SPELL_AURA_PROC_FAILED;
if (procSpell->Id == 20267)
return SPELL_AURA_PROC_FAILED;
// find caster main aura at beacon
Aura* dummy = NULL;
Unit::AuraList const& baa = beacon->GetAurasByType(SPELL_AURA_PERIODIC_TRIGGER_SPELL);
for(Unit::AuraList::const_iterator i = baa.begin(); i != baa.end(); ++i)
{
if ((*i)->GetId() == 53563 && (*i)->GetCasterGuid() == pVictim->GetObjectGuid())
{
dummy = (*i);
break;
}
}
// original heal must be form beacon caster
if (!dummy)
return SPELL_AURA_PROC_FAILED;
triggered_spell_id = 53652; // Beacon of Light
basepoints[0] = triggeredByAura->GetModifier()->m_amount*damage/100;
// cast with original caster set but beacon to beacon for apply caster mods and avoid LoS check
beacon->CastCustomSpell(beacon,triggered_spell_id,&basepoints[0],NULL,NULL,true,castItem,triggeredByAura,pVictim->GetGUID());
return SPELL_AURA_PROC_OK;
}
// Seal of Corruption (damage calc on apply aura)
case 53736:
{
if (effIndex != EFFECT_INDEX_0) // effect 1,2 used by seal unleashing code
return SPELL_AURA_PROC_FAILED;
// At melee attack or Hammer of the Righteous spell damage considered as melee attack
if ((procFlag & PROC_FLAG_SUCCESSFUL_MELEE_HIT) || (procSpell && procSpell->Id == 53595))
triggered_spell_id = 53742; // Blood Corruption
// Add 5-stack effect from Blood Corruption
uint32 stacks = 0;
AuraList const& auras = target->GetAurasByType(SPELL_AURA_PERIODIC_DAMAGE);
for(AuraList::const_iterator itr = auras.begin(); itr!=auras.end(); ++itr)
{
if (((*itr)->GetId() == 53742) && (*itr)->GetCasterGuid() == GetObjectGuid())
{
stacks = (*itr)->GetStackAmount();
break;
}
}
if (stacks >= 5)
CastSpell(target,53739,true,NULL,triggeredByAura);
break;
}
// Glyph of Holy Light
case 54937:
{
triggered_spell_id = 54968;
basepoints[0] = triggerAmount*damage/100;
break;
}
// Sacred Shield (buff)
case 58597:
{
triggered_spell_id = 66922;
SpellEntry const* triggeredEntry = sSpellStore.LookupEntry(triggered_spell_id);
if (!triggeredEntry)
return SPELL_AURA_PROC_FAILED;
if(pVictim)
if(!pVictim->HasAura(53569, EFFECT_INDEX_0) && !pVictim->HasAura(53576, EFFECT_INDEX_0))
return SPELL_AURA_PROC_FAILED;
basepoints[0] = int32(damage / (GetSpellDuration(triggeredEntry) / triggeredEntry->EffectAmplitude[EFFECT_INDEX_0]));
target = this;
break;
}
// Sacred Shield (talent rank)
case 53601:
{
// triggered_spell_id in spell data
target = this;
break;
}
// Item - Paladin T10 Holy 2P Bonus
case 70755:
{
triggered_spell_id = 71166;
break;
}
// Item - Paladin T10 Retribution 2P Bonus
case 70765:
{
if (GetTypeId() != TYPEID_PLAYER)
return SPELL_AURA_PROC_FAILED;
((Player*)this)->RemoveSpellCooldown(53385, true);
return SPELL_AURA_PROC_OK;
}
// Anger Capacitor
case 71406: // normal
case 71545: // heroic
{
if (!pVictim)
return SPELL_AURA_PROC_FAILED;
SpellEntry const* mote = sSpellStore.LookupEntry(71432);
if (!mote)
return SPELL_AURA_PROC_FAILED;
uint32 maxStack = mote->StackAmount - (dummySpell->Id == 71545 ? 1 : 0);
SpellAuraHolder *aurHolder = GetSpellAuraHolder(71432);
if (aurHolder && uint32(aurHolder->GetStackAmount() +1) >= maxStack)
{
RemoveAurasDueToSpell(71432); // Mote of Anger
// Manifest Anger (main hand/off hand)
CastSpell(pVictim, !haveOffhandWeapon() || roll_chance_i(50) ? 71433 : 71434, true);
return SPELL_AURA_PROC_OK;
}
else
triggered_spell_id = 71432;
break;
}
// Heartpierce, Item - Icecrown 25 Normal Dagger Proc
case 71880:
{
if(GetTypeId() != TYPEID_PLAYER)
return SPELL_AURA_PROC_FAILED;
switch (this->getPowerType())
{
case POWER_ENERGY: triggered_spell_id = 71882; break;
case POWER_RAGE: triggered_spell_id = 71883; break;
case POWER_MANA: triggered_spell_id = 71881; break;
default:
return SPELL_AURA_PROC_FAILED;
}
break;
}
// Heartpierce, Item - Icecrown 25 Heroic Dagger Proc
case 71892:
{
if(GetTypeId() != TYPEID_PLAYER)
return SPELL_AURA_PROC_FAILED;
switch (this->getPowerType())
{
case POWER_ENERGY: triggered_spell_id = 71887; break;
case POWER_RAGE: triggered_spell_id = 71886; break;
case POWER_MANA: triggered_spell_id = 71888; break;
default:
return SPELL_AURA_PROC_FAILED;
}
break;
}
}
break;
}
case SPELLFAMILY_SHAMAN:
{
switch(dummySpell->Id)
{
// Totemic Power (The Earthshatterer set)
case 28823:
{
if (!pVictim)
return SPELL_AURA_PROC_FAILED;
// Set class defined buff
switch (pVictim->getClass())
{
case CLASS_PALADIN:
case CLASS_PRIEST:
case CLASS_SHAMAN:
case CLASS_DRUID:
triggered_spell_id = 28824; // Increases the friendly target's mana regeneration by $s1 per 5 sec. for $d.
break;
case CLASS_MAGE:
case CLASS_WARLOCK:
triggered_spell_id = 28825; // Increases the friendly target's spell damage and healing by up to $s1 for $d.
break;
case CLASS_HUNTER:
case CLASS_ROGUE:
triggered_spell_id = 28826; // Increases the friendly target's attack power by $s1 for $d.
break;
case CLASS_WARRIOR:
triggered_spell_id = 28827; // Increases the friendly target's armor
break;
default:
return SPELL_AURA_PROC_FAILED;
}
break;
}
// Lesser Healing Wave (Totem of Flowing Water Relic)
case 28849:
{
target = this;
triggered_spell_id = 28850;
break;
}
// Windfury Weapon (Passive) 1-5 Ranks
case 33757:
{
if(GetTypeId()!=TYPEID_PLAYER)
return SPELL_AURA_PROC_FAILED;
if(!castItem || !castItem->IsEquipped())
return SPELL_AURA_PROC_FAILED;
// custom cooldown processing case
if (cooldown && ((Player*)this)->HasSpellCooldown(dummySpell->Id))
return SPELL_AURA_PROC_FAILED;
// Now amount of extra power stored in 1 effect of Enchant spell
// Get it by item enchant id
uint32 spellId;
switch (castItem->GetEnchantmentId(EnchantmentSlot(TEMP_ENCHANTMENT_SLOT)))
{
case 283: spellId = 8232; break; // 1 Rank
case 284: spellId = 8235; break; // 2 Rank
case 525: spellId = 10486; break; // 3 Rank
case 1669:spellId = 16362; break; // 4 Rank
case 2636:spellId = 25505; break; // 5 Rank
case 3785:spellId = 58801; break; // 6 Rank
case 3786:spellId = 58803; break; // 7 Rank
case 3787:spellId = 58804; break; // 8 Rank
default:
{
sLog.outError("Unit::HandleDummyAuraProc: non handled item enchantment (rank?) %u for spell id: %u (Windfury)",
castItem->GetEnchantmentId(EnchantmentSlot(TEMP_ENCHANTMENT_SLOT)),dummySpell->Id);
return SPELL_AURA_PROC_FAILED;
}
}
SpellEntry const* windfurySpellEntry = sSpellStore.LookupEntry(spellId);
if(!windfurySpellEntry)
{
sLog.outError("Unit::HandleDummyAuraProc: nonexistent spell id: %u (Windfury)",spellId);
return SPELL_AURA_PROC_FAILED;
}
int32 extra_attack_power = CalculateSpellDamage(pVictim, windfurySpellEntry, EFFECT_INDEX_1);
// Totem of Splintering
if (Aura* aura = GetAura(60764, EFFECT_INDEX_0))
extra_attack_power += aura->GetModifier()->m_amount;
// Off-Hand case
if (castItem->GetSlot() == EQUIPMENT_SLOT_OFFHAND)
{
// Value gained from additional AP
basepoints[0] = int32(extra_attack_power/14.0f * GetAttackTime(OFF_ATTACK)/1000/2);
triggered_spell_id = 33750;
}
// Main-Hand case
else
{
// Value gained from additional AP
basepoints[0] = int32(extra_attack_power/14.0f * GetAttackTime(BASE_ATTACK)/1000);
triggered_spell_id = 25504;
}
// apply cooldown before cast to prevent processing itself
if( cooldown )
((Player*)this)->AddSpellCooldown(dummySpell->Id,0,time(NULL) + cooldown);
// Attack Twice
for ( uint32 i = 0; i<2; ++i )
CastCustomSpell(pVictim,triggered_spell_id,&basepoints[0],NULL,NULL,true,castItem,triggeredByAura);
return SPELL_AURA_PROC_OK;
}
// Shaman Tier 6 Trinket
case 40463:
{
if (!procSpell)
return SPELL_AURA_PROC_FAILED;
float chance;
if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000001))
{
triggered_spell_id = 40465; // Lightning Bolt
chance = 15.0f;
}
else if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000080))
{
triggered_spell_id = 40465; // Lesser Healing Wave
chance = 10.0f;
}
else if (procSpell->SpellFamilyFlags & UI64LIT(0x0000001000000000))
{
triggered_spell_id = 40466; // Stormstrike
chance = 50.0f;
}
else
return SPELL_AURA_PROC_FAILED;
if (!roll_chance_f(chance))
return SPELL_AURA_PROC_FAILED;
target = this;
break;
}
// Earthen Power
case 51523:
case 51524:
{
triggered_spell_id = 63532;
break;
}
// Glyph of Healing Wave
case 55440:
{
// Not proc from self heals
if (this==pVictim)
return SPELL_AURA_PROC_FAILED;
basepoints[0] = triggerAmount * damage / 100;
target = this;
triggered_spell_id = 55533;
break;
}
// Spirit Hunt
case 58877:
{
// Cast on owner
target = GetOwner();
if (!target)
return SPELL_AURA_PROC_FAILED;
basepoints[0] = triggerAmount * damage / 100;
triggered_spell_id = 58879;
break;
}
// Glyph of Totem of Wrath
case 63280:
{
Totem* totem = GetTotem(TOTEM_SLOT_FIRE);
if (!totem)
return SPELL_AURA_PROC_FAILED;
// find totem aura bonus
AuraList const& spellPower = totem->GetAurasByType(SPELL_AURA_NONE);
for(AuraList::const_iterator i = spellPower.begin();i != spellPower.end(); ++i)
{
// select proper aura for format aura type in spell proto
if ((*i)->GetTarget()==totem && (*i)->GetSpellProto()->EffectApplyAuraName[(*i)->GetEffIndex()] == SPELL_AURA_MOD_HEALING_DONE &&
(*i)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_SHAMAN && (*i)->GetSpellProto()->SpellFamilyFlags & UI64LIT(0x0000000004000000))
{
basepoints[0] = triggerAmount * (*i)->GetModifier()->m_amount / 100;
break;
}
}
if (!basepoints[0])
return SPELL_AURA_PROC_FAILED;
basepoints[1] = basepoints[0];
triggered_spell_id = 63283; // Totem of Wrath, caster bonus
target = this;
break;
}
// Shaman T8 Elemental 4P Bonus
case 64928:
{
basepoints[0] = int32( basepoints[0] / 2); // basepoints is for 1 tick, not all DoT amount
triggered_spell_id = 64930; // Electrified
break;
}
// Shaman T9 Elemental 4P Bonus
case 67228:
{
basepoints[0] = int32( basepoints[0] / 3); // basepoints is for 1 tick, not all DoT amount
triggered_spell_id = 71824;
break;
}
// Item - Shaman T10 Restoration 4P Bonus
case 70808:
{
basepoints[0] = int32( triggerAmount * damage / 100 );
basepoints[0] = int32( basepoints[0] / 3); // basepoints is for 1 tick, not all DoT amount
triggered_spell_id = 70809;
break;
}
// Item - Shaman T10 Elemental 4P Bonus
case 70817:
{
if (Aura *aur = pVictim->GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_SHAMAN, UI64LIT(0x0000000010000000), 0, GetGUID()))
{
int32 amount = aur->GetAuraDuration() + triggerAmount * IN_MILLISECONDS;
aur->SetAuraDuration(amount);
aur->UpdateAura(false);
return SPELL_AURA_PROC_OK;
}
return SPELL_AURA_PROC_FAILED;
}
}
// Storm, Earth and Fire
if (dummySpell->SpellIconID == 3063)
{
// Earthbind Totem summon only
if(procSpell->Id != 2484)
return SPELL_AURA_PROC_FAILED;
if (!roll_chance_i(triggerAmount))
return SPELL_AURA_PROC_FAILED;
triggered_spell_id = 64695;
break;
}
// Ancestral Awakening
if (dummySpell->SpellIconID == 3065)
{
triggered_spell_id = 52759;
basepoints[0] = triggerAmount * damage / 100;
target = this;
break;
}
// Flametongue Weapon (Passive), Ranks
if (dummySpell->SpellFamilyFlags & UI64LIT(0x0000000000200000))
{
if (GetTypeId()!=TYPEID_PLAYER || !castItem)
return SPELL_AURA_PROC_FAILED;
// Only proc for enchanted weapon
Item *usedWeapon = ((Player *)this)->GetWeaponForAttack(procFlag & PROC_FLAG_SUCCESSFUL_OFFHAND_HIT ? OFF_ATTACK : BASE_ATTACK, true, true);
if (usedWeapon != castItem)
return SPELL_AURA_PROC_FAILED;
switch (dummySpell->Id)
{
case 10400: triggered_spell_id = 8026; break; // Rank 1
case 15567: triggered_spell_id = 8028; break; // Rank 2
case 15568: triggered_spell_id = 8029; break; // Rank 3
case 15569: triggered_spell_id = 10445; break; // Rank 4
case 16311: triggered_spell_id = 16343; break; // Rank 5
case 16312: triggered_spell_id = 16344; break; // Rank 6
case 16313: triggered_spell_id = 25488; break; // Rank 7
case 58784: triggered_spell_id = 58786; break; // Rank 8
case 58791: triggered_spell_id = 58787; break; // Rank 9
case 58792: triggered_spell_id = 58788; break; // Rank 10
default:
return SPELL_AURA_PROC_FAILED;
}
break;
}
// Earth Shield
if (dummySpell->SpellFamilyFlags & UI64LIT(0x0000040000000000))
{
originalCaster = triggeredByAura->GetCasterGuid();
target = this;
basepoints[0] = triggerAmount;
// Glyph of Earth Shield
if (Aura* aur = GetDummyAura(63279))
{
int32 aur_mod = aur->GetModifier()->m_amount;
basepoints[0] = int32(basepoints[0] * (aur_mod + 100.0f) / 100.0f);
}
triggered_spell_id = 379;
break;
}
// Improved Water Shield
if (dummySpell->SpellIconID == 2287)
{
// Lesser Healing Wave need aditional 60% roll
if ((procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000080)) && !roll_chance_i(60))
return SPELL_AURA_PROC_FAILED;
// Chain Heal needs additional 30% roll
if ((procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000100)) && !roll_chance_i(30))
return SPELL_AURA_PROC_FAILED;
// lookup water shield
AuraList const& vs = GetAurasByType(SPELL_AURA_PROC_TRIGGER_SPELL);
for(AuraList::const_iterator itr = vs.begin(); itr != vs.end(); ++itr)
{
if ((*itr)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_SHAMAN &&
((*itr)->GetSpellProto()->SpellFamilyFlags & UI64LIT(0x0000002000000000)))
{
uint32 spell = (*itr)->GetSpellProto()->EffectTriggerSpell[(*itr)->GetEffIndex()];
CastSpell(this, spell, true, castItem, triggeredByAura);
return SPELL_AURA_PROC_OK;
}
}
return SPELL_AURA_PROC_FAILED;
}
// Lightning Overload
if (dummySpell->SpellIconID == 2018) // only this spell have SpellFamily Shaman SpellIconID == 2018 and dummy aura
{
if(!procSpell || GetTypeId() != TYPEID_PLAYER || !pVictim )
return SPELL_AURA_PROC_FAILED;
// custom cooldown processing case
if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(dummySpell->Id))
return SPELL_AURA_PROC_FAILED;
uint32 spellId = 0;
// Every Lightning Bolt and Chain Lightning spell have duplicate vs half damage and zero cost
switch (procSpell->Id)
{
// Lightning Bolt
case 403: spellId = 45284; break; // Rank 1
case 529: spellId = 45286; break; // Rank 2
case 548: spellId = 45287; break; // Rank 3
case 915: spellId = 45288; break; // Rank 4
case 943: spellId = 45289; break; // Rank 5
case 6041: spellId = 45290; break; // Rank 6
case 10391: spellId = 45291; break; // Rank 7
case 10392: spellId = 45292; break; // Rank 8
case 15207: spellId = 45293; break; // Rank 9
case 15208: spellId = 45294; break; // Rank 10
case 25448: spellId = 45295; break; // Rank 11
case 25449: spellId = 45296; break; // Rank 12
case 49237: spellId = 49239; break; // Rank 13
case 49238: spellId = 49240; break; // Rank 14
// Chain Lightning
case 421: spellId = 45297; break; // Rank 1
case 930: spellId = 45298; break; // Rank 2
case 2860: spellId = 45299; break; // Rank 3
case 10605: spellId = 45300; break; // Rank 4
case 25439: spellId = 45301; break; // Rank 5
case 25442: spellId = 45302; break; // Rank 6
case 49270: spellId = 49268; break; // Rank 7
case 49271: spellId = 49269; break; // Rank 8
default:
sLog.outError("Unit::HandleDummyAuraProc: non handled spell id: %u (LO)", procSpell->Id);
return SPELL_AURA_PROC_FAILED;
}
// Remove cooldown (Chain Lightning - have Category Recovery time)
if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000002))
((Player*)this)->RemoveSpellCooldown(spellId);
CastSpell(pVictim, spellId, true, castItem, triggeredByAura);
if (cooldown && GetTypeId() == TYPEID_PLAYER)
((Player*)this)->AddSpellCooldown(dummySpell->Id, 0, time(NULL) + cooldown);
return SPELL_AURA_PROC_OK;
}
// Static Shock
if(dummySpell->SpellIconID == 3059)
{
// lookup Lightning Shield
AuraList const& vs = GetAurasByType(SPELL_AURA_PROC_TRIGGER_SPELL);
for(AuraList::const_iterator itr = vs.begin(); itr != vs.end(); ++itr)
{
if ((*itr)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_SHAMAN &&
((*itr)->GetSpellProto()->SpellFamilyFlags & UI64LIT(0x0000000000000400)))
{
uint32 spell = 0;
switch ((*itr)->GetId())
{
case 324: spell = 26364; break;
case 325: spell = 26365; break;
case 905: spell = 26366; break;
case 945: spell = 26367; break;
case 8134: spell = 26369; break;
case 10431: spell = 26370; break;
case 10432: spell = 26363; break;
case 25469: spell = 26371; break;
case 25472: spell = 26372; break;
case 49280: spell = 49278; break;
case 49281: spell = 49279; break;
default:
return SPELL_AURA_PROC_FAILED;
}
CastSpell(target, spell, true, castItem, triggeredByAura);
if ((*itr)->GetHolder()->DropAuraCharge())
RemoveAuraHolderFromStack((*itr)->GetId());
return SPELL_AURA_PROC_OK;
}
}
return SPELL_AURA_PROC_FAILED;
}
// Frozen Power
if (dummySpell->SpellIconID == 3780)
{
Unit *caster = triggeredByAura->GetCaster();
if (!procSpell || !caster)
return SPELL_AURA_PROC_FAILED;
float distance = caster->GetDistance(pVictim);
int32 chance = triggerAmount;
if (distance < 15.0f || !roll_chance_i(chance))
return SPELL_AURA_PROC_FAILED;
// make triggered cast apply after current damage spell processing for prevent remove by it
if(Spell* spell = GetCurrentSpell(CURRENT_GENERIC_SPELL))
spell->AddTriggeredSpell(63685);
return SPELL_AURA_PROC_OK;
}
break;
}
case SPELLFAMILY_DEATHKNIGHT:
{
// Butchery
if (dummySpell->SpellIconID == 2664)
{
basepoints[0] = triggerAmount;
triggered_spell_id = 50163;
target = this;
break;
}
// Dancing Rune Weapon
if (dummySpell->Id == 49028)
{
// 1 dummy aura for dismiss rune blade
if (effIndex != EFFECT_INDEX_1)
return SPELL_AURA_PROC_FAILED;
Pet* runeBlade = FindGuardianWithEntry(27893);
if (runeBlade && pVictim && damage && procSpell)
{
int32 procDmg = damage * 0.5;
runeBlade->CastCustomSpell(pVictim, procSpell->Id, &procDmg, NULL, NULL, true, NULL, NULL, runeBlade->GetGUID());
SendSpellNonMeleeDamageLog(pVictim, procSpell->Id, procDmg, SPELL_SCHOOL_MASK_NORMAL, 0, 0, false, 0, false);
break;
}
else
return SPELL_AURA_PROC_FAILED;
}
// Mark of Blood
if (dummySpell->Id == 49005)
{
if (target->GetTypeId() != TYPEID_PLAYER)
return SPELL_AURA_PROC_FAILED;
// TODO: need more info (cooldowns/PPM)
target->CastSpell(target, 61607, true, NULL, triggeredByAura);
return SPELL_AURA_PROC_OK;
}
// Unholy Blight
if (dummySpell->Id == 49194)
{
basepoints[0] = damage * triggerAmount / 100;
// Glyph of Unholy Blight
if (Aura *aura = GetDummyAura(63332))
basepoints[0] += basepoints[0] * aura->GetModifier()->m_amount / 100;
// Split between 10 ticks
basepoints[0] /= 10;
triggered_spell_id = 50536;
break;
}
// Vendetta
if (dummySpell->SpellFamilyFlags & UI64LIT(0x0000000000010000))
{
basepoints[0] = triggerAmount * GetMaxHealth() / 100;
triggered_spell_id = 50181;
target = this;
break;
}
// Necrosis
if (dummySpell->SpellIconID == 2709)
{
// only melee auto attack affected and Rune Strike
if (procSpell && procSpell->Id != 56815)
return SPELL_AURA_PROC_FAILED;
basepoints[0] = triggerAmount * damage / 100;
triggered_spell_id = 51460;
break;
}
// Threat of Thassarian
if (dummySpell->SpellIconID == 2023)
{
// Must Dual Wield
if (!procSpell || !haveOffhandWeapon())
return SPELL_AURA_PROC_FAILED;
// Chance as basepoints for dummy aura
if (!roll_chance_i(triggerAmount))
return SPELL_AURA_PROC_FAILED;
switch (procSpell->Id)
{
// Obliterate
case 49020: // Rank 1
triggered_spell_id = 66198; break;
case 51423: // Rank 2
triggered_spell_id = 66972; break;
case 51424: // Rank 3
triggered_spell_id = 66973; break;
case 51425: // Rank 4
triggered_spell_id = 66974; break;
// Frost Strike
case 49143: // Rank 1
triggered_spell_id = 66196; break;
case 51416: // Rank 2
triggered_spell_id = 66958; break;
case 51417: // Rank 3
triggered_spell_id = 66959; break;
case 51418: // Rank 4
triggered_spell_id = 66960; break;
case 51419: // Rank 5
triggered_spell_id = 66961; break;
case 55268: // Rank 6
triggered_spell_id = 66962; break;
// Plague Strike
case 45462: // Rank 1
triggered_spell_id = 66216; break;
case 49917: // Rank 2
triggered_spell_id = 66988; break;
case 49918: // Rank 3
triggered_spell_id = 66989; break;
case 49919: // Rank 4
triggered_spell_id = 66990; break;
case 49920: // Rank 5
triggered_spell_id = 66991; break;
case 49921: // Rank 6
triggered_spell_id = 66992; break;
// Death Strike
case 49998: // Rank 1
triggered_spell_id = 66188; break;
case 49999: // Rank 2
triggered_spell_id = 66950; break;
case 45463: // Rank 3
triggered_spell_id = 66951; break;
case 49923: // Rank 4
triggered_spell_id = 66952; break;
case 49924: // Rank 5
triggered_spell_id = 66953; break;
// Rune Strike
case 56815:
triggered_spell_id = 66217; break;
// Blood Strike
case 45902: // Rank 1
triggered_spell_id = 66215; break;
case 49926: // Rank 2
triggered_spell_id = 66975; break;
case 49927: // Rank 3
triggered_spell_id = 66976; break;
case 49928: // Rank 4
triggered_spell_id = 66977; break;
case 49929: // Rank 5
triggered_spell_id = 66978; break;
case 49930: // Rank 6
triggered_spell_id = 66979; break;
default:
return SPELL_AURA_PROC_FAILED;
}
break;
}
// Runic Power Back on Snare/Root
if (dummySpell->Id == 61257)
{
// only for spells and hit/crit (trigger start always) and not start from self casted spells
if (procSpell == 0 || !(procEx & (PROC_EX_NORMAL_HIT|PROC_EX_CRITICAL_HIT)) || this == pVictim)
return SPELL_AURA_PROC_FAILED;
// Need snare or root mechanic
if (!(GetAllSpellMechanicMask(procSpell) & IMMUNE_TO_ROOT_AND_SNARE_MASK))
return SPELL_AURA_PROC_FAILED;
triggered_spell_id = 61258;
target = this;
break;
}
// Sudden Doom
if (dummySpell->SpellIconID == 1939)
{
if (!target || !target->isAlive() || this->GetTypeId() != TYPEID_PLAYER)
return SPELL_AURA_PROC_FAILED;
// get highest rank of Death Coil spell
const PlayerSpellMap& sp_list = ((Player*)this)->GetSpellMap();
for (PlayerSpellMap::const_iterator itr = sp_list.begin(); itr != sp_list.end(); ++itr)
{
if(!itr->second.active || itr->second.disabled || itr->second.state == PLAYERSPELL_REMOVED)
continue;
SpellEntry const *spellInfo = sSpellStore.LookupEntry(itr->first);
if (!spellInfo)
continue;
if (spellInfo->SpellFamilyName == SPELLFAMILY_DEATHKNIGHT && spellInfo->SpellFamilyFlags & UI64LIT(0x2000))
{
triggered_spell_id = spellInfo->Id;
break;
}
}
break;
}
// Wandering Plague
if (dummySpell->SpellIconID == 1614)
{
if (!roll_chance_f(GetUnitCriticalChance(BASE_ATTACK, pVictim)))
return SPELL_AURA_PROC_FAILED;
basepoints[0] = triggerAmount * damage / 100;
triggered_spell_id = 50526;
break;
}
// Blood of the North and Reaping
if (dummySpell->SpellIconID == 3041 || dummySpell->SpellIconID == 22)
{
if(GetTypeId()!=TYPEID_PLAYER)
return SPELL_AURA_PROC_FAILED;
Player *player = (Player*)this;
for (uint32 i = 0; i < MAX_RUNES; ++i)
{
if (player->GetCurrentRune(i) == RUNE_BLOOD)
{
if(!player->GetRuneCooldown(i))
player->ConvertRune(i, RUNE_DEATH, dummySpell->Id);
else
{
// search for another rune that might be available
for (uint32 iter = i; iter < MAX_RUNES; ++iter)
{
if(player->GetCurrentRune(iter) == RUNE_BLOOD && !player->GetRuneCooldown(iter))
{
player->ConvertRune(iter, RUNE_DEATH, dummySpell->Id);
triggeredByAura->SetAuraPeriodicTimer(0);
return SPELL_AURA_PROC_OK;
}
}
player->SetNeedConvertRune(i, true, dummySpell->Id);
}
triggeredByAura->SetAuraPeriodicTimer(0);
return SPELL_AURA_PROC_OK;
}
}
return SPELL_AURA_PROC_FAILED;
}
// Death Rune Mastery
if (dummySpell->SpellIconID == 2622)
{
if(GetTypeId()!=TYPEID_PLAYER)
return SPELL_AURA_PROC_FAILED;
Player *player = (Player*)this;
for (uint32 i = 0; i < MAX_RUNES; ++i)
{
RuneType currRune = player->GetCurrentRune(i);
if (currRune == RUNE_UNHOLY || currRune == RUNE_FROST)
{
uint16 cd = player->GetRuneCooldown(i);
if(!cd)
player->ConvertRune(i, RUNE_DEATH, dummySpell->Id);
else // there is a cd
player->SetNeedConvertRune(i, true, dummySpell->Id);
// no break because it converts all
}
}
triggeredByAura->SetAuraPeriodicTimer(0);
return SPELL_AURA_PROC_OK;
}
// Hungering Cold - not break from diseases
if (dummySpell->SpellIconID == 2797)
{
if (procSpell && procSpell->Dispel == DISPEL_DISEASE)
return SPELL_AURA_PROC_FAILED;
}
// Blood-Caked Blade
if (dummySpell->SpellIconID == 138)
{
// only main hand melee auto attack affected and Rune Strike
if ((procFlag & PROC_FLAG_SUCCESSFUL_OFFHAND_HIT) || procSpell && procSpell->Id != 56815)
return SPELL_AURA_PROC_FAILED;
// triggered_spell_id in spell data
break;
}
break;
}
case SPELLFAMILY_PET:
{
// Improved Cower
if (dummySpell->SpellIconID == 958 && procSpell->SpellIconID == 958)
{
triggered_spell_id = dummySpell->Id == 53180 ? 54200 : 54201;
target = this;
break;
}
// Guard Dog
if (dummySpell->SpellIconID == 201 && procSpell->SpellIconID == 201)
{
triggered_spell_id = 54445;
target = this;
break;
}
// Silverback
if (dummySpell->SpellIconID == 1582 && procSpell->SpellIconID == 201)
{
triggered_spell_id = dummySpell->Id == 62764 ? 62800 : 62801;
target = this;
break;
}
break;
}
default:
break;
}
// processed charge only counting case
if (!triggered_spell_id)
return SPELL_AURA_PROC_OK;
SpellEntry const* triggerEntry = sSpellStore.LookupEntry(triggered_spell_id);
if (!triggerEntry)
{
sLog.outError("Unit::HandleDummyAuraProc: Spell %u have nonexistent triggered spell %u",dummySpell->Id,triggered_spell_id);
return SPELL_AURA_PROC_FAILED;
}
// default case
if (!target || (target != this && !target->isAlive()))
return SPELL_AURA_PROC_FAILED;
if (cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(triggered_spell_id))
return SPELL_AURA_PROC_FAILED;
if (basepoints[EFFECT_INDEX_0] || basepoints[EFFECT_INDEX_1] || basepoints[EFFECT_INDEX_2])
CastCustomSpell(target, triggerEntry,
basepoints[EFFECT_INDEX_0] ? &basepoints[EFFECT_INDEX_0] : NULL,
basepoints[EFFECT_INDEX_1] ? &basepoints[EFFECT_INDEX_1] : NULL,
basepoints[EFFECT_INDEX_2] ? &basepoints[EFFECT_INDEX_2] : NULL,
true, castItem, triggeredByAura, originalCaster);
else
CastSpell(target, triggerEntry, true, castItem, triggeredByAura);
if (cooldown && GetTypeId()==TYPEID_PLAYER)
((Player*)this)->AddSpellCooldown(triggered_spell_id,0,time(NULL) + cooldown);
return SPELL_AURA_PROC_OK;
}
SpellAuraProcResult Unit::HandleProcTriggerSpellAuraProc(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const *procSpell, uint32 procFlags, uint32 procEx, uint32 cooldown)
{
// Get triggered aura spell info
SpellEntry const* auraSpellInfo = triggeredByAura->GetSpellProto();
// Basepoints of trigger aura
int32 triggerAmount = triggeredByAura->GetModifier()->m_amount;
// Set trigger spell id, target, custom basepoints
uint32 trigger_spell_id = auraSpellInfo->EffectTriggerSpell[triggeredByAura->GetEffIndex()];
Unit* target = NULL;
int32 basepoints[MAX_EFFECT_INDEX] = {0, 0, 0};
if(triggeredByAura->GetModifier()->m_auraname == SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE)
basepoints[0] = triggerAmount;
Item* castItem = !triggeredByAura->GetCastItemGuid().IsEmpty() && GetTypeId()==TYPEID_PLAYER
? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGuid()) : NULL;
// Try handle unknown trigger spells
// Custom requirements (not listed in procEx) Warning! damage dealing after this
// Custom triggered spells
switch (auraSpellInfo->SpellFamilyName)
{
case SPELLFAMILY_GENERIC:
switch(auraSpellInfo->Id)
{
//case 191: // Elemental Response
// switch (procSpell->School)
// {
// case SPELL_SCHOOL_FIRE: trigger_spell_id = 34192; break;
// case SPELL_SCHOOL_FROST: trigger_spell_id = 34193; break;
// case SPELL_SCHOOL_ARCANE:trigger_spell_id = 34194; break;
// case SPELL_SCHOOL_NATURE:trigger_spell_id = 34195; break;
// case SPELL_SCHOOL_SHADOW:trigger_spell_id = 34196; break;
// case SPELL_SCHOOL_HOLY: trigger_spell_id = 34197; break;
// case SPELL_SCHOOL_NORMAL:trigger_spell_id = 34198; break;
// }
// break;
//case 5301: break; // Defensive State (DND)
//case 7137: break: // Shadow Charge (Rank 1)
//case 7377: break: // Take Immune Periodic Damage <Not Working>
//case 13358: break; // Defensive State (DND)
//case 16092: break; // Defensive State (DND)
//case 18943: break; // Double Attack
//case 19194: break; // Double Attack
//case 19817: break; // Double Attack
//case 19818: break; // Double Attack
//case 22835: break; // Drunken Rage
// trigger_spell_id = 14822; break;
case 23780: // Aegis of Preservation (Aegis of Preservation trinket)
trigger_spell_id = 23781;
break;
//case 24949: break; // Defensive State 2 (DND)
case 27522: // Mana Drain Trigger
case 40336: // Mana Drain Trigger
// On successful melee or ranged attack gain $29471s1 mana and if possible drain $27526s1 mana from the target.
if (isAlive())
CastSpell(this, 29471, true, castItem, triggeredByAura);
if (pVictim && pVictim->isAlive())
CastSpell(pVictim, 27526, true, castItem, triggeredByAura);
return SPELL_AURA_PROC_OK;
case 31255: // Deadly Swiftness (Rank 1)
// whenever you deal damage to a target who is below 20% health.
if (pVictim->GetHealth() > pVictim->GetMaxHealth() / 5)
return SPELL_AURA_PROC_FAILED;
target = this;
trigger_spell_id = 22588;
break;
//case 33207: break; // Gossip NPC Periodic - Fidget
case 33896: // Desperate Defense (Stonescythe Whelp, Stonescythe Alpha, Stonescythe Ambusher)
trigger_spell_id = 33898;
break;
//case 34082: break; // Advantaged State (DND)
//case 34783: break: // Spell Reflection
//case 35205: break: // Vanish
//case 35321: break; // Gushing Wound
//case 36096: break: // Spell Reflection
//case 36207: break: // Steal Weapon
//case 36576: break: // Shaleskin (Shaleskin Flayer, Shaleskin Ripper) 30023 trigger
//case 37030: break; // Chaotic Temperament
case 38164: // Unyielding Knights
if (pVictim->GetEntry() != 19457)
return SPELL_AURA_PROC_FAILED;
break;
//case 38363: break; // Gushing Wound
//case 39215: break; // Gushing Wound
//case 40250: break; // Improved Duration
//case 40329: break; // Demo Shout Sensor
//case 40364: break; // Entangling Roots Sensor
//case 41054: break; // Copy Weapon
// trigger_spell_id = 41055; break;
//case 41248: break; // Consuming Strikes
// trigger_spell_id = 41249; break;
//case 42730: break: // Woe Strike
//case 43453: break: // Rune Ward
//case 43504: break; // Alterac Valley OnKill Proc Aura
//case 44326: break: // Pure Energy Passive
//case 44526: break; // Hate Monster (Spar) (30 sec)
//case 44527: break; // Hate Monster (Spar Buddy) (30 sec)
//case 44819: break; // Hate Monster (Spar Buddy) (>30% Health)
//case 44820: break; // Hate Monster (Spar) (<30%)
case 45057: // Evasive Maneuvers (Commendation of Kael`thas trinket)
// reduce you below $s1% health
if (GetHealth() - damage > GetMaxHealth() * triggerAmount / 100)
return SPELL_AURA_PROC_FAILED;
break;
//case 45903: break: // Offensive State
//case 46146: break: // [PH] Ahune Spanky Hands
//case 46939: break; // Black Bow of the Betrayer
// trigger_spell_id = 29471; - gain mana
// 27526; - drain mana if possible
case 43820: // Charm of the Witch Doctor (Amani Charm of the Witch Doctor trinket)
// Pct value stored in dummy
basepoints[0] = pVictim->GetCreateHealth() * auraSpellInfo->CalculateSimpleValue(EFFECT_INDEX_1) / 100;
target = pVictim;
break;
//case 45205: break; // Copy Offhand Weapon
//case 45343: break; // Dark Flame Aura
//case 47300: break; // Dark Flame Aura
//case 48876: break; // Beast's Mark
// trigger_spell_id = 48877; break;
//case 49059: break; // Horde, Hate Monster (Spar Buddy) (>30% Health)
//case 50051: break; // Ethereal Pet Aura
//case 50689: break; // Blood Presence (Rank 1)
//case 50844: break; // Blood Mirror
//case 52856: break; // Charge
//case 54072: break; // Knockback Ball Passive
//case 54476: break; // Blood Presence
//case 54775: break; // Abandon Vehicle on Poly
case 56702: //
{
trigger_spell_id = 56701;
break;
}
case 57345: // Darkmoon Card: Greatness
{
float stat = 0.0f;
// strength
if (GetStat(STAT_STRENGTH) > stat) { trigger_spell_id = 60229;stat = GetStat(STAT_STRENGTH); }
// agility
if (GetStat(STAT_AGILITY) > stat) { trigger_spell_id = 60233;stat = GetStat(STAT_AGILITY); }
// intellect
if (GetStat(STAT_INTELLECT)> stat) { trigger_spell_id = 60234;stat = GetStat(STAT_INTELLECT);}
// spirit
if (GetStat(STAT_SPIRIT) > stat) { trigger_spell_id = 60235; }
break;
}
//case 55580: break: // Mana Link
//case 57587: break: // Steal Ranged ()
//case 57594: break; // Copy Ranged Weapon
//case 59237: break; // Beast's Mark
// trigger_spell_id = 59233; break;
//case 59288: break; // Infra-Green Shield
//case 59532: break; // Abandon Passengers on Poly
//case 59735: break: // Woe Strike
case 64415: // // Val'anyr Hammer of Ancient Kings - Equip Effect
{
// for DOT procs
if (!IsPositiveSpell(procSpell->Id))
return SPELL_AURA_PROC_FAILED;
break;
}
case 64440: // Blade Warding
{
trigger_spell_id = 64442;
// need scale damage base at stack size
if (SpellEntry const* trigEntry = sSpellStore.LookupEntry(trigger_spell_id))
basepoints[EFFECT_INDEX_0] = trigEntry->CalculateSimpleValue(EFFECT_INDEX_0) * triggeredByAura->GetStackAmount();
break;
}
case 64568: // Blood Reserve
{
// Check health condition - should drop to less 35%
if (!(10*(int32(GetHealth() - damage)) < 3.5 * GetMaxHealth()))
return SPELL_AURA_PROC_FAILED;
if (!roll_chance_f(50))
return SPELL_AURA_PROC_FAILED;
trigger_spell_id = 64569;
basepoints[0] = triggerAmount;
break;
}
case 67702: // Death's Choice, Item - Coliseum 25 Normal Melee Trinket
{
float stat = 0.0f;
// strength
if (GetStat(STAT_STRENGTH) > stat) { trigger_spell_id = 67708;stat = GetStat(STAT_STRENGTH); }
// agility
if (GetStat(STAT_AGILITY) > stat) { trigger_spell_id = 67703; }
break;
}
case 67771: // Death's Choice (heroic), Item - Coliseum 25 Heroic Melee Trinket
{
float stat = 0.0f;
// strength
if (GetStat(STAT_STRENGTH) > stat) { trigger_spell_id = 67773;stat = GetStat(STAT_STRENGTH); }
// agility
if (GetStat(STAT_AGILITY) > stat) { trigger_spell_id = 67772; }
break;
}
case 72178: // Blood link Saurfang aura
{
target = this;
trigger_spell_id = 72195;
break;
}
}
break;
case SPELLFAMILY_MAGE:
if (auraSpellInfo->SpellIconID == 2127) // Blazing Speed
{
switch (auraSpellInfo->Id)
{
case 31641: // Rank 1
case 31642: // Rank 2
trigger_spell_id = 31643;
break;
default:
sLog.outError("Unit::HandleProcTriggerSpellAuraProc: Spell %u miss possibly Blazing Speed",auraSpellInfo->Id);
return SPELL_AURA_PROC_FAILED;
}
}
else if(auraSpellInfo->Id == 26467) // Persistent Shield (Scarab Brooch trinket)
{
// This spell originally trigger 13567 - Dummy Trigger (vs dummy effect)
basepoints[0] = damage * 15 / 100;
target = pVictim;
trigger_spell_id = 26470;
}
else if(auraSpellInfo->Id == 71761) // Deep Freeze Immunity State
{
// spell applied only to permanent immunes to stun targets (bosses)
if (pVictim->GetTypeId() != TYPEID_UNIT ||
(((Creature*)pVictim)->GetCreatureInfo()->MechanicImmuneMask & (1 << (MECHANIC_STUN - 1))) == 0)
return SPELL_AURA_PROC_FAILED;
}
break;
case SPELLFAMILY_WARRIOR:
// Deep Wounds (replace triggered spells to directly apply DoT), dot spell have familyflags
if (auraSpellInfo->SpellFamilyFlags == UI64LIT(0x0) && auraSpellInfo->SpellIconID == 243)
{
float weaponDamage;
// DW should benefit of attack power, damage percent mods etc.
// TODO: check if using offhand damage is correct and if it should be divided by 2
if (haveOffhandWeapon() && getAttackTimer(BASE_ATTACK) > getAttackTimer(OFF_ATTACK))
weaponDamage = (GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE) + GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE))/2;
else
weaponDamage = (GetFloatValue(UNIT_FIELD_MINDAMAGE) + GetFloatValue(UNIT_FIELD_MAXDAMAGE))/2;
switch (auraSpellInfo->Id)
{
case 12834: basepoints[0] = int32(weaponDamage * 16 / 100); break;
case 12849: basepoints[0] = int32(weaponDamage * 32 / 100); break;
case 12867: basepoints[0] = int32(weaponDamage * 48 / 100); break;
// Impossible case
default:
sLog.outError("Unit::HandleProcTriggerSpellAuraProc: DW unknown spell rank %u",auraSpellInfo->Id);
return SPELL_AURA_PROC_FAILED;
}
// 1 tick/sec * 6 sec = 6 ticks
basepoints[0] /= 6;
trigger_spell_id = 12721;
break;
}
if (auraSpellInfo->Id == 50421) // Scent of Blood
trigger_spell_id = 50422;
break;
case SPELLFAMILY_WARLOCK:
{
// Drain Soul
if (auraSpellInfo->SpellFamilyFlags & UI64LIT(0x0000000000004000))
{
// search for "Improved Drain Soul" dummy aura
Unit::AuraList const& mDummyAura = GetAurasByType(SPELL_AURA_DUMMY);
for(Unit::AuraList::const_iterator i = mDummyAura.begin(); i != mDummyAura.end(); ++i)
{
if ((*i)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_WARLOCK && (*i)->GetSpellProto()->SpellIconID == 113)
{
// basepoints of trigger spell stored in dummyeffect of spellProto
int32 basepoints = GetMaxPower(POWER_MANA) * (*i)->GetSpellProto()->CalculateSimpleValue(EFFECT_INDEX_2) / 100;
CastCustomSpell(this, 18371, &basepoints, NULL, NULL, true, castItem, triggeredByAura);
break;
}
}
// Not remove charge (aura removed on death in any cases)
// Need for correct work Drain Soul SPELL_AURA_CHANNEL_DEATH_ITEM aura
return SPELL_AURA_PROC_FAILED;
}
// Nether Protection
else if (auraSpellInfo->SpellIconID == 1985)
{
if (!procSpell)
return SPELL_AURA_PROC_FAILED;
switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell)))
{
case SPELL_SCHOOL_NORMAL:
return SPELL_AURA_PROC_FAILED; // ignore
case SPELL_SCHOOL_HOLY: trigger_spell_id = 54370; break;
case SPELL_SCHOOL_FIRE: trigger_spell_id = 54371; break;
case SPELL_SCHOOL_NATURE: trigger_spell_id = 54375; break;
case SPELL_SCHOOL_FROST: trigger_spell_id = 54372; break;
case SPELL_SCHOOL_SHADOW: trigger_spell_id = 54374; break;
case SPELL_SCHOOL_ARCANE: trigger_spell_id = 54373; break;
default:
return SPELL_AURA_PROC_FAILED;
}
}
// Cheat Death
else if (auraSpellInfo->Id == 28845)
{
// When your health drops below 20% ....
if (GetHealth() - damage > GetMaxHealth() / 5 || GetHealth() < GetMaxHealth() / 5)
return SPELL_AURA_PROC_FAILED;
}
// Decimation
else if (auraSpellInfo->Id == 63156 || auraSpellInfo->Id == 63158)
{
// Looking for dummy effect
Aura *aur = GetAura(auraSpellInfo->Id, EFFECT_INDEX_1);
if (!aur)
return SPELL_AURA_PROC_FAILED;
// If target's health is not below equal certain value (35%) not proc
if (int32(pVictim->GetHealth() * 100 / pVictim->GetMaxHealth()) > aur->GetModifier()->m_amount)
return SPELL_AURA_PROC_FAILED;
}
break;
}
case SPELLFAMILY_PRIEST:
{
// Greater Heal Refund (Avatar Raiment set)
if (auraSpellInfo->Id==37594)
{
// Not give if target already have full health
if (pVictim->GetHealth() == pVictim->GetMaxHealth())
return SPELL_AURA_PROC_FAILED;
// If your Greater Heal brings the target to full health, you gain $37595s1 mana.
if (pVictim->GetHealth() + damage < pVictim->GetMaxHealth())
return SPELL_AURA_PROC_FAILED;
trigger_spell_id = 37595;
}
// Blessed Recovery
else if (auraSpellInfo->SpellIconID == 1875)
{
switch (auraSpellInfo->Id)
{
case 27811: trigger_spell_id = 27813; break;
case 27815: trigger_spell_id = 27817; break;
case 27816: trigger_spell_id = 27818; break;
default:
sLog.outError("Unit::HandleProcTriggerSpellAuraProc: Spell %u not handled in BR", auraSpellInfo->Id);
return SPELL_AURA_PROC_FAILED;
}
basepoints[0] = damage * triggerAmount / 100 / 3;
target = this;
}
// Glyph of Shadow Word: Pain
else if (auraSpellInfo->Id == 55681)
basepoints[0] = triggerAmount * GetCreateMana() / 100;
break;
}
case SPELLFAMILY_DRUID:
{
// Druid Forms Trinket
if (auraSpellInfo->Id==37336)
{
switch(GetShapeshiftForm())
{
case FORM_NONE: trigger_spell_id = 37344;break;
case FORM_CAT: trigger_spell_id = 37341;break;
case FORM_BEAR:
case FORM_DIREBEAR: trigger_spell_id = 37340;break;
case FORM_TREE: trigger_spell_id = 37342;break;
case FORM_MOONKIN: trigger_spell_id = 37343;break;
default:
return SPELL_AURA_PROC_FAILED;
}
}
// Druid T9 Feral Relic (Lacerate, Swipe, Mangle, and Shred)
else if (auraSpellInfo->Id==67353)
{
switch(GetShapeshiftForm())
{
case FORM_CAT: trigger_spell_id = 67355; break;
case FORM_BEAR:
case FORM_DIREBEAR: trigger_spell_id = 67354; break;
default:
return SPELL_AURA_PROC_FAILED;
}
}
break;
}
case SPELLFAMILY_ROGUE:
// Item - Rogue T10 2P Bonus
if (auraSpellInfo->Id == 70805)
{
if (pVictim != this)
return SPELL_AURA_PROC_FAILED;
}
// Item - Rogue T10 4P Bonus
else if (auraSpellInfo->Id == 70803)
{
if (!procSpell)
return SPELL_AURA_PROC_FAILED;
// only allow melee finishing move to proc
if (!(procSpell->AttributesEx & SPELL_ATTR_EX_REQ_TARGET_COMBO_POINTS) || procSpell->Id == 26679)
return SPELL_AURA_PROC_FAILED;
trigger_spell_id = 70802;
target = this;
}
break;
case SPELLFAMILY_HUNTER:
{
// Piercing Shots
if (auraSpellInfo->SpellIconID == 3247 && auraSpellInfo->SpellVisual[0] == 0)
{
basepoints[0] = damage * triggerAmount / 100 / 8;
trigger_spell_id = 63468;
target = pVictim;
}
// Rapid Recuperation
else if (auraSpellInfo->Id == 53228 || auraSpellInfo->Id == 53232)
{
// This effect only from Rapid Fire (ability cast)
if (!(procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000020)))
return SPELL_AURA_PROC_FAILED;
}
// Entrapment correction
else if ((auraSpellInfo->Id == 19184 || auraSpellInfo->Id == 19387 || auraSpellInfo->Id == 19388) &&
!(procSpell->SpellFamilyFlags & UI64LIT(0x200000000000) || procSpell->SpellFamilyFlags2 & UI64LIT(0x40000)))
return SPELL_AURA_PROC_FAILED;
// Lock and Load
else if (auraSpellInfo->SpellIconID == 3579)
{
// Check for Lock and Load Marker
if (HasAura(67544))
return SPELL_AURA_PROC_FAILED;
}
break;
}
case SPELLFAMILY_PALADIN:
{
/*
// Blessed Life
if (auraSpellInfo->SpellIconID == 2137)
{
switch (auraSpellInfo->Id)
{
case 31828: // Rank 1
case 31829: // Rank 2
case 31830: // Rank 3
break;
default:
sLog.outError("Unit::HandleProcTriggerSpellAuraProc: Spell %u miss posibly Blessed Life", auraSpellInfo->Id);
return SPELL_AURA_PROC_FAILED;
}
}
*/
// Healing Discount
if (auraSpellInfo->Id==37705)
{
trigger_spell_id = 37706;
target = this;
}
// Soul Preserver
if (auraSpellInfo->Id==60510)
{
trigger_spell_id = 60515;
target = this;
}
// Illumination
else if (auraSpellInfo->SpellIconID==241)
{
if(!procSpell)
return SPELL_AURA_PROC_FAILED;
// procspell is triggered spell but we need mana cost of original casted spell
uint32 originalSpellId = procSpell->Id;
// Holy Shock heal
if (procSpell->SpellFamilyFlags & UI64LIT(0x0001000000000000))
{
switch(procSpell->Id)
{
case 25914: originalSpellId = 20473; break;
case 25913: originalSpellId = 20929; break;
case 25903: originalSpellId = 20930; break;
case 27175: originalSpellId = 27174; break;
case 33074: originalSpellId = 33072; break;
case 48820: originalSpellId = 48824; break;
case 48821: originalSpellId = 48825; break;
default:
sLog.outError("Unit::HandleProcTriggerSpellAuraProc: Spell %u not handled in HShock",procSpell->Id);
return SPELL_AURA_PROC_FAILED;
}
}
SpellEntry const *originalSpell = sSpellStore.LookupEntry(originalSpellId);
if(!originalSpell)
{
sLog.outError("Unit::HandleProcTriggerSpellAuraProc: Spell %u unknown but selected as original in Illu",originalSpellId);
return SPELL_AURA_PROC_FAILED;
}
// percent stored in effect 1 (class scripts) base points
int32 cost = originalSpell->manaCost + originalSpell->ManaCostPercentage * GetCreateMana() / 100;
basepoints[0] = cost*auraSpellInfo->CalculateSimpleValue(EFFECT_INDEX_1)/100;
trigger_spell_id = 20272;
target = this;
}
// Lightning Capacitor
else if (auraSpellInfo->Id==37657)
{
if(!pVictim || !pVictim->isAlive())
return SPELL_AURA_PROC_FAILED;
// stacking
CastSpell(this, 37658, true, NULL, triggeredByAura);
Aura * dummy = GetDummyAura(37658);
// release at 3 aura in stack (cont contain in basepoint of trigger aura)
if(!dummy || dummy->GetStackAmount() < uint32(triggerAmount))
return SPELL_AURA_PROC_FAILED;
RemoveAurasDueToSpell(37658);
trigger_spell_id = 37661;
target = pVictim;
}
// Bonus Healing (Crystal Spire of Karabor mace)
else if (auraSpellInfo->Id == 40971)
{
// If your target is below $s1% health
if (pVictim->GetHealth() > pVictim->GetMaxHealth() * triggerAmount / 100)
return SPELL_AURA_PROC_FAILED;
}
// Thunder Capacitor
else if (auraSpellInfo->Id == 54841)
{
if(!pVictim || !pVictim->isAlive())
return SPELL_AURA_PROC_FAILED;
// stacking
CastSpell(this, 54842, true, NULL, triggeredByAura);
// counting
Aura * dummy = GetDummyAura(54842);
// release at 3 aura in stack (cont contain in basepoint of trigger aura)
if(!dummy || dummy->GetStackAmount() < uint32(triggerAmount))
return SPELL_AURA_PROC_FAILED;
RemoveAurasDueToSpell(54842);
trigger_spell_id = 54843;
target = pVictim;
}
break;
}
case SPELLFAMILY_SHAMAN:
{
// Lightning Shield (overwrite non existing triggered spell call in spell.dbc
if (auraSpellInfo->SpellFamilyFlags & UI64LIT(0x0000000000000400) && auraSpellInfo->SpellVisual[0] == 37)
{
switch(auraSpellInfo->Id)
{
case 324: // Rank 1
trigger_spell_id = 26364; break;
case 325: // Rank 2
trigger_spell_id = 26365; break;
case 905: // Rank 3
trigger_spell_id = 26366; break;
case 945: // Rank 4
trigger_spell_id = 26367; break;
case 8134: // Rank 5
trigger_spell_id = 26369; break;
case 10431: // Rank 6
trigger_spell_id = 26370; break;
case 10432: // Rank 7
trigger_spell_id = 26363; break;
case 25469: // Rank 8
trigger_spell_id = 26371; break;
case 25472: // Rank 9
trigger_spell_id = 26372; break;
case 49280: // Rank 10
trigger_spell_id = 49278; break;
case 49281: // Rank 11
trigger_spell_id = 49279; break;
default:
sLog.outError("Unit::HandleProcTriggerSpellAuraProc: Spell %u not handled in LShield", auraSpellInfo->Id);
return SPELL_AURA_PROC_FAILED;
}
}
// Lightning Shield (The Ten Storms set)
else if (auraSpellInfo->Id == 23551)
{
trigger_spell_id = 23552;
target = pVictim;
}
// Damage from Lightning Shield (The Ten Storms set)
else if (auraSpellInfo->Id == 23552)
trigger_spell_id = 27635;
// Mana Surge (The Earthfury set)
else if (auraSpellInfo->Id == 23572)
{
if(!procSpell)
return SPELL_AURA_PROC_FAILED;
basepoints[0] = procSpell->manaCost * 35 / 100;
trigger_spell_id = 23571;
target = this;
}
// Nature's Guardian
else if (auraSpellInfo->SpellIconID == 2013)
{
// Check health condition - should drop to less 30% (damage deal after this!)
if (!(10*(int32(GetHealth() - damage)) < int32(3 * GetMaxHealth())))
return SPELL_AURA_PROC_FAILED;
if(pVictim && pVictim->isAlive())
pVictim->getThreatManager().modifyThreatPercent(this,-10);
basepoints[0] = triggerAmount * GetMaxHealth() / 100;
trigger_spell_id = 31616;
target = this;
}
// Item - Shaman T10 Restoration 2P Bonus
else if (auraSpellInfo->Id == 70807)
{
if (!procSpell)
return SPELL_AURA_PROC_FAILED;
// only allow Riptide to proc
switch(procSpell->Id)
{
case 61295: // Rank 1
case 61299: // Rank 2
case 61300: // Rank 3
case 61301: // Rank 4
break;
default:
return SPELL_AURA_PROC_FAILED;
}
trigger_spell_id = 70806;
target = this;
}
break;
}
case SPELLFAMILY_DEATHKNIGHT:
{
// Acclimation
if (auraSpellInfo->SpellIconID == 1930)
{
if (!procSpell)
return SPELL_AURA_PROC_FAILED;
switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell)))
{
case SPELL_SCHOOL_NORMAL:
return SPELL_AURA_PROC_FAILED; // ignore
case SPELL_SCHOOL_HOLY: trigger_spell_id = 50490; break;
case SPELL_SCHOOL_FIRE: trigger_spell_id = 50362; break;
case SPELL_SCHOOL_NATURE: trigger_spell_id = 50488; break;
case SPELL_SCHOOL_FROST: trigger_spell_id = 50485; break;
case SPELL_SCHOOL_SHADOW: trigger_spell_id = 50489; break;
case SPELL_SCHOOL_ARCANE: trigger_spell_id = 50486; break;
default:
return SPELL_AURA_PROC_FAILED;
}
}
// Glyph of Death's Embrace
else if (auraSpellInfo->Id == 58677)
{
if (procSpell->Id != 47633)
return SPELL_AURA_PROC_FAILED;
}
//Glyph of Death Grip
if (auraSpellInfo->Id == 62259)
{
//remove cooldown of Death Grip
if (GetTypeId() == TYPEID_PLAYER)
((Player*)this)->RemoveSpellCooldown(49576, true);
return SPELL_AURA_PROC_OK;
}
// Item - Death Knight T10 Melee 4P Bonus
else if (auraSpellInfo->Id == 70656)
{
if (GetTypeId() != TYPEID_PLAYER || getClass() != CLASS_DEATH_KNIGHT)
return SPELL_AURA_PROC_FAILED;
for(uint32 i = 0; i < MAX_RUNES; ++i)
if (((Player*)this)->GetRuneCooldown(i) == 0)
return SPELL_AURA_PROC_FAILED;
}
// Blade Barrier
else if (auraSpellInfo->SpellIconID == 85)
{
if (GetTypeId() != TYPEID_PLAYER || getClass() != CLASS_DEATH_KNIGHT ||
!((Player*)this)->IsBaseRuneSlotsOnCooldown(RUNE_BLOOD))
return SPELL_AURA_PROC_FAILED;
}
// Improved Blood Presence
else if (auraSpellInfo->Id == 63611)
{
if (GetTypeId() != TYPEID_PLAYER || !((Player*)this)->isHonorOrXPTarget(pVictim) || !damage)
return SPELL_AURA_PROC_FAILED;
basepoints[0] = triggerAmount * damage / 100;
trigger_spell_id = 50475;
}
// Glyph of Death's Embrace
else if (auraSpellInfo->Id == 58677)
{
if (procSpell->Id != 47633)
return SPELL_AURA_PROC_FAILED;
}
break;
}
default:
break;
}
// All ok. Check current trigger spell
SpellEntry const* triggerEntry = sSpellStore.LookupEntry(trigger_spell_id);
if (!triggerEntry)
{
// Not cast unknown spell
// sLog.outError("Unit::HandleProcTriggerSpellAuraProc: Spell %u have 0 in EffectTriggered[%d], not handled custom case?",auraSpellInfo->Id,triggeredByAura->GetEffIndex());
return SPELL_AURA_PROC_FAILED;
}
// not allow proc extra attack spell at extra attack
if (m_extraAttacks && IsSpellHaveEffect(triggerEntry, SPELL_EFFECT_ADD_EXTRA_ATTACKS))
return SPELL_AURA_PROC_FAILED;
// Custom basepoints/target for exist spell
// dummy basepoints or other customs
switch(trigger_spell_id)
{
// Cast positive spell on enemy target
case 7099: // Curse of Mending
case 39647: // Curse of Mending
case 29494: // Temptation
case 20233: // Improved Lay on Hands (cast on target)
{
target = pVictim;
break;
}
// Combo points add triggers (need add combopoint only for main target, and after possible combopoints reset)
case 15250: // Rogue Setup
{
if(!pVictim || pVictim != getVictim()) // applied only for main target
return SPELL_AURA_PROC_FAILED;
break; // continue normal case
}
// Finishing moves that add combo points
case 14189: // Seal Fate (Netherblade set)
case 14157: // Ruthlessness
case 70802: // Mayhem (Shadowblade sets)
{
// Need add combopoint AFTER finishing move (or they get dropped in finish phase)
if (Spell* spell = GetCurrentSpell(CURRENT_GENERIC_SPELL))
{
spell->AddTriggeredSpell(trigger_spell_id);
return SPELL_AURA_PROC_OK;
}
return SPELL_AURA_PROC_FAILED;
}
// Bloodthirst (($m/100)% of max health)
case 23880:
{
basepoints[0] = int32(GetMaxHealth() * triggerAmount / 100);
break;
}
// Shamanistic Rage triggered spell
case 30824:
{
basepoints[0] = int32(GetTotalAttackPowerValue(BASE_ATTACK) * triggerAmount / 100);
break;
}
// Enlightenment (trigger only from mana cost spells)
case 35095:
{
if(!procSpell || procSpell->powerType!=POWER_MANA || procSpell->manaCost==0 && procSpell->ManaCostPercentage==0 && procSpell->manaCostPerlevel==0)
return SPELL_AURA_PROC_FAILED;
break;
}
// Demonic Pact
case 48090:
{
// As the spell is proced from pet's attack - find owner
Unit* owner = GetOwner();
if (!owner || owner->GetTypeId() != TYPEID_PLAYER)
return SPELL_AURA_PROC_FAILED;
// This spell doesn't stack, but refreshes duration. So we receive current bonuses to minus them later.
int32 curBonus = 0;
if (Aura* aur = owner->GetAura(48090, EFFECT_INDEX_0))
curBonus = aur->GetModifier()->m_amount;
int32 spellDamage = owner->SpellBaseDamageBonusDone(SPELL_SCHOOL_MASK_MAGIC) - curBonus;
if(spellDamage <= 0)
return SPELL_AURA_PROC_FAILED;
// percent stored in owner talent dummy
AuraList const& dummyAuras = owner->GetAurasByType(SPELL_AURA_DUMMY);
for (AuraList::const_iterator i = dummyAuras.begin(); i != dummyAuras.end(); ++i)
{
if ((*i)->GetSpellProto()->SpellIconID == 3220)
{
basepoints[0] = basepoints[1] = int32(spellDamage * (*i)->GetModifier()->m_amount / 100);
break;
}
}
break;
}
// Sword and Board
case 50227:
{
// Remove cooldown on Shield Slam
if (GetTypeId() == TYPEID_PLAYER)
((Player*)this)->RemoveSpellCategoryCooldown(1209, true);
break;
}
// Maelstrom Weapon
case 53817:
{
// Item - Shaman T10 Enhancement 4P Bonus
// Calculate before roll_chance of ranks
if (Aura * dummy = GetDummyAura(70832))
{
if (SpellAuraHolder *aurHolder = GetSpellAuraHolder(53817))
if ((aurHolder->GetStackAmount() == aurHolder->GetSpellProto()->StackAmount) && roll_chance_i(dummy->GetBasePoints()))
CastSpell(this,70831,true,castItem,triggeredByAura);
}
// have rank dependent proc chance, ignore too often cases
// PPM = 2.5 * (rank of talent),
uint32 rank = sSpellMgr.GetSpellRank(auraSpellInfo->Id);
// 5 rank -> 100% 4 rank -> 80% and etc from full rate
if(!roll_chance_i(20*rank))
return SPELL_AURA_PROC_FAILED;
// Item - Shaman T10 Enhancement 4P Bonus
if (Aura *aur = GetAura(70832, EFFECT_INDEX_0))
{
Aura *maelBuff = GetAura(trigger_spell_id, EFFECT_INDEX_0);
if (maelBuff && maelBuff->GetStackAmount() + 1 == maelBuff->GetSpellProto()->StackAmount)
if (roll_chance_i(aur->GetModifier()->m_amount))
CastSpell(this, 70831, true, NULL, aur);
}
break;
}
// Brain Freeze
case 57761:
{
if(!procSpell)
return SPELL_AURA_PROC_FAILED;
// For trigger from Blizzard need exist Improved Blizzard
if (procSpell->SpellFamilyName==SPELLFAMILY_MAGE && (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000080)))
{
bool found = false;
AuraList const& mOverrideClassScript = GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
for(AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
{
int32 script = (*i)->GetModifier()->m_miscvalue;
if(script==836 || script==988 || script==989)
{
found=true;
break;
}
}
if(!found)
return SPELL_AURA_PROC_FAILED;
}
break;
}
// Astral Shift
case 52179:
{
if (procSpell == 0 || !(procEx & (PROC_EX_NORMAL_HIT|PROC_EX_CRITICAL_HIT)) || this == pVictim)
return SPELL_AURA_PROC_FAILED;
// Need stun, fear or silence mechanic
if (!(GetAllSpellMechanicMask(procSpell) & IMMUNE_TO_SILENCE_AND_STUN_AND_FEAR_MASK))
return SPELL_AURA_PROC_FAILED;
break;
}
// Burning Determination
case 54748:
{
if(!procSpell)
return SPELL_AURA_PROC_FAILED;
// Need Interrupt or Silenced mechanic
if (!(GetAllSpellMechanicMask(procSpell) & IMMUNE_TO_INTERRUPT_AND_SILENCE_MASK))
return SPELL_AURA_PROC_FAILED;
break;
}
// Lock and Load
case 56453:
{
// Proc only from trap activation (from periodic proc another aura of this spell)
// because some spells have both flags (ON_TRAP_ACTIVATION and ON_PERIODIC), but should only proc ON_PERIODIC!!
if (!(procFlags & PROC_FLAG_ON_TRAP_ACTIVATION) || !procSpell ||
!(procSpell->SchoolMask & SPELL_SCHOOL_MASK_FROST) || !roll_chance_i(triggerAmount))
return SPELL_AURA_PROC_FAILED;
break;
}
// Freezing Fog (Rime triggered)
case 59052:
{
// Howling Blast cooldown reset
if (GetTypeId() == TYPEID_PLAYER)
((Player*)this)->RemoveSpellCategoryCooldown(1248, true);
break;
}
// Druid - Savage Defense
case 62606:
{
basepoints[0] = int32(GetTotalAttackPowerValue(BASE_ATTACK) * triggerAmount / 100);
break;
}
// Hack for Blood mark (ICC Saurfang)
case 72255:
case 72444:
case 72445:
case 72446:
{
float radius = GetSpellRadius(sSpellRadiusStore.LookupEntry(auraSpellInfo->EffectRadiusIndex[EFFECT_INDEX_0]));
Map::PlayerList const& pList = GetMap()->GetPlayers();
for (Map::PlayerList::const_iterator itr = pList.begin(); itr != pList.end(); ++itr)
if (itr->getSource() && itr->getSource()->IsWithinDistInMap(this,radius) && itr->getSource()->HasAura(triggerEntry->targetAuraSpell))
{
target = itr->getSource();
break;
}
break;
}
}
if (cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(trigger_spell_id))
return SPELL_AURA_PROC_FAILED;
// try detect target manually if not set
if (target == NULL)
target = !(procFlags & PROC_FLAG_SUCCESSFUL_POSITIVE_SPELL) && IsPositiveSpell(trigger_spell_id) ? this : pVictim;
// default case
if (!target || (target != this && !target->isAlive()))
return SPELL_AURA_PROC_FAILED;
if (SpellEntry const* triggeredSpellInfo = sSpellStore.LookupEntry(trigger_spell_id))
{
if (basepoints[EFFECT_INDEX_0] || basepoints[EFFECT_INDEX_1] || basepoints[EFFECT_INDEX_2])
CastCustomSpell(target,triggeredSpellInfo,
basepoints[EFFECT_INDEX_0] ? &basepoints[EFFECT_INDEX_0] : NULL,
basepoints[EFFECT_INDEX_1] ? &basepoints[EFFECT_INDEX_1] : NULL,
basepoints[EFFECT_INDEX_2] ? &basepoints[EFFECT_INDEX_2] : NULL,
true, castItem, triggeredByAura);
else
CastSpell(target,triggeredSpellInfo,true,castItem,triggeredByAura);
}
else
{
sLog.outError("HandleProcTriggerSpellAuraProc: unknown spell id %u by caster: %s triggered by aura %u (eff %u)", trigger_spell_id, GetGuidStr().c_str(), triggeredByAura->GetId(), triggeredByAura->GetEffIndex());
return SPELL_AURA_PROC_FAILED;
}
if (cooldown && GetTypeId()==TYPEID_PLAYER)
((Player*)this)->AddSpellCooldown(trigger_spell_id,0,time(NULL) + cooldown);
return SPELL_AURA_PROC_OK;
}
SpellAuraProcResult Unit::HandleProcTriggerDamageAuraProc(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const *procSpell, uint32 procFlags, uint32 procEx, uint32 cooldown)
{
SpellEntry const *spellInfo = triggeredByAura->GetSpellProto();
DEBUG_FILTER_LOG(LOG_FILTER_SPELL_CAST, "ProcDamageAndSpell: doing %u damage from spell id %u (triggered by auratype %u of spell %u)",
triggeredByAura->GetModifier()->m_amount, spellInfo->Id, triggeredByAura->GetModifier()->m_auraname, triggeredByAura->GetId());
SpellNonMeleeDamage damageInfo(this, pVictim, spellInfo->Id, SpellSchoolMask(spellInfo->SchoolMask));
CalculateSpellDamage(&damageInfo, triggeredByAura->GetModifier()->m_amount, spellInfo);
damageInfo.target->CalculateAbsorbResistBlock(this, &damageInfo, spellInfo);
DealDamageMods(damageInfo.target,damageInfo.damage,&damageInfo.absorb);
SendSpellNonMeleeDamageLog(&damageInfo);
DealSpellDamage(&damageInfo, true);
return SPELL_AURA_PROC_OK;
}
SpellAuraProcResult Unit::HandleOverrideClassScriptAuraProc(Unit *pVictim, uint32 /*damage*/, Aura *triggeredByAura, SpellEntry const *procSpell, uint32 /*procFlag*/, uint32 /*procEx*/ ,uint32 cooldown)
{
int32 scriptId = triggeredByAura->GetModifier()->m_miscvalue;
if(!pVictim || !pVictim->isAlive())
return SPELL_AURA_PROC_FAILED;
Item* castItem = !triggeredByAura->GetCastItemGuid().IsEmpty() && GetTypeId()==TYPEID_PLAYER
? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGuid()) : NULL;
// Basepoints of trigger aura
int32 triggerAmount = triggeredByAura->GetModifier()->m_amount;
uint32 triggered_spell_id = 0;
switch(scriptId)
{
case 836: // Improved Blizzard (Rank 1)
{
if (!procSpell || procSpell->SpellVisual[0]!=9487)
return SPELL_AURA_PROC_FAILED;
triggered_spell_id = 12484;
break;
}
case 988: // Improved Blizzard (Rank 2)
{
if (!procSpell || procSpell->SpellVisual[0]!=9487)
return SPELL_AURA_PROC_FAILED;
triggered_spell_id = 12485;
break;
}
case 989: // Improved Blizzard (Rank 3)
{
if (!procSpell || procSpell->SpellVisual[0]!=9487)
return SPELL_AURA_PROC_FAILED;
triggered_spell_id = 12486;
break;
}
case 4086: // Improved Mend Pet (Rank 1)
case 4087: // Improved Mend Pet (Rank 2)
{
if(!roll_chance_i(triggerAmount))
return SPELL_AURA_PROC_FAILED;
triggered_spell_id = 24406;
break;
}
case 4533: // Dreamwalker Raiment 2 pieces bonus
{
// Chance 50%
if (!roll_chance_i(50))
return SPELL_AURA_PROC_FAILED;
switch (pVictim->getPowerType())
{
case POWER_MANA: triggered_spell_id = 28722; break;
case POWER_RAGE: triggered_spell_id = 28723; break;
case POWER_ENERGY: triggered_spell_id = 28724; break;
default:
return SPELL_AURA_PROC_FAILED;
}
break;
}
case 4537: // Dreamwalker Raiment 6 pieces bonus
triggered_spell_id = 28750; // Blessing of the Claw
break;
case 5497: // Improved Mana Gems (Serpent-Coil Braid)
triggered_spell_id = 37445; // Mana Surge
break;
case 6953: // Warbringer
RemoveAurasAtMechanicImmunity(IMMUNE_TO_ROOT_AND_SNARE_MASK,0,true);
return SPELL_AURA_PROC_OK;
case 7010: // Revitalize (rank 1)
case 7011: // Revitalize (rank 2)
case 7012: // Revitalize (rank 3)
{
if(!roll_chance_i(triggerAmount))
return SPELL_AURA_PROC_FAILED;
switch( pVictim->getPowerType() )
{
case POWER_MANA: triggered_spell_id = 48542; break;
case POWER_RAGE: triggered_spell_id = 48541; break;
case POWER_ENERGY: triggered_spell_id = 48540; break;
case POWER_RUNIC_POWER: triggered_spell_id = 48543; break;
default: return SPELL_AURA_PROC_FAILED;
}
break;
}
case 7282: // Crypt Fever & Ebon Plaguebringer
{
if (!procSpell || pVictim == this)
return SPELL_AURA_PROC_FAILED;
bool HasEP = false;
Unit::AuraList const& scriptAuras = GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
for(Unit::AuraList::const_iterator i = scriptAuras.begin(); i != scriptAuras.end(); ++i)
{
if ((*i)->GetSpellProto()->SpellIconID == 1766)
{
HasEP = true;
break;
}
}
if (!HasEP)
switch(triggeredByAura->GetId())
{
case 49032: triggered_spell_id = 50508; break;
case 49631: triggered_spell_id = 50509; break;
case 49632: triggered_spell_id = 50510; break;
default: return SPELL_AURA_PROC_FAILED;
}
else
switch(triggeredByAura->GetId())
{
case 51099: triggered_spell_id = 51726; break;
case 51160: triggered_spell_id = 51734; break;
case 51161: triggered_spell_id = 51735; break;
default: return SPELL_AURA_PROC_FAILED;
}
break;
}
}
// not processed
if(!triggered_spell_id)
return SPELL_AURA_PROC_FAILED;
// standard non-dummy case
SpellEntry const* triggerEntry = sSpellStore.LookupEntry(triggered_spell_id);
if(!triggerEntry)
{
sLog.outError("Unit::HandleOverrideClassScriptAuraProc: Spell %u triggering for class script id %u",triggered_spell_id,scriptId);
return SPELL_AURA_PROC_FAILED;
}
if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(triggered_spell_id))
return SPELL_AURA_PROC_FAILED;
CastSpell(pVictim, triggered_spell_id, true, castItem, triggeredByAura);
if( cooldown && GetTypeId()==TYPEID_PLAYER )
((Player*)this)->AddSpellCooldown(triggered_spell_id,0,time(NULL) + cooldown);
return SPELL_AURA_PROC_OK;
}
SpellAuraProcResult Unit::HandleMendingAuraProc( Unit* /*pVictim*/, uint32 /*damage*/, Aura* triggeredByAura, SpellEntry const* /*procSpell*/, uint32 /*procFlag*/, uint32 /*procEx*/, uint32 /*cooldown*/ )
{
// aura can be deleted at casts
SpellEntry const* spellProto = triggeredByAura->GetSpellProto();
SpellEffectIndex effIdx = triggeredByAura->GetEffIndex();
int32 heal = triggeredByAura->GetModifier()->m_amount;
ObjectGuid caster_guid = triggeredByAura->GetCasterGuid();
// jumps
int32 jumps = triggeredByAura->GetHolder()->GetAuraCharges()-1;
// current aura expire
triggeredByAura->GetHolder()->SetAuraCharges(1); // will removed at next charges decrease
// next target selection
if (jumps > 0 && GetTypeId()==TYPEID_PLAYER && caster_guid.IsPlayer())
{
float radius;
if (spellProto->EffectRadiusIndex[effIdx])
radius = GetSpellRadius(sSpellRadiusStore.LookupEntry(spellProto->EffectRadiusIndex[effIdx]));
else
radius = GetSpellMaxRange(sSpellRangeStore.LookupEntry(spellProto->rangeIndex));
if(Player* caster = ((Player*)triggeredByAura->GetCaster()))
{
caster->ApplySpellMod(spellProto->Id, SPELLMOD_RADIUS, radius,NULL);
if(Player* target = ((Player*)this)->GetNextRandomRaidMember(radius))
{
// aura will applied from caster, but spell casted from current aura holder
SpellModifier *mod = new SpellModifier(SPELLMOD_CHARGES,SPELLMOD_FLAT,jumps-5,spellProto->Id,spellProto->SpellFamilyFlags,spellProto->SpellFamilyFlags2);
// remove before apply next (locked against deleted)
triggeredByAura->SetInUse(true);
RemoveAurasByCasterSpell(spellProto->Id,caster->GetGUID());
caster->AddSpellMod(mod, true);
CastCustomSpell(target,spellProto->Id,&heal,NULL,NULL,true,NULL,triggeredByAura,caster->GetGUID());
caster->AddSpellMod(mod, false);
triggeredByAura->SetInUse(false);
}
}
}
// heal
CastCustomSpell(this,33110,&heal,NULL,NULL,true,NULL,NULL,caster_guid);
return SPELL_AURA_PROC_OK;
}
SpellAuraProcResult Unit::HandleModCastingSpeedNotStackAuraProc(Unit* /*pVictim*/, uint32 /*damage*/, Aura* /*triggeredByAura*/, SpellEntry const* procSpell, uint32 /*procFlag*/, uint32 /*procEx*/, uint32 /*cooldown*/)
{
// Skip melee hits or instant cast spells
return !(procSpell == NULL || GetSpellCastTime(procSpell) == 0) ? SPELL_AURA_PROC_OK : SPELL_AURA_PROC_FAILED;
}
SpellAuraProcResult Unit::HandleReflectSpellsSchoolAuraProc(Unit* /*pVictim*/, uint32 /*damage*/, Aura* triggeredByAura, SpellEntry const* procSpell, uint32 /*procFlag*/, uint32 /*procEx*/, uint32 /*cooldown*/)
{
// Skip Melee hits and spells ws wrong school
return !(procSpell == NULL || (triggeredByAura->GetModifier()->m_miscvalue & procSpell->SchoolMask) == 0) ? SPELL_AURA_PROC_OK : SPELL_AURA_PROC_FAILED;
}
SpellAuraProcResult Unit::HandleModPowerCostSchoolAuraProc(Unit* /*pVictim*/, uint32 /*damage*/, Aura* triggeredByAura, SpellEntry const* procSpell, uint32 /*procFlag*/, uint32 /*procEx*/, uint32 /*cooldown*/)
{
// Skip melee hits and spells ws wrong school or zero cost
return !(procSpell == NULL ||
(procSpell->manaCost == 0 && procSpell->ManaCostPercentage == 0) || // Cost check
(triggeredByAura->GetModifier()->m_miscvalue & procSpell->SchoolMask) == 0) ? SPELL_AURA_PROC_OK : SPELL_AURA_PROC_FAILED; // School check
}
SpellAuraProcResult Unit::HandleMechanicImmuneResistanceAuraProc(Unit* /*pVictim*/, uint32 /*damage*/, Aura* triggeredByAura, SpellEntry const* procSpell, uint32 /*procFlag*/, uint32 /*procEx*/, uint32 /*cooldown*/)
{
// Compare mechanic
return !(procSpell==NULL || int32(procSpell->Mechanic) != triggeredByAura->GetModifier()->m_miscvalue)
? SPELL_AURA_PROC_OK : SPELL_AURA_PROC_FAILED;
}
SpellAuraProcResult Unit::HandleModDamageFromCasterAuraProc(Unit* pVictim, uint32 /*damage*/, Aura* triggeredByAura, SpellEntry const* /*procSpell*/, uint32 /*procFlag*/, uint32 /*procEx*/, uint32 /*cooldown*/)
{
// Compare casters
return triggeredByAura->GetCasterGuid() == pVictim->GetObjectGuid() ? SPELL_AURA_PROC_OK : SPELL_AURA_PROC_FAILED;
}
SpellAuraProcResult Unit::HandleAddFlatModifierAuraProc(Unit* /*pVictim*/, uint32 /*damage*/, Aura* triggeredByAura, SpellEntry const * /*procSpell*/, uint32 /*procFlag*/, uint32 /*procEx*/, uint32 /*cooldown*/)
{
SpellEntry const *spellInfo = triggeredByAura->GetSpellProto();
if (spellInfo->Id == 55166) // Tidal Force
{
// Remove only single aura from stack
if (triggeredByAura->GetStackAmount() > 1 && !triggeredByAura->GetHolder()->ModStackAmount(-1))
return SPELL_AURA_PROC_CANT_TRIGGER;
}
return SPELL_AURA_PROC_OK;
}
SpellAuraProcResult Unit::HandleAddPctModifierAuraProc(Unit* /*pVictim*/, uint32 /*damage*/, Aura* triggeredByAura, SpellEntry const *procSpell, uint32 /*procFlag*/, uint32 procEx, uint32 /*cooldown*/)
{
SpellEntry const *spellInfo = triggeredByAura->GetSpellProto();
Item* castItem = !triggeredByAura->GetCastItemGuid().IsEmpty() && GetTypeId()==TYPEID_PLAYER
? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGuid()) : NULL;
switch(spellInfo->SpellFamilyName)
{
case SPELLFAMILY_MAGE:
{
// Combustion
if (spellInfo->Id == 11129)
{
//last charge and crit
if (triggeredByAura->GetHolder()->GetAuraCharges() <= 1 && (procEx & PROC_EX_CRITICAL_HIT) )
return SPELL_AURA_PROC_OK; // charge counting (will removed)
CastSpell(this, 28682, true, castItem, triggeredByAura);
return (procEx & PROC_EX_CRITICAL_HIT) ? SPELL_AURA_PROC_OK : SPELL_AURA_PROC_FAILED; // charge update only at crit hits, no hidden cooldowns
}
break;
}
case SPELLFAMILY_PRIEST:
{
// Serendipity
if (spellInfo->SpellIconID == 2900)
{
RemoveAurasDueToSpell(spellInfo->Id);
return SPELL_AURA_PROC_OK;
}
break;
}
case SPELLFAMILY_PALADIN:
{
// Glyph of Divinity
if (spellInfo->Id == 11129)
{
// Lookup base amount mana restore
for (int i = 0; i < MAX_EFFECT_INDEX; ++i)
{
if (procSpell->Effect[i] == SPELL_EFFECT_ENERGIZE)
{
int32 mana = procSpell->CalculateSimpleValue(SpellEffectIndex(i));
CastCustomSpell(this, 54986, NULL, &mana, NULL, true, castItem, triggeredByAura);
break;
}
}
return SPELL_AURA_PROC_OK;
}
break;
}
}
return SPELL_AURA_PROC_OK;
}
SpellAuraProcResult Unit::HandleModDamagePercentDoneAuraProc(Unit* /*pVictim*/, uint32 /*damage*/, Aura* triggeredByAura, SpellEntry const *procSpell, uint32 /*procFlag*/, uint32 procEx, uint32 cooldown)
{
SpellEntry const *spellInfo = triggeredByAura->GetSpellProto();
Item* castItem = !triggeredByAura->GetCastItemGuid().IsEmpty() && GetTypeId()==TYPEID_PLAYER
? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGuid()) : NULL;
// Aspect of the Viper
if (spellInfo->SpellFamilyName == SPELLFAMILY_HUNTER && spellInfo->SpellFamilyFlags & UI64LIT(0x4000000000000))
{
uint32 maxmana = GetMaxPower(POWER_MANA);
int32 bp = int32(maxmana* GetAttackTime(RANGED_ATTACK)/1000.0f/100.0f);
if(cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(34075))
return SPELL_AURA_PROC_FAILED;
CastCustomSpell(this, 34075, &bp, NULL, NULL, true, castItem, triggeredByAura);
}
// Arcane Blast
else if (spellInfo->Id == 36032 && procSpell->SpellFamilyName == SPELLFAMILY_MAGE && procSpell->SpellIconID == 2294)
// prevent proc from self(spell that triggered this aura)
return SPELL_AURA_PROC_FAILED;
return SPELL_AURA_PROC_OK;
}
SpellAuraProcResult Unit::HandlePeriodicDummyAuraProc(Unit* /*pVictim*/, uint32 /*damage*/, Aura* triggeredByAura, SpellEntry const *procSpell, uint32 /*procFlag*/, uint32 /*procEx*/, uint32 /*cooldown*/)
{
if (!triggeredByAura)
return SPELL_AURA_PROC_FAILED;
SpellEntry const *spellProto = triggeredByAura->GetSpellProto();
if (!spellProto)
return SPELL_AURA_PROC_FAILED;
switch (spellProto->SpellFamilyName)
{
case SPELLFAMILY_DEATHKNIGHT:
{
switch (spellProto->SpellIconID)
{
// Reaping
// Death Rune Mastery
// Blood of the North
case 22:
case 2622:
case 3041:
{
if(!procSpell)
return SPELL_AURA_PROC_FAILED;
if (getClass() != CLASS_DEATH_KNIGHT)
return SPELL_AURA_PROC_FAILED;
Player * plr = GetTypeId() == TYPEID_PLAYER? ((Player*)this) : NULL;
if (!plr)
return SPELL_AURA_PROC_FAILED;
//get spell rune cost
SpellRuneCostEntry const *runeCost = sSpellRuneCostStore.LookupEntry(procSpell->runeCostID);
if (!runeCost)
return SPELL_AURA_PROC_FAILED;
//convert runes to death
for (uint32 i = 0; i < NUM_RUNE_TYPES -1/*don't count death rune*/; ++i)
{
uint32 remainingCost = runeCost->RuneCost[i];
while(remainingCost)
{
int32 convertedRuneCooldown = -1;
uint32 convertedRune = i;
for(uint32 j = 0; j < MAX_RUNES; ++j)
{
// convert only valid runes
if (RuneType(i) != plr->GetCurrentRune(j) &&
RuneType(i) != plr->GetBaseRune(j))
continue;
// select rune with longest cooldown
if (convertedRuneCooldown < plr->GetRuneCooldown(j))
{
convertedRuneCooldown = int32(plr->GetRuneCooldown(j));
convertedRune = j;
}
}
if (convertedRuneCooldown >= 0)
plr->ConvertRune(convertedRune, RUNE_DEATH);
--remainingCost;
}
}
return SPELL_AURA_PROC_OK;
}
default:
break;
}
break;
}
default:
break;
}
return SPELL_AURA_PROC_OK;
}
SpellAuraProcResult Unit::HandleModRating(Unit* /*pVictim*/, uint32 /*damage*/, Aura* triggeredByAura, SpellEntry const * /*procSpell*/, uint32 /*procFlag*/, uint32 /*procEx*/, uint32 /*cooldown*/)
{
SpellEntry const *spellInfo = triggeredByAura->GetSpellProto();
if (spellInfo->Id == 71564) // Deadly Precision
{
// Remove only single aura from stack
if (triggeredByAura->GetStackAmount() > 1 && !triggeredByAura->GetHolder()->ModStackAmount(-1))
return SPELL_AURA_PROC_CANT_TRIGGER;
}
return SPELL_AURA_PROC_OK;
}
SpellAuraProcResult Unit::HandleRemoveByDamageProc(Unit* pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const *procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown)
{
triggeredByAura->SetInUse(true);
RemoveAurasByCasterSpell(triggeredByAura->GetSpellProto()->Id, triggeredByAura->GetCasterGUID());
triggeredByAura->SetInUse(false);
return SPELL_AURA_PROC_OK;
}
SpellAuraProcResult Unit::HandleRemoveByDamageChanceProc(Unit* pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const *procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown)
{
// The chance to dispel an aura depends on the damage taken with respect to the casters level.
uint32 max_dmg = getLevel() > 8 ? 25 * getLevel() - 150 : 50;
float chance = float(damage) / max_dmg * 100.0f;
if (roll_chance_f(chance))
return HandleRemoveByDamageProc(pVictim, damage, triggeredByAura, procSpell, procFlag, procEx, cooldown);
return SPELL_AURA_PROC_FAILED;
}
| lordaragorn/infinity_335 | src/game/UnitAuraProcHandler.cpp | C++ | gpl-2.0 | 228,258 |
# -*- coding: utf-8 -*-
"""
nidaba.plugins.leptonica
~~~~~~~~~~~~~~~~~~~~~~~~
Plugin accessing `leptonica <http://leptonica.com>`_ functions.
This plugin requires a liblept shared object in the current library search
path. On Debian-based systems it can be installed using apt-get
.. code-block:: console
# apt-get install libleptonica-dev
Leptonica's APIs are rather unstable and may differ significantly between
versions. If this plugin fails with weird error messages or workers are just
dying without discernable cause please submit a bug report including your
leptonica version.
"""
from __future__ import unicode_literals, print_function, absolute_import
import ctypes
from nidaba import storage
from nidaba.celery import app
from nidaba.tasks.helper import NidabaTask
from nidaba.nidabaexceptions import (NidabaInvalidParameterException,
NidabaLeptonicaException,
NidabaPluginException)
leptlib = 'liblept.so'
def setup(*args, **kwargs):
try:
ctypes.cdll.LoadLibrary(leptlib)
except Exception as e:
raise NidabaPluginException(e.message)
@app.task(base=NidabaTask, name=u'nidaba.binarize.sauvola',
arg_values={'whsize': 'int', 'factor': (0.0, 1.0)})
def sauvola(doc, method=u'sauvola', whsize=10, factor=0.35):
"""
Binarizes an input document utilizing Sauvola thresholding as described in
[0]. Expects 8bpp grayscale images as input.
[0] Sauvola, Jaakko, and Matti Pietikäinen. "Adaptive document image
binarization." Pattern recognition 33.2 (2000): 225-236.
Args:
doc (unicode): The input document tuple.
method (unicode): The suffix string appended to all output files
whsize (int): The window width and height that local statistics are
calculated on are twice the value of whsize. The minimal
value is 2.
factor (float): The threshold reduction factor due to variance. 0 =<
factor < 1.
Returns:
(unicode, unicode): Storage tuple of the output file
Raises:
NidabaInvalidParameterException: Input parameters are outside the valid
range.
"""
input_path = storage.get_abs_path(*doc)
output_path = storage.insert_suffix(input_path, method, unicode(whsize),
unicode(factor))
lept_sauvola(input_path, output_path, whsize, factor)
return storage.get_storage_path(output_path)
def lept_sauvola(image_path, output_path, whsize=10, factor=0.35):
"""
Binarizes an input document utilizing Sauvola thresholding as described in
[0]. Expects 8bpp grayscale images as input.
[0] Sauvola, Jaakko, and Matti Pietikäinen. "Adaptive document image
binarization." Pattern recognition 33.2 (2000): 225-236.
Args:
image_path (unicode): Input image path
output_path (unicode): Output image path
whsize (int): The window width and height that local statistics are
calculated on are twice the value of whsize. The minimal
value is 2.
factor (float): The threshold reduction factor due to variance. 0 =<
factor < 1.
Raises:
NidabaInvalidParameterException: Input parameters are outside the valid
range.
"""
if whsize < 2 or factor >= 1.0 or factor < 0:
raise NidabaInvalidParameterException('Parameters ({}, {}) outside of valid range'.format(whsize, factor))
try:
lept = ctypes.cdll.LoadLibrary(leptlib)
except OSError as e:
raise NidabaLeptonicaException('Loading leptonica failed: ' +
e.message)
pix = ctypes.c_void_p(lept.pixRead(image_path.encode('utf-8')))
opix = ctypes.c_void_p()
if lept.pixGetDepth(pix) != 8:
lept.pixDestroy(ctypes.byref(pix))
raise NidabaLeptonicaException('Input image is not grayscale')
if lept.pixSauvolaBinarize(pix, whsize, ctypes.c_float(factor), 0, None,
None, None, ctypes.byref(opix)):
lept.pixDestroy(ctypes.byref(pix))
raise NidabaLeptonicaException('Binarization failed for unknown '
'reason.')
if lept.pixWriteImpliedFormat(output_path.encode('utf-8'), opix, 100, 0):
lept.pixDestroy(ctypes.byref(pix))
lept.pixDestroy(ctypes.byref(pix))
raise NidabaLeptonicaException('Writing binarized PIX failed')
lept.pixDestroy(ctypes.byref(opix))
lept.pixDestroy(ctypes.byref(pix))
@app.task(base=NidabaTask, name=u'nidaba.img.dewarp')
def dewarp(doc, method=u'dewarp'):
"""
Removes perspective distortion (as commonly exhibited by overhead scans)
from an 1bpp input image.
Args:
doc (unicode, unicode): The input document tuple.
method (unicode): The suffix string appended to all output files.
Returns:
(unicode, unicode): Storage tuple of the output file
"""
input_path = storage.get_abs_path(*doc)
output_path = storage.insert_suffix(input_path, method)
lept_dewarp(input_path, output_path)
return storage.get_storage_path(output_path)
def lept_dewarp(image_path, output_path):
"""
Removes perspective distortion from an 1bpp input image.
Args:
image_path (unicode): Path to the input image
output_path (unicode): Path to the output image
Raises:
NidabaLeptonicaException if one of leptonica's functions failed.
"""
try:
lept = ctypes.cdll.LoadLibrary(leptlib)
except OSError as e:
raise NidabaLeptonicaException('Loading leptonica failed: ' +
e.message)
pix = ctypes.c_void_p(lept.pixRead(image_path.encode('utf-8')))
opix = ctypes.c_void_p()
ret = lept.dewarpSinglePage(pix, 0, 1, 1, ctypes.byref(opix), None, 0)
if ret == 1 or ret is None:
lept.pixDestroy(ctypes.byref(pix))
lept.pixDestroy(ctypes.byref(opix))
raise NidabaLeptonicaException('Dewarping failed for unknown reason.')
if lept.pixWriteImpliedFormat(output_path.encode('utf-8'), opix, 100, 0):
lept.pixDestroy(ctypes.byref(pix))
lept.pixDestroy(ctypes.byref(opix))
raise NidabaLeptonicaException('Writing dewarped PIX failed')
lept.pixDestroy(ctypes.byref(pix))
lept.pixDestroy(ctypes.byref(opix))
@app.task(base=NidabaTask, name=u'nidaba.img.deskew')
def deskew(doc, method=u'deskew'):
"""
Removes skew (rotational distortion) from an 1bpp input image.
Args:
doc (unicode, unicode): The input document tuple.
method (unicode): The suffix string appended to all output files.
Returns:
(unicode, unicode): Storage tuple of the output file
"""
input_path = storage.get_abs_path(*doc)
output_path = storage.insert_suffix(input_path, method)
lept_deskew(input_path, output_path)
return storage.get_storage_path(output_path)
def lept_deskew(image_path, output_path):
"""
Removes skew (rotational distortion from an 1bpp input image.
Args:
image_path (unicode): Input image
output_path (unicode): Path to the output document
Raises:
NidabaLeptonicaException if one of leptonica's functions failed.
"""
try:
lept = ctypes.cdll.LoadLibrary(leptlib)
except OSError as e:
raise NidabaLeptonicaException('Loading leptonica failed: ' +
e.message)
pix = ctypes.c_void_p(lept.pixRead(image_path.encode('utf-8')))
opix = ctypes.c_void_p(lept.pixFindSkewAndDeskew(pix, 4, None, None))
if opix is None:
lept.pixDestroy(ctypes.byref(pix))
raise NidabaLeptonicaException('Deskewing failed for unknown reason.')
if lept.pixWriteImpliedFormat(output_path.encode('utf-8'), opix, 100, 0):
lept.pixDestroy(ctypes.byref(pix))
lept.pixDestroy(ctypes.byref(opix))
raise NidabaLeptonicaException('Writing deskewed PIX failed')
lept.pixDestroy(ctypes.byref(pix))
lept.pixDestroy(ctypes.byref(opix))
| OpenPhilology/nidaba | nidaba/plugins/leptonica.py | Python | gpl-2.0 | 8,246 |
<?php
/**
* @version 0.0.6
* @package com_jazz_mastering
* @copyright Copyright (C) 2012. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
* @author Artur Pañach Bargalló <arturictus@gmail.com> - http://
*/
defined('_JEXEC') or die;
jimport('joomla.application.component.modellist');
/**
* Methods supporting a list of Jazz_mastering records.
*/
class Jazz_masteringModelCadencias extends JModelList {
/**
* Constructor.
*
* @param array An optional associative array of configuration settings.
* @see JController
* @since 1.6
*/
public function __construct($config = array()) {
parent::__construct($config);
}
/**
* Method to auto-populate the model state.
*
* Note. Calling getState in this method will result in recursion.
*
* @since 1.6
*/
protected function populateState($ordering = null, $direction = null) {
// Initialise variables.
$app = JFactory::getApplication();
// List state information
$limit = $app->getUserStateFromRequest('global.list.limit', 'limit', $app->getCfg('list_limit'));
$this->setState('list.limit', $limit);
$limitstart = JFactory::getApplication()->input->getInt('limitstart', 0);
$this->setState('list.start', $limitstart);
// List state information.
parent::populateState($ordering, $direction);
}
/**
* Build an SQL query to load the list data.
*
* @return JDatabaseQuery
* @since 1.6
*/
protected function getListQuery() {
// Create a new query object.
$db = $this->getDbo();
$query = $db->getQuery(true);
// Select the required fields from the table.
$query->select(
$this->getState(
'list.select', 'a.*'
)
);
$query->from('`#__jazz_mastering_cadencia` AS a');
// Join over the created by field 'values_cadencia_creado_por'
$query->select('values_cadencia_creado_por.name AS values_cadencia_creado_por');
$query->join('LEFT', '#__users AS values_cadencia_creado_por ON values_cadencia_creado_por.id = a.values_cadencia_creado_por');
// Filter by search in title
$search = $this->getState('filter.search');
if (!empty($search)) {
if (stripos($search, 'id:') === 0) {
$query->where('a.id = '.(int) substr($search, 3));
} else {
$search = $db->Quote('%'.$db->escape($search, true).'%');
}
}
return $query;
}
}
| lion01/weprob | components/com_jazz_mastering/models/cadencias.php | PHP | gpl-2.0 | 2,698 |
#include "Card.h"
#include "Game.h"
#include <iostream>
#include <array>
#include <string>
#include <vector>
#include <algorithm>
#include <random>
#include <cstdlib>
#include <ctime>
using namespace std;
using namespace zks::game::card;
int test_deck() {
CardDeck deck(1);
CardDeck d1, d2;
deck.shuffle();
cout << "deck: " << deck.str() << endl;
cout << "d1: " << d1.str() << endl;
cout << "d2: " << d2.str() << endl;
cout << "\nget from back:\n";
for (auto i = 0; i<10; ++i) {
d1.put_card(deck.get_card());
cout << d1.str() << endl;
}
cout << "\nget from front:\n";
for (auto i = 0; i<10; ++i) {
d2.put_card(deck.get_card(false));
cout << d2.str() << endl;
}
cout << "\n";
cout << "deck: " << deck.str() << endl;
return 0;
}
int main() {
Game g;
cout << "game: \n" << g.str() << endl;
g.prepare();
cout << "game: \n" << g.str() << endl;
g.play();
cout << "game: \n" << g.str() << endl;
g.post();
cout << "game: \n" << g.str() << endl;
return 0;
}
int test_suite() {
for (const auto& s : Suite()) {
cout << to_string(s) << ", ";
}
cout << endl;
return 0;
}
int test_number() {
for (const auto& n : Number()) {
cout << to_string(n) << ", ";
}
cout << endl;
return 0;
}
int test_card() {
vector<Card> deck;
for (auto s = begin(Suite()); s<Suite::JOKER; ++s) {
for (const auto& n : Number()) {
deck.emplace_back(s, n);
}
}
cout << "\n";
for (auto const& c : deck) {
cout << to_string(c) << ", ";
}
cout << "\n";
std::srand(std::time(0));
std::array<int, std::mt19937::state_size> seed_data;
std::generate(seed_data.begin(), seed_data.end(), std::rand);
std::seed_seq seq(seed_data.begin(), seed_data.end());
std::mt19937 g(seq);
std::shuffle(deck.begin(), deck.end(), g);
cout << "\n";
for (auto const& c : deck) {
cout << to_string(c) << ", ";
}
cout << "\n";
return 0;
}
| jimzshi/game | src/card/main.cpp | C++ | gpl-2.0 | 1,866 |
<?php
/*
* This file is part of Respect/Validation.
*
* (c) Alexandre Gomes Gaigalas <alexandre@gaigalas.net>
*
* For the full copyright and license information, please view the "LICENSE.md"
* file that was distributed with this source code.
*/
namespace Respect\Validation\Rules\SubdivisionCode;
use Respect\Validation\Rules\AbstractSearcher;
/**
* Validator for Turks and Caicos Islands subdivision code.
*
* ISO 3166-1 alpha-2: TC
*
* @link https://salsa.debian.org/iso-codes-team/iso-codes
*/
class TcSubdivisionCode extends AbstractSearcher
{
public $haystack = [
'AC', // Ambergris Cays
'DC', // Dellis Cay
'EC', // East Caicos
'FC', // French Cay
'GT', // Grand Turk
'LW', // Little Water Cay
'MC', // Middle Caicos
'NC', // North Caicos
'PN', // Pine Cay
'PR', // Providenciales
'RC', // Parrot Cay
'SC', // South Caicos
'SL', // Salt Cay
'WC', // West Caicos
];
public $compareIdentical = true;
}
| PaymentHighway/woocommerce-gateway-paymenthighway | includes/vendor/respect/validation/library/Rules/SubdivisionCode/TcSubdivisionCode.php | PHP | gpl-2.0 | 1,048 |
<?php
/* @particles/assets.html.twig */
class __TwigTemplate_299c183811cc71a2e64a3daab6e1f6fca93d29687649f11bd1c1431814d9f4f7 extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
// line 1
$this->parent = $this->loadTemplate("@nucleus/partials/particle.html.twig", "@particles/assets.html.twig", 1);
$this->blocks = array(
'stylesheets' => array($this, 'block_stylesheets'),
'javascript' => array($this, 'block_javascript'),
'javascript_footer' => array($this, 'block_javascript_footer'),
);
}
protected function doGetParent(array $context)
{
return "@nucleus/partials/particle.html.twig";
}
protected function doDisplay(array $context, array $blocks = array())
{
$this->parent->display($context, array_merge($this->blocks, $blocks));
}
// line 3
public function block_stylesheets($context, array $blocks = array())
{
// line 4
echo " ";
if ($this->getAttribute((isset($context["particle"]) ? $context["particle"] : null), "enabled", array())) {
// line 5
echo " ";
$context['_parent'] = $context;
$context['_seq'] = twig_ensure_traversable($this->getAttribute((isset($context["particle"]) ? $context["particle"] : null), "css", array()));
foreach ($context['_seq'] as $context["_key"] => $context["css"]) {
// line 6
echo " ";
$context["attr_extra"] = "";
// line 7
echo " ";
if ($this->getAttribute($context["css"], "extra", array())) {
// line 8
echo " ";
$context['_parent'] = $context;
$context['_seq'] = twig_ensure_traversable($this->getAttribute($context["css"], "extra", array()));
foreach ($context['_seq'] as $context["_key"] => $context["attributes"]) {
// line 9
echo " ";
$context['_parent'] = $context;
$context['_seq'] = twig_ensure_traversable($context["attributes"]);
foreach ($context['_seq'] as $context["key"] => $context["value"]) {
// line 10
echo " ";
$context["attr_extra"] = ((((((isset($context["attr_extra"]) ? $context["attr_extra"] : null) . " ") . twig_escape_filter($this->env, $context["key"])) . "=\"") . twig_escape_filter($this->env, $context["value"], "html_attr")) . "\"");
// line 11
echo " ";
}
$_parent = $context['_parent'];
unset($context['_seq'], $context['_iterated'], $context['key'], $context['value'], $context['_parent'], $context['loop']);
$context = array_intersect_key($context, $_parent) + $_parent;
// line 12
echo " ";
}
$_parent = $context['_parent'];
unset($context['_seq'], $context['_iterated'], $context['_key'], $context['attributes'], $context['_parent'], $context['loop']);
$context = array_intersect_key($context, $_parent) + $_parent;
// line 13
echo " ";
}
// line 14
echo "
";
// line 15
if ($this->getAttribute($context["css"], "location", array())) {
// line 16
echo " <link rel=\"stylesheet\" href=\"";
echo twig_escape_filter($this->env, $this->env->getExtension('GantryTwig')->urlFunc($this->getAttribute($context["css"], "location", array())), "html", null, true);
echo "\" type=\"text/css\"";
echo (isset($context["attr_extra"]) ? $context["attr_extra"] : null);
echo " />
";
}
// line 18
echo "
";
// line 19
if ($this->getAttribute($context["css"], "inline", array())) {
// line 20
echo " <style type=\"text/css\"";
echo (isset($context["attr_extra"]) ? $context["attr_extra"] : null);
echo ">";
echo $this->getAttribute($context["css"], "inline", array());
echo "</style>
";
}
// line 22
echo " ";
}
$_parent = $context['_parent'];
unset($context['_seq'], $context['_iterated'], $context['_key'], $context['css'], $context['_parent'], $context['loop']);
$context = array_intersect_key($context, $_parent) + $_parent;
// line 23
echo " ";
}
}
// line 26
public function block_javascript($context, array $blocks = array())
{
// line 27
echo " ";
if ($this->getAttribute((isset($context["particle"]) ? $context["particle"] : null), "enabled", array())) {
// line 28
echo " ";
$context['_parent'] = $context;
$context['_seq'] = twig_ensure_traversable($this->getAttribute((isset($context["particle"]) ? $context["particle"] : null), "javascript", array()));
foreach ($context['_seq'] as $context["_key"] => $context["script"]) {
// line 29
echo " ";
if (($this->getAttribute($context["script"], "in_footer", array()) == false)) {
// line 30
echo " ";
$context["attr_extra"] = "";
// line 31
echo " ";
if ($this->getAttribute($context["script"], "extra", array())) {
// line 32
echo " ";
$context['_parent'] = $context;
$context['_seq'] = twig_ensure_traversable($this->getAttribute($context["script"], "extra", array()));
foreach ($context['_seq'] as $context["_key"] => $context["attributes"]) {
// line 33
echo " ";
$context['_parent'] = $context;
$context['_seq'] = twig_ensure_traversable($context["attributes"]);
foreach ($context['_seq'] as $context["key"] => $context["value"]) {
// line 34
echo " ";
$context["attr_extra"] = ((((((isset($context["attr_extra"]) ? $context["attr_extra"] : null) . " ") . twig_escape_filter($this->env, $context["key"])) . "=\"") . twig_escape_filter($this->env, $context["value"], "html_attr")) . "\"");
// line 35
echo " ";
}
$_parent = $context['_parent'];
unset($context['_seq'], $context['_iterated'], $context['key'], $context['value'], $context['_parent'], $context['loop']);
$context = array_intersect_key($context, $_parent) + $_parent;
// line 36
echo " ";
}
$_parent = $context['_parent'];
unset($context['_seq'], $context['_iterated'], $context['_key'], $context['attributes'], $context['_parent'], $context['loop']);
$context = array_intersect_key($context, $_parent) + $_parent;
// line 37
echo " ";
}
// line 38
echo "
";
// line 39
if ($this->getAttribute($context["script"], "location", array())) {
// line 40
echo " <script src=\"";
echo twig_escape_filter($this->env, $this->env->getExtension('GantryTwig')->urlFunc($this->getAttribute($context["script"], "location", array())), "html", null, true);
echo "\" type=\"text/javascript\"";
echo (isset($context["attr_extra"]) ? $context["attr_extra"] : null);
echo "></script>
";
}
// line 42
echo "
";
// line 43
if ($this->getAttribute($context["script"], "inline", array())) {
// line 44
echo " <script type=\"text/javascript\"";
echo (isset($context["attr_extra"]) ? $context["attr_extra"] : null);
echo ">";
echo $this->getAttribute($context["script"], "inline", array());
echo "</script>
";
}
// line 46
echo " ";
}
// line 47
echo " ";
}
$_parent = $context['_parent'];
unset($context['_seq'], $context['_iterated'], $context['_key'], $context['script'], $context['_parent'], $context['loop']);
$context = array_intersect_key($context, $_parent) + $_parent;
// line 48
echo " ";
}
}
// line 51
public function block_javascript_footer($context, array $blocks = array())
{
// line 52
echo " ";
if ($this->getAttribute((isset($context["particle"]) ? $context["particle"] : null), "enabled", array())) {
// line 53
echo " ";
$context['_parent'] = $context;
$context['_seq'] = twig_ensure_traversable($this->getAttribute((isset($context["particle"]) ? $context["particle"] : null), "javascript", array()));
foreach ($context['_seq'] as $context["_key"] => $context["script"]) {
// line 54
echo " ";
if (($this->getAttribute($context["script"], "in_footer", array()) == true)) {
// line 55
echo " ";
$context["attr_extra"] = "";
// line 56
echo "
";
// line 57
if ($this->getAttribute($context["script"], "extra", array())) {
// line 58
echo " ";
$context['_parent'] = $context;
$context['_seq'] = twig_ensure_traversable($this->getAttribute($context["script"], "extra", array()));
foreach ($context['_seq'] as $context["_key"] => $context["attributes"]) {
// line 59
echo " ";
$context['_parent'] = $context;
$context['_seq'] = twig_ensure_traversable($context["attributes"]);
foreach ($context['_seq'] as $context["key"] => $context["value"]) {
// line 60
echo " ";
$context["attr_extra"] = ((((((isset($context["attr_extra"]) ? $context["attr_extra"] : null) . " ") . twig_escape_filter($this->env, $context["key"])) . "=\"") . twig_escape_filter($this->env, $context["value"], "html_attr")) . "\"");
// line 61
echo " ";
}
$_parent = $context['_parent'];
unset($context['_seq'], $context['_iterated'], $context['key'], $context['value'], $context['_parent'], $context['loop']);
$context = array_intersect_key($context, $_parent) + $_parent;
// line 62
echo " ";
}
$_parent = $context['_parent'];
unset($context['_seq'], $context['_iterated'], $context['_key'], $context['attributes'], $context['_parent'], $context['loop']);
$context = array_intersect_key($context, $_parent) + $_parent;
// line 63
echo " ";
}
// line 64
echo "
";
// line 65
if ($this->getAttribute($context["script"], "location", array())) {
// line 66
echo " <script src=\"";
echo twig_escape_filter($this->env, $this->env->getExtension('GantryTwig')->urlFunc($this->getAttribute($context["script"], "location", array())), "html", null, true);
echo "\" type=\"text/javascript\"";
echo (isset($context["attr_extra"]) ? $context["attr_extra"] : null);
echo "></script>
";
}
// line 68
echo "
";
// line 69
if ($this->getAttribute($context["script"], "inline", array())) {
// line 70
echo " <script type=\"text/javascript\"";
echo (isset($context["attr_extra"]) ? $context["attr_extra"] : null);
echo ">";
echo $this->getAttribute($context["script"], "inline", array());
echo "</script>
";
}
// line 72
echo " ";
}
// line 73
echo " ";
}
$_parent = $context['_parent'];
unset($context['_seq'], $context['_iterated'], $context['_key'], $context['script'], $context['_parent'], $context['loop']);
$context = array_intersect_key($context, $_parent) + $_parent;
// line 74
echo " ";
}
}
public function getTemplateName()
{
return "@particles/assets.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 285 => 74, 279 => 73, 276 => 72, 268 => 70, 266 => 69, 263 => 68, 255 => 66, 253 => 65, 250 => 64, 247 => 63, 241 => 62, 235 => 61, 232 => 60, 227 => 59, 222 => 58, 220 => 57, 217 => 56, 214 => 55, 211 => 54, 206 => 53, 203 => 52, 200 => 51, 195 => 48, 189 => 47, 186 => 46, 178 => 44, 176 => 43, 173 => 42, 165 => 40, 163 => 39, 160 => 38, 157 => 37, 151 => 36, 145 => 35, 142 => 34, 137 => 33, 132 => 32, 129 => 31, 126 => 30, 123 => 29, 118 => 28, 115 => 27, 112 => 26, 107 => 23, 101 => 22, 93 => 20, 91 => 19, 88 => 18, 80 => 16, 78 => 15, 75 => 14, 72 => 13, 66 => 12, 60 => 11, 57 => 10, 52 => 9, 47 => 8, 44 => 7, 41 => 6, 36 => 5, 33 => 4, 30 => 3, 11 => 1,);
}
}
/* {% extends '@nucleus/partials/particle.html.twig' %}*/
/* */
/* {% block stylesheets %}*/
/* {% if (particle.enabled) %}*/
/* {% for css in particle.css %}*/
/* {% set attr_extra = '' %}*/
/* {% if css.extra %}*/
/* {% for attributes in css.extra %}*/
/* {% for key, value in attributes %}*/
/* {% set attr_extra = attr_extra ~ ' ' ~ key|e ~ '="' ~ value|e('html_attr') ~ '"' %}*/
/* {% endfor %}*/
/* {% endfor %}*/
/* {% endif %}*/
/* */
/* {% if css.location %}*/
/* <link rel="stylesheet" href="{{ url(css.location) }}" type="text/css"{{ attr_extra|raw }} />*/
/* {% endif %}*/
/* */
/* {% if css.inline %}*/
/* <style type="text/css"{{ attr_extra|raw }}>{{ css.inline|raw }}</style>*/
/* {% endif %}*/
/* {% endfor %}*/
/* {% endif %}*/
/* {% endblock %}*/
/* */
/* {% block javascript %}*/
/* {% if particle.enabled %}*/
/* {% for script in particle.javascript %}*/
/* {% if script.in_footer == false %}*/
/* {% set attr_extra = '' %}*/
/* {% if script.extra %}*/
/* {% for attributes in script.extra %}*/
/* {% for key, value in attributes %}*/
/* {% set attr_extra = attr_extra ~ ' ' ~ key|e ~ '="' ~ value|e('html_attr') ~ '"' %}*/
/* {% endfor %}*/
/* {% endfor %}*/
/* {% endif %}*/
/* */
/* {% if script.location %}*/
/* <script src="{{ url(script.location) }}" type="text/javascript"{{ attr_extra|raw }}></script>*/
/* {% endif %}*/
/* */
/* {% if script.inline %}*/
/* <script type="text/javascript"{{ attr_extra|raw }}>{{ script.inline|raw }}</script>*/
/* {% endif %}*/
/* {% endif %}*/
/* {% endfor %}*/
/* {% endif %}*/
/* {% endblock %}*/
/* */
/* {% block javascript_footer %}*/
/* {% if particle.enabled %}*/
/* {% for script in particle.javascript %}*/
/* {% if script.in_footer == true %}*/
/* {% set attr_extra = '' %}*/
/* */
/* {% if script.extra %}*/
/* {% for attributes in script.extra %}*/
/* {% for key, value in attributes %}*/
/* {% set attr_extra = attr_extra ~ ' ' ~ key|e ~ '="' ~ value|e('html_attr') ~ '"' %}*/
/* {% endfor %}*/
/* {% endfor %}*/
/* {% endif %}*/
/* */
/* {% if script.location %}*/
/* <script src="{{ url(script.location) }}" type="text/javascript"{{ attr_extra|raw }}></script>*/
/* {% endif %}*/
/* */
/* {% if script.inline %}*/
/* <script type="text/javascript"{{ attr_extra|raw }}>{{ script.inline|raw }}</script>*/
/* {% endif %}*/
/* {% endif %}*/
/* {% endfor %}*/
/* {% endif %}*/
/* {% endblock %}*/
/* */
/* */
| JozefAB/neoacu | cache/gantry5/g5_hydrogen/twig/f3/f36bf52c1bc96552cfcecedfc074a62f36b34d410df8d972a61f3bb3c60d3ea1.php | PHP | gpl-2.0 | 19,381 |
# -*- coding: utf-8 -*-
#
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.exceptions import MethodNotAllowed
from rest_framework.response import Response
from common.const.http import POST, PUT
from common.mixins.api import CommonApiMixin
from common.permissions import IsValidUser, IsOrgAdmin
from tickets import serializers
from tickets.models import Ticket
from tickets.permissions.ticket import IsAssignee, IsAssigneeOrApplicant, NotClosed
__all__ = ['TicketViewSet']
class TicketViewSet(CommonApiMixin, viewsets.ModelViewSet):
permission_classes = (IsValidUser,)
serializer_class = serializers.TicketDisplaySerializer
serializer_classes = {
'open': serializers.TicketApplySerializer,
'approve': serializers.TicketApproveSerializer,
}
filterset_fields = [
'id', 'title', 'type', 'action', 'status', 'applicant', 'applicant_display', 'processor',
'processor_display', 'assignees__id'
]
search_fields = [
'title', 'action', 'type', 'status', 'applicant_display', 'processor_display'
]
def create(self, request, *args, **kwargs):
raise MethodNotAllowed(self.action)
def update(self, request, *args, **kwargs):
raise MethodNotAllowed(self.action)
def destroy(self, request, *args, **kwargs):
raise MethodNotAllowed(self.action)
def get_queryset(self):
queryset = Ticket.get_user_related_tickets(self.request.user)
return queryset
def perform_create(self, serializer):
instance = serializer.save()
instance.open(applicant=self.request.user)
@action(detail=False, methods=[POST], permission_classes=[IsValidUser, ])
def open(self, request, *args, **kwargs):
return super().create(request, *args, **kwargs)
@action(detail=True, methods=[PUT], permission_classes=[IsOrgAdmin, IsAssignee, NotClosed])
def approve(self, request, *args, **kwargs):
response = super().update(request, *args, **kwargs)
instance = self.get_object()
instance.approve(processor=self.request.user)
return response
@action(detail=True, methods=[PUT], permission_classes=[IsOrgAdmin, IsAssignee, NotClosed])
def reject(self, request, *args, **kwargs):
instance = self.get_object()
serializer = self.get_serializer(instance)
instance.reject(processor=request.user)
return Response(serializer.data)
@action(detail=True, methods=[PUT], permission_classes=[IsAssigneeOrApplicant, NotClosed])
def close(self, request, *args, **kwargs):
instance = self.get_object()
serializer = self.get_serializer(instance)
instance.close(processor=request.user)
return Response(serializer.data)
| skyoo/jumpserver | apps/tickets/api/ticket.py | Python | gpl-2.0 | 2,796 |
/*
* Copyright (C) 2014-2017 StormCore
*
* 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 2 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/>.
*/
/* ScriptData
SDName: Boss_Twinemperors
SD%Complete: 95
SDComment:
SDCategory: Temple of Ahn'Qiraj
EndScriptData */
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "temple_of_ahnqiraj.h"
#include "WorldPacket.h"
#include "Item.h"
#include "Spell.h"
enum Spells
{
SPELL_HEAL_BROTHER = 7393,
SPELL_TWIN_TELEPORT = 800, // CTRA watches for this spell to start its teleport timer
SPELL_TWIN_TELEPORT_VISUAL = 26638, // visual
SPELL_EXPLODEBUG = 804,
SPELL_MUTATE_BUG = 802,
SPELL_BERSERK = 26662,
SPELL_UPPERCUT = 26007,
SPELL_UNBALANCING_STRIKE = 26613,
SPELL_SHADOWBOLT = 26006,
SPELL_BLIZZARD = 26607,
SPELL_ARCANEBURST = 568,
};
enum Sound
{
SOUND_VL_AGGRO = 8657, //8657 - Aggro - To Late
SOUND_VL_KILL = 8658, //8658 - Kill - You will not
SOUND_VL_DEATH = 8659, //8659 - Death
SOUND_VN_DEATH = 8660, //8660 - Death - Feel
SOUND_VN_AGGRO = 8661, //8661 - Aggro - Let none
SOUND_VN_KILL = 8662, //8661 - Kill - your fate
};
enum Misc
{
PULL_RANGE = 50,
ABUSE_BUG_RANGE = 20,
VEKLOR_DIST = 20, // VL will not come to melee when attacking
TELEPORTTIME = 30000
};
struct boss_twinemperorsAI : public ScriptedAI
{
boss_twinemperorsAI(Creature* creature): ScriptedAI(creature)
{
Initialize();
instance = creature->GetInstanceScript();
}
void Initialize()
{
Heal_Timer = 0; // first heal immediately when they get close together
Teleport_Timer = TELEPORTTIME;
AfterTeleport = false;
tspellcast = false;
AfterTeleportTimer = 0;
Abuse_Bug_Timer = urand(10000, 17000);
BugsTimer = 2000;
DontYellWhenDead = false;
EnrageTimer = 15 * 60000;
}
InstanceScript* instance;
uint32 Heal_Timer;
uint32 Teleport_Timer;
bool AfterTeleport;
uint32 AfterTeleportTimer;
bool DontYellWhenDead;
uint32 Abuse_Bug_Timer, BugsTimer;
bool tspellcast;
uint32 EnrageTimer;
virtual bool IAmVeklor() = 0;
virtual void Reset() override = 0;
virtual void CastSpellOnBug(Creature* target) = 0;
void TwinReset()
{
Initialize();
me->ClearUnitState(UNIT_STATE_STUNNED);
}
Creature* GetOtherBoss()
{
return ObjectAccessor::GetCreature(*me, instance->GetGuidData(IAmVeklor() ? DATA_VEKNILASH : DATA_VEKLOR));
}
void DamageTaken(Unit* /*done_by*/, uint32 &damage) override
{
Unit* pOtherBoss = GetOtherBoss();
if (pOtherBoss)
{
float dPercent = ((float)damage) / ((float)me->GetMaxHealth());
int odmg = (int)(dPercent * ((float)pOtherBoss->GetMaxHealth()));
int ohealth = pOtherBoss->GetHealth()-odmg;
pOtherBoss->SetHealth(ohealth > 0 ? ohealth : 0);
if (ohealth <= 0)
{
pOtherBoss->setDeathState(JUST_DIED);
pOtherBoss->SetFlag(OBJECT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE);
}
}
}
void JustDied(Unit* /*killer*/) override
{
Creature* pOtherBoss = GetOtherBoss();
if (pOtherBoss)
{
pOtherBoss->SetHealth(0);
pOtherBoss->setDeathState(JUST_DIED);
pOtherBoss->SetFlag(OBJECT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE);
ENSURE_AI(boss_twinemperorsAI, pOtherBoss->AI())->DontYellWhenDead = true;
}
if (!DontYellWhenDead) // I hope AI is not threaded
DoPlaySoundToSet(me, IAmVeklor() ? SOUND_VL_DEATH : SOUND_VN_DEATH);
}
void KilledUnit(Unit* /*victim*/) override
{
DoPlaySoundToSet(me, IAmVeklor() ? SOUND_VL_KILL : SOUND_VN_KILL);
}
void EnterCombat(Unit* who) override
{
DoZoneInCombat();
Creature* pOtherBoss = GetOtherBoss();
if (pOtherBoss)
{
/// @todo we should activate the other boss location so he can start attackning even if nobody
// is near I dont know how to do that
if (!pOtherBoss->IsInCombat())
{
ScriptedAI* otherAI = ENSURE_AI(ScriptedAI, pOtherBoss->AI());
DoPlaySoundToSet(me, IAmVeklor() ? SOUND_VL_AGGRO : SOUND_VN_AGGRO);
otherAI->AttackStart(who);
otherAI->DoZoneInCombat();
}
}
}
void SpellHit(Unit* caster, const SpellInfo* entry) override
{
if (caster == me)
return;
Creature* pOtherBoss = GetOtherBoss();
if (entry->Id != SPELL_HEAL_BROTHER || !pOtherBoss)
return;
// add health so we keep same percentage for both brothers
uint32 mytotal = me->GetMaxHealth(), histotal = pOtherBoss->GetMaxHealth();
float mult = ((float)mytotal) / ((float)histotal);
if (mult < 1)
mult = 1.0f/mult;
#define HEAL_BROTHER_AMOUNT 30000.0f
uint32 largerAmount = (uint32)((HEAL_BROTHER_AMOUNT * mult) - HEAL_BROTHER_AMOUNT);
if (mytotal > histotal)
{
uint32 h = me->GetHealth()+largerAmount;
me->SetHealth(std::min(mytotal, h));
}
else
{
uint32 h = pOtherBoss->GetHealth()+largerAmount;
pOtherBoss->SetHealth(std::min(histotal, h));
}
}
void TryHealBrother(uint32 diff)
{
if (IAmVeklor()) // this spell heals caster and the other brother so let VN cast it
return;
if (Heal_Timer <= diff)
{
Unit* pOtherBoss = GetOtherBoss();
if (pOtherBoss && pOtherBoss->IsWithinDist(me, 60))
{
DoCast(pOtherBoss, SPELL_HEAL_BROTHER);
Heal_Timer = 1000;
}
} else Heal_Timer -= diff;
}
void TeleportToMyBrother()
{
Teleport_Timer = TELEPORTTIME;
if (IAmVeklor())
return; // mechanics handled by veknilash so they teleport exactly at the same time and to correct coordinates
Creature* pOtherBoss = GetOtherBoss();
if (pOtherBoss)
{
//me->MonsterYell("Teleporting ...", LANG_UNIVERSAL, 0);
Position thisPos;
thisPos.Relocate(me);
Position otherPos;
otherPos.Relocate(pOtherBoss);
pOtherBoss->SetPosition(thisPos);
me->SetPosition(otherPos);
SetAfterTeleport();
ENSURE_AI(boss_twinemperorsAI, pOtherBoss->AI())->SetAfterTeleport();
}
}
void SetAfterTeleport()
{
me->InterruptNonMeleeSpells(false);
DoStopAttack();
DoResetThreat();
DoCast(me, SPELL_TWIN_TELEPORT_VISUAL);
me->AddUnitState(UNIT_STATE_STUNNED);
AfterTeleport = true;
AfterTeleportTimer = 2000;
tspellcast = false;
}
bool TryActivateAfterTTelep(uint32 diff)
{
if (AfterTeleport)
{
if (!tspellcast)
{
me->ClearUnitState(UNIT_STATE_STUNNED);
DoCast(me, SPELL_TWIN_TELEPORT);
me->AddUnitState(UNIT_STATE_STUNNED);
}
tspellcast = true;
if (AfterTeleportTimer <= diff)
{
AfterTeleport = false;
me->ClearUnitState(UNIT_STATE_STUNNED);
if (Unit* nearu = me->SelectNearestTarget(100))
{
//DoYell(nearu->GetName(), LANG_UNIVERSAL, 0);
AttackStart(nearu);
me->AddThreat(nearu, 10000);
}
return true;
}
else
{
AfterTeleportTimer -= diff;
// update important timers which would otherwise get skipped
if (EnrageTimer > diff)
EnrageTimer -= diff;
else
EnrageTimer = 0;
if (Teleport_Timer > diff)
Teleport_Timer -= diff;
else
Teleport_Timer = 0;
return false;
}
}
else
{
return true;
}
}
void MoveInLineOfSight(Unit* who) override
{
if (!who || me->GetVictim())
return;
if (me->CanCreatureAttack(who))
{
float attackRadius = me->GetAttackDistance(who);
if (attackRadius < PULL_RANGE)
attackRadius = PULL_RANGE;
if (me->IsWithinDistInMap(who, attackRadius) && me->GetDistanceZ(who) <= /*CREATURE_Z_ATTACK_RANGE*/7 /*there are stairs*/)
{
//if (who->HasStealthAura())
// who->RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
AttackStart(who);
}
}
}
Creature* RespawnNearbyBugsAndGetOne()
{
std::list<Creature*> lUnitList;
me->GetCreatureListWithEntryInGrid(lUnitList, 15316, 150.0f);
me->GetCreatureListWithEntryInGrid(lUnitList, 15317, 150.0f);
if (lUnitList.empty())
return NULL;
Creature* nearb = NULL;
for (std::list<Creature*>::const_iterator iter = lUnitList.begin(); iter != lUnitList.end(); ++iter)
{
Creature* c = *iter;
if (c)
{
if (c->isDead())
{
c->Respawn();
c->setFaction(7);
c->RemoveAllAuras();
}
if (c->IsWithinDistInMap(me, ABUSE_BUG_RANGE))
{
if (!nearb || (rand32() % 4) == 0)
nearb = c;
}
}
}
return nearb;
}
void HandleBugs(uint32 diff)
{
if (BugsTimer < diff || Abuse_Bug_Timer <= diff)
{
Creature* c = RespawnNearbyBugsAndGetOne();
if (Abuse_Bug_Timer <= diff)
{
if (c)
{
CastSpellOnBug(c);
Abuse_Bug_Timer = urand(10000, 17000);
}
else
{
Abuse_Bug_Timer = 1000;
}
}
else
{
Abuse_Bug_Timer -= diff;
}
BugsTimer = 2000;
}
else
{
BugsTimer -= diff;
Abuse_Bug_Timer -= diff;
}
}
void CheckEnrage(uint32 diff)
{
if (EnrageTimer <= diff)
{
if (!me->IsNonMeleeSpellCast(true))
{
DoCast(me, SPELL_BERSERK);
EnrageTimer = 60*60000;
} else EnrageTimer = 0;
} else EnrageTimer-=diff;
}
};
class boss_veknilash : public CreatureScript
{
public:
boss_veknilash() : CreatureScript("boss_veknilash") { }
CreatureAI* GetAI(Creature* creature) const override
{
return GetInstanceAI<boss_veknilashAI>(creature);
}
struct boss_veknilashAI : public boss_twinemperorsAI
{
bool IAmVeklor() override {return false;}
boss_veknilashAI(Creature* creature) : boss_twinemperorsAI(creature)
{
Initialize();
}
void Initialize()
{
UpperCut_Timer = urand(14000, 29000);
UnbalancingStrike_Timer = urand(8000, 18000);
Scarabs_Timer = urand(7000, 14000);
}
uint32 UpperCut_Timer;
uint32 UnbalancingStrike_Timer;
uint32 Scarabs_Timer;
void Reset() override
{
TwinReset();
Initialize();
//Added. Can be removed if its included in DB.
me->ApplySpellImmune(0, IMMUNITY_DAMAGE, SPELL_SCHOOL_MASK_MAGIC, true);
}
void CastSpellOnBug(Creature* target) override
{
target->setFaction(14);
target->AI()->AttackStart(me->getThreatManager().getHostilTarget());
target->AddAura(SPELL_MUTATE_BUG, target);
target->SetFullHealth();
}
void UpdateAI(uint32 diff) override
{
//Return since we have no target
if (!UpdateVictim())
return;
if (!TryActivateAfterTTelep(diff))
return;
//UnbalancingStrike_Timer
if (UnbalancingStrike_Timer <= diff)
{
DoCastVictim(SPELL_UNBALANCING_STRIKE);
UnbalancingStrike_Timer = 8000 + rand32() % 12000;
} else UnbalancingStrike_Timer -= diff;
if (UpperCut_Timer <= diff)
{
Unit* randomMelee = SelectTarget(SELECT_TARGET_RANDOM, 0, NOMINAL_MELEE_RANGE, true);
if (randomMelee)
DoCast(randomMelee, SPELL_UPPERCUT);
UpperCut_Timer = 15000 + rand32() % 15000;
} else UpperCut_Timer -= diff;
HandleBugs(diff);
//Heal brother when 60yrds close
TryHealBrother(diff);
//Teleporting to brother
if (Teleport_Timer <= diff)
{
TeleportToMyBrother();
} else Teleport_Timer -= diff;
CheckEnrage(diff);
DoMeleeAttackIfReady();
}
};
};
class boss_veklor : public CreatureScript
{
public:
boss_veklor() : CreatureScript("boss_veklor") { }
CreatureAI* GetAI(Creature* creature) const override
{
return GetInstanceAI<boss_veklorAI>(creature);
}
struct boss_veklorAI : public boss_twinemperorsAI
{
bool IAmVeklor() override {return true;}
boss_veklorAI(Creature* creature) : boss_twinemperorsAI(creature)
{
Initialize();
}
void Initialize()
{
ShadowBolt_Timer = 0;
Blizzard_Timer = urand(15000, 20000);
ArcaneBurst_Timer = 1000;
Scorpions_Timer = urand(7000, 14000);
}
uint32 ShadowBolt_Timer;
uint32 Blizzard_Timer;
uint32 ArcaneBurst_Timer;
uint32 Scorpions_Timer;
void Reset() override
{
TwinReset();
Initialize();
//Added. Can be removed if its included in DB.
me->ApplySpellImmune(0, IMMUNITY_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, true);
}
void CastSpellOnBug(Creature* target) override
{
target->setFaction(14);
target->AddAura(SPELL_EXPLODEBUG, target);
target->SetFullHealth();
}
void UpdateAI(uint32 diff) override
{
//Return since we have no target
if (!UpdateVictim())
return;
// reset arcane burst after teleport - we need to do this because
// when VL jumps to VN's location there will be a warrior who will get only 2s to run away
// which is almost impossible
if (AfterTeleport)
ArcaneBurst_Timer = 5000;
if (!TryActivateAfterTTelep(diff))
return;
//ShadowBolt_Timer
if (ShadowBolt_Timer <= diff)
{
if (!me->IsWithinDist(me->GetVictim(), 45.0f))
me->GetMotionMaster()->MoveChase(me->GetVictim(), VEKLOR_DIST, 0);
else
DoCastVictim(SPELL_SHADOWBOLT);
ShadowBolt_Timer = 2000;
} else ShadowBolt_Timer -= diff;
//Blizzard_Timer
if (Blizzard_Timer <= diff)
{
Unit* target = NULL;
target = SelectTarget(SELECT_TARGET_RANDOM, 0, 45, true);
if (target)
DoCast(target, SPELL_BLIZZARD);
Blizzard_Timer = 15000 + rand32() % 15000;
} else Blizzard_Timer -= diff;
if (ArcaneBurst_Timer <= diff)
{
if (Unit* mvic = SelectTarget(SELECT_TARGET_NEAREST, 0, NOMINAL_MELEE_RANGE, true))
{
DoCast(mvic, SPELL_ARCANEBURST);
ArcaneBurst_Timer = 5000;
}
} else ArcaneBurst_Timer -= diff;
HandleBugs(diff);
//Heal brother when 60yrds close
TryHealBrother(diff);
//Teleporting to brother
if (Teleport_Timer <= diff)
{
TeleportToMyBrother();
} else Teleport_Timer -= diff;
CheckEnrage(diff);
//VL doesn't melee
//DoMeleeAttackIfReady();
}
void AttackStart(Unit* who) override
{
if (!who)
return;
if (who->isTargetableForAttack())
{
// VL doesn't melee
if (me->Attack(who, false))
{
me->GetMotionMaster()->MoveChase(who, VEKLOR_DIST, 0);
me->AddThreat(who, 0.0f);
}
}
}
};
};
void AddSC_boss_twinemperors()
{
new boss_veknilash();
new boss_veklor();
}
| Ragebones/StormCore | src/server/scripts/Kalimdor/TempleOfAhnQiraj/boss_twinemperors.cpp | C++ | gpl-2.0 | 18,489 |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SQLite;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
namespace VariablesManager
{
public partial class Form1 : Form
{
private string _selectedTm;
private string _selectedLrt;
public string SelectedTm
{
get => _selectedTm.Trim();
set => _selectedTm = value;
}
public string SelectedLrt
{
get => _selectedLrt.Trim();
set => _selectedLrt = value;
}
public Form1()
{
InitializeComponent();
}
private void btnBrowseTM_Click(object sender, EventArgs e)
{
openFileDialog.Filter = @"Translation memory (*.sdltm)|*.sdltm";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
SelectedTm = openFileDialog.FileName;
txtTM.Text = Path.GetFileName(openFileDialog.FileName);
}
}
private void btnBrowseLRT_Click(object sender, EventArgs e)
{
openFileDialog.Filter = @"Language Resource Template (*.resource)|*.resource";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
SelectedLrt = openFileDialog.FileName;
txtLRT.Text = Path.GetFileName(openFileDialog.FileName);
}
}
private void btnImportFromFile_Click(object sender, EventArgs e)
{
openFileDialog.Filter = @"Text files (*.txt)|*.txt|All files (*.*)|*.*";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
using (var sr = new StreamReader(openFileDialog.FileName))
{
txtVariables.Text = sr.ReadToEnd();
}
}
catch
{
}
}
}
private void btnExportToFile_Click(object sender, EventArgs e)
{
saveFileDialog.Filter = @"Text files (*.txt)|*.txt|All files (*.*)|*.*";
saveFileDialog.DefaultExt = "txt";
saveFileDialog.AddExtension = true;
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
using (var sw = new StreamWriter(saveFileDialog.FileName, false))
{
sw.Write(txtVariables.Text);
}
}
catch
{
}
}
MessageBox.Show(@"The variables list was exported to the selected file.");
}
private void btnFetchList_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(txtTM.Text))
{
FetchFromTm();
}
if (!string.IsNullOrEmpty(txtLRT.Text))
{
FetchFromLrt();
}
}
private void FetchFromLrt()
{
if (string.IsNullOrEmpty(SelectedLrt))
return;
var vars = GetVariablesAsTextFromLrt();
if (string.IsNullOrEmpty(vars))
return;
if (!string.IsNullOrEmpty(txtVariables.Text) &&
txtVariables.Text[txtVariables.Text.Length - 1] != '\n')
txtVariables.Text += "\r\n";
txtVariables.Text += vars;
}
private string GetVariablesAsTextFromLrt()
{
try
{
var xFinalDoc = new XmlDocument();
xFinalDoc.Load(SelectedLrt);
XmlNodeList languageResources = xFinalDoc.DocumentElement.GetElementsByTagName("LanguageResource");
if (languageResources.Count > 0)
{
foreach (XmlElement languageResource in languageResources)
{
if (languageResource.HasAttribute("Type") &&
languageResource.Attributes["Type"].Value == "Variables")
{
IEnumerable<XmlText> textElements = languageResource.ChildNodes.OfType<XmlText>();
if (textElements.Any())
{
var textElement = textElements.FirstOrDefault();
var base64Vars = textElement.Value;
return Encoding.UTF8.GetString(Convert.FromBase64String(base64Vars));
}
}
}
}
}
catch
{
}
return string.Empty;
}
private void FetchFromTm()
{
if (string.IsNullOrEmpty(txtTM.Text) || string.IsNullOrEmpty(SelectedTm))
return;
int count = 0;
var vars = GetVariablesAsTextFromTm(out count);
if (string.IsNullOrEmpty(vars))
return;
if (!string.IsNullOrEmpty(txtVariables.Text) && txtVariables.Text[txtVariables.Text.Length - 1] != '\n')
txtVariables.Text += "\r\n";
txtVariables.Text += vars;
}
private string GetVariablesAsTextFromTm(out int count)
{
count = 0;
try
{
SQLiteConnectionStringBuilder sb = new SQLiteConnectionStringBuilder();
sb.DataSource = SelectedTm;
sb.Version = 3;
sb.JournalMode = SQLiteJournalModeEnum.Off;
using (var connection = new SQLiteConnection(sb.ConnectionString, true))
using (var command = new SQLiteCommand(connection))
{
connection.Open();
command.CommandText = "SELECT data FROM resources where type = 1";
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
count++;
var buffer = GetBytes(reader);
return Encoding.UTF8.GetString(buffer);
}
}
}
}
catch
{
}
return string.Empty;
}
static byte[] GetBytes(SQLiteDataReader reader)
{
const int CHUNK_SIZE = 2 * 1024;
var buffer = new byte[CHUNK_SIZE];
long bytesRead;
long fieldOffset = 0;
using (MemoryStream stream = new MemoryStream())
{
while ((bytesRead = reader.GetBytes(0, fieldOffset, buffer, 0, buffer.Length)) > 0)
{
stream.Write(buffer, 0, (int)bytesRead);
fieldOffset += bytesRead;
}
return stream.ToArray();
}
}
private void btnAddToTMorLRT_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(txtTM.Text))
AddToTm();
if (!string.IsNullOrEmpty(txtLRT.Text))
AddToLrt();
}
private void AddToLrt()
{
if (string.IsNullOrEmpty(SelectedLrt) || string.IsNullOrEmpty(txtVariables.Text))
return;
var vars = GetVariablesAsTextFromLrt() + txtVariables.Text;
if (!string.IsNullOrEmpty(vars) && vars[vars.Length - 1] != '\n')
vars += "\r\n";
var base64Vars = Convert.ToBase64String(Encoding.UTF8.GetBytes(vars));
SetVariablesInLrt(base64Vars);
MessageBox.Show(@"The variables list was add to the selected Language Resource Template.");
}
private void SetVariablesInLrt(string base64Vars)
{
try
{
var xFinalDoc = new XmlDocument();
xFinalDoc.Load(SelectedLrt);
XmlNodeList languageResources = xFinalDoc.DocumentElement.GetElementsByTagName("LanguageResource");
if (languageResources.Count > 0)
{
foreach (XmlElement languageResource in languageResources)
{
if (languageResource.HasAttribute("Type") &&
languageResource.Attributes["Type"].Value == "Variables")
{
languageResource.InnerText = base64Vars;
}
}
}
using (var writer = new XmlTextWriter(SelectedLrt, null))
{
writer.Formatting = Formatting.None;
xFinalDoc.Save(writer);
}
}
catch
{
}
}
private void AddToTm()
{
if (string.IsNullOrEmpty(SelectedTm) || string.IsNullOrEmpty(txtVariables.Text))
return;
int count = 0;
var vars = GetVariablesAsTextFromTm(out count) + txtVariables.Text;
if (!string.IsNullOrEmpty(vars) && vars[vars.Length - 1] != '\n')
vars += "\r\n";
SetVariablesInTm(Encoding.UTF8.GetBytes(vars), count);
MessageBox.Show(@"The variables list was add to the selected Translation Memory.");
}
private void SetVariablesInTm(byte[] variablesAsBytes, int count)
{
try
{
var sb = new SQLiteConnectionStringBuilder
{
DataSource = SelectedTm,
Version = 3,
JournalMode = SQLiteJournalModeEnum.Off
};
int maxID = 0;
if (count == 0)
{
using (var connection = new SQLiteConnection(sb.ConnectionString, true))
{
using (var command = new SQLiteCommand(connection))
{
connection.Open();
command.CommandText = "Select max(id) from resources";
object oId = command.ExecuteScalar();
maxID = oId == DBNull.Value ? 1 : Convert.ToInt32(oId) + 1;
}
}
}
using (var connection = new SQLiteConnection(sb.ConnectionString, true))
{
using (var command = new SQLiteCommand(connection))
{
connection.Open();
if (count == 0)
{
command.CommandText =
string.Format(
"insert into resources (rowid, id, guid, type, language, data) values ({2}, {2}, '{0}', 1, '{1}', @data)",
Guid.NewGuid(), GetTmLanguage(), maxID);
}
else
{
command.CommandText = "update resources set data = @data where type = 1";
}
command.Parameters.Add("@data", DbType.Binary).Value = variablesAsBytes;
command.ExecuteNonQuery();
}
}
}
catch (Exception e)
{
}
}
private object GetTmLanguage()
{
try
{
var sb = new SQLiteConnectionStringBuilder
{
DataSource = SelectedTm,
Version = 3,
JournalMode = SQLiteJournalModeEnum.Off
};
using (var connection = new SQLiteConnection(sb.ConnectionString, true))
using (var command = new SQLiteCommand(connection))
{
connection.Open();
command.CommandText = "SELECT source_language FROM translation_memories";
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
return reader.GetString(0);
}
}
}
}
catch
{
}
return string.Empty;
}
private void btnReplateToTMorLRT_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(txtTM.Text))
{
ReplaceToTm();
}
if (!string.IsNullOrEmpty(txtLRT.Text))
{
ReplaceToLrt();
}
}
private void ReplaceToLrt()
{
if (string.IsNullOrEmpty(SelectedLrt))
{
return;
}
var vars = txtVariables.Text;
if (!string.IsNullOrEmpty(vars) && vars[vars.Length - 1] != '\n')
{
vars += "\r\n";
}
var base64Vars = Convert.ToBase64String(Encoding.UTF8.GetBytes(vars));
SetVariablesInLrt(base64Vars);
MessageBox.Show(@"The variables list from the selected Language Resource Template was replaced with the new one.");
}
private void ReplaceToTm()
{
if (string.IsNullOrEmpty(SelectedTm))
return;
var vars = txtVariables.Text;
if (!string.IsNullOrEmpty(vars) && vars[vars.Length - 1] != '\n')
vars += "\r\n";
var count = 0;
GetVariablesAsTextFromTm(out count);
SetVariablesInTm(Encoding.UTF8.GetBytes(vars), count);
MessageBox.Show(@"The variables list from the selected Translation Memory was replaced with the new one.");
}
private void btnClear_Click(object sender, EventArgs e)
{
txtVariables.Clear();
}
}
}
| sdl/Sdl-Community | VariablesManager/VariablesManager/Form1.cs | C# | gpl-2.0 | 13,948 |
<?php
include_once "./_common.php";
//pc버전에서 모바일가기 링크 타고 들어올 경우 세션을 삭제한다. 세션이 삭제되면 모바일 기기에서 PC버전 접속시 자동으로 모바일로 이동된다. /extend/g4m.config.php 파일 참고.
if($_GET['from'] == 'pc'){
set_session("frommoblie", "");
}
include_once './_head.php';
// 최신글
$sql = " select bo_table, bo_subject,bo_m_latest_skin from {$g4['board_table']} where bo_m_use='1' order by gr_id, bo_m_sort, bo_table ";
$result = sql_query($sql);
for ($i = 0; $row = sql_fetch_array($result); $i++) {
echo g4m_latest($row['bo_m_latest_skin'], $row['bo_table']);
}
include_once './_tail.php';
?> | typeofb/SmartTongsin | m/index.php | PHP | gpl-2.0 | 690 |
package org.mo.game.editor.face.apl.logic.form;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.HeaderFooter;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Phrase;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;
import java.awt.Color;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import org.mo.com.lang.FFatalError;
import org.mo.com.lang.RString;
import org.mo.com.logging.ILogger;
import org.mo.com.logging.RLogger;
import org.mo.com.validator.RStringValidator;
import org.mo.com.xml.FXmlNode;
import org.mo.com.xml.IXmlObject;
import org.mo.core.aop.face.ALink;
import org.mo.eng.data.common.ISqlContext;
import org.mo.web.core.servlet.common.IWebServletResponse;
import org.mo.web.core.webform.FWebFormDatasetArgs;
import org.mo.web.core.webform.IWebFormConsole;
import org.mo.web.core.webform.IWebFormDatasetConsole;
import org.mo.web.protocol.context.IWebContext;
public class FWebFormPdfServlet
implements
IWebFormPdfServlet{
private static ILogger _logger = RLogger.find(FWebFormPdfServlet.class);
public static byte[] creatPdf(FXmlNode dsNode,
IXmlObject formNode){
// 创建一个Document对象
Rectangle rectPageSize = new Rectangle(PageSize.A4);// 定义A4页面大小
rectPageSize = rectPageSize.rotate();// 实现A4页面的横置
Document document = new Document(rectPageSize, 50, 30, 30, 30);// 4个参数,
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
// 设置了页面的4个边距
try{
// 生成名为 HelloWorld.pdf 的文档
PdfWriter.getInstance(document, buffer);
BaseFont bfChinese;
try{
bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", false);
}catch(IOException e){
throw new FFatalError(e);
}
Font fontChinese = new Font(bfChinese, 12, Font.NORMAL, Color.red);
document.open();
// 插入一个段落
//获得模块名称
Paragraph par = new Paragraph(formNode.innerGet("label"), fontChinese);
document.add(par);
int tableColumns = formNode.children().count();
// 定义表格填充内容
PdfPTable datatable = new PdfPTable(tableColumns); // 创建新表.
// int headerwidths[] = { 9, 4, 8, 10, 8, 7 }; // percentage 定义表格头宽度
// datatable.setWidths(headerwidths);
datatable.setWidthPercentage(100);
// 设置表头的高度
datatable.getDefaultCell().setPadding(2);
// 设置表头的粗细线条
datatable.getDefaultCell().setBorderWidth(1);
datatable.getDefaultCell().setGrayFill(0.8f);
datatable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
// 以下是填充表头
for(int i = 0; i < tableColumns; i++){
datatable.addCell(new Phrase(formNode.children().get(i).innerGet("label"), fontChinese));
}
datatable.setHeaderRows(1);
// 结束表格的头部
// 设置页码
HeaderFooter footer = new HeaderFooter(new Phrase("页码:", fontChinese), true);
footer.setBorder(Rectangle.NO_BORDER);
document.setFooter(footer);
// 结束页码的设置
//设置表格颜色参数
int i = 1;
datatable.getDefaultCell().setBorderWidth(1);
for(FXmlNode row : dsNode.nodes()){
if(i % 2 == 1){
// 设置表格颜色
datatable.getDefaultCell().setGrayFill(1.0f);
}
//根据数据列项,依次取出该列所对应的值
for(int x = 0; x < tableColumns; x++){
String columnName = formNode.children().get(x).innerGet("data_name");
datatable.addCell(new Phrase(row.get(columnName), fontChinese));
}
if(i % 2 == 1){
// 设置表格颜色
datatable.getDefaultCell().setGrayFill(0.9f);
}
i++;
}
document.add(datatable);// 加载新表
}catch(DocumentException de){
de.printStackTrace();
System.err.println("document: " + de.getMessage());
}finally{
document.close();
}
return buffer.toByteArray();
}
@ALink
protected IWebFormConsole _webformConsole;
@ALink
IWebFormDatasetConsole _webFormDataConsole;
@Override
public void build(IWebContext context,
ISqlContext sqlContext,
IWebServletResponse response){
String formName = context.parameter("form_name");
RStringValidator.checkEmpty(formName, "form_name");
IXmlObject xform = findForm(formName);
// 查找数据集
FWebFormDatasetArgs args = new FWebFormDatasetArgs(context, sqlContext);
args.setPageSize(-1);
xform.children().get(0).innerGet("label");
args.setForm(xform);
FXmlNode dsNode = _webFormDataConsole.fetchNode(args);
// 生成PDF文件
byte[] bytes = creatPdf(dsNode, xform);
_logger.debug(this, "build", "Make form pdf file. (form={0}, pdf size={1})", xform.name(), bytes.length);
response.write(bytes);
}
public IXmlObject findForm(String formName){
IXmlObject xform = null;
if(RString.isNotEmpty(formName)){
xform = _webformConsole.find(formName);
if(null == xform){
throw new FFatalError("Show form is null. (name={0})", formName);
}
}
return xform;
}
}
| favedit/MoPlatform | mo-gm-develop/src/editor-face/org/mo/game/editor/face/apl/logic/form/FWebFormPdfServlet.java | Java | gpl-2.0 | 5,836 |
<?php
# Lifter007: TODO
# Lifter003: TODO
# Lifter010: TODO
/*
* Copyright (C) 2009 - Marcus Lunzenauer <mlunzena@uos.de>
*
* 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 2 of
* the License, or (at your option) any later version.
*/
require_once 'studip_controller.php';
abstract class AuthenticatedController extends StudipController {
/**
* Callback function being called before an action is executed. If this
* function does not return FALSE, the action will be called, otherwise
* an error will be generated and processing will be aborted. If this function
* already #rendered or #redirected, further processing of the action is
* withheld.
*
* @param string Name of the action to perform.
* @param array An array of arguments to the action.
*
* @return bool
*/
function before_filter(&$action, &$args) {
parent::before_filter($action, $args);
# open session
page_open(array('sess' => 'Seminar_Session',
'auth' => 'Seminar_Auth',
'perm' => 'Seminar_Perm',
'user' => 'Seminar_User'));
// show login-screen, if authentication is "nobody"
$GLOBALS['auth']->login_if($GLOBALS['auth']->auth['uid'] == 'nobody');
$this->flash = Trails_Flash::instance();
// set up user session
include 'lib/seminar_open.php';
# Set base layout
#
# If your controller needs another layout, overwrite your controller's
# before filter:
#
# class YourController extends AuthenticatedController {
# function before_filter(&$action, &$args) {
# parent::before_filter($action, $args);
# $this->set_layout("your_layout");
# }
# }
#
# or unset layout by sending:
#
# $this->set_layout(NULL)
#
$this->set_layout($GLOBALS['template_factory']->open('layouts/base'));
}
/**
* Callback function being called after an action is executed.
*
* @param string Name of the action to perform.
* @param array An array of arguments to the action.
*
* @return void
*/
function after_filter($action, $args) {
page_close();
}
}
| ipf/studip | app/controllers/authenticated_controller.php | PHP | gpl-2.0 | 2,304 |
/**
*
* Copyright (c) 2009-2016 Freedomotic team http://freedomotic.com
*
* This file is part of Freedomotic
*
* 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 2, 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
* Freedomotic; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*/
package com.freedomotic.api;
import com.google.inject.AbstractModule;
import com.google.inject.Singleton;
/**
*
* @author Enrico Nicoletti
*/
public class InjectorApi extends AbstractModule {
@Override
protected void configure() {
bind(API.class).to(APIStandardImpl.class).in(Singleton.class);
}
}
| abollaert/freedomotic | framework/freedomotic-core/src/main/java/com/freedomotic/api/InjectorApi.java | Java | gpl-2.0 | 1,096 |
<?php
/**
* @package Zen Library
* @subpackage Zen Library
* @author Joomla Bamboo - design@joomlabamboo.com
* @copyright Copyright (c) 2013 Joomla Bamboo. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
* @version 1.0.2
*/
/*
* Adapted from Minify_CSS_UriRewriter class by Stephen Clay <steve@mrclay.org>
*/
// no direct access
defined('_JEXEC') or die('Restricted access');
class ZenUriRewriter
{
/**
* Defines which class to call as part of callbacks, change this
* if you extend Minify_CSS_UriRewriter
* @var string
*/
protected static $className = 'ZenUriRewriter';
/**
* rewrite() and rewriteRelative() append debugging information here
* @var string
*/
public static $debugText = '';
/**
* Rewrite file relative URIs as root relative in CSS files
*
* @param string $css
*
* @param string $currentDir The directory of the current CSS file.
*
* @param string $docRoot The document root of the web site in which
* the CSS file resides (default = $_SERVER['DOCUMENT_ROOT']).
*
* @param array $symlinks (default = array()) If the CSS file is stored in
* a symlink-ed directory, provide an array of link paths to
* target paths, where the link paths are within the document root. Because
* paths need to be normalized for this to work, use "//" to substitute
* the doc root in the link paths (the array keys). E.g.:
* <code>
* array('//symlink' => '/real/target/path') // unix
* array('//static' => 'D:\\staticStorage') // Windows
* </code>
*
* @return string
*/
public static function rewrite($css, $currentDir, $docRoot = null, $symlinks = array())
{
self::$_docRoot = self::_realpath(
$docRoot ? $docRoot : $_SERVER['DOCUMENT_ROOT']
);
self::$_currentDir = self::_realpath($currentDir);
self::$_symlinks = array();
// normalize symlinks
foreach ($symlinks as $link => $target) {
$link = ($link === '//')
? self::$_docRoot
: str_replace('//', self::$_docRoot . '/', $link);
$link = strtr($link, '/', DIRECTORY_SEPARATOR);
self::$_symlinks[$link] = self::_realpath($target);
}
self::$debugText .= "docRoot : " . self::$_docRoot . "\n"
. "currentDir : " . self::$_currentDir . "\n";
if (self::$_symlinks) {
self::$debugText .= "symlinks : " . var_export(self::$_symlinks, 1) . "\n";
}
self::$debugText .= "\n";
$css = self::_trimUrls($css);
// rewrite
$css = preg_replace_callback('/@import\\s+([\'"])(.*?)[\'"]/'
, array(self::$className, '_processUriCB'), $css);
$css = preg_replace_callback('/url\\(\\s*([^\\)\\s]+)\\s*\\)/'
, array(self::$className, '_processUriCB'), $css);
return $css;
}
/**
* Prepend a path to relative URIs in CSS files
*
* @param string $css
*
* @param string $path The path to prepend.
*
* @return string
*/
public static function prepend($css, $path)
{
self::$_prependPath = $path;
$css = self::_trimUrls($css);
// append
$css = preg_replace_callback('/@import\\s+([\'"])(.*?)[\'"]/'
, array(self::$className, '_processUriCB'), $css);
$css = preg_replace_callback('/url\\(\\s*([^\\)\\s]+)\\s*\\)/'
, array(self::$className, '_processUriCB'), $css);
self::$_prependPath = null;
return $css;
}
/**
* @var string directory of this stylesheet
*/
private static $_currentDir = '';
/**
* @var string DOC_ROOT
*/
private static $_docRoot = '';
/**
* @var array directory replacements to map symlink targets back to their
* source (within the document root) E.g. '/var/www/symlink' => '/var/realpath'
*/
private static $_symlinks = array();
/**
* @var string path to prepend
*/
private static $_prependPath = null;
private static function _trimUrls($css)
{
return preg_replace('/
url\\( # url(
\\s*
([^\\)]+?) # 1 = URI (assuming does not contain ")")
\\s*
\\) #)
/x', 'url($1)', $css);
}
private static function _processUriCB($m)
{
// $m matched either '/@import\\s+([\'"])(.*?)[\'"]/' or '/url\\(\\s*([^\\)\\s]+)\\s*\\)/'
$isImport = ($m[0][0] === '@');
// determine URI and the quote character (if any)
if ($isImport) {
$quoteChar = $m[1];
$uri = $m[2];
} else {
// $m[1] is either quoted or not
$quoteChar = ($m[1][0] === "'" || $m[1][0] === '"')
? $m[1][0]
: '';
$uri = ($quoteChar === '')
? $m[1]
: substr($m[1], 1, strlen($m[1]) - 2);
}
// analyze URI
if ('/' !== $uri[0] // root-relative
&& false === strpos($uri, '//') // protocol (non-data)
&& 0 !== strpos($uri, 'data:') // data protocol
) {
// URI is file-relative: rewrite depending on options
$uri = (self::$_prependPath !== null)
? (self::$_prependPath . $uri)
: self::rewriteRelative($uri, self::$_currentDir, self::$_docRoot, self::$_symlinks);
}
return $isImport
? "@import {$quoteChar}{$uri}{$quoteChar}"
: "url({$quoteChar}{$uri}{$quoteChar})";
}
/**
* Rewrite a file relative URI as root relative
*
* <code>
* Minify_CSS_UriRewriter::rewriteRelative(
* '../img/hello.gif'
* , '/home/user/www/css' // path of CSS file
* , '/home/user/www' // doc root
*);
* // returns '/img/hello.gif'
*
* // example where static files are stored in a symlinked directory
* Minify_CSS_UriRewriter::rewriteRelative(
* 'hello.gif'
* , '/var/staticFiles/theme'
* , '/home/user/www'
* , array('/home/user/www/static' => '/var/staticFiles')
*);
* // returns '/static/theme/hello.gif'
* </code>
*
* @param string $uri file relative URI
*
* @param string $realCurrentDir realpath of the current file's directory.
*
* @param string $realDocRoot realpath of the site document root.
*
* @param array $symlinks (default = array()) If the file is stored in
* a symlink-ed directory, provide an array of link paths to
* real target paths, where the link paths "appear" to be within the document
* root. E.g.:
* <code>
* array('/home/foo/www/not/real/path' => '/real/target/path') // unix
* array('C:\\htdocs\\not\\real' => 'D:\\real\\target\\path') // Windows
* </code>
*
* @return string
*/
public static function rewriteRelative($uri, $realCurrentDir, $realDocRoot, $symlinks = array())
{
// prepend path with current dir separator (OS-independent)
$path = strtr($realCurrentDir, '/', DIRECTORY_SEPARATOR)
. DIRECTORY_SEPARATOR . strtr($uri, '/', DIRECTORY_SEPARATOR);
self::$debugText .= "file-relative URI : {$uri}\n"
. "path prepended : {$path}\n";
// "unresolve" a symlink back to doc root
foreach ($symlinks as $link => $target) {
if (0 === strpos($path, $target)) {
// replace $target with $link
$path = $link . substr($path, strlen($target));
self::$debugText .= "symlink unresolved : {$path}\n";
break;
}
}
// strip doc root
$path = substr($path, strlen($realDocRoot));
self::$debugText .= "docroot stripped : {$path}\n";
// fix to root-relative URI
$uri = strtr($path, '/\\', '//');
// remove /./ and /../ where possible
$uri = str_replace('/./', '/', $uri);
// inspired by patch from Oleg Cherniy
do {
$uri = preg_replace('@/[^/]+/\\.\\./@', '/', $uri, 1, $changed);
} while ($changed);
self::$debugText .= "traversals removed : {$uri}\n\n";
return $uri;
}
/**
* Get realpath with any trailing slash removed. If realpath() fails,
* just remove the trailing slash.
*
* @param string $path
*
* @return mixed path with no trailing slash
*/
protected static function _realpath($path)
{
$realPath = realpath($path);
if ($realPath !== false) {
$path = $realPath;
}
return rtrim($path, '/\\');
}
}
| fenix20113/homework3 | libraries/zen/uri/rewriter.php | PHP | gpl-2.0 | 7,740 |
package com.lonebytesoft.thetaleclient.api.model;
import android.os.Parcel;
import android.os.Parcelable;
import com.lonebytesoft.thetaleclient.api.dictionary.CompanionSpecies;
import com.lonebytesoft.thetaleclient.util.ObjectUtils;
import org.json.JSONException;
import org.json.JSONObject;
/**
* @author Hamster
* @since 17.02.2015
*/
public class CompanionInfo implements Parcelable {
public final CompanionSpecies species;
public final String name;
public final int healthCurrent;
public final int healthMax;
public final int coherence;
public final int experienceCurrent;
public final int experienceForNextLevel;
public CompanionInfo(final JSONObject json) throws JSONException {
species = ObjectUtils.getEnumForCode(CompanionSpecies.class, json.getInt("type"));
name = json.getString("name");
healthCurrent = json.getInt("health");
healthMax = json.getInt("max_health");
coherence = json.getInt("coherence");
experienceCurrent = json.getInt("experience");
experienceForNextLevel = json.getInt("experience_to_level");
}
// parcelable stuff
private CompanionInfo(final Parcel in) {
final int index = in.readInt();
species = index == -1 ? null : CompanionSpecies.values()[index];
name = in.readString();
healthCurrent = in.readInt();
healthMax = in.readInt();
coherence = in.readInt();
experienceCurrent = in.readInt();
experienceForNextLevel = in.readInt();
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel out, int flags) {
out.writeInt(species == null ? -1 : species.ordinal());
out.writeString(name);
out.writeInt(healthCurrent);
out.writeInt(healthMax);
out.writeInt(coherence);
out.writeInt(experienceCurrent);
out.writeInt(experienceForNextLevel);
}
public static final Parcelable.Creator<CompanionInfo> CREATOR = new Parcelable.Creator<CompanionInfo>() {
@Override
public CompanionInfo createFromParcel(Parcel source) {
return new CompanionInfo(source);
}
@Override
public CompanionInfo[] newArray(int size) {
return new CompanionInfo[size];
}
};
}
| hamsterxc/TheTaleClient | app/src/main/java/com/lonebytesoft/thetaleclient/api/model/CompanionInfo.java | Java | gpl-2.0 | 2,364 |
package tasslegro.base;
import java.io.IOException;
import java.net.URI;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.annotation.NotThreadSafe;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
public class Http_Delete {
@NotThreadSafe
class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase {
public static final String METHOD_NAME = "DELETE";
public String getMethod() {
return METHOD_NAME;
}
public HttpDeleteWithBody(final String uri) {
super();
setURI(URI.create(uri));
}
public HttpDeleteWithBody(final URI uri) {
super();
setURI(uri);
}
public HttpDeleteWithBody() {
super();
}
}
CloseableHttpClient httpClient = new DefaultHttpClient();
HttpDeleteWithBody delete = null;
HttpResponse response = null;
public Http_Delete(String url, String entity) throws ClientProtocolException, IOException {
this.delete = new HttpDeleteWithBody(url);
this.delete.setHeader("Content-type", "application/json");
StringEntity stringEntity = new StringEntity(entity.toString(), "UTF-8");
this.delete.setEntity(stringEntity);
this.response = this.httpClient.execute(this.delete);
}
public Http_Delete() {
}
public void setURL(String url, String entity) throws ClientProtocolException, IOException {
this.delete = new HttpDeleteWithBody(url);
this.delete.setHeader("Content-type", "application/json");
StringEntity stringEntity = new StringEntity(entity.toString(), "UTF-8");
this.delete.setEntity(stringEntity);
this.response = this.httpClient.execute(this.delete);
}
public int getStatusCode() {
if (response == null) {
return 0;
}
return this.response.getStatusLine().getStatusCode();
}
public String getStrinResponse() throws ParseException, IOException {
if (response == null) {
return null;
}
HttpEntity entity = this.response.getEntity();
return EntityUtils.toString(entity, "UTF-8");
}
}
| kaczla/TAS | Client/src/main/java/tasslegro/base/Http_Delete.java | Java | gpl-2.0 | 2,256 |
<div class="header-title">
<?php if(is_home()){ ?>
<?php $blog_text = of_get_option('blog_text'); ?>
<?php if($blog_text){?>
<h1><?php echo of_get_option('blog_text'); ?></h1>
<?php } else { ?>
<h1><?php _e('Blog','theme1599');?></h1>
<?php } ?>
<?php } else { ?>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<?php $pagetitle = get_post_custom_values("page-title");?>
<?php $pagedesc = get_post_custom_values("page-desc");?>
<?php if($pagetitle == ""){ ?>
<h1><?php the_title(); ?></h1>
<?php } else { ?>
<h1><?php echo $pagetitle[0]; ?></h1>
<?php } ?>
<?php if($pagedesc != ""){ ?>
<span class="page-desc"><?php echo $pagedesc[0];?></span>
<?php } ?>
<?php endwhile; endif; ?>
<?php wp_reset_query();?>
<?php } ?>
</div> | yosagarrane/testsite | wp-content/themes/65_65fd76e4b7c1e295a14f4b0cdfb23039/title.php | PHP | gpl-2.0 | 822 |
package com.fjaviermo.dropdroid;
import java.io.ByteArrayOutputStream;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
public final class CoverImageDialogFragment extends DialogFragment {
private Bitmap mImage;
private static final String IMAGE="image";
/**
* Create a new instance of CoverImageDialogFragment, providing "image"
* as an argument.
*/
static CoverImageDialogFragment newInstance(Bitmap image) {
CoverImageDialogFragment coverImageDialog = new CoverImageDialogFragment();
Bundle args = new Bundle();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
args.putByteArray(IMAGE, byteArray);
coverImageDialog.setArguments(args);
coverImageDialog.setStyle(DialogFragment.STYLE_NO_TITLE, 0);
return coverImageDialog;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
byte[] byteArray = getArguments().getByteArray(IMAGE);
mImage = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.image_dialog, container, false);
ImageView imgView=(ImageView)view.findViewById(R.id.thumbnail_epub);
imgView.setImageBitmap(mImage);
return view;
}
}
| fjaviermo/dropdroid | app/src/com/fjaviermo/dropdroid/CoverImageDialogFragment.java | Java | gpl-2.0 | 1,793 |
(function() {
var preview = true;
var themeShortcuts = {
insert: function(where) {
switch(where) {
case 'st_button_more':
var href = jQuery("#btn_more_src").val();
var what = '[st_button_more href="'+href+'"]';
break;
case 'st_button':
var text = jQuery("#text").val();
var text_color = jQuery("#color").val();
var link = jQuery("#link").val();
var bg = jQuery("#bg").val();
var size = jQuery("#size").val();
var icon = jQuery("#name").val();
var target = jQuery("#target").val();
var border_radius = jQuery("#border_radius").val();
var what = '[st_button text_color="'+text_color+'" link="'+link+'" background="'+bg+'" size="'+size+'" target="'+target+'" icon="'+icon+'" border_radius="'+border_radius+'"]'+text+'[/st_button]';
break;
case 'st_hover_fill_button':
var text = jQuery("#text").val();
var text_color = jQuery("#color").val();
var link = jQuery("#link").val();
var bg = jQuery("#bg").val();
var hover_bg = jQuery("#hover_bg").val();
var size = jQuery("#size").val();
var icon = jQuery("#name").val();
var target = jQuery("#target").val();
var hover_direction = jQuery("#hover_direction").val();
var border_radius = jQuery("#border_radius").val();
var what = '[st_hover_fill_button text_color="'+text_color+'" link="'+link+'" background="'+bg+'" hover_background="'+hover_bg+'" size="'+size+'" target="'+target+'" icon="'+icon+'" border_radius="'+border_radius+'" hover_direction="'+hover_direction+'"]'+text+'[/st_hover_fill_button]';
break;
case 'st_hover_fancy_icon_button':
var text = jQuery("#text").val();
var text_color = jQuery("#color").val();
var link = jQuery("#link").val();
var bg = jQuery("#bg").val();
var size = jQuery("#size").val();
var icon = jQuery("#name").val();
var icon_color = jQuery("#icon_color").val();
var icon_bg = jQuery("#icon_bg").val();
var target = jQuery("#target").val();
var icon_position = jQuery("#icon_pos").val();
var icon_separator = jQuery("#icon_sep").val();
var border_radius = jQuery("#border_radius").val();
var what = '[st_hover_fancy_icon_button text_color="'+text_color+'" link="'+link+'" background="'+bg+'" size="'+size+'" target="'+target+'" icon="'+icon+'" icon_color="'+icon_color+'" icon_background="'+icon_bg+'" icon_position="'+icon_position+'" icon_separator="'+icon_separator+'" border_radius="'+border_radius+'"]'+text+'[/st_hover_fancy_icon_button]';
break;
case 'st_hover_arrows_button':
var text = jQuery("#text").val();
var text_color = jQuery("#color").val();
var link = jQuery("#link").val();
var bg = jQuery("#bg").val();
var size = jQuery("#size").val();
var icon = jQuery("#name").val();
var target = jQuery("#target").val();
var border_radius = jQuery("#border_radius").val();
var arrow_direction = jQuery("#arrow_direction").val();
var what = '[st_hover_arrows_button text_color="'+text_color+'" link="'+link+'" background="'+bg+'" size="'+size+'" target="'+target+'" icon="'+icon+'" border_radius="'+border_radius+'" arrow_direction="'+arrow_direction+'"]'+text+'[/st_hover_arrows_button]';
break;
case 'st_hover_icon_button':
var text = jQuery("#text").val();
var text_color = jQuery("#color").val();
var link = jQuery("#link").val();
var bg = jQuery("#bg").val();
var size = jQuery("#size").val();
var icon = jQuery("#name").val();
var target = jQuery("#target").val();
var border_radius = jQuery("#border_radius").val();
var icon_direction = jQuery("#icon_direction").val();
var what = '[st_hover_icon_button text_color="'+text_color+'" link="'+link+'" background="'+bg+'" size="'+size+'" target="'+target+'" icon="'+icon+'" icon_direction="'+icon_direction+'" border_radius="'+border_radius+'"]'+text+'[/st_hover_icon_button]';
break;
case 'st_hover_bordered_button':
var text = jQuery("#text").val();
var text_color = jQuery("#color").val();
var link = jQuery("#link").val();
var bg = jQuery("#bg").val();
var size = jQuery("#size").val();
var icon = jQuery("#name").val();
var target = jQuery("#target").val();
var border_type = jQuery("#border_type").val();
var border_radius = jQuery("#border_radius").val();
var what = '[st_hover_bordered_button text_color="'+text_color+'" link="'+link+'" background="'+bg+'" size="'+size+'" target="'+target+'" icon="'+icon+'" border_radius="'+border_radius+'" border_type="'+border_type+'"]'+text+'[/st_hover_bordered_button]';
break;
case 'st_unordered':
var list = '<li>First list item</li>';
var listicon = jQuery("#listicon").val();
var what = '[st_unordered listicon="'+listicon+'"]'+list+'[/st_unordered]';
break;
case 'st_box':
var title = jQuery("#box_title").val();
var text = jQuery("#text").val();
var type = jQuery("#box_type").val();
var what = '[st_box title="'+title+'" type="'+type+'"]'+text+'[/st_box]';
break;
case 'st_callout':
var title = jQuery("#callout_title").val();
var text = jQuery("#text").val();
var btn_text = jQuery("#btn_text").val();
var btn_link = jQuery("#btn_link").val();
var text_color = jQuery("#color").val();
var bg = jQuery("#bg").val();
var what = '[st_callout title="'+title+'" button_text="'+btn_text+'" link="'+btn_link+'" text_color="'+text_color+'" background="'+bg+'"]'+text+'[/st_callout]';
break;
case 'st_tooltip':
var text = jQuery("#text").val();
var tooltip_text = jQuery("#tooltip_text").val();
var type = jQuery("#tooltip_type").val();
var what = '[st_tooltip type="'+type+'" tooltip_text="'+tooltip_text+'"]'+text+'[/st_tooltip]';
break;
case 'st_popover':
var content = 'Your text here';
var title = jQuery("#popover_title").val();
var text = jQuery("#popover_text").val();
var type = jQuery("#popover_type").val();
var what = '[st_popover type="'+type+'" popover_title="'+title+'" text="'+text+'"]'+content+'[/st_popover]';
break;
case 'st_modal':
var title = jQuery("#modal_title").val();
var content = jQuery("#modal_text").val();
var modal_link = jQuery("#modal_link").val();
var primary_text = jQuery("#primary").val();
var primary_link = jQuery("#primary_link").val();
var what = '[st_modal modal_link="'+modal_link+'" primary_text="'+primary_text+'" primary_link="'+primary_link+'" modal_title="'+title+'"]'+content+'[/st_modal]';
break;
case 'st_tables':
var colsEl = jQuery("#cols");
var rowsEl = jQuery("#rows");
var cols = new Array();
var rows = new Array();
for(var i=0; i<jQuery(rowsEl).val(); i++) {
for(var j=0; j<jQuery(colsEl).val(); j++) {
if(i == 0) {
cols.push(jQuery('#input_'+i+''+j).val());
} else if (i == 1) {
rows.push(jQuery('#input_'+i+''+j).val());
j = jQuery(colsEl).val();
} else {
rows.push(jQuery('#input_'+i+''+j).val());
}
}
}
var what = '[st_table cols="'+cols.join('||')+'" data="'+rows.join('||')+'"]';
break;
case 'st_tabs':
var tabs = '';
var boxes = jQuery(".box");
boxes.splice(0,1);
jQuery(boxes).each(function() {
var title = jQuery(this).find('input').val();
var text = jQuery(this).find('textarea').val();
tabs += '[st_tab title="'+title+'"]'+text+'[/st_tab]';
});
var what = '[st_tabs]'+tabs+'[/st_tabs]';
break;
case 'st_toggle':
var accs = '';
var boxes = jQuery(".box");
jQuery(boxes).each(function() {
var title = jQuery(this).find('input').val();
var text = jQuery(this).find('textarea').val();
var state = jQuery(this).find('select').val();
accs += '[st_panel title="'+title+'" state="'+state+'"]'+text+'[/st_panel]<br />';
});
var what = '[st_toggle]<br />'+accs+'[/st_toggle]';
break;
case 'st_accordion':
var accs = '';
var boxes = jQuery(".box");
jQuery(boxes).each(function() {
var title = jQuery(this).find('input').val();
var text = jQuery(this).find('textarea').val();
var state = jQuery(this).find('select').val();
accs += '[st_acc_panel title="'+title+'" state="'+state+'"]'+text+'[/st_acc_panel]<br />';
});
var what = '[st_accordion]<br />'+accs+'[/st_accordion]';
break;
case 'st_progress_bar':
var width = jQuery("#width").val();
var style = jQuery("#style").val();
var striped = jQuery("#striped").val();
var active = jQuery("#active").val();
var what = '[st_progress_bar width="'+width+'" style="'+style+'" striped="'+striped+'" active="'+active+'"]';
break;
case 'st_related_posts':
var limit = jQuery("#limit").val();
var what = '[st_related_posts limit="'+limit+'"]';
break;
case 'st_highlight':
var background_color = jQuery("#background_color").val();
var text_color = jQuery("#text_color").val();
var what = '[st_highlight background_color="'+background_color+'" text_color="'+text_color+'"]Highlighted text[/st_highlight]';
break;
case 'st_loginout':
var text_col = jQuery("#color").val();
var bg = jQuery("#bg").val();
var size = jQuery("#size").val();
var type = jQuery("#login_type").val();
var target = jQuery("#target").val();
var login_msg = jQuery("#login_msg").val();
var logout_msg = jQuery("#logout_msg").val();
var what = '[st_loginout text_col="'+text_col+'" background="'+bg+'" size="'+size+'" login_msg="'+login_msg+'" logout_msg="'+logout_msg+'"]';
break;
case 'st_quote':
var author = jQuery("#author-name").val();
var content = jQuery("#text").val();
var what = '[st_quote author="'+author+'"]' +content+ '[/st_quote]';
break;
case 'st_abbreviation':
var text = jQuery("#text").val();
var abbreviation = jQuery("#abbreviation").val();
var what = '[st_abbr title="'+abbreviation+'"]' + text + '[/st_abbr]';
break;
case 'st_twitter':
var style = jQuery("#style").val();
var url = jQuery("#url").val();
var sourceVal = jQuery("#source").val();
var related = jQuery("#related").val();
var text = jQuery("#text").val();
var lang = jQuery("#lang").val();
var what = '[st_twitter style="'+style+'" url="'+url+'" source="'+sourceVal+'" related="'+related+'" text="'+text+'" lang="'+lang+'"]';
break;
case 'st_digg':
var style = jQuery("#style").val();
var link = jQuery("#link").val();
var title = jQuery("#digg_title").val();
var what = '[st_digg style="'+style+'" title="'+title+'" link="'+link+'"]';
break;
case 'st_fblike':
var style = jQuery("#style").val();
var url = jQuery("#url").val();
var show_faces = jQuery("#show_faces").val();
var width = jQuery("#width").val();
var verb = jQuery("#verb_to_display").val();
var font = jQuery("#font").val();
var what = '[st_fblike url="'+url+'" style="'+style+'" showfaces="'+show_faces+'" width="'+width+'" verb="'+verb+'" font="'+font+'"]';
break;
case 'st_fbshare':
var url = jQuery("#link").val();
var what = '[st_fbshare url="'+url+'"]';
break;
case 'st_lishare':
var style = jQuery("#style").val();
var url = jQuery("#link").val();
var sourceVal = jQuery("#source").val();
var related = jQuery("#related").val();
var text = jQuery("#text").val();
var lang = jQuery("#lang").val();
var what = '[st_linkedin_share url="'+url+'" style="'+style+'"]';
break;
case 'st_gplus':
var style = jQuery("#style").val();
var size = jQuery("#size").val();
var what = '[st_gplus style="'+style+'" size="'+size+'"]';
break;
case 'st_pinterest_pin':
var style = jQuery("#style").val();
var what = '[st_pinterest_pin style="'+style+'"]';
break;
case 'st_tumblr':
var style = jQuery("#style").val();
var what = '[st_tumblr style="'+style+'"]';
break;
case 'st_pricingTable':
var content = '';
var columns = jQuery("#columns").val();
var highlighted = jQuery("#highlighted").val();
for(x=0;x<columns;x++) {
var highlight = ((x+1) == highlighted) ? " highlight='true'" : '';
content += "\n[st_pricing_column title='Column " + (x+1) + "'" + highlight + "]\n[st_price_info cost='$14.99/month'][/st_price_info]<ul><li>Item description and details...</li>\n<li>Item description and details...</li>\n<li>Some more info...</li>\n<li>[st_button text_color='#444444' link='#' background='#E6E6E6' size='small']Button text[/st_button]</li></ul>\n[/st_pricing_column]\n";
}
var what = "[st_pricing_table columns='"+columns+"']\n" + content + "\n[/st_pricing_table]";
break;
case 'st_gmap':
var additional = '';
additional = (jQuery("#latitude").val() != '') ? additional + ' latitude="'+ jQuery("#latitude").val() +'"' : additional;
additional = (jQuery("#longitute").val() != '') ? additional + ' longitute="'+ jQuery("#longitute").val() +'"' : additional;
additional = (jQuery("#html").val() != '') ? additional + ' html="'+ jQuery("#html").val() +'"' : additional;
additional = (jQuery("#zoom").val() != '') ? additional + ' zoom="'+ jQuery("#zoom").val() +'"' : additional;
additional = (jQuery("#gheight").val() != '') ? additional + ' height="'+ jQuery("#gheight").val() +'"' : additional;
additional = (jQuery("#gwidth").val() != '') ? additional + ' width="'+ jQuery("#gwidth").val() +'"' : additional;
additional = (jQuery("#maptype").val() != '') ? additional + ' maptype="'+ jQuery("#maptype").val() +'"' : additional;
additional = (jQuery("#color").val() != '') ? additional + ' color="'+ jQuery("#color").val() +'"' : additional;
var what = '[st_gmap '+additional+']';
break;
case 'st_trends':
var width = jQuery("#width").val();
var height = jQuery("#height").val();
var query = jQuery("#query").val();
var geo = jQuery("#geo").val();
var what = '[st_trends width="'+width+'" height="'+height+'" query="'+query+'" geo="'+geo+'"]';
break;
case 'st_gchart':
var data = jQuery("#data").val();
var title = jQuery("#g_title").val();
var width = jQuery("#width").val();
var height = jQuery("#height").val();
var series_type = jQuery("#series_type").val();
var vAxis = jQuery("#vAxis").val();
var hAxis = jQuery("#hAxis").val();
var type = jQuery("#gchart_type").val();
var red_from = jQuery("#red_from").val();
var red_to = jQuery("#red_to").val();
var yellow_from = jQuery("#yellow_from").val();
var yellow_to = jQuery("#yellow_to").val();
var gauge_minor_ticks = jQuery("#gauge_minor_ticks").val();
var what = '[st_chart title="'+title+'" data="'+data+'" width="'+width+'" height="'+height+'" type="'+type+'" series_type="'+series_type+'" vAxis="'+vAxis+'" hAxis="'+hAxis+'" red_from="'+red_from+'" red_to="'+red_to+'" yellow_from="'+yellow_from+'" yellow_to="'+yellow_to+'" gauge_minor_ticks="'+gauge_minor_ticks+'"]';
break;
case 'st_chart_pie':
var data = jQuery("#data").val();
var title = jQuery("#pie_title").val();
var what = '[st_chart_pie title="'+title+'" data="'+data+'"]';
break;
case 'st_chart_bar':
var data = jQuery("#data").val();
var title = jQuery("#bar_title").val();
var vaxis = jQuery("#vaxis_title").val();
var haxis = jQuery("#haxis_title").val();
var what = '[st_chart_bar title="'+title+'" data="'+data+'" vaxis="'+vaxis+'" haxis="'+haxis+'"]';
break;
case 'st_chart_area':
var data = jQuery("#data").val();
var title = jQuery("#area_title").val();
var vaxis = jQuery("#vaxis_title").val();
var haxis = jQuery("#haxis_title").val();
var what = '[st_chart_area title="'+title+'" data="'+data+'" vaxis="'+vaxis+'" haxis="'+haxis+'"]';
break;
case 'st_chart_geo':
var data = jQuery("#data").val();
var title = jQuery("#geo_title").val();
var primary = jQuery("#primary").val();
var secondary = jQuery("#secondary").val();
var what = '[st_chart_geo title="'+title+'" data="'+data+'" primary="'+primary+'" secondary="'+secondary+'"]';
break;
case 'st_chart_combo':
var data = jQuery("#data").val();
var title = jQuery("#combo_title").val();
var vaxis = jQuery("#vaxis_title").val();
var haxis = jQuery("#haxis_title").val();
var series = jQuery("#series").val();
var what = '[st_chart_combo title="'+title+'" data="'+data+'" vaxis="'+vaxis+'" haxis="'+haxis+'" series="'+series+'"]';
break;
case 'st_chart_org':
var data = jQuery("#data").val();
var what = '[st_chart_org data="'+data+'"]';
break;
case 'st_chart_bubble':
var data = jQuery("#data").val();
var title = jQuery("#bubble_title").val();
var primary = jQuery("#primary").val();
var secondary = jQuery("#secondary").val();
var what = '[st_chart_bubble title="'+title+'" data="'+data+'" primary="'+primary+'" secondary="'+secondary+'"]';
break;
case 'st_gdocs':
var url = jQuery("#url").val();
var width = jQuery("#width").val();
var height = jQuery("#height").val();
var what = "[st_gdocs width='"+width+"' height='"+height+"' url='"+ url +"']";
break;
case 'st_children':
var parent = jQuery("#page").val();
var what = "[st_children of='"+ parent +"']";
break;
case 'st_contact_form_dark':
var email_d = jQuery("#email_d").val();
var what = "[st_contact_form_dark email='"+ email_d +"']";
break;
case 'st_contact_form_light':
var email_l = jQuery("#email_l").val();
var what = "[st_contact_form_light email='"+ email_l +"']";
break;
case 'st_fancyboxImages':
var href = jQuery("#href").val();
var thumb = jQuery("#thumb").val();
var thumb_width = jQuery("#thumb_width").val();
var group = jQuery("#group").val();
var title = jQuery("#title_lb").val();
var what = "[st_fancyboxImages href='"+ href +"' thumb='"+thumb+"' thumb_width='"+thumb_width+"' group='"+group+"' title='"+title+"']";
break;
case 'st_fancyboxInline':
var title = jQuery("#in_title").val();
var content_title = jQuery("#content_title").val();
var content = jQuery("#in_content").val();
var what = "[st_fancyboxInline title='"+title+"' content_title='"+content_title+"' content='"+content+"']";
break;
case 'st_fancyboxIframe':
var title = jQuery("#iframe_title").val();
var href = jQuery("#iframe_href").val();
var what = "[st_fancyboxIframe title='"+title+"' href='"+ href +"']";
break;
case 'st_fancyboxPage':
var title = jQuery("#ipage_title").val();
var href = jQuery("#ipage").val();
var what = "[st_fancyboxPage title='"+title+"' href='"+ href +"']";
break;
case 'st_fancyboxSwf':
var title = jQuery("#swf_title").val();
var href = jQuery("#swf").val();
var what = "[st_fancyboxSwf title='"+title+"' href='"+href+"']";
break;
case 'st_video':
var title = jQuery("#video_title").val();
var display = jQuery("#display").val();
var width = jQuery("#width").val();
var height = jQuery("#height").val();
var type = jQuery("#video_type").val();
if (type == 'flash') {
var src = jQuery("#src").val();
var what = "[st_video title='"+title+"' type='"+ type +"' width='"+width+"' height='"+height+"' src='"+src+"']";
} else if (type == 'html5') {
var poster = jQuery("#poster").val();
var mp4 = jQuery("#mp4").val();
var webm = jQuery("#webm").val();
var ogg = jQuery("#ogg").val();
var what = "[st_video title='"+title+"' type='"+ type +"' width='"+width+"' height='"+height+"' poster='"+poster+"' mp4='"+mp4+"' webm='"+webm+"' ogg='"+ogg+"']";
} else {
var src = jQuery("#clip_id").val();
var what = "[st_video title='"+title+"' type='"+ type +"' width='"+width+"' height='"+height+"' src='"+src+"']";
}
var group = jQuery("#group").val();
var title = jQuery("#title_lb").val();
break;
case 'st_audio':
var title = jQuery("#audio_title").val();
var src = jQuery("#audio_src").val();
var what = "[st_audio title='"+title+"' src='"+src+"']";
break;
case 'st_soundcloud':
var src = jQuery("#sound_src").val();
var color = jQuery("#sound_color").val();
var what = "[st_soundcloud color='"+color+"' src='"+src+"']";
break;
case 'st_mixcloud':
var src = jQuery("#mix_src").val();
var width = jQuery("#mix_width").val();
var height = jQuery("#mix_height").val();
var what = "[st_mixcloud width='"+width+"' height='"+height+"' src='"+src+"']";
break;
case 'st_section_image':
var image_id = jQuery("#imageid").val();
var bg_color = jQuery("#bg_color").val();
var type = jQuery("#section_image_type").val();
var bg_position = jQuery("#bg_position").val();
var bg_size = jQuery("#bg_size").val();
var repeat = jQuery("#repeat").val();
var padding = jQuery("#img_padding").val();
var what = "[st_section_image image_id='"+image_id+"' bg_color='"+bg_color+"' type='"+type+"' position='"+bg_position+"' bg_size='"+bg_size+"' repeat='"+repeat+"' padding='"+padding+"']Section content goes here[/st_section_image]";
break;
case 'st_section_color':
var color = jQuery("#color").val();
var padding = jQuery("#col_padding").val();
var what = "[st_section_color color='"+color+"' padding='"+padding+"']Section content goes here[/st_section_color]";
break;
case 'st_text_color':
var color = jQuery("#color").val();
var what = "[st_text_color color='"+color+"']Text goes here[/st_text_color]";
break;
case 'st_posts_carousel':
var posts = jQuery("#posts").val();
var number = jQuery("#number").val();
var cat = jQuery("#cat").val();
var display_title = jQuery("#display_title").val();
var what = "[st_posts_carousel posts='"+posts+"' number='"+number+"' cat='"+cat+"' display_title='"+display_title+"']";
break;
case 'st_swiper':
var posts = jQuery("#swiper_posts").val();
var number = jQuery("#swiper_number").val();
var category = jQuery("#category").val();
var display_title = jQuery("#display_title").val();
var what = "[st_swiper posts='"+posts+"' number='"+number+"' category='"+category+"' display_title='"+display_title+"']";
break;
case 'st_animated':
var type = jQuery("#animated_type").val();
var trigger = jQuery("#trigger").val();
var precent = jQuery("#precent").val();
var what = "[st_animated type='"+type+"' trigger='"+trigger+"' precent='"+precent+"']Animated element goes here[/st_animated]";
break;
case 'st_svg_drawing':
var type = jQuery("#drawing_type").val();
var image_id = jQuery("#image_id").val();
var color = jQuery("#drawing_color").val();
var what = "[st_svg_drawing type='"+type+"' image_id='"+image_id+"' color='"+color+"']";
break;
case 'st_animated_boxes':
var posts = jQuery("#posts").val();
var what = "[st_animated_boxes posts='"+posts+"']";
break;
case 'st_icon':
var name = jQuery("#name").val();
var size = jQuery("#size").val();
var type = jQuery("#icon_type").val();
var color = jQuery("#icon_color").val();
var bg_color = jQuery("#icon_bg_color").val();
var border_color = jQuery("#icon_border_color").val();
var align = jQuery("#align").val();
var what = "[st_icon name='"+name+"' size='"+size+"' color='"+color+"' type='"+type+"' background='"+bg_color+"' border_color='"+border_color+"' align='"+align+"']";
break;
case 'st_icon_melon':
var name = jQuery("#name").val();
var size = jQuery("#size").val();
var type = jQuery("#icon_type").val();
var color = jQuery("#icon_color").val();
var bg_color = jQuery("#icon_bg_color").val();
var border_color = jQuery("#icon_border_color").val();
var align = jQuery("#align").val();
var what = "[st_icon_melon name='"+name+"' size='"+size+"' color='"+color+"' type='"+type+"' background='"+bg_color+"' border_color='"+border_color+"' align='"+align+"']";
break;
case 'st_social_icon':
var name = jQuery("#name").val();
var href = jQuery("#href").val();
var target = jQuery("#target").val();
var align = jQuery("#align").val();
var what = "[st_social_icon name='"+name+"' href='"+href+"' target='"+target+"' align='"+align+"']";
break;
case 'st_divider_text':
var type = jQuery("#divider_type").val();
var text = jQuery("#text").val();
var what = "[st_divider_text position='"+type+"' text='"+text+"']";
break;
case 'st_countdown':
var id = jQuery("#event_id").val();
var align = jQuery("#countdown_align").val();
var what = "[st_countdown id='"+id+"' align='"+align+"']";
break;
case 'st_testimonials':
var color = jQuery("#color").val();
var number = jQuery("#number").val();
var what = "[st_testimonials color='"+color+"' number='"+number+"']";
break;
}
if(this.validate()) {
if(preview === true) {
var values = {
'data': what
};
jQuery.ajax({
url: stPluginUrl + '/ajaxPlugin.php?act=preview',
type: 'POST',
data: values,
loading: function() {
jQuery("#previewDiv").empty().html('<div class="loading"> </div>')
},
success: function(response) {
jQuery("#previewDiv").empty().html(response);
}
});
} else {
tinyMCE.activeEditor.execCommand('mceInsertContent', 0, what);
}
}
},
validate: function() {
ret = true;
jQuery('.req').each(function() {
if(jQuery(this).find('input').val() == '') {
ret = false;
jQuery(this).find('input').addClass('errorInput');
} else {
jQuery(this).find('input').removeClass('errorInput');
}
if(jQuery(this).find('textarea').val() == '') {
ret = false;
jQuery(this).find('textarea').addClass('errorInput');
} else {
jQuery(this).find('textarea').removeClass('errorInput');
}
});
return ret;
},
readMore: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=readMore&preview');
what = 'st_button_more';
},
breakLine: function() {
tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_break_line]");
},
horizontalLine: function() {
tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_horizontal_line]");
},
divClear: function() {
tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_clear]");
},
createDividerDotted: function() {
tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_divider_dotted]");
},
createDividerDashed: function() {
tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_divider_dashed]");
},
createDividerTop: function() {
tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_divider_top]");
},
createDividerShadow: function() {
tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_divider_shadow]");
},
insertButton: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=insertButton&preview');
what = 'st_button';
},
insertHoverFillButton: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=insertHoverFillButton&preview');
what = 'st_hover_fill_button';
},
insertHoverFancyIconButton: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=insertHoverFancyIconButton&preview');
what = 'st_hover_fancy_icon_button';
},
insertHoverArrowsButton: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=insertHoverArrowsButton&preview');
what = 'st_hover_arrows_button';
},
insertHoverIconOnHoverButton: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=insertHoverIconOnHoverButton&preview');
what = 'st_hover_icon_button';
},
insertHoverBorderedButton: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=insertHoverBorderedButton&preview');
what = 'st_hover_bordered_button';
},
insertBox: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=insertBox&preview');
what = 'st_box';
},
dividerText: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=dividerText&preview');
what = 'st_divider_text';
},
eventCountdown: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=eventCountdown');
what = 'st_countdown';
},
createTestimonials: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=testimonials');
what = 'st_testimonials';
},
insertCallout: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=insertCallout&preview');
what = 'st_callout';
},
insertTooltip: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=insertTooltip&preview=remove');
what = 'st_tooltip';
},
insertPopover: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=insertPopover&preview=remove');
what = 'st_popover';
},
insertModal: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=insertModal&preview=remove');
what = 'st_modal';
},
createTabs: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=createTabs&preview=remove');
what = 'st_tabs';
},
createUnorderedList: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=createUnorderedList&preview');
what = 'st_unordered';
},
createOrderedList: function() {
var content = (tinyMCE.activeEditor.selection.getContent() != '') ? tinyMCE.activeEditor.selection.getContent() : '<ol><li>First list item</li></ol>';
tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_ordered]"+ content +"[/st_ordered]");
},
createToggle: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=toggle&preview');
what = 'st_toggle';
},
createAccordion: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=createAccordion&preview');
what = 'st_accordion';
},
createProgressBar: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=progress_bar&preview');
what = 'st_progress_bar';
},
createTables: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=createTable&preview');
what = 'st_tables';
},
relatedPosts: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=related&preview=remove');
what = 'st_related_posts';
},
logInOut: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=logInOut&preview');
what = 'st_loginout';
},
dropCap: function(type) {
tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_dropcap type='"+type+"']"+ tinyMCE.activeEditor.selection.getContent() +"[/st_dropcap]");
},
highlight: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=highlight&preview');
what = 'st_highlight';
},
labels: function(type) {
tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_label type='"+type+"']"+ tinyMCE.activeEditor.selection.getContent() +"[/st_label]");
},
quote: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=quote&preview');
what = 'st_quote';
},
abbreviation: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=abbreviation&preview');
what = 'st_abbreviation';
},
createTwitterButton: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=twitter&preview');
what = 'st_twitter';
},
createDiggButton: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=digg&preview');
what = 'st_digg';
},
createFBlikeButton: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=fblike&preview');
what = 'st_fblike';
},
createFBShareButton: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=fbshare&preview');
what = 'st_fbshare';
},
createLIShareButton: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=lishare&preview');
what = 'st_lishare';
},
createGplusButton: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=gplus&preview');
what = 'st_gplus';
},
createPinButton: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=pinterest_pin&preview');
what = 'st_pinterest_pin';
},
createTumblrButton: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=tumblr&preview');
what = 'st_tumblr';
},
createSocialIcon: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=social_icon&preview');
what = 'st_social_icon';
},
createPricingTables: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=pricingTable&preview');
what = 'st_pricingTable';
},
createFancyboxImages: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=fancyboxImages&preview=remove');
what = 'st_fancyboxImages';
},
createFancyboxInline: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=fancyboxInline&preview=remove');
what = 'st_fancyboxInline';
},
createFancyboxIframe: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=fancyboxIframe&preview=remove');
what = 'st_fancyboxIframe';
},
createFancyboxPage: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=fancyboxPage&preview=remove');
what = 'st_fancyboxPage';
},
createFancyboxSwf: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=fancyboxSwf&preview=remove');
what = 'st_fancyboxSwf';
},
createVideo: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=video&preview');
what = 'st_video';
},
createAudio: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=audio&preview');
what = 'st_audio';
},
createSoundcloud: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=soundcloud&preview');
what = 'st_soundcloud';
},
createMixcloud: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=mixcloud&preview');
what = 'st_mixcloud';
},
createSectionImage: function(){
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=section_image&preview=remove');
what = 'st_section_image';
},
createSectionColor: function(){
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=section_color&preview=remove');
what = 'st_section_color';
},
createContainer: function(){
var currentVal = 'Put your content here';
tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_container]"+ currentVal +"[/st_container]");
},
createTextColor: function(){
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=text_color&preview=remove');
what = 'st_text_color';
},
createRow: function(){
var currentVal = 'Put your columns here';
tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_row]"+ currentVal +"[/st_row]");
},
createColumnLayout: function(n) {
var col = '';
var values = {
'st_column1': 'st_column1',
'st_column2': 'st_column2',
'st_column3': 'st_column3',
'st_column4': 'st_column4',
'st_column5': 'st_column5',
'st_column6': 'st_column6',
'st_column7': 'st_column7',
'st_column8': 'st_column8',
'st_column9': 'st_column9',
'st_column10': 'st_column10',
'st_column11': 'st_column11',
'st_column12': 'st_column12',
}
col = values[n];
var currentVal = 'Your content goes here';
tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "["+col+"]"+ currentVal +"[/"+col+"]");
},
createGoogleMaps: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=gmap&preview=remove');
what = 'st_gmap';
},
createGoogleTrends: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=trends&preview=remove');
what = 'st_trends';
},
createChartPie: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=chart_pie&preview=remove');
what = 'st_chart_pie';
},
createChartBar: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=chart_bar&preview=remove');
what = 'st_chart_bar';
},
createChartArea: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=chart_area&preview=remove');
what = 'st_chart_area';
},
createChartGeo: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=chart_geo&preview=remove');
what = 'st_chart_geo';
},
createChartCombo: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=chart_combo&preview=remove');
what = 'st_chart_combo';
},
createChartOrg: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=chart_org&preview=remove');
what = 'st_chart_org';
},
createChartBubble: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=chart_bubble&preview=remove');
what = 'st_chart_bubble';
},
createGoogleDocs: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=gdocs&preview=remove');
what = 'st_gdocs';
},
pageSiblings: function() {
tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_siblings]");
},
children: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=children&preview');
what = 'st_children';
},
contactFormDark: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=contact_form_dark&preview');
what = 'st_contact_form_dark';
},
contactFormLight: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=contact_form_light&preview');
what = 'st_contact_form_light';
},
createCarousel: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=posts_carousel&preview=remove');
what = 'st_posts_carousel';
},
createSwiper: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=swiper&preview=remove');
what = 'st_swiper';
},
insertAnimated: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=animated&preview=remove');
what = 'st_animated';
},
insertDrawing: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=svg_drawing&preview=remove');
what = 'st_svg_drawing';
},
createIcon: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=icon&preview');
what = 'st_icon';
},
createIconMelon: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=melonIcon&preview');
what = 'st_icon_melon';
},
createCode: function() {
var currentVal = 'Put your code here';
tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_code]"+ currentVal +"[/st_code]");
}
};
var what = '';
jQuery('#insert').live('click', function(e) {
preview = false;
e.preventDefault();
themeShortcuts.insert(what);
tb_remove();
return false;
});
jQuery('#preview').live('click', function(e) {
preview = true;
e.preventDefault();
themeShortcuts.insert(what);
return false;
});
jQuery('#SupremeSocialTheme_preview input').live('blur', function() {
preview = true;
setTimeout(function() {
themeShortcuts.insert(what);
}, 300);
});
jQuery('#SupremeSocialTheme_preview select').live('change', function() {
preview = true;
setTimeout(function() {
themeShortcuts.insert(what);
}, 300);
});
jQuery('#cancel').live('click', function(e) {
tb_remove();
return false;
});
///////////////////////////////////////
// CHECK THE VERSION OF TINYMCE !!
///////////////////////////////////////
if (tinymce.majorVersion < 4) {
//////////////////////////////
// IF IS TINYMCE VERSION 3
//////////////////////////////
tinymce.create('tinymce.plugins.themeShortcuts', {
init: function(ed, url) {
},
createControl: function(n, cm) {
switch (n) {
case 'themeShortcuts':
var c = cm.createSplitButton('themeShortcuts', {
title : 'Theme shortcuts',
image : stPluginUrl + '/images/supremetheme-logo-19x19.png',
onclick : function() {
c.showMenu();
}
});
c.onRenderMenu.add(function(c,m) {
e = m.addMenu({title : 'Lines'});
e.add({title : 'Break Line', onclick : themeShortcuts.breakLine});
e.add({title : 'Horizontal Line', onclick : themeShortcuts.horizontalLine});
e.add({title : 'Clear', onclick : themeShortcuts.divClear});
var ea = e.addMenu({title : 'Dividers'});
ea.add({title : 'Dotted', onclick : themeShortcuts.createDividerDotted});
ea.add({title : 'Dashed', onclick : themeShortcuts.createDividerDashed});
ea.add({title : 'To Top', onclick : themeShortcuts.createDividerTop});
ea.add({title : 'Shadow', onclick : themeShortcuts.createDividerShadow});
ea.add({title : 'Text', onclick : themeShortcuts.dividerText});
b = m.addMenu({title : 'Buttons'});
b.add({title : 'Button', onclick : function() { themeShortcuts.insertButton() }});
var ba = b.addMenu({title : 'Hover Buttons'});
ba.add({title: 'Fill In', onclick : themeShortcuts.insertHoverFillButton});
ba.add({title: 'Fancy Icon', onclick : themeShortcuts.insertHoverFancyIconButton});
ba.add({title: 'Arrows', onclick : themeShortcuts.insertHoverArrowsButton});
ba.add({title: 'Icon on hover', onclick : themeShortcuts.insertHoverIconOnHoverButton});
ba.add({title: 'Bordered', onclick : themeShortcuts.insertHoverBorderedButton});
b.add({title : 'Read More', onclick : themeShortcuts.readMore});
var be = b.addMenu({title : 'Share Buttons'});
be.add({title: 'Twitter', onclick : themeShortcuts.createTwitterButton});
be.add({title: 'Digg', onclick : themeShortcuts.createDiggButton});
be.add({title: 'Facebook Like', onclick : themeShortcuts.createFBlikeButton});
be.add({title: 'Facebook Share', onclick : themeShortcuts.createFBShareButton});
be.add({title: 'LinkedIn', onclick : themeShortcuts.createLIShareButton});
be.add({title: 'Google+', onclick : themeShortcuts.createGplusButton});
be.add({title: 'Pinterest', onclick : themeShortcuts.createPinButton});
be.add({title: 'Tumbler', onclick : themeShortcuts.createTumblrButton});
b.add({title : 'Log in / out button', onclick : themeShortcuts.logInOut});
i = m.addMenu({title : 'Boxes'});
i.add({title : 'Box', onclick : themeShortcuts.insertBox});
i.add({title : 'Callout', onclick : themeShortcuts.insertCallout});
p = m.addMenu({title : 'Icons'});
p.add({title : 'Font Awesome', onclick : themeShortcuts.createIcon});
p.add({title : 'Icon Melon', onclick : themeShortcuts.createIconMelon});
p.add({title : 'Social Icons', onclick : themeShortcuts.createSocialIcon});
m.add({title : 'Animated', onclick : themeShortcuts.insertAnimated});
m.add({title : 'SVG Drawing', onclick : themeShortcuts.insertDrawing});
s = m.addMenu({title : 'Elements'});
s.add({title : 'Tooltip', onclick : themeShortcuts.insertTooltip});
s.add({title : 'Popover', onclick : themeShortcuts.insertPopover});
s.add({title : 'Modal', onclick : themeShortcuts.insertModal});
s.add({title : 'Tabs', onclick : themeShortcuts.createTabs});
s.add({title : 'Toggle', onclick : themeShortcuts.createToggle});
s.add({title : 'Accordion', onclick : themeShortcuts.createAccordion});
s.add({title : 'Progress Bar', onclick : themeShortcuts.createProgressBar});
r = m.addMenu({title : 'Section'});
r.add({title : 'Image', onclick : themeShortcuts.createSectionImage});
r.add({title : 'Color', onclick : themeShortcuts.createSectionColor});
m.add({title : 'Container', onclick : themeShortcuts.createContainer});
h = m.addMenu({title : 'Responsive'});
h.add({title : 'Row', onclick : themeShortcuts.createRow});
h.add({title: '1 column', onclick : function() { themeShortcuts.createColumnLayout('st_column1') }});
h.add({title: '2 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column2') }});
h.add({title: '3 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column3') }});
h.add({title: '4 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column4') }});
h.add({title: '5 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column5') }});
h.add({title: '6 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column6') }});
h.add({title: '7 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column7') }});
h.add({title: '8 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column8') }});
h.add({title: '9 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column9') }});
h.add({title: '10 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column10') }});
h.add({title: '11 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column11') }});
h.add({title: '12 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column12') }});
d = m.addMenu({title : 'Google'});
d.add({title : 'Google Maps', onclick : themeShortcuts.createGoogleMaps});
d.add({title : 'Google Trends', onclick : themeShortcuts.createGoogleTrends});
d.add({title : 'Google Docs', onclick : themeShortcuts.createGoogleDocs});
var da = d.addMenu({title : 'Google Charts'});
da.add({title : 'Pie', onclick : themeShortcuts.createChartPie});
da.add({title : 'Bar', onclick : themeShortcuts.createChartBar});
da.add({title : 'Area', onclick : themeShortcuts.createChartArea});
da.add({title : 'Geo', onclick : themeShortcuts.createChartGeo});
da.add({title : 'Combo', onclick : themeShortcuts.createChartCombo});
da.add({title : 'Org', onclick : themeShortcuts.createChartOrg});
da.add({title : 'Bubble', onclick : themeShortcuts.createChartBubble});
f = m.addMenu({title: 'Lists'});
f.add({title : 'Unordered list', onclick : themeShortcuts.createUnorderedList});
f.add({title : 'Ordered list', onclick : themeShortcuts.createOrderedList});
o = m.addMenu({title: 'Tables'});
o.add({title : 'Styled table', onclick : themeShortcuts.createTables});
o.add({title : 'Pricing table', onclick : themeShortcuts.createPricingTables});
l = m.addMenu({title : 'Media'});
l.add({title : 'Video', onclick : themeShortcuts.createVideo});
var la = l.addMenu({title : 'Audio'});
la.add({title : 'Soundcloud', onclick : themeShortcuts.createSoundcloud});
la.add({title : 'Mixcloud', onclick : themeShortcuts.createMixcloud});
la.add({title : 'Other', onclick : themeShortcuts.createAudio});
d = m.addMenu({title: 'Typography'});
var dc = d.addMenu({title : 'Dropcap'});
dc.add({title : 'Light', onclick : function() { themeShortcuts.dropCap('light') }});
dc.add({title : 'Light Circled', onclick : function() {themeShortcuts.dropCap('light_circled')}});
dc.add({title : 'Dark', onclick : function() {themeShortcuts.dropCap('dark')}});
dc.add({title : 'Dark Circled', onclick : function() {themeShortcuts.dropCap('dark_circled')}});
d.add({title : 'Quote', onclick : themeShortcuts.quote});
d.add({title : 'Highlight', onclick : themeShortcuts.highlight});
var df = d.addMenu({title: 'Label'});
df.add({title : 'Default', onclick : function() { themeShortcuts.labels('default') }});
df.add({title : 'New', onclick : function() {themeShortcuts.labels('success')}});
df.add({title : 'Warning', onclick : function() {themeShortcuts.labels('warning')}});
df.add({title : 'Important', onclick : function() {themeShortcuts.labels('important')}});
df.add({title : 'Notice', onclick : function() {themeShortcuts.labels('notice')}});
d.add({title : 'Colored Text', onclick : themeShortcuts.createTextColor});
d.add({title : 'Abbreviation', onclick : themeShortcuts.abbreviation});
p = m.addMenu({title : 'Related'});
p.add({title : 'Related posts', onclick : themeShortcuts.relatedPosts});
p.add({title : 'Siblings', onclick : themeShortcuts.pageSiblings});
p.add({title : 'Children', onclick : themeShortcuts.children});
k = m.addMenu({title : 'Fancybox'});
k.add({title : 'Images', onclick : themeShortcuts.createFancyboxImages});
k.add({title : 'Inline', onclick : themeShortcuts.createFancyboxInline});
k.add({title : 'iFrame', onclick : themeShortcuts.createFancyboxIframe});
k.add({title : 'Page', onclick : themeShortcuts.createFancyboxPage});
k.add({title : 'Swf', onclick : themeShortcuts.createFancyboxSwf});
j = m.addMenu({title : 'Contact form'});
j.add({title : 'Light', onclick : themeShortcuts.contactFormLight});
j.add({title : 'Dark', onclick : themeShortcuts.contactFormDark});
t = m.addMenu({title : 'Carousel'});
t.add({title : 'Post Carousel', onclick : themeShortcuts.createCarousel});
t.add({title : 'Swiper', onclick : themeShortcuts.createSwiper});
//t.add({title : 'Testimonial', onclick : themeShortcuts.createTestimonials});
//m.add({title : 'Countdown', onclick : themeShortcuts.eventCountdown});
m.add({title : 'Code', onclick : themeShortcuts.createCode});
});
return c;
}
return null;
},
});
}else{
//////////////////////////////
// IF IS TINYMCE VERSION 4+
//////////////////////////////
tinymce.create('tinymce.plugins.themeShortcuts', {
init : function(ed, url) {
ed.addButton( 'themeShortcuts', {
type: 'listbox',
text: 'Supreme',
icon: 'supreme',
classes: 'mce-btn supreme-class',
tooltip: 'Supreme Shortcodes',
onselect: function(e) {
},
values: [
{
type: 'listbox',
text: 'Lines',
icon: false,
classes: 'has-dropdown',
values: [
{ text: 'Break Line', onclick : themeShortcuts.breakLine},
{ text: 'Horizontal Line', onclick : themeShortcuts.horizontalLine},
{ text: 'Clear', onclick : themeShortcuts.divClear},
{
type: 'listbox',
text: 'Dividers',
icon: false,
classes: 'has-dropdown',
values: [
{ text: 'Dotted', onclick : function() {
tinymce.execCommand('mceInsertContent', false, '[st_divider_dotted]');
}},
{ text: 'Dashed', onclick : function() {
tinymce.execCommand('mceInsertContent', false, '[st_divider_dashed]');
}},
{ text: 'To Top', onclick : function() {
tinymce.execCommand('mceInsertContent', false, '[st_divider_top]');
}},
{ text: 'Shadow', onclick : function() {
tinymce.execCommand('mceInsertContent', false, '[st_divider_shadow]');
}},
{text: 'Text', onclick : function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=dividerText&preview');
what = 'st_divider_text';
}},
]
},
]
},
{
type: 'listbox',
text: 'Buttons',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Button', onclick : function() { themeShortcuts.insertButton() }},
{
type: 'listbox',
text: 'Hover Button',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Fill In', onclick : function() { themeShortcuts.insertHoverFillButton() }},
{text: 'Fancy Icon', onclick : function() { themeShortcuts.insertHoverFancyIconButton() }},
{text: 'Arrows', onclick : function() { themeShortcuts.insertHoverArrowsButton() }},
{text: 'Icon on hover', onclick : function() { themeShortcuts.insertHoverIconOnHoverButton() }},
{text: 'Bordered', onclick : function() { themeShortcuts.insertHoverBorderedButton() }},
]
},
{text: 'Read more', onclick : themeShortcuts.readMore},
{
type: 'listbox',
text: 'Share buttons',
icon: false,
classes: 'has-dropdown',
values: [
{ text: 'Twitter', onclick : themeShortcuts.createTwitterButton},
{ text: 'Digg', onclick : themeShortcuts.createDiggButton},
{ text: 'Facebook Like', onclick : themeShortcuts.createFBlikeButton},
{ text: 'Facebook Share', onclick : themeShortcuts.createFBShareButton},
{ text: 'LinkedIn', onclick : themeShortcuts.createLIShareButton},
{ text: 'Google+', onclick : themeShortcuts.createGplusButton},
{ text: 'Pinterest', onclick : themeShortcuts.createPinButton},
{ text: 'Tumbler', onclick : themeShortcuts.createTumblrButton},
]
},
{text: 'Log in / out button', onclick : themeShortcuts.logInOut},
]
},
{
type: 'listbox',
text: 'Boxes',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Info Box', onclick : themeShortcuts.insertBox},
{text: 'Callout', onclick : themeShortcuts.insertCallout},
]
},
{
type: 'listbox',
text: 'Icons',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Font Awesome', onclick : themeShortcuts.createIcon},
{text: 'Icon Melon', onclick : themeShortcuts.createIconMelon},
{text: 'Social Icons', onclick : themeShortcuts.createSocialIcon},
]
},
{classes: 'no-dropdown', text: 'Animated', onclick : themeShortcuts.insertAnimated},
{classes: 'no-dropdown', text: 'SVG Drawing', onclick : themeShortcuts.insertDrawing},
{
type: 'listbox',
text: 'Elements',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Tooltip', onclick : themeShortcuts.insertTooltip},
{text: 'Popover', onclick : themeShortcuts.insertPopover},
{text: 'Modal', onclick : themeShortcuts.insertModal},
{text: 'Tabs', onclick : themeShortcuts.createTabs},
{text: 'Toggle', onclick : themeShortcuts.createToggle},
{text: 'Accordion', onclick : themeShortcuts.createAccordion},
{text: 'Progress Bar', onclick : themeShortcuts.createProgressBar},
]
},
{
type: 'listbox',
text: 'Section',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Image', onclick : themeShortcuts.createSectionImage},
{text: 'Color', onclick : themeShortcuts.createSectionColor},
]
},
{classes: 'no-dropdown', text: 'Container', onclick : themeShortcuts.createContainer},
{
type: 'listbox',
text: 'Responsive',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Row', onclick : themeShortcuts.createRow},
{text: '1 column', onclick : function() { themeShortcuts.createColumnLayout('st_column1') }},
{text: '2 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column2') }},
{text: '3 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column3') }},
{text: '4 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column4') }},
{text: '5 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column5') }},
{text: '6 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column6') }},
{text: '7 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column7') }},
{text: '8 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column8') }},
{text: '9 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column9') }},
{text: '10 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column10') }},
{text: '11 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column11') }},
{text: '12 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column12') }},
]
},
{
type: 'listbox',
text: 'Google',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Google Maps', onclick : themeShortcuts.createGoogleMaps},
{text: 'Google Trends', onclick : themeShortcuts.createGoogleTrends},
{text: 'Google Docs', onclick : themeShortcuts.createGoogleDocs},
{
type: 'listbox',
text: 'Google Charts',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Pie', onclick : themeShortcuts.createChartPie},
{text: 'Bar', onclick : themeShortcuts.createChartBar},
{text: 'Area', onclick : themeShortcuts.createChartArea},
{text: 'Geo', onclick : themeShortcuts.createChartGeo},
{text: 'Combo', onclick : themeShortcuts.createChartCombo},
{text: 'Org', onclick : themeShortcuts.createChartOrg},
{text: 'Bubble', onclick : themeShortcuts.createChartBubble},
]
},
]
},
{
type: 'listbox',
text: 'Lists',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Unordered list', onclick : themeShortcuts.createUnorderedList},
{text: 'Ordered list', onclick : themeShortcuts.createOrderedList},
]
},
{
type: 'listbox',
text: 'Tables',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Styled table', onclick : themeShortcuts.createTables},
{text: 'Pricing table', onclick : themeShortcuts.createPricingTables},
]
},
{
type: 'listbox',
text: 'Media',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Video', onclick : themeShortcuts.createVideo},
{
type: 'listbox',
text: 'Audio',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Soundcloud', onclick : themeShortcuts.createSoundcloud},
{text: 'Mixcloud', onclick : themeShortcuts.createMixcloud},
{text: 'Other', onclick : themeShortcuts.createAudio},
]
},
]
},
{
type: 'listbox',
text: 'Typography',
icon: false,
classes: 'has-dropdown',
values: [
{
type: 'listbox',
text: 'Dropcap',
icon: false,
values: [
{text: 'Light', onclick : function() {themeShortcuts.dropCap('light')}},
{text: 'Light Circled', onclick : function() {themeShortcuts.dropCap('light_circled')}},
{text: 'Dark', onclick : function() {themeShortcuts.dropCap('dark')}},
{text: 'Dark Circled', onclick : function() {themeShortcuts.dropCap('dark_circled')}},
]
},
{text: 'Quote', onclick : themeShortcuts.quote},
{text: 'Highlight', onclick : themeShortcuts.highlight},
{
type: 'listbox',
text: 'Label',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Default', onclick : function() { themeShortcuts.labels('default') }},
{text: 'New', onclick : function() { themeShortcuts.labels('success') }},
{text: 'Warning', onclick : function() { themeShortcuts.labels('warning') }},
{text: 'Important', onclick : function() { themeShortcuts.labels('important') }},
{text: 'Notice', onclick : function() { themeShortcuts.labels('notice') }},
]
},
{text: 'Colored Text', onclick : themeShortcuts.createTextColor},
{text: 'Abbreviation', onclick : themeShortcuts.abbreviation},
]
},
{
type: 'listbox',
text: 'Related',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Related posts', onclick : themeShortcuts.relatedPosts},
{text: 'Siblings', onclick : themeShortcuts.pageSiblings},
{text: 'Children', onclick : themeShortcuts.children},
]
},
{
type: 'listbox',
text: 'Fancybox',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Images', onclick : themeShortcuts.createFancyboxImages},
{text: 'Inline', onclick : themeShortcuts.createFancyboxInline},
{text: 'iFrame', onclick : themeShortcuts.createFancyboxIframe},
{text: 'Page', onclick : themeShortcuts.createFancyboxPage},
{text: 'Swf', onclick : themeShortcuts.createFancyboxSwf},
]
},
{
type: 'listbox',
text: 'Contact form',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Light', onclick : themeShortcuts.contactFormLight},
{text: 'Dark', onclick : themeShortcuts.contactFormDark},
]
},
{
type: 'listbox',
text: 'Carousel',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Post Carousel', onclick : themeShortcuts.createCarousel},
{text: 'Swiper', onclick : themeShortcuts.createSwiper},
//{text: 'Testimonial', onclick : themeShortcuts.createTestimonials},
]
},
//{classes: 'no-dropdown', text: 'Countdown', onclick : themeShortcuts.eventCountdown},
{classes: 'no-dropdown', text: 'Code', onclick : themeShortcuts.createCode},
]
});
},
});
};//end else
tinymce.PluginManager.add('themeShortcuts', tinymce.plugins.themeShortcuts);
})() | vinciteng/bookitforward | wp-content/plugins/SupremeShortcodes/js/editor_plugin.js | JavaScript | gpl-2.0 | 66,280 |
require 'rails_helper'
BitcoinConf = Rails.configuration.payment
def give_bitcoins(amount, address, confirm=false)
http = Net::HTTP.start(BitcoinConf['host'], BitcoinConf['port'])
req = Net::HTTP::Post.new("/debug/give/#{amount}/#{address}")
req.basic_auth BitcoinConf['user'], BitcoinConf['password']
http.request(req)
if confirm
gen_blocks 3
end
end
def gen_blocks(number)
http = Net::HTTP.start(BitcoinConf['host'], BitcoinConf['port'])
req = Net::HTTP::Post.new("/debug/gen/#{number}")
req.basic_auth BitcoinConf['user'], BitcoinConf['password']
http.request(req)
end
def sync
http = Net::HTTP.start(BitcoinConf['host'], BitcoinConf['port'])
req = Net::HTTP::Post.new('/sync')
req.basic_auth BitcoinConf['user'], BitcoinConf['password']
http.request(req)
end
RSpec.describe BitcoinHelper, type: :helper do
describe 'with bitcoin adapter running' do
it 'should not throw error on new_address' do
expect do
new_address
end.not_to raise_error
end
it 'should not throw error on address_info' do
expect do
address_info 'none'
end.not_to raise_error
end
end
describe '#new_address' do
it 'should return the address of any user' do
address = new_address
expect(address).to be_a String
expect(address.length).to be >= 24
expect(address.length).to be <= 34
end
it 'should never return the same address' do
addresses = 10.times.map do |i| new_address end
expect(addresses).to eq addresses.uniq
end
end
describe '#address_info' do
before do gen_blocks 101 end # ensure we have enough (fake) bitcoins
it 'should return a hash' do
address = new_address
expect(address_info address).to be_a Hash
end
it 'should start address with no balance' do
address = new_address
expect(address_info(address)[:balance].to_s).to eq '0.0'
end
it 'should have balance when given bitcoins' do
address = new_address
expect(address_info(address)[:balance].to_s).to eq '0.0'
give_bitcoins '1.2345678', address, true
sync
expect(address_info(address)[:balance].to_s).to eq '1.2345678'
end
it 'should keep bitcoin amount accurately' do
address = new_address
expect(address).to be_a String
expect(address.length).to be >= 24
expect(address.length).to be <= 34
expect(address_info(address)[:balance].to_s).to eq '0.0'
12.times do
give_bitcoins('0.00001', address)
end
gen_blocks 101
sync
expect(address_info(address)[:transactions].length).to eq 12
expect(address_info(address)[:balance].to_s).to eq '0.00012'
end
it 'should require three confirmations' do
address = new_address
expect(address_info(address)[:balance].to_s).to eq '0.0'
give_bitcoins '0.00001', address
sync
expect(address_info(address)[:balance].to_s).to eq '0.0'
gen_blocks 1
sync
expect(address_info(address)[:balance].to_s).to eq '0.0'
gen_blocks 1
sync
expect(address_info(address)[:balance].to_s).to eq '0.0'
gen_blocks 1
sync
expect(address_info(address)[:balance].to_s).to eq '0.00001'
end
it 'should return an array for transactions' do
expect(address_info(new_address)[:transactions]).to be_a Array
end
it 'user should start with no transactions' do
address = new_address
expect(address_info(new_address)[:transactions].length).to eq 0
end
it 'should show new transactions' do
address = new_address
expect(address_info(address)[:transactions].length).to eq 0
give_bitcoins '0.00001', address
sync
expect(address_info(address)[:transactions].length).to eq 1
expect(address_info(address)[:transactions][0][:amount].to_s).to eq '0.00001'
expect(address_info(address)[:transactions][0][:confirmations]).to eq 0
gen_blocks 1
give_bitcoins '0.00002', address
sync
expect(address_info(address)[:transactions].length).to eq 2
expect(address_info(address)[:transactions][0][:amount].to_s).to eq '0.00001'
expect(address_info(address)[:transactions][0][:confirmations]).to eq 1
expect(address_info(address)[:transactions][1][:amount].to_s).to eq '0.00002'
expect(address_info(address)[:transactions][1][:confirmations]).to eq 0
end
end
end
| turbio/skeem.club | spec/helpers/bitcoin_helper_spec.rb | Ruby | gpl-2.0 | 4,191 |
<?php
/**
* WordPress基础配置文件。
*
* 本文件包含以下配置选项:MySQL设置、数据库表名前缀、密钥、
* WordPress语言设定以及ABSPATH。如需更多信息,请访问
* {@link http://codex.wordpress.org/zh-cn:%E7%BC%96%E8%BE%91_wp-config.php
* 编辑wp-config.php}Codex页面。MySQL设置具体信息请咨询您的空间提供商。
*
* 这个文件被安装程序用于自动生成wp-config.php配置文件,
* 您可以手动复制这个文件,并重命名为“wp-config.php”,然后填入相关信息。
*
* @package WordPress
*/
// ** MySQL 设置 - 具体信息来自您正在使用的主机 ** //
/** WordPress数据库的名称 */
define('DB_NAME', 'wordpress-example');
/** MySQL数据库用户名 */
define('DB_USER', 'root');
/** MySQL数据库密码 */
define('DB_PASSWORD', 'usbw');
/** MySQL主机 */
define('DB_HOST', 'localhost');
/** 创建数据表时默认的文字编码 */
define('DB_CHARSET', 'utf8mb4');
/** 数据库整理类型。如不确定请勿更改 */
define('DB_COLLATE', '');
/**#@+
* 身份认证密钥与盐。
*
* 修改为任意独一无二的字串!
* 或者直接访问{@link https://api.wordpress.org/secret-key/1.1/salt/
* WordPress.org密钥生成服务}
* 任何修改都会导致所有cookies失效,所有用户将必须重新登录。
*
* @since 2.6.0
*/
define('AUTH_KEY', '#aW$yz|7k+TH=QYh_@JdBYoTneUk fPE;TQ6Y~>jiJC5Iq5${w^@ll9=IE$b%Bw$');
define('SECURE_AUTH_KEY', 'wm0Kp-9BQOdKzfn+rXFLIcaEFW=2[ETFBr!VMN9rRo@u++K+-WmOv|?JR0K<v*o~');
define('LOGGED_IN_KEY', 'qHC8~]W&#gTOdq{J+X|m4!78Ay$E0pu#@mG=#V|Y.t<HgKN|yFQ0MNME_rJ}wG#B');
define('NONCE_KEY', 'uRZ[j T5V+W3Mjz[|BZ(4MH^4X.z$H?TaQb 1L3-xT-H&.@JBW 1TSb$LY+|N2d;');
define('AUTH_SALT', 'V3RuF2}ICN7h|D-a5%cGVo{i!EE]D ;6K+MY~TiZNOG(hVEimE`jVLjYV16r{rc+');
define('SECURE_AUTH_SALT', 'G-+=4IOrajJ.J]r!6>_w(<,Oxb9oxd-||,y,2p%H?r,9yC6J<&59$73b4R!30u`t');
define('LOGGED_IN_SALT', 'c_i}*snL:aL^C`Vc780;^&SVrR_khGCKjhSi01]|+$+|t;8ZmWyo29R?X` O1C_!');
define('NONCE_SALT', '~yOsagc$nT|)z m|4ykEO{hYdd[]/f)<7L5[$3n.WjH$edY+PV7vmy3nnt@_5XAm');
/**#@-*/
/**
* WordPress数据表前缀。
*
* 如果您有在同一数据库内安装多个WordPress的需求,请为每个WordPress设置
* 不同的数据表前缀。前缀名只能为数字、字母加下划线。
*/
$table_prefix = 'wp_';
/**
* 开发者专用:WordPress调试模式。
*
* 将这个值改为true,WordPress将显示所有用于开发的提示。
* 强烈建议插件开发者在开发环境中启用WP_DEBUG。
*/
define('WP_DEBUG', false);
/**
* zh_CN本地化设置:启用ICP备案号显示
*
* 可在设置→常规中修改。
* 如需禁用,请移除或注释掉本行。
*/
define('WP_ZH_CN_ICP_NUM', true);
/* 好了!请不要再继续编辑。请保存本文件。使用愉快! */
/** WordPress目录的绝对路径。 */
if ( !defined('ABSPATH') )
define('ABSPATH', dirname(__FILE__) . '/');
/** 设置WordPress变量和包含文件。 */
require_once(ABSPATH . 'wp-settings.php');
| jianganglu/wordpress-example | wp-config.php | PHP | gpl-2.0 | 3,091 |
<?php
namespace MediaWiki\Extension\AbuseFilter\Variables;
use ContentHandler;
use Diff;
use Language;
use MediaWiki\Extension\AbuseFilter\Hooks\AbuseFilterHookRunner;
use MediaWiki\Extension\AbuseFilter\Parser\AFPData;
use MediaWiki\Extension\AbuseFilter\TextExtractor;
use MediaWiki\Permissions\PermissionManager;
use MediaWiki\Revision\RevisionLookup;
use MediaWiki\Revision\RevisionStore;
use MediaWiki\User\UserEditTracker;
use MediaWiki\User\UserGroupManager;
use MediaWiki\User\UserIdentity;
use MWException;
use Parser;
use ParserOptions;
use Psr\Log\LoggerInterface;
use stdClass;
use StringUtils;
use TextContent;
use Title;
use UnifiedDiffFormatter;
use User;
use WANObjectCache;
use Wikimedia\Rdbms\Database;
use Wikimedia\Rdbms\ILoadBalancer;
use WikiPage;
/**
* Service used to compute lazy-loaded variable.
* @internal
*/
class LazyVariableComputer {
public const SERVICE_NAME = 'AbuseFilterLazyVariableComputer';
/**
* @var float The amount of time to subtract from profiling
* @todo This is a hack
*/
public static $profilingExtraTime = 0;
/** @var TextExtractor */
private $textExtractor;
/** @var AbuseFilterHookRunner */
private $hookRunner;
/** @var LoggerInterface */
private $logger;
/** @var ILoadBalancer */
private $loadBalancer;
/** @var WANObjectCache */
private $wanCache;
/** @var RevisionLookup */
private $revisionLookup;
/** @var RevisionStore */
private $revisionStore;
/** @var Language */
private $contentLanguage;
/** @var Parser */
private $parser;
/** @var UserEditTracker */
private $userEditTracker;
/** @var UserGroupManager */
private $userGroupManager;
/** @var PermissionManager */
private $permissionManager;
/** @var string */
private $wikiID;
/**
* @param TextExtractor $textExtractor
* @param AbuseFilterHookRunner $hookRunner
* @param LoggerInterface $logger
* @param ILoadBalancer $loadBalancer
* @param WANObjectCache $wanCache
* @param RevisionLookup $revisionLookup
* @param RevisionStore $revisionStore
* @param Language $contentLanguage
* @param Parser $parser
* @param UserEditTracker $userEditTracker
* @param UserGroupManager $userGroupManager
* @param PermissionManager $permissionManager
* @param string $wikiID
*/
public function __construct(
TextExtractor $textExtractor,
AbuseFilterHookRunner $hookRunner,
LoggerInterface $logger,
ILoadBalancer $loadBalancer,
WANObjectCache $wanCache,
RevisionLookup $revisionLookup,
RevisionStore $revisionStore,
Language $contentLanguage,
Parser $parser,
UserEditTracker $userEditTracker,
UserGroupManager $userGroupManager,
PermissionManager $permissionManager,
string $wikiID
) {
$this->textExtractor = $textExtractor;
$this->hookRunner = $hookRunner;
$this->logger = $logger;
$this->loadBalancer = $loadBalancer;
$this->wanCache = $wanCache;
$this->revisionLookup = $revisionLookup;
$this->revisionStore = $revisionStore;
$this->contentLanguage = $contentLanguage;
$this->parser = $parser;
$this->userEditTracker = $userEditTracker;
$this->userGroupManager = $userGroupManager;
$this->permissionManager = $permissionManager;
$this->wikiID = $wikiID;
}
/**
* XXX: $getVarCB is a hack to hide the cyclic dependency with VariablesManager. See T261069 for possible
* solutions. This might also be merged into VariablesManager, but it would bring a ton of dependencies.
* @todo Should we remove $vars parameter (check hooks)?
*
* @param LazyLoadedVariable $var
* @param VariableHolder $vars
* @param callable $getVarCB
* @phan-param callable(string $name):AFPData $getVarCB
* @return AFPData
* @throws MWException
*/
public function compute( LazyLoadedVariable $var, VariableHolder $vars, callable $getVarCB ) {
$parameters = $var->getParameters();
$varMethod = $var->getMethod();
$result = null;
if ( !$this->hookRunner->onAbuseFilter_interceptVariable(
$varMethod,
$vars,
$parameters,
$result
) ) {
return $result instanceof AFPData
? $result : AFPData::newFromPHPVar( $result );
}
switch ( $varMethod ) {
case 'diff':
$text1Var = $parameters['oldtext-var'];
$text2Var = $parameters['newtext-var'];
$text1 = $getVarCB( $text1Var )->toString();
$text2 = $getVarCB( $text2Var )->toString();
// T74329: if there's no text, don't return an array with the empty string
$text1 = $text1 === '' ? [] : explode( "\n", $text1 );
$text2 = $text2 === '' ? [] : explode( "\n", $text2 );
$diffs = new Diff( $text1, $text2 );
$format = new UnifiedDiffFormatter();
$result = $format->format( $diffs );
break;
case 'diff-split':
$diff = $getVarCB( $parameters['diff-var'] )->toString();
$line_prefix = $parameters['line-prefix'];
$diff_lines = explode( "\n", $diff );
$result = [];
foreach ( $diff_lines as $line ) {
if ( substr( $line, 0, 1 ) === $line_prefix ) {
$result[] = substr( $line, strlen( $line_prefix ) );
}
}
break;
case 'links-from-wikitext':
// This should ONLY be used when sharing a parse operation with the edit.
/** @var WikiPage $article */
$article = $parameters['article'];
if ( $article->getContentModel() === CONTENT_MODEL_WIKITEXT ) {
// Shared with the edit, don't count it in profiling
$startTime = microtime( true );
$textVar = $parameters['text-var'];
$new_text = $getVarCB( $textVar )->toString();
$content = ContentHandler::makeContent( $new_text, $article->getTitle() );
$editInfo = $article->prepareContentForEdit(
$content,
null,
$parameters['contextUser']
);
$result = array_keys( $editInfo->output->getExternalLinks() );
self::$profilingExtraTime += ( microtime( true ) - $startTime );
break;
}
// Otherwise fall back to database
case 'links-from-wikitext-or-database':
// TODO: use Content object instead, if available!
/** @var WikiPage $article */
$article = $article ?? $parameters['article'];
// this inference is ugly, but the name isn't accessible from here
// and we only want this for debugging
$varName = strpos( $parameters['text-var'], 'old_' ) === 0 ? 'old_links' : 'all_links';
if ( $vars->forFilter ) {
$this->logger->debug( "Loading $varName from DB" );
$links = $this->getLinksFromDB( $article );
} elseif ( $article->getContentModel() === CONTENT_MODEL_WIKITEXT ) {
$this->logger->debug( "Loading $varName from Parser" );
$textVar = $parameters['text-var'];
$wikitext = $getVarCB( $textVar )->toString();
$editInfo = $this->parseNonEditWikitext(
$wikitext,
$article,
$parameters['contextUser']
);
$links = array_keys( $editInfo->output->getExternalLinks() );
} else {
// TODO: Get links from Content object. But we don't have the content object.
// And for non-text content, $wikitext is usually not going to be a valid
// serialization, but rather some dummy text for filtering.
$links = [];
}
$result = $links;
break;
case 'link-diff-added':
case 'link-diff-removed':
$oldLinkVar = $parameters['oldlink-var'];
$newLinkVar = $parameters['newlink-var'];
$oldLinks = $getVarCB( $oldLinkVar )->toNative();
$newLinks = $getVarCB( $newLinkVar )->toNative();
if ( $varMethod === 'link-diff-added' ) {
$result = array_diff( $newLinks, $oldLinks );
}
if ( $varMethod === 'link-diff-removed' ) {
$result = array_diff( $oldLinks, $newLinks );
}
break;
case 'parse-wikitext':
// Should ONLY be used when sharing a parse operation with the edit.
// TODO: use Content object instead, if available!
/* @var WikiPage $article */
$article = $parameters['article'];
if ( $article->getContentModel() === CONTENT_MODEL_WIKITEXT ) {
// Shared with the edit, don't count it in profiling
$startTime = microtime( true );
$textVar = $parameters['wikitext-var'];
$new_text = $getVarCB( $textVar )->toString();
$content = ContentHandler::makeContent( $new_text, $article->getTitle() );
$editInfo = $article->prepareContentForEdit(
$content,
null,
$parameters['contextUser']
);
if ( isset( $parameters['pst'] ) && $parameters['pst'] ) {
$result = $editInfo->pstContent->serialize( $editInfo->format );
} else {
// Note: as of core change r727361, the PP limit comments (which we don't want to be here)
// are already excluded.
$result = $editInfo->getOutput()->getText();
}
self::$profilingExtraTime += ( microtime( true ) - $startTime );
} else {
$result = '';
}
break;
case 'strip-html':
$htmlVar = $parameters['html-var'];
$html = $getVarCB( $htmlVar )->toString();
$stripped = StringUtils::delimiterReplace( '<', '>', '', $html );
// We strip extra spaces to the right because the stripping above
// could leave a lot of whitespace.
// @fixme Find a better way to do this.
$result = TextContent::normalizeLineEndings( $stripped );
break;
case 'load-recent-authors':
$result = $this->getLastPageAuthors( $parameters['title'] );
break;
case 'load-first-author':
$revision = $this->revisionLookup->getFirstRevision( $parameters['title'] );
if ( $revision ) {
// TODO T233241
$user = $revision->getUser();
$result = $user === null ? '' : $user->getName();
} else {
$result = '';
}
break;
case 'get-page-restrictions':
$action = $parameters['action'];
/** @var Title $title */
$title = $parameters['title'];
$result = $title->getRestrictions( $action );
break;
case 'user-editcount':
/** @var UserIdentity $userIdentity */
$userIdentity = $parameters['user-identity'];
$result = $this->userEditTracker->getUserEditCount( $userIdentity );
break;
case 'user-emailconfirm':
/** @var User $user */
$user = $parameters['user'];
$result = $user->getEmailAuthenticationTimestamp();
break;
case 'user-groups':
/** @var UserIdentity $userIdentity */
$userIdentity = $parameters['user-identity'];
$result = $this->userGroupManager->getUserEffectiveGroups( $userIdentity );
break;
case 'user-rights':
/** @var UserIdentity $userIdentity */
$userIdentity = $parameters['user-identity'];
$result = $this->permissionManager->getUserPermissions( $userIdentity );
break;
case 'user-block':
// @todo Support partial blocks?
/** @var User $user */
$user = $parameters['user'];
$result = (bool)$user->getBlock();
break;
case 'user-age':
/** @var User $user */
$user = $parameters['user'];
$asOf = $parameters['asof'];
if ( !$user->isRegistered() ) {
$result = 0;
} else {
$registration = $user->getRegistration();
// HACK: If there's no registration date, assume 2008-01-15, Wikipedia Day
// in the year before the new user log was created. See T243469.
if ( $registration === null ) {
$registration = "20080115000000";
}
$result = (int)wfTimestamp( TS_UNIX, $asOf ) - (int)wfTimestamp( TS_UNIX, $registration );
}
break;
case 'page-age':
/** @var Title $title */
$title = $parameters['title'];
$firstRev = $this->revisionLookup->getFirstRevision( $title );
$firstRevisionTime = $firstRev ? $firstRev->getTimestamp() : null;
if ( !$firstRevisionTime ) {
$result = 0;
break;
}
$asOf = $parameters['asof'];
$result = (int)wfTimestamp( TS_UNIX, $asOf ) - (int)wfTimestamp( TS_UNIX, $firstRevisionTime );
break;
case 'length':
$s = $getVarCB( $parameters['length-var'] )->toString();
$result = strlen( $s );
break;
case 'subtract-int':
$v1 = $getVarCB( $parameters['val1-var'] )->toInt();
$v2 = $getVarCB( $parameters['val2-var'] )->toInt();
$result = $v1 - $v2;
break;
case 'revision-text-by-id':
$revRec = $this->revisionLookup->getRevisionById( $parameters['revid'] );
$result = $this->textExtractor->revisionToString( $revRec, $parameters['contextUser'] );
break;
case 'get-wiki-name':
$result = $this->wikiID;
break;
case 'get-wiki-language':
$result = $this->contentLanguage->getCode();
break;
default:
if ( $this->hookRunner->onAbuseFilter_computeVariable(
$varMethod,
$vars,
$parameters,
$result
) ) {
throw new MWException( 'Unknown variable compute type ' . $varMethod );
}
}
return $result instanceof AFPData ? $result : AFPData::newFromPHPVar( $result );
}
/**
* @param WikiPage $article
* @return array
*/
private function getLinksFromDB( WikiPage $article ) {
// Stolen from ConfirmEdit, SimpleCaptcha::getLinksFromTracker
$id = $article->getId();
if ( !$id ) {
return [];
}
$dbr = $this->loadBalancer->getConnectionRef( DB_REPLICA );
return $dbr->selectFieldValues(
'externallinks',
'el_to',
[ 'el_from' => $id ],
__METHOD__
);
}
/**
* @todo Move to MW core (T272050)
* @param Title $title
* @return string[] Usernames of the last 10 (unique) authors from $title
*/
private function getLastPageAuthors( Title $title ) {
if ( !$title->exists() ) {
return [];
}
$fname = __METHOD__;
return $this->wanCache->getWithSetCallback(
$this->wanCache->makeKey( 'last-10-authors', 'revision', $title->getLatestRevID() ),
WANObjectCache::TTL_MINUTE,
function ( $oldValue, &$ttl, array &$setOpts ) use ( $title, $fname ) {
$dbr = $this->loadBalancer->getConnectionRef( DB_REPLICA );
// T270033 Index renaming
$revIndex = $dbr->indexExists( 'revision', 'page_timestamp', $fname )
? 'page_timestamp'
: 'rev_page_timestamp';
$setOpts += Database::getCacheSetOptions( $dbr );
// Get the last 100 edit authors with a trivial query (avoid T116557)
$revQuery = $this->revisionStore->getQueryInfo();
$revAuthors = $dbr->selectFieldValues(
$revQuery['tables'],
$revQuery['fields']['rev_user_text'],
[
'rev_page' => $title->getArticleID(),
// TODO Should deleted names be counted in the 10 authors? If yes, this check should
// be moved inside the foreach
'rev_deleted' => 0
],
$fname,
// Some pages have < 10 authors but many revisions (e.g. bot pages)
[ 'ORDER BY' => 'rev_timestamp DESC, rev_id DESC',
'LIMIT' => 100,
// Force index per T116557
'USE INDEX' => [ 'revision' => $revIndex ],
],
$revQuery['joins']
);
// Get the last 10 distinct authors within this set of edits
$users = [];
foreach ( $revAuthors as $author ) {
$users[$author] = 1;
if ( count( $users ) >= 10 ) {
break;
}
}
return array_keys( $users );
}
);
}
/**
* It's like WikiPage::prepareContentForEdit, but not for editing (old wikitext usually)
*
* @param string $wikitext
* @param WikiPage $article
* @param User $user Context user
*
* @return stdClass
*/
private function parseNonEditWikitext( $wikitext, WikiPage $article, User $user ) {
static $cache = [];
$cacheKey = md5( $wikitext ) . ':' . $article->getTitle()->getPrefixedText();
if ( isset( $cache[$cacheKey] ) ) {
return $cache[$cacheKey];
}
$edit = (object)[];
$options = ParserOptions::newFromUser( $user );
$edit->output = $this->parser->parse( $wikitext, $article->getTitle(), $options );
$cache[$cacheKey] = $edit;
return $edit;
}
}
| wikimedia/mediawiki-extensions-AbuseFilter | includes/Variables/LazyVariableComputer.php | PHP | gpl-2.0 | 15,514 |
/* Yet Another Forum.NET
* Copyright (C) 2006-2013 Jaben Cargman
* http://www.yetanotherforum.net/
*
* 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 2
* 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, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
namespace YAF.Controls
{
#region Using
using System;
using System.Data;
using System.Text;
using YAF.Classes;
using YAF.Classes.Data;
using YAF.Core;
using YAF.Core.Model;
using YAF.Types;
using YAF.Types.Extensions;
using YAF.Types.Interfaces;
using YAF.Types.Models;
using YAF.Utilities;
using YAF.Utils;
#endregion
/// <summary>
/// Summary description for smileys.
/// </summary>
public partial class smileys : BaseUserControl
{
#region Constants and Fields
/// <summary>
/// The _dt smileys.
/// </summary>
protected DataTable _dtSmileys;
/// <summary>
/// The _onclick.
/// </summary>
private string _onclick;
/// <summary>
/// The _perrow.
/// </summary>
private int _perrow = 6;
#endregion
#region Properties
/// <summary>
/// Sets OnClick.
/// </summary>
public string OnClick
{
set
{
this._onclick = value;
}
}
#endregion
#region Methods
/// <summary>
/// The On PreRender event.
/// </summary>
/// <param name="e">
/// the Event Arguments
/// </param>
protected override void OnPreRender([NotNull] EventArgs e)
{
LoadingImage.ImageUrl = YafForumInfo.GetURLToResource("images/loader.gif");
LoadingImage.AlternateText = this.Get<ILocalization>().GetText("COMMON", "LOADING");
LoadingImage.ToolTip = this.Get<ILocalization>().GetText("COMMON", "LOADING");
LoadingText.Text = this.Get<ILocalization>().GetText("COMMON", "LOADING");
// Setup Pagination js
YafContext.Current.PageElements.RegisterJsResourceInclude("paginationjs", "js/jquery.pagination.js");
YafContext.Current.PageElements.RegisterJsBlock("paginationloadjs", JavaScriptBlocks.PaginationLoadJs);
base.OnPreRender(e);
}
/// <summary>
/// The page_ load.
/// </summary>
/// <param name="sender">
/// The sender.
/// </param>
/// <param name="e">
/// The e.
/// </param>
protected void Page_Load([NotNull] object sender, [NotNull] EventArgs e)
{
this._dtSmileys = this.GetRepository<Smiley>().ListUnique(this.PageContext.PageBoardID);
if (this._dtSmileys.Rows.Count == 0)
{
this.SmiliesPlaceholder.Visible = false;
}
else
{
this.CreateSmileys();
}
}
/// <summary>
/// The create smileys.
/// </summary>
private void CreateSmileys()
{
var html = new StringBuilder();
html.Append("<div class=\"result\">");
html.AppendFormat("<ul class=\"SmilieList\">");
int rowPanel = 0;
for (int i = 0; i < this._dtSmileys.Rows.Count; i++)
{
DataRow row = this._dtSmileys.Rows[i];
if (i % this._perrow == 0 && i > 0 && i < this._dtSmileys.Rows.Count)
{
rowPanel++;
if (rowPanel == 3)
{
html.Append("</ul></div>");
html.Append("<div class=\"result\">");
html.Append("<ul class=\"SmilieList\">\n");
rowPanel = 0;
}
}
string evt = string.Empty;
if (this._onclick.Length > 0)
{
string strCode = Convert.ToString(row["Code"]).ToLower();
strCode = strCode.Replace("&", "&");
strCode = strCode.Replace(">", ">");
strCode = strCode.Replace("<", "<");
strCode = strCode.Replace("\"", """);
strCode = strCode.Replace("\\", "\\\\");
strCode = strCode.Replace("'", "\\'");
evt = "javascript:{0}('{1} ','{3}{4}/{2}')".FormatWith(
this._onclick,
strCode,
row["Icon"],
YafForumInfo.ForumClientFileRoot,
YafBoardFolders.Current.Emoticons);
}
else
{
evt = "javascript:void()";
}
html.AppendFormat(
"<li><a tabindex=\"999\" href=\"{2}\"><img src=\"{0}\" alt=\"{1}\" title=\"{1}\" /></a></li>\n",
YafBuildLink.Smiley((string)row["Icon"]),
row["Emoticon"],
evt);
}
html.Append("</ul>");
html.Append("</div>");
this.SmileyResults.Text = html.ToString();
}
#endregion
}
} | chiadem/YET | YetAnotherForum.NET/controls/smileys.ascx.cs | C# | gpl-2.0 | 5,905 |
/*
* Copyright (C) 2002-2015 The DOSBox Team
*
* 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 2 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, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include "dosbox.h"
#include "dos_system.h"
#include "drives.h"
#include "setup.h"
#include "mapper.h"
#include "support.h"
#include "../save_state.h"
bool WildFileCmp(const char * file, const char * wild)
{
char file_name[9];
char file_ext[4];
char wild_name[9];
char wild_ext[4];
const char * find_ext;
Bitu r;
strcpy(file_name," ");
strcpy(file_ext," ");
strcpy(wild_name," ");
strcpy(wild_ext," ");
find_ext=strrchr(file,'.');
if (find_ext) {
Bitu size=(Bitu)(find_ext-file);
if (size>8) size=8;
memcpy(file_name,file,size);
find_ext++;
memcpy(file_ext,find_ext,(strlen(find_ext)>3) ? 3 : strlen(find_ext));
} else {
memcpy(file_name,file,(strlen(file) > 8) ? 8 : strlen(file));
}
upcase(file_name);upcase(file_ext);
find_ext=strrchr(wild,'.');
if (find_ext) {
Bitu size=(Bitu)(find_ext-wild);
if (size>8) size=8;
memcpy(wild_name,wild,size);
find_ext++;
memcpy(wild_ext,find_ext,(strlen(find_ext)>3) ? 3 : strlen(find_ext));
} else {
memcpy(wild_name,wild,(strlen(wild) > 8) ? 8 : strlen(wild));
}
upcase(wild_name);upcase(wild_ext);
/* Names are right do some checking */
r=0;
while (r<8) {
if (wild_name[r]=='*') goto checkext;
if (wild_name[r]!='?' && wild_name[r]!=file_name[r]) return false;
r++;
}
checkext:
r=0;
while (r<3) {
if (wild_ext[r]=='*') return true;
if (wild_ext[r]!='?' && wild_ext[r]!=file_ext[r]) return false;
r++;
}
return true;
}
void Set_Label(char const * const input, char * const output, bool cdrom) {
Bitu togo = 8;
Bitu vnamePos = 0;
Bitu labelPos = 0;
bool point = false;
//spacepadding the filenamepart to include spaces after the terminating zero is more closely to the specs. (not doing this now)
// HELLO\0' '' '
while (togo > 0) {
if (input[vnamePos]==0) break;
if (!point && (input[vnamePos]=='.')) { togo=4; point=true; }
//another mscdex quirk. Label is not always uppercase. (Daggerfall)
output[labelPos] = (cdrom?input[vnamePos]:toupper(input[vnamePos]));
labelPos++; vnamePos++;
togo--;
if ((togo==0) && !point) {
if (input[vnamePos]=='.') vnamePos++;
output[labelPos]='.'; labelPos++; point=true; togo=3;
}
};
output[labelPos]=0;
//Remove trailing dot. except when on cdrom and filename is exactly 8 (9 including the dot) letters. MSCDEX feature/bug (fifa96 cdrom detection)
if((labelPos > 0) && (output[labelPos-1] == '.') && !(cdrom && labelPos ==9))
output[labelPos-1] = 0;
}
DOS_Drive::DOS_Drive() {
curdir[0]=0;
info[0]=0;
}
const char * DOS_Drive::GetInfo(void) {
return info;
}
// static members variables
int DriveManager::currentDrive;
DriveManager::DriveInfo DriveManager::driveInfos[26];
void DriveManager::AppendDisk(int drive, DOS_Drive* disk) {
driveInfos[drive].disks.push_back(disk);
}
void DriveManager::InitializeDrive(int drive) {
currentDrive = drive;
DriveInfo& driveInfo = driveInfos[currentDrive];
if (driveInfo.disks.size() > 0) {
driveInfo.currentDisk = 0;
DOS_Drive* disk = driveInfo.disks[driveInfo.currentDisk];
Drives[currentDrive] = disk;
disk->Activate();
}
}
/*
void DriveManager::CycleDrive(bool pressed) {
if (!pressed) return;
// do one round through all drives or stop at the next drive with multiple disks
int oldDrive = currentDrive;
do {
currentDrive = (currentDrive + 1) % DOS_DRIVES;
int numDisks = driveInfos[currentDrive].disks.size();
if (numDisks > 1) break;
} while (currentDrive != oldDrive);
}
void DriveManager::CycleDisk(bool pressed) {
if (!pressed) return;
int numDisks = driveInfos[currentDrive].disks.size();
if (numDisks > 1) {
// cycle disk
int currentDisk = driveInfos[currentDrive].currentDisk;
DOS_Drive* oldDisk = driveInfos[currentDrive].disks[currentDisk];
currentDisk = (currentDisk + 1) % numDisks;
DOS_Drive* newDisk = driveInfos[currentDrive].disks[currentDisk];
driveInfos[currentDrive].currentDisk = currentDisk;
// copy working directory, acquire system resources and finally switch to next drive
strcpy(newDisk->curdir, oldDisk->curdir);
newDisk->Activate();
Drives[currentDrive] = newDisk;
}
}
*/
void DriveManager::CycleAllDisks(void) {
for (int idrive=0; idrive<2; idrive++) { /* Cycle all DISKS meaning A: and B: */
int numDisks = (int)driveInfos[idrive].disks.size();
if (numDisks > 1) {
// cycle disk
int currentDisk = driveInfos[idrive].currentDisk;
DOS_Drive* oldDisk = driveInfos[idrive].disks[currentDisk];
currentDisk = (currentDisk + 1) % numDisks;
DOS_Drive* newDisk = driveInfos[idrive].disks[currentDisk];
driveInfos[idrive].currentDisk = currentDisk;
// copy working directory, acquire system resources and finally switch to next drive
strcpy(newDisk->curdir, oldDisk->curdir);
newDisk->Activate();
Drives[idrive] = newDisk;
LOG_MSG("Drive %c: disk %d of %d now active", 'A'+idrive, currentDisk+1, numDisks);
}
}
}
void DriveManager::CycleAllCDs(void) {
for (int idrive=2; idrive<DOS_DRIVES; idrive++) { /* Cycle all CDs in C: D: ... Z: */
int numDisks = (int)driveInfos[idrive].disks.size();
if (numDisks > 1) {
// cycle disk
int currentDisk = driveInfos[idrive].currentDisk;
DOS_Drive* oldDisk = driveInfos[idrive].disks[currentDisk];
currentDisk = (currentDisk + 1) % numDisks;
DOS_Drive* newDisk = driveInfos[idrive].disks[currentDisk];
driveInfos[idrive].currentDisk = currentDisk;
// copy working directory, acquire system resources and finally switch to next drive
strcpy(newDisk->curdir, oldDisk->curdir);
newDisk->Activate();
Drives[idrive] = newDisk;
LOG_MSG("Drive %c: disk %d of %d now active", 'A'+idrive, currentDisk+1, numDisks);
}
}
}
int DriveManager::UnmountDrive(int drive) {
int result = 0;
// unmanaged drive
if (driveInfos[drive].disks.size() == 0) {
result = Drives[drive]->UnMount();
} else {
// managed drive
int currentDisk = driveInfos[drive].currentDisk;
result = driveInfos[drive].disks[currentDisk]->UnMount();
// only delete on success, current disk set to NULL because of UnMount
if (result == 0) {
driveInfos[drive].disks[currentDisk] = NULL;
for (int i = 0; i < (int)driveInfos[drive].disks.size(); i++) {
delete driveInfos[drive].disks[i];
}
driveInfos[drive].disks.clear();
}
}
return result;
}
bool int13_extensions_enable = true;
void DriveManager::Init(Section* s) {
Section_prop * section=static_cast<Section_prop *>(s);
int13_extensions_enable = section->Get_bool("int 13 extensions");
// setup driveInfos structure
currentDrive = 0;
for(int i = 0; i < DOS_DRIVES; i++) {
driveInfos[i].currentDisk = 0;
}
// MAPPER_AddHandler(&CycleDisk, MK_f3, MMOD1, "cycledisk", "Cycle Disk");
// MAPPER_AddHandler(&CycleDrive, MK_f3, MMOD2, "cycledrive", "Cycle Drv");
}
void DRIVES_Init(Section* sec) {
DriveManager::Init(sec);
}
char * DOS_Drive::GetBaseDir(void) {
return info + 16;
}
// save state support
void DOS_Drive::SaveState( std::ostream& stream )
{
// - pure data
WRITE_POD( &curdir, curdir );
WRITE_POD( &info, info );
}
void DOS_Drive::LoadState( std::istream& stream )
{
// - pure data
READ_POD( &curdir, curdir );
READ_POD( &info, info );
}
void DriveManager::SaveState( std::ostream& stream )
{
// - pure data
WRITE_POD( ¤tDrive, currentDrive );
}
void DriveManager::LoadState( std::istream& stream )
{
// - pure data
READ_POD( ¤tDrive, currentDrive );
}
void POD_Save_DOS_DriveManager( std::ostream& stream )
{
DriveManager::SaveState(stream);
}
void POD_Load_DOS_DriveManager( std::istream& stream )
{
DriveManager::LoadState(stream);
}
/*
ykhwong svn-daum 2012-05-21
class DriveManager
// - pure data
int currentDrive;
// - system data
static struct DriveInfo {
std::vector<DOS_Drive*> disks;
Bit32u currentDisk;
} driveInfos[DOS_DRIVES];
class DOS_Drive
// - pure data
char curdir[DOS_PATHLENGTH];
char info[256];
*/
| petmac/DOSBox | src/dos/drives.cpp | C++ | gpl-2.0 | 8,709 |
class UsersController < ApplicationController
before_filter :init
before_action :require_login
def index
@users = User.all.where.not(email: current_user.email).order('created_at DESC')
end
def create
@user = User.new(user_params)
if @user.save
@activity = Activity.new({'user_id' => current_user.id, 'activity' => 'Created new user'})
@activity.save
redirect_to :back, notice: "Account Created"
else
redirect_to :back, notice: "Failed to create account"
end
end
def update
@user = User.find(params[:id])
password_salt = current_user.password_salt
pwd = user_params[:current].present? ? BCrypt::Engine.hash_secret(user_params[:current], password_salt) : current_user.password_hash
confirmed = true if pwd == current_user.password_hash
if user_params[:current].present? && !confirmed
redirect_to :back, alert: "Current Password is not valid"
else
name = "#{user_params[:firstname]} #{user_params[:lastname]}"
if @user.update(user_params.except(:firstname, :lastname).merge(name: name))
Activity.new({'user_id' => current_user.id, 'activity' => "Updated a user" }).save
redirect_to :back, alert: "Account Updated"
else
redirect_to :back, alert: @user.errors.full_messages
end
end
end
def destroy
user = User.find(params[:id])
if user.destroy
Activity.new({'user_id' => current_user.id, 'activity' => "Deleted a user" }).save
redirect_to :back
end
end
private
def user_params
params.require(:user).permit(:email, :role, :password, :avatar, :firstname, :lastname, :current)
end
def init
@preferences = Preference.find(1)
end
def require_login
unless session[:user_id].present?
redirect_to root_url
end
end
end
| bl4ckdu5t/vitabiotics | app/controllers/users_controller.rb | Ruby | gpl-2.0 | 1,808 |
<?php
/**
* @file
* @brief sigplus Image Gallery Plus metadata extraction
* @author Levente Hunyadi
* @version 1.3.0
* @remarks Copyright (C) 2009-2010 Levente Hunyadi
* @remarks Licensed under GNU/GPLv3, see http://www.gnu.org/licenses/gpl-3.0.html
* @see http://hunyadi.info.hu/projects/sigplus
*/
/*
* sigplus Image Gallery Plus plug-in for Joomla
* Copyright 2009-2010 Levente Hunyadi
*
* sigplus 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.
*
* sigplus 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/>.
*/
// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );
class SIGPlusIPTCServices {
private static $enveloperecord = array(
0=>'Envelope Record Version',
5=>'Destination',
20=>'File Format',
22=>'File Version',
30=>'Service Identifier',
40=>'Envelope Number',
50=>'Product ID',
60=>'Envelope Priority',
70=>'Date Sent',
80=>'Time Sent',
90=>'Coded Character Set',
100=>'Unique Object Name',
120=>'ARM Identifier',
122=>'ARM Version');
private static $applicationrecord = array(
0=>'Application Record Version',
3=>'Object Type Reference',
4=>'Object Attribute Reference',
5=>'Object Name',
7=>'Edit Status',
8=>'Editorial Update',
10=>'Urgency',
12=>'Subject Reference',
15=>'Category',
20=>'Supplemental Categories',
22=>'Fixture Identifier',
25=>'Keywords',
26=>'Content Location Code',
27=>'Content Location Name',
30=>'Release Date',
35=>'Release Time',
37=>'Expiration Date',
38=>'Expiration Time',
40=>'Special Instructions',
42=>'Action Advised',
45=>'Reference Service',
47=>'Reference Date',
50=>'Reference Number',
55=>'Date Created',
60=>'Time Created',
62=>'Digital Creation Date',
63=>'Digital Creation Time',
65=>'Originating Program',
70=>'Program Version',
75=>'Object Cycle',
80=>'By-line',
85=>'By-line Title',
90=>'City',
92=>'Sub-location',
95=>'Province-State',
100=>'Country-Primary Location Code',
101=>'Country-Primary Location Name',
103=>'Original Transmission Reference',
105=>'Headline',
110=>'Credit',
115=>'Source',
116=>'Copyright Notice',
118=>'Contact',
120=>'Caption-Abstract',
121=>'Local Caption',
122=>'Writer-Editor',
125=>'Rasterized Caption',
130=>'Image Type',
131=>'Image Orientation',
135=>'Language Identifier',
150=>'Audio Type',
151=>'Audio Sampling Rate',
152=>'Audio Sampling Resolution',
153=>'Audio Duration',
154=>'Audio Outcue',
184=>'JobID',
185=>'Master Document ID',
186=>'Short Document ID',
187=>'Unique Document ID',
188=>'Owner ID',
200=>'Object Preview File Format',
201=>'Object Preview File Version',
202=>'Object Preview Data',
221=>'Prefs',
225=>'Classify State',
228=>'Similarity Index',
230=>'Document Notes',
231=>'Document History',
232=>'Exif Camera Info');
private static $fileformats = array(
0=>'No Object Data',
1=>'IPTC-NAA Digital Newsphoto Parameter Record',
2=>'IPTC7901 Recommended Message Format',
3=>'Tagged Image File Format (Adobe/Aldus Image data)',
4=>'Illustrator (Adobe Graphics data)',
5=>'AppleSingle (Apple Computer Inc)',
6=>'NAA 89-3 (ANPA 1312)',
7=>'MacBinary II',
8=>'IPTC Unstructured Character Oriented File Format (UCOFF)',
9=>'United Press International ANPA 1312 variant',
10=>'United Press International Down-Load Message',
11=>'JPEG File Interchange (JFIF)',
12=>'Photo-CD Image-Pac (Eastman Kodak)',
13=>'Bit Mapped Graphics File [.BMP] (Microsoft)',
14=>'Digital Audio File [.WAV] (Microsoft & Creative Labs)',
15=>'Audio plus Moving Video [.AVI] (Microsoft)',
16=>'PC DOS/Windows Executable Files [.COM][.EXE]',
17=>'Compressed Binary File [.ZIP] (PKWare Inc)',
18=>'Audio Interchange File Format AIFF (Apple Computer Inc)',
19=>'RIFF Wave (Microsoft Corporation)',
20=>'Freehand (Macromedia/Aldus)',
21=>'Hypertext Markup Language [.HTML] (The Internet Society)',
22=>'MPEG 2 Audio Layer 2 (Musicom), ISO/IEC',
23=>'MPEG 2 Audio Layer 3, ISO/IEC',
24=>'Portable Document File [.PDF] Adobe',
25=>'News Industry Text Format (NITF)',
26=>'Tape Archive [.TAR]',
27=>'Tidningarnas Telegrambyra NITF version (TTNITF DTD)',
28=>'Ritzaus Bureau NITF version (RBNITF DTD)',
29=>'Corel Draw [.CDR]');
/**
* Canonicalizes the value of a metadata entry to ensure proper display.
*/
private static function canonicalizeMetadataValue($key, $value) {
if (is_array($value)) {
switch (count($value)) {
case 0: return false; // nothing to process
case 1: $value = reset($value); break; // extract the only element from single-entry array
}
}
switch ($key) {
case 'Coded Character Set':
switch ($value) {
case "\x1b%G": $value = 'utf-8'; break;
case "\x1b.A": $value = 'iso-8859-1'; break;
case "\x1b.B": $value = 'iso-8859-2'; break;
case "\x1b.C": $value = 'iso-8859-3'; break;
case "\x1b.D": $value = 'iso-8859-4'; break;
default: $value = 'ascii'; // assume ASCII for unrecognized escape sequences
}
break;
case 'Envelope Record Version':
case 'File Version':
case 'ARM Identifier':
case 'ARM Version':
case 'Application Record Version':
case 'ObjectPreviewFileVersion':
$value = (int) $value;
break;
case 'File Format':
case 'ObjectPreviewFileFormat':
$value = (int) $value;
if (isset(self::$fileformats[$value])) {
$value = self::$fileformats[$value];
}
break;
case 'Image Orientation':
switch ($value) {
case 'L': $value = 'landscape'; break;
case 'P': $value = 'portrait'; break;
case 'S': $value = 'square'; break;
}
break;
}
return $value;
}
/**
* Map keys from PHP function @c iptcparse.
*/
private static function mapMetadataKeys($array) {
$metadata = array();
if ($array === false) {
return $metadata;
}
foreach ($array as $key => $value) {
@list($recordid, $tagid) = explode('#', $key, 2); // key = record number + # + tag ID
$recordid = (int) $recordid;
$tagid = (int) $tagid;
switch ($recordid) {
case 1: // envelope record
if (isset(self::$enveloperecord[$tagid])) {
$tagname = self::$enveloperecord[$tagid];
$metadata[$tagname] = self::canonicalizeMetadataValue($tagname, $value);
}
break;
case 2: // application record
if (isset(self::$applicationrecord[$tagid])) {
$tagname = self::$applicationrecord[$tagid];
$metadata[$tagname] = self::canonicalizeMetadataValue($tagname, $value);
}
break;
}
}
if (!isset($metadata['Coded Character Set'])) { // assume cp1252 (Latin1) if no character set is specified
$charset = 'cp1252';
} else {
$charset = $metadata['Coded Character Set'];
}
if ($charset != 'utf-8') {
foreach ($metadata as $key => &$value) {
$value = iconv($charset, 'utf-8', $value);
}
}
unset($metadata['Envelope Record Version']);
unset($metadata['Coded Character Set']);
unset($metadata['Application Record Version']);
return $metadata;
}
private static function getIptcData($imagefile) {
$info = array();
$size = getimagesize($imagefile, $info);
if ($size !== false && isset($info["APP13"])) {
return self::mapMetadataKeys(iptcparse($info["APP13"]));
} else {
return false;
}
}
private static function getExifData($imagefile) {
if (!function_exists('exif_read_data')) {
return false;
}
if (($exifdata = exif_read_data($imagefile, 'EXIF')) === false) {
return false;
} else {
unset($exifdata['SectionsFound']);
unset($exifdata['Exif_IFD_Pointer']);
unset($exifdata['COMPUTED']);
unset($exifdata['THUMBNAIL']);
return $exifdata;
}
}
/**
* Returns IPTC metadata for an image
*/
public static function getImageMetadata($imagefile) {
$iptcdata = self::getIptcData($imagefile);
if (false) { // whether to include EXIF information in metadata
$exifdata = self::getExifData($imagefile);
} else {
$exifdata = false;
}
if (is_array($iptcdata) && is_array($exifdata)) {
return array_merge($iptcdata, $exifdata);
} elseif (is_array($iptcdata)) {
return $iptcdata;
} elseif (is_array($exifdata)) {
return $exifdata;
} else {
return false;
}
}
} | lucashappy/ibmodels | plugins/content/sigplus/metadata.php | PHP | gpl-2.0 | 8,735 |
package MultiplyStrings;
/**
* Created by gzhou on 6/1/15.
*/
public class Solution {
public static void main(String[] args) {
System.out.println(multiply("123", "20"));
}
public static String multiply(String num1, String num2) {
String n1 = new StringBuilder(num1).reverse().toString();
String n2 = new StringBuilder(num2).reverse().toString();
int[] tmp = new int[n1.length() + n2.length()];
for (int i = 0; i < n1.length(); i++) {
int a = n1.charAt(i) - '0';
for (int j = 0; j < n2.length(); j++) {
int b = n2.charAt(j) - '0';
tmp[i + j] += b * a;
}
}
StringBuilder sb = new StringBuilder();
for (int k = 0; k < tmp.length; k++) {
int d = tmp[k] % 10;
int carry = tmp[k] / 10;
// will insert digit from left most
sb.insert(0, d);
if (k < tmp.length - 1) {
tmp[k + 1] += carry;
}
}
// remove zeros which are created by initialization of 'tmp'
while(sb.length()>0 && sb.charAt(0)=='0'){
sb.deleteCharAt(0);
}
return sb.length()==0? "0" : sb.toString();
}
}
| hyattgra/leetcode | MultiplyStrings/Solution.java | Java | gpl-2.0 | 1,253 |
#
# bootloader_advanced.py: gui advanced bootloader configuration dialog
#
# Jeremy Katz <katzj@redhat.com>
#
# Copyright 2001-2002 Red Hat, Inc.
#
# This software may be freely redistributed under the terms of the GNU
# library public license.
#
# You should have received a copy of the GNU Library Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#
import gtk
import gobject
import iutil
import partedUtils
import gui
from iw_gui import *
from rhpl.translate import _, N_
from bootlocwidget import BootloaderLocationWidget
class AdvancedBootloaderWindow(InstallWindow):
windowTitle = N_("Advanced Boot Loader Configuration")
def __init__(self, ics):
InstallWindow.__init__(self, ics)
self.parent = ics.getICW().window
def getPrev(self):
pass
def getNext(self):
# forcing lba32 can be a bad idea.. make sure they really want to
if (self.forceLBA.get_active() and not self.bl.forceLBA32):
rc = self.intf.messageWindow(_("Warning"),
_("Forcing the use of LBA32 for your bootloader when "
"not supported by the BIOS can cause your machine "
"to be unable to boot.\n\n"
"Would you like to continue and force LBA32 mode?"),
type = "custom",
custom_buttons = [_("Cancel"),
_("Force LBA32")])
if rc != 1:
raise gui.StayOnScreen
# set forcelba
self.bl.setForceLBA(self.forceLBA.get_active())
# set kernel args
self.bl.args.set(self.appendEntry.get_text())
# set the boot device
self.bl.setDevice(self.blloc.getBootDevice())
# set the drive order
self.bl.drivelist = self.blloc.getDriveOrder()
# set up the vbox with force lba32 and kernel append
def setupOptionsVbox(self):
self.options_vbox = gtk.VBox(False, 5)
self.options_vbox.set_border_width(5)
self.forceLBA = gtk.CheckButton(_("_Force LBA32 (not normally required)"))
self.options_vbox.pack_start(self.forceLBA, False)
self.forceLBA.set_active(self.bl.forceLBA32)
label = gui.WrappingLabel(_("If you wish to add default options to the "
"boot command, enter them into "
"the 'General kernel parameters' field."))
label.set_alignment(0.0, 0.0)
self.options_vbox.pack_start(label, False)
label = gui.MnemonicLabel(_("_General kernel parameters"))
self.appendEntry = gtk.Entry()
label.set_mnemonic_widget(self.appendEntry)
args = self.bl.args.get()
if args:
self.appendEntry.set_text(args)
box = gtk.HBox(False, 0)
box.pack_start(label)
box.pack_start(self.appendEntry)
al = gtk.Alignment(0.0, 0.0)
al.add(box)
self.options_vbox.pack_start(al, False)
def getScreen(self, anaconda):
self.dispatch = anaconda.dispatch
self.bl = anaconda.id.bootloader
self.intf = anaconda.intf
thebox = gtk.VBox (False, 10)
# boot loader location bits (mbr vs boot, drive order)
self.blloc = BootloaderLocationWidget(anaconda, self.parent)
thebox.pack_start(self.blloc.getWidget(), False)
thebox.pack_start (gtk.HSeparator(), False)
# some optional things
self.setupOptionsVbox()
thebox.pack_start(self.options_vbox, False)
return thebox
| sergey-senozhatsky/anaconda-11-vlan-support | iw/bootloader_advanced_gui.py | Python | gpl-2.0 | 3,639 |
import Backbone from 'backbone';
export default class Router extends Backbone.Router {
get routes() {
return {
'(/)': 'home',
'login': 'login',
'access_token=*token': 'token',
'activity': 'activity',
'swim': 'swim',
'sleep': 'sleep',
'about': 'about',
'privacy': 'privacy'
};
}
}
| clementprdhomme/misfit-dashboard | src/js/router.js | JavaScript | gpl-2.0 | 443 |
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using TournamentMaker.BO;
using TournamentMaker.DAL.Interfaces;
namespace TournamentMaker.BP.Tests
{
[TestClass]
public class MatchBPTests
{
private readonly Mock<IMatchStore> _matchStoreMock;
private readonly Mock<IPlayerStore> _playerStoreMock;
private readonly Mock<ITeamStore> _teamStoreMock;
private readonly Mock<ISportStore> _sportStoreMock;
public MatchBPTests()
{
_matchStoreMock = new Mock<IMatchStore>(MockBehavior.Strict);
_playerStoreMock = new Mock<IPlayerStore>(MockBehavior.Strict);
_teamStoreMock = new Mock<ITeamStore>(MockBehavior.Strict);
_sportStoreMock = new Mock<ISportStore>(MockBehavior.Strict);
}
[TestMethod]
public async Task Close2PlayersTest()
{
var matchBP = new MatchBP(_matchStoreMock.Object, _playerStoreMock.Object, _teamStoreMock.Object, _sportStoreMock.Object);
var rank1 = new Rank { Level = 1000, SportKey = "sport" };
var rank2 = new Rank { Level = 1000, SportKey = "sport" };
var match = new BO.Match
{
Id = 1,
CreatorId = "creator",
SportKey = "sport",
Scores = "1-2;3-1;3-2",
Teams = new List<Team>
{
new Team {Players = new List<Player> {new Player {Matricule = "S123456", Ranks = new Collection<Rank> {rank1}}}, Id = 1},
new Team {Players = new List<Player> {new Player {Matricule = "S123457", Ranks = new Collection<Rank> {rank2}}}, Id = 2}
}
};
_matchStoreMock.Setup(m => m.GetWithPlayersAndRanks(1)).ReturnsAsync(match);
_matchStoreMock.Setup(m => m.SaveChangesAsync()).Returns(() => Task.FromResult(default(Task)));
var result = await matchBP.Close(match, "creator");
_matchStoreMock.VerifyAll();
Assert.AreEqual(match, result);
Assert.AreEqual(rank1.Level, 1007);
Assert.AreEqual(rank2.Level, 993);
}
[TestMethod]
public async Task Close2PlayersDrawTest()
{
var matchBP = new MatchBP(_matchStoreMock.Object, _playerStoreMock.Object, _teamStoreMock.Object, _sportStoreMock.Object);
var rank1 = new Rank {Level = 1000, SportKey = "sport"};
var rank2 = new Rank {Level = 1000, SportKey = "sport"};
var match = new BO.Match
{
Id = 1,
CreatorId = "creator",
SportKey = "sport",
Scores = "1-2;1-1;2-1",
Teams = new List<Team>
{
new Team {Players = new List<Player> {new Player {Matricule = "S123456", Ranks = new Collection<Rank> {rank1}}}, Id = 1},
new Team {Players = new List<Player> {new Player {Matricule = "S123457", Ranks = new Collection<Rank> {rank2}}}, Id = 2}
}
};
_matchStoreMock.Setup(m => m.GetWithPlayersAndRanks(1)).ReturnsAsync(match);
_matchStoreMock.Setup(m => m.SaveChangesAsync()).Returns(() => Task.FromResult(default(Task)));
var result = await matchBP.Close(match,"creator");
_matchStoreMock.VerifyAll();
Assert.AreEqual(match, result);
Assert.AreEqual(rank1.Level, 1000);
Assert.AreEqual(rank2.Level, 1000);
}
[TestMethod]
public async Task Close2PlayersDrawTest2()
{
var matchBP = new MatchBP(_matchStoreMock.Object, _playerStoreMock.Object, _teamStoreMock.Object, _sportStoreMock.Object);
var rank1 = new Rank { Level = 1800, SportKey = "sport", };
var rank2 = new Rank { Level = 2005, SportKey = "sport" };
var match = new BO.Match
{
Id = 1,
CreatorId = "creator",
SportKey = "sport",
Scores = "1-2;1-1;2-1",
Teams = new List<Team>
{
new Team {Players = new List<Player> {new Player {Parties = 31, Matricule = "S123456", Ranks = new Collection<Rank> {rank1}}}, Id = 1},
new Team {Players = new List<Player> {new Player {Parties = 31, Matricule = "S123457", Ranks = new Collection<Rank> {rank2}}}, Id = 2}
}
};
_matchStoreMock.Setup(m => m.GetWithPlayersAndRanks(1)).ReturnsAsync(match);
_matchStoreMock.Setup(m => m.SaveChangesAsync()).Returns(() => Task.FromResult(default(Task)));
var result = await matchBP.Close(match,"creator");
_matchStoreMock.VerifyAll();
Assert.AreEqual(match, result);
Assert.AreEqual(1804, rank1.Level);
Assert.AreEqual(2001, rank2.Level);
}
}
} | ideesdumidi/TournamentMaker | TournamentMaker.BP.Tests/MatchBPTests.cs | C# | gpl-2.0 | 5,067 |
// Copyright (C) 1999,2000 Bruce Guenter <bruceg@em.ca>
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#include <config.h>
#include "response.h"
mystring response::codestr() const
{
static const mystring errstr = "ERROR";
static const mystring econnstr = "ECONN";
static const mystring badstr = "BAD";
static const mystring okstr = "OK";
static const mystring unknownstr = "???";
switch(code) {
case err: return errstr;
case econn: return econnstr;
case bad: return badstr;
case ok: return okstr;
default: return unknownstr;
}
}
mystring response::message() const
{
return codestr() + ": " + msg;
}
| hetznerZApackages/vmailmgr | lib/misc/response_message.cc | C++ | gpl-2.0 | 1,297 |
<?php
/**
* Created by PhpStorm.
* User: Tu TV
* Date: 14/10/2015
* Time: 1:12 AM
*/
require_once 'unirest/Unirest.php';
/**
* Get content from url via unirest.io
*
* @param $url
*
* @return mixed
*/
function fries_file_get_contents( $url ) {
$obj_unirest = Unirest\Request::get( $url, null, null );
$content = $obj_unirest->raw_body;
return $content;
} | fries-uet/maps-service | laravel/app/Library/Maps/helpers/file-get-contents/file-get-contents.php | PHP | gpl-2.0 | 374 |
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title><?php wp_title('', true, 'right'); ?> <?php bloginfo('name'); ?></title>
<link rel="pingback" href="<?php bloginfo('pingback_url'); ?>" />
<link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); ?>" type="text/css" media="screen" />
<?php wp_head(); ?>
<!--[if lte IE 9]><link rel="stylesheet" type="text/css" media="all" href="<?php bloginfo('template_directory');?>/css/ie.css" /><![endif]-->
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery.fn.cleardefault = function() {
return this.focus(function() {
if( this.value == this.defaultValue ) {
this.value = "";
}
}).blur(function() {
if( !this.value.length ) {
this.value = this.defaultValue;
}
});
};
jQuery(".clearit input, .clearit textarea").cleardefault();
});
</script>
</head>
<body<?php if(is_front_page()) {echo ' class="inner-page"';} ?>>
<!--[if lt IE 7]><p class=chromeframe>Your browser is <em>ancient!</em> <a href="http://browsehappy.com/">Upgrade to a different browser</a> or <a href="http://www.google.com/chromeframe/?redirect=true">install Google Chrome Frame</a> to experience this site.</p><![endif]-->
<div class="wrapper">
<header>
<div class="holder">
<strong class="ipad-icon"><a href="http://angel.co/wtf">Coming soon to iPad and iPhone</a></strong>
<strong class="logo"><a href="<?php bloginfo('url'); ?>"><?php bloginfo('name'); ?></a></strong>
</div>
</header><!-- / header -->
<div id="main">
| natemcguire/wtf | wp-content/themes/wtf/header-inner.php | PHP | gpl-2.0 | 1,904 |
/*
* Copyright (c) 2013, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.graal.nodes.calc;
import java.nio.*;
import com.oracle.graal.api.meta.*;
import com.oracle.graal.compiler.common.type.*;
import com.oracle.graal.graph.*;
import com.oracle.graal.graph.spi.*;
import com.oracle.graal.lir.gen.*;
import com.oracle.graal.nodeinfo.*;
import com.oracle.graal.nodes.*;
import com.oracle.graal.nodes.spi.*;
/**
* The {@code ReinterpretNode} class represents a reinterpreting conversion that changes the stamp
* of a primitive value to some other incompatible stamp. The new stamp must have the same width as
* the old stamp.
*/
@NodeInfo
public final class ReinterpretNode extends UnaryNode implements ArithmeticLIRLowerable {
public static final NodeClass<ReinterpretNode> TYPE = NodeClass.create(ReinterpretNode.class);
public ReinterpretNode(Kind to, ValueNode value) {
this(StampFactory.forKind(to), value);
}
public ReinterpretNode(Stamp to, ValueNode value) {
super(TYPE, to, value);
assert to instanceof ArithmeticStamp;
}
private SerializableConstant evalConst(SerializableConstant c) {
/*
* We don't care about byte order here. Either would produce the correct result.
*/
ByteBuffer buffer = ByteBuffer.wrap(new byte[c.getSerializedSize()]).order(ByteOrder.nativeOrder());
c.serialize(buffer);
buffer.rewind();
SerializableConstant ret = ((ArithmeticStamp) stamp()).deserialize(buffer);
assert !buffer.hasRemaining();
return ret;
}
@Override
public ValueNode canonical(CanonicalizerTool tool, ValueNode forValue) {
if (forValue.isConstant()) {
return ConstantNode.forConstant(stamp(), evalConst((SerializableConstant) forValue.asConstant()), null);
}
if (stamp().isCompatible(forValue.stamp())) {
return forValue;
}
if (forValue instanceof ReinterpretNode) {
ReinterpretNode reinterpret = (ReinterpretNode) forValue;
return new ReinterpretNode(stamp(), reinterpret.getValue());
}
return this;
}
@Override
public void generate(NodeMappableLIRBuilder builder, ArithmeticLIRGenerator gen) {
LIRKind kind = gen.getLIRKind(stamp());
builder.setResult(this, gen.emitReinterpret(kind, builder.operand(getValue())));
}
public static ValueNode reinterpret(Kind toKind, ValueNode value) {
return value.graph().unique(new ReinterpretNode(toKind, value));
}
@NodeIntrinsic
public static native float reinterpret(@ConstantNodeParameter Kind kind, int value);
@NodeIntrinsic
public static native int reinterpret(@ConstantNodeParameter Kind kind, float value);
@NodeIntrinsic
public static native double reinterpret(@ConstantNodeParameter Kind kind, long value);
@NodeIntrinsic
public static native long reinterpret(@ConstantNodeParameter Kind kind, double value);
}
| BunnyWei/truffle-llvmir | graal/com.oracle.graal.nodes/src/com/oracle/graal/nodes/calc/ReinterpretNode.java | Java | gpl-2.0 | 4,000 |
#!/usr/bin/env python
# **********************************************************************
#
# Copyright (c) 2003-2011 ZeroC, Inc. All rights reserved.
#
# This copy of Ice is licensed to you under the terms described in the
# ICE_LICENSE file included in this distribution.
#
# **********************************************************************
import os, sys
path = [ ".", "..", "../..", "../../..", "../../../.." ]
head = os.path.dirname(sys.argv[0])
if len(head) > 0:
path = [os.path.join(head, p) for p in path]
path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ]
if len(path) == 0:
raise "can't find toplevel directory!"
sys.path.append(os.path.join(path[0]))
from scripts import *
dbdir = os.path.join(os.getcwd(), "db")
TestUtil.cleanDbDir(dbdir)
client = os.path.join(os.getcwd(), "client")
if TestUtil.appverifier:
TestUtil.setAppVerifierSettings([client])
clientProc = TestUtil.startClient(client, ' --Freeze.Warn.Rollback=0 "%s"' % os.getcwd())
clientProc.waitTestSuccess()
if TestUtil.appverifier:
TestUtil.appVerifierAfterTestEnd([client])
| joshmoore/zeroc-ice | cpp/test/Freeze/dbmap/run.py | Python | gpl-2.0 | 1,137 |
<?php
/**
* HTML helper class
*
* This class was developed to provide some standard HTML functions.
*
* @package VirtueMart
* @subpackage Helpers
* @author RickG
* @copyright Copyright (c) 2004-2008 Soeren Eberhardt-Biermann, 2009 VirtueMart Team. All rights reserved.
*/
// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die();
/**
* HTML Helper
*
* @package VirtueMart
* @subpackage Helpers
* @author RickG
*/
class VmHTML{
/**
* Converts all special chars to html entities
*
* @param string $string
* @param string $quote_style
* @param boolean $only_special_chars Only Convert Some Special Chars ? ( <, >, &, ... )
* @return string
*/
function shopMakeHtmlSafe( $string, $quote_style='ENT_QUOTES', $use_entities=false ) {
if( defined( $quote_style )) {
$quote_style = constant($quote_style);
}
if( $use_entities ) {
$string = @htmlentities( $string, constant($quote_style), self::vmGetCharset() );
} else {
$string = @htmlspecialchars( $string, $quote_style, self::vmGetCharset() );
}
return $string;
}
/**
* Returns the charset string from the global _ISO constant
*
* @return string UTF-8 by default
* @since 1.0.5
*/
function vmGetCharset() {
$iso = explode( '=', @constant('_ISO') );
if( !empty( $iso[1] )) {
return $iso[1];
}
else {
return 'UTF-8';
}
}
/**
* Generate HTML code for a row using VmHTML function
*
* @func string : function to call
* @label string : Text Label
* @args array : arguments
* @return string: HTML code for row table
*/
function row($func,$label){
$VmHTML="VmHTML";
$passedArgs = func_get_args();
array_shift( $passedArgs );//remove function
array_shift( $passedArgs );//remove label
$args = array();
foreach ($passedArgs as $k => $v) {
$args[] = &$passedArgs[$k];
}
$lang =& JFactory::getLanguage();
$label = $lang->hasKey($label.'_TIP') ? '<span class="hasTip" title="'.JText::_($label.'_TIP').'">'.JText::_($label).'</span>' : JText::_($label) ;
$html = '
<tr>
<td class="key">
'.$label.'
</td>
<td>
'.call_user_func_array(array($VmHTML, $func), $args).'
</td>
</tr>';
return $html ;
}
/* simple value display */
function value( $value ){
$lang =& JFactory::getLanguage();
return $lang->hasKey($value) ? JText::_($value) : $value;
}
/* simple raw render */
function raw( $value ){
return $value;
}
/**
* Generate HTML code for a checkbox
*
* @param string Name for the chekcbox
* @param mixed Current value of the checkbox
* @param mixed Value to assign when checkbox is checked
* @param mixed Value to assign when checkbox is not checked
* @return string HTML code for checkbox
*/
function checkbox($name, $value, $checkedValue=1, $uncheckedValue=0, $extraAttribs = '') {
if ($value == $checkedValue) {
$checked = 'checked="checked"';
}
else {
$checked = '';
}
$htmlcode = '<input type="hidden" name="' . $name . '" value="' . $uncheckedValue . '">';
$htmlcode .= '<input '.$extraAttribs.' id="' . $name . '" type="checkbox" name="' . $name . '" value="' . $checkedValue . '" ' . $checked . ' />';
return $htmlcode;
}
/**
* Prints an HTML dropdown box named $name using $arr to
* load the drop down. If $value is in $arr, then $value
* will be the selected option in the dropdown.
* @author gday
* @author soeren
*
* @param string $name The name of the select element
* @param string $value The pre-selected value
* @param array $arr The array containting $key and $val
* @param int $size The size of the select element
* @param string $multiple use "multiple=\"multiple\" to have a multiple choice select list
* @param string $extra More attributes when needed
* @return string HTML drop-down list
*/
function selectList($name, $value, $arrIn, $size=1, $multiple="", $extra="") {
$html = '';
if( empty( $arrIn ) ) {
$arr = array();
} else {
if(!is_array($arrIn)){
$arr=array($arrIn);
} else {
$arr=$arrIn;
}
}
$html = '<select class="inputbox" id="'.$name.'" name="'.$name.'" size="'.$size.'" '.$multiple.' '.$extra.'>';
while (list($key, $val) = each($arr)) {
// foreach ($arr as $key=>$val){
$selected = "";
if( is_array( $value )) {
if( in_array( $key, $value )) {
$selected = 'selected="selected"';
}
}
else {
if(strtolower($value) == strtolower($key) ) {
$selected = 'selected="selected"';
}
}
$html .= '<option value="'.$key.'" '.$selected.'>'.self::shopMakeHtmlSafe($val);
$html .= '</option>';
}
$html .= '</select>';
return $html;
}
// /**
// *
// */
// function selectListParamParser( $arrIn, $tag_name, $tag_attribs, $key, $text, $selected, $required=0 ) {
//// function selectListParamParser($tag_name ,$tag_attribs ,$arrIn , $key, $text, $selected, $required=0 ) {
//
// echo '<br />$tag_name '.$tag_name;
// echo '<br />$tag_attribs '.$tag_attribs;
// echo '<br />$key '.$key;
// echo '<br />$text '.$text;
// echo '<br />$selected '.$selected;
// if(empty($arrIn)){
// return 'Error selectListParamParser no first argument given';
// }
// if(!is_array($arrIn)){
// $arr=array($arrIn);
// } else {
// $arr=$arrIn;
// }
// reset( $arr );
// $html = "\n<select name=\"$tag_name\" id=\"".str_replace('[]', '', $tag_name)."\" $tag_attribs>";
// if(!$required) $html .= "\n\t<option value=\"\">".JText::_('COM_VIRTUEMART_SELECT')."</option>";
// $n=count( $arr );
// for ($i=0; $i < $n; $i++ ) {
//
// $k = stripslashes($arr[$i]->$key);
// $t = stripslashes($arr[$i]->$text);
// $id = isset($arr[$i]->id) ? $arr[$i]->id : null;
//
// $extra = '';
// $extra .= $id ? " id=\"" . $arr[$i]->id . "\"" : '';
// if (is_array( $selected )) {
// foreach ($selected as $obj) {
// $k2 = stripslashes($obj->$key);
// if ($k == $k2) {
// $extra .= " selected=\"selected\"";
// break;
// }
// }
// } else {
// $extra .= ($k == stripslashes($selected) ? " selected=\"selected\"" : '');
// }
// $html .= "\n\t<option value=\"".$k."\"$extra>";
// if( $t[0] == '_' ) $t = substr( $t, 1 );
// $html .= JText::_($t);
// $html .= "</option>";
// }
// $html .= "\n</select>\n";
// return $html;
// }
/**
* Creates a Radio Input List
*
* @param string $name
* @param string $value default value
* @param string $arr
* @param string $extra
* @return string
*/
function radioList($name, $value, &$arr, $extra="") {
$html = '';
if( empty( $arr ) ) {
$arr = array();
}
$html = '';
$i = 0;
foreach($arr as $key => $val) {
$checked = '';
if( is_array( $value )) {
if( in_array( $key, $value )) {
$checked = 'checked="checked"';
}
}
else {
if(strtolower($value) == strtolower($key) ) {
$checked = 'checked="checked"';
}
}
$html .= '<input type="radio" name="'.$name.'" id="'.$name.$i.'" value="'.htmlspecialchars($key, ENT_QUOTES).'" '.$checked.' '.$extra." />\n";
$html .= '<label for="'.$name.$i++.'">'.$val."</label><br />\n";
}
return $html;
}
/**
* Creates radio List
* @param array $radios
* @param string $name
* @param string $default
* @return string
*/
function radio( $name, $radios, $default,$key='value',$text='text') {
return '<fieldset class="radio">'.JHTML::_('select.radiolist', $radios, $name, '', $key, $text, $default).'</fieldset>';
}
/**
* Creating rows with boolean list
*
* @author Patrick Kohl
* @param string $label
* @param string $name
* @param string $value
*
*/
public function booleanlist ( $name, $value,$class='class="inputbox"'){
return '<fieldset class="radio">'.JHTML::_( 'select.booleanlist', $name , $class , $value).'</fieldset>' ;
}
/**
* Creating rows with input fields
*
* @author Patrick Kohl
* @param string $text
* @param string $name
* @param string $value
*/
public function input($name,$value,$class='class="inputbox"',$readonly='',$size='37',$maxlength='255',$more=''){
return '<input type="text" '.$readonly.' '.$class.' id="'.$name.'" name="'.$name.'" size="'.$size.'" maxlength="'.$maxlength.'" value="'.$value.'" />'.$more.'</td>';
}
/**
* Creating rows with input fields
*
* @author Patrick Kohl
* @param string $text
* @param string $name
* @param string $value
*/
public function textarea($name,$value,$class='class="inputbox"',$cols='70',$rows="10"){
return '<textarea '.$class.' id="'.$name.'" name="'.$name.'" cols="'.$cols.'" rows="'.$rows.'"/>'.$value.'</textarea ></td>';
}
/**
* render editor code
*
* @author Patrick Kohl
* @param string $text
* @param string $name
* @param string $value
*/
public function editor($name,$value,$size='100%',$height='300',$hide = array('pagebreak', 'readmore')){
$editor =& JFactory::getEditor();
return $editor->display($name, $value, $size, $height, null, null ,$hide ) ;
}
/**
*
* @author Patrick Kohl
* @param array $options( value & text)
* @param string $name option name
* @param string $defaut defaut value
* @param string $key option value
* @param string $text option text
* @param boolean $zero add a '0' value in the option
* return a select list
*/
public function select($name, $options, $default = '0',$attrib = "onchange='submit();'",$key ='value' ,$text ='text', $zero=true){
if ($zero==true) {
$option = array($key =>"0", $text => JText::_('COM_VIRTUEMART_LIST_EMPTY_OPTION'));
$options = array_merge(array($option), $options);
}
return JHTML::_('select.genericlist', $options,$name,$attrib,$key,$text,$default,false,true);
}
/**
* renders the hidden input
* @author Max Milbers
*/
public function inputHidden($values){
$html='';
foreach($values as $k=>$v){
$html .= '<input type="hidden" name="'.$k.'" value="'.$v.'" />';
}
return $html;
} /**
* renders the Edit Form hidden default input
* @author Patrick Kohl
*/
public function HiddenEdit($controller=0, $task=''){
if (!$controller) $controller = JRequest::getCmd('view');
return '
<input type="hidden" name="task" value="'.$task.'" />
<input type="hidden" name="option" value="com_virtuemart" />
<input type="hidden" name="boxchecked" value="0" />
<input type="hidden" name="controller" value="'.$controller.'" />
'. JHTML::_( 'form.token' ) ;
}
/**
* @author Patrick Kohl
* @var $type type of regular Expression to validate
* $type can be I integer, F Float, A date, M, time, T text, L link, U url, P phone
*@bool $required field is required
*@Int $min minimum of char
*@Int $max max of char
*@var $match original ID field to compare with this such as Email, passsword
*@ Return $html class for validate javascript
**/
public function validate($type='',$required=true, $min=null,$max=null,$match=null) {
if ($required) $validTxt = 'required';
else $validTxt = 'optional';
if (isset($min)) $validTxt .= ',minSize['.$min.']';
if (isset($max)) $validTxt .= ',maxSize['.$max.']';
static $validateID=0 ;
$validateID++;
if ($type=='S' ) return 'id="validate'.$validateID.'" class="validate[required,minSize[2],maxSize[255]]"';
$validate = array ( 'I'=>'onlyNumberSp', 'F'=>'number','D'=>'dateTime','A'=>'date','M'=>'time','T'=>'Text','L'=>'link','U'=>'url','P'=>'phone');
if (isset ($validate[$type])) $validTxt .= ',custom['.$validate[$type].']';
$html ='id="validate'.$validateID.'" class="validate['.$validTxt.']"';
return $html ;
}
} | kenbabu/emproj | administrator/components/com_virtuemart/helpers/html.php | PHP | gpl-2.0 | 12,034 |
#!/usr/bin/python
import os
import sys
import re
# file name unified by the following rule:
# 1. always save the osm under ../osmFiles directory
# 2. the result automatically generate to ../trajectorySets
# 3.1. change variable "osmName", or
# 3.2. use command argument to specify osm file name
# 4. this script generates a set of paths, each includes a series of of points,
# and save in originOfLife folder for further parsing.
# also, please scroll down the very bottom to see what's the next step
osmName = 'San_Jose_20x20.osm' # sample: 'ucla.osm'
#osmName = 'Los_Angeles_20x20.osm' # sample: 'ucla.osm'
#osmName = 'ucla_5x5.osm' # sample: 'ucla.osm'
optionAllowLoop = False # most of the cases are building bounding boxes
# support system parameters
if len(sys.argv) >= 2:
osmName = sys.argv[1]
if len(sys.argv) >= 3:
optionAllowLoop = (sys.argv[2] == '1')
inFile = '../../../Data/osmFiles/' + osmName
if len(osmName.split('.')) == 1:
osmNameWoExt = osmName
else:
osmNameWoExt = osmName[:-(1+len(osmName.split('.')[-1]))]
outRootDir = '../../../Data/trajectorySets/'
outFile = outRootDir + osmNameWoExt + '.tfix'
print('input file = ' + inFile)
print('output file = ' + outFile)
print('')
f = open('/tmp/in', 'w')
f.write('<in>' + inFile + '</in>');
f.close()
# the following command can be slow. a 3x3 mile^2 area takes 53 seconds to generate the result.
xmlWayDetail = outRootDir + 'originOfLife/' + osmNameWoExt + '.xml'
cmd = 'basex findWayTrajectory.xq > ' + xmlWayDetail
print('CMD: ' + cmd)
if os.path.isfile(xmlWayDetail):
print('File existed. Skip.')
else:
os.system(cmd)
# the next step should be executing the python3 ../makeElevSegMap.py with the input
# parameter outFile, but because of the relative folder path issue, integrating
# makeElevSegMap.py into this code needs to make big changes. So at this stage,
# we still stay on manually executing that script.
| nesl/mercury | Services/Mapping/fixProgram/script.py | Python | gpl-2.0 | 1,925 |
package com.cf.tradeprocessor.web.rest.response;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
public class JsonResponse {
private Boolean success;
@JsonInclude(Include.NON_NULL)
private Object result;
public JsonResponse() {
}
private JsonResponse(Boolean success, Object result) {
this.success = success;
this.result = result;
}
public static JsonResponse success(Object result) {
return new JsonResponse(true, result);
}
public static JsonResponse success() {
return success(null);
}
public static JsonResponse error(String message) {
return new JsonResponse(false, message);
}
public static JsonResponse error() {
return error(null);
}
public Boolean getSuccess() {
return success;
}
public Object getResult() {
return result;
}
}
| camposer/cf | trade-processor/src/main/java/com/cf/tradeprocessor/web/rest/response/JsonResponse.java | Java | gpl-2.0 | 855 |
/*jslint browser: true */ /*global jQuery: true */
/**
* jQuery Cookie plugin
*
* Copyright (c) 2010 Klaus Hartl (stilbuero.de)
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
*/
// TODO JsDoc
/**
* Create a cookie with the given key and value and other optional parameters.
*
* @example $.cookie('the_cookie', 'the_value');
* @desc Set the value of a cookie.
* @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
* @desc Create a cookie with all available options.
* @example $.cookie('the_cookie', 'the_value');
* @desc Create a session cookie.
* @example $.cookie('the_cookie', null);
* @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
* used when the cookie was set.
*
* @param String key The key of the cookie.
* @param String value The value of the cookie.
* @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
* @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
* If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
* If set to null or omitted, the cookie will be a session cookie and will not be retained
* when the the browser exits.
* @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
* @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
* @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
* require a secure protocol (like HTTPS).
* @type undefined
*
* @name $.cookie
* @cat Plugins/Cookie
* @author Klaus Hartl/klaus.hartl@stilbuero.de
*/
/**
* Get the value of a cookie with the given key.
*
* @example $.cookie('the_cookie');
* @desc Get the value of a cookie.
*
* @param String key The key of the cookie.
* @return The value of the cookie.
* @type String
*
* @name $.cookie
* @cat Plugins/Cookie
* @author Klaus Hartl/klaus.hartl@stilbuero.de
*/
jQuery.cookie = function (key, value, options) {
// key and value given, set cookie...
if (arguments.length > 1 && (value === null || typeof value !== "object")) {
options = jQuery.extend({}, options);
if (value === null) {
options.expires = -1;
}
if (typeof options.expires === 'number') {
var days = options.expires, t = options.expires = new Date();
t.setDate(t.getDate() + days);
}
return (document.cookie = [
encodeURIComponent(key), '=',
options.raw ? String(value) : encodeURIComponent(String(value)),
options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
options.path ? '; path=' + options.path : '',
options.domain ? '; domain=' + options.domain : '',
options.secure ? '; secure' : ''
].join(''));
}
// key and possibly options given, get cookie...
options = value || {};
var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};
;
(function ($) {
/**
* This script transforms a set of fieldsets into a stack of vertical
* tabs. Another tab pane can be selected by clicking on the respective
* tab.
*
* Each tab may have a summary which can be updated by another
* script. For that to work, each fieldset has an associated
* 'verticalTabCallback' (with jQuery.data() attached to the fieldset),
* which is called every time the user performs an update to a form
* element inside the tab pane.
*/
Drupal.behaviors.verticalTabs = {
attach: function (context) {
$('.vertical-tabs-panes', context).once('vertical-tabs', function () {
var focusID = $(':hidden.vertical-tabs-active-tab', this).val();
var tab_focus;
// Check if there are some fieldsets that can be converted to vertical-tabs
var $fieldsets = $('> fieldset', this);
if ($fieldsets.length == 0) {
return;
}
// Create the tab column.
var tab_list = $('<ul class="vertical-tabs-list"></ul>');
$(this).wrap('<div class="vertical-tabs clearfix"></div>').before(tab_list);
// Transform each fieldset into a tab.
$fieldsets.each(function () {
var vertical_tab = new Drupal.verticalTab({
title: $('> legend', this).text(),
fieldset: $(this)
});
tab_list.append(vertical_tab.item);
$(this)
.removeClass('collapsible collapsed')
.addClass('vertical-tabs-pane')
.data('verticalTab', vertical_tab);
if (this.id == focusID) {
tab_focus = $(this);
}
});
$('> li:first', tab_list).addClass('first');
$('> li:last', tab_list).addClass('last');
if (!tab_focus) {
// If the current URL has a fragment and one of the tabs contains an
// element that matches the URL fragment, activate that tab.
if (window.location.hash && $(this).find(window.location.hash).length) {
tab_focus = $(this).find(window.location.hash).closest('.vertical-tabs-pane');
}
else {
tab_focus = $('> .vertical-tabs-pane:first', this);
}
}
if (tab_focus.length) {
tab_focus.data('verticalTab').focus();
}
});
}
};
/**
* The vertical tab object represents a single tab within a tab group.
*
* @param settings
* An object with the following keys:
* - title: The name of the tab.
* - fieldset: The jQuery object of the fieldset that is the tab pane.
*/
Drupal.verticalTab = function (settings) {
var self = this;
$.extend(this, settings, Drupal.theme('verticalTab', settings));
this.link.click(function () {
self.focus();
return false;
});
// Keyboard events added:
// Pressing the Enter key will open the tab pane.
this.link.keydown(function(event) {
if (event.keyCode == 13) {
self.focus();
// Set focus on the first input field of the visible fieldset/tab pane.
$("fieldset.vertical-tabs-pane :input:visible:enabled:first").focus();
return false;
}
});
this.fieldset
.bind('summaryUpdated', function () {
self.updateSummary();
})
.trigger('summaryUpdated');
};
Drupal.verticalTab.prototype = {
/**
* Displays the tab's content pane.
*/
focus: function () {
this.fieldset
.siblings('fieldset.vertical-tabs-pane')
.each(function () {
var tab = $(this).data('verticalTab');
tab.fieldset.hide();
tab.item.removeClass('selected');
})
.end()
.show()
.siblings(':hidden.vertical-tabs-active-tab')
.val(this.fieldset.attr('id'));
this.item.addClass('selected');
// Mark the active tab for screen readers.
$('#active-vertical-tab').remove();
this.link.append('<span id="active-vertical-tab" class="element-invisible">' + Drupal.t('(active tab)') + '</span>');
},
/**
* Updates the tab's summary.
*/
updateSummary: function () {
this.summary.html(this.fieldset.drupalGetSummary());
},
/**
* Shows a vertical tab pane.
*/
tabShow: function () {
// Display the tab.
this.item.show();
// Update .first marker for items. We need recurse from parent to retain the
// actual DOM element order as jQuery implements sortOrder, but not as public
// method.
this.item.parent().children('.vertical-tab-button').removeClass('first')
.filter(':visible:first').addClass('first');
// Display the fieldset.
this.fieldset.removeClass('vertical-tab-hidden').show();
// Focus this tab.
this.focus();
return this;
},
/**
* Hides a vertical tab pane.
*/
tabHide: function () {
// Hide this tab.
this.item.hide();
// Update .first marker for items. We need recurse from parent to retain the
// actual DOM element order as jQuery implements sortOrder, but not as public
// method.
this.item.parent().children('.vertical-tab-button').removeClass('first')
.filter(':visible:first').addClass('first');
// Hide the fieldset.
this.fieldset.addClass('vertical-tab-hidden').hide();
// Focus the first visible tab (if there is one).
var $firstTab = this.fieldset.siblings('.vertical-tabs-pane:not(.vertical-tab-hidden):first');
if ($firstTab.length) {
$firstTab.data('verticalTab').focus();
}
return this;
}
};
/**
* Theme function for a vertical tab.
*
* @param settings
* An object with the following keys:
* - title: The name of the tab.
* @return
* This function has to return an object with at least these keys:
* - item: The root tab jQuery element
* - link: The anchor tag that acts as the clickable area of the tab
* (jQuery version)
* - summary: The jQuery element that contains the tab summary
*/
Drupal.theme.prototype.verticalTab = function (settings) {
var tab = {};
tab.item = $('<li class="vertical-tab-button" tabindex="-1"></li>')
.append(tab.link = $('<a href="#"></a>')
.append(tab.title = $('<strong></strong>').text(settings.title))
.append(tab.summary = $('<span class="summary"></span>')
)
);
return tab;
};
})(jQuery);
;
(function ($) {
/**
* The base States namespace.
*
* Having the local states variable allows us to use the States namespace
* without having to always declare "Drupal.states".
*/
var states = Drupal.states = {
// An array of functions that should be postponed.
postponed: []
};
/**
* Attaches the states.
*/
Drupal.behaviors.states = {
attach: function (context, settings) {
var $context = $(context);
for (var selector in settings.states) {
for (var state in settings.states[selector]) {
new states.Dependent({
element: $context.find(selector),
state: states.State.sanitize(state),
constraints: settings.states[selector][state]
});
}
}
// Execute all postponed functions now.
while (states.postponed.length) {
(states.postponed.shift())();
}
}
};
/**
* Object representing an element that depends on other elements.
*
* @param args
* Object with the following keys (all of which are required):
* - element: A jQuery object of the dependent element
* - state: A State object describing the state that is dependent
* - constraints: An object with dependency specifications. Lists all elements
* that this element depends on. It can be nested and can contain arbitrary
* AND and OR clauses.
*/
states.Dependent = function (args) {
$.extend(this, { values: {}, oldValue: null }, args);
this.dependees = this.getDependees();
for (var selector in this.dependees) {
this.initializeDependee(selector, this.dependees[selector]);
}
};
/**
* Comparison functions for comparing the value of an element with the
* specification from the dependency settings. If the object type can't be
* found in this list, the === operator is used by default.
*/
states.Dependent.comparisons = {
'RegExp': function (reference, value) {
return reference.test(value);
},
'Function': function (reference, value) {
// The "reference" variable is a comparison function.
return reference(value);
},
'Number': function (reference, value) {
// If "reference" is a number and "value" is a string, then cast reference
// as a string before applying the strict comparison in compare(). Otherwise
// numeric keys in the form's #states array fail to match string values
// returned from jQuery's val().
return (typeof value === 'string') ? compare(reference.toString(), value) : compare(reference, value);
}
};
states.Dependent.prototype = {
/**
* Initializes one of the elements this dependent depends on.
*
* @param selector
* The CSS selector describing the dependee.
* @param dependeeStates
* The list of states that have to be monitored for tracking the
* dependee's compliance status.
*/
initializeDependee: function (selector, dependeeStates) {
var state;
// Cache for the states of this dependee.
this.values[selector] = {};
for (var i in dependeeStates) {
if (dependeeStates.hasOwnProperty(i)) {
state = dependeeStates[i];
// Make sure we're not initializing this selector/state combination twice.
if ($.inArray(state, dependeeStates) === -1) {
continue;
}
state = states.State.sanitize(state);
// Initialize the value of this state.
this.values[selector][state.name] = null;
// Monitor state changes of the specified state for this dependee.
$(selector).bind('state:' + state, $.proxy(function (e) {
this.update(selector, state, e.value);
}, this));
// Make sure the event we just bound ourselves to is actually fired.
new states.Trigger({ selector: selector, state: state });
}
}
},
/**
* Compares a value with a reference value.
*
* @param reference
* The value used for reference.
* @param selector
* CSS selector describing the dependee.
* @param state
* A State object describing the dependee's updated state.
*
* @return
* true or false.
*/
compare: function (reference, selector, state) {
var value = this.values[selector][state.name];
if (reference.constructor.name in states.Dependent.comparisons) {
// Use a custom compare function for certain reference value types.
return states.Dependent.comparisons[reference.constructor.name](reference, value);
}
else {
// Do a plain comparison otherwise.
return compare(reference, value);
}
},
/**
* Update the value of a dependee's state.
*
* @param selector
* CSS selector describing the dependee.
* @param state
* A State object describing the dependee's updated state.
* @param value
* The new value for the dependee's updated state.
*/
update: function (selector, state, value) {
// Only act when the 'new' value is actually new.
if (value !== this.values[selector][state.name]) {
this.values[selector][state.name] = value;
this.reevaluate();
}
},
/**
* Triggers change events in case a state changed.
*/
reevaluate: function () {
// Check whether any constraint for this dependent state is satisifed.
var value = this.verifyConstraints(this.constraints);
// Only invoke a state change event when the value actually changed.
if (value !== this.oldValue) {
// Store the new value so that we can compare later whether the value
// actually changed.
this.oldValue = value;
// Normalize the value to match the normalized state name.
value = invert(value, this.state.invert);
// By adding "trigger: true", we ensure that state changes don't go into
// infinite loops.
this.element.trigger({ type: 'state:' + this.state, value: value, trigger: true });
}
},
/**
* Evaluates child constraints to determine if a constraint is satisfied.
*
* @param constraints
* A constraint object or an array of constraints.
* @param selector
* The selector for these constraints. If undefined, there isn't yet a
* selector that these constraints apply to. In that case, the keys of the
* object are interpreted as the selector if encountered.
*
* @return
* true or false, depending on whether these constraints are satisfied.
*/
verifyConstraints: function(constraints, selector) {
var result;
if ($.isArray(constraints)) {
// This constraint is an array (OR or XOR).
var hasXor = $.inArray('xor', constraints) === -1;
for (var i = 0, len = constraints.length; i < len; i++) {
if (constraints[i] != 'xor') {
var constraint = this.checkConstraints(constraints[i], selector, i);
// Return if this is OR and we have a satisfied constraint or if this
// is XOR and we have a second satisfied constraint.
if (constraint && (hasXor || result)) {
return hasXor;
}
result = result || constraint;
}
}
}
// Make sure we don't try to iterate over things other than objects. This
// shouldn't normally occur, but in case the condition definition is bogus,
// we don't want to end up with an infinite loop.
else if ($.isPlainObject(constraints)) {
// This constraint is an object (AND).
for (var n in constraints) {
if (constraints.hasOwnProperty(n)) {
result = ternary(result, this.checkConstraints(constraints[n], selector, n));
// False and anything else will evaluate to false, so return when any
// false condition is found.
if (result === false) { return false; }
}
}
}
return result;
},
/**
* Checks whether the value matches the requirements for this constraint.
*
* @param value
* Either the value of a state or an array/object of constraints. In the
* latter case, resolving the constraint continues.
* @param selector
* The selector for this constraint. If undefined, there isn't yet a
* selector that this constraint applies to. In that case, the state key is
* propagates to a selector and resolving continues.
* @param state
* The state to check for this constraint. If undefined, resolving
* continues.
* If both selector and state aren't undefined and valid non-numeric
* strings, a lookup for the actual value of that selector's state is
* performed. This parameter is not a State object but a pristine state
* string.
*
* @return
* true or false, depending on whether this constraint is satisfied.
*/
checkConstraints: function(value, selector, state) {
// Normalize the last parameter. If it's non-numeric, we treat it either as
// a selector (in case there isn't one yet) or as a trigger/state.
if (typeof state !== 'string' || (/[0-9]/).test(state[0])) {
state = null;
}
else if (typeof selector === 'undefined') {
// Propagate the state to the selector when there isn't one yet.
selector = state;
state = null;
}
if (state !== null) {
// constraints is the actual constraints of an element to check for.
state = states.State.sanitize(state);
return invert(this.compare(value, selector, state), state.invert);
}
else {
// Resolve this constraint as an AND/OR operator.
return this.verifyConstraints(value, selector);
}
},
/**
* Gathers information about all required triggers.
*/
getDependees: function() {
var cache = {};
// Swivel the lookup function so that we can record all available selector-
// state combinations for initialization.
var _compare = this.compare;
this.compare = function(reference, selector, state) {
(cache[selector] || (cache[selector] = [])).push(state.name);
// Return nothing (=== undefined) so that the constraint loops are not
// broken.
};
// This call doesn't actually verify anything but uses the resolving
// mechanism to go through the constraints array, trying to look up each
// value. Since we swivelled the compare function, this comparison returns
// undefined and lookup continues until the very end. Instead of lookup up
// the value, we record that combination of selector and state so that we
// can initialize all triggers.
this.verifyConstraints(this.constraints);
// Restore the original function.
this.compare = _compare;
return cache;
}
};
states.Trigger = function (args) {
$.extend(this, args);
if (this.state in states.Trigger.states) {
this.element = $(this.selector);
// Only call the trigger initializer when it wasn't yet attached to this
// element. Otherwise we'd end up with duplicate events.
if (!this.element.data('trigger:' + this.state)) {
this.initialize();
}
}
};
states.Trigger.prototype = {
initialize: function () {
var trigger = states.Trigger.states[this.state];
if (typeof trigger == 'function') {
// We have a custom trigger initialization function.
trigger.call(window, this.element);
}
else {
for (var event in trigger) {
if (trigger.hasOwnProperty(event)) {
this.defaultTrigger(event, trigger[event]);
}
}
}
// Mark this trigger as initialized for this element.
this.element.data('trigger:' + this.state, true);
},
defaultTrigger: function (event, valueFn) {
var oldValue = valueFn.call(this.element);
// Attach the event callback.
this.element.bind(event, $.proxy(function (e) {
var value = valueFn.call(this.element, e);
// Only trigger the event if the value has actually changed.
if (oldValue !== value) {
this.element.trigger({ type: 'state:' + this.state, value: value, oldValue: oldValue });
oldValue = value;
}
}, this));
states.postponed.push($.proxy(function () {
// Trigger the event once for initialization purposes.
this.element.trigger({ type: 'state:' + this.state, value: oldValue, oldValue: null });
}, this));
}
};
/**
* This list of states contains functions that are used to monitor the state
* of an element. Whenever an element depends on the state of another element,
* one of these trigger functions is added to the dependee so that the
* dependent element can be updated.
*/
states.Trigger.states = {
// 'empty' describes the state to be monitored
empty: {
// 'keyup' is the (native DOM) event that we watch for.
'keyup': function () {
// The function associated to that trigger returns the new value for the
// state.
return this.val() == '';
}
},
checked: {
'change': function () {
return this.attr('checked');
}
},
// For radio buttons, only return the value if the radio button is selected.
value: {
'keyup': function () {
// Radio buttons share the same :input[name="key"] selector.
if (this.length > 1) {
// Initial checked value of radios is undefined, so we return false.
return this.filter(':checked').val() || false;
}
return this.val();
},
'change': function () {
// Radio buttons share the same :input[name="key"] selector.
if (this.length > 1) {
// Initial checked value of radios is undefined, so we return false.
return this.filter(':checked').val() || false;
}
return this.val();
}
},
collapsed: {
'collapsed': function(e) {
return (typeof e !== 'undefined' && 'value' in e) ? e.value : this.is('.collapsed');
}
}
};
/**
* A state object is used for describing the state and performing aliasing.
*/
states.State = function(state) {
// We may need the original unresolved name later.
this.pristine = this.name = state;
// Normalize the state name.
while (true) {
// Iteratively remove exclamation marks and invert the value.
while (this.name.charAt(0) == '!') {
this.name = this.name.substring(1);
this.invert = !this.invert;
}
// Replace the state with its normalized name.
if (this.name in states.State.aliases) {
this.name = states.State.aliases[this.name];
}
else {
break;
}
}
};
/**
* Creates a new State object by sanitizing the passed value.
*/
states.State.sanitize = function (state) {
if (state instanceof states.State) {
return state;
}
else {
return new states.State(state);
}
};
/**
* This list of aliases is used to normalize states and associates negated names
* with their respective inverse state.
*/
states.State.aliases = {
'enabled': '!disabled',
'invisible': '!visible',
'invalid': '!valid',
'untouched': '!touched',
'optional': '!required',
'filled': '!empty',
'unchecked': '!checked',
'irrelevant': '!relevant',
'expanded': '!collapsed',
'readwrite': '!readonly'
};
states.State.prototype = {
invert: false,
/**
* Ensures that just using the state object returns the name.
*/
toString: function() {
return this.name;
}
};
/**
* Global state change handlers. These are bound to "document" to cover all
* elements whose state changes. Events sent to elements within the page
* bubble up to these handlers. We use this system so that themes and modules
* can override these state change handlers for particular parts of a page.
*/
$(document).bind('state:disabled', function(e) {
// Only act when this change was triggered by a dependency and not by the
// element monitoring itself.
if (e.trigger) {
$(e.target)
.attr('disabled', e.value)
.closest('.form-item, .form-submit, .form-wrapper').toggleClass('form-disabled', e.value)
.find('select, input, textarea').attr('disabled', e.value);
// Note: WebKit nightlies don't reflect that change correctly.
// See https://bugs.webkit.org/show_bug.cgi?id=23789
}
});
$(document).bind('state:required', function(e) {
if (e.trigger) {
if (e.value) {
$(e.target).closest('.form-item, .form-wrapper').find('label').append('<span class="form-required">*</span>');
}
else {
$(e.target).closest('.form-item, .form-wrapper').find('label .form-required').remove();
}
}
});
$(document).bind('state:visible', function(e) {
if (e.trigger) {
$(e.target).closest('.form-item, .form-submit, .form-wrapper').toggle(e.value);
}
});
$(document).bind('state:checked', function(e) {
if (e.trigger) {
$(e.target).attr('checked', e.value);
}
});
$(document).bind('state:collapsed', function(e) {
if (e.trigger) {
if ($(e.target).is('.collapsed') !== e.value) {
$('> legend a', e.target).click();
}
}
});
/**
* These are helper functions implementing addition "operators" and don't
* implement any logic that is particular to states.
*/
// Bitwise AND with a third undefined state.
function ternary (a, b) {
return typeof a === 'undefined' ? b : (typeof b === 'undefined' ? a : a && b);
}
// Inverts a (if it's not undefined) when invert is true.
function invert (a, invert) {
return (invert && typeof a !== 'undefined') ? !a : a;
}
// Compares two values while ignoring undefined values.
function compare (a, b) {
return (a === b) ? (typeof a === 'undefined' ? a : true) : (typeof a === 'undefined' || typeof b === 'undefined');
}
})(jQuery);
;
(function ($) {
/**
* Retrieves the summary for the first element.
*/
$.fn.drupalGetSummary = function () {
var callback = this.data('summaryCallback');
return (this[0] && callback) ? $.trim(callback(this[0])) : '';
};
/**
* Sets the summary for all matched elements.
*
* @param callback
* Either a function that will be called each time the summary is
* retrieved or a string (which is returned each time).
*/
$.fn.drupalSetSummary = function (callback) {
var self = this;
// To facilitate things, the callback should always be a function. If it's
// not, we wrap it into an anonymous function which just returns the value.
if (typeof callback != 'function') {
var val = callback;
callback = function () { return val; };
}
return this
.data('summaryCallback', callback)
// To prevent duplicate events, the handlers are first removed and then
// (re-)added.
.unbind('formUpdated.summary')
.bind('formUpdated.summary', function () {
self.trigger('summaryUpdated');
})
// The actual summaryUpdated handler doesn't fire when the callback is
// changed, so we have to do this manually.
.trigger('summaryUpdated');
};
/**
* Sends a 'formUpdated' event each time a form element is modified.
*/
Drupal.behaviors.formUpdated = {
attach: function (context) {
// These events are namespaced so that we can remove them later.
var events = 'change.formUpdated click.formUpdated blur.formUpdated keyup.formUpdated';
$(context)
// Since context could be an input element itself, it's added back to
// the jQuery object and filtered again.
.find(':input').andSelf().filter(':input')
// To prevent duplicate events, the handlers are first removed and then
// (re-)added.
.unbind(events).bind(events, function () {
$(this).trigger('formUpdated');
});
}
};
/**
* Prepopulate form fields with information from the visitor cookie.
*/
Drupal.behaviors.fillUserInfoFromCookie = {
attach: function (context, settings) {
$('form.user-info-from-cookie').once('user-info-from-cookie', function () {
var formContext = this;
$.each(['name', 'mail', 'homepage'], function () {
var $element = $('[name=' + this + ']', formContext);
var cookie = $.cookie('Drupal.visitor.' + this);
if ($element.length && cookie) {
$element.val(cookie);
}
});
});
}
};
})(jQuery);
;
| tungcan1501/hdtv | sites/default/files/js/js_FxzL6y_vG1Dd9B-MsolHGVlVoN_lbUIGopU6FCDDV9U.js | JavaScript | gpl-2.0 | 29,612 |
<?php
/**
* Profiler showing execution trace.
*
* 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 2 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, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
* http://www.gnu.org/copyleft/gpl.html
*
* @file
* @ingroup Profiler
*/
/**
* Execution trace
* @todo document methods (?)
* @ingroup Profiler
*/
class ProfilerSimpleTrace extends ProfilerSimple {
var $trace = "Beginning trace: \n";
var $memory = 0;
function profileIn( $functionname ) {
parent::profileIn( $functionname );
$this->trace .= " " . sprintf("%6.1f",$this->memoryDiff()) .
str_repeat( " ", count($this->mWorkStack)) . " > " . $functionname . "\n";
}
function profileOut($functionname) {
global $wgDebugFunctionEntry;
if ( $wgDebugFunctionEntry ) {
$this->debug(str_repeat(' ', count($this->mWorkStack) - 1).'Exiting '.$functionname."\n");
}
list( $ofname, /* $ocount */ , $ortime ) = array_pop( $this->mWorkStack );
if ( !$ofname ) {
$this->trace .= "Profiling error: $functionname\n";
} else {
if ( $functionname == 'close' ) {
$message = "Profile section ended by close(): {$ofname}";
$functionname = $ofname;
$this->trace .= $message . "\n";
}
elseif ( $ofname != $functionname ) {
$this->trace .= "Profiling error: in({$ofname}), out($functionname)";
}
$elapsedreal = $this->getTime() - $ortime;
$this->trace .= sprintf( "%03.6f %6.1f", $elapsedreal, $this->memoryDiff() ) .
str_repeat(" ", count( $this->mWorkStack ) + 1 ) . " < " . $functionname . "\n";
}
}
function memoryDiff() {
$diff = memory_get_usage() - $this->memory;
$this->memory = memory_get_usage();
return $diff / 1024;
}
function logData() {
if ( php_sapi_name() === 'cli' ) {
print "<!-- \n {$this->trace} \n -->";
} elseif ( $this->getContentType() === 'text/html' ) {
print "<!-- \n {$this->trace} \n -->";
} elseif ( $this->getContentType() === 'text/javascript' ) {
print "\n/*\n {$this->trace}\n*/";
} elseif ( $this->getContentType() === 'text/css' ) {
print "\n/*\n {$this->trace}\n*/";
}
}
}
| flamusdiu/mediawiki | includes/profiler/ProfilerSimpleTrace.php | PHP | gpl-2.0 | 2,680 |
# OpenSSL is more stable then ssl
# but OpenSSL is different then ssl, so need a wrapper
import sys
import os
import OpenSSL
SSLError = OpenSSL.SSL.WantReadError
import select
import time
import socket
import logging
ssl_version = ''
class SSLConnection(object):
"""OpenSSL Connection Wrapper"""
def __init__(self, context, sock):
self._context = context
self._sock = sock
self._connection = OpenSSL.SSL.Connection(context, sock)
self._makefile_refs = 0
def __getattr__(self, attr):
if attr not in ('_context', '_sock', '_connection', '_makefile_refs'):
return getattr(self._connection, attr)
def __iowait(self, io_func, *args, **kwargs):
timeout = self._sock.gettimeout() or 0.1
fd = self._sock.fileno()
time_start = time.time()
while True:
try:
return io_func(*args, **kwargs)
except (OpenSSL.SSL.WantReadError, OpenSSL.SSL.WantX509LookupError):
sys.exc_clear()
_, _, errors = select.select([fd], [], [fd], timeout)
if errors:
break
time_now = time.time()
if time_now - time_start > timeout:
break
except OpenSSL.SSL.WantWriteError:
sys.exc_clear()
_, _, errors = select.select([], [fd], [fd], timeout)
if errors:
break
time_now = time.time()
if time_now - time_start > timeout:
break
def accept(self):
sock, addr = self._sock.accept()
client = OpenSSL.SSL.Connection(sock._context, sock)
return client, addr
def do_handshake(self):
self.__iowait(self._connection.do_handshake)
def connect(self, *args, **kwargs):
return self.__iowait(self._connection.connect, *args, **kwargs)
def __send(self, data, flags=0):
try:
return self.__iowait(self._connection.send, data, flags)
except OpenSSL.SSL.SysCallError as e:
if e[0] == -1 and not data:
# errors when writing empty strings are expected and can be ignored
return 0
raise
def __send_memoryview(self, data, flags=0):
if hasattr(data, 'tobytes'):
data = data.tobytes()
return self.__send(data, flags)
send = __send if sys.version_info >= (2, 7, 5) else __send_memoryview
def recv(self, bufsiz, flags=0):
pending = self._connection.pending()
if pending:
return self._connection.recv(min(pending, bufsiz))
try:
return self.__iowait(self._connection.recv, bufsiz, flags)
except OpenSSL.SSL.ZeroReturnError:
return ''
except OpenSSL.SSL.SysCallError as e:
if e[0] == -1 and 'Unexpected EOF' in e[1]:
# errors when reading empty strings are expected and can be ignored
return ''
raise
def read(self, bufsiz, flags=0):
return self.recv(bufsiz, flags)
def write(self, buf, flags=0):
return self.sendall(buf, flags)
def close(self):
if self._makefile_refs < 1:
self._connection = None
if self._sock:
socket.socket.close(self._sock)
else:
self._makefile_refs -= 1
def makefile(self, mode='r', bufsize=-1):
self._makefile_refs += 1
return socket._fileobject(self, mode, bufsize, close=True)
@staticmethod
def context_builder(ca_certs=None, cipher_suites=('ALL:!RC4-SHA:!ECDHE-RSA-RC4-SHA:!ECDHE-RSA-AES128-GCM-SHA256:!AES128-GCM-SHA256',)):
# 'ALL', '!aNULL', '!eNULL'
global ssl_version
if not ssl_version:
if hasattr(OpenSSL.SSL, "TLSv1_2_METHOD"):
ssl_version = "TLSv1_2"
elif hasattr(OpenSSL.SSL, "TLSv1_1_METHOD"):
ssl_version = "TLSv1_1"
elif hasattr(OpenSSL.SSL, "TLSv1_METHOD"):
ssl_version = "TLSv1"
else:
ssl_version = "SSLv23"
if sys.platform == "darwin":
ssl_version = "TLSv1"
logging.info("SSL use version:%s", ssl_version)
protocol_version = getattr(OpenSSL.SSL, '%s_METHOD' % ssl_version)
ssl_context = OpenSSL.SSL.Context(protocol_version)
if ca_certs:
ssl_context.load_verify_locations(os.path.abspath(ca_certs))
ssl_context.set_verify(OpenSSL.SSL.VERIFY_PEER, lambda c, x, e, d, ok: ok)
else:
ssl_context.set_verify(OpenSSL.SSL.VERIFY_NONE, lambda c, x, e, d, ok: ok)
ssl_context.set_cipher_list(':'.join(cipher_suites))
return ssl_context
| lichuan261/wuand | XX-Net/goagent/3.1.49/local/openssl_wrap.py | Python | gpl-2.0 | 4,813 |
<?php
namespace Guzzle\Common\Filter;
/**
* Check if the supplied variable is a string
*
* @author Michael Dowling <michael@guzzlephp.org>
*/
class StringFilter extends AbstractFilter
{
/**
* {@inheritdoc}
*/
protected function filterCommand($command)
{
if (!is_string($command)) {
return 'The supplied value is not a string: ' . gettype($command)
. ' supplied';
}
return true;
}
} | wakeless-net/currinda-wordpress-login | vendor/guzzle/guzzle/src/Guzzle/Common/Filter/StringFilter.php | PHP | gpl-2.0 | 467 |
<?php
return array(
'id' => 'jkreativ_page_fssingle_video',
'types' => array('page'),
'title' => 'Jkreativ Fullscreen Single video',
'priority' => 'high',
'template' => array(
array(
'name' => 'video_type',
'type' => 'select',
'label' => 'Video Type',
'default' => 'youtube',
'items' => array(
array(
'value' => 'youtube',
'label' => 'Youtube',
),
array(
'value' => 'vimeo',
'label' => 'Vimeo',
)
)
),
array(
'type' => 'textbox',
'name' => 'youtube_video',
'label' => 'Youtube Video',
'description' => 'url of your youtube url, ex : http://www.youtube.com/watch?v=9B7UcTBJYCA',
'dependency' => array(
'field' => 'video_type',
'function' => 'jeg_heading_type_youtube',
),
),
array(
'type' => 'textbox',
'name' => 'vimeo_video',
'label' => 'Vimeo Video',
'description' => 'url of your vimeo url, ex : http://vimeo.com/71536276',
'dependency' => array(
'field' => 'video_type',
'function' => 'jeg_heading_type_vimeo',
),
),
array(
'type' => 'toggle',
'name' => 'enable_autoplay',
'label' => 'Enable Video Autoplay'
),
),
); | OpenDoorBrewCo/odbc-wp-prod | wp-content/themes/jkreativ-themes/admin/metabox/page/fssinglevideo.php | PHP | gpl-2.0 | 1,351 |
<?php
chdir('../../');
require_once ('pika-danio.php');
pika_init();
$report_title = 'LSC Interim Case Services';
$report_name = "lsc_interim";
$base_url = pl_settings_get('base_url');
if(!pika_report_authorize($report_name))
{
$main_html = array();
$main_html['base_url'] = $base_url;
$main_html['page_title'] = $report_title;
$main_html['nav'] = "<a href=\"{$base_url}/\">Pika Home</a>
> <a href=\"{$base_url}/reports/\">Reports</a>
> $report_title";
$main_html['content'] = "You are not authorized to run this report";
$buffer = pl_template('templates/default.html', $main_html);
pika_exit($buffer);
}
$report_format = pl_grab_get('report_format');
$close_date_begin = pl_grab_get('close_date_begin');
$close_date_end = pl_grab_get('close_date_end');
$open_on_date = pl_grab_get('open_on_date');
$funding = pl_grab_get('funding');
$office = pl_grab_get('office');
$status = pl_grab_get('status');
$county = pl_grab_get('county');
$gender = pl_grab_get('gender');
$undup = pl_grab_get('undup');
$calendar_year = pl_grab_get('calendar_year');
$clean_calendar_year = mysql_real_escape_string($calendar_year);
$show_sql = pl_grab_get('show_sql');
$menu_undup = pl_menu_get('undup');
if ('csv' == $report_format)
{
require_once ('app/lib/plCsvReportTable.php');
require_once ('app/lib/plCsvReport.php');
$t = new plCsvReport();
}
else
{
require_once ('app/lib/plHtmlReportTable.php');
require_once ('app/lib/plHtmlReport.php');
$t = new plHtmlReport();
}
// run the report
$clb = $clean_calendar_year . "-01-01";
$cle = $clean_calendar_year . "-06-30";
$ood = $clean_calendar_year . "-06-30";
$eth_sql = "SELECT SUBSTRING(LPAD(problem, 2, '0'),1,1) AS category,
SUM(IF(close_code IN ('A', 'B'), 1, 0)) AS 'Cases Closed after Limited Service',
SUM(IF(close_code IN ('F', 'G', 'H', 'IA', 'IB', 'IC', 'K', 'L'), 1, 0)) AS 'Cases Closed after Extended Service',
SUM(IF(ISNULL(close_date) OR close_date > '{$clean_calendar_year}-06-30', 1, 0)) AS 'Cases Remaining Open on June 30'
FROM cases
WHERE status='2'";
// handle the crazy date range selection
$range1 = $range2 = "";
$sql = '';
$safe_clb = mysql_real_escape_string($clb);
$safe_cle = mysql_real_escape_string($cle);
$safe_ood = mysql_real_escape_string($ood);
if ($clb && $cle)
{
//$t->add_parameter('Closed Between', $safe_clb . " - " . $safe_cle);
$range1 = "close_date >= '{$safe_clb}' AND close_date <= '{$safe_cle}'";
}
elseif ($clb)
{
//$t->add_parameter('Closed After', $safe_clb);
$range1 = "close_date >= '{$safe_clb}'";
}
elseif ($cle)
{
//$t->add_parameter('Closed Before', $safe_cle);
$range1 = "close_date <= '{$safe_cle}'";
}
if ($ood)
{
//$t->add_parameter('Open On', $safe_ood);
$range2 = "(open_date <= '{$safe_ood}' AND (close_date IS NULL OR close_date > '{$safe_ood}'))";
}
if ($ood)
{
if ($clb || $cle)
{
$sql .= " AND (($range1) OR $range2)";
}
else
{
$sql .= " AND $range2";
}
}
else
{
if ($clb || $cle)
{
$sql .= " AND $range1";
}
}
// Other filters
$x = pl_process_comma_vals($funding);
if ($x != false)
{
$t->add_parameter('Funding Code(s)',$funding);
$sql .= " AND funding IN $x";
}
$x = pl_process_comma_vals($office);
if ($x != false)
{
$t->add_parameter('Office Code(s)',$office);
$sql .= " AND office IN $x";
}
$x = pl_process_comma_vals($status);
if ($x != false)
{
$t->add_parameter('Case Status Code(s)',$status);
$sql .= " AND status IN $x";
}
$x = pl_process_comma_vals($county);
if ($x != false)
{
$t->add_parameter('Counties',$county);
$sql .= " AND county IN $x";
}
if ($gender)
{
$t->add_parameter('Gender Code',$gender);
$safe_gender = mysql_real_escape_string($gender);
$sql .= " AND gender='{$safe_gender}'";
}
if ($undup == 1 || ($undup == 0 && $undup != ''))
{
$t->add_parameter('Undup Service',pl_array_lookup($undup,$menu_undup));
$safe_undup = mysql_real_escape_string($undup);
$sql .= " AND undup = '{$safe_undup}'";
}
$eth_sql .= $sql . " GROUP BY category";
$t->title = $report_title;
$t->set_table_title("Form G-1: Interim Case Services");
$t->display_row_count(false);
$t->set_header(array('Category','Cases Closed after Limited Service','Cases Closed after Extended Service','Cases Remaining Open on June 30'));
$t->add_parameter('Cases open between', $safe_clb . " - " . $safe_cle);
$t->add_parameter('Status Codes', "2, 5");
$t->add_parameter('Limited Service Closing Codes', 'A, B');
$t->add_parameter('Extended Service Closing Codes', 'F, G, H, IA, IB, IC, K, L');
$t->add_parameter('Funding', $funding);
$total = array();
$total['code'] = "";
$total['category'] = "";
$total["A"] = "0";
$total["B"] = "0";
$total["C"] = "0";
$total["D"] = "0";
$total["total"] = "0";
$result = mysql_query($eth_sql) or trigger_error();
while ($row = mysql_fetch_assoc($result))
{
$t->add_row($row);
$total["A"] += $row["Under 18"];
$total["B"] += $row["18 to 59"];
$total["C"] += $row["60 and Older"];
$total["D"] += $row["No Age Data"];
$total["total"] += $row["Total"];
}
//$t->add_row($total);
if($show_sql)
{
$t->set_sql($eth_sql);
}
// Add the PAI table
$t->add_table();
$t->set_table_title("Form G-1(d): Interim Case Services (PAI)");
$t->display_row_count(false);
$t->set_header(array('Category', 'Cases Closed after Limited Service','Cases Closed after Extended Service','Cases Remaining Open on June 30'));
$pai_sql = "SELECT SUBSTRING(LPAD(problem, 2, '0'),1,1) AS category,
SUM(IF(close_code IN ('A', 'B'), 1, 0)) AS 'Cases Closed after Limited Service',
SUM(IF(close_code IN ('F', 'G', 'H', 'IA', 'IB', 'IC', 'K', 'L'), 1, 0)) AS 'Cases Closed after Extended Service',
SUM(IF(ISNULL(close_date) OR close_date > '{$clean_calendar_year}-06-30', 1, 0)) AS 'Cases Remaining Open on June 30'
FROM cases
WHERE status='5'" . $sql . " GROUP BY category";
$result = mysql_query($pai_sql) or trigger_error();
while ($row = mysql_fetch_assoc($result))
{
$t->add_row($row);
}
//$t->add_row($total);
if($show_sql)
{
$t->set_sql($pai_sql);
}
$t->display();
exit();
?>
| brianlawlor/ocm | blawlor/reports/lsc_interim/report.php | PHP | gpl-2.0 | 6,045 |
<?php
namespace Gh\Gloggiheime\Controller;
use FluidTYPO3\Flux\Controller\AbstractFluxController;
/**
* My custom ContentController to render my package's Content templates.
*
* @package Gloggiheime
* @subpackage Controller
*/
class ContentController extends AbstractFluxController {
/**
* bookingRepository
*
* @var \Gh\Gloggiheime\Domain\Repository\BookingRepository
* @inject
*/
protected $bookingRepository = NULL;
/**
* heimeRepository
*
* @var \Gh\Gloggiheime\Domain\Repository\HeimeRepository
* @inject
*/
protected $heimeRepository = NULL;
public function bookingAction() {
// Fix for stupid Extbase Persistency problems in Repository
$ext_conf = $this->getData();
$heim_id = $ext_conf[settings][flexform][heim_id];
$end_date_months = $ext_conf[settings][flexform][monate];
$heime = $this->heimeRepository->findAll();
$this->view->assign('heime', $heime);
// $bookings = $this->bookingRepository->findAll();
// $this->view->assign('bookings', $bookings);
$query = $this->bookingRepository->createQuery();
$date_start = new \DateTime('-1 month');
// $date_end = new \DateTime('+'.end_date_months.' month');
$query->matching(
$query->greaterThanOrEqual('from_booking', $date_start->format('Y-m-d H:i:s'))
);
debug($query);
$bookings = $query->execute();
$this->view->assign('bookings', $bookings);
$heim = $this->heimeRepository->findByUid($heim_id);
$this->view->assign('selectedheim', $heim);
}
public function preiseAction() {
// print($this);
$heime = $this->heimeRepository->findAll();
$this->view->assign('heime', $heime);
}
public function mapAction() {
$ext_conf = $this->getData();
$heim_id = $ext_conf[settings][flexform][heim_id];
$heimsingle = $this->heimeRepository->findByUid($heim_id);
$this->view->assign('heimsingle', $heimsingle);
// print($this);
$heime = $this->heimeRepository->findAll();
$this->view->assign('heime', $heime);
}
public function detailsAction() {
$ext_conf = $this->getData();
$heim_id = $ext_conf[settings][flexform][heim_id];
$heim = $this->heimeRepository->findByUid($heim_id);
$this->view->assign('heim', $heim);
}
}
?>
| boris85/gloggiheime | Classes/Controller/ContentController.php | PHP | gpl-2.0 | 2,227 |
/* Copyright (C) 2022, Specify Collections Consortium
*
* Specify Collections Consortium, Biodiversity Institute, University of Kansas,
* 1345 Jayhawk Boulevard, Lawrence, Kansas, 66045, USA, support@specifysoftware.org
*
* 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 2
* 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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package edu.ku.brc.specify.datamodel.busrules;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.text.DateFormat;
import java.util.List;
import java.util.Set;
import java.util.Vector;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import edu.ku.brc.af.core.AppContextMgr;
import edu.ku.brc.af.core.db.DBFieldInfo;
import edu.ku.brc.af.core.db.DBTableIdMgr;
import edu.ku.brc.af.core.db.DBTableInfo;
import edu.ku.brc.af.core.expresssearch.QueryAdjusterForDomain;
import edu.ku.brc.af.ui.forms.FormViewObj;
import edu.ku.brc.af.ui.forms.Viewable;
import edu.ku.brc.af.ui.forms.persist.AltViewIFace.CreationMode;
import edu.ku.brc.af.ui.forms.validation.UIValidator;
import edu.ku.brc.af.ui.forms.validation.ValComboBox;
import edu.ku.brc.af.ui.forms.validation.ValComboBoxFromQuery;
import edu.ku.brc.af.ui.forms.validation.ValTextField;
import edu.ku.brc.dbsupport.DataProviderFactory;
import edu.ku.brc.dbsupport.DataProviderSessionIFace;
import edu.ku.brc.dbsupport.DataProviderSessionIFace.QueryIFace;
import edu.ku.brc.specify.config.SpecifyAppContextMgr;
import edu.ku.brc.specify.conversion.BasicSQLUtils;
import edu.ku.brc.specify.datamodel.CollectionMember;
import edu.ku.brc.specify.datamodel.Discipline;
import edu.ku.brc.specify.datamodel.SpTaskSemaphore;
import edu.ku.brc.specify.datamodel.TreeDefIface;
import edu.ku.brc.specify.datamodel.TreeDefItemIface;
import edu.ku.brc.specify.datamodel.TreeDefItemStandardEntry;
import edu.ku.brc.specify.datamodel.Treeable;
import edu.ku.brc.specify.dbsupport.TaskSemaphoreMgr;
import edu.ku.brc.specify.dbsupport.TaskSemaphoreMgr.USER_ACTION;
import edu.ku.brc.specify.dbsupport.TaskSemaphoreMgrCallerIFace;
import edu.ku.brc.specify.dbsupport.TreeDefStatusMgr;
import edu.ku.brc.specify.treeutils.TreeDataService;
import edu.ku.brc.specify.treeutils.TreeDataServiceFactory;
import edu.ku.brc.specify.treeutils.TreeHelper;
import edu.ku.brc.ui.GetSetValueIFace;
import edu.ku.brc.ui.UIRegistry;
/**
* @author rod
*
* (original author was JDS)
*
* @code_status Alpha
*
* Jan 10, 2008
*
* @param <T>
* @param <D>
* @param <I>
*/
public abstract class BaseTreeBusRules<T extends Treeable<T,D,I>,
D extends TreeDefIface<T,D,I>,
I extends TreeDefItemIface<T,D,I>>
extends AttachmentOwnerBaseBusRules
{
public static final boolean ALLOW_CONCURRENT_FORM_ACCESS = true;
public static final long FORM_SAVE_LOCK_MAX_DURATION_IN_MILLIS = 60000;
private static final Logger log = Logger.getLogger(BaseTreeBusRules.class);
private boolean processedRules = false;
/**
* Constructor.
*
* @param dataClasses a var args list of classes that this business rules implementation handles
*/
public BaseTreeBusRules(Class<?>... dataClasses)
{
super(dataClasses);
}
/* (non-Javadoc)
* @see edu.ku.brc.ui.forms.BaseBusRules#initialize(edu.ku.brc.ui.forms.Viewable)
*/
@Override
public void initialize(Viewable viewableArg)
{
super.initialize(viewableArg);
GetSetValueIFace parentField = (GetSetValueIFace)formViewObj.getControlByName("parent");
Component comp = formViewObj.getControlByName("definitionItem");
if (comp instanceof ValComboBox)
{
final ValComboBox rankComboBox = (ValComboBox)comp;
final JCheckBox acceptedCheckBox = (JCheckBox)formViewObj.getControlByName("isAccepted");
Component apComp = formViewObj.getControlByName("acceptedParent");
final ValComboBoxFromQuery acceptedParentWidget = apComp instanceof ValComboBoxFromQuery ?
(ValComboBoxFromQuery )apComp : null;
if (parentField instanceof ValComboBoxFromQuery)
{
final ValComboBoxFromQuery parentCBX = (ValComboBoxFromQuery)parentField;
if (parentCBX != null && rankComboBox != null)
{
parentCBX.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e)
{
if (e == null || !e.getValueIsAdjusting())
{
parentChanged(formViewObj, parentCBX, rankComboBox, acceptedCheckBox, acceptedParentWidget);
}
}
});
rankComboBox.getComboBox().addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e)
{
rankChanged(formViewObj, parentCBX, rankComboBox, acceptedCheckBox, acceptedParentWidget);
}
});
}
}
if (acceptedCheckBox != null && acceptedParentWidget != null)
{
acceptedCheckBox.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent e)
{
if (acceptedCheckBox.isSelected())
{
acceptedParentWidget.setValue(null, null);
acceptedParentWidget.setChanged(true); // This should be done automatically
acceptedParentWidget.setEnabled(false);
}
else
{
acceptedParentWidget.setEnabled(true);
}
}
});
}
}
}
/**
* @return list of foreign key relationships for purposes of checking
* if a record can be deleted.
* The list contains two entries for each relationship. The first entry
* is the related table name. The second is the name of the foreign key field in the related table.
*/
public abstract String[] getRelatedTableAndColumnNames();
/**
* @return list of ass foreign key relationships.
* The list contains two entries for each relationship. The first entry
* is the related table name. The second is the name of the foreign key field in the related table.
*/
public String[] getAllRelatedTableAndColumnNames()
{
return getRelatedTableAndColumnNames();
}
/* (non-Javadoc)
* @see edu.ku.brc.af.ui.forms.BaseBusRules#okToEnableDelete(java.lang.Object)
*/
@SuppressWarnings("unchecked")
@Override
public boolean okToEnableDelete(Object dataObj)
{
// This is a little weak and chessey, but it gets the job done.
// Becase both the Tree and Definition want/need to share Business Rules.
String viewName = formViewObj.getView().getName();
if (StringUtils.contains(viewName, "TreeDef"))
{
final I treeDefItem = (I)dataObj;
if (treeDefItem != null && treeDefItem.getTreeDef() != null)
{
return treeDefItem.getTreeDef().isRequiredLevel(treeDefItem.getRankId());
}
}
return super.okToEnableDelete(dataObj);
}
/**
* @param node
* @return
*/
@SuppressWarnings("unchecked")
public boolean okToDeleteNode(T node)
{
if (node.getDefinition() != null && !node.getDefinition().getNodeNumbersAreUpToDate() && !node.getDefinition().isUploadInProgress())
{
//Scary. If nodes are not up to date, tree rules may not work.
//The application should prevent edits to items/trees whose tree numbers are not up to date except while uploading
//workbenches.
throw new RuntimeException(node.getDefinition().getName() + " has out of date node numbers.");
}
if (node.getDefinition() != null && node.getDefinition().isUploadInProgress())
{
//don't think this will ever get called during an upload/upload-undo, but just in case.
return true;
}
Integer id = node.getTreeId();
if (id == null)
{
return true;
}
String[] relationships = getRelatedTableAndColumnNames();
// if the given node can't be deleted, return false
if (!super.okToDelete(relationships, node.getTreeId()))
{
return false;
}
// now check the children
// get a list of all descendent IDs
DataProviderSessionIFace session = null;
List<Integer> childIDs = null;
try
{
session = DataProviderFactory.getInstance().createSession();
String queryStr = "SELECT n.id FROM " + node.getClass().getName() + " n WHERE n.nodeNumber <= :highChild AND n.nodeNumber > :nodeNum ORDER BY n.rankId DESC";
QueryIFace query = session.createQuery(queryStr, false);
query.setParameter("highChild", node.getHighestChildNodeNumber());
query.setParameter("nodeNum", node.getNodeNumber());
childIDs = (List<Integer>)query.list();
} catch (Exception ex)
{
edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(BaseTreeBusRules.class, ex);
// Error Dialog
ex.printStackTrace();
} finally
{
if (session != null)
{
session.close();
}
}
// if there are no descendent nodes, return true
if (childIDs != null && childIDs.size() == 0)
{
return true;
}
// break the descendent checks up into chunks or queries
// This is an arbitrary number. Trial and error will determine a good value. This determines
// the number of IDs that wind up in the "IN" clause of the query run inside okToDelete().
int chunkSize = 250;
int lastRecordChecked = -1;
boolean childrenDeletable = true;
while (lastRecordChecked + 1 < childIDs.size() && childrenDeletable)
{
int startOfChunk = lastRecordChecked + 1;
int endOfChunk = Math.min(lastRecordChecked+1+chunkSize, childIDs.size());
// grabs selected subset, exclusive of the last index
List<Integer> chunk = childIDs.subList(startOfChunk, endOfChunk);
Integer[] idChunk = chunk.toArray(new Integer[1]);
childrenDeletable = super.okToDelete(relationships, idChunk);
lastRecordChecked = endOfChunk - 1;
}
return childrenDeletable;
}
@Override
protected String getExtraWhereColumns(DBTableInfo tableInfo) {
String result = super.getExtraWhereColumns(tableInfo);
if (CollectionMember.class.isAssignableFrom(tableInfo.getClassObj()))
{
Vector<Object> cols = BasicSQLUtils.querySingleCol("select distinct CollectionID from collection "
+ "where DisciplineID = " + AppContextMgr.getInstance().getClassObject(Discipline.class).getId());
if (cols != null)
{
String colList = "";
for (Object col : cols)
{
if (!"".equals(colList))
{
colList += ",";
}
colList += col;
}
if (!"".equals(colList))
{
result = "((" + result + ") or " + tableInfo.getAbbrev() + ".CollectionMemberID in(" + colList + "))";
}
}
}
return result;
}
@SuppressWarnings("unchecked")
protected void rankChanged(final FormViewObj form,
final ValComboBoxFromQuery parentComboBox,
final ValComboBox rankComboBox,
final JCheckBox acceptedCheckBox,
final ValComboBoxFromQuery acceptedParentWidget)
{
if (form.getAltView().getMode() != CreationMode.EDIT)
{
return;
}
//log.debug("form was validated: calling adjustRankComboBoxModel()");
Object objInForm = form.getDataObj();
//log.debug("form data object = " + objInForm);
if (objInForm == null)
{
return;
}
final T formNode = (T)objInForm;
T parent = null;
if (parentComboBox.getValue() instanceof String)
{
// the data is still in the VIEW mode for some reason
log.debug("Form is in mode (" + form.getAltView().getMode() + ") but the parent data is a String");
parentComboBox.getValue();
parent = formNode.getParent();
}
else
{
parent = (T)parentComboBox.getValue();
}
final T theParent = parent;
I rankObj = (I )rankComboBox.getValue();
final int rank = rankObj == null ? -2 : rankObj.getRankId();
SwingUtilities.invokeLater(new Runnable() {
public void run()
{
boolean canSynonymize = false;
if (canAccessSynonymy(formNode, rank))
{
canSynonymize = formNode.getDefinition() != null && formNode.getDefinition()
.getSynonymizedLevel() <= rank
&& formNode.getDescendantCount() == 0;
}
if (acceptedCheckBox != null && acceptedParentWidget != null)
{
acceptedCheckBox.setEnabled(canSynonymize && theParent != null);
if (acceptedCheckBox.isSelected() && acceptedCheckBox.isEnabled())
{
acceptedParentWidget.setValue(null, null);
acceptedParentWidget.setChanged(true); // This should be done automatically
acceptedParentWidget.setEnabled(false);
}
}
form.getValidator().validateForm();
}
});
}
@SuppressWarnings("unchecked")
protected void parentChanged(final FormViewObj form,
final ValComboBoxFromQuery parentComboBox,
final ValComboBox rankComboBox,
final JCheckBox acceptedCheckBox,
final ValComboBoxFromQuery acceptedParentWidget)
{
if (form.getAltView().getMode() != CreationMode.EDIT)
{
return;
}
//log.debug("form was validated: calling adjustRankComboBoxModel()");
Object objInForm = form.getDataObj();
//log.debug("form data object = " + objInForm);
if (objInForm == null)
{
return;
}
final T formNode = (T)objInForm;
// set the contents of this combobox based on the value chosen as the parent
adjustRankComboBoxModel(parentComboBox, rankComboBox, formNode);
T parent = null;
if (parentComboBox.getValue() instanceof String)
{
// the data is still in the VIEW mode for some reason
log.debug("Form is in mode (" + form.getAltView().getMode() + ") but the parent data is a String");
parentComboBox.getValue();
parent = formNode.getParent();
}
else
{
parent = (T)parentComboBox.getValue();
}
// set the tree def for the object being edited by using the parent node's tree def
// set the parent too??? (lookups for the AcceptedParent QueryComboBox need this)
if (parent != null)
{
formNode.setDefinition(parent.getDefinition());
formNode.setParent(parent);
}
SwingUtilities.invokeLater(new Runnable() {
public void run()
{
boolean rnkEnabled = rankComboBox.getComboBox().getModel().getSize() > 0;
rankComboBox.setEnabled(rnkEnabled);
JLabel label = form.getLabelFor(rankComboBox);
if (label != null)
{
label.setEnabled(rnkEnabled);
}
if (rankComboBox.hasFocus() && !rnkEnabled)
{
parentComboBox.requestFocus();
}
rankChanged(formViewObj, parentComboBox, rankComboBox, acceptedCheckBox, acceptedParentWidget);
form.getValidator().validateForm();
}
});
}
/**
* @param parentField
* @param rankComboBox
* @param nodeInForm
*/
@SuppressWarnings("unchecked")
protected void adjustRankComboBoxModel(final GetSetValueIFace parentField,
final ValComboBox rankComboBox,
final T nodeInForm)
{
log.debug("Adjusting the model for the 'rank' combo box in a tree node form");
if (nodeInForm == null)
{
return;
}
log.debug("nodeInForm = " + nodeInForm.getName());
DefaultComboBoxModel<I> model = (DefaultComboBoxModel<I>)rankComboBox.getModel();
model.removeAllElements();
// this is the highest rank the edited item can possibly be
I topItem = null;
// this is the lowest rank the edited item can possibly be
I bottomItem = null;
Object value = parentField.getValue();
T parent = null;
if (value instanceof String)
{
// this happens when the combobox is in view mode, which means it's really a textfield
// in that case, the parent of the node in the form will do, since the user can't change the parents
parent = nodeInForm.getParent();
}
else
{
parent = (T)parentField.getValue();
}
if (parent == null)
{
return;
}
// grab all the def items from just below the parent's item all the way to the next enforced level
// or to the level of the highest ranked child
topItem = parent.getDefinitionItem().getChild();
log.debug("highest valid tree level: " + topItem);
if (topItem == null)
{
// this only happens if a parent was chosen that cannot have children b/c it is at the
// lowest defined level in the tree
log.warn("Chosen node cannot be a parent node. It is at the lowest defined level of the tree.");
return;
}
// find the child with the highest rank and set that child's def item as the bottom of the range
if (!nodeInForm.getChildren().isEmpty())
{
for (T child: nodeInForm.getChildren())
{
if (bottomItem==null || child.getRankId()>bottomItem.getRankId())
{
bottomItem = child.getDefinitionItem().getParent();
}
}
}
log.debug("lowest valid tree level: " + bottomItem);
I item = topItem;
boolean done = false;
while (!done)
{
model.addElement(item);
if (item.getChild()==null || item.getIsEnforced()==Boolean.TRUE || (bottomItem != null && item.getRankId().intValue()==bottomItem.getRankId().intValue()) )
{
done = true;
}
item = item.getChild();
}
if (nodeInForm.getDefinitionItem() != null)
{
I defItem = nodeInForm.getDefinitionItem();
for (int i = 0; i < model.getSize(); ++i)
{
I modelItem = (I)model.getElementAt(i);
if (modelItem.getRankId().equals(defItem.getRankId()))
{
log.debug("setting rank selected value to " + modelItem);
model.setSelectedItem(modelItem);
}
}
// if (model.getIndexOf(defItem) != -1)
// {
// model.setSelectedItem(defItem);
// }
}
else if (model.getSize() == 1)
{
Object defItem = model.getElementAt(0);
log.debug("setting rank selected value to the only available option: " + defItem);
model.setSelectedItem(defItem);
}
}
/* (non-Javadoc)
* @see edu.ku.brc.ui.forms.BaseBusRules#afterFillForm(java.lang.Object)
*/
@SuppressWarnings("unchecked")
@Override
public void afterFillForm(final Object dataObj)
{
// This is a little weak and cheesey, but it gets the job done.
// Because both the Tree and Definition want/need to share Business Rules.
String viewName = formViewObj.getView().getName();
if (StringUtils.contains(viewName, "TreeDef"))
{
if (formViewObj.getAltView().getMode() != CreationMode.EDIT)
{
// when we're not in edit mode, we don't need to setup any listeners since the user can't change anything
//log.debug("form is not in edit mode: no special listeners will be attached");
return;
}
if (!StringUtils.contains(viewName, "TreeDefItem"))
{
return;
}
final I nodeInForm = (I)formViewObj.getDataObj();
//disable FullName -related fields if TreeDefItem is used by nodes in the tree
//NOTE: Can remove the edit restriction. Tree rebuilds now update fullname fields. Need to add tree rebuild after fullname def edits.
if (nodeInForm != null && nodeInForm.getTreeDef() != null)
{
// boolean canNOTEditFullNameFlds = nodeInForm.hasTreeEntries();
// if (canNOTEditFullNameFlds)
// {
// ValTextField ftCtrl = (ValTextField )formViewObj.getControlByName("textAfter");
// if (ftCtrl != null)
// {
// ftCtrl.setEnabled(false);
// }
// ftCtrl = (ValTextField )formViewObj.getControlByName("textBefore");
// if (ftCtrl != null)
// {
// ftCtrl.setEnabled(false);
// }
// ftCtrl = (ValTextField )formViewObj.getControlByName("fullNameSeparator");
// if (ftCtrl != null)
// {
// ftCtrl.setEnabled(false);
// }
// ValCheckBox ftBox = (ValCheckBox )formViewObj.getControlByName("isInFullName");
// if (ftBox != null)
// {
// ftBox.setEnabled(false);
// }
// }
if (!viewName.endsWith("TreeDefItem"))
{
return;
}
//disabling editing of name and rank for standard levels.
List<TreeDefItemStandardEntry> stds = nodeInForm.getTreeDef().getStandardLevels();
TreeDefItemStandardEntry stdLevel = null;
for (TreeDefItemStandardEntry std : stds)
{
//if (std.getTitle().equals(nodeInForm.getName()) && std.getRank() == nodeInForm.getRankId())
if (std.getRank() == nodeInForm.getRankId())
{
stdLevel = std;
break;
}
}
if (stdLevel != null)
{
ValTextField nameCtrl = (ValTextField )formViewObj.getControlByName("name");
Component rankCtrl = formViewObj.getControlByName("rankId");
if (nameCtrl != null)
{
nameCtrl.setEnabled(false);
}
if (rankCtrl != null)
{
rankCtrl.setEnabled(false);
}
if (nodeInForm.getTreeDef().isRequiredLevel(stdLevel.getRank()))
{
Component enforcedCtrl = formViewObj.getControlByName("isEnforced");
if (enforcedCtrl != null)
{
enforcedCtrl.setEnabled(false);
}
}
}
}
return;
}
final T nodeInForm = (T) formViewObj.getDataObj();
if (formViewObj.getAltView().getMode() != CreationMode.EDIT)
{
if (nodeInForm != null)
{
//XXX this MAY be necessary due to a bug with TextFieldFromPickListTable??
// TextFieldFromPickListTable.setValue() does nothing because of a null adapter member.
Component comp = formViewObj.getControlByName("definitionItem");
if (comp instanceof JTextField)
{
((JTextField )comp).setText(nodeInForm.getDefinitionItem().getName());
}
}
}
else
{
processedRules = false;
GetSetValueIFace parentField = (GetSetValueIFace) formViewObj
.getControlByName("parent");
Component comp = formViewObj.getControlByName("definitionItem");
if (comp instanceof ValComboBox)
{
final ValComboBox rankComboBox = (ValComboBox) comp;
if (parentField instanceof ValComboBoxFromQuery)
{
final ValComboBoxFromQuery parentCBX = (ValComboBoxFromQuery) parentField;
if (parentCBX != null && rankComboBox != null && nodeInForm != null)
{
parentCBX.registerQueryBuilder(new TreeableSearchQueryBuilder(nodeInForm,
rankComboBox, TreeableSearchQueryBuilder.PARENT));
}
}
if (nodeInForm != null && nodeInForm.getDefinitionItem() != null)
{
// log.debug("node in form already has a set rank: forcing a call to
// adjustRankComboBoxModel()");
UIValidator.setIgnoreAllValidation(this, true);
adjustRankComboBoxModel(parentField, rankComboBox, nodeInForm);
UIValidator.setIgnoreAllValidation(this, false);
}
// TODO: the form system MUST require the accepted parent widget to be present if
// the
// isAccepted checkbox is present
final JCheckBox acceptedCheckBox = (JCheckBox) formViewObj
.getControlByName("isAccepted");
final ValComboBoxFromQuery acceptedParentWidget = (ValComboBoxFromQuery) formViewObj
.getControlByName("acceptedParent");
if (canAccessSynonymy(nodeInForm))
{
if (acceptedCheckBox != null
&& acceptedParentWidget != null)
{
if (acceptedCheckBox.isSelected() && nodeInForm != null
&& nodeInForm.getDefinition() != null)
{
// disable if necessary
boolean canSynonymize = nodeInForm.getDefinition()
.getSynonymizedLevel() <= nodeInForm
.getRankId()
&& nodeInForm.getDescendantCount() == 0;
acceptedCheckBox.setEnabled(canSynonymize);
}
acceptedParentWidget.setEnabled(!acceptedCheckBox
.isSelected()
&& acceptedCheckBox.isEnabled());
if (acceptedCheckBox.isSelected())
{
acceptedParentWidget.setValue(null, null);
}
if (nodeInForm != null && acceptedParentWidget != null
&& rankComboBox != null)
{
acceptedParentWidget
.registerQueryBuilder(new TreeableSearchQueryBuilder(
nodeInForm,
rankComboBox,
TreeableSearchQueryBuilder.ACCEPTED_PARENT));
}
}
}
else
{
if (acceptedCheckBox != null)
{
acceptedCheckBox.setEnabled(false);
}
if (acceptedParentWidget != null)
{
acceptedParentWidget.setEnabled(false);
}
}
if (parentField instanceof ValComboBoxFromQuery)
{
parentChanged(formViewObj, (ValComboBoxFromQuery) parentField, rankComboBox,
acceptedCheckBox, acceptedParentWidget);
}
}
}
}
/**
* @param tableInfo
*
* @return Select (i.e. everything before where clause) of sqlTemplate
*/
protected String getSqlSelectTemplate(final DBTableInfo tableInfo)
{
StringBuilder sb = new StringBuilder();
sb.append("select %s1 FROM "); //$NON-NLS-1$
sb.append(tableInfo.getClassName());
sb.append(" as "); //$NON-NLS-1$
sb.append(tableInfo.getAbbrev());
String joinSnipet = QueryAdjusterForDomain.getInstance().getJoinClause(tableInfo, true, null, false); //arg 2: false means SQL
if (joinSnipet != null)
{
sb.append(' ');
sb.append(joinSnipet);
}
sb.append(' ');
return sb.toString();
}
/**
* @param dataObj
*
* return true if acceptedParent and accepted fields should be enabled on data forms.
*/
@SuppressWarnings("unchecked")
protected boolean canAccessSynonymy(final T dataObj)
{
if (dataObj == null)
{
return false; //??
}
if (dataObj.getChildren().size() > 0)
{
return false;
}
TreeDefItemIface<?,?,?> defItem = dataObj.getDefinitionItem();
if (defItem == null)
{
return false; //???
}
TreeDefIface<?,?,?> def = dataObj.getDefinition();
if (def == null)
{
def = ((SpecifyAppContextMgr )AppContextMgr.getInstance()).getTreeDefForClass((Class<? extends Treeable<?,?,?>> )dataObj.getClass());
}
if (!def.isSynonymySupported())
{
return false;
}
return defItem.getRankId() >= def.getSynonymizedLevel();
}
/**
* @param dataObj
* @param rank
* @return true if the rank is synonymizable according to the relevant TreeDefinition
*
* For use when dataObj's rank has not yet been assigned or updated.
*/
@SuppressWarnings("unchecked")
protected boolean canAccessSynonymy(final T dataObj, final int rank)
{
if (dataObj == null)
{
return false; //??
}
if (dataObj.getChildren().size() > 0)
{
return false;
}
TreeDefIface<?,?,?> def = ((SpecifyAppContextMgr )AppContextMgr.getInstance()).getTreeDefForClass((Class<? extends Treeable<?,?,?>> )dataObj.getClass());
if (!def.isSynonymySupported())
{
return false;
}
return rank >= def.getSynonymizedLevel();
}
/**
* Updates the fullname field of any nodes effected by changes to <code>node</code> that are about
* to be saved to the DB.
*
* @param node
* @param session
* @param nameChanged
* @param parentChanged
* @param rankChanged
*/
@SuppressWarnings("unchecked")
protected void updateFullNamesIfNecessary(T node, DataProviderSessionIFace session)
{
if (!(node.getDefinition().getDoNodeNumberUpdates() && node.getDefinition().getNodeNumbersAreUpToDate())) {
return;
}
if (node.getTreeId() == null)
{
// this is a new node
// it shouldn't need updating since we set the fullname at creation time
return;
}
boolean updateNodeFullName = false;
boolean updateDescFullNames = false;
// we need a way to determine if the name changed
// load a fresh copy from the DB and get the values needed for comparison
DataProviderSessionIFace tmpSession = DataProviderFactory.getInstance().createSession();
T fromDB = (T)tmpSession.get(node.getClass(), node.getTreeId());
tmpSession.close();
if (fromDB == null)
{
// this node is new and hasn't yet been flushed to the DB, so we don't need to worry about updating fullnames
//return;
fromDB = node;
}
T origParent = fromDB.getParent();
boolean parentChanged = false;
T currentParent = node.getParent();
if ((currentParent == null && origParent != null) || (currentParent != null && origParent == null))
{
// I can't imagine how this would ever happen, but just in case
parentChanged = true;
}
if (currentParent != null && origParent != null && !currentParent.getTreeId().equals(origParent.getTreeId()))
{
// the parent ID changed
parentChanged = true;
}
boolean higherLevelsIncluded = false;
if (parentChanged)
{
higherLevelsIncluded = higherLevelsIncludedInFullname(node);
higherLevelsIncluded |= higherLevelsIncludedInFullname(fromDB);
}
if (parentChanged && higherLevelsIncluded)
{
updateNodeFullName = true;
updateDescFullNames = true;
}
boolean nameChanged = !(fromDB.getName().equals(node.getName()));
boolean rankChanged = !(fromDB.getRankId().equals(node.getRankId()));
if (rankChanged || nameChanged)
{
updateNodeFullName = true;
if (booleanValue(fromDB.getDefinitionItem().getIsInFullName(), false) == true)
{
updateDescFullNames = true;
}
if (booleanValue(node.getDefinitionItem().getIsInFullName(), false) == true)
{
updateDescFullNames = true;
}
} else if (fromDB == node)
{
updateNodeFullName = true;
}
if (updateNodeFullName)
{
if (updateDescFullNames)
{
// this could take a long time
TreeHelper.fixFullnameForNodeAndDescendants(node);
}
else
{
// this should be really fast
String fullname = TreeHelper.generateFullname(node);
node.setFullName(fullname);
}
}
}
protected boolean higherLevelsIncludedInFullname(T node)
{
boolean higherLevelsIncluded = false;
// this doesn't necessarily mean the fullname has to be changed
// if no higher levels are included in the fullname, then nothing needs updating
// so, let's see if higher levels factor into the fullname
T l = node.getParent();
while (l != null)
{
if ((l.getDefinitionItem().getIsInFullName() != null) &&
(l.getDefinitionItem().getIsInFullName().booleanValue() == true))
{
higherLevelsIncluded = true;
break;
}
l = l.getParent();
}
return higherLevelsIncluded;
}
/* (non-Javadoc)
* @see edu.ku.brc.specify.datamodel.busrules.BaseBusRules#beforeSave(java.lang.Object, edu.ku.brc.dbsupport.DataProviderSessionIFace)
*/
@SuppressWarnings("unchecked")
@Override
public void beforeSave(Object dataObj, DataProviderSessionIFace session)
{
super.beforeSave(dataObj, session);
if (dataObj instanceof Treeable)
{
// NOTE: the instanceof check can't check against 'T' since T isn't a class
// this has a SMALL amount of risk to it
T node = (T)dataObj;
if (!node.getDefinition().getNodeNumbersAreUpToDate() && !node.getDefinition().isUploadInProgress())
{
//Scary. If nodes are not up to date, tree rules may not work (actually this one is OK. (for now)).
//The application should prevent edits to items/trees whose tree numbers are not up to date except while uploading
//workbenches.
throw new RuntimeException(node.getDefinition().getName() + " has out of date node numbers.");
}
// set it's fullname
String fullname = TreeHelper.generateFullname(node);
node.setFullName(fullname);
}
}
/* (non-Javadoc)
* @see edu.ku.brc.specify.datamodel.busrules.BaseBusRules#afterSaveCommit(java.lang.Object)
*/
@SuppressWarnings("unchecked")
@Override
public boolean beforeSaveCommit(final Object dataObj, final DataProviderSessionIFace session) throws Exception
{
// PLEASE NOTE!
// If any changes are made to this check to make sure no one (Like GeologicTimePeriod) is overriding this method
// and make the appropriate changes there also.
if (!super.beforeSaveCommit(dataObj, session))
{
return false;
}
boolean success = true;
// compare the dataObj values to the nodeBeforeSave values to determine if a node was moved or added
if (dataObj instanceof Treeable)
{
// NOTE: the instanceof check can't check against 'T' since T isn't a class
// this has a SMALL amount of risk to it
T node = (T)dataObj;
if (!node.getDefinition().getNodeNumbersAreUpToDate() && !node.getDefinition().isUploadInProgress())
{
//Scary. If nodes are not up to date, tree rules may not work.
//The application should prevent edits to items/trees whose tree numbers are not up to date except while uploading
//workbenches.
throw new RuntimeException(node.getDefinition().getName() + " has out of date node numbers.");
}
// if the node doesn't have any assigned node number, it must be new
boolean added = (node.getNodeNumber() == null);
if (node.getDefinition().getDoNodeNumberUpdates() && node.getDefinition().getNodeNumbersAreUpToDate())
{
log.info("Saved tree node was added. Updating node numbers appropriately.");
TreeDataService<T,D,I> dataServ = TreeDataServiceFactory.createService();
if (added)
{
success = dataServ.updateNodeNumbersAfterNodeAddition(node, session);
}
else
{
success = dataServ.updateNodeNumbersAfterNodeEdit(node, session);
}
}
else
{
node.getDefinition().setNodeNumbersAreUpToDate(false);
}
}
return success;
}
/* (non-Javadoc)
* @see edu.ku.brc.af.ui.forms.BaseBusRules#beforeDeleteCommit(java.lang.Object, edu.ku.brc.dbsupport.DataProviderSessionIFace)
*/
/*
* NOTE: If this method is overridden, freeLocks() MUST be called when result is false
* !!
*
*/
@Override
public boolean beforeDeleteCommit(Object dataObj,
DataProviderSessionIFace session) throws Exception
{
if (!super.beforeDeleteCommit(dataObj, session))
{
return false;
}
if (dataObj != null && (formViewObj == null || !StringUtils.contains(formViewObj.getView().getName(), "TreeDef")) &&
BaseTreeBusRules.ALLOW_CONCURRENT_FORM_ACCESS && viewable != null)
{
return getRequiredLocks(dataObj);
}
else
{
return true;
}
}
/* (non-Javadoc)
* @see edu.ku.brc.ui.forms.BaseBusRules#afterDeleteCommit(java.lang.Object)
*/
@SuppressWarnings("unchecked")
@Override
public void afterDeleteCommit(Object dataObj)
{
try
{
if (dataObj instanceof Treeable)
{
// NOTE: the instanceof check can't check against 'T' since T
// isn't a class
// this has a SMALL amount of risk to it
T node = (T) dataObj;
if (!node.getDefinition().getNodeNumbersAreUpToDate()
&& !node.getDefinition().isUploadInProgress())
{
// Scary. If nodes are not up to date, tree rules may not
// work.
// The application should prevent edits to items/trees whose
// tree numbers are not up to date except while uploading
// workbenches.
throw new RuntimeException(node.getDefinition().getName()
+ " has out of date node numbers.");
}
if (node.getDefinition().getDoNodeNumberUpdates()
&& node.getDefinition().getNodeNumbersAreUpToDate())
{
log
.info("A tree node was deleted. Updating node numbers appropriately.");
TreeDataService<T, D, I> dataServ = TreeDataServiceFactory
.createService();
// apparently a refresh() is necessary. node can hold
// obsolete values otherwise.
// Possibly needs to be done for all business rules??
DataProviderSessionIFace session = null;
try
{
session = DataProviderFactory.getInstance()
.createSession();
// rods - 07/28/08 commented out because the node is
// already deleted
// session.refresh(node);
dataServ.updateNodeNumbersAfterNodeDeletion(node,
session);
} catch (Exception ex)
{
edu.ku.brc.exceptions.ExceptionTracker.getInstance()
.capture(BaseTreeBusRules.class, ex);
ex.printStackTrace();
} finally
{
if (session != null)
{
session.close();
}
}
} else
{
node.getDefinition().setNodeNumbersAreUpToDate(false);
}
}
} finally
{
if (BaseTreeBusRules.ALLOW_CONCURRENT_FORM_ACCESS && viewable != null)
{
this.freeLocks();
}
}
}
/**
* Handles the {@link #beforeSave(Object)} method if the passed in {@link Object}
* is an instance of {@link TreeDefItemIface}. The real work of this method is to
* update the 'fullname' field of all {@link Treeable} objects effected by the changes
* to the passed in {@link TreeDefItemIface}.
*
* @param defItem the {@link TreeDefItemIface} being saved
*/
@SuppressWarnings("unchecked")
protected void beforeSaveTreeDefItem(I defItem)
{
// we need a way to determine if the 'isInFullname' value changed
// load a fresh copy from the DB and get the values needed for comparison
DataProviderSessionIFace tmpSession = DataProviderFactory.getInstance().createSession();
I fromDB = (I)tmpSession.load(defItem.getClass(), defItem.getTreeDefItemId());
tmpSession.close();
DataProviderSessionIFace session = DataProviderFactory.getInstance().createSession();
session.attach(defItem);
boolean changeThisLevel = false;
boolean changeAllDescendants = false;
boolean fromDBIsInFullname = makeNotNull(fromDB.getIsInFullName());
boolean currentIsInFullname = makeNotNull(defItem.getIsInFullName());
if (fromDBIsInFullname != currentIsInFullname)
{
changeAllDescendants = true;
}
// look for changes in the 'textBefore', 'textAfter' or 'fullNameSeparator' fields
String fromDbBeforeText = makeNotNull(fromDB.getTextBefore());
String fromDbAfterText = makeNotNull(fromDB.getTextAfter());
String fromDbSeparator = makeNotNull(fromDB.getFullNameSeparator());
String before = makeNotNull(defItem.getTextBefore());
String after = makeNotNull(defItem.getTextAfter());
String separator = makeNotNull(defItem.getFullNameSeparator());
boolean textFieldChanged = false;
boolean beforeChanged = !before.equals(fromDbBeforeText);
boolean afterChanged = !after.equals(fromDbAfterText);
boolean sepChanged = !separator.equals(fromDbSeparator);
if (beforeChanged || afterChanged || sepChanged)
{
textFieldChanged = true;
}
if (textFieldChanged)
{
if (currentIsInFullname)
{
changeAllDescendants = true;
}
changeThisLevel = true;
}
if (changeThisLevel && !changeAllDescendants)
{
Set<T> levelNodes = defItem.getTreeEntries();
for (T node: levelNodes)
{
String generated = TreeHelper.generateFullname(node);
node.setFullName(generated);
}
}
else if (changeThisLevel && changeAllDescendants)
{
Set<T> levelNodes = defItem.getTreeEntries();
for (T node: levelNodes)
{
TreeHelper.fixFullnameForNodeAndDescendants(node);
}
}
else if (!changeThisLevel && changeAllDescendants)
{
Set<T> levelNodes = defItem.getTreeEntries();
for (T node: levelNodes)
{
// grab all child nodes and go from there
for (T child: node.getChildren())
{
TreeHelper.fixFullnameForNodeAndDescendants(child);
}
}
}
// else don't change anything
session.close();
}
protected boolean booleanValue(Boolean bool, boolean defaultIfNull)
{
if (bool != null)
{
return bool.booleanValue();
}
return defaultIfNull;
}
/**
* Converts a null string into an empty string. If the provided String is not
* null, it is returned unchanged.
*
* @param s a string
* @return the string or " ", if null
*/
private String makeNotNull(String s)
{
return (s == null) ? "" : s;
}
/**
* Returns the provided {@link Boolean}, or <code>false</code> if null
*
* @param b the {@link Boolean} to convert to non-null
* @return the provided {@link Boolean}, or <code>false</code> if null
*/
private boolean makeNotNull(Boolean b)
{
return (b == null) ? false : b.booleanValue();
}
/* (non-Javadoc)
* @see edu.ku.brc.ui.forms.BaseBusRules#beforeDelete(java.lang.Object, edu.ku.brc.dbsupport.DataProviderSessionIFace)
*/
@Override
public Object beforeDelete(Object dataObj, DataProviderSessionIFace session)
{
super.beforeDelete(dataObj, session);
if (dataObj instanceof Treeable<?,?,?>)
{
Treeable<?, ?, ?> node = (Treeable<?,?,?> )dataObj;
if (node.getAcceptedParent() != null)
{
node.getAcceptedParent().getAcceptedChildren().remove(node);
node.setAcceptedParent(null);
}
}
return dataObj;
}
/**
* @param parentDataObj
* @param dataObj
* @return
*/
@SuppressWarnings("unchecked")
protected boolean parentHasChildWithSameName(final Object parentDataObj, final Object dataObj)
{
if (dataObj instanceof Treeable<?,?,?>)
{
Treeable<T, D, I> node = (Treeable<T,D,I> )dataObj;
Treeable<T, D, I> parent = parentDataObj == null ? node.getParent() : (Treeable<T, D, I> )parentDataObj;
if (parent != null)
{
//XXX the sql below will only work if all Treeable tables use fields named 'isAccepted' and 'name' to store
//the name and isAccepted properties.
String tblName = DBTableIdMgr.getInstance().getInfoById(node.getTableId()).getName();
String sql = "SELECT count(*) FROM " + tblName + " where isAccepted "
+ "and name = " + BasicSQLUtils.getEscapedSQLStrExpr(node.getName());
if (parent.getTreeId() != null)
{
sql += " and parentid = " + parent.getTreeId();
}
if (node.getTreeId() != null)
{
sql += " and " + tblName + "id != " + node.getTreeId();
}
return BasicSQLUtils.getNumRecords(sql) > 0;
}
}
return false;
}
/**
* @param parentDataObj
* @param dataObj
* @param isExistingObject
* @return
*/
@SuppressWarnings("unchecked")
public STATUS checkForSiblingWithSameName(final Object parentDataObj, final Object dataObj,
final boolean isExistingObject)
{
STATUS result = STATUS.OK;
if (parentHasChildWithSameName(parentDataObj, dataObj))
{
String parentName;
if (parentDataObj == null)
{
parentName = ((Treeable<T,D,I> )dataObj).getParent().getFullName();
}
else
{
parentName = ((Treeable<T,D,I> )parentDataObj).getFullName();
}
boolean saveIt = UIRegistry.displayConfirm(
UIRegistry.getResourceString("BaseTreeBusRules.IDENTICALLY_NAMED_SIBLING_TITLE"),
String.format(UIRegistry.getResourceString("BaseTreeBusRules.IDENTICALLY_NAMED_SIBLING_MSG"),
parentName, ((Treeable<T,D,I> )dataObj).getName()),
UIRegistry.getResourceString("SAVE"),
UIRegistry.getResourceString("CANCEL"),
JOptionPane.QUESTION_MESSAGE);
if (!saveIt)
{
//Adding to reasonList prevents blank "Issue of Concern" popup -
//but causes annoying second "duplicate child" nag.
reasonList
.add(UIRegistry
.getResourceString("BaseTreeBusRules.IDENTICALLY_NAMED_SIBLING")); // XXX
// i18n
result = STATUS.Error;
}
}
return result;
}
/**
* @param dataObj
* @return OK if required data is present.
*
* Checks for requirements that can't be defined in the database schema.
*/
protected STATUS checkForRequiredFields(Object dataObj)
{
if (dataObj instanceof Treeable<?,?,?>)
{
STATUS result = STATUS.OK;
Treeable<?,?,?> obj = (Treeable<?,?,?> )dataObj;
if (obj.getParent() == null )
{
if (obj.getDefinitionItem() != null && obj.getDefinitionItem().getParent() == null)
{
//it's the root, null parent is OK.
return result;
}
result = STATUS.Error;
DBTableInfo info = DBTableIdMgr.getInstance().getInfoById(obj.getTableId());
DBFieldInfo fld = info.getFieldByColumnName("Parent");
String fldTitle = fld != null ? fld.getTitle() : UIRegistry.getResourceString("PARENT");
reasonList.add(String.format(UIRegistry.getResourceString("GENERIC_FIELD_MISSING"), fldTitle));
}
//check that non-accepted node has an 'AcceptedParent'
if (obj.getIsAccepted() == null || !obj.getIsAccepted() && obj.getAcceptedParent() == null)
{
result = STATUS.Error;
DBTableInfo info = DBTableIdMgr.getInstance().getInfoById(obj.getTableId());
DBFieldInfo fld = info.getFieldByColumnName("AcceptedParent");
String fldTitle = fld != null ? fld.getTitle() : UIRegistry.getResourceString("ACCEPTED");
reasonList.add(String.format(UIRegistry.getResourceString("GENERIC_FIELD_MISSING"), fldTitle));
}
return result;
}
return STATUS.None; //???
}
/* (non-Javadoc)
* @see edu.ku.brc.af.ui.forms.BaseBusRules#processBusinessRules(java.lang.Object, java.lang.Object, boolean)
*/
@Override
public STATUS processBusinessRules(Object parentDataObj, Object dataObj,
boolean isExistingObject)
{
reasonList.clear();
STATUS result = STATUS.OK;
if (!processedRules && dataObj instanceof Treeable<?, ?, ?>)
{
result = checkForSiblingWithSameName(parentDataObj, dataObj, isExistingObject);
if (result == STATUS.OK)
{
result = checkForRequiredFields(dataObj);
}
if (result == STATUS.OK)
{
processedRules = true;
}
}
return result;
}
/* (non-Javadoc)
* @see edu.ku.brc.af.ui.forms.BaseBusRules#isOkToSave(java.lang.Object, edu.ku.brc.dbsupport.DataProviderSessionIFace)
*/
/*
* NOTE: If this method is overridden, freeLocks() MUST be called when result is false
* !!
*
*/
@Override
public boolean isOkToSave(Object dataObj, DataProviderSessionIFace session)
{
boolean result = super.isOkToSave(dataObj, session);
if (result && dataObj != null && !StringUtils.contains(formViewObj.getView().getName(), "TreeDef")
&& BaseTreeBusRules.ALLOW_CONCURRENT_FORM_ACCESS)
{
if (!getRequiredLocks(dataObj))
{
result = false;
reasonList.add(getUnableToLockMsg());
}
}
return result;
}
/**
* @return true if locks were aquired.
*
* Locks necessary tables prior to a save.
* Only used when ALLOW_CONCURRENT_FORM_ACCESS is true.
*/
protected boolean getRequiredLocks(Object dataObj)
{
TreeDefIface<?,?,?> treeDef = ((Treeable<?,?,?>)dataObj).getDefinition();
boolean result = !TreeDefStatusMgr.isRenumberingNodes(treeDef) && TreeDefStatusMgr.isNodeNumbersAreUpToDate(treeDef);
if (!result) {
try {
Thread.sleep(1500);
result = !TreeDefStatusMgr.isRenumberingNodes(treeDef) && TreeDefStatusMgr.isNodeNumbersAreUpToDate(treeDef);
} catch (Exception e) {
result = false;
}
}
if (result) {
TaskSemaphoreMgr.USER_ACTION r = TaskSemaphoreMgr.lock(getFormSaveLockTitle(), getFormSaveLockName(), "save",
TaskSemaphoreMgr.SCOPE.Discipline, false, new TaskSemaphoreMgrCallerIFace(){
/* (non-Javadoc)
* @see edu.ku.brc.specify.dbsupport.TaskSemaphoreMgrCallerIFace#resolveConflict(edu.ku.brc.specify.datamodel.SpTaskSemaphore, boolean, java.lang.String)
*/
@Override
public USER_ACTION resolveConflict(
SpTaskSemaphore semaphore,
boolean previouslyLocked, String prevLockBy)
{
if (System.currentTimeMillis() - semaphore.getLockedTime().getTime() > FORM_SAVE_LOCK_MAX_DURATION_IN_MILLIS) {
//something is clearly wrong with the lock. Ignore it and re-use it. It will be cleared when save succeeds.
log.warn("automatically overriding expired " + getFormSaveLockTitle() + " lock set by " +
prevLockBy + " at " + DateFormat.getDateTimeInstance().format(semaphore.getLockedTime()));
return USER_ACTION.OK;
} else {
return USER_ACTION.Error;
}
}
}, false);
result = r == TaskSemaphoreMgr.USER_ACTION.OK;
}
return result;
}
/**
* @return the class for the generic parameter <T>
*/
protected abstract Class<?> getNodeClass();
/**
* @return the title for the form save lock.
*/
protected String getFormSaveLockTitle()
{
return String.format(UIRegistry.getResourceString("BaseTreeBusRules.SaveLockTitle"), getNodeClass().getSimpleName());
}
/**
* @return the name for the form save lock.
*/
protected String getFormSaveLockName()
{
return getNodeClass().getSimpleName() + "Save";
}
/**
* @return localized message to display in case of failure to lock for saving.
*/
protected String getUnableToLockMsg()
{
return UIRegistry.getResourceString("BaseTreeBusRules.UnableToLockForSave");
}
/**
* Free locks acquired for saving.
*/
protected void freeLocks()
{
TaskSemaphoreMgr.unlock(getFormSaveLockTitle(), getFormSaveLockName(), TaskSemaphoreMgr.SCOPE.Discipline);
}
/* (non-Javadoc)
* @see edu.ku.brc.af.ui.forms.BaseBusRules#afterSaveCommit(java.lang.Object, edu.ku.brc.dbsupport.DataProviderSessionIFace)
*/
@Override
public boolean afterSaveCommit(Object dataObj,
DataProviderSessionIFace session)
{
boolean result = false;
if (!super.afterSaveCommit(dataObj, session))
{
result = false;
}
if (BaseTreeBusRules.ALLOW_CONCURRENT_FORM_ACCESS && viewable != null)
{
freeLocks();
}
return result;
}
/* (non-Javadoc)
* @see edu.ku.brc.af.ui.forms.BaseBusRules#afterSaveFailure(java.lang.Object, edu.ku.brc.dbsupport.DataProviderSessionIFace)
*/
@Override
public void afterSaveFailure(Object dataObj,
DataProviderSessionIFace session)
{
super.afterSaveFailure(dataObj, session);
if (BaseTreeBusRules.ALLOW_CONCURRENT_FORM_ACCESS && viewable != null)
{
freeLocks();
}
}
/* (non-Javadoc)
* @see edu.ku.brc.af.ui.forms.BaseBusRules#processBusinessRules(java.lang.Object)
*/
@Override
public STATUS processBusinessRules(Object dataObj) {
STATUS result = STATUS.OK;
if (!processedRules)
{
result = super.processBusinessRules(dataObj);
if (result == STATUS.OK)
{
result = checkForSiblingWithSameName(null, dataObj, false);
}
if (result == STATUS.OK)
{
result = checkForRequiredFields(dataObj);
}
}
else
{
processedRules = false;
}
return result;
}
}
| specify/specify6 | src/edu/ku/brc/specify/datamodel/busrules/BaseTreeBusRules.java | Java | gpl-2.0 | 58,365 |
<?php
/**
* @package WordPress Plugin
* @subpackage CMSMasters Content Composer
* @version 1.1.0
*
* Profiles Post Type
* Created by CMSMasters
*
*/
class Cmsms_Profiles {
function Cmsms_Profiles() {
$cmsms_option = cmsms_get_global_options();
$profile_labels = array(
'name' => __('Profiles', 'cmsms_content_composer'),
'singular_name' => __('Profiles', 'cmsms_content_composer'),
'menu_name' => __('Profiles', 'cmsms_content_composer'),
'all_items' => __('All Profiles', 'cmsms_content_composer'),
'add_new' => __('Add New', 'cmsms_content_composer'),
'add_new_item' => __('Add New Profile', 'cmsms_content_composer'),
'edit_item' => __('Edit Profile', 'cmsms_content_composer'),
'new_item' => __('New Profile', 'cmsms_content_composer'),
'view_item' => __('View Profile', 'cmsms_content_composer'),
'search_items' => __('Search Profiles', 'cmsms_content_composer'),
'not_found' => __('No Profiles found', 'cmsms_content_composer'),
'not_found_in_trash' => __('No Profiles found in Trash', 'cmsms_content_composer')
);
$profile_args = array(
'labels' => $profile_labels,
'query_var' => 'profile',
'capability_type' => 'post',
'menu_position' => 52,
'menu_icon' => 'dashicons-id',
'public' => true,
'show_ui' => true,
'hierarchical' => false,
'has_archive' => true,
'supports' => array(
'title',
'editor',
'thumbnail',
'excerpt',
'trackbacks',
'custom-fields',
'comments',
'revisions',
'page-attributes'
),
'rewrite' => array(
'slug' => $cmsms_option[CMSMS_SHORTNAME . '_profile_post_slug'],
'with_front' => true
)
);
register_post_type('profile', $profile_args);
add_filter('manage_edit-profile_columns', array(&$this, 'edit_columns'));
add_filter('manage_edit-profile_sortable_columns', array(&$this, 'edit_sortable_columns'));
register_taxonomy('pl-categs', array('profile'), array(
'hierarchical' => true,
'label' => __('Profile Categories', 'cmsms_content_composer'),
'singular_label' => __('Profile Category', 'cmsms_content_composer'),
'rewrite' => array(
'slug' => 'pl-categs',
'with_front' => true
)
));
add_action('manage_posts_custom_column', array(&$this, 'custom_columns'));
}
function edit_columns($columns) {
unset($columns['author']);
unset($columns['comments']);
unset($columns['date']);
$new_columns = array(
'cb' => '<input type="checkbox" />',
'title' => __('Title', 'cmsms_content_composer'),
'pl_avatar' => __('Avatar', 'cmsms_content_composer'),
'pl_categs' => __('Categories', 'cmsms_content_composer'),
'comments' => '<span class="vers"><div title="' . __('Comments', 'cmsms_content_composer') . '" class="comment-grey-bubble"></div></span>',
'menu_order' => '<span class="vers"><div class="dashicons dashicons-sort" title="' . __('Order', 'cmsms_content_composer') . '"></div></span>'
);
$result_columns = array_merge($columns, $new_columns);
return $result_columns;
}
function custom_columns($column) {
switch ($column) {
case 'pl_avatar':
if (has_post_thumbnail() != '') {
echo get_the_post_thumbnail(get_the_ID(), 'thumbnail', array(
'alt' => cmsms_title(get_the_ID(), false),
'title' => cmsms_title(get_the_ID(), false),
'style' => 'width:75px; height:75px;'
));
} else {
echo '<em>' . __('No Avatar', 'cmsms_content_composer') . '</em>';
}
break;
case 'pl_categs':
if (get_the_terms(0, 'pl-categs') != '') {
$pl_categs = get_the_terms(0, 'pl-categs');
$pl_categs_html = array();
foreach ($pl_categs as $pl_categ) {
array_push($pl_categs_html, '<a href="' . get_term_link($pl_categ->slug, 'pl-categs') . '">' . $pl_categ->name . '</a>');
}
echo implode($pl_categs_html, ', ');
} else {
echo '<em>' . __('Uncategorized', 'cmsms_content_composer') . '</em>';
}
break;
case 'menu_order':
$custom_pl_post = get_post(get_the_ID());
$custom_pl_ord = $custom_pl_post->menu_order;
echo $custom_pl_ord;
break;
}
}
function edit_sortable_columns($columns) {
$columns['menu_order'] = 'menu_order';
return $columns;
}
}
function cmsms_profiles_init() {
global $pl;
$pl = new Cmsms_Profiles();
}
add_action('init', 'cmsms_profiles_init');
| d8ta/CMS_Skiclub | wp-content/plugins/cmsms-content-composer/inc/profile/profiles-posttype.php | PHP | gpl-2.0 | 4,628 |
<?php
namespace Goetas\XML\XSDReader\Schema\Element;
interface ElementSingle extends ElementItem
{
/**
* @return \Goetas\XML\XSDReader\Schema\Type\Type
*/
public function getType();
/**
*
* @return int
*/
public function getMin();
/**
*
* @param int $qualified
*/
public function setMin($min);
/**
*
* @return int
*/
public function getMax();
/**
*
* @param int $qualified
*/
public function setMax($max);
/**
*
* @return bool
*/
public function isQualified();
/**
*
* @param boolean $qualified
*/
public function setQualified($qualified);
/**
*
* @return bool
*/
public function isNil();
/**
*
* @param boolean $qualified
*/
public function setNil($nil);
}
| DLoBoston/simply.fund | wp-content/plugins/charitable-authorize-net/includes/libraries/anet_php_sdk/vendor/goetas/xsd-reader/src/Schema/Element/ElementSingle.php | PHP | gpl-2.0 | 870 |
// Copyright 2017 Dolphin Emulator Project
// Licensed under GPLv2+
// Refer to the license.txt file included.
#include <QComboBox>
#include <QDialogButtonBox>
#include <QGroupBox>
#include <QHBoxLayout>
#include <QMessageBox>
#include <QPushButton>
#include <QTabWidget>
#include <QVBoxLayout>
#include "DolphinQt2/Config/Mapping/MappingWindow.h"
#include "Common/FileUtil.h"
#include "Common/IniFile.h"
#include "Core/Core.h"
#include "Core/HW/GCPad.h"
#include "DolphinQt2/Config/Mapping/GCKeyboardEmu.h"
#include "DolphinQt2/Config/Mapping/GCPadEmu.h"
#include "DolphinQt2/Config/Mapping/GCPadWiiU.h"
#include "DolphinQt2/Config/Mapping/WiimoteEmuExtension.h"
#include "DolphinQt2/Config/Mapping/WiimoteEmuGeneral.h"
#include "DolphinQt2/Config/Mapping/WiimoteEmuMotionControl.h"
#include "DolphinQt2/Settings.h"
#include "InputCommon/ControllerEmu/ControllerEmu.h"
#include "InputCommon/ControllerInterface/Device.h"
#include "InputCommon/InputConfig.h"
#include "InputCommon/ControllerInterface/ControllerInterface.h"
MappingWindow::MappingWindow(QWidget* parent, int port_num) : QDialog(parent), m_port(port_num)
{
setWindowTitle(tr("Port %1").arg(port_num + 1));
CreateDevicesLayout();
CreateProfilesLayout();
CreateResetLayout();
CreateMainLayout();
ConnectWidgets();
}
void MappingWindow::CreateDevicesLayout()
{
m_devices_layout = new QHBoxLayout();
m_devices_box = new QGroupBox(tr("Devices"));
m_devices_combo = new QComboBox();
m_devices_refresh = new QPushButton(tr("Refresh"));
m_devices_refresh->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
m_devices_layout->addWidget(m_devices_combo);
m_devices_layout->addWidget(m_devices_refresh);
m_devices_box->setLayout(m_devices_layout);
}
void MappingWindow::CreateProfilesLayout()
{
m_profiles_layout = new QVBoxLayout();
m_profiles_box = new QGroupBox(tr("Profiles"));
m_profiles_combo = new QComboBox();
m_profiles_load = new QPushButton(tr("Load"));
m_profiles_save = new QPushButton(tr("Save"));
m_profiles_delete = new QPushButton(tr("Delete"));
auto* button_layout = new QHBoxLayout();
m_profiles_box->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
m_profiles_combo->setEditable(true);
m_profiles_layout->addWidget(m_profiles_combo);
button_layout->addWidget(m_profiles_load);
button_layout->addWidget(m_profiles_save);
button_layout->addWidget(m_profiles_delete);
m_profiles_layout->addItem(button_layout);
m_profiles_box->setLayout(m_profiles_layout);
}
void MappingWindow::CreateResetLayout()
{
m_reset_layout = new QVBoxLayout();
m_reset_box = new QGroupBox(tr("Reset"));
m_reset_clear = new QPushButton(tr("Clear"));
m_reset_default = new QPushButton(tr("Default"));
m_reset_box->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
m_reset_layout->addWidget(m_reset_clear);
m_reset_layout->addWidget(m_reset_default);
m_reset_box->setLayout(m_reset_layout);
}
void MappingWindow::CreateMainLayout()
{
m_main_layout = new QVBoxLayout();
m_config_layout = new QHBoxLayout();
m_tab_widget = new QTabWidget();
m_button_box = new QDialogButtonBox(QDialogButtonBox::Ok);
m_config_layout->addWidget(m_profiles_box);
m_config_layout->addWidget(m_reset_box);
m_main_layout->addWidget(m_devices_box);
m_main_layout->addItem(m_config_layout);
m_main_layout->addWidget(m_tab_widget);
m_main_layout->addWidget(m_button_box);
setLayout(m_main_layout);
}
void MappingWindow::ConnectWidgets()
{
connect(m_devices_refresh, &QPushButton::clicked, this, &MappingWindow::RefreshDevices);
connect(m_devices_combo, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged),
this, &MappingWindow::OnDeviceChanged);
connect(m_reset_clear, &QPushButton::clicked, this, [this] { emit ClearFields(); });
connect(m_reset_default, &QPushButton::clicked, this, &MappingWindow::OnDefaultFieldsPressed);
connect(m_profiles_save, &QPushButton::clicked, this, &MappingWindow::OnSaveProfilePressed);
connect(m_profiles_load, &QPushButton::clicked, this, &MappingWindow::OnLoadProfilePressed);
connect(m_profiles_delete, &QPushButton::clicked, this, &MappingWindow::OnDeleteProfilePressed);
connect(m_button_box, &QDialogButtonBox::accepted, this, &MappingWindow::accept);
}
void MappingWindow::OnDeleteProfilePressed()
{
auto& settings = Settings::Instance();
const QString profile_name = m_profiles_combo->currentText();
if (!settings.GetProfiles(m_config).contains(profile_name))
{
QMessageBox error;
error.setIcon(QMessageBox::Critical);
error.setText(tr("The profile '%1' does not exist").arg(profile_name));
error.exec();
return;
}
QMessageBox confirm(this);
confirm.setIcon(QMessageBox::Warning);
confirm.setText(tr("Are you sure that you want to delete '%1'?").arg(profile_name));
confirm.setInformativeText(tr("This cannot be undone!"));
confirm.setStandardButtons(QMessageBox::Yes | QMessageBox::Cancel);
if (confirm.exec() != QMessageBox::Yes)
{
return;
}
m_profiles_combo->removeItem(m_profiles_combo->currentIndex());
QMessageBox result(this);
std::string profile_path = settings.GetProfileINIPath(m_config, profile_name).toStdString();
File::CreateFullPath(profile_path);
File::Delete(profile_path);
result.setIcon(QMessageBox::Information);
result.setText(tr("Successfully deleted '%1'.").arg(profile_name));
}
void MappingWindow::OnLoadProfilePressed()
{
const QString profile_name = m_profiles_combo->currentText();
if (profile_name.isEmpty())
return;
std::string profile_path =
Settings::Instance().GetProfileINIPath(m_config, profile_name).toStdString();
File::CreateFullPath(profile_path);
IniFile ini;
ini.Load(profile_path);
m_controller->LoadConfig(ini.GetOrCreateSection("Profile"));
m_controller->UpdateReferences(g_controller_interface);
emit Update();
RefreshDevices();
}
void MappingWindow::OnSaveProfilePressed()
{
const QString profile_name = m_profiles_combo->currentText();
if (profile_name.isEmpty())
return;
std::string profile_path =
Settings::Instance().GetProfileINIPath(m_config, profile_name).toStdString();
File::CreateFullPath(profile_path);
IniFile ini;
m_controller->SaveConfig(ini.GetOrCreateSection("Profile"));
ini.Save(profile_path);
if (m_profiles_combo->currentIndex() == 0)
{
m_profiles_combo->addItem(profile_name);
m_profiles_combo->setCurrentIndex(m_profiles_combo->count() - 1);
}
}
void MappingWindow::OnDeviceChanged(int index)
{
const auto device = m_devices_combo->currentText().toStdString();
m_devq.FromString(device);
m_controller->default_device.FromString(device);
}
void MappingWindow::RefreshDevices()
{
m_devices_combo->clear();
const bool paused = Core::PauseAndLock(true);
g_controller_interface.RefreshDevices();
m_controller->UpdateReferences(g_controller_interface);
m_controller->UpdateDefaultDevice();
const auto default_device = m_controller->default_device.ToString();
m_devices_combo->addItem(QString::fromStdString(default_device));
for (const auto& name : g_controller_interface.GetAllDeviceStrings())
{
if (name != default_device)
m_devices_combo->addItem(QString::fromStdString(name));
}
m_devices_combo->setCurrentIndex(0);
Core::PauseAndLock(false, paused);
}
void MappingWindow::ChangeMappingType(MappingWindow::Type type)
{
if (m_mapping_type == type)
return;
ClearWidgets();
m_controller = nullptr;
MappingWidget* widget;
switch (type)
{
case Type::MAPPING_GC_KEYBOARD:
widget = new GCKeyboardEmu(this);
AddWidget(tr("GameCube Keyboard"), widget);
setWindowTitle(tr("GameCube Keyboard at Port %1").arg(GetPort() + 1));
break;
case Type::MAPPING_GC_BONGOS:
case Type::MAPPING_GC_STEERINGWHEEL:
case Type::MAPPING_GC_DANCEMAT:
case Type::MAPPING_GCPAD:
widget = new GCPadEmu(this);
setWindowTitle(tr("GameCube Controller at Port %1").arg(GetPort() + 1));
AddWidget(tr("GameCube Controller"), widget);
break;
case Type::MAPPING_GCPAD_WIIU:
widget = new GCPadWiiU(this);
setWindowTitle(tr("GameCube Adapter for Wii U at Port %1").arg(GetPort() + 1));
AddWidget(tr("GameCube Adapter for Wii U"), widget);
break;
case Type::MAPPING_WIIMOTE_EMU:
case Type::MAPPING_WIIMOTE_HYBRID:
{
auto* extension = new WiimoteEmuExtension(this);
widget = new WiimoteEmuGeneral(this, extension);
setWindowTitle(tr("Wii Remote at Port %1").arg(GetPort() + 1));
AddWidget(tr("General and Options"), widget);
AddWidget(tr("Motion Controls and IR"), new WiimoteEmuMotionControl(this));
AddWidget(tr("Extension"), extension);
break;
}
default:
return;
}
widget->LoadSettings();
m_profiles_combo->clear();
m_config = widget->GetConfig();
if (m_config)
{
m_controller = m_config->GetController(GetPort());
m_profiles_combo->addItem(QStringLiteral(""));
for (const auto& item : Settings::Instance().GetProfiles(m_config))
m_profiles_combo->addItem(item);
}
SetLayoutComplex(type != Type::MAPPING_GCPAD_WIIU);
if (m_controller != nullptr)
RefreshDevices();
m_mapping_type = type;
}
void MappingWindow::ClearWidgets()
{
m_tab_widget->clear();
}
void MappingWindow::AddWidget(const QString& name, QWidget* widget)
{
m_tab_widget->addTab(widget, name);
}
void MappingWindow::SetLayoutComplex(bool is_complex)
{
m_reset_box->setHidden(!is_complex);
m_profiles_box->setHidden(!is_complex);
m_devices_box->setHidden(!is_complex);
m_is_complex = is_complex;
}
int MappingWindow::GetPort() const
{
return m_port;
}
const ciface::Core::DeviceQualifier& MappingWindow::GetDeviceQualifier() const
{
return m_devq;
}
std::shared_ptr<ciface::Core::Device> MappingWindow::GetDevice() const
{
return g_controller_interface.FindDevice(m_devq);
}
void MappingWindow::SetBlockInputs(const bool block)
{
m_block = block;
}
bool MappingWindow::event(QEvent* event)
{
if (!m_block)
return QDialog::event(event);
return false;
}
| Freyaday/dolphin | Source/Core/DolphinQt2/Config/Mapping/MappingWindow.cpp | C++ | gpl-2.0 | 10,097 |
<?php
/**
* Created by PhpStorm.
* User: Angga Ari Wijaya
* Date: 9/12/2015
* Time: 1:04 AM
*/
namespace DecoratorPattern;
class VisaPayment implements PaymentMethod
{
public function getDescription()
{
return "Visa description";
}
} | anggadarkprince/design-pattern | DecoratorPattern/VisaPayment.php | PHP | gpl-2.0 | 262 |
import sys,os
#sys.path.append(os.path.join(os.path.dirname(__file__), '../../..'))
#from ethosgame.ethos.level import Level
from ..level import Level
#from ethosgame.ethos.gameobject import GameObject
from ..gameobject import GameObject
#from ethosgame.ethos.drawnobject import DrawnObject
from ..drawnobject import DrawnObject
import pygame
from pygame.locals import *
from pygame import Color, image, font, sprite
class Level0(Level):
def __init__(self):
super(Level0, self).__init__()
self.activeSprites = sprite.RenderClear()
self.drawnSprites = []
self.npc = GameObject(image.load('User.png'), 100,50)
self.activeSprites.add(self.npc)
self.block1 = GameObject(image.load('platform.png'), 100, 400)
self.activeSprites.add(self.block1);
self.mousex = 0
self.mousey = 0
#The highest height our npc
#can climb. If a the dY with a
#point is higher than this, the
#npc will just fall to his death
self.MAX_HILL_HEIGHT = 3
self.toDrawRectTopLeft = (0,0)
self.toDrawRectBottomRight = (0,0)
self.drawing = False
self.pts = []
print "Level 0 initialized."
def update(self, dT):
#print "Running level0"
#Character info
for gobject in self.activeSprites:
if gobject is not self.npc:
if not gobject.rect.colliderect(self.npc.rect):
#if self.npc.vy < 0.3 and (gobject.rect.y >= self.npc.rect.y + self.npc.rect.height):
if self.npc.vy < 0.3:
self.npc.vy += 0.1
else:
self.npc.vy = 0
gobject.update(dT)
collidingPoints = []
for drawnstuff in self.drawnSprites:
for point in drawnstuff.pts:
x = self.npc.rect.collidepoint(point)
if x:
collidingPoints.append(point)
if(len(collidingPoints) > 0):
self.npc.processPointCollision(collidingPoints)
def processKeyDown(self,key):
print "You hit the key " + str(key) + "!"
if key == pygame.K_RIGHT:
self.npc.vx = 0.1
def processMouseMotion(self,pos):
#print "Your mouse is at " + str(pos[0]) + " " + str(pos[1])
self.mousex = pos[0]
self.mousey = pos[1]
if self.drawing and len(self.pts) < 100:
self.pts.append( pos )
def processMouseButtonDown(self, pos):
print "Ya clicked at " + str(pos[0]) + " " + str(pos[1]) + " ya goof!"
self.drawing = True
self.toDrawRectTopLeft = (pos[0],pos[1])
if len(self.pts) > 0:
self.pts = []
def processMouseButtonUp(self, pos):
print "Ya let go"
if self.drawing is True:
self.drawing = False
self.drawnSprites.append ( DrawnObject(self.pts) )
self.toDrawRectBottomRight = (pos[0], pos[1])
| Berulacks/ethosgame | ethos/levels/level0.py | Python | gpl-2.0 | 2,904 |
<?php
/*
Template Name: Nos fromages
*
* This is your custom page template. You can create as many of these as you need.
* Simply name is "page-whatever.php" and in add the "Template Name" title at the
* top, the same way it is here.
*
* When you create your page, you can just select the template and viola, you have
* a custom page template to call your very own. Your mother would be so proud.
*
* For more info: http://codex.wordpress.org/Page_Templates
*/
?>
<?php get_header(); ?>
<div id="content" class="montagneBackground">
<div class="container_12">
<section class="categories-f-r">
<?php $taxonomy = 'fromages_cat';
$tax_terms = get_terms( $taxonomy, array( 'hide_empty' => 0, 'orderby' => 'id', 'order' => DESC ) ); ?>
<div class="text-wrapper">
<h1>Nos Fromages RichesMonts</h1>
<h2>Variez les plaisirs ! <br> Découvrez toutes nos Raclettes,<br> Fondues et Tartiflettes !</h2>
</div>
<div class="categorie-bloc">
<img src="<?php echo get_template_directory_uri(); ?>/library/images/categorie-fromage-1.jpg" alt="">
<a href="<?php echo get_term_link($tax_terms[0]); ?>"><h3><?php echo $tax_terms[0]->name; ?></h3></a>
</div>
<div class="categorie-bloc">
<img src="<?php echo get_template_directory_uri(); ?>/library/images/categorie-fromage-2.jpg" alt="">
<a href="<?php echo get_term_link($tax_terms[1]); ?>"><h3><?php echo $tax_terms[1]->name; ?></h3></a>
</div>
<div class="categorie-bloc">
<img src="<?php echo get_template_directory_uri(); ?>/library/images/categorie-fromage-3.jpg" alt="">
<a href="<?php echo get_term_link($tax_terms[2]); ?>"><h3><?php echo $tax_terms[2]->name; ?></h3></a>
</div>
</section>
<div class="clearfix"></div>
<?php $the_query = new WP_Query( array('post_type' => 'partenaires', 'showposts' => 5) );
if ( $the_query->have_posts() ) { ?>
<section class="partenaires container_12">
<div class="outer-center">
<div class="inner-center">
<h2>Nos partenaires :</h2>
<?php while ( $the_query->have_posts() ) { ?>
<?php $the_query->the_post(); ?>
<?php $image = get_field('logo'); ?>
<a href="<?php the_field('lien'); ?>"><img src="<?php echo $image['url'] ?>" alt="<?php the_title(); ?>"></a>
<?php } ?>
</div>
</div>
</section>
<?php } wp_reset_postdata(); ?>
<div class="clearfix"></div>
</div>
</div>
<?php get_footer(); ?> | LSERRE/RichesMonts | wp-content/themes/richesmonts/page-nos-fromages.php | PHP | gpl-2.0 | 2,538 |
<?php
/**
* Sample implementation of the Custom Header feature.
*
* You can add an optional custom header image to header.php like so ...
*
<?php if ( get_header_image() ) : ?>
<a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home">
<img src="<?php header_image(); ?>" width="<?php echo esc_attr( get_custom_header()->width ); ?>" height="<?php echo esc_attr( get_custom_header()->height ); ?>" alt="">
</a>
<?php endif; // End header image check. ?>
*
* @link https://developer.wordpress.org/themes/functionality/custom-headers/
*
* @package sachyya
*/
/**
* Set up the WordPress core custom header feature.
*
* @uses sachyya_header_style()
*/
function sachyya_custom_header_setup() {
add_theme_support( 'custom-header', apply_filters( 'sachyya_custom_header_args', array(
'default-image' => '',
'default-text-color' => '000000',
'width' => 1000,
'height' => 250,
'flex-height' => true,
'wp-head-callback' => 'sachyya_header_style',
) ) );
}
add_action( 'after_setup_theme', 'sachyya_custom_header_setup' );
if ( ! function_exists( 'sachyya_header_style' ) ) :
/**
* Styles the header image and text displayed on the blog.
*
* @see sachyya_custom_header_setup().
*/
function sachyya_header_style() {
$header_text_color = get_header_textcolor();
/*
* If no custom options for text are set, let's bail.
* get_header_textcolor() options: Any hex value, 'blank' to hide text. Default: HEADER_TEXTCOLOR.
*/
if ( HEADER_TEXTCOLOR === $header_text_color ) {
return;
}
// If we get this far, we have custom styles. Let's do this.
?>
<style type="text/css">
<?php
// Has the text been hidden?
if ( ! display_header_text() ) :
?>
.site-title,
.site-description {
position: absolute;
clip: rect(1px, 1px, 1px, 1px);
}
<?php
// If the user has set a custom color for the text use that.
else :
?>
.site-title a,
.site-description {
color: #<?php echo esc_attr( $header_text_color ); ?>;
}
<?php endif; ?>
</style>
<?php
}
endif;
| sachyya/portfolio | wp-content/themes/sachyya/inc/custom-header.php | PHP | gpl-2.0 | 2,080 |
<?php
require_once(sfConfig::get('sf_lib_dir').'/filter/base/BaseFormFilterPropel.class.php');
/**
* CatArt filter form base class.
*
* @package sf_sandbox
* @subpackage filter
* @author Your name here
* @version SVN: $Id: sfPropelFormFilterGeneratedTemplate.php 16976 2009-04-04 12:47:44Z fabien $
*/
class BaseCatArtFormFilter extends BaseFormFilterPropel
{
public function setup()
{
$this->setWidgets(array(
'cat_des' => new sfWidgetFormFilterInput(),
'dis_cen' => new sfWidgetFormFilterInput(),
'campo1' => new sfWidgetFormFilterInput(),
'campo2' => new sfWidgetFormFilterInput(),
'campo3' => new sfWidgetFormFilterInput(),
'campo4' => new sfWidgetFormFilterInput(),
'co_us_in' => new sfWidgetFormFilterInput(),
'fe_us_in' => new sfWidgetFormFilterInput(),
'co_us_mo' => new sfWidgetFormFilterInput(),
'fe_us_mo' => new sfWidgetFormFilterInput(),
'co_us_el' => new sfWidgetFormFilterInput(),
'fe_us_el' => new sfWidgetFormFilterInput(),
'revisado' => new sfWidgetFormFilterInput(),
'trasnfe' => new sfWidgetFormFilterInput(),
'co_sucu' => new sfWidgetFormFilterInput(),
'rowguid' => new sfWidgetFormFilterInput(),
'co_imun' => new sfWidgetFormFilterInput(),
'co_reten' => new sfWidgetFormFilterInput(),
'row_id' => new sfWidgetFormFilterInput(),
'movil' => new sfWidgetFormChoice(array('choices' => array('' => 'yes or no', 1 => 'yes', 0 => 'no'))),
));
$this->setValidators(array(
'cat_des' => new sfValidatorPass(array('required' => false)),
'dis_cen' => new sfValidatorPass(array('required' => false)),
'campo1' => new sfValidatorPass(array('required' => false)),
'campo2' => new sfValidatorPass(array('required' => false)),
'campo3' => new sfValidatorPass(array('required' => false)),
'campo4' => new sfValidatorPass(array('required' => false)),
'co_us_in' => new sfValidatorPass(array('required' => false)),
'fe_us_in' => new sfValidatorPass(array('required' => false)),
'co_us_mo' => new sfValidatorPass(array('required' => false)),
'fe_us_mo' => new sfValidatorPass(array('required' => false)),
'co_us_el' => new sfValidatorPass(array('required' => false)),
'fe_us_el' => new sfValidatorPass(array('required' => false)),
'revisado' => new sfValidatorPass(array('required' => false)),
'trasnfe' => new sfValidatorPass(array('required' => false)),
'co_sucu' => new sfValidatorPass(array('required' => false)),
'rowguid' => new sfValidatorPass(array('required' => false)),
'co_imun' => new sfValidatorPass(array('required' => false)),
'co_reten' => new sfValidatorPass(array('required' => false)),
'row_id' => new sfValidatorPass(array('required' => false)),
'movil' => new sfValidatorChoice(array('required' => false, 'choices' => array('', 1, 0))),
));
$this->widgetSchema->setNameFormat('cat_art_filters[%s]');
$this->errorSchema = new sfValidatorErrorSchema($this->validatorSchema);
parent::setup();
}
public function getModelName()
{
return 'CatArt';
}
public function getFields()
{
return array(
'co_cat' => 'Text',
'cat_des' => 'Text',
'dis_cen' => 'Text',
'campo1' => 'Text',
'campo2' => 'Text',
'campo3' => 'Text',
'campo4' => 'Text',
'co_us_in' => 'Text',
'fe_us_in' => 'Text',
'co_us_mo' => 'Text',
'fe_us_mo' => 'Text',
'co_us_el' => 'Text',
'fe_us_el' => 'Text',
'revisado' => 'Text',
'trasnfe' => 'Text',
'co_sucu' => 'Text',
'rowguid' => 'Text',
'co_imun' => 'Text',
'co_reten' => 'Text',
'row_id' => 'Text',
'movil' => 'Boolean',
);
}
}
| luelher/gescob | lib/filter/profit/base/BaseCatArtFormFilter.class.php | PHP | gpl-2.0 | 3,869 |
require File.join(File.dirname(__FILE__), 'test_helper')
class PointTest < Test::Unit::TestCase
context "A point" do
setup do
@point = Pathfinder::Point.new 1, 2
end
should "respond to #x and #y" do
assert_equal 1, @point.x
assert_equal 2, @point.y
end
should "convert to an Array using #to_a" do
assert_equal [1,2], @point.to_a
end
should "output in ordered-pair notation upon #inspect" do
assert_equal "(1,2)", @point.inspect
end
should "have distance zero from itself" do
assert_equal 0.0, @point.distance(@point)
end
should "use the distance formula to calculate #distance" do
origin = Pathfinder::Point.new 0,0
assert_in_delta Math.sqrt(5), @point.distance(origin), 0.0001
end
end
end
| madriska/pathfinder | test/point_test.rb | Ruby | gpl-2.0 | 809 |
package org.iq4j.webcam;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.Transparency;
import java.awt.color.ColorSpace;
import java.awt.color.ICC_ColorSpace;
import java.awt.color.ICC_ProfileRGB;
import java.awt.event.KeyEvent;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;
import com.googlecode.javacv.cpp.opencv_core.CvScalar;
import com.googlecode.javacv.cpp.opencv_core.IplImage;
/**
*
* @author Samuel Audet
*
*
* Make sure OpenGL or XRender is enabled to get low latency, something like
* export _JAVA_OPTIONS=-Dsun.java2d.opengl=True
* export _JAVA_OPTIONS=-Dsun.java2d.xrender=True
*
* @author Sertac ANADOLLU ( anatolian )
*
* JPanel version of javacv CanvasFrame
*
*/
public class CanvasPanel extends JPanel {
private static final long serialVersionUID = 1L;
public static class Exception extends java.lang.Exception {
private static final long serialVersionUID = 1L;
public Exception(String message) { super(message); }
public Exception(String message, Throwable cause) { super(message, cause); }
}
public static GraphicsDevice getDefaultScreenDevice() {
return GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
}
public static double getGamma(GraphicsDevice screen) {
ColorSpace cs = screen.getDefaultConfiguration().getColorModel().getColorSpace();
if (cs.isCS_sRGB()) {
return 2.2;
} else {
try {
return ((ICC_ProfileRGB)((ICC_ColorSpace)cs).getProfile()).getGamma(0);
} catch (RuntimeException e) { }
}
return 0.0;
}
public CanvasPanel() {
this(0.0);
}
public CanvasPanel(double gamma) {
this(gamma, Dimensions.DEFAULT_SIZE);
}
public CanvasPanel(double gamma, Dimension size) {
this.gamma = gamma;
setPreferredSize(size);
setSize(size);
setBackground(Color.LIGHT_GRAY);
}
private void startCanvas() {
Runnable r = new Runnable() { public void run() {
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(keyEventDispatch);
GraphicsDevice gd = getGraphicsConfiguration().getDevice();
double g = gamma == 0.0 ? getGamma(gd) : gamma;
inverseGamma = g == 0.0 ? 1.0 : 1.0/g;
setVisible(true);
setupCanvas(gamma);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}};
if (EventQueue.isDispatchThread()) {
r.run();
setCanvasSize(getSize().width, getSize().height);
} else {
try {
EventQueue.invokeAndWait(r);
} catch (java.lang.Exception ex) { }
}
}
public void resetCanvas() {
canvas = null;
}
protected void setupCanvas(double gamma) {
canvas = new Canvas() {
private static final long serialVersionUID = 1L;
@Override public void update(Graphics g) {
paint(g);
}
@Override public void paint(Graphics g) {
// Calling BufferStrategy.show() here sometimes throws
// NullPointerException or IllegalStateException,
// but otherwise seems to work fine.
try {
BufferStrategy strategy = canvas.getBufferStrategy();
do {
do {
g = strategy.getDrawGraphics();
if (color != null) {
g.setColor(color);
g.fillRect(0, 0, getWidth(), getHeight());
}
if (image != null) {
g.drawImage(image, 0, 0, getWidth(), getHeight(), null);
}
if (buffer != null) {
g.drawImage(buffer, 0, 0, getWidth(), getHeight(), null);
}
g.dispose();
} while (strategy.contentsRestored());
strategy.show();
} while (strategy.contentsLost());
} catch (NullPointerException e) {
} catch (IllegalStateException e) { }
}
};
needInitialResize = true;
add(canvas);
canvas.setVisible(true);
canvas.createBufferStrategy(2);
}
// used for example as debugging console...
public static CanvasPanel global = null;
// Latency is about 60 ms on Metacity and Windows XP, and 90 ms on Compiz Fusion,
// but we set the default to twice as much to take into account the roundtrip
// camera latency as well, just to be sure
public static final long DEFAULT_LATENCY = 200;
private long latency = DEFAULT_LATENCY;
private KeyEvent keyEvent = null;
private KeyEventDispatcher keyEventDispatch = new KeyEventDispatcher() {
public boolean dispatchKeyEvent(KeyEvent e) {
if (e.getID() == KeyEvent.KEY_PRESSED) {
synchronized (CanvasPanel.this) {
keyEvent = e;
CanvasPanel.this.notify();
}
}
return false;
}
};
protected Canvas canvas = null;
protected boolean needInitialResize = false;
protected double initialScale = 1.0;
protected double inverseGamma = 1.0;
private Color color = null;
private Image image = null;
private BufferedImage buffer = null;
private final double gamma;
public long getLatency() {
// if there exists some way to estimate the latency in real time,
// add it here
return latency;
}
public void setLatency(long latency) {
this.latency = latency;
}
public void waitLatency() throws InterruptedException {
Thread.sleep(getLatency());
}
public KeyEvent waitKey() throws InterruptedException {
return waitKey(0);
}
public synchronized KeyEvent waitKey(int delay) throws InterruptedException {
if (delay >= 0) {
keyEvent = null;
wait(delay);
}
KeyEvent e = keyEvent;
keyEvent = null;
return e;
}
public Canvas getCanvas() {
return canvas;
}
public Dimension getCanvasSize() {
return canvas.getSize();
}
public void setCanvasSize(final int width, final int height) {
Dimension d = getCanvasSize();
if (d.width == width && d.height == height) {
return;
}
Runnable r = new Runnable() { public void run() {
// There is apparently a bug in Java code for Linux, and what happens goes like this:
// 1. Canvas gets resized, checks the visible area (has not changed) and updates
// BufferStrategy with the same size. 2. pack() resizes the frame and changes
// the visible area 3. We call Canvas.setSize() with different dimensions, to make
// it check the visible area and reallocate the BufferStrategy almost correctly
// 4. Finally, we resize the Canvas to the desired size... phew!
canvas.setSize(width, height);
setSize(width, height);
canvas.setSize(width+1, height+1);
canvas.setSize(width, height);
needInitialResize = false;
}};
if (EventQueue.isDispatchThread()) {
r.run();
} else {
try {
EventQueue.invokeAndWait(r);
} catch (java.lang.Exception ex) { }
}
}
public double getCanvasScale() {
return initialScale;
}
public void setCanvasScale(double initialScale) {
this.initialScale = initialScale;
this.needInitialResize = true;
}
public Graphics2D createGraphics() {
if (buffer == null || buffer.getWidth() != canvas.getWidth() || buffer.getHeight() != canvas.getHeight()) {
BufferedImage newbuffer = canvas.getGraphicsConfiguration().createCompatibleImage(
canvas.getWidth(), canvas.getHeight(), Transparency.TRANSLUCENT);
if (buffer != null) {
Graphics g = newbuffer.getGraphics();
g.drawImage(buffer, 0, 0, null);
g.dispose();
}
buffer = newbuffer;
}
return buffer.createGraphics();
}
public void releaseGraphics(Graphics2D g) {
g.dispose();
canvas.paint(null);
}
public void showColor(CvScalar color) {
showColor(new Color((int)color.red(), (int)color.green(), (int)color.blue()));
}
public void showColor(Color color) {
this.color = color;
this.image = null;
canvas.paint(null);
}
// Java2D will do gamma correction for TYPE_CUSTOM BufferedImage, but
// not for the standard types, so we need to do it manually.
public void showImage(IplImage image) {
showImage(image, false);
}
public void showImage(IplImage image, boolean flipChannels) {
showImage(image.getBufferedImage(image.getBufferedImageType() ==
BufferedImage.TYPE_CUSTOM ? 1.0 : inverseGamma, flipChannels));
}
public void showImage(Image image) {
if(canvas == null) {
startCanvas();
}
if (image == null) {
return;
} else if (needInitialResize) {
int w = (int)Math.round(image.getWidth (null)*initialScale);
int h = (int)Math.round(image.getHeight(null)*initialScale);
setCanvasSize(w, h);
}
this.color = null;
this.image = image;
canvas.paint(null);
}
}
| anadollu/iq4j-javacv | iq4j-javacv/src/main/java/org/iq4j/webcam/CanvasPanel.java | Java | gpl-2.0 | 10,318 |