diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..ac2448a9 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 Mark Friedrich + +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. diff --git a/app/lib/audit.php b/app/lib/audit.php index 4c91740d..f4075542 100644 --- a/app/lib/audit.php +++ b/app/lib/audit.php @@ -2,7 +2,7 @@ /* - Copyright (c) 2009-2016 F3::Factory/Bong Cosca, All rights reserved. + Copyright (c) 2009-2017 F3::Factory/Bong Cosca, All rights reserved. This file is part of the Fat-Free Framework (http://fatfreeframework.com). diff --git a/app/lib/auth.php b/app/lib/auth.php index 56f89ed5..6fd79099 100644 --- a/app/lib/auth.php +++ b/app/lib/auth.php @@ -2,7 +2,7 @@ /* - Copyright (c) 2009-2016 F3::Factory/Bong Cosca, All rights reserved. + Copyright (c) 2009-2017 F3::Factory/Bong Cosca, All rights reserved. This file is part of the Fat-Free Framework (http://fatfreeframework.com). diff --git a/app/lib/base.php b/app/lib/base.php index b5a7bdca..df49ed60 100644 --- a/app/lib/base.php +++ b/app/lib/base.php @@ -2,7 +2,7 @@ /* - Copyright (c) 2009-2016 F3::Factory/Bong Cosca, All rights reserved. + Copyright (c) 2009-2017 F3::Factory/Bong Cosca, All rights reserved. This file is part of the Fat-Free Framework (http://fatfreeframework.com). @@ -45,7 +45,7 @@ final class Base extends Prefab implements ArrayAccess { //@{ Framework details const PACKAGE='Fat-Free Framework', - VERSION='3.6.0-Release'; + VERSION='3.6.1-Dev'; //@} //@{ HTTP status codes (RFC 2616) @@ -96,7 +96,7 @@ final class Base extends Prefab implements ArrayAccess { //! Mapped PHP globals GLOBALS='GET|POST|COOKIE|REQUEST|SESSION|FILES|SERVER|ENV', //! HTTP verbs - VERBS='GET|HEAD|POST|PUT|PATCH|DELETE|CONNECT', + VERBS='GET|HEAD|POST|PUT|PATCH|DELETE|CONNECT|OPTIONS', //! Default directory permissions MODE=0755, //! Syntax highlighting stylesheet @@ -128,6 +128,8 @@ final class Base extends Prefab implements ArrayAccess { $init, //! Language lookup sequence $languages, + //! Mutex locks + $locks=[], //! Default fallback language $fallback='en'; @@ -1009,10 +1011,11 @@ final class Base extends Prefab implements ArrayAccess { $country=@constant('ISO::CC_'.strtolower($parts[1]))) $locale.='-'.$country; } - $locales[]=$locale; + $locale=str_replace('-','_',$locale); $locales[]=$locale.'.'.ini_get('default_charset'); + $locales[]=$locale; } - setlocale(LC_ALL,str_replace('-','_',$locales)); + setlocale(LC_ALL,$locales); return implode(',',$this->languages); } @@ -1160,7 +1163,7 @@ final class Base extends Prefab implements ArrayAccess { return isset($headers['Client-IP'])? $headers['Client-IP']: (isset($headers['X-Forwarded-For'])? - $headers['X-Forwarded-For']: + explode(',',$headers['X-Forwarded-For'])[0]: (isset($_SERVER['REMOTE_ADDR'])? $_SERVER['REMOTE_ADDR']:'')); } @@ -1182,7 +1185,7 @@ final class Base extends Prefab implements ArrayAccess { $trace=array_filter( $trace, function($frame) use($debug) { - return $debug && isset($frame['file']) && + return isset($frame['file']) && ($frame['file']!=__FILE__ || $debug>1) && (empty($frame['function']) || !preg_match('/^(?:(?:trigger|user)_error|'. @@ -1372,7 +1375,7 @@ final class Base extends Prefab implements ArrayAccess { if (($handler=$this->hive['ONREROUTE']) && $this->call($handler,[$url,$permanent])!==FALSE) return; - if ($url[0]=='/') { + if ($url[0]=='/' && (empty($url[1]) || $url[1]!='/')) { $port=$this->hive['PORT']; $port=in_array($port,[80,443])?'':':'.$port; $url=$this->hive['SCHEME'].'://'. @@ -1383,7 +1386,7 @@ final class Base extends Prefab implements ArrayAccess { $this->status($permanent?301:302); die; } - $this->mock('GET '.$url); + $this->mock('GET '.$url.' [cli]'); } /** @@ -1470,7 +1473,7 @@ final class Base extends Prefab implements ArrayAccess { '(?P<\3>[^\/\?]+)', $wild).'\/?$/'.$case.'um',$url,$args); foreach (array_keys($args) as $key) { - if (preg_match('/_\d+/',$key)) { + if (preg_match('/^_\d+$/',$key)) { if (empty($args['*'])) $args['*']=$args[$key]; else { @@ -1509,7 +1512,7 @@ final class Base extends Prefab implements ArrayAccess { array_multisort($paths,SORT_DESC,$keys,$vals); $this->hive['ROUTES']=array_combine($keys,$vals); // Convert to BASE-relative URL - $req=$this->rel(urldecode($this->hive['PATH'])); + $req=urldecode($this->hive['PATH']); if ($cors=(isset($this->hive['HEADERS']['Origin']) && $this->hive['CORS']['origin'])) { $cors=$this->hive['CORS']; @@ -1529,8 +1532,7 @@ final class Base extends Prefab implements ArrayAccess { $route=$routes[$ptr]; if (!$route) continue; - if ($this->hive['VERB']!='OPTIONS' && - isset($route[$this->hive['VERB']])) { + if (isset($route[$this->hive['VERB']])) { if ($this->hive['VERB']=='GET' && preg_match('/.+\/$/',$this->hive['PATH'])) $this->reroute(substr($this->hive['PATH'],0,-1). @@ -1622,7 +1624,8 @@ final class Base extends Prefab implements ArrayAccess { else echo $body; } - return $result; + if ($result || $this->hive['VERB']!='OPTIONS') + return $result; } $allowed=array_merge($allowed,array_keys($route)); } @@ -1923,9 +1926,11 @@ final class Base extends Prefab implements ArrayAccess { @unlink($lock); while (!($handle=@fopen($lock,'x')) && !connection_aborted()) usleep(mt_rand(0,100)); + $this->locks[$id]=$lock; $out=$this->call($func,$args); fclose($handle); @unlink($lock); + unset($this->locks[$id]); return $out; } @@ -2025,6 +2030,8 @@ final class Base extends Prefab implements ArrayAccess { if (!($error=error_get_last()) && session_status()==PHP_SESSION_ACTIVE) session_commit(); + foreach ($this->locks as $lock) + @unlink($lock); $handler=$this->hive['UNLOAD']; if ((!$handler || $this->call($handler,$this)===FALSE) && $error && in_array($error['type'], @@ -2236,8 +2243,10 @@ final class Base extends Prefab implements ArrayAccess { 'httponly'=>TRUE ] ); - $port=0; - if (isset($_SERVER['SERVER_PORT'])) + $port=80; + if (isset($headers['X-Forwarded-Port'])) + $port=$headers['X-Forwarded-Port']; + elseif (isset($_SERVER['SERVER_PORT'])) $port=$_SERVER['SERVER_PORT']; // Default configuration $this->hive+=[ @@ -2295,8 +2304,8 @@ final class Base extends Prefab implements ArrayAccess { 'QUIET'=>FALSE, 'RAW'=>FALSE, 'REALM'=>$scheme.'://'.$_SERVER['SERVER_NAME']. - ($port && $port!=80 && $port!=443? - (':'.$port):'').$_SERVER['REQUEST_URI'], + ($port && !in_array($port,[80,443])?(':'.$port):''). + $_SERVER['REQUEST_URI'], 'RESPONSE'=>'', 'ROOT'=>$_SERVER['DOCUMENT_ROOT'], 'ROUTES'=>[], @@ -2375,6 +2384,9 @@ class Cache extends Prefab { case 'memcache': $raw=memcache_get($this->ref,$ndx); break; + case 'memcached': + $raw=$this->ref->get($ndx); + break; case 'wincache': $raw=wincache_ucache_get($ndx); break; @@ -2420,6 +2432,8 @@ class Cache extends Prefab { return $this->ref->set($ndx,$data, $ttl ? ['ex'=>$ttl] : []); case 'memcache': return memcache_set($this->ref,$ndx,$data,0,$ttl); + case 'memcached': + return $this->ref->set($ndx,$data,$ttl); case 'wincache': return wincache_ucache_set($ndx,$data,$ttl); case 'xcache': @@ -2457,6 +2471,8 @@ class Cache extends Prefab { return $this->ref->del($ndx); case 'memcache': return memcache_delete($this->ref,$ndx); + case 'memcached': + return $this->ref->delete($ndx); case 'wincache': return wincache_ucache_delete($ndx); case 'xcache': @@ -2471,12 +2487,11 @@ class Cache extends Prefab { * Clear contents of cache backend * @return bool * @param $suffix string - * @param $lifetime int **/ - function reset($suffix=NULL,$lifetime=0) { + function reset($suffix=NULL) { if (!$this->dsn) return TRUE; - $regex='/'.preg_quote($this->prefix.'.','/').'.+?'. + $regex='/'.preg_quote($this->prefix.'.','/').'.+'. preg_quote($suffix,'/').'/'; $parts=explode('=',$this->dsn,2); switch ($parts[0]) { @@ -2489,19 +2504,15 @@ class Cache extends Prefab { $mtkey=array_key_exists('mtime',$info['cache_list'][0])? 'mtime':'modification_time'; foreach ($info['cache_list'] as $item) - if (preg_match($regex,$item[$key]) && - $item[$mtkey]+$lifetimeref->keys($this->prefix.'.*'.$suffix); - foreach($keys as $key) { - $val=$fw->unserialize($this->ref->get($key)); - if ($val[1]+$lifetimeref->del($key); - } + foreach($keys as $key) + $this->ref->del($key); return TRUE; case 'memcache': $fw=Base::instance(); @@ -2513,17 +2524,20 @@ class Cache extends Prefab { $this->ref,'cachedump',$id) as $data) if (is_array($data)) foreach (array_keys($data) as $key) - if (preg_match($regex,$key) && - ($val=$fw->unserialize(memcache_get($this->ref,$key))) && - $val[1]+$lifetimeref,$key); return TRUE; + case 'memcached': + $fw=Base::instance(); + foreach ($this->ref->getallkeys() as $key) + if (preg_match($regex,$key)) + $this->ref->delete($key); + return TRUE; case 'wincache': $info=wincache_ucache_info(); foreach ($info['ucache_entries'] as $item) - if (preg_match($regex,$item['key_name']) && - $item['use_time']+$lifetimeprefix.'.'); @@ -2531,8 +2545,7 @@ class Cache extends Prefab { case 'folder': if ($glob=@glob($parts[1].'*')) foreach ($glob as $file) - if (preg_match($regex,basename($file)) && - filemtime($file)+$lifetimeref,$host,$port); } + elseif (preg_match('/^memcached=(.+)/',$dsn,$parts) && + extension_loaded('memcached')) + foreach ($fw->split($parts[1]) as $server) { + list($host,$port)=explode(':',$server)+[1=>11211]; + if (empty($this->ref)) + $this->ref=new Memcached(); + $this->ref->addServer($host,$port); + } if (empty($this->ref) && !preg_match('/^folder\h*=/',$dsn)) $dsn=($grep=preg_grep('/^(apc|wincache|xcache)/', array_map('strtolower',get_loaded_extensions())))? @@ -2631,28 +2652,50 @@ class View extends Prefab { ); } + /** + * Send resource to browser using HTTP/2 server push + * @return string + * @param $file string + **/ + function push($file) { + $fw=Base::instance(); + $hive=$fw->hive(); + if ($hive['SCHEME']=='https') { + $base=''; + if (!preg_match('/^[.\/]/',$file)) + $base=$hive['BASE'].'/'; + if (preg_match('/'.$key.'$/',$file)) + header('Link: '.'<'.$base.$file.'>; '.'rel=preload',FALSE); + } + return $file; + } + /** * Create sandbox for template execution * @return string * @param $hive array + * @param $mime string **/ - protected function sandbox(array $hive=NULL) { - $this->level++; + protected function sandbox(array $hive=NULL,$mime=NULL) { $fw=Base::instance(); $implicit=FALSE; if (is_null($hive)) { $implicit=TRUE; $hive=$fw->hive(); } - if ($this->level<2 || $implicit) { + if ($this->level<1 || $implicit) { + if (!$hive['CLI'] && !headers_sent() && + !preg_grep ('/^Content-Type:/',headers_list())) + header('Content-Type: '.($mime?:'text/html').'; '. + 'charset='.$fw->get('ENCODING')); if ($fw->get('ESCAPE')) $hive=$this->esc($hive); if (isset($hive['ALIASES'])) $hive['ALIASES']=$fw->build($hive['ALIASES']); } - unset($fw,$implicit); extract($hive); - unset($hive); + unset($fw,$hive,$implicit,$mime); + $this->level++; ob_start(); require($this->view); $this->level--; @@ -2667,21 +2710,18 @@ class View extends Prefab { * @param $hive array * @param $ttl int **/ - function render($file,$mime='text/html',array $hive=NULL,$ttl=0) { + function render($file,$mime=NULL,array $hive=NULL,$ttl=0) { $fw=Base::instance(); $cache=Cache::instance(); if ($cache->exists($hash=$fw->hash($file),$data)) return $data; - foreach ($fw->split($fw->get('UI').';./') as $dir) + foreach ($fw->split($fw->get('UI')) as $dir) if (is_file($this->view=$fw->fixslashes($dir.$file))) { if (isset($_COOKIE[session_name()]) && !headers_sent() && session_status()!=PHP_SESSION_ACTIVE) session_start(); $fw->sync('SESSION'); - if ($mime && !$fw->get('CLI') && !headers_sent()) - header('Content-Type: '.$mime.'; '. - 'charset='.$fw->get('ENCODING')); - $data=$this->sandbox($hive); + $data=$this->sandbox($hive,$mime); if(isset($this->trigger['afterrender'])) foreach($this->trigger['afterrender'] as $func) $data=$fw->call($func,$data); @@ -2706,12 +2746,11 @@ class View extends Prefab { class Preview extends View { protected - //! MIME type - $mime, //! token filter $filter=[ 'esc'=>'$this->esc', 'raw'=>'$this->raw', + 'push'=>'$this->push', 'alias'=>'\Base::instance()->alias', 'format'=>'\Base::instance()->format' ]; @@ -2804,10 +2843,6 @@ class Preview extends View { function render($file,$mime=NULL,array $hive=NULL,$ttl=0) { $fw=Base::instance(); $cache=Cache::instance(); - if ($mime) - $this->mime=$mime; - elseif (!$this->mime) - $this->mime='text/html'; if (!is_dir($tmp=$fw->get('TEMP'))) mkdir($tmp,Base::MODE,TRUE); foreach ($fw->split($fw->get('UI')) as $dir) { @@ -2830,10 +2865,7 @@ class Preview extends View { !headers_sent() && session_status()!=PHP_SESSION_ACTIVE) session_start(); $fw->sync('SESSION'); - if (!$fw->get('CLI') && !headers_sent()) - header('Content-Type: '.$this->mime.'; '. - 'charset='.$fw->get('ENCODING')); - $data=$this->sandbox($hive); + $data=$this->sandbox($hive,$mime); if(isset($this->trigger['afterrender'])) foreach ($this->trigger['afterrender'] as $func) $data = $fw->call($func, $data); diff --git a/app/lib/basket.php b/app/lib/basket.php index ffb498e7..20a01b74 100644 --- a/app/lib/basket.php +++ b/app/lib/basket.php @@ -2,7 +2,7 @@ /* - Copyright (c) 2009-2016 F3::Factory/Bong Cosca, All rights reserved. + Copyright (c) 2009-2017 F3::Factory/Bong Cosca, All rights reserved. This file is part of the Fat-Free Framework (http://fatfreeframework.com). diff --git a/app/lib/bcrypt.php b/app/lib/bcrypt.php index 2f44d39b..23554719 100644 --- a/app/lib/bcrypt.php +++ b/app/lib/bcrypt.php @@ -1,9 +1,7 @@ . * -* @deprecated use http://php.net/manual/en/ref.password.php instead (PHP 5.5+ only) **/ +/** +* Lightweight password hashing library (PHP 5.5+ only) +* @deprecated Use http://php.net/manual/en/ref.password.php instead +**/ class Bcrypt extends Prefab { //@{ Error messages @@ -52,8 +53,6 @@ class Bcrypt extends Prefab { else { $raw=16; $iv=''; - if (extension_loaded('mcrypt')) - $iv=mcrypt_create_iv($raw,MCRYPT_DEV_URANDOM); if (!$iv && extension_loaded('openssl')) $iv=openssl_random_pseudo_bytes($raw); if (!$iv) diff --git a/app/lib/cli/ws.php b/app/lib/cli/ws.php index 390fa733..c11e8add 100644 --- a/app/lib/cli/ws.php +++ b/app/lib/cli/ws.php @@ -2,7 +2,7 @@ /* - Copyright (c) 2009-2016 F3::Factory/Bong Cosca, All rights reserved. + Copyright (c) 2009-2017 F3::Factory/Bong Cosca, All rights reserved. This file is part of the Fat-Free Framework (http://fatfreeframework.com). diff --git a/app/lib/composer.json b/app/lib/composer.json new file mode 100644 index 00000000..01bdca12 --- /dev/null +++ b/app/lib/composer.json @@ -0,0 +1,12 @@ +{ + "name": "bcosca/fatfree-core", + "description": "A powerful yet easy-to-use PHP micro-framework designed to help you build dynamic and robust Web applications - fast!", + "homepage": "http://fatfreeframework.com/", + "license": "GPL-3.0", + "require": { + "php": ">=5.4" + }, + "autoload": { + "classmap": ["."] + } +} diff --git a/app/lib/db/cortex.php b/app/lib/db/cortex.php index 78f035fb..18120ab8 100644 --- a/app/lib/db/cortex.php +++ b/app/lib/db/cortex.php @@ -18,7 +18,7 @@ * https://github.com/ikkez/F3-Sugar/ * * @package DB - * @version 1.4.1 + * @version 1.4.2-dev * @date 29.01.2016 * @since 24.04.2012 */ @@ -28,2611 +28,2668 @@ use DB\SQL\Schema; class Cortex extends Cursor { - protected - // config - $db, // DB object [ \DB\SQL, \DB\Jig, \DB\Mongo ] - $table, // selected table, string - $fluid, // fluid sql schema mode, boolean - $fieldConf, // field configuration, array - $ttl, // default mapper schema ttl - $rel_ttl, // default mapper rel ttl - $primary, // SQL table primary key - // behaviour - $smartLoading, // intelligent lazy eager loading, boolean - $standardiseID, // return standardized '_id' field for SQL when casting - // internals - $dbsType, // mapper engine type [jig, sql, mongo] - $fieldsCache, // relation field cache - $saveCsd, // mm rel save cascade - $collection, // collection - $relFilter, // filter for loading related models - $hasCond, // IDs of records the next find should have - $whitelist, // restrict to these fields - $relWhitelist, // restrict relations to these fields - $grp_stack, // stack of group conditions - $countFields, // relational counter buffer - $preBinds, // bind values to be prepended to $filter - $vFields, // virtual fields buffer - $_ttl; // rel_ttl overwrite + protected + // config + $db, // DB object [ \DB\SQL, \DB\Jig, \DB\Mongo ] + $table, // selected table, string + $fluid, // fluid sql schema mode, boolean + $fieldConf, // field configuration, array + $ttl, // default mapper schema ttl + $rel_ttl, // default mapper rel ttl + $primary, // SQL table primary key + // behaviour + $smartLoading, // intelligent lazy eager loading, boolean + $standardiseID, // return standardized '_id' field for SQL when casting + // internals + $dbsType, // mapper engine type [jig, sql, mongo] + $fieldsCache, // relation field cache + $saveCsd, // mm rel save cascade + $collection, // collection + $relFilter, // filter for loading related models + $hasCond, // IDs of records the next find should have + $whitelist, // restrict to these fields + $relWhitelist, // restrict relations to these fields + $grp_stack, // stack of group conditions + $countFields, // relational counter buffer + $preBinds, // bind values to be prepended to $filter + $vFields, // virtual fields buffer + $_ttl; // rel_ttl overwrite - /** @var Cursor */ - protected $mapper; + /** @var Cursor */ + protected $mapper; - /** @var CortexQueryParser */ - protected $queryParser; + /** @var CortexQueryParser */ + protected $queryParser; - static - $init = false; // just init without mapper + static + $init = false; // just init without mapper - const - // special datatypes - DT_SERIALIZED = 'SERIALIZED', - DT_JSON = 'JSON', + const + // special datatypes + DT_SERIALIZED = 'SERIALIZED', + DT_JSON = 'JSON', - // error messages - E_ARRAY_DATATYPE = 'Unable to save an Array in field %s. Use DT_SERIALIZED or DT_JSON.', - E_CONNECTION = 'No valid DB Connection given.', - E_NO_TABLE = 'No table specified.', - E_UNKNOWN_DB_ENGINE = 'This unknown DB system is not supported: %s', - E_FIELD_SETUP = 'No field setup defined', - E_UNKNOWN_FIELD = 'Field %s does not exist in %s.', - E_INVALID_RELATION_OBJECT = 'You can only save hydrated mapper objects', - E_NULLABLE_COLLISION = 'Unable to set NULL to the NOT NULLABLE field: %s', - E_WRONG_RELATION_CLASS = 'Relations only works with Cortex objects', - E_MM_REL_VALUE = 'Invalid value for many field "%s". Expecting null, split-able string, hydrated mapper object, or array of mapper objects.', - E_MM_REL_CLASS = 'Mismatching m:m relation config from class `%s` to `%s`.', - E_MM_REL_FIELD = 'Mismatching m:m relation keys from `%s` to `%s`.', - E_REL_CONF_INC = 'Incomplete relation config for `%s`. Linked key is missing.', - E_MISSING_REL_CONF = 'Cannot create related model. Specify a model name or relConf array.', - E_HAS_COND = 'Cannot use a "has"-filter on a non-bidirectional relation field'; + // error messages + E_ARRAY_DATATYPE = 'Unable to save an Array in field %s. Use DT_SERIALIZED or DT_JSON.', + E_CONNECTION = 'No valid DB Connection given.', + E_NO_TABLE = 'No table specified.', + E_UNKNOWN_DB_ENGINE = 'This unknown DB system is not supported: %s', + E_FIELD_SETUP = 'No field setup defined', + E_UNKNOWN_FIELD = 'Field %s does not exist in %s.', + E_INVALID_RELATION_OBJECT = 'You can only save hydrated mapper objects', + E_NULLABLE_COLLISION = 'Unable to set NULL to the NOT NULLABLE field: %s', + E_WRONG_RELATION_CLASS = 'Relations only works with Cortex objects', + E_MM_REL_VALUE = 'Invalid value for many field "%s". Expecting null, split-able string, hydrated mapper object, or array of mapper objects.', + E_MM_REL_CLASS = 'Mismatching m:m relation config from class `%s` to `%s`.', + E_MM_REL_FIELD = 'Mismatching m:m relation keys from `%s` to `%s`.', + E_REL_CONF_INC = 'Incomplete relation config for `%s`. Linked key is missing.', + E_MISSING_REL_CONF = 'Cannot create related model. Specify a model name or relConf array.', + E_HAS_COND = 'Cannot use a "has"-filter on a non-bidirectional relation field'; - /** - * init the ORM, based on given DBS - * @param null|object $db - * @param string $table - * @param null|bool $fluid - * @param int $ttl - */ - public function __construct($db = NULL, $table = NULL, $fluid = NULL, $ttl = 0) - { - if (!is_null($fluid)) - $this->fluid = $fluid; - if (!is_object($this->db=(is_string($db=($db?:$this->db))?\Base::instance()->get($db):$db))) - trigger_error(self::E_CONNECTION); - if ($this->db instanceof Jig) - $this->dbsType = 'jig'; - elseif ($this->db instanceof SQL) - $this->dbsType = 'sql'; - elseif ($this->db instanceof Mongo) - $this->dbsType = 'mongo'; - if ($table) - $this->table = $table; - if ($this->dbsType != 'sql') - $this->primary = '_id'; - elseif (!$this->primary) - $this->primary = 'id'; - $this->table = $this->getTable(); - if (!$this->table) - trigger_error(self::E_NO_TABLE); - $this->ttl = $ttl ?: 60; - if (!$this->rel_ttl) - $this->rel_ttl = 0; - $this->_ttl = $this->rel_ttl ?: 0; - if (static::$init == TRUE) return; - if ($this->fluid) - static::setup($this->db,$this->table,array()); - $this->initMapper(); - } + /** + * init the ORM, based on given DBS + * @param null|object $db + * @param string $table + * @param null|bool $fluid + * @param int $ttl + */ + public function __construct($db = NULL, $table = NULL, $fluid = NULL, $ttl = 0) { + if (!is_null($fluid)) + $this->fluid = $fluid; + if (!is_object($this->db=(is_string($db=($db?:$this->db))?\Base::instance()->get($db):$db))) + trigger_error(self::E_CONNECTION,E_USER_ERROR); + if ($this->db instanceof Jig) + $this->dbsType = 'jig'; + elseif ($this->db instanceof SQL) + $this->dbsType = 'sql'; + elseif ($this->db instanceof Mongo) + $this->dbsType = 'mongo'; + if ($table) + $this->table = $table; + if ($this->dbsType != 'sql') + $this->primary = '_id'; + elseif (!$this->primary) + $this->primary = 'id'; + $this->table = $this->getTable(); + if (!$this->table) + trigger_error(self::E_NO_TABLE,E_USER_ERROR); + $this->ttl = $ttl ?: 60; + if (!$this->rel_ttl) + $this->rel_ttl = 0; + $this->_ttl = $this->rel_ttl ?: 0; + if (static::$init == TRUE) return; + if ($this->fluid) + static::setup($this->db,$this->table,array()); + $this->initMapper(); + } - /** - * create mapper instance - */ - public function initMapper() - { - switch ($this->dbsType) { - case 'jig': - $this->mapper = new Jig\Mapper($this->db, $this->table); - break; - case 'sql': - $this->mapper = new SQL\Mapper($this->db, $this->table, $this->whitelist, - ($this->fluid)?0:$this->ttl); - break; - case 'mongo': - $this->mapper = new Mongo\Mapper($this->db, $this->table); - break; - default: - trigger_error(sprintf(self::E_UNKNOWN_DB_ENGINE,$this->dbsType)); - } - $this->queryParser = CortexQueryParser::instance(); - $this->reset(); - $this->clearFilter(); - $f3 = \Base::instance(); - $this->smartLoading = $f3->exists('CORTEX.smartLoading') ? - $f3->get('CORTEX.smartLoading') : TRUE; - $this->standardiseID = $f3->exists('CORTEX.standardiseID') ? - $f3->get('CORTEX.standardiseID') : TRUE; - if(!empty($this->fieldConf)) - foreach($this->fieldConf as &$conf) { - $conf=static::resolveRelationConf($conf); - unset($conf); - } - } + /** + * create mapper instance + */ + public function initMapper() { + switch ($this->dbsType) { + case 'jig': + $this->mapper = new Jig\Mapper($this->db, $this->table); + break; + case 'sql': + $this->mapper = new SQL\Mapper($this->db, $this->table, $this->whitelist, + ($this->fluid)?0:$this->ttl); + break; + case 'mongo': + $this->mapper = new Mongo\Mapper($this->db, $this->table); + break; + default: + trigger_error(sprintf(self::E_UNKNOWN_DB_ENGINE,$this->dbsType),E_USER_ERROR); + } + $this->queryParser = CortexQueryParser::instance(); + $this->reset(); + $this->clearFilter(); + $f3 = \Base::instance(); + $this->smartLoading = $f3->exists('CORTEX.smartLoading') ? + $f3->get('CORTEX.smartLoading') : TRUE; + $this->standardiseID = $f3->exists('CORTEX.standardiseID') ? + $f3->get('CORTEX.standardiseID') : TRUE; + if(!empty($this->fieldConf)) + foreach($this->fieldConf as &$conf) { + $conf=static::resolveRelationConf($conf); + unset($conf); + } + } - /** - * get fields or set whitelist / blacklist of fields - * @param array $fields - * @param bool $exclude - * @return array - */ - public function fields(array $fields=array(), $exclude=false) - { - if ($fields) - // collect restricted fields for related mappers - foreach($fields as $i=>$val) - if(is_int(strpos($val,'.'))) { - list($key, $relField) = explode('.',$val,2); - $this->relWhitelist[$key][(int)$exclude][] = $relField; - unset($fields[$i]); - $fields[] = $key; - } - $fields = array_unique($fields); - $schema = $this->whitelist ?: $this->mapper->fields(); - if (!$schema && !$this->dbsType != 'sql' && $this->dry()) { - $schema = $this->load()->mapper->fields(); - $this->reset(); - } - if (!$this->whitelist && $this->fieldConf) - $schema=array_unique(array_merge($schema,array_keys($this->fieldConf))); - if (!$fields || empty($fields)) - return $schema; - elseif ($exclude) { - $this->whitelist=array_diff($schema,$fields); - } else - $this->whitelist=$fields; - $id=$this->dbsType=='sql'?$this->primary:'_id'; - if(!in_array($id,$this->whitelist)) - $this->whitelist[]=$id; - $this->initMapper(); - return $this->whitelist; - } + /** + * get fields or set whitelist / blacklist of fields + * @param array $fields + * @param bool $exclude + * @return array + */ + public function fields(array $fields=array(), $exclude=false) { + if ($fields) + // collect restricted fields for related mappers + foreach($fields as $i=>$val) + if(is_int(strpos($val,'.'))) { + list($key, $relField) = explode('.',$val,2); + $this->relWhitelist[$key][(int)$exclude][] = $relField; + unset($fields[$i]); + $fields[] = $key; + } + $fields = array_unique($fields); + $schema = $this->whitelist ?: $this->mapper->fields(); + if (!$schema && !$this->dbsType != 'sql' && $this->dry()) { + $schema = $this->load()->mapper->fields(); + $this->reset(); + } + if (!$this->whitelist && $this->fieldConf) + $schema=array_unique(array_merge($schema,array_keys($this->fieldConf))); + if (!$fields || empty($fields)) + return $schema; + elseif ($exclude) { + $this->whitelist=array_diff($schema,$fields); + } else + $this->whitelist=$fields; + $id=$this->dbsType=='sql'?$this->primary:'_id'; + if(!in_array($id,$this->whitelist)) + $this->whitelist[]=$id; + $this->initMapper(); + return $this->whitelist; + } - /** - * set model definition - * config example: - * array('title' => array( - * 'type' => \DB\SQL\Schema::DT_TEXT, - * 'default' => 'new record title', - * 'nullable' => true - * ) - * '...' => ... - * ) - * @param array $config - */ - function setFieldConfiguration(array $config) - { - $this->fieldConf = $config; - $this->reset(); - } + /** + * set model definition + * config example: + * array('title' => array( + * 'type' => \DB\SQL\Schema::DT_TEXT, + * 'default' => 'new record title', + * 'nullable' => true + * ) + * '...' => ... + * ) + * @param array $config + */ + function setFieldConfiguration(array $config) { + $this->fieldConf = $config; + $this->reset(); + } - /** - * returns model field conf array - * @return array|null - */ - public function getFieldConfiguration() - { - return $this->fieldConf; - } + /** + * returns model field conf array + * @return array|null + */ + public function getFieldConfiguration() { + return $this->fieldConf; + } - /** - * kick start to just fetch the config - * @return array - */ - static public function resolveConfiguration() - { - static::$init=true; - $self = new static(); - static::$init=false; - $conf = array ( - 'table'=>$self->getTable(), - 'fieldConf'=>$self->getFieldConfiguration(), - 'db'=>$self->db, - 'fluid'=>$self->fluid, - 'primary'=>$self->primary, - ); - unset($self); - return $conf; - } + /** + * kick start to just fetch the config + * @return array + */ + static public function resolveConfiguration() { + static::$init=true; + $self = new static(); + static::$init=false; + $conf = array ( + 'table'=>$self->getTable(), + 'fieldConf'=>$self->getFieldConfiguration(), + 'db'=>$self->db, + 'fluid'=>$self->fluid, + 'primary'=>$self->primary, + ); + unset($self); + return $conf; + } - /** - * give this model a reference to the collection it is part of - * @param CortexCollection $cx - */ - public function addToCollection($cx) { - $this->collection = $cx; - } + /** + * give this model a reference to the collection it is part of + * @param CortexCollection $cx + */ + public function addToCollection($cx) { + $this->collection = $cx; + } - /** - * returns the collection where this model lives in - * @return CortexCollection - */ - protected function getCollection() - { - return ($this->collection && $this->smartLoading) - ? $this->collection : false; - } + /** + * returns the collection where this model lives in + * @return CortexCollection + */ + protected function getCollection() { + return ($this->collection && $this->smartLoading) + ? $this->collection : false; + } - /** - * returns model table name - * @return string - */ - public function getTable() - { - if (!$this->table && ($this->fluid || static::$init)) - $this->table = strtolower(get_class($this)); - return $this->table; - } + /** + * returns model table name + * @return string + */ + public function getTable() { + if (!$this->table && ($this->fluid || static::$init)) + $this->table = strtolower(get_class($this)); + return $this->table; + } - /** - * setup / update table schema - * @static - * @param $db - * @param $table - * @param $fields - * @return bool - */ - static public function setup($db=null, $table=null, $fields=null) - { - /** @var Cortex $self */ - $self = get_called_class(); - if (is_null($db) || is_null($table) || is_null($fields)) - $df = $self::resolveConfiguration(); - if (!is_object($db=(is_string($db=($db?:$df['db']))?\Base::instance()->get($db):$db))) - trigger_error(self::E_CONNECTION); - if (strlen($table=$table?:$df['table'])==0) - trigger_error(self::E_NO_TABLE); - if (is_null($fields)) - if (!empty($df['fieldConf'])) - $fields = $df['fieldConf']; - elseif(!$df['fluid']) { - trigger_error(self::E_FIELD_SETUP); - return false; - } else - $fields = array(); - if ($db instanceof SQL) { - $schema = new Schema($db); - // prepare field configuration - if (!empty($fields)) - foreach($fields as $key => &$field) { - // fetch relation field types - $field = static::resolveRelationConf($field); - // check m:m relation - if (array_key_exists('has-many', $field)) { - // m:m relation conf [class,to-key,from-key] - if (is_array($relConf = $field['has-many'])) { - $rel = $relConf[0]::resolveConfiguration(); - // check if foreign conf matches m:m - if (array_key_exists($relConf[1],$rel['fieldConf']) - && !is_null($rel['fieldConf'][$relConf[1]]) - && $relConf['hasRel'] == 'has-many') { - // compute mm table name - $mmTable = isset($relConf[2]) ? $relConf[2] : - static::getMMTableName( - $rel['table'], $relConf[1], $table, $key, - $rel['fieldConf'][$relConf[1]]['has-many']); - if (!in_array($mmTable,$schema->getTables())) { - $mmt = $schema->createTable($mmTable); - $mmt->addColumn($relConf[1])->type($relConf['relFieldType']); - $mmt->addColumn($key)->type($field['type']); - $index = array($relConf[1],$key); - sort($index); - $mmt->addIndex($index); - $mmt->build(); - } - } - } - unset($fields[$key]); - continue; - } - // skip virtual fields with no type - if (!array_key_exists('type', $field)) { - unset($fields[$key]); - continue; - } - // transform array fields - if (in_array($field['type'], array(self::DT_JSON, self::DT_SERIALIZED))) - $field['type']=$schema::DT_TEXT; - // defaults values - if (!array_key_exists('nullable', $field)) - $field['nullable'] = true; - unset($field); - } - if (!in_array($table, $schema->getTables())) { - // create table - $table = $schema->createTable($table); - foreach ($fields as $field_key => $field_conf) - $table->addColumn($field_key, $field_conf); - if(isset($df) && $df['primary'] != 'id') { - $table->addColumn($df['primary'])->type_int(); - $table->primary($df['primary']); - } - $table->build(); - } else { - // add missing fields - $table = $schema->alterTable($table); - $existingCols = $table->getCols(); - foreach ($fields as $field_key => $field_conf) - if (!in_array($field_key, $existingCols)) - $table->addColumn($field_key, $field_conf); - // remove unused fields - // foreach ($existingCols as $col) - // if (!in_array($col, array_keys($fields)) && $col!='id') - // $table->dropColumn($col); - $table->build(); - } - } - return true; - } + /** + * setup / update table schema + * @static + * @param $db + * @param $table + * @param $fields + * @return bool + */ + static public function setup($db=null, $table=null, $fields=null) { + /** @var Cortex $self */ + $self = get_called_class(); + if (is_null($db) || is_null($table) || is_null($fields)) + $df = $self::resolveConfiguration(); + if (!is_object($db=(is_string($db=($db?:$df['db']))?\Base::instance()->get($db):$db))) + trigger_error(self::E_CONNECTION,E_USER_ERROR); + if (strlen($table=$table?:$df['table'])==0) + trigger_error(self::E_NO_TABLE,E_USER_ERROR); + if (is_null($fields)) + if (!empty($df['fieldConf'])) + $fields = $df['fieldConf']; + elseif(!$df['fluid']) { + trigger_error(self::E_FIELD_SETUP,E_USER_ERROR); + return false; + } else + $fields = array(); + if ($db instanceof SQL) { + $schema = new Schema($db); + // prepare field configuration + if (!empty($fields)) + foreach($fields as $key => &$field) { + // fetch relation field types + $field = static::resolveRelationConf($field); + // check m:m relation + if (array_key_exists('has-many', $field)) { + // m:m relation conf [class,to-key,from-key] + if (is_array($relConf = $field['has-many'])) { + $rel = $relConf[0]::resolveConfiguration(); + // check if foreign conf matches m:m + if (array_key_exists($relConf[1],$rel['fieldConf']) + && !is_null($rel['fieldConf'][$relConf[1]]) + && $relConf['hasRel'] == 'has-many') { + // compute mm table name + $mmTable = isset($relConf[2]) ? $relConf[2] : + static::getMMTableName($rel['table'], $relConf['relField'], + $table, $key, $rel['fieldConf'][$relConf[1]]['has-many']); + if (!in_array($mmTable,$schema->getTables())) { + $mmt = $schema->createTable($mmTable); + $relField = $relConf['relField'].($relConf['isSelf']?'_ref':''); + $mmt->addColumn($relField)->type($relConf['relFieldType']); + $mmt->addColumn($key)->type($field['type']); + $index = array($relField,$key); + sort($index); + $mmt->addIndex($index); + $mmt->build(); + } + } + } + unset($fields[$key]); + continue; + } + // skip virtual fields with no type + if (!array_key_exists('type', $field)) { + unset($fields[$key]); + continue; + } + // transform array fields + if (in_array($field['type'], array(self::DT_JSON, self::DT_SERIALIZED))) + $field['type']=$schema::DT_TEXT; + // defaults values + if (!array_key_exists('nullable', $field)) + $field['nullable'] = true; + unset($field); + } + if (!in_array($table, $schema->getTables())) { + // create table + $table = $schema->createTable($table); + foreach ($fields as $field_key => $field_conf) + $table->addColumn($field_key, $field_conf); + if(isset($df) && $df['primary'] != 'id') { + $table->addColumn($df['primary'])->type_int(); + $table->primary($df['primary']); + } + $table->build(); + } else { + // add missing fields + $table = $schema->alterTable($table); + $existingCols = $table->getCols(); + foreach ($fields as $field_key => $field_conf) + if (!in_array($field_key, $existingCols)) + $table->addColumn($field_key, $field_conf); + // remove unused fields + // foreach ($existingCols as $col) + // if (!in_array($col, array_keys($fields)) && $col!='id') + // $table->dropColumn($col); + $table->build(); + } + } + return true; + } - /** - * erase all model data, handle with care - * @param null $db - * @param null $table - */ - static public function setdown($db=null, $table=null) - { - $self = get_called_class(); - if (is_null($db) || is_null($table)) - $df = $self::resolveConfiguration(); - if (!is_object($db=(is_string($db=($db?:$df['db']))?\Base::instance()->get($db):$db))) - trigger_error(self::E_CONNECTION); - if (strlen($table=strtolower($table?:$df['table']))==0) - trigger_error(self::E_NO_TABLE); - if (isset($df) && !empty($df['fieldConf'])) - $fields = $df['fieldConf']; - else - $fields = array(); - $deletable = array(); - $deletable[] = $table; - foreach ($fields as $key => $field) { - $field = static::resolveRelationConf($field); - if (array_key_exists('has-many',$field)) { - if (!is_array($relConf = $field['has-many'])) - continue; - $rel = $relConf[0]::resolveConfiguration(); - // check if foreign conf matches m:m - if (array_key_exists($relConf[1],$rel['fieldConf']) && !is_null($relConf[1]) - && key($rel['fieldConf'][$relConf[1]]) == 'has-many') { - // compute mm table name - $deletable[] = isset($relConf[2]) ? $relConf[2] : - static::getMMTableName( - $rel['table'], $relConf[1], $table, $key, - $rel['fieldConf'][$relConf[1]]['has-many']); - } - } - } + /** + * erase all model data, handle with care + * @param null $db + * @param null $table + */ + static public function setdown($db=null, $table=null) { + $self = get_called_class(); + if (is_null($db) || is_null($table)) + $df = $self::resolveConfiguration(); + if (!is_object($db=(is_string($db=($db?:$df['db']))?\Base::instance()->get($db):$db))) + trigger_error(self::E_CONNECTION,E_USER_ERROR); + if (strlen($table=strtolower($table?:$df['table']))==0) + trigger_error(self::E_NO_TABLE,E_USER_ERROR); + if (isset($df) && !empty($df['fieldConf'])) + $fields = $df['fieldConf']; + else + $fields = array(); + $deletable = array(); + $deletable[] = $table; + foreach ($fields as $key => $field) { + $field = static::resolveRelationConf($field); + if (array_key_exists('has-many',$field)) { + if (!is_array($relConf = $field['has-many'])) + continue; + $rel = $relConf[0]::resolveConfiguration(); + // check if foreign conf matches m:m + if (array_key_exists($relConf[1],$rel['fieldConf']) && !is_null($relConf[1]) + && key($rel['fieldConf'][$relConf[1]]) == 'has-many') { + // compute mm table name + $deletable[] = isset($relConf[2]) ? $relConf[2] : + static::getMMTableName( + $rel['table'], $relConf[1], $table, $key, + $rel['fieldConf'][$relConf[1]]['has-many']); + } + } + } - if($db instanceof Jig) { - /** @var Jig $db */ - $dir = $db->dir(); - foreach ($deletable as $item) - if(file_exists($dir.$item)) - unlink($dir.$item); - } elseif($db instanceof SQL) { - /** @var SQL $db */ - $schema = new Schema($db); - $tables = $schema->getTables(); - foreach ($deletable as $item) - if(in_array($item, $tables)) - $schema->dropTable($item); - } elseif($db instanceof Mongo) { - /** @var Mongo $db */ - foreach ($deletable as $item) - $db->selectCollection($item)->drop(); - } - } + if($db instanceof Jig) { + /** @var Jig $db */ + $dir = $db->dir(); + foreach ($deletable as $item) + if(file_exists($dir.$item)) + unlink($dir.$item); + } elseif($db instanceof SQL) { + /** @var SQL $db */ + $schema = new Schema($db); + $tables = $schema->getTables(); + foreach ($deletable as $item) + if(in_array($item, $tables)) + $schema->dropTable($item); + } elseif($db instanceof Mongo) { + /** @var Mongo $db */ + foreach ($deletable as $item) + $db->selectCollection($item)->drop(); + } + } - /** - * computes the m:m table name - * @param string $ftable foreign table - * @param string $fkey foreign key - * @param string $ptable own table - * @param string $pkey own key - * @param null|array $fConf foreign conf [class,key] - * @return string - */ - static protected function getMMTableName($ftable, $fkey, $ptable, $pkey, $fConf=null) - { - if ($fConf) { - list($fclass, $pfkey) = $fConf; - $self = get_called_class(); - // check for a matching config - if (!is_int(strpos($fclass, $self))) - trigger_error(sprintf(self::E_MM_REL_CLASS, $fclass, $self)); - if ($pfkey != $pkey) - trigger_error(sprintf(self::E_MM_REL_FIELD, - $fclass.'.'.$pfkey, $self.'.'.$pkey)); - } - $mmTable = array($ftable.'__'.$fkey, $ptable.'__'.$pkey); - natcasesort($mmTable); - $return = strtolower(str_replace('\\', '_', implode('_mm_', $mmTable))); - return $return; - } + /** + * computes the m:m table name + * @param string $ftable foreign table + * @param string $fkey foreign key + * @param string $ptable own table + * @param string $pkey own key + * @param null|array $fConf foreign conf [class,key] + * @return string + */ + static protected function getMMTableName($ftable, $fkey, $ptable, $pkey, $fConf=null) { + if ($fConf) { + list($fclass, $pfkey) = $fConf; + $self = get_called_class(); + // check for a matching config + if (!is_int(strpos($fclass, $self))) + trigger_error(sprintf(self::E_MM_REL_CLASS, $fclass, $self),E_USER_ERROR); + if ($pfkey != $pkey) + trigger_error(sprintf(self::E_MM_REL_FIELD, + $fclass.'.'.$pfkey, $self.'.'.$pkey),E_USER_ERROR); + } + $mmTable = array($ftable.'__'.$fkey, $ptable.'__'.$pkey); + natcasesort($mmTable); + // shortcut for self-referencing mm tables + if ($mmTable[0] == $mmTable[1] || ($fConf && $fConf['isSelf']==true)) + return array_shift($mmTable); + $return = strtolower(str_replace('\\', '_', implode('_mm_', $mmTable))); + return $return; + } - /** - * get mm table name from config - * @param array $conf own relation config - * @param string $key relation field - * @param null|array $fConf optional foreign config - * @return string - */ - protected function mmTable($conf, $key, $fConf=null) - { - if (!isset($conf['refTable'])) { - // compute mm table name - $mmTable = isset($conf[2]) ? $conf[2] : - static::getMMTableName($conf['relTable'], - $conf['relField'], $this->table, $key, $fConf); - $this->fieldConf[$key]['has-many']['refTable'] = $mmTable; - } else - $mmTable = $conf['refTable']; - return $mmTable; - } + /** + * get mm table name from config + * @param array $conf own relation config + * @param string $key relation field + * @param null|array $fConf optional foreign config + * @return string + */ + protected function mmTable($conf, $key, $fConf=null) { + if (!isset($conf['refTable'])) { + // compute mm table name + $mmTable = isset($conf[2]) ? $conf[2] : + static::getMMTableName($conf['relTable'], + $conf['relField'], $this->table, $key, $fConf); + $this->fieldConf[$key]['has-many']['refTable'] = $mmTable; + } else + $mmTable = $conf['refTable']; + return $mmTable; + } - /** - * resolve relation field types - * @param $field - * @return mixed - */ - protected static function resolveRelationConf($field) - { - if (array_key_exists('belongs-to-one', $field)) { - // find primary field definition - if (!is_array($relConf = $field['belongs-to-one'])) - $relConf = array($relConf, '_id'); - // set field type - if ($relConf[1] == '_id') - $field['type'] = Schema::DT_INT4; - else { - // find foreign field type - $fc = $relConf[0]::resolveConfiguration(); - $field['belongs-to-one']['relPK'] = $fc['primary']; - $field['type'] = $fc['fieldConf'][$relConf[1]]['type']; - } - $field['nullable'] = true; - $field['relType'] = 'belongs-to-one'; - } - elseif (array_key_exists('belongs-to-many', $field)){ - $field['type'] = self::DT_JSON; - $field['nullable'] = true; - $field['relType'] = 'belongs-to-many'; - } - elseif (array_key_exists('has-many', $field)){ - $field['relType'] = 'has-many'; - if (!isset($field['type'])) - $field['type'] = Schema::DT_INT; - $relConf = $field['has-many']; - if(!is_array($relConf)) - return $field; - $rel = $relConf[0]::resolveConfiguration(); - if(array_key_exists('has-many',$rel['fieldConf'][$relConf[1]])) { - $field['has-many']['hasRel'] = 'has-many'; - $field['has-many']['relTable'] = $rel['table']; - $field['has-many']['relField'] = $relConf[1]; - $field['has-many']['relFieldType'] = isset($rel['fieldConf'][$relConf[1]]['type']) ? - $rel['fieldConf'][$relConf[1]]['type'] : Schema::DT_INT; - $field['has-many']['relPK'] = isset($relConf[3])?$relConf[3]:$rel['primary']; - } else { - $field['has-many']['hasRel'] = 'belongs-to-one'; - $toConf=$rel['fieldConf'][$relConf[1]]['belongs-to-one']; - if (is_array($toConf)) - $field['has-many']['relField'] = $toConf[1]; - } - } elseif(array_key_exists('has-one', $field)) - $field['relType'] = 'has-one'; - return $field; - } + /** + * resolve relation field types + * @param array $field + * @return array + */ + protected static function resolveRelationConf($field) { + if (array_key_exists('belongs-to-one', $field)) { + // find primary field definition + if (!is_array($relConf = $field['belongs-to-one'])) + $relConf = array($relConf, '_id'); + // set field type + if ($relConf[1] == '_id') + $field['type'] = Schema::DT_INT4; + else { + // find foreign field type + $fc = $relConf[0]::resolveConfiguration(); + $field['belongs-to-one']['relPK'] = $fc['primary']; + $field['type'] = $fc['fieldConf'][$relConf[1]]['type']; + } + $field['nullable'] = true; + $field['relType'] = 'belongs-to-one'; + } + elseif (array_key_exists('belongs-to-many', $field)){ + $field['type'] = self::DT_JSON; + $field['nullable'] = true; + $field['relType'] = 'belongs-to-many'; + } + elseif (array_key_exists('has-many', $field)){ + $field['relType'] = 'has-many'; + if (!isset($field['type'])) + $field['type'] = Schema::DT_INT; + $relConf = $field['has-many']; + if(!is_array($relConf)) + return $field; + $rel = $relConf[0]::resolveConfiguration(); + if(array_key_exists('has-many',$rel['fieldConf'][$relConf[1]])) { + // has-many <> has-many (m:m) + $field['has-many']['hasRel'] = 'has-many'; + $field['has-many']['isSelf'] = (ltrim($relConf[0],'\\')==get_called_class()); + $field['has-many']['relTable'] = $rel['table']; + $field['has-many']['relField'] = $relConf[1]; + $field['has-many']['relFieldType'] = isset($rel['fieldConf'][$relConf[1]]['type']) ? + $rel['fieldConf'][$relConf[1]]['type'] : Schema::DT_INT; + $field['has-many']['relPK'] = isset($relConf[3])?$relConf[3]:$rel['primary']; + } else { + // has-many <> belongs-to-one (m:1) + $field['has-many']['hasRel'] = 'belongs-to-one'; + $toConf=$rel['fieldConf'][$relConf[1]]['belongs-to-one']; + if (is_array($toConf)) + $field['has-many']['relField'] = $toConf[1]; + } + } elseif(array_key_exists('has-one', $field)) + $field['relType'] = 'has-one'; + return $field; + } - /** - * Return an array of result arrays matching criteria - * @param null $filter - * @param array $options - * @param int $ttl - * @param int $rel_depths - * @return array - */ - public function afind($filter = NULL, array $options = NULL, $ttl = 0, $rel_depths = 1) - { - $result = $this->find($filter, $options, $ttl); - return $result ? $result->castAll($rel_depths): NULL; - } + /** + * Return an array of result arrays matching criteria + * @param null $filter + * @param array $options + * @param int $ttl + * @param int $rel_depths + * @return array + */ + public function afind($filter = NULL, array $options = NULL, $ttl = 0, $rel_depths = 1) { + $result = $this->find($filter, $options, $ttl); + return $result ? $result->castAll($rel_depths): NULL; + } - /** - * Return an array of objects matching criteria - * @param array|null $filter - * @param array|null $options - * @param int $ttl - * @return CortexCollection - */ - public function find($filter = NULL, array $options = NULL, $ttl = 0) - { - $sort=false; - if ($this->dbsType!='sql') { - if (!empty($this->countFields)) - // see if reordering is needed - foreach($this->countFields as $counter) { - if ($options && isset($options['order']) && - preg_match('/count_'.$counter.'\h+(asc|desc)/i',$options['order'],$match)) - $sort=true; - } - if ($sort) { - // backup slice settings - if (isset($options['limit'])) { - $limit = $options['limit']; - unset($options['limit']); - } - if (isset($options['offset'])) { - $offset = $options['offset']; - unset($options['offset']); - } - } - } - $this->_ttl=$ttl?:$this->rel_ttl; - $result = $this->filteredFind($filter,$options,$ttl); - if (empty($result)) - return false; - foreach($result as &$record) { - $record = $this->factory($record); - unset($record); - } - if (!empty($this->countFields)) - // add counter for NoSQL engines - foreach($this->countFields as $counter) - foreach($result as &$mapper) { - $cr=$mapper->get($counter); - $mapper->virtual('count_'.$counter,$cr?count($cr):null); - unset($mapper); - } - $cc = new CortexCollection(); - $cc->setModels($result); - if($sort) { - $cc->orderBy($options['order']); - $cc->slice(isset($offset)?$offset:0,isset($limit)?$limit:NULL); - } - $this->clearFilter(); - return $cc; - } + /** + * Return an array of objects matching criteria + * @param array|null $filter + * @param array|null $options + * @param int $ttl + * @return CortexCollection + */ + public function find($filter = NULL, array $options = NULL, $ttl = 0) { + $sort=false; + if ($this->dbsType!='sql') { + if (!empty($this->countFields)) + // see if reordering is needed + foreach($this->countFields as $counter) { + if ($options && isset($options['order']) && + preg_match('/count_'.$counter.'\h+(asc|desc)/i',$options['order'],$match)) + $sort=true; + } + if ($sort) { + // backup slice settings + if (isset($options['limit'])) { + $limit = $options['limit']; + unset($options['limit']); + } + if (isset($options['offset'])) { + $offset = $options['offset']; + unset($options['offset']); + } + } + } + $this->_ttl=$ttl?:$this->rel_ttl; + $result = $this->filteredFind($filter,$options,$ttl); + if (empty($result)) + return false; + foreach($result as &$record) { + $record = $this->factory($record); + unset($record); + } + if (!empty($this->countFields)) + // add counter for NoSQL engines + foreach($this->countFields as $counter) + foreach($result as &$mapper) { + $cr=$mapper->get($counter); + $mapper->virtual('count_'.$counter,$cr?count($cr):null); + unset($mapper); + } + $cc = new CortexCollection(); + $cc->setModels($result); + if($sort) { + $cc->orderBy($options['order']); + $cc->slice(isset($offset)?$offset:0,isset($limit)?$limit:NULL); + } + $this->clearFilter(); + return $cc; + } - /** - * wrapper for custom find queries - * @param array $filter - * @param array $options - * @param int $ttl - * @param bool $count - * @return array|false array of underlying cursor objects - */ - protected function filteredFind($filter = NULL, array $options = NULL, $ttl = 0, $count=false) - { - if ($this->grp_stack) { - if ($this->dbsType == 'mongo') { - $group = array( - 'keys' => $this->grp_stack['keys'], - 'reduce' => 'function (obj, prev) {'.$this->grp_stack['reduce'].'}', - 'initial' => $this->grp_stack['initial'], - 'finalize' => $this->grp_stack['finalize'], - ); - if ($options && isset($options['group'])) { - if(is_array($options['group'])) - $options['group'] = array_merge($options['group'],$group); - else { - $keys = explode(',',$options['group']); - $keys = array_combine($keys,array_fill(0,count($keys),1)); - $group['keys'] = array_merge($group['keys'],$keys); - $options['group'] = $group; - } - } else - $options = array('group'=>$group); - } - if($this->dbsType == 'sql') { - if ($options && isset($options['group'])) - $options['group'].= ','.$this->grp_stack; - else - $options['group'] = $this->grp_stack; - } - // Jig can't group yet, but pending enhancement https://github.com/bcosca/fatfree/pull/616 - } - if ($this->dbsType == 'sql' && !$count) { - $m_refl=new \ReflectionObject($this->mapper); - $m_ad_prop=$m_refl->getProperty('adhoc'); - $m_ad_prop->setAccessible(true); - $m_refl_adhoc=$m_ad_prop->getValue($this->mapper); - $m_ad_prop->setAccessible(false); - unset($m_ad_prop,$m_refl); - } - $hasJoin = array(); - if ($this->hasCond) { - foreach($this->hasCond as $key => $hasCond) { - $addToFilter = null; - if ($deep = is_int(strpos($key,'.'))) { - $key = rtrim($key,'.'); - $hasCond = array(null,null); - } - list($has_filter,$has_options) = $hasCond; - $type = $this->fieldConf[$key]['relType']; - $fromConf = $this->fieldConf[$key][$type]; - switch($type) { - case 'has-one': - case 'has-many': - if (!is_array($fromConf)) - trigger_error(sprintf(self::E_REL_CONF_INC, $key)); - $id = $this->dbsType == 'sql' ? $this->primary : '_id'; - if ($type=='has-many' && isset($fromConf['relField']) - && $fromConf['hasRel'] == 'belongs-to-one') - $id=$fromConf['relField']; - // many-to-many - if ($type == 'has-many' && $fromConf['hasRel'] == 'has-many') { - if (!$deep && $this->dbsType == 'sql' - && !isset($has_options['limit']) && !isset($has_options['offset'])) { - $hasJoin = array_merge($hasJoin, - $this->_hasJoinMM_sql($key,$hasCond,$filter,$options)); - $options['group'] = (isset($options['group'])?$options['group'].',':''). - $this->db->quotekey($this->table.'.'.$this->primary); - $groupFields = explode(',', preg_replace('/"/','',$options['group'])); - // all non-aggregated fields need to be present in the GROUP BY clause - if (isset($m_refl_adhoc) && preg_match('/sybase|dblib|odbc|sqlsrv/i',$this->db->driver())) - foreach (array_diff($this->mapper->fields(),array_keys($m_refl_adhoc)) as $field) - if (!in_array($this->table.'.'.$field,$groupFields)) - $options['group'] .= ', '.$this->db->quotekey($this->table.'.'.$field); - } - elseif ($result = $this->_hasRefsInMM($key,$has_filter,$has_options,$ttl)) - $addToFilter = array($id.' IN ?', $result); - } // *-to-one - elseif ($result = $this->_hasRefsIn($key,$has_filter,$has_options,$ttl)) - $addToFilter = array($id.' IN ?', $result); - break; - // one-to-* - case 'belongs-to-one': - if (!$deep && $this->dbsType == 'sql' - && !isset($has_options['limit']) && !isset($has_options['offset'])) { - if (!is_array($fromConf)) - $fromConf = array($fromConf, '_id'); - $rel = $fromConf[0]::resolveConfiguration(); - if ($this->dbsType == 'sql' && $fromConf[1] == '_id') - $fromConf[1] = $rel['primary']; - $hasJoin[] = $this->_hasJoin_sql($key,$rel['table'],$hasCond,$filter,$options); - } elseif ($result = $this->_hasRefsIn($key,$has_filter,$has_options,$ttl)) - $addToFilter = array($key.' IN ?', $result); - break; - default: - trigger_error(self::E_HAS_COND); - } - if (isset($result) && !isset($addToFilter)) - return false; - elseif (isset($addToFilter)) { - if (!$filter) - $filter = array(''); - if (!empty($filter[0])) - $filter[0] .= ' and '; - $cond = array_shift($addToFilter); - if ($this->dbsType=='sql') - $cond = $this->_sql_quoteCondition($cond,$this->db->quotekey($this->table)); - $filter[0] .= '('.$cond.')'; - $filter = array_merge($filter, $addToFilter); - } - } - $this->hasCond = null; - } - $filter = $this->queryParser->prepareFilter($filter,$this->dbsType,$this->fieldConf); - if ($this->dbsType=='sql') { - $qtable = $this->db->quotekey($this->table); - if (isset($options['order']) && $this->db->driver() == 'pgsql') - // PostgreSQLism: sort NULL values to the end of a table - $options['order'] = preg_replace('/\h+DESC/i',' DESC NULLS LAST',$options['order']); - if (!empty($hasJoin)) { - // assemble full sql query - $adhoc=''; - if ($count) - $sql = 'SELECT COUNT(*) AS '.$this->db->quotekey('rows').' FROM '.$qtable; - else { - if (!empty($this->preBinds)) { - $crit = array_shift($filter); - $filter = array_merge($this->preBinds,$filter); - array_unshift($filter,$crit); - } - if (!empty($m_refl_adhoc)) - foreach ($m_refl_adhoc as $key=>$val) - $adhoc.=', '.$val['expr'].' AS '.$key; - $sql = 'SELECT '.$qtable.'.*'.$adhoc.' FROM '.$qtable; - } - $sql .= ' '.implode(' ',$hasJoin).' WHERE '.$filter[0]; - if (!$count) { - if (isset($options['group'])) - $sql .= ' GROUP BY '.$this->_sql_quoteCondition($options['group'], $this->table); - if (isset($options['order'])) - $sql .= ' ORDER BY '.$options['order']; - if (preg_match('/mssql|sqlsrv|odbc/', $this->db->driver()) && - (isset($options['limit']) || isset($options['offset']))) { - $ofs=isset($options['offset'])?(int)$options['offset']:0; - $lmt=isset($options['limit'])?(int)$options['limit']:0; - if (strncmp($this->db->version(),'11',2)>=0) { - // SQL Server 2012 - if (!isset($options['order'])) - $sql.=' ORDER BY '.$this->db->quotekey($this->primary); - $sql.=' OFFSET '.$ofs.' ROWS'.($lmt?' FETCH NEXT '.$lmt.' ROWS ONLY':''); - } else { - // SQL Server 2008 - $order=(!isset($options['order'])) - ?($this->db->quotekey($this->table.'.'.$this->primary)):$options['order']; - $sql=str_replace('SELECT','SELECT '.($lmt>0?'TOP '.($ofs+$lmt):'').' ROW_NUMBER() '. - 'OVER (ORDER BY '.$order.') AS rnum,',$sql); - $sql='SELECT * FROM ('.$sql.') x WHERE rnum > '.($ofs); - } - } else { - if (isset($options['limit'])) - $sql.=' LIMIT '.(int)$options['limit']; - if (isset($options['offset'])) - $sql.=' OFFSET '.(int)$options['offset']; - } - } - unset($filter[0]); - $result = $this->db->exec($sql, $filter, $ttl); - if ($count) - return $result[0]['rows']; - foreach ($result as &$record) { - // factory new mappers - $mapper = clone($this->mapper); - $mapper->reset(); - // TODO: refactor this. Reflection can be removed for F3 >= v3.4.1 - $mapper->query= array($record); - $m_adhoc = empty($adhoc) ? array() : $m_refl_adhoc; - foreach ($record as $key=>$val) - if (isset($m_refl_adhoc[$key])) - $m_adhoc[$key]['value']=$val; - else - $mapper->set($key, $val); - if (!empty($adhoc)) { - $refl = new \ReflectionObject($mapper); - $prop = $refl->getProperty('adhoc'); - $prop->setAccessible(true); - $prop->setValue($mapper,$m_adhoc); - $prop->setAccessible(false); - } - $record = $mapper; - unset($record, $mapper); - } - return $result; - } elseif (!empty($this->preBinds) && !$count) { - // bind values to adhoc queries - if (!$filter) - // we (PDO) need any filter to bind values - $filter = array('1=1'); - $crit = array_shift($filter); - $filter = array_merge($this->preBinds,$filter); - array_unshift($filter,$crit); - } - } - return ($count) - ? $this->mapper->count($filter,$ttl) - : $this->mapper->find($filter,$this->queryParser->prepareOptions($options,$this->dbsType),$ttl); - } - - /** - * Retrieve first object that satisfies criteria - * @param null $filter - * @param array $options - * @param int $ttl - * @return Cortex - */ - public function load($filter = NULL, array $options = NULL, $ttl = 0) - { - $this->reset(); - $this->_ttl=$ttl?:$this->rel_ttl; - $res = $this->filteredFind($filter, $options, $ttl); - if ($res) { - $this->mapper->query = $res; - $this->first(); - } else - $this->mapper->reset(); - $this->emit('load'); - return $this; - } - - /** - * add has-conditional filter to next find call - * @param string $key - * @param array $filter - * @param null $options - * @return $this - */ - public function has($key, $filter, $options = null) { - if (is_string($filter)) - $filter=array($filter); - if (is_int(strpos($key,'.'))) { - list($key,$fkey) = explode('.',$key,2); - if (!isset($this->hasCond[$key.'.'])) - $this->hasCond[$key.'.'] = array(); - $this->hasCond[$key.'.'][$fkey] = array($filter,$options); - } else { - if (!isset($this->fieldConf[$key])) - trigger_error(sprintf(self::E_UNKNOWN_FIELD,$key,get_called_class())); - if (!isset($this->fieldConf[$key]['relType'])) - trigger_error(self::E_HAS_COND); - $this->hasCond[$key] = array($filter,$options); - } - return $this; - } - - /** - * return IDs of records that has a linkage to this mapper - * @param string $key relation field - * @param array $filter condition for foreign records - * @param array $options filter options for foreign records - * @param int $ttl - * @return array|false - */ - protected function _hasRefsIn($key, $filter, $options, $ttl = 0) - { - $type = $this->fieldConf[$key]['relType']; - $fieldConf = $this->fieldConf[$key][$type]; - // one-to-many shortcut - $rel = $this->getRelFromConf($fieldConf,$key); - $hasSet = $rel->find($filter, $options, $ttl); - if (!$hasSet) - return false; - $hasSetByRelId = array_unique($hasSet->getAll($fieldConf[1], true)); - return empty($hasSetByRelId) ? false : $hasSetByRelId; - } - - /** - * return IDs of own mappers that match the given relation filter on pivot tables - * @param string $key - * @param array $filter - * @param array $options - * @param int $ttl - * @return array|false - */ - protected function _hasRefsInMM($key, $filter, $options, $ttl=0) - { - $fieldConf = $this->fieldConf[$key]['has-many']; - $rel = $this->getRelInstance($fieldConf[0],null,$key,true); - $hasSet = $rel->find($filter,$options,$ttl); - $result = false; - if ($hasSet) { - $hasIDs = $hasSet->getAll('_id',true); - $mmTable = $this->mmTable($fieldConf,$key); - $pivot = $this->getRelInstance(null,array('db'=>$this->db,'table'=>$mmTable)); - $pivotSet = $pivot->find(array($key.' IN ?',$hasIDs),null,$ttl); - if ($pivotSet) - $result = array_unique($pivotSet->getAll($fieldConf['relField'],true)); - } - return $result; - } - - /** - * build query for SQL pivot table join and merge conditions - */ - protected function _hasJoinMM_sql($key, $hasCond, &$filter, &$options) - { - $fieldConf = $this->fieldConf[$key]['has-many']; - $hasJoin = array(); - $mmTable = $this->mmTable($fieldConf,$key); - $hasJoin[] = $this->_sql_left_join($this->primary,$this->table,$fieldConf['relField'],$mmTable); - $hasJoin[] = $this->_sql_left_join($key,$mmTable,$fieldConf['relPK'],$fieldConf['relTable']); - $this->_sql_mergeRelCondition($hasCond,$fieldConf['relTable'],$filter,$options); - return $hasJoin; - } - - /** - * build query for single SQL table join and merge conditions - */ - protected function _hasJoin_sql($key, $table, $cond, &$filter, &$options) - { - $relConf = $this->fieldConf[$key]['belongs-to-one']; - $relModel = is_array($relConf)?$relConf[0]:$relConf; - $rel = $this->getRelInstance($relModel,null,$key); - $fkey = is_array($this->fieldConf[$key]['belongs-to-one']) ? - $this->fieldConf[$key]['belongs-to-one'][1] : $rel->primary; - $query = $this->_sql_left_join($key,$this->table,$fkey,$table); - $this->_sql_mergeRelCondition($cond,$table,$filter,$options); - return $query; - } - - /** - * assemble SQL join query string - */ - protected function _sql_left_join($skey,$sTable,$fkey,$fTable) - { - $skey = $this->db->quotekey($skey); - $sTable = $this->db->quotekey($sTable); - $fkey = $this->db->quotekey($fkey); - $fTable = $this->db->quotekey($fTable); - return 'LEFT JOIN '.$fTable.' ON '.$sTable.'.'.$skey.' = '.$fTable.'.'.$fkey; - } - - /** - * merge condition of relation with current condition - * @param array $cond condition of related model - * @param string $table table of related model - * @param array $filter current filter to merge with - * @param array $options current options to merge with - */ - protected function _sql_mergeRelCondition($cond, $table, &$filter, &$options) - { - $table = $this->db->quotekey($table); - if (!empty($cond[0])) { - $whereClause = '('.array_shift($cond[0]).')'; - $whereClause = $this->_sql_quoteCondition($whereClause,$table); - if (!$filter) - $filter = array($whereClause); - elseif (!empty($filter[0])) - $filter[0] = '('.$this->_sql_quoteCondition($filter[0], - $this->db->quotekey($this->table)).') and '.$whereClause; - $filter = array_merge($filter, $cond[0]); - } - if ($cond[1] && isset($cond[1]['group'])) { - $hasGroup = preg_replace('/(\w+)/i', $table.'.$1', $cond[1]['group']); - $options['group'] .= ','.$hasGroup; - } - } - - protected function _sql_quoteCondition($cond, $table) - { - $db = $this->db; - if (preg_match('/[`\'"\[\]]/i',$cond)) - return $cond; - return preg_replace_callback('/\w+/i',function($match) use($table,$db) { - if (preg_match('/\b(AND|OR|IN|LIKE|NOT)\b/i',$match[0])) - return $match[0]; - return $table.'.'.$db->quotekey($match[0]); - }, $cond); - } - - /** - * add filter for loading related models - * @param string $key - * @param array $filter - * @param array $option - * @return $this - */ - public function filter($key,$filter=null,$option=null) - { - if (is_int(strpos($key,'.'))) { - list($key,$fkey) = explode('.',$key,2); - if (!isset($this->relFilter[$key.'.'])) - $this->relFilter[$key.'.'] = array(); - $this->relFilter[$key.'.'][$fkey] = array($filter,$option); - } else - $this->relFilter[$key] = array($filter,$option); - return $this; - } - - /** - * removes one or all relation filter - * @param null|string $key - */ - public function clearFilter($key = null) - { - if (!$key) - $this->relFilter = array(); - elseif(isset($this->relFilter[$key])) - unset($this->relFilter[$key]); - } - - /** - * merge the relation filter to the query criteria if it exists - * @param string $key - * @param array $crit - * @return array - */ - protected function mergeWithRelFilter($key,$crit) - { - if (array_key_exists($key, $this->relFilter) && - !empty($this->relFilter[$key][0])) - $crit=$this->mergeFilter(array($this->relFilter[$key][0],$crit)); - return $crit; - } - - /** - * merge multiple filters - * @param $filters - * @param string $glue - * @return array - */ - public function mergeFilter($filters,$glue='and') { - $crit = array(); - $params = array(); - if ($filters) { - foreach($filters as $filter) { - $crit[] = array_shift($filter); - $params = array_merge($params,$filter); - } - array_unshift($params,'( '.implode(' ) '.$glue.' ( ',$crit).' )'); - } - return $params; - } - - /** - * returns the option condition for a relation filter, if defined - * @param string $key - * @return array null - */ - protected function getRelFilterOption($key) - { - return (array_key_exists($key, $this->relFilter) && - !empty($this->relFilter[$key][1])) - ? $this->relFilter[$key][1] : null; - } - - /** - * Delete object/s and reset ORM - * @param $filter - * @return bool - */ - public function erase($filter = null) - { - $filter = $this->queryParser->prepareFilter($filter, $this->dbsType); - if (!$filter) { - if ($this->emit('beforeerase')===false) - return false; - if ($this->fieldConf) { - $changed = false; - foreach($this->fieldConf as $field => $conf){ - if (isset($conf['has-many']) && $conf['has-many']['hasRel']=='has-many'){ - $this->set($field,null); - $changed = true; + /** + * wrapper for custom find queries + * @param array $filter + * @param array $options + * @param int $ttl + * @param bool $count + * @return array|false array of underlying cursor objects + */ + protected function filteredFind($filter = NULL, array $options = NULL, $ttl = 0, $count=false) { + if ($this->grp_stack) { + if ($this->dbsType == 'mongo') { + $group = array( + 'keys' => $this->grp_stack['keys'], + 'reduce' => 'function (obj, prev) {'.$this->grp_stack['reduce'].'}', + 'initial' => $this->grp_stack['initial'], + 'finalize' => $this->grp_stack['finalize'], + ); + if ($options && isset($options['group'])) { + if(is_array($options['group'])) + $options['group'] = array_merge($options['group'],$group); + else { + $keys = explode(',',$options['group']); + $keys = array_combine($keys,array_fill(0,count($keys),1)); + $group['keys'] = array_merge($group['keys'],$keys); + $options['group'] = $group; + } + } else + $options = array('group'=>$group); + } + if($this->dbsType == 'sql') { + if ($options && isset($options['group'])) + $options['group'].= ','.$this->grp_stack; + else + $options['group'] = $this->grp_stack; + } + // Jig can't group yet, but pending enhancement https://github.com/bcosca/fatfree/pull/616 + } + if ($this->dbsType == 'sql' && !$count) { + $m_refl=new \ReflectionObject($this->mapper); + $m_ad_prop=$m_refl->getProperty('adhoc'); + $m_ad_prop->setAccessible(true); + $m_refl_adhoc=$m_ad_prop->getValue($this->mapper); + $m_ad_prop->setAccessible(false); + unset($m_ad_prop,$m_refl); + } + $hasJoin = array(); + if ($this->hasCond) { + foreach($this->hasCond as $key => $hasCond) { + $addToFilter = null; + if ($deep = is_int(strpos($key,'.'))) { + $key = rtrim($key,'.'); + $hasCond = array(null,null); + } + list($has_filter,$has_options) = $hasCond; + $type = $this->fieldConf[$key]['relType']; + $fromConf = $this->fieldConf[$key][$type]; + switch($type) { + case 'has-one': + case 'has-many': + if (!is_array($fromConf)) + trigger_error(sprintf(self::E_REL_CONF_INC, $key),E_USER_ERROR); + $id = $this->dbsType == 'sql' ? $this->primary : '_id'; + if ($type=='has-many' && isset($fromConf['relField']) + && $fromConf['hasRel'] == 'belongs-to-one') + $id=$fromConf['relField']; + // many-to-many + if ($type == 'has-many' && $fromConf['hasRel'] == 'has-many') { + if (!$deep && $this->dbsType == 'sql' + && !isset($has_options['limit']) && !isset($has_options['offset'])) { + $hasJoin = array_merge($hasJoin, + $this->_hasJoinMM_sql($key,$hasCond,$filter,$options)); + $options['group'] = (isset($options['group'])?$options['group'].',':''). + $this->table.'.'.$this->primary; + $groupFields = explode(',', preg_replace('/"/','',$options['group'])); + // all non-aggregated fields need to be present in the GROUP BY clause + if (isset($m_refl_adhoc) && preg_match('/sybase|dblib|odbc|sqlsrv/i',$this->db->driver())) + foreach (array_diff($this->mapper->fields(),array_keys($m_refl_adhoc)) as $field) + if (!in_array($this->table.'.'.$field,$groupFields)) + $options['group'] .= ', '.$this->table.'.'.$field; + } + elseif ($result = $this->_hasRefsInMM($key,$has_filter,$has_options,$ttl)) + $addToFilter = array($id.' IN ?', $result); + } // *-to-one + elseif ($result = $this->_hasRefsIn($key,$has_filter,$has_options,$ttl)) + $addToFilter = array($id.' IN ?', $result); + break; + // one-to-* + case 'belongs-to-one': + if (!$deep && $this->dbsType == 'sql' + && !isset($has_options['limit']) && !isset($has_options['offset'])) { + if (!is_array($fromConf)) + $fromConf = array($fromConf, '_id'); + $rel = $fromConf[0]::resolveConfiguration(); + if ($this->dbsType == 'sql' && $fromConf[1] == '_id') + $fromConf[1] = $rel['primary']; + $hasJoin[] = $this->_hasJoin_sql($key,$rel['table'],$hasCond,$filter,$options); + } elseif ($result = $this->_hasRefsIn($key,$has_filter,$has_options,$ttl)) + $addToFilter = array($key.' IN ?', $result); + break; + default: + trigger_error(self::E_HAS_COND,E_USER_ERROR); + } + if (isset($result) && !isset($addToFilter)) + return false; + elseif (isset($addToFilter)) { + if (!$filter) + $filter = array(''); + if (!empty($filter[0])) + $filter[0] .= ' and '; + $cond = array_shift($addToFilter); + if ($this->dbsType=='sql') + $cond = $this->_sql_prependTableToFields($cond,$this->table); + $filter[0] .= '('.$cond.')'; + $filter = array_merge($filter, $addToFilter); + } + } + $this->hasCond = null; + } + $filter = $this->queryParser->prepareFilter($filter, $this->dbsType, $this->db, $this->fieldConf); + if ($this->dbsType=='sql') { + $qtable = $this->db->quotekey($this->table); + if (isset($options['order']) && $this->db->driver() == 'pgsql') + // PostgreSQLism: sort NULL values to the end of a table + $options['order'] = preg_replace('/\h+DESC/i',' DESC NULLS LAST',$options['order']); + if (!empty($hasJoin)) { + // assemble full sql query + $adhoc=''; + if ($count) + $sql = 'SELECT COUNT(*) AS '.$this->db->quotekey('rows').' FROM '.$qtable; + else { + if (!empty($this->preBinds)) { + $crit = array_shift($filter); + $filter = array_merge($this->preBinds,$filter); + array_unshift($filter,$crit); + } + if (!empty($m_refl_adhoc)) + foreach ($m_refl_adhoc as $key=>$val) + $adhoc.=', '.$val['expr'].' AS '.$key; + $sql = 'SELECT '.$qtable.'.*'.$adhoc.' FROM '.$qtable; + } + $sql .= ' '.implode(' ',$hasJoin).' WHERE '.$filter[0]; + if (!$count) { + $db=$this->db; + if (isset($options['group'])) + $sql.=' GROUP BY '.preg_replace_callback('/\w+[._\-\w]*/i', function($match) use($db) { + return $db->quotekey($match[0]); + }, $options['group']); + if (isset($options['order'])) + $sql .= ' ORDER BY '.$options['order']; + if (preg_match('/mssql|sqlsrv|odbc/', $this->db->driver()) && + (isset($options['limit']) || isset($options['offset']))) { + $ofs=isset($options['offset'])?(int)$options['offset']:0; + $lmt=isset($options['limit'])?(int)$options['limit']:0; + if (strncmp($this->db->version(),'11',2)>=0) { + // SQL Server 2012 + if (!isset($options['order'])) + $sql.=' ORDER BY '.$this->db->quotekey($this->primary); + $sql.=' OFFSET '.$ofs.' ROWS'.($lmt?' FETCH NEXT '.$lmt.' ROWS ONLY':''); + } else { + // SQL Server 2008 + $order=(!isset($options['order'])) + ?($this->db->quotekey($this->table.'.'.$this->primary)):$options['order']; + $sql=str_replace('SELECT','SELECT '.($lmt>0?'TOP '.($ofs+$lmt):'').' ROW_NUMBER() '. + 'OVER (ORDER BY '.$order.') AS rnum,',$sql); + $sql='SELECT * FROM ('.$sql.') x WHERE rnum > '.($ofs); + } + } else { + if (isset($options['limit'])) + $sql.=' LIMIT '.(int)$options['limit']; + if (isset($options['offset'])) + $sql.=' OFFSET '.(int)$options['offset']; } } - if($changed){ - $this->save(); + unset($filter[0]); + $result = $this->db->exec($sql, $filter, $ttl); + if ($count) + return $result[0]['rows']; + foreach ($result as &$record) { + // factory new mappers + $mapper = clone($this->mapper); + $mapper->reset(); + $mapper->query= array($record); + foreach ($record as $key=>$val) + $mapper->set($key, $val); + $record = $mapper; + unset($record, $mapper); } - } - $this->mapper->erase(); - $this->emit('aftererase'); - } elseif($filter) - $this->mapper->erase($filter); - return true; - } + return $result; + } elseif (!empty($this->preBinds) && !$count) { + // bind values to adhoc queries + if (!$filter) + // we (PDO) need any filter to bind values + $filter = array('1=1'); + $crit = array_shift($filter); + $filter = array_merge($this->preBinds,$filter); + array_unshift($filter,$crit); + } + } + return ($count) + ? $this->mapper->count($filter, [], $ttl) + : $this->mapper->find($filter,$this->queryParser->prepareOptions($options,$this->dbsType),$ttl); + } - /** - * Save mapped record - * @return mixed - **/ - function save() - { - // update changed collections - $fields = $this->fieldConf; - if ($fields) - foreach($fields as $key=>$conf) - if (!empty($this->fieldsCache[$key]) && $this->fieldsCache[$key] instanceof CortexCollection - && $this->fieldsCache[$key]->hasChanged()) - $this->set($key,$this->fieldsCache[$key]->getAll('_id',true)); - // perform event & save operations - if ($new = $this->dry()) { - if ($this->emit('beforeinsert')===false) - return false; - $result=$this->insert(); - } else { - if ($this->emit('beforeupdate')===false) - return false; - $result=$this->update(); - } - // m:m save cascade - if (!empty($this->saveCsd)) { - foreach($this->saveCsd as $key => $val) { - if($fields[$key]['relType'] == 'has-many') { - $relConf = $fields[$key]['has-many']; - $mmTable = $this->mmTable($relConf,$key); - $rel = $this->getRelInstance(null, array('db'=>$this->db, 'table'=>$mmTable)); - $id = $this->get($relConf['relPK'],true); - // delete all refs - if (is_null($val)) - $rel->erase(array($relConf['relField'].' = ?', $id)); - // update refs - elseif (is_array($val)) { - $rel->erase(array($relConf['relField'].' = ?', $id)); - foreach($val as $v) { - $rel->set($key,$v); - $rel->set($relConf['relField'],$id); - $rel->save(); - $rel->reset(); - } - } - unset($rel); - } elseif($fields[$key]['relType'] == 'has-one') { - $val->save(); - } - } - $this->saveCsd = array(); - } - $this->emit($new?'afterinsert':'afterupdate'); - return $result; - } + /** + * Retrieve first object that satisfies criteria + * @param null $filter + * @param array $options + * @param int $ttl + * @return Cortex + */ + public function load($filter = NULL, array $options = NULL, $ttl = 0) { + $this->reset(); + $this->_ttl=$ttl?:$this->rel_ttl; + $res = $this->filteredFind($filter, $options, $ttl); + if ($res) { + $this->mapper->query = $res; + $this->first(); + } else + $this->mapper->reset(); + $this->emit('load'); + return $this; + } - /** - * Count records that match criteria - * @param null $filter - * @param int $ttl - * @return mixed - */ - public function count($filter = NULL, $ttl = 60) - { - $has=$this->hasCond; - $count=$this->filteredFind($filter,null,$ttl,true); - $this->hasCond=$has; - return $count; - } + /** + * add has-conditional filter to next find call + * @param string $key + * @param array $filter + * @param null $options + * @return $this + */ + public function has($key, $filter, $options = null) { + if (is_string($filter)) + $filter=array($filter); + if (is_int(strpos($key,'.'))) { + list($key,$fkey) = explode('.',$key,2); + if (!isset($this->hasCond[$key.'.'])) + $this->hasCond[$key.'.'] = array(); + $this->hasCond[$key.'.'][$fkey] = array($filter,$options); + } else { + if (!isset($this->fieldConf[$key])) + trigger_error(sprintf(self::E_UNKNOWN_FIELD,$key,get_called_class()),E_USER_ERROR); + if (!isset($this->fieldConf[$key]['relType'])) + trigger_error(self::E_HAS_COND,E_USER_ERROR); + $this->hasCond[$key] = array($filter,$options); + } + return $this; + } - /** - * Count records that are currently loaded - * @return int - */ - public function loaded() { - return count($this->mapper->query); - } + /** + * return IDs of records that has a linkage to this mapper + * @param string $key relation field + * @param array $filter condition for foreign records + * @param array $options filter options for foreign records + * @param int $ttl + * @return array|false + */ + protected function _hasRefsIn($key, $filter, $options, $ttl = 0) { + $type = $this->fieldConf[$key]['relType']; + $fieldConf = $this->fieldConf[$key][$type]; + // one-to-many shortcut + $rel = $this->getRelFromConf($fieldConf,$key); + $hasSet = $rel->find($filter, $options, $ttl); + if (!$hasSet) + return false; + $hasSetByRelId = array_unique($hasSet->getAll($fieldConf[1], true)); + return empty($hasSetByRelId) ? false : $hasSetByRelId; + } - /** - * add a virtual field that counts occurring relations - * @param $key - */ - public function countRel($key) { - if (isset($this->fieldConf[$key])){ - // one-to-one, one-to-many - if ($this->fieldConf[$key]['relType'] == 'belongs-to-one') { - if ($this->dbsType == 'sql') { - $this->set('count_'.$key,'count('.$key.')'); - $this->grp_stack=(!$this->grp_stack)?$key:$this->grp_stack.','.$key; - } elseif ($this->dbsType == 'mongo') - $this->_mongo_addGroup(array( - 'keys'=>array($key=>1), - 'reduce' => 'prev.count_'.$key.'++;', - "initial" => array("count_".$key => 0) - )); - else - trigger_error('Cannot add direct relational counter.'); - } elseif($this->fieldConf[$key]['relType'] == 'has-many') { - $relConf=$this->fieldConf[$key]['has-many']; - if ($relConf['hasRel']=='has-many') { - // many-to-many - if ($this->dbsType == 'sql') { - $mmTable = $this->mmTable($relConf,$key); - $filter = array($this->db->quotekey($mmTable).'.'.$this->db->quotekey($relConf['relField']) - .' = '.$this->db->quotekey($this->table).'.'.$this->db->quotekey($this->primary)); - $from=$mmTable; - if (array_key_exists($key, $this->relFilter) && - !empty($this->relFilter[$key][0])) { - $options=array(); - $from = $mmTable.' '.$this->_sql_left_join($key,$mmTable,$relConf['relPK'],$relConf['relTable']); - $relFilter = $this->relFilter[$key]; - $this->_sql_mergeRelCondition($relFilter,$relConf['relTable'],$filter,$options); - } - $filter = $this->queryParser->prepareFilter($filter,$this->dbsType,$this->fieldConf); - $crit = array_shift($filter); - if (count($filter)>0) - $this->preBinds+=$filter; - $this->set('count_'.$key,'(select count('.$mmTable.'.'.$relConf['relField'].') from '.$from. - ' where '.$crit.' group by '.$mmTable.'.'.$relConf['relField'].')'); - } else { - // count rel - $this->countFields[]=$key; - } - } elseif($this->fieldConf[$key]['has-many']['hasRel']=='belongs-to-one') { - // many-to-one - if ($this->dbsType == 'sql') { - $fConf=$relConf[0]::resolveConfiguration(); - $fTable=$this->db->quotekey($fConf['table']); - $fKey=$this->db->quotekey($fConf['primary']); - $rKey=$this->db->quotekey($relConf[1]); - $pKey=$this->db->quotekey($this->primary); - $table=$this->db->quotekey($this->table); - $crit = $fTable.'.'.$rKey.' = '.$table.'.'.$pKey; - $filter = $this->mergeWithRelFilter($key,array($crit)); - $filter = $this->queryParser->prepareFilter($filter,$this->dbsType,$this->fieldConf); - $crit = array_shift($filter); - if (count($filter)>0) - $this->preBinds+=$filter; - $this->set('count_'.$key,'(select count('.$fTable.'.'.$fKey.') from '.$fTable.' where '. - $crit.' group by '.$fTable.'.'.$rKey.')'); - } else { - // count rel - $this->countFields[]=$key; - } - } - } - } - } + /** + * return IDs of own mappers that match the given relation filter on pivot tables + * @param string $key + * @param array $filter + * @param array $options + * @param int $ttl + * @return array|false + */ + protected function _hasRefsInMM($key, $filter, $options, $ttl=0) { + $fieldConf = $this->fieldConf[$key]['has-many']; + $rel = $this->getRelInstance($fieldConf[0],null,$key,true); + $hasSet = $rel->find($filter,$options,$ttl); + $result = false; + if ($hasSet) { + $hasIDs = $hasSet->getAll('_id',true); + $mmTable = $this->mmTable($fieldConf,$key); + $pivot = $this->getRelInstance(null,array('db'=>$this->db,'table'=>$mmTable)); + $filter = [$key.' IN ?',$hasIDs]; + if ($fieldConf['isSelf']) { + $filter[0].= ' OR '.$key.'_ref IN ?'; + $filter[] = $hasIDs; + } + $pivotSet = $pivot->find($filter,null,$ttl); + if ($pivotSet) { + $result = $pivotSet->getAll($fieldConf['relField'],true); + if ($fieldConf['isSelf']) + $result = array_merge($result, + $pivotSet->getAll($fieldConf['relField'].'_ref',true)); + $result = array_diff(array_unique($result),$hasIDs); + } + } + return $result; + } - /** - * merge mongo group options array - * @param $opt - */ - protected function _mongo_addGroup($opt){ - if (!$this->grp_stack) - $this->grp_stack = array('keys'=>array(),'initial'=>array(),'reduce'=>'','finalize'=>''); - if (isset($opt['keys'])) - $this->grp_stack['keys']+=$opt['keys']; - if (isset($opt['reduce'])) - $this->grp_stack['reduce'].=$opt['reduce']; - if (isset($opt['initial'])) - $this->grp_stack['initial']+=$opt['initial']; - if (isset($opt['finalize'])) - $this->grp_stack['finalize'].=$opt['finalize']; - } + /** + * build query for SQL pivot table join and merge conditions + */ + protected function _hasJoinMM_sql($key, $hasCond, &$filter, &$options) { + $fieldConf = $this->fieldConf[$key]['has-many']; + $relTable = $fieldConf['relTable']; + $hasJoin = array(); + $mmTable = $this->mmTable($fieldConf,$key); + if ($fieldConf['isSelf']) { + $relTable .= '_ref'; + $hasJoin[] = $this->_sql_left_join($this->primary,$this->table,$fieldConf['relField'].'_ref',$mmTable); + $hasJoin[] = $this->_sql_left_join($key,$mmTable,$fieldConf['relPK'], + [$fieldConf['relTable'],$relTable]); + // cross-linked + $hasJoin[] = $this->_sql_left_join($this->primary,$this->table, + $fieldConf['relField'],[$mmTable,$mmTable.'_c']); + $hasJoin[] = $this->_sql_left_join($key.'_ref',$mmTable.'_c',$fieldConf['relPK'], + [$fieldConf['relTable'],$relTable.'_c']); + $this->_sql_mergeRelCondition($hasCond,$relTable,$filter,$options); + $this->_sql_mergeRelCondition($hasCond,$relTable.'_c',$filter,$options,'OR'); + } else { + $hasJoin[] = $this->_sql_left_join($this->primary,$this->table,$fieldConf['relField'],$mmTable); + $hasJoin[] = $this->_sql_left_join($key,$mmTable,$fieldConf['relPK'],$relTable); + $this->_sql_mergeRelCondition($hasCond,$relTable,$filter,$options); + } + return $hasJoin; + } - /** - * update a given date or time field with the current time - * @param string $key - */ - public function touch($key) { - if (isset($this->fieldConf[$key]) - && isset($this->fieldConf[$key]['type'])) { - $type = $this->fieldConf[$key]['type']; - $date = ($this->dbsType=='sql' && preg_match('/mssql|sybase|dblib|odbc|sqlsrv/', - $this->db->driver())) ? 'Ymd' : 'Y-m-d'; - if ($type == Schema::DT_DATETIME || Schema::DT_TIMESTAMP) - $this->set($key,date($date.' H:i:s')); - elseif ($type == Schema::DT_DATE) - $this->set($key,date($date)); - } - } + /** + * build query for single SQL table join and merge conditions + */ + protected function _hasJoin_sql($key, $table, $cond, &$filter, &$options) { + $relConf = $this->fieldConf[$key]['belongs-to-one']; + $relModel = is_array($relConf)?$relConf[0]:$relConf; + $rel = $this->getRelInstance($relModel,null,$key); + $fkey = is_array($this->fieldConf[$key]['belongs-to-one']) ? + $this->fieldConf[$key]['belongs-to-one'][1] : $rel->primary; + $query = $this->_sql_left_join($key,$this->table,$fkey,$table); + $this->_sql_mergeRelCondition($cond,$table,$filter,$options); + return $query; + } - /** - * Bind value to key - * @return mixed - * @param $key string - * @param $val mixed - */ - function set($key, $val) - { - $fields = $this->fieldConf; - unset($this->fieldsCache[$key]); - // pre-process if field config available - if (!empty($fields) && isset($fields[$key]) && is_array($fields[$key])) { - // handle relations - if (isset($fields[$key]['belongs-to-one'])) { - // one-to-many, one-to-one - if (is_null($val)) - $val = NULL; - elseif (is_object($val) && - !($this->dbsType=='mongo' && $val instanceof \MongoId)) { - // fetch fkey from mapper - if (!$val instanceof Cortex || $val->dry()) - trigger_error(self::E_INVALID_RELATION_OBJECT); - else { - $relConf = $fields[$key]['belongs-to-one']; - $rel_field = (is_array($relConf) ? $relConf[1] : '_id'); - $val = $val->get($rel_field,true); - } - } elseif ($this->dbsType == 'mongo' && !$val instanceof \MongoId) - $val = new \MongoId($val); - } elseif (isset($fields[$key]['has-one'])){ - $relConf = $fields[$key]['has-one']; - if (is_null($val)) { - $val = $this->get($key); - $val->set($relConf[1],NULL); - } else { - if (!$val instanceof Cortex) { - $rel = $this->getRelInstance($relConf[0],null,$key); - $rel->load(array('_id = ?', $val)); - $val = $rel; - } - $val->set($relConf[1], $this->_id); - } - $this->saveCsd[$key] = $val; - return $val; - } elseif (isset($fields[$key]['belongs-to-many'])) { - // many-to-many, unidirectional - $fields[$key]['type'] = self::DT_JSON; - $relConf = $fields[$key]['belongs-to-many']; - $rel_field = (is_array($relConf) ? $relConf[1] : '_id'); - $val = $this->getForeignKeysArray($val, $rel_field, $key); - } - elseif (isset($fields[$key]['has-many'])) { - // many-to-many, bidirectional - $relConf = $fields[$key]['has-many']; - if ($relConf['hasRel'] == 'has-many') { - // custom setter - $val = $this->emit('set_'.$key, $val); - $val = $this->getForeignKeysArray($val,'_id',$key); - $this->saveCsd[$key] = $val; // array of keys - $this->fieldsCache[$key] = $val; - return $val; - } elseif ($relConf['hasRel'] == 'belongs-to-one') { - // TODO: many-to-one, bidirectional, inverse way - trigger_error("not implemented"); - } - } - // convert array content - if (is_array($val) && $this->dbsType == 'sql') - if ($fields[$key]['type'] == self::DT_SERIALIZED) - $val = serialize($val); - elseif ($fields[$key]['type'] == self::DT_JSON) - $val = json_encode($val); - else - trigger_error(sprintf(self::E_ARRAY_DATATYPE, $key)); - // add nullable polyfill - if ($val === NULL && ($this->dbsType == 'jig' || $this->dbsType == 'mongo') - && array_key_exists('nullable', $fields[$key]) && $fields[$key]['nullable'] === false) - trigger_error(sprintf(self::E_NULLABLE_COLLISION,$key)); - // MongoId shorthand - if ($this->dbsType == 'mongo' && !$val instanceof \MongoId) { - if ($key == '_id') - $val = new \MongoId($val); - elseif (preg_match('/INT/i',$fields[$key]['type']) - && !isset($fields[$key]['relType'])) - $val = (int) $val; - } - if (preg_match('/BOOL/i',$fields[$key]['type'])) { - $val = !$val || $val==='false' ? false : (bool) $val; - if ($this->dbsType == 'sql') - $val = (int) $val; - } - } - // fluid SQL - if ($this->fluid && $this->dbsType == 'sql') { - $schema = new Schema($this->db); - $table = $schema->alterTable($this->table); - // add missing field - if (!in_array($key,$table->getCols())) { - // determine data type - if (isset($this->fieldConf[$key]) && isset($this->fieldConf[$key]['type'])) - $type = $this->fieldConf[$key]['type']; - elseif (is_int($val)) $type = $schema::DT_INT; - elseif (is_double($val)) $type = $schema::DT_DOUBLE; - elseif (is_float($val)) $type = $schema::DT_FLOAT; - elseif (is_bool($val)) $type = $schema::DT_BOOLEAN; - elseif (date('Y-m-d H:i:s', strtotime($val)) == $val) $type = $schema::DT_DATETIME; - elseif (date('Y-m-d', strtotime($val)) == $val) $type = $schema::DT_DATE; - elseif (\UTF::instance()->strlen($val)<=255) $type = $schema::DT_VARCHAR256; - else $type = $schema::DT_TEXT; - $table->addColumn($key)->type($type); - $table->build(); - // update mapper fields - $newField = $table->getCols(true); - $newField = $newField[$key]; - $refl = new \ReflectionObject($this->mapper); - $prop = $refl->getProperty('fields'); - $prop->setAccessible(true); - $fields = $prop->getValue($this->mapper); - $fields[$key] = $newField + array('value'=>NULL,'changed'=>NULL); - $prop->setValue($this->mapper,$fields); - } - } - // custom setter - $val = $this->emit('set_'.$key, $val); - return $this->mapper->set($key, $val); - } + /** + * assemble SQL join query string + * @param string $skey + * @param string $sTable + * @param string $fkey + * @param string|array $fTable + * @return string + */ + protected function _sql_left_join($skey, $sTable, $fkey, $fTable) { + if (is_array($fTable)) + list($fTable,$fTable_alias) = $fTable; + $skey = $this->db->quotekey($skey); + $sTable = $this->db->quotekey($sTable); + $fkey = $this->db->quotekey($fkey); + $fTable = $this->db->quotekey($fTable); + if (isset($fTable_alias)) { + $fTable_alias = $this->db->quotekey($fTable_alias); + return 'LEFT JOIN '.$fTable.' AS '.$fTable_alias.' ON '.$sTable.'.'.$skey.' = '.$fTable_alias.'.'.$fkey; + } else + return 'LEFT JOIN '.$fTable.' ON '.$sTable.'.'.$skey.' = '.$fTable.'.'.$fkey; + } - /** - * call custom field handlers - * @param $event - * @param $val - * @return mixed - */ - protected function emit($event, $val=null) - { - if (isset($this->trigger[$event])) { - if (preg_match('/^[sg]et_/',$event)) { - $val = (is_string($f=$this->trigger[$event]) - && preg_match('/^[sg]et_/',$f)) - ? call_user_func(array($this,$event),$val) - : \Base::instance()->call($f,array($this,$val)); - } else - $val = \Base::instance()->call($this->trigger[$event],array($this,$val)); - } elseif (preg_match('/^[sg]et_/',$event) && method_exists($this,$event)) { - $this->trigger[] = $event; - $val = call_user_func(array($this,$event),$val); - } - return $val; - } + /** + * merge condition of relation with current condition + * @param array $cond condition of related model + * @param string $table table of related model + * @param array $filter current filter to merge with + * @param array $options current options to merge with + * @param string $glue + */ + protected function _sql_mergeRelCondition($cond, $table, &$filter, &$options, $glue='AND') { + if (!empty($cond[0])) { + $whereClause = '('.array_shift($cond[0]).')'; + $whereClause = $this->_sql_prependTableToFields($whereClause,$table); + if (!$filter) + $filter = array($whereClause); + elseif (!empty($filter[0])) + $filter[0] = '('.$this->_sql_prependTableToFields($filter[0],$this->table) + .') '.$glue.' '.$whereClause; + $filter = array_merge($filter, $cond[0]); + } + if ($cond[1] && isset($cond[1]['group'])) { + $hasGroup = preg_replace('/(\w+)/i', $table.'.$1', $cond[1]['group']); + $options['group'] .= ','.$hasGroup; + } + } - /** - * Define a custom field setter - * @param $key - * @param $func - */ - public function onset($key,$func) { - $this->trigger['set_'.$key] = $func; - } + /** + * add table prefix to identifiers which do not have a table prefix yet + * @param string $cond + * @param string $table + * @return string + */ + protected function _sql_prependTableToFields($cond, $table) { + return preg_replace_callback('/(\w+\((?:[^)(]+|(?R))*\))|'. + '(?:(\s)|^|(?<=[(]))([a-zA-Z_](?:[\w\-_]+))(?=[\s<>=!)]|$)/i', + function($match) use($table) { + if (!isset($match[3])) + return $match[1]; + if (preg_match('/\b(AND|OR|IN|LIKE|NOT)\b/i',$match[3])) + return $match[0]; + return $match[2].$table.'.'.$match[3]; + }, $cond); + } - /** - * Define a custom field getter - * @param $key - * @param $func - */ - public function onget($key,$func) { - $this->trigger['get_'.$key] = $func; - } + /** + * add filter for loading related models + * @param string $key + * @param array $filter + * @param array $option + * @return $this + */ + public function filter($key, $filter=null, $option=null) { + if (is_int(strpos($key,'.'))) { + list($key,$fkey) = explode('.',$key,2); + if (!isset($this->relFilter[$key.'.'])) + $this->relFilter[$key.'.'] = array(); + $this->relFilter[$key.'.'][$fkey] = array($filter,$option); + } else + $this->relFilter[$key] = array($filter,$option); + return $this; + } - /** - * virtual mapper field setter - * @param string $key - * @param mixed|callback $val - * @return mixed|null - */ - public function virtual($key,$val) { - $this->vFields[$key]=$val; - } + /** + * removes one or all relation filter + * @param null|string $key + */ + public function clearFilter($key = null) { + if (!$key) + $this->relFilter = array(); + elseif(isset($this->relFilter[$key])) + unset($this->relFilter[$key]); + } - /** - * Retrieve contents of key - * @return mixed - * @param string $key - * @param bool $raw - */ - function &get($key,$raw = false) - { - // handle virtual fields - if (isset($this->vFields[$key])) { - $out = (is_callable($this->vFields[$key])) - ? call_user_func($this->vFields[$key], $this) : $this->vFields[$key]; - return $out; - } - $fields = $this->fieldConf; - $id = $this->primary; - if ($key == '_id' && $this->dbsType == 'sql') - $key = $id; - if ($this->whitelist && !in_array($key,$this->whitelist)) { - $out = null; - return $out; - } - if ($raw) { - $out = $this->exists($key) ? $this->mapper->{$key} : NULL; - return $out; - } - if (!empty($fields) && isset($fields[$key]) && is_array($fields[$key]) - && !array_key_exists($key,$this->fieldsCache)) { - // load relations - if (isset($fields[$key]['belongs-to-one'])) { - // one-to-X, bidirectional, direct way - if (!$this->exists($key) || is_null($this->mapper->{$key})) - $this->fieldsCache[$key] = null; - else { - // get config for this field - $relConf = $fields[$key]['belongs-to-one']; - // fetch related model - $rel = $this->getRelFromConf($relConf,$key); - // am i part of a result collection? - if ($cx = $this->getCollection()) { - // does the collection has cached results for this key? - if (!$cx->hasRelSet($key)) { - // build the cache, find all values of current key - $relKeys = array_unique($cx->getAll($key,true)); - // find related models - $crit = array($relConf[1].' IN ?', $relKeys); - $relSet = $rel->find($this->mergeWithRelFilter($key, $crit), - $this->getRelFilterOption($key),$this->_ttl); - // cache relSet, sorted by ID - $cx->setRelSet($key, $relSet ? $relSet->getBy($relConf[1]) : NULL); - } - // get a subset of the preloaded set - $result = $cx->getSubset($key,(string) $this->get($key,true)); - $this->fieldsCache[$key] = $result ? $result[0] : NULL; - } else { - $crit = array($relConf[1].' = ?', $this->get($key, true)); - $crit = $this->mergeWithRelFilter($key, $crit); - $this->fieldsCache[$key] = $rel->findone($crit, - $this->getRelFilterOption($key),$this->_ttl); - } - } - } - elseif (($type = isset($fields[$key]['has-one'])) - || isset($fields[$key]['has-many'])) { - $type = $type ? 'has-one' : 'has-many'; - $fromConf = $fields[$key][$type]; - if (!is_array($fromConf)) - trigger_error(sprintf(self::E_REL_CONF_INC, $key)); - $rel = $this->getRelInstance($fromConf[0],null,$key,true); - $relFieldConf = $rel->getFieldConfiguration(); - $relType = isset($relFieldConf[$fromConf[1]]['belongs-to-one']) ? - 'belongs-to-one' : 'has-many'; - // one-to-*, bidirectional, inverse way - if ($relType == 'belongs-to-one') { - $toConf = $relFieldConf[$fromConf[1]]['belongs-to-one']; - if(!is_array($toConf)) - $toConf = array($toConf, $id); - if ($toConf[1] != $id && (!$this->exists($toConf[1]) - || is_null($this->mapper->get($toConf[1])))) - $this->fieldsCache[$key] = null; - elseif($cx = $this->getCollection()) { - // part of a result set - if(!$cx->hasRelSet($key)) { - // emit eager loading - $relKeys = $cx->getAll($toConf[1],true); - $crit = array($fromConf[1].' IN ?', $relKeys); - $relSet = $rel->find($this->mergeWithRelFilter($key,$crit), - $this->getRelFilterOption($key),$this->_ttl); - $cx->setRelSet($key, $relSet ? $relSet->getBy($fromConf[1],true) : NULL); - } - $result = $cx->getSubset($key, array($this->get($toConf[1]))); - $this->fieldsCache[$key] = $result ? (($type == 'has-one') - ? $result[0][0] : CortexCollection::factory($result[0])) : NULL; - } else { - $crit = array($fromConf[1].' = ?', $this->get($toConf[1],true)); - $crit = $this->mergeWithRelFilter($key, $crit); - $opt = $this->getRelFilterOption($key); - $this->fieldsCache[$key] = (($type == 'has-one') - ? $rel->findone($crit,$opt,$this->_ttl) - : $rel->find($crit,$opt,$this->_ttl)) ?: NULL; - } - } - // many-to-many, bidirectional - elseif ($relType == 'has-many') { - $toConf = $relFieldConf[$fromConf[1]]['has-many']; - $mmTable = $this->mmTable($fromConf,$key,$toConf); - // create mm table mapper - if (!$this->get($id,true)) { - $this->fieldsCache[$key] = null; - return $this->fieldsCache[$key]; - } - $id = $toConf['relPK']; - $rel = $this->getRelInstance(null,array('db'=>$this->db,'table'=>$mmTable)); - if ($cx = $this->getCollection()) { - if (!$cx->hasRelSet($key)) { - // get IDs of all results - $relKeys = $cx->getAll($id,true); - // get all pivot IDs - $mmRes = $rel->find(array($fromConf['relField'].' IN ?', $relKeys),null,$this->_ttl); - if (!$mmRes) - $cx->setRelSet($key, NULL); - else { - $pivotRel = array(); - $pivotKeys = array(); - foreach($mmRes as $model) { - $val = $model->get($key,true); - $pivotRel[ (string) $model->get($fromConf['relField'])][] = $val; - $pivotKeys[] = $val; - } - // cache pivot keys - $cx->setRelSet($key.'_pivot', $pivotRel); - // preload all rels - $pivotKeys = array_unique($pivotKeys); - $fRel = $this->getRelInstance($fromConf[0],null,$key,true); - $crit = array($toConf['relPK'].' IN ?', $pivotKeys); - $relSet = $fRel->find($this->mergeWithRelFilter($key, $crit), - $this->getRelFilterOption($key),$this->_ttl); - $cx->setRelSet($key, $relSet ? $relSet->getBy($id) : NULL); - unset($fRel); - } - } - // fetch subset from preloaded rels using cached pivot keys - $fkeys = $cx->getSubset($key.'_pivot', array($this->get($id))); - $this->fieldsCache[$key] = $fkeys ? - CortexCollection::factory($cx->getSubset($key, $fkeys[0])) : NULL; - } // no collection - else { - // find foreign keys - $results = $rel->find( - array($fromConf['relField'].' = ?', $this->get($fromConf['relPK'],true)),null,$this->_ttl); - if(!$results) - $this->fieldsCache[$key] = NULL; - else { - $fkeys = $results->getAll($key,true); - // create foreign table mapper - unset($rel); - $rel = $this->getRelInstance($fromConf[0],null,$key,true); - // load foreign models - $filter = array($toConf['relPK'].' IN ?', $fkeys); - $filter = $this->mergeWithRelFilter($key, $filter); - $this->fieldsCache[$key] = $rel->find($filter, - $this->getRelFilterOption($key),$this->_ttl); - } - } - } - } - elseif (isset($fields[$key]['belongs-to-many'])) { - // many-to-many, unidirectional - $fields[$key]['type'] = self::DT_JSON; - $result = !$this->exists($key) ? null :$this->mapper->get($key); - if ($this->dbsType == 'sql') - $result = json_decode($result, true); - if (!is_array($result)) - $this->fieldsCache[$key] = $result; - else { - // create foreign table mapper - $relConf = $fields[$key]['belongs-to-many']; - $rel = $this->getRelFromConf($relConf,$key); - $fkeys = array(); - foreach ($result as $el) - $fkeys[] = is_int($el)||ctype_digit($el)?(int)$el:(string)$el; - // if part of a result set - if ($cx = $this->getCollection()) { - if (!$cx->hasRelSet($key)) { - // find all keys - $relKeys = ($cx->getAll($key,true)); - if ($this->dbsType == 'sql'){ - foreach ($relKeys as &$val) { - $val = substr($val, 1, -1); - unset($val); - } - $relKeys = json_decode('['.implode(',',$relKeys).']'); - } else - $relKeys = call_user_func_array('array_merge', $relKeys); - // get related models - $crit = array($relConf[1].' IN ?', array_unique($relKeys)); - $relSet = $rel->find($this->mergeWithRelFilter($key, $crit), - $this->getRelFilterOption($key),$this->_ttl); - // cache relSet, sorted by ID - $cx->setRelSet($key, $relSet ? $relSet->getBy($relConf[1]) : NULL); - } - // get a subset of the preloaded set - $this->fieldsCache[$key] = CortexCollection::factory($cx->getSubset($key, $fkeys)); - } else { - // load foreign models - $filter = array($relConf[1].' IN ?', $fkeys); - $filter = $this->mergeWithRelFilter($key, $filter); - $this->fieldsCache[$key] = $rel->find($filter, - $this->getRelFilterOption($key),$this->_ttl); - } - } - } - // resolve array fields - elseif (isset($fields[$key]['type'])) { - if ($this->dbsType == 'sql') { - if ($fields[$key]['type'] == self::DT_SERIALIZED) - $this->fieldsCache[$key] = unserialize($this->mapper->{$key}); - elseif ($fields[$key]['type'] == self::DT_JSON) - $this->fieldsCache[$key] = json_decode($this->mapper->{$key},true); - } - if ($this->exists($key) && preg_match('/BOOL/i',$fields[$key]['type'])) { - $this->fieldsCache[$key] = (bool) $this->mapper->{$key}; - } - } - } - // fetch cached value, if existing - $val = array_key_exists($key,$this->fieldsCache) ? $this->fieldsCache[$key] - : (($this->exists($key)) ? $this->mapper->{$key} : null); - if ($this->dbsType == 'mongo' && $val instanceof \MongoId) { - // conversion to string makes further processing in template, etc. much easier - $val = (string) $val; - } - // custom getter - $out = $this->emit('get_'.$key, $val); - return $out; - } + /** + * merge the relation filter to the query criteria if it exists + * @param string $key + * @param array $crit + * @return array + */ + protected function mergeWithRelFilter($key, $crit) { + if (array_key_exists($key, $this->relFilter) && + !empty($this->relFilter[$key][0])) + $crit=$this->mergeFilter(array($this->relFilter[$key][0],$crit)); + return $crit; + } - /** - * find the ID values of given relation collection - * @param $val string|array|object|bool - * @param $rel_field string - * @param $key string - * @return array|Cortex|null|object - */ - protected function getForeignKeysArray($val, $rel_field, $key) - { - if (is_null($val)) - return NULL; - if (is_object($val) && $val instanceof CortexCollection) - $val = $val->expose(); - elseif (is_string($val)) - // split-able string of collection IDs - $val = \Base::instance()->split($val); - elseif (!is_array($val) && !(is_object($val) - && ($val instanceof Cortex && !$val->dry()))) - trigger_error(sprintf(self::E_MM_REL_VALUE, $key)); - // hydrated mapper as collection - if (is_object($val)) { - $nval = array(); - while (!$val->dry()) { - $nval[] = $val->get($rel_field,true); - $val->next(); - } - $val = $nval; - } - elseif (is_array($val)) { - // array of single hydrated mappers, raw ID value or mixed - $isMongo = ($this->dbsType == 'mongo'); - foreach ($val as &$item) { - if (is_object($item) && - !($isMongo && $item instanceof \MongoId)) { - if (!$item instanceof Cortex || $item->dry()) - trigger_error(self::E_INVALID_RELATION_OBJECT); - else $item = $item->get($rel_field,true); - } - if ($isMongo && $rel_field == '_id' && is_string($item)) - $item = new \MongoId($item); - if (is_numeric($item)) - $item = (int) $item; - unset($item); - } - } - return $val; - } + /** + * merge multiple filters + * @param array $filters + * @param string $glue + * @return array + */ + public function mergeFilter($filters, $glue='and') { + $crit = array(); + $params = array(); + if ($filters) { + foreach($filters as $filter) { + $crit[] = array_shift($filter); + $params = array_merge($params,$filter); + } + array_unshift($params,'( '.implode(' ) '.$glue.' ( ',$crit).' )'); + } + return $params; + } - /** - * creates and caches related mapper objects - * @param string $model - * @param array $relConf - * @param string $key - * @param bool $pushFilter - * @return Cortex - */ - protected function getRelInstance($model=null,$relConf=null,$key='',$pushFilter=false) - { - if (!$model && !$relConf) - trigger_error(self::E_MISSING_REL_CONF); - $relConf = $model ? $model::resolveConfiguration() : $relConf; - $relName = ($model?:'Cortex').'\\'.$relConf['db']->uuid(). - '\\'.$relConf['table'].'\\'.$key; - if (\Registry::exists($relName)) { - $rel = \Registry::get($relName); - $rel->reset(); - } else { - $rel = $model ? new $model : new Cortex($relConf['db'], $relConf['table']); - if (!$rel instanceof Cortex) - trigger_error(self::E_WRONG_RELATION_CLASS); - \Registry::set($relName, $rel); - } - // restrict fields of related mapper - if(!empty($key) && isset($this->relWhitelist[$key])) { - if (isset($this->relWhitelist[$key][0])) - $rel->fields($this->relWhitelist[$key][0],false); - if (isset($this->relWhitelist[$key][1])) - $rel->fields($this->relWhitelist[$key][1],true); - } - if ($pushFilter && !empty($key)) { - if (isset($this->relFilter[$key.'.'])) { - foreach($this->relFilter[$key.'.'] as $fkey=>$conf) - $rel->filter($fkey,$conf[0],$conf[1]); - } - if (isset($this->hasCond[$key.'.'])) { - foreach($this->hasCond[$key.'.'] as $fkey=>$conf) - $rel->has($fkey,$conf[0],$conf[1]); - } - } - return $rel; - } + /** + * returns the option condition for a relation filter, if defined + * @param string $key + * @return array null + */ + protected function getRelFilterOption($key) { + return (array_key_exists($key, $this->relFilter) && + !empty($this->relFilter[$key][1])) + ? $this->relFilter[$key][1] : null; + } - /** - * get relation model from config - * @param $fieldConf - * @param $key - * @return Cortex - */ - protected function getRelFromConf(&$fieldConf, $key) { - if (!is_array($fieldConf)) - $fieldConf = array($fieldConf, '_id'); - $rel = $this->getRelInstance($fieldConf[0],null,$key,true); - if($this->dbsType=='sql' && $fieldConf[1] == '_id') - $fieldConf[1] = $rel->primary; - return $rel; - } + /** + * Delete object/s and reset ORM + * @param $filter + * @return bool + */ + public function erase($filter = null) { + $filter = $this->queryParser->prepareFilter($filter, $this->dbsType, $this->db); + if (!$filter) { + if ($this->emit('beforeerase')===false) + return false; + if ($this->fieldConf) { + // clear all m:m references + foreach($this->fieldConf as $key => $conf) + if (isset($conf['has-many']) && + $conf['has-many']['hasRel']=='has-many') { + $rel = $this->getRelInstance(null, array( + 'db'=>$this->db, + 'table'=>$this->mmTable($conf['has-many'],$key))); + $id = $this->get($conf['has-many']['relPK'],true); + $rel->erase(array($conf['has-many']['relField'].' = ?', $id)); + } + } + $this->mapper->erase(); + $this->emit('aftererase'); + } elseif($filter) + $this->mapper->erase($filter); + return true; + } - /** - * returns a clean/dry model from a relation - * @param string $key - * @return Cortex - */ - public function rel($key) - { - $rt = $this->fieldConf[$key]['relType']; - $rc = $this->fieldConf[$key][$rt]; - if (!is_array($rc)) - $rc = array($rc,'_id'); - return $this->getRelInstance($rc[0],null,$key); - } + /** + * Save mapped record + * @return mixed + **/ + function save() { + // update changed collections + $fields = $this->fieldConf; + if ($fields) + foreach($fields as $key=>$conf) + if (!empty($this->fieldsCache[$key]) && $this->fieldsCache[$key] instanceof CortexCollection + && $this->fieldsCache[$key]->hasChanged()) + $this->set($key,$this->fieldsCache[$key]->getAll('_id',true)); + // perform event & save operations + if ($new = $this->dry()) { + if ($this->emit('beforeinsert')===false) + return false; + $result=$this->insert(); + } else { + if ($this->emit('beforeupdate')===false) + return false; + $result=$this->update(); + } + // m:m save cascade + if (!empty($this->saveCsd)) { + foreach($this->saveCsd as $key => $val) { + if($fields[$key]['relType'] == 'has-many') { + $relConf = $fields[$key]['has-many']; + $mmTable = $this->mmTable($relConf,$key); + $rel = $this->getRelInstance(null, array('db'=>$this->db, 'table'=>$mmTable)); + $id = $this->get($relConf['relPK'],true); + $filter = [$relConf['relField'].' = ?',$id]; + if ($relConf['isSelf']) { + $filter[0].= ' OR '.$relConf['relField'].'_ref = ?'; + $filter[] = $id; + } + // delete all refs + if (is_null($val)) + $rel->erase($filter); + // update refs + elseif (is_array($val)) { + $rel->erase($filter); + foreach($val as $v) { + if ($relConf['isSelf'] && $v==$id) + continue; + $rel->set($key,$v); + $rel->set($relConf['relField'].($relConf['isSelf']?'_ref':''),$id); + $rel->save(); + $rel->reset(); + } + } + unset($rel); + } elseif($fields[$key]['relType'] == 'has-one') { + $val->save(); + } + } + $this->saveCsd = array(); + } + $this->emit($new?'afterinsert':'afterupdate'); + return $result; + } - /** - * Return fields of mapper object as an associative array - * @return array - * @param bool|Cortex $obj - * @param int|array $rel_depths depths to resolve relations - */ - public function cast($obj = NULL, $rel_depths = 1) - { - $fields = $this->mapper->cast( ($obj) ? $obj->mapper : null ); - if (!empty($this->vFields)) - foreach(array_keys($this->vFields) as $key) - $fields[$key]=$this->get($key); - if (is_int($rel_depths)) - $rel_depths = array('*'=>$rel_depths-1); - elseif (is_array($rel_depths)) - $rel_depths['*'] = isset($rel_depths['*'])?--$rel_depths['*']:-1; - if (!empty($this->fieldConf)) { - $fields += array_fill_keys(array_keys($this->fieldConf),NULL); - if($this->whitelist) - $fields = array_intersect_key($fields, array_flip($this->whitelist)); - $mp = $obj ? : $this; - foreach ($fields as $key => &$val) { - // post process configured fields - if (isset($this->fieldConf[$key]) && is_array($this->fieldConf[$key])) { - // handle relations - $rd = isset($rel_depths[$key]) ? $rel_depths[$key] : $rel_depths['*']; - if ((is_array($rd) || $rd >= 0) && $type=preg_grep('/[belongs|has]-(to-)*[one|many]/', - array_keys($this->fieldConf[$key]))) { - $relType=current($type); - // cast relations - $val = (($relType == 'belongs-to-one' || $relType == 'belongs-to-many') - && !$mp->exists($key)) ? NULL : $mp->get($key); - if ($val instanceof Cortex) - $val = $val->cast(null, $rd); - elseif ($val instanceof CortexCollection) - $val = $val->castAll($rd); - } - // extract array fields - elseif (isset($this->fieldConf[$key]['type'])) { - if ($this->dbsType == 'sql') { - if ($this->fieldConf[$key]['type'] == self::DT_SERIALIZED) - $val=unserialize($mp->mapper->{$key}); - elseif ($this->fieldConf[$key]['type'] == self::DT_JSON) - $val=json_decode($mp->mapper->{$key}, true); - } - if ($this->exists($key) - && preg_match('/BOOL/i',$this->fieldConf[$key]['type'])) { - $val = (bool) $mp->mapper->{$key}; - } - } - } - if ($this->dbsType == 'mongo' && $key == '_id') - $val = (string) $val; - if ($this->dbsType == 'sql' && $key == 'id' && $this->standardiseID) { - $fields['_id'] = $val; - unset($fields[$key]); - } - unset($val); - } - } - // custom getter - foreach ($fields as $key => &$val) { - $val = $this->emit('get_'.$key, $val); - unset($val); - } - return $fields; - } + /** + * @param null $filter + * @param array|NULL $options + * @param int $ttl + * @return array|false + */ + public function count($filter = NULL, array $options=NULL, $ttl = 60) { + $has=$this->hasCond; + $count=$this->filteredFind($filter,null,$ttl,true); + $this->hasCond=$has; + return $count; + } - /** - * cast a related collection of mappers - * @param string $key field name - * @param int $rel_depths depths to resolve relations - * @return array array of associative arrays - */ - function castField($key, $rel_depths=0) - { - if (!$key) - return NULL; - $mapper_arr = $this->get($key); - if(!$mapper_arr) - return NULL; - $out = array(); - foreach ($mapper_arr as $mp) - $out[] = $mp->cast(null,$rel_depths); - return $out; - } + /** + * Count records that are currently loaded + * @return int + */ + public function loaded() { + return count($this->mapper->query); + } - /** - * wrap result mapper - * @param Cursor|array $mapper - * @return Cortex - */ - protected function factory($mapper) - { - if (is_array($mapper)) { - $mp = clone($this->mapper); - $mp->reset(); - $cx = $this->factory($mp); - $cx->copyfrom($mapper); - } else { - $cx = clone($this); - $cx->reset(false); - $cx->mapper = $mapper; - } - $cx->emit('load'); - return $cx; - } + /** + * add a virtual field that counts occurring relations + * @param $key + */ + public function countRel($key) { + if (isset($this->fieldConf[$key])){ + // one-to-one, one-to-many + if ($this->fieldConf[$key]['relType'] == 'belongs-to-one') { + if ($this->dbsType == 'sql') { + $this->mapper->set('count_'.$key,'count('.$key.')'); + $this->grp_stack=(!$this->grp_stack)?$key:$this->grp_stack.','.$key; + } elseif ($this->dbsType == 'mongo') + $this->_mongo_addGroup(array( + 'keys'=>array($key=>1), + 'reduce' => 'prev.count_'.$key.'++;', + "initial" => array("count_".$key => 0) + )); + else + trigger_error('Cannot add direct relational counter.',E_USER_ERROR); + } elseif($this->fieldConf[$key]['relType'] == 'has-many') { + $relConf=$this->fieldConf[$key]['has-many']; + if ($relConf['hasRel']=='has-many') { + // many-to-many + if ($this->dbsType == 'sql') { + $mmTable = $this->mmTable($relConf,$key); + $filter = array($mmTable.'.'.$relConf['relField'] + .' = '.$this->table.'.'.$this->primary); + $from=$mmTable; + if (array_key_exists($key, $this->relFilter) && + !empty($this->relFilter[$key][0])) { + $options=array(); + $from = $mmTable.' '.$this->_sql_left_join($key,$mmTable,$relConf['relPK'],$relConf['relTable']); + $relFilter = $this->relFilter[$key]; + $this->_sql_mergeRelCondition($relFilter,$relConf['relTable'],$filter,$options); + } + $filter = $this->queryParser->prepareFilter($filter, $this->dbsType, $this->db, $this->fieldConf); + $crit = array_shift($filter); + if (count($filter)>0) + $this->preBinds+=$filter; + $this->mapper->set('count_'.$key,'(select count('.$mmTable.'.'.$relConf['relField'].') from '.$from. + ' where '.$crit.' group by '.$mmTable.'.'.$relConf['relField'].')'); + } else { + // count rel + $this->countFields[]=$key; + } + } elseif($this->fieldConf[$key]['has-many']['hasRel']=='belongs-to-one') { + // many-to-one + if ($this->dbsType == 'sql') { + $fConf=$relConf[0]::resolveConfiguration(); + $fTable=$fConf['table']; + $rKey=$relConf[1]; + $crit = $fTable.'.'.$rKey.' = '.$this->table.'.'.$this->primary; + $filter = $this->mergeWithRelFilter($key,array($crit)); + $filter = $this->queryParser->prepareFilter($filter, $this->dbsType, $this->db, $this->fieldConf); + $crit = array_shift($filter); + if (count($filter)>0) + $this->preBinds+=$filter; + $this->mapper->set('count_'.$key,'(select count('.$fTable.'.'.$fConf['primary'].') from '.$fTable.' where '. + $crit.' group by '.$fTable.'.'.$rKey.')'); + } else { + // count rel + $this->countFields[]=$key; + } + } + } + } + } - public function dry() { - return $this->mapper->dry(); - } + /** + * merge mongo group options array + * @param $opt + */ + protected function _mongo_addGroup($opt) { + if (!$this->grp_stack) + $this->grp_stack = array('keys'=>array(),'initial'=>array(),'reduce'=>'','finalize'=>''); + if (isset($opt['keys'])) + $this->grp_stack['keys']+=$opt['keys']; + if (isset($opt['reduce'])) + $this->grp_stack['reduce'].=$opt['reduce']; + if (isset($opt['initial'])) + $this->grp_stack['initial']+=$opt['initial']; + if (isset($opt['finalize'])) + $this->grp_stack['finalize'].=$opt['finalize']; + } - /** - * hydrate the mapper from hive key or given array - * @param string|array $key - * @param callback|array|string $fields - * @return NULL - */ - public function copyfrom($key, $fields = null) - { - $f3 = \Base::instance(); - $srcfields = is_array($key) ? $key : $f3->get($key); - if ($fields) - if (is_callable($fields)) - $srcfields = $fields($srcfields); - else { - if (is_string($fields)) - $fields = $f3->split($fields); - $srcfields = array_intersect_key($srcfields, array_flip($fields)); - } - foreach ($srcfields as $key => $val) { - if (isset($this->fieldConf[$key]) && isset($this->fieldConf[$key]['type'])) { - if ($this->fieldConf[$key]['type'] == self::DT_JSON && is_string($val)) - $val = json_decode($val); - elseif ($this->fieldConf[$key]['type'] == self::DT_SERIALIZED && is_string($val)) - $val = unserialize($val); - } - $this->set($key, $val); - } - } + /** + * update a given date or time field with the current time + * @param string $key + */ + public function touch($key) { + if (isset($this->fieldConf[$key]) + && isset($this->fieldConf[$key]['type'])) { + $type = $this->fieldConf[$key]['type']; + $date = ($this->dbsType=='sql' && preg_match('/mssql|sybase|dblib|odbc|sqlsrv/', + $this->db->driver())) ? 'Ymd' : 'Y-m-d'; + if ($type == Schema::DT_DATETIME || $type == Schema::DT_TIMESTAMP) + $this->set($key,date($date.' H:i:s')); + elseif ($type == Schema::DT_DATE) + $this->set($key,date($date)); + elseif ($type == Schema::DT_INT4) + $this->set($key,time()); + } + } - /** - * copy mapper values into hive key - * @param string $key the hive key to copy into - * @param int $relDepth the depth of relations to resolve - * @return NULL|void - */ - public function copyto($key, $relDepth=0) { - \Base::instance()->set($key, $this->cast(null,$relDepth)); - } + /** + * Bind value to key + * @return mixed + * @param $key string + * @param $val mixed + */ + function set($key, $val) { + if ($key == '_id' && $this->dbsType == 'sql') + $key = $this->primary; + $fields = $this->fieldConf; + unset($this->fieldsCache[$key]); + // pre-process if field config available + if (!empty($fields) && isset($fields[$key]) && is_array($fields[$key])) { + // handle relations + if (isset($fields[$key]['belongs-to-one'])) { + // one-to-many, one-to-one + if (is_null($val)) + $val = NULL; + elseif (is_object($val) && + !($this->dbsType=='mongo' && $val instanceof \MongoId)) { + // fetch fkey from mapper + if (!$val instanceof Cortex || $val->dry()) + trigger_error(self::E_INVALID_RELATION_OBJECT,E_USER_ERROR); + else { + $relConf = $fields[$key]['belongs-to-one']; + $rel_field = (is_array($relConf) ? $relConf[1] : '_id'); + $val = $val->get($rel_field,true); + } + } elseif ($this->dbsType == 'mongo' && !$val instanceof \MongoId) + $val = new \MongoId($val); + } elseif (isset($fields[$key]['has-one'])){ + $relConf = $fields[$key]['has-one']; + if (is_null($val)) { + $val = $this->get($key); + $val->set($relConf[1],NULL); + } else { + if (!$val instanceof Cortex) { + $rel = $this->getRelInstance($relConf[0],null,$key); + $rel->load(array('_id = ?', $val)); + $val = $rel; + } + $val->set($relConf[1], $this->_id); + } + $this->saveCsd[$key] = $val; + return $val; + } elseif (isset($fields[$key]['belongs-to-many'])) { + // many-to-many, unidirectional + $fields[$key]['type'] = self::DT_JSON; + $relConf = $fields[$key]['belongs-to-many']; + $rel_field = (is_array($relConf) ? $relConf[1] : '_id'); + $val = $this->getForeignKeysArray($val, $rel_field, $key); + } + elseif (isset($fields[$key]['has-many'])) { + // many-to-many, bidirectional + $relConf = $fields[$key]['has-many']; + if ($relConf['hasRel'] == 'has-many') { + // custom setter + $val = $this->emit('set_'.$key, $val); + $val = $this->getForeignKeysArray($val,'_id',$key); + $this->saveCsd[$key] = $val; // array of keys + $this->fieldsCache[$key] = $val; + return $val; + } elseif ($relConf['hasRel'] == 'belongs-to-one') { + // TODO: many-to-one, bidirectional, inverse way + trigger_error("not implemented",E_USER_ERROR); + } + } + // convert array content + if (is_array($val) && $this->dbsType == 'sql') + if ($fields[$key]['type'] == self::DT_SERIALIZED) + $val = serialize($val); + elseif ($fields[$key]['type'] == self::DT_JSON) + $val = json_encode($val); + else + trigger_error(sprintf(self::E_ARRAY_DATATYPE, $key),E_USER_ERROR); + // add nullable polyfill + if ($val === NULL && ($this->dbsType == 'jig' || $this->dbsType == 'mongo') + && array_key_exists('nullable', $fields[$key]) && $fields[$key]['nullable'] === false) + trigger_error(sprintf(self::E_NULLABLE_COLLISION,$key),E_USER_ERROR); + // MongoId shorthand + if ($this->dbsType == 'mongo' && !$val instanceof \MongoId) { + if ($key == '_id') + $val = new \MongoId($val); + elseif (preg_match('/INT/i',$fields[$key]['type']) + && !isset($fields[$key]['relType'])) + $val = (int) $val; + } + if (preg_match('/BOOL/i',$fields[$key]['type'])) { + $val = !$val || $val==='false' ? false : (bool) $val; + if ($this->dbsType == 'sql') + $val = (int) $val; + } + } + // fluid SQL + if ($this->fluid && $this->dbsType == 'sql') { + $schema = new Schema($this->db); + $table = $schema->alterTable($this->table); + // add missing field + if (!in_array($key,$table->getCols())) { + // determine data type + if (isset($this->fieldConf[$key]) && isset($this->fieldConf[$key]['type'])) + $type = $this->fieldConf[$key]['type']; + elseif (is_int($val)) $type = $schema::DT_INT; + elseif (is_double($val)) $type = $schema::DT_DOUBLE; + elseif (is_float($val)) $type = $schema::DT_FLOAT; + elseif (is_bool($val)) $type = $schema::DT_BOOLEAN; + elseif (strlen($val)>10 && strtotime($val)) $type = $schema::DT_DATETIME; + elseif (date('Y-m-d H:i:s', strtotime($val)) == $val) $type = $schema::DT_DATETIME; + elseif (date('Y-m-d', strtotime($val)) == $val) $type = $schema::DT_DATE; + elseif (\UTF::instance()->strlen($val)<=255) $type = $schema::DT_VARCHAR256; + else $type = $schema::DT_TEXT; + $table->addColumn($key)->type($type); + $table->build(); + // update mapper fields + $newField = $table->getCols(true); + $newField = $newField[$key]; + $refl = new \ReflectionObject($this->mapper); + $prop = $refl->getProperty('fields'); + $prop->setAccessible(true); + $fields = $prop->getValue($this->mapper); + $fields[$key] = $newField + array('value'=>NULL,'initial'=>NULL,'changed'=>NULL); + $prop->setValue($this->mapper,$fields); + } + } + // custom setter + $val = $this->emit('set_'.$key, $val); + return $this->mapper->set($key, $val); + } - public function skip($ofs = 1) - { - $this->reset(false); - if ($this->mapper->skip($ofs)) - return $this; - else - $this->reset(false); - } + /** + * call custom field handlers + * @param $event + * @param $val + * @return mixed + */ + protected function emit($event, $val=null) { + if (isset($this->trigger[$event])) { + if (preg_match('/^[sg]et_/',$event)) { + $val = (is_string($f=$this->trigger[$event]) + && preg_match('/^[sg]et_/',$f)) + ? call_user_func(array($this,$event),$val) + : \Base::instance()->call($f,array($this,$val)); + } else + $val = \Base::instance()->call($this->trigger[$event],array($this,$val)); + } elseif (preg_match('/^[sg]et_/',$event) && method_exists($this,$event)) { + $this->trigger[] = $event; + $val = call_user_func(array($this,$event),$val); + } + return $val; + } - public function first() - { - $this->reset(false); - $this->mapper->first(); - return $this; - } + /** + * Define a custom field setter + * @param $key + * @param $func + */ + public function onset($key, $func) { + $this->trigger['set_'.$key] = $func; + } - public function last() - { - $this->reset(false); - $this->mapper->last(); - return $this; - } + /** + * Define a custom field getter + * @param $key + * @param $func + */ + public function onget($key, $func) { + $this->trigger['get_'.$key] = $func; + } - /** - * reset and re-initialize the mapper - * @param bool $mapper - * @return NULL|void - */ - public function reset($mapper = true) - { - if ($mapper) - $this->mapper->reset(); - $this->fieldsCache=array(); - $this->saveCsd=array(); - $this->countFields=array(); - $this->preBinds=array(); - $this->grp_stack=null; - // set default values - if (($this->dbsType == 'jig' || $this->dbsType == 'mongo') - && !empty($this->fieldConf)) - foreach($this->fieldConf as $field_key => $field_conf) - if (array_key_exists('default',$field_conf)) { - $val = ($field_conf['default'] === \DB\SQL\Schema::DF_CURRENT_TIMESTAMP) - ? date('Y-m-d H:i:s') : $field_conf['default']; - $this->set($field_key, $val); - } - } + /** + * virtual mapper field setter + * @param string $key + * @param mixed|callback $val + */ + public function virtual($key, $val) { + $this->vFields[$key]=$val; + } - /** - * check if a certain field exists in the mapper or - * or is a virtual relation field - * @param string $key - * @param bool $relField - * @return bool - */ - function exists($key, $relField = false) { - if (!$this->dry() && $key == '_id') return true; - return $this->mapper->exists($key) || - ($relField && isset($this->fieldConf[$key]['relType'])); - } + /** + * Retrieve contents of key + * @return mixed + * @param string $key + * @param bool $raw + */ + function &get($key, $raw = false) { + // handle virtual fields + if (isset($this->vFields[$key])) { + $out = (is_callable($this->vFields[$key])) + ? call_user_func($this->vFields[$key], $this) : $this->vFields[$key]; + return $out; + } + $fields = $this->fieldConf; + $id = $this->primary; + if ($key == '_id' && $this->dbsType == 'sql') + $key = $id; + if ($this->whitelist && !in_array($key,$this->whitelist)) { + $out = null; + return $out; + } + if ($raw) { + $out = $this->exists($key) ? $this->mapper->{$key} : NULL; + return $out; + } + if (!empty($fields) && isset($fields[$key]) && is_array($fields[$key]) + && !array_key_exists($key,$this->fieldsCache)) { + // load relations + if (isset($fields[$key]['belongs-to-one'])) { + // one-to-X, bidirectional, direct way + if (!$this->exists($key) || is_null($this->mapper->{$key})) + $this->fieldsCache[$key] = null; + else { + // get config for this field + $relConf = $fields[$key]['belongs-to-one']; + // fetch related model + $rel = $this->getRelFromConf($relConf,$key); + // am i part of a result collection? + if ($cx = $this->getCollection()) { + // does the collection has cached results for this key? + if (!$cx->hasRelSet($key)) { + // build the cache, find all values of current key + $relKeys = array_unique($cx->getAll($key,true)); + // find related models + $crit = array($relConf[1].' IN ?', $relKeys); + $relSet = $rel->find($this->mergeWithRelFilter($key, $crit), + $this->getRelFilterOption($key),$this->_ttl); + // cache relSet, sorted by ID + $cx->setRelSet($key, $relSet ? $relSet->getBy($relConf[1]) : NULL); + } + // get a subset of the preloaded set + $result = $cx->getSubset($key,(string) $this->get($key,true)); + $this->fieldsCache[$key] = $result ? $result[0] : NULL; + } else { + $crit = array($relConf[1].' = ?', $this->get($key, true)); + $crit = $this->mergeWithRelFilter($key, $crit); + $this->fieldsCache[$key] = $rel->findone($crit, + $this->getRelFilterOption($key),$this->_ttl); + } + } + } + elseif (($type = isset($fields[$key]['has-one'])) + || isset($fields[$key]['has-many'])) { + $type = $type ? 'has-one' : 'has-many'; + $fromConf = $fields[$key][$type]; + if (!is_array($fromConf)) + trigger_error(sprintf(self::E_REL_CONF_INC, $key),E_USER_ERROR); + $rel = $this->getRelInstance($fromConf[0],null,$key,true); + $relFieldConf = $rel->getFieldConfiguration(); + $relType = isset($relFieldConf[$fromConf[1]]['belongs-to-one']) ? + 'belongs-to-one' : 'has-many'; + // one-to-*, bidirectional, inverse way + if ($relType == 'belongs-to-one') { + $toConf = $relFieldConf[$fromConf[1]]['belongs-to-one']; + if(!is_array($toConf)) + $toConf = array($toConf, $id); + if ($toConf[1] != $id && (!$this->exists($toConf[1]) + || is_null($this->mapper->get($toConf[1])))) + $this->fieldsCache[$key] = null; + elseif($cx = $this->getCollection()) { + // part of a result set + if(!$cx->hasRelSet($key)) { + // emit eager loading + $relKeys = $cx->getAll($toConf[1],true); + $crit = array($fromConf[1].' IN ?', $relKeys); + $relSet = $rel->find($this->mergeWithRelFilter($key,$crit), + $this->getRelFilterOption($key),$this->_ttl); + $cx->setRelSet($key, $relSet ? $relSet->getBy($fromConf[1],true) : NULL); + } + $result = $cx->getSubset($key, array($this->get($toConf[1]))); + $this->fieldsCache[$key] = $result ? (($type == 'has-one') + ? $result[0][0] : CortexCollection::factory($result[0])) : NULL; + } else { + $crit = array($fromConf[1].' = ?', $this->get($toConf[1],true)); + $crit = $this->mergeWithRelFilter($key, $crit); + $opt = $this->getRelFilterOption($key); + $this->fieldsCache[$key] = (($type == 'has-one') + ? $rel->findone($crit,$opt,$this->_ttl) + : $rel->find($crit,$opt,$this->_ttl)) ?: NULL; + } + } + // many-to-many, bidirectional + elseif ($relType == 'has-many') { + $toConf = $relFieldConf[$fromConf[1]]['has-many']; + $mmTable = $this->mmTable($fromConf,$key,$toConf); + // create mm table mapper + if (!$this->get($id,true)) { + $this->fieldsCache[$key] = null; + return $this->fieldsCache[$key]; + } + $id = $toConf['relPK']; + $rel = $this->getRelInstance(null,array('db'=>$this->db,'table'=>$mmTable)); + if ($cx = $this->getCollection()) { + if (!$cx->hasRelSet($key)) { + // get IDs of all results + $relKeys = $cx->getAll($id,true); + // get all pivot IDs + $filter = [$fromConf['relField'].' IN ?',$relKeys]; + if ($fromConf['isSelf']) { + $filter[0].= ' OR '.$fromConf['relField'].'_ref IN ?'; + $filter[] = $relKeys; + } + $mmRes = $rel->find($filter,null,$this->_ttl); + if (!$mmRes) + $cx->setRelSet($key, NULL); + else { + $pivotRel = array(); + $pivotKeys = array(); + foreach($mmRes as $model) { + $val = $model->get($key,true); + if ($fromConf['isSelf']) { + $refVal = $model->get($fromConf['relField'].'_ref',true); + $pivotRel[(string) $refVal][] = $val; + $pivotRel[(string) $val][] = $refVal; + $pivotKeys[] = $val; + $pivotKeys[] = $refVal; + } else { + $pivotRel[ (string) $model->get($fromConf['relField'])][] = $val; + $pivotKeys[] = $val; + } + } + // cache pivot keys + $cx->setRelSet($key.'_pivot', $pivotRel); + // preload all rels + $pivotKeys = array_unique($pivotKeys); + $fRel = $this->getRelInstance($fromConf[0],null,$key,true); + $crit = array($id.' IN ?', $pivotKeys); + $relSet = $fRel->find($this->mergeWithRelFilter($key, $crit), + $this->getRelFilterOption($key),$this->_ttl); + $cx->setRelSet($key, $relSet ? $relSet->getBy($id) : NULL); + unset($fRel); + } + } + // fetch subset from preloaded rels using cached pivot keys + $fkeys = $cx->getSubset($key.'_pivot', array($this->get($id))); + $this->fieldsCache[$key] = $fkeys ? + CortexCollection::factory($cx->getSubset($key, $fkeys[0])) : NULL; + } // no collection + else { + // find foreign keys + $fId=$this->get($fromConf['relPK'],true); + $filter = [$fromConf['relField'].' = ?',$fId]; + if ($fromConf['isSelf']) { + $filter = [$fromConf['relField'].' = ?',$fId]; + $filter[0].= ' OR '.$fromConf['relField'].'_ref = ?'; + $filter[] = $filter[1]; + } + $results = $rel->find($filter,null,$this->_ttl); + if (!$results) + $this->fieldsCache[$key] = NULL; + else { + $fkeys = $results->getAll($key,true); + if ($fromConf['isSelf']) { + // merge both rel sides and remove itself + $fkeys = array_diff(array_merge($fkeys, + $results->getAll($key.'_ref',true)),[$fId]); + } + // create foreign table mapper + unset($rel); + $rel = $this->getRelInstance($fromConf[0],null,$key,true); + // load foreign models + $filter = array($toConf['relPK'].' IN ?', $fkeys); + $filter = $this->mergeWithRelFilter($key, $filter); + $this->fieldsCache[$key] = $rel->find($filter, + $this->getRelFilterOption($key),$this->_ttl); + } + } + } + } + elseif (isset($fields[$key]['belongs-to-many'])) { + // many-to-many, unidirectional + $fields[$key]['type'] = self::DT_JSON; + $result = !$this->exists($key) ? null :$this->mapper->get($key); + if ($this->dbsType == 'sql') + $result = json_decode($result, true); + if (!is_array($result)) + $this->fieldsCache[$key] = $result; + else { + // create foreign table mapper + $relConf = $fields[$key]['belongs-to-many']; + $rel = $this->getRelFromConf($relConf,$key); + $fkeys = array(); + foreach ($result as $el) + $fkeys[] = (is_int($el)||ctype_digit($el))?(int)$el:(string)$el; + // if part of a result set + if ($cx = $this->getCollection()) { + if (!$cx->hasRelSet($key)) { + // find all keys + $relKeys = ($cx->getAll($key,true)); + if ($this->dbsType == 'sql'){ + foreach ($relKeys as &$val) { + $val = substr($val, 1, -1); + unset($val); + } + $relKeys = json_decode('['.implode(',',$relKeys).']'); + } else + $relKeys = call_user_func_array('array_merge', $relKeys); + // get related models + if (!empty($relKeys)) { + $crit = array($relConf[1].' IN ?', array_unique($relKeys)); + $relSet = $rel->find($this->mergeWithRelFilter($key, $crit), + $this->getRelFilterOption($key),$this->_ttl); + // cache relSet, sorted by ID + $cx->setRelSet($key, $relSet ? $relSet->getBy($relConf[1]) : NULL); + } else + $cx->setRelSet($key, NULL); + } + // get a subset of the preloaded set + $this->fieldsCache[$key] = CortexCollection::factory($cx->getSubset($key, $fkeys)); + } else { + // load foreign models + $filter = array($relConf[1].' IN ?', $fkeys); + $filter = $this->mergeWithRelFilter($key, $filter); + $this->fieldsCache[$key] = $rel->find($filter, + $this->getRelFilterOption($key),$this->_ttl); + } + } + } + // resolve array fields + elseif (isset($fields[$key]['type'])) { + if ($this->dbsType == 'sql') { + if ($fields[$key]['type'] == self::DT_SERIALIZED) + $this->fieldsCache[$key] = unserialize($this->mapper->{$key}); + elseif ($fields[$key]['type'] == self::DT_JSON) + $this->fieldsCache[$key] = json_decode($this->mapper->{$key},true); + } + if ($this->exists($key) && preg_match('/BOOL/i',$fields[$key]['type'])) { + $this->fieldsCache[$key] = (bool) $this->mapper->{$key}; + } + } + } + // fetch cached value, if existing + $val = array_key_exists($key,$this->fieldsCache) ? $this->fieldsCache[$key] + : (($this->exists($key)) ? $this->mapper->{$key} : null); + if ($this->dbsType == 'mongo' && $val instanceof \MongoId) { + // conversion to string makes further processing in template, etc. much easier + $val = (string) $val; + } + // custom getter + $out = $this->emit('get_'.$key, $val); + return $out; + } - /** - * clear any mapper field or relation - * @param string $key - * @return NULL|void - */ - function clear($key) { - unset($this->fieldsCache[$key]); - if (isset($this->fieldConf[$key]['relType'])) - $this->set($key,null); - $this->mapper->clear($key); - } + /** + * find the ID values of given relation collection + * @param $val string|array|object|bool + * @param $rel_field string + * @param $key string + * @return array|Cortex|null|object + */ + protected function getForeignKeysArray($val, $rel_field, $key) { + if (is_null($val)) + return NULL; + if (is_object($val) && $val instanceof CortexCollection) + $val = $val->expose(); + elseif (is_string($val)) + // split-able string of collection IDs + $val = \Base::instance()->split($val); + elseif (!is_array($val) && !(is_object($val) + && ($val instanceof Cortex && !$val->dry()))) + trigger_error(sprintf(self::E_MM_REL_VALUE, $key),E_USER_ERROR); + // hydrated mapper as collection + if (is_object($val)) { + $nval = array(); + while (!$val->dry()) { + $nval[] = $val->get($rel_field,true); + $val->next(); + } + $val = $nval; + } + elseif (is_array($val)) { + // array of single hydrated mappers, raw ID value or mixed + $isMongo = ($this->dbsType == 'mongo'); + foreach ($val as &$item) { + if (is_object($item) && + !($isMongo && $item instanceof \MongoId)) { + if (!$item instanceof Cortex || $item->dry()) + trigger_error(self::E_INVALID_RELATION_OBJECT,E_USER_ERROR); + else $item = $item->get($rel_field,true); + } + if ($isMongo && $rel_field == '_id' && is_string($item)) + $item = new \MongoId($item); + if (is_numeric($item)) + $item = (int) $item; + unset($item); + } + } + return $val; + } - function insert() { - $res = $this->mapper->insert(); - if (is_array($res)) - $res = $this->mapper; - if (is_object($res)) - $res = $this->factory($res); - return is_int($res) ? $this : $res; - } + /** + * creates and caches related mapper objects + * @param string $model + * @param array $relConf + * @param string $key + * @param bool $pushFilter + * @return Cortex + */ + protected function getRelInstance($model=null, $relConf=null, $key='', $pushFilter=false) { + if (!$model && !$relConf) + trigger_error(self::E_MISSING_REL_CONF,E_USER_ERROR); + $relConf = $model ? $model::resolveConfiguration() : $relConf; + $relName = ($model?:'Cortex').'\\'.$relConf['db']->uuid(). + '\\'.$relConf['table'].'\\'.$key; + if (\Registry::exists($relName)) { + $rel = \Registry::get($relName); + $rel->reset(); + } else { + $rel = $model ? new $model : new Cortex($relConf['db'], $relConf['table']); + if (!$rel instanceof Cortex) + trigger_error(self::E_WRONG_RELATION_CLASS,E_USER_ERROR); + \Registry::set($relName, $rel); + } + // restrict fields of related mapper + if(!empty($key) && isset($this->relWhitelist[$key])) { + if (isset($this->relWhitelist[$key][0])) + $rel->fields($this->relWhitelist[$key][0],false); + if (isset($this->relWhitelist[$key][1])) + $rel->fields($this->relWhitelist[$key][1],true); + } + if ($pushFilter && !empty($key)) { + if (isset($this->relFilter[$key.'.'])) { + foreach($this->relFilter[$key.'.'] as $fkey=>$conf) + $rel->filter($fkey,$conf[0],$conf[1]); + } + if (isset($this->hasCond[$key.'.'])) { + foreach($this->hasCond[$key.'.'] as $fkey=>$conf) + $rel->has($fkey,$conf[0],$conf[1]); + } + } + return $rel; + } - function update() { - $res = $this->mapper->update(); - if (is_array($res)) - $res = $this->mapper; - if (is_object($res)) - $res = $this->factory($res); - return is_int($res) ? $this : $res; - } + /** + * get relation model from config + * @param $fieldConf + * @param $key + * @return Cortex + */ + protected function getRelFromConf(&$fieldConf, $key) { + if (!is_array($fieldConf)) + $fieldConf = array($fieldConf, '_id'); + $rel = $this->getRelInstance($fieldConf[0],null,$key,true); + if($this->dbsType=='sql' && $fieldConf[1] == '_id') + $fieldConf[1] = $rel->primary; + return $rel; + } - function dbtype() { - return $this->mapper->dbtype(); - } + /** + * returns a clean/dry model from a relation + * @param string $key + * @return Cortex + */ + public function rel($key) { + $rt = $this->fieldConf[$key]['relType']; + $rc = $this->fieldConf[$key][$rt]; + if (!is_array($rc)) + $rc = array($rc,'_id'); + return $this->getRelInstance($rc[0],null,$key); + } - public function __destruct() { - unset($this->mapper); - } + /** + * Return fields of mapper object as an associative array + * @return array + * @param bool|Cortex $obj + * @param int|array $rel_depths depths to resolve relations + */ + public function cast($obj = NULL, $rel_depths = 1) { + $fields = $this->mapper->cast( ($obj) ? $obj->mapper : null ); + if (!empty($this->vFields)) + foreach(array_keys($this->vFields) as $key) + $fields[$key]=$this->get($key); + if (is_int($rel_depths)) + $rel_depths = array('*'=>$rel_depths-1); + elseif (is_array($rel_depths)) + $rel_depths['*'] = isset($rel_depths['*'])?--$rel_depths['*']:-1; + if (!empty($this->fieldConf)) { + $fields += array_fill_keys(array_keys($this->fieldConf),NULL); + if($this->whitelist) + $fields = array_intersect_key($fields, array_flip($this->whitelist)); + $mp = $obj ? : $this; + foreach ($fields as $key => &$val) { + // post process configured fields + if (isset($this->fieldConf[$key]) && is_array($this->fieldConf[$key])) { + // handle relations + $rd = isset($rel_depths[$key]) ? $rel_depths[$key] : $rel_depths['*']; + if ((is_array($rd) || $rd >= 0) && $type=preg_grep('/[belongs|has]-(to-)*[one|many]/', + array_keys($this->fieldConf[$key]))) { + $relType=current($type); + // cast relations + $val = (($relType == 'belongs-to-one' || $relType == 'belongs-to-many') + && !$mp->exists($key)) ? NULL : $mp->get($key); + if ($val instanceof Cortex) + $val = $val->cast(null, $rd); + elseif ($val instanceof CortexCollection) + $val = $val->castAll($rd); + } + // extract array fields + elseif (isset($this->fieldConf[$key]['type'])) { + if ($this->dbsType == 'sql') { + if ($this->fieldConf[$key]['type'] == self::DT_SERIALIZED) + $val=unserialize($mp->mapper->{$key}); + elseif ($this->fieldConf[$key]['type'] == self::DT_JSON) + $val=json_decode($mp->mapper->{$key}, true); + } + if ($this->exists($key) + && preg_match('/BOOL/i',$this->fieldConf[$key]['type'])) { + $val = (bool) $mp->mapper->{$key}; + } + } + } + if ($this->dbsType == 'mongo' && $key == '_id') + $val = (string) $val; + if ($this->dbsType == 'sql' && $key == 'id' && $this->standardiseID) { + $fields['_id'] = $val; + unset($fields[$key]); + } + unset($val); + } + } + // custom getter + foreach ($fields as $key => &$val) { + $val = $this->emit('get_'.$key, $val); + unset($val); + } + return $fields; + } - public function __clone() { - $this->mapper = clone($this->mapper); - } + /** + * cast a related collection of mappers + * @param string $key field name + * @param int $rel_depths depths to resolve relations + * @return array array of associative arrays + */ + function castField($key, $rel_depths=0) { + if (!$key) + return NULL; + $mapper_arr = $this->get($key); + if(!$mapper_arr) + return NULL; + $out = array(); + foreach ($mapper_arr as $mp) + $out[] = $mp->cast(null,$rel_depths); + return $out; + } - function getiterator() { + /** + * wrap result mapper + * @param Cursor|array $mapper + * @return Cortex + */ + protected function factory($mapper) { + if (is_array($mapper)) { + $mp = clone($this->mapper); + $mp->reset(); + $cx = $this->factory($mp); + $cx->copyfrom($mapper); + } else { + $cx = clone($this); + $cx->reset(false); + $cx->mapper = $mapper; + } + $cx->emit('load'); + return $cx; + } + + public function dry() { + return $this->mapper->dry(); + } + + /** + * hydrate the mapper from hive key or given array + * @param string|array $key + * @param callback|array|string $fields + * @return NULL + */ + public function copyfrom($key, $fields = null) { + $f3 = \Base::instance(); + $srcfields = is_array($key) ? $key : $f3->get($key); + if ($fields) + if (is_callable($fields)) + $srcfields = $fields($srcfields); + else { + if (is_string($fields)) + $fields = $f3->split($fields); + $srcfields = array_intersect_key($srcfields, array_flip($fields)); + } + foreach ($srcfields as $key => $val) { + if (isset($this->fieldConf[$key]) && isset($this->fieldConf[$key]['type'])) { + if ($this->fieldConf[$key]['type'] == self::DT_JSON && is_string($val)) + $val = json_decode($val); + elseif ($this->fieldConf[$key]['type'] == self::DT_SERIALIZED && is_string($val)) + $val = unserialize($val); + } + $this->set($key, $val); + } + } + + /** + * copy mapper values into hive key + * @param string $key the hive key to copy into + * @param int $relDepth the depth of relations to resolve + * @return NULL|void + */ + public function copyto($key, $relDepth=0) { + \Base::instance()->set($key, $this->cast(null,$relDepth)); + } + + public function skip($ofs = 1) { + $this->reset(false); + if ($this->mapper->skip($ofs)) + return $this; + else + $this->reset(false); + } + + public function first() { + $this->reset(false); + $this->mapper->first(); + return $this; + } + + public function last() { + $this->reset(false); + $this->mapper->last(); + return $this; + } + + /** + * reset and re-initialize the mapper + * @param bool $mapper + * @return NULL|void + */ + public function reset($mapper = true) { + if ($mapper) + $this->mapper->reset(); + $this->fieldsCache=array(); + $this->saveCsd=array(); + $this->countFields=array(); + $this->preBinds=array(); + $this->grp_stack=null; + // set default values + if (($this->dbsType == 'jig' || $this->dbsType == 'mongo') + && !empty($this->fieldConf)) + foreach($this->fieldConf as $field_key => $field_conf) + if (array_key_exists('default',$field_conf)) { + $val = ($field_conf['default'] === \DB\SQL\Schema::DF_CURRENT_TIMESTAMP) + ? date('Y-m-d H:i:s') : $field_conf['default']; + $this->set($field_key, $val); + } + } + + /** + * check if a certain field exists in the mapper or + * or is a virtual relation field + * @param string $key + * @param bool $relField + * @return bool + */ + function exists($key, $relField = false) { + if (!$this->dry() && $key == '_id') return true; + return $this->mapper->exists($key) || + ($relField && isset($this->fieldConf[$key]['relType'])); + } + + /** + * clear any mapper field or relation + * @param string $key + * @return NULL|void + */ + function clear($key) { + unset($this->fieldsCache[$key]); + if (isset($this->fieldConf[$key]['relType'])) + $this->set($key,null); + $this->mapper->clear($key); + } + + function insert() { + $res = $this->mapper->insert(); + if (is_array($res)) + $res = $this->mapper; + if (is_object($res)) + $res = $this->factory($res); + return is_int($res) ? $this : $res; + } + + function update() { + $res = $this->mapper->update(); + if (is_array($res)) + $res = $this->mapper; + if (is_object($res)) + $res = $this->factory($res); + return is_int($res) ? $this : $res; + } + + function dbtype() { + return $this->mapper->dbtype(); + } + + public function __clone() { + $this->mapper = clone($this->mapper); + } + + function getiterator() { // return new \ArrayIterator($this->cast(null,false)); - return new \ArrayIterator(array()); - } + return new \ArrayIterator(array()); + } } class CortexQueryParser extends \Prefab { - const - E_BRACKETS = 'Invalid query: unbalanced brackets found', - E_INBINDVALUE = 'Bind value for IN operator must be a populated array', - E_ENGINEERROR = 'Engine not supported', - E_MISSINGBINDKEY = 'Named bind parameter `%s` does not exist in filter arguments'; + const + E_BRACKETS = 'Invalid query: unbalanced brackets found', + E_INBINDVALUE = 'Bind value for IN operator must be a populated array', + E_ENGINEERROR = 'Engine not supported', + E_MISSINGBINDKEY = 'Named bind parameter `%s` does not exist in filter arguments'; - protected - $queryCache = array(); + protected + $queryCache = array(); - /** - * converts the given filter array to fit the used DBS - * - * example filter: - * array('text = ? AND num = ?','bar',5) - * array('num > ? AND num2 <= ?',5,10) - * array('num1 > num2') - * array('text like ?','%foo%') - * array('(text like ? OR text like ?) AND num != ?','foo%','%bar',23) - * - * @param array $cond - * @param string $engine - * @param null $fieldConf - * @return array|bool|null - */ - public function prepareFilter($cond, $engine,$fieldConf=null) - { - if (is_null($cond)) return $cond; - if (is_string($cond)) - $cond = array($cond); - $f3 = \Base::instance(); - $cacheHash = $f3->hash($f3->stringify($cond)).'.'.$engine; - if (isset($this->queryCache[$cacheHash])) - // load from memory - return $this->queryCache[$cacheHash]; - elseif ($f3->exists('CORTEX.queryParserCache') - && ($ttl = (int) $f3->get('CORTEX.queryParserCache'))) { - $cache = \Cache::instance(); - // load from cache - if ($f3->get('CACHE') && $ttl && ($cached = $cache->exists($cacheHash, $ncond)) - && $cached[0] + $ttl > microtime(TRUE)) { - $this->queryCache[$cacheHash] = $ncond; - return $ncond; - } - } - $where = array_shift($cond); - $args = $cond; - $where = str_replace(array('&&', '||'), array('AND', 'OR'), $where); - // prepare IN condition - $where = preg_replace('/\bIN\b\s*\(\s*(\?|:\w+)?\s*\)/i', 'IN $1', $where); - switch ($engine) { - case 'jig': - $ncond = $this->_jig_parse_filter($where, $args); - break; - case 'mongo': - $parts = $this->splitLogical($where); - if (is_int(strpos($where, ':'))) - list($parts, $args) = $this->convertNamedParams($parts, $args); - foreach ($parts as &$part) { - $part = $this->_mongo_parse_relational_op($part, $args, $fieldConf); - unset($part); - } - $ncond = $this->_mongo_parse_logical_op($parts); - break; - case 'sql': - // preserve identifier - $where = preg_replace('/(?!\B)_id/', 'id', $where); - $parts = $this->splitLogical($where); - // ensure positional bind params - if (is_int(strpos($where, ':'))) - list($parts, $args) = $this->convertNamedParams($parts, $args); - $ncond = array(); - foreach ($parts as &$part) { - // enhanced IN handling - if (is_int(strpos($part, '?'))) { - $val = array_shift($args); - if (is_int($pos = strpos($part, 'IN ?'))) { - if (!is_array($val) || empty($val)) - trigger_error(self::E_INBINDVALUE); - $bindMarks = str_repeat('?,', count($val) - 1).'?'; - $part = substr($part, 0, $pos).'IN ('.$bindMarks.')'; - $ncond = array_merge($ncond, $val); - } else - $ncond[] = $val; - } - unset($part); - } - array_unshift($ncond, array_reduce($parts,function($out,$part){ - return $out.((!$out||in_array($part,array('(',')')) - ||preg_match('/\($/',$out))?'':' ').$part; - },'')); - break; - default: - trigger_error(self::E_ENGINEERROR); - } - $this->queryCache[$cacheHash] = $ncond; - if(isset($ttl) && $f3->get('CACHE')) { - // save to cache - $cache = \Cache::instance(); - $cache->set($cacheHash,$ncond,$ttl); - } - return $ncond; - } + /** + * converts the given filter array to fit the used DBS + * + * example filter: + * array('text = ? AND num = ?','bar',5) + * array('num > ? AND num2 <= ?',5,10) + * array('num1 > num2') + * array('text like ?','%foo%') + * array('(text like ? OR text like ?) AND num != ?','foo%','%bar',23) + * + * @param array $cond + * @param string $engine + * @param object $db + * @param null $fieldConf + * @return array|bool|null + */ + public function prepareFilter($cond, $engine, $db, $fieldConf=null) { + if (is_null($cond)) return $cond; + if (is_string($cond)) + $cond = array($cond); + $f3 = \Base::instance(); + $cacheHash = $f3->hash($f3->stringify($cond)).'.'.$engine; + if ($engine=='sql') + $cacheHash.='-'.$db->driver(); + if (isset($this->queryCache[$cacheHash])) + // load from memory + return $this->queryCache[$cacheHash]; + elseif ($f3->exists('CORTEX.queryParserCache') + && ($ttl = (int) $f3->get('CORTEX.queryParserCache'))) { + $cache = \Cache::instance(); + // load from cache + if ($f3->get('CACHE') && $ttl && ($cached = $cache->exists($cacheHash, $ncond)) + && $cached[0] + $ttl > microtime(TRUE)) { + $this->queryCache[$cacheHash] = $ncond; + return $ncond; + } + } + $where = array_shift($cond); + $args = $cond; + $where = str_replace(array('&&', '||'), array('AND', 'OR'), $where); + // prepare IN condition + $where = preg_replace('/\bIN\b\s*\(\s*(\?|:\w+)?\s*\)/i', 'IN $1', $where); + switch ($engine) { + case 'jig': + $ncond = $this->_jig_parse_filter($where, $args); + break; + case 'mongo': + $parts = $this->splitLogical($where); + if (is_int(strpos($where, ':'))) + list($parts, $args) = $this->convertNamedParams($parts, $args); + foreach ($parts as &$part) { + $part = $this->_mongo_parse_relational_op($part, $args, $fieldConf); + unset($part); + } + $ncond = $this->_mongo_parse_logical_op($parts); + break; + case 'sql': + if (!$f3->exists('CORTEX.quoteConditions',$qc) || $qc) + $where = $this->sql_quoteCondition($where,$db); + // preserve identifier + $where = preg_replace('/(?!\B)_id/', 'id', $where); + if ($db->driver() == 'pgsql') + $where = preg_replace('/\s+like\s+/i', ' ILIKE ', $where); + $parts = $this->splitLogical($where); + // ensure positional bind params + if (is_int(strpos($where, ':'))) + list($parts, $args) = $this->convertNamedParams($parts, $args); + $ncond = array(); + foreach ($parts as &$part) { + // enhanced IN handling + if (is_int(strpos($part, '?'))) { + $val = array_shift($args); + if (is_int($pos = strpos($part, 'IN ?'))) { + if (!is_array($val) || empty($val)) + trigger_error(self::E_INBINDVALUE,E_USER_ERROR); + $bindMarks = str_repeat('?,', count($val) - 1).'?'; + $part = substr($part, 0, $pos).'IN ('.$bindMarks.')'; + $ncond = array_merge($ncond, $val); + } elseif($val === null && preg_match('/(\w+)\s*([!=<>]+)\s*\?/i',$part,$match)) { + $part = $match[1].' IS '.($match[2]=='='||$match[2]=='=='?'':'NOT ').'NULL'; + } else + $ncond[] = $val; + } + unset($part); + } + array_unshift($ncond, implode($parts)); +// array_unshift($ncond, array_reduce($parts,function($out,$part){ +// return $out.((!$out||in_array($part,array('(',')')) +// ||preg_match('/\($/',$out))?'':' ').$part; +// },'')); + break; + default: + trigger_error(self::E_ENGINEERROR,E_USER_ERROR); + } + $this->queryCache[$cacheHash] = $ncond; + if(isset($ttl) && $f3->get('CACHE')) { + // save to cache + $cache = \Cache::instance(); + $cache->set($cacheHash,$ncond,$ttl); + } + return $ncond; + } - /** - * split where criteria string into logical chunks - * @param $cond - * @return array - */ - protected function splitLogical($cond) - { - return preg_split('/\s*((?splitLogical($where); - if (is_int(strpos($where, ':'))) - list($parts, $args) = $this->convertNamedParams($parts, $args); - $ncond = array(); - foreach ($parts as &$part) { - if (in_array(strtoupper($part), array('AND', 'OR'))) - continue; - // prefix field names - $part = preg_replace('/([a-z_-]+)/i', '@$1', $part, -1, $count); - // value comparison - if (is_int(strpos($part, '?'))) { - $val = array_shift($args); - preg_match('/(@\w+)/i', $part, $match); - $skipVal=false; - // find like operator - if (is_int(strpos($upart = strtoupper($part), ' @LIKE '))) { - if ($not = is_int($npos = strpos($upart, '@NOT'))) - $pos = $npos; - $val = $this->_likeValueToRegEx($val); - $part = ($not ? '!' : '').'preg_match(?,'.$match[0].')'; - } // find IN operator - elseif (is_int($pos = strpos($upart, ' @IN '))) { - if ($not = is_int($npos = strpos($upart, '@NOT'))) - $pos = $npos; - $part = ($not ? '!' : '').'in_array('.substr($part, 0, $pos). - ',array(\''.implode('\',\'', $val).'\'))'; - $skipVal=true; - } - // add existence check - $part = ($val===null && !$skipVal) - ? '(array_key_exists(\''.ltrim($match[0],'@').'\',$_row) && '.$part.')' - : '(isset('.$match[0].') && '.$part.')'; - if (!$skipVal) - $ncond[] = $val; - } elseif ($count >= 1) { - // field comparison - preg_match_all('/(@\w+)/i', $part, $matches); - $chks = array(); - foreach ($matches[0] as $field) - $chks[] = 'isset('.$field.')'; - $part = '('.implode(' && ',$chks).' && ('.$part.'))'; - } - unset($part); - } - array_unshift($ncond, implode(' ', $parts)); - return $ncond; - } + /** + * quote identifiers in condition + * @param string $cond + * @param object $db + * @param string|bool $table + * @return string + */ + public function sql_quoteCondition($cond, $db, $table=false) { + // https://www.debuggex.com/r/6AXwJ1Y3Aac8aocQ/3 + // https://regex101.com/r/yM5vK4/1 + // this took me lots of sleepless nights + return preg_replace_callback('/'. + '(\w+\((?:[^)(]+|(?R))*\))|'. // exclude SQL function names "foo(" + '(?:(\b(?=!)]|$))/i', // only when part of condition or within brackets + function($match) use($table,$db) { + if (!isset($match[2])) + return $match[1]; + if (preg_match('/\b(AND|OR|IN|LIKE|NOT)\b/i',$match[2])) + return $match[2]; + return $db->quotekey(($table?$table.'.':'').$match[2]); + }, $cond); + } - /** - * find and wrap logical operators AND, OR, (, ) - * @param $parts - * @return array - */ - protected function _mongo_parse_logical_op($parts) - { - $b_offset = 0; - $ncond = array(); - $child = array(); - for ($i = 0, $max = count($parts); $i < $max; $i++) { - $part = $parts[$i]; - if ($part == '(') { - // add sub-bracket to parse array - if ($b_offset > 0) - $child[] = $part; - $b_offset++; - } elseif ($part == ')') { - $b_offset--; - // found closing bracket - if ($b_offset == 0) { - $ncond[] = ($this->_mongo_parse_logical_op($child)); - $child = array(); - } elseif ($b_offset < 0) - trigger_error(self::E_BRACKETS); - else - // add sub-bracket to parse array - $child[] = $part; - } // add to parse array - elseif ($b_offset > 0) - $child[] = $part; - // condition type - elseif (!is_array($part)) { - if (strtoupper($part) == 'AND') - $add = true; - elseif (strtoupper($part) == 'OR') - $or = true; - } else // skip - $ncond[] = $part; - } - if ($b_offset > 0) - trigger_error(self::E_BRACKETS); - if (isset($add)) - return array('$and' => $ncond); - elseif (isset($or)) - return array('$or' => $ncond); - else - return $ncond[0]; - } + /** + * convert filter array to jig syntax + * @param $where + * @param $args + * @return array + */ + protected function _jig_parse_filter($where, $args) { + $parts = $this->splitLogical($where); + if (is_int(strpos($where, ':'))) + list($parts, $args) = $this->convertNamedParams($parts, $args); + $ncond = array(); + foreach ($parts as &$part) { + if (preg_match('/\s*\b(AND|OR)\b\s*/i',$part)) + continue; + // prefix field names + $part = preg_replace('/([a-z_-]+)/i', '@$1', $part, -1, $count); + // value comparison + if (is_int(strpos($part, '?'))) { + $val = array_shift($args); + preg_match('/(@\w+)/i', $part, $match); + $skipVal=false; + // find like operator + if (is_int(strpos($upart = strtoupper($part), ' @LIKE '))) { + if ($not = is_int($npos = strpos($upart, '@NOT'))) + $pos = $npos; + $val = $this->_likeValueToRegEx($val); + $part = ($not ? '!' : '').'preg_match(?,'.$match[0].')'; + } // find IN operator + elseif (is_int($pos = strpos($upart, ' @IN '))) { + if ($not = is_int($npos = strpos($upart, '@NOT'))) + $pos = $npos; + $part = ($not ? '!' : '').'in_array('.substr($part, 0, $pos). + ',array(\''.implode('\',\'', $val).'\'))'; + $skipVal=true; + } + elseif($val===null && preg_match('/(\w+)\s*([!=<>]+)\s*\?/i',$part,$nmatch) + && ($nmatch[2]=='=' || $nmatch[2]=='==')){ + $part = '(!array_key_exists(\''.ltrim($nmatch[1],'@').'\',$_row))'; + unset($part); + continue; + } + // add existence check + $part = ($val===null && !$skipVal) + ? '(array_key_exists(\''.ltrim($match[0],'@').'\',$_row) && '.$part.')' + : '(isset('.$match[0].') && '.$part.')'; + if (!$skipVal) + $ncond[] = $val; + } elseif ($count >= 1) { + // field comparison + preg_match_all('/(@\w+)/i', $part, $matches); + $chks = array(); + foreach ($matches[0] as $field) + $chks[] = 'isset('.$field.')'; + $part = '('.implode(' && ',$chks).' && ('.$part.'))'; + } + unset($part); + } + array_unshift($ncond, implode(' ', $parts)); + return $ncond; + } - /** - * find and convert relational operators - * @param $part - * @param $args - * @param null $fieldConf - * @return array|null - */ - protected function _mongo_parse_relational_op($part, &$args, $fieldConf=null) - { - if (is_null($part)) - return $part; - if (preg_match('/\<\=|\>\=|\<\>|\<|\>|\!\=|\=\=|\=|like|not like|in|not in/i', $part, $match)) { - $var = is_int(strpos($part, '?')) ? array_shift($args) : null; - $exp = explode($match[0], $part); - $key = trim($exp[0]); - // unbound value - if (is_numeric($exp[1])) - $var = $exp[1]; - // field comparison - elseif (!is_int(strpos($exp[1], '?'))) - return array('$where' => 'this.'.$key.' '.$match[0].' this.'.trim($exp[1])); - $upart = strtoupper($match[0]); - // MongoID shorthand - if ($key == '_id' || (isset($fieldConf[$key]) && isset($fieldConf[$key]['relType']))) { - if (is_array($var)) - foreach ($var as &$id) { - if (!$id instanceof \MongoId) - $id = new \MongoId($id); - unset($id); - } - elseif(!$var instanceof \MongoId) - $var = new \MongoId($var); - } - // find LIKE operator - if (in_array($upart, array('LIKE','NOT LIKE'))) { - $rgx = $this->_likeValueToRegEx($var); - $var = new \MongoRegex($rgx); - if ($upart == 'NOT LIKE') - $var = array('$not' => $var); - } // find IN operator - elseif (in_array($upart, array('IN','NOT IN'))) { - $var = array(($upart=='NOT IN')?'$nin':'$in' => array_values($var)); - } // translate operators - elseif (!in_array($match[0], array('==', '='))) { - $opr = str_replace(array('<>', '<', '>', '!', '='), - array('$ne', '$lt', '$gt', '$n', 'e'), $match[0]); - $var = array($opr => (strtolower($var) == 'null') ? null : - (is_object($var) ? $var : (is_numeric($var) ? $var + 0 : $var))); - } - return array($key => $var); - } - return $part; - } + /** + * find and wrap logical operators AND, OR, (, ) + * @param $parts + * @return array + */ + protected function _mongo_parse_logical_op($parts) { + $b_offset = 0; + $ncond = array(); + $child = array(); + for ($i = 0, $max = count($parts); $i < $max; $i++) { + $part = $parts[$i]; + if ($part == '(') { + // add sub-bracket to parse array + if ($b_offset > 0) + $child[] = $part; + $b_offset++; + } elseif ($part == ')') { + $b_offset--; + // found closing bracket + if ($b_offset == 0) { + $ncond[] = ($this->_mongo_parse_logical_op($child)); + $child = array(); + } elseif ($b_offset < 0) + trigger_error(self::E_BRACKETS,E_USER_ERROR); + else + // add sub-bracket to parse array + $child[] = $part; + } // add to parse array + elseif ($b_offset > 0) + $child[] = $part; + // condition type + elseif (!is_array($part)) { + if (strtoupper(trim($part)) == 'AND') + $add = true; + elseif (strtoupper(trim($part)) == 'OR') + $or = true; + } else // skip + $ncond[] = $part; + } + if ($b_offset > 0) + trigger_error(self::E_BRACKETS,E_USER_ERROR); + if (isset($add)) + return array('$and' => $ncond); + elseif (isset($or)) + return array('$or' => $ncond); + else + return $ncond[0]; + } - /** - * @param string $var - * @return string - */ - protected function _likeValueToRegEx($var) - { - $lC = substr($var, -1, 1); - // %var% -> /var/ - if ($var[0] == '%' && $lC == '%') - $var = substr($var, 1, -1); - // var% -> /^var/ - elseif ($lC == '%') - $var = '^'.substr($var, 0, -1); - // %var -> /var$/ - elseif ($var[0] == '%') - $var = substr($var, 1).'$'; - return '/'.$var.'/iu'; - } + /** + * find and convert relational operators + * @param $part + * @param $args + * @param null $fieldConf + * @return array|null + */ + protected function _mongo_parse_relational_op($part, &$args, $fieldConf=null) { + if (is_null($part)) + return $part; + if (preg_match('/\<\=|\>\=|\<\>|\<|\>|\!\=|\=\=|\=|like|not like|in|not in/i', $part, $match)) { + $var = is_int(strpos($part, '?')) ? array_shift($args) : null; + $exp = explode($match[0], $part); + $key = trim($exp[0]); + // unbound value + if (is_numeric($exp[1])) + $var = $exp[1]; + // field comparison + elseif (!is_int(strpos($exp[1], '?'))) + return array('$where' => 'this.'.$key.' '.$match[0].' this.'.trim($exp[1])); + $upart = strtoupper($match[0]); + // MongoID shorthand + if ($key == '_id' || (isset($fieldConf[$key]) && isset($fieldConf[$key]['relType']))) { + if (is_array($var)) + foreach ($var as &$id) { + if (!$id instanceof \MongoId) + $id = new \MongoId($id); + unset($id); + } + elseif(!$var instanceof \MongoId) + $var = new \MongoId($var); + } + // find LIKE operator + if (in_array($upart, array('LIKE','NOT LIKE'))) { + $rgx = $this->_likeValueToRegEx($var); + $var = new \MongoRegex($rgx); + if ($upart == 'NOT LIKE') + $var = array('$not' => $var); + } // find IN operator + elseif (in_array($upart, array('IN','NOT IN'))) { + $var = array(($upart=='NOT IN')?'$nin':'$in' => array_values($var)); + } // translate operators + elseif (!in_array($match[0], array('==', '='))) { + $opr = str_replace(array('<>', '<', '>', '!', '='), + array('$ne', '$lt', '$gt', '$n', 'e'), $match[0]); + $var = array($opr => (strtolower($var) == 'null') ? null : + (is_object($var) ? $var : (is_numeric($var) ? $var + 0 : $var))); + } + return array($key => $var); + } + return $part; + } - /** - * convert options array syntax to given engine type - * - * example: - * array('order'=>'location') // default direction is ASC - * array('order'=>'num1 desc, num2 asc') - * - * @param array $options - * @param string $engine - * @return array|null - */ - public function prepareOptions($options, $engine) - { - if (empty($options) || !is_array($options)) - return null; - switch ($engine) { - case 'jig': - if (array_key_exists('order', $options)) - $options['order'] = str_replace(array('asc', 'desc'), - array('SORT_ASC', 'SORT_DESC'), strtolower($options['order'])); - break; - case 'mongo': - if (array_key_exists('order', $options)) { - $sorts = explode(',', $options['order']); - $sorting = array(); - foreach ($sorts as $sort) { - $sp = explode(' ', trim($sort)); - $sorting[$sp[0]] = (array_key_exists(1, $sp) && - strtoupper($sp[1]) == 'DESC') ? -1 : 1; - } - $options['order'] = $sorting; - } - if (array_key_exists('group', $options) && is_string($options['group'])) { - $keys = explode(',',$options['group']); - $options['group']=array('keys'=>array(),'initial'=>array(), - 'reduce'=>'function (obj, prev) {}','finalize'=>''); - $keys = array_combine($keys,array_fill(0,count($keys),1)); - $options['group']['keys']=$keys; - $options['group']['initial']=$keys; - } - break; - } - return $options; - } + /** + * @param string $var + * @return string + */ + protected function _likeValueToRegEx($var) { + $lC = substr($var, -1, 1); + // %var% -> /var/ + if ($var[0] == '%' && $lC == '%') + $var = substr($var, 1, -1); + // var% -> /^var/ + elseif ($lC == '%') + $var = '^'.substr($var, 0, -1); + // %var -> /var$/ + elseif ($var[0] == '%') + $var = substr($var, 1).'$'; + return '/'.$var.'/iu'; + } + + /** + * convert options array syntax to given engine type + * + * example: + * array('order'=>'location') // default direction is ASC + * array('order'=>'num1 desc, num2 asc') + * + * @param array $options + * @param string $engine + * @return array|null + */ + public function prepareOptions($options, $engine) { + if (empty($options) || !is_array($options)) + return null; + switch ($engine) { + case 'jig': + if (array_key_exists('order', $options)) + $options['order'] = str_replace(array('asc', 'desc'), + array('SORT_ASC', 'SORT_DESC'), strtolower($options['order'])); + break; + case 'mongo': + if (array_key_exists('order', $options)) { + $sorts = explode(',', $options['order']); + $sorting = array(); + foreach ($sorts as $sort) { + $sp = explode(' ', trim($sort)); + $sorting[$sp[0]] = (array_key_exists(1, $sp) && + strtoupper($sp[1]) == 'DESC') ? -1 : 1; + } + $options['order'] = $sorting; + } + if (array_key_exists('group', $options) && is_string($options['group'])) { + $keys = explode(',',$options['group']); + $options['group']=array('keys'=>array(),'initial'=>array(), + 'reduce'=>'function (obj, prev) {}','finalize'=>''); + $keys = array_combine($keys,array_fill(0,count($keys),1)); + $options['group']['keys']=$keys; + $options['group']['initial']=$keys; + } + break; + } + return $options; + } } class CortexCollection extends \ArrayIterator { - protected - $relSets = array(), - $pointer = 0, - $changed = false, - $cid; + protected + $relSets = array(), + $pointer = 0, + $changed = false, + $cid; - const - E_UnknownCID = 'This Collection does not exist: %s', - E_SubsetKeysValue = '$keys must be an array or split-able string, but %s was given.'; + const + E_UnknownCID = 'This Collection does not exist: %s', + E_SubsetKeysValue = '$keys must be an array or split-able string, but %s was given.'; - public function __construct() { - $this->cid = uniqid('cortex_collection_'); - parent::__construct(); - } + public function __construct() { + $this->cid = uniqid('cortex_collection_'); + parent::__construct(); + } - //! Prohibit cloning to ensure an existing relation cache - private function __clone() { } + //! Prohibit cloning to ensure an existing relation cache + private function __clone() { } - /** - * set a collection of models - * @param $models - */ - function setModels($models,$init=true) { - array_map(array($this,'add'),$models); - if ($init) - $this->changed = false; - } + /** + * set a collection of models + * @param $models + */ + function setModels($models, $init=true) { + array_map(array($this,'add'),$models); + if ($init) + $this->changed = false; + } - /** - * add single model to collection - * @param $model - */ - function add(Cortex $model) { - $model->addToCollection($this); - $this->append($model); - } + /** + * add single model to collection + * @param $model + */ + function add(Cortex $model) { + $model->addToCollection($this); + $this->append($model); + } - public function offsetSet($i, $val) { - $this->changed=true; - parent::offsetSet($i,$val); - } + public function offsetSet($i, $val) { + $this->changed=true; + parent::offsetSet($i,$val); + } - public function hasChanged() { - return $this->changed; - } + public function hasChanged() { + return $this->changed; + } - /** - * get a related collection - * @param $key - * @return null - */ - public function getRelSet($key) { - return (isset($this->relSets[$key])) ? $this->relSets[$key] : null; - } + /** + * get a related collection + * @param $key + * @return null + */ + public function getRelSet($key) { + return (isset($this->relSets[$key])) ? $this->relSets[$key] : null; + } - /** - * set a related collection for caching it for the lifetime of this collection - * @param $key - * @param $set - */ - public function setRelSet($key,$set) { - $this->relSets[$key] = $set; - } + /** + * set a related collection for caching it for the lifetime of this collection + * @param $key + * @param $set + */ + public function setRelSet($key,$set) { + $this->relSets[$key] = $set; + } - /** - * check if a related collection exists in runtime cache - * @param $key - * @return bool - */ - public function hasRelSet($key) { - return array_key_exists($key,$this->relSets); - } + /** + * check if a related collection exists in runtime cache + * @param $key + * @return bool + */ + public function hasRelSet($key) { + return array_key_exists($key,$this->relSets); + } - public function expose() { - return $this->getArrayCopy(); - } + public function expose() { + return $this->getArrayCopy(); + } - /** - * get an intersection from a cached relation-set, based on given keys - * @param string $prop - * @param array|string $keys - * @return array - */ - public function getSubset($prop,$keys) { - if (is_string($keys)) - $keys = \Base::instance()->split($keys); - if (!is_array($keys)) - trigger_error(sprintf(self::E_SubsetKeysValue,gettype($keys))); - if (!$this->hasRelSet($prop) || !($relSet = $this->getRelSet($prop))) - return null; - foreach ($keys as &$key) { - if ($key instanceof \MongoId) - $key = (string) $key; - unset($key); - } - return array_values(array_intersect_key($relSet, array_flip($keys))); - } + /** + * get an intersection from a cached relation-set, based on given keys + * @param string $prop + * @param array|string $keys + * @return array + */ + public function getSubset($prop, $keys) { + if (is_string($keys)) + $keys = \Base::instance()->split($keys); + if (!is_array($keys)) + trigger_error(sprintf(self::E_SubsetKeysValue,gettype($keys)),E_USER_ERROR); + if (!$this->hasRelSet($prop) || !($relSet = $this->getRelSet($prop))) + return null; + foreach ($keys as &$key) { + if ($key instanceof \MongoId) + $key = (string) $key; + unset($key); + } + return array_values(array_intersect_key($relSet, array_flip($keys))); + } - /** - * returns all values of a specified property from all models - * @param string $prop - * @param bool $raw - * @return array - */ - public function getAll($prop, $raw = false) - { - $out = array(); - foreach ($this->getArrayCopy() as $model) { - if ($model instanceof Cortex && $model->exists($prop,true)) { - $val = $model->get($prop, $raw); - if (!empty($val)) - $out[] = $val; - } elseif($raw) - $out[] = $model; - } - return $out; - } + /** + * returns all values of a specified property from all models + * @param string $prop + * @param bool $raw + * @return array + */ + public function getAll($prop, $raw = false) { + $out = array(); + foreach ($this->getArrayCopy() as $model) { + if ($model instanceof Cortex && $model->exists($prop,true)) { + $val = $model->get($prop, $raw); + if (!empty($val)) + $out[] = $val; + } elseif($raw) + $out[] = $model; + } + return $out; + } - /** - * cast all contained mappers to a nested array - * @param int|array $rel_depths depths to resolve relations - * @return array - */ - public function castAll($rel_depths=1) { - $out = array(); - foreach ($this->getArrayCopy() as $model) - $out[] = $model->cast(null,$rel_depths); - return $out; - } + /** + * cast all contained mappers to a nested array + * @param int|array $rel_depths depths to resolve relations + * @return array + */ + public function castAll($rel_depths=1) { + $out = array(); + foreach ($this->getArrayCopy() as $model) + $out[] = $model->cast(null,$rel_depths); + return $out; + } - /** - * return all models keyed by a specified index key - * @param string $index - * @param bool $nested - * @return array - */ - public function getBy($index, $nested = false) - { - $out = array(); - foreach ($this->getArrayCopy() as $model) - if ($model->exists($index)) { - $val = $model->get($index, true); - if (!empty($val)) - if($nested) $out[(string) $val][] = $model; - else $out[(string) $val] = $model; - } - return $out; - } + /** + * return all models keyed by a specified index key + * @param string $index + * @param bool $nested + * @return array + */ + public function getBy($index, $nested = false) { + $out = array(); + foreach ($this->getArrayCopy() as $model) + if ($model->exists($index)) { + $val = $model->get($index, true); + if (!empty($val)) + if($nested) $out[(string) $val][] = $model; + else $out[(string) $val] = $model; + } + return $out; + } - /** - * re-assort the current collection using a sql-like syntax - * @param $cond - */ - public function orderBy($cond){ - $cols=\Base::instance()->split($cond); - $this->uasort(function($val1,$val2) use($cols) { - foreach ($cols as $col) { - $parts=explode(' ',$col,2); - $order=empty($parts[1])?'ASC':$parts[1]; - $col=$parts[0]; - list($v1,$v2)=array($val1[$col],$val2[$col]); - if ($out=strnatcmp($v1,$v2)* - ((strtoupper($order)=='ASC')*2-1)) - return $out; - } - return 0; - }); - } + /** + * re-assort the current collection using a sql-like syntax + * @param $cond + */ + public function orderBy($cond) { + $cols=\Base::instance()->split($cond); + $this->uasort(function($val1,$val2) use($cols) { + foreach ($cols as $col) { + $parts=explode(' ',$col,2); + $order=empty($parts[1])?'ASC':$parts[1]; + $col=$parts[0]; + list($v1,$v2)=array($val1[$col],$val2[$col]); + if ($out=strnatcmp($v1,$v2)* + ((strtoupper($order)=='ASC')*2-1)) + return $out; + } + return 0; + }); + } - /** - * slice the collection - * @param $offset - * @param null $limit - */ - public function slice($offset,$limit=null) { - $this->rewind(); - $i=0; - $del=array(); - while ($this->valid()) { - if ($i < $offset) - $del[]=$this->key(); - elseif ($i >= $offset && $limit && $i >= ($offset+$limit)) - $del[]=$this->key(); - $i++; - $this->next(); - } - foreach ($del as $ii) - unset($this[$ii]); - } + /** + * slice the collection + * @param $offset + * @param null $limit + */ + public function slice($offset, $limit=null) { + $this->rewind(); + $i=0; + $del=array(); + while ($this->valid()) { + if ($i < $offset) + $del[]=$this->key(); + elseif ($i >= $offset && $limit && $i >= ($offset+$limit)) + $del[]=$this->key(); + $i++; + $this->next(); + } + foreach ($del as $ii) + unset($this[$ii]); + } - static public function factory($records) { - $cc = new self(); - $cc->setModels($records); - return $cc; - } + static public function factory($records) { + $cc = new self(); + $cc->setModels($records); + return $cc; + } } \ No newline at end of file diff --git a/app/lib/db/cursor.php b/app/lib/db/cursor.php index 9ea7cdc9..b844e90c 100644 --- a/app/lib/db/cursor.php +++ b/app/lib/db/cursor.php @@ -2,7 +2,7 @@ /* - Copyright (c) 2009-2016 F3::Factory/Bong Cosca, All rights reserved. + Copyright (c) 2009-2017 F3::Factory/Bong Cosca, All rights reserved. This file is part of the Fat-Free Framework (http://fatfreeframework.com). @@ -70,9 +70,10 @@ abstract class Cursor extends \Magic implements \IteratorAggregate { * Count records that match criteria * @return int * @param $filter array + * @param $options array * @param $ttl int **/ - abstract function count($filter=NULL,$ttl=0); + abstract function count($filter=NULL,array $options=NULL,$ttl=0); /** * Insert new record @@ -145,7 +146,7 @@ abstract class Cursor extends \Magic implements \IteratorAggregate { **/ function paginate( $pos=0,$size=10,$filter=NULL,array $options=NULL,$ttl=0) { - $total=$this->count($filter,$ttl); + $total=$this->count($filter,$options,$ttl); $count=ceil($total/$size); $pos=max(0,min($pos,$count-1)); return [ diff --git a/app/lib/db/jig.php b/app/lib/db/jig.php index d4337933..4221448a 100644 --- a/app/lib/db/jig.php +++ b/app/lib/db/jig.php @@ -2,7 +2,7 @@ /* - Copyright (c) 2009-2016 F3::Factory/Bong Cosca, All rights reserved. + Copyright (c) 2009-2017 F3::Factory/Bong Cosca, All rights reserved. This file is part of the Fat-Free Framework (http://fatfreeframework.com). diff --git a/app/lib/db/jig/mapper.php b/app/lib/db/jig/mapper.php index 74335fcd..860c92a9 100644 --- a/app/lib/db/jig/mapper.php +++ b/app/lib/db/jig/mapper.php @@ -2,7 +2,7 @@ /* - Copyright (c) 2009-2016 F3::Factory/Bong Cosca, All rights reserved. + Copyright (c) 2009-2017 F3::Factory/Bong Cosca, All rights reserved. This file is part of the Fat-Free Framework (http://fatfreeframework.com). @@ -286,11 +286,12 @@ class Mapper extends \DB\Cursor { * Count records that match criteria * @return int * @param $filter array + * @param $options array * @param $ttl int **/ - function count($filter=NULL,$ttl=0) { + function count($filter=NULL,array $options=NULL,$ttl=0) { $now=microtime(TRUE); - $out=count($this->find($filter,NULL,$ttl,FALSE)); + $out=count($this->find($filter,$options,$ttl,FALSE)); $this->db->jot('('.sprintf('%.1f',1e3*(microtime(TRUE)-$now)).'ms) '. $this->file.' [count] '.($filter?json_encode($filter):'')); return $out; diff --git a/app/lib/db/jig/session.php b/app/lib/db/jig/session.php index d3a92d9b..5ebb2069 100644 --- a/app/lib/db/jig/session.php +++ b/app/lib/db/jig/session.php @@ -2,7 +2,7 @@ /* - Copyright (c) 2009-2016 F3::Factory/Bong Cosca, All rights reserved. + Copyright (c) 2009-2017 F3::Factory/Bong Cosca, All rights reserved. This file is part of the Fat-Free Framework (http://fatfreeframework.com). @@ -59,13 +59,13 @@ class Session extends Mapper { /** * Return session data in serialized format - * @return string|FALSE + * @return string * @param $id string **/ function read($id) { $this->load(['@session_id=?',$this->sid=$id]); if ($this->dry()) - return FALSE; + return ''; if ($this->get('ip')!=$this->_ip || $this->get('agent')!=$this->_agent) { $fw=\Base::instance(); if (!isset($this->onsuspect) || diff --git a/app/lib/db/mongo.php b/app/lib/db/mongo.php index fedec0cd..08481ebf 100644 --- a/app/lib/db/mongo.php +++ b/app/lib/db/mongo.php @@ -2,7 +2,7 @@ /* - Copyright (c) 2009-2016 F3::Factory/Bong Cosca, All rights reserved. + Copyright (c) 2009-2017 F3::Factory/Bong Cosca, All rights reserved. This file is part of the Fat-Free Framework (http://fatfreeframework.com). @@ -37,6 +37,8 @@ class Mongo { $dsn, //! MongoDB object $db, + //! Legacy flag + $legacy, //! MongoDB log $log; @@ -63,7 +65,7 @@ class Mongo { **/ function log($flag=TRUE) { if ($flag) { - $cursor=$this->selectcollection('system.profile')->find(); + $cursor=$this->db->selectcollection('system.profile')->find(); foreach (iterator_to_array($cursor) as $frame) if (!preg_match('/\.system\..+$/',$frame['ns'])) $this->log.=date('r',$frame['ts']->sec).' ('. @@ -76,7 +78,10 @@ class Mongo { PHP_EOL; } else { $this->log=FALSE; - $this->setprofilinglevel(-1); + if ($this->legacy) + $this->db->setprofilinglevel(-1); + else + $this->db->command(['profile'=>-1]); } return $this->log; } @@ -87,8 +92,12 @@ class Mongo { **/ function drop() { $out=$this->db->drop(); - if ($this->log!==FALSE) - $this->setprofilinglevel(2); + if ($this->log!==FALSE) { + if ($this->legacy) + $this->db->setprofilinglevel(2); + else + $this->db->command(['profile'=>2]); + } return $out; } @@ -102,6 +111,14 @@ class Mongo { return call_user_func_array([$this->db,$func],$args); } + /** + * Return TRUE if legacy driver is loaded + * @return bool + **/ + function legacy() { + return $this->legacy; + } + //! Prohibit cloning private function __clone() { } @@ -114,9 +131,14 @@ class Mongo { **/ function __construct($dsn,$dbname,array $options=NULL) { $this->uuid=\Base::instance()->hash($this->dsn=$dsn); - $class=class_exists('\MongoClient')?'\MongoClient':'\Mongo'; - $this->db=new \MongoDB(new $class($dsn,$options?:[]),$dbname); - $this->setprofilinglevel(2); + if ($this->legacy=class_exists('\MongoClient')) { + $this->db=new \MongoDB(new \MongoClient($dsn,$options?:[]),$dbname); + $this->db->setprofilinglevel(2); + } + else { + $this->db=(new \MongoDB\Client($dsn,$options?:[]))->$dbname; + $this->db->command(['profile'=>2]); + } } } diff --git a/app/lib/db/mongo/mapper.php b/app/lib/db/mongo/mapper.php index 411c524b..85f68129 100644 --- a/app/lib/db/mongo/mapper.php +++ b/app/lib/db/mongo/mapper.php @@ -2,7 +2,7 @@ /* - Copyright (c) 2009-2016 F3::Factory/Bong Cosca, All rights reserved. + Copyright (c) 2009-2017 F3::Factory/Bong Cosca, All rights reserved. This file is part of the Fat-Free Framework (http://fatfreeframework.com). @@ -28,6 +28,8 @@ class Mapper extends \DB\Cursor { protected //! MongoDB wrapper $db, + //! Legacy flag + $legacy, //! Mongo collection $collection, //! Mongo document @@ -155,16 +157,26 @@ class Mapper extends \DB\Cursor { $filter=$filter?:[]; $collection=$this->collection; } - $this->cursor=$collection->find($filter,$fields?:[]); - if ($options['order']) - $this->cursor=$this->cursor->sort($options['order']); - if ($options['limit']) - $this->cursor=$this->cursor->limit($options['limit']); - if ($options['offset']) - $this->cursor=$this->cursor->skip($options['offset']); - $result=[]; - while ($this->cursor->hasnext()) - $result[]=$this->cursor->getnext(); + if ($this->legacy) { + $this->cursor=$collection->find($filter,$fields?:[]); + if ($options['order']) + $this->cursor=$this->cursor->sort($options['order']); + if ($options['limit']) + $this->cursor=$this->cursor->limit($options['limit']); + if ($options['offset']) + $this->cursor=$this->cursor->skip($options['offset']); + $result=[]; + while ($this->cursor->hasnext()) + $result[]=$this->cursor->getnext(); + } + else { + $this->cursor=$collection->find($filter,[ + 'sort'=>$options['order'], + 'limit'=>$options['limit'], + 'skip'=>$options['offset'] + ]); + $result=$this->cursor->toarray(); + } if ($options['group']) $tmp->drop(); if ($fw->get('CACHE') && $ttl) @@ -200,9 +212,10 @@ class Mapper extends \DB\Cursor { * Count records that match criteria * @return int * @param $filter array + * @param $options array * @param $ttl int **/ - function count($filter=NULL,$ttl=0) { + function count($filter=NULL,array $options=NULL,$ttl=0) { $fw=\Base::instance(); $cache=\Cache::instance(); if (!($cached=$cache->exists($hash=$fw->hash($fw->stringify( @@ -240,8 +253,14 @@ class Mapper extends \DB\Cursor { \Base::instance()->call($this->trigger['beforeinsert'], [$this,['_id'=>$this->document['_id']]])===FALSE) return $this->document; - $this->collection->insert($this->document); - $pkey=['_id'=>$this->document['_id']]; + if ($this->legacy) { + $this->collection->insert($this->document); + $pkey=['_id'=>$this->document['_id']]; + } + else { + $result=$this->collection->insertone($this->document); + $pkey=['_id'=>$result->getinsertedid()]; + } if (isset($this->trigger['afterinsert'])) \Base::instance()->call($this->trigger['afterinsert'], [$this,$pkey]); @@ -259,8 +278,11 @@ class Mapper extends \DB\Cursor { \Base::instance()->call($this->trigger['beforeupdate'], [$this,$pkey])===FALSE) return $this->document; - $this->collection->update( - $pkey,$this->document,['upsert'=>TRUE]); + $upsert=['upsert'=>TRUE]; + if ($this->legacy) + $this->collection->update($pkey,$this->document,$upsert); + else + $this->collection->replaceone($pkey,$this->document,$upsert); if (isset($this->trigger['afterupdate'])) \Base::instance()->call($this->trigger['afterupdate'], [$this,$pkey]); @@ -273,15 +295,19 @@ class Mapper extends \DB\Cursor { * @param $filter array **/ function erase($filter=NULL) { - if ($filter) - return $this->collection->remove($filter); + if ($filter) { + return $this->legacy? + $this->collection->remove($filter): + $this->collection->deletemany($filter); + } $pkey=['_id'=>$this->document['_id']]; if (isset($this->trigger['beforeerase']) && \Base::instance()->call($this->trigger['beforeerase'], [$this,$pkey])===FALSE) return FALSE; - $result=$this->collection-> - remove(['_id'=>$this->document['_id']]); + $result=$this->legacy? + $this->collection->remove(['_id'=>$this->document['_id']]): + $this->collection->deleteone(['_id'=>$this->document['_id']]); parent::erase(); if (isset($this->trigger['aftererase'])) \Base::instance()->call($this->trigger['aftererase'], @@ -357,6 +383,7 @@ class Mapper extends \DB\Cursor { **/ function __construct(\DB\Mongo $db,$collection,$fields=NULL) { $this->db=$db; + $this->legacy=$db->legacy(); $this->collection=$db->selectcollection($collection); $this->fields=$fields; $this->reset(); diff --git a/app/lib/db/mongo/session.php b/app/lib/db/mongo/session.php index 5ea894b8..09f123a9 100644 --- a/app/lib/db/mongo/session.php +++ b/app/lib/db/mongo/session.php @@ -2,7 +2,7 @@ /* - Copyright (c) 2009-2016 F3::Factory/Bong Cosca, All rights reserved. + Copyright (c) 2009-2017 F3::Factory/Bong Cosca, All rights reserved. This file is part of the Fat-Free Framework (http://fatfreeframework.com). @@ -59,13 +59,13 @@ class Session extends Mapper { /** * Return session data in serialized format - * @return string|FALSE + * @return string * @param $id string **/ function read($id) { $this->load(['session_id'=>$this->sid=$id]); if ($this->dry()) - return FALSE; + return ''; if ($this->get('ip')!=$this->_ip || $this->get('agent')!=$this->_agent) { $fw=\Base::instance(); if (!isset($this->onsuspect) || diff --git a/app/lib/db/sql.php b/app/lib/db/sql.php index 48b49cc1..005d6430 100644 --- a/app/lib/db/sql.php +++ b/app/lib/db/sql.php @@ -2,7 +2,7 @@ /* - Copyright (c) 2009-2016 F3::Factory/Bong Cosca, All rights reserved. + Copyright (c) 2009-2017 F3::Factory/Bong Cosca, All rights reserved. This file is part of the Fat-Free Framework (http://fatfreeframework.com). @@ -113,16 +113,16 @@ class SQL { /** * Cast value to PHP type - * @return scalar + * @return mixed * @param $type string - * @param $val scalar + * @param $val mixed **/ function value($type,$val) { switch ($type) { case self::PARAM_FLOAT: - return (float)(is_string($val) - ? str_replace(',','.',preg_replace('/([.,])(?!\d+$)/','',$val)) - : $val); + if (!is_string($val)) + $val=str_replace(',','.',$val); + return $val; case \PDO::PARAM_NULL: return (unset)$val; case \PDO::PARAM_INT: diff --git a/app/lib/db/sql/mapper.php b/app/lib/db/sql/mapper.php index ac4dd87c..5548d36a 100644 --- a/app/lib/db/sql/mapper.php +++ b/app/lib/db/sql/mapper.php @@ -2,7 +2,7 @@ /* - Copyright (c) 2009-2016 F3::Factory/Bong Cosca, All rights reserved. + Copyright (c) 2009-2017 F3::Factory/Bong Cosca, All rights reserved. This file is part of the Fat-Free Framework (http://fatfreeframework.com). @@ -226,7 +226,8 @@ class Mapper extends \DB\Cursor { return preg_replace_callback( '/\b(\w+)\h*(HAVING.+|$)/i', function($parts) use($db) { - return $db->quotekey($parts[1]).(isset($parts[2])?(' '.$parts[2]):''); + return $db->quotekey($parts[1]). + (isset($parts[2])?(' '.$parts[2]):''); }, $str ); @@ -324,24 +325,18 @@ class Mapper extends \DB\Cursor { * Count records that match criteria * @return int * @param $filter string|array + * @param $options array * @param $ttl int|array **/ - function count($filter=NULL,$ttl=0) { - $sql='SELECT COUNT(*) AS '. - $this->db->quotekey('rows').' FROM '.$this->table; - $args=[]; - if ($filter) { - if (is_array($filter)) { - $args=isset($filter[1]) && is_array($filter[1])? - $filter[1]: - array_slice($filter,1,NULL,TRUE); - $args=is_array($args)?$args:[1=>$args]; - list($filter)=$filter; - } - $sql.=' WHERE '.$filter; - } - $result=$this->db->exec($sql,$args,$ttl); - return $result[0]['rows']; + function count($filter=NULL,array $options=NULL,$ttl=0) { + $expr='COUNT(*)'; + $field='rows'; + $this->adhoc[$field]=['expr'=>$expr,'value'=>NULL]; + $result=$this->select($expr.' AS '.$this->db->quotekey($field), + $filter,$options,$ttl); + $out=$result[0]->adhoc[$field]['value']; + unset($this->adhoc[$field]); + return $out; } /** @@ -473,10 +468,10 @@ class Mapper extends \DB\Cursor { if ($pairs) { $sql='UPDATE '.$this->table.' SET '.$pairs.$filter; $this->db->exec($sql,$args); - if (isset($this->trigger['afterupdate'])) - \Base::instance()->call($this->trigger['afterupdate'], - [$this,$pkeys]); } + if (isset($this->trigger['afterupdate'])) + \Base::instance()->call($this->trigger['afterupdate'], + [$this,$pkeys]); // reset changed flag after calling afterupdate foreach ($this->fields as $key=>&$field) { $field['changed']=FALSE; @@ -492,7 +487,7 @@ class Mapper extends \DB\Cursor { * @param $filter string|array **/ function erase($filter=NULL) { - if ($filter) { + if (isset($filter)) { $args=[]; if (is_array($filter)) { $args=isset($filter[1]) && is_array($filter[1])? @@ -502,7 +497,7 @@ class Mapper extends \DB\Cursor { list($filter)=$filter; } return $this->db-> - exec('DELETE FROM '.$this->table.' WHERE '.$filter.';',$args); + exec('DELETE FROM '.$this->table.($filter?' WHERE '.$filter:'').';',$args); } $args=[]; $ctr=0; diff --git a/app/lib/db/sql/session.php b/app/lib/db/sql/session.php index 56c1f430..d02f46e2 100644 --- a/app/lib/db/sql/session.php +++ b/app/lib/db/sql/session.php @@ -2,7 +2,7 @@ /* - Copyright (c) 2009-2016 F3::Factory/Bong Cosca, All rights reserved. + Copyright (c) 2009-2017 F3::Factory/Bong Cosca, All rights reserved. This file is part of the Fat-Free Framework (http://fatfreeframework.com). @@ -59,13 +59,13 @@ class Session extends Mapper { /** * Return session data in serialized format - * @return string|FALSE + * @return string * @param $id string **/ function read($id) { $this->load(['session_id=?',$this->sid=$id]); if ($this->dry()) - return FALSE; + return ''; if ($this->get('ip')!=$this->_ip || $this->get('agent')!=$this->_agent) { $fw=\Base::instance(); if (!isset($this->onsuspect) || diff --git a/app/lib/f3.php b/app/lib/f3.php index d68cd1fb..3b96a63c 100644 --- a/app/lib/f3.php +++ b/app/lib/f3.php @@ -2,7 +2,7 @@ /* - Copyright (c) 2009-2016 F3::Factory/Bong Cosca, All rights reserved. + Copyright (c) 2009-2017 F3::Factory/Bong Cosca, All rights reserved. This file is part of the Fat-Free Framework (http://fatfreeframework.com). diff --git a/app/lib/image.php b/app/lib/image.php index a8514c22..ad63bf87 100644 --- a/app/lib/image.php +++ b/app/lib/image.php @@ -2,7 +2,7 @@ /* - Copyright (c) 2009-2016 F3::Factory/Bong Cosca, All rights reserved. + Copyright (c) 2009-2017 F3::Factory/Bong Cosca, All rights reserved. This file is part of the Fat-Free Framework (http://fatfreeframework.com). diff --git a/app/lib/log.php b/app/lib/log.php index 2bbe4c27..19337218 100644 --- a/app/lib/log.php +++ b/app/lib/log.php @@ -2,7 +2,7 @@ /* - Copyright (c) 2009-2016 F3::Factory/Bong Cosca, All rights reserved. + Copyright (c) 2009-2017 F3::Factory/Bong Cosca, All rights reserved. This file is part of the Fat-Free Framework (http://fatfreeframework.com). diff --git a/app/lib/magic.php b/app/lib/magic.php index 76ea221e..2502bf19 100644 --- a/app/lib/magic.php +++ b/app/lib/magic.php @@ -2,7 +2,7 @@ /* - Copyright (c) 2009-2016 F3::Factory/Bong Cosca, All rights reserved. + Copyright (c) 2009-2017 F3::Factory/Bong Cosca, All rights reserved. This file is part of the Fat-Free Framework (http://fatfreeframework.com). diff --git a/app/lib/markdown.php b/app/lib/markdown.php index 1c3fb163..e05ea791 100644 --- a/app/lib/markdown.php +++ b/app/lib/markdown.php @@ -2,7 +2,7 @@ /* - Copyright (c) 2009-2016 F3::Factory/Bong Cosca, All rights reserved. + Copyright (c) 2009-2017 F3::Factory/Bong Cosca, All rights reserved. This file is part of the Fat-Free Framework (http://fatfreeframework.com). diff --git a/app/lib/matrix.php b/app/lib/matrix.php index f20e9890..f3d71821 100644 --- a/app/lib/matrix.php +++ b/app/lib/matrix.php @@ -2,7 +2,7 @@ /* - Copyright (c) 2009-2016 F3::Factory/Bong Cosca, All rights reserved. + Copyright (c) 2009-2017 F3::Factory/Bong Cosca, All rights reserved. This file is part of the Fat-Free Framework (http://fatfreeframework.com). diff --git a/app/lib/session.php b/app/lib/session.php index 583193d9..7df365e9 100644 --- a/app/lib/session.php +++ b/app/lib/session.php @@ -2,7 +2,7 @@ /* - Copyright (c) 2009-2016 F3::Factory/Bong Cosca, All rights reserved. + Copyright (c) 2009-2017 F3::Factory/Bong Cosca, All rights reserved. This file is part of the Fat-Free Framework (http://fatfreeframework.com). @@ -58,13 +58,13 @@ class Session { /** * Return session data in serialized format - * @return string|FALSE + * @return string * @param $id string **/ function read($id) { $this->sid=$id; if (!$data=$this->_cache->get($id.'.@')) - return FALSE; + return ''; if ($data['ip']!=$this->_ip || $data['agent']!=$this->_agent) { $fw=Base::instance(); if (!isset($this->onsuspect) || diff --git a/app/lib/smtp.php b/app/lib/smtp.php index 00ee9b2d..64e8d04f 100644 --- a/app/lib/smtp.php +++ b/app/lib/smtp.php @@ -2,7 +2,7 @@ /* - Copyright (c) 2009-2016 F3::Factory/Bong Cosca, All rights reserved. + Copyright (c) 2009-2017 F3::Factory/Bong Cosca, All rights reserved. This file is part of the Fat-Free Framework (http://fatfreeframework.com). @@ -45,6 +45,8 @@ class SMTP extends Magic { $user, //! Password $pw, + //! TLS/SSL stream context + $context, //! TCP/IP socket $socket, //! Server-client conversation @@ -117,7 +119,7 @@ class SMTP extends Magic { * Send SMTP command and record server response * @return string * @param $cmd string - * @param $log bool + * @param $log bool|string * @param $mock bool **/ protected function dialog($cmd=NULL,$log=TRUE,$mock=FALSE) { @@ -177,7 +179,7 @@ class SMTP extends Magic { * Transmit message * @return bool * @param $message string - * @param $log bool + * @param $log bool|string * @param $mock bool **/ function send($message,$log=TRUE,$mock=FALSE) { @@ -192,7 +194,9 @@ class SMTP extends Magic { // Connect to the server if (!$mock) { $socket=&$this->socket; - $socket=@fsockopen($this->host,$this->port,$errno,$errstr); + $socket=@stream_socket_client($this->host.':'.$this->port, + $errno,$errstr,ini_get('default_socket_timeout'), + STREAM_CLIENT_CONNECT,$this->context); if (!$socket) { $fw->error(500,$errstr); return FALSE; @@ -221,16 +225,16 @@ class SMTP extends Magic { // Authenticate $this->dialog('AUTH LOGIN',$log,$mock); $this->dialog(base64_encode($this->user),$log,$mock); - $auth_rply=$this->dialog(base64_encode($this->pw),$log,$mock); - if (!preg_match('/^235\s.*/',$auth_rply)) { + $reply=$this->dialog(base64_encode($this->pw),$log,$mock); + if (!preg_match('/^235\s.*/',$reply)) { $this->dialog('QUIT',$log,$mock); if (!$mock && $socket) fclose($socket); return FALSE; } } - if (empty($headers['Message-ID'])) - $headers['Message-ID']='<'.uniqid('',TRUE).'@'.$this->host.'>'; + if (empty($headers['Message-Id'])) + $headers['Message-Id']='<'.uniqid('',TRUE).'@'.$this->host.'>'; if (empty($headers['Date'])) $headers['Date']=date('r'); // Required headers @@ -297,7 +301,7 @@ class SMTP extends Magic { $out.='Content-Type: application/octet-stream'.$eol; $out.='Content-Transfer-Encoding: base64'.$eol; if ($attachment['cid']) - $out.='Content-ID: '.$attachment['cid'].$eol; + $out.='Content-Id: '.$attachment['cid'].$eol; $out.='Content-Disposition: attachment; '. 'filename="'.$alias.'"'.$eol; $out.=$eol; @@ -307,7 +311,7 @@ class SMTP extends Magic { $out.=$eol; $out.='--'.$hash.'--'.$eol; $out.='.'; - $this->dialog($out,TRUE,$mock); + $this->dialog($out,preg_match('/verbose/i',$log),$mock); } else { // Send mail headers @@ -319,7 +323,7 @@ class SMTP extends Magic { $out.=$message.$eol; $out.='.'; // Send message - $this->dialog($out,TRUE,$mock); + $this->dialog($out,preg_match('/verbose/i',$log),$mock); } $this->dialog('QUIT',$log,$mock); if (!$mock && $socket) @@ -336,18 +340,18 @@ class SMTP extends Magic { * @param $pw string **/ function __construct( - $host='localhost',$port=25,$scheme=NULL,$user=NULL,$pw=NULL) { + $host='localhost',$port=25,$scheme=NULL,$user=NULL,$pw=NULL,$ctx=NULL) { $this->headers=[ 'MIME-Version'=>'1.0', 'Content-Type'=>'text/plain; '. 'charset='.Base::instance()->get('ENCODING') ]; - $this->host=$host; - if (strtolower($this->scheme=strtolower($scheme))=='ssl') - $this->host='ssl://'.$host; + $this->host=(strtolower($this->scheme=strtolower($scheme))=='ssl'? + 'ssl':'tcp').'://'.$host; $this->port=$port; $this->user=$user; $this->pw=$pw; + $this->context=$ctx; } } diff --git a/app/lib/template.php b/app/lib/template.php index c9c0d61b..a8277376 100644 --- a/app/lib/template.php +++ b/app/lib/template.php @@ -2,7 +2,7 @@ /* - Copyright (c) 2009-2016 F3::Factory/Bong Cosca, All rights reserved. + Copyright (c) 2009-2017 F3::Factory/Bong Cosca, All rights reserved. This file is part of the Fat-Free Framework (http://fatfreeframework.com). diff --git a/app/lib/test.php b/app/lib/test.php index 2070dab4..721faf76 100644 --- a/app/lib/test.php +++ b/app/lib/test.php @@ -2,7 +2,7 @@ /* - Copyright (c) 2009-2016 F3::Factory/Bong Cosca, All rights reserved. + Copyright (c) 2009-2017 F3::Factory/Bong Cosca, All rights reserved. This file is part of the Fat-Free Framework (http://fatfreeframework.com). diff --git a/app/lib/utf.php b/app/lib/utf.php index 22b41c3d..bcc083be 100644 --- a/app/lib/utf.php +++ b/app/lib/utf.php @@ -2,7 +2,7 @@ /* - Copyright (c) 2009-2016 F3::Factory/Bong Cosca, All rights reserved. + Copyright (c) 2009-2017 F3::Factory/Bong Cosca, All rights reserved. This file is part of the Fat-Free Framework (http://fatfreeframework.com). diff --git a/app/lib/web.php b/app/lib/web.php index 22864898..204d9490 100644 --- a/app/lib/web.php +++ b/app/lib/web.php @@ -2,7 +2,7 @@ /* - Copyright (c) 2009-2016 F3::Factory/Bong Cosca, All rights reserved. + Copyright (c) 2009-2017 F3::Factory/Bong Cosca, All rights reserved. This file is part of the Fat-Free Framework (http://fatfreeframework.com). @@ -140,26 +140,33 @@ class Web extends Prefab { header('Content-Length: '.$size); header('X-Powered-By: '.Base::instance()->get('PACKAGE')); } - $ctr=0; - $handle=fopen($file,'rb'); - $start=microtime(TRUE); - while (!feof($handle) && - ($info=stream_get_meta_data($handle)) && - !$info['timed_out'] && !connection_aborted()) { - if ($kbps) { - // Throttle output - $ctr++; - if ($ctr/$kbps>$elapsed=microtime(TRUE)-$start) - usleep(1e6*($ctr/$kbps-$elapsed)); - } - // Send 1KiB and reset timer - echo fread($handle,1024); - if ($flush) { - ob_flush(); - flush(); - } + if (!$kbps && $flush) { + while (ob_get_level()) + ob_end_clean(); + readfile($file); + } + else { + $ctr=0; + $handle=fopen($file,'rb'); + $start=microtime(TRUE); + while (!feof($handle) && + ($info=stream_get_meta_data($handle)) && + !$info['timed_out'] && !connection_aborted()) { + if ($kbps) { + // Throttle output + $ctr++; + if ($ctr/$kbps>$elapsed=microtime(TRUE)-$start) + usleep(1e6*($ctr/$kbps-$elapsed)); + } + // Send 1KiB and reset timer + echo fread($handle,1024); + if ($flush) { + ob_flush(); + flush(); + } + } + fclose($handle); } - fclose($handle); return $size; } diff --git a/app/lib/web/geo.php b/app/lib/web/geo.php index 7d7a0bce..d7cb9cba 100644 --- a/app/lib/web/geo.php +++ b/app/lib/web/geo.php @@ -2,7 +2,7 @@ /* - Copyright (c) 2009-2016 F3::Factory/Bong Cosca, All rights reserved. + Copyright (c) 2009-2017 F3::Factory/Bong Cosca, All rights reserved. This file is part of the Fat-Free Framework (http://fatfreeframework.com). diff --git a/app/lib/web/google/staticmap.php b/app/lib/web/google/staticmap.php index 6a3f1601..8310fe4c 100644 --- a/app/lib/web/google/staticmap.php +++ b/app/lib/web/google/staticmap.php @@ -2,7 +2,7 @@ /* - Copyright (c) 2009-2016 F3::Factory/Bong Cosca, All rights reserved. + Copyright (c) 2009-2017 F3::Factory/Bong Cosca, All rights reserved. This file is part of the Fat-Free Framework (http://fatfreeframework.com). diff --git a/app/lib/web/oauth2.php b/app/lib/web/oauth2.php index a41f9fb3..5bf4dcb8 100644 --- a/app/lib/web/oauth2.php +++ b/app/lib/web/oauth2.php @@ -2,7 +2,7 @@ /* - Copyright (c) 2009-2016 F3::Factory/Bong Cosca, All rights reserved. + Copyright (c) 2009-2017 F3::Factory/Bong Cosca, All rights reserved. This file is part of the Fat-Free Framework (http://fatfreeframework.com). @@ -62,6 +62,8 @@ class OAuth2 extends \Magic { ) ); $response=$web->request($uri,$options); + if ($response['error']) + user_error($response['error']); return $response['body'] && preg_grep('/HTTP\/1\.\d 200/',$response['headers'])? json_decode($response['body'],TRUE): @@ -121,7 +123,7 @@ class OAuth2 extends \Magic { /** * Remove scope/claim * @return NULL - * @param $key + * @param $key string **/ function clear($key=NULL) { if ($key) diff --git a/app/lib/web/openid.php b/app/lib/web/openid.php index f795cb37..d19ff6a9 100644 --- a/app/lib/web/openid.php +++ b/app/lib/web/openid.php @@ -2,7 +2,7 @@ /* - Copyright (c) 2009-2016 F3::Factory/Bong Cosca, All rights reserved. + Copyright (c) 2009-2017 F3::Factory/Bong Cosca, All rights reserved. This file is part of the Fat-Free Framework (http://fatfreeframework.com). diff --git a/app/lib/web/pingback.php b/app/lib/web/pingback.php index f063f104..a9fca95b 100644 --- a/app/lib/web/pingback.php +++ b/app/lib/web/pingback.php @@ -2,7 +2,7 @@ /* - Copyright (c) 2009-2016 F3::Factory/Bong Cosca, All rights reserved. + Copyright (c) 2009-2017 F3::Factory/Bong Cosca, All rights reserved. This file is part of the Fat-Free Framework (http://fatfreeframework.com). diff --git a/app/main/controller/api/map.php b/app/main/controller/api/map.php index 7e178dde..7c9de808 100644 --- a/app/main/controller/api/map.php +++ b/app/main/controller/api/map.php @@ -577,23 +577,17 @@ class Map extends Controller\AccessController { * -> if characters with map access found -> broadcast mapData to them * @param Model\MapModel $map * @param array $characterIds - * @return int */ protected function broadcastMapAccess($map, $characterIds){ - $connectionCount = 0; - $mapAccess = [ 'id' => $map->_id, 'characterIds' => $characterIds ]; - $charCount = (int)(new Socket( Config::getSocketUri() ))->sendData('mapAccess', $mapAccess); - if($charCount > 0){ - // map has active connections that should receive map Data - $connectionCount = $this->broadcastMapData($map); - } + (new Socket( Config::getSocketUri() ))->sendData('mapAccess', $mapAccess); - return $connectionCount; + // map has (probably) active connections that should receive map Data + $this->broadcastMapData($map); } /** @@ -1069,6 +1063,39 @@ class Map extends Controller\AccessController { return $map; } + /** + * get connectionData + * @param \Base $f3 + */ + public function getConnectionData (\Base $f3){ + $postData = (array)$f3->get('POST'); + $connectionData = []; + + if($mapId = (int)$postData['mapId']){ + $activeCharacter = $this->getCharacter(); + + /** + * @var Model\MapModel $map + */ + $map = Model\BasicModel::getNew('MapModel'); + $map->getById($mapId); + + if($map->hasAccess($activeCharacter)){ + $connections = $map->getConnections('wh'); + foreach($connections as $connection){ + $data = $connection->getData(true); + // skip connections whiteout signature data + if($data->signatures){ + $connectionData[] = $data; + + } + } + } + } + + echo json_encode($connectionData); + } + } diff --git a/app/main/controller/api/signature.php b/app/main/controller/api/signature.php index 3d2c8cb4..fe6e8545 100644 --- a/app/main/controller/api/signature.php +++ b/app/main/controller/api/signature.php @@ -68,7 +68,6 @@ class Signature extends Controller\AccessController { // delete all signatures that are not available in this request $deleteOldSignatures = (bool)$requestData['deleteOld']; - $return = (object) []; $return->error = []; $return->signatures = []; @@ -135,9 +134,17 @@ class Signature extends Controller\AccessController { $data['name'] => $data['value'] ]; - // if groupID changed -> typeID set to 0 + // if groupId changed if($data['name'] == 'groupId'){ + // -> typeId set to 0 $newData['typeId'] = 0; + // -> connectionId set to 0 + $newData['connectionId'] = 0; + } + + // if connectionId changed + if($data['name'] == 'connectionId'){ + $newData['connectionId'] = (int)$newData['connectionId']; } }else{ diff --git a/app/main/controller/mailcontroller.php b/app/main/controller/mailcontroller.php index d34ef8f8..39eca2ab 100644 --- a/app/main/controller/mailcontroller.php +++ b/app/main/controller/mailcontroller.php @@ -22,7 +22,7 @@ class MailController extends \SMTP{ parent::__construct($host,$port,$scheme,$user,$pw); // error handling - $this->set('Errors-to', '' . Controller::getEnvironmentData('SMTP_ERROR') . '>'); + $this->set('Errors-to', '<' . Controller::getEnvironmentData('SMTP_ERROR') . '>'); $this->set('MIME-Version', '1.0'); $this->set('Content-Type', 'text/html; charset=ISO-8859-1'); } @@ -35,7 +35,7 @@ class MailController extends \SMTP{ */ public function sendDeleteAccount($to, $msg){ $this->set('To', '<' . $to . '>'); - $this->set('From', 'Pathfinder <' . Controller::getEnvironmentData('SMTP_FROM') . '>'); + $this->set('From', '"Pathfinder" <' . Controller::getEnvironmentData('SMTP_FROM') . '>'); $this->set('Subject', 'Account deleted'); $status = $this->send($msg); @@ -50,7 +50,7 @@ class MailController extends \SMTP{ */ public function sendRallyPoint($to, $msg){ $this->set('To', '<' . $to . '>'); - $this->set('From', 'Pathfinder <' . Controller::getEnvironmentData('SMTP_FROM') . '>'); + $this->set('From', '"Pathfinder" <' . Controller::getEnvironmentData('SMTP_FROM') . '>'); $this->set('Subject', 'PATHFINDER - New rally point'); $status = $this->send($msg); diff --git a/app/main/controller/setup.php b/app/main/controller/setup.php index 414be18f..67eef140 100644 --- a/app/main/controller/setup.php +++ b/app/main/controller/setup.php @@ -423,7 +423,7 @@ class Setup extends Controller { ], 'php' => [ 'label' => 'PHP', - 'required' => $f3->get('REQUIREMENTS.PHP.VERSION'), + 'required' => number_format((float)$f3->get('REQUIREMENTS.PHP.VERSION'), 1, '.', ''), 'version' => phpversion(), 'check' => version_compare( phpversion(), $f3->get('REQUIREMENTS.PHP.VERSION'), '>=') ], @@ -925,7 +925,7 @@ class Setup extends Controller { $checkTables = []; if($db){ // set/change default "character set" and "collation" - $db->exec('ALTER DATABASE ' . $db->name() + $db->exec('ALTER DATABASE ' . $db->quotekey($db->name()) . ' CHARACTER SET ' . self::getRequiredMySqlVariables('CHARACTER_SET_DATABASE') . ' COLLATE ' . self::getRequiredMySqlVariables('COLLATION_DATABASE') ); diff --git a/app/main/db/sql/mysql/tablemodifier.php b/app/main/db/sql/mysql/tablemodifier.php index c620e521..0afa57f0 100644 --- a/app/main/db/sql/mysql/tablemodifier.php +++ b/app/main/db/sql/mysql/tablemodifier.php @@ -52,7 +52,7 @@ class TableModifier extends SQL\TableModifier { ':constraint_name' => $constraintName ]); // switch back to current DB - $this->db->exec("USE " . $this->db->name()); + $this->db->exec("USE " . $this->db->quotekey($this->db->name())); $constraints = []; foreach($constraintsData as $data){ diff --git a/app/main/model/connectionmodel.php b/app/main/model/connectionmodel.php index 0b50281c..6d2b2917 100644 --- a/app/main/model/connectionmodel.php +++ b/app/main/model/connectionmodel.php @@ -71,6 +71,9 @@ class ConnectionModel extends BasicModel{ 'eolUpdated' => [ 'type' => Schema::DT_TIMESTAMP, 'default' => null + ], + 'signatures' => [ + 'has-many' => ['Model\SystemSignatureModel', 'connectionId'] ] ]; @@ -79,9 +82,7 @@ class ConnectionModel extends BasicModel{ * @param $systemData */ public function setData($systemData){ - foreach((array)$systemData as $key => $value){ - if( !is_array($value) ){ if( $this->exists($key) ){ $this->$key = $value; @@ -95,19 +96,26 @@ class ConnectionModel extends BasicModel{ /** * get connection data as array - * @return array + * @param bool $addSignatureData + * @return \stdClass */ - public function getData(){ + public function getData($addSignatureData = false){ - $connectionData = [ - 'id' => $this->id, - 'source' => $this->source->id, - 'target' => $this->target->id, - 'scope' => $this->scope, - 'type' => $this->type, - 'updated' => strtotime($this->updated), - 'eolUpdated' => strtotime($this->eolUpdated) - ]; + $connectionData = (object) []; + $connectionData->id = $this->id; + $connectionData->source = $this->source->id; + $connectionData->target = $this->target->id; + $connectionData->scope = $this->scope; + $connectionData->type = $this->type; + $connectionData->updated = strtotime($this->updated); + $connectionData->created = strtotime($this->created); + $connectionData->eolUpdated = strtotime($this->eolUpdated); + + if($addSignatureData){ + if( !empty($signaturesData = $this->getSignaturesData()) ){ + $connectionData->signatures = $signaturesData; + } + } return $connectionData; } @@ -140,7 +148,11 @@ class ConnectionModel extends BasicModel{ * @return mixed */ public function hasAccess(CharacterModel $characterModel){ - return $this->mapId->hasAccess($characterModel); + $access = false; + if( !$this->dry() ){ + $access = $this->mapId->hasAccess($characterModel); + } + return $access; } /** @@ -302,6 +314,35 @@ class ConnectionModel extends BasicModel{ $this->mapId->clearCacheData(); } + /** + * get all signatures that are connected with this connection + * @return array|mixed + */ + public function getSignatures(){ + $signatures = []; + $this->filter('signatures', [ + 'active = :active', + ':active' => 1 + ]); + + if($this->signatures){ + $signatures = $this->signatures; + } + + return $signatures; + } + + public function getSignaturesData(){ + $signaturesData = []; + $signatures = $this->getSignatures(); + + foreach($signatures as $signature){ + $signaturesData[] = $signature->getData(); + } + + return $signaturesData; + } + /** * overwrites parent * @param null $db diff --git a/app/main/model/mapmodel.php b/app/main/model/mapmodel.php index 53796b12..47b74660 100644 --- a/app/main/model/mapmodel.php +++ b/app/main/model/mapmodel.php @@ -20,6 +20,11 @@ class MapModel extends BasicModel { */ const DATA_CACHE_KEY_CHARACTER = 'CHARACTERS'; + /** + * default TTL for getData(); cache + */ + const DEFAULT_CACHE_TTL = 60; + protected $fieldConf = [ 'active' => [ 'type' => Schema::DT_BOOL, @@ -205,7 +210,7 @@ class MapModel extends BasicModel { // max caching time for a map // the cached date has to be cleared manually on any change // this includes system, connection,... changes (all dependencies) - $this->updateCacheData($mapDataAll); + $this->updateCacheData($mapDataAll, '', self::DEFAULT_CACHE_TTL); } return $mapDataAll; @@ -391,15 +396,23 @@ class MapModel extends BasicModel { /** * get all connections in this map + * @param string $scope * @return ConnectionModel[] */ - public function getConnections(){ + public function getConnections($scope = ''){ $connections = []; - $this->filter('connections', [ + $query = [ 'active = :active AND source > 0 AND target > 0', ':active' => 1 - ]); + ]; + + if(!empty($scope)){ + $query[0] .= ' AND scope = :scope'; + $query[':scope'] = $scope; + } + + $this->filter('connections', $query); if($this->connections){ $connections = $this->connections; diff --git a/app/main/model/systemsignaturemodel.php b/app/main/model/systemsignaturemodel.php index 44385146..553301af 100644 --- a/app/main/model/systemsignaturemodel.php +++ b/app/main/model/systemsignaturemodel.php @@ -46,6 +46,18 @@ class SystemSignatureModel extends BasicModel { 'index' => true, 'activity-log' => true ], + 'connectionId' => [ + 'type' => Schema::DT_INT, + 'index' => true, + 'belongs-to-one' => 'Model\ConnectionModel', + 'constraint' => [ + [ + 'table' => 'connection', + 'on-delete' => 'CASCADE' + ] + ], + 'activity-log' => true + ], 'name' => [ 'type' => Schema::DT_VARCHAR128, 'nullable' => false, @@ -112,11 +124,20 @@ class SystemSignatureModel extends BasicModel { $signatureData = (object) []; $signatureData->id = $this->id; + + $signatureData->system = (object) []; + $signatureData->system->id = $this->get('systemId', true); + $signatureData->groupId = $this->groupId; $signatureData->typeId = $this->typeId; $signatureData->name = $this->name; $signatureData->description = $this->description; + if($connection = $this->getConnection()){ + $signatureData->connection = (object) []; + $signatureData->connection->id = $connection->_id; + } + $signatureData->created = (object) []; $signatureData->created->created = strtotime($this->created); if( is_object($this->createdCharacterId) ){ @@ -132,6 +153,48 @@ class SystemSignatureModel extends BasicModel { return $signatureData; } + /** + * setter for connectionId + * @param $connectionId + * @return int|null + */ + public function set_connectionId($connectionId){ + $connectionId = (int)$connectionId; + $validConnectionId = null; + + if($connectionId > 0){ + // check if connectionId is valid + $systemId = (int) $this->get('systemId', true); + + /** + * @var $connection ConnectionModel + */ + $connection = $this->rel('connectionId'); + $connection->getById($connectionId); + + if( + !$connection->dry() && + ( + $connection->get('source', true) === $systemId|| + $connection->get('target', true) === $systemId + ) + ){ + // connectionId belongs to same system as $this signature -> is valid + $validConnectionId = $connectionId; + } + } + + return $validConnectionId; + } + + /** + * get the connection (if attached) + * @return \Model\ConnectionModel|null + */ + public function getConnection(){ + return $this->connectionId; + } + /** * compares a new data set (array) with the current values * and checks if something has changed diff --git a/app/pathfinder.ini b/app/pathfinder.ini index 412baa8a..9fc6e64d 100644 --- a/app/pathfinder.ini +++ b/app/pathfinder.ini @@ -3,7 +3,7 @@ [PATHFINDER] NAME = Pathfinder ; installed version (used for CSS/JS cache busting) -VERSION = v1.2.0 +VERSION = v1.2.1 ; contact information [optional] CONTACT = https://github.com/exodus4d ; public contact email [optional] @@ -60,7 +60,7 @@ LOGIN = templates/view/login.html ; - Whether user activity should be logged for a map type ; - E.g. create/update/delete of systems/connections/signatures [PATHFINDER.MAP.PRIVATE] -LIFETIME = 14 +LIFETIME = 30 MAX_COUNT = 3 MAX_SHARED = 10 MAX_SYSTEMS = 50 @@ -100,28 +100,28 @@ RALLY_SET = ; TIMER =========================================================================================== [PATHFINDER.TIMER] -; login time (minutes) -LOGGED = 240 -; double click timer (ms) +; login time (minutes) (default: 480) +LOGGED = 480 +; double click timer (milliseconds) (default: 250) DBL_CLICK = 250 -; time for status change visibility in header (ms) +; time for status change visibility in header (milliseconds) (default: 5000) PROGRAM_STATUS_VISIBLE = 5000 -; main map update ping (ajax) (ms) +; main map update ping (ajax) (milliseconds) [PATHFINDER.TIMER.UPDATE_SERVER_MAP] DELAY = 5000 EXECUTION_LIMIT = 200 -; update client map data (ms) +; update client map data (milliseconds) [PATHFINDER.TIMER.UPDATE_CLIENT_MAP] EXECUTION_LIMIT = 50 -; map user update ping (ajax) (ms) +; map user update ping (ajax) (milliseconds) [PATHFINDER.TIMER.UPDATE_SERVER_USER_DATA] DELAY = 5000 EXECUTION_LIMIT = 500 -; update client user data (ms) +; update client user data (milliseconds) [PATHFINDER.TIMER.UPDATE_CLIENT_USER_DATA] EXECUTION_LIMIT = 50 diff --git a/app/requirements.ini b/app/requirements.ini index ef298c1e..36f727dc 100644 --- a/app/requirements.ini +++ b/app/requirements.ini @@ -10,7 +10,7 @@ NGINX.VERSION = 1.9 [REQUIREMENTS.PHP] ; recommended is >= 5.6 -VERSION = 5.6 +VERSION = 7.0 ; "Perl-Compatible Regular Expressions" ; usually shipped with PHP package, diff --git a/app/routes.ini b/app/routes.ini index 067dc6f3..e139be66 100644 --- a/app/routes.ini +++ b/app/routes.ini @@ -12,6 +12,6 @@ GET @sso: /sso/@action [sync] = Controller\Ccp\Sso-> GET @map: /map [sync] = Controller\MapController->init ; ajax wildcard APIs (throttled) -GET|POST /api/@controller/@action [ajax] = Controller\Api\@controller->@action, , 512 -GET|POST /api/@controller/@action/@arg1 [ajax] = Controller\Api\@controller->@action, , 512 -GET|POST /api/@controller/@action/@arg1/@arg2 [ajax] = Controller\Api\@controller->@action, , 512 +GET|POST /api/@controller/@action [ajax] = Controller\Api\@controller->@action, 0, 512 +GET|POST /api/@controller/@action/@arg1 [ajax] = Controller\Api\@controller->@action, 0, 512 +GET|POST /api/@controller/@action/@arg1/@arg2 [ajax] = Controller\Api\@controller->@action, 0, 512 diff --git a/export/csv/system_wormhole.csv b/export/csv/system_wormhole.csv index 7ab7caaa..cc8aa239 100644 --- a/export/csv/system_wormhole.csv +++ b/export/csv/system_wormhole.csv @@ -1,152 +1,235 @@ "Id";"Created";"Updated";"SystemId";"WormholeId"; -"1";"2016-07-16 13:53:19";"2016-07-16 13:53:19";"31002572";"59"; -"2";"2016-07-16 13:53:19";"2016-07-16 13:53:19";"31002572";"25"; -"3";"2016-07-16 13:53:19";"2016-07-16 13:53:19";"31002518";"6"; -"4";"2016-07-16 13:53:19";"2016-07-16 13:53:19";"31002518";"21"; -"5";"2016-07-16 13:53:19";"2016-07-16 13:53:19";"31002543";"12"; -"6";"2016-07-16 13:53:19";"2016-07-16 13:53:19";"31002543";"68"; -"7";"2016-07-16 13:53:19";"2016-07-16 13:53:19";"31002528";"18"; -"8";"2016-07-16 13:53:19";"2016-07-16 13:53:19";"31002528";"59"; -"9";"2016-07-16 13:53:19";"2016-07-16 13:53:19";"31002535";"18"; -"10";"2016-07-16 13:53:19";"2016-07-16 13:53:19";"31002535";"59"; -"11";"2016-07-16 13:53:19";"2016-07-16 13:53:19";"31002530";"18"; -"12";"2016-07-16 13:53:19";"2016-07-16 13:53:19";"31002530";"59"; -"13";"2016-07-16 13:53:19";"2016-07-16 13:53:19";"31002557";"59"; -"14";"2016-07-16 13:53:19";"2016-07-16 13:53:19";"31002557";"25"; -"15";"2016-07-16 13:53:19";"2016-07-16 13:53:19";"31002548";"12"; -"16";"2016-07-16 13:53:19";"2016-07-16 13:53:19";"31002548";"68"; -"17";"2016-07-16 13:53:19";"2016-07-16 13:53:19";"31002564";"59"; -"18";"2016-07-16 13:53:19";"2016-07-16 13:53:19";"31002564";"25"; -"19";"2016-07-16 13:53:19";"2016-07-16 13:53:19";"31002524";"6"; -"20";"2016-07-16 13:53:19";"2016-07-16 13:53:19";"31002524";"21"; -"21";"2016-07-16 13:53:19";"2016-07-16 13:53:19";"31002514";"39"; -"22";"2016-07-16 13:53:19";"2016-07-16 13:53:19";"31002514";"28"; -"23";"2016-07-16 13:53:19";"2016-07-16 13:53:19";"31002542";"12"; -"24";"2016-07-16 13:53:19";"2016-07-16 13:53:19";"31002542";"68"; -"25";"2016-07-16 13:53:19";"2016-07-16 13:53:19";"31002538";"12"; -"26";"2016-07-16 13:53:19";"2016-07-16 13:53:19";"31002538";"68"; -"27";"2016-07-16 13:53:19";"2016-07-16 13:53:19";"31002511";"39"; -"28";"2016-07-16 13:53:19";"2016-07-16 13:53:19";"31002511";"28"; -"29";"2016-07-16 13:53:19";"2016-07-16 13:53:19";"31002529";"18"; -"30";"2016-07-16 13:53:19";"2016-07-16 13:53:19";"31002529";"59"; -"31";"2016-07-16 13:53:19";"2016-07-16 13:53:19";"31002525";"6"; -"32";"2016-07-16 13:53:19";"2016-07-16 13:53:19";"31002525";"21"; -"33";"2016-07-16 13:53:19";"2016-07-16 13:53:19";"31002562";"59"; -"34";"2016-07-16 13:53:19";"2016-07-16 13:53:19";"31002562";"25"; -"35";"2016-07-16 13:53:19";"2016-07-16 13:53:19";"31002563";"59"; -"36";"2016-07-16 13:53:19";"2016-07-16 13:53:19";"31002563";"25"; -"37";"2016-07-16 13:53:19";"2016-07-16 13:53:19";"31002532";"18"; -"38";"2016-07-16 13:53:19";"2016-07-16 13:53:19";"31002532";"59"; -"39";"2016-07-16 13:53:19";"2016-07-16 13:53:19";"31002569";"59"; -"40";"2016-07-16 13:53:19";"2016-07-16 13:53:19";"31002569";"25"; -"41";"2016-07-16 13:53:19";"2016-07-16 13:53:19";"31002558";"59"; -"42";"2016-07-16 13:53:19";"2016-07-16 13:53:19";"31002558";"25"; -"43";"2016-07-16 13:53:19";"2016-07-16 13:53:19";"31002570";"59"; -"44";"2016-07-16 13:53:19";"2016-07-16 13:53:19";"31002570";"25"; -"45";"2016-07-16 13:53:19";"2016-07-16 13:53:19";"31002549";"12"; -"46";"2016-07-16 13:53:19";"2016-07-16 13:53:19";"31002549";"68"; -"47";"2016-07-16 13:53:19";"2016-07-16 13:53:19";"31002537";"30"; -"48";"2016-07-16 13:53:19";"2016-07-16 13:53:19";"31002537";"59"; -"49";"2016-07-16 13:53:19";"2016-07-16 13:53:19";"31002513";"39"; -"50";"2016-07-16 13:53:19";"2016-07-16 13:53:19";"31002513";"28"; -"51";"2016-07-16 13:53:19";"2016-07-16 13:53:19";"31002539";"12"; -"52";"2016-07-16 13:53:19";"2016-07-16 13:53:19";"31002539";"68"; -"53";"2016-07-16 13:53:19";"2016-07-16 13:53:19";"31002526";"6"; -"54";"2016-07-16 13:53:19";"2016-07-16 13:53:19";"31002526";"21"; -"55";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002512";"39"; -"56";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002512";"28"; -"57";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002574";"59"; -"58";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002574";"25"; -"59";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002561";"59"; -"60";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002561";"25"; -"61";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002571";"59"; -"62";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002571";"25"; -"63";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002567";"59"; -"64";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002567";"20"; -"65";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002546";"12"; -"66";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002546";"68"; -"67";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002555";"12"; -"68";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002555";"68"; -"69";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002552";"12"; -"70";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002552";"68"; -"71";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002515";"6"; -"72";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002515";"21"; -"73";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002568";"59"; -"74";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002568";"25"; -"75";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002573";"59"; -"76";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002573";"25"; -"77";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002506";"39"; -"78";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002506";"28"; -"79";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002550";"12"; -"80";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002550";"68"; -"81";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002516";"6"; -"82";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002516";"21"; -"83";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002534";"30"; -"84";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002534";"59"; -"85";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002508";"39"; -"86";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002508";"28"; -"87";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002547";"12"; -"88";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002547";"68"; -"89";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002523";"6"; -"90";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002523";"21"; -"91";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002541";"12"; -"92";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002541";"68"; -"93";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002576";"30"; -"94";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002576";"65"; -"95";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002544";"12"; -"96";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002544";"68"; -"97";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002509";"39"; -"98";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002509";"28"; -"99";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002556";"59"; -"100";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002556";"25"; -"101";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002579";"30"; -"102";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002579";"65"; -"103";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002554";"12"; -"104";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002554";"68"; -"105";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002519";"6"; -"106";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002519";"21"; -"107";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002536";"18"; -"108";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002536";"59"; -"109";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002553";"12"; -"110";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002553";"68"; -"111";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002551";"12"; -"112";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002551";"68"; -"113";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002527";"18"; -"114";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002527";"59"; -"115";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002545";"12"; -"116";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002545";"68"; -"117";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002559";"59"; -"118";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002559";"25"; -"119";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002540";"12"; -"120";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002540";"68"; -"121";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002510";"39"; -"122";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002510";"28"; -"123";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002507";"39"; -"124";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002507";"28"; -"125";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002577";"30"; -"126";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002577";"65"; -"127";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002565";"59"; -"128";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002565";"25"; -"129";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002522";"6"; -"130";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002522";"21"; -"131";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002575";"30"; -"132";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002575";"65"; -"133";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002521";"6"; -"134";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002521";"21"; -"135";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002566";"59"; -"136";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002566";"25"; -"137";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002533";"18"; -"138";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002533";"59"; -"139";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002517";"6"; -"140";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002517";"21"; -"141";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002520";"6"; -"142";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002520";"21"; -"143";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002560";"59"; -"144";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002560";"25"; -"145";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002531";"18"; -"146";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002531";"59"; -"147";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002505";"39"; -"148";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002505";"28"; -"149";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002578";"30"; -"150";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002578";"13"; -"151";"2016-07-16 13:53:20";"2016-07-16 13:53:20";"31002578";"66"; \ No newline at end of file +"1";"2016-07-16 13:53:19";"2017-02-11 17:11:18";"31002572";"59"; +"2";"2016-07-16 13:53:19";"2017-02-11 17:11:18";"31002572";"25"; +"3";"2016-07-16 13:53:19";"2017-02-11 17:11:19";"31002518";"6"; +"4";"2016-07-16 13:53:19";"2017-02-11 17:11:19";"31002518";"21"; +"5";"2016-07-16 13:53:19";"2017-02-11 17:11:19";"31002543";"12"; +"6";"2016-07-16 13:53:19";"2017-02-11 17:11:19";"31002543";"68"; +"7";"2016-07-16 13:53:19";"2017-02-11 17:11:19";"31002528";"18"; +"8";"2016-07-16 13:53:19";"2017-02-11 17:11:19";"31002528";"59"; +"9";"2016-07-16 13:53:19";"2017-02-11 17:11:19";"31002535";"18"; +"10";"2016-07-16 13:53:19";"2017-02-11 17:11:19";"31002535";"59"; +"11";"2016-07-16 13:53:19";"2017-02-11 17:11:19";"31002530";"18"; +"12";"2016-07-16 13:53:19";"2017-02-11 17:11:19";"31002530";"59"; +"13";"2016-07-16 13:53:19";"2017-02-11 17:11:19";"31002557";"59"; +"14";"2016-07-16 13:53:19";"2017-02-11 17:11:19";"31002557";"25"; +"15";"2016-07-16 13:53:19";"2017-02-11 17:11:19";"31002548";"12"; +"16";"2016-07-16 13:53:19";"2017-02-11 17:11:19";"31002548";"68"; +"17";"2016-07-16 13:53:19";"2017-02-11 17:11:19";"31002564";"59"; +"18";"2016-07-16 13:53:19";"2017-02-11 17:11:19";"31002564";"25"; +"19";"2016-07-16 13:53:19";"2017-02-11 17:11:19";"31002524";"6"; +"20";"2016-07-16 13:53:19";"2017-02-11 17:11:19";"31002524";"21"; +"21";"2016-07-16 13:53:19";"2017-02-11 17:11:19";"31002514";"39"; +"22";"2016-07-16 13:53:19";"2017-02-11 17:11:19";"31002514";"28"; +"23";"2016-07-16 13:53:19";"2017-02-11 17:11:19";"31002542";"12"; +"24";"2016-07-16 13:53:19";"2017-02-11 17:11:19";"31002542";"68"; +"25";"2016-07-16 13:53:19";"2017-02-11 17:11:19";"31002538";"12"; +"26";"2016-07-16 13:53:19";"2017-02-11 17:11:19";"31002538";"68"; +"27";"2016-07-16 13:53:19";"2017-02-11 17:11:19";"31002511";"39"; +"28";"2016-07-16 13:53:19";"2017-02-11 17:11:19";"31002511";"28"; +"29";"2016-07-16 13:53:19";"2017-02-11 17:11:19";"31002529";"18"; +"30";"2016-07-16 13:53:19";"2017-02-11 17:11:19";"31002529";"59"; +"31";"2016-07-16 13:53:19";"2017-02-11 17:11:19";"31002525";"6"; +"32";"2016-07-16 13:53:19";"2017-02-11 17:11:19";"31002525";"21"; +"33";"2016-07-16 13:53:19";"2017-02-11 17:11:19";"31002562";"59"; +"34";"2016-07-16 13:53:19";"2017-02-11 17:11:19";"31002562";"25"; +"35";"2016-07-16 13:53:19";"2017-02-11 17:11:19";"31002563";"59"; +"36";"2016-07-16 13:53:19";"2017-02-11 17:11:19";"31002563";"25"; +"37";"2016-07-16 13:53:19";"2017-02-11 17:11:19";"31002532";"18"; +"38";"2016-07-16 13:53:19";"2017-02-11 17:11:19";"31002532";"59"; +"39";"2016-07-16 13:53:19";"2017-02-11 17:11:19";"31002569";"59"; +"40";"2016-07-16 13:53:19";"2017-02-11 17:11:19";"31002569";"25"; +"41";"2016-07-16 13:53:19";"2017-02-11 17:11:19";"31002558";"59"; +"42";"2016-07-16 13:53:19";"2017-02-11 17:11:19";"31002558";"25"; +"43";"2016-07-16 13:53:19";"2017-02-11 17:11:19";"31002570";"59"; +"44";"2016-07-16 13:53:19";"2017-02-11 17:11:19";"31002570";"25"; +"45";"2016-07-16 13:53:19";"2017-02-11 17:11:19";"31002549";"12"; +"46";"2016-07-16 13:53:19";"2017-02-11 17:11:19";"31002549";"68"; +"47";"2016-07-16 13:53:19";"2017-02-11 17:11:19";"31002537";"30"; +"48";"2016-07-16 13:53:19";"2017-02-11 17:11:19";"31002537";"59"; +"49";"2016-07-16 13:53:19";"2017-02-11 17:11:19";"31002513";"39"; +"50";"2016-07-16 13:53:19";"2017-02-11 17:11:19";"31002513";"28"; +"51";"2016-07-16 13:53:19";"2017-02-11 17:11:19";"31002539";"12"; +"52";"2016-07-16 13:53:19";"2017-02-11 17:11:19";"31002539";"68"; +"53";"2016-07-16 13:53:19";"2017-02-11 17:11:19";"31002526";"6"; +"54";"2016-07-16 13:53:19";"2017-02-11 17:11:19";"31002526";"21"; +"55";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002512";"39"; +"56";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002512";"28"; +"57";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002574";"59"; +"58";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002574";"25"; +"59";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002561";"59"; +"60";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002561";"25"; +"61";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002571";"59"; +"62";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002571";"25"; +"63";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002567";"59"; +"64";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002567";"20"; +"65";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002546";"12"; +"66";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002546";"68"; +"67";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002555";"12"; +"68";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002555";"68"; +"69";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002552";"12"; +"70";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002552";"68"; +"71";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002515";"6"; +"72";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002515";"21"; +"73";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002568";"59"; +"74";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002568";"25"; +"75";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002573";"59"; +"76";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002573";"25"; +"77";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002506";"39"; +"78";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002506";"28"; +"79";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002550";"12"; +"80";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002550";"68"; +"81";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002516";"6"; +"82";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002516";"21"; +"83";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002534";"30"; +"84";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002534";"59"; +"85";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002508";"39"; +"86";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002508";"28"; +"87";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002547";"12"; +"88";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002547";"68"; +"89";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002523";"6"; +"90";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002523";"21"; +"91";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002541";"12"; +"92";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002541";"68"; +"93";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002576";"30"; +"94";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002576";"65"; +"95";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002544";"12"; +"96";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002544";"68"; +"97";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002509";"39"; +"98";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002509";"28"; +"99";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002556";"59"; +"100";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002556";"25"; +"101";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002579";"30"; +"102";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002579";"65"; +"103";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002554";"12"; +"104";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002554";"68"; +"105";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002519";"6"; +"106";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002519";"21"; +"107";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002536";"18"; +"108";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002536";"59"; +"109";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002553";"12"; +"110";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002553";"68"; +"111";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002551";"12"; +"112";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002551";"68"; +"113";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002527";"18"; +"114";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002527";"59"; +"115";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002545";"12"; +"116";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002545";"68"; +"117";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002559";"59"; +"118";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002559";"25"; +"119";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002540";"12"; +"120";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002540";"68"; +"121";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002510";"39"; +"122";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002510";"28"; +"123";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002507";"39"; +"124";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002507";"28"; +"125";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002577";"30"; +"126";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002577";"65"; +"127";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002565";"59"; +"128";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002565";"25"; +"129";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002522";"6"; +"130";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002522";"21"; +"131";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002575";"30"; +"132";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002575";"65"; +"133";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002521";"6"; +"134";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002521";"21"; +"135";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002566";"59"; +"136";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002566";"25"; +"137";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002533";"18"; +"138";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002533";"59"; +"139";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002517";"6"; +"140";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002517";"21"; +"141";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002520";"6"; +"142";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002520";"21"; +"143";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002560";"59"; +"144";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002560";"25"; +"145";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002531";"18"; +"146";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002531";"59"; +"147";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002505";"39"; +"148";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002505";"28"; +"149";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002578";"30"; +"150";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002578";"13"; +"151";"2016-07-16 13:53:20";"2017-02-11 17:11:19";"31002578";"66"; +"152";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002572";"35"; +"153";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002518";"16"; +"154";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002543";"30"; +"155";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002543";"26"; +"156";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002543";"61"; +"157";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002535";"30"; +"158";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002530";"30"; +"159";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002557";"30"; +"160";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002548";"30"; +"161";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002548";"26"; +"162";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002524";"2"; +"163";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002524";"75"; +"164";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002514";"72"; +"165";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002542";"18"; +"166";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002542";"49"; +"167";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002542";"42"; +"168";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002538";"59"; +"169";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002511";"72"; +"170";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002529";"30"; +"171";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002525";"2"; +"172";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002525";"38"; +"173";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002562";"15"; +"174";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002563";"35"; +"175";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002569";"30"; +"176";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002569";"20"; +"177";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002558";"30"; +"178";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002549";"18"; +"179";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002549";"42"; +"180";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002539";"59"; +"181";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002526";"2"; +"182";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002526";"47"; +"183";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002574";"30"; +"184";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002571";"30"; +"185";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002571";"64"; +"186";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002546";"18"; +"187";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002555";"59"; +"188";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002552";"30"; +"189";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002552";"26"; +"190";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002515";"2"; +"191";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002515";"75"; +"192";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002573";"30"; +"193";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002506";"72"; +"194";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002550";"59"; +"195";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002550";"49"; +"196";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002516";"2"; +"197";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002516";"69"; +"198";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002547";"30"; +"199";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002547";"26"; +"200";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002547";"61"; +"201";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002523";"75"; +"202";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002523";"16"; +"203";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002541";"59"; +"204";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002541";"42"; +"205";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002576";"66"; +"206";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002544";"18"; +"207";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002544";"49"; +"208";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002544";"42"; +"209";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002556";"30"; +"210";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002556";"64"; +"211";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002554";"59"; +"212";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002554";"26"; +"213";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002519";"69"; +"214";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002551";"59"; +"215";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002551";"26"; +"216";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002545";"18"; +"217";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002545";"49"; +"218";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002559";"17"; +"219";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002559";"30"; +"220";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002559";"35"; +"221";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002540";"59"; +"222";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002510";"72"; +"223";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002507";"72"; +"224";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002522";"2"; +"225";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002521";"47"; +"226";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002566";"20"; +"227";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002533";"30"; +"228";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002517";"2"; +"229";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002517";"53"; +"230";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002520";"2"; +"231";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002520";"16"; +"232";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002560";"30"; +"233";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31002505";"72"; +"234";"2017-02-25 17:52:14";"2017-02-25 17:52:14";"31000001";"16"; \ No newline at end of file diff --git a/export/json/statics.json b/export/json/statics.json index 79238bf9..702d4d77 100644 --- a/export/json/statics.json +++ b/export/json/statics.json @@ -1,75 +1,76 @@ -{"J001025":["U210","H296"], -"J001057":["B274","E545"], -"J001302":["C247","X877"], +{"J001025":["U210","M267"], +"J001057":["B274","E545","D382"], +"J001302":["K346","H900","U574"], "J001348":["D845","U210"], -"J001398":["D845","U210"], -"J001670":["D845","U210"], -"J001694":["U210","H296"], -"J001769":["C247","X877"], +"J001398":["U210","K346"], +"J001670":["U210","K346"], +"J001694":["K346","H296"], +"J001769":["K346","X877","H900"], "J001820":["U210","H296"], -"J001890":["B274","E545"], -"J002216":["N110","J244"], -"J002423":["C247","X877"], -"J002625":["C247","X877"], -"J002757":["N110","J244"], -"J002838":["D845","U210"], -"J002964":["B274","E545"], -"J003382":["U210","H296"], -"J003546":["U210","H296"], +"J001890":["B274","A239","Z647"], +"J002216":["J244","Z060"], +"J002423":["D845","P060","N766"], +"J002625":["U210","C247","X877"], +"J002757":["N110","Z060"], +"J002838":["U210","K346"], +"J002964":["A239","E545","N062"], +"J003382":["U210","D364"], +"J003546":["U210","M267"], "J003789":["D845","U210"], -"J003793":["U210","H296"], -"J003941":["U210","H296"], +"J003793":["K346","E175"], +"J003941":["K346","H296"], "J004128":["U210","H296"], -"J004150":["C247","X877"], -"J004283":["K346","U210"], +"J004150":["D845","N766","C247"], +"J004283":["U210","K346"], "J004317":["N110","J244"], -"J004470":["C247","X877"], -"J004686":["B274","E545"], +"J004470":["U210","C247","X877"], +"J004686":["A239","E545","O477"], "J004791":["N110","J244"], -"J004921":["U210","H296"], +"J004921":["K346","H296"], "J004998":["U210","H296"], -"J005070":["U210","H296"], +"J005070":["K346","V753"], "J005223":["U210","E175"], -"J005259":["C247","X877"], -"J005280":["C247","X877"], -"J005299":["C247","X877"], -"J005482":["B274","E545"], -"J005663":["U210","H296"], -"J005724":["U210","H296"], -"J005834":["N110","J244"], -"J005872":["C247","X877"], -"J005900":["B274","E545"], -"J005923":["D845","U210"], +"J005259":["D845","C247","X877"], +"J005280":["U210","C247","X877"], +"J005299":["K346","C247","H900"], +"J005482":["B274","A239","Z647"], +"J005663":["U210"], +"J005724":["K346","H296"], +"J005834":["N110","Z060"], +"J005872":["U210","P060","C247"], +"J005900":["A239","E545","Y683"], +"J005923":["U210","K346"], "J005926":["N110","J244"], -"J005969":["C247","X877"], -"J010000":["B274","E545"], -"J010247":["C247","X877"], -"J010366":["K346","V911"], -"J010556":["C247","X877"], +"J005969":["K346","H900","U574"], +"J010000":["B274","Z647","D382"], +"J010247":["U210","N766","X877"], +"J010366":["W237"], +"J010556":["D845","P060","N766"], "J010569":["N110","J244"], -"J010811":["U210","H296"], +"J010811":["K346","V753"], "J010951":["K346","V911"], -"J011195":["C247","X877"], -"J011321":["B274","E545"], +"J011195":["U210","X877","H900"], +"J011321":["B274","E545","Y683"], "J011339":["D845","U210"], "J011355":["C247","X877"], -"J011376":["C247","X877"], +"J011376":["U210","X877","H900"], "J011563":["D845","U210"], -"J011778":["C247","X877"], -"J011790":["U210","H296"], -"J011824":["C247","X877"], -"J012157":["N110","J244"], -"J012402":["N110","J244"], +"J011778":["D845","P060","C247"], +"J011790":["D792","K346","M267"], +"J011824":["U210","C247","X877"], +"J012157":["J244","Z060"], +"J012402":["N110","Z060"], "J012475":["K346","V911"], "J012578":["U210","H296"], -"J012635":["B274","E545"], +"J012635":["B274","A239"], "J012686":["K346","V911"], -"J012735":["B274","E545"], -"J012773":["U210","H296"], -"J012794":["D845","U210"], -"J013070":["B274","E545"], -"J013123":["B274","E545"], -"J013146":["U210","H296"], +"J012735":["B274","E545","O477"], +"J012773":["E175"], +"J012794":["U210","K346"], +"J013070":["A239","E545","R474"], +"J013123":["B274","A239","D382"], +"J013146":["K346","H296"], "J014348":["D845","U210"], -"J015092":["N110","J244"], -"J015227":["K346","C248", "W237"]} \ No newline at end of file +"J015092":["N110","Z060"], +"J015227":["K346","W237"], +"J055520":["D382"]} diff --git a/js/app.js b/js/app.js index 063467b8..df982a8e 100644 --- a/js/app.js +++ b/js/app.js @@ -21,7 +21,7 @@ requirejs.config({ mappage: './app/mappage', // initial start "map page" view setup: './app/setup', // initial start "setup page" view - jquery: 'lib/jquery-3.0.0.min', // v3.0.0 jQuery + jquery: 'lib/jquery-3.1.1.min', // v3.1.1 jQuery bootstrap: 'lib/bootstrap.min', // v3.3.0 Bootstrap js code - http://getbootstrap.com/javascript text: 'lib/requirejs/text', // v2.0.12 A RequireJS/AMD loader plugin for loading text resources. mustache: 'lib/mustache.min', // v1.0.0 Javascript template engine - http://mustache.github.io diff --git a/js/app/config/signature_type.js b/js/app/config/signature_type.js index 97f2b056..5110501a 100644 --- a/js/app/config/signature_type.js +++ b/js/app/config/signature_type.js @@ -15,7 +15,7 @@ define(['jquery'], function($) { // NullSec Relic sites, which can also spawn in C1, C2, C3 wormholes - var nullSecRelicSites = { + let nullSecRelicSites = { 10: 'Ruined Angel Crystal Quarry', 11: 'Ruined Angel Monument Site', 12: 'Ruined Angel Science Outpost', @@ -39,7 +39,7 @@ define(['jquery'], function($) { }; // NulSec Data sites, which can also spawn in C1, C2, C3 wormholes - var nullSecDataSites = { + let nullSecDataSites = { 10: 'Abandoned Research Complex DA005', 11: 'Abandoned Research Complex DA015', 12: 'Abandoned Research Complex DC007', @@ -70,7 +70,7 @@ define(['jquery'], function($) { // signature types - var signatureTypes = { + let signatureTypes = { 1: { // system type (wh) 1: { // C1 (area id) 1: { // Combat @@ -342,32 +342,31 @@ define(['jquery'], function($) { 4: 'L005 - C2', 5: 'N766 - C2', 6: 'C247 - C3', - 7: 'K346 - C3', - 8: 'M267 - C3', - 9: 'O477 - C3', - 10: 'X877 - C4', - 11: 'Y683 - C4', - 12: 'H296 - C5', - 13: 'H900 - C5', - 14: 'H296 - C5', - 15: 'N062 - C5', - 16: 'V911 - C5', - 17: 'U574 - C6', - 18: 'V753 - C6', - 19: 'W237 - C6', - 20: 'B274 - HS', - 21: 'D792 - HS', - 22: 'D845 - HS', - 23: 'N110 - HS', - 24: 'A239 - LS', - 25: 'C391 - LS', - 26: 'J244 - LS', - 27: 'U201 - LS', - 28: 'U210 - LS', - 29: 'C248 - 0.0', - 30: 'E545 - 0.0', - 31: 'K346 - 0.0', - 32: 'Z060 - 0.0' + 7: 'M267 - C3', + 8: 'O477 - C3', + 9: 'X877 - C4', + 10: 'Y683 - C4', + 11: 'H296 - C5', + 12: 'H900 - C5', + 13: 'H296 - C5', + 14: 'N062 - C5', // ?? + 15: 'V911 - C5', + 16: 'U574 - C6', + 17: 'V753 - C6', + 18: 'W237 - C6', + 19: 'B274 - HS', + 20: 'D792 - HS', + 21: 'D845 - HS', + 22: 'N110 - HS', + 23: 'A239 - LS', + 24: 'C391 - LS', + 25: 'J244 - LS', + 26: 'U201 - LS', // ?? + 27: 'U210 - LS', + 28: 'C248 - 0.0', + 29: 'E545 - 0.0', + 30: 'K346 - 0.0', + 31: 'Z060 - 0.0' } } }, // system type (k-space) diff --git a/js/app/config/system_effect.js b/js/app/config/system_effect.js index b433d937..fe97afa2 100644 --- a/js/app/config/system_effect.js +++ b/js/app/config/system_effect.js @@ -9,7 +9,7 @@ define([], function() { 'use strict'; // system effects - var systemEffects = { + let systemEffects = { wh: { magnetar: { 1: [ diff --git a/js/app/init.js b/js/app/init.js index e067560d..d32b5315 100644 --- a/js/app/init.js +++ b/js/app/init.js @@ -8,51 +8,52 @@ define(['jquery'], function($) { let Config = { path: { - img: 'public/img/', // path for images + img: 'public/img/', // path for images // user API - getCaptcha: 'api/user/getCaptcha', // ajax URL - get captcha image - getServerStatus: 'api/user/getEveServerStatus', // ajax URL - get EVE-Online server status - getCookieCharacterData: 'api/user/getCookieCharacter', // ajax URL - get character data from cookie - logIn: 'api/user/logIn', // ajax URL - login - logout: 'api/user/logout', // ajax URL - logout - deleteLog: 'api/user/deleteLog', // ajax URL - delete character log - saveUserConfig: 'api/user/saveAccount', // ajax URL - saves/update user account - deleteAccount: 'api/user/deleteAccount', // ajax URL - delete Account data + getCaptcha: 'api/user/getCaptcha', // ajax URL - get captcha image + getServerStatus: 'api/user/getEveServerStatus', // ajax URL - get EVE-Online server status + getCookieCharacterData: 'api/user/getCookieCharacter', // ajax URL - get character data from cookie + logIn: 'api/user/logIn', // ajax URL - login + logout: 'api/user/logout', // ajax URL - logout + deleteLog: 'api/user/deleteLog', // ajax URL - delete character log + saveUserConfig: 'api/user/saveAccount', // ajax URL - saves/update user account + deleteAccount: 'api/user/deleteAccount', // ajax URL - delete Account data // access API - searchAccess: 'api/access/search', // ajax URL - search user/corporation/ally by name + searchAccess: 'api/access/search', // ajax URL - search user/corporation/ally by name // main config/map ping API - initMap: 'api/map/init', // ajax URL - get static data - getAccessData: 'api/map/getAccessData', // ajax URL - get map access tokens (WebSocket) - updateMapData: 'api/map/updateData', // ajax URL - main map update trigger - updateUserData: 'api/map/updateUserData', // ajax URL - main map user data trigger + initMap: 'api/map/init', // ajax URL - get static data + getAccessData: 'api/map/getAccessData', // ajax URL - get map access tokens (WebSocket) + updateMapData: 'api/map/updateData', // ajax URL - main map update trigger + updateUserData: 'api/map/updateUserData', // ajax URL - main map user data trigger // map API - saveMap: 'api/map/save', // ajax URL - save/update map - deleteMap: 'api/map/delete', // ajax URL - delete map - importMap: 'api/map/import', // ajax URL - import map + saveMap: 'api/map/save', // ajax URL - save/update map + deleteMap: 'api/map/delete', // ajax URL - delete map + importMap: 'api/map/import', // ajax URL - import map + getMapConnectionData: 'api/map/getConnectionData', // ajax URL - get connection data // system API - searchSystem: 'api/system/search', // ajax URL - search system by name - saveSystem: 'api/system/save', // ajax URL - saves system to map - deleteSystem: 'api/system/delete', // ajax URL - delete system from map - getSystemGraphData: 'api/system/graphData', // ajax URL - get all system graph data - getConstellationData: 'api/system/constellationData', // ajax URL - get system constellation data - setDestination: 'api/system/setDestination', // ajax URL - set destination + searchSystem: 'api/system/search', // ajax URL - search system by name + saveSystem: 'api/system/save', // ajax URL - saves system to map + deleteSystem: 'api/system/delete', // ajax URL - delete system from map + getSystemGraphData: 'api/system/graphData', // ajax URL - get all system graph data + getConstellationData: 'api/system/constellationData', // ajax URL - get system constellation data + setDestination: 'api/system/setDestination', // ajax URL - set destination // connection API - saveConnection: 'api/connection/save', // ajax URL - save new connection to map - deleteConnection: 'api/connection/delete', // ajax URL - delete connection from map + saveConnection: 'api/connection/save', // ajax URL - save new connection to map + deleteConnection: 'api/connection/delete', // ajax URL - delete connection from map // signature API - getSignatures: 'api/signature/getAll', // ajax URL - get all signature data for system - saveSignatureData: 'api/signature/save', // ajax URL - save signature data for system - deleteSignatureData: 'api/signature/delete', // ajax URL - delete signature data for system + getSignatures: 'api/signature/getAll', // ajax URL - get all signature data for system + saveSignatureData: 'api/signature/save', // ajax URL - save signature data for system + deleteSignatureData: 'api/signature/delete', // ajax URL - delete signature data for system // route API - searchRoute: 'api/route/search', // ajax URL - search system routes + searchRoute: 'api/route/search', // ajax URL - search system routes // stats API - getStatisticsData: 'api/statistic/getData', // ajax URL - get statistics data (activity log) + getStatisticsData: 'api/statistic/getData', // ajax URL - get statistics data (activity log) // GitHub API - gitHubReleases: 'api/github/releases' // ajax URL - get release info from GitHub + gitHubReleases: 'api/github/releases' // ajax URL - get release info from GitHub }, url: { - ccpImageServer: 'https://image.eveonline.com/', // CCP image Server - zKillboard: 'https://zkillboard.com/api/' // killboard api + ccpImageServer: 'https://image.eveonline.com/', // CCP image Server + zKillboard: 'https://zkillboard.com/api/' // killboard api }, breakpoints: [ { name: 'desktop', width: Infinity }, @@ -61,13 +62,13 @@ define(['jquery'], function($) { { name: 'phone', width: 480 } ], animationSpeed: { - splashOverlay: 300, // "splash" loading overlay - headerLink: 100, // links in head bar - mapOverlay: 200, // show/hide duration for map overlays - mapMoveSystem: 180, // system position has changed animation - mapDeleteSystem: 200, // remove system from map - mapModule: 200, // show/hide of an map module - dialogEvents: 180 // dialog events /slide/show/... + splashOverlay: 300, // "splash" loading overlay + headerLink: 100, // links in head bar + mapOverlay: 200, // show/hide duration for map overlays + mapMoveSystem: 180, // system position has changed animation + mapDeleteSystem: 200, // remove system from map + mapModule: 200, // show/hide of an map module + dialogEvents: 180 // dialog events /slide/show/... }, syncStatus: { type: 'ajax', @@ -77,7 +78,7 @@ define(['jquery'], function($) { timestamp: undefined }, sharedWorker: { - status: 'offline', // SharedWorker status + status: 'offline', // SharedWorker status class: 'txt-color-danger', timestamp: undefined }, @@ -88,12 +89,12 @@ define(['jquery'], function($) { } }, performanceLogging: { - keyServerMapData: 'UPDATE_SERVER_MAP', // ajax request update map data - keyClientMapData: 'UPDATE_CLIENT_MAP', // update client map data - keyServerUserData: 'UPDATE_SERVER_USER_DATA', // ajax request update map user data - keyClientUserData: 'UPDATE_CLIENT_USER_DATA', // update client map user data + keyServerMapData: 'UPDATE_SERVER_MAP', // ajax request update map data + keyClientMapData: 'UPDATE_CLIENT_MAP', // update client map data + keyServerUserData: 'UPDATE_SERVER_USER_DATA', // ajax request update map user data + keyClientUserData: 'UPDATE_CLIENT_USER_DATA', // update client map user data }, - mapIcons: [ // map tab-icons + mapIcons: [ // map tab-icons { class: 'fa-desktop', label: 'desktop', @@ -186,7 +187,7 @@ define(['jquery'], function($) { class: 'pf-system-sec-unknown' }, 'H': { - class: 'pf-system-sec-highSec' + class: 'pf-system-sec-highSec' }, 'L': { class: 'pf-system-sec-lowSec' @@ -258,12 +259,12 @@ define(['jquery'], function($) { }, // easy-pie-charts pieChart: { - class: 'pf-pie-chart', // class for all pie charts - pieChartMapCounterClass: 'pf-pie-chart-map-timer' // class for timer chart + class: 'pf-pie-chart', // class for all pie charts + pieChartMapCounterClass: 'pf-pie-chart-map-timer' // class for timer chart } }, // map scopes - defaultMapScope: 'wh', // default scope for connection + defaultMapScope: 'wh', // default scope for connection // map connection types connectionTypes: { jumpbridge: { @@ -400,7 +401,7 @@ define(['jquery'], function($) { 6: 'G008 - C6', 7: 'Q003 - 0.0', 8: 'A009 - (shattered)' - }, + }, 5: { // C5 1: 'E004 - C1', 2: 'L005 - C2', diff --git a/js/app/key.js b/js/app/key.js new file mode 100644 index 00000000..01a04cdb --- /dev/null +++ b/js/app/key.js @@ -0,0 +1,442 @@ +define([ + 'jquery' +], function($) { + 'use strict'; + + let allCombo = { + // global ------------------------------------------------------------------------------------------- + tabReload: { + group: 'global', + label: 'Close open dialog', + keyNames: ['ESC'] + }, + // signature ---------------------------------------------------------------------------------------- + signatureSelect: { + group: 'signatures', + label: 'Select multiple rows', + keyNames: ['CONTROL', 'CLICK'] + } + }; + + let allEvents = { + // global ------------------------------------------------------------------------------------------- + tabReload: { + group: 'global', + label: 'Reload tab', + keyNames: ['CONTROL', 'R'] + }, + signaturePaste: { + group: 'global', + label: 'Paste signatures from clipboard', + keyNames: ['CONTROL', 'V'], + alias: 'paste' + }, + + // map ---------------------------------------------------------------------------------------------- + mapSystemAdd: { + group: 'map', + label: 'Add new system', + keyNames: ['CONTROL', 'S'] + }, + mapSystemsSelect: { + group: 'map', + label: 'Select all systems', + keyNames: ['CONTROL', 'A'] + }, + mapSystemsDelete: { + group: 'map', + label: 'Delete selected systems', + keyNames: ['CONTROL', 'D'] + } + }; + + let groups = { + global: { + label: 'Global' + }, + map: { + label: 'Map' + }, + signatures: { + label: 'Signature' + } + }; + + /** + * enables some console.log() information + * @type {boolean} + */ + let debug = false; + + /** + * check interval for "new" active keys + * @type {number} + */ + let keyWatchPeriod = 100; + + /** + * DOM data key for an element that lists all active events (comma separated) + * @type {string} + */ + let dataKeyEvents = 'key-events'; + + /** + * DOM data key prefix whether domElement that holds the trigger needs to be "focused" + * @type {string} + */ + let dataKeyFocusPrefix = 'key-focus-'; + + /** + * DOM data key that holds the callback function for that element + * @type {string} + */ + let dataKeyCallbackPrefix = 'key-callback-'; + + /** + * check if module is initiated + */ + let isInit = false; + + /** + * global key map holds all active (hold down) keys + * @type {{}} + */ + let map = {}; + + /** + * show debug information in console + * @param msg + * @param element + */ + let debugWatchKey = (msg, element) => { + if(debug){ + console.info(msg, element); + } + }; + + /** + * get all active (hold down) keys at this moment + * @returns {Array} + */ + let getActiveKeys = () => { + return Object.keys(map); + }; + + /** + * callback function that compares two arrays + * @param element + * @param index + * @param array + */ + let compareKeyLists = function(element, index, array) { + return this.find(x => x === element); + }; + + /** + * get event names that COULD lead to a "full" event (not all keys pressed yet) + * @param keyList + * @returns {Array} + */ + let checkEventNames = (keyList) => { + let incompleteEvents = []; + for(let event in allEvents){ + // check if "some" or "all" keys are pressed for en event + if( keyList.every(compareKeyLists, allEvents[event].keyNames) ){ + incompleteEvents.push(event); + } + } + + return incompleteEvents; + }; + + /** + * get all event names + * @returns {Array} + */ + let getAllEventNames = () => { + let eventNames = []; + for(let event in allEvents){ + eventNames.push(event); + } + return eventNames; + }; + + /** + * get all event names that matches a given keyList + * @param keyList + * @param checkEvents + * @returns {Array} + */ + let getMatchingEventNames = (keyList, checkEvents) => { + checkEvents = checkEvents || getAllEventNames(); + let events = []; + + for(let event of checkEvents){ + // check if both key arrays are equal + if( + allEvents[event].keyNames.every(compareKeyLists, keyList) && + keyList.every(compareKeyLists, allEvents[event].keyNames) + ){ + events.push(event); + } + } + + return events; + }; + + /** + * init global keyWatch interval and check for event trigger (hotKey combinations) + */ + let init = () => { + if( !isInit ){ + // key watch loop ------------------------------------------------------------------------------- + let prevActiveKeys = []; + + /** + * + * @param e + * @returns {number} 0: no keys hold, 1: invalid match, 2: partial match, 3: match, 4: alias match, 5: event(s) fired + */ + let checkForEvents = (e) => { + let status = 0; + + // get all pressed keys + let activeKeys = getActiveKeys(); + debugWatchKey('activeKeys', activeKeys); + + // check if "active" keys has changes since last loop + if(activeKeys.length){ + // check for "incomplete" events (not all keys pressed yet) + let incompleteEvents = checkEventNames(activeKeys); + if(incompleteEvents.length){ + // "some" event keys pressed OR "all" keys pressed + status = 2; + + // check if key combo matches a registered (valid) event + let events = getMatchingEventNames(activeKeys, incompleteEvents); + if(events.length){ + status = 3; + // check events if there are attached elements to it + events.forEach((event) => { + // skip events that has an alias and should not be triggered by key combo + if( !allEvents[event].alias ){ + if(allEvents[event].elements){ + // search for callback functions attached to each element + allEvents[event].elements.forEach((domElement) => { + let domElementObj = $(domElement); + // check if event on this element requires active "focus" + let optFocus = domElementObj.data(dataKeyFocusPrefix + event); + + if( !( + optFocus && + document.activeElement !== domElement + ) + ){ + // execute callback if valid + let callback = domElementObj.data(dataKeyCallbackPrefix + event); + if(typeof callback === 'function'){ + status = 5; + callback.call(domElement, domElement, e); + } + } + }); + } + }else{ + status = 4; + } + + }); + } + }else{ + // invalid combo + status = 1; + } + } + + // store current keys for next loop check + prevActiveKeys = activeKeys; + + return status; + }; + + // set key-events ------------------------------------------------------------------------------- + let evKeyDown = (e) => { + // exclude some HTML Tags from watcher + if( + e.target.tagName !== 'INPUT' && + e.target.tagName !== 'TEXTAREA' + ){ + let key = e.key.toUpperCase(); + map[key] = true; + + // check for any shortcut combo that triggers an event + let status = checkForEvents(e); + + if( + status === 2 || + status === 3 || + status === 5 + ){ + // prevent SOME browser default actions -> we want 'Pathfinder' shortcuts :) + e.preventDefault(); + } + } + }; + + let evKeyUp = (e) => { + let key = e.key.toUpperCase(); + + if(map.hasOwnProperty(key)){ + delete map[key]; + } + }; + + let container = $('body'); + container.on('keydown', evKeyDown); + container.on('keyup', evKeyUp); + + // global dom remove listener ------------------------------------------------------------------- + // -> check whether the removed element had an event listener active and removes them. + document.body.addEventListener ('DOMNodeRemoved', function(e){ + if(typeof e.target.getAttribute === 'function'){ + let eventNames = e.target.getAttribute(dataKeyEvents); + if(eventNames){ + eventNames.split(',').forEach((event) => { + let index = allEvents[event].elements.indexOf(e.target); + if(index > -1){ + // remove element from event list + allEvents[event].elements.splice(index, 1); + } + }); + } + } + }, false); + + isInit = true; + } + }; + + /** + * add a new "shortCut" combination (event) to a DOM element + * @param event + * @param callback + * @param options + */ + $.fn.watchKey = function(event, callback, options){ + + // default options for keyWatcher on elements + let defaultOptions = { + focus: false, // element must be focused (active) + bubbling: true // elements deeper (children) in the DOM can bubble the event up + }; + + let customOptions = $.extend(true, {}, defaultOptions, options ); + + return this.each((i, domElement) => { + let element = $(domElement); + + // init global key events + init(); + + // check if event is "valid" (exists) and is not already set for this element + let validEvent = false; + if(allEvents[event].elements){ + if(allEvents[event].elements.indexOf(domElement) === -1){ + validEvent = true; + }else{ + console.warn('Event "' + event + '" already set'); + } + }else{ + validEvent = true; + allEvents[event].elements = []; + } + + if(validEvent){ + // store callback options to dom element + if(customOptions.focus){ + let dataAttr = dataKeyFocusPrefix + event; + element.data(dataAttr, true); + + // check if DOM element has "tabindex" attr -> required to manually set focus() to it + if(!domElement.hasAttribute('tabindex')){ + domElement.setAttribute('tabindex', 0); + } + + // element requires a "focus" listener + element.off('click.focusKeyWatcher').on('click.focusKeyWatcher', function(e){ + if( + e.target === this || + customOptions.bubbling + ){ + this.focus(); + debugWatchKey('focus set:', this); + } + }); + } + + // check if is key combo has a native JS event that should be used instead + if(allEvents[event].alias){ + element.on(allEvents[event].alias, callback); + }else{ + // store callback function to dom element + let dataAttr = dataKeyCallbackPrefix + event; + element.data(dataAttr, callback); + } + + // add eventName to dom element as attribute ---------------------------------------------------- + let currentEventNames = element.attr(dataKeyEvents) ? element.attr(dataKeyEvents).split(',') : []; + currentEventNames.push(event); + element.attr(dataKeyEvents, currentEventNames.join(',')); + + // store domElement to event (global) + allEvents[event].elements.push(domElement); + + debugWatchKey('new event "' + event + '" registered', domElement); + } + }); + }; + + /** + * get a array with all available shortcut groups and their events + * @returns {Array} + */ + let getGroupedShortcuts = () => { + let result = $.extend(true, {}, groups); + + // add combos and events to groups + let allEntries = [allCombo, allEvents]; + for(let i = 0; i < allEntries.length; i++){ + for(let event in allEntries[i]){ + let data = allEntries[i][event]; + + //format keyNames for UI + let keyNames = data.keyNames.map( (key) => { + if(key === 'CONTROL'){ + key = 'ctrl'; + } + return key; + }); + + let newEventData = { + label: data.label, + keyNames: keyNames + }; + + if( result[data.group].events ){ + result[data.group].events.push(newEventData); + }else{ + result[data.group].events = [newEventData]; + } + } + } + + // convert obj into array + result = Object.values(result); + + return result; + }; + + return { + getGroupedShortcuts: getGroupedShortcuts + }; +}); \ No newline at end of file diff --git a/js/app/map/contextmenu.js b/js/app/map/contextmenu.js index cce9f84e..649d9bdc 100644 --- a/js/app/map/contextmenu.js +++ b/js/app/map/contextmenu.js @@ -85,6 +85,7 @@ define([ }; settings.menuSelected.call(this, params); + return false; }); } }); diff --git a/js/app/map/magnetizing.js b/js/app/map/magnetizing.js index 618014a1..f83e8885 100644 --- a/js/app/map/magnetizing.js +++ b/js/app/map/magnetizing.js @@ -15,15 +15,15 @@ define([ * Cached current "Magnetizer" object * @type {Magnetizer} */ - var m8 = null; + let m8 = null; /** * init a jsPlumb (map) Element for "magnetised" function. * this is optional and prevents systems from being overlapped */ $.fn.initMagnetizer = function(){ - var mapContainer = this; - var systems = mapContainer.getSystems(); + let mapContainer = this; + let systems = mapContainer.getSystems(); /** * helper function @@ -32,10 +32,10 @@ define([ * @returns {{left, top}} * @private */ - var _offset = function(system) { + let _offset = function(system) { - var _ = function(p) { - var v = system.style[p]; + let _ = function(p) { + let v = system.style[p]; return parseInt(v.substring(0, v.length - 2)); }; @@ -52,8 +52,8 @@ define([ * @param o * @private */ - var _setOffset = function(system, o) { - var markAsUpdated = false; + let _setOffset = function(system, o) { + let markAsUpdated = false; // new position must be within parent container // no negative offset! @@ -85,11 +85,11 @@ define([ * @returns {boolean} * @private */ - var _dragFilter = function(id) { + let _dragFilter = function(id) { return !$('#' + id).is('.jsPlumb_dragged, .pf-system-locked'); }; - var gridConstrain = function(gridX, gridY) { + let gridConstrain = function(gridX, gridY) { return function(id, current, delta) { if( mapContainer.hasClass(MapUtil.config.mapGridClass) ){ // active grid @@ -126,7 +126,7 @@ define([ }; $.fn.destroyMagnetizer = function(){ - var mapContainer = this; + let mapContainer = this; // remove cached "magnetizer" instance m8 = null; @@ -137,7 +137,7 @@ define([ * @param map * @param e */ - var executeAtEvent = function(map, e){ + let executeAtEvent = function(map, e){ if(m8 !== null && e ){ m8.executeAtEvent(e); map.repaintEverything(); @@ -149,7 +149,7 @@ define([ * needs "magnetization" to be active * @param map */ - var executeAtCenter = function(map){ + let executeAtCenter = function(map){ if(m8 !== null){ m8.executeAtCenter(); map.repaintEverything(); @@ -161,10 +161,10 @@ define([ * -> (e.g. new systems was added) * @param map */ - var setElements = function(map){ + let setElements = function(map){ if(m8 !== null){ - var mapContainer = $(map.getContainer()); - var systems = mapContainer.getSystems(); + let mapContainer = $(map.getContainer()); + let systems = mapContainer.getSystems(); m8.setElements(systems); // re-arrange systems diff --git a/js/app/map/map.js b/js/app/map/map.js index 4e6cc5af..571ab544 100644 --- a/js/app/map/map.js +++ b/js/app/map/map.js @@ -22,17 +22,12 @@ define([ let config = { zIndexCounter: 110, - newSystemOffset: { - x: 130, - y: 0 - }, mapSnapToGrid: false, // "Snap to Grid" feature for drag&drop systems on map (optional) mapWrapperClass: 'pf-map-wrapper', // wrapper div (scrollable) mapClass: 'pf-map', // class for all maps mapIdPrefix: 'pf-map-', // id prefix for all maps - systemIdPrefix: 'pf-system-', // id prefix for a system systemClass: 'pf-system', // class for all systems systemActiveClass: 'pf-system-active', // class for an active system in a map systemSelectedClass: 'pf-system-selected', // class for selected systems in a map @@ -79,6 +74,10 @@ define([ // active connections per map (cache object) let connectionCache = {}; + // mapIds that receive updates while they are "locked" (active timer) + // -> those maps queue their updates until "pf:unlocked" event + let mapUpdateQueue = []; + // jsPlumb config let globalMapConfig = { source: { @@ -92,7 +91,7 @@ define([ }, connectionsDetachable: true, // dragOptions are set -> allow detaching them maxConnections: 10, // due to isTarget is true, this is the max count of !out!-going connections - // isSource:true, + // isSource:true, anchor: 'Continuous' }, target: { @@ -105,8 +104,8 @@ define([ hoverClass: config.systemActiveClass, activeClass: 'dragActive' }, - // isTarget:true, - // uniqueEndpoint: false, + // isTarget:true, + // uniqueEndpoint: false, anchor: 'Continuous' }, connectionTypes: Init.connectionTypes @@ -174,20 +173,20 @@ define([ let item = $('
', { class: config.systemBodyItemClass }).append( - $('', { - text: userData.log.ship.typeName, - class: config.systemBodyRightClass - }) - ).append( - $('', { - class: ['fa', 'fa-circle', config.systemBodyItemStatusClass, statusClass].join(' ') - }) - ).append( - $('', { - class: config.systemBodyItemNameClass, - text: userName - }) - ); + $('', { + text: userData.log.ship.typeName, + class: config.systemBodyRightClass + }) + ).append( + $('', { + class: ['fa', 'fa-circle', config.systemBodyItemStatusClass, statusClass].join(' ') + }) + ).append( + $('', { + class: config.systemBodyItemNameClass, + text: userName + }) + ); systemBody.append(item); } @@ -453,21 +452,14 @@ define([ $.fn.getSystem = function(map, data){ // get map container for mapId information let mapContainer = $(this); - let systemId = config.systemIdPrefix + mapContainer.data('id') + '-' + data.id; + let systemId = MapUtil.getSystemId(mapContainer.data('id'), data.id); // check if system already exists let system = document.getElementById( systemId ); - - // just update data if system is new OR "updated" timestamp vary - let updateSystemData = false; - - let updated = parseInt(data.updated.updated); let newPosX = data.position.x + 'px'; let newPosY = data.position.y + 'px'; if(!system){ - updateSystemData = true; - // set system name or alias let systemName = data.name; @@ -493,32 +485,32 @@ define([ $('
', { class: config.systemHeadClass }).append( - // System name is editable - $('', { - href: '#', - class: config.systemHeadNameClass - }).attr('data-value', systemName) - ).append( - // System locked status - $('', { - class: ['fa', 'fa-lock', 'fa-fw'].join(' ') - }).attr('title', 'locked') - ).append( - // System effect color - $('', { - class: ['fa', 'fa-square ', 'fa-fw', effectBasicClass, effectClass].join(' ') - }).attr('title', effectName) - ).append( - // expand option - $('', { - class: ['fa', 'fa-angle-down ', config.systemHeadExpandClass].join(' ') - }) - ).prepend( - $('', { - class: [config.systemSec, secClass].join(' '), - text: data.security - }) - ) + // System name is editable + $('', { + href: '#', + class: config.systemHeadNameClass + }).attr('data-value', systemName) + ).append( + // System locked status + $('', { + class: ['fa', 'fa-lock', 'fa-fw'].join(' ') + }).attr('title', 'locked') + ).append( + // System effect color + $('', { + class: ['fa', 'fa-square ', 'fa-fw', effectBasicClass, effectClass].join(' ') + }).attr('title', effectName) + ).append( + // expand option + $('', { + class: ['fa', 'fa-angle-down ', config.systemHeadExpandClass].join(' ') + }) + ).prepend( + $('', { + class: [config.systemSec, secClass].join(' '), + text: data.security + }) + ) ).append( // system body $('
', { @@ -528,94 +520,88 @@ define([ // set initial system position system.css({ - 'left': newPosX, - 'top': newPosY + 'left': newPosX, + 'top': newPosY }); }else{ system = $(system); - if( system.data('updated') !== updated){ - // system Data has changed - updateSystemData = true; + // set system position + let currentPosX = system.css('left'); + let currentPosY = system.css('top'); - // set system position - let currentPosX = system.css('left'); - let currentPosY = system.css('top'); + if( + newPosX !== currentPosX || + newPosY !== currentPosY + ){ + // change position with animation + system.velocity( + { + left: newPosX, + top: newPosY + },{ + easing: 'linear', + duration: Init.animationSpeed.mapMoveSystem, + begin: function(system){ + // hide system tooltip + $(system).toggleSystemTooltip('hide', {}); - if( - newPosX !== currentPosX || - newPosY !== currentPosY - ){ - // change position with animation - system.velocity( - { - left: newPosX, - top: newPosY - },{ - easing: 'linear', - duration: Init.animationSpeed.mapMoveSystem, - begin: function(system){ - // hide system tooltip - $(system).toggleSystemTooltip('hide', {}); + // move them to the "top" + $(system).updateSystemZIndex(); + }, + progress: function(){ + map.revalidate( systemId ); + }, + complete: function(system){ + // show tooltip + $(system).toggleSystemTooltip('show', {show: true}); - // move them to the "top" - $(system).updateSystemZIndex(); - }, - progress: function(){ - map.revalidate( systemId ); - }, - complete: function(system){ - // show tooltip - $(system).toggleSystemTooltip('show', {show: true}); - - map.revalidate( systemId ); - } + map.revalidate( systemId ); } - ); - } + } + ); + } - // set system alias - let alias = system.getSystemInfo(['alias']); + // set system alias + let alias = system.getSystemInfo(['alias']); - if(alias !== data.alias){ - // alias changed - system.find('.' + config.systemHeadNameClass).editable('setValue', data.alias); - } + if(alias !== data.alias){ + // alias changed + system.find('.' + config.systemHeadNameClass).editable('setValue', data.alias); } } - if(updateSystemData){ - // set system status - system.setSystemStatus(data.status.name); - system.data('id', parseInt(data.id)); - system.data('systemId', parseInt(data.systemId)); - system.data('name', data.name); - system.data('typeId', parseInt(data.type.id)); - system.data('effect', data.effect); - system.data('security', data.security); - system.data('trueSec', parseFloat(data.trueSec)); - system.data('regionId', parseInt(data.region.id)); - system.data('region', data.region.name); - system.data('constellationId', parseInt(data.constellation.id)); - system.data('constellation', data.constellation.name); - system.data('statics', data.statics); - system.data('updated', parseInt(data.updated.updated)); - system.attr('data-mapid', parseInt(mapContainer.data('id'))); + // set system status + system.setSystemStatus(data.status.name); + system.data('id', parseInt(data.id)); + system.data('systemId', parseInt(data.systemId)); + system.data('name', data.name); + system.data('typeId', parseInt(data.type.id)); + system.data('effect', data.effect); + system.data('security', data.security); + system.data('trueSec', parseFloat(data.trueSec)); + system.data('regionId', parseInt(data.region.id)); + system.data('region', data.region.name); + system.data('constellationId', parseInt(data.constellation.id)); + system.data('constellation', data.constellation.name); + system.data('statics', data.statics); + system.data('updated', parseInt(data.updated.updated)); + system.data('changed', false); + system.attr('data-mapid', parseInt(mapContainer.data('id'))); - // locked system - if( Boolean( system.data( 'locked') ) !== data.locked ){ - system.toggleLockSystem(false, {hideNotification: true, hideCounter: true, map: map}); - } - - // rally system - system.setSystemRally(data.rallyUpdated, { - poke: data.rallyPoke || false, - hideNotification: true, - hideCounter: true, - }); + // locked system + if( Boolean( system.data( 'locked') ) !== data.locked ){ + system.toggleLockSystem(false, {hideNotification: true, hideCounter: true, map: map}); } + // rally system + system.setSystemRally(data.rallyUpdated, { + poke: data.rallyPoke || false, + hideNotification: true, + hideCounter: true, + }); + return system; }; @@ -753,8 +739,8 @@ define([ let mapId = mapContainer.data('id'); let connectionId = connectionData.id || 0; let connection; - let sourceSystem = $('#' + config.systemIdPrefix + mapId + '-' + connectionData.source); - let targetSystem = $('#' + config.systemIdPrefix + mapId + '-' + connectionData.target); + let sourceSystem = $('#' + MapUtil.getSystemId(mapId, connectionData.source) ); + let targetSystem = $('#' + MapUtil.getSystemId(mapId, connectionData.target) ); // check if both systems exists // (If not -> something went wrong e.g. DB-Foreign keys for "ON DELETE",...) @@ -789,6 +775,7 @@ define([ connection.setParameters({ connectionId: connectionId, updated: connectionData.updated, + created: connectionData.created, eolUpdated: connectionData.eolUpdated }); @@ -851,10 +838,10 @@ define([ // check if source or target has changed if(connectionData.source !== newConnectionData.source ){ - map.setSource(connection, config.systemIdPrefix + mapId + '-' + newConnectionData.source); + map.setSource(connection, MapUtil.getSystemId(mapId, newConnectionData.source) ); } if(connectionData.target !== newConnectionData.target ){ - map.setTarget(connection, config.systemIdPrefix + mapId + '-' + newConnectionData.target); + map.setTarget(connection, MapUtil.getSystemId(mapId, newConnectionData.target) ); } // connection.targetId @@ -888,53 +875,61 @@ define([ // set update date (important for update check) // important: set parameters ONE-by-ONE! // -> (setParameters() will overwrite all previous params) + connection.setParameter('created', newConnectionData.created); connection.setParameter('updated', newConnectionData.updated); connection.setParameter('eolUpdated', newConnectionData.eolUpdated); + connection.setParameter('changed', false); return connection; }; /** - * draw a new map or update an existing map with all its systems and connections + * get a mapMapElement * @param parentElement * @param mapConfig * @returns {*} */ - let updateMap = function(parentElement, mapConfig){ + let newMapElement = (parentElement, mapConfig) => { + let mapId = mapConfig.config.id; + // create map wrapper + let mapWrapper = $('
', { + class: config.mapWrapperClass + }); + + // create new map container + let mapContainer = $('
', { + id: config.mapIdPrefix + mapId, + class: [config.mapClass].join(' ') + }); + + // add additional information + mapContainer.data('id', mapId); + + mapWrapper.append(mapContainer); + + // append mapWrapper to parent element (at the top) + $(parentElement).prepend(mapWrapper); + + // set main Container for current map -> the container exists now in DOM !! very important + mapConfig.map.setContainer( config.mapIdPrefix + mapId ); + + // set map observer + setMapObserver(mapConfig.map); + + return mapConfig; + }; + + /** + * draw a new map or update an existing map with all its systems and connections + * @param mapConfig + * @returns {*} + */ + let updateMap = function(mapConfig){ let mapContainer = mapConfig.map.getContainer(); - + let mapId = mapConfig.config.id; let newSystems = 0; - if(mapContainer === undefined){ - // add new map - - // create map wrapper - let mapWrapper = $('
', { - class: config.mapWrapperClass - }); - - // create new map container - mapContainer = $('
', { - id: config.mapIdPrefix + mapConfig.config.id, - class: [config.mapClass].join(' ') - }); - - // add additional information - mapContainer.data('id', mapConfig.config.id); - - mapWrapper.append(mapContainer); - - // append mapWrapper to parent element (at the top) - $(parentElement).prepend(mapWrapper); - - // set main Container for current map -> the container exists now in DOM !! very important - mapConfig.map.setContainer( config.mapIdPrefix + mapConfig.config.id ); - - // set map observer - setMapObserver(mapConfig.map); - } - mapContainer = $(mapContainer); // add additional information for this map @@ -948,7 +943,6 @@ define([ mapContainer.data('updated', mapConfig.config.updated); } - // get map data let mapData = mapContainer.getMapDataFromClient({forceData: false}); @@ -998,7 +992,7 @@ define([ } if(deleteThisSystem === true){ - let deleteSystem = $('#' + config.systemIdPrefix + mapContainer.data('id') + '-' + currentSystemData[a].id); + let deleteSystem = $('#' + MapUtil.getSystemId(mapContainer.data('id'), currentSystemData[a].id) ); // system not found -> delete system System.removeSystems(mapConfig.map, deleteSystem); @@ -1080,6 +1074,11 @@ define([ if(newSystems > 0){ MagnetizerWrapper.setElements(mapConfig.map); } + }else{ + // map is currently logged -> queue update for this map until unlock + if( mapUpdateQueue.indexOf(mapId) === -1 ){ + mapUpdateQueue.push(mapId); + } } return mapContainer; @@ -1369,6 +1368,205 @@ define([ } }; + /** + * save a new system and add it to the map + * @param map + * @param requestData + * @param sourceSystem + * @param callback + */ + let saveSystem = function(map, requestData, sourceSystem, callback){ + $.ajax({ + type: 'POST', + url: Init.path.saveSystem, + data: requestData, + dataType: 'json', + context: { + map: map, + sourceSystem: sourceSystem + } + }).done(function(newSystemData){ + Util.showNotify({title: 'New system', text: newSystemData.name, type: 'success'}); + + // draw new system to map + drawSystem(this.map, newSystemData, this.sourceSystem); + + // re/arrange systems (prevent overlapping) + MagnetizerWrapper.setElements(this.map); + + if(callback){ + callback(); + } + }).fail(function( jqXHR, status, error) { + let reason = status + ' ' + error; + Util.showNotify({title: jqXHR.status + ': saveSystem', text: reason, type: 'warning'}); + $(document).setProgramStatus('problem'); + }); + }; + + /** + * open "new system" dialog and add the system to map + * optional the new system is connected to a "sourceSystem" (if available) + * + * @param map + * @param options + */ + let showNewSystemDialog = function(map, options){ + let mapContainer = $(map.getContainer()); + + // format system status for form select ------------------------------------------------------------- + let systemStatus = {}; + // "default" selection (id = 0) prevents status from being overwritten + // -> e.g. keep status information if system was just inactive (active = 0) + systemStatus[0] = 'default'; + + $.each(Init.systemStatus, function(status, statusData){ + systemStatus[statusData.id] = statusData.label; + }); + + // default system status -> first status entry + let defaultSystemStatus = 0; + + // get current map data ----------------------------------------------------------------------------- + let mapData = mapContainer.getMapDataFromClient({forceData: true}); + let mapSystems = mapData.data.systems; + let mapSystemCount = mapSystems.length; + let mapTypeName = mapContainer.data('typeName'); + let maxAllowedSystems = Init.mapTypes[mapTypeName].defaultConfig.max_systems; + + // show error if system max count reached ----------------------------------------------------------- + if(mapSystemCount >= maxAllowedSystems){ + Util.showNotify({title: 'Max system count exceeded', text: 'Limit of ' + maxAllowedSystems + ' systems reached', type: 'warning'}); + return; + } + + // disable systems that are already on it ----------------------------------------------------------- + let mapSystemIds = []; + for(let i = 0; i < mapSystems.length; i++ ){ + mapSystemIds.push( mapSystems[i].systemId ); + } + + // dialog data -------------------------------------------------------------------------------------- + let data = { + id: config.systemDialogId, + selectClass: config.systemDialogSelectClass + }; + + // set current position as "default" system to add -------------------------------------------------- + let currentCharacterLog = Util.getCurrentCharacterLog(); + + if( + currentCharacterLog !== false && + mapSystemIds.indexOf( currentCharacterLog.system.id ) === -1 + ){ + // current system is NOT already on this map + // set current position as "default" system to add + data.currentSystem = currentCharacterLog.system; + } + + requirejs(['text!templates/dialog/system.html', 'mustache'], function(template, Mustache) { + + let content = Mustache.render(template, data); + + let systemDialog = bootbox.dialog({ + title: 'Add new system', + message: content, + buttons: { + close: { + label: 'cancel', + className: 'btn-default' + }, + success: { + label: ' save', + className: 'btn-success', + callback: function (e) { + // get form Values + let form = $('#' + config.systemDialogId).find('form'); + + let systemDialogData = $(form).getFormValues(); + + // validate form + form.validator('validate'); + + // check whether the form is valid + let formValid = form.isValidForm(); + + if(formValid === false){ + // don't close dialog + return false; + } + + // calculate new system position ------------------------------------------------ + let newPosition = { + x: 0, + y: 0 + }; + + let sourceSystem = null; + + // add new position + if(options.sourceSystem !== undefined){ + + sourceSystem = options.sourceSystem; + + // get new position + newPosition = System.calculateNewSystemPosition(sourceSystem); + }else{ + // check mouse cursor position (add system to map) + newPosition = { + x: options.position.x, + y: options.position.y + }; + } + + systemDialogData.position = newPosition; + + // ------------------------------------------------------------------------------ + + let requestData = { + systemData: systemDialogData, + mapData: { + id: mapContainer.data('id') + } + }; + + saveSystem(map, requestData, sourceSystem, function(){ + bootbox.hideAll(); + }); + return false; + } + } + } + }); + + // init dialog + systemDialog.on('shown.bs.modal', function(e) { + + let modalContent = $('#' + config.systemDialogId); + + // init system select live search - some delay until modal transition has finished + let selectElement = modalContent.find('.' + config.systemDialogSelectClass); + selectElement.delay(240).initSystemSelect({ + key: 'systemId', + disabledOptions: mapSystemIds + }); + }); + + // init system status select + let modalFields = $('.bootbox .modal-dialog').find('.pf-editable-system-status'); + + modalFields.editable({ + mode: 'inline', + emptytext: 'unknown', + onblur: 'submit', + showbuttons: false, + source: systemStatus, + value: defaultSystemStatus, + inputclass: config.systemDialogSelectClass + }); + }); + }; + /** * make a system name/alias editable by x-editable * @param system @@ -1423,7 +1621,6 @@ define([ * @returns {{id: Number, source: Number, sourceName: (*|T|JQuery|{}), target: Number, targetName: (*|T|JQuery), scope: *, type: *, updated: Number}} */ let getDataByConnection = function(connection){ - let source = $(connection.source); let target = $(connection.target); @@ -1607,7 +1804,6 @@ define([ * load context menu template for map */ let initMapContextMenu = function(){ - let moduleConfig = { name: 'modules/contextmenu', position: $('#' + config.dynamicElementWrapperId) @@ -1636,7 +1832,6 @@ define([ * load contextmenu template for connections */ let initConnectionContextMenu = function(){ - let moduleConfig = { name: 'modules/contextmenu', position: $('#' + config.dynamicElementWrapperId) @@ -1674,8 +1869,8 @@ define([ * load contextmenu template for systems */ let initSystemContextMenu = function(){ - let systemStatus = []; + $.each(Init.systemStatus, function(status, statusData){ let tempStatus = { subIcon: 'fa-tag', @@ -1719,7 +1914,6 @@ define([ * @returns {Array} */ let getHiddenContextMenuOptions = function(component){ - let hiddenOptions = []; if(component instanceof jsPlumb.Connection){ @@ -1758,7 +1952,6 @@ define([ * @returns {Array} */ let getActiveContextMenuOptions = function(component){ - let activeOptions = []; if(component instanceof jsPlumb.Connection){ @@ -1808,169 +2001,6 @@ define([ return activeOptions; }; - /** - * open "new system" dialog and add the system to map - * optional the new system is connected to a "sourceSystem" (if available) - * - * @param map - * @param options - */ - let showNewSystemDialog = function(map, options){ - let mapContainer = $(map.getContainer()); - - // format system status for form select ------------------------------------------------------------- - let systemStatus = {}; - // "default" selection (id = 0) prevents status from being overwritten - // -> e.g. keep status information if system was just inactive (active = 0) - systemStatus[0] = 'default'; - - $.each(Init.systemStatus, function(status, statusData){ - systemStatus[statusData.id] = statusData.label; - }); - - // default system status -> first status entry - let defaultSystemStatus = 0; - - // get current map data ----------------------------------------------------------------------------- - let mapData = mapContainer.getMapDataFromClient({forceData: true}); - let mapSystems = mapData.data.systems; - let mapSystemCount = mapSystems.length; - let mapTypeName = mapContainer.data('typeName'); - let maxAllowedSystems = Init.mapTypes[mapTypeName].defaultConfig.max_systems; - - // show error if system max count reached ----------------------------------------------------------- - if(mapSystemCount >= maxAllowedSystems){ - Util.showNotify({title: 'Max system count exceeded', text: 'Limit of ' + maxAllowedSystems + ' systems reached', type: 'warning'}); - return; - } - - // disable systems that are already on it ----------------------------------------------------------- - let mapSystemIds = []; - for(let i = 0; i < mapSystems.length; i++ ){ - mapSystemIds.push( mapSystems[i].systemId ); - } - - // dialog data -------------------------------------------------------------------------------------- - let data = { - id: config.systemDialogId, - selectClass: config.systemDialogSelectClass - }; - - // set current position as "default" system to add -------------------------------------------------- - let currentCharacterLog = Util.getCurrentCharacterLog(); - - if( - currentCharacterLog !== false && - mapSystemIds.indexOf( currentCharacterLog.system.id ) === -1 - ){ - // current system is NOT already on this map - // set current position as "default" system to add - data.currentSystem = currentCharacterLog.system; - } - - requirejs(['text!templates/dialog/system.html', 'mustache'], function(template, Mustache) { - - let content = Mustache.render(template, data); - - let systemDialog = bootbox.dialog({ - title: 'Add new system', - message: content, - buttons: { - close: { - label: 'cancel', - className: 'btn-default' - }, - success: { - label: ' save', - className: 'btn-success', - callback: function (e) { - // get form Values - let form = $('#' + config.systemDialogId).find('form'); - - let systemDialogData = $(form).getFormValues(); - - // validate form - form.validator('validate'); - - // check whether the form is valid - let formValid = form.isValidForm(); - - if(formValid === false){ - // don't close dialog - return false; - } - - // calculate new system position ------------------------------------------------ - let newPosition = { - x: 0, - y: 0 - }; - - let sourceSystem = null; - - // add new position - if(options.sourceSystem !== undefined){ - - sourceSystem = options.sourceSystem; - - // get new position - newPosition = calculateNewSystemPosition(sourceSystem); - }else{ - // check mouse cursor position (add system to map) - newPosition = { - x: options.position.x, - y: options.position.y - }; - } - - systemDialogData.position = newPosition; - - // ------------------------------------------------------------------------------ - - let requestData = { - systemData: systemDialogData, - mapData: { - id: mapContainer.data('id') - } - }; - - saveSystem(map, requestData, sourceSystem, function(){ - bootbox.hideAll(); - }); - return false; - } - } - } - }); - - // init dialog - systemDialog.on('shown.bs.modal', function(e) { - - let modalContent = $('#' + config.systemDialogId); - - // init system select live search - some delay until modal transition has finished - let selectElement = modalContent.find('.' + config.systemDialogSelectClass); - selectElement.delay(240).initSystemSelect({ - key: 'systemId', - disabledOptions: mapSystemIds - }); - }); - - // init system status select - let modalFields = $('.bootbox .modal-dialog').find('.pf-editable-system-status'); - - modalFields.editable({ - mode: 'inline', - emptytext: 'unknown', - onblur: 'submit', - showbuttons: false, - source: systemStatus, - value: defaultSystemStatus, - inputclass: config.systemDialogSelectClass - }); - }); - }; - /** * set up all actions that can be preformed on a system * @param map @@ -2304,10 +2334,10 @@ define([ if( element.hasClass(config.systemClass) ){ // system element - element.data('updated', 0); + element.data('changed', true); }else{ // connection element - this.setParameter('updated', 0); + this.setParameter('changed', true); } }); }; @@ -2322,10 +2352,10 @@ define([ if( element.hasClass(config.systemClass) ){ // system element - changed = (element.data('updated') === 0); + changed = element.data('changed') || false; }else{ // connection element - changed = (this[0].getParameter('updated') === 0); + changed = this[0].getParameter('changed') || false; } return changed; @@ -2356,6 +2386,28 @@ define([ $(tabContentElement).trigger('pf:drawSystemModules'); }; + /** + * select all (selectable) systems on a mapElement + */ + $.fn.selectAllSystems = function(){ + return this.each(function(){ + let mapElement = $(this); + let map = getMapInstance(mapElement.data('id')); + + let allSystems = mapElement.find('.' + config.systemClass + ':not(.' + config.systemSelectedClass + ')'); + + // filter non-locked systems + allSystems = allSystems.filter(function(i, el){ + return ( $(el).data('locked') !== true ); + }); + + allSystems.toggleSelectSystem(map); + + Util.showNotify({title: allSystems.length + ' systems selected', type: 'success'}); + + }); + }; + /** * toggle selectable status of a system */ @@ -2378,15 +2430,6 @@ define([ }); }; - /** - * get all selected (NOT active) systems in a map - * @returns {*} - */ - $.fn.getSelectedSystems = function(){ - let mapElement = $(this); - return mapElement.find('.' + config.systemSelectedClass); - }; - /** * toggle log status of a system * @param poke @@ -2486,11 +2529,14 @@ define([ // event after DragStop a connection or new connection ------------------------------------------ newJsPlumbInstance.bind('beforeDrop', function(info) { let connection = info.connection; + let dropEndpoint = info.dropEndpoint; + let sourceId = info.sourceId; + let targetId = info.targetId; // lock the target system for "click" events // to prevent loading system information - let sourceSystem = $('#' + info.sourceId); - let targetSystem = $('#' + info.targetId); + let sourceSystem = $('#' + sourceId); + let targetSystem = $('#' + targetId); sourceSystem.addClass('no-click'); targetSystem.addClass('no-click'); setTimeout(function(){ @@ -2498,14 +2544,25 @@ define([ targetSystem.removeClass('no-click'); }, Init.timer.DBL_CLICK + 50); + // loop connection not allowed + if(sourceId === targetId){ + console.warn('Source/Target systems are identical'); + return false; + } + + // connection can not be dropped on an endpoint that already has other connections on it + if(dropEndpoint.connections.length > 0){ + console.warn('Endpoint already occupied'); + return false; + } + // set "default" connection status only for NEW connections if(!connection.suspendedElement){ MapUtil.setConnectionWHStatus(connection, MapUtil.getDefaultConnectionTypeByScope(connection.scope) ); } // prevent multiple connections between same systems - let connections = MapUtil.checkForConnection(newJsPlumbInstance, info.sourceId, info.targetId ); - + let connections = MapUtil.checkForConnection(newJsPlumbInstance, sourceId, targetId); if(connections.length > 1){ bootbox.confirm('Connection already exists. Do you really want to add an additional one?', function(result) { if(!result){ @@ -2520,7 +2577,12 @@ define([ return true; }); - // event before Detach connection --------------------------------------------------------------- + // event before detach (existing connection) ---------------------------------------------------- + newJsPlumbInstance.bind('beforeStartDetach', function(info) { + return true; + }); + + // event before detach connection --------------------------------------------------------------- newJsPlumbInstance.bind('beforeDetach', function(info) { return true; }); @@ -2532,10 +2594,12 @@ define([ }); newJsPlumbInstance.bind('checkDropAllowed', function(params){ - // connections can not be attached to foreign endpoints - // the only endpoint available is endpoint from where the connection was dragged away (re-attach) + let sourceEndpoint = params.sourceEndpoint; + let targetEndpoint = params.targetEndpoint; - return true; + // connections can not be attached to foreign endpoints + // the only endpoint available is the endpoint from where the connection was dragged away (re-attach) + return (targetEndpoint.connections.length === 0); }); activeInstances[mapId] = newJsPlumbInstance; @@ -2549,11 +2613,10 @@ define([ * @param map */ let setMapObserver = function(map){ - // get map container - let mapContainer = map.getContainer(); + let mapContainer = $( map.getContainer() ); - $(mapContainer).bind('contextmenu', function(e){ + mapContainer.bind('contextmenu', function(e){ e.preventDefault(); e.stopPropagation(); @@ -2571,7 +2634,7 @@ define([ return false; }); - $(mapContainer).contextMenu({ + mapContainer.contextMenu({ menuSelector: '#' + config.mapContextMenuId, menuSelected: function (params) { @@ -2584,7 +2647,7 @@ define([ let currentMapId = parseInt( currentMapElement.data('id') ); // get map instance - let currentMap = getMapInstance(currentMapId); + let currentMap = getMapInstance(currentMapId); // click position let position = params.position; @@ -2595,17 +2658,7 @@ define([ showNewSystemDialog(currentMap, {position: position}); break; case 'select_all': - - let allSystems = currentMapElement.find('.' + config.systemClass + ':not(.' + config.systemSelectedClass + ')'); - - // filter non-locked systems - allSystems = allSystems.filter(function(i, el){ - return ( $(el).data('locked') !== true ); - }); - - allSystems.toggleSelectSystem(currentMap); - - Util.showNotify({title: allSystems.length + ' systems selected', type: 'success'}); + currentMapElement.selectAllSystems(); break; case 'filter_wh': case 'filter_stargate': @@ -2674,11 +2727,11 @@ define([ }); // init drag-frame selection - $(mapContainer).dragToSelect({ + mapContainer.dragToSelect({ selectOnMove: true, selectables: '.' + config.systemClass, onHide: function (selectBox, deselectedSystems) { - let selectedSystems = $(mapContainer).getSelectedSystems(); + let selectedSystems = mapContainer.getSelectedSystems(); if(selectedSystems.length > 0){ // make all selected systems draggable @@ -2702,10 +2755,10 @@ define([ } }); - // catch events ========================================================= + // catch events ===================================================================================== // toggle global map option (e.g. "grid snap", "magnetization") - $(mapContainer).on('pf:menuMapOption', function(e, mapOption){ + mapContainer.on('pf:menuMapOption', function(e, mapOption){ let mapElement = $(this); // get map menu config options @@ -2780,13 +2833,14 @@ define([ // delete system event // triggered from "map info" dialog scope - $(mapContainer).on('pf:deleteSystems', function(e, data){ + mapContainer.on('pf:deleteSystems', function(e, data){ System.deleteSystems(map, data.systems, data.callback); }); - $(mapContainer).on('pf:menuSelectSystem', function(e, data){ + // triggered from "header" link (if user is active in one of the systems) + mapContainer.on('pf:menuSelectSystem', function(e, data){ let tempMapContainer = $(this); - let systemId = config.systemIdPrefix + tempMapContainer.data('id') + '-' + data.systemId; + let systemId = MapUtil.getSystemId(tempMapContainer.data('id'), data.systemId); let system = $(this).find('#' + systemId); if(system.length === 1){ @@ -2798,6 +2852,27 @@ define([ system.showSystemInfo(map); } }); + + // triggered when map lock timer (interval) was cleared + mapContainer.on('pf:unlocked', function(){ + let mapElement = $(this); + let mapId = mapElement.data('id'); + + // check if there was a mapUpdate during map was locked + let mapQueueIndex = mapUpdateQueue.indexOf(mapId); + if(mapQueueIndex !== -1){ + // get current mapConfig + let mapConfig = Util.getCurrentMapData(mapId); + + if(mapConfig){ + // map data is available => update map + updateMap(mapConfig); + } + + // update done -> clear mapId from mapUpdateQueue + mapUpdateQueue.splice(mapQueueIndex, 1); + } + }); }; /** @@ -2850,65 +2925,6 @@ define([ } }; - /** - * save a new system and add it to the map - * @param map - * @param requestData - * @param sourceSystem - * @param callback - */ - let saveSystem = function(map, requestData, sourceSystem, callback){ - $.ajax({ - type: 'POST', - url: Init.path.saveSystem, - data: requestData, - dataType: 'json', - context: { - map: map, - sourceSystem: sourceSystem - } - }).done(function(newSystemData){ - Util.showNotify({title: 'New system', text: newSystemData.name, type: 'success'}); - - // draw new system to map - drawSystem(this.map, newSystemData, this.sourceSystem); - - // re/arrange systems (prevent overlapping) - MagnetizerWrapper.setElements(this.map); - - if(callback){ - callback(); - } - }).fail(function( jqXHR, status, error) { - let reason = status + ' ' + error; - Util.showNotify({title: jqXHR.status + ': saveSystem', text: reason, type: 'warning'}); - $(document).setProgramStatus('problem'); - }); - }; - - /** - * calculate the x/y coordinates for a new system - relativ to a source system - * @param sourceSystem - * @returns {{x: *, y: *}} - */ - let calculateNewSystemPosition = function(sourceSystem){ - - // related system is available - let currentX = sourceSystem.css('left'); - let currentY = sourceSystem.css('top'); - - // remove "px" - currentX = parseInt( currentX.substring(0, currentX.length - 2) ); - currentY = parseInt( currentY.substring(0, currentY.length - 2) ); - - let newPosition = { - x: currentX + config.newSystemOffset.x, - y: currentY + config.newSystemOffset.y - }; - - return newPosition; - }; - /** * updates all systems on map with current user Data (all users on this map) * update the Data of the user that is currently viewing the map (if available) @@ -3020,16 +3036,11 @@ define([ */ $.fn.getMapDataFromClient = function(options){ let mapElement = $(this); - let map = getMapInstance( mapElement.data('id') ); - let mapData = {}; - // check if there is an active map counter that prevents collecting map data - let overlay = mapElement.getMapOverlay('timer'); - let counterChart = overlay.getMapCounter(); - - let interval = counterChart.data('interval'); + // check if there is an active map counter that prevents collecting map data (locked map) + let interval = mapElement.getMapOverlayInterval(); if( ! interval || @@ -3188,7 +3199,6 @@ define([ * @param options */ $.fn.loadMap = function(mapConfig, options){ - // parent element where the map will be loaded let parentElement = $(this); @@ -3197,9 +3207,6 @@ define([ initConnectionContextMenu(); initSystemContextMenu(); - // new map init - let newMap = false; - // init jsPlumb jsPlumb.ready(function() { // get new map instance or load existing @@ -3208,24 +3215,26 @@ define([ // check for map Container -> first time initialization if(mapConfig.map.getContainer() === undefined){ // new map instance - newMap = true; - } + mapConfig = newMapElement(parentElement, mapConfig); - // draw/update map initial map and set container - let mapContainer = updateMap(parentElement, mapConfig); - - if(newMap){ // init custom scrollbars and add overlay parentElement.initMapScrollbar(); - // show static overlay actions - let mapElement = mapConfig.map.getContainer(); - let mapOverlay = $(mapElement).getMapOverlay('info'); - mapOverlay.updateOverlayIcon('systemRegion', 'show'); + let mapElement = $(mapConfig.map.getContainer()); - mapOverlay.updateOverlayIcon('systemConnectionTimer', 'show'); + // set shortcuts + parentElement.find('.' + config.mapWrapperClass).setMapShortcuts(); + + // show static overlay actions + let mapOverlay = mapElement.getMapOverlay('info'); + mapOverlay.updateOverlayIcon('systemRegion', 'show'); + mapOverlay.updateOverlayIcon('connection', 'show'); + mapOverlay.updateOverlayIcon('connectionEol', 'show'); } + // draw/update map initial map and set container + let mapContainer = updateMap(mapConfig); + // callback function after tab switch function switchTabCallback( mapName, mapContainer ){ Util.showNotify({title: 'Map initialized', text: mapName + ' - loaded', type: 'success'}); @@ -3257,6 +3266,12 @@ define([ toggle: false }); + // init endpoint overlay -------------------------------------------------------------------- + mapContainer.triggerMenuEvent('MapOption', { + option: 'mapEndpoint', + toggle: false + }); + return false; } @@ -3309,8 +3324,8 @@ define([ return { getMapInstance: getMapInstance, clearMapInstance: clearMapInstance, - - getDataByConnection: getDataByConnection + getDataByConnection: getDataByConnection, + showNewSystemDialog: showNewSystemDialog }; }); \ No newline at end of file diff --git a/js/app/map/overlay.js b/js/app/map/overlay.js index 49ec6d93..214d4e12 100644 --- a/js/app/map/overlay.js +++ b/js/app/map/overlay.js @@ -7,26 +7,37 @@ define([ 'app/init', 'app/util' ], function($, Init, Util) { - 'use strict'; let config = { - logTimerCount: 3, // map log timer in seconds + logTimerCount: 3, // map log timer in seconds // map - mapClass: 'pf-map', // class for all maps - mapWrapperClass: 'pf-map-wrapper', // wrapper div (scrollable) + mapClass: 'pf-map', // class for all maps + mapWrapperClass: 'pf-map-wrapper', // wrapper div (scrollable) + + // map overlay positions + mapOverlayClass: 'pf-map-overlay', // class for all map overlays + mapOverlayTimerClass: 'pf-map-overlay-timer', // class for map overlay timer e.g. map timer + mapOverlayInfoClass: 'pf-map-overlay-info', // class for map overlay info e.g. map info + + // connection overlays - // map overlays - mapOverlayClass: 'pf-map-overlay', // class for all map overlays - mapOverlayTimerClass: 'pf-map-overlay-timer', // class for map overlay timer e.g. map timer - mapOverlayInfoClass: 'pf-map-overlay-info', // class for map overlay info e.g. map info // system - systemHeadClass: 'pf-system-head', // class for system head + systemHeadClass: 'pf-system-head', // class for system head - // connection - connectionOverlayEolId: 'overlayEol' // connection overlay ID (jsPlumb) + // overlay IDs + connectionOverlayId: 'pf-map-connection-overlay', // connection "normal size" ID (jsPlumb) + connectionOverlayEolId: 'pf-map-connection-eol-overlay', // connection EOL overlay ID (jsPlumb) + connectionOverlayArrowId: 'pf-map-connection-arrow-overlay', // connection Arrows overlay ID (jsPlumb) + connectionOverlaySmallId: 'pf-map-connection-small-overlay', // connection "smaller" overlay ID (jsPlumb) + + // overlay classes + connectionOverlayClass: 'pf-map-connection-overlay', // class for "normal size" overlay + connectionArrowOverlayClass: 'pf-map-connection-arrow-overlay', // class for "connection arrow" overlay + connectionDiamondOverlayClass: 'pf-map-connection-diamond-overlay', // class for "connection diamond" overlay + connectionOverlaySmallClass: 'pf-map-connection-small-overlay' // class for "smaller" overlays }; @@ -35,10 +46,308 @@ define([ * @param mapOverlay * @returns {JQuery} */ - let getMapFromOverlay = function(mapOverlay){ + let getMapElementFromOverlay = (mapOverlay) => { return $(mapOverlay).parents('.' + config.mapWrapperClass).find('.' + config.mapClass); }; + /** + * get MapObject (jsPlumb) from mapElement + * @param mapElement + * @returns {*} + */ + let getMapObjectFromMapElement = (mapElement) => { + let Map = require('app/map/map'); + return Map.getMapInstance( mapElement.data('id') ); + }; + + /** + * get map object (jsPlumb) from iconElement + * @param overlayIcon + * @returns {*} + */ + let getMapObjectFromOverlayIcon = (overlayIcon) => { + let mapElement = getMapElementFromOverlay(overlayIcon); + + return getMapObjectFromMapElement( mapElement ); + }; + + /** + * add overlays to connections (signature based data) + * @param connections + * @param connectionsData + */ + let addConnectionsOverlay = (connections, connectionsData) => { + let SystemSignatures = require('app/ui/system_signature'); + + /** + * add label to endpoint + * @param endpoint + * @param label + */ + let addEndpointOverlay = (endpoint, label) => { + let newLabel = ''; + let colorClass = 'txt-color-grayLighter'; + + if(label.length > 0){ + newLabel = label; + + // check if multiple labels found => conflict + if( label.includes(', ') ){ + colorClass = 'txt-color-orangeLight'; + }else if( !label.includes('K162') ){ + colorClass = 'txt-color-yellow'; + } + }else{ + // endpoint not connected with a signature + newLabel = ''; + colorClass = 'txt-color-red'; + } + + endpoint.addOverlay([ + 'Label', + { + label: '' + newLabel + '', + id: config.connectionOverlaySmallId, + cssClass: config.connectionOverlaySmallClass, + location: [ 0.5, 0.5 ] + } + ]); + + }; + + // loop through all map connections (get from DOM) + for(let connection of connections) { + let connectionId = connection.getParameter('connectionId'); + let sourceEndpoint = connection.endpoints[0]; + let targetEndpoint = connection.endpoints[1]; + let sourceSystem = $(sourceEndpoint.element); + let targetSystem = $(targetEndpoint.element); + let sourceId = sourceSystem.data('id'); + let targetId = targetSystem.data('id'); + + let signatureTypeNames = { + sourceLabels: [], + targetLabels: [] + }; + + // ... find matching connectionData (from Ajax) + for(let connectionData of connectionsData){ + if( + connectionData.id === connectionId && + connectionData.signatures // signature data is required... + ){ + + // ... collect overlay/label data from signatures + for(let signatureData of connectionData.signatures){ + // ... typeId is required to get a valid name + if(signatureData.typeId > 0){ + + // whether "source" or "target" system is relevant for current connection and current signature... + let tmpSystem = null; + let tmpSystemType = null; + + if(signatureData.system.id === sourceId){ + // relates to "source" endpoint + tmpSystemType = 'sourceLabels'; + tmpSystem = sourceSystem; + }else if(signatureData.system.id === targetId){ + // relates to "target" endpoint + tmpSystemType = 'targetLabels'; + tmpSystem = targetSystem; + } + + // ... get endpoint label for source || target system + if(tmpSystem && tmpSystem){ + // ... get all available signature type (wormholes) names + let availableSigTypeNames = SystemSignatures.getAllSignatureNamesBySystem(tmpSystem, 5); + let flattenSigTypeNames = Util.flattenXEditableSelectArray(availableSigTypeNames); + + if( flattenSigTypeNames.hasOwnProperty(signatureData.typeId) ){ + let label = flattenSigTypeNames[signatureData.typeId]; + // shorten label, just take the in game name + label = label.substr(0, label.indexOf(' ')); + signatureTypeNames[tmpSystemType].push(label); + } + } + } + } + + // ... connection matched -> continue with next one + break; + } + } + + let sourceLabel = signatureTypeNames.sourceLabels.join(', '); + let targetLabel = signatureTypeNames.targetLabels.join(', '); + + // add endpoint overlays ------------------------------------------------------ + addEndpointOverlay(sourceEndpoint, sourceLabel); + addEndpointOverlay(targetEndpoint, targetLabel); + + // add arrow (connection) overlay that points from "XXX" => "K162" ------------ + let overlayType = 'Diamond'; // not specified + let arrowDirection = 1; + + if( + (sourceLabel.includes('K162') && targetLabel.includes('K162')) || + (sourceLabel.length === 0 && targetLabel.length === 0) || + ( + sourceLabel.length > 0 && targetLabel.length > 0 && + !sourceLabel.includes('K162') && !targetLabel.includes('K162') + ) + ){ + // unknown direction + overlayType = 'Diamond'; // not specified + arrowDirection = 1; + }else if( + (sourceLabel.includes('K162')) || + (sourceLabel.length === 0 && !targetLabel.includes('K162')) + ){ + // convert default arrow direction + overlayType = 'Arrow'; + arrowDirection = -1; + }else{ + // default arrow direction is fine + overlayType = 'Arrow'; + arrowDirection = 1; + } + + connection.addOverlay([ + overlayType, + { + width: 12, + length: 15, + location: 0.5, + foldback: 0.85, + direction: arrowDirection, + id: config.connectionOverlayArrowId, + cssClass: (overlayType === 'Arrow') ? config.connectionArrowOverlayClass : config.connectionDiamondOverlayClass + } + ]); + + } + }; + + /** + * remove overviews from a Tooltip + * @param endpoint + * @param i + */ + let removeEndpointOverlay = (endpoint, i) => { + endpoint.removeOverlays(config.connectionOverlaySmallId); + }; + + /** + * format json object with "time parts" into string + * @param parts + * @returns {string} + */ + let formatTimeParts = (parts) => { + let label = ''; + if(parts.days){ + label += parts.days + 'd '; + } + label += ('00' + parts.hours).slice(-2); + label += ':' + ('00' + parts.min).slice(-2); + return label; + }; + + /** + * hide default icon and replace it with "loading" icon + * @param iconElement + */ + let showLoading = (iconElement) => { + iconElement = $(iconElement); + let dataName = 'default-icon'; + let defaultIconClass = iconElement.data(dataName); + + // get default icon class + if( !defaultIconClass ){ + // index 0 == 'fa-fw', index 1 == IconName + defaultIconClass = $(iconElement).attr('class').match(/\bfa-\S*/g)[1]; + iconElement.data(dataName, defaultIconClass); + } + + iconElement.toggleClass( defaultIconClass + ' fa-refresh fa-spin' ); + }; + + /** + * hide "loading" icon and replace with default icon + * @param iconElement + */ + let hideLoading = (iconElement) => { + iconElement = $(iconElement); + let dataName = 'default-icon'; + let defaultIconClass = iconElement.data(dataName); + + iconElement.toggleClass( defaultIconClass + ' fa-refresh fa-spin' ); + }; + + /** + * git signature data that is linked to a connection for a mapId + * @param mapElement + * @param connections + * @param callback + */ + let getConnectionSignatureData = (mapElement, connections, callback) => { + let mapOverlay = $(mapElement).getMapOverlay('info'); + let overlayConnectionIcon = mapOverlay.find('.pf-map-overlay-endpoint'); + + showLoading(overlayConnectionIcon); + + let requestData = { + mapId: mapElement.data('id') + }; + + $.ajax({ + type: 'POST', + url: Init.path.getMapConnectionData, + data: requestData, + dataType: 'json', + context: { + mapElement: mapElement, + connections: connections, + overlayConnectionIcon: overlayConnectionIcon + } + }).done(function(connectionsData){ + // hide all connection before add them (refresh) + this.mapElement.hideEndpointOverlays(); + // ... add overlays + callback(this.connections, connectionsData); + }).always(function() { + hideLoading(this.overlayConnectionIcon); + }); + }; + + /** + * showEndpointOverlays + * -> used by "refresh" overlays (hover) AND/OR initial menu trigger + */ + $.fn.showEndpointOverlays = function(){ + let mapElement = $(this); + let map = getMapObjectFromMapElement(mapElement); + let MapUtil = require('app/map/util'); + let connections = MapUtil.searchConnectionsByScopeAndType(map, 'wh'); + + // get connection signature information --------------------------------------- + getConnectionSignatureData(mapElement, connections, addConnectionsOverlay); + }; + + /** + * hideEndpointOverlays + * -> see showEndpointOverlays() + */ + $.fn.hideEndpointOverlays = function(){ + let map = getMapObjectFromMapElement($(this)); + let MapUtil = require('app/map/util'); + let connections = MapUtil.searchConnectionsByScopeAndType(map, 'wh'); + + for (let connection of connections){ + connection.removeOverlays(config.connectionOverlayArrowId); + connection.endpoints.forEach(removeEndpointOverlay); + } + }; + /** * Overlay options (all available map options shown in overlay) * "active": (active || hover) indicated whether an icon/option @@ -72,7 +381,7 @@ define([ iconClass: ['fa', 'fa-fw', 'fa-tags'], hoverIntent: { over: function(e){ - let mapElement = getMapFromOverlay(this); + let mapElement = getMapElementFromOverlay(this); mapElement.find('.' + config.systemHeadClass).each(function(){ let system = $(this); // init tooltip if not already exists @@ -90,22 +399,87 @@ define([ }); }, out: function(e){ - let mapElement = getMapFromOverlay(this); + let mapElement = getMapElementFromOverlay(this); mapElement.find('.' + config.systemHeadClass).tooltip('hide'); } } }, - systemConnectionTimer: { - title: 'show EOL timer', + mapEndpoint: { + title: 'refresh signature overlays', + trigger: 'refresh', + class: 'pf-map-overlay-endpoint', + iconClass: ['fa', 'fa-fw', 'fa-link'], + hoverIntent: { + over: function(e){ + let mapElement = getMapElementFromOverlay(this); + mapElement.showEndpointOverlays(); + }, + out: function(e){ + // just "refresh" on hover + } + } + }, + connection: { + title: 'WH data', trigger: 'hover', - class: 'pf-map-overlay-connection-timer', + class: 'pf-map-overlay-connection', + iconClass: ['fa', 'fa-fw', 'fa-fighter-jet'], + hoverIntent: { + over: function(e){ + let map = getMapObjectFromOverlayIcon(this); + let MapUtil = require('app/map/util'); + let connections = MapUtil.searchConnectionsByScopeAndType(map, 'wh'); + let serverDate = Util.getServerTime(); + + // show connection overlays --------------------------------------------------- + for (let connection of connections) { + let createdTimestamp = connection.getParameter('created'); + let updatedTimestamp = connection.getParameter('updated'); + + let createdDate = Util.convertTimestampToServerTime(createdTimestamp); + let updatedDate = Util.convertTimestampToServerTime(updatedTimestamp); + + let createdDiff = Util.getTimeDiffParts(createdDate, serverDate); + let updatedDiff = Util.getTimeDiffParts(updatedDate, serverDate); + + // format overlay label + let labels = [ + ' ' + formatTimeParts(createdDiff), + ' ' + formatTimeParts(updatedDiff) + ]; + + // add label overlay ------------------------------------------------------ + connection.addOverlay([ + 'Label', + { + label: labels.join('
'), + id: config.connectionOverlayId, + cssClass: config.connectionOverlaySmallClass, + location: 0.35 + } + ]); + } + }, + out: function(e){ + let map = getMapObjectFromOverlayIcon(this); + let MapUtil = require('app/map/util'); + let connections = MapUtil.searchConnectionsByScopeAndType(map, 'wh'); + + for (let connection of connections){ + connection.removeOverlays(config.connectionOverlayId); + } + } + } + }, + connectionEol: { + title: 'EOL timer', + trigger: 'hover', + class: 'pf-map-overlay-connection-eol', iconClass: ['fa', 'fa-fw', 'fa-clock-o'], hoverIntent: { over: function(e){ - let mapElement = getMapFromOverlay(this); + let map = getMapObjectFromOverlayIcon(this); let MapUtil = require('app/map/util'); - let Map = require('app/map/map'); - let map = Map.getMapInstance( mapElement.data('id') ); let connections = MapUtil.searchConnectionsByScopeAndType(map, 'wh', ['wh_eol']); let serverDate = Util.getServerTime(); @@ -114,30 +488,20 @@ define([ let eolDate = Util.convertTimestampToServerTime(eolTimestamp); let diff = Util.getTimeDiffParts(eolDate, serverDate); - // format overlay label - let label = ''; - if(diff.days){ - label += diff.days + 'd '; - } - label += ('00' + diff.hours).slice(-2); - label += ':' + ('00' + diff.min).slice(-2); - connection.addOverlay([ 'Label', { - label: ' ' + label, + label: ' ' + formatTimeParts(diff), id: config.connectionOverlayEolId, - cssClass: ['pf-map-connection-overlay', 'eol'].join(' '), + cssClass: [config.connectionOverlayClass, 'eol'].join(' '), location: 0.25 } ]); } }, out: function(e){ - let mapElement = getMapFromOverlay(this); + let map = getMapObjectFromOverlayIcon(this); let MapUtil = require('app/map/util'); - let Map = require('app/map/map'); - let map = Map.getMapInstance( mapElement.data('id') ); let connections = MapUtil.searchConnectionsByScopeAndType(map, 'wh', ['wh_eol']); for (let connection of connections) { @@ -209,14 +573,15 @@ define([ }; /** - * get the map counter chart by an overlay - * @returns {*} + * get the map counter chart from overlay + * @returns {JQuery|*|T|{}|jQuery} */ $.fn.getMapCounter = function(){ + return $(this).find('.' + Init.classes.pieChart.pieChartMapCounterClass); + }; - let mapOverlayTimer = $(this); - - return mapOverlayTimer.find('.' + Init.classes.pieChart.pieChartMapCounterClass); + $.fn.getMapOverlayInterval = function(){ + return $(this).getMapOverlay('timer').getMapCounter().data('interval'); }; /** @@ -261,6 +626,7 @@ define([ duration: Init.animationSpeed.mapOverlay, complete: function(){ counterChart.data('interval', false); + getMapElementFromOverlay(mapOverlayTimer).trigger('pf:unlocked'); } }); } @@ -313,7 +679,10 @@ define([ showOverlay = true; // check "trigger" and mark as "active" - if(options[option].trigger === 'active'){ + if( + options[option].trigger === 'active' || + options[option].trigger === 'refresh' + ){ iconElement.addClass('active'); } @@ -324,7 +693,7 @@ define([ iconElement.velocity({ opacity: [0.8, 0], scale: [1, 0], - width: ['26px', 0], + width: ['30px', 0], marginLeft: ['3px', 0] },{ duration: 240, @@ -374,7 +743,7 @@ define([ }); parentElement.append(mapOverlayTimer); - // --------------------------------------------------------------------------- + // ------------------------------------------------------------------------------------ // add map overlay info. after scrollbar is initialized let mapOverlayInfo = $('
', { class: [config.mapOverlayClass, config.mapOverlayInfoClass].join(' ') @@ -392,7 +761,10 @@ define([ }); // add "hover" action for some icons - if(options[prop].trigger === 'hover'){ + if( + options[prop].trigger === 'hover' || + options[prop].trigger === 'refresh' + ){ icon.hoverIntent(options[prop].hoverIntent); } diff --git a/js/app/map/scrollbar.js b/js/app/map/scrollbar.js index 5563d312..6347b6d5 100644 --- a/js/app/map/scrollbar.js +++ b/js/app/map/scrollbar.js @@ -16,7 +16,7 @@ define([ $.fn.initCustomScrollbar = function(config){ // default config ------------------------------------------------------------------------- - var defaultConfig = { + let defaultConfig = { axis: 'x', theme: 'light-thick', scrollInertia: 300, @@ -52,7 +52,7 @@ define([ config = $.extend(true, {}, defaultConfig, config); return this.each(function(){ - var scrollableElement = $(this); + let scrollableElement = $(this); // prevent multiple initialization scrollableElement.mCustomScrollbar('destroy'); diff --git a/js/app/map/system.js b/js/app/map/system.js index 7a38b67c..e2b82cd8 100644 --- a/js/app/map/system.js +++ b/js/app/map/system.js @@ -13,6 +13,11 @@ define([ 'use strict'; let config = { + newSystemOffset: { + x: 130, + y: 0 + }, + systemActiveClass: 'pf-system-active' // class for an active system in a map }; @@ -193,8 +198,32 @@ define([ } }; + /** + * calculate the x/y coordinates for a new system - relativ to a source system + * @param sourceSystem + * @returns {{x: *, y: *}} + */ + let calculateNewSystemPosition = function(sourceSystem){ + + // related system is available + let currentX = sourceSystem.css('left'); + let currentY = sourceSystem.css('top'); + + // remove "px" + currentX = parseInt( currentX.substring(0, currentX.length - 2) ); + currentY = parseInt( currentY.substring(0, currentY.length - 2) ); + + let newPosition = { + x: currentX + config.newSystemOffset.x, + y: currentY + config.newSystemOffset.y + }; + + return newPosition; + }; + return { deleteSystems: deleteSystems, - removeSystems: removeSystems + removeSystems: removeSystems, + calculateNewSystemPosition: calculateNewSystemPosition }; }); \ No newline at end of file diff --git a/js/app/map/util.js b/js/app/map/util.js index c9c4a1f1..aeeff14d 100644 --- a/js/app/map/util.js +++ b/js/app/map/util.js @@ -5,8 +5,9 @@ define([ 'jquery', 'app/init', - 'app/util' -], function($, Init, Util) { + 'app/util', + 'bootbox' +], function($, Init, Util, bootbox) { 'use strict'; let config = { @@ -17,8 +18,12 @@ define([ mapLocalStoragePrefix: 'map_', // prefix for map data local storage key mapTabContentClass: 'pf-map-tab-content', // Tab-Content element (parent element) + mapClass: 'pf-map', // class for all maps + mapGridClass: 'pf-grid-small', // class for map grid snapping + + systemIdPrefix: 'pf-system-', // id prefix for a system systemClass: 'pf-system', // class for all systems - mapGridClass: 'pf-grid-small' // class for map grid snapping + systemSelectedClass: 'pf-system-selected' // class for selected systems in a map }; // map menu options @@ -26,13 +31,19 @@ define([ mapMagnetizer: { buttonId: Util.config.menuButtonMagnetizerId, description: 'Magnetizer', - onEnable: 'initMagnetizer', // jQuery extension function - onDisable: 'destroyMagnetizer' // jQuery extension function + onEnable: 'initMagnetizer', // jQuery extension function + onDisable: 'destroyMagnetizer' // jQuery extension function }, mapSnapToGrid : { buttonId: Util.config.menuButtonGridId, description: 'Grid snapping', class: 'mapGridClass' + }, + mapEndpoint : { + buttonId: Util.config.menuButtonEndpointId, + description: 'Endpoint overlay', + onEnable: 'showEndpointOverlays', // jQuery extension function + onDisable: 'hideEndpointOverlays' // jQuery extension function } }; @@ -191,6 +202,14 @@ define([ return this.find('.' + config.systemClass); }; + /** + * get all selected (NOT active) systems in a map + * @returns {*} + */ + $.fn.getSelectedSystems = function(){ + let mapElement = $(this); + return mapElement.find('.' + config.systemSelectedClass); + }; /** * search connections by systems @@ -200,7 +219,7 @@ define([ */ let searchConnectionsBySystems = function(map, systems){ let connections = []; - let withBackConnection = false; + let withBackConnection = true; $.each(systems, function(i, system){ // get connections where system is source @@ -571,6 +590,48 @@ define([ }); }; + /** + * set map "shortcut" events + */ + $.fn.setMapShortcuts = function(){ + return this.each((i, mapWrapper) => { + mapWrapper = $(mapWrapper); + let mapElement = mapWrapper.findMapElement(); + + // dynamic require Map module -> otherwise there is a require(), loop + let Map = require('app/map/map'); + let map = Map.getMapInstance( mapElement.data('id')); + + mapWrapper.watchKey('mapSystemAdd', (mapWrapper) => { + Map.showNewSystemDialog(map, {position: {x: 0, y: 0}}); + },{focus: true}); + + mapWrapper.watchKey('mapSystemsSelect', (mapWrapper) => { + mapElement.selectAllSystems(); + },{focus: true}); + + mapWrapper.watchKey('mapSystemsDelete', (mapWrapper) => { + let selectedSystems = mapElement.getSelectedSystems(); + $.fn.showDeleteSystemDialog(map, selectedSystems); + },{focus: true}); + + }); + }; + + $.fn.findMapElement = function(){ + return $(this).find('.' + config.mapClass); + }; + + /** + * get systemId string (selector + * @param mapId + * @param systemId + * @returns {string} + */ + let getSystemId = (mapId, systemId) => { + return config.systemIdPrefix + mapId + '-' + systemId; + }; + return { config: config, mapOptions: mapOptions, @@ -593,6 +654,7 @@ define([ storeDefaultMapId: storeDefaultMapId, getLocaleData: getLocaleData, storeLocalData: storeLocalData, - deleteLocalData: deleteLocalData + deleteLocalData: deleteLocalData, + getSystemId: getSystemId }; }); \ No newline at end of file diff --git a/js/app/mappage.js b/js/app/mappage.js index 5d4429c8..30d31716 100644 --- a/js/app/mappage.js +++ b/js/app/mappage.js @@ -10,6 +10,7 @@ define([ 'app/logging', 'app/page', 'app/map/worker', + 'app/key', 'app/ui/form_element', 'app/module_map' ], ($, Init, Util, Render, Logging, Page, MapWorker) => { @@ -30,7 +31,7 @@ define([ // load page // load info (maintenance) info panel (if scheduled) - $('body').loadPageStructure(); + $('body').loadPageStructure().setGlobalShortcuts(); // show app information in browser console Util.showVersionInfo(); diff --git a/js/app/module_map.js b/js/app/module_map.js index 219ed3df..0c52a51d 100644 --- a/js/app/module_map.js +++ b/js/app/module_map.js @@ -56,16 +56,14 @@ define([ }; /** - * get the current active map for - * @returns {*} + * get the current active mapElement + * @returns {JQuery|*|T|{}|jQuery} */ $.fn.getActiveMap = function(){ let map = $(this).find('.active.' + config.mapTabContentClass + ' .' + config.mapClass); - - if(map.length === 0){ + if(!map.length){ map = false; } - return map; }; @@ -563,7 +561,7 @@ define([ activeMapIds.push(mapId); // check for map data change and update tab - if(tabMapData.config.updated !== tabElement.data('updated')){ + if(tabMapData.config.updated > tabElement.data('updated')){ tabElement.updateTabData(tabMapData.config); } }else{ @@ -631,7 +629,6 @@ define([ // add new tab for each map for(let j = 0; j < tempMapData.length; j++){ - let data = tempMapData[j]; tabMapElement.addTab(data.config); } diff --git a/js/app/page.js b/js/app/page.js index 2d175d19..be493cee 100644 --- a/js/app/page.js +++ b/js/app/page.js @@ -16,6 +16,7 @@ define([ 'dialog/map_info', 'dialog/account_settings', 'dialog/manual', + 'dialog/shortcuts', 'dialog/map_settings', 'dialog/system_effects', 'dialog/jump_info', @@ -62,7 +63,10 @@ define([ menuHeadMenuLogoClass: 'pf-head-menu-logo', // class for main menu logo // helper element - dynamicElementWrapperId: 'pf-dialog-wrapper' + dynamicElementWrapperId: 'pf-dialog-wrapper', + + // system signature module + systemSigModuleClass: 'pf-sig-table-module', // module wrapper (signatures) }; let programStatusCounter = 0; // current count down in s until next status change is possible @@ -74,49 +78,84 @@ define([ * @returns {*|jQuery|HTMLElement} */ $.fn.loadPageStructure = function(){ - let body = $(this); + return this.each((i, body) => { + body = $(body); - // menu left - body.prepend( - $('
', { - class: [config.pageSlidebarClass, config.pageSlidebarLeftClass, 'sb-style-push', 'sb-width-custom'].join(' ') - }).attr('data-sb-width', config.pageSlideLeftWidth) - ); + // menu left + body.prepend( + $('
', { + class: [config.pageSlidebarClass, config.pageSlidebarLeftClass, 'sb-style-push', 'sb-width-custom'].join(' ') + }).attr('data-sb-width', config.pageSlideLeftWidth) + ); - // menu right - body.prepend( - $('
', { - class: [config.pageSlidebarClass, config.pageSlidebarRightClass, 'sb-style-push', 'sb-width-custom'].join(' ') - }).attr('data-sb-width', config.pageSlideRightWidth) - ); + // menu right + body.prepend( + $('
', { + class: [config.pageSlidebarClass, config.pageSlidebarRightClass, 'sb-style-push', 'sb-width-custom'].join(' ') + }).attr('data-sb-width', config.pageSlideRightWidth) + ); - // main page - body.prepend( - $('
', { - id: config.pageId, - class: config.pageClass - }).append( + // main page + body.prepend( + $('
', { + id: config.pageId, + class: config.pageClass + }).append( Util.getMapModule() ).append( $('
', { id: config.dynamicElementWrapperId }) ) - ); + ); - // load header / footer - $('.' + config.pageClass).loadHeader().loadFooter(); + // load header / footer + $('.' + config.pageClass).loadHeader().loadFooter(); - // load left menu - $('.' + config.pageSlidebarLeftClass).loadLeftMenu(); + // load left menu + $('.' + config.pageSlidebarLeftClass).loadLeftMenu(); - // load right menu - $('.' + config.pageSlidebarRightClass).loadRightMenu(); + // load right menu + $('.' + config.pageSlidebarRightClass).loadRightMenu(); - // set document observer for global events - setDocumentObserver(); + // set document observer for global events + setDocumentObserver(); + }); + }; - return body; + /** + * set global shortcuts to element + */ + $.fn.setGlobalShortcuts = function(){ + return this.each((i, body) => { + body = $(body); + + body.watchKey('tabReload', (body) => { + location.reload(); + }); + + body.watchKey('signaturePaste', (e) => { + let moduleElement = $('.' + config.systemSigModuleClass); + + // check if there is a signature module active (system clicked) + if(moduleElement.length){ + e = e.originalEvent; + let targetElement = $(e.target); + + // do not read clipboard if pasting into form elements + if( + targetElement.prop('tagName').toLowerCase() !== 'input' && + targetElement.prop('tagName').toLowerCase() !== 'textarea' || ( + targetElement.is('input[type="search"]') // Datatables "search" field bubbles `paste.DT` event :( + ) + ){ + let clipboard = (e.originalEvent || e).clipboardData.getData('text/plain'); + moduleElement.trigger('pf:updateSystemSignatureModuleByClipboard', [clipboard]); + } + } + }); + + }); }; /** @@ -148,10 +187,10 @@ define([ class: 'list-group-item', href: '/' }).html('  Home').prepend( - $('',{ - class: 'fa fa-home fa-fw' - }) - ) + $('',{ + class: 'fa fa-home fa-fw' + }) + ) ).append( getMenuHeadline('Information') ).append( @@ -162,11 +201,6 @@ define([ $('',{ class: 'fa fa-line-chart fa-fw' }) - ).append( - $('',{ - class: 'badge bg-color bg-color-gray txt-color txt-color-warning', - text: 'beta' - }) ).on('click', function(){ $(document).triggerMenuEvent('ShowStatsDialog'); }) @@ -175,23 +209,23 @@ define([ class: 'list-group-item list-group-item-info', href: '#' }).html('  Effect info').prepend( - $('',{ - class: 'fa fa-crosshairs fa-fw' - }) - ).on('click', function(){ - $(document).triggerMenuEvent('ShowSystemEffectInfo'); + $('',{ + class: 'fa fa-crosshairs fa-fw' }) + ).on('click', function(){ + $(document).triggerMenuEvent('ShowSystemEffectInfo'); + }) ).append( $('', { class: 'list-group-item list-group-item-info', href: '#' }).html('  Jump info').prepend( - $('',{ - class: 'fa fa-space-shuttle fa-fw' - }) - ).on('click', function(){ - $(document).triggerMenuEvent('ShowJumpInfo'); + $('',{ + class: 'fa fa-space-shuttle fa-fw' }) + ).on('click', function(){ + $(document).triggerMenuEvent('ShowJumpInfo'); + }) ).append( getMenuHeadline('Settings') ).append( @@ -211,32 +245,32 @@ define([ id: Util.config.menuButtonFullScreenId, href: '#' }).html('  Full screen').prepend( - $('',{ - class: 'glyphicon glyphicon-fullscreen', - css: {width: '1.23em'} - }) - ).on('click', function(){ - let fullScreenElement = $('body'); - requirejs(['jquery', 'fullScreen'], function($) { - - if($.fullscreen.isFullScreen()){ - $.fullscreen.exit(); - }else{ - fullScreenElement.fullscreen({overflow: 'scroll', toggleClass: config.fullScreenClass}); - } - }); + $('',{ + class: 'glyphicon glyphicon-fullscreen', + css: {width: '1.23em'} }) + ).on('click', function(){ + let fullScreenElement = $('body'); + requirejs(['jquery', 'fullScreen'], function($) { + + if($.fullscreen.isFullScreen()){ + $.fullscreen.exit(); + }else{ + fullScreenElement.fullscreen({overflow: 'scroll', toggleClass: config.fullScreenClass}); + } + }); + }) ).append( $('', { class: 'list-group-item', href: '#' }).html('  Notification test').prepend( - $('',{ - class: 'fa fa-volume-up fa-fw' - }) - ).on('click', function(){ - $(document).triggerMenuEvent('NotificationTest'); + $('',{ + class: 'fa fa-volume-up fa-fw' }) + ).on('click', function(){ + $(document).triggerMenuEvent('NotificationTest'); + }) ).append( getMenuHeadline('Danger zone') ).append( @@ -248,19 +282,19 @@ define([ class: 'fa fa-user-times fa-fw' }) ).on('click', function(){ - $(document).triggerMenuEvent('DeleteAccount'); - }) + $(document).triggerMenuEvent('DeleteAccount'); + }) ).append( $('', { class: 'list-group-item list-group-item-warning', href: '#' }).html('  Logout').prepend( - $('',{ - class: 'fa fa-sign-in fa-fw' - }) - ).on('click', function(){ - $(document).triggerMenuEvent('Logout', {clearCookies: 1}); + $('',{ + class: 'fa fa-sign-in fa-fw' }) + ).on('click', function(){ + $(document).triggerMenuEvent('Logout', {clearCookies: 1}); + }) ) ); @@ -332,6 +366,21 @@ define([ toggle: true }); }) + ).append( + $('', { + class: 'list-group-item', + id: Util.config.menuButtonEndpointId, + href: '#' + }).html('   Signatures').prepend( + $('',{ + class: 'fa fa-link fa-fw' + }) + ).on('click', function(){ + Util.getMapModule().getActiveMap().triggerMenuEvent('MapOption', { + option: 'mapEndpoint', + toggle: true + }); + }) ).append( getMenuHeadline('Help') ).append( @@ -343,8 +392,24 @@ define([ class: 'fa fa-book fa-fw' }) ).on('click', function(){ - $(document).triggerMenuEvent('Manual'); + $(document).triggerMenuEvent('Manual'); + }) + ).append( + $('', { + class: 'list-group-item list-group-item-info', + href: '#' + }).html('  Shortcuts').prepend( + $('',{ + class: 'fa fa-keyboard-o fa-fw' }) + ).append( + $('',{ + class: 'badge bg-color bg-color-gray txt-color txt-color-warning', + text: 'beta' + }) + ).on('click', function(){ + $(document).triggerMenuEvent('Shortcuts'); + }) ).append( $('', { class: 'list-group-item list-group-item-info', @@ -367,8 +432,8 @@ define([ class: 'fa fa-trash fa-fw' }) ).on('click', function(){ - $(document).triggerMenuEvent('DeleteMap'); - }) + $(document).triggerMenuEvent('DeleteMap'); + }) ) ); }; @@ -576,6 +641,18 @@ define([ return false; }); + $(document).on('pf:menuShowTaskManager', function(e, data){ + // show log dialog + Logging.showDialog(); + return false; + }); + + $(document).on('pf:menuShortcuts', function(e, data){ + // show shortcuts dialog + $.fn.showShortcutsDialog(); + return false; + }); + $(document).on('pf:menuShowSettingsDialog', function(e){ // show character select dialog $.fn.showSettingsDialog(); @@ -616,12 +693,6 @@ define([ return false; }); - $(document).on('pf:menuShowTaskManager', function(e, data){ - // show log dialog - Logging.showDialog(); - return false; - }); - $(document).on('pf:menuLogout', function(e, data){ let clearCookies = false; @@ -921,8 +992,8 @@ define([ */ let notificationTest = function(){ Util.showNotify({ - title: 'Test Notification', - text: 'Accept browser security question'}, + title: 'Test Notification', + text: 'Accept browser security question'}, { desktop: true, stack: 'barBottom' diff --git a/js/app/ui/dialog/jump_info.js b/js/app/ui/dialog/jump_info.js index b247cd43..00d4528e 100644 --- a/js/app/ui/dialog/jump_info.js +++ b/js/app/ui/dialog/jump_info.js @@ -9,9 +9,10 @@ define([ 'app/render', 'bootbox', ], function($, Init, Util, Render, bootbox) { + 'use strict'; - var config = { + let config = { // jump info dialog jumpInfoDialogClass: 'pf-jump-info-dialog' // class for jump info dialog }; @@ -22,12 +23,10 @@ define([ $.fn.showJumpInfoDialog = function(){ requirejs(['text!templates/dialog/jump_info.html', 'mustache'], function(template, Mustache) { + let data = {}; + let content = Mustache.render(template, data); - var data = {}; - - var content = Mustache.render(template, data); - - var signatureReaderDialog = bootbox.dialog({ + let signatureReaderDialog = bootbox.dialog({ className: config.jumpInfoDialogClass, title: 'Wormhole jump information', message: content diff --git a/js/app/ui/dialog/manual.js b/js/app/ui/dialog/manual.js index 01b4e3fd..90acd394 100644 --- a/js/app/ui/dialog/manual.js +++ b/js/app/ui/dialog/manual.js @@ -12,7 +12,7 @@ define([ 'use strict'; - var config = { + let config = { // global dialog dialogNavigationClass: 'pf-dialog-navigation-list', // class for dialog navigation bar dialogNavigationListItemClass: 'pf-dialog-navigation-list-item', // class for map manual li main navigation elements @@ -28,7 +28,7 @@ define([ requirejs(['text!templates/dialog/map_manual.html', 'mustache'], function(template, Mustache) { - var data = { + let data = { dialogNavigationClass: config.dialogNavigationClass, dialogNavLiClass: config.dialogNavigationListItemClass, scrollspyId: config.mapManualScrollspyId, @@ -36,10 +36,10 @@ define([ mapCounterClass : Init.classes.pieChart.pieChartMapCounterClass }; - var content = Mustache.render(template, data); + let content = Mustache.render(template, data); // show dialog - var mapManualDialog = bootbox.dialog({ + let mapManualDialog = bootbox.dialog({ title: 'Manual', message: content, size: 'large', @@ -56,15 +56,15 @@ define([ }); // modal offset top - var modalOffsetTop = 200; + let modalOffsetTop = 200; // disable on scroll event - var disableOnScrollEvent = false; + let disableOnScrollEvent = false; // scroll breakpoints - var scrolLBreakpointElements = null; + let scrolLBreakpointElements = null; // scroll navigation links - var scrollNavLiElements = null; + let scrollNavLiElements = null; mapManualDialog.on('shown.bs.modal', function(e) { // modal on open @@ -72,13 +72,13 @@ define([ scrollNavLiElements = $('.' + config.dialogNavigationListItemClass); }); - var scrollspyElement = $('#' + config.mapManualScrollspyId); + let scrollspyElement = $('#' + config.mapManualScrollspyId); - var whileScrolling = function(){ + let whileScrolling = function(){ if(disableOnScrollEvent === false){ - for(var i = 0; i < scrolLBreakpointElements.length; i++){ - var offset = $(scrolLBreakpointElements[i]).offset().top; + for(let i = 0; i < scrolLBreakpointElements.length; i++){ + let offset = $(scrolLBreakpointElements[i]).offset().top; if( (offset - modalOffsetTop) > 0){ @@ -116,11 +116,11 @@ define([ scrollspyElement.find('.' + data.mapCounterClass).initMapUpdateCounter(); // set navigation button observer - var mainNavigationLinks = $('.' + config.dialogNavigationClass).find('a'); + let mainNavigationLinks = $('.' + config.dialogNavigationClass).find('a'); // text anchor links - var subNavigationLinks = scrollspyElement.find('a[data-target]'); + let subNavigationLinks = scrollspyElement.find('a[data-target]'); - var navigationLinks = mainNavigationLinks.add(subNavigationLinks); + let navigationLinks = mainNavigationLinks.add(subNavigationLinks); navigationLinks.on('click', function(e){ e.preventDefault(); @@ -130,7 +130,7 @@ define([ // scroll to anchor scrollspyElement.mCustomScrollbar('scrollTo', $(this).attr('data-target')); - var mainNavigationLiElement = $(this).parent('.' + config.dialogNavigationListItemClass); + let mainNavigationLiElement = $(this).parent('.' + config.dialogNavigationListItemClass); whileScrolling(); diff --git a/js/app/ui/dialog/map_info.js b/js/app/ui/dialog/map_info.js index 0d747d74..55e54220 100644 --- a/js/app/ui/dialog/map_info.js +++ b/js/app/ui/dialog/map_info.js @@ -36,8 +36,6 @@ define([ tableActionCellClass: 'pf-table-action-cell', // class for table "action" cells tableCounterCellClass: 'pf-table-counter-cell', // class for table "counter" cells - systemIdPrefix: 'pf-system-', // id prefix for a system - loadingOptions: { // config for loading overlay icon: { size: 'fa-2x' @@ -430,12 +428,12 @@ define([ let deleteRowElement = $(target).parents('tr'); let activeMap = Util.getMapModule().getActiveMap(); - let systemElement = $('#' + config.systemIdPrefix + mapData.config.id + '-' + rowData.id); + let systemElement = $('#' + MapUtil.getSystemId(mapData.config.id, rowData.id) ); - if(systemElement){ + if(systemElement.length){ // trigger system delete event activeMap.trigger('pf:deleteSystems', [{ - systems: [systemElement], + systems: [systemElement[0]], callback: function(){ // callback function after ajax "delete" success // remove table row diff --git a/js/app/ui/dialog/notification.js b/js/app/ui/dialog/notification.js index 73a77849..128d14f4 100644 --- a/js/app/ui/dialog/notification.js +++ b/js/app/ui/dialog/notification.js @@ -12,7 +12,7 @@ define([ 'use strict'; - var config = { + let config = { // shutdown dialog notificationDialogId: 'pf-notification-dialog', // id for "notification" dialog @@ -23,8 +23,8 @@ define([ * show/animate dialog page content * @param dialog */ - var showPageContent = function(dialog){ - var headlineElement = dialog.find('h1'); + let showPageContent = function(dialog){ + let headlineElement = dialog.find('h1'); headlineElement.delay(300).velocity('transition.shrinkIn', { duration: 500 @@ -45,7 +45,7 @@ define([ $.fn.showNotificationDialog = function(dialogData){ // check if there is already a notification dialog open - var notificationDialogClassDialoges = $('.' + config.notificationDialogClass); + let notificationDialogClassDialoges = $('.' + config.notificationDialogClass); if(notificationDialogClassDialoges.length === 0){ @@ -54,15 +54,15 @@ define([ requirejs(['text!templates/dialog/notification.html', 'mustache'], function(template, Mustache) { - var data = { + let data = { id: config.notificationDialogId, content: dialogData.content }; - var content = Mustache.render(template, data); + let content = Mustache.render(template, data); // show dialog - var shutdownDialog = bootbox.dialog({ + let shutdownDialog = bootbox.dialog({ title: dialogData.content.title, message: content, className: config.notificationDialogClass, @@ -72,7 +72,7 @@ define([ shutdownDialog.on('shown.bs.modal', function(e) { // remove close button - var dialog = $(this); + let dialog = $(this); dialog.find('.bootbox-close-button').remove(); dialog.find('button').blur(); diff --git a/js/app/ui/dialog/shortcuts.js b/js/app/ui/dialog/shortcuts.js new file mode 100644 index 00000000..da89b92b --- /dev/null +++ b/js/app/ui/dialog/shortcuts.js @@ -0,0 +1,50 @@ +/** + * shortcuts dialog + */ + +define([ + 'jquery', + 'app/init', + 'app/util', + 'app/render', + 'bootbox', + 'app/key', +], function($, Init, Util, Render, bootbox, Key) { + + 'use strict'; + + let config = { + // map dialog + shortcutsDialogId: 'pf-shortcuts-dialog', // id for shortcuts dialog + }; + + /** + * shows the map manual modal dialog + */ + $.fn.showShortcutsDialog = function(){ + requirejs(['text!templates/dialog/shortcuts.html', 'mustache'], function(template, Mustache){ + + let data = { + id: config.shortcutsDialogId, + shortcuts: Key.getGroupedShortcuts() + }; + + let content = Mustache.render(template, data); + + // show dialog + let shortcutsDialog = bootbox.dialog({ + title: 'Keyboard Shortcuts', + message: content, + size: 'large', + buttons: { + success: { + label: 'close', + className: 'btn-default' + } + }, + show: true + }); + + }); + }; +}); \ No newline at end of file diff --git a/js/app/ui/dialog/system_effects.js b/js/app/ui/dialog/system_effects.js index 2849d7e0..0328275b 100644 --- a/js/app/ui/dialog/system_effects.js +++ b/js/app/ui/dialog/system_effects.js @@ -13,12 +13,12 @@ define([ ], function($, Init, Util, Render, bootbox, MapUtil) { 'use strict'; - var config = { + let config = { // system effect dialog systemEffectDialogWrapperClass: 'pf-system-effect-dialog-wrapper' // class for system effect dialog }; - var cache = { + let cache = { systemEffectDialog: false // system effect info dialog }; @@ -30,31 +30,31 @@ define([ // cache table structure if(!cache.systemEffectDialog){ - var dialogWrapperElement = $('
', { + let dialogWrapperElement = $('
', { class: config.systemEffectDialogWrapperClass }); - var systemEffectData = Util.getSystemEffectData(); + let systemEffectData = Util.getSystemEffectData(); $.each( systemEffectData.wh, function( effectName, effectData ) { - var table = $('', { + let table = $('
', { class: ['table', 'table-condensed'].join(' ') }); - var tbody = $(''); - var thead = $(''); + let tbody = $(''); + let thead = $(''); - var rows = []; + let rows = []; // get formatted system effect name - var systemEffectName = MapUtil.getEffectInfoForSystem(effectName, 'name'); - var systemEffectClass = MapUtil.getEffectInfoForSystem(effectName, 'class'); + let systemEffectName = MapUtil.getEffectInfoForSystem(effectName, 'name'); + let systemEffectClass = MapUtil.getEffectInfoForSystem(effectName, 'class'); $.each( effectData, function( areaId, areaData ) { - var systemType = 'C' + areaId; - var securityClass = Util.getSecurityClassForSystem( systemType ); + let systemType = 'C' + areaId; + let securityClass = Util.getSecurityClassForSystem( systemType ); if(areaId === '1'){ rows.push( $('') ); diff --git a/js/app/ui/form_element.js b/js/app/ui/form_element.js index 36b6cfe8..ce858c08 100644 --- a/js/app/ui/form_element.js +++ b/js/app/ui/form_element.js @@ -15,7 +15,7 @@ define([ * init a select element as "select2" for map selection */ $.fn.initMapSelect = function(){ - var selectElement = $(this); + let selectElement = $(this); $.when( selectElement.select2({ @@ -31,9 +31,9 @@ define([ * @param options */ $.fn.initSystemSelect = function(options){ - var selectElement = $(this); + let selectElement = $(this); - var config = { + let config = { maxSelectionLength: 1 }; options = $.extend({}, config, options); @@ -46,12 +46,12 @@ define([ } // show effect info just for wormholes - var hideEffectClass = ''; + let hideEffectClass = ''; if(data.effect === ''){ hideEffectClass = 'hide'; } - var markup = '
'; + let markup = '
'; markup += '
' + data.text + '
'; markup += '
'; markup += ''; @@ -83,12 +83,12 @@ define([ results: data.map( function(item){ // "systemId" or "name" - var id = item[options.key]; - var disabled = false; - var trueSec = parseFloat(item.trueSec); - var secClass = Util.getSecurityClassForSystem(item.security); - var trueSecClass = Util.getTrueSecClassForSystem( trueSec ); - var effectClass = MapUtil.getEffectInfoForSystem(item.effect, 'class'); + let id = item[options.key]; + let disabled = false; + let trueSec = parseFloat(item.trueSec); + let secClass = Util.getSecurityClassForSystem(item.security); + let trueSecClass = Util.getTrueSecClassForSystem( trueSec ); + let effectClass = MapUtil.getEffectInfoForSystem(item.effect, 'class'); // check if system is dialed if( @@ -126,7 +126,7 @@ define([ error: function (jqXHR, status, error) { if( !Util.isXHRAborted(jqXHR) ){ - var reason = status + ' ' + jqXHR.status + ': ' + error; + let reason = status + ' ' + jqXHR.status + ': ' + error; Util.showNotify({title: 'System select warning', text: reason + ' deleted', type: 'warning'}); } @@ -161,7 +161,7 @@ define([ return this.each(function(){ - var selectElement = $(this); + let selectElement = $(this); // format result data function formatResultData (data) { @@ -172,7 +172,7 @@ define([ // check if an option is already selected // do not show the same result twice - var currentValues = selectElement.val(); + let currentValues = selectElement.val(); if( currentValues && @@ -181,8 +181,8 @@ define([ return ; } - var imagePath = ''; - var previewContent = ''; + let imagePath = ''; + let previewContent = ''; switch(options.type){ case 'character': @@ -199,7 +199,7 @@ define([ break; } - var markup = '
'; + let markup = '
'; markup += '
' + previewContent + '
'; markup += '
' + data.text + '
'; @@ -213,7 +213,7 @@ define([ return data.text; } - var markup = '
'; + let markup = '
'; markup += '
' + data.text + '
'; return markup; @@ -248,7 +248,7 @@ define([ error: function (jqXHR, status, error) { if( !Util.isXHRAborted(jqXHR) ){ - var reason = status + ' ' + jqXHR.status + ': ' + error; + let reason = status + ' ' + jqXHR.status + ': ' + error; Util.showNotify({title: 'Access select warning', text: reason + ' deleted', type: 'warning'}); } diff --git a/js/app/ui/system_signature.js b/js/app/ui/system_signature.js index 8544e6e5..313e8ea4 100644 --- a/js/app/ui/system_signature.js +++ b/js/app/ui/system_signature.js @@ -7,8 +7,10 @@ define([ 'app/init', 'app/util', 'app/render', - 'bootbox' -], function($, Init, Util, Render, bootbox) { + 'bootbox', + 'app/map/map', + 'app/map/util' +], function($, Init, Util, Render, bootbox, Map, MapUtil) { 'use strict'; let config = { @@ -40,10 +42,12 @@ define([ sigTableEditSigNameInput: 'pf-sig-table-edit-name-input', // class for editable fields (input) sigTableEditSigGroupSelect: 'pf-sig-table-edit-group-select', // class for editable fields (sig group) sigTableEditSigTypeSelect: 'pf-sig-table-edit-type-select', // class for editable fields (sig type) + sigTableEditSigConnectionSelect: 'pf-sig-table-edit-connection-select', // class for editable fields (sig connection) sigTableEditSigDescriptionTextarea: 'pf-sig-table-edit-desc-text', // class for editable fields (sig description) sigTableCreatedCellClass: 'pf-sig-table-created', // class for "created" cells sigTableUpdatedCellClass: 'pf-sig-table-updated', // class for "updated" cells + sigTableConnectionClass: 'pf-table-connection-cell', // class for "connection" cells sigTableCounterClass: 'pf-table-counter-cell', // class for "counter" cells sigTableActionCellClass: 'pf-table-action-cell', // class for "action" cells @@ -159,7 +163,7 @@ define([ let updateCell = signatureTableApi.cell( rowIndex, cellIndex ); let updateCellElement = updateCell.nodes().to$(); - if(cellIndex === 6){ + if(cellIndex === 7){ // clear existing counter interval clearInterval( updateCellElement.data('interval') ); } @@ -167,7 +171,7 @@ define([ // set new value updateCell.data( data ).draw(); - if(cellIndex === 6){ + if(cellIndex === 7){ updateCellElement.initTimestampCounter(); } }; @@ -694,6 +698,27 @@ define([ tempData.type = sigType; + // set connection (to target system) ------------------------------------------------------------------ + let sigConnection = ' 0){ + sigConnection += 'data-pk="' + data.id + '" '; + } + + // set disabled if group is not wromhole + if(data.groupId !== 5){ + sigConnection += 'data-disabled="1" '; + } + + if(data.connection){ + sigConnection += 'data-value="' + data.connection.id + '" '; + } + sigConnection += '>'; + + tempData.connection = { + render: sigConnection, + connection: data.connection + }; + // set description ------------------------------------------------------------------------------------ let sigDescription = ' 0){ @@ -1014,6 +1039,7 @@ define([ let sigGroupFields = tableElement.find('.' + config.sigTableEditSigGroupSelect); let sigTypeFields = tableElement.find('.' + config.sigTableEditSigTypeSelect); let sigDescriptionFields = tableElement.find('.' + config.sigTableEditSigDescriptionTextarea); + let sigConnectionFields = tableElement.find('.' + config.sigTableEditSigConnectionSelect); // jump to "next" editable field on save let openNextEditDialogOnSave = function(fields){ @@ -1038,8 +1064,16 @@ define([ }; // helper function - get the next editable field in next table column - let getNextEditableField = function(field){ - let nextEditableField = $(field).closest('td').next().find('.editable'); + let getNextEditableField = function(field, selector){ + let nextEditableField = null; + if(selector){ + // search specific sibling + nextEditableField = $(field).closest('td').nextAll(selector).find('.editable'); + }else{ + // get next sibling + nextEditableField = $(field).closest('td').next().find('.editable'); + } + return $(nextEditableField); }; @@ -1108,7 +1142,7 @@ define([ updateTooltip(columnElement, newValue); // update "updated" cell - updateSignatureCell(rowElement, 6, newRowData.updated); + updateSignatureCell(rowElement, 7, newRowData.updated); } } }); @@ -1145,7 +1179,7 @@ define([ let newRowData = response.signatures[0]; // update "updated" cell - updateSignatureCell(rowElement, 6, newRowData.updated); + updateSignatureCell(rowElement, 7, newRowData.updated); } // find related "type" select (same row) and change options @@ -1166,6 +1200,18 @@ define([ }else{ typeSelect.editable('disable'); } + + // find "connection" select (same row) and change "enabled" flag + let connectionSelect = getNextEditableField(signatureTypeField, '.' + config.sigTableConnectionClass); + connectionSelect.editable('setValue', null); + + if(newValue === 5){ + // wormhole + connectionSelect.editable('enable'); + }else{ + checkConnectionConflicts(); + connectionSelect.editable('disable'); + } } }); @@ -1204,7 +1250,7 @@ define([ let newRowData = response.signatures[0]; // update "updated" cell - updateSignatureCell(rowElement, 6, newRowData.updated); + updateSignatureCell(rowElement, 7, newRowData.updated); } } }); @@ -1227,7 +1273,62 @@ define([ let newRowData = response.signatures[0]; // update "updated" cell - updateSignatureCell(rowElement, 6, newRowData.updated); + updateSignatureCell(rowElement, 7, newRowData.updated); + } + } + }); + + // Select connection (target system) -------------------------------------------------------------------------- + let initCount = 0; + sigConnectionFields.on('init', function(e, editable) { + if(++initCount >= sigConnectionFields.length){ + checkConnectionConflicts(); + } + }); + + sigConnectionFields.editable({ + type: 'select', + title: 'system', + name: 'connectionId', + emptytext: 'unknown', + onblur: 'submit', + showbuttons: false, + params: modifyFieldParamsOnSend, + display: function(value, sourceData) { + let editableElement = $(this); + let newValue = ''; + + if(value !== null){ + let selected = $.fn.editableutils.itemsByValue(value, sourceData); + if( + selected.length && + selected[0].text !== '' + ){ + newValue += ''; + newValue += ' ' + selected[0].text; + }else{ + newValue = 'unknown'; + } + } + + editableElement.html(newValue); + }, + source: function(a,b){ + let activeMap = Util.getMapModule().getActiveMap(); + let mapId = activeMap.data('id'); + + let availableConnections = getSignatureConnectionOptions(mapId, systemData); + + return availableConnections; + }, + success: function(response, newValue){ + if(response){ + let signatureConnectionField = $(this); + let rowElement = signatureConnectionField.parents('tr'); + let newRowData = response.signatures[0]; + + // update "updated" cell + updateSignatureCell(rowElement, 7, newRowData.updated); } } }); @@ -1244,13 +1345,109 @@ define([ tableElement.parents('.' + config.tableToolsActionClass).css( 'height', '-=35px' ); }); + // save events + sigConnectionFields.on('save', function(e, editable){ + checkConnectionConflicts(); + }); + // open next field dialog ------------------------------------------------------------------------------------- openNextEditDialogOnSave(sigNameFields); openNextEditDialogOnSave(sigGroupFields); }; /** - * get all signatures that can exist for a given system + * get all connection select options + * @param mapId + * @param systemData + * @returns {Array} + */ + let getSignatureConnectionOptions = (mapId, systemData) => { + let map = Map.getMapInstance( mapId ); + let systemId = MapUtil.getSystemId(mapId, systemData.id); + let systemConnections = MapUtil.searchConnectionsBySystems(map, [systemId]); + let connectionOptions = []; + + for(let i = 0; i < systemConnections.length; i++){ + let connectionData = Map.getDataByConnection(systemConnections[i]); + + // connectionId is required (must be stored) + if(connectionData.id){ + // check whether "source" or "target" system is relevant for this connection + // -> hint "source" === 'target' --> loop + if(systemData.id !== connectionData.target){ + // take target... + connectionOptions.push({ + value: connectionData.id, + text: connectionData.targetName + }); + }else if(systemData.id !== connectionData.source){ + // take source... + connectionOptions.push({ + value: connectionData.id, + text: connectionData.sourceName + }); + } + } + } + + // add empty entry + connectionOptions.unshift({ value: null, text: ''}); + + return connectionOptions; + }; + + /** + * check connectionIds for conflicts (multiple signatures -> same connection) + * -> show "conflict" icon next to select + */ + let checkConnectionConflicts = () => { + setTimeout(function() { + let connectionSelects = $('.' + config.sigTableConnectionClass + ' .editable'); + let connectionIds = []; + let duplicateConnectionIds = []; + let groupedSelects = []; + + connectionSelects.each(function(){ + let select = $(this); + let value = parseInt(select.editable('getValue', true) )|| 0; + + if( + connectionIds.indexOf(value) > -1 && + duplicateConnectionIds.indexOf(value) === -1 + ){ + // duplicate found + duplicateConnectionIds.push(value); + } + + if(groupedSelects[value] !== undefined){ + groupedSelects[value].push(select[0]); + }else{ + groupedSelects[value] = [select[0]]; + } + + connectionIds.push(value); + }); + + // update "conflict" icon next to select label for connectionIds + connectionSelects.each(function(){ + let select = $(this); + let value = parseInt(select.editable('getValue', true) )|| 0; + let conflictIcon = select.find('.fa-exclamation-triangle'); + if( + duplicateConnectionIds.indexOf(value) > -1 && + groupedSelects[value].indexOf(select[0]) > -1 + ){ + conflictIcon.removeClass('hide'); + }else{ + conflictIcon.addClass('hide'); + } + }); + }, 200); + }; + + /** + * get all signature types that can exist for a given system + * -> result is partially cached * @param systemData * @param systemTypeId * @param areaId @@ -1265,6 +1462,7 @@ define([ // check for cached signature names if(sigNameCache.hasOwnProperty( cacheKey )){ // cached signatures do not include static WHs! + // -> ".slice(0)" creates copy newSelectOptions = sigNameCache[cacheKey].slice(0); newSelectOptionsCount = sumSignaturesRecursive('children', newSelectOptions); }else{ @@ -1281,7 +1479,7 @@ define([ tempSelectOptions.hasOwnProperty(key) ) { newSelectOptionsCount++; - fixSelectOptions.push( {value: key, text: tempSelectOptions[key] } ); + fixSelectOptions.push( {value: parseInt(key), text: tempSelectOptions[key] } ); } } @@ -1366,6 +1564,19 @@ define([ return newSelectOptions; }; + /** + * get all signature types that can exist for a system (jQuery obj) + * @param systemElement + * @param groupId + * @returns {Array} + */ + let getAllSignatureNamesBySystem = (systemElement, groupId) => { + let systemTypeId = systemElement.data('typeId'); + let areaId = Util.getAreaIdBySecurity(systemElement.data('security')); + let systemData = {statics: systemElement.data('statics')}; + return getAllSignatureNames(systemData, systemTypeId, areaId, groupId); + }; + /** * recursive sum array.length for a given object key * -> e.g. @@ -1451,6 +1662,9 @@ define([ // update signature bar moduleElement.updateScannedSignaturesBar({showNotice: false}); + // update connection conflicts + checkConnectionConflicts(); + Util.showNotify({title: 'Signature deleted', text: signatureCount + ' signatures deleted', type: 'success'}); } }; @@ -1539,16 +1753,16 @@ define([ .css({ 'willChange': 'height' }).velocity('slideUp', { - duration: duration, - complete: function(animationElements){ - // remove wrapper - $(animationElements).children().unwrap(); + duration: duration, + complete: function(animationElements){ + // remove wrapper + $(animationElements).children().unwrap(); - if(callback !== undefined){ - callback(rowElement); - } + if(callback !== undefined){ + callback(rowElement); } - }); + } + }); }else{ // show row @@ -1577,23 +1791,23 @@ define([ .css({ 'willChange': 'height' }).velocity('slideDown', { - duration: duration, - complete: function(animationElements){ - // remove wrapper - for(let i = 0; i < animationElements.length; i++){ - let currentWrapper = $(animationElements[i]); - if(currentWrapper.children().length > 0){ - currentWrapper.children().unwrap(); - }else{ - currentWrapper.parent().html( currentWrapper.html() ); - } - } - - if(callback !== undefined){ - callback(rowElement); + duration: duration, + complete: function(animationElements){ + // remove wrapper + for(let i = 0; i < animationElements.length; i++){ + let currentWrapper = $(animationElements[i]); + if(currentWrapper.children().length > 0){ + currentWrapper.children().unwrap(); + }else{ + currentWrapper.parent().html( currentWrapper.html() ); } } - }); + + if(callback !== undefined){ + callback(rowElement); + } + } + }); } }); } @@ -1789,6 +2003,18 @@ define([ data: 'description' },{ targets: 5, + orderable: false, + searchable: false, + className: [config.sigTableConnectionClass].join(' '), + title: 'leads to', + type: 'html', + width: '70px', + data: 'connection', + render: { + _: 'render' + } + },{ + targets: 6, title: 'created', width: '90px', searchable: false, @@ -1802,7 +2028,7 @@ define([ $(cell).initTimestampCounter(); } },{ - targets: 6, + targets: 7, title: 'updated', width: '90px', searchable: false, @@ -1824,7 +2050,7 @@ define([ } } },{ - targets: 7, + targets: 8, title: '', orderable: false, searchable: false, @@ -1845,7 +2071,7 @@ define([ } } },{ - targets: 8, + targets: 9, title: '', orderable: false, searchable: false, @@ -1924,6 +2150,9 @@ define([ btnOkLabel: 'delete', btnOkIcon: 'fa fa-fw fa-close', onConfirm : function(e, target){ + // top scroll to top + e.preventDefault(); + let deleteRowElement = $(target).parents('tr'); let row = tempTableElement.DataTable().rows(deleteRowElement); deleteSignatures(row); @@ -1977,17 +2206,8 @@ define([ }); // event listener for global "paste" signatures into the page ------------------------------------------------- - $(document).off('paste').on('paste', function(e){ - - // do not read clipboard if pasting into form elements - if( - $(e.target).prop('tagName').toLowerCase() !== 'input' && - $(e.target).prop('tagName').toLowerCase() !== 'textarea' - ){ - let clipboard = (e.originalEvent || e).clipboardData.getData('text/plain'); - - moduleElement.updateSignatureTableByClipboard(systemData, clipboard, {}); - } + moduleElement.on('pf:updateSystemSignatureModuleByClipboard', function(e, clipboard){ + $(this).updateSignatureTableByClipboard(systemData, clipboard, {}); }); }; @@ -2097,9 +2317,9 @@ define([ moduleElement.velocity('transition.slideDownOut', { duration: Init.animationSpeed.mapModule, complete: function(tempElement){ - // Destroying the data tables throws - // save remove of all dataTables - signatureTable.api().destroy(); + // Destroying the data tables throws + // save remove of all dataTables + signatureTable.api().destroy(); $(tempElement).remove(); @@ -2118,4 +2338,8 @@ define([ } }; + return { + getAllSignatureNamesBySystem: getAllSignatureNamesBySystem + }; + }); \ No newline at end of file diff --git a/js/app/util.js b/js/app/util.js index fefba264..781d9ec5 100644 --- a/js/app/util.js +++ b/js/app/util.js @@ -40,6 +40,7 @@ define([ menuButtonFullScreenId: 'pf-menu-button-fullscreen', // id for menu button "fullscreen" menuButtonMagnetizerId: 'pf-menu-button-magnetizer', // id for menu button "magnetizer" menuButtonGridId: 'pf-menu-button-grid', // id for menu button "grid snap" + menuButtonEndpointId: 'pf-menu-button-endpoint', // id for menu button "endpoint" overlays settingsMessageVelocityOptions: { @@ -712,7 +713,7 @@ define([ content: '', container: 'body', title: tooltipData.name + - '' + tooltipData.security + '', + '' + tooltipData.security + '', delay: { show: 250, hide: 0 @@ -881,6 +882,27 @@ define([ }; }; + /** + * flatten XEditable array for select fields + * @param dataArray + * @returns {{}} + */ + let flattenXEditableSelectArray = (dataArray) => { + let flatten = {}; + + for(let data of dataArray){ + if(data.children && data.children.length > 0){ + for(let child of data.children){ + flatten[child.value] = child.text; + } + }else{ + flatten[data.value] = data.text; + } + } + + return flatten; + } ; + /** * set default configuration for "Bootbox" dialogs */ @@ -1205,7 +1227,7 @@ define([ * @returns {string} */ let getSyncType = () => { - return Init.syncStatus.type; + return Init.syncStatus.type; }; /** @@ -1230,9 +1252,7 @@ define([ * @returns {JQuery|*|{}|T} */ $.fn.getMapTabElements = function(mapId){ - let mapModuleElement = $(this); - let mapTabElements = mapModuleElement.find('#' + config.mapTabBarId).find('a'); if(mapId){ @@ -1861,8 +1881,8 @@ define([ let getCurrentLocationData = function(){ let currentLocationLink = $('#' + config.headCurrentLocationId).find('a'); return { - id: currentLocationLink.data('systemId'), - name: currentLocationLink.data('systemName') + id: currentLocationLink.data('systemId'), + name: currentLocationLink.data('systemName') }; }; @@ -2037,6 +2057,7 @@ define([ getCurrentLocationData: getCurrentLocationData, getCurrentUserInfo: getCurrentUserInfo, getCurrentCharacterLog: getCurrentCharacterLog, + flattenXEditableSelectArray: flattenXEditableSelectArray, setDestination: setDestination, convertDateToString: convertDateToString, getOpenDialogs: getOpenDialogs, diff --git a/js/lib/jquery-3.0.0.min.js b/js/lib/jquery-3.0.0.min.js deleted file mode 100644 index 62d410d9..00000000 --- a/js/lib/jquery-3.0.0.min.js +++ /dev/null @@ -1,4 +0,0 @@ -/*! jQuery v3.0.0 | (c) jQuery Foundation | jquery.org/license */ -!function(a,b){"use strict";"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){"use strict";var c=[],d=a.document,e=Object.getPrototypeOf,f=c.slice,g=c.concat,h=c.push,i=c.indexOf,j={},k=j.toString,l=j.hasOwnProperty,m=l.toString,n=m.call(Object),o={};function p(a,b){b=b||d;var c=b.createElement("script");c.text=a,b.head.appendChild(c).parentNode.removeChild(c)}var q="3.0.0",r=function(a,b){return new r.fn.init(a,b)},s=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,t=/^-ms-/,u=/-([a-z])/g,v=function(a,b){return b.toUpperCase()};r.fn=r.prototype={jquery:q,constructor:r,length:0,toArray:function(){return f.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:f.call(this)},pushStack:function(a){var b=r.merge(this.constructor(),a);return b.prevObject=this,b},each:function(a){return r.each(this,a)},map:function(a){return this.pushStack(r.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(f.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor()},push:h,sort:c.sort,splice:c.splice},r.extend=r.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||r.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(a=arguments[h]))for(b in a)c=g[b],d=a[b],g!==d&&(j&&d&&(r.isPlainObject(d)||(e=r.isArray(d)))?(e?(e=!1,f=c&&r.isArray(c)?c:[]):f=c&&r.isPlainObject(c)?c:{},g[b]=r.extend(j,f,d)):void 0!==d&&(g[b]=d));return g},r.extend({expando:"jQuery"+(q+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===r.type(a)},isArray:Array.isArray,isWindow:function(a){return null!=a&&a===a.window},isNumeric:function(a){var b=r.type(a);return("number"===b||"string"===b)&&!isNaN(a-parseFloat(a))},isPlainObject:function(a){var b,c;return a&&"[object Object]"===k.call(a)?(b=e(a))?(c=l.call(b,"constructor")&&b.constructor,"function"==typeof c&&m.call(c)===n):!0:!1},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?j[k.call(a)]||"object":typeof a},globalEval:function(a){p(a)},camelCase:function(a){return a.replace(t,"ms-").replace(u,v)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b){var c,d=0;if(w(a)){for(c=a.length;c>d;d++)if(b.call(a[d],d,a[d])===!1)break}else for(d in a)if(b.call(a[d],d,a[d])===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(s,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(w(Object(a))?r.merge(c,"string"==typeof a?[a]:a):h.call(c,a)),c},inArray:function(a,b,c){return null==b?-1:i.call(b,a,c)},merge:function(a,b){for(var c=+b.length,d=0,e=a.length;c>d;d++)a[e++]=b[d];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,e,f=0,h=[];if(w(a))for(d=a.length;d>f;f++)e=b(a[f],f,c),null!=e&&h.push(e);else for(f in a)e=b(a[f],f,c),null!=e&&h.push(e);return g.apply([],h)},guid:1,proxy:function(a,b){var c,d,e;return"string"==typeof b&&(c=a[b],b=a,a=c),r.isFunction(a)?(d=f.call(arguments,2),e=function(){return a.apply(b||this,d.concat(f.call(arguments)))},e.guid=a.guid=a.guid||r.guid++,e):void 0},now:Date.now,support:o}),"function"==typeof Symbol&&(r.fn[Symbol.iterator]=c[Symbol.iterator]),r.each("Boolean Number String Function Array Date RegExp Object Error Symbol".split(" "),function(a,b){j["[object "+b+"]"]=b.toLowerCase()});function w(a){var b=!!a&&"length"in a&&a.length,c=r.type(a);return"function"===c||r.isWindow(a)?!1:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var x=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+1*new Date,v=a.document,w=0,x=0,y=ha(),z=ha(),A=ha(),B=function(a,b){return a===b&&(l=!0),0},C={}.hasOwnProperty,D=[],E=D.pop,F=D.push,G=D.push,H=D.slice,I=function(a,b){for(var c=0,d=a.length;d>c;c++)if(a[c]===b)return c;return-1},J="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",K="[\\x20\\t\\r\\n\\f]",L="(?:\\\\.|[\\w-]|[^\x00-\\xa0])+",M="\\["+K+"*("+L+")(?:"+K+"*([*^$|!~]?=)"+K+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+L+"))|)"+K+"*\\]",N=":("+L+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+M+")*)|.*)\\)|)",O=new RegExp(K+"+","g"),P=new RegExp("^"+K+"+|((?:^|[^\\\\])(?:\\\\.)*)"+K+"+$","g"),Q=new RegExp("^"+K+"*,"+K+"*"),R=new RegExp("^"+K+"*([>+~]|"+K+")"+K+"*"),S=new RegExp("="+K+"*([^\\]'\"]*?)"+K+"*\\]","g"),T=new RegExp(N),U=new RegExp("^"+L+"$"),V={ID:new RegExp("^#("+L+")"),CLASS:new RegExp("^\\.("+L+")"),TAG:new RegExp("^("+L+"|[*])"),ATTR:new RegExp("^"+M),PSEUDO:new RegExp("^"+N),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+K+"*(even|odd|(([+-]|)(\\d*)n|)"+K+"*(?:([+-]|)"+K+"*(\\d+)|))"+K+"*\\)|)","i"),bool:new RegExp("^(?:"+J+")$","i"),needsContext:new RegExp("^"+K+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+K+"*((?:-\\d)?\\d*)"+K+"*\\)|)(?=[^-]|$)","i")},W=/^(?:input|select|textarea|button)$/i,X=/^h\d$/i,Y=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,$=/[+~]/,_=new RegExp("\\\\([\\da-f]{1,6}"+K+"?|("+K+")|.)","ig"),aa=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)},ba=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\x80-\uFFFF\w-]/g,ca=function(a,b){return b?"\x00"===a?"\ufffd":a.slice(0,-1)+"\\"+a.charCodeAt(a.length-1).toString(16)+" ":"\\"+a},da=function(){m()},ea=ta(function(a){return a.disabled===!0},{dir:"parentNode",next:"legend"});try{G.apply(D=H.call(v.childNodes),v.childNodes),D[v.childNodes.length].nodeType}catch(fa){G={apply:D.length?function(a,b){F.apply(a,H.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function ga(a,b,d,e){var f,h,j,k,l,o,r,s=b&&b.ownerDocument,w=b?b.nodeType:9;if(d=d||[],"string"!=typeof a||!a||1!==w&&9!==w&&11!==w)return d;if(!e&&((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,p)){if(11!==w&&(l=Z.exec(a)))if(f=l[1]){if(9===w){if(!(j=b.getElementById(f)))return d;if(j.id===f)return d.push(j),d}else if(s&&(j=s.getElementById(f))&&t(b,j)&&j.id===f)return d.push(j),d}else{if(l[2])return G.apply(d,b.getElementsByTagName(a)),d;if((f=l[3])&&c.getElementsByClassName&&b.getElementsByClassName)return G.apply(d,b.getElementsByClassName(f)),d}if(c.qsa&&!A[a+" "]&&(!q||!q.test(a))){if(1!==w)s=b,r=a;else if("object"!==b.nodeName.toLowerCase()){(k=b.getAttribute("id"))?k=k.replace(ba,ca):b.setAttribute("id",k=u),o=g(a),h=o.length;while(h--)o[h]="#"+k+" "+sa(o[h]);r=o.join(","),s=$.test(a)&&qa(b.parentNode)||b}if(r)try{return G.apply(d,s.querySelectorAll(r)),d}catch(x){}finally{k===u&&b.removeAttribute("id")}}}return i(a.replace(P,"$1"),b,d,e)}function ha(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function ia(a){return a[u]=!0,a}function ja(a){var b=n.createElement("fieldset");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function ka(a,b){var c=a.split("|"),e=c.length;while(e--)d.attrHandle[c[e]]=b}function la(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&a.sourceIndex-b.sourceIndex;if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function ma(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function na(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function oa(a){return function(b){return"label"in b&&b.disabled===a||"form"in b&&b.disabled===a||"form"in b&&b.disabled===!1&&(b.isDisabled===a||b.isDisabled!==!a&&("label"in b||!ea(b))!==a)}}function pa(a){return ia(function(b){return b=+b,ia(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function qa(a){return a&&"undefined"!=typeof a.getElementsByTagName&&a}c=ga.support={},f=ga.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=ga.setDocument=function(a){var b,e,g=a?a.ownerDocument||a:v;return g!==n&&9===g.nodeType&&g.documentElement?(n=g,o=n.documentElement,p=!f(n),v!==n&&(e=n.defaultView)&&e.top!==e&&(e.addEventListener?e.addEventListener("unload",da,!1):e.attachEvent&&e.attachEvent("onunload",da)),c.attributes=ja(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ja(function(a){return a.appendChild(n.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=Y.test(n.getElementsByClassName),c.getById=ja(function(a){return o.appendChild(a).id=u,!n.getElementsByName||!n.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if("undefined"!=typeof b.getElementById&&p){var c=b.getElementById(a);return c?[c]:[]}},d.filter.ID=function(a){var b=a.replace(_,aa);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(_,aa);return function(a){var c="undefined"!=typeof a.getAttributeNode&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return"undefined"!=typeof b.getElementsByTagName?b.getElementsByTagName(a):c.qsa?b.querySelectorAll(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return"undefined"!=typeof b.getElementsByClassName&&p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=Y.test(n.querySelectorAll))&&(ja(function(a){o.appendChild(a).innerHTML="",a.querySelectorAll("[msallowcapture^='']").length&&q.push("[*^$]="+K+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+K+"*(?:value|"+J+")"),a.querySelectorAll("[id~="+u+"-]").length||q.push("~="),a.querySelectorAll(":checked").length||q.push(":checked"),a.querySelectorAll("a#"+u+"+*").length||q.push(".#.+[+~]")}),ja(function(a){a.innerHTML="";var b=n.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+K+"*[*^$|!~]?="),2!==a.querySelectorAll(":enabled").length&&q.push(":enabled",":disabled"),o.appendChild(a).disabled=!0,2!==a.querySelectorAll(":disabled").length&&q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=Y.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ja(function(a){c.disconnectedMatch=s.call(a,"*"),s.call(a,"[s!='']:x"),r.push("!=",N)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=Y.test(o.compareDocumentPosition),t=b||Y.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===n||a.ownerDocument===v&&t(v,a)?-1:b===n||b.ownerDocument===v&&t(v,b)?1:k?I(k,a)-I(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,e=a.parentNode,f=b.parentNode,g=[a],h=[b];if(!e||!f)return a===n?-1:b===n?1:e?-1:f?1:k?I(k,a)-I(k,b):0;if(e===f)return la(a,b);c=a;while(c=c.parentNode)g.unshift(c);c=b;while(c=c.parentNode)h.unshift(c);while(g[d]===h[d])d++;return d?la(g[d],h[d]):g[d]===v?-1:h[d]===v?1:0},n):n},ga.matches=function(a,b){return ga(a,null,null,b)},ga.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(S,"='$1']"),c.matchesSelector&&p&&!A[b+" "]&&(!r||!r.test(b))&&(!q||!q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return ga(b,n,null,[a]).length>0},ga.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},ga.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&C.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},ga.escape=function(a){return(a+"").replace(ba,ca)},ga.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},ga.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=ga.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=ga.selectors={cacheLength:50,createPseudo:ia,match:V,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(_,aa),a[3]=(a[3]||a[4]||a[5]||"").replace(_,aa),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||ga.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&ga.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return V.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&T.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(_,aa).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+K+")"+a+"("+K+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||"undefined"!=typeof a.getAttribute&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=ga.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e.replace(O," ")+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h,t=!1;if(q){if(f){while(p){m=b;while(m=m[p])if(h?m.nodeName.toLowerCase()===r:1===m.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){m=q,l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),j=k[a]||[],n=j[0]===w&&j[1],t=n&&j[2],m=n&&q.childNodes[n];while(m=++n&&m&&m[p]||(t=n=0)||o.pop())if(1===m.nodeType&&++t&&m===b){k[a]=[w,n,t];break}}else if(s&&(m=b,l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),j=k[a]||[],n=j[0]===w&&j[1],t=n),t===!1)while(m=++n&&m&&m[p]||(t=n=0)||o.pop())if((h?m.nodeName.toLowerCase()===r:1===m.nodeType)&&++t&&(s&&(l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),k[a]=[w,t]),m===b))break;return t-=e,t===d||t%d===0&&t/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||ga.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?ia(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=I(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:ia(function(a){var b=[],c=[],d=h(a.replace(P,"$1"));return d[u]?ia(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),b[0]=null,!c.pop()}}),has:ia(function(a){return function(b){return ga(a,b).length>0}}),contains:ia(function(a){return a=a.replace(_,aa),function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:ia(function(a){return U.test(a||"")||ga.error("unsupported lang: "+a),a=a.replace(_,aa).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:oa(!1),disabled:oa(!0),checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return X.test(a.nodeName)},input:function(a){return W.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:pa(function(){return[0]}),last:pa(function(a,b){return[b-1]}),eq:pa(function(a,b,c){return[0>c?c+b:c]}),even:pa(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:pa(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:pa(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:pa(function(a,b,c){for(var d=0>c?c+b:c;++db;b++)d+=a[b].value;return d}function ta(a,b,c){var d=b.dir,e=b.next,f=e||d,g=c&&"parentNode"===f,h=x++;return b.first?function(b,c,e){while(b=b[d])if(1===b.nodeType||g)return a(b,c,e)}:function(b,c,i){var j,k,l,m=[w,h];if(i){while(b=b[d])if((1===b.nodeType||g)&&a(b,c,i))return!0}else while(b=b[d])if(1===b.nodeType||g)if(l=b[u]||(b[u]={}),k=l[b.uniqueID]||(l[b.uniqueID]={}),e&&e===b.nodeName.toLowerCase())b=b[d]||b;else{if((j=k[f])&&j[0]===w&&j[1]===h)return m[2]=j[2];if(k[f]=m,m[2]=a(b,c,i))return!0}}}function ua(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function va(a,b,c){for(var d=0,e=b.length;e>d;d++)ga(a,b[d],c);return c}function wa(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(c&&!c(f,d,e)||(g.push(f),j&&b.push(h)));return g}function xa(a,b,c,d,e,f){return d&&!d[u]&&(d=xa(d)),e&&!e[u]&&(e=xa(e,f)),ia(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||va(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:wa(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=wa(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?I(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=wa(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):G.apply(g,r)})}function ya(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=ta(function(a){return a===b},h,!0),l=ta(function(a){return I(b,a)>-1},h,!0),m=[function(a,c,d){var e=!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d));return b=null,e}];f>i;i++)if(c=d.relative[a[i].type])m=[ta(ua(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;f>e;e++)if(d.relative[a[e].type])break;return xa(i>1&&ua(m),i>1&&sa(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(P,"$1"),c,e>i&&ya(a.slice(i,e)),f>e&&ya(a=a.slice(e)),f>e&&sa(a))}m.push(c)}return ua(m)}function za(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,o,q,r=0,s="0",t=f&&[],u=[],v=j,x=f||e&&d.find.TAG("*",k),y=w+=null==v?1:Math.random()||.1,z=x.length;for(k&&(j=g===n||g||k);s!==z&&null!=(l=x[s]);s++){if(e&&l){o=0,g||l.ownerDocument===n||(m(l),h=!p);while(q=a[o++])if(q(l,g||n,h)){i.push(l);break}k&&(w=y)}c&&((l=!q&&l)&&r--,f&&t.push(l))}if(r+=s,c&&s!==r){o=0;while(q=b[o++])q(t,u,g,h);if(f){if(r>0)while(s--)t[s]||u[s]||(u[s]=E.call(i));u=wa(u)}G.apply(i,u),k&&!f&&u.length>0&&r+b.length>1&&ga.uniqueSort(i)}return k&&(w=y,j=v),t};return c?ia(f):f}return h=ga.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=ya(b[c]),f[u]?d.push(f):e.push(f);f=A(a,za(e,d)),f.selector=a}return f},i=ga.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(_,aa),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=V.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(_,aa),$.test(j[0].type)&&qa(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&sa(j),!a)return G.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,!b||$.test(a)&&qa(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ja(function(a){return 1&a.compareDocumentPosition(n.createElement("fieldset"))}),ja(function(a){return a.innerHTML="","#"===a.firstChild.getAttribute("href")})||ka("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ja(function(a){return a.innerHTML="",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||ka("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ja(function(a){return null==a.getAttribute("disabled")})||ka(J,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),ga}(a);r.find=x,r.expr=x.selectors,r.expr[":"]=r.expr.pseudos,r.uniqueSort=r.unique=x.uniqueSort,r.text=x.getText,r.isXMLDoc=x.isXML,r.contains=x.contains,r.escapeSelector=x.escape;var y=function(a,b,c){var d=[],e=void 0!==c;while((a=a[b])&&9!==a.nodeType)if(1===a.nodeType){if(e&&r(a).is(c))break;d.push(a)}return d},z=function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c},A=r.expr.match.needsContext,B=/^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i,C=/^.[^:#\[\.,]*$/;function D(a,b,c){if(r.isFunction(b))return r.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return r.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(C.test(b))return r.filter(b,a,c);b=r.filter(b,a)}return r.grep(a,function(a){return i.call(b,a)>-1!==c&&1===a.nodeType})}r.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?r.find.matchesSelector(d,a)?[d]:[]:r.find.matches(a,r.grep(b,function(a){return 1===a.nodeType}))},r.fn.extend({find:function(a){var b,c,d=this.length,e=this;if("string"!=typeof a)return this.pushStack(r(a).filter(function(){for(b=0;d>b;b++)if(r.contains(e[b],this))return!0}));for(c=this.pushStack([]),b=0;d>b;b++)r.find(a,e[b],c);return d>1?r.uniqueSort(c):c},filter:function(a){return this.pushStack(D(this,a||[],!1))},not:function(a){return this.pushStack(D(this,a||[],!0))},is:function(a){return!!D(this,"string"==typeof a&&A.test(a)?r(a):a||[],!1).length}});var E,F=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/,G=r.fn.init=function(a,b,c){var e,f;if(!a)return this;if(c=c||E,"string"==typeof a){if(e="<"===a[0]&&">"===a[a.length-1]&&a.length>=3?[null,a,null]:F.exec(a),!e||!e[1]&&b)return!b||b.jquery?(b||c).find(a):this.constructor(b).find(a);if(e[1]){if(b=b instanceof r?b[0]:b,r.merge(this,r.parseHTML(e[1],b&&b.nodeType?b.ownerDocument||b:d,!0)),B.test(e[1])&&r.isPlainObject(b))for(e in b)r.isFunction(this[e])?this[e](b[e]):this.attr(e,b[e]);return this}return f=d.getElementById(e[2]),f&&(this[0]=f,this.length=1),this}return a.nodeType?(this[0]=a,this.length=1,this):r.isFunction(a)?void 0!==c.ready?c.ready(a):a(r):r.makeArray(a,this)};G.prototype=r.fn,E=r(d);var H=/^(?:parents|prev(?:Until|All))/,I={children:!0,contents:!0,next:!0,prev:!0};r.fn.extend({has:function(a){var b=r(a,this),c=b.length;return this.filter(function(){for(var a=0;c>a;a++)if(r.contains(this,b[a]))return!0})},closest:function(a,b){var c,d=0,e=this.length,f=[],g="string"!=typeof a&&r(a);if(!A.test(a))for(;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&r.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?r.uniqueSort(f):f)},index:function(a){return a?"string"==typeof a?i.call(r(a),this[0]):i.call(this,a.jquery?a[0]:a):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(r.uniqueSort(r.merge(this.get(),r(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function J(a,b){while((a=a[b])&&1!==a.nodeType);return a}r.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return y(a,"parentNode")},parentsUntil:function(a,b,c){return y(a,"parentNode",c)},next:function(a){return J(a,"nextSibling")},prev:function(a){return J(a,"previousSibling")},nextAll:function(a){return y(a,"nextSibling")},prevAll:function(a){return y(a,"previousSibling")},nextUntil:function(a,b,c){return y(a,"nextSibling",c)},prevUntil:function(a,b,c){return y(a,"previousSibling",c)},siblings:function(a){return z((a.parentNode||{}).firstChild,a)},children:function(a){return z(a.firstChild)},contents:function(a){return a.contentDocument||r.merge([],a.childNodes)}},function(a,b){r.fn[a]=function(c,d){var e=r.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=r.filter(d,e)),this.length>1&&(I[a]||r.uniqueSort(e),H.test(a)&&e.reverse()),this.pushStack(e)}});var K=/\S+/g;function L(a){var b={};return r.each(a.match(K)||[],function(a,c){b[c]=!0}),b}r.Callbacks=function(a){a="string"==typeof a?L(a):r.extend({},a);var b,c,d,e,f=[],g=[],h=-1,i=function(){for(e=a.once,d=b=!0;g.length;h=-1){c=g.shift();while(++h-1)f.splice(c,1),h>=c&&h--}),this},has:function(a){return a?r.inArray(a,f)>-1:f.length>0},empty:function(){return f&&(f=[]),this},disable:function(){return e=g=[],f=c="",this},disabled:function(){return!f},lock:function(){return e=g=[],c||b||(f=c=""),this},locked:function(){return!!e},fireWith:function(a,c){return e||(c=c||[],c=[a,c.slice?c.slice():c],g.push(c),b||i()),this},fire:function(){return j.fireWith(this,arguments),this},fired:function(){return!!d}};return j};function M(a){return a}function N(a){throw a}function O(a,b,c){var d;try{a&&r.isFunction(d=a.promise)?d.call(a).done(b).fail(c):a&&r.isFunction(d=a.then)?d.call(a,b,c):b.call(void 0,a)}catch(a){c.call(void 0,a)}}r.extend({Deferred:function(b){var c=[["notify","progress",r.Callbacks("memory"),r.Callbacks("memory"),2],["resolve","done",r.Callbacks("once memory"),r.Callbacks("once memory"),0,"resolved"],["reject","fail",r.Callbacks("once memory"),r.Callbacks("once memory"),1,"rejected"]],d="pending",e={state:function(){return d},always:function(){return f.done(arguments).fail(arguments),this},"catch":function(a){return e.then(null,a)},pipe:function(){var a=arguments;return r.Deferred(function(b){r.each(c,function(c,d){var e=r.isFunction(a[d[4]])&&a[d[4]];f[d[1]](function(){var a=e&&e.apply(this,arguments);a&&r.isFunction(a.promise)?a.promise().progress(b.notify).done(b.resolve).fail(b.reject):b[d[0]+"With"](this,e?[a]:arguments)})}),a=null}).promise()},then:function(b,d,e){var f=0;function g(b,c,d,e){return function(){var h=this,i=arguments,j=function(){var a,j;if(!(f>b)){if(a=d.apply(h,i),a===c.promise())throw new TypeError("Thenable self-resolution");j=a&&("object"==typeof a||"function"==typeof a)&&a.then,r.isFunction(j)?e?j.call(a,g(f,c,M,e),g(f,c,N,e)):(f++,j.call(a,g(f,c,M,e),g(f,c,N,e),g(f,c,M,c.notifyWith))):(d!==M&&(h=void 0,i=[a]),(e||c.resolveWith)(h,i))}},k=e?j:function(){try{j()}catch(a){r.Deferred.exceptionHook&&r.Deferred.exceptionHook(a,k.stackTrace),b+1>=f&&(d!==N&&(h=void 0,i=[a]),c.rejectWith(h,i))}};b?k():(r.Deferred.getStackHook&&(k.stackTrace=r.Deferred.getStackHook()),a.setTimeout(k))}}return r.Deferred(function(a){c[0][3].add(g(0,a,r.isFunction(e)?e:M,a.notifyWith)),c[1][3].add(g(0,a,r.isFunction(b)?b:M)),c[2][3].add(g(0,a,r.isFunction(d)?d:N))}).promise()},promise:function(a){return null!=a?r.extend(a,e):e}},f={};return r.each(c,function(a,b){var g=b[2],h=b[5];e[b[1]]=g.add,h&&g.add(function(){d=h},c[3-a][2].disable,c[0][2].lock),g.add(b[3].fire),f[b[0]]=function(){return f[b[0]+"With"](this===f?void 0:this,arguments),this},f[b[0]+"With"]=g.fireWith}),e.promise(f),b&&b.call(f,f),f},when:function(a){var b=arguments.length,c=b,d=Array(c),e=f.call(arguments),g=r.Deferred(),h=function(a){return function(c){d[a]=this,e[a]=arguments.length>1?f.call(arguments):c,--b||g.resolveWith(d,e)}};if(1>=b&&(O(a,g.done(h(c)).resolve,g.reject),"pending"===g.state()||r.isFunction(e[c]&&e[c].then)))return g.then();while(c--)O(e[c],h(c),g.reject);return g.promise()}});var P=/^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/;r.Deferred.exceptionHook=function(b,c){a.console&&a.console.warn&&b&&P.test(b.name)&&a.console.warn("jQuery.Deferred exception: "+b.message,b.stack,c)};var Q=r.Deferred();r.fn.ready=function(a){return Q.then(a),this},r.extend({isReady:!1,readyWait:1,holdReady:function(a){a?r.readyWait++:r.ready(!0)},ready:function(a){(a===!0?--r.readyWait:r.isReady)||(r.isReady=!0,a!==!0&&--r.readyWait>0||Q.resolveWith(d,[r]))}}),r.ready.then=Q.then;function R(){d.removeEventListener("DOMContentLoaded",R),a.removeEventListener("load",R),r.ready()}"complete"===d.readyState||"loading"!==d.readyState&&!d.documentElement.doScroll?a.setTimeout(r.ready):(d.addEventListener("DOMContentLoaded",R),a.addEventListener("load",R));var S=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===r.type(c)){e=!0;for(h in c)S(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,r.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){ -return j.call(r(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},T=function(a){return 1===a.nodeType||9===a.nodeType||!+a.nodeType};function U(){this.expando=r.expando+U.uid++}U.uid=1,U.prototype={cache:function(a){var b=a[this.expando];return b||(b={},T(a)&&(a.nodeType?a[this.expando]=b:Object.defineProperty(a,this.expando,{value:b,configurable:!0}))),b},set:function(a,b,c){var d,e=this.cache(a);if("string"==typeof b)e[r.camelCase(b)]=c;else for(d in b)e[r.camelCase(d)]=b[d];return e},get:function(a,b){return void 0===b?this.cache(a):a[this.expando]&&a[this.expando][r.camelCase(b)]},access:function(a,b,c){return void 0===b||b&&"string"==typeof b&&void 0===c?this.get(a,b):(this.set(a,b,c),void 0!==c?c:b)},remove:function(a,b){var c,d=a[this.expando];if(void 0!==d){if(void 0!==b){r.isArray(b)?b=b.map(r.camelCase):(b=r.camelCase(b),b=b in d?[b]:b.match(K)||[]),c=b.length;while(c--)delete d[b[c]]}(void 0===b||r.isEmptyObject(d))&&(a.nodeType?a[this.expando]=void 0:delete a[this.expando])}},hasData:function(a){var b=a[this.expando];return void 0!==b&&!r.isEmptyObject(b)}};var V=new U,W=new U,X=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,Y=/[A-Z]/g;function Z(a,b,c){var d;if(void 0===c&&1===a.nodeType)if(d="data-"+b.replace(Y,"-$&").toLowerCase(),c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:X.test(c)?JSON.parse(c):c}catch(e){}W.set(a,b,c)}else c=void 0;return c}r.extend({hasData:function(a){return W.hasData(a)||V.hasData(a)},data:function(a,b,c){return W.access(a,b,c)},removeData:function(a,b){W.remove(a,b)},_data:function(a,b,c){return V.access(a,b,c)},_removeData:function(a,b){V.remove(a,b)}}),r.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=W.get(f),1===f.nodeType&&!V.get(f,"hasDataAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=r.camelCase(d.slice(5)),Z(f,d,e[d])));V.set(f,"hasDataAttrs",!0)}return e}return"object"==typeof a?this.each(function(){W.set(this,a)}):S(this,function(b){var c;if(f&&void 0===b){if(c=W.get(f,a),void 0!==c)return c;if(c=Z(f,a),void 0!==c)return c}else this.each(function(){W.set(this,a,b)})},null,b,arguments.length>1,null,!0)},removeData:function(a){return this.each(function(){W.remove(this,a)})}}),r.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=V.get(a,b),c&&(!d||r.isArray(c)?d=V.access(a,b,r.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=r.queue(a,b),d=c.length,e=c.shift(),f=r._queueHooks(a,b),g=function(){r.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return V.get(a,c)||V.access(a,c,{empty:r.Callbacks("once memory").add(function(){V.remove(a,[b+"queue",c])})})}}),r.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.lengthf;f++)d=a[f],d.style&&(c=d.style.display,b?("none"===c&&(e[f]=V.get(d,"display")||null,e[f]||(d.style.display="")),""===d.style.display&&ba(d)&&(e[f]=fa(d))):"none"!==c&&(e[f]="none",V.set(d,"display",c)));for(f=0;g>f;f++)null!=e[f]&&(a[f].style.display=e[f]);return a}r.fn.extend({show:function(){return ga(this,!0)},hide:function(){return ga(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){ba(this)?r(this).show():r(this).hide()})}});var ha=/^(?:checkbox|radio)$/i,ia=/<([a-z][^\/\0>\x20\t\r\n\f]+)/i,ja=/^$|\/(?:java|ecma)script/i,ka={option:[1,""],thead:[1,"
","
"],col:[2,"","
"],tr:[2,"","
"],td:[3,"","
"],_default:[0,"",""]};ka.optgroup=ka.option,ka.tbody=ka.tfoot=ka.colgroup=ka.caption=ka.thead,ka.th=ka.td;function la(a,b){var c="undefined"!=typeof a.getElementsByTagName?a.getElementsByTagName(b||"*"):"undefined"!=typeof a.querySelectorAll?a.querySelectorAll(b||"*"):[];return void 0===b||b&&r.nodeName(a,b)?r.merge([a],c):c}function ma(a,b){for(var c=0,d=a.length;d>c;c++)V.set(a[c],"globalEval",!b||V.get(b[c],"globalEval"))}var na=/<|&#?\w+;/;function oa(a,b,c,d,e){for(var f,g,h,i,j,k,l=b.createDocumentFragment(),m=[],n=0,o=a.length;o>n;n++)if(f=a[n],f||0===f)if("object"===r.type(f))r.merge(m,f.nodeType?[f]:f);else if(na.test(f)){g=g||l.appendChild(b.createElement("div")),h=(ia.exec(f)||["",""])[1].toLowerCase(),i=ka[h]||ka._default,g.innerHTML=i[1]+r.htmlPrefilter(f)+i[2],k=i[0];while(k--)g=g.lastChild;r.merge(m,g.childNodes),g=l.firstChild,g.textContent=""}else m.push(b.createTextNode(f));l.textContent="",n=0;while(f=m[n++])if(d&&r.inArray(f,d)>-1)e&&e.push(f);else if(j=r.contains(f.ownerDocument,f),g=la(l.appendChild(f),"script"),j&&ma(g),c){k=0;while(f=g[k++])ja.test(f.type||"")&&c.push(f)}return l}!function(){var a=d.createDocumentFragment(),b=a.appendChild(d.createElement("div")),c=d.createElement("input");c.setAttribute("type","radio"),c.setAttribute("checked","checked"),c.setAttribute("name","t"),b.appendChild(c),o.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,b.innerHTML="",o.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue}();var pa=d.documentElement,qa=/^key/,ra=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,sa=/^([^.]*)(?:\.(.+)|)/;function ta(){return!0}function ua(){return!1}function va(){try{return d.activeElement}catch(a){}}function wa(a,b,c,d,e,f){var g,h;if("object"==typeof b){"string"!=typeof c&&(d=d||c,c=void 0);for(h in b)wa(a,h,c,d,b[h],f);return a}if(null==d&&null==e?(e=c,d=c=void 0):null==e&&("string"==typeof c?(e=d,d=void 0):(e=d,d=c,c=void 0)),e===!1)e=ua;else if(!e)return a;return 1===f&&(g=e,e=function(a){return r().off(a),g.apply(this,arguments)},e.guid=g.guid||(g.guid=r.guid++)),a.each(function(){r.event.add(this,b,e,d,c)})}r.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,n,o,p,q=V.get(a);if(q){c.handler&&(f=c,c=f.handler,e=f.selector),e&&r.find.matchesSelector(pa,e),c.guid||(c.guid=r.guid++),(i=q.events)||(i=q.events={}),(g=q.handle)||(g=q.handle=function(b){return"undefined"!=typeof r&&r.event.triggered!==b.type?r.event.dispatch.apply(a,arguments):void 0}),b=(b||"").match(K)||[""],j=b.length;while(j--)h=sa.exec(b[j])||[],n=p=h[1],o=(h[2]||"").split(".").sort(),n&&(l=r.event.special[n]||{},n=(e?l.delegateType:l.bindType)||n,l=r.event.special[n]||{},k=r.extend({type:n,origType:p,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&r.expr.match.needsContext.test(e),namespace:o.join(".")},f),(m=i[n])||(m=i[n]=[],m.delegateCount=0,l.setup&&l.setup.call(a,d,o,g)!==!1||a.addEventListener&&a.addEventListener(n,g)),l.add&&(l.add.call(a,k),k.handler.guid||(k.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,k):m.push(k),r.event.global[n]=!0)}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,n,o,p,q=V.hasData(a)&&V.get(a);if(q&&(i=q.events)){b=(b||"").match(K)||[""],j=b.length;while(j--)if(h=sa.exec(b[j])||[],n=p=h[1],o=(h[2]||"").split(".").sort(),n){l=r.event.special[n]||{},n=(d?l.delegateType:l.bindType)||n,m=i[n]||[],h=h[2]&&new RegExp("(^|\\.)"+o.join("\\.(?:.*\\.|)")+"(\\.|$)"),g=f=m.length;while(f--)k=m[f],!e&&p!==k.origType||c&&c.guid!==k.guid||h&&!h.test(k.namespace)||d&&d!==k.selector&&("**"!==d||!k.selector)||(m.splice(f,1),k.selector&&m.delegateCount--,l.remove&&l.remove.call(a,k));g&&!m.length&&(l.teardown&&l.teardown.call(a,o,q.handle)!==!1||r.removeEvent(a,n,q.handle),delete i[n])}else for(n in i)r.event.remove(a,n+b[j],c,d,!0);r.isEmptyObject(i)&&V.remove(a,"handle events")}},dispatch:function(a){var b=r.event.fix(a),c,d,e,f,g,h,i=new Array(arguments.length),j=(V.get(this,"events")||{})[b.type]||[],k=r.event.special[b.type]||{};for(i[0]=b,c=1;cc;c++)f=b[c],e=f.selector+" ",void 0===d[e]&&(d[e]=f.needsContext?r(e,this).index(i)>-1:r.find(e,this,null,[i]).length),d[e]&&d.push(f);d.length&&g.push({elem:i,handlers:d})}return h\x20\t\r\n\f]*)[^>]*)\/>/gi,ya=/\s*$/g;function Ca(a,b){return r.nodeName(a,"table")&&r.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a:a}function Da(a){return a.type=(null!==a.getAttribute("type"))+"/"+a.type,a}function Ea(a){var b=Aa.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function Fa(a,b){var c,d,e,f,g,h,i,j;if(1===b.nodeType){if(V.hasData(a)&&(f=V.access(a),g=V.set(b,f),j=f.events)){delete g.handle,g.events={};for(e in j)for(c=0,d=j[e].length;d>c;c++)r.event.add(b,e,j[e][c])}W.hasData(a)&&(h=W.access(a),i=r.extend({},h),W.set(b,i))}}function Ga(a,b){var c=b.nodeName.toLowerCase();"input"===c&&ha.test(a.type)?b.checked=a.checked:"input"!==c&&"textarea"!==c||(b.defaultValue=a.defaultValue)}function Ha(a,b,c,d){b=g.apply([],b);var e,f,h,i,j,k,l=0,m=a.length,n=m-1,q=b[0],s=r.isFunction(q);if(s||m>1&&"string"==typeof q&&!o.checkClone&&za.test(q))return a.each(function(e){var f=a.eq(e);s&&(b[0]=q.call(this,e,f.html())),Ha(f,b,c,d)});if(m&&(e=oa(b,a[0].ownerDocument,!1,a,d),f=e.firstChild,1===e.childNodes.length&&(e=f),f||d)){for(h=r.map(la(e,"script"),Da),i=h.length;m>l;l++)j=e,l!==n&&(j=r.clone(j,!0,!0),i&&r.merge(h,la(j,"script"))),c.call(a[l],j,l);if(i)for(k=h[h.length-1].ownerDocument,r.map(h,Ea),l=0;i>l;l++)j=h[l],ja.test(j.type||"")&&!V.access(j,"globalEval")&&r.contains(k,j)&&(j.src?r._evalUrl&&r._evalUrl(j.src):p(j.textContent.replace(Ba,""),k))}return a}function Ia(a,b,c){for(var d,e=b?r.filter(b,a):a,f=0;null!=(d=e[f]);f++)c||1!==d.nodeType||r.cleanData(la(d)),d.parentNode&&(c&&r.contains(d.ownerDocument,d)&&ma(la(d,"script")),d.parentNode.removeChild(d));return a}r.extend({htmlPrefilter:function(a){return a.replace(xa,"<$1>")},clone:function(a,b,c){var d,e,f,g,h=a.cloneNode(!0),i=r.contains(a.ownerDocument,a);if(!(o.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||r.isXMLDoc(a)))for(g=la(h),f=la(a),d=0,e=f.length;e>d;d++)Ga(f[d],g[d]);if(b)if(c)for(f=f||la(a),g=g||la(h),d=0,e=f.length;e>d;d++)Fa(f[d],g[d]);else Fa(a,h);return g=la(h,"script"),g.length>0&&ma(g,!i&&la(a,"script")),h},cleanData:function(a){for(var b,c,d,e=r.event.special,f=0;void 0!==(c=a[f]);f++)if(T(c)){if(b=c[V.expando]){if(b.events)for(d in b.events)e[d]?r.event.remove(c,d):r.removeEvent(c,d,b.handle);c[V.expando]=void 0}c[W.expando]&&(c[W.expando]=void 0)}}}),r.fn.extend({detach:function(a){return Ia(this,a,!0)},remove:function(a){return Ia(this,a)},text:function(a){return S(this,function(a){return void 0===a?r.text(this):this.empty().each(function(){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||(this.textContent=a)})},null,a,arguments.length)},append:function(){return Ha(this,arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=Ca(this,a);b.appendChild(a)}})},prepend:function(){return Ha(this,arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=Ca(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return Ha(this,arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return Ha(this,arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},empty:function(){for(var a,b=0;null!=(a=this[b]);b++)1===a.nodeType&&(r.cleanData(la(a,!1)),a.textContent="");return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return r.clone(this,a,b)})},html:function(a){return S(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a&&1===b.nodeType)return b.innerHTML;if("string"==typeof a&&!ya.test(a)&&!ka[(ia.exec(a)||["",""])[1].toLowerCase()]){a=r.htmlPrefilter(a);try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(r.cleanData(la(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=[];return Ha(this,arguments,function(b){var c=this.parentNode;r.inArray(this,a)<0&&(r.cleanData(la(this)),c&&c.replaceChild(b,this))},a)}}),r.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){r.fn[a]=function(a){for(var c,d=[],e=r(a),f=e.length-1,g=0;f>=g;g++)c=g===f?this:this.clone(!0),r(e[g])[b](c),h.apply(d,c.get());return this.pushStack(d)}});var Ja=/^margin/,Ka=new RegExp("^("+$+")(?!px)[a-z%]+$","i"),La=function(b){var c=b.ownerDocument.defaultView;return c&&c.opener||(c=a),c.getComputedStyle(b)};!function(){function b(){if(i){i.style.cssText="box-sizing:border-box;position:relative;display:block;margin:auto;border:1px;padding:1px;top:1%;width:50%",i.innerHTML="",pa.appendChild(h);var b=a.getComputedStyle(i);c="1%"!==b.top,g="2px"===b.marginLeft,e="4px"===b.width,i.style.marginRight="50%",f="4px"===b.marginRight,pa.removeChild(h),i=null}}var c,e,f,g,h=d.createElement("div"),i=d.createElement("div");i.style&&(i.style.backgroundClip="content-box",i.cloneNode(!0).style.backgroundClip="",o.clearCloneStyle="content-box"===i.style.backgroundClip,h.style.cssText="border:0;width:8px;height:0;top:0;left:-9999px;padding:0;margin-top:1px;position:absolute",h.appendChild(i),r.extend(o,{pixelPosition:function(){return b(),c},boxSizingReliable:function(){return b(),e},pixelMarginRight:function(){return b(),f},reliableMarginLeft:function(){return b(),g}}))}();function Ma(a,b,c){var d,e,f,g,h=a.style;return c=c||La(a),c&&(g=c.getPropertyValue(b)||c[b],""!==g||r.contains(a.ownerDocument,a)||(g=r.style(a,b)),!o.pixelMarginRight()&&Ka.test(g)&&Ja.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f)),void 0!==g?g+"":g}function Na(a,b){return{get:function(){return a()?void delete this.get:(this.get=b).apply(this,arguments)}}}var Oa=/^(none|table(?!-c[ea]).+)/,Pa={position:"absolute",visibility:"hidden",display:"block"},Qa={letterSpacing:"0",fontWeight:"400"},Ra=["Webkit","Moz","ms"],Sa=d.createElement("div").style;function Ta(a){if(a in Sa)return a;var b=a[0].toUpperCase()+a.slice(1),c=Ra.length;while(c--)if(a=Ra[c]+b,a in Sa)return a}function Ua(a,b,c){var d=_.exec(b);return d?Math.max(0,d[2]-(c||0))+(d[3]||"px"):b}function Va(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=r.css(a,c+aa[f],!0,e)),d?("content"===c&&(g-=r.css(a,"padding"+aa[f],!0,e)),"margin"!==c&&(g-=r.css(a,"border"+aa[f]+"Width",!0,e))):(g+=r.css(a,"padding"+aa[f],!0,e),"padding"!==c&&(g+=r.css(a,"border"+aa[f]+"Width",!0,e)));return g}function Wa(a,b,c){var d,e=!0,f=La(a),g="border-box"===r.css(a,"boxSizing",!1,f);if(a.getClientRects().length&&(d=a.getBoundingClientRect()[b]),0>=d||null==d){if(d=Ma(a,b,f),(0>d||null==d)&&(d=a.style[b]),Ka.test(d))return d;e=g&&(o.boxSizingReliable()||d===a.style[b]),d=parseFloat(d)||0}return d+Va(a,b,c||(g?"border":"content"),e,f)+"px"}r.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Ma(a,"opacity");return""===c?"1":c}}}},cssNumber:{animationIterationCount:!0,columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":"cssFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=r.camelCase(b),i=a.style;return b=r.cssProps[h]||(r.cssProps[h]=Ta(h)||h),g=r.cssHooks[b]||r.cssHooks[h],void 0===c?g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b]:(f=typeof c,"string"===f&&(e=_.exec(c))&&e[1]&&(c=da(a,b,e),f="number"),null!=c&&c===c&&("number"===f&&(c+=e&&e[3]||(r.cssNumber[h]?"":"px")),o.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),g&&"set"in g&&void 0===(c=g.set(a,c,d))||(i[b]=c)),void 0)}},css:function(a,b,c,d){var e,f,g,h=r.camelCase(b);return b=r.cssProps[h]||(r.cssProps[h]=Ta(h)||h),g=r.cssHooks[b]||r.cssHooks[h],g&&"get"in g&&(e=g.get(a,!0,c)),void 0===e&&(e=Ma(a,b,d)),"normal"===e&&b in Qa&&(e=Qa[b]),""===c||c?(f=parseFloat(e),c===!0||isFinite(f)?f||0:e):e}}),r.each(["height","width"],function(a,b){r.cssHooks[b]={get:function(a,c,d){return c?!Oa.test(r.css(a,"display"))||a.getClientRects().length&&a.getBoundingClientRect().width?Wa(a,b,d):ca(a,Pa,function(){return Wa(a,b,d)}):void 0},set:function(a,c,d){var e,f=d&&La(a),g=d&&Va(a,b,d,"border-box"===r.css(a,"boxSizing",!1,f),f);return g&&(e=_.exec(c))&&"px"!==(e[3]||"px")&&(a.style[b]=c,c=r.css(a,b)),Ua(a,c,g)}}}),r.cssHooks.marginLeft=Na(o.reliableMarginLeft,function(a,b){return b?(parseFloat(Ma(a,"marginLeft"))||a.getBoundingClientRect().left-ca(a,{marginLeft:0},function(){return a.getBoundingClientRect().left}))+"px":void 0}),r.each({margin:"",padding:"",border:"Width"},function(a,b){r.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+aa[d]+b]=f[d]||f[d-2]||f[0];return e}},Ja.test(a)||(r.cssHooks[a+b].set=Ua)}),r.fn.extend({css:function(a,b){return S(this,function(a,b,c){var d,e,f={},g=0;if(r.isArray(b)){for(d=La(a),e=b.length;e>g;g++)f[b[g]]=r.css(a,b[g],!1,d);return f}return void 0!==c?r.style(a,b,c):r.css(a,b)},a,b,arguments.length>1)}});function Xa(a,b,c,d,e){return new Xa.prototype.init(a,b,c,d,e)}r.Tween=Xa,Xa.prototype={constructor:Xa,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||r.easing._default,this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(r.cssNumber[c]?"":"px")},cur:function(){var a=Xa.propHooks[this.prop];return a&&a.get?a.get(this):Xa.propHooks._default.get(this)},run:function(a){var b,c=Xa.propHooks[this.prop];return this.options.duration?this.pos=b=r.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):this.pos=b=a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):Xa.propHooks._default.set(this),this}},Xa.prototype.init.prototype=Xa.prototype,Xa.propHooks={_default:{get:function(a){var b;return 1!==a.elem.nodeType||null!=a.elem[a.prop]&&null==a.elem.style[a.prop]?a.elem[a.prop]:(b=r.css(a.elem,a.prop,""),b&&"auto"!==b?b:0)},set:function(a){r.fx.step[a.prop]?r.fx.step[a.prop](a):1!==a.elem.nodeType||null==a.elem.style[r.cssProps[a.prop]]&&!r.cssHooks[a.prop]?a.elem[a.prop]=a.now:r.style(a.elem,a.prop,a.now+a.unit)}}},Xa.propHooks.scrollTop=Xa.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},r.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2},_default:"swing"},r.fx=Xa.prototype.init,r.fx.step={};var Ya,Za,$a=/^(?:toggle|show|hide)$/,_a=/queueHooks$/;function ab(){Za&&(a.requestAnimationFrame(ab),r.fx.tick())}function bb(){return a.setTimeout(function(){Ya=void 0}),Ya=r.now()}function cb(a,b){var c,d=0,e={height:a};for(b=b?1:0;4>d;d+=2-b)c=aa[d],e["margin"+c]=e["padding"+c]=a;return b&&(e.opacity=e.width=a),e}function db(a,b,c){for(var d,e=(gb.tweeners[b]||[]).concat(gb.tweeners["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function eb(a,b,c){var d,e,f,g,h,i,j,k,l="width"in b||"height"in b,m=this,n={},o=a.style,p=a.nodeType&&ba(a),q=V.get(a,"fxshow");c.queue||(g=r._queueHooks(a,"fx"),null==g.unqueued&&(g.unqueued=0,h=g.empty.fire,g.empty.fire=function(){g.unqueued||h()}),g.unqueued++,m.always(function(){m.always(function(){g.unqueued--,r.queue(a,"fx").length||g.empty.fire()})}));for(d in b)if(e=b[d],$a.test(e)){if(delete b[d],f=f||"toggle"===e,e===(p?"hide":"show")){if("show"!==e||!q||void 0===q[d])continue;p=!0}n[d]=q&&q[d]||r.style(a,d)}if(i=!r.isEmptyObject(b),i||!r.isEmptyObject(n)){l&&1===a.nodeType&&(c.overflow=[o.overflow,o.overflowX,o.overflowY],j=q&&q.display,null==j&&(j=V.get(a,"display")),k=r.css(a,"display"),"none"===k&&(j?k=j:(ga([a],!0),j=a.style.display||j,k=r.css(a,"display"),ga([a]))),("inline"===k||"inline-block"===k&&null!=j)&&"none"===r.css(a,"float")&&(i||(m.done(function(){o.display=j}),null==j&&(k=o.display,j="none"===k?"":k)),o.display="inline-block")),c.overflow&&(o.overflow="hidden",m.always(function(){o.overflow=c.overflow[0],o.overflowX=c.overflow[1],o.overflowY=c.overflow[2]})),i=!1;for(d in n)i||(q?"hidden"in q&&(p=q.hidden):q=V.access(a,"fxshow",{display:j}),f&&(q.hidden=!p),p&&ga([a],!0),m.done(function(){p||ga([a]),V.remove(a,"fxshow");for(d in n)r.style(a,d,n[d])})),i=db(p?q[d]:0,d,m),d in q||(q[d]=i.start,p&&(i.end=i.start,i.start=0))}}function fb(a,b){var c,d,e,f,g;for(c in a)if(d=r.camelCase(c),e=b[d],f=a[c],r.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=r.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function gb(a,b,c){var d,e,f=0,g=gb.prefilters.length,h=r.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=Ya||bb(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:r.extend({},b),opts:r.extend(!0,{specialEasing:{},easing:r.easing._default},c),originalProperties:b,originalOptions:c,startTime:Ya||bb(),duration:c.duration,tweens:[],createTween:function(b,c){var d=r.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?(h.notifyWith(a,[j,1,0]),h.resolveWith(a,[j,b])):h.rejectWith(a,[j,b]),this}}),k=j.props;for(fb(k,j.opts.specialEasing);g>f;f++)if(d=gb.prefilters[f].call(j,a,k,j.opts))return r.isFunction(d.stop)&&(r._queueHooks(j.elem,j.opts.queue).stop=r.proxy(d.stop,d)),d;return r.map(k,db,j),r.isFunction(j.opts.start)&&j.opts.start.call(a,j),r.fx.timer(r.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}r.Animation=r.extend(gb,{tweeners:{"*":[function(a,b){var c=this.createTween(a,b);return da(c.elem,a,_.exec(b),c),c}]},tweener:function(a,b){r.isFunction(a)?(b=a,a=["*"]):a=a.match(K);for(var c,d=0,e=a.length;e>d;d++)c=a[d],gb.tweeners[c]=gb.tweeners[c]||[],gb.tweeners[c].unshift(b)},prefilters:[eb],prefilter:function(a,b){b?gb.prefilters.unshift(a):gb.prefilters.push(a)}}),r.speed=function(a,b,c){var e=a&&"object"==typeof a?r.extend({},a):{complete:c||!c&&b||r.isFunction(a)&&a,duration:a,easing:c&&b||b&&!r.isFunction(b)&&b};return r.fx.off||d.hidden?e.duration=0:e.duration="number"==typeof e.duration?e.duration:e.duration in r.fx.speeds?r.fx.speeds[e.duration]:r.fx.speeds._default,null!=e.queue&&e.queue!==!0||(e.queue="fx"),e.old=e.complete,e.complete=function(){r.isFunction(e.old)&&e.old.call(this),e.queue&&r.dequeue(this,e.queue)},e},r.fn.extend({fadeTo:function(a,b,c,d){return this.filter(ba).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=r.isEmptyObject(a),f=r.speed(b,c,d),g=function(){var b=gb(this,r.extend({},a),f);(e||V.get(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=r.timers,g=V.get(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&_a.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));!b&&c||r.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=V.get(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=r.timers,g=d?d.length:0;for(c.finish=!0,r.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),r.each(["toggle","show","hide"],function(a,b){var c=r.fn[b];r.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(cb(b,!0),a,d,e)}}),r.each({slideDown:cb("show"),slideUp:cb("hide"),slideToggle:cb("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){r.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),r.timers=[],r.fx.tick=function(){var a,b=0,c=r.timers;for(Ya=r.now();b1)},removeAttr:function(a){return this.each(function(){r.removeAttr(this,a)})}}),r.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(3!==f&&8!==f&&2!==f)return"undefined"==typeof a.getAttribute?r.prop(a,b,c):(1===f&&r.isXMLDoc(a)||(e=r.attrHooks[b.toLowerCase()]||(r.expr.match.bool.test(b)?hb:void 0)),void 0!==c?null===c?void r.removeAttr(a,b):e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:(a.setAttribute(b,c+""),c):e&&"get"in e&&null!==(d=e.get(a,b))?d:(d=r.find.attr(a,b),null==d?void 0:d))},attrHooks:{type:{set:function(a,b){if(!o.radioValue&&"radio"===b&&r.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}},removeAttr:function(a,b){var c,d=0,e=b&&b.match(K);if(e&&1===a.nodeType)while(c=e[d++])a.removeAttribute(c); -}}),hb={set:function(a,b,c){return b===!1?r.removeAttr(a,c):a.setAttribute(c,c),c}},r.each(r.expr.match.bool.source.match(/\w+/g),function(a,b){var c=ib[b]||r.find.attr;ib[b]=function(a,b,d){var e,f,g=b.toLowerCase();return d||(f=ib[g],ib[g]=e,e=null!=c(a,b,d)?g:null,ib[g]=f),e}});var jb=/^(?:input|select|textarea|button)$/i,kb=/^(?:a|area)$/i;r.fn.extend({prop:function(a,b){return S(this,r.prop,a,b,arguments.length>1)},removeProp:function(a){return this.each(function(){delete this[r.propFix[a]||a]})}}),r.extend({prop:function(a,b,c){var d,e,f=a.nodeType;if(3!==f&&8!==f&&2!==f)return 1===f&&r.isXMLDoc(a)||(b=r.propFix[b]||b,e=r.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=r.find.attr(a,"tabindex");return b?parseInt(b,10):jb.test(a.nodeName)||kb.test(a.nodeName)&&a.href?0:-1}}},propFix:{"for":"htmlFor","class":"className"}}),o.optSelected||(r.propHooks.selected={get:function(a){var b=a.parentNode;return b&&b.parentNode&&b.parentNode.selectedIndex,null},set:function(a){var b=a.parentNode;b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex)}}),r.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){r.propFix[this.toLowerCase()]=this});var lb=/[\t\r\n\f]/g;function mb(a){return a.getAttribute&&a.getAttribute("class")||""}r.fn.extend({addClass:function(a){var b,c,d,e,f,g,h,i=0;if(r.isFunction(a))return this.each(function(b){r(this).addClass(a.call(this,b,mb(this)))});if("string"==typeof a&&a){b=a.match(K)||[];while(c=this[i++])if(e=mb(c),d=1===c.nodeType&&(" "+e+" ").replace(lb," ")){g=0;while(f=b[g++])d.indexOf(" "+f+" ")<0&&(d+=f+" ");h=r.trim(d),e!==h&&c.setAttribute("class",h)}}return this},removeClass:function(a){var b,c,d,e,f,g,h,i=0;if(r.isFunction(a))return this.each(function(b){r(this).removeClass(a.call(this,b,mb(this)))});if(!arguments.length)return this.attr("class","");if("string"==typeof a&&a){b=a.match(K)||[];while(c=this[i++])if(e=mb(c),d=1===c.nodeType&&(" "+e+" ").replace(lb," ")){g=0;while(f=b[g++])while(d.indexOf(" "+f+" ")>-1)d=d.replace(" "+f+" "," ");h=r.trim(d),e!==h&&c.setAttribute("class",h)}}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):r.isFunction(a)?this.each(function(c){r(this).toggleClass(a.call(this,c,mb(this),b),b)}):this.each(function(){var b,d,e,f;if("string"===c){d=0,e=r(this),f=a.match(K)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else void 0!==a&&"boolean"!==c||(b=mb(this),b&&V.set(this,"__className__",b),this.setAttribute&&this.setAttribute("class",b||a===!1?"":V.get(this,"__className__")||""))})},hasClass:function(a){var b,c,d=0;b=" "+a+" ";while(c=this[d++])if(1===c.nodeType&&(" "+mb(c)+" ").replace(lb," ").indexOf(b)>-1)return!0;return!1}});var nb=/\r/g,ob=/[\x20\t\r\n\f]+/g;r.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=r.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,r(this).val()):a,null==e?e="":"number"==typeof e?e+="":r.isArray(e)&&(e=r.map(e,function(a){return null==a?"":a+""})),b=r.valHooks[this.type]||r.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=r.valHooks[e.type]||r.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(nb,""):null==c?"":c)}}}),r.extend({valHooks:{option:{get:function(a){var b=r.find.attr(a,"value");return null!=b?b:r.trim(r.text(a)).replace(ob," ")}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],(c.selected||i===e)&&!c.disabled&&(!c.parentNode.disabled||!r.nodeName(c.parentNode,"optgroup"))){if(b=r(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=r.makeArray(b),g=e.length;while(g--)d=e[g],(d.selected=r.inArray(r.valHooks.option.get(d),f)>-1)&&(c=!0);return c||(a.selectedIndex=-1),f}}}}),r.each(["radio","checkbox"],function(){r.valHooks[this]={set:function(a,b){return r.isArray(b)?a.checked=r.inArray(r(a).val(),b)>-1:void 0}},o.checkOn||(r.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var pb=/^(?:focusinfocus|focusoutblur)$/;r.extend(r.event,{trigger:function(b,c,e,f){var g,h,i,j,k,m,n,o=[e||d],p=l.call(b,"type")?b.type:b,q=l.call(b,"namespace")?b.namespace.split("."):[];if(h=i=e=e||d,3!==e.nodeType&&8!==e.nodeType&&!pb.test(p+r.event.triggered)&&(p.indexOf(".")>-1&&(q=p.split("."),p=q.shift(),q.sort()),k=p.indexOf(":")<0&&"on"+p,b=b[r.expando]?b:new r.Event(p,"object"==typeof b&&b),b.isTrigger=f?2:3,b.namespace=q.join("."),b.rnamespace=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=e),c=null==c?[b]:r.makeArray(c,[b]),n=r.event.special[p]||{},f||!n.trigger||n.trigger.apply(e,c)!==!1)){if(!f&&!n.noBubble&&!r.isWindow(e)){for(j=n.delegateType||p,pb.test(j+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),i=h;i===(e.ownerDocument||d)&&o.push(i.defaultView||i.parentWindow||a)}g=0;while((h=o[g++])&&!b.isPropagationStopped())b.type=g>1?j:n.bindType||p,m=(V.get(h,"events")||{})[b.type]&&V.get(h,"handle"),m&&m.apply(h,c),m=k&&h[k],m&&m.apply&&T(h)&&(b.result=m.apply(h,c),b.result===!1&&b.preventDefault());return b.type=p,f||b.isDefaultPrevented()||n._default&&n._default.apply(o.pop(),c)!==!1||!T(e)||k&&r.isFunction(e[p])&&!r.isWindow(e)&&(i=e[k],i&&(e[k]=null),r.event.triggered=p,e[p](),r.event.triggered=void 0,i&&(e[k]=i)),b.result}},simulate:function(a,b,c){var d=r.extend(new r.Event,c,{type:a,isSimulated:!0});r.event.trigger(d,null,b)}}),r.fn.extend({trigger:function(a,b){return this.each(function(){r.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?r.event.trigger(a,b,c,!0):void 0}}),r.each("blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu".split(" "),function(a,b){r.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),r.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}}),o.focusin="onfocusin"in a,o.focusin||r.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){r.event.simulate(b,a.target,r.event.fix(a))};r.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=V.access(d,b);e||d.addEventListener(a,c,!0),V.access(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=V.access(d,b)-1;e?V.access(d,b,e):(d.removeEventListener(a,c,!0),V.remove(d,b))}}});var qb=a.location,rb=r.now(),sb=/\?/;r.parseXML=function(b){var c;if(!b||"string"!=typeof b)return null;try{c=(new a.DOMParser).parseFromString(b,"text/xml")}catch(d){c=void 0}return c&&!c.getElementsByTagName("parsererror").length||r.error("Invalid XML: "+b),c};var tb=/\[\]$/,ub=/\r?\n/g,vb=/^(?:submit|button|image|reset|file)$/i,wb=/^(?:input|select|textarea|keygen)/i;function xb(a,b,c,d){var e;if(r.isArray(b))r.each(b,function(b,e){c||tb.test(a)?d(a,e):xb(a+"["+("object"==typeof e&&null!=e?b:"")+"]",e,c,d)});else if(c||"object"!==r.type(b))d(a,b);else for(e in b)xb(a+"["+e+"]",b[e],c,d)}r.param=function(a,b){var c,d=[],e=function(a,b){var c=r.isFunction(b)?b():b;d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(null==c?"":c)};if(r.isArray(a)||a.jquery&&!r.isPlainObject(a))r.each(a,function(){e(this.name,this.value)});else for(c in a)xb(c,a[c],b,e);return d.join("&")},r.fn.extend({serialize:function(){return r.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=r.prop(this,"elements");return a?r.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!r(this).is(":disabled")&&wb.test(this.nodeName)&&!vb.test(a)&&(this.checked||!ha.test(a))}).map(function(a,b){var c=r(this).val();return null==c?null:r.isArray(c)?r.map(c,function(a){return{name:b.name,value:a.replace(ub,"\r\n")}}):{name:b.name,value:c.replace(ub,"\r\n")}}).get()}});var yb=/%20/g,zb=/#.*$/,Ab=/([?&])_=[^&]*/,Bb=/^(.*?):[ \t]*([^\r\n]*)$/gm,Cb=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Db=/^(?:GET|HEAD)$/,Eb=/^\/\//,Fb={},Gb={},Hb="*/".concat("*"),Ib=d.createElement("a");Ib.href=qb.href;function Jb(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(K)||[];if(r.isFunction(c))while(d=f[e++])"+"===d[0]?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function Kb(a,b,c,d){var e={},f=a===Gb;function g(h){var i;return e[h]=!0,r.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function Lb(a,b){var c,d,e=r.ajaxSettings.flatOptions||{};for(c in b)void 0!==b[c]&&((e[c]?a:d||(d={}))[c]=b[c]);return d&&r.extend(!0,a,d),a}function Mb(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===d&&(d=a.mimeType||b.getResponseHeader("Content-Type"));if(d)for(e in h)if(h[e]&&h[e].test(d)){i.unshift(e);break}if(i[0]in c)f=i[0];else{for(e in c){if(!i[0]||a.converters[e+" "+i[0]]){f=e;break}g||(g=e)}f=f||g}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function Nb(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}r.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:qb.href,type:"GET",isLocal:Cb.test(qb.protocol),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Hb,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/\bxml\b/,html:/\bhtml/,json:/\bjson\b/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":JSON.parse,"text xml":r.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Lb(Lb(a,r.ajaxSettings),b):Lb(r.ajaxSettings,a)},ajaxPrefilter:Jb(Fb),ajaxTransport:Jb(Gb),ajax:function(b,c){"object"==typeof b&&(c=b,b=void 0),c=c||{};var e,f,g,h,i,j,k,l,m,n,o=r.ajaxSetup({},c),p=o.context||o,q=o.context&&(p.nodeType||p.jquery)?r(p):r.event,s=r.Deferred(),t=r.Callbacks("once memory"),u=o.statusCode||{},v={},w={},x="canceled",y={readyState:0,getResponseHeader:function(a){var b;if(k){if(!h){h={};while(b=Bb.exec(g))h[b[1].toLowerCase()]=b[2]}b=h[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return k?g:null},setRequestHeader:function(a,b){return null==k&&(a=w[a.toLowerCase()]=w[a.toLowerCase()]||a,v[a]=b),this},overrideMimeType:function(a){return null==k&&(o.mimeType=a),this},statusCode:function(a){var b;if(a)if(k)y.always(a[y.status]);else for(b in a)u[b]=[u[b],a[b]];return this},abort:function(a){var b=a||x;return e&&e.abort(b),A(0,b),this}};if(s.promise(y),o.url=((b||o.url||qb.href)+"").replace(Eb,qb.protocol+"//"),o.type=c.method||c.type||o.method||o.type,o.dataTypes=(o.dataType||"*").toLowerCase().match(K)||[""],null==o.crossDomain){j=d.createElement("a");try{j.href=o.url,j.href=j.href,o.crossDomain=Ib.protocol+"//"+Ib.host!=j.protocol+"//"+j.host}catch(z){o.crossDomain=!0}}if(o.data&&o.processData&&"string"!=typeof o.data&&(o.data=r.param(o.data,o.traditional)),Kb(Fb,o,c,y),k)return y;l=r.event&&o.global,l&&0===r.active++&&r.event.trigger("ajaxStart"),o.type=o.type.toUpperCase(),o.hasContent=!Db.test(o.type),f=o.url.replace(zb,""),o.hasContent?o.data&&o.processData&&0===(o.contentType||"").indexOf("application/x-www-form-urlencoded")&&(o.data=o.data.replace(yb,"+")):(n=o.url.slice(f.length),o.data&&(f+=(sb.test(f)?"&":"?")+o.data,delete o.data),o.cache===!1&&(f=f.replace(Ab,""),n=(sb.test(f)?"&":"?")+"_="+rb++ +n),o.url=f+n),o.ifModified&&(r.lastModified[f]&&y.setRequestHeader("If-Modified-Since",r.lastModified[f]),r.etag[f]&&y.setRequestHeader("If-None-Match",r.etag[f])),(o.data&&o.hasContent&&o.contentType!==!1||c.contentType)&&y.setRequestHeader("Content-Type",o.contentType),y.setRequestHeader("Accept",o.dataTypes[0]&&o.accepts[o.dataTypes[0]]?o.accepts[o.dataTypes[0]]+("*"!==o.dataTypes[0]?", "+Hb+"; q=0.01":""):o.accepts["*"]);for(m in o.headers)y.setRequestHeader(m,o.headers[m]);if(o.beforeSend&&(o.beforeSend.call(p,y,o)===!1||k))return y.abort();if(x="abort",t.add(o.complete),y.done(o.success),y.fail(o.error),e=Kb(Gb,o,c,y)){if(y.readyState=1,l&&q.trigger("ajaxSend",[y,o]),k)return y;o.async&&o.timeout>0&&(i=a.setTimeout(function(){y.abort("timeout")},o.timeout));try{k=!1,e.send(v,A)}catch(z){if(k)throw z;A(-1,z)}}else A(-1,"No Transport");function A(b,c,d,h){var j,m,n,v,w,x=c;k||(k=!0,i&&a.clearTimeout(i),e=void 0,g=h||"",y.readyState=b>0?4:0,j=b>=200&&300>b||304===b,d&&(v=Mb(o,y,d)),v=Nb(o,v,y,j),j?(o.ifModified&&(w=y.getResponseHeader("Last-Modified"),w&&(r.lastModified[f]=w),w=y.getResponseHeader("etag"),w&&(r.etag[f]=w)),204===b||"HEAD"===o.type?x="nocontent":304===b?x="notmodified":(x=v.state,m=v.data,n=v.error,j=!n)):(n=x,!b&&x||(x="error",0>b&&(b=0))),y.status=b,y.statusText=(c||x)+"",j?s.resolveWith(p,[m,x,y]):s.rejectWith(p,[y,x,n]),y.statusCode(u),u=void 0,l&&q.trigger(j?"ajaxSuccess":"ajaxError",[y,o,j?m:n]),t.fireWith(p,[y,x]),l&&(q.trigger("ajaxComplete",[y,o]),--r.active||r.event.trigger("ajaxStop")))}return y},getJSON:function(a,b,c){return r.get(a,b,c,"json")},getScript:function(a,b){return r.get(a,void 0,b,"script")}}),r.each(["get","post"],function(a,b){r[b]=function(a,c,d,e){return r.isFunction(c)&&(e=e||d,d=c,c=void 0),r.ajax(r.extend({url:a,type:b,dataType:e,data:c,success:d},r.isPlainObject(a)&&a))}}),r._evalUrl=function(a){return r.ajax({url:a,type:"GET",dataType:"script",cache:!0,async:!1,global:!1,"throws":!0})},r.fn.extend({wrapAll:function(a){var b;return this[0]&&(r.isFunction(a)&&(a=a.call(this[0])),b=r(a,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstElementChild)a=a.firstElementChild;return a}).append(this)),this},wrapInner:function(a){return r.isFunction(a)?this.each(function(b){r(this).wrapInner(a.call(this,b))}):this.each(function(){var b=r(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=r.isFunction(a);return this.each(function(c){r(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(a){return this.parent(a).not("body").each(function(){r(this).replaceWith(this.childNodes)}),this}}),r.expr.pseudos.hidden=function(a){return!r.expr.pseudos.visible(a)},r.expr.pseudos.visible=function(a){return!!(a.offsetWidth||a.offsetHeight||a.getClientRects().length)},r.ajaxSettings.xhr=function(){try{return new a.XMLHttpRequest}catch(b){}};var Ob={0:200,1223:204},Pb=r.ajaxSettings.xhr();o.cors=!!Pb&&"withCredentials"in Pb,o.ajax=Pb=!!Pb,r.ajaxTransport(function(b){var c,d;return o.cors||Pb&&!b.crossDomain?{send:function(e,f){var g,h=b.xhr();if(h.open(b.type,b.url,b.async,b.username,b.password),b.xhrFields)for(g in b.xhrFields)h[g]=b.xhrFields[g];b.mimeType&&h.overrideMimeType&&h.overrideMimeType(b.mimeType),b.crossDomain||e["X-Requested-With"]||(e["X-Requested-With"]="XMLHttpRequest");for(g in e)h.setRequestHeader(g,e[g]);c=function(a){return function(){c&&(c=d=h.onload=h.onerror=h.onabort=h.onreadystatechange=null,"abort"===a?h.abort():"error"===a?"number"!=typeof h.status?f(0,"error"):f(h.status,h.statusText):f(Ob[h.status]||h.status,h.statusText,"text"!==(h.responseType||"text")||"string"!=typeof h.responseText?{binary:h.response}:{text:h.responseText},h.getAllResponseHeaders()))}},h.onload=c(),d=h.onerror=c("error"),void 0!==h.onabort?h.onabort=d:h.onreadystatechange=function(){4===h.readyState&&a.setTimeout(function(){c&&d()})},c=c("abort");try{h.send(b.hasContent&&b.data||null)}catch(i){if(c)throw i}},abort:function(){c&&c()}}:void 0}),r.ajaxPrefilter(function(a){a.crossDomain&&(a.contents.script=!1)}),r.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/\b(?:java|ecma)script\b/},converters:{"text script":function(a){return r.globalEval(a),a}}}),r.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET")}),r.ajaxTransport("script",function(a){if(a.crossDomain){var b,c;return{send:function(e,f){b=r("