code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
<?php defined('C5_EXECUTE') or die('Access denied.');
$form = Core::make('helper/form');
$dh = Core::make('helper/date'); /* @var $dh \Concrete\Core\Localization\Service\Date */
/* @var Concrete\Core\Form\Service\Form $form */
?>
<form class="concrete-login-form" method="post" action="<?= URL::to('/login', 'authenticate', $this->getAuthenticationTypeHandle()); ?>">
<div class="form-group row">
<label class="col-sm-3 col-form-label" for="uName">
<?=Config::get('concrete.user.registration.email_registration') ? t('Email Address') : t('User Name'); ?>
</label>
<div class="col-sm-9">
<input name="uName" id="uName" class="form-control" autofocus="autofocus" />
</div>
</div>
<div class="form-group row">
<label class="col-sm-3 col-form-label" for="uPassword">
<?=t('Password'); ?>
</label>
<div class="col-sm-9">
<input name="uPassword" id="uPassword" class="form-control" type="password" />
</div>
</div>
<div class="form-group row">
<label class="col-sm-3 col-form-label" for="uPassword">
</label>
<div class="col-sm-9 text-right">
<a href="<?= URL::to('/login', 'concrete', 'forgot_password'); ?>" class="btn-link"><?= t('Forgot Password'); ?></a>
</div>
</div>
<?php if (Config::get('concrete.session.remember_me.lifetime') > 0) {
?>
<div class="form-group row">
<div class="col-sm-3 col-form-label pt-0"><?=t('Remember Me'); ?></div>
<div class="col-sm-9">
<div class="form-check">
<input class="form-check-input" type="checkbox" id="uMaintainLogin" name="uMaintainLogin" value="1">
<label class="form-check-label form-check-remember-me" for="uMaintainLogin">
<?php echo t('Stay signed in for %s', $dh->describeInterval(Config::get('concrete.session.remember_me.lifetime'))); ?>
</label>
</div>
</div>
</div>
<?php
} ?>
<?php if (isset($locales) && is_array($locales) && count($locales) > 0) {
?>
<div class="form-group">
<label for="USER_LOCALE" class="control-label"><?= t('Language'); ?></label>
<?= $form->select('USER_LOCALE', $locales); ?>
</div>
<?php
} ?>
<div class="form-group row">
<div class="col-sm-12 text-right">
<a href="<?= \URL::to('/'); ?>" class="btn btn-secondary"> <?= t('Cancel'); ?> </a>
<button class="btn btn-primary"><?= t('Sign In'); ?></button>
<?php Core::make('helper/validation/token')->output('login_' . $this->getAuthenticationTypeHandle()); ?>
</div>
</div>
<?php if (Config::get('concrete.user.registration.enabled')) {
?>
<hr/>
<div class="text-center sign-up-container">
<?=t("Don't have an account?"); ?>
<a href="<?=URL::to('/register'); ?>" class="btn-link"><?=t('Sign up'); ?></a>
</div>
<?php
} ?>
</form>
| haeflimi/concrete5 | concrete/authentication/concrete/form.php | PHP | mit | 3,065 |
# -*- encoding : utf-8 -*-
module Cequel
module Record
#
# This class represents a subset of records from a particular table. Record
# sets encapsulate a CQL query, and are constructed using a chained builder
# interface.
#
# The primary mechanism for specifying which rows should be returned by a
# CQL query is by specifying values for one or more primary key columns. A
# record set acts like a deeply-nested hash, where each primary key column
# is a level of nesting. The {#[]} method is used to narrow the result set
# by successive primary key values.
#
# If {#[]} is used successively to specify all of the columns of a primary
# key, the result will be a single {Record} or a {LazyRecordCollection},
# depending on whether multiple values were specified for one of the key
# columns. In either case, the record instances will be unloaded.
#
# Certain methods have behavior that is dependent on which primary keys
# have been specified using {#[]}. In many methods, such as {#[]},
# {#values_at}, {#before}, {#after}, {#from}, {#upto}, and {#in}, the
# *first unscoped primary key column* serves as implicit context for the
# method: the value passed to those methods is an exact or bounding value
# for that column.
#
# CQL does not allow ordering by arbitrary columns; the ordering of a table
# is determined by its clustering column(s). You read records in reverse
# clustering order using {#reverse}.
#
# Record sets are enumerable collections; under the hood, results are
# paginated. This pagination can be made explicit using {#find_in_batches}.
# RecordSets do not store their records in memory; each time {#each} or an
# `Enumerable` method is called, the database is queried.
#
# All `RecordSet` methods are also exposed directly on {Record}
# classes. So, for instance, `Post.limit(10)` or `Post.select(:id, :title)`
# work as expected.
#
# Conversely, you may call any class method of a record class on a record
# set that targets that class. The class method will be executed in the
# context of the record set that the method is called on. See below for
# examples.
#
# @example Model class used for further examples
# class Post
# include Cequel::Record
#
# belongs_to :blog # defines key :blog_subdomain
# key :id, :timeuuid, auto: true
#
# column :title, :text
# column :author_id, :integer, index: true
#
# def self.for_author(author)
# where(:author_id, author.id)
# end
# end
#
# @example A record set scoped to all posts
# Post.all # returns a record set with no scope restrictions
#
# @example The first ten posts
# # returns a ten-element array of loaded posts
# Post.first(10)
#
# # returns a record set scoped to yield the first 10 posts
# Post.limit(10)
#
# @example The posts in the "cassandra" blog
# # returns a record set where blog_subdomain = "cassandra"
# Post['cassandra']
#
# @example The post in the "cassandra" blog with id `params[:id]`
# # returns an unloaded Post instance
# Post['cassandra'][params[:id]]
#
# @example The posts in the "cassandra" blog with ids `id1, id2`
# # returns a LazyRecordCollection containing two unloaded Post instances
# Post['cassandra'].values_at('id1', 'id2')
#
# @example The posts in the "cassandra" blog in descending order of id
# # returns a LazyRecordCollection where blog_subdomain="cassandra" in
# # descending order of creation
# Post['cassandra'].reverse
#
# @example The posts in the "cassandra" blog created in the last week
# # returns a LazyRecordCollection where blog_subdomain="cassandra" and
# the timestamp encoded in the uuid is in the last week. This only works
# for timeuuid clustering columns
# Post['cassandra'].reverse.after(1.week.ago)
#
# @example 10 posts by a given author
# # Scoped to 10 posts where author_id=author.id. Results will not be in
# # a defined order because the partition key is not specified
# Post.for_author(author).limit(10)
#
# @see Scoped
# @see LazyRecordCollection
# @since 1.0.0
#
class RecordSet < SimpleDelegator
extend Util::Forwardable
extend Cequel::Util::HashAccessors
include Enumerable
include BulkWrites
# @private
def self.default_attributes
{scoped_key_values: [], select_columns: []}
end
# @return [Class] the Record class that this collection yields instances
# of
attr_reader :target_class
#
# @param target_class [Class] the Record class that this collection
# yields instances of
# @param attributes [Hash] initial scoping attributes
#
# @api private
#
def initialize(target_class, attributes = {})
attributes = self.class.default_attributes.merge!(attributes)
@target_class, @attributes = target_class, attributes
super(target_class)
end
#
# @return [RecordSet] self
#
def all
self
end
#
# @overload select
#
# @yieldparam record [Record] each record in the record set
# @return [Array] records that pass the test given by the block
#
# @see
# http://ruby-doc.org/core-2.0.0/Enumerable.html#method-i-select
# Enumerable#select
#
# @overload select(*columns)
# Restrict which columns are selected when records are retrieved from
# the database
#
# @param columns [Symbol] column names
# @return [RecordSet] record set with the given column selections
# applied
#
# @see
# http://cassandra.apache.org/doc/cql3/CQL.html#selectStmt
# CQL SELECT documentation
#
# @return [Array,RecordSet]
#
def select(*columns)
return super if block_given?
scoped { |attributes| attributes[:select_columns].concat(columns) }
end
#
# Restrict the number of records that the RecordSet can contain.
#
# @param count [Integer] the maximum number of records to return
# @return [RecordSet] record set with limit applied
#
# @see
# http://cassandra.apache.org/doc/cql3/CQL.html#selectStmt
# CQL SELECT documentation
#
def limit(count)
scoped(row_limit: count)
end
#
# Filter the record set to records containing a given value in an indexed
# column
#
# @overload where(column_name, value)
# @param column_name [Symbol] column for filter
# @param value value to match in given column
# @return [RecordSet] record set with filter applied
# @deprecated
#
# @overload where(column_values)
# @param column_values [Hash] map of key column names to values
# @return [RecordSet] record set with filter applied
#
# @raise [IllegalQuery] if applying filter would generate an impossible
# query
# @raise [ArgumentError] if the specified column is not a column that
# can be filtered on
#
# @note Filtering on a primary key requires also filtering on all prior
# primary keys
# @note Only one secondary index filter can be used in a given query
# @note Secondary index filters cannot be mixed with primary key filters
#
def where(*args)
if args.length == 1
column_filters = args.first.symbolize_keys
elsif args.length == 2
warn "where(column_name, value) is deprecated. Use " \
"where(column_name => value) instead"
column_filters = {args.first.to_sym => args.second}
else
fail ArgumentError,
"wrong number of arguments (#{args.length} for 1..2)"
end
filter_columns(column_filters)
end
#
# @deprecated Use {#[]} instead
#
# Scope to values for one or more primary key columns
#
# @param scoped_key_values values for primary key columns
# @return (see #[])
#
def at(*scoped_key_values)
warn "`at` is deprecated. Use `[]` instead"
traverse(*scoped_key_values)
end
#
# Restrict this record set to a given value for the next unscoped
# primary key column
#
# Record sets can be thought of like deeply-nested hashes, where each
# primary key column is a level of nesting. For instance, if a table
# consists of a single record with primary key `(blog_subdomain,
# permalink) = ("cassandra", "cequel")`, the record set can be thought of
# like so:
#
# ```ruby
# {
# "cassandra" => {
# "cequel" => #<Post blog_subdomain: "cassandra",
# permalink: "cequel", title: "Cequel">
# }
# }
# ```
#
# If `[]` is invoked enough times to specify all primary keys, then an
# unloaded `Record` instance is returned; this is the same behavior you
# would expect from a `Hash`. If only some subset of the primary keys
# have been specified, the result is still a `RecordSet`.
#
# @param primary_key_value value for the first unscoped primary key
# @return [RecordSet] record set with primary key filter applied, if not
# all primary keys are specified
# @return [Record] unloaded record, if all primary keys are specified
#
# @example Partially specified primary key
# Post['cequel'] # returns a RecordSet
#
# @example Fully specified primary key
# Post['cequel']['cassandra'] # returns an unloaded Record
#
# @note Accepting multiple arguments is deprecated behavior. Use
# {#values_at} instead.
#
def [](*primary_key_value)
if primary_key_value.many?
warn "Calling #[] with multiple arguments is deprecated. Use " \
"#values_at"
return values_at(*primary_key_value)
end
primary_key_value = cast_range_key(primary_key_value.first)
scope_and_resolve do |attributes|
attributes[:scoped_key_values] << primary_key_value
end
end
alias_method :/, :[]
#
# Restrict the records in this record set to those containing any of a
# set of values
#
# @param primary_key_values values to match in the next unscoped primary
# key
# @return [RecordSet] record set with primary key scope applied if not
# all primary key columns are specified
# @return [LazyRecordCollection] collection of unloaded records if all
# primary key columns are specified
# @raise IllegalQuery if the scoped key column is neither the last
# partition key column nor the last clustering column
#
# @see #[]
#
def values_at(*primary_key_values)
unless next_unscoped_key_column_valid_for_in_query?
fail IllegalQuery,
"Only the last partition key column and the last clustering " \
"column can match multiple values"
end
primary_key_values = primary_key_values.map(&method(:cast_range_key))
scope_and_resolve do |attributes|
attributes[:scoped_key_values] << primary_key_values
end
end
#
# Return a loaded Record or collection of loaded Records with the
# specified primary key values
#
# Multiple arguments are mapped onto unscoped key columns. To specify
# multiple values for a given key column, use an array.
#
# @param scoped_key_values one or more values for the final primary key
# column
# @return [Record] if a single key is specified, return the loaded
# record at that key
# @return [LazyRecordCollection] if multiple keys are specified, return a
# collection of loaded records at those keys
# @raise [RecordNotFound] if not all the keys correspond to records in
# the table
#
# @example One record with one-column primary key
# # find the blog with subdomain 'cassandra'
# Blog.find('cassandra')
#
# @example Multiple records with one-column primary key
# # find the blogs with subdomain 'cassandra' and 'postgres'
# Blog.find(['cassandra', 'postgres'])
#
# @example One record with two-column primary key
# # find the post instance with blog subdomain 'cassandra' and
# # permalink 'my-post'
# Post.find('cassandra', 'my-post')
#
# @example Multiple records with two-column primary key
# # find the post instances with blog subdomain cassandra and
# # permalinks 'my-post' and 'my-new-post'
# Post.find('cassandra', ['my-post', 'my-new-post']
#
def find(*keys)
return super if block_given?
keys = [keys] if almost_fully_specified? && keys.many?
records = traverse(*keys).assert_fully_specified!.load!
force_array = keys.any? { |value| value.is_a?(Array) }
force_array ? Array.wrap(records) : records
end
#
# Restrict records to ones whose value in the first unscoped primary key
# column are strictly greater than the given start_key.
#
# @param start_key the exclusive lower bound for the key column
# @return [RecordSet] record set with lower bound applied
#
# @see #from
#
def after(start_key)
scoped(lower_bound: bound(true, false, start_key))
end
#
# Restrict records to ones whose value in the first unscoped primary key
# column are strictly less than the given end_key.
#
# @param end_key the exclusive upper bound for the key column
# @return [RecordSet] record set with upper bound applied
#
# @see #upto
#
def before(end_key)
scoped(upper_bound: bound(false, false, end_key))
end
#
# Restrict records to those whose value in the first unscoped primary key
# column are in the given range. Will accept both inclusive ranges
# (`1..5`) and end-exclusive ranges (`1...5`). If you need a range with
# an exclusive start value, use {#after}, which can be combined with
# {#before} or {#from} to create a range.
#
# @param range [Range] range of values for the key column
# @return [RecordSet] record set with range restriction applied
#
# @see #after
# @see #before
# @see #from
# @see #upto
#
def in(range)
scoped(
lower_bound: bound(true, true, range.first),
upper_bound: bound(false, !range.exclude_end?, range.last)
)
end
#
# Restrict records to those whose value in the first unscoped primary key
# column are greater than or equal to the given start key.
#
# @param start_key the inclusive lower bound for values in the key column
# @return [RecordSet] record set with the lower bound applied
#
# @see #after
#
def from(start_key)
unless partition_specified?
fail IllegalQuery,
"Can't construct exclusive range on partition key " \
"#{range_key_name}"
end
scoped(lower_bound: bound(true, true, start_key))
end
#
# Restrict records to those whose value in the first unscoped primary key
# column are less than or equal to the given start key.
#
# @param end_key the inclusive upper bound for values in the key column
# @return [RecordSet] record set with the upper bound applied
#
# @see #before
#
def upto(end_key)
unless partition_specified?
fail IllegalQuery,
"Can't construct exclusive range on partition key " \
"#{range_key_name}"
end
scoped(upper_bound: bound(false, true, end_key))
end
#
# Reverse the order in which records will be returned from the record set
#
# @return [RecordSet] record set with order reversed
#
# @note This method can only be called on record sets whose partition key
# columns are fully specified. See {#[]} for a discussion of partition
# key scoping.
#
def reverse
unless partition_specified?
fail IllegalQuery,
"Can't reverse without scoping to partition key " \
"#{range_key_name}"
end
scoped(reversed: !reversed?)
end
#
# Set the consistency at which to read records into the record set.
#
# @param consistency [Symbol] consistency for reads
# @return [RecordSet] record set tuned to given consistency
#
def consistency(consistency)
scoped(query_consistency: consistency)
end
#
# Set the page_size at which to read records into the record set.
#
# @param page_size [Integer] page_size for reads
# @return [RecordSet] record set tuned to given page_size
#
def page_size(page_size)
scoped(query_page_size: page_size)
end
#
# Set the paging_state at which to read records into the record set.
#
# @param paging_state [String] paging_state for reads
# @return [RecordSet] record set tuned to given paging_state
#
def paging_state(paging_state)
scoped(query_paging_state: paging_state)
end
def next_paging_state
data_set.next_paging_state
end
#
# @overload first
# @return [Record] the first record in this record set
#
# @overload first(count)
# @param count [Integer] how many records to return
# @return [Array] the first `count` records of the record set
#
# @return [Record,Array]
#
def first(count = nil)
count ? limit(count).entries : limit(1).each.first
end
#
# @return [Record] the first record or a new instance
#
def first_or_initialize
first || new
end
#
# @return [Record] the first record
# @raise [RecordNotFound] if the record set is empty
#
def first!
first or fail(RecordNotFound,
"Couldn't find record with keys: #{
scoped_key_attributes.map { |k, v|
"#{k}: #{v}" }.join(', ')}")
end
#
# @overload last
# @return [Record] the last record in this record set
#
# @overload last(count)
# @param count [Integer] how many records to return
# @return [Array] the last `count` records in the record set in
# ascending order
#
# @return [Record,Array]
#
def last(count = nil)
reverse.first(count).tap do |results|
results.reverse! if count
end
end
#
# @return [Integer] the total number of records in this record set
#
def count
data_set.count
end
alias_method :length, :count
alias_method :size, :count
#
# Enumerate over the records in this record set
#
# @yieldparam record [Record] each successive record in the record set
# @return [Enumerator] if no block given
# @return [void]
#
# @see find_each
#
def each(&block)
find_each(&block)
end
#
# Enumerate over the records in this record set, with control over how
# the database is queried
#
# @param (see #find_rows_in_batches)
# @yieldparam (see #each)
# @option (see #find_rows_in_batches)
# @return (see #each)
#
# @see #find_in_batches
#
def find_each(options = {})
return enum_for(:find_each, options) unless block_given?
find_each_row(options) { |row| yield target_class.hydrate(row) }
end
#
# Enumerate over the records in this record set in batches. Note that the
# given batch_size controls the maximum number of records that can be
# returned per query, but no batch is guaranteed to be exactly the given
# `batch_size`
#
# @param (see #find_rows_in_batches)
# @option (see #find_rows_in_batches)
# @yieldparam batch [Array<Record>] batch of records
# @return (see #each)
#
def find_in_batches(options = {})
return enum_for(:find_in_batches, options) unless block_given?
find_rows_in_batches(options) do |rows|
yield rows.map { |row| target_class.hydrate(row) }
end
end
#
# Enumerate over the row data for each record in this record set, without
# hydrating an actual {Record} instance. Useful for operations where
# speed is at a premium.
#
# @param (see #find_rows_in_batches)
# @option (see #find_rows_in_batches)
# @yieldparam row [Hash<Symbol,Object>] a hash of column names to values
# for each row
# @return (see #each)
#
# @see #find_rows_in_batches
#
def find_each_row(options = {}, &block)
return enum_for(:find_each_row, options) unless block
find_rows_in_batches(options) { |rows| rows.each(&block) }
end
#
# Enumerate over batches of row data for the records in this record set.
#
# @param options [Options] options for querying the database
# @option options [Integer] :batch_size (1000) the maximum number of rows
# to return per batch query
# @yieldparam batch [Array<Hash<Symbol,Object>>] a batch of rows
# @return (see #each)
#
# @see #find_each_row
# @see #find_in_batches
#
def find_rows_in_batches(options = {}, &block)
return find_rows_in_single_batch(options, &block) if row_limit
options.assert_valid_keys(:batch_size)
batch_size = options.fetch(:batch_size, 1000)
batch_record_set = base_record_set = limit(batch_size)
more_results = true
while more_results
rows = batch_record_set.find_rows_in_single_batch
yield rows if rows.any?
more_results = rows.length == batch_size
last_row = rows.last
if more_results
find_nested_batches_from(last_row, options, &block)
batch_record_set = base_record_set.next_batch_from(last_row)
end
end
end
#
# @return [Cequel::Metal::DataSet] the data set underlying this record
# set
#
def data_set
@data_set ||= construct_data_set
end
#
# @return [Hash] map of key column names to the values that have been
# specified in this record set
#
def scoped_key_attributes
Hash[scoped_key_columns.map { |col| col.name }.zip(scoped_key_values)]
end
# (see BulkWrites#delete_all)
def delete_all
if partition_specified?
data_set.delete
else
super
end
end
# @private
def assert_fully_specified!
raise ArgumentError,
"Missing key component(s) " \
"#{unscoped_key_names.join(', ')}"
end
def_delegators :entries, :inspect
# @private
def ==(other)
entries == other.to_a
end
# @private
def to_ary
entries
end
protected
attr_reader :attributes
hattr_reader :attributes, :select_columns, :scoped_key_values,
:row_limit, :lower_bound, :upper_bound,
:scoped_indexed_column, :query_consistency,
:query_page_size, :query_paging_state
protected :select_columns, :scoped_key_values, :row_limit, :lower_bound,
:upper_bound, :scoped_indexed_column, :query_consistency,
:query_page_size, :query_paging_state
hattr_inquirer :attributes, :reversed
protected :reversed?
def next_batch_from(row)
range_key_value = row[range_key_name]
if ascends_by?(range_key_column)
after(range_key_value)
else
before(range_key_value)
end
end
def ascends_by?(column)
!descends_by?(column)
end
def descends_by?(column)
column.clustering_column? &&
(reversed? ^ (column.clustering_order == :desc))
end
def find_nested_batches_from(row, options, &block)
return unless next_range_key_column
without_bounds_on(range_key_column)[row[range_key_name]]
.next_batch_from(row)
.find_rows_in_batches(options, &block)
end
# @return [RecordSet] self but without any bounds conditions on
# the specified column.
#
# @private
def without_bounds_on(column)
without_lower_bound_on(column)
.without_upper_bound_on(column)
end
def without_lower_bound_on(column)
if lower_bound && lower_bound.column == column
scoped(lower_bound: nil)
else
self
end
end
def without_upper_bound_on(column)
if upper_bound && upper_bound.column == column
scoped(upper_bound: nil)
else
self
end
end
def find_rows_in_single_batch(options = {})
if options.key?(:batch_size)
fail ArgumentError,
"Can't pass :batch_size argument with a limit in the scope"
else
data_set.entries.tap do |batch|
yield batch if batch.any? && block_given?
end
end
end
def traverse(*keys)
keys.reduce(self) do |record_set, key_value|
if key_value.is_a?(Array)
record_set.values_at(*key_value)
else
record_set[key_value]
end
end
end
def filter_columns(column_values)
return self if column_values.empty?
if column_values.key?(next_unscoped_key_name)
filter_primary_key(column_values.delete(next_unscoped_key_name))
else
filter_secondary_index(*column_values.shift)
end.filter_columns(column_values)
end
def filter_primary_key(value)
if value.is_a?(Range)
self.in(value)
else
scoped do |attributes|
attributes[:scoped_key_values] << cast_next_primary_key(value)
end
end
end
def filter_secondary_index(column_name, value)
column = target_class.reflect_on_column(column_name)
if column.nil?
fail ArgumentError,
"No column #{column_name} configured for #{target_class.name}"
end
if column.key?
missing_column_names = unscoped_key_names.take_while do |key_name|
key_name != column_name
end
fail IllegalQuery,
"Can't scope key column #{column_name} without also scoping " \
"#{missing_column_names.join(', ')}"
end
if scoped_indexed_column
fail IllegalQuery,
"Can't scope by more than one indexed column in the same query"
end
unless column.indexed?
fail ArgumentError,
"Can't scope by non-indexed column #{column_name}"
end
scoped(scoped_indexed_column: {column_name => column.cast(value)})
end
def scoped_key_names
scoped_key_columns.map { |column| column.name }
end
def scoped_key_columns
target_class.key_columns.first(scoped_key_values.length)
end
def unscoped_key_columns
target_class.key_columns.drop(scoped_key_values.length)
end
def unscoped_key_names
unscoped_key_columns.map { |column| column.name }
end
def range_key_column
unscoped_key_columns.first
end
def range_key_name
range_key_column.name
end
def next_unscoped_key_column
unscoped_key_columns.first
end
def next_unscoped_key_name
next_unscoped_key_column.name
end
def next_range_key_column
unscoped_key_columns.second
end
def next_range_key_name
next_range_key_column.try(:name)
end
def fully_specified?
scoped_key_values.length == target_class.key_columns.length
end
def almost_fully_specified?
scoped_key_values.length == target_class.key_columns.length - 1
end
def partition_specified?
scoped_key_values.length >= target_class.partition_key_columns.length
end
def partition_exactly_specified?
scoped_key_values.length == target_class.partition_key_columns.length
end
def multiple_records_specified?
scoped_key_values.any? { |values| values.is_a?(Array) }
end
def next_unscoped_key_column_valid_for_in_query?
next_unscoped_key_column == partition_key_columns.last ||
next_unscoped_key_column == clustering_columns.last
end
def resolve_if_fully_specified
if fully_specified?
if multiple_records_specified?
LazyRecordCollection.new(select_non_collection_columns!)
else
LazyRecordCollection.new(self).first
end
else
self
end
end
def order_by_column
if target_class.clustering_columns.any?
target_class.clustering_columns.first
end
end
def selects_collection_columns?
select_columns.any? do |column_name|
target_class.reflect_on_column(column_name).collection_column?
end
end
def select_non_collection_columns!
if selects_collection_columns?
fail ArgumentError,
"Can't scope by multiple keys when selecting a collection " \
"column."
end
if select_columns.empty?
non_collection_columns = target_class.columns
.reject { |column| column.collection_column? }
.map { |column| column.name }
select(*non_collection_columns)
else
self
end
end
private
def_delegators :target_class, :connection
def_delegator :range_key_column, :cast, :cast_range_key
private :connection, :cast_range_key
def method_missing(method, *args, &block)
target_class.with_scope(self) { super }
end
def construct_data_set
DataSetBuilder.build_for(self)
end
def bound(gt, inclusive, value)
Bound.create(range_key_column, gt, inclusive, value)
end
def load!
fail ArgumentError, "Not all primary key columns have specified values"
end
def scoped(new_attributes = {}, &block)
attributes_copy = Marshal.load(Marshal.dump(attributes))
attributes_copy.merge!(new_attributes)
attributes_copy.tap(&block) if block
RecordSet.new(target_class, attributes_copy)
end
def scope_and_resolve(&block)
scoped(&block).resolve_if_fully_specified
end
def key_attributes_for_each_row
return enum_for(:key_attributes_for_each_row) unless block_given?
select(*key_column_names).find_each do |record|
yield record.key_attributes
end
end
def cast_next_primary_key(value)
if value.is_a?(Array)
value.map { |element| next_unscoped_key_column.cast(element) }
else
next_unscoped_key_column.cast(value)
end
end
end
end
end
| shaqonline/cequel | lib/cequel/record/record_set.rb | Ruby | mit | 31,987 |
#include <gloperate/painter/Camera.h>
#include <cassert>
#include <gloperate/ext-includes-begin.h>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/matrix_inverse.hpp>
#include <gloperate/ext-includes-end.h>
using namespace glm;
namespace gloperate
{
Camera::Camera(const vec3 & eye, const vec3 & center, const vec3 & up)
: m_dirty(false)
, m_autoUpdate(false)
, m_eye(eye)
, m_center(center)
, m_up(up)
, m_fovy(radians(40.f))
, m_aspect(1.f)
, m_zNear(0.1f)
, m_zFar(64.0f)
{
}
Camera::~Camera()
{
}
bool Camera::autoUpdating() const
{
return m_autoUpdate;
}
void Camera::setAutoUpdating(bool autoUpdate)
{
m_autoUpdate = autoUpdate;
if (m_dirty && m_autoUpdate)
{
update();
}
}
void Camera::update() const
{
if (!m_dirty)
return;
invalidateMatrices();
m_dirty = false;
const_cast<Camera*>(this)->changed();
}
const vec3 & Camera::eye() const
{
return m_eye;
}
void Camera::setEye(const vec3 & eye)
{
if (eye == m_eye)
return;
m_eye = eye;
dirty();
}
const vec3 & Camera::center() const
{
return m_center;
}
void Camera::setCenter(const vec3 & center)
{
if (center == m_center)
return;
m_center = center;
dirty();
}
const vec3 & Camera::up() const
{
return m_up;
}
void Camera::setUp(const vec3 & up)
{
if (up == m_up)
return;
m_up = up;
dirty();
}
float Camera::zNear() const
{
return m_zNear;
}
void Camera::setZNear(const float zNear)
{
if (std::abs(zNear - m_zNear) < std::numeric_limits<float>::epsilon())
return;
m_zNear = zNear;
assert(m_zNear > 0.0);
dirty();
}
float Camera::zFar() const
{
return m_zFar;
}
void Camera::setZFar(const float zFar)
{
if (std::abs(zFar - m_zFar) < std::numeric_limits<float>::epsilon())
return;
m_zFar = zFar;
assert(m_zFar > m_zNear);
dirty();
}
float Camera::fovy() const
{
return m_fovy;
}
void Camera::setFovy(const float fovy)
{
if (std::abs(fovy - m_fovy) < std::numeric_limits<float>::epsilon())
return;
m_fovy = fovy;
assert(m_fovy > 0.0);
dirty();
}
float Camera::aspectRatio() const
{
return m_aspect;
}
void Camera::setAspectRatio(float ratio)
{
m_aspect = ratio;
dirty();
}
void Camera::setAspectRatio(const ivec2 & viewport)
{
m_aspect = static_cast<float>(viewport.x) / max(static_cast<float>(viewport.y), 1.f);
dirty();
}
const mat4 & Camera::view() const
{
if (m_dirty)
update();
if (!m_view.isValid())
m_view.setValue(lookAt(m_eye, m_center, m_up));
return m_view.value();
}
const mat4 & Camera::projection() const
{
if (m_dirty)
update();
if (!m_projection.isValid())
m_projection.setValue(perspective(m_fovy, m_aspect, m_zNear, m_zFar));
return m_projection.value();
}
const mat4 & Camera::viewProjection() const
{
if (m_dirty)
update();
if (!m_viewProjection.isValid())
m_viewProjection.setValue(projection() * view());
return m_viewProjection.value();
}
const mat4 & Camera::viewInverted() const
{
if (m_dirty)
update();
if (!m_viewInverted.isValid())
m_viewInverted.setValue(inverse(view()));
return m_viewInverted.value();
}
const mat4 & Camera::projectionInverted() const
{
if (m_dirty)
update();
if (!m_projectionInverted.isValid())
m_projectionInverted.setValue(inverse(projection()));
return m_projectionInverted.value();
}
const mat4 & Camera::viewProjectionInverted() const
{
if (m_dirty)
update();
if (!m_viewProjectionInverted.isValid())
m_viewProjectionInverted.setValue(inverse(viewProjection()));
return m_viewProjectionInverted.value();
}
const mat3 & Camera::normal() const
{
if (m_dirty)
update();
if (!m_normal.isValid())
m_normal.setValue(inverseTranspose(mat3(view())));
return m_normal.value();
}
void Camera::changed()
{
invalidated();
}
void Camera::dirty(bool update)
{
m_dirty = true;
if (update || m_autoUpdate)
this->update();
}
void Camera::invalidateMatrices() const
{
m_view.invalidate();
m_viewInverted.invalidate();
m_projection.invalidate();
m_projectionInverted.invalidate();
m_viewProjection.invalidate();
m_viewProjectionInverted.invalidate();
m_normal.invalidate();
}
} // namespace gloperate
| lanice/gloperate | source/gloperate/source/painter/Camera.cpp | C++ | mit | 4,446 |
<?php
// autoload_namespaces.php @generated by Composer
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
'phpDocumentor' => array($vendorDir . '/phpdocumentor/reflection-docblock/src'),
'Psy\\' => array($vendorDir . '/psy/psysh/src'),
'Psr\\Log\\' => array($vendorDir . '/psr/log'),
'Prophecy\\' => array($vendorDir . '/phpspec/prophecy/src'),
'PhpSpec' => array($vendorDir . '/phpspec/phpspec/src'),
'Mockery' => array($vendorDir . '/mockery/mockery/library'),
'JakubOnderka\\PhpConsoleHighlighter' => array($vendorDir . '/jakub-onderka/php-console-highlighter/src'),
'JakubOnderka\\PhpConsoleColor' => array($vendorDir . '/jakub-onderka/php-console-color/src'),
'Dotenv' => array($vendorDir . '/vlucas/phpdotenv/src'),
'Doctrine\\Common\\Inflector\\' => array($vendorDir . '/doctrine/inflector/lib'),
'Diff' => array($vendorDir . '/phpspec/php-diff/lib'),
'Cron' => array($vendorDir . '/mtdowling/cron-expression/src'),
);
| fypyuhu/raw | vendor/composer/autoload_namespaces.php | PHP | mit | 1,014 |
package main
import (
"fmt"
"log"
"net/http"
"net/url"
"os"
"os/signal"
"syscall"
"github.com/codegangsta/cli"
)
var wslog *log.Logger
// var (
// mirror = flag.String("mirror", "", "Mirror Web Base URL")
// logfile = flag.String("log", "-", "Set log file, default STDOUT")
// upstream = flag.String("upstream", "", "Server base URL, conflict with -mirror")
// address = flag.String("addr", ":5000", "Listen address")
// token = flag.String("token", "1234567890ABCDEFG", "peer and master token should be same")
// cachedir = flag.String("cachedir", "cache", "Cache directory to store big files")
// )
func InitSignal() {
sig := make(chan os.Signal, 10)
signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP)
go func() {
for {
s := <-sig
fmt.Println("Got signal:", s)
if state.IsClosed() {
fmt.Println("Cold close !!!")
os.Exit(1)
}
fmt.Println("Warm close, waiting ...")
go func() {
state.Close()
os.Exit(0)
}()
}
}()
}
func checkErr(er error) {
if er != nil {
log.Fatal(er)
}
}
func createCliApp() *cli.App {
app := cli.NewApp()
app.Name = "minicdn"
app.Usage = "type help for more information"
// global flags
app.Flags = []cli.Flag{
cli.StringFlag{
Name: "token",
Value: "123456",
Usage: "token that verify between master and slave",
},
cli.StringFlag{
Name: "cachedir",
Value: "cache",
Usage: "caeche dir which store big files",
},
}
app.Action = func(c *cli.Context) {
log.Println("Default action")
}
app.Commands = []cli.Command{
{
Name: "master",
Usage: "mater mode",
Flags: []cli.Flag{
cli.StringFlag{
Name: "mirror",
Usage: "mirror http address",
},
cli.StringFlag{
Name: "logfile, l",
Value: "-",
Usage: "log file",
},
cli.StringFlag{
Name: "addr",
Value: ":5000",
Usage: "listen address",
},
},
Action: masterAction,
},
{
Name: "slave",
Usage: "slave mode",
Flags: []cli.Flag{
cli.StringFlag{
Name: "master-addr, m",
Usage: "master listen address",
},
cli.StringFlag{
Name: "addr",
Value: ":5000",
Usage: "listen address",
},
},
Action: slaveAction,
},
}
return app
}
func masterAction(c *cli.Context) {
println("Master mode")
mirror := c.String("mirror")
if mirror == "" {
log.Fatal("mirror option required")
}
if _, err := url.Parse(mirror); err != nil {
log.Fatal(err)
}
logfile := c.String("logfile")
if logfile == "-" || logfile == "" {
wslog = log.New(os.Stderr, "", log.LstdFlags)
} else {
fd, err := os.OpenFile(logfile, os.O_APPEND|os.O_CREATE|os.O_RDWR, 0644)
if err != nil {
log.Fatal(err)
}
wslog = log.New(fd, "", 0)
}
http.HandleFunc(defaultWSURL, NewWsHandler(mirror, wslog))
http.HandleFunc("/", NewFileHandler(true, mirror, c.GlobalString("cachedir")))
http.HandleFunc("/_log", func(w http.ResponseWriter, r *http.Request) {
if logfile == "" || logfile == "-" {
http.Error(w, "Log file not found", 404)
return
}
http.ServeFile(w, r, logfile)
})
listenAddr := c.String("addr")
log.Printf("Listening on %s", listenAddr)
InitSignal()
log.Fatal(http.ListenAndServe(listenAddr, nil))
}
func slaveAction(c *cli.Context) {
cachedir := c.GlobalString("cachedir")
token := c.GlobalString("token")
listenAddr := c.String("addr")
masterAddr := c.String("master-addr")
if _, err := os.Stat(cachedir); os.IsNotExist(err) {
er := os.MkdirAll(cachedir, 0755)
checkErr(er)
}
if err := InitPeer(masterAddr, listenAddr, cachedir, token); err != nil {
log.Fatal(err)
}
log.Printf("Listening on %s", listenAddr)
InitSignal()
log.Fatal(http.ListenAndServe(listenAddr, nil))
}
func main() {
app := createCliApp()
if err := app.Run(os.Args); err != nil {
log.Fatal(err)
}
}
| wxdublin/minicdn | main.go | GO | mit | 3,838 |
'use strict';
angular.module('copayApp.controllers').controller('preferencesBwsUrlController',
function($scope, configService, isMobile, isCordova, go, applicationService ) {
this.isSafari = isMobile.Safari();
this.isCordova = isCordova;
this.error = null;
this.success = null;
var config = configService.getSync();
this.bwsurl = config.bws.url;
this.save = function() {
var opts = {
bws: {
url: this.bwsurl,
}
};
configService.set(opts, function(err) {
if (err) console.log(err);
$scope.$emit('Local/BWSUpdated');
applicationService.restart(true);
go.walletHome();
});
};
});
| xhad/burse | src/js/controllers/preferencesBwsUrl.js | JavaScript | mit | 703 |
import {Aurelia} from 'aurelia-framework';
import * as LogManager from 'aurelia-logging';
let logger = LogManager.getLogger('aurelia-kendoui-plugin');
import {KendoConfigBuilder} from './config-builder';
import 'jquery';
export function configure(aurelia: Aurelia, configCallback?: (builder: KendoConfigBuilder) => void) {
let builder = new KendoConfigBuilder();
if (configCallback !== undefined && typeof(configCallback) === 'function') {
configCallback(builder);
}
// Provide core if nothing was specified
if (builder.resources.length === 0) {
logger.warn('Nothing specified for kendo configuration - using defaults for Kendo Core');
builder.core();
}
// Pull the data off the builder
let resources = builder.resources;
if (builder.useGlobalResources) {
aurelia.globalResources(resources);
}
}
| smccrea/aurelia-kendoui-plugin | src/index.js | JavaScript | mit | 841 |
import forEach from '../util/forEach'
class JSONConverter {
importDocument(doc, json) {
if (!json.nodes) {
throw new Error('Invalid JSON format.')
}
var schema = doc.getSchema()
if (json.schema && schema.name !== json.schema.name) {
throw new Error('Incompatible schema.')
}
// the json should just be an array of nodes
var nodes = json.nodes
// import data in a block with deactivated indexers and listeners
// as the data contains cyclic references which
// cause problems.
doc.import(function(tx) {
forEach(nodes, function(node) {
// overwrite existing nodes
if (tx.get(node.id)) {
tx.delete(node.id)
}
tx.create(node)
})
})
return doc
}
exportDocument(doc) {
var schema = doc.getSchema()
var json = {
schema: {
name: schema.name
},
nodes: {}
}
forEach(doc.getNodes(), function(node) {
if (node._isDocumentNode) {
json.nodes[node.id] = node.toJSON()
}
})
return json
}
}
export default JSONConverter
| andene/substance | model/JSONConverter.js | JavaScript | mit | 1,103 |
# coding=utf-8
"""
The Lists API endpoint
Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/lists/
Schema: https://api.mailchimp.com/schema/3.0/Lists/Instance.json
"""
from __future__ import unicode_literals
from mailchimp3.baseapi import BaseApi
from mailchimp3.entities.listabusereports import ListAbuseReports
from mailchimp3.entities.listactivity import ListActivity
from mailchimp3.entities.listclients import ListClients
from mailchimp3.entities.listgrowthhistory import ListGrowthHistory
from mailchimp3.entities.listinterestcategories import ListInterestCategories
from mailchimp3.entities.listmembers import ListMembers
from mailchimp3.entities.listmergefields import ListMergeFields
from mailchimp3.entities.listsegments import ListSegments
from mailchimp3.entities.listsignupforms import ListSignupForms
from mailchimp3.entities.listwebhooks import ListWebhooks
from mailchimp3.helpers import check_email
class Lists(BaseApi):
"""
A MailChimp list is a powerful and flexible tool that helps you manage your contacts.
"""
def __init__(self, *args, **kwargs):
"""
Initialize the endpoint
"""
super(Lists, self).__init__(*args, **kwargs)
self.endpoint = 'lists'
self.list_id = None
self.abuse_reports = ListAbuseReports(self)
self.activity = ListActivity(self)
self.clients = ListClients(self)
self.growth_history = ListGrowthHistory(self)
self.interest_categories = ListInterestCategories(self)
self.members = ListMembers(self)
self.merge_fields = ListMergeFields(self)
self.segments = ListSegments(self)
self.signup_forms = ListSignupForms(self)
self.webhooks = ListWebhooks(self)
def create(self, data):
"""
Create a new list in your MailChimp account.
:param data: The request body parameters
:type data: :py:class:`dict`
data = {
"name": string*,
"contact": object*
{
"company": string*,
"address1": string*,
"city": string*,
"state": string*,
"zip": string*,
"country": string*
},
"permission_reminder": string*,
"campaign_defaults": object*
{
"from_name": string*,
"from_email": string*,
"subject": string*,
"language": string*
},
"email_type_option": boolean
}
"""
if 'name' not in data:
raise KeyError('The list must have a name')
if 'contact' not in data:
raise KeyError('The list must have a contact')
if 'company' not in data['contact']:
raise KeyError('The list contact must have a company')
if 'address1' not in data['contact']:
raise KeyError('The list contact must have a address1')
if 'city' not in data['contact']:
raise KeyError('The list contact must have a city')
if 'state' not in data['contact']:
raise KeyError('The list contact must have a state')
if 'zip' not in data['contact']:
raise KeyError('The list contact must have a zip')
if 'country' not in data['contact']:
raise KeyError('The list contact must have a country')
if 'permission_reminder' not in data:
raise KeyError('The list must have a permission_reminder')
if 'campaign_defaults' not in data:
raise KeyError('The list must have a campaign_defaults')
if 'from_name' not in data['campaign_defaults']:
raise KeyError('The list campaign_defaults must have a from_name')
if 'from_email' not in data['campaign_defaults']:
raise KeyError('The list campaign_defaults must have a from_email')
check_email(data['campaign_defaults']['from_email'])
if 'subject' not in data['campaign_defaults']:
raise KeyError('The list campaign_defaults must have a subject')
if 'language' not in data['campaign_defaults']:
raise KeyError('The list campaign_defaults must have a language')
if 'email_type_option' not in data:
raise KeyError('The list must have an email_type_option')
if data['email_type_option'] not in [True, False]:
raise TypeError('The list email_type_option must be True or False')
response = self._mc_client._post(url=self._build_path(), data=data)
if response is not None:
self.list_id = response['id']
else:
self.list_id = None
return response
def update_members(self, list_id, data):
"""
Batch subscribe or unsubscribe list members.
Only the members array is required in the request body parameters.
Within the members array, each member requires an email_address
and either a status or status_if_new. The update_existing parameter
will also be considered required to help prevent accidental updates
to existing members and will default to false if not present.
:param list_id: The unique id for the list.
:type list_id: :py:class:`str`
:param data: The request body parameters
:type data: :py:class:`dict`
data = {
"members": array*
[
{
"email_address": string*,
"status": string* (Must be one of 'subscribed', 'unsubscribed', 'cleaned', or 'pending'),
"status_if_new": string* (Must be one of 'subscribed', 'unsubscribed', 'cleaned', or 'pending')
}
],
"update_existing": boolean*
}
"""
self.list_id = list_id
if 'members' not in data:
raise KeyError('The update must have at least one member')
else:
if not len(data['members']) <= 500:
raise ValueError('You may only batch sub/unsub 500 members at a time')
for member in data['members']:
if 'email_address' not in member:
raise KeyError('Each list member must have an email_address')
check_email(member['email_address'])
if 'status' not in member and 'status_if_new' not in member:
raise KeyError('Each list member must have either a status or a status_if_new')
valid_statuses = ['subscribed', 'unsubscribed', 'cleaned', 'pending']
if 'status' in member and member['status'] not in valid_statuses:
raise ValueError('The list member status must be one of "subscribed", "unsubscribed", "cleaned", or '
'"pending"')
if 'status_if_new' in member and member['status_if_new'] not in valid_statuses:
raise ValueError('The list member status_if_new must be one of "subscribed", "unsubscribed", '
'"cleaned", or "pending"')
if 'update_existing' not in data:
data['update_existing'] = False
return self._mc_client._post(url=self._build_path(list_id), data=data)
def all(self, get_all=False, **queryparams):
"""
Get information about all lists in the account.
:param get_all: Should the query get all results
:type get_all: :py:class:`bool`
:param queryparams: The query string parameters
queryparams['fields'] = []
queryparams['exclude_fields'] = []
queryparams['count'] = integer
queryparams['offset'] = integer
queryparams['before_date_created'] = string
queryparams['since_date_created'] = string
queryparams['before_campaign_last_sent'] = string
queryparams['since_campaign_last_sent'] = string
queryparams['email'] = string
queryparams['sort_field'] = string (Must be 'date_created')
queryparams['sort_dir'] = string (Must be one of 'ASC' or 'DESC')
"""
self.list_id = None
if get_all:
return self._iterate(url=self._build_path(), **queryparams)
else:
return self._mc_client._get(url=self._build_path(), **queryparams)
def get(self, list_id, **queryparams):
"""
Get information about a specific list in your MailChimp account.
Results include list members who have signed up but havenโt confirmed
their subscription yet and unsubscribed or cleaned.
:param list_id: The unique id for the list.
:type list_id: :py:class:`str`
:param queryparams: The query string parameters
queryparams['fields'] = []
queryparams['exclude_fields'] = []
"""
self.list_id = list_id
return self._mc_client._get(url=self._build_path(list_id), **queryparams)
def update(self, list_id, data):
"""
Update the settings for a specific list.
:param list_id: The unique id for the list.
:type list_id: :py:class:`str`
:param data: The request body parameters
:type data: :py:class:`dict`
data = {
"name": string*,
"contact": object*
{
"company": string*,
"address1": string*,
"city": string*,
"state": string*,
"zip": string*,
"country": string*
},
"permission_reminder": string*,
"campaign_defaults": object*
{
"from_name": string*,
"from_email": string*,
"subject": string*,
"language": string*
},
"email_type_option": boolean
}
"""
self.list_id = list_id
if 'name' not in data:
raise KeyError('The list must have a name')
if 'contact' not in data:
raise KeyError('The list must have a contact')
if 'company' not in data['contact']:
raise KeyError('The list contact must have a company')
if 'address1' not in data['contact']:
raise KeyError('The list contact must have a address1')
if 'city' not in data['contact']:
raise KeyError('The list contact must have a city')
if 'state' not in data['contact']:
raise KeyError('The list contact must have a state')
if 'zip' not in data['contact']:
raise KeyError('The list contact must have a zip')
if 'country' not in data['contact']:
raise KeyError('The list contact must have a country')
if 'permission_reminder' not in data:
raise KeyError('The list must have a permission_reminder')
if 'campaign_defaults' not in data:
raise KeyError('The list must have a campaign_defaults')
if 'from_name' not in data['campaign_defaults']:
raise KeyError('The list campaign_defaults must have a from_name')
if 'from_email' not in data['campaign_defaults']:
raise KeyError('The list campaign_defaults must have a from_email')
check_email(data['campaign_defaults']['from_email'])
if 'subject' not in data['campaign_defaults']:
raise KeyError('The list campaign_defaults must have a subject')
if 'language' not in data['campaign_defaults']:
raise KeyError('The list campaign_defaults must have a language')
if 'email_type_option' not in data:
raise KeyError('The list must have an email_type_option')
if data['email_type_option'] not in [True, False]:
raise TypeError('The list email_type_option must be True or False')
return self._mc_client._patch(url=self._build_path(list_id), data=data)
def delete(self, list_id):
"""
Delete a list from your MailChimp account. If you delete a list,
youโll lose the list historyโincluding subscriber activity,
unsubscribes, complaints, and bounces. Youโll also lose subscribersโ
email addresses, unless you exported and backed up your list.
:param list_id: The unique id for the list.
:type list_id: :py:class:`str`
"""
self.list_id = list_id
return self._mc_client._delete(url=self._build_path(list_id))
| charlesthk/python-mailchimp | mailchimp3/entities/lists.py | Python | mit | 12,424 |
package main
import (
"flag"
"fmt"
"io"
"log"
"net"
"github.com/dustin/gomemcached"
"github.com/dustin/gomemcached/server"
)
var port *int = flag.Int("port", 11212, "Port on which to listen")
type chanReq struct {
req *gomemcached.MCRequest
res chan *gomemcached.MCResponse
}
type reqHandler struct {
ch chan chanReq
}
func (rh *reqHandler) HandleMessage(w io.Writer, req *gomemcached.MCRequest) *gomemcached.MCResponse {
cr := chanReq{
req,
make(chan *gomemcached.MCResponse),
}
rh.ch <- cr
return <-cr.res
}
func connectionHandler(s net.Conn, h memcached.RequestHandler) {
// Explicitly ignoring errors since they all result in the
// client getting hung up on and many are common.
_ = memcached.HandleIO(s, h)
}
func waitForConnections(ls net.Listener) {
reqChannel := make(chan chanReq)
go RunServer(reqChannel)
handler := &reqHandler{reqChannel}
log.Printf("Listening on port %d", *port)
for {
s, e := ls.Accept()
if e == nil {
log.Printf("Got a connection from %v", s.RemoteAddr())
go connectionHandler(s, handler)
} else {
log.Printf("Error accepting from %s", ls)
}
}
}
func main() {
flag.Parse()
ls, e := net.Listen("tcp", fmt.Sprintf(":%d", *port))
if e != nil {
log.Fatalf("Got an error: %s", e)
}
waitForConnections(ls)
}
| jj-tyro/raftmcd | vendor/github.com/dustin/gomemcached/gocache/gocache.go | GO | mit | 1,299 |
package main
import (
"fmt"
"os"
"github.com/qiniu/qshell/v2/cmd"
)
func main() {
if err := cmd.RootCmd.Execute(); err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
os.Exit(1)
}
}
| qiniu-lab/qshell | main.go | GO | mit | 192 |
/*
* angular-ui-bootstrap
* http://angular-ui.github.io/bootstrap/
* Version: 0.13.3 - 2015-08-09
* License: MIT
*/
angular.module("ui.bootstrap", ["ui.bootstrap.tabs","ui.bootstrap.buttons","ui.bootstrap.dropdown","ui.bootstrap.position","ui.bootstrap.modal","ui.bootstrap.tooltip","ui.bootstrap.bindHtml","ui.bootstrap.collapse","ui.bootstrap.transition"]);
/**
* @ngdoc overview
* @name ui.bootstrap.tabs
*
* @description
* AngularJS version of the tabs directive.
*/
angular.module('ui.bootstrap.tabs', [])
.controller('TabsetController', ['$scope', function TabsetCtrl($scope) {
var ctrl = this,
tabs = ctrl.tabs = $scope.tabs = [];
ctrl.select = function(selectedTab) {
angular.forEach(tabs, function(tab) {
if (tab.active && tab !== selectedTab) {
tab.active = false;
tab.onDeselect();
}
});
selectedTab.active = true;
selectedTab.onSelect();
};
ctrl.addTab = function addTab(tab) {
tabs.push(tab);
// we can't run the select function on the first tab
// since that would select it twice
if (tabs.length === 1 && tab.active !== false) {
tab.active = true;
} else if (tab.active) {
ctrl.select(tab);
}
else {
tab.active = false;
}
};
ctrl.removeTab = function removeTab(tab) {
var index = tabs.indexOf(tab);
//Select a new tab if the tab to be removed is selected and not destroyed
if (tab.active && tabs.length > 1 && !destroyed) {
//If this is the last tab, select the previous tab. else, the next tab.
var newActiveIndex = index == tabs.length - 1 ? index - 1 : index + 1;
ctrl.select(tabs[newActiveIndex]);
}
tabs.splice(index, 1);
};
var destroyed;
$scope.$on('$destroy', function() {
destroyed = true;
});
}])
/**
* @ngdoc directive
* @name ui.bootstrap.tabs.directive:tabset
* @restrict EA
*
* @description
* Tabset is the outer container for the tabs directive
*
* @param {boolean=} vertical Whether or not to use vertical styling for the tabs.
* @param {boolean=} justified Whether or not to use justified styling for the tabs.
*
* @example
<example module="ui.bootstrap">
<file name="index.html">
<tabset>
<tab heading="Tab 1"><b>First</b> Content!</tab>
<tab heading="Tab 2"><i>Second</i> Content!</tab>
</tabset>
<hr />
<tabset vertical="true">
<tab heading="Vertical Tab 1"><b>First</b> Vertical Content!</tab>
<tab heading="Vertical Tab 2"><i>Second</i> Vertical Content!</tab>
</tabset>
<tabset justified="true">
<tab heading="Justified Tab 1"><b>First</b> Justified Content!</tab>
<tab heading="Justified Tab 2"><i>Second</i> Justified Content!</tab>
</tabset>
</file>
</example>
*/
.directive('tabset', function() {
return {
restrict: 'EA',
transclude: true,
replace: true,
scope: {
type: '@'
},
controller: 'TabsetController',
templateUrl: 'template/tabs/tabset.html',
link: function(scope, element, attrs) {
scope.vertical = angular.isDefined(attrs.vertical) ? scope.$parent.$eval(attrs.vertical) : false;
scope.justified = angular.isDefined(attrs.justified) ? scope.$parent.$eval(attrs.justified) : false;
}
};
})
/**
* @ngdoc directive
* @name ui.bootstrap.tabs.directive:tab
* @restrict EA
*
* @param {string=} heading The visible heading, or title, of the tab. Set HTML headings with {@link ui.bootstrap.tabs.directive:tabHeading tabHeading}.
* @param {string=} select An expression to evaluate when the tab is selected.
* @param {boolean=} active A binding, telling whether or not this tab is selected.
* @param {boolean=} disabled A binding, telling whether or not this tab is disabled.
*
* @description
* Creates a tab with a heading and content. Must be placed within a {@link ui.bootstrap.tabs.directive:tabset tabset}.
*
* @example
<example module="ui.bootstrap">
<file name="index.html">
<div ng-controller="TabsDemoCtrl">
<button class="btn btn-small" ng-click="items[0].active = true">
Select item 1, using active binding
</button>
<button class="btn btn-small" ng-click="items[1].disabled = !items[1].disabled">
Enable/disable item 2, using disabled binding
</button>
<br />
<tabset>
<tab heading="Tab 1">First Tab</tab>
<tab select="alertMe()">
<tab-heading><i class="icon-bell"></i> Alert me!</tab-heading>
Second Tab, with alert callback and html heading!
</tab>
<tab ng-repeat="item in items"
heading="{{item.title}}"
disabled="item.disabled"
active="item.active">
{{item.content}}
</tab>
</tabset>
</div>
</file>
<file name="script.js">
function TabsDemoCtrl($scope) {
$scope.items = [
{ title:"Dynamic Title 1", content:"Dynamic Item 0" },
{ title:"Dynamic Title 2", content:"Dynamic Item 1", disabled: true }
];
$scope.alertMe = function() {
setTimeout(function() {
alert("You've selected the alert tab!");
});
};
};
</file>
</example>
*/
/**
* @ngdoc directive
* @name ui.bootstrap.tabs.directive:tabHeading
* @restrict EA
*
* @description
* Creates an HTML heading for a {@link ui.bootstrap.tabs.directive:tab tab}. Must be placed as a child of a tab element.
*
* @example
<example module="ui.bootstrap">
<file name="index.html">
<tabset>
<tab>
<tab-heading><b>HTML</b> in my titles?!</tab-heading>
And some content, too!
</tab>
<tab>
<tab-heading><i class="icon-heart"></i> Icon heading?!?</tab-heading>
That's right.
</tab>
</tabset>
</file>
</example>
*/
.directive('tab', ['$parse', '$log', function($parse, $log) {
return {
require: '^tabset',
restrict: 'EA',
replace: true,
templateUrl: 'template/tabs/tab.html',
transclude: true,
scope: {
active: '=?',
heading: '@',
onSelect: '&select', //This callback is called in contentHeadingTransclude
//once it inserts the tab's content into the dom
onDeselect: '&deselect'
},
controller: function() {
//Empty controller so other directives can require being 'under' a tab
},
link: function(scope, elm, attrs, tabsetCtrl, transclude) {
scope.$watch('active', function(active) {
if (active) {
tabsetCtrl.select(scope);
}
});
scope.disabled = false;
if ( attrs.disable ) {
scope.$parent.$watch($parse(attrs.disable), function(value) {
scope.disabled = !! value;
});
}
// Deprecation support of "disabled" parameter
// fix(tab): IE9 disabled attr renders grey text on enabled tab #2677
// This code is duplicated from the lines above to make it easy to remove once
// the feature has been completely deprecated
if ( attrs.disabled ) {
$log.warn('Use of "disabled" attribute has been deprecated, please use "disable"');
scope.$parent.$watch($parse(attrs.disabled), function(value) {
scope.disabled = !! value;
});
}
scope.select = function() {
if ( !scope.disabled ) {
scope.active = true;
}
};
tabsetCtrl.addTab(scope);
scope.$on('$destroy', function() {
tabsetCtrl.removeTab(scope);
});
//We need to transclude later, once the content container is ready.
//when this link happens, we're inside a tab heading.
scope.$transcludeFn = transclude;
}
};
}])
.directive('tabHeadingTransclude', [function() {
return {
restrict: 'A',
require: '^tab',
link: function(scope, elm, attrs, tabCtrl) {
scope.$watch('headingElement', function updateHeadingElement(heading) {
if (heading) {
elm.html('');
elm.append(heading);
}
});
}
};
}])
.directive('tabContentTransclude', function() {
return {
restrict: 'A',
require: '^tabset',
link: function(scope, elm, attrs) {
var tab = scope.$eval(attrs.tabContentTransclude);
//Now our tab is ready to be transcluded: both the tab heading area
//and the tab content area are loaded. Transclude 'em both.
tab.$transcludeFn(tab.$parent, function(contents) {
angular.forEach(contents, function(node) {
if (isTabHeading(node)) {
//Let tabHeadingTransclude know.
tab.headingElement = node;
} else {
elm.append(node);
}
});
});
}
};
function isTabHeading(node) {
return node.tagName && (
node.hasAttribute('tab-heading') ||
node.hasAttribute('data-tab-heading') ||
node.tagName.toLowerCase() === 'tab-heading' ||
node.tagName.toLowerCase() === 'data-tab-heading'
);
}
})
;
angular.module('ui.bootstrap.buttons', [])
.constant('buttonConfig', {
activeClass: 'active',
toggleEvent: 'click'
})
.controller('ButtonsController', ['buttonConfig', function(buttonConfig) {
this.activeClass = buttonConfig.activeClass || 'active';
this.toggleEvent = buttonConfig.toggleEvent || 'click';
}])
.directive('btnRadio', function () {
return {
require: ['btnRadio', 'ngModel'],
controller: 'ButtonsController',
controllerAs: 'buttons',
link: function (scope, element, attrs, ctrls) {
var buttonsCtrl = ctrls[0], ngModelCtrl = ctrls[1];
//model -> UI
ngModelCtrl.$render = function () {
element.toggleClass(buttonsCtrl.activeClass, angular.equals(ngModelCtrl.$modelValue, scope.$eval(attrs.btnRadio)));
};
//ui->model
element.bind(buttonsCtrl.toggleEvent, function () {
if (attrs.disabled) {
return;
}
var isActive = element.hasClass(buttonsCtrl.activeClass);
if (!isActive || angular.isDefined(attrs.uncheckable)) {
scope.$apply(function () {
ngModelCtrl.$setViewValue(isActive ? null : scope.$eval(attrs.btnRadio));
ngModelCtrl.$render();
});
}
});
}
};
})
.directive('btnCheckbox', function () {
return {
require: ['btnCheckbox', 'ngModel'],
controller: 'ButtonsController',
controllerAs: 'button',
link: function (scope, element, attrs, ctrls) {
var buttonsCtrl = ctrls[0], ngModelCtrl = ctrls[1];
function getTrueValue() {
return getCheckboxValue(attrs.btnCheckboxTrue, true);
}
function getFalseValue() {
return getCheckboxValue(attrs.btnCheckboxFalse, false);
}
function getCheckboxValue(attributeValue, defaultValue) {
var val = scope.$eval(attributeValue);
return angular.isDefined(val) ? val : defaultValue;
}
//model -> UI
ngModelCtrl.$render = function () {
element.toggleClass(buttonsCtrl.activeClass, angular.equals(ngModelCtrl.$modelValue, getTrueValue()));
};
//ui->model
element.bind(buttonsCtrl.toggleEvent, function () {
if (attrs.disabled) {
return;
}
scope.$apply(function () {
ngModelCtrl.$setViewValue(element.hasClass(buttonsCtrl.activeClass) ? getFalseValue() : getTrueValue());
ngModelCtrl.$render();
});
});
}
};
});
angular.module('ui.bootstrap.dropdown', ['ui.bootstrap.position'])
.constant('dropdownConfig', {
openClass: 'open'
})
.service('dropdownService', ['$document', '$rootScope', function($document, $rootScope) {
var openScope = null;
this.open = function( dropdownScope ) {
if ( !openScope ) {
$document.bind('click', closeDropdown);
$document.bind('keydown', keybindFilter);
}
if ( openScope && openScope !== dropdownScope ) {
openScope.isOpen = false;
}
openScope = dropdownScope;
};
this.close = function( dropdownScope ) {
if ( openScope === dropdownScope ) {
openScope = null;
$document.unbind('click', closeDropdown);
$document.unbind('keydown', keybindFilter);
}
};
var closeDropdown = function( evt ) {
// This method may still be called during the same mouse event that
// unbound this event handler. So check openScope before proceeding.
if (!openScope) { return; }
if( evt && openScope.getAutoClose() === 'disabled' ) { return ; }
var toggleElement = openScope.getToggleElement();
if ( evt && toggleElement && toggleElement[0].contains(evt.target) ) {
return;
}
var dropdownElement = openScope.getDropdownElement();
if (evt && openScope.getAutoClose() === 'outsideClick' &&
dropdownElement && dropdownElement[0].contains(evt.target)) {
return;
}
openScope.isOpen = false;
if (!$rootScope.$$phase) {
openScope.$apply();
}
};
var keybindFilter = function( evt ) {
if ( evt.which === 27 ) {
openScope.focusToggleElement();
closeDropdown();
}
else if ( openScope.isKeynavEnabled() && /(38|40)/.test(evt.which) && openScope.isOpen ) {
evt.preventDefault();
evt.stopPropagation();
openScope.focusDropdownEntry(evt.which);
}
};
}])
.controller('DropdownController', ['$scope', '$attrs', '$parse', 'dropdownConfig', 'dropdownService', '$animate', '$position', '$document', '$compile', '$templateRequest', function($scope, $attrs, $parse, dropdownConfig, dropdownService, $animate, $position, $document, $compile, $templateRequest) {
var self = this,
scope = $scope.$new(), // create a child scope so we are not polluting original one
templateScope,
openClass = dropdownConfig.openClass,
getIsOpen,
setIsOpen = angular.noop,
toggleInvoker = $attrs.onToggle ? $parse($attrs.onToggle) : angular.noop,
appendToBody = false,
keynavEnabled =false,
selectedOption = null;
this.init = function( element ) {
self.$element = element;
if ( $attrs.isOpen ) {
getIsOpen = $parse($attrs.isOpen);
setIsOpen = getIsOpen.assign;
$scope.$watch(getIsOpen, function(value) {
scope.isOpen = !!value;
});
}
appendToBody = angular.isDefined($attrs.dropdownAppendToBody);
keynavEnabled = angular.isDefined($attrs.keyboardNav);
if ( appendToBody && self.dropdownMenu ) {
$document.find('body').append( self.dropdownMenu );
element.on('$destroy', function handleDestroyEvent() {
self.dropdownMenu.remove();
});
}
};
this.toggle = function( open ) {
return scope.isOpen = arguments.length ? !!open : !scope.isOpen;
};
// Allow other directives to watch status
this.isOpen = function() {
return scope.isOpen;
};
scope.getToggleElement = function() {
return self.toggleElement;
};
scope.getAutoClose = function() {
return $attrs.autoClose || 'always'; //or 'outsideClick' or 'disabled'
};
scope.getElement = function() {
return self.$element;
};
scope.isKeynavEnabled = function() {
return keynavEnabled;
};
scope.focusDropdownEntry = function(keyCode) {
var elems = self.dropdownMenu ? //If append to body is used.
(angular.element(self.dropdownMenu).find('a')) :
(angular.element(self.$element).find('ul').eq(0).find('a'));
switch (keyCode) {
case (40): {
if ( !angular.isNumber(self.selectedOption)) {
self.selectedOption = 0;
} else {
self.selectedOption = (self.selectedOption === elems.length -1 ?
self.selectedOption :
self.selectedOption + 1);
}
break;
}
case (38): {
if ( !angular.isNumber(self.selectedOption)) {
return;
} else {
self.selectedOption = (self.selectedOption === 0 ?
0 :
self.selectedOption - 1);
}
break;
}
}
elems[self.selectedOption].focus();
};
scope.getDropdownElement = function() {
return self.dropdownMenu;
};
scope.focusToggleElement = function() {
if ( self.toggleElement ) {
self.toggleElement[0].focus();
}
};
scope.$watch('isOpen', function( isOpen, wasOpen ) {
if (appendToBody && self.dropdownMenu) {
var pos = $position.positionElements(self.$element, self.dropdownMenu, 'bottom-left', true);
var css = {
top: pos.top + 'px',
display: isOpen ? 'block' : 'none'
};
var rightalign = self.dropdownMenu.hasClass('dropdown-menu-right');
if (!rightalign) {
css.left = pos.left + 'px';
css.right = 'auto';
} else {
css.left = 'auto';
css.right = (window.innerWidth - (pos.left + self.$element.prop('offsetWidth'))) + 'px';
}
self.dropdownMenu.css(css);
}
$animate[isOpen ? 'addClass' : 'removeClass'](self.$element, openClass).then(function() {
if (angular.isDefined(isOpen) && isOpen !== wasOpen) {
toggleInvoker($scope, { open: !!isOpen });
}
});
if ( isOpen ) {
if (self.dropdownMenuTemplateUrl) {
$templateRequest(self.dropdownMenuTemplateUrl).then(function(tplContent) {
templateScope = scope.$new();
$compile(tplContent.trim())(templateScope, function(dropdownElement) {
var newEl = dropdownElement;
self.dropdownMenu.replaceWith(newEl);
self.dropdownMenu = newEl;
});
});
}
scope.focusToggleElement();
dropdownService.open( scope );
} else {
if (self.dropdownMenuTemplateUrl) {
if (templateScope) {
templateScope.$destroy();
}
var newEl = angular.element('<ul class="dropdown-menu"></ul>');
self.dropdownMenu.replaceWith(newEl);
self.dropdownMenu = newEl;
}
dropdownService.close( scope );
self.selectedOption = null;
}
if (angular.isFunction(setIsOpen)) {
setIsOpen($scope, isOpen);
}
});
$scope.$on('$locationChangeSuccess', function() {
if (scope.getAutoClose() !== 'disabled') {
scope.isOpen = false;
}
});
$scope.$on('$destroy', function() {
scope.$destroy();
});
}])
.directive('dropdown', function() {
return {
controller: 'DropdownController',
link: function(scope, element, attrs, dropdownCtrl) {
dropdownCtrl.init( element );
element.addClass('dropdown');
}
};
})
.directive('dropdownMenu', function() {
return {
restrict: 'AC',
require: '?^dropdown',
link: function(scope, element, attrs, dropdownCtrl) {
if (!dropdownCtrl) {
return;
}
var tplUrl = attrs.templateUrl;
if (tplUrl) {
dropdownCtrl.dropdownMenuTemplateUrl = tplUrl;
}
if (!dropdownCtrl.dropdownMenu) {
dropdownCtrl.dropdownMenu = element;
}
}
};
})
.directive('keyboardNav', function() {
return {
restrict: 'A',
require: '?^dropdown',
link: function (scope, element, attrs, dropdownCtrl) {
element.bind('keydown', function(e) {
if ([38, 40].indexOf(e.which) !== -1) {
e.preventDefault();
e.stopPropagation();
var elems = dropdownCtrl.dropdownMenu.find('a');
switch (e.which) {
case (40): { // Down
if ( !angular.isNumber(dropdownCtrl.selectedOption)) {
dropdownCtrl.selectedOption = 0;
} else {
dropdownCtrl.selectedOption = (dropdownCtrl.selectedOption === elems.length -1 ? dropdownCtrl.selectedOption : dropdownCtrl.selectedOption+1);
}
}
break;
case (38): { // Up
dropdownCtrl.selectedOption = (dropdownCtrl.selectedOption === 0 ? 0 : dropdownCtrl.selectedOption-1);
}
break;
}
elems[dropdownCtrl.selectedOption].focus();
}
});
}
};
})
.directive('dropdownToggle', function() {
return {
require: '?^dropdown',
link: function(scope, element, attrs, dropdownCtrl) {
if ( !dropdownCtrl ) {
return;
}
element.addClass('dropdown-toggle');
dropdownCtrl.toggleElement = element;
var toggleDropdown = function(event) {
event.preventDefault();
if ( !element.hasClass('disabled') && !attrs.disabled ) {
scope.$apply(function() {
dropdownCtrl.toggle();
});
}
};
element.bind('click', toggleDropdown);
// WAI-ARIA
element.attr({ 'aria-haspopup': true, 'aria-expanded': false });
scope.$watch(dropdownCtrl.isOpen, function( isOpen ) {
element.attr('aria-expanded', !!isOpen);
});
scope.$on('$destroy', function() {
element.unbind('click', toggleDropdown);
});
}
};
});
angular.module('ui.bootstrap.position', [])
/**
* A set of utility methods that can be use to retrieve position of DOM elements.
* It is meant to be used where we need to absolute-position DOM elements in
* relation to other, existing elements (this is the case for tooltips, popovers,
* typeahead suggestions etc.).
*/
.factory('$position', ['$document', '$window', function ($document, $window) {
function getStyle(el, cssprop) {
if (el.currentStyle) { //IE
return el.currentStyle[cssprop];
} else if ($window.getComputedStyle) {
return $window.getComputedStyle(el)[cssprop];
}
// finally try and get inline style
return el.style[cssprop];
}
/**
* Checks if a given element is statically positioned
* @param element - raw DOM element
*/
function isStaticPositioned(element) {
return (getStyle(element, 'position') || 'static' ) === 'static';
}
/**
* returns the closest, non-statically positioned parentOffset of a given element
* @param element
*/
var parentOffsetEl = function (element) {
var docDomEl = $document[0];
var offsetParent = element.offsetParent || docDomEl;
while (offsetParent && offsetParent !== docDomEl && isStaticPositioned(offsetParent) ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || docDomEl;
};
return {
/**
* Provides read-only equivalent of jQuery's position function:
* http://api.jquery.com/position/
*/
position: function (element) {
var elBCR = this.offset(element);
var offsetParentBCR = { top: 0, left: 0 };
var offsetParentEl = parentOffsetEl(element[0]);
if (offsetParentEl != $document[0]) {
offsetParentBCR = this.offset(angular.element(offsetParentEl));
offsetParentBCR.top += offsetParentEl.clientTop - offsetParentEl.scrollTop;
offsetParentBCR.left += offsetParentEl.clientLeft - offsetParentEl.scrollLeft;
}
var boundingClientRect = element[0].getBoundingClientRect();
return {
width: boundingClientRect.width || element.prop('offsetWidth'),
height: boundingClientRect.height || element.prop('offsetHeight'),
top: elBCR.top - offsetParentBCR.top,
left: elBCR.left - offsetParentBCR.left
};
},
/**
* Provides read-only equivalent of jQuery's offset function:
* http://api.jquery.com/offset/
*/
offset: function (element) {
var boundingClientRect = element[0].getBoundingClientRect();
return {
width: boundingClientRect.width || element.prop('offsetWidth'),
height: boundingClientRect.height || element.prop('offsetHeight'),
top: boundingClientRect.top + ($window.pageYOffset || $document[0].documentElement.scrollTop),
left: boundingClientRect.left + ($window.pageXOffset || $document[0].documentElement.scrollLeft)
};
},
/**
* Provides coordinates for the targetEl in relation to hostEl
*/
positionElements: function (hostEl, targetEl, positionStr, appendToBody) {
var positionStrParts = positionStr.split('-');
var pos0 = positionStrParts[0], pos1 = positionStrParts[1] || 'center';
var hostElPos,
targetElWidth,
targetElHeight,
targetElPos;
hostElPos = appendToBody ? this.offset(hostEl) : this.position(hostEl);
targetElWidth = targetEl.prop('offsetWidth');
targetElHeight = targetEl.prop('offsetHeight');
var shiftWidth = {
center: function () {
return hostElPos.left + hostElPos.width / 2 - targetElWidth / 2;
},
left: function () {
return hostElPos.left;
},
right: function () {
return hostElPos.left + hostElPos.width;
}
};
var shiftHeight = {
center: function () {
return hostElPos.top + hostElPos.height / 2 - targetElHeight / 2;
},
top: function () {
return hostElPos.top;
},
bottom: function () {
return hostElPos.top + hostElPos.height;
}
};
switch (pos0) {
case 'right':
targetElPos = {
top: shiftHeight[pos1](),
left: shiftWidth[pos0]()
};
break;
case 'left':
targetElPos = {
top: shiftHeight[pos1](),
left: hostElPos.left - targetElWidth
};
break;
case 'bottom':
targetElPos = {
top: shiftHeight[pos0](),
left: shiftWidth[pos1]()
};
break;
default:
targetElPos = {
top: hostElPos.top - targetElHeight,
left: shiftWidth[pos1]()
};
break;
}
return targetElPos;
}
};
}]);
angular.module('ui.bootstrap.modal', [])
/**
* A helper, internal data structure that acts as a map but also allows getting / removing
* elements in the LIFO order
*/
.factory('$$stackedMap', function () {
return {
createNew: function () {
var stack = [];
return {
add: function (key, value) {
stack.push({
key: key,
value: value
});
},
get: function (key) {
for (var i = 0; i < stack.length; i++) {
if (key == stack[i].key) {
return stack[i];
}
}
},
keys: function() {
var keys = [];
for (var i = 0; i < stack.length; i++) {
keys.push(stack[i].key);
}
return keys;
},
top: function () {
return stack[stack.length - 1];
},
remove: function (key) {
var idx = -1;
for (var i = 0; i < stack.length; i++) {
if (key == stack[i].key) {
idx = i;
break;
}
}
return stack.splice(idx, 1)[0];
},
removeTop: function () {
return stack.splice(stack.length - 1, 1)[0];
},
length: function () {
return stack.length;
}
};
}
};
})
/**
* A helper directive for the $modal service. It creates a backdrop element.
*/
.directive('modalBackdrop', [
'$animate', '$injector', '$modalStack',
function ($animate , $injector, $modalStack) {
var $animateCss = null;
if ($injector.has('$animateCss')) {
$animateCss = $injector.get('$animateCss');
}
return {
restrict: 'EA',
replace: true,
templateUrl: 'template/modal/backdrop.html',
compile: function (tElement, tAttrs) {
tElement.addClass(tAttrs.backdropClass);
return linkFn;
}
};
function linkFn(scope, element, attrs) {
if (attrs.modalInClass) {
if ($animateCss) {
$animateCss(element, {
addClass: attrs.modalInClass
}).start();
} else {
$animate.addClass(element, attrs.modalInClass);
}
scope.$on($modalStack.NOW_CLOSING_EVENT, function (e, setIsAsync) {
var done = setIsAsync();
if ($animateCss) {
$animateCss(element, {
removeClass: attrs.modalInClass
}).start().then(done);
} else {
$animate.removeClass(element, attrs.modalInClass).then(done);
}
});
}
}
}])
.directive('modalWindow', [
'$modalStack', '$q', '$animate', '$injector',
function ($modalStack , $q , $animate, $injector) {
var $animateCss = null;
if ($injector.has('$animateCss')) {
$animateCss = $injector.get('$animateCss');
}
return {
restrict: 'EA',
scope: {
index: '@'
},
replace: true,
transclude: true,
templateUrl: function(tElement, tAttrs) {
return tAttrs.templateUrl || 'template/modal/window.html';
},
link: function (scope, element, attrs) {
element.addClass(attrs.windowClass || '');
scope.size = attrs.size;
scope.close = function (evt) {
var modal = $modalStack.getTop();
if (modal && modal.value.backdrop && modal.value.backdrop != 'static' && (evt.target === evt.currentTarget)) {
evt.preventDefault();
evt.stopPropagation();
$modalStack.dismiss(modal.key, 'backdrop click');
}
};
// This property is only added to the scope for the purpose of detecting when this directive is rendered.
// We can detect that by using this property in the template associated with this directive and then use
// {@link Attribute#$observe} on it. For more details please see {@link TableColumnResize}.
scope.$isRendered = true;
// Deferred object that will be resolved when this modal is render.
var modalRenderDeferObj = $q.defer();
// Observe function will be called on next digest cycle after compilation, ensuring that the DOM is ready.
// In order to use this way of finding whether DOM is ready, we need to observe a scope property used in modal's template.
attrs.$observe('modalRender', function (value) {
if (value == 'true') {
modalRenderDeferObj.resolve();
}
});
modalRenderDeferObj.promise.then(function () {
if (attrs.modalInClass) {
if ($animateCss) {
$animateCss(element, {
addClass: attrs.modalInClass
}).start();
} else {
$animate.addClass(element, attrs.modalInClass);
}
scope.$on($modalStack.NOW_CLOSING_EVENT, function (e, setIsAsync) {
var done = setIsAsync();
if ($animateCss) {
$animateCss(element, {
removeClass: attrs.modalInClass
}).start().then(done);
} else {
$animate.removeClass(element, attrs.modalInClass).then(done);
}
});
}
var inputsWithAutofocus = element[0].querySelectorAll('[autofocus]');
/**
* Auto-focusing of a freshly-opened modal element causes any child elements
* with the autofocus attribute to lose focus. This is an issue on touch
* based devices which will show and then hide the onscreen keyboard.
* Attempts to refocus the autofocus element via JavaScript will not reopen
* the onscreen keyboard. Fixed by updated the focusing logic to only autofocus
* the modal element if the modal does not contain an autofocus element.
*/
if (inputsWithAutofocus.length) {
inputsWithAutofocus[0].focus();
} else {
element[0].focus();
}
// Notify {@link $modalStack} that modal is rendered.
var modal = $modalStack.getTop();
if (modal) {
$modalStack.modalRendered(modal.key);
}
});
}
};
}])
.directive('modalAnimationClass', [
function () {
return {
compile: function (tElement, tAttrs) {
if (tAttrs.modalAnimation) {
tElement.addClass(tAttrs.modalAnimationClass);
}
}
};
}])
.directive('modalTransclude', function () {
return {
link: function($scope, $element, $attrs, controller, $transclude) {
$transclude($scope.$parent, function(clone) {
$element.empty();
$element.append(clone);
});
}
};
})
.factory('$modalStack', [
'$animate', '$timeout', '$document', '$compile', '$rootScope',
'$q',
'$injector',
'$$stackedMap',
function ($animate , $timeout , $document , $compile , $rootScope ,
$q,
$injector,
$$stackedMap) {
var $animateCss = null;
if ($injector.has('$animateCss')) {
$animateCss = $injector.get('$animateCss');
}
var OPENED_MODAL_CLASS = 'modal-open';
var backdropDomEl, backdropScope;
var openedWindows = $$stackedMap.createNew();
var $modalStack = {
NOW_CLOSING_EVENT: 'modal.stack.now-closing'
};
//Modal focus behavior
var focusableElementList;
var focusIndex = 0;
var tababbleSelector = 'a[href], area[href], input:not([disabled]), ' +
'button:not([disabled]),select:not([disabled]), textarea:not([disabled]), ' +
'iframe, object, embed, *[tabindex], *[contenteditable=true]';
function backdropIndex() {
var topBackdropIndex = -1;
var opened = openedWindows.keys();
for (var i = 0; i < opened.length; i++) {
if (openedWindows.get(opened[i]).value.backdrop) {
topBackdropIndex = i;
}
}
return topBackdropIndex;
}
$rootScope.$watch(backdropIndex, function(newBackdropIndex) {
if (backdropScope) {
backdropScope.index = newBackdropIndex;
}
});
function removeModalWindow(modalInstance, elementToReceiveFocus) {
var body = $document.find('body').eq(0);
var modalWindow = openedWindows.get(modalInstance).value;
//clean up the stack
openedWindows.remove(modalInstance);
removeAfterAnimate(modalWindow.modalDomEl, modalWindow.modalScope, function() {
body.toggleClass(modalInstance.openedClass || OPENED_MODAL_CLASS, openedWindows.length() > 0);
});
checkRemoveBackdrop();
//move focus to specified element if available, or else to body
if (elementToReceiveFocus && elementToReceiveFocus.focus) {
elementToReceiveFocus.focus();
} else {
body.focus();
}
}
function checkRemoveBackdrop() {
//remove backdrop if no longer needed
if (backdropDomEl && backdropIndex() == -1) {
var backdropScopeRef = backdropScope;
removeAfterAnimate(backdropDomEl, backdropScope, function () {
backdropScopeRef = null;
});
backdropDomEl = undefined;
backdropScope = undefined;
}
}
function removeAfterAnimate(domEl, scope, done) {
var asyncDeferred;
var asyncPromise = null;
var setIsAsync = function () {
if (!asyncDeferred) {
asyncDeferred = $q.defer();
asyncPromise = asyncDeferred.promise;
}
return function asyncDone() {
asyncDeferred.resolve();
};
};
scope.$broadcast($modalStack.NOW_CLOSING_EVENT, setIsAsync);
// Note that it's intentional that asyncPromise might be null.
// That's when setIsAsync has not been called during the
// NOW_CLOSING_EVENT broadcast.
return $q.when(asyncPromise).then(afterAnimating);
function afterAnimating() {
if (afterAnimating.done) {
return;
}
afterAnimating.done = true;
if ($animateCss) {
$animateCss(domEl, {
event: 'leave'
}).start().then(function() {
domEl.remove();
});
} else {
$animate.leave(domEl);
}
scope.$destroy();
if (done) {
done();
}
}
}
$document.bind('keydown', function (evt) {
if (evt.isDefaultPrevented()) {
return evt;
}
var modal = openedWindows.top();
if (modal && modal.value.keyboard) {
switch (evt.which){
case 27: {
evt.preventDefault();
$rootScope.$apply(function () {
$modalStack.dismiss(modal.key, 'escape key press');
});
break;
}
case 9: {
$modalStack.loadFocusElementList(modal);
var focusChanged = false;
if (evt.shiftKey) {
if ($modalStack.isFocusInFirstItem(evt)) {
focusChanged = $modalStack.focusLastFocusableElement();
}
} else {
if ($modalStack.isFocusInLastItem(evt)) {
focusChanged = $modalStack.focusFirstFocusableElement();
}
}
if (focusChanged) {
evt.preventDefault();
evt.stopPropagation();
}
break;
}
}
}
});
$modalStack.open = function (modalInstance, modal) {
var modalOpener = $document[0].activeElement;
openedWindows.add(modalInstance, {
deferred: modal.deferred,
renderDeferred: modal.renderDeferred,
modalScope: modal.scope,
backdrop: modal.backdrop,
keyboard: modal.keyboard,
openedClass: modal.openedClass
});
var body = $document.find('body').eq(0),
currBackdropIndex = backdropIndex();
if (currBackdropIndex >= 0 && !backdropDomEl) {
backdropScope = $rootScope.$new(true);
backdropScope.index = currBackdropIndex;
var angularBackgroundDomEl = angular.element('<div modal-backdrop="modal-backdrop"></div>');
angularBackgroundDomEl.attr('backdrop-class', modal.backdropClass);
if (modal.animation) {
angularBackgroundDomEl.attr('modal-animation', 'true');
}
backdropDomEl = $compile(angularBackgroundDomEl)(backdropScope);
body.append(backdropDomEl);
}
var angularDomEl = angular.element('<div modal-window="modal-window"></div>');
angularDomEl.attr({
'template-url': modal.windowTemplateUrl,
'window-class': modal.windowClass,
'size': modal.size,
'index': openedWindows.length() - 1,
'animate': 'animate'
}).html(modal.content);
if (modal.animation) {
angularDomEl.attr('modal-animation', 'true');
}
var modalDomEl = $compile(angularDomEl)(modal.scope);
openedWindows.top().value.modalDomEl = modalDomEl;
openedWindows.top().value.modalOpener = modalOpener;
body.append(modalDomEl);
body.addClass(modal.openedClass || OPENED_MODAL_CLASS);
$modalStack.clearFocusListCache();
};
function broadcastClosing(modalWindow, resultOrReason, closing) {
return !modalWindow.value.modalScope.$broadcast('modal.closing', resultOrReason, closing).defaultPrevented;
}
$modalStack.close = function (modalInstance, result) {
var modalWindow = openedWindows.get(modalInstance);
if (modalWindow && broadcastClosing(modalWindow, result, true)) {
modalWindow.value.modalScope.$$uibDestructionScheduled = true;
modalWindow.value.deferred.resolve(result);
removeModalWindow(modalInstance, modalWindow.value.modalOpener);
return true;
}
return !modalWindow;
};
$modalStack.dismiss = function (modalInstance, reason) {
var modalWindow = openedWindows.get(modalInstance);
if (modalWindow && broadcastClosing(modalWindow, reason, false)) {
modalWindow.value.modalScope.$$uibDestructionScheduled = true;
modalWindow.value.deferred.reject(reason);
removeModalWindow(modalInstance, modalWindow.value.modalOpener);
return true;
}
return !modalWindow;
};
$modalStack.dismissAll = function (reason) {
var topModal = this.getTop();
while (topModal && this.dismiss(topModal.key, reason)) {
topModal = this.getTop();
}
};
$modalStack.getTop = function () {
return openedWindows.top();
};
$modalStack.modalRendered = function (modalInstance) {
var modalWindow = openedWindows.get(modalInstance);
if (modalWindow) {
modalWindow.value.renderDeferred.resolve();
}
};
$modalStack.focusFirstFocusableElement = function() {
if (focusableElementList.length > 0) {
focusableElementList[0].focus();
return true;
}
return false;
};
$modalStack.focusLastFocusableElement = function() {
if (focusableElementList.length > 0) {
focusableElementList[focusableElementList.length - 1].focus();
return true;
}
return false;
};
$modalStack.isFocusInFirstItem = function(evt) {
if (focusableElementList.length > 0) {
return (evt.target || evt.srcElement) == focusableElementList[0];
}
return false;
};
$modalStack.isFocusInLastItem = function(evt) {
if (focusableElementList.length > 0) {
return (evt.target || evt.srcElement) == focusableElementList[focusableElementList.length - 1];
}
return false;
};
$modalStack.clearFocusListCache = function() {
focusableElementList = [];
focusIndex = 0;
};
$modalStack.loadFocusElementList = function(modalWindow) {
if (focusableElementList === undefined || !focusableElementList.length0) {
if (modalWindow) {
var modalDomE1 = modalWindow.value.modalDomEl;
if (modalDomE1 && modalDomE1.length) {
focusableElementList = modalDomE1[0].querySelectorAll(tababbleSelector);
}
}
}
};
return $modalStack;
}])
.provider('$modal', function () {
var $modalProvider = {
options: {
animation: true,
backdrop: true, //can also be false or 'static'
keyboard: true
},
$get: ['$injector', '$rootScope', '$q', '$templateRequest', '$controller', '$modalStack',
function ($injector, $rootScope, $q, $templateRequest, $controller, $modalStack) {
var $modal = {};
function getTemplatePromise(options) {
return options.template ? $q.when(options.template) :
$templateRequest(angular.isFunction(options.templateUrl) ? (options.templateUrl)() : options.templateUrl);
}
function getResolvePromises(resolves) {
var promisesArr = [];
angular.forEach(resolves, function (value) {
if (angular.isFunction(value) || angular.isArray(value)) {
promisesArr.push($q.when($injector.invoke(value)));
} else if (angular.isString(value)) {
promisesArr.push($q.when($injector.get(value)));
}
});
return promisesArr;
}
$modal.open = function (modalOptions) {
var modalResultDeferred = $q.defer();
var modalOpenedDeferred = $q.defer();
var modalRenderDeferred = $q.defer();
//prepare an instance of a modal to be injected into controllers and returned to a caller
var modalInstance = {
result: modalResultDeferred.promise,
opened: modalOpenedDeferred.promise,
rendered: modalRenderDeferred.promise,
close: function (result) {
return $modalStack.close(modalInstance, result);
},
dismiss: function (reason) {
return $modalStack.dismiss(modalInstance, reason);
}
};
//merge and clean up options
modalOptions = angular.extend({}, $modalProvider.options, modalOptions);
modalOptions.resolve = modalOptions.resolve || {};
//verify options
if (!modalOptions.template && !modalOptions.templateUrl) {
throw new Error('One of template or templateUrl options is required.');
}
var templateAndResolvePromise =
$q.all([getTemplatePromise(modalOptions)].concat(getResolvePromises(modalOptions.resolve)));
templateAndResolvePromise.then(function resolveSuccess(tplAndVars) {
var modalScope = (modalOptions.scope || $rootScope).$new();
modalScope.$close = modalInstance.close;
modalScope.$dismiss = modalInstance.dismiss;
modalScope.$on('$destroy', function() {
if (!modalScope.$$uibDestructionScheduled) {
modalScope.$dismiss('$uibUnscheduledDestruction');
}
});
var ctrlInstance, ctrlLocals = {};
var resolveIter = 1;
//controllers
if (modalOptions.controller) {
ctrlLocals.$scope = modalScope;
ctrlLocals.$modalInstance = modalInstance;
angular.forEach(modalOptions.resolve, function (value, key) {
ctrlLocals[key] = tplAndVars[resolveIter++];
});
ctrlInstance = $controller(modalOptions.controller, ctrlLocals);
if (modalOptions.controllerAs) {
if (modalOptions.bindToController) {
angular.extend(ctrlInstance, modalScope);
}
modalScope[modalOptions.controllerAs] = ctrlInstance;
}
}
$modalStack.open(modalInstance, {
scope: modalScope,
deferred: modalResultDeferred,
renderDeferred: modalRenderDeferred,
content: tplAndVars[0],
animation: modalOptions.animation,
backdrop: modalOptions.backdrop,
keyboard: modalOptions.keyboard,
backdropClass: modalOptions.backdropClass,
windowClass: modalOptions.windowClass,
windowTemplateUrl: modalOptions.windowTemplateUrl,
size: modalOptions.size,
openedClass: modalOptions.openedClass
});
}, function resolveError(reason) {
modalResultDeferred.reject(reason);
});
templateAndResolvePromise.then(function () {
modalOpenedDeferred.resolve(true);
}, function (reason) {
modalOpenedDeferred.reject(reason);
});
return modalInstance;
};
return $modal;
}]
};
return $modalProvider;
});
/**
* The following features are still outstanding: animation as a
* function, placement as a function, inside, support for more triggers than
* just mouse enter/leave, html tooltips, and selector delegation.
*/
angular.module( 'ui.bootstrap.tooltip', [ 'ui.bootstrap.position', 'ui.bootstrap.bindHtml' ] )
/**
* The $tooltip service creates tooltip- and popover-like directives as well as
* houses global options for them.
*/
.provider( '$tooltip', function () {
// The default options tooltip and popover.
var defaultOptions = {
placement: 'top',
animation: true,
popupDelay: 0,
useContentExp: false
};
// Default hide triggers for each show trigger
var triggerMap = {
'mouseenter': 'mouseleave',
'click': 'click',
'focus': 'blur'
};
// The options specified to the provider globally.
var globalOptions = {};
/**
* `options({})` allows global configuration of all tooltips in the
* application.
*
* var app = angular.module( 'App', ['ui.bootstrap.tooltip'], function( $tooltipProvider ) {
* // place tooltips left instead of top by default
* $tooltipProvider.options( { placement: 'left' } );
* });
*/
this.options = function( value ) {
angular.extend( globalOptions, value );
};
/**
* This allows you to extend the set of trigger mappings available. E.g.:
*
* $tooltipProvider.setTriggers( 'openTrigger': 'closeTrigger' );
*/
this.setTriggers = function setTriggers ( triggers ) {
angular.extend( triggerMap, triggers );
};
/**
* This is a helper function for translating camel-case to snake-case.
*/
function snake_case(name){
var regexp = /[A-Z]/g;
var separator = '-';
return name.replace(regexp, function(letter, pos) {
return (pos ? separator : '') + letter.toLowerCase();
});
}
/**
* Returns the actual instance of the $tooltip service.
* TODO support multiple triggers
*/
this.$get = [ '$window', '$compile', '$timeout', '$document', '$position', '$interpolate', '$rootScope', function ( $window, $compile, $timeout, $document, $position, $interpolate, $rootScope ) {
return function $tooltip ( type, prefix, defaultTriggerShow, options ) {
options = angular.extend( {}, defaultOptions, globalOptions, options );
/**
* Returns an object of show and hide triggers.
*
* If a trigger is supplied,
* it is used to show the tooltip; otherwise, it will use the `trigger`
* option passed to the `$tooltipProvider.options` method; else it will
* default to the trigger supplied to this directive factory.
*
* The hide trigger is based on the show trigger. If the `trigger` option
* was passed to the `$tooltipProvider.options` method, it will use the
* mapped trigger from `triggerMap` or the passed trigger if the map is
* undefined; otherwise, it uses the `triggerMap` value of the show
* trigger; else it will just use the show trigger.
*/
function getTriggers ( trigger ) {
var show = (trigger || options.trigger || defaultTriggerShow).split(' ');
var hide = show.map(function(trigger) {
return triggerMap[trigger] || trigger;
});
return {
show: show,
hide: hide
};
}
var directiveName = snake_case( type );
var startSym = $interpolate.startSymbol();
var endSym = $interpolate.endSymbol();
var template =
'<div '+ directiveName +'-popup '+
'title="'+startSym+'title'+endSym+'" '+
(options.useContentExp ?
'content-exp="contentExp()" ' :
'content="'+startSym+'content'+endSym+'" ') +
'placement="'+startSym+'placement'+endSym+'" '+
'popup-class="'+startSym+'popupClass'+endSym+'" '+
'animation="animation" '+
'is-open="isOpen"'+
'origin-scope="origScope" '+
'>'+
'</div>';
return {
restrict: 'EA',
compile: function (tElem, tAttrs) {
var tooltipLinker = $compile( template );
return function link ( scope, element, attrs, tooltipCtrl ) {
var tooltip;
var tooltipLinkedScope;
var transitionTimeout;
var popupTimeout;
var appendToBody = angular.isDefined( options.appendToBody ) ? options.appendToBody : false;
var triggers = getTriggers( undefined );
var hasEnableExp = angular.isDefined(attrs[prefix+'Enable']);
var ttScope = scope.$new(true);
var repositionScheduled = false;
var positionTooltip = function () {
if (!tooltip) { return; }
var ttPosition = $position.positionElements(element, tooltip, ttScope.placement, appendToBody);
ttPosition.top += 'px';
ttPosition.left += 'px';
// Now set the calculated positioning.
tooltip.css( ttPosition );
};
var positionTooltipAsync = function () {
$timeout(positionTooltip, 0, false);
};
// Set up the correct scope to allow transclusion later
ttScope.origScope = scope;
// By default, the tooltip is not open.
// TODO add ability to start tooltip opened
ttScope.isOpen = false;
function toggleTooltipBind () {
if ( ! ttScope.isOpen ) {
showTooltipBind();
} else {
hideTooltipBind();
}
}
// Show the tooltip with delay if specified, otherwise show it immediately
function showTooltipBind() {
if(hasEnableExp && !scope.$eval(attrs[prefix+'Enable'])) {
return;
}
prepareTooltip();
if ( ttScope.popupDelay ) {
// Do nothing if the tooltip was already scheduled to pop-up.
// This happens if show is triggered multiple times before any hide is triggered.
if (!popupTimeout) {
popupTimeout = $timeout( show, ttScope.popupDelay, false );
popupTimeout.then(function(reposition){reposition();});
}
} else {
show()();
}
}
function hideTooltipBind () {
hide();
if (!$rootScope.$$phase) {
$rootScope.$digest();
}
}
// Show the tooltip popup element.
function show() {
popupTimeout = null;
// If there is a pending remove transition, we must cancel it, lest the
// tooltip be mysteriously removed.
if ( transitionTimeout ) {
$timeout.cancel( transitionTimeout );
transitionTimeout = null;
}
// Don't show empty tooltips.
if ( !(options.useContentExp ? ttScope.contentExp() : ttScope.content) ) {
return angular.noop;
}
createTooltip();
// Set the initial positioning.
tooltip.css({ top: 0, left: 0, display: 'block' });
positionTooltip();
// And show the tooltip.
ttScope.isOpen = true;
ttScope.$apply(); // digest required as $apply is not called
// Return positioning function as promise callback for correct
// positioning after draw.
return positionTooltip;
}
// Hide the tooltip popup element.
function hide() {
// First things first: we don't show it anymore.
ttScope.isOpen = false;
//if tooltip is going to be shown after delay, we must cancel this
$timeout.cancel( popupTimeout );
popupTimeout = null;
// And now we remove it from the DOM. However, if we have animation, we
// need to wait for it to expire beforehand.
// FIXME: this is a placeholder for a port of the transitions library.
if ( ttScope.animation ) {
if (!transitionTimeout) {
transitionTimeout = $timeout(removeTooltip, 500);
}
} else {
removeTooltip();
}
}
function createTooltip() {
// There can only be one tooltip element per directive shown at once.
if (tooltip) {
removeTooltip();
}
tooltipLinkedScope = ttScope.$new();
tooltip = tooltipLinker(tooltipLinkedScope, function (tooltip) {
if ( appendToBody ) {
$document.find( 'body' ).append( tooltip );
} else {
element.after( tooltip );
}
});
if (options.useContentExp) {
tooltipLinkedScope.$watch('contentExp()', function (val) {
if (!val && ttScope.isOpen) {
hide();
}
});
tooltipLinkedScope.$watch(function() {
if (!repositionScheduled) {
repositionScheduled = true;
tooltipLinkedScope.$$postDigest(function() {
repositionScheduled = false;
positionTooltipAsync();
});
}
});
}
}
function removeTooltip() {
transitionTimeout = null;
if (tooltip) {
tooltip.remove();
tooltip = null;
}
if (tooltipLinkedScope) {
tooltipLinkedScope.$destroy();
tooltipLinkedScope = null;
}
}
function prepareTooltip() {
prepPopupClass();
prepPlacement();
prepPopupDelay();
}
ttScope.contentExp = function () {
return scope.$eval(attrs[type]);
};
/**
* Observe the relevant attributes.
*/
if (!options.useContentExp) {
attrs.$observe( type, function ( val ) {
ttScope.content = val;
if (!val && ttScope.isOpen) {
hide();
} else {
positionTooltipAsync();
}
});
}
attrs.$observe( 'disabled', function ( val ) {
if (popupTimeout && val) {
$timeout.cancel(popupTimeout);
}
if (val && ttScope.isOpen ) {
hide();
}
});
attrs.$observe( prefix+'Title', function ( val ) {
ttScope.title = val;
positionTooltipAsync();
});
attrs.$observe( prefix + 'Placement', function () {
if (ttScope.isOpen) {
$timeout(function () {
prepPlacement();
show()();
}, 0, false);
}
});
function prepPopupClass() {
ttScope.popupClass = attrs[prefix + 'Class'];
}
function prepPlacement() {
var val = attrs[ prefix + 'Placement' ];
ttScope.placement = angular.isDefined( val ) ? val : options.placement;
}
function prepPopupDelay() {
var val = attrs[ prefix + 'PopupDelay' ];
var delay = parseInt( val, 10 );
ttScope.popupDelay = ! isNaN(delay) ? delay : options.popupDelay;
}
var unregisterTriggers = function () {
triggers.show.forEach(function(trigger) {
element.unbind(trigger, showTooltipBind);
});
triggers.hide.forEach(function(trigger) {
element.unbind(trigger, hideTooltipBind);
});
};
function prepTriggers() {
var val = attrs[ prefix + 'Trigger' ];
unregisterTriggers();
triggers = getTriggers( val );
triggers.show.forEach(function(trigger, idx) {
if (trigger === triggers.hide[idx]) {
element.bind(trigger, toggleTooltipBind);
} else if (trigger) {
element.bind(trigger, showTooltipBind);
element.bind(triggers.hide[idx], hideTooltipBind);
}
});
}
prepTriggers();
var animation = scope.$eval(attrs[prefix + 'Animation']);
ttScope.animation = angular.isDefined(animation) ? !!animation : options.animation;
var appendToBodyVal = scope.$eval(attrs[prefix + 'AppendToBody']);
appendToBody = angular.isDefined(appendToBodyVal) ? appendToBodyVal : appendToBody;
// if a tooltip is attached to <body> we need to remove it on
// location change as its parent scope will probably not be destroyed
// by the change.
if ( appendToBody ) {
scope.$on('$locationChangeSuccess', function closeTooltipOnLocationChangeSuccess () {
if ( ttScope.isOpen ) {
hide();
}
});
}
// Make sure tooltip is destroyed and removed.
scope.$on('$destroy', function onDestroyTooltip() {
$timeout.cancel( transitionTimeout );
$timeout.cancel( popupTimeout );
unregisterTriggers();
removeTooltip();
ttScope = null;
});
};
}
};
};
}];
})
// This is mostly ngInclude code but with a custom scope
.directive( 'tooltipTemplateTransclude', [
'$animate', '$sce', '$compile', '$templateRequest',
function ($animate , $sce , $compile , $templateRequest) {
return {
link: function ( scope, elem, attrs ) {
var origScope = scope.$eval(attrs.tooltipTemplateTranscludeScope);
var changeCounter = 0,
currentScope,
previousElement,
currentElement;
var cleanupLastIncludeContent = function() {
if (previousElement) {
previousElement.remove();
previousElement = null;
}
if (currentScope) {
currentScope.$destroy();
currentScope = null;
}
if (currentElement) {
$animate.leave(currentElement).then(function() {
previousElement = null;
});
previousElement = currentElement;
currentElement = null;
}
};
scope.$watch($sce.parseAsResourceUrl(attrs.tooltipTemplateTransclude), function (src) {
var thisChangeId = ++changeCounter;
if (src) {
//set the 2nd param to true to ignore the template request error so that the inner
//contents and scope can be cleaned up.
$templateRequest(src, true).then(function(response) {
if (thisChangeId !== changeCounter) { return; }
var newScope = origScope.$new();
var template = response;
var clone = $compile(template)(newScope, function(clone) {
cleanupLastIncludeContent();
$animate.enter(clone, elem);
});
currentScope = newScope;
currentElement = clone;
currentScope.$emit('$includeContentLoaded', src);
}, function() {
if (thisChangeId === changeCounter) {
cleanupLastIncludeContent();
scope.$emit('$includeContentError', src);
}
});
scope.$emit('$includeContentRequested', src);
} else {
cleanupLastIncludeContent();
}
});
scope.$on('$destroy', cleanupLastIncludeContent);
}
};
}])
/**
* Note that it's intentional that these classes are *not* applied through $animate.
* They must not be animated as they're expected to be present on the tooltip on
* initialization.
*/
.directive('tooltipClasses', function () {
return {
restrict: 'A',
link: function (scope, element, attrs) {
if (scope.placement) {
element.addClass(scope.placement);
}
if (scope.popupClass) {
element.addClass(scope.popupClass);
}
if (scope.animation()) {
element.addClass(attrs.tooltipAnimationClass);
}
}
};
})
.directive( 'tooltipPopup', function () {
return {
restrict: 'EA',
replace: true,
scope: { content: '@', placement: '@', popupClass: '@', animation: '&', isOpen: '&' },
templateUrl: 'template/tooltip/tooltip-popup.html'
};
})
.directive( 'tooltip', [ '$tooltip', function ( $tooltip ) {
return $tooltip( 'tooltip', 'tooltip', 'mouseenter' );
}])
.directive( 'tooltipTemplatePopup', function () {
return {
restrict: 'EA',
replace: true,
scope: { contentExp: '&', placement: '@', popupClass: '@', animation: '&', isOpen: '&',
originScope: '&' },
templateUrl: 'template/tooltip/tooltip-template-popup.html'
};
})
.directive( 'tooltipTemplate', [ '$tooltip', function ( $tooltip ) {
return $tooltip('tooltipTemplate', 'tooltip', 'mouseenter', {
useContentExp: true
});
}])
.directive( 'tooltipHtmlPopup', function () {
return {
restrict: 'EA',
replace: true,
scope: { contentExp: '&', placement: '@', popupClass: '@', animation: '&', isOpen: '&' },
templateUrl: 'template/tooltip/tooltip-html-popup.html'
};
})
.directive( 'tooltipHtml', [ '$tooltip', function ( $tooltip ) {
return $tooltip('tooltipHtml', 'tooltip', 'mouseenter', {
useContentExp: true
});
}])
/*
Deprecated
*/
.directive( 'tooltipHtmlUnsafePopup', function () {
return {
restrict: 'EA',
replace: true,
scope: { content: '@', placement: '@', popupClass: '@', animation: '&', isOpen: '&' },
templateUrl: 'template/tooltip/tooltip-html-unsafe-popup.html'
};
})
.value('tooltipHtmlUnsafeSuppressDeprecated', false)
.directive( 'tooltipHtmlUnsafe', [
'$tooltip', 'tooltipHtmlUnsafeSuppressDeprecated', '$log',
function ( $tooltip , tooltipHtmlUnsafeSuppressDeprecated , $log) {
if (!tooltipHtmlUnsafeSuppressDeprecated) {
$log.warn('tooltip-html-unsafe is now deprecated. Use tooltip-html or tooltip-template instead.');
}
return $tooltip( 'tooltipHtmlUnsafe', 'tooltip', 'mouseenter' );
}]);
angular.module('ui.bootstrap.bindHtml', [])
.value('$bindHtmlUnsafeSuppressDeprecated', false)
.directive('bindHtmlUnsafe', ['$log', '$bindHtmlUnsafeSuppressDeprecated', function ($log, $bindHtmlUnsafeSuppressDeprecated) {
return function (scope, element, attr) {
if (!$bindHtmlUnsafeSuppressDeprecated) {
$log.warn('bindHtmlUnsafe is now deprecated. Use ngBindHtml instead');
}
element.addClass('ng-binding').data('$binding', attr.bindHtmlUnsafe);
scope.$watch(attr.bindHtmlUnsafe, function bindHtmlUnsafeWatchAction(value) {
element.html(value || '');
});
};
}]);
angular.module('ui.bootstrap.collapse', [])
.directive('collapse', ['$animate', function ($animate) {
return {
link: function (scope, element, attrs) {
function expand() {
element.removeClass('collapse')
.addClass('collapsing')
.attr('aria-expanded', true)
.attr('aria-hidden', false);
$animate.addClass(element, 'in', {
to: { height: element[0].scrollHeight + 'px' }
}).then(expandDone);
}
function expandDone() {
element.removeClass('collapsing');
element.css({height: 'auto'});
}
function collapse() {
if(! element.hasClass('collapse') && ! element.hasClass('in')) {
return collapseDone();
}
element
// IMPORTANT: The height must be set before adding "collapsing" class.
// Otherwise, the browser attempts to animate from height 0 (in
// collapsing class) to the given height here.
.css({height: element[0].scrollHeight + 'px'})
// initially all panel collapse have the collapse class, this removal
// prevents the animation from jumping to collapsed state
.removeClass('collapse')
.addClass('collapsing')
.attr('aria-expanded', false)
.attr('aria-hidden', true);
$animate.removeClass(element, 'in', {
to: {height: '0'}
}).then(collapseDone);
}
function collapseDone() {
element.css({height: '0'}); // Required so that collapse works when animation is disabled
element.removeClass('collapsing');
element.addClass('collapse');
}
scope.$watch(attrs.collapse, function (shouldCollapse) {
if (shouldCollapse) {
collapse();
} else {
expand();
}
});
}
};
}]);
angular.module('ui.bootstrap.transition', [])
.value('$transitionSuppressDeprecated', false)
/**
* $transition service provides a consistent interface to trigger CSS 3 transitions and to be informed when they complete.
* @param {DOMElement} element The DOMElement that will be animated.
* @param {string|object|function} trigger The thing that will cause the transition to start:
* - As a string, it represents the css class to be added to the element.
* - As an object, it represents a hash of style attributes to be applied to the element.
* - As a function, it represents a function to be called that will cause the transition to occur.
* @return {Promise} A promise that is resolved when the transition finishes.
*/
.factory('$transition', [
'$q', '$timeout', '$rootScope', '$log', '$transitionSuppressDeprecated',
function($q , $timeout , $rootScope , $log , $transitionSuppressDeprecated) {
if (!$transitionSuppressDeprecated) {
$log.warn('$transition is now deprecated. Use $animate from ngAnimate instead.');
}
var $transition = function(element, trigger, options) {
options = options || {};
var deferred = $q.defer();
var endEventName = $transition[options.animation ? 'animationEndEventName' : 'transitionEndEventName'];
var transitionEndHandler = function(event) {
$rootScope.$apply(function() {
element.unbind(endEventName, transitionEndHandler);
deferred.resolve(element);
});
};
if (endEventName) {
element.bind(endEventName, transitionEndHandler);
}
// Wrap in a timeout to allow the browser time to update the DOM before the transition is to occur
$timeout(function() {
if ( angular.isString(trigger) ) {
element.addClass(trigger);
} else if ( angular.isFunction(trigger) ) {
trigger(element);
} else if ( angular.isObject(trigger) ) {
element.css(trigger);
}
//If browser does not support transitions, instantly resolve
if ( !endEventName ) {
deferred.resolve(element);
}
});
// Add our custom cancel function to the promise that is returned
// We can call this if we are about to run a new transition, which we know will prevent this transition from ending,
// i.e. it will therefore never raise a transitionEnd event for that transition
deferred.promise.cancel = function() {
if ( endEventName ) {
element.unbind(endEventName, transitionEndHandler);
}
deferred.reject('Transition cancelled');
};
return deferred.promise;
};
// Work out the name of the transitionEnd event
var transElement = document.createElement('trans');
var transitionEndEventNames = {
'WebkitTransition': 'webkitTransitionEnd',
'MozTransition': 'transitionend',
'OTransition': 'oTransitionEnd',
'transition': 'transitionend'
};
var animationEndEventNames = {
'WebkitTransition': 'webkitAnimationEnd',
'MozTransition': 'animationend',
'OTransition': 'oAnimationEnd',
'transition': 'animationend'
};
function findEndEventName(endEventNames) {
for (var name in endEventNames){
if (transElement.style[name] !== undefined) {
return endEventNames[name];
}
}
}
$transition.transitionEndEventName = findEndEventName(transitionEndEventNames);
$transition.animationEndEventName = findEndEventName(animationEndEventNames);
return $transition;
}]);
| rawrsome/leaddyno_recurly_example | public/ui-bootstrap-custom-build/ui-bootstrap-custom-0.13.3.js | JavaScript | mit | 72,502 |
importScripts('/node_modules/chai/chai.js')
importScripts('/node_modules/mocha/mocha.js')
mocha.setup('tdd')
self.assert = chai.assert
importScripts('/node_modules/promise-polyfill/promise.js')
importScripts('/test/test.js')
importScripts('/fetch.js')
function title(test) {
return test.fullTitle().replace(/#/g, '');
}
function reporter(runner) {
runner.on('pending', function(test){
self.postMessage({name: 'pending', title: title(test)});
});
runner.on('pass', function(test){
self.postMessage({name: 'pass', title: title(test)});
});
runner.on('fail', function(test, err){
self.postMessage({
name: 'fail',
title: title(test),
message: err.message,
stack: err.stack
});
});
runner.on('end', function(){
self.postMessage({name: 'end'});
});
}
mocha.reporter(reporter).run()
| benestudio/fetch | test/worker.js | JavaScript | mit | 846 |
package tsdb
import (
"context"
"errors"
"fmt"
"io"
"os"
"regexp"
"sort"
"time"
"github.com/influxdata/influxdb/models"
"github.com/influxdata/influxdb/pkg/estimator"
"github.com/influxdata/influxdb/pkg/limiter"
"github.com/influxdata/influxdb/query"
"github.com/influxdata/influxql"
"github.com/uber-go/zap"
)
var (
// ErrFormatNotFound is returned when no format can be determined from a path.
ErrFormatNotFound = errors.New("format not found")
// ErrUnknownEngineFormat is returned when the engine format is
// unknown. ErrUnknownEngineFormat is currently returned if a format
// other than tsm1 is encountered.
ErrUnknownEngineFormat = errors.New("unknown engine format")
)
// Engine represents a swappable storage engine for the shard.
type Engine interface {
Open() error
Close() error
SetEnabled(enabled bool)
SetCompactionsEnabled(enabled bool)
WithLogger(zap.Logger)
LoadMetadataIndex(shardID uint64, index Index) error
CreateSnapshot() (string, error)
Backup(w io.Writer, basePath string, since time.Time) error
Restore(r io.Reader, basePath string) error
Import(r io.Reader, basePath string) error
CreateIterator(ctx context.Context, measurement string, opt query.IteratorOptions) (query.Iterator, error)
CreateCursor(ctx context.Context, r *CursorRequest) (Cursor, error)
IteratorCost(measurement string, opt query.IteratorOptions) (query.IteratorCost, error)
WritePoints(points []models.Point) error
CreateSeriesIfNotExists(key, name []byte, tags models.Tags) error
CreateSeriesListIfNotExists(keys, names [][]byte, tags []models.Tags) error
DeleteSeriesRange(keys [][]byte, min, max int64) error
SeriesSketches() (estimator.Sketch, estimator.Sketch, error)
MeasurementsSketches() (estimator.Sketch, estimator.Sketch, error)
SeriesN() int64
MeasurementExists(name []byte) (bool, error)
MeasurementNamesByExpr(expr influxql.Expr) ([][]byte, error)
MeasurementNamesByRegex(re *regexp.Regexp) ([][]byte, error)
MeasurementFields(measurement []byte) *MeasurementFields
ForEachMeasurementName(fn func(name []byte) error) error
DeleteMeasurement(name []byte) error
// TagKeys(name []byte) ([][]byte, error)
HasTagKey(name, key []byte) (bool, error)
MeasurementTagKeysByExpr(name []byte, expr influxql.Expr) (map[string]struct{}, error)
MeasurementTagKeyValuesByExpr(auth query.Authorizer, name []byte, key []string, expr influxql.Expr, keysSorted bool) ([][]string, error)
ForEachMeasurementTagKey(name []byte, fn func(key []byte) error) error
TagKeyCardinality(name, key []byte) int
// InfluxQL iterators
MeasurementSeriesKeysByExpr(name []byte, condition influxql.Expr) ([][]byte, error)
SeriesPointIterator(opt query.IteratorOptions) (query.Iterator, error)
// Statistics will return statistics relevant to this engine.
Statistics(tags map[string]string) []models.Statistic
LastModified() time.Time
DiskSize() int64
IsIdle() bool
Free() error
io.WriterTo
}
// EngineFormat represents the format for an engine.
type EngineFormat int
const (
// TSM1Format is the format used by the tsm1 engine.
TSM1Format EngineFormat = 2
)
// NewEngineFunc creates a new engine.
type NewEngineFunc func(id uint64, i Index, database, path string, walPath string, options EngineOptions) Engine
// newEngineFuncs is a lookup of engine constructors by name.
var newEngineFuncs = make(map[string]NewEngineFunc)
// RegisterEngine registers a storage engine initializer by name.
func RegisterEngine(name string, fn NewEngineFunc) {
if _, ok := newEngineFuncs[name]; ok {
panic("engine already registered: " + name)
}
newEngineFuncs[name] = fn
}
// RegisteredEngines returns the slice of currently registered engines.
func RegisteredEngines() []string {
a := make([]string, 0, len(newEngineFuncs))
for k := range newEngineFuncs {
a = append(a, k)
}
sort.Strings(a)
return a
}
// NewEngine returns an instance of an engine based on its format.
// If the path does not exist then the DefaultFormat is used.
func NewEngine(id uint64, i Index, database, path string, walPath string, options EngineOptions) (Engine, error) {
// Create a new engine
if _, err := os.Stat(path); os.IsNotExist(err) {
return newEngineFuncs[options.EngineVersion](id, i, database, path, walPath, options), nil
}
// If it's a dir then it's a tsm1 engine
format := DefaultEngine
if fi, err := os.Stat(path); err != nil {
return nil, err
} else if !fi.Mode().IsDir() {
return nil, ErrUnknownEngineFormat
} else {
format = "tsm1"
}
// Lookup engine by format.
fn := newEngineFuncs[format]
if fn == nil {
return nil, fmt.Errorf("invalid engine format: %q", format)
}
return fn(id, i, database, path, walPath, options), nil
}
// EngineOptions represents the options used to initialize the engine.
type EngineOptions struct {
EngineVersion string
IndexVersion string
ShardID uint64
InmemIndex interface{} // shared in-memory index
CompactionLimiter limiter.Fixed
Config Config
}
// NewEngineOptions returns the default options.
func NewEngineOptions() EngineOptions {
return EngineOptions{
EngineVersion: DefaultEngine,
IndexVersion: DefaultIndex,
Config: NewConfig(),
}
}
// NewInmemIndex returns a new "inmem" index type.
var NewInmemIndex func(name string) (interface{}, error)
| shrutir25/acs-engine | vendor/github.com/influxdata/influxdb/tsdb/engine.go | GO | mit | 5,295 |
package com.viesis.viescraft.network.server.song;
import com.viesis.viescraft.client.gui.airship.music.GuiAirshipMusicPg1;
import com.viesis.viescraft.common.entity.airshipcolors.EntityAirshipBaseVC;
import com.viesis.viescraft.network.packet.MessageBase;
import io.netty.buffer.ByteBuf;
import net.minecraft.entity.player.EntityPlayer;
public class MessageHelperGuiMusicPg1 extends MessageBase<MessageHelperGuiMusicPg1> {
private int metaSong;
@Override
public void fromBytes(ByteBuf buf)
{
metaSong = buf.readInt();
}
@Override
public void toBytes(ByteBuf buf)
{
buf.writeInt(GuiAirshipMusicPg1.metaInfo);
}
@Override
public void handleClientSide(MessageHelperGuiMusicPg1 message, EntityPlayer player)
{
}
@Override
public void handleServerSide(MessageHelperGuiMusicPg1 message, EntityPlayer player)
{
EntityAirshipBaseVC airship = (EntityAirshipBaseVC) player.getRidingEntity();
airship.metaJukeboxSelectedSong = message.metaSong;
}
}
| Weisses/Ebonheart-Mods | ViesCraft/1.12.2 - 2555/src/main/java/com/viesis/viescraft/network/server/song/MessageHelperGuiMusicPg1.java | Java | mit | 983 |
"""
The MIT License
Copyright (c) 2009 Vic Fryzel
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.
"""
import sys, os
sys.path[0:0] = [os.path.join(os.path.dirname(__file__), ".."),]
import unittest
import oauth2 as oauth
import random
import time
import urllib
import urlparse
from types import ListType
# Fix for python2.5 compatibility
try:
from urlparse import parse_qs, parse_qsl
except ImportError:
from cgi import parse_qs, parse_qsl
class TestError(unittest.TestCase):
def test_message(self):
try:
raise oauth.Error
except oauth.Error, e:
self.assertEqual(e.message, 'OAuth error occured.')
msg = 'OMG THINGS BROKE!!!!'
try:
raise oauth.Error(msg)
except oauth.Error, e:
self.assertEqual(e.message, msg)
class TestGenerateFunctions(unittest.TestCase):
def test_build_auth_header(self):
header = oauth.build_authenticate_header()
self.assertEqual(header['WWW-Authenticate'], 'OAuth realm=""')
self.assertEqual(len(header), 1)
realm = 'http://example.myrealm.com/'
header = oauth.build_authenticate_header(realm)
self.assertEqual(header['WWW-Authenticate'], 'OAuth realm="%s"' %
realm)
self.assertEqual(len(header), 1)
def test_escape(self):
string = 'http://whatever.com/~someuser/?test=test&other=other'
self.assert_('~' in oauth.escape(string))
string = '../../../../../../../etc/passwd'
self.assert_('../' not in oauth.escape(string))
def test_gen_nonce(self):
nonce = oauth.generate_nonce()
self.assertEqual(len(nonce), 8)
nonce = oauth.generate_nonce(20)
self.assertEqual(len(nonce), 20)
def test_gen_verifier(self):
verifier = oauth.generate_verifier()
self.assertEqual(len(verifier), 8)
verifier = oauth.generate_verifier(16)
self.assertEqual(len(verifier), 16)
def test_gen_timestamp(self):
exp = int(time.time())
now = oauth.generate_timestamp()
self.assertEqual(exp, now)
class TestConsumer(unittest.TestCase):
def setUp(self):
self.key = 'my-key'
self.secret = 'my-secret'
self.consumer = oauth.Consumer(key=self.key, secret=self.secret)
def test_init(self):
self.assertEqual(self.consumer.key, self.key)
self.assertEqual(self.consumer.secret, self.secret)
def test_basic(self):
self.assertRaises(ValueError, lambda: oauth.Consumer(None, None))
self.assertRaises(ValueError, lambda: oauth.Consumer('asf', None))
self.assertRaises(ValueError, lambda: oauth.Consumer(None, 'dasf'))
def test_str(self):
res = dict(parse_qsl(str(self.consumer)))
self.assertTrue('oauth_consumer_key' in res)
self.assertTrue('oauth_consumer_secret' in res)
self.assertEquals(res['oauth_consumer_key'], self.consumer.key)
self.assertEquals(res['oauth_consumer_secret'], self.consumer.secret)
class TestToken(unittest.TestCase):
def setUp(self):
self.key = 'my-key'
self.secret = 'my-secret'
self.token = oauth.Token(self.key, self.secret)
def test_basic(self):
self.assertRaises(ValueError, lambda: oauth.Token(None, None))
self.assertRaises(ValueError, lambda: oauth.Token('asf', None))
self.assertRaises(ValueError, lambda: oauth.Token(None, 'dasf'))
def test_init(self):
self.assertEqual(self.token.key, self.key)
self.assertEqual(self.token.secret, self.secret)
self.assertEqual(self.token.callback, None)
self.assertEqual(self.token.callback_confirmed, None)
self.assertEqual(self.token.verifier, None)
def test_set_callback(self):
self.assertEqual(self.token.callback, None)
self.assertEqual(self.token.callback_confirmed, None)
cb = 'http://www.example.com/my-callback'
self.token.set_callback(cb)
self.assertEqual(self.token.callback, cb)
self.assertEqual(self.token.callback_confirmed, 'true')
self.token.set_callback(None)
self.assertEqual(self.token.callback, None)
# TODO: The following test should probably not pass, but it does
# To fix this, check for None and unset 'true' in set_callback
# Additionally, should a confirmation truly be done of the callback?
self.assertEqual(self.token.callback_confirmed, 'true')
def test_set_verifier(self):
self.assertEqual(self.token.verifier, None)
v = oauth.generate_verifier()
self.token.set_verifier(v)
self.assertEqual(self.token.verifier, v)
self.token.set_verifier()
self.assertNotEqual(self.token.verifier, v)
self.token.set_verifier('')
self.assertEqual(self.token.verifier, '')
def test_get_callback_url(self):
self.assertEqual(self.token.get_callback_url(), None)
self.token.set_verifier()
self.assertEqual(self.token.get_callback_url(), None)
cb = 'http://www.example.com/my-callback?save=1&return=true'
v = oauth.generate_verifier()
self.token.set_callback(cb)
self.token.set_verifier(v)
url = self.token.get_callback_url()
verifier_str = '&oauth_verifier=%s' % v
self.assertEqual(url, '%s%s' % (cb, verifier_str))
cb = 'http://www.example.com/my-callback-no-query'
v = oauth.generate_verifier()
self.token.set_callback(cb)
self.token.set_verifier(v)
url = self.token.get_callback_url()
verifier_str = '?oauth_verifier=%s' % v
self.assertEqual(url, '%s%s' % (cb, verifier_str))
def test_to_string(self):
string = 'oauth_token_secret=%s&oauth_token=%s' % (self.secret,
self.key)
self.assertEqual(self.token.to_string(), string)
self.token.set_callback('http://www.example.com/my-callback')
string += '&oauth_callback_confirmed=true'
self.assertEqual(self.token.to_string(), string)
def _compare_tokens(self, new):
self.assertEqual(self.token.key, new.key)
self.assertEqual(self.token.secret, new.secret)
# TODO: What about copying the callback to the new token?
# self.assertEqual(self.token.callback, new.callback)
self.assertEqual(self.token.callback_confirmed,
new.callback_confirmed)
# TODO: What about copying the verifier to the new token?
# self.assertEqual(self.token.verifier, new.verifier)
def test_to_string(self):
tok = oauth.Token('tooken', 'seecret')
self.assertEqual(str(tok), 'oauth_token_secret=seecret&oauth_token=tooken')
def test_from_string(self):
self.assertRaises(ValueError, lambda: oauth.Token.from_string(''))
self.assertRaises(ValueError, lambda: oauth.Token.from_string('blahblahblah'))
self.assertRaises(ValueError, lambda: oauth.Token.from_string('blah=blah'))
self.assertRaises(ValueError, lambda: oauth.Token.from_string('oauth_token_secret=asfdasf'))
self.assertRaises(ValueError, lambda: oauth.Token.from_string('oauth_token_secret='))
self.assertRaises(ValueError, lambda: oauth.Token.from_string('oauth_token=asfdasf'))
self.assertRaises(ValueError, lambda: oauth.Token.from_string('oauth_token='))
self.assertRaises(ValueError, lambda: oauth.Token.from_string('oauth_token=&oauth_token_secret='))
self.assertRaises(ValueError, lambda: oauth.Token.from_string('oauth_token=tooken%26oauth_token_secret=seecret'))
string = self.token.to_string()
new = oauth.Token.from_string(string)
self._compare_tokens(new)
self.token.set_callback('http://www.example.com/my-callback')
string = self.token.to_string()
new = oauth.Token.from_string(string)
self._compare_tokens(new)
class TestRequest(unittest.TestCase):
def test_setter(self):
url = "http://example.com"
method = "GET"
req = oauth.Request(method)
try:
url = req.url
self.fail("AttributeError should have been raised on empty url.")
except AttributeError:
pass
except Exception, e:
self.fail(str(e))
def test_deleter(self):
url = "http://example.com"
method = "GET"
req = oauth.Request(method, url)
try:
del req.url
url = req.url
self.fail("AttributeError should have been raised on empty url.")
except AttributeError:
pass
except Exception, e:
self.fail(str(e))
def test_url(self):
url1 = "http://example.com:80/foo.php"
url2 = "https://example.com:443/foo.php"
exp1 = "http://example.com/foo.php"
exp2 = "https://example.com/foo.php"
method = "GET"
req = oauth.Request(method, url1)
self.assertEquals(req.url, exp1)
req = oauth.Request(method, url2)
self.assertEquals(req.url, exp2)
def test_get_parameter(self):
url = "http://example.com"
method = "GET"
params = {'oauth_consumer' : 'asdf'}
req = oauth.Request(method, url, parameters=params)
self.assertEquals(req.get_parameter('oauth_consumer'), 'asdf')
self.assertRaises(oauth.Error, req.get_parameter, 'blah')
def test_get_nonoauth_parameters(self):
oauth_params = {
'oauth_consumer': 'asdfasdfasdf'
}
other_params = {
'foo': 'baz',
'bar': 'foo',
'multi': ['FOO','BAR']
}
params = oauth_params
params.update(other_params)
req = oauth.Request("GET", "http://example.com", params)
self.assertEquals(other_params, req.get_nonoauth_parameters())
def test_to_header(self):
realm = "http://sp.example.com/"
params = {
'oauth_version': "1.0",
'oauth_nonce': "4572616e48616d6d65724c61686176",
'oauth_timestamp': "137131200",
'oauth_consumer_key': "0685bd9184jfhq22",
'oauth_signature_method': "HMAC-SHA1",
'oauth_token': "ad180jjd733klru7",
'oauth_signature': "wOJIO9A2W5mFwDgiDvZbTSMK%2FPY%3D",
}
req = oauth.Request("GET", realm, params)
header, value = req.to_header(realm).items()[0]
parts = value.split('OAuth ')
vars = parts[1].split(', ')
self.assertTrue(len(vars), (len(params) + 1))
res = {}
for v in vars:
var, val = v.split('=')
res[var] = urllib.unquote(val.strip('"'))
self.assertEquals(realm, res['realm'])
del res['realm']
self.assertTrue(len(res), len(params))
for key, val in res.items():
self.assertEquals(val, params.get(key))
def test_to_postdata(self):
realm = "http://sp.example.com/"
params = {
'multi': ['FOO','BAR'],
'oauth_version': "1.0",
'oauth_nonce': "4572616e48616d6d65724c61686176",
'oauth_timestamp': "137131200",
'oauth_consumer_key': "0685bd9184jfhq22",
'oauth_signature_method': "HMAC-SHA1",
'oauth_token': "ad180jjd733klru7",
'oauth_signature': "wOJIO9A2W5mFwDgiDvZbTSMK%2FPY%3D",
}
req = oauth.Request("GET", realm, params)
flat = [('multi','FOO'),('multi','BAR')]
del params['multi']
flat.extend(params.items())
kf = lambda x: x[0]
self.assertEquals(sorted(flat, key=kf), sorted(parse_qsl(req.to_postdata()), key=kf))
def test_to_url(self):
url = "http://sp.example.com/"
params = {
'oauth_version': "1.0",
'oauth_nonce': "4572616e48616d6d65724c61686176",
'oauth_timestamp': "137131200",
'oauth_consumer_key': "0685bd9184jfhq22",
'oauth_signature_method': "HMAC-SHA1",
'oauth_token': "ad180jjd733klru7",
'oauth_signature': "wOJIO9A2W5mFwDgiDvZbTSMK%2FPY%3D",
}
req = oauth.Request("GET", url, params)
exp = urlparse.urlparse("%s?%s" % (url, urllib.urlencode(params)))
res = urlparse.urlparse(req.to_url())
self.assertEquals(exp.scheme, res.scheme)
self.assertEquals(exp.netloc, res.netloc)
self.assertEquals(exp.path, res.path)
a = parse_qs(exp.query)
b = parse_qs(res.query)
self.assertEquals(a, b)
def test_get_normalized_parameters(self):
url = "http://sp.example.com/"
params = {
'oauth_version': "1.0",
'oauth_nonce': "4572616e48616d6d65724c61686176",
'oauth_timestamp': "137131200",
'oauth_consumer_key': "0685bd9184jfhq22",
'oauth_signature_method': "HMAC-SHA1",
'oauth_token': "ad180jjd733klru7",
'multi': ['FOO','BAR'],
}
req = oauth.Request("GET", url, params)
res = req.get_normalized_parameters()
srtd = [(k, v if type(v) != ListType else sorted(v)) for k,v in sorted(params.items())]
self.assertEquals(urllib.urlencode(srtd, True), res)
def test_get_normalized_parameters_ignores_auth_signature(self):
url = "http://sp.example.com/"
params = {
'oauth_version': "1.0",
'oauth_nonce': "4572616e48616d6d65724c61686176",
'oauth_timestamp': "137131200",
'oauth_consumer_key': "0685bd9184jfhq22",
'oauth_signature_method': "HMAC-SHA1",
'oauth_signature': "some-random-signature-%d" % random.randint(1000, 2000),
'oauth_token': "ad180jjd733klru7",
}
req = oauth.Request("GET", url, params)
res = req.get_normalized_parameters()
self.assertNotEquals(urllib.urlencode(sorted(params.items())), res)
foo = params.copy()
del foo["oauth_signature"]
self.assertEqual(urllib.urlencode(sorted(foo.items())), res)
def test_get_normalized_string_escapes_spaces_properly(self):
url = "http://sp.example.com/"
params = {
"some_random_data": random.randint(100, 1000),
"data": "This data with a random number (%d) has spaces!" % random.randint(1000, 2000),
}
req = oauth.Request("GET", url, params)
res = req.get_normalized_parameters()
expected = urllib.urlencode(sorted(params.items())).replace('+', '%20')
self.assertEqual(expected, res)
def test_sign_request(self):
url = "http://sp.example.com/"
params = {
'oauth_version': "1.0",
'oauth_nonce': "4572616e48616d6d65724c61686176",
'oauth_timestamp': "137131200"
}
tok = oauth.Token(key="tok-test-key", secret="tok-test-secret")
con = oauth.Consumer(key="con-test-key", secret="con-test-secret")
params['oauth_token'] = tok.key
params['oauth_consumer_key'] = con.key
req = oauth.Request(method="GET", url=url, parameters=params)
methods = {
'TQ6vGQ5A6IZn8dmeGB4+/Jl3EMI=': oauth.SignatureMethod_HMAC_SHA1(),
'con-test-secret&tok-test-secret': oauth.SignatureMethod_PLAINTEXT()
}
for exp, method in methods.items():
req.sign_request(method, con, tok)
self.assertEquals(req['oauth_signature_method'], method.name)
self.assertEquals(req['oauth_signature'], exp)
def test_from_request(self):
url = "http://sp.example.com/"
params = {
'oauth_version': "1.0",
'oauth_nonce': "4572616e48616d6d65724c61686176",
'oauth_timestamp': "137131200",
'oauth_consumer_key': "0685bd9184jfhq22",
'oauth_signature_method': "HMAC-SHA1",
'oauth_token': "ad180jjd733klru7",
'oauth_signature': "wOJIO9A2W5mFwDgiDvZbTSMK%2FPY%3D",
}
req = oauth.Request("GET", url, params)
headers = req.to_header()
# Test from the headers
req = oauth.Request.from_request("GET", url, headers)
self.assertEquals(req.method, "GET")
self.assertEquals(req.url, url)
self.assertEquals(params, req.copy())
# Test with bad OAuth headers
bad_headers = {
'Authorization' : 'OAuth this is a bad header'
}
self.assertRaises(oauth.Error, oauth.Request.from_request, "GET",
url, bad_headers)
# Test getting from query string
qs = urllib.urlencode(params)
req = oauth.Request.from_request("GET", url, query_string=qs)
exp = parse_qs(qs, keep_blank_values=False)
for k, v in exp.iteritems():
exp[k] = urllib.unquote(v[0])
self.assertEquals(exp, req.copy())
# Test that a boned from_request() call returns None
req = oauth.Request.from_request("GET", url)
self.assertEquals(None, req)
def test_from_token_and_callback(self):
url = "http://sp.example.com/"
params = {
'oauth_version': "1.0",
'oauth_nonce': "4572616e48616d6d65724c61686176",
'oauth_timestamp': "137131200",
'oauth_consumer_key': "0685bd9184jfhq22",
'oauth_signature_method': "HMAC-SHA1",
'oauth_token': "ad180jjd733klru7",
'oauth_signature': "wOJIO9A2W5mFwDgiDvZbTSMK%2FPY%3D",
}
tok = oauth.Token(key="tok-test-key", secret="tok-test-secret")
req = oauth.Request.from_token_and_callback(tok)
self.assertFalse('oauth_callback' in req)
self.assertEquals(req['oauth_token'], tok.key)
req = oauth.Request.from_token_and_callback(tok, callback=url)
self.assertTrue('oauth_callback' in req)
self.assertEquals(req['oauth_callback'], url)
def test_from_consumer_and_token(self):
url = "http://sp.example.com/"
tok = oauth.Token(key="tok-test-key", secret="tok-test-secret")
con = oauth.Consumer(key="con-test-key", secret="con-test-secret")
req = oauth.Request.from_consumer_and_token(con, token=tok,
http_method="GET", http_url=url)
self.assertEquals(req['oauth_token'], tok.key)
self.assertEquals(req['oauth_consumer_key'], con.key)
class SignatureMethod_Bad(oauth.SignatureMethod):
name = "BAD"
def signing_base(self, request, consumer, token):
return ""
def sign(self, request, consumer, token):
return "invalid-signature"
class TestServer(unittest.TestCase):
def setUp(self):
url = "http://sp.example.com/"
params = {
'oauth_version': "1.0",
'oauth_nonce': "4572616e48616d6d65724c61686176",
'oauth_timestamp': int(time.time()),
'bar': 'blerg',
'multi': ['FOO','BAR'],
'foo': 59
}
self.consumer = oauth.Consumer(key="consumer-key",
secret="consumer-secret")
self.token = oauth.Token(key="token-key", secret="token-secret")
params['oauth_token'] = self.token.key
params['oauth_consumer_key'] = self.consumer.key
self.request = oauth.Request(method="GET", url=url, parameters=params)
signature_method = oauth.SignatureMethod_HMAC_SHA1()
self.request.sign_request(signature_method, self.consumer, self.token)
def test_init(self):
server = oauth.Server(signature_methods={'HMAC-SHA1' : oauth.SignatureMethod_HMAC_SHA1()})
self.assertTrue('HMAC-SHA1' in server.signature_methods)
self.assertTrue(isinstance(server.signature_methods['HMAC-SHA1'],
oauth.SignatureMethod_HMAC_SHA1))
server = oauth.Server()
self.assertEquals(server.signature_methods, {})
def test_add_signature_method(self):
server = oauth.Server()
res = server.add_signature_method(oauth.SignatureMethod_HMAC_SHA1())
self.assertTrue(len(res) == 1)
self.assertTrue('HMAC-SHA1' in res)
self.assertTrue(isinstance(res['HMAC-SHA1'],
oauth.SignatureMethod_HMAC_SHA1))
res = server.add_signature_method(oauth.SignatureMethod_PLAINTEXT())
self.assertTrue(len(res) == 2)
self.assertTrue('PLAINTEXT' in res)
self.assertTrue(isinstance(res['PLAINTEXT'],
oauth.SignatureMethod_PLAINTEXT))
def test_verify_request(self):
server = oauth.Server()
server.add_signature_method(oauth.SignatureMethod_HMAC_SHA1())
parameters = server.verify_request(self.request, self.consumer,
self.token)
self.assertTrue('bar' in parameters)
self.assertTrue('foo' in parameters)
self.assertTrue('multi' in parameters)
self.assertEquals(parameters['bar'], 'blerg')
self.assertEquals(parameters['foo'], 59)
self.assertEquals(parameters['multi'], ['FOO','BAR'])
def test_no_version(self):
url = "http://sp.example.com/"
params = {
'oauth_nonce': "4572616e48616d6d65724c61686176",
'oauth_timestamp': int(time.time()),
'bar': 'blerg',
'multi': ['FOO','BAR'],
'foo': 59
}
self.consumer = oauth.Consumer(key="consumer-key",
secret="consumer-secret")
self.token = oauth.Token(key="token-key", secret="token-secret")
params['oauth_token'] = self.token.key
params['oauth_consumer_key'] = self.consumer.key
self.request = oauth.Request(method="GET", url=url, parameters=params)
signature_method = oauth.SignatureMethod_HMAC_SHA1()
self.request.sign_request(signature_method, self.consumer, self.token)
server = oauth.Server()
server.add_signature_method(oauth.SignatureMethod_HMAC_SHA1())
parameters = server.verify_request(self.request, self.consumer,
self.token)
def test_invalid_version(self):
url = "http://sp.example.com/"
params = {
'oauth_version': '222.9922',
'oauth_nonce': "4572616e48616d6d65724c61686176",
'oauth_timestamp': int(time.time()),
'bar': 'blerg',
'multi': ['foo','bar'],
'foo': 59
}
consumer = oauth.Consumer(key="consumer-key",
secret="consumer-secret")
token = oauth.Token(key="token-key", secret="token-secret")
params['oauth_token'] = token.key
params['oauth_consumer_key'] = consumer.key
request = oauth.Request(method="GET", url=url, parameters=params)
signature_method = oauth.SignatureMethod_HMAC_SHA1()
request.sign_request(signature_method, consumer, token)
server = oauth.Server()
server.add_signature_method(oauth.SignatureMethod_HMAC_SHA1())
self.assertRaises(oauth.Error, server.verify_request, request,
consumer, token)
def test_invalid_signature_method(self):
url = "http://sp.example.com/"
params = {
'oauth_version': '1.0',
'oauth_nonce': "4572616e48616d6d65724c61686176",
'oauth_timestamp': int(time.time()),
'bar': 'blerg',
'multi': ['FOO','BAR'],
'foo': 59
}
consumer = oauth.Consumer(key="consumer-key",
secret="consumer-secret")
token = oauth.Token(key="token-key", secret="token-secret")
params['oauth_token'] = token.key
params['oauth_consumer_key'] = consumer.key
request = oauth.Request(method="GET", url=url, parameters=params)
signature_method = SignatureMethod_Bad()
request.sign_request(signature_method, consumer, token)
server = oauth.Server()
server.add_signature_method(oauth.SignatureMethod_HMAC_SHA1())
self.assertRaises(oauth.Error, server.verify_request, request,
consumer, token)
def test_missing_signature(self):
url = "http://sp.example.com/"
params = {
'oauth_version': '1.0',
'oauth_nonce': "4572616e48616d6d65724c61686176",
'oauth_timestamp': int(time.time()),
'bar': 'blerg',
'multi': ['FOO','BAR'],
'foo': 59
}
consumer = oauth.Consumer(key="consumer-key",
secret="consumer-secret")
token = oauth.Token(key="token-key", secret="token-secret")
params['oauth_token'] = token.key
params['oauth_consumer_key'] = consumer.key
request = oauth.Request(method="GET", url=url, parameters=params)
signature_method = oauth.SignatureMethod_HMAC_SHA1()
request.sign_request(signature_method, consumer, token)
del request['oauth_signature']
server = oauth.Server()
server.add_signature_method(oauth.SignatureMethod_HMAC_SHA1())
self.assertRaises(oauth.MissingSignature, server.verify_request,
request, consumer, token)
# Request Token: http://oauth-sandbox.sevengoslings.net/request_token
# Auth: http://oauth-sandbox.sevengoslings.net/authorize
# Access Token: http://oauth-sandbox.sevengoslings.net/access_token
# Two-legged: http://oauth-sandbox.sevengoslings.net/two_legged
# Three-legged: http://oauth-sandbox.sevengoslings.net/three_legged
# Key: bd37aed57e15df53
# Secret: 0e9e6413a9ef49510a4f68ed02cd
class TestClient(unittest.TestCase):
# oauth_uris = {
# 'request_token': '/request_token.php',
# 'access_token': '/access_token.php'
# }
oauth_uris = {
'request_token': '/request_token',
'authorize': '/authorize',
'access_token': '/access_token',
'two_legged': '/two_legged',
'three_legged': '/three_legged'
}
consumer_key = 'bd37aed57e15df53'
consumer_secret = '0e9e6413a9ef49510a4f68ed02cd'
host = 'http://oauth-sandbox.sevengoslings.net'
def setUp(self):
self.consumer = oauth.Consumer(key=self.consumer_key,
secret=self.consumer_secret)
self.body = {
'foo': 'bar',
'bar': 'foo',
'multi': ['FOO','BAR'],
'blah': 599999
}
def _uri(self, type):
uri = self.oauth_uris.get(type)
if uri is None:
raise KeyError("%s is not a valid OAuth URI type." % type)
return "%s%s" % (self.host, uri)
def test_access_token_get(self):
"""Test getting an access token via GET."""
client = oauth.Client(self.consumer, None)
resp, content = client.request(self._uri('request_token'), "GET")
self.assertEquals(int(resp['status']), 200)
def test_access_token_post(self):
"""Test getting an access token via POST."""
client = oauth.Client(self.consumer, None)
resp, content = client.request(self._uri('request_token'), "POST")
self.assertEquals(int(resp['status']), 200)
res = dict(parse_qsl(content))
self.assertTrue('oauth_token' in res)
self.assertTrue('oauth_token_secret' in res)
def _two_legged(self, method):
client = oauth.Client(self.consumer, None)
return client.request(self._uri('two_legged'), method,
body=urllib.urlencode(self.body))
def test_two_legged_post(self):
"""A test of a two-legged OAuth POST request."""
resp, content = self._two_legged("POST")
self.assertEquals(int(resp['status']), 200)
def test_two_legged_get(self):
"""A test of a two-legged OAuth GET request."""
resp, content = self._two_legged("GET")
self.assertEquals(int(resp['status']), 200)
if __name__ == "__main__":
unittest.main()
| oauth-xx/python-oauth2 | tests/test_oauth.py | Python | mit | 28,822 |
using System;
namespace SIL.WritingSystems.Migration
{
/// <summary>
/// This class keeps track of a file's name change due to updates in the ieft language tag
/// </summary>
public class LdmlMigrationInfo
{
private readonly string _fileName;
public LdmlMigrationInfo(string fileName)
{
_fileName = fileName;
}
public string FileName
{
get { return _fileName; }
}
/// <summary>
/// Should really be FilenameBeforeMigration
/// </summary>
public string LanguageTagBeforeMigration { get; set; }
/// <summary>
/// Should really be FilenameAfterMigration
/// </summary>
public string LanguageTagAfterMigration { get; set; }
internal Action<WritingSystemDefinition> RemovedPropertiesSetter { get; set; }
}
}
| sillsdev/libpalaso | SIL.WritingSystems/Migration/LdmlMigrationInfo.cs | C# | mit | 754 |
<?php
/**
* Plugin Name: Elementor
* Description: The most advanced frontend drag & drop page builder. Create high-end, pixel perfect websites at record speeds. Any theme, any page, any design.
* Plugin URI: https://elementor.com/
* Author: Elementor.com
* Version: 0.10.7
* Author URI: https://elementor.com/
*
* Text Domain: elementor
*
* Elementor is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* Elementor is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
define( 'ELEMENTOR_VERSION', '0.10.7' );
define( 'ELEMENTOR__FILE__', __FILE__ );
define( 'ELEMENTOR_PLUGIN_BASE', plugin_basename( ELEMENTOR__FILE__ ) );
define( 'ELEMENTOR_URL', plugins_url( '/', ELEMENTOR__FILE__ ) );
define( 'ELEMENTOR_PATH', plugin_dir_path( ELEMENTOR__FILE__ ) );
define( 'ELEMENTOR_ASSETS_URL', ELEMENTOR_URL . 'assets/' );
add_action( 'plugins_loaded', 'elementor_load_plugin_textdomain' );
if ( ! version_compare( PHP_VERSION, '5.4', '>=' ) ) {
add_action( 'admin_notices', 'elementor_fail_php_version' );
} else {
require( ELEMENTOR_PATH . 'includes/plugin.php' );
}
/**
* Load gettext translate for our text domain.
*
* @since 1.0.0
*
* @return void
*/
function elementor_load_plugin_textdomain() {
load_plugin_textdomain( 'elementor' );
}
/**
* Show in WP Dashboard notice about the plugin is not activated.
*
* @since 1.0.0
*
* @return void
*/
function elementor_fail_php_version() {
$message = esc_html__( 'Elementor requires PHP version 5.4+, plugin is currently NOT ACTIVE.', 'elementor' );
$html_message = sprintf( '<div class="error">%s</div>', wpautop( $message ) );
echo wp_kses_post( $html_message );
}
| abettermap/bike-coop-plugin | framework/vendor/elementor/elementor.php | PHP | mit | 2,059 |
<?php
namespace TYPO3\Flow\Tests\Unit\Core;
/*
* This file is part of the TYPO3.Flow package.
*
* (c) Contributors of the Neos Project - www.neos.io
*
* This package is Open Source Software. For the full copyright and license
* information, please view the LICENSE file which was distributed with this
* source code.
*/
use TYPO3\Flow\Core\Bootstrap;
/**
* Testcase for the Bootstrap class
*/
class BootstrapTest extends \TYPO3\Flow\Tests\UnitTestCase
{
/**
* @return array
*/
public function commandIdentifiersAndCompiletimeControllerInfo()
{
return array(
array(array('typo3.flow:core:shell', 'typo3.flow:cache:flush'), 'typo3.flow:core:shell', true),
array(array('typo3.flow:core:shell', 'typo3.flow:cache:flush'), 'flow:core:shell', true),
array(array('typo3.flow:core:shell', 'typo3.flow:cache:flush'), 'core:shell', false),
array(array('typo3.flow:core:*', 'typo3.flow:cache:flush'), 'typo3.flow:core:shell', true),
array(array('typo3.flow:core:*', 'typo3.flow:cache:flush'), 'flow:core:shell', true),
array(array('typo3.flow:core:shell', 'typo3.flow:cache:flush'), 'typo3.flow:help:help', false),
array(array('typo3.flow:core:*', 'typo3.flow:cache:*'), 'flow:cache:flush', true),
array(array('typo3.flow:core:*', 'typo3.flow:cache:*'), 'flow5:core:shell', false),
array(array('typo3.flow:core:*', 'typo3.flow:cache:*'), 'typo3:core:shell', false),
);
}
/**
* @test
* @dataProvider commandIdentifiersAndCompiletimeControllerInfo
*/
public function isCompileTimeCommandControllerChecksIfTheGivenCommandIdentifierRefersToACompileTimeController($compiletimeCommandControllerIdentifiers, $givenCommandIdentifier, $expectedResult)
{
$bootstrap = new Bootstrap('Testing');
foreach ($compiletimeCommandControllerIdentifiers as $compiletimeCommandControllerIdentifier) {
$bootstrap->registerCompiletimeCommand($compiletimeCommandControllerIdentifier);
}
$this->assertSame($expectedResult, $bootstrap->isCompiletimeCommand($givenCommandIdentifier));
}
/**
* @test
* @expectedException \TYPO3\Flow\Exception
*/
public function resolveRequestHandlerThrowsUsefulExceptionIfNoRequestHandlerFound()
{
$bootstrap = $this->getAccessibleMock('\TYPO3\Flow\Core\Bootstrap', array('dummy'), array(), '', false);
$bootstrap->_call('resolveRequestHandler');
}
}
| mkeitsch/flow-development-collection | TYPO3.Flow/Tests/Unit/Core/BootstrapTest.php | PHP | mit | 2,534 |
<?php
namespace NodeSearchBundle\Helper;
// here you can define custom actions
// all public methods declared in helper class will be available in $I
class Unit extends \Codeception\Module
{
}
| treeleaf/KunstmaanBundlesCMS | src/Kunstmaan/NodeSearchBundle/Tests/_support/Helper/Unit.php | PHP | mit | 196 |
๏ปฟ// AssemblyInfo.cs
// (c) Copyright Cirrious Ltd. http://www.cirrious.com
// MvvmCross is licensed using Microsoft Public License (Ms-PL)
// Contributions and inspirations noted in readme.md and license.txt
//
// Project Lead - Stuart Lodge, @slodge, me@slodge.com
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("MvvmCross.Plugins.Visibility.WinRT")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Cirrious")]
[assembly: AssemblyProduct("MvvmCross.Plugins.Visibility.WinRT")]
[assembly: AssemblyCopyright("Copyright ยฉ 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("4.0.0.0")]
[assembly: AssemblyFileVersion("4.0.0.0")]
[assembly: ComVisible(false)] | martijn00/MvvmCross-Plugins | Visibility/MvvmCross.Plugins.Visibility.WindowsStore/Properties/AssemblyInfo.cs | C# | mit | 1,321 |
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.recoveryservices.backup.v2017_07_01;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.fasterxml.jackson.annotation.JsonSubTypes;
/**
* Base class for feature request.
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "featureType")
@JsonTypeName("FeatureSupportRequest")
@JsonSubTypes({
@JsonSubTypes.Type(name = "AzureBackupGoals", value = AzureBackupGoalFeatureSupportRequest.class),
@JsonSubTypes.Type(name = "AzureVMResourceBackup", value = AzureVMResourceFeatureSupportRequest.class)
})
public class FeatureSupportRequest {
}
| selvasingh/azure-sdk-for-java | sdk/recoveryservices.backup/mgmt-v2017_07_01/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2017_07_01/FeatureSupportRequest.java | Java | mit | 926 |
// Copyright (c) 2012 VMware, Inc.
package sigar
import (
"bytes"
"errors"
"fmt"
"os/exec"
"strconv"
"syscall"
"time"
"unsafe"
)
var (
kernel32DLL = syscall.MustLoadDLL("kernel32")
procGetDiskFreeSpace = kernel32DLL.MustFindProc("GetDiskFreeSpaceW")
procGetSystemTimes = kernel32DLL.MustFindProc("GetSystemTimes")
procGetTickCount64 = kernel32DLL.MustFindProc("GetTickCount64")
procGlobalMemoryStatusEx = kernel32DLL.MustFindProc("GlobalMemoryStatusEx")
)
func (self *LoadAverage) Get() error {
return ErrNotImplemented
}
func (u *Uptime) Get() error {
r1, _, e1 := syscall.Syscall(procGetTickCount64.Addr(), 0, 0, 0, 0)
if e1 != 0 {
return error(e1)
}
u.Length = (time.Duration(r1) * time.Millisecond).Seconds()
return nil
}
type memorystatusex struct {
Length uint32
MemoryLoad uint32
TotalPhys uint64
AvailPhys uint64
TotalPageFile uint64
AvailPageFile uint64
TotalVirtual uint64
AvailVirtual uint64
AvailExtendedVirtual uint64
}
func (m *Mem) Get() error {
var x memorystatusex
x.Length = uint32(unsafe.Sizeof(x))
r1, _, e1 := syscall.Syscall(procGlobalMemoryStatusEx.Addr(), 1,
uintptr(unsafe.Pointer(&x)),
0,
0,
)
if err := checkErrno(r1, e1); err != nil {
return fmt.Errorf("GlobalMemoryStatusEx: %s", err)
}
m.Total = x.TotalPhys
m.Free = x.AvailPhys
m.ActualFree = m.Free
m.Used = m.Total - m.Free
return nil
}
func (s *Swap) Get() error {
const MB = 1024 * 1024
out, err := exec.Command("wmic", "pagefile", "list", "full").Output()
if err != nil {
return err
}
total, err := parseWmicOutput(out, []byte("AllocatedBaseSize"))
if err != nil {
return err
}
used, err := parseWmicOutput(out, []byte("CurrentUsage"))
if err != nil {
return err
}
s.Total = total * MB
s.Used = used * MB
s.Free = s.Total - s.Used
return nil
}
func parseWmicOutput(s, sep []byte) (uint64, error) {
bb := bytes.Split(s, []byte("\n"))
for i := 0; i < len(bb); i++ {
b := bytes.TrimSpace(bb[i])
n := bytes.IndexByte(b, '=')
if n > 0 && bytes.Equal(sep, b[:n]) {
return strconv.ParseUint(string(b[n+1:]), 10, 64)
}
}
return 0, errors.New("parseWmicOutput: missing field: " + string(sep))
}
func (c *Cpu) Get() error {
var (
idleTime syscall.Filetime
kernelTime syscall.Filetime // Includes kernel and idle time.
userTime syscall.Filetime
)
r1, _, e1 := syscall.Syscall(procGetSystemTimes.Addr(), 3,
uintptr(unsafe.Pointer(&idleTime)),
uintptr(unsafe.Pointer(&kernelTime)),
uintptr(unsafe.Pointer(&userTime)),
)
if err := checkErrno(r1, e1); err != nil {
return fmt.Errorf("GetSystemTimes: %s", err)
}
c.Idle = uint64(idleTime.Nanoseconds())
c.Sys = uint64(kernelTime.Nanoseconds()) - c.Idle
c.User = uint64(userTime.Nanoseconds())
return nil
}
func (self *CpuList) Get() error {
return ErrNotImplemented
}
func (self *FileSystemList) Get() error {
return ErrNotImplemented
}
func (self *ProcList) Get() error {
return ErrNotImplemented
}
func (self *ProcState) Get(pid int) error {
return ErrNotImplemented
}
func (self *ProcMem) Get(pid int) error {
return ErrNotImplemented
}
func (self *ProcTime) Get(pid int) error {
return ErrNotImplemented
}
func (self *ProcArgs) Get(pid int) error {
return ErrNotImplemented
}
func (self *ProcExe) Get(pid int) error {
return ErrNotImplemented
}
func (fs *FileSystemUsage) Get(path string) error {
root, err := syscall.UTF16PtrFromString(path)
if err != nil {
return fmt.Errorf("FileSystemUsage (%s): %s", path, err)
}
var (
SectorsPerCluster uint32
BytesPerSector uint32
// Free clusters available to the user
// associated with the calling thread.
NumberOfFreeClusters uint32
// Total clusters available to the user
// associated with the calling thread.
TotalNumberOfClusters uint32
)
r1, _, e1 := syscall.Syscall6(procGetDiskFreeSpace.Addr(), 5,
uintptr(unsafe.Pointer(root)),
uintptr(unsafe.Pointer(&SectorsPerCluster)),
uintptr(unsafe.Pointer(&BytesPerSector)),
uintptr(unsafe.Pointer(&NumberOfFreeClusters)),
uintptr(unsafe.Pointer(&TotalNumberOfClusters)),
0,
)
if err := checkErrno(r1, e1); err != nil {
return fmt.Errorf("FileSystemUsage (%s): %s", path, err)
}
m := uint64(SectorsPerCluster * BytesPerSector)
fs.Total = uint64(TotalNumberOfClusters) * m
fs.Free = uint64(NumberOfFreeClusters) * m
fs.Avail = fs.Free
fs.Used = fs.Total - fs.Free
return nil
}
func checkErrno(r1 uintptr, e1 error) error {
if r1 == 0 {
if e, ok := e1.(syscall.Errno); ok && e != 0 {
return e1
}
return syscall.EINVAL
}
return nil
}
| ocdogan/fluentgo | vendor/github.com/cloudfoundry/gosigar/sigar_windows.go | GO | mit | 4,648 |
/**
* jQuery Accessible combobox v0.1.0
* https://github.com/choi4450/jquery.accessiblecombobox
*
* Copyright 2015 Gyumin Choi Foundation and other contributors
* Released under the MIT license
* https://github.com/choi4450/jquery.accessiblecombobox/blob/master/LICENSE.txt
*/
(function($) {
$.fn.accessibleComboboxConfig = {
label: 'Select another option',
bullet: '',
style: null,
animate: false,
duration: 0,
easingOpen: null,
easingClose: null
};
$.fn.accessibleCombobox = function(defaults) {
if (navigator.userAgent.indexOf("MSIE 6") >= 0) return false;
var config = $.extend({}, $.fn.accessibleComboboxConfig, defaults),
fn = {},
dom = {};
dom.cbo = $(this);
config.elemId = dom.cbo.attr('id') || '';
config.elemClass = dom.cbo.attr('class') || '';
config.elemName = dom.cbo.attr('name') || '';
config.elemTitle = dom.cbo.attr('title') || '';
config.elemWidth = dom.cbo.width();
config.selectedOpt = dom.cbo.find('option:selected');
config.selectedOptTxt = config.selectedOpt.text();
config.propDisabled = dom.cbo.prop('disabled');
config.propRequired = dom.cbo.prop('required');
fn.replaceCbo = function() {
var attrGroup = {};
attrGroup.boxSelector = 'class="' + config.elemClass + ' accessiblecbo';
attrGroup.boxSelector += config.propDisabled ? ' is-disabled"' : '"';
attrGroup.boxSelector += config.elemId != '' ? ' id="' + config.elemId + '"' : '';
attrGroup.btnTitle = config.elemTitle != '' ? 'title="' + config.elemTitle + '"' : '';
attrGroup.btnLabel = 'aria-label="' + config.label + '"';
attrGroup.optName = config.elemName != '' ? 'name="' + config.elemName + '"' : '';
attrGroup.boxRequired = config.propRequired ? 'aria-required="true"' : '';
attrGroup.optRequired = config.propRequired ? 'required="required"' : '';
attrGroup.btnDisabled = config.propDisabled ? 'aria-disabled="true" tabindex="-1"' : '';
attrGroup.optDisabled = config.propDisabled ? 'disabled="disabled"' : '';
var addOptionHtmlStr = function(element) {
var returnHtmlStr = '';
element.each(function(_i) {
var $this = $(this),
thisAttrVal = $this.val() ? 'value="' + $this.val() + '"' : '',
selectedClass = '',
selectedAttr = '';
if ($this.prop('selected')) {
selectedClass = $this.prop('selected') ? ' is-selected' : '';
selectedAttr = $this.prop('selected') ? 'checked="checked"' : '';
}
returnHtmlStr +=
'<label class="accessiblecbo-opt' + selectedClass + '">' +
'<input type="radio" class="accessiblecbo-opt-radio" ' + attrGroup.optName + ' ' + thisAttrVal + ' ' + attrGroup.optDisabled + ' ' + attrGroup.optRequired + ' ' + selectedAttr + '>' +
'<span class="accessiblecbo-opt-txt">' + $this.text() + '</span>' +
'</label>';
});
return returnHtmlStr;
};
var replaceHtmlStr =
'<span ' + attrGroup.boxSelector + ' role="menu" aria-live="polite" aria-relevant="all" aria-haspopup="true" aria-expanded="false" style="width: ' + config.elemWidth + 'px;" ' + attrGroup.btnDisabled + ' ' + attrGroup.boxRequired + '>' +
'<a href="#" class="accessiblecbo-btn" role="button" aria-live="off" ' + attrGroup.btnTitle + ' ' + attrGroup.btnLabel + ' ' + attrGroup.btnDisabled + '>' +
'<span class="accessiblecbo-btn-txt">' + config.selectedOptTxt + '</span>' +
'<span class="accessiblecbo-btn-bu" aria-hidden="true">' + config.bullet + '</span>' +
'</a>' +
'<span class="accessiblecbo-listbox" role="radiogroup" aria-hidden="true" ' + attrGroup.boxRequired + '>' +
'<span class="accessiblecbo-listbox-wrap">';
dom.cbo.find('>*').each(function(_i) {
var $this = $(this);
if ($this.is('optgroup')) {
replaceHtmlStr +=
'<span class="accessiblecbo-optgroup" role="radiogroup">' +
'<em class="accessiblecbo-optgroup-tit">Optgroup</em>' +
addOptionHtmlStr($this.find('option')) +
'</span>';
} else {
replaceHtmlStr +=
addOptionHtmlStr($this);
}
});
replaceHtmlStr +=
'</span>' +
'</span>' +
'</span>';
var replaceHtml = $(replaceHtmlStr);
dom.cbo.replaceWith(replaceHtml);
dom.cbo = replaceHtml;
dom.cboBtn = dom.cbo.find('.accessiblecbo-btn');
dom.cboBtnTxt = dom.cboBtn.find('.accessiblecbo-btn-txt');
dom.cboListbox = dom.cbo.find('.accessiblecbo-listbox');
dom.cboOpt = dom.cboListbox.find('.accessiblecbo-opt');
dom.cboOptRadio = dom.cboOpt.find('.accessiblecbo-opt-radio');
};
fn.toggleExpandCbo = function(action) {
if (typeof action == 'undefined') action = 'toggle';
var propExpanded = dom.cbo.attr('aria-expanded'),
setOpenExpanded = function() {
dom.cbo.attr('aria-expanded', 'true').addClass('is-expanded');
dom.cboListbox.attr('aria-hidden', 'false');
dom.cboOptRadio.filter(':checked').focus();
},
setCloseExpanded = function() {
dom.cbo.attr('aria-expanded', 'false').removeClass('is-expanded');
dom.cboListbox.attr('aria-hidden', 'true');
},
returnBoolChkAction = function(chk) {
return action == 'toggle' || action == chk;
};
if (returnBoolChkAction('open') && propExpanded == 'false') {
setOpenExpanded();
setTimeout(function() {
$(document).one('click.accessibleCbo-closeExpanded', function(e) {
if (dom.cbo.has(e.target).length < 1) setCloseExpanded();
});
}, 0);
} else if (returnBoolChkAction('close') && propExpanded == 'true') {
setCloseExpanded();
$(document).off('.accessibleCbo-closeExpanded');
}
};
fn.activeOpt = function(element, change) {
var thisOpt = element,
thisOptRadio = thisOpt.find('.accessiblecbo-opt-radio');
if (typeof change == 'undefined') change = true;
dom.cboOpt.removeClass('is-selected');
thisOpt.addClass('is-selected');
if (change == true) {
thisOptRadio.focus().prop('checked', true);
dom.cboBtnTxt.text(thisOptRadio.siblings('.accessiblecbo-opt-txt').text());
}
};
fn.replaceCbo();
dom.cboBtn.on('click', function(e) {
e.preventDefault();
if (e.type != 'keydown' || e.keyCode === 13 || e.keyCode === 32) {
if (!config.propDisabled) {
fn.toggleExpandCbo();
}
}
});
dom.cboOpt.on({
mouseover: function(e) {
var $this = $(this);
fn.activeOpt($this, false);
},
mousedown: function(e) {
var $this = $(this);
fn.activeOpt($this);
fn.toggleExpandCbo('close');
}
});
dom.cboOptRadio.on('keydown', function(e) {
var $this = $(this);
if (e.keyCode === 9 || e.keyCode === 13) {
e.preventDefault();
dom.cboBtn.focus();
fn.toggleExpandCbo('close');
} else if (e.keyCode >= 37 && e.keyCode <= 40) {
e.preventDefault();
var thisOpt = $this.parent('.accessiblecbo-opt'),
thisOptIdx = dom.cboOpt.index(thisOpt),
controlsOpt,
allOptLen = dom.cboOpt.length,
listboxHeight = dom.cboListbox.height(),
listboxOffsetTop = dom.cboListbox.offset().top,
listboxScrollTop = dom.cboListbox.scrollTop();
if (e.keyCode >= 37 && e.keyCode <= 38) {
if (thisOptIdx == 0) controlsOpt = dom.cboOpt.last();
else controlsOpt = dom.cboOpt.eq(thisOptIdx - 1);
} else if (e.keyCode >= 39 && e.keyCode <= 40) {
if (thisOptIdx == (allOptLen - 1)) controlsOpt = dom.cboOpt.first();
else controlsOpt = dom.cboOpt.eq(thisOptIdx + 1);
}
var controlsOptHeight = controlsOpt.height(),
controlsOptOffsetTop = controlsOpt.offset().top - listboxOffsetTop + listboxScrollTop;
setTimeout(function() {
fn.activeOpt(controlsOpt);
if (controlsOptOffsetTop >= (listboxHeight + listboxScrollTop)) {
dom.cboListbox.scrollTop(controlsOptOffsetTop - (listboxHeight - controlsOptHeight));
} else if (controlsOptOffsetTop < listboxScrollTop) {
dom.cboListbox.scrollTop(controlsOptOffsetTop);
}
}, 0);
}
});
};
$(function() {
$('select[data-accessiblecbo]').each(function() {
var $this = $(this),
argumentStr = $this.attr('data-accessiblecbo'),
argumentObj = eval('({' + argumentStr + '})');
$this.accessibleCombobox(argumentObj);
});
});
}(jQuery));
| choi4450/combobAx | dist/jquery.accessiblecombobox-0.1.0.js | JavaScript | mit | 8,150 |
/****************************************************************************
** Meta object code from reading C++ file 'paymentserver.h'
**
** Created: Wed Jan 15 20:36:01 2014
** by: The Qt Meta Object Compiler version 63 (Qt 4.8.3)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../src/qt/paymentserver.h"
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'paymentserver.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 63
#error "This file was generated using the moc from 4.8.3. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
static const uint qt_meta_data_PaymentServer[] = {
// content:
6, // revision
0, // classname
0, 0, // classinfo
3, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
1, // signalCount
// signals: signature, parameters, type, tag, flags
15, 14, 14, 14, 0x05,
// slots: signature, parameters, type, tag, flags
36, 14, 14, 14, 0x0a,
46, 14, 14, 14, 0x08,
0 // eod
};
static const char qt_meta_stringdata_PaymentServer[] = {
"PaymentServer\0\0receivedURI(QString)\0"
"uiReady()\0handleURIConnection()\0"
};
void PaymentServer::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
Q_ASSERT(staticMetaObject.cast(_o));
PaymentServer *_t = static_cast<PaymentServer *>(_o);
switch (_id) {
case 0: _t->receivedURI((*reinterpret_cast< QString(*)>(_a[1]))); break;
case 1: _t->uiReady(); break;
case 2: _t->handleURIConnection(); break;
default: ;
}
}
}
const QMetaObjectExtraData PaymentServer::staticMetaObjectExtraData = {
0, qt_static_metacall
};
const QMetaObject PaymentServer::staticMetaObject = {
{ &QObject::staticMetaObject, qt_meta_stringdata_PaymentServer,
qt_meta_data_PaymentServer, &staticMetaObjectExtraData }
};
#ifdef Q_NO_DATA_RELOCATION
const QMetaObject &PaymentServer::getStaticMetaObject() { return staticMetaObject; }
#endif //Q_NO_DATA_RELOCATION
const QMetaObject *PaymentServer::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject;
}
void *PaymentServer::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_PaymentServer))
return static_cast<void*>(const_cast< PaymentServer*>(this));
return QObject::qt_metacast(_clname);
}
int PaymentServer::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QObject::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 3)
qt_static_metacall(this, _c, _id, _a);
_id -= 3;
}
return _id;
}
// SIGNAL 0
void PaymentServer::receivedURI(QString _t1)
{
void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
QMetaObject::activate(this, &staticMetaObject, 0, _a);
}
QT_END_MOC_NAMESPACE
| BenFromLA/HFRcoin | build/moc_paymentserver.cpp | C++ | mit | 3,334 |
export { default } from 'ember-paper/components/paper-autocomplete/eps-trigger/component';
| bjornharrtell/ember-paper | app/components/paper-autocomplete/eps-trigger.js | JavaScript | mit | 91 |
Blumine::Application.routes.draw do
get 'register' => 'users#new'
get '/search/:keyword' => 'issues#search'
get 'rebuild_index' => 'issues#rebuild_index'
get '/stats' => "pages#stats"
post '/user_sessions' => "user_sessions#create"
get 'logout' => "user_sessions#destroy"
post '/assigned_issues/sort' => 'issue_assignments#sort'
resources :activities, :only => :create
resources :users, :comments
resources :projects do
resources :issues do
collection do
get 'new/:label' => 'issues#new'
get 'filter/:state', :action => 'index'
get 'label/:label', :action => 'view_by_label'
end
end
resources :milestones, :documents
end
get "milestones/new"
post "milestones/create"
resources :issues do
resources :comments
resources :todo_items
member do
post 'change_state'
post 'assign_to'
post 'planning'
end
collection do
get 'autocomplete'
end
end
resources :todo_items do
member do
post :change_state
end
collection do
post :sort
end
end
resource :account
resources :images, :only => [:new, :create, :destroy]
namespace 'sudo' do
resources :users
end
root :to => "pages#index"
# The priority is based upon order of creation:
# first created -> highest priority.
# Sample of regular route:
# match 'products/:id' => 'catalog#view'
# Keep in mind you can assign values other than :controller and :action
# Sample of named route:
# match 'products/:id/purchase' => 'catalog#purchase', :as => :purchase
# This route can be invoked with purchase_url(:id => product.id)
# Sample resource route (maps HTTP verbs to controller actions automatically):
# resources :products
# Sample resource route with options:
# resources :products do
# member do
# get 'short'
# post 'toggle'
# end
#
# collection do
# get 'sold'
# end
# end
# Sample resource route with sub-resources:
# resources :products do
# resources :comments, :sales
# resource :seller
# end
# Sample resource route with more complex sub-resources
# resources :products do
# resources :comments
# resources :sales do
# get 'recent', :on => :collection
# end
# end
# Sample resource route within a namespace:
# namespace :admin do
# # Directs /admin/products/* to Admin::ProductsController
# # (app/controllers/admin/products_controller.rb)
# resources :products
# end
# You can have the root of your site routed with "root"
# just remember to delete public/index.html.
# root :to => "welcome#index"
# See how all your routes lay out with "rake routes"
# This is a legacy wild controller route that's not recommended for RESTful applications.
# Note: This route will make all actions in every controller accessible via GET requests.
# match ':controller(/:action(/:id(.:format)))'
end
| forging2012/blumine | config/routes.rb | Ruby | mit | 3,009 |
from hamper.interfaces import ChatCommandPlugin, Command
try:
# Python 2
import HTMLParser
html = HTMLParser.HTMLParser()
except ImportError:
# Python 3
import html.parser
html = html.parser.HTMLParser()
import re
import requests
import json
class Lookup(ChatCommandPlugin):
name = 'lookup'
priority = 2
short_desc = 'lookup <something> - look something up'
long_desc = ('lookup and cite <something> - look something up and cite a '
'source\n')
# Inspired by http://googlesystem.blogspot.com/2009/12/on-googles-unofficial-dictionary-api.html # noqa
search_url = "http://www.google.com/dictionary/json?callback=dict_api.callbacks.id100&q={query}&sl=en&tl=en&restrict=pr%2Cde&client=te" # noqa
def setup(self, loader):
super(Lookup, self).setup(loader)
class Lookup(Command):
name = 'lookup'
regex = '^(lookup\s+and\s+cite|lookup)\s*(\d+)?\s+(.*)'
def command(self, bot, comm, groups):
lookup_type = groups[0]
def_num = int(groups[1]) if groups[1] else 1
query = groups[2]
resp = requests.get(self.plugin.search_url.format(query=query))
if resp.status_code != 200:
raise Exception(
"Lookup Error: A non 200 status code was returned"
)
# We have actually asked for this cruft to be tacked onto our JSON
# response. When I tried to remove the callback parameter from the
# URL the api broke, so I'm going to leave it. Put it down, and
# walk away...
# Strip off the JS callback
gr = resp.content.strip('dict_api.callbacks.id100(')
gr = gr.strip(',200,null)')
gr = gr.replace('\\x', "\u00") # Google uses javascript JSON crap
gr = json.loads(gr)
if 'primaries' in gr:
entries = gr['primaries'][0]['entries']
elif 'webDefinitions' in gr:
entries = gr['webDefinitions'][0]['entries']
else:
bot.reply(comm, "No definition found")
return False
seen = 0
definition = None
url = None
for entry in entries:
if not entry['type'] == 'meaning':
continue
for term in entry['terms']:
if term['type'] == 'url':
url = re.sub('<[^<]+?>', '', term['text'])
else:
seen += 1
if not definition and seen == def_num:
definition = term['text']
if not definition or def_num > seen:
bot.reply(
comm,
"Looks like there might not be %s definitions" % def_num
)
else:
bot.reply(
comm, "%s (%s/%s)" % (
html.unescape(definition), def_num, seen
)
)
if 'cite' in lookup_type:
if url:
bot.reply(comm, html.unescape(url))
else:
bot.reply(comm, '[No citation]')
# Always let the other plugins run
return False
| iankronquist/hamper | hamper/plugins/dictionary.py | Python | mit | 3,376 |
class AddLogoToInstitutions < ActiveRecord::Migration
def change
add_column :institutions, :logo, :string
end
end
| CDLUC3/dash-ingest | db/migrate/20140811213557_add_logo_to_institutions.rb | Ruby | mit | 122 |
/*
* The MIT License
*
* Copyright (c) 2004-2010, Sun Microsystems, Inc.
*
* 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.
*/
package hudson.cli;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.Cause;
import hudson.model.ParametersAction;
import hudson.model.ParameterValue;
import hudson.model.ParametersDefinitionProperty;
import hudson.model.ParameterDefinition;
import hudson.Extension;
import hudson.AbortException;
import hudson.model.Item;
import hudson.util.EditDistance;
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.Option;
import java.util.concurrent.Future;
import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Map.Entry;
import java.io.PrintStream;
/**
* Builds a job, and optionally waits until its completion.
*
* @author Kohsuke Kawaguchi
*/
@Extension
public class BuildCommand extends CLICommand {
@Override
public String getShortDescription() {
return "Builds a job, and optionally waits until its completion.";
}
@Argument(metaVar="JOB",usage="Name of the job to build",required=true)
public AbstractProject<?,?> job;
@Option(name="-s",usage="Wait until the completion/abortion of the command")
public boolean sync = false;
@Option(name="-p",usage="Specify the build parameters in the key=value format.")
public Map<String,String> parameters = new HashMap<String, String>();
protected int run() throws Exception {
job.checkPermission(Item.BUILD);
ParametersAction a = null;
if (!parameters.isEmpty()) {
ParametersDefinitionProperty pdp = job.getProperty(ParametersDefinitionProperty.class);
if (pdp==null)
throw new AbortException(job.getFullDisplayName()+" is not parameterized but the -p option was specified");
List<ParameterValue> values = new ArrayList<ParameterValue>();
for (Entry<String, String> e : parameters.entrySet()) {
String name = e.getKey();
ParameterDefinition pd = pdp.getParameterDefinition(name);
if (pd==null)
throw new AbortException(String.format("\'%s\' is not a valid parameter. Did you mean %s?",
name, EditDistance.findNearest(name, pdp.getParameterDefinitionNames())));
values.add(pd.createValue(this,e.getValue()));
}
for (ParameterDefinition pd : pdp.getParameterDefinitions()) {
if (parameters.get(pd.getName()) == null) {
values.add(pd.getDefaultParameterValue());
}
}
a = new ParametersAction(values);
}
Future<? extends AbstractBuild> f = job.scheduleBuild2(0, new CLICause(), a);
if (!sync) return 0;
AbstractBuild b = f.get(); // wait for the completion
stdout.println("Completed "+b.getFullDisplayName()+" : "+b.getResult());
return b.getResult().ordinal;
}
@Override
protected void printUsageSummary(PrintStream stderr) {
stderr.println(
"Starts a build, and optionally waits for a completion.\n" +
"Aside from general scripting use, this command can be\n" +
"used to invoke another job from within a build of one job.\n" +
"With the -s option, this command changes the exit code based on\n" +
"the outcome of the build (exit code 0 indicates a success.)\n"
);
}
// TODO: CLI can authenticate as different users, so should record which user here..
public static class CLICause extends Cause {
public String getShortDescription() {
return "Started by command line";
}
@Override
public boolean equals(Object o) {
return o instanceof CLICause;
}
@Override
public int hashCode() {
return 7;
}
}
}
| sincere520/testGitRepo | hudson-core/src/main/java/hudson/cli/BuildCommand.java | Java | mit | 5,030 |
/**
* ReturnTrue
*/
var returnTrue = function() {
return true;
}; | apiaryio/Amanda | src/utils/returnTrue.js | JavaScript | mit | 69 |
#include <iostream>
auto main() -> int {
std::cout << "abc";
std::cout.flush();
std::cout << "def";
std::cout << std::endl;
return 0;
}
| ordinary-developer/book_professional_c_plus_plus_3_ed_m_gregoire | my_code/chapter_12/04_flush/main.cpp | C++ | mit | 159 |
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.autobahn = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
// shim for using process in browser
var process = module.exports = {};
var queue = [];
var draining = false;
function drainQueue() {
if (draining) {
return;
}
draining = true;
var currentQueue;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
var i = -1;
while (++i < len) {
currentQueue[i]();
}
len = queue.length;
}
draining = false;
}
process.nextTick = function (fun) {
queue.push(fun);
if (!draining) {
setTimeout(drainQueue, 0);
}
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
// TODO(shtylman)
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
},{}],2:[function(require,module,exports){
///////////////////////////////////////////////////////////////////////////////
//
// AutobahnJS - http://autobahn.ws, http://wamp.ws
//
// A JavaScript library for WAMP ("The Web Application Messaging Protocol").
//
// Copyright (C) 2011-2014 Tavendo GmbH, http://tavendo.com
//
// Licensed under the MIT License.
// http://www.opensource.org/licenses/mit-license.php
//
///////////////////////////////////////////////////////////////////////////////
// require('assert') would be nice .. but it does not
// work with Google Closure after Browserify
var crypto = require('crypto-js');
// PBKDF2-base key derivation function for salted WAMP-CRA
//
function derive_key (secret, salt, iterations, keylen) {
var iterations = iterations || 1000;
var keylen = keylen || 32;
var config = {
keySize: keylen / 4,
iterations: iterations,
hasher: crypto.algo.SHA256
}
var key = crypto.PBKDF2(secret, salt, config);
return key.toString(crypto.enc.Base64);
}
function sign (key, challenge) {
return crypto.HmacSHA256(challenge, key).toString(crypto.enc.Base64);
}
exports.sign = sign;
exports.derive_key = derive_key;
},{"crypto-js":28}],3:[function(require,module,exports){
///////////////////////////////////////////////////////////////////////////////
//
// AutobahnJS - http://autobahn.ws, http://wamp.ws
//
// A JavaScript library for WAMP ("The Web Application Messaging Protocol").
//
// Copyright (C) 2011-2014 Tavendo GmbH, http://tavendo.com
//
// Licensed under the MIT License.
// http://www.opensource.org/licenses/mit-license.php
//
///////////////////////////////////////////////////////////////////////////////
var when = require('when');
var when_fn = require("when/function");
function auth(session, user, extra) {
// Persona Issues:
//
// Chrome: https://github.com/mozilla/persona/issues/4083
// IE11: https://groups.google.com/forum/#!topic/mozilla.dev.identity/keEkVpvfLA8
var d = session.defer();
navigator.id.watch({
loggedInUser: user,
onlogin: function (assertion) {
// A user has logged in! Here you need to:
// 1. Send the assertion to your backend for verification and to create a session.
// 2. Update your UI.
d.resolve(assertion);
},
onlogout: function() {
// A user has logged out! Here you need to:
// Tear down the user's session by redirecting the user or making a call to your backend.
// Also, make sure loggedInUser will get set to null on the next page load.
// (That's a literal JavaScript null. Not false, 0, or undefined. null.)
session.leave("wamp.close.logout");
}
});
if (d.promise.then) {
// whenjs has the actual user promise in an attribute
return d.promise;
} else {
return d;
}
}
exports.auth = auth;
},{"when":78,"when/function":54}],4:[function(require,module,exports){
(function (global){
///////////////////////////////////////////////////////////////////////////////
//
// AutobahnJS - http://autobahn.ws, http://wamp.ws
//
// A JavaScript library for WAMP ("The Web Application Messaging Protocol").
//
// Copyright (C) 2011-2014 Tavendo GmbH, http://tavendo.com
//
// Licensed under the MIT License.
// http://www.opensource.org/licenses/mit-license.php
//
///////////////////////////////////////////////////////////////////////////////
// Polyfills for <= IE9
require('./polyfill.js');
var pjson = require('../package.json');
var when = require('when');
//var fn = require("when/function");
if ('AUTOBAHN_DEBUG' in global && AUTOBAHN_DEBUG) {
// https://github.com/cujojs/when/blob/master/docs/api.md#whenmonitor
require('when/monitor/console');
if ('console' in global) {
console.log("AutobahnJS debug enabled");
}
}
var util = require('./util.js');
var log = require('./log.js');
var session = require('./session.js');
var connection = require('./connection.js');
var configure = require('./configure.js');
var persona = require('./auth/persona.js');
var cra = require('./auth/cra.js');
exports.version = pjson.version;
exports.transports = configure.transports;
exports.Connection = connection.Connection;
exports.Session = session.Session;
exports.Invocation = session.Invocation;
exports.Event = session.Event;
exports.Result = session.Result;
exports.Error = session.Error;
exports.Subscription = session.Subscription;
exports.Registration = session.Registration;
exports.Publication = session.Publication;
exports.auth_persona = persona.auth;
exports.auth_cra = cra;
exports.when = when;
exports.util = util;
exports.log = log;
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"../package.json":80,"./auth/cra.js":2,"./auth/persona.js":3,"./configure.js":5,"./connection.js":6,"./log.js":7,"./polyfill.js":8,"./session.js":16,"./util.js":19,"when":78,"when/monitor/console":76}],5:[function(require,module,exports){
///////////////////////////////////////////////////////////////////////////////
//
// AutobahnJS - http://autobahn.ws, http://wamp.ws
//
// A JavaScript library for WAMP ("The Web Application Messaging Protocol").
//
// Copyright (C) 2011-2014 Tavendo GmbH, http://tavendo.com
//
// Licensed under the MIT License.
// http://www.opensource.org/licenses/mit-license.php
//
///////////////////////////////////////////////////////////////////////////////
function Transports() {
this._repository = {};
}
Transports.prototype.register = function (name, factory) {
this._repository[name] = factory;
};
Transports.prototype.isRegistered = function (name) {
return this._repository[name] ? true : false;
};
Transports.prototype.get = function (name) {
if (this._repository[name] !== undefined) {
return this._repository[name];
} else {
throw "no such transport: " + name;
}
}
Transports.prototype.list = function() {
var items = [];
for (var name in this._repository) {
items.push(name);
}
return items;
};
var _transports = new Transports();
// register default transports
var websocket = require('./transport/websocket.js');
_transports.register("websocket", websocket.Factory);
var longpoll = require('./transport/longpoll.js');
_transports.register("longpoll", longpoll.Factory);
exports.transports = _transports;
},{"./transport/longpoll.js":17,"./transport/websocket.js":18}],6:[function(require,module,exports){
(function (global){
///////////////////////////////////////////////////////////////////////////////
//
// AutobahnJS - http://autobahn.ws, http://wamp.ws
//
// A JavaScript library for WAMP ("The Web Application Messaging Protocol").
//
// Copyright (C) 2011-2014 Tavendo GmbH, http://tavendo.com
//
// Licensed under the MIT License.
// http://www.opensource.org/licenses/mit-license.php
//
///////////////////////////////////////////////////////////////////////////////
var when = require('when');
var session = require('./session.js');
var util = require('./util.js');
var log = require('./log.js');
var autobahn = require('./autobahn.js');
var Connection = function (options) {
var self = this;
self._options = options;
// Deferred factory
//
if (options && options.use_es6_promises) {
if ('Promise' in global) {
// ES6-based deferred factory
//
self._defer = function () {
var deferred = {};
deferred.promise = new Promise(function (resolve, reject) {
deferred.resolve = resolve;
deferred.reject = reject;
});
return deferred;
};
} else {
log.debug("Warning: ES6 promises requested, but not found! Falling back to whenjs.");
// whenjs-based deferred factory
//
self._defer = when.defer;
}
} else if (options && options.use_deferred) {
// use explicit deferred factory, e.g. jQuery.Deferred or Q.defer
//
self._defer = options.use_deferred;
} else {
// whenjs-based deferred factory
//
self._defer = when.defer;
}
// WAMP transport
//
// backward compatiblity
if (!self._options.transports) {
self._options.transports = [
{
type: 'websocket',
url: self._options.url
}
];
}
self._transport_factories = [];
self._init_transport_factories();
// WAMP session
//
self._session = null;
self._session_close_reason = null;
self._session_close_message = null;
// automatic reconnection configuration
//
// enable automatic reconnect if host is unreachable
if (self._options.retry_if_unreachable !== undefined) {
self._retry_if_unreachable = self._options.retry_if_unreachable;
} else {
self._retry_if_unreachable = true;
}
// maximum number of reconnection attempts
self._max_retries = self._options.max_retries || 15;
// initial retry delay in seconds
self._initial_retry_delay = self._options.initial_retry_delay || 1.5;
// maximum seconds between reconnection attempts
self._max_retry_delay = self._options.max_retry_delay || 300;
// the growth factor applied to the retry delay on each retry cycle
self._retry_delay_growth = self._options.retry_delay_growth || 1.5;
// the SD of a Gaussian to jitter the delay on each retry cycle
// as a fraction of the mean
self._retry_delay_jitter = self._options.retry_delay_jitter || 0.1;
// reconnection tracking
//
// total number of successful connections
self._connect_successes = 0;
// controls if we should try to reconnect
self._retry = false;
// current number of reconnect cycles we went through
self._retry_count = 0;
// the current retry delay
self._retry_delay = self._initial_retry_delay;
// flag indicating if we are currently in a reconnect cycle
self._is_retrying = false;
// when retrying, this is the timer object returned from window.setTimeout()
self._retry_timer = null;
};
Connection.prototype._create_transport = function () {
for (var i = 0; i < this._transport_factories.length; ++i) {
var transport_factory = this._transport_factories[i];
log.debug("trying to create WAMP transport of type: " + transport_factory.type);
try {
var transport = transport_factory.create();
if (transport) {
log.debug("using WAMP transport type: " + transport_factory.type);
return transport;
}
} catch (e) {
// ignore
log.debug("could not create WAMP transport '" + transport_factory.type + "': " + e);
}
}
// could not create any WAMP transport
return null;
};
Connection.prototype._init_transport_factories = function () {
// WAMP transport
//
var transports, transport_options, transport_factory, transport_factory_klass;
util.assert(this._options.transports, "No transport.factory specified");
transports = this._options.transports;
//if(typeof transports === "object") {
// this._options.transports = [transports];
//}
for(var i = 0; i < this._options.transports.length; ++i) {
// cascading transports until we find one which works
transport_options = this._options.transports[i];
if (!transport_options.url) {
// defaulting to options.url if none is provided
transport_options.url = this._options.url;
}
if (!transport_options.protocols) {
transport_options.protocols = this._options.protocols;
}
util.assert(transport_options.type, "No transport.type specified");
util.assert(typeof transport_options.type === "string", "transport.type must be a string");
try {
transport_factory_klass = autobahn.transports.get(transport_options.type);
if (transport_factory_klass) {
transport_factory = new transport_factory_klass(transport_options);
this._transport_factories.push(transport_factory);
}
} catch (exc) {
console.error(exc);
}
}
};
Connection.prototype._autoreconnect_reset_timer = function () {
var self = this;
if (self._retry_timer) {
clearTimeout(self._retry_timer);
}
self._retry_timer = null;
}
Connection.prototype._autoreconnect_reset = function () {
var self = this;
self._autoreconnect_reset_timer();
self._retry_count = 0;
self._retry_delay = self._initial_retry_delay;
self._is_retrying = false;
}
Connection.prototype._autoreconnect_advance = function () {
var self = this;
// jitter retry delay
if (self._retry_delay_jitter) {
self._retry_delay = util.rand_normal(self._retry_delay, self._retry_delay * self._retry_delay_jitter);
}
// cap the retry delay
if (self._retry_delay > self._max_retry_delay) {
self._retry_delay = self._max_retry_delay;
}
// count number of retries
self._retry_count += 1;
var res;
if (self._retry && self._retry_count <= self._max_retries) {
res = {
count: self._retry_count,
delay: self._retry_delay,
will_retry: true
};
} else {
res = {
count: null,
delay: null,
will_retry: false
}
}
// retry delay growth for next retry cycle
if (self._retry_delay_growth) {
self._retry_delay = self._retry_delay * self._retry_delay_growth;
}
return res;
}
Connection.prototype.open = function () {
var self = this;
if (self._transport) {
throw "connection already open (or opening)";
}
self._autoreconnect_reset();
self._retry = true;
function retry () {
// create a WAMP transport
self._transport = self._create_transport();
if (!self._transport) {
// failed to create a WAMP transport
self._retry = false;
if (self.onclose) {
var details = {
reason: null,
message: null,
retry_delay: null,
retry_count: null,
will_retry: false
};
self.onclose("unsupported", details);
}
return;
}
// create a new WAMP session using the WebSocket connection as transport
self._session = new session.Session(self._transport, self._defer, self._options.onchallenge);
self._session_close_reason = null;
self._session_close_message = null;
self._transport.onopen = function () {
// reset auto-reconnect timer and tracking
self._autoreconnect_reset();
// log successful connections
self._connect_successes += 1;
// start WAMP session
self._session.join(self._options.realm, self._options.authmethods, self._options.authid);
};
self._session.onjoin = function (details) {
if (self.onopen) {
try {
self.onopen(self._session, details);
} catch (e) {
log.debug("Exception raised from app code while firing Connection.onopen()", e);
}
}
};
//
// ... WAMP session is now attached to realm.
//
self._session.onleave = function (reason, details) {
self._session_close_reason = reason;
self._session_close_message = details.message || "";
self._retry = false;
self._transport.close(1000);
};
self._transport.onclose = function (evt) {
// remove any pending reconnect timer
self._autoreconnect_reset_timer();
self._transport = null;
var reason = null;
if (self._connect_successes === 0) {
reason = "unreachable";
if (!self._retry_if_unreachable) {
self._retry = false;
}
} else if (!evt.wasClean) {
reason = "lost";
} else {
reason = "closed";
}
var next_retry = self._autoreconnect_advance();
// fire app code handler
//
if (self.onclose) {
var details = {
reason: self._session_close_reason,
message: self._session_close_message,
retry_delay: next_retry.delay,
retry_count: next_retry.count,
will_retry: next_retry.will_retry
};
try {
// Connection.onclose() allows to cancel any subsequent retry attempt
var stop_retrying = self.onclose(reason, details);
} catch (e) {
log.debug("Exception raised from app code while firing Connection.onclose()", e);
}
}
// reset session info
//
if (self._session) {
self._session._id = null;
self._session = null;
self._session_close_reason = null;
self._session_close_message = null;
}
// automatic reconnection
//
if (self._retry && !stop_retrying) {
if (next_retry.will_retry) {
self._is_retrying = true;
log.debug("retrying in " + next_retry.delay + " s");
self._retry_timer = setTimeout(retry, next_retry.delay * 1000);
} else {
log.debug("giving up trying to reconnect");
}
}
}
}
retry();
};
Connection.prototype.close = function (reason, message) {
var self = this;
if (!self._transport && !self._is_retrying) {
throw "connection already closed";
}
// the app wants to close .. don't retry
self._retry = false;
if (self._session && self._session.isOpen) {
// if there is an open session, close that first.
self._session.leave(reason, message);
} else if (self._transport) {
// no session active: just close the transport
self._transport.close(1000);
}
};
Object.defineProperty(Connection.prototype, "defer", {
get: function () {
return this._defer;
}
});
Object.defineProperty(Connection.prototype, "session", {
get: function () {
return this._session;
}
});
Object.defineProperty(Connection.prototype, "isOpen", {
get: function () {
if (this._session && this._session.isOpen) {
return true;
} else {
return false;
}
}
});
Object.defineProperty(Connection.prototype, "isConnected", {
get: function () {
if (this._transport) {
return true;
} else {
return false;
}
}
});
Object.defineProperty(Connection.prototype, "transport", {
get: function () {
if (this._transport) {
return this._transport;
} else {
return {info: {type: 'none', url: null, protocol: null}};
}
}
});
Object.defineProperty(Connection.prototype, "isRetrying", {
get: function () {
return this._is_retrying;
}
});
exports.Connection = Connection;
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./autobahn.js":4,"./log.js":7,"./session.js":16,"./util.js":19,"when":78}],7:[function(require,module,exports){
(function (global){
///////////////////////////////////////////////////////////////////////////////
//
// AutobahnJS - http://autobahn.ws, http://wamp.ws
//
// A JavaScript library for WAMP ("The Web Application Messaging Protocol").
//
// Copyright (C) 2011-2014 Tavendo GmbH, http://tavendo.com
//
// Licensed under the MIT License.
// http://www.opensource.org/licenses/mit-license.php
//
///////////////////////////////////////////////////////////////////////////////
var debug = function () {};
if ('AUTOBAHN_DEBUG' in global && AUTOBAHN_DEBUG && 'console' in global) {
debug = function () {
console.log.apply(console, arguments);
}
}
exports.debug = debug;
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],8:[function(require,module,exports){
require('./polyfill/object');
require('./polyfill/array');
require('./polyfill/string');
require('./polyfill/function');
require('./polyfill/console');
require('./polyfill/typedarray');
require('./polyfill/json');
},{"./polyfill/array":9,"./polyfill/console":10,"./polyfill/function":11,"./polyfill/json":12,"./polyfill/object":13,"./polyfill/string":14,"./polyfill/typedarray":15}],9:[function(require,module,exports){
if ( 'function' !== typeof Array.prototype.reduce ) {
Array.prototype.reduce = function( callback /*, initialValue*/ ) {
'use strict';
var len, t, value, k;
if ( null === this || 'undefined' === typeof this ) {
throw new TypeError(
'Array.prototype.reduce called on null or undefined' );
}
if ( 'function' !== typeof callback ) {
throw new TypeError( callback + ' is not a function' );
}
t = Object( this );
len = t.length >>> 0;
k = 0;
if ( arguments.length >= 2 ) {
value = arguments[1];
} else {
while ( k < len && ! k in t ) k++;
if ( k >= len )
throw new TypeError('Reduce of empty array with no initial value');
value = t[ k++ ];
}
for ( ; k < len ; k++ ) {
if ( k in t ) {
value = callback( value, t[k], k, t );
}
}
return value;
};
}
// Add ECMA262-5 Array methods if not supported natively
//
if (!('indexOf' in Array.prototype)) {
Array.prototype.indexOf= function(find, i /*opt*/) {
if (i===undefined) i= 0;
if (i<0) i+= this.length;
if (i<0) i= 0;
for (var n= this.length; i<n; i++)
if (i in this && this[i]===find)
return i;
return -1;
};
}
if (!('lastIndexOf' in Array.prototype)) {
Array.prototype.lastIndexOf= function(find, i /*opt*/) {
if (i===undefined) i= this.length-1;
if (i<0) i+= this.length;
if (i>this.length-1) i= this.length-1;
for (i++; i-->0;) /* i++ because from-argument is sadly inclusive */
if (i in this && this[i]===find)
return i;
return -1;
};
}
if (!('forEach' in Array.prototype)) {
Array.prototype.forEach= function(action, that /*opt*/) {
for (var i= 0, n= this.length; i<n; i++)
if (i in this)
action.call(that, this[i], i, this);
};
}
if (!('map' in Array.prototype)) {
Array.prototype.map= function(mapper, that /*opt*/) {
var other= new Array(this.length);
for (var i= 0, n= this.length; i<n; i++)
if (i in this)
other[i]= mapper.call(that, this[i], i, this);
return other;
};
}
if (!('filter' in Array.prototype)) {
Array.prototype.filter= function(filter, that /*opt*/) {
var other= [], v;
for (var i=0, n= this.length; i<n; i++)
if (i in this && filter.call(that, v= this[i], i, this))
other.push(v);
return other;
};
}
if (!('every' in Array.prototype)) {
Array.prototype.every= function(tester, that /*opt*/) {
for (var i= 0, n= this.length; i<n; i++)
if (i in this && !tester.call(that, this[i], i, this))
return false;
return true;
};
}
if (!('some' in Array.prototype)) {
Array.prototype.some= function(tester, that /*opt*/) {
for (var i= 0, n= this.length; i<n; i++)
if (i in this && tester.call(that, this[i], i, this))
return true;
return false;
};
}
if ( 'function' !== typeof Array.prototype.reduceRight ) {
Array.prototype.reduceRight = function( callback /*, initialValue*/ ) {
'use strict';
if ( null === this || 'undefined' === typeof this ) {
throw new TypeError(
'Array.prototype.reduce called on null or undefined' );
}
if ( 'function' !== typeof callback ) {
throw new TypeError( callback + ' is not a function' );
}
var t = Object( this ), len = t.length >>> 0, k = len - 1, value;
if ( arguments.length >= 2 ) {
value = arguments[1];
} else {
while ( k >= 0 && ! k in t ) k--;
if ( k < 0 )
throw new TypeError('Reduce of empty array with no initial value');
value = t[ k-- ];
}
for ( ; k >= 0 ; k-- ) {
if ( k in t ) {
value = callback( value, t[k], k, t );
}
}
return value;
};
}
},{}],10:[function(require,module,exports){
(function (global){
(function(console) {
/*********************************************************************************************
* Make sure console exists because IE blows up if it's not open and you attempt to access it
* Create some dummy functions if we need to, so we don't have to if/else everything
*********************************************************************************************/
console||(console = window.console = {
// all this "a, b, c, d, e" garbage is to make the IDEs happy, since they can't do variable argument lists
/**
* @param a
* @param [b]
* @param [c]
* @param [d]
* @param [e]
*/
log: function(a, b, c, d, e) {},
/**
* @param a
* @param [b]
* @param [c]
* @param [d]
* @param [e]
*/
info: function(a, b, c, d, e) {},
/**
* @param a
* @param [b]
* @param [c]
* @param [d]
* @param [e]
*/
warn: function(a, b, c, d, e) {},
/**
* @param a
* @param [b]
* @param [c]
* @param [d]
* @param [e]
*/
error: function(a, b, c, d, e) {},
assert: function(test, message) {}
});
// IE 9 won't allow us to call console.log.apply (WTF IE!) It also reports typeof(console.log) as 'object' (UNH!)
// but together, those two errors can be useful in allowing us to fix stuff so it works right
if( typeof(console.log) === 'object' ) {
// Array.forEach doesn't work in IE 8 so don't try that :(
console.log = Function.prototype.call.bind(console.log, console);
console.info = Function.prototype.call.bind(console.info, console);
console.warn = Function.prototype.call.bind(console.warn, console);
console.error = Function.prototype.call.bind(console.error, console);
console.debug = Function.prototype.call.bind(console.info, console);
}
/**
* Support group and groupEnd functions
*/
('group' in console) ||
(console.group = function(msg) {
console.info("\n--- "+msg+" ---\n");
});
('groupEnd' in console) ||
(console.groupEnd = function() {
console.log("\n");
});
('assert' in console) ||
(console.assert = function(test, message) {
if (!test) {
try {
// attempt to preserve the stack
throw new Error("assertion failed: " + message);
} catch(error) {
setTimeout(function(){
throw error;
}, 0);
}
}
});
/**
* Support time and timeEnd functions
*/
('time' in console) ||
(function() {
var trackedTimes = {};
console.time = function(msg) {
trackedTimes[msg] = new Date().getTime();
};
console.timeEnd = function(msg) {
var end = new Date().getTime(), time = (msg in trackedTimes)? end - trackedTimes[msg] : 0;
console.info(msg+': '+time+'ms')
};
}());
})(global.console);
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],11:[function(require,module,exports){
if (!Function.prototype.bind) {
//credits: taken from bind_even_never in this discussion: https://prototype.lighthouseapp.com/projects/8886/tickets/215-optimize-bind-bindaseventlistener#ticket-215-9
Function.prototype.bind = function(context) {
var fn = this, args = Array.prototype.slice.call(arguments, 1);
return function(){
return fn.apply(context, Array.prototype.concat.apply(args, arguments));
};
};
}
},{}],12:[function(require,module,exports){
/*
json2.js
2014-02-04
Public Domain.
NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
See http://www.JSON.org/js.html
This code should be minified before deployment.
See http://javascript.crockford.com/jsmin.html
USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
NOT CONTROL.
This file creates a global JSON object containing two methods: stringify
and parse.
JSON.stringify(value, replacer, space)
value any JavaScript value, usually an object or array.
replacer an optional parameter that determines how object
values are stringified for objects. It can be a
function or an array of strings.
space an optional parameter that specifies the indentation
of nested structures. If it is omitted, the text will
be packed without extra whitespace. If it is a number,
it will specify the number of spaces to indent at each
level. If it is a string (such as '\t' or ' '),
it contains the characters used to indent at each level.
This method produces a JSON text from a JavaScript value.
When an object value is found, if the object contains a toJSON
method, its toJSON method will be called and the result will be
stringified. A toJSON method does not serialize: it returns the
value represented by the name/value pair that should be serialized,
or undefined if nothing should be serialized. The toJSON method
will be passed the key associated with the value, and this will be
bound to the value
For example, this would serialize Dates as ISO strings.
Date.prototype.toJSON = function (key) {
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
return this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z';
};
You can provide an optional replacer method. It will be passed the
key and value of each member, with this bound to the containing
object. The value that is returned from your method will be
serialized. If your method returns undefined, then the member will
be excluded from the serialization.
If the replacer parameter is an array of strings, then it will be
used to select the members to be serialized. It filters the results
such that only members with keys listed in the replacer array are
stringified.
Values that do not have JSON representations, such as undefined or
functions, will not be serialized. Such values in objects will be
dropped; in arrays they will be replaced with null. You can use
a replacer function to replace those with JSON values.
JSON.stringify(undefined) returns undefined.
The optional space parameter produces a stringification of the
value that is filled with line breaks and indentation to make it
easier to read.
If the space parameter is a non-empty string, then that string will
be used for indentation. If the space parameter is a number, then
the indentation will be that many spaces.
Example:
text = JSON.stringify(['e', {pluribus: 'unum'}]);
// text is '["e",{"pluribus":"unum"}]'
text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
// text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
text = JSON.stringify([new Date()], function (key, value) {
return this[key] instanceof Date ?
'Date(' + this[key] + ')' : value;
});
// text is '["Date(---current time---)"]'
JSON.parse(text, reviver)
This method parses a JSON text to produce an object or array.
It can throw a SyntaxError exception.
The optional reviver parameter is a function that can filter and
transform the results. It receives each of the keys and values,
and its return value is used instead of the original value.
If it returns what it received, then the structure is not modified.
If it returns undefined then the member is deleted.
Example:
// Parse the text. Values that look like ISO date strings will
// be converted to Date objects.
myData = JSON.parse(text, function (key, value) {
var a;
if (typeof value === 'string') {
a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
if (a) {
return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
+a[5], +a[6]));
}
}
return value;
});
myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
var d;
if (typeof value === 'string' &&
value.slice(0, 5) === 'Date(' &&
value.slice(-1) === ')') {
d = new Date(value.slice(5, -1));
if (d) {
return d;
}
}
return value;
});
This is a reference implementation. You are free to copy, modify, or
redistribute.
*/
/*jslint evil: true, regexp: true */
/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
lastIndex, length, parse, prototype, push, replace, slice, stringify,
test, toJSON, toString, valueOf
*/
// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.
if (typeof JSON !== 'object') {
JSON = {};
}
(function () {
'use strict';
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
if (typeof Date.prototype.toJSON !== 'function') {
Date.prototype.toJSON = function () {
return isFinite(this.valueOf())
? this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z'
: null;
};
String.prototype.toJSON =
Number.prototype.toJSON =
Boolean.prototype.toJSON = function () {
return this.valueOf();
};
}
var cx,
escapable,
gap,
indent,
meta,
rep;
function quote(string) {
// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.
escapable.lastIndex = 0;
return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
var c = meta[a];
return typeof c === 'string'
? c
: '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
}) + '"' : '"' + string + '"';
}
function str(key, holder) {
// Produce a string from holder[key].
var i, // The loop counter.
k, // The member key.
v, // The member value.
length,
mind = gap,
partial,
value = holder[key];
// If the value has a toJSON method, call it to obtain a replacement value.
if (value && typeof value === 'object' &&
typeof value.toJSON === 'function') {
value = value.toJSON(key);
}
// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.
if (typeof rep === 'function') {
value = rep.call(holder, key, value);
}
// What happens next depends on the value's type.
switch (typeof value) {
case 'string':
return quote(value);
case 'number':
// JSON numbers must be finite. Encode non-finite numbers as null.
return isFinite(value) ? String(value) : 'null';
case 'boolean':
case 'null':
// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce 'null'. The case is included here in
// the remote chance that this gets fixed someday.
return String(value);
// If the type is 'object', we might be dealing with an object or an array or
// null.
case 'object':
// Due to a specification blunder in ECMAScript, typeof null is 'object',
// so watch out for that case.
if (!value) {
return 'null';
}
// Make an array to hold the partial results of stringifying this object value.
gap += indent;
partial = [];
// Is the value an array?
if (Object.prototype.toString.apply(value) === '[object Array]') {
// The value is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.
length = value.length;
for (i = 0; i < length; i += 1) {
partial[i] = str(i, value) || 'null';
}
// Join all of the elements together, separated with commas, and wrap them in
// brackets.
v = partial.length === 0
? '[]'
: gap
? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']'
: '[' + partial.join(',') + ']';
gap = mind;
return v;
}
// If the replacer is an array, use it to select the members to be stringified.
if (rep && typeof rep === 'object') {
length = rep.length;
for (i = 0; i < length; i += 1) {
if (typeof rep[i] === 'string') {
k = rep[i];
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
} else {
// Otherwise, iterate through all of the keys in the object.
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
}
// Join all of the member texts together, separated with commas,
// and wrap them in braces.
v = partial.length === 0
? '{}'
: gap
? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}'
: '{' + partial.join(',') + '}';
gap = mind;
return v;
}
}
// If the JSON object does not yet have a stringify method, give it one.
if (typeof JSON.stringify !== 'function') {
escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
meta = { // table of character substitutions
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
};
JSON.stringify = function (value, replacer, space) {
// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.
var i;
gap = '';
indent = '';
// If the space parameter is a number, make an indent string containing that
// many spaces.
if (typeof space === 'number') {
for (i = 0; i < space; i += 1) {
indent += ' ';
}
// If the space parameter is a string, it will be used as the indent string.
} else if (typeof space === 'string') {
indent = space;
}
// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.
rep = replacer;
if (replacer && typeof replacer !== 'function' &&
(typeof replacer !== 'object' ||
typeof replacer.length !== 'number')) {
throw new Error('JSON.stringify');
}
// Make a fake root object containing our value under the key of ''.
// Return the result of stringifying the value.
return str('', {'': value});
};
}
// If the JSON object does not yet have a parse method, give it one.
if (typeof JSON.parse !== 'function') {
cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
JSON.parse = function (text, reviver) {
// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON text.
var j;
function walk(holder, key) {
// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.
var k, v, value = holder[key];
if (value && typeof value === 'object') {
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = walk(value, k);
if (v !== undefined) {
value[k] = v;
} else {
delete value[k];
}
}
}
}
return reviver.call(holder, key, value);
}
// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.
text = String(text);
cx.lastIndex = 0;
if (cx.test(text)) {
text = text.replace(cx, function (a) {
return '\\u' +
('0000' + a.charCodeAt(0).toString(16)).slice(-4);
});
}
// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.
// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
if (/^[\],:{}\s]*$/
.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
.replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.
j = eval('(' + text + ')');
// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.
return typeof reviver === 'function'
? walk({'': j}, '')
: j;
}
// If the text is not JSON parseable, then a SyntaxError is thrown.
throw new SyntaxError('JSON.parse');
};
}
}());
exports.JSON = JSON;
},{}],13:[function(require,module,exports){
if (!Object.create) {
Object.create = (function(){
function F(){}
return function(o){
if (arguments.length != 1) {
throw new Error('Object.create implementation only accepts one parameter.');
}
F.prototype = o;
return new F()
}
})()
}
// From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
if (!Object.keys) {
Object.keys = (function () {
'use strict';
var hasOwnProperty = Object.prototype.hasOwnProperty,
hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
dontEnums = [
'toString',
'toLocaleString',
'valueOf',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'constructor'
],
dontEnumsLength = dontEnums.length;
return function (obj) {
if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) {
throw new TypeError('Object.keys called on non-object');
}
var result = [], prop, i;
for (prop in obj) {
if (hasOwnProperty.call(obj, prop)) {
result.push(prop);
}
}
if (hasDontEnumBug) {
for (i = 0; i < dontEnumsLength; i++) {
if (hasOwnProperty.call(obj, dontEnums[i])) {
result.push(dontEnums[i]);
}
}
}
return result;
};
}());
}
},{}],14:[function(require,module,exports){
// Add ECMA262-5 string trim if not supported natively
//
if (!('trim' in String.prototype)) {
String.prototype.trim= function() {
return this.replace(/^\s+/, '').replace(/\s+$/, '');
};
}
},{}],15:[function(require,module,exports){
(function (global){
/*
Copyright (c) 2010, Linden Research, Inc.
Copyright (c) 2014, Joshua Bell
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.
$/LicenseInfo$
*/
// Original can be found at:
// https://bitbucket.org/lindenlab/llsd
// Modifications by Joshua Bell inexorabletash@gmail.com
// https://github.com/inexorabletash/polyfill
// ES3/ES5 implementation of the Krhonos Typed Array Specification
// Ref: http://www.khronos.org/registry/typedarray/specs/latest/
// Date: 2011-02-01
//
// Variations:
// * Allows typed_array.get/set() as alias for subscripts (typed_array[])
// * Gradually migrating structure from Khronos spec to ES6 spec
if (typeof global["Uint8Array"] === "undefined") {
(function (global, win) {
'use strict';
var undefined = (void 0); // Paranoia
// Beyond this value, index getters/setters (i.e. array[0], array[1]) are so slow to
// create, and consume so much memory, that the browser appears frozen.
var MAX_ARRAY_LENGTH = 1e5;
// Approximations of internal ECMAScript conversion functions
function Type(v) {
switch (typeof v) {
case 'undefined':
return 'undefined';
case 'boolean':
return 'boolean';
case 'number':
return 'number';
case 'string':
return 'string';
default:
return v === null ? 'null' : 'object';
}
}
// Class returns internal [[Class]] property, used to avoid cross-frame instanceof issues:
function Class(v) {
return Object.prototype.toString.call(v).replace(/^\[object *|\]$/g, '');
}
function IsCallable(o) {
return typeof o === 'function';
}
function ToObject(v) {
if (v === null || v === undefined) throw TypeError();
return Object(v);
}
function ToInt32(v) {
return v >> 0;
}
function ToUint32(v) {
return v >>> 0;
}
// Snapshot intrinsics
var LN2 = Math.LN2,
abs = Math.abs,
floor = Math.floor,
log = Math.log,
max = Math.max,
min = Math.min,
pow = Math.pow,
round = Math.round;
// emulate ES5 getter/setter API using legacy APIs
// http://blogs.msdn.com/b/ie/archive/2010/09/07/transitioning-existing-code-to-the-es5-getter-setter-apis.aspx
// (second clause tests for Object.defineProperty() in IE<9 that only supports extending DOM prototypes, but
// note that IE<9 does not support __defineGetter__ or __defineSetter__ so it just renders the method harmless)
(function () {
var orig = Object.defineProperty;
var dom_only = !(function () {
try {
return Object.defineProperty({}, 'x', {});
} catch (_) {
return false;
}
}());
if (!orig || dom_only) {
Object.defineProperty = function (o, prop, desc) {
// In IE8 try built-in implementation for defining properties on DOM prototypes.
if (orig) {
try {
return orig(o, prop, desc);
} catch (_) {
}
}
if (o !== Object(o))
throw TypeError('Object.defineProperty called on non-object');
if (Object.prototype.__defineGetter__ && ('get' in desc))
Object.prototype.__defineGetter__.call(o, prop, desc.get);
if (Object.prototype.__defineSetter__ && ('set' in desc))
Object.prototype.__defineSetter__.call(o, prop, desc.set);
if ('value' in desc)
o[prop] = desc.value;
return o;
};
}
}());
// ES5: Make obj[index] an alias for obj._getter(index)/obj._setter(index, value)
// for index in 0 ... obj.length
function makeArrayAccessors(obj) {
if (obj.length > MAX_ARRAY_LENGTH) throw RangeError('Array too large for polyfill');
function makeArrayAccessor(index) {
Object.defineProperty(obj, index, {
'get': function () {
return obj._getter(index);
},
'set': function (v) {
obj._setter(index, v);
},
enumerable: true,
configurable: false
});
}
var i;
for (i = 0; i < obj.length; i += 1) {
makeArrayAccessor(i);
}
}
// Internal conversion functions:
// pack<Type>() - take a number (interpreted as Type), output a byte array
// unpack<Type>() - take a byte array, output a Type-like number
function as_signed(value, bits) {
var s = 32 - bits;
return (value << s) >> s;
}
function as_unsigned(value, bits) {
var s = 32 - bits;
return (value << s) >>> s;
}
function packI8(n) {
return [n & 0xff];
}
function unpackI8(bytes) {
return as_signed(bytes[0], 8);
}
function packU8(n) {
return [n & 0xff];
}
function unpackU8(bytes) {
return as_unsigned(bytes[0], 8);
}
function packU8Clamped(n) {
n = round(Number(n));
return [n < 0 ? 0 : n > 0xff ? 0xff : n & 0xff];
}
function packI16(n) {
return [(n >> 8) & 0xff, n & 0xff];
}
function unpackI16(bytes) {
return as_signed(bytes[0] << 8 | bytes[1], 16);
}
function packU16(n) {
return [(n >> 8) & 0xff, n & 0xff];
}
function unpackU16(bytes) {
return as_unsigned(bytes[0] << 8 | bytes[1], 16);
}
function packI32(n) {
return [(n >> 24) & 0xff, (n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff];
}
function unpackI32(bytes) {
return as_signed(bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3], 32);
}
function packU32(n) {
return [(n >> 24) & 0xff, (n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff];
}
function unpackU32(bytes) {
return as_unsigned(bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3], 32);
}
function packIEEE754(v, ebits, fbits) {
var bias = (1 << (ebits - 1)) - 1,
s, e, f, ln,
i, bits, str, bytes;
function roundToEven(n) {
var w = floor(n), f = n - w;
if (f < 0.5)
return w;
if (f > 0.5)
return w + 1;
return w % 2 ? w + 1 : w;
}
// Compute sign, exponent, fraction
if (v !== v) {
// NaN
// http://dev.w3.org/2006/webapi/WebIDL/#es-type-mapping
e = (1 << ebits) - 1;
f = pow(2, fbits - 1);
s = 0;
} else if (v === Infinity || v === -Infinity) {
e = (1 << ebits) - 1;
f = 0;
s = (v < 0) ? 1 : 0;
} else if (v === 0) {
e = 0;
f = 0;
s = (1 / v === -Infinity) ? 1 : 0;
} else {
s = v < 0;
v = abs(v);
if (v >= pow(2, 1 - bias)) {
e = min(floor(log(v) / LN2), 1023);
f = roundToEven(v / pow(2, e) * pow(2, fbits));
if (f / pow(2, fbits) >= 2) {
e = e + 1;
f = 1;
}
if (e > bias) {
// Overflow
e = (1 << ebits) - 1;
f = 0;
} else {
// Normalized
e = e + bias;
f = f - pow(2, fbits);
}
} else {
// Denormalized
e = 0;
f = roundToEven(v / pow(2, 1 - bias - fbits));
}
}
// Pack sign, exponent, fraction
bits = [];
for (i = fbits; i; i -= 1) {
bits.push(f % 2 ? 1 : 0);
f = floor(f / 2);
}
for (i = ebits; i; i -= 1) {
bits.push(e % 2 ? 1 : 0);
e = floor(e / 2);
}
bits.push(s ? 1 : 0);
bits.reverse();
str = bits.join('');
// Bits to bytes
bytes = [];
while (str.length) {
bytes.push(parseInt(str.substring(0, 8), 2));
str = str.substring(8);
}
return bytes;
}
function unpackIEEE754(bytes, ebits, fbits) {
// Bytes to bits
var bits = [], i, j, b, str,
bias, s, e, f;
for (i = bytes.length; i; i -= 1) {
b = bytes[i - 1];
for (j = 8; j; j -= 1) {
bits.push(b % 2 ? 1 : 0);
b = b >> 1;
}
}
bits.reverse();
str = bits.join('');
// Unpack sign, exponent, fraction
bias = (1 << (ebits - 1)) - 1;
s = parseInt(str.substring(0, 1), 2) ? -1 : 1;
e = parseInt(str.substring(1, 1 + ebits), 2);
f = parseInt(str.substring(1 + ebits), 2);
// Produce number
if (e === (1 << ebits) - 1) {
return f !== 0 ? NaN : s * Infinity;
} else if (e > 0) {
// Normalized
return s * pow(2, e - bias) * (1 + f / pow(2, fbits));
} else if (f !== 0) {
// Denormalized
return s * pow(2, -(bias - 1)) * (f / pow(2, fbits));
} else {
return s < 0 ? -0 : 0;
}
}
function unpackF64(b) {
return unpackIEEE754(b, 11, 52);
}
function packF64(v) {
return packIEEE754(v, 11, 52);
}
function unpackF32(b) {
return unpackIEEE754(b, 8, 23);
}
function packF32(v) {
return packIEEE754(v, 8, 23);
}
//
// 3 The ArrayBuffer Type
//
(function () {
function ArrayBuffer(length) {
length = ToInt32(length);
if (length < 0) throw RangeError('ArrayBuffer size is not a small enough positive integer.');
Object.defineProperty(this, 'byteLength', {value: length});
Object.defineProperty(this, '_bytes', {value: Array(length)});
for (var i = 0; i < length; i += 1)
this._bytes[i] = 0;
}
global.ArrayBuffer = global.ArrayBuffer || ArrayBuffer;
//
// 5 The Typed Array View Types
//
function $TypedArray$() {
// %TypedArray% ( length )
if (!arguments.length || typeof arguments[0] !== 'object') {
return (function (length) {
length = ToInt32(length);
if (length < 0) throw RangeError('length is not a small enough positive integer.');
Object.defineProperty(this, 'length', {value: length});
Object.defineProperty(this, 'byteLength', {value: length * this.BYTES_PER_ELEMENT});
Object.defineProperty(this, 'buffer', {value: new ArrayBuffer(this.byteLength)});
Object.defineProperty(this, 'byteOffset', {value: 0});
}).apply(this, arguments);
}
// %TypedArray% ( typedArray )
if (arguments.length >= 1 &&
Type(arguments[0]) === 'object' &&
arguments[0] instanceof $TypedArray$) {
return (function (typedArray) {
if (this.constructor !== typedArray.constructor) throw TypeError();
var byteLength = typedArray.length * this.BYTES_PER_ELEMENT;
Object.defineProperty(this, 'buffer', {value: new ArrayBuffer(byteLength)});
Object.defineProperty(this, 'byteLength', {value: byteLength});
Object.defineProperty(this, 'byteOffset', {value: 0});
Object.defineProperty(this, 'length', {value: typedArray.length});
for (var i = 0; i < this.length; i += 1)
this._setter(i, typedArray._getter(i));
}).apply(this, arguments);
}
// %TypedArray% ( array )
if (arguments.length >= 1 &&
Type(arguments[0]) === 'object' && !(arguments[0] instanceof $TypedArray$) && !(arguments[0] instanceof ArrayBuffer || Class(arguments[0]) === 'ArrayBuffer')) {
return (function (array) {
var byteLength = array.length * this.BYTES_PER_ELEMENT;
Object.defineProperty(this, 'buffer', {value: new ArrayBuffer(byteLength)});
Object.defineProperty(this, 'byteLength', {value: byteLength});
Object.defineProperty(this, 'byteOffset', {value: 0});
Object.defineProperty(this, 'length', {value: array.length});
for (var i = 0; i < this.length; i += 1) {
var s = array[i];
this._setter(i, Number(s));
}
}).apply(this, arguments);
}
// %TypedArray% ( buffer, byteOffset=0, length=undefined )
if (arguments.length >= 1 &&
Type(arguments[0]) === 'object' &&
(arguments[0] instanceof ArrayBuffer || Class(arguments[0]) === 'ArrayBuffer')) {
return (function (buffer, byteOffset, length) {
byteOffset = ToUint32(byteOffset);
if (byteOffset > buffer.byteLength)
throw RangeError('byteOffset out of range');
// The given byteOffset must be a multiple of the element
// size of the specific type, otherwise an exception is raised.
if (byteOffset % this.BYTES_PER_ELEMENT)
throw RangeError('buffer length minus the byteOffset is not a multiple of the element size.');
if (length === undefined) {
var byteLength = buffer.byteLength - byteOffset;
if (byteLength % this.BYTES_PER_ELEMENT)
throw RangeError('length of buffer minus byteOffset not a multiple of the element size');
length = byteLength / this.BYTES_PER_ELEMENT;
} else {
length = ToUint32(length);
byteLength = length * this.BYTES_PER_ELEMENT;
}
if ((byteOffset + byteLength) > buffer.byteLength)
throw RangeError('byteOffset and length reference an area beyond the end of the buffer');
Object.defineProperty(this, 'buffer', {value: buffer});
Object.defineProperty(this, 'byteLength', {value: byteLength});
Object.defineProperty(this, 'byteOffset', {value: byteOffset});
Object.defineProperty(this, 'length', {value: length});
}).apply(this, arguments);
}
// %TypedArray% ( all other argument combinations )
throw TypeError();
}
// Properties of the %TypedArray Instrinsic Object
// %TypedArray%.from ( source , mapfn=undefined, thisArg=undefined )
Object.defineProperty($TypedArray$, 'from', {value: function (iterable) {
return new this(iterable);
}});
// %TypedArray%.of ( ...items )
Object.defineProperty($TypedArray$, 'of', {value: function (/*...items*/) {
return new this(arguments);
}});
// %TypedArray%.prototype
var $TypedArrayPrototype$ = {};
$TypedArray$.prototype = $TypedArrayPrototype$;
// WebIDL: getter type (unsigned long index);
Object.defineProperty($TypedArray$.prototype, '_getter', {value: function (index) {
if (arguments.length < 1) throw SyntaxError('Not enough arguments');
index = ToUint32(index);
if (index >= this.length)
return undefined;
var bytes = [], i, o;
for (i = 0, o = this.byteOffset + index * this.BYTES_PER_ELEMENT;
i < this.BYTES_PER_ELEMENT;
i += 1, o += 1) {
bytes.push(this.buffer._bytes[o]);
}
return this._unpack(bytes);
}});
// NONSTANDARD: convenience alias for getter: type get(unsigned long index);
Object.defineProperty($TypedArray$.prototype, 'get', {value: $TypedArray$.prototype._getter});
// WebIDL: setter void (unsigned long index, type value);
Object.defineProperty($TypedArray$.prototype, '_setter', {value: function (index, value) {
if (arguments.length < 2) throw SyntaxError('Not enough arguments');
index = ToUint32(index);
if (index >= this.length)
return;
var bytes = this._pack(value), i, o;
for (i = 0, o = this.byteOffset + index * this.BYTES_PER_ELEMENT;
i < this.BYTES_PER_ELEMENT;
i += 1, o += 1) {
this.buffer._bytes[o] = bytes[i];
}
}});
// get %TypedArray%.prototype.buffer
// get %TypedArray%.prototype.byteLength
// get %TypedArray%.prototype.byteOffset
// -- applied directly to the object in the constructor
// %TypedArray%.prototype.constructor
Object.defineProperty($TypedArray$.prototype, 'constructor', {value: $TypedArray$});
// %TypedArray%.prototype.copyWithin (target, start, end = this.length )
Object.defineProperty($TypedArray$.prototype, 'copyWithin', {value: function (m_target, m_start) {
var m_end = arguments[2];
var m_o = ToObject(this);
var lenVal = m_o.length;
var m_len = ToUint32(lenVal);
m_len = max(m_len, 0);
var relativeTarget = ToInt32(m_target);
var m_to;
if (relativeTarget < 0)
{
m_to = max(m_len + relativeTarget, 0);
}
else
{
m_to = min(relativeTarget, m_len);
}
var relativeStart = ToInt32(m_start);
var m_from;
if (relativeStart < 0)
{
m_from = max(m_len + relativeStart, 0);
}
else
{
m_from = min(relativeStart, m_len);
}
var relativeEnd;
if (m_end === undefined)
{
relativeEnd = m_len;
}
else
{
relativeEnd = ToInt32(m_end);
}
var m_final;
if (relativeEnd < 0) {
m_final = max(m_len + relativeEnd, 0);
} else {
m_final = min(relativeEnd, m_len);
}
var m_count = min(m_final - m_from, m_len - m_to);
var direction;
if (from < m_to && m_to < m_from + m_count) {
direction = -1;
m_from = m_from + m_count - 1;
m_to = m_to + m_count - 1;
} else {
direction = 1;
}
while (count > 0) {
m_o._setter(m_to, m_o._getter(m_from));
m_from = m_from + direction;
m_to = m_to + direction;
m_count = m_count - 1;
}
return m_o;
}});
// %TypedArray%.prototype.entries ( )
// -- defined in es6.js to shim browsers w/ native TypedArrays
// %TypedArray%.prototype.every ( callbackfn, thisArg = undefined )
Object.defineProperty($TypedArray$.prototype, 'every', {value: function (callbackfn) {
if (this === undefined || this === null) throw TypeError();
var t = Object(this);
var len = ToUint32(t.length);
if (!IsCallable(callbackfn)) throw TypeError();
var thisArg = arguments[1];
for (var i = 0; i < len; i++) {
if (!callbackfn.call(thisArg, t._getter(i), i, t))
return false;
}
return true;
}});
// %TypedArray%.prototype.fill (value, start = 0, end = this.length )
Object.defineProperty($TypedArray$.prototype, 'fill', {value: function (value) {
var m_start = arguments[1],
m_end = arguments[2];
var m_o = ToObject(this);
var lenVal = m_o.length;
var m_len = ToUint32(lenVal);
m_len = max(m_len, 0);
var relativeStart = ToInt32(m_start);
var m_k;
if (relativeStart < 0)
{
m_k = max((m_len + relativeStart), 0);
}
else
{
m_k = min(relativeStart, m_len);
}
var relativeEnd;
if (m_end === undefined)
{
relativeEnd = m_len;
}
else
{
relativeEnd = ToInt32(m_end);
}
var m_final;
if (relativeEnd < 0)
{
m_final = max((m_len + relativeEnd), 0);
}
else
{
m_final = min(relativeEnd, m_len);
}
while (m_k < m_final) {
m_o._setter(m_k, value);
m_k += 1;
}
return m_o;
}});
// %TypedArray%.prototype.filter ( callbackfn, thisArg = undefined )
Object.defineProperty($TypedArray$.prototype, 'filter', {value: function (callbackfn) {
if (this === undefined || this === null) throw TypeError();
var t = Object(this);
var len = ToUint32(t.length);
if (!IsCallable(callbackfn)) throw TypeError();
var res = [];
var thisp = arguments[1];
for (var i = 0; i < len; i++) {
var val = t._getter(i); // in case fun mutates this
if (callbackfn.call(thisp, val, i, t))
res.push(val);
}
return new this.constructor(res);
}});
// %TypedArray%.prototype.find (predicate, thisArg = undefined)
Object.defineProperty($TypedArray$.prototype, 'find', {value: function (predicate) {
var o = ToObject(this);
var lenValue = o.length;
var len = ToUint32(lenValue);
if (!IsCallable(predicate)) throw TypeError();
var t = arguments.length > 1 ? arguments[1] : undefined;
var k = 0;
while (k < len) {
var kValue = o._getter(k);
var testResult = predicate.call(t, kValue, k, o);
if (Boolean(testResult))
return kValue;
++k;
}
return undefined;
}});
// %TypedArray%.prototype.findIndex ( predicate, thisArg = undefined )
Object.defineProperty($TypedArray$.prototype, 'findIndex', {value: function (predicate) {
var o = ToObject(this);
var lenValue = o.length;
var len = ToUint32(lenValue);
if (!IsCallable(predicate)) throw TypeError();
var t = arguments.length > 1 ? arguments[1] : undefined;
var k = 0;
while (k < len) {
var kValue = o._getter(k);
var testResult = predicate.call(t, kValue, k, o);
if (Boolean(testResult))
return k;
++k;
}
return -1;
}});
// %TypedArray%.prototype.forEach ( callbackfn, thisArg = undefined )
Object.defineProperty($TypedArray$.prototype, 'forEach', {value: function (callbackfn) {
if (this === undefined || this === null) throw TypeError();
var t = Object(this);
var len = ToUint32(t.length);
if (!IsCallable(callbackfn)) throw TypeError();
var thisp = arguments[1];
for (var i = 0; i < len; i++)
callbackfn.call(thisp, t._getter(i), i, t);
}});
// %TypedArray%.prototype.indexOf (searchElement, fromIndex = 0 )
Object.defineProperty($TypedArray$.prototype, 'indexOf', {value: function (searchElement) {
if (this === undefined || this === null) throw TypeError();
var t = Object(this);
var len = ToUint32(t.length);
if (len === 0) return -1;
var no = 0;
var na;
if (arguments.length > 0) {
na = Number(arguments[1]);
if (na !== no) {
no = 0;
} else if (na !== 0 && na !== (1 / 0) && na !== -(1 / 0)) {
no = (na > 0 || -1) * floor(abs(na));
}
}
if (no >= len) return -1;
var k = no >= 0 ? no : max(len - abs(no), 0);
for (; k < len; k++) {
if (t._getter(k) === searchElement) {
return k;
}
}
return -1;
}});
// %TypedArray%.prototype.join ( separator )
Object.defineProperty($TypedArray$.prototype, 'join', {value: function (separator) {
if (this === undefined || this === null) throw TypeError();
var t = Object(this);
var len = ToUint32(t.length);
var tmp = Array(len);
for (var i = 0; i < len; ++i)
tmp[i] = t._getter(i);
return tmp.join(separator === undefined ? ',' : separator); // Hack for IE7
}});
// %TypedArray%.prototype.keys ( )
// -- defined in es6.js to shim browsers w/ native TypedArrays
// %TypedArray%.prototype.lastIndexOf ( searchElement, fromIndex = this.length-1 )
Object.defineProperty($TypedArray$.prototype, 'lastIndexOf', {value: function (searchElement) {
if (this === undefined || this === null) throw TypeError();
var t = Object(this);
var len = ToUint32(t.length);
if (len === 0) return -1;
var n = len;
if (arguments.length > 1) {
n = Number(arguments[1]);
if (n !== n) {
n = 0;
} else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
n = (n > 0 || -1) * floor(abs(n));
}
}
var k = n >= 0 ? min(n, len - 1) : len - abs(n);
for (; k >= 0; k--) {
if (t._getter(k) === searchElement)
return k;
}
return -1;
}});
// get %TypedArray%.prototype.length
// -- applied directly to the object in the constructor
// %TypedArray%.prototype.map ( callbackfn, thisArg = undefined )
Object.defineProperty($TypedArray$.prototype, 'map', {value: function (callbackfn) {
if (this === undefined || this === null) throw TypeError();
var t = Object(this);
var len = ToUint32(t.length);
if (!IsCallable(callbackfn)) throw TypeError();
var res = [];
res.length = len;
var thisp = arguments[1];
for (var i = 0; i < len; i++)
res[i] = callbackfn.call(thisp, t._getter(i), i, t);
return new this.constructor(res);
}});
// %TypedArray%.prototype.reduce ( callbackfn [, initialValue] )
Object.defineProperty($TypedArray$.prototype, 'reduce', {value: function (callbackfn) {
if (this === undefined || this === null) throw TypeError();
var t = Object(this);
var len = ToUint32(t.length);
if (!IsCallable(callbackfn)) throw TypeError();
// no value to return if no initial value and an empty array
if (len === 0 && arguments.length === 1) throw TypeError();
var k = 0;
var accumulator;
if (arguments.length >= 2) {
accumulator = arguments[1];
} else {
accumulator = t._getter(k++);
}
while (k < len) {
accumulator = callbackfn.call(undefined, accumulator, t._getter(k), k, t);
k++;
}
return accumulator;
}});
// %TypedArray%.prototype.reduceRight ( callbackfn [, initialValue] )
Object.defineProperty($TypedArray$.prototype, 'reduceRight', {value: function (callbackfn) {
if (this === undefined || this === null) throw TypeError();
var t = Object(this);
var len = ToUint32(t.length);
if (!IsCallable(callbackfn)) throw TypeError();
// no value to return if no initial value, empty array
if (len === 0 && arguments.length === 1) throw TypeError();
var k = len - 1;
var accumulator;
if (arguments.length >= 2) {
accumulator = arguments[1];
} else {
accumulator = t._getter(k--);
}
while (k >= 0) {
accumulator = callbackfn.call(undefined, accumulator, t._getter(k), k, t);
k--;
}
return accumulator;
}});
// %TypedArray%.prototype.reverse ( )
Object.defineProperty($TypedArray$.prototype, 'reverse', {value: function () {
if (this === undefined || this === null) throw TypeError();
var t = Object(this);
var len = ToUint32(t.length);
var half = floor(len / 2);
for (var i = 0, j = len - 1; i < half; ++i, --j) {
var tmp = t._getter(i);
t._setter(i, t._getter(j));
t._setter(j, tmp);
}
return t;
}});
// %TypedArray%.prototype.set(array, offset = 0 )
// %TypedArray%.prototype.set(typedArray, offset = 0 )
// WebIDL: void set(TypedArray array, optional unsigned long offset);
// WebIDL: void set(sequence<type> array, optional unsigned long offset);
Object.defineProperty($TypedArray$.prototype, 'set', {value: function (index, value) {
if (arguments.length < 1) throw SyntaxError('Not enough arguments');
var array, sequence, offset, len,
i, s, d,
byteOffset, byteLength, tmp;
if (typeof arguments[0] === 'object' && arguments[0].constructor === this.constructor) {
// void set(TypedArray array, optional unsigned long offset);
array = arguments[0];
offset = ToUint32(arguments[1]);
if (offset + array.length > this.length) {
throw RangeError('Offset plus length of array is out of range');
}
byteOffset = this.byteOffset + offset * this.BYTES_PER_ELEMENT;
byteLength = array.length * this.BYTES_PER_ELEMENT;
if (array.buffer === this.buffer) {
tmp = [];
for (i = 0, s = array.byteOffset; i < byteLength; i += 1, s += 1) {
tmp[i] = array.buffer._bytes[s];
}
for (i = 0, d = byteOffset; i < byteLength; i += 1, d += 1) {
this.buffer._bytes[d] = tmp[i];
}
} else {
for (i = 0, s = array.byteOffset, d = byteOffset;
i < byteLength; i += 1, s += 1, d += 1) {
this.buffer._bytes[d] = array.buffer._bytes[s];
}
}
} else if (typeof arguments[0] === 'object' && typeof arguments[0].length !== 'undefined') {
// void set(sequence<type> array, optional unsigned long offset);
sequence = arguments[0];
len = ToUint32(sequence.length);
offset = ToUint32(arguments[1]);
if (offset + len > this.length) {
throw RangeError('Offset plus length of array is out of range');
}
for (i = 0; i < len; i += 1) {
s = sequence[i];
this._setter(offset + i, Number(s));
}
} else {
throw TypeError('Unexpected argument type(s)');
}
}});
// %TypedArray%.prototype.slice ( start, end )
Object.defineProperty($TypedArray$.prototype, 'slice', {value: function (m_start, m_end) {
var m_o = ToObject(this);
var lenVal = m_o.length;
var m_len = ToUint32(lenVal);
var relativeStart = ToInt32(m_start);
var m_k = (relativeStart < 0) ? max(m_len + relativeStart, 0) : min(relativeStart, m_len);
var relativeEnd = (m_end === undefined) ? m_len : ToInt32(m_end);
var m_final = (relativeEnd < 0) ? max(m_len + relativeEnd, 0) : min(relativeEnd, m_len);
var m_count = m_final - m_k;
var m_c = m_o.constructor;
var m_a = new m_c(m_count);
var m_n = 0;
while (m_k < m_final) {
var kValue = m_o._getter(m_k);
m_a._setter(m_n, kValue);
++m_k;
++m_n;
}
return m_a;
}});
// %TypedArray%.prototype.some ( callbackfn, thisArg = undefined )
Object.defineProperty($TypedArray$.prototype, 'some', {value: function (callbackfn) {
if (this === undefined || this === null) throw TypeError();
var t = Object(this);
var len = ToUint32(t.length);
if (!IsCallable(callbackfn)) throw TypeError();
var thisp = arguments[1];
for (var i = 0; i < len; i++) {
if (callbackfn.call(thisp, t._getter(i), i, t)) {
return true;
}
}
return false;
}});
// %TypedArray%.prototype.sort ( comparefn )
Object.defineProperty($TypedArray$.prototype, 'sort', {value: function (comparefn) {
if (this === undefined || this === null) throw TypeError();
var t = Object(this);
var len = ToUint32(t.length);
var tmp = Array(len);
for (var i = 0; i < len; ++i)
tmp[i] = t._getter(i);
if (comparefn) tmp.sort(comparefn); else tmp.sort(); // Hack for IE8/9
for (i = 0; i < len; ++i)
t._setter(i, tmp[i]);
return t;
}});
// %TypedArray%.prototype.subarray(begin = 0, end = this.length )
// WebIDL: TypedArray subarray(long begin, optional long end);
Object.defineProperty($TypedArray$.prototype, 'subarray', {value: function (start, end) {
function clamp(v, min, max) {
return v < min ? min : v > max ? max : v;
}
start = ToInt32(start);
end = ToInt32(end);
if (arguments.length < 1) {
start = 0;
}
if (arguments.length < 2) {
end = this.length;
}
if (start < 0) {
start = this.length + start;
}
if (end < 0) {
end = this.length + end;
}
start = clamp(start, 0, this.length);
end = clamp(end, 0, this.length);
var len = end - start;
if (len < 0) {
len = 0;
}
return new this.constructor(
this.buffer, this.byteOffset + start * this.BYTES_PER_ELEMENT, len);
}});
// %TypedArray%.prototype.toLocaleString ( )
// %TypedArray%.prototype.toString ( )
// %TypedArray%.prototype.values ( )
// %TypedArray%.prototype [ @@iterator ] ( )
// get %TypedArray%.prototype [ @@toStringTag ]
// -- defined in es6.js to shim browsers w/ native TypedArrays
function makeTypedArray(elementSize, pack, unpack) {
// Each TypedArray type requires a distinct constructor instance with
// identical logic, which this produces.
var TypedArray = function () {
Object.defineProperty(this, 'constructor', {value: TypedArray});
$TypedArray$.apply(this, arguments);
makeArrayAccessors(this);
};
if ('__proto__' in TypedArray) {
TypedArray.__proto__ = $TypedArray$;
} else {
TypedArray.from = $TypedArray$.from;
TypedArray.of = $TypedArray$.of;
}
TypedArray.BYTES_PER_ELEMENT = elementSize;
var TypedArrayPrototype = function () {
};
TypedArrayPrototype.prototype = $TypedArrayPrototype$;
TypedArray.prototype = new TypedArrayPrototype();
Object.defineProperty(TypedArray.prototype, 'BYTES_PER_ELEMENT', {value: elementSize});
Object.defineProperty(TypedArray.prototype, '_pack', {value: pack});
Object.defineProperty(TypedArray.prototype, '_unpack', {value: unpack});
return TypedArray;
}
var Int8Array = makeTypedArray(1, packI8, unpackI8);
var Uint8Array = makeTypedArray(1, packU8, unpackU8);
var Uint8ClampedArray = makeTypedArray(1, packU8Clamped, unpackU8);
var Int16Array = makeTypedArray(2, packI16, unpackI16);
var Uint16Array = makeTypedArray(2, packU16, unpackU16);
var Int32Array = makeTypedArray(4, packI32, unpackI32);
var Uint32Array = makeTypedArray(4, packU32, unpackU32);
var Float32Array = makeTypedArray(4, packF32, unpackF32);
var Float64Array = makeTypedArray(8, packF64, unpackF64);
global.Int8Array = win.Int8Array = global.Int8Array || Int8Array;
global.Uint8Array = win.Uint8Array = global.Uint8Array || Uint8Array;
global.Uint8ClampedArray = win.Uint8ClampedArray = global.Uint8ClampedArray || Uint8ClampedArray;
global.Int16Array = win.Int16Array = global.Int16Array || Int16Array;
global.Uint16Array = win.Uint16Array = global.Uint16Array || Uint16Array;
global.Int32Array = win.Int32Array = global.Int32Array || Int32Array;
global.Uint32Array = win.Uint32Array = global.Uint32Array || Uint32Array;
global.Float32Array = win.Float32Array = global.Float32Array || Float32Array;
global.Float64Array = win.Float64Array = global.Float64Array || Float64Array;
}());
//
// 6 The DataView View Type
//
(function () {
function r(array, index) {
return IsCallable(array.get) ? array.get(index) : array[index];
}
var IS_BIG_ENDIAN = (function () {
var u16array = new global.Uint16Array([0x1234]),
u8array = new global.Uint8Array(u16array.buffer);
return r(u8array, 0) === 0x12;
}());
// DataView(buffer, byteOffset=0, byteLength=undefined)
// WebIDL: Constructor(ArrayBuffer buffer,
// optional unsigned long byteOffset,
// optional unsigned long byteLength)
function DataView(buffer, byteOffset, byteLength) {
if (!(buffer instanceof ArrayBuffer || Class(buffer) === 'ArrayBuffer')) throw TypeError();
byteOffset = ToUint32(byteOffset);
if (byteOffset > buffer.byteLength)
throw RangeError('byteOffset out of range');
if (byteLength === undefined)
byteLength = buffer.byteLength - byteOffset;
else
byteLength = ToUint32(byteLength);
if ((byteOffset + byteLength) > buffer.byteLength)
throw RangeError('byteOffset and length reference an area beyond the end of the buffer');
Object.defineProperty(this, 'buffer', {value: buffer});
Object.defineProperty(this, 'byteLength', {value: byteLength});
Object.defineProperty(this, 'byteOffset', {value: byteOffset});
};
// get DataView.prototype.buffer
// get DataView.prototype.byteLength
// get DataView.prototype.byteOffset
// -- applied directly to instances by the constructor
function makeGetter(arrayType) {
return function GetViewValue(byteOffset, littleEndian) {
byteOffset = ToUint32(byteOffset);
if (byteOffset + arrayType.BYTES_PER_ELEMENT > this.byteLength)
throw RangeError('Array index out of range');
byteOffset += this.byteOffset;
var uint8Array = new global.Uint8Array(this.buffer, byteOffset, arrayType.BYTES_PER_ELEMENT),
bytes = [];
for (var i = 0; i < arrayType.BYTES_PER_ELEMENT; i += 1)
bytes.push(r(uint8Array, i));
if (Boolean(littleEndian) === Boolean(IS_BIG_ENDIAN))
bytes.reverse();
return r(new arrayType(new global.Uint8Array(bytes).buffer), 0);
};
}
Object.defineProperty(DataView.prototype, 'getUint8', {value: makeGetter(global.Uint8Array)});
Object.defineProperty(DataView.prototype, 'getInt8', {value: makeGetter(global.Int8Array)});
Object.defineProperty(DataView.prototype, 'getUint16', {value: makeGetter(global.Uint16Array)});
Object.defineProperty(DataView.prototype, 'getInt16', {value: makeGetter(global.Int16Array)});
Object.defineProperty(DataView.prototype, 'getUint32', {value: makeGetter(global.Uint32Array)});
Object.defineProperty(DataView.prototype, 'getInt32', {value: makeGetter(global.Int32Array)});
Object.defineProperty(DataView.prototype, 'getFloat32', {value: makeGetter(global.Float32Array)});
Object.defineProperty(DataView.prototype, 'getFloat64', {value: makeGetter(global.Float64Array)});
function makeSetter(arrayType) {
return function SetViewValue(byteOffset, value, littleEndian) {
byteOffset = ToUint32(byteOffset);
if (byteOffset + arrayType.BYTES_PER_ELEMENT > this.byteLength)
throw RangeError('Array index out of range');
// Get bytes
var typeArray = new arrayType([value]),
byteArray = new global.Uint8Array(typeArray.buffer),
bytes = [], i, byteView;
for (i = 0; i < arrayType.BYTES_PER_ELEMENT; i += 1)
bytes.push(r(byteArray, i));
// Flip if necessary
if (Boolean(littleEndian) === Boolean(IS_BIG_ENDIAN))
bytes.reverse();
// Write them
byteView = new Uint8Array(this.buffer, byteOffset, arrayType.BYTES_PER_ELEMENT);
byteView.set(bytes);
};
}
Object.defineProperty(DataView.prototype, 'setUint8', {value: makeSetter(global.Uint8Array)});
Object.defineProperty(DataView.prototype, 'setInt8', {value: makeSetter(global.Int8Array)});
Object.defineProperty(DataView.prototype, 'setUint16', {value: makeSetter(global.Uint16Array)});
Object.defineProperty(DataView.prototype, 'setInt16', {value: makeSetter(global.Int16Array)});
Object.defineProperty(DataView.prototype, 'setUint32', {value: makeSetter(global.Uint32Array)});
Object.defineProperty(DataView.prototype, 'setInt32', {value: makeSetter(global.Int32Array)});
Object.defineProperty(DataView.prototype, 'setFloat32', {value: makeSetter(global.Float32Array)});
Object.defineProperty(DataView.prototype, 'setFloat64', {value: makeSetter(global.Float64Array)});
global.DataView = global.DataView || DataView;
}());
}(exports, window)
);
}
// workaround for crypto-js on IE11
// http://code.google.com/p/crypto-js/issues/detail?id=81
if ('window' in global) {
if (!('Uint8ClampedArray' in window)) {
window.Uint8ClampedArray = global.Uint8Array;
}
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],16:[function(require,module,exports){
(function (global){
///////////////////////////////////////////////////////////////////////////////
//
// AutobahnJS - http://autobahn.ws, http://wamp.ws
//
// A JavaScript library for WAMP ("The Web Application Messaging Protocol").
//
// Copyright (C) 2011-2014 Tavendo GmbH, http://tavendo.com
//
// Licensed under the MIT License.
// http://www.opensource.org/licenses/mit-license.php
//
///////////////////////////////////////////////////////////////////////////////
// require('assert') would be nice .. but it does not
// work with Google Closure after Browserify
var when = require('when');
var when_fn = require("when/function");
var log = require('./log.js');
var util = require('./util.js');
// IE fallback (http://afuchs.tumblr.com/post/23550124774/date-now-in-ie8)
Date.now = Date.now || function() { return +new Date; };
// WAMP "Advanced Profile" support in AutobahnJS per role
//
WAMP_FEATURES = {
caller: {
features: {
caller_identification: true,
progressive_call_results: true
}
},
callee: {
features: {
caller_identification: true,
pattern_based_registration: true,
shared_registration: true,
progressive_call_results: true,
registration_revocation: true
}
},
publisher: {
features: {
publisher_identification: true,
subscriber_blackwhite_listing: true,
publisher_exclusion: true
}
},
subscriber: {
features: {
publisher_identification: true,
pattern_based_subscription: true,
subscription_revocation: true
}
}
};
// generate a WAMP ID
//
function newid () {
return Math.floor(Math.random() * 9007199254740992);
}
var Invocation = function (caller, progress, procedure) {
var self = this;
self.caller = caller;
self.progress = progress;
self.procedure = procedure;
};
var Event = function (publication, publisher, topic) {
var self = this;
self.publication = publication;
self.publisher = publisher;
self.topic = topic;
};
var Result = function (args, kwargs) {
var self = this;
self.args = args || [];
self.kwargs = kwargs || {};
};
var Error = function (error, args, kwargs) {
var self = this;
self.error = error;
self.args = args || [];
self.kwargs = kwargs || {};
};
var Subscription = function (topic, handler, options, session, id) {
var self = this;
self.topic = topic;
self.handler = handler;
self.options = options || {};
self.session = session;
self.id = id;
self.active = true;
// this will fire when the handler is unsubscribed
self._on_unsubscribe = session._defer();
if (self._on_unsubscribe.promise.then) {
// whenjs has the actual user promise in an attribute
self.on_unsubscribe = self._on_unsubscribe.promise;
} else {
self.on_unsubscribe = self._on_unsubscribe;
}
};
Subscription.prototype.unsubscribe = function () {
var self = this;
return self.session.unsubscribe(self);
};
var Registration = function (procedure, endpoint, options, session, id) {
var self = this;
self.procedure = procedure;
self.endpoint = endpoint;
self.options = options || {};
self.session = session;
self.id = id;
self.active = true;
// this will fire when the endpoint is unregistered
self._on_unregister = session._defer();
if (self._on_unregister.promise.then) {
// whenjs has the actual user promise in an attribute
self.on_unregister = self._on_unregister.promise;
} else {
self.on_unregister = self._on_unregister;
}
};
Registration.prototype.unregister = function () {
var self = this;
return self.session.unregister(self);
};
var Publication = function (id) {
var self = this;
self.id = id;
};
var MSG_TYPE = {
HELLO: 1,
WELCOME: 2,
ABORT: 3,
CHALLENGE: 4,
AUTHENTICATE: 5,
GOODBYE: 6,
HEARTBEAT: 7,
ERROR: 8,
PUBLISH: 16,
PUBLISHED: 17,
SUBSCRIBE: 32,
SUBSCRIBED: 33,
UNSUBSCRIBE: 34,
UNSUBSCRIBED: 35,
EVENT: 36,
CALL: 48,
CANCEL: 49,
RESULT: 50,
REGISTER: 64,
REGISTERED: 65,
UNREGISTER: 66,
UNREGISTERED: 67,
INVOCATION: 68,
INTERRUPT: 69,
YIELD: 70
};
var Session = function (socket, defer, onchallenge) {
var self = this;
// the transport connection (WebSocket object)
self._socket = socket;
// the Deferred factory to use
self._defer = defer;
// the WAMP authentication challenge handler
self._onchallenge = onchallenge;
// the WAMP session ID
self._id = null;
// the WAMP realm joined
self._realm = null;
// the WAMP features in use
self._features = null;
// closing state
self._goodbye_sent = false;
self._transport_is_closing = false;
// outstanding requests;
self._publish_reqs = {};
self._subscribe_reqs = {};
self._unsubscribe_reqs = {};
self._call_reqs = {};
self._register_reqs = {};
self._unregister_reqs = {};
// subscriptions in place;
self._subscriptions = {};
// registrations in place;
self._registrations = {};
// incoming invocations;
self._invocations = {};
// prefix shortcuts for URIs
self._prefixes = {};
// the defaults for 'disclose_me'
self._caller_disclose_me = false;
self._publisher_disclose_me = false;
self._send_wamp = function (msg) {
// forward WAMP message to be sent to WAMP transport
self._socket.send(msg);
};
self._protocol_violation = function (reason) {
log.debug("failing transport due to protocol violation: " + reason);
self._socket.close(1002, "protocol violation: " + reason);
};
self._MESSAGE_MAP = {};
self._MESSAGE_MAP[MSG_TYPE.ERROR] = {};
self._process_SUBSCRIBED = function (msg) {
//
// process SUBSCRIBED reply to SUBSCRIBE
//
var request = msg[1];
var subscription = msg[2];
if (request in self._subscribe_reqs) {
var r = self._subscribe_reqs[request];
var d = r[0];
var topic = r[1];
var handler = r[2];
var options = r[3];
if (!(subscription in self._subscriptions)) {
self._subscriptions[subscription] = [];
}
var sub = new Subscription(topic, handler, options, self, subscription);
self._subscriptions[subscription].push(sub);
d.resolve(sub);
delete self._subscribe_reqs[request];
} else {
self._protocol_violation("SUBSCRIBED received for non-pending request ID " + request);
}
};
self._MESSAGE_MAP[MSG_TYPE.SUBSCRIBED] = self._process_SUBSCRIBED;
self._process_SUBSCRIBE_ERROR = function (msg) {
//
// process ERROR reply to SUBSCRIBE
//
var request = msg[2];
if (request in self._subscribe_reqs) {
var details = msg[3];
var error = new Error(msg[4], msg[5], msg[6]);
var r = self._subscribe_reqs[request];
var d = r[0];
d.reject(error);
delete self._subscribe_reqs[request];
} else {
self._protocol_violation("SUBSCRIBE-ERROR received for non-pending request ID " + request);
}
};
self._MESSAGE_MAP[MSG_TYPE.ERROR][MSG_TYPE.SUBSCRIBE] = self._process_SUBSCRIBE_ERROR;
self._process_UNSUBSCRIBED = function (msg) {
//
// process UNSUBSCRIBED reply to UNSUBSCRIBE
//
var request = msg[1];
if (request in self._unsubscribe_reqs) {
var r = self._unsubscribe_reqs[request];
var d = r[0];
var subscription = r[1];
if (subscription.id in self._subscriptions) {
var subs = self._subscriptions[subscription.id];
// the following should actually be NOP, since UNSUBSCRIBE was
// only sent when subs got empty
for (var i = 0; i < subs.length; ++i) {
subs[i].active = false;
subs[i].on_unsubscribe.resolve();
}
delete self._subscriptions[subscription];
}
d.resolve(true);
delete self._unsubscribe_reqs[request];
} else {
if (request === 0) {
// router actively revoked our subscription
//
var details = msg[2];
var subscription_id = details.subscription;
var reason = details.reason;
if (subscription_id in self._subscriptions) {
var subs = self._subscriptions[subscription_id];
for (var i = 0; i < subs.length; ++i) {
subs[i].active = false;
subs[i]._on_unsubscribe.resolve(reason);
}
delete self._subscriptions[subscription_id];
} else {
self._protocol_violation("non-voluntary UNSUBSCRIBED received for non-existing subscription ID " + subscription_id);
}
} else {
self._protocol_violation("UNSUBSCRIBED received for non-pending request ID " + request);
}
}
};
self._MESSAGE_MAP[MSG_TYPE.UNSUBSCRIBED] = self._process_UNSUBSCRIBED;
self._process_UNSUBSCRIBE_ERROR = function (msg) {
//
// process ERROR reply to UNSUBSCRIBE
//
var request = msg[2];
if (request in self._unsubscribe_reqs) {
var details = msg[3];
var error = new Error(msg[4], msg[5], msg[6]);
var r = self._unsubscribe_reqs[request];
var d = r[0];
var subscription = r[1];
d.reject(error);
delete self._unsubscribe_reqs[request];
} else {
self._protocol_violation("UNSUBSCRIBE-ERROR received for non-pending request ID " + request);
}
};
self._MESSAGE_MAP[MSG_TYPE.ERROR][MSG_TYPE.UNSUBSCRIBE] = self._process_UNSUBSCRIBE_ERROR;
self._process_PUBLISHED = function (msg) {
//
// process PUBLISHED reply to PUBLISH
//
var request = msg[1];
var publication = msg[2];
if (request in self._publish_reqs) {
var r = self._publish_reqs[request];
var d = r[0];
var options = r[1];
var pub = new Publication(publication);
d.resolve(pub);
delete self._publish_reqs[request];
} else {
self._protocol_violation("PUBLISHED received for non-pending request ID " + request);
}
};
self._MESSAGE_MAP[MSG_TYPE.PUBLISHED] = self._process_PUBLISHED;
self._process_PUBLISH_ERROR = function (msg) {
//
// process ERROR reply to PUBLISH
//
var request = msg[2];
if (request in self._publish_reqs) {
var details = msg[3];
var error = new Error(msg[4], msg[5], msg[6]);
var r = self._publish_reqs[request];
var d = r[0];
var options = r[1];
d.reject(error);
delete self._publish_reqs[request];
} else {
self._protocol_violation("PUBLISH-ERROR received for non-pending request ID " + request);
}
};
self._MESSAGE_MAP[MSG_TYPE.ERROR][MSG_TYPE.PUBLISH] = self._process_PUBLISH_ERROR;
self._process_EVENT = function (msg) {
//
// process EVENT message
//
// [EVENT, SUBSCRIBED.Subscription|id, PUBLISHED.Publication|id, Details|dict, PUBLISH.Arguments|list, PUBLISH.ArgumentsKw|dict]
var subscription = msg[1];
if (subscription in self._subscriptions) {
var publication = msg[2];
var details = msg[3];
var args = msg[4] || [];
var kwargs = msg[5] || {};
var ed = new Event(publication, details.publisher, details.topic);
var subs = self._subscriptions[subscription];
for (var i = 0; i < subs.length; ++i) {
try {
subs[i].handler(args, kwargs, ed);
} catch (e) {
log.debug("Exception raised in event handler", e);
}
}
} else {
self._protocol_violation("EVENT received for non-subscribed subscription ID " + subscription);
}
};
self._MESSAGE_MAP[MSG_TYPE.EVENT] = self._process_EVENT;
self._process_REGISTERED = function (msg) {
//
// process REGISTERED reply to REGISTER
//
var request = msg[1];
var registration = msg[2];
if (request in self._register_reqs) {
var r = self._register_reqs[request];
var d = r[0];
var procedure = r[1];
var endpoint = r[2];
var options = r[3];
var reg = new Registration(procedure, endpoint, options, self, registration);
self._registrations[registration] = reg;
d.resolve(reg);
delete self._register_reqs[request];
} else {
self._protocol_violation("REGISTERED received for non-pending request ID " + request);
}
};
self._MESSAGE_MAP[MSG_TYPE.REGISTERED] = self._process_REGISTERED;
self._process_REGISTER_ERROR = function (msg) {
//
// process ERROR reply to REGISTER
//
var request = msg[2];
if (request in self._register_reqs) {
var details = msg[3];
var error = new Error(msg[4], msg[5], msg[6]);
var r = self._register_reqs[request];
var d = r[0];
d.reject(error);
delete self._register_reqs[request];
} else {
self._protocol_violation("REGISTER-ERROR received for non-pending request ID " + request);
}
};
self._MESSAGE_MAP[MSG_TYPE.ERROR][MSG_TYPE.REGISTER] = self._process_REGISTER_ERROR;
self._process_UNREGISTERED = function (msg) {
//
// process UNREGISTERED reply to UNREGISTER
//
var request = msg[1];
if (request in self._unregister_reqs) {
var r = self._unregister_reqs[request];
var d = r[0];
var registration = r[1];
if (registration.id in self._registrations) {
delete self._registrations[registration.id];
}
registration.active = false;
d.resolve();
delete self._unregister_reqs[request];
} else {
if (request === 0) {
// the router actively revoked our registration
//
var details = msg[2];
var registration_id = details.registration;
var reason = details.reason;
if (registration_id in self._registrations) {
var registration = self._registrations[registration_id];
registration.active = false;
registration._on_unregister.resolve(reason);
delete self._registrations[registration_id];
} else {
self._protocol_violation("non-voluntary UNREGISTERED received for non-existing registration ID " + registration_id);
}
} else {
self._protocol_violation("UNREGISTERED received for non-pending request ID " + request);
}
}
};
self._MESSAGE_MAP[MSG_TYPE.UNREGISTERED] = self._process_UNREGISTERED;
self._process_UNREGISTER_ERROR = function (msg) {
//
// process ERROR reply to UNREGISTER
//
var request = msg[2];
if (request in self._unregister_reqs) {
var details = msg[3];
var error = new Error(msg[4], msg[5], msg[6]);
var r = self._unregister_reqs[request];
var d = r[0];
var registration = r[1];
d.reject(error);
delete self._unregister_reqs[request];
} else {
self._protocol_violation("UNREGISTER-ERROR received for non-pending request ID " + request);
}
};
self._MESSAGE_MAP[MSG_TYPE.ERROR][MSG_TYPE.UNREGISTER] = self._process_UNREGISTER_ERROR;
self._process_RESULT = function (msg) {
//
// process RESULT reply to CALL
//
var request = msg[1];
if (request in self._call_reqs) {
var details = msg[2];
var args = msg[3] || [];
var kwargs = msg[4] || {};
// maybe wrap complex result:
var result = null;
if (args.length > 1 || Object.keys(kwargs).length > 0) {
// wrap complex result is more than 1 positional result OR
// non-empty keyword result
result = new Result(args, kwargs);
} else if (args.length > 0) {
// single positional result
result = args[0];
}
var r = self._call_reqs[request];
var d = r[0];
var options = r[1];
if (details.progress) {
if (options && options.receive_progress) {
d.notify(result);
}
} else {
d.resolve(result);
delete self._call_reqs[request];
}
} else {
self._protocol_violation("CALL-RESULT received for non-pending request ID " + request);
}
};
self._MESSAGE_MAP[MSG_TYPE.RESULT] = self._process_RESULT;
self._process_CALL_ERROR = function (msg) {
//
// process ERROR reply to CALL
//
var request = msg[2];
if (request in self._call_reqs) {
var details = msg[3];
var error = new Error(msg[4], msg[5], msg[6]);
var r = self._call_reqs[request];
var d = r[0];
var options = r[1];
d.reject(error);
delete self._call_reqs[request];
} else {
self._protocol_violation("CALL-ERROR received for non-pending request ID " + request);
}
};
self._MESSAGE_MAP[MSG_TYPE.ERROR][MSG_TYPE.CALL] = self._process_CALL_ERROR;
self._process_INVOCATION = function (msg) {
//
// process INVOCATION message
//
// [INVOCATION, Request|id, REGISTERED.Registration|id, Details|dict, CALL.Arguments|list, CALL.ArgumentsKw|dict]
//
var request = msg[1];
var registration = msg[2];
var details = msg[3];
// receive_progress
// timeout
// caller
if (registration in self._registrations) {
var endpoint = self._registrations[registration].endpoint;
var args = msg[4] || [];
var kwargs = msg[5] || {};
// create progress function for invocation
//
var progress = null;
if (details.receive_progress) {
progress = function (args, kwargs) {
var progress_msg = [MSG_TYPE.YIELD, request, {progress: true}];
args = args || [];
kwargs = kwargs || {};
var kwargs_len = Object.keys(kwargs).length;
if (args.length || kwargs_len) {
progress_msg.push(args);
if (kwargs_len) {
progress_msg.push(kwargs);
}
}
self._send_wamp(progress_msg);
}
};
var cd = new Invocation(details.caller, progress, details.procedure);
// We use the following whenjs call wrapper, which automatically
// wraps a plain, non-promise value in a (immediately resolved) promise
//
// See: https://github.com/cujojs/when/blob/master/docs/api.md#fncall
//
when_fn.call(endpoint, args, kwargs, cd).then(
function (res) {
// construct YIELD message
// FIXME: Options
//
var reply = [MSG_TYPE.YIELD, request, {}];
if (res instanceof Result) {
var kwargs_len = Object.keys(res.kwargs).length;
if (res.args.length || kwargs_len) {
reply.push(res.args);
if (kwargs_len) {
reply.push(res.kwargs);
}
}
} else {
reply.push([res]);
}
// send WAMP message
//
self._send_wamp(reply);
},
function (err) {
// construct ERROR message
// [ERROR, REQUEST.Type|int, REQUEST.Request|id, Details|dict, Error|uri, Arguments|list, ArgumentsKw|dict]
var reply = [MSG_TYPE.ERROR, MSG_TYPE.INVOCATION, request, {}];
if (err instanceof Error) {
reply.push(err.error);
var kwargs_len = Object.keys(err.kwargs).length;
if (err.args.length || kwargs_len) {
reply.push(err.args);
if (kwargs_len) {
reply.push(err.kwargs);
}
}
} else {
reply.push('wamp.error.runtime_error');
reply.push([err]);
}
// send WAMP message
//
self._send_wamp(reply);
}
);
} else {
self._protocol_violation("INVOCATION received for non-registered registration ID " + request);
}
};
self._MESSAGE_MAP[MSG_TYPE.INVOCATION] = self._process_INVOCATION;
// callback fired by WAMP transport on receiving a WAMP message
//
self._socket.onmessage = function (msg) {
var msg_type = msg[0];
// WAMP session not yet open
//
if (!self._id) {
// the first message must be WELCOME, ABORT or CHALLENGE ..
//
if (msg_type === MSG_TYPE.WELCOME) {
self._id = msg[1];
// determine actual set of advanced features that can be used
//
var rf = msg[2];
self._features = {};
if (rf.roles.broker) {
// "Basic Profile" is mandatory
self._features.subscriber = {};
self._features.publisher = {};
// fill in features that both peers support
if (rf.roles.broker.features) {
for (var att in WAMP_FEATURES.publisher.features) {
self._features.publisher[att] = WAMP_FEATURES.publisher.features[att] &&
rf.roles.broker.features[att];
}
for (var att in WAMP_FEATURES.subscriber.features) {
self._features.subscriber[att] = WAMP_FEATURES.subscriber.features[att] &&
rf.roles.broker.features[att];
}
}
}
if (rf.roles.dealer) {
// "Basic Profile" is mandatory
self._features.caller = {};
self._features.callee = {};
// fill in features that both peers support
if (rf.roles.dealer.features) {
for (var att in WAMP_FEATURES.caller.features) {
self._features.caller[att] = WAMP_FEATURES.caller.features[att] &&
rf.roles.dealer.features[att];
}
for (var att in WAMP_FEATURES.callee.features) {
self._features.callee[att] = WAMP_FEATURES.callee.features[att] &&
rf.roles.dealer.features[att];
}
}
}
if (self.onjoin) {
self.onjoin(msg[2]);
}
} else if (msg_type === MSG_TYPE.ABORT) {
var details = msg[1];
var reason = msg[2];
if (self.onleave) {
self.onleave(reason, details);
}
} else if (msg_type === MSG_TYPE.CHALLENGE) {
if (self._onchallenge) {
var method = msg[1];
var extra = msg[2];
when_fn.call(self._onchallenge, self, method, extra).then(
function (signature) {
var msg = [MSG_TYPE.AUTHENTICATE, signature, {}];
self._send_wamp(msg);
},
function (err) {
log.debug("onchallenge() raised:", err);
var msg = [MSG_TYPE.ABORT, {message: "sorry, I cannot authenticate (onchallenge handler raised an exception)"}, "wamp.error.cannot_authenticate"];
self._send_wamp(msg);
self._socket.close(1000);
}
);
} else {
log.debug("received WAMP challenge, but no onchallenge() handler set");
var msg = [MSG_TYPE.ABORT, {message: "sorry, I cannot authenticate (no onchallenge handler set)"}, "wamp.error.cannot_authenticate"];
self._send_wamp(msg);
self._socket.close(1000);
}
} else {
self._protocol_violation("unexpected message type " + msg_type);
}
// WAMP session is open
//
} else {
if (msg_type === MSG_TYPE.GOODBYE) {
if (!self._goodbye_sent) {
var reply = [MSG_TYPE.GOODBYE, {}, "wamp.error.goodbye_and_out"];
self._send_wamp(reply);
}
self._id = null;
self._realm = null;
self._features = null;
var details = msg[1];
var reason = msg[2];
if (self.onleave) {
self.onleave(reason, details);
}
} else {
if (msg_type === MSG_TYPE.ERROR) {
var request_type = msg[1];
if (request_type in self._MESSAGE_MAP[MSG_TYPE.ERROR]) {
self._MESSAGE_MAP[msg_type][request_type](msg);
} else {
self._protocol_violation("unexpected ERROR message with request_type " + request_type);
}
} else {
if (msg_type in self._MESSAGE_MAP) {
self._MESSAGE_MAP[msg_type](msg);
} else {
self._protocol_violation("unexpected message type " + msg_type);
}
}
}
}
};
// session object constructed .. track creation time
//
if ('performance' in global && 'now' in performance) {
self._created = performance.now();
} else {
self._created = Date.now();
}
};
Object.defineProperty(Session.prototype, "defer", {
get: function () {
return this._defer;
}
});
Object.defineProperty(Session.prototype, "id", {
get: function () {
return this._id;
}
});
Object.defineProperty(Session.prototype, "realm", {
get: function () {
return this._realm;
}
});
Object.defineProperty(Session.prototype, "isOpen", {
get: function () {
return this.id !== null;
}
});
Object.defineProperty(Session.prototype, "features", {
get: function () {
return this._features;
}
});
Object.defineProperty(Session.prototype, "caller_disclose_me", {
get: function () {
return this._caller_disclose_me;
},
set: function (newValue) {
this._caller_disclose_me = newValue;
}
});
Object.defineProperty(Session.prototype, "publisher_disclose_me", {
get: function () {
return this._publisher_disclose_me;
},
set: function (newValue) {
this._publisher_disclose_me = newValue;
}
});
Object.defineProperty(Session.prototype, "subscriptions", {
get: function () {
var keys = Object.keys(this._subscriptions);
var vals = [];
for (var i = 0; i < keys.length; ++i) {
vals.push(this._subscriptions[keys[i]]);
}
return vals;
}
});
Object.defineProperty(Session.prototype, "registrations", {
get: function () {
var keys = Object.keys(this._registrations);
var vals = [];
for (var i = 0; i < keys.length; ++i) {
vals.push(this._registrations[keys[i]]);
}
return vals;
}
});
Session.prototype.log = function () {
var self = this;
if ('console' in global) {
var header = null;
if (self._id && self._created) {
var now = null;
if ('performance' in global && 'now' in performance) {
now = performance.now() - self._created;
} else {
now = Date.now() - self._created;
}
header = "WAMP session " + self._id + " on '" + self._realm + "' at " + Math.round(now * 1000) / 1000 + " ms";
} else {
header = "WAMP session";
}
if ('group' in console) {
console.group(header);
for (var i = 0; i < arguments.length; i += 1) {
console.log(arguments[i]);
}
console.groupEnd();
} else {
var items = [header + ": "];
for (var i = 0; i < arguments.length; i += 1) {
items.push(arguments[i]);
}
console.log.apply(console, items);
}
}
};
Session.prototype.join = function (realm, authmethods, authid) {
util.assert(typeof realm === 'string', "Session.join: <realm> must be a string");
util.assert(!authmethods || Array.isArray(authmethods), "Session.join: <authmethods> must be an array []");
util.assert(!authid || typeof authid === 'string', "Session.join: <authid> must be a string");
var self = this;
if (self.isOpen) {
throw "session already open";
}
self._goodbye_sent = false;
self._realm = realm;
var details = {};
details.roles = WAMP_FEATURES;
if (authmethods) {
details.authmethods = authmethods;
}
if (authid) {
details.authid = authid;
}
var msg = [MSG_TYPE.HELLO, realm, details];
self._send_wamp(msg);
};
Session.prototype.leave = function (reason, message) {
util.assert(!reason || typeof reason === 'string', "Session.leave: <reason> must be a string");
util.assert(!message || typeof message === 'string', "Session.leave: <message> must be a string");
var self = this;
if (!self.isOpen) {
throw "session not open";
}
if (!reason) {
reason = "wamp.close.normal";
}
var details = {};
if (message) {
details.message = message;
}
var msg = [MSG_TYPE.GOODBYE, details, reason];
self._send_wamp(msg);
self._goodbye_sent = true;
};
Session.prototype.call = function (procedure, args, kwargs, options) {
util.assert(typeof procedure === 'string', "Session.call: <procedure> must be a string");
util.assert(!args || Array.isArray(args), "Session.call: <args> must be an array []");
util.assert(!kwargs || kwargs instanceof Object, "Session.call: <kwargs> must be an object {}");
util.assert(!options || options instanceof Object, "Session.call: <options> must be an object {}");
var self = this;
if (!self.isOpen) {
throw "session not open";
}
options = options || {};
// only set option if user hasn't set a value and global option is "on"
if (options.disclose_me === undefined && self._caller_disclose_me) {
options.disclose_me = true;
}
// create and remember new CALL request
//
var d = self._defer();
var request = newid();
self._call_reqs[request] = [d, options];
// construct CALL message
//
var msg = [MSG_TYPE.CALL, request, options, self.resolve(procedure)];
if (args) {
msg.push(args);
if (kwargs) {
msg.push(kwargs);
}
} else if (kwargs) {
msg.push([]);
msg.push(kwargs);
}
// send WAMP message
//
self._send_wamp(msg);
if (d.promise.then) {
// whenjs has the actual user promise in an attribute
return d.promise;
} else {
return d;
}
};
Session.prototype.publish = function (topic, args, kwargs, options) {
util.assert(typeof topic === 'string', "Session.publish: <topic> must be a string");
util.assert(!args || Array.isArray(args), "Session.publish: <args> must be an array []");
util.assert(!kwargs || kwargs instanceof Object, "Session.publish: <kwargs> must be an object {}");
util.assert(!options || options instanceof Object, "Session.publish: <options> must be an object {}");
var self = this;
if (!self.isOpen) {
throw "session not open";
}
options = options || {};
// only set option if user hasn't set a value and global option is "on"
if (options.disclose_me === undefined && self._publisher_disclose_me) {
options.disclose_me = true;
}
// create and remember new PUBLISH request
//
var d = null;
var request = newid();
if (options.acknowledge) {
d = self._defer();
self._publish_reqs[request] = [d, options];
}
// construct PUBLISH message
//
var msg = [MSG_TYPE.PUBLISH, request, options, self.resolve(topic)];
if (args) {
msg.push(args);
if (kwargs) {
msg.push(kwargs);
}
} else if (kwargs) {
msg.push([]);
msg.push(kwargs);
}
// send WAMP message
//
self._send_wamp(msg);
if (d) {
if (d.promise.then) {
// whenjs has the actual user promise in an attribute
return d.promise;
} else {
return d;
}
}
};
Session.prototype.subscribe = function (topic, handler, options) {
util.assert(typeof topic === 'string', "Session.subscribe: <topic> must be a string");
util.assert(typeof handler === 'function', "Session.subscribe: <handler> must be a function");
util.assert(!options || options instanceof Object, "Session.subscribe: <options> must be an object {}");
var self = this;
if (!self.isOpen) {
throw "session not open";
}
// create an remember new SUBSCRIBE request
//
var request = newid();
var d = self._defer();
self._subscribe_reqs[request] = [d, topic, handler, options];
// construct SUBSCRIBE message
//
var msg = [MSG_TYPE.SUBSCRIBE, request];
if (options) {
msg.push(options);
} else {
msg.push({});
}
msg.push(self.resolve(topic));
// send WAMP message
//
self._send_wamp(msg);
if (d.promise.then) {
// whenjs has the actual user promise in an attribute
return d.promise;
} else {
return d;
}
};
Session.prototype.register = function (procedure, endpoint, options) {
util.assert(typeof procedure === 'string', "Session.register: <procedure> must be a string");
util.assert(typeof endpoint === 'function', "Session.register: <endpoint> must be a function");
util.assert(!options || options instanceof Object, "Session.register: <options> must be an object {}");
var self = this;
if (!self.isOpen) {
throw "session not open";
}
// create an remember new REGISTER request
//
var request = newid();
var d = self._defer();
self._register_reqs[request] = [d, procedure, endpoint, options];
// construct REGISTER message
//
var msg = [MSG_TYPE.REGISTER, request];
if (options) {
msg.push(options);
} else {
msg.push({});
}
msg.push(self.resolve(procedure));
// send WAMP message
//
self._send_wamp(msg);
if (d.promise.then) {
// whenjs has the actual user promise in an attribute
return d.promise;
} else {
return d;
}
};
Session.prototype.unsubscribe = function (subscription) {
util.assert(subscription instanceof Subscription, "Session.unsubscribe: <subscription> must be an instance of class autobahn.Subscription");
var self = this;
if (!self.isOpen) {
throw "session not open";
}
if (!subscription.active || !(subscription.id in self._subscriptions)) {
throw "subscription not active";
}
var subs = self._subscriptions[subscription.id];
var i = subs.indexOf(subscription);
if (i === -1) {
throw "subscription not active";
}
// remove handler subscription
subs.splice(i, 1);
subscription.active = false;
var d = self._defer();
if (subs.length) {
// there are still handlers on the subscription ..
d.resolve(false);
} else {
// no handlers left ..
// create and remember new UNSUBSCRIBE request
//
var request = newid();
self._unsubscribe_reqs[request] = [d, subscription.id];
// construct UNSUBSCRIBE message
//
var msg = [MSG_TYPE.UNSUBSCRIBE, request, subscription.id];
// send WAMP message
//
self._send_wamp(msg);
}
if (d.promise.then) {
// whenjs has the actual user promise in an attribute
return d.promise;
} else {
return d;
}
};
Session.prototype.unregister = function (registration) {
util.assert(registration instanceof Registration, "Session.unregister: <registration> must be an instance of class autobahn.Registration");
var self = this;
if (!self.isOpen) {
throw "session not open";
}
if (!registration.active || !(registration.id in self._registrations)) {
throw "registration not active";
}
// create and remember new UNREGISTER request
//
var request = newid();
var d = self._defer();
self._unregister_reqs[request] = [d, registration];
// construct UNREGISTER message
//
var msg = [MSG_TYPE.UNREGISTER, request, registration.id];
// send WAMP message
//
self._send_wamp(msg);
if (d.promise.then) {
// whenjs has the actual user promise in an attribute
return d.promise;
} else {
return d;
}
};
Session.prototype.prefix = function (prefix, uri) {
util.assert(typeof prefix === 'string', "Session.prefix: <prefix> must be a string");
util.assert(!uri || typeof uri === 'string', "Session.prefix: <uri> must be a string or falsy");
var self = this;
if (uri) {
self._prefixes[prefix] = uri;
} else {
if (prefix in self._prefixes) {
delete self._prefixes[prefix];
}
}
};
Session.prototype.resolve = function (curie) {
util.assert(typeof curie === 'string', "Session.resolve: <curie> must be a string");
var self = this;
// skip if not a CURIE
var i = curie.indexOf(":");
if (i >= 0) {
var prefix = curie.substring(0, i);
if (prefix in self._prefixes) {
return self._prefixes[prefix] + '.' + curie.substring(i + 1);
} else {
throw "cannot resolve CURIE prefix '" + prefix + "'";
}
} else {
return curie;
}
};
exports.Session = Session;
exports.Invocation = Invocation;
exports.Event = Event;
exports.Result = Result;
exports.Error = Error;
exports.Subscription = Subscription;
exports.Registration = Registration;
exports.Publication = Publication;
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./log.js":7,"./util.js":19,"when":78,"when/function":54}],17:[function(require,module,exports){
///////////////////////////////////////////////////////////////////////////////
//
// AutobahnJS - http://autobahn.ws, http://wamp.ws
//
// A JavaScript library for WAMP ("The Web Application Messaging Protocol").
//
// Copyright (C) 2011-2014 Tavendo GmbH, http://tavendo.com
//
// Licensed under the MIT License.
// http://www.opensource.org/licenses/mit-license.php
//
///////////////////////////////////////////////////////////////////////////////
var util = require('../util.js');
var log = require('../log.js');
var when = require('when');
function Factory (options) {
var self = this;
util.assert(options.url !== undefined, "options.url missing");
util.assert(typeof options.url === "string", "options.url must be a string");
self._options = options;
};
Factory.prototype.type = "longpoll";
Factory.prototype.create = function () {
var self = this;
log.debug("longpoll.Factory.create");
// the WAMP transport we create
var transport = {};
// these will get defined further below
transport.protocol = undefined;
transport.send = undefined;
transport.close = undefined;
// these will get overridden by the WAMP session using this transport
transport.onmessage = function () {};
transport.onopen = function () {};
transport.onclose = function () {};
transport.info = {
type: 'longpoll',
url: null,
protocol: 'wamp.2.json'
};
transport._run = function () {
var session_info = null;
var send_buffer = [];
var is_closing = false;
var txseq = 0;
var rxseq = 0;
var options = {'protocols': ['wamp.2.json']};
var request_timeout = self._options.request_timeout || 2000;
util.http_post(self._options.url + '/open', JSON.stringify(options), request_timeout).then(
function (payload) {
session_info = JSON.parse(payload);
var base_url = self._options.url + '/' + session_info.transport;
transport.info.url = base_url;
log.debug("longpoll.Transport: open", session_info);
transport.close = function (code, reason) {
if (is_closing) {
throw "transport is already closing";
}
is_closing = true;
util.http_post(base_url + '/close', null, request_timeout).then(
function () {
log.debug("longpoll.Transport: transport closed");
var details = {
code: 1000,
reason: "transport closed",
wasClean: true
}
transport.onclose(details);
},
function (err) {
log.debug("longpoll.Transport: could not close transport", err.code, err.text);
}
);
}
transport.send = function (msg) {
if (is_closing) {
throw "transport is closing or closed already";
}
txseq += 1;
log.debug("longpoll.Transport: sending message ...", msg);
var payload = JSON.stringify(msg);
util.http_post(base_url + '/send', payload, request_timeout).then(
function () {
// ok, message sent
log.debug("longpoll.Transport: message sent");
},
function (err) {
log.debug("longpoll.Transport: could not send message", err.code, err.text);
is_closing = true;
var details = {
code: 1001,
reason: "transport send failure (HTTP/POST status " + err.code + " - '" + err.text + "')",
wasClean: false
}
transport.onclose(details);
}
);
};
function receive() {
rxseq += 1;
log.debug("longpoll.Transport: polling for message ...");
util.http_post(base_url + '/receive', null, request_timeout).then(
function (payload) {
if (payload) {
var msg = JSON.parse(payload);
log.debug("longpoll.Transport: message received", msg);
transport.onmessage(msg);
}
if (!is_closing) {
receive();
}
},
function (err) {
log.debug("longpoll.Transport: could not receive message", err.code, err.text);
is_closing = true;
var details = {
code: 1001,
reason: "transport receive failure (HTTP/POST status " + err.code + " - '" + err.text + "')",
wasClean: false
}
transport.onclose(details);
}
);
}
receive();
transport.onopen();
},
function (err) {
log.debug("longpoll.Transport: could not open transport", err.code, err.text);
is_closing = true;
var details = {
code: 1001,
reason: "transport open failure (HTTP/POST status " + err.code + " - '" + err.text + "')",
wasClean: false
}
transport.onclose(details);
}
);
}
transport._run();
return transport;
};
exports.Factory = Factory;
},{"../log.js":7,"../util.js":19,"when":78}],18:[function(require,module,exports){
(function (global){
///////////////////////////////////////////////////////////////////////////////
//
// AutobahnJS - http://autobahn.ws, http://wamp.ws
//
// A JavaScript library for WAMP ("The Web Application Messaging Protocol").
//
// Copyright (C) 2011-2014 Tavendo GmbH, http://tavendo.com
//
// Licensed under the MIT License.
// http://www.opensource.org/licenses/mit-license.php
//
///////////////////////////////////////////////////////////////////////////////
var util = require('../util.js');
var log = require('../log.js');
function Factory (options) {
var self = this;
util.assert(options.url !== undefined, "options.url missing");
util.assert(typeof options.url === "string", "options.url must be a string");
if (!options.protocols) {
options.protocols = ['wamp.2.json'];
} else {
util.assert(Array.isArray(options.protocols), "options.protocols must be an array");
}
self._options = options;
}
Factory.prototype.type = "websocket";
Factory.prototype.create = function () {
var self = this;
// the WAMP transport we create
var transport = {};
// these will get defined further below
transport.protocol = undefined;
transport.send = undefined;
transport.close = undefined;
// these will get overridden by the WAMP session using this transport
transport.onmessage = function () {};
transport.onopen = function () {};
transport.onclose = function () {};
transport.info = {
type: 'websocket',
url: null,
protocol: 'wamp.2.json'
};
//
// running in Node.js
//
if (global.process && global.process.versions.node) {
(function () {
var WebSocket = require('ws'); // https://github.com/einaros/ws
var websocket;
var protocols;
if (self._options.protocols) {
protocols = self._options.protocols;
if (Array.isArray(protocols)) {
protocols = protocols.join(',');
}
websocket = new WebSocket(self._options.url, {protocol: protocols});
} else {
websocket = new WebSocket(self._options.url);
}
transport.send = function (msg) {
var payload = JSON.stringify(msg);
websocket.send(payload, {binary: false});
};
transport.close = function (code, reason) {
websocket.close();
};
websocket.on('open', function () {
transport.onopen();
});
websocket.on('message', function (data, flags) {
if (flags.binary) {
// FIXME!
} else {
var msg = JSON.parse(data);
transport.onmessage(msg);
}
});
// FIXME: improve mapping to WS API for the following
// https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent#Close_codes
//
websocket.on('close', function (code, message) {
var details = {
code: code,
reason: message,
wasClean: code === 1000
}
transport.onclose(details);
});
websocket.on('error', function (error) {
var details = {
code: 1006,
reason: '',
wasClean: false
}
transport.onclose(details);
});
})();
//
// running in the browser
//
} else {
(function () {
var websocket;
// Chrome, MSIE, newer Firefox
if ("WebSocket" in global) {
if (self._options.protocols) {
websocket = new global.WebSocket(self._options.url, self._options.protocols);
} else {
websocket = new global.WebSocket(self._options.url);
}
// older versions of Firefox prefix the WebSocket object
} else if ("MozWebSocket" in global) {
if (self._options.protocols) {
websocket = new global.MozWebSocket(self._options.url, self._options.protocols);
} else {
websocket = new global.MozWebSocket(self._options.url);
}
} else {
throw "browser does not support WebSocket";
}
websocket.onmessage = function (evt) {
log.debug("WebSocket transport receive", evt.data);
var msg = JSON.parse(evt.data);
transport.onmessage(msg);
}
websocket.onopen = function () {
transport.info.url = self._options.url;
transport.onopen();
}
websocket.onclose = function (evt) {
var details = {
code: evt.code,
reason: evt.message,
wasClean: evt.wasClean
}
transport.onclose(details);
}
// do NOT do the following, since that will make
// transport.onclose() fire twice (browsers already fire
// websocket.onclose() for errors also)
//websocket.onerror = websocket.onclose;
transport.send = function (msg) {
var payload = JSON.stringify(msg);
log.debug("WebSocket transport send", payload);
websocket.send(payload);
}
transport.close = function (code, reason) {
websocket.close(code, reason);
};
})();
}
return transport;
};
exports.Factory = Factory;
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"../log.js":7,"../util.js":19,"ws":79}],19:[function(require,module,exports){
(function (global){
///////////////////////////////////////////////////////////////////////////////
//
// AutobahnJS - http://autobahn.ws, http://wamp.ws
//
// A JavaScript library for WAMP ("The Web Application Messaging Protocol").
//
// Copyright (C) 2011-2014 Tavendo GmbH, http://tavendo.com
//
// Licensed under the MIT License.
// http://www.opensource.org/licenses/mit-license.php
//
///////////////////////////////////////////////////////////////////////////////
var log = require('./log.js');
var when = require('when');
var rand_normal = function (mean, sd) {
// Derive a Gaussian from Uniform random variables
// http://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform
var x1, x2, rad;
do {
x1 = 2 * Math.random() - 1;
x2 = 2 * Math.random() - 1;
rad = x1 * x1 + x2 * x2;
} while (rad >= 1 || rad == 0);
var c = Math.sqrt(-2 * Math.log(rad) / rad);
return (mean || 0) + (x1 * c) * (sd || 1);
};
var assert = function (cond, text) {
if (cond) {
return;
}
if (assert.useDebugger || ('AUTOBAHN_DEBUG' in global && AUTOBAHN_DEBUG)) {
debugger;
}
throw new Error(text || "Assertion failed!");
};
// Helper to do HTTP/POST requests returning deferreds. This function is
// supposed to work on IE8, IE9 and old Android WebKit browsers. We don't care
// if it works with other browsers.
//
var http_post = function (url, data, timeout) {
log.debug("new http_post request", url, data, timeout);
var d = when.defer();
var req = new XMLHttpRequest();
req.onreadystatechange = function () {
if (req.readyState === 4) {
// Normalize IE's response to HTTP 204 when Win error 1223.
// http://stackoverflow.com/a/10047236/884770
//
var status = (req.status === 1223) ? 204 : req.status;
if (status === 200) {
// response with content
//
d.resolve(req.responseText);
} if (status === 204) {
// empty response
//
d.resolve();
} else {
// anything else is a fail
//
var statusText = null;
try {
statusText = req.statusText;
} catch (e) {
// IE8 fucks up on this
}
d.reject({code: status, text: statusText});
}
}
}
req.open("POST", url, true);
req.setRequestHeader("Content-type", "application/json; charset=utf-8");
if (timeout > 0) {
req.timeout = timeout; // request timeout in ms
req.ontimeout = function () {
d.reject({code: 501, text: "request timeout"});
}
}
if (data) {
req.send(data);
} else {
req.send();
}
if (d.promise.then) {
// whenjs has the actual user promise in an attribute
return d.promise;
} else {
return d;
}
};
exports.rand_normal = rand_normal;
exports.assert = assert;
exports.http_post = http_post;
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./log.js":7,"when":78}],20:[function(require,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"), require("./enc-base64"), require("./md5"), require("./evpkdf"), require("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var BlockCipher = C_lib.BlockCipher;
var C_algo = C.algo;
// Lookup tables
var SBOX = [];
var INV_SBOX = [];
var SUB_MIX_0 = [];
var SUB_MIX_1 = [];
var SUB_MIX_2 = [];
var SUB_MIX_3 = [];
var INV_SUB_MIX_0 = [];
var INV_SUB_MIX_1 = [];
var INV_SUB_MIX_2 = [];
var INV_SUB_MIX_3 = [];
// Compute lookup tables
(function () {
// Compute double table
var d = [];
for (var i = 0; i < 256; i++) {
if (i < 128) {
d[i] = i << 1;
} else {
d[i] = (i << 1) ^ 0x11b;
}
}
// Walk GF(2^8)
var x = 0;
var xi = 0;
for (var i = 0; i < 256; i++) {
// Compute sbox
var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4);
sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63;
SBOX[x] = sx;
INV_SBOX[sx] = x;
// Compute multiplication
var x2 = d[x];
var x4 = d[x2];
var x8 = d[x4];
// Compute sub bytes, mix columns tables
var t = (d[sx] * 0x101) ^ (sx * 0x1010100);
SUB_MIX_0[x] = (t << 24) | (t >>> 8);
SUB_MIX_1[x] = (t << 16) | (t >>> 16);
SUB_MIX_2[x] = (t << 8) | (t >>> 24);
SUB_MIX_3[x] = t;
// Compute inv sub bytes, inv mix columns tables
var t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100);
INV_SUB_MIX_0[sx] = (t << 24) | (t >>> 8);
INV_SUB_MIX_1[sx] = (t << 16) | (t >>> 16);
INV_SUB_MIX_2[sx] = (t << 8) | (t >>> 24);
INV_SUB_MIX_3[sx] = t;
// Compute next counter
if (!x) {
x = xi = 1;
} else {
x = x2 ^ d[d[d[x8 ^ x2]]];
xi ^= d[d[xi]];
}
}
}());
// Precomputed Rcon lookup
var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];
/**
* AES block cipher algorithm.
*/
var AES = C_algo.AES = BlockCipher.extend({
_doReset: function () {
// Shortcuts
var key = this._key;
var keyWords = key.words;
var keySize = key.sigBytes / 4;
// Compute number of rounds
var nRounds = this._nRounds = keySize + 6
// Compute number of key schedule rows
var ksRows = (nRounds + 1) * 4;
// Compute key schedule
var keySchedule = this._keySchedule = [];
for (var ksRow = 0; ksRow < ksRows; ksRow++) {
if (ksRow < keySize) {
keySchedule[ksRow] = keyWords[ksRow];
} else {
var t = keySchedule[ksRow - 1];
if (!(ksRow % keySize)) {
// Rot word
t = (t << 8) | (t >>> 24);
// Sub word
t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff];
// Mix Rcon
t ^= RCON[(ksRow / keySize) | 0] << 24;
} else if (keySize > 6 && ksRow % keySize == 4) {
// Sub word
t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff];
}
keySchedule[ksRow] = keySchedule[ksRow - keySize] ^ t;
}
}
// Compute inv key schedule
var invKeySchedule = this._invKeySchedule = [];
for (var invKsRow = 0; invKsRow < ksRows; invKsRow++) {
var ksRow = ksRows - invKsRow;
if (invKsRow % 4) {
var t = keySchedule[ksRow];
} else {
var t = keySchedule[ksRow - 4];
}
if (invKsRow < 4 || ksRow <= 4) {
invKeySchedule[invKsRow] = t;
} else {
invKeySchedule[invKsRow] = INV_SUB_MIX_0[SBOX[t >>> 24]] ^ INV_SUB_MIX_1[SBOX[(t >>> 16) & 0xff]] ^
INV_SUB_MIX_2[SBOX[(t >>> 8) & 0xff]] ^ INV_SUB_MIX_3[SBOX[t & 0xff]];
}
}
},
encryptBlock: function (M, offset) {
this._doCryptBlock(M, offset, this._keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX);
},
decryptBlock: function (M, offset) {
// Swap 2nd and 4th rows
var t = M[offset + 1];
M[offset + 1] = M[offset + 3];
M[offset + 3] = t;
this._doCryptBlock(M, offset, this._invKeySchedule, INV_SUB_MIX_0, INV_SUB_MIX_1, INV_SUB_MIX_2, INV_SUB_MIX_3, INV_SBOX);
// Inv swap 2nd and 4th rows
var t = M[offset + 1];
M[offset + 1] = M[offset + 3];
M[offset + 3] = t;
},
_doCryptBlock: function (M, offset, keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX) {
// Shortcut
var nRounds = this._nRounds;
// Get input, add round key
var s0 = M[offset] ^ keySchedule[0];
var s1 = M[offset + 1] ^ keySchedule[1];
var s2 = M[offset + 2] ^ keySchedule[2];
var s3 = M[offset + 3] ^ keySchedule[3];
// Key schedule row counter
var ksRow = 4;
// Rounds
for (var round = 1; round < nRounds; round++) {
// Shift rows, sub bytes, mix columns, add round key
var t0 = SUB_MIX_0[s0 >>> 24] ^ SUB_MIX_1[(s1 >>> 16) & 0xff] ^ SUB_MIX_2[(s2 >>> 8) & 0xff] ^ SUB_MIX_3[s3 & 0xff] ^ keySchedule[ksRow++];
var t1 = SUB_MIX_0[s1 >>> 24] ^ SUB_MIX_1[(s2 >>> 16) & 0xff] ^ SUB_MIX_2[(s3 >>> 8) & 0xff] ^ SUB_MIX_3[s0 & 0xff] ^ keySchedule[ksRow++];
var t2 = SUB_MIX_0[s2 >>> 24] ^ SUB_MIX_1[(s3 >>> 16) & 0xff] ^ SUB_MIX_2[(s0 >>> 8) & 0xff] ^ SUB_MIX_3[s1 & 0xff] ^ keySchedule[ksRow++];
var t3 = SUB_MIX_0[s3 >>> 24] ^ SUB_MIX_1[(s0 >>> 16) & 0xff] ^ SUB_MIX_2[(s1 >>> 8) & 0xff] ^ SUB_MIX_3[s2 & 0xff] ^ keySchedule[ksRow++];
// Update state
s0 = t0;
s1 = t1;
s2 = t2;
s3 = t3;
}
// Shift rows, sub bytes, add round key
var t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++];
var t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++];
var t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++];
var t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++];
// Set output
M[offset] = t0;
M[offset + 1] = t1;
M[offset + 2] = t2;
M[offset + 3] = t3;
},
keySize: 256/32
});
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.AES.encrypt(message, key, cfg);
* var plaintext = CryptoJS.AES.decrypt(ciphertext, key, cfg);
*/
C.AES = BlockCipher._createHelper(AES);
}());
return CryptoJS.AES;
}));
},{"./cipher-core":21,"./core":22,"./enc-base64":23,"./evpkdf":25,"./md5":30}],21:[function(require,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Cipher core components.
*/
CryptoJS.lib.Cipher || (function (undefined) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var WordArray = C_lib.WordArray;
var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm;
var C_enc = C.enc;
var Utf8 = C_enc.Utf8;
var Base64 = C_enc.Base64;
var C_algo = C.algo;
var EvpKDF = C_algo.EvpKDF;
/**
* Abstract base cipher template.
*
* @property {number} keySize This cipher's key size. Default: 4 (128 bits)
* @property {number} ivSize This cipher's IV size. Default: 4 (128 bits)
* @property {number} _ENC_XFORM_MODE A constant representing encryption mode.
* @property {number} _DEC_XFORM_MODE A constant representing decryption mode.
*/
var Cipher = C_lib.Cipher = BufferedBlockAlgorithm.extend({
/**
* Configuration options.
*
* @property {WordArray} iv The IV to use for this operation.
*/
cfg: Base.extend(),
/**
* Creates this cipher in encryption mode.
*
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {Cipher} A cipher instance.
*
* @static
*
* @example
*
* var cipher = CryptoJS.algo.AES.createEncryptor(keyWordArray, { iv: ivWordArray });
*/
createEncryptor: function (key, cfg) {
return this.create(this._ENC_XFORM_MODE, key, cfg);
},
/**
* Creates this cipher in decryption mode.
*
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {Cipher} A cipher instance.
*
* @static
*
* @example
*
* var cipher = CryptoJS.algo.AES.createDecryptor(keyWordArray, { iv: ivWordArray });
*/
createDecryptor: function (key, cfg) {
return this.create(this._DEC_XFORM_MODE, key, cfg);
},
/**
* Initializes a newly created cipher.
*
* @param {number} xformMode Either the encryption or decryption transormation mode constant.
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @example
*
* var cipher = CryptoJS.algo.AES.create(CryptoJS.algo.AES._ENC_XFORM_MODE, keyWordArray, { iv: ivWordArray });
*/
init: function (xformMode, key, cfg) {
// Apply config defaults
this.cfg = this.cfg.extend(cfg);
// Store transform mode and key
this._xformMode = xformMode;
this._key = key;
// Set initial values
this.reset();
},
/**
* Resets this cipher to its initial state.
*
* @example
*
* cipher.reset();
*/
reset: function () {
// Reset data buffer
BufferedBlockAlgorithm.reset.call(this);
// Perform concrete-cipher logic
this._doReset();
},
/**
* Adds data to be encrypted or decrypted.
*
* @param {WordArray|string} dataUpdate The data to encrypt or decrypt.
*
* @return {WordArray} The data after processing.
*
* @example
*
* var encrypted = cipher.process('data');
* var encrypted = cipher.process(wordArray);
*/
process: function (dataUpdate) {
// Append
this._append(dataUpdate);
// Process available blocks
return this._process();
},
/**
* Finalizes the encryption or decryption process.
* Note that the finalize operation is effectively a destructive, read-once operation.
*
* @param {WordArray|string} dataUpdate The final data to encrypt or decrypt.
*
* @return {WordArray} The data after final processing.
*
* @example
*
* var encrypted = cipher.finalize();
* var encrypted = cipher.finalize('data');
* var encrypted = cipher.finalize(wordArray);
*/
finalize: function (dataUpdate) {
// Final data update
if (dataUpdate) {
this._append(dataUpdate);
}
// Perform concrete-cipher logic
var finalProcessedData = this._doFinalize();
return finalProcessedData;
},
keySize: 128/32,
ivSize: 128/32,
_ENC_XFORM_MODE: 1,
_DEC_XFORM_MODE: 2,
/**
* Creates shortcut functions to a cipher's object interface.
*
* @param {Cipher} cipher The cipher to create a helper for.
*
* @return {Object} An object with encrypt and decrypt shortcut functions.
*
* @static
*
* @example
*
* var AES = CryptoJS.lib.Cipher._createHelper(CryptoJS.algo.AES);
*/
_createHelper: (function () {
function selectCipherStrategy(key) {
if (typeof key == 'string') {
return PasswordBasedCipher;
} else {
return SerializableCipher;
}
}
return function (cipher) {
return {
encrypt: function (message, key, cfg) {
return selectCipherStrategy(key).encrypt(cipher, message, key, cfg);
},
decrypt: function (ciphertext, key, cfg) {
return selectCipherStrategy(key).decrypt(cipher, ciphertext, key, cfg);
}
};
};
}())
});
/**
* Abstract base stream cipher template.
*
* @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 1 (32 bits)
*/
var StreamCipher = C_lib.StreamCipher = Cipher.extend({
_doFinalize: function () {
// Process partial blocks
var finalProcessedBlocks = this._process(!!'flush');
return finalProcessedBlocks;
},
blockSize: 1
});
/**
* Mode namespace.
*/
var C_mode = C.mode = {};
/**
* Abstract base block cipher mode template.
*/
var BlockCipherMode = C_lib.BlockCipherMode = Base.extend({
/**
* Creates this mode for encryption.
*
* @param {Cipher} cipher A block cipher instance.
* @param {Array} iv The IV words.
*
* @static
*
* @example
*
* var mode = CryptoJS.mode.CBC.createEncryptor(cipher, iv.words);
*/
createEncryptor: function (cipher, iv) {
return this.Encryptor.create(cipher, iv);
},
/**
* Creates this mode for decryption.
*
* @param {Cipher} cipher A block cipher instance.
* @param {Array} iv The IV words.
*
* @static
*
* @example
*
* var mode = CryptoJS.mode.CBC.createDecryptor(cipher, iv.words);
*/
createDecryptor: function (cipher, iv) {
return this.Decryptor.create(cipher, iv);
},
/**
* Initializes a newly created mode.
*
* @param {Cipher} cipher A block cipher instance.
* @param {Array} iv The IV words.
*
* @example
*
* var mode = CryptoJS.mode.CBC.Encryptor.create(cipher, iv.words);
*/
init: function (cipher, iv) {
this._cipher = cipher;
this._iv = iv;
}
});
/**
* Cipher Block Chaining mode.
*/
var CBC = C_mode.CBC = (function () {
/**
* Abstract base CBC mode.
*/
var CBC = BlockCipherMode.extend();
/**
* CBC encryptor.
*/
CBC.Encryptor = CBC.extend({
/**
* Processes the data block at offset.
*
* @param {Array} words The data words to operate on.
* @param {number} offset The offset where the block starts.
*
* @example
*
* mode.processBlock(data.words, offset);
*/
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher;
var blockSize = cipher.blockSize;
// XOR and encrypt
xorBlock.call(this, words, offset, blockSize);
cipher.encryptBlock(words, offset);
// Remember this block to use with next block
this._prevBlock = words.slice(offset, offset + blockSize);
}
});
/**
* CBC decryptor.
*/
CBC.Decryptor = CBC.extend({
/**
* Processes the data block at offset.
*
* @param {Array} words The data words to operate on.
* @param {number} offset The offset where the block starts.
*
* @example
*
* mode.processBlock(data.words, offset);
*/
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher;
var blockSize = cipher.blockSize;
// Remember this block to use with next block
var thisBlock = words.slice(offset, offset + blockSize);
// Decrypt and XOR
cipher.decryptBlock(words, offset);
xorBlock.call(this, words, offset, blockSize);
// This block becomes the previous block
this._prevBlock = thisBlock;
}
});
function xorBlock(words, offset, blockSize) {
// Shortcut
var iv = this._iv;
// Choose mixing block
if (iv) {
var block = iv;
// Remove IV for subsequent blocks
this._iv = undefined;
} else {
var block = this._prevBlock;
}
// XOR blocks
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= block[i];
}
}
return CBC;
}());
/**
* Padding namespace.
*/
var C_pad = C.pad = {};
/**
* PKCS #5/7 padding strategy.
*/
var Pkcs7 = C_pad.Pkcs7 = {
/**
* Pads data using the algorithm defined in PKCS #5/7.
*
* @param {WordArray} data The data to pad.
* @param {number} blockSize The multiple that the data should be padded to.
*
* @static
*
* @example
*
* CryptoJS.pad.Pkcs7.pad(wordArray, 4);
*/
pad: function (data, blockSize) {
// Shortcut
var blockSizeBytes = blockSize * 4;
// Count padding bytes
var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes;
// Create padding word
var paddingWord = (nPaddingBytes << 24) | (nPaddingBytes << 16) | (nPaddingBytes << 8) | nPaddingBytes;
// Create padding
var paddingWords = [];
for (var i = 0; i < nPaddingBytes; i += 4) {
paddingWords.push(paddingWord);
}
var padding = WordArray.create(paddingWords, nPaddingBytes);
// Add padding
data.concat(padding);
},
/**
* Unpads data that had been padded using the algorithm defined in PKCS #5/7.
*
* @param {WordArray} data The data to unpad.
*
* @static
*
* @example
*
* CryptoJS.pad.Pkcs7.unpad(wordArray);
*/
unpad: function (data) {
// Get number of padding bytes from last byte
var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff;
// Remove padding
data.sigBytes -= nPaddingBytes;
}
};
/**
* Abstract base block cipher template.
*
* @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 4 (128 bits)
*/
var BlockCipher = C_lib.BlockCipher = Cipher.extend({
/**
* Configuration options.
*
* @property {Mode} mode The block mode to use. Default: CBC
* @property {Padding} padding The padding strategy to use. Default: Pkcs7
*/
cfg: Cipher.cfg.extend({
mode: CBC,
padding: Pkcs7
}),
reset: function () {
// Reset cipher
Cipher.reset.call(this);
// Shortcuts
var cfg = this.cfg;
var iv = cfg.iv;
var mode = cfg.mode;
// Reset block mode
if (this._xformMode == this._ENC_XFORM_MODE) {
var modeCreator = mode.createEncryptor;
} else /* if (this._xformMode == this._DEC_XFORM_MODE) */ {
var modeCreator = mode.createDecryptor;
// Keep at least one block in the buffer for unpadding
this._minBufferSize = 1;
}
this._mode = modeCreator.call(mode, this, iv && iv.words);
},
_doProcessBlock: function (words, offset) {
this._mode.processBlock(words, offset);
},
_doFinalize: function () {
// Shortcut
var padding = this.cfg.padding;
// Finalize
if (this._xformMode == this._ENC_XFORM_MODE) {
// Pad data
padding.pad(this._data, this.blockSize);
// Process final blocks
var finalProcessedBlocks = this._process(!!'flush');
} else /* if (this._xformMode == this._DEC_XFORM_MODE) */ {
// Process final blocks
var finalProcessedBlocks = this._process(!!'flush');
// Unpad data
padding.unpad(finalProcessedBlocks);
}
return finalProcessedBlocks;
},
blockSize: 128/32
});
/**
* A collection of cipher parameters.
*
* @property {WordArray} ciphertext The raw ciphertext.
* @property {WordArray} key The key to this ciphertext.
* @property {WordArray} iv The IV used in the ciphering operation.
* @property {WordArray} salt The salt used with a key derivation function.
* @property {Cipher} algorithm The cipher algorithm.
* @property {Mode} mode The block mode used in the ciphering operation.
* @property {Padding} padding The padding scheme used in the ciphering operation.
* @property {number} blockSize The block size of the cipher.
* @property {Format} formatter The default formatting strategy to convert this cipher params object to a string.
*/
var CipherParams = C_lib.CipherParams = Base.extend({
/**
* Initializes a newly created cipher params object.
*
* @param {Object} cipherParams An object with any of the possible cipher parameters.
*
* @example
*
* var cipherParams = CryptoJS.lib.CipherParams.create({
* ciphertext: ciphertextWordArray,
* key: keyWordArray,
* iv: ivWordArray,
* salt: saltWordArray,
* algorithm: CryptoJS.algo.AES,
* mode: CryptoJS.mode.CBC,
* padding: CryptoJS.pad.PKCS7,
* blockSize: 4,
* formatter: CryptoJS.format.OpenSSL
* });
*/
init: function (cipherParams) {
this.mixIn(cipherParams);
},
/**
* Converts this cipher params object to a string.
*
* @param {Format} formatter (Optional) The formatting strategy to use.
*
* @return {string} The stringified cipher params.
*
* @throws Error If neither the formatter nor the default formatter is set.
*
* @example
*
* var string = cipherParams + '';
* var string = cipherParams.toString();
* var string = cipherParams.toString(CryptoJS.format.OpenSSL);
*/
toString: function (formatter) {
return (formatter || this.formatter).stringify(this);
}
});
/**
* Format namespace.
*/
var C_format = C.format = {};
/**
* OpenSSL formatting strategy.
*/
var OpenSSLFormatter = C_format.OpenSSL = {
/**
* Converts a cipher params object to an OpenSSL-compatible string.
*
* @param {CipherParams} cipherParams The cipher params object.
*
* @return {string} The OpenSSL-compatible string.
*
* @static
*
* @example
*
* var openSSLString = CryptoJS.format.OpenSSL.stringify(cipherParams);
*/
stringify: function (cipherParams) {
// Shortcuts
var ciphertext = cipherParams.ciphertext;
var salt = cipherParams.salt;
// Format
if (salt) {
var wordArray = WordArray.create([0x53616c74, 0x65645f5f]).concat(salt).concat(ciphertext);
} else {
var wordArray = ciphertext;
}
return wordArray.toString(Base64);
},
/**
* Converts an OpenSSL-compatible string to a cipher params object.
*
* @param {string} openSSLStr The OpenSSL-compatible string.
*
* @return {CipherParams} The cipher params object.
*
* @static
*
* @example
*
* var cipherParams = CryptoJS.format.OpenSSL.parse(openSSLString);
*/
parse: function (openSSLStr) {
// Parse base64
var ciphertext = Base64.parse(openSSLStr);
// Shortcut
var ciphertextWords = ciphertext.words;
// Test for salt
if (ciphertextWords[0] == 0x53616c74 && ciphertextWords[1] == 0x65645f5f) {
// Extract salt
var salt = WordArray.create(ciphertextWords.slice(2, 4));
// Remove salt from ciphertext
ciphertextWords.splice(0, 4);
ciphertext.sigBytes -= 16;
}
return CipherParams.create({ ciphertext: ciphertext, salt: salt });
}
};
/**
* A cipher wrapper that returns ciphertext as a serializable cipher params object.
*/
var SerializableCipher = C_lib.SerializableCipher = Base.extend({
/**
* Configuration options.
*
* @property {Formatter} format The formatting strategy to convert cipher param objects to and from a string. Default: OpenSSL
*/
cfg: Base.extend({
format: OpenSSLFormatter
}),
/**
* Encrypts a message.
*
* @param {Cipher} cipher The cipher algorithm to use.
* @param {WordArray|string} message The message to encrypt.
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {CipherParams} A cipher params object.
*
* @static
*
* @example
*
* var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key);
* var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv });
* var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv, format: CryptoJS.format.OpenSSL });
*/
encrypt: function (cipher, message, key, cfg) {
// Apply config defaults
cfg = this.cfg.extend(cfg);
// Encrypt
var encryptor = cipher.createEncryptor(key, cfg);
var ciphertext = encryptor.finalize(message);
// Shortcut
var cipherCfg = encryptor.cfg;
// Create and return serializable cipher params
return CipherParams.create({
ciphertext: ciphertext,
key: key,
iv: cipherCfg.iv,
algorithm: cipher,
mode: cipherCfg.mode,
padding: cipherCfg.padding,
blockSize: cipher.blockSize,
formatter: cfg.format
});
},
/**
* Decrypts serialized ciphertext.
*
* @param {Cipher} cipher The cipher algorithm to use.
* @param {CipherParams|string} ciphertext The ciphertext to decrypt.
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {WordArray} The plaintext.
*
* @static
*
* @example
*
* var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, key, { iv: iv, format: CryptoJS.format.OpenSSL });
* var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, key, { iv: iv, format: CryptoJS.format.OpenSSL });
*/
decrypt: function (cipher, ciphertext, key, cfg) {
// Apply config defaults
cfg = this.cfg.extend(cfg);
// Convert string to CipherParams
ciphertext = this._parse(ciphertext, cfg.format);
// Decrypt
var plaintext = cipher.createDecryptor(key, cfg).finalize(ciphertext.ciphertext);
return plaintext;
},
/**
* Converts serialized ciphertext to CipherParams,
* else assumed CipherParams already and returns ciphertext unchanged.
*
* @param {CipherParams|string} ciphertext The ciphertext.
* @param {Formatter} format The formatting strategy to use to parse serialized ciphertext.
*
* @return {CipherParams} The unserialized ciphertext.
*
* @static
*
* @example
*
* var ciphertextParams = CryptoJS.lib.SerializableCipher._parse(ciphertextStringOrParams, format);
*/
_parse: function (ciphertext, format) {
if (typeof ciphertext == 'string') {
return format.parse(ciphertext, this);
} else {
return ciphertext;
}
}
});
/**
* Key derivation function namespace.
*/
var C_kdf = C.kdf = {};
/**
* OpenSSL key derivation function.
*/
var OpenSSLKdf = C_kdf.OpenSSL = {
/**
* Derives a key and IV from a password.
*
* @param {string} password The password to derive from.
* @param {number} keySize The size in words of the key to generate.
* @param {number} ivSize The size in words of the IV to generate.
* @param {WordArray|string} salt (Optional) A 64-bit salt to use. If omitted, a salt will be generated randomly.
*
* @return {CipherParams} A cipher params object with the key, IV, and salt.
*
* @static
*
* @example
*
* var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32);
* var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32, 'saltsalt');
*/
execute: function (password, keySize, ivSize, salt) {
// Generate random salt
if (!salt) {
salt = WordArray.random(64/8);
}
// Derive key and IV
var key = EvpKDF.create({ keySize: keySize + ivSize }).compute(password, salt);
// Separate key and IV
var iv = WordArray.create(key.words.slice(keySize), ivSize * 4);
key.sigBytes = keySize * 4;
// Return params
return CipherParams.create({ key: key, iv: iv, salt: salt });
}
};
/**
* A serializable cipher wrapper that derives the key from a password,
* and returns ciphertext as a serializable cipher params object.
*/
var PasswordBasedCipher = C_lib.PasswordBasedCipher = SerializableCipher.extend({
/**
* Configuration options.
*
* @property {KDF} kdf The key derivation function to use to generate a key and IV from a password. Default: OpenSSL
*/
cfg: SerializableCipher.cfg.extend({
kdf: OpenSSLKdf
}),
/**
* Encrypts a message using a password.
*
* @param {Cipher} cipher The cipher algorithm to use.
* @param {WordArray|string} message The message to encrypt.
* @param {string} password The password.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {CipherParams} A cipher params object.
*
* @static
*
* @example
*
* var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password');
* var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password', { format: CryptoJS.format.OpenSSL });
*/
encrypt: function (cipher, message, password, cfg) {
// Apply config defaults
cfg = this.cfg.extend(cfg);
// Derive key and other params
var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize);
// Add IV to config
cfg.iv = derivedParams.iv;
// Encrypt
var ciphertext = SerializableCipher.encrypt.call(this, cipher, message, derivedParams.key, cfg);
// Mix in derived params
ciphertext.mixIn(derivedParams);
return ciphertext;
},
/**
* Decrypts serialized ciphertext using a password.
*
* @param {Cipher} cipher The cipher algorithm to use.
* @param {CipherParams|string} ciphertext The ciphertext to decrypt.
* @param {string} password The password.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {WordArray} The plaintext.
*
* @static
*
* @example
*
* var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, 'password', { format: CryptoJS.format.OpenSSL });
* var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, 'password', { format: CryptoJS.format.OpenSSL });
*/
decrypt: function (cipher, ciphertext, password, cfg) {
// Apply config defaults
cfg = this.cfg.extend(cfg);
// Convert string to CipherParams
ciphertext = this._parse(ciphertext, cfg.format);
// Derive key and other params
var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize, ciphertext.salt);
// Add IV to config
cfg.iv = derivedParams.iv;
// Decrypt
var plaintext = SerializableCipher.decrypt.call(this, cipher, ciphertext, derivedParams.key, cfg);
return plaintext;
}
});
}());
}));
},{"./core":22}],22:[function(require,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory();
}
else if (typeof define === "function" && define.amd) {
// AMD
define([], factory);
}
else {
// Global (browser)
root.CryptoJS = factory();
}
}(this, function () {
/**
* CryptoJS core components.
*/
var CryptoJS = CryptoJS || (function (Math, undefined) {
/**
* CryptoJS namespace.
*/
var C = {};
/**
* Library namespace.
*/
var C_lib = C.lib = {};
/**
* Base object for prototypal inheritance.
*/
var Base = C_lib.Base = (function () {
function F() {}
return {
/**
* Creates a new object that inherits from this object.
*
* @param {Object} overrides Properties to copy into the new object.
*
* @return {Object} The new object.
*
* @static
*
* @example
*
* var MyType = CryptoJS.lib.Base.extend({
* field: 'value',
*
* method: function () {
* }
* });
*/
extend: function (overrides) {
// Spawn
F.prototype = this;
var subtype = new F();
// Augment
if (overrides) {
subtype.mixIn(overrides);
}
// Create default initializer
if (!subtype.hasOwnProperty('init')) {
subtype.init = function () {
subtype.$super.init.apply(this, arguments);
};
}
// Initializer's prototype is the subtype object
subtype.init.prototype = subtype;
// Reference supertype
subtype.$super = this;
return subtype;
},
/**
* Extends this object and runs the init method.
* Arguments to create() will be passed to init().
*
* @return {Object} The new object.
*
* @static
*
* @example
*
* var instance = MyType.create();
*/
create: function () {
var instance = this.extend();
instance.init.apply(instance, arguments);
return instance;
},
/**
* Initializes a newly created object.
* Override this method to add some logic when your objects are created.
*
* @example
*
* var MyType = CryptoJS.lib.Base.extend({
* init: function () {
* // ...
* }
* });
*/
init: function () {
},
/**
* Copies properties into this object.
*
* @param {Object} properties The properties to mix in.
*
* @example
*
* MyType.mixIn({
* field: 'value'
* });
*/
mixIn: function (properties) {
for (var propertyName in properties) {
if (properties.hasOwnProperty(propertyName)) {
this[propertyName] = properties[propertyName];
}
}
// IE won't copy toString using the loop above
if (properties.hasOwnProperty('toString')) {
this.toString = properties.toString;
}
},
/**
* Creates a copy of this object.
*
* @return {Object} The clone.
*
* @example
*
* var clone = instance.clone();
*/
clone: function () {
return this.init.prototype.extend(this);
}
};
}());
/**
* An array of 32-bit words.
*
* @property {Array} words The array of 32-bit words.
* @property {number} sigBytes The number of significant bytes in this word array.
*/
var WordArray = C_lib.WordArray = Base.extend({
/**
* Initializes a newly created word array.
*
* @param {Array} words (Optional) An array of 32-bit words.
* @param {number} sigBytes (Optional) The number of significant bytes in the words.
*
* @example
*
* var wordArray = CryptoJS.lib.WordArray.create();
* var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]);
* var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6);
*/
init: function (words, sigBytes) {
words = this.words = words || [];
if (sigBytes != undefined) {
this.sigBytes = sigBytes;
} else {
this.sigBytes = words.length * 4;
}
},
/**
* Converts this word array to a string.
*
* @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex
*
* @return {string} The stringified word array.
*
* @example
*
* var string = wordArray + '';
* var string = wordArray.toString();
* var string = wordArray.toString(CryptoJS.enc.Utf8);
*/
toString: function (encoder) {
return (encoder || Hex).stringify(this);
},
/**
* Concatenates a word array to this word array.
*
* @param {WordArray} wordArray The word array to append.
*
* @return {WordArray} This word array.
*
* @example
*
* wordArray1.concat(wordArray2);
*/
concat: function (wordArray) {
// Shortcuts
var thisWords = this.words;
var thatWords = wordArray.words;
var thisSigBytes = this.sigBytes;
var thatSigBytes = wordArray.sigBytes;
// Clamp excess bits
this.clamp();
// Concat
if (thisSigBytes % 4) {
// Copy one byte at a time
for (var i = 0; i < thatSigBytes; i++) {
var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8);
}
} else if (thatWords.length > 0xffff) {
// Copy one word at a time
for (var i = 0; i < thatSigBytes; i += 4) {
thisWords[(thisSigBytes + i) >>> 2] = thatWords[i >>> 2];
}
} else {
// Copy all words at once
thisWords.push.apply(thisWords, thatWords);
}
this.sigBytes += thatSigBytes;
// Chainable
return this;
},
/**
* Removes insignificant bits.
*
* @example
*
* wordArray.clamp();
*/
clamp: function () {
// Shortcuts
var words = this.words;
var sigBytes = this.sigBytes;
// Clamp
words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8);
words.length = Math.ceil(sigBytes / 4);
},
/**
* Creates a copy of this word array.
*
* @return {WordArray} The clone.
*
* @example
*
* var clone = wordArray.clone();
*/
clone: function () {
var clone = Base.clone.call(this);
clone.words = this.words.slice(0);
return clone;
},
/**
* Creates a word array filled with random bytes.
*
* @param {number} nBytes The number of random bytes to generate.
*
* @return {WordArray} The random word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.lib.WordArray.random(16);
*/
random: function (nBytes) {
var words = [];
var r = (function (m_w) {
var m_w = m_w;
var m_z = 0x3ade68b1;
var mask = 0xffffffff;
return function () {
m_z = (0x9069 * (m_z & 0xFFFF) + (m_z >> 0x10)) & mask;
m_w = (0x4650 * (m_w & 0xFFFF) + (m_w >> 0x10)) & mask;
var result = ((m_z << 0x10) + m_w) & mask;
result /= 0x100000000;
result += 0.5;
return result * (Math.random() > .5 ? 1 : -1);
}
});
for (var i = 0, rcache; i < nBytes; i += 4) {
var _r = r((rcache || Math.random()) * 0x100000000);
rcache = _r() * 0x3ade67b7;
words.push((_r() * 0x100000000) | 0);
}
return new WordArray.init(words, nBytes);
}
});
/**
* Encoder namespace.
*/
var C_enc = C.enc = {};
/**
* Hex encoding strategy.
*/
var Hex = C_enc.Hex = {
/**
* Converts a word array to a hex string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The hex string.
*
* @static
*
* @example
*
* var hexString = CryptoJS.enc.Hex.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
// Convert
var hexChars = [];
for (var i = 0; i < sigBytes; i++) {
var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
hexChars.push((bite >>> 4).toString(16));
hexChars.push((bite & 0x0f).toString(16));
}
return hexChars.join('');
},
/**
* Converts a hex string to a word array.
*
* @param {string} hexStr The hex string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Hex.parse(hexString);
*/
parse: function (hexStr) {
// Shortcut
var hexStrLength = hexStr.length;
// Convert
var words = [];
for (var i = 0; i < hexStrLength; i += 2) {
words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4);
}
return new WordArray.init(words, hexStrLength / 2);
}
};
/**
* Latin1 encoding strategy.
*/
var Latin1 = C_enc.Latin1 = {
/**
* Converts a word array to a Latin1 string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The Latin1 string.
*
* @static
*
* @example
*
* var latin1String = CryptoJS.enc.Latin1.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
// Convert
var latin1Chars = [];
for (var i = 0; i < sigBytes; i++) {
var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
latin1Chars.push(String.fromCharCode(bite));
}
return latin1Chars.join('');
},
/**
* Converts a Latin1 string to a word array.
*
* @param {string} latin1Str The Latin1 string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Latin1.parse(latin1String);
*/
parse: function (latin1Str) {
// Shortcut
var latin1StrLength = latin1Str.length;
// Convert
var words = [];
for (var i = 0; i < latin1StrLength; i++) {
words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8);
}
return new WordArray.init(words, latin1StrLength);
}
};
/**
* UTF-8 encoding strategy.
*/
var Utf8 = C_enc.Utf8 = {
/**
* Converts a word array to a UTF-8 string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The UTF-8 string.
*
* @static
*
* @example
*
* var utf8String = CryptoJS.enc.Utf8.stringify(wordArray);
*/
stringify: function (wordArray) {
try {
return decodeURIComponent(escape(Latin1.stringify(wordArray)));
} catch (e) {
throw new Error('Malformed UTF-8 data');
}
},
/**
* Converts a UTF-8 string to a word array.
*
* @param {string} utf8Str The UTF-8 string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Utf8.parse(utf8String);
*/
parse: function (utf8Str) {
return Latin1.parse(unescape(encodeURIComponent(utf8Str)));
}
};
/**
* Abstract buffered block algorithm template.
*
* The property blockSize must be implemented in a concrete subtype.
*
* @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0
*/
var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({
/**
* Resets this block algorithm's data buffer to its initial state.
*
* @example
*
* bufferedBlockAlgorithm.reset();
*/
reset: function () {
// Initial values
this._data = new WordArray.init();
this._nDataBytes = 0;
},
/**
* Adds new data to this block algorithm's buffer.
*
* @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8.
*
* @example
*
* bufferedBlockAlgorithm._append('data');
* bufferedBlockAlgorithm._append(wordArray);
*/
_append: function (data) {
// Convert string to WordArray, else assume WordArray already
if (typeof data == 'string') {
data = Utf8.parse(data);
}
// Append
this._data.concat(data);
this._nDataBytes += data.sigBytes;
},
/**
* Processes available data blocks.
*
* This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype.
*
* @param {boolean} doFlush Whether all blocks and partial blocks should be processed.
*
* @return {WordArray} The processed data.
*
* @example
*
* var processedData = bufferedBlockAlgorithm._process();
* var processedData = bufferedBlockAlgorithm._process(!!'flush');
*/
_process: function (doFlush) {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var dataSigBytes = data.sigBytes;
var blockSize = this.blockSize;
var blockSizeBytes = blockSize * 4;
// Count blocks ready
var nBlocksReady = dataSigBytes / blockSizeBytes;
if (doFlush) {
// Round up to include partial blocks
nBlocksReady = Math.ceil(nBlocksReady);
} else {
// Round down to include only full blocks,
// less the number of blocks that must remain in the buffer
nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0);
}
// Count words ready
var nWordsReady = nBlocksReady * blockSize;
// Count bytes ready
var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes);
// Process blocks
if (nWordsReady) {
for (var offset = 0; offset < nWordsReady; offset += blockSize) {
// Perform concrete-algorithm logic
this._doProcessBlock(dataWords, offset);
}
// Remove processed words
var processedWords = dataWords.splice(0, nWordsReady);
data.sigBytes -= nBytesReady;
}
// Return processed words
return new WordArray.init(processedWords, nBytesReady);
},
/**
* Creates a copy of this object.
*
* @return {Object} The clone.
*
* @example
*
* var clone = bufferedBlockAlgorithm.clone();
*/
clone: function () {
var clone = Base.clone.call(this);
clone._data = this._data.clone();
return clone;
},
_minBufferSize: 0
});
/**
* Abstract hasher template.
*
* @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits)
*/
var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({
/**
* Configuration options.
*/
cfg: Base.extend(),
/**
* Initializes a newly created hasher.
*
* @param {Object} cfg (Optional) The configuration options to use for this hash computation.
*
* @example
*
* var hasher = CryptoJS.algo.SHA256.create();
*/
init: function (cfg) {
// Apply config defaults
this.cfg = this.cfg.extend(cfg);
// Set initial values
this.reset();
},
/**
* Resets this hasher to its initial state.
*
* @example
*
* hasher.reset();
*/
reset: function () {
// Reset data buffer
BufferedBlockAlgorithm.reset.call(this);
// Perform concrete-hasher logic
this._doReset();
},
/**
* Updates this hasher with a message.
*
* @param {WordArray|string} messageUpdate The message to append.
*
* @return {Hasher} This hasher.
*
* @example
*
* hasher.update('message');
* hasher.update(wordArray);
*/
update: function (messageUpdate) {
// Append
this._append(messageUpdate);
// Update the hash
this._process();
// Chainable
return this;
},
/**
* Finalizes the hash computation.
* Note that the finalize operation is effectively a destructive, read-once operation.
*
* @param {WordArray|string} messageUpdate (Optional) A final message update.
*
* @return {WordArray} The hash.
*
* @example
*
* var hash = hasher.finalize();
* var hash = hasher.finalize('message');
* var hash = hasher.finalize(wordArray);
*/
finalize: function (messageUpdate) {
// Final message update
if (messageUpdate) {
this._append(messageUpdate);
}
// Perform concrete-hasher logic
var hash = this._doFinalize();
return hash;
},
blockSize: 512/32,
/**
* Creates a shortcut function to a hasher's object interface.
*
* @param {Hasher} hasher The hasher to create a helper for.
*
* @return {Function} The shortcut function.
*
* @static
*
* @example
*
* var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256);
*/
_createHelper: function (hasher) {
return function (message, cfg) {
return new hasher.init(cfg).finalize(message);
};
},
/**
* Creates a shortcut function to the HMAC's object interface.
*
* @param {Hasher} hasher The hasher to use in this HMAC helper.
*
* @return {Function} The shortcut function.
*
* @static
*
* @example
*
* var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256);
*/
_createHmacHelper: function (hasher) {
return function (message, key) {
return new C_algo.HMAC.init(hasher, key).finalize(message);
};
}
});
/**
* Algorithm namespace.
*/
var C_algo = C.algo = {};
return C;
}(Math));
return CryptoJS;
}));
},{}],23:[function(require,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var C_enc = C.enc;
/**
* Base64 encoding strategy.
*/
var Base64 = C_enc.Base64 = {
/**
* Converts a word array to a Base64 string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The Base64 string.
*
* @static
*
* @example
*
* var base64String = CryptoJS.enc.Base64.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
var map = this._map;
// Clamp excess bits
wordArray.clamp();
// Convert
var base64Chars = [];
for (var i = 0; i < sigBytes; i += 3) {
var byte1 = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
var byte2 = (words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xff;
var byte3 = (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xff;
var triplet = (byte1 << 16) | (byte2 << 8) | byte3;
for (var j = 0; (j < 4) && (i + j * 0.75 < sigBytes); j++) {
base64Chars.push(map.charAt((triplet >>> (6 * (3 - j))) & 0x3f));
}
}
// Add padding
var paddingChar = map.charAt(64);
if (paddingChar) {
while (base64Chars.length % 4) {
base64Chars.push(paddingChar);
}
}
return base64Chars.join('');
},
/**
* Converts a Base64 string to a word array.
*
* @param {string} base64Str The Base64 string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Base64.parse(base64String);
*/
parse: function (base64Str) {
// Shortcuts
var base64StrLength = base64Str.length;
var map = this._map;
// Ignore padding
var paddingChar = map.charAt(64);
if (paddingChar) {
var paddingIndex = base64Str.indexOf(paddingChar);
if (paddingIndex != -1) {
base64StrLength = paddingIndex;
}
}
// Convert
var words = [];
var nBytes = 0;
for (var i = 0; i < base64StrLength; i++) {
if (i % 4) {
var bits1 = map.indexOf(base64Str.charAt(i - 1)) << ((i % 4) * 2);
var bits2 = map.indexOf(base64Str.charAt(i)) >>> (6 - (i % 4) * 2);
words[nBytes >>> 2] |= (bits1 | bits2) << (24 - (nBytes % 4) * 8);
nBytes++;
}
}
return WordArray.create(words, nBytes);
},
_map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
};
}());
return CryptoJS.enc.Base64;
}));
},{"./core":22}],24:[function(require,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var C_enc = C.enc;
/**
* UTF-16 BE encoding strategy.
*/
var Utf16BE = C_enc.Utf16 = C_enc.Utf16BE = {
/**
* Converts a word array to a UTF-16 BE string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The UTF-16 BE string.
*
* @static
*
* @example
*
* var utf16String = CryptoJS.enc.Utf16.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
// Convert
var utf16Chars = [];
for (var i = 0; i < sigBytes; i += 2) {
var codePoint = (words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff;
utf16Chars.push(String.fromCharCode(codePoint));
}
return utf16Chars.join('');
},
/**
* Converts a UTF-16 BE string to a word array.
*
* @param {string} utf16Str The UTF-16 BE string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Utf16.parse(utf16String);
*/
parse: function (utf16Str) {
// Shortcut
var utf16StrLength = utf16Str.length;
// Convert
var words = [];
for (var i = 0; i < utf16StrLength; i++) {
words[i >>> 1] |= utf16Str.charCodeAt(i) << (16 - (i % 2) * 16);
}
return WordArray.create(words, utf16StrLength * 2);
}
};
/**
* UTF-16 LE encoding strategy.
*/
C_enc.Utf16LE = {
/**
* Converts a word array to a UTF-16 LE string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The UTF-16 LE string.
*
* @static
*
* @example
*
* var utf16Str = CryptoJS.enc.Utf16LE.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
// Convert
var utf16Chars = [];
for (var i = 0; i < sigBytes; i += 2) {
var codePoint = swapEndian((words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff);
utf16Chars.push(String.fromCharCode(codePoint));
}
return utf16Chars.join('');
},
/**
* Converts a UTF-16 LE string to a word array.
*
* @param {string} utf16Str The UTF-16 LE string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Utf16LE.parse(utf16Str);
*/
parse: function (utf16Str) {
// Shortcut
var utf16StrLength = utf16Str.length;
// Convert
var words = [];
for (var i = 0; i < utf16StrLength; i++) {
words[i >>> 1] |= swapEndian(utf16Str.charCodeAt(i) << (16 - (i % 2) * 16));
}
return WordArray.create(words, utf16StrLength * 2);
}
};
function swapEndian(word) {
return ((word << 8) & 0xff00ff00) | ((word >>> 8) & 0x00ff00ff);
}
}());
return CryptoJS.enc.Utf16;
}));
},{"./core":22}],25:[function(require,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"), require("./sha1"), require("./hmac"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./sha1", "./hmac"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var WordArray = C_lib.WordArray;
var C_algo = C.algo;
var MD5 = C_algo.MD5;
/**
* This key derivation function is meant to conform with EVP_BytesToKey.
* www.openssl.org/docs/crypto/EVP_BytesToKey.html
*/
var EvpKDF = C_algo.EvpKDF = Base.extend({
/**
* Configuration options.
*
* @property {number} keySize The key size in words to generate. Default: 4 (128 bits)
* @property {Hasher} hasher The hash algorithm to use. Default: MD5
* @property {number} iterations The number of iterations to perform. Default: 1
*/
cfg: Base.extend({
keySize: 128/32,
hasher: MD5,
iterations: 1
}),
/**
* Initializes a newly created key derivation function.
*
* @param {Object} cfg (Optional) The configuration options to use for the derivation.
*
* @example
*
* var kdf = CryptoJS.algo.EvpKDF.create();
* var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8 });
* var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8, iterations: 1000 });
*/
init: function (cfg) {
this.cfg = this.cfg.extend(cfg);
},
/**
* Derives a key from a password.
*
* @param {WordArray|string} password The password.
* @param {WordArray|string} salt A salt.
*
* @return {WordArray} The derived key.
*
* @example
*
* var key = kdf.compute(password, salt);
*/
compute: function (password, salt) {
// Shortcut
var cfg = this.cfg;
// Init hasher
var hasher = cfg.hasher.create();
// Initial values
var derivedKey = WordArray.create();
// Shortcuts
var derivedKeyWords = derivedKey.words;
var keySize = cfg.keySize;
var iterations = cfg.iterations;
// Generate key
while (derivedKeyWords.length < keySize) {
if (block) {
hasher.update(block);
}
var block = hasher.update(password).finalize(salt);
hasher.reset();
// Iterations
for (var i = 1; i < iterations; i++) {
block = hasher.finalize(block);
hasher.reset();
}
derivedKey.concat(block);
}
derivedKey.sigBytes = keySize * 4;
return derivedKey;
}
});
/**
* Derives a key from a password.
*
* @param {WordArray|string} password The password.
* @param {WordArray|string} salt A salt.
* @param {Object} cfg (Optional) The configuration options to use for this computation.
*
* @return {WordArray} The derived key.
*
* @static
*
* @example
*
* var key = CryptoJS.EvpKDF(password, salt);
* var key = CryptoJS.EvpKDF(password, salt, { keySize: 8 });
* var key = CryptoJS.EvpKDF(password, salt, { keySize: 8, iterations: 1000 });
*/
C.EvpKDF = function (password, salt, cfg) {
return EvpKDF.create(cfg).compute(password, salt);
};
}());
return CryptoJS.EvpKDF;
}));
},{"./core":22,"./hmac":27,"./sha1":46}],26:[function(require,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"), require("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function (undefined) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var CipherParams = C_lib.CipherParams;
var C_enc = C.enc;
var Hex = C_enc.Hex;
var C_format = C.format;
var HexFormatter = C_format.Hex = {
/**
* Converts the ciphertext of a cipher params object to a hexadecimally encoded string.
*
* @param {CipherParams} cipherParams The cipher params object.
*
* @return {string} The hexadecimally encoded string.
*
* @static
*
* @example
*
* var hexString = CryptoJS.format.Hex.stringify(cipherParams);
*/
stringify: function (cipherParams) {
return cipherParams.ciphertext.toString(Hex);
},
/**
* Converts a hexadecimally encoded ciphertext string to a cipher params object.
*
* @param {string} input The hexadecimally encoded string.
*
* @return {CipherParams} The cipher params object.
*
* @static
*
* @example
*
* var cipherParams = CryptoJS.format.Hex.parse(hexString);
*/
parse: function (input) {
var ciphertext = Hex.parse(input);
return CipherParams.create({ ciphertext: ciphertext });
}
};
}());
return CryptoJS.format.Hex;
}));
},{"./cipher-core":21,"./core":22}],27:[function(require,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var C_enc = C.enc;
var Utf8 = C_enc.Utf8;
var C_algo = C.algo;
/**
* HMAC algorithm.
*/
var HMAC = C_algo.HMAC = Base.extend({
/**
* Initializes a newly created HMAC.
*
* @param {Hasher} hasher The hash algorithm to use.
* @param {WordArray|string} key The secret key.
*
* @example
*
* var hmacHasher = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, key);
*/
init: function (hasher, key) {
// Init hasher
hasher = this._hasher = new hasher.init();
// Convert string to WordArray, else assume WordArray already
if (typeof key == 'string') {
key = Utf8.parse(key);
}
// Shortcuts
var hasherBlockSize = hasher.blockSize;
var hasherBlockSizeBytes = hasherBlockSize * 4;
// Allow arbitrary length keys
if (key.sigBytes > hasherBlockSizeBytes) {
key = hasher.finalize(key);
}
// Clamp excess bits
key.clamp();
// Clone key for inner and outer pads
var oKey = this._oKey = key.clone();
var iKey = this._iKey = key.clone();
// Shortcuts
var oKeyWords = oKey.words;
var iKeyWords = iKey.words;
// XOR keys with pad constants
for (var i = 0; i < hasherBlockSize; i++) {
oKeyWords[i] ^= 0x5c5c5c5c;
iKeyWords[i] ^= 0x36363636;
}
oKey.sigBytes = iKey.sigBytes = hasherBlockSizeBytes;
// Set initial values
this.reset();
},
/**
* Resets this HMAC to its initial state.
*
* @example
*
* hmacHasher.reset();
*/
reset: function () {
// Shortcut
var hasher = this._hasher;
// Reset
hasher.reset();
hasher.update(this._iKey);
},
/**
* Updates this HMAC with a message.
*
* @param {WordArray|string} messageUpdate The message to append.
*
* @return {HMAC} This HMAC instance.
*
* @example
*
* hmacHasher.update('message');
* hmacHasher.update(wordArray);
*/
update: function (messageUpdate) {
this._hasher.update(messageUpdate);
// Chainable
return this;
},
/**
* Finalizes the HMAC computation.
* Note that the finalize operation is effectively a destructive, read-once operation.
*
* @param {WordArray|string} messageUpdate (Optional) A final message update.
*
* @return {WordArray} The HMAC.
*
* @example
*
* var hmac = hmacHasher.finalize();
* var hmac = hmacHasher.finalize('message');
* var hmac = hmacHasher.finalize(wordArray);
*/
finalize: function (messageUpdate) {
// Shortcut
var hasher = this._hasher;
// Compute HMAC
var innerHash = hasher.finalize(messageUpdate);
hasher.reset();
var hmac = hasher.finalize(this._oKey.clone().concat(innerHash));
return hmac;
}
});
}());
}));
},{"./core":22}],28:[function(require,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"), require("./x64-core"), require("./lib-typedarrays"), require("./enc-utf16"), require("./enc-base64"), require("./md5"), require("./sha1"), require("./sha256"), require("./sha224"), require("./sha512"), require("./sha384"), require("./sha3"), require("./ripemd160"), require("./hmac"), require("./pbkdf2"), require("./evpkdf"), require("./cipher-core"), require("./mode-cfb"), require("./mode-ctr"), require("./mode-ctr-gladman"), require("./mode-ofb"), require("./mode-ecb"), require("./pad-ansix923"), require("./pad-iso10126"), require("./pad-iso97971"), require("./pad-zeropadding"), require("./pad-nopadding"), require("./format-hex"), require("./aes"), require("./tripledes"), require("./rc4"), require("./rabbit"), require("./rabbit-legacy"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./x64-core", "./lib-typedarrays", "./enc-utf16", "./enc-base64", "./md5", "./sha1", "./sha256", "./sha224", "./sha512", "./sha384", "./sha3", "./ripemd160", "./hmac", "./pbkdf2", "./evpkdf", "./cipher-core", "./mode-cfb", "./mode-ctr", "./mode-ctr-gladman", "./mode-ofb", "./mode-ecb", "./pad-ansix923", "./pad-iso10126", "./pad-iso97971", "./pad-zeropadding", "./pad-nopadding", "./format-hex", "./aes", "./tripledes", "./rc4", "./rabbit", "./rabbit-legacy"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
return CryptoJS;
}));
},{"./aes":20,"./cipher-core":21,"./core":22,"./enc-base64":23,"./enc-utf16":24,"./evpkdf":25,"./format-hex":26,"./hmac":27,"./lib-typedarrays":29,"./md5":30,"./mode-cfb":31,"./mode-ctr":33,"./mode-ctr-gladman":32,"./mode-ecb":34,"./mode-ofb":35,"./pad-ansix923":36,"./pad-iso10126":37,"./pad-iso97971":38,"./pad-nopadding":39,"./pad-zeropadding":40,"./pbkdf2":41,"./rabbit":43,"./rabbit-legacy":42,"./rc4":44,"./ripemd160":45,"./sha1":46,"./sha224":47,"./sha256":48,"./sha3":49,"./sha384":50,"./sha512":51,"./tripledes":52,"./x64-core":53}],29:[function(require,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Check if typed arrays are supported
if (typeof ArrayBuffer != 'function') {
return;
}
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
// Reference original init
var superInit = WordArray.init;
// Augment WordArray.init to handle typed arrays
var subInit = WordArray.init = function (typedArray) {
// Convert buffers to uint8
if (typedArray instanceof ArrayBuffer) {
typedArray = new Uint8Array(typedArray);
}
// Convert other array views to uint8
if (
typedArray instanceof Int8Array ||
typedArray instanceof Uint8ClampedArray ||
typedArray instanceof Int16Array ||
typedArray instanceof Uint16Array ||
typedArray instanceof Int32Array ||
typedArray instanceof Uint32Array ||
typedArray instanceof Float32Array ||
typedArray instanceof Float64Array
) {
typedArray = new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength);
}
// Handle Uint8Array
if (typedArray instanceof Uint8Array) {
// Shortcut
var typedArrayByteLength = typedArray.byteLength;
// Extract bytes
var words = [];
for (var i = 0; i < typedArrayByteLength; i++) {
words[i >>> 2] |= typedArray[i] << (24 - (i % 4) * 8);
}
// Initialize this word array
superInit.call(this, words, typedArrayByteLength);
} else {
// Else call normal init
superInit.apply(this, arguments);
}
};
subInit.prototype = WordArray;
}());
return CryptoJS.lib.WordArray;
}));
},{"./core":22}],30:[function(require,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function (Math) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_algo = C.algo;
// Constants table
var T = [];
// Compute constants
(function () {
for (var i = 0; i < 64; i++) {
T[i] = (Math.abs(Math.sin(i + 1)) * 0x100000000) | 0;
}
}());
/**
* MD5 hash algorithm.
*/
var MD5 = C_algo.MD5 = Hasher.extend({
_doReset: function () {
this._hash = new WordArray.init([
0x67452301, 0xefcdab89,
0x98badcfe, 0x10325476
]);
},
_doProcessBlock: function (M, offset) {
// Swap endian
for (var i = 0; i < 16; i++) {
// Shortcuts
var offset_i = offset + i;
var M_offset_i = M[offset_i];
M[offset_i] = (
(((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) |
(((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00)
);
}
// Shortcuts
var H = this._hash.words;
var M_offset_0 = M[offset + 0];
var M_offset_1 = M[offset + 1];
var M_offset_2 = M[offset + 2];
var M_offset_3 = M[offset + 3];
var M_offset_4 = M[offset + 4];
var M_offset_5 = M[offset + 5];
var M_offset_6 = M[offset + 6];
var M_offset_7 = M[offset + 7];
var M_offset_8 = M[offset + 8];
var M_offset_9 = M[offset + 9];
var M_offset_10 = M[offset + 10];
var M_offset_11 = M[offset + 11];
var M_offset_12 = M[offset + 12];
var M_offset_13 = M[offset + 13];
var M_offset_14 = M[offset + 14];
var M_offset_15 = M[offset + 15];
// Working varialbes
var a = H[0];
var b = H[1];
var c = H[2];
var d = H[3];
// Computation
a = FF(a, b, c, d, M_offset_0, 7, T[0]);
d = FF(d, a, b, c, M_offset_1, 12, T[1]);
c = FF(c, d, a, b, M_offset_2, 17, T[2]);
b = FF(b, c, d, a, M_offset_3, 22, T[3]);
a = FF(a, b, c, d, M_offset_4, 7, T[4]);
d = FF(d, a, b, c, M_offset_5, 12, T[5]);
c = FF(c, d, a, b, M_offset_6, 17, T[6]);
b = FF(b, c, d, a, M_offset_7, 22, T[7]);
a = FF(a, b, c, d, M_offset_8, 7, T[8]);
d = FF(d, a, b, c, M_offset_9, 12, T[9]);
c = FF(c, d, a, b, M_offset_10, 17, T[10]);
b = FF(b, c, d, a, M_offset_11, 22, T[11]);
a = FF(a, b, c, d, M_offset_12, 7, T[12]);
d = FF(d, a, b, c, M_offset_13, 12, T[13]);
c = FF(c, d, a, b, M_offset_14, 17, T[14]);
b = FF(b, c, d, a, M_offset_15, 22, T[15]);
a = GG(a, b, c, d, M_offset_1, 5, T[16]);
d = GG(d, a, b, c, M_offset_6, 9, T[17]);
c = GG(c, d, a, b, M_offset_11, 14, T[18]);
b = GG(b, c, d, a, M_offset_0, 20, T[19]);
a = GG(a, b, c, d, M_offset_5, 5, T[20]);
d = GG(d, a, b, c, M_offset_10, 9, T[21]);
c = GG(c, d, a, b, M_offset_15, 14, T[22]);
b = GG(b, c, d, a, M_offset_4, 20, T[23]);
a = GG(a, b, c, d, M_offset_9, 5, T[24]);
d = GG(d, a, b, c, M_offset_14, 9, T[25]);
c = GG(c, d, a, b, M_offset_3, 14, T[26]);
b = GG(b, c, d, a, M_offset_8, 20, T[27]);
a = GG(a, b, c, d, M_offset_13, 5, T[28]);
d = GG(d, a, b, c, M_offset_2, 9, T[29]);
c = GG(c, d, a, b, M_offset_7, 14, T[30]);
b = GG(b, c, d, a, M_offset_12, 20, T[31]);
a = HH(a, b, c, d, M_offset_5, 4, T[32]);
d = HH(d, a, b, c, M_offset_8, 11, T[33]);
c = HH(c, d, a, b, M_offset_11, 16, T[34]);
b = HH(b, c, d, a, M_offset_14, 23, T[35]);
a = HH(a, b, c, d, M_offset_1, 4, T[36]);
d = HH(d, a, b, c, M_offset_4, 11, T[37]);
c = HH(c, d, a, b, M_offset_7, 16, T[38]);
b = HH(b, c, d, a, M_offset_10, 23, T[39]);
a = HH(a, b, c, d, M_offset_13, 4, T[40]);
d = HH(d, a, b, c, M_offset_0, 11, T[41]);
c = HH(c, d, a, b, M_offset_3, 16, T[42]);
b = HH(b, c, d, a, M_offset_6, 23, T[43]);
a = HH(a, b, c, d, M_offset_9, 4, T[44]);
d = HH(d, a, b, c, M_offset_12, 11, T[45]);
c = HH(c, d, a, b, M_offset_15, 16, T[46]);
b = HH(b, c, d, a, M_offset_2, 23, T[47]);
a = II(a, b, c, d, M_offset_0, 6, T[48]);
d = II(d, a, b, c, M_offset_7, 10, T[49]);
c = II(c, d, a, b, M_offset_14, 15, T[50]);
b = II(b, c, d, a, M_offset_5, 21, T[51]);
a = II(a, b, c, d, M_offset_12, 6, T[52]);
d = II(d, a, b, c, M_offset_3, 10, T[53]);
c = II(c, d, a, b, M_offset_10, 15, T[54]);
b = II(b, c, d, a, M_offset_1, 21, T[55]);
a = II(a, b, c, d, M_offset_8, 6, T[56]);
d = II(d, a, b, c, M_offset_15, 10, T[57]);
c = II(c, d, a, b, M_offset_6, 15, T[58]);
b = II(b, c, d, a, M_offset_13, 21, T[59]);
a = II(a, b, c, d, M_offset_4, 6, T[60]);
d = II(d, a, b, c, M_offset_11, 10, T[61]);
c = II(c, d, a, b, M_offset_2, 15, T[62]);
b = II(b, c, d, a, M_offset_9, 21, T[63]);
// Intermediate hash value
H[0] = (H[0] + a) | 0;
H[1] = (H[1] + b) | 0;
H[2] = (H[2] + c) | 0;
H[3] = (H[3] + d) | 0;
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
var nBitsTotalH = Math.floor(nBitsTotal / 0x100000000);
var nBitsTotalL = nBitsTotal;
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = (
(((nBitsTotalH << 8) | (nBitsTotalH >>> 24)) & 0x00ff00ff) |
(((nBitsTotalH << 24) | (nBitsTotalH >>> 8)) & 0xff00ff00)
);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = (
(((nBitsTotalL << 8) | (nBitsTotalL >>> 24)) & 0x00ff00ff) |
(((nBitsTotalL << 24) | (nBitsTotalL >>> 8)) & 0xff00ff00)
);
data.sigBytes = (dataWords.length + 1) * 4;
// Hash final blocks
this._process();
// Shortcuts
var hash = this._hash;
var H = hash.words;
// Swap endian
for (var i = 0; i < 4; i++) {
// Shortcut
var H_i = H[i];
H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) |
(((H_i << 24) | (H_i >>> 8)) & 0xff00ff00);
}
// Return final computed hash
return hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
}
});
function FF(a, b, c, d, x, s, t) {
var n = a + ((b & c) | (~b & d)) + x + t;
return ((n << s) | (n >>> (32 - s))) + b;
}
function GG(a, b, c, d, x, s, t) {
var n = a + ((b & d) | (c & ~d)) + x + t;
return ((n << s) | (n >>> (32 - s))) + b;
}
function HH(a, b, c, d, x, s, t) {
var n = a + (b ^ c ^ d) + x + t;
return ((n << s) | (n >>> (32 - s))) + b;
}
function II(a, b, c, d, x, s, t) {
var n = a + (c ^ (b | ~d)) + x + t;
return ((n << s) | (n >>> (32 - s))) + b;
}
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.MD5('message');
* var hash = CryptoJS.MD5(wordArray);
*/
C.MD5 = Hasher._createHelper(MD5);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacMD5(message, key);
*/
C.HmacMD5 = Hasher._createHmacHelper(MD5);
}(Math));
return CryptoJS.MD5;
}));
},{"./core":22}],31:[function(require,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"), require("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Cipher Feedback block mode.
*/
CryptoJS.mode.CFB = (function () {
var CFB = CryptoJS.lib.BlockCipherMode.extend();
CFB.Encryptor = CFB.extend({
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher;
var blockSize = cipher.blockSize;
generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher);
// Remember this block to use with next block
this._prevBlock = words.slice(offset, offset + blockSize);
}
});
CFB.Decryptor = CFB.extend({
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher;
var blockSize = cipher.blockSize;
// Remember this block to use with next block
var thisBlock = words.slice(offset, offset + blockSize);
generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher);
// This block becomes the previous block
this._prevBlock = thisBlock;
}
});
function generateKeystreamAndEncrypt(words, offset, blockSize, cipher) {
// Shortcut
var iv = this._iv;
// Generate keystream
if (iv) {
var keystream = iv.slice(0);
// Remove IV for subsequent blocks
this._iv = undefined;
} else {
var keystream = this._prevBlock;
}
cipher.encryptBlock(keystream, 0);
// Encrypt
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= keystream[i];
}
}
return CFB;
}());
return CryptoJS.mode.CFB;
}));
},{"./cipher-core":21,"./core":22}],32:[function(require,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"), require("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/** @preserve
* Counter block mode compatible with Dr Brian Gladman fileenc.c
* derived from CryptoJS.mode.CTR
* Jan Hruby jhruby.web@gmail.com
*/
CryptoJS.mode.CTRGladman = (function () {
var CTRGladman = CryptoJS.lib.BlockCipherMode.extend();
function incWord(word)
{
if (((word >> 24) & 0xff) === 0xff) { //overflow
var b1 = (word >> 16)&0xff;
var b2 = (word >> 8)&0xff;
var b3 = word & 0xff;
if (b1 === 0xff) // overflow b1
{
b1 = 0;
if (b2 === 0xff)
{
b2 = 0;
if (b3 === 0xff)
{
b3 = 0;
}
else
{
++b3;
}
}
else
{
++b2;
}
}
else
{
++b1;
}
word = 0;
word += (b1 << 16);
word += (b2 << 8);
word += b3;
}
else
{
word += (0x01 << 24);
}
return word;
}
function incCounter(counter)
{
if ((counter[0] = incWord(counter[0])) === 0)
{
// encr_data in fileenc.c from Dr Brian Gladman's counts only with DWORD j < 8
counter[1] = incWord(counter[1]);
}
return counter;
}
var Encryptor = CTRGladman.Encryptor = CTRGladman.extend({
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher
var blockSize = cipher.blockSize;
var iv = this._iv;
var counter = this._counter;
// Generate keystream
if (iv) {
counter = this._counter = iv.slice(0);
// Remove IV for subsequent blocks
this._iv = undefined;
}
incCounter(counter);
var keystream = counter.slice(0);
cipher.encryptBlock(keystream, 0);
// Encrypt
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= keystream[i];
}
}
});
CTRGladman.Decryptor = Encryptor;
return CTRGladman;
}());
return CryptoJS.mode.CTRGladman;
}));
},{"./cipher-core":21,"./core":22}],33:[function(require,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"), require("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Counter block mode.
*/
CryptoJS.mode.CTR = (function () {
var CTR = CryptoJS.lib.BlockCipherMode.extend();
var Encryptor = CTR.Encryptor = CTR.extend({
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher
var blockSize = cipher.blockSize;
var iv = this._iv;
var counter = this._counter;
// Generate keystream
if (iv) {
counter = this._counter = iv.slice(0);
// Remove IV for subsequent blocks
this._iv = undefined;
}
var keystream = counter.slice(0);
cipher.encryptBlock(keystream, 0);
// Increment counter
counter[blockSize - 1] = (counter[blockSize - 1] + 1) | 0
// Encrypt
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= keystream[i];
}
}
});
CTR.Decryptor = Encryptor;
return CTR;
}());
return CryptoJS.mode.CTR;
}));
},{"./cipher-core":21,"./core":22}],34:[function(require,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"), require("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Electronic Codebook block mode.
*/
CryptoJS.mode.ECB = (function () {
var ECB = CryptoJS.lib.BlockCipherMode.extend();
ECB.Encryptor = ECB.extend({
processBlock: function (words, offset) {
this._cipher.encryptBlock(words, offset);
}
});
ECB.Decryptor = ECB.extend({
processBlock: function (words, offset) {
this._cipher.decryptBlock(words, offset);
}
});
return ECB;
}());
return CryptoJS.mode.ECB;
}));
},{"./cipher-core":21,"./core":22}],35:[function(require,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"), require("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Output Feedback block mode.
*/
CryptoJS.mode.OFB = (function () {
var OFB = CryptoJS.lib.BlockCipherMode.extend();
var Encryptor = OFB.Encryptor = OFB.extend({
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher
var blockSize = cipher.blockSize;
var iv = this._iv;
var keystream = this._keystream;
// Generate keystream
if (iv) {
keystream = this._keystream = iv.slice(0);
// Remove IV for subsequent blocks
this._iv = undefined;
}
cipher.encryptBlock(keystream, 0);
// Encrypt
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= keystream[i];
}
}
});
OFB.Decryptor = Encryptor;
return OFB;
}());
return CryptoJS.mode.OFB;
}));
},{"./cipher-core":21,"./core":22}],36:[function(require,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"), require("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* ANSI X.923 padding strategy.
*/
CryptoJS.pad.AnsiX923 = {
pad: function (data, blockSize) {
// Shortcuts
var dataSigBytes = data.sigBytes;
var blockSizeBytes = blockSize * 4;
// Count padding bytes
var nPaddingBytes = blockSizeBytes - dataSigBytes % blockSizeBytes;
// Compute last byte position
var lastBytePos = dataSigBytes + nPaddingBytes - 1;
// Pad
data.clamp();
data.words[lastBytePos >>> 2] |= nPaddingBytes << (24 - (lastBytePos % 4) * 8);
data.sigBytes += nPaddingBytes;
},
unpad: function (data) {
// Get number of padding bytes from last byte
var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff;
// Remove padding
data.sigBytes -= nPaddingBytes;
}
};
return CryptoJS.pad.Ansix923;
}));
},{"./cipher-core":21,"./core":22}],37:[function(require,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"), require("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* ISO 10126 padding strategy.
*/
CryptoJS.pad.Iso10126 = {
pad: function (data, blockSize) {
// Shortcut
var blockSizeBytes = blockSize * 4;
// Count padding bytes
var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes;
// Pad
data.concat(CryptoJS.lib.WordArray.random(nPaddingBytes - 1)).
concat(CryptoJS.lib.WordArray.create([nPaddingBytes << 24], 1));
},
unpad: function (data) {
// Get number of padding bytes from last byte
var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff;
// Remove padding
data.sigBytes -= nPaddingBytes;
}
};
return CryptoJS.pad.Iso10126;
}));
},{"./cipher-core":21,"./core":22}],38:[function(require,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"), require("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* ISO/IEC 9797-1 Padding Method 2.
*/
CryptoJS.pad.Iso97971 = {
pad: function (data, blockSize) {
// Add 0x80 byte
data.concat(CryptoJS.lib.WordArray.create([0x80000000], 1));
// Zero pad the rest
CryptoJS.pad.ZeroPadding.pad(data, blockSize);
},
unpad: function (data) {
// Remove zero padding
CryptoJS.pad.ZeroPadding.unpad(data);
// Remove one more byte -- the 0x80 byte
data.sigBytes--;
}
};
return CryptoJS.pad.Iso97971;
}));
},{"./cipher-core":21,"./core":22}],39:[function(require,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"), require("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* A noop padding strategy.
*/
CryptoJS.pad.NoPadding = {
pad: function () {
},
unpad: function () {
}
};
return CryptoJS.pad.NoPadding;
}));
},{"./cipher-core":21,"./core":22}],40:[function(require,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"), require("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Zero padding strategy.
*/
CryptoJS.pad.ZeroPadding = {
pad: function (data, blockSize) {
// Shortcut
var blockSizeBytes = blockSize * 4;
// Pad
data.clamp();
data.sigBytes += blockSizeBytes - ((data.sigBytes % blockSizeBytes) || blockSizeBytes);
},
unpad: function (data) {
// Shortcut
var dataWords = data.words;
// Unpad
var i = data.sigBytes - 1;
while (!((dataWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff)) {
i--;
}
data.sigBytes = i + 1;
}
};
return CryptoJS.pad.ZeroPadding;
}));
},{"./cipher-core":21,"./core":22}],41:[function(require,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"), require("./sha1"), require("./hmac"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./sha1", "./hmac"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var WordArray = C_lib.WordArray;
var C_algo = C.algo;
var SHA1 = C_algo.SHA1;
var HMAC = C_algo.HMAC;
/**
* Password-Based Key Derivation Function 2 algorithm.
*/
var PBKDF2 = C_algo.PBKDF2 = Base.extend({
/**
* Configuration options.
*
* @property {number} keySize The key size in words to generate. Default: 4 (128 bits)
* @property {Hasher} hasher The hasher to use. Default: SHA1
* @property {number} iterations The number of iterations to perform. Default: 1
*/
cfg: Base.extend({
keySize: 128/32,
hasher: SHA1,
iterations: 1
}),
/**
* Initializes a newly created key derivation function.
*
* @param {Object} cfg (Optional) The configuration options to use for the derivation.
*
* @example
*
* var kdf = CryptoJS.algo.PBKDF2.create();
* var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8 });
* var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8, iterations: 1000 });
*/
init: function (cfg) {
this.cfg = this.cfg.extend(cfg);
},
/**
* Computes the Password-Based Key Derivation Function 2.
*
* @param {WordArray|string} password The password.
* @param {WordArray|string} salt A salt.
*
* @return {WordArray} The derived key.
*
* @example
*
* var key = kdf.compute(password, salt);
*/
compute: function (password, salt) {
// Shortcut
var cfg = this.cfg;
// Init HMAC
var hmac = HMAC.create(cfg.hasher, password);
// Initial values
var derivedKey = WordArray.create();
var blockIndex = WordArray.create([0x00000001]);
// Shortcuts
var derivedKeyWords = derivedKey.words;
var blockIndexWords = blockIndex.words;
var keySize = cfg.keySize;
var iterations = cfg.iterations;
// Generate key
while (derivedKeyWords.length < keySize) {
var block = hmac.update(salt).finalize(blockIndex);
hmac.reset();
// Shortcuts
var blockWords = block.words;
var blockWordsLength = blockWords.length;
// Iterations
var intermediate = block;
for (var i = 1; i < iterations; i++) {
intermediate = hmac.finalize(intermediate);
hmac.reset();
// Shortcut
var intermediateWords = intermediate.words;
// XOR intermediate with block
for (var j = 0; j < blockWordsLength; j++) {
blockWords[j] ^= intermediateWords[j];
}
}
derivedKey.concat(block);
blockIndexWords[0]++;
}
derivedKey.sigBytes = keySize * 4;
return derivedKey;
}
});
/**
* Computes the Password-Based Key Derivation Function 2.
*
* @param {WordArray|string} password The password.
* @param {WordArray|string} salt A salt.
* @param {Object} cfg (Optional) The configuration options to use for this computation.
*
* @return {WordArray} The derived key.
*
* @static
*
* @example
*
* var key = CryptoJS.PBKDF2(password, salt);
* var key = CryptoJS.PBKDF2(password, salt, { keySize: 8 });
* var key = CryptoJS.PBKDF2(password, salt, { keySize: 8, iterations: 1000 });
*/
C.PBKDF2 = function (password, salt, cfg) {
return PBKDF2.create(cfg).compute(password, salt);
};
}());
return CryptoJS.PBKDF2;
}));
},{"./core":22,"./hmac":27,"./sha1":46}],42:[function(require,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"), require("./enc-base64"), require("./md5"), require("./evpkdf"), require("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var StreamCipher = C_lib.StreamCipher;
var C_algo = C.algo;
// Reusable objects
var S = [];
var C_ = [];
var G = [];
/**
* Rabbit stream cipher algorithm.
*
* This is a legacy version that neglected to convert the key to little-endian.
* This error doesn't affect the cipher's security,
* but it does affect its compatibility with other implementations.
*/
var RabbitLegacy = C_algo.RabbitLegacy = StreamCipher.extend({
_doReset: function () {
// Shortcuts
var K = this._key.words;
var iv = this.cfg.iv;
// Generate initial state values
var X = this._X = [
K[0], (K[3] << 16) | (K[2] >>> 16),
K[1], (K[0] << 16) | (K[3] >>> 16),
K[2], (K[1] << 16) | (K[0] >>> 16),
K[3], (K[2] << 16) | (K[1] >>> 16)
];
// Generate initial counter values
var C = this._C = [
(K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff),
(K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff),
(K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff),
(K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff)
];
// Carry bit
this._b = 0;
// Iterate the system four times
for (var i = 0; i < 4; i++) {
nextState.call(this);
}
// Modify the counters
for (var i = 0; i < 8; i++) {
C[i] ^= X[(i + 4) & 7];
}
// IV setup
if (iv) {
// Shortcuts
var IV = iv.words;
var IV_0 = IV[0];
var IV_1 = IV[1];
// Generate four subvectors
var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00);
var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00);
var i1 = (i0 >>> 16) | (i2 & 0xffff0000);
var i3 = (i2 << 16) | (i0 & 0x0000ffff);
// Modify counter values
C[0] ^= i0;
C[1] ^= i1;
C[2] ^= i2;
C[3] ^= i3;
C[4] ^= i0;
C[5] ^= i1;
C[6] ^= i2;
C[7] ^= i3;
// Iterate the system four times
for (var i = 0; i < 4; i++) {
nextState.call(this);
}
}
},
_doProcessBlock: function (M, offset) {
// Shortcut
var X = this._X;
// Iterate the system
nextState.call(this);
// Generate four keystream words
S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16);
S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16);
S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16);
S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16);
for (var i = 0; i < 4; i++) {
// Swap endian
S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) |
(((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00);
// Encrypt
M[offset + i] ^= S[i];
}
},
blockSize: 128/32,
ivSize: 64/32
});
function nextState() {
// Shortcuts
var X = this._X;
var C = this._C;
// Save old counter values
for (var i = 0; i < 8; i++) {
C_[i] = C[i];
}
// Calculate new counter values
C[0] = (C[0] + 0x4d34d34d + this._b) | 0;
C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0;
C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0;
C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0;
C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0;
C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0;
C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0;
C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0;
this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0;
// Calculate the g-values
for (var i = 0; i < 8; i++) {
var gx = X[i] + C[i];
// Construct high and low argument for squaring
var ga = gx & 0xffff;
var gb = gx >>> 16;
// Calculate high and low result of squaring
var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb;
var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0);
// High XOR low
G[i] = gh ^ gl;
}
// Calculate new state values
X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0;
X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0;
X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0;
X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0;
X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0;
X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0;
X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0;
X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0;
}
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.RabbitLegacy.encrypt(message, key, cfg);
* var plaintext = CryptoJS.RabbitLegacy.decrypt(ciphertext, key, cfg);
*/
C.RabbitLegacy = StreamCipher._createHelper(RabbitLegacy);
}());
return CryptoJS.RabbitLegacy;
}));
},{"./cipher-core":21,"./core":22,"./enc-base64":23,"./evpkdf":25,"./md5":30}],43:[function(require,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"), require("./enc-base64"), require("./md5"), require("./evpkdf"), require("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var StreamCipher = C_lib.StreamCipher;
var C_algo = C.algo;
// Reusable objects
var S = [];
var C_ = [];
var G = [];
/**
* Rabbit stream cipher algorithm
*/
var Rabbit = C_algo.Rabbit = StreamCipher.extend({
_doReset: function () {
// Shortcuts
var K = this._key.words;
var iv = this.cfg.iv;
// Swap endian
for (var i = 0; i < 4; i++) {
K[i] = (((K[i] << 8) | (K[i] >>> 24)) & 0x00ff00ff) |
(((K[i] << 24) | (K[i] >>> 8)) & 0xff00ff00);
}
// Generate initial state values
var X = this._X = [
K[0], (K[3] << 16) | (K[2] >>> 16),
K[1], (K[0] << 16) | (K[3] >>> 16),
K[2], (K[1] << 16) | (K[0] >>> 16),
K[3], (K[2] << 16) | (K[1] >>> 16)
];
// Generate initial counter values
var C = this._C = [
(K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff),
(K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff),
(K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff),
(K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff)
];
// Carry bit
this._b = 0;
// Iterate the system four times
for (var i = 0; i < 4; i++) {
nextState.call(this);
}
// Modify the counters
for (var i = 0; i < 8; i++) {
C[i] ^= X[(i + 4) & 7];
}
// IV setup
if (iv) {
// Shortcuts
var IV = iv.words;
var IV_0 = IV[0];
var IV_1 = IV[1];
// Generate four subvectors
var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00);
var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00);
var i1 = (i0 >>> 16) | (i2 & 0xffff0000);
var i3 = (i2 << 16) | (i0 & 0x0000ffff);
// Modify counter values
C[0] ^= i0;
C[1] ^= i1;
C[2] ^= i2;
C[3] ^= i3;
C[4] ^= i0;
C[5] ^= i1;
C[6] ^= i2;
C[7] ^= i3;
// Iterate the system four times
for (var i = 0; i < 4; i++) {
nextState.call(this);
}
}
},
_doProcessBlock: function (M, offset) {
// Shortcut
var X = this._X;
// Iterate the system
nextState.call(this);
// Generate four keystream words
S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16);
S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16);
S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16);
S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16);
for (var i = 0; i < 4; i++) {
// Swap endian
S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) |
(((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00);
// Encrypt
M[offset + i] ^= S[i];
}
},
blockSize: 128/32,
ivSize: 64/32
});
function nextState() {
// Shortcuts
var X = this._X;
var C = this._C;
// Save old counter values
for (var i = 0; i < 8; i++) {
C_[i] = C[i];
}
// Calculate new counter values
C[0] = (C[0] + 0x4d34d34d + this._b) | 0;
C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0;
C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0;
C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0;
C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0;
C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0;
C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0;
C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0;
this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0;
// Calculate the g-values
for (var i = 0; i < 8; i++) {
var gx = X[i] + C[i];
// Construct high and low argument for squaring
var ga = gx & 0xffff;
var gb = gx >>> 16;
// Calculate high and low result of squaring
var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb;
var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0);
// High XOR low
G[i] = gh ^ gl;
}
// Calculate new state values
X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0;
X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0;
X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0;
X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0;
X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0;
X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0;
X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0;
X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0;
}
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.Rabbit.encrypt(message, key, cfg);
* var plaintext = CryptoJS.Rabbit.decrypt(ciphertext, key, cfg);
*/
C.Rabbit = StreamCipher._createHelper(Rabbit);
}());
return CryptoJS.Rabbit;
}));
},{"./cipher-core":21,"./core":22,"./enc-base64":23,"./evpkdf":25,"./md5":30}],44:[function(require,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"), require("./enc-base64"), require("./md5"), require("./evpkdf"), require("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var StreamCipher = C_lib.StreamCipher;
var C_algo = C.algo;
/**
* RC4 stream cipher algorithm.
*/
var RC4 = C_algo.RC4 = StreamCipher.extend({
_doReset: function () {
// Shortcuts
var key = this._key;
var keyWords = key.words;
var keySigBytes = key.sigBytes;
// Init sbox
var S = this._S = [];
for (var i = 0; i < 256; i++) {
S[i] = i;
}
// Key setup
for (var i = 0, j = 0; i < 256; i++) {
var keyByteIndex = i % keySigBytes;
var keyByte = (keyWords[keyByteIndex >>> 2] >>> (24 - (keyByteIndex % 4) * 8)) & 0xff;
j = (j + S[i] + keyByte) % 256;
// Swap
var t = S[i];
S[i] = S[j];
S[j] = t;
}
// Counters
this._i = this._j = 0;
},
_doProcessBlock: function (M, offset) {
M[offset] ^= generateKeystreamWord.call(this);
},
keySize: 256/32,
ivSize: 0
});
function generateKeystreamWord() {
// Shortcuts
var S = this._S;
var i = this._i;
var j = this._j;
// Generate keystream word
var keystreamWord = 0;
for (var n = 0; n < 4; n++) {
i = (i + 1) % 256;
j = (j + S[i]) % 256;
// Swap
var t = S[i];
S[i] = S[j];
S[j] = t;
keystreamWord |= S[(S[i] + S[j]) % 256] << (24 - n * 8);
}
// Update counters
this._i = i;
this._j = j;
return keystreamWord;
}
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.RC4.encrypt(message, key, cfg);
* var plaintext = CryptoJS.RC4.decrypt(ciphertext, key, cfg);
*/
C.RC4 = StreamCipher._createHelper(RC4);
/**
* Modified RC4 stream cipher algorithm.
*/
var RC4Drop = C_algo.RC4Drop = RC4.extend({
/**
* Configuration options.
*
* @property {number} drop The number of keystream words to drop. Default 192
*/
cfg: RC4.cfg.extend({
drop: 192
}),
_doReset: function () {
RC4._doReset.call(this);
// Drop
for (var i = this.cfg.drop; i > 0; i--) {
generateKeystreamWord.call(this);
}
}
});
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.RC4Drop.encrypt(message, key, cfg);
* var plaintext = CryptoJS.RC4Drop.decrypt(ciphertext, key, cfg);
*/
C.RC4Drop = StreamCipher._createHelper(RC4Drop);
}());
return CryptoJS.RC4;
}));
},{"./cipher-core":21,"./core":22,"./enc-base64":23,"./evpkdf":25,"./md5":30}],45:[function(require,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/** @preserve
(c) 2012 by Cรฉdric Mesnil. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
(function (Math) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_algo = C.algo;
// Constants table
var _zl = WordArray.create([
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,
1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,
4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13]);
var _zr = WordArray.create([
5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,
6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,
15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,
8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,
12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11]);
var _sl = WordArray.create([
11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,
7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,
11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,
11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,
9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 ]);
var _sr = WordArray.create([
8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,
9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,
9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,
15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,
8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 ]);
var _hl = WordArray.create([ 0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E]);
var _hr = WordArray.create([ 0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0x00000000]);
/**
* RIPEMD160 hash algorithm.
*/
var RIPEMD160 = C_algo.RIPEMD160 = Hasher.extend({
_doReset: function () {
this._hash = WordArray.create([0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]);
},
_doProcessBlock: function (M, offset) {
// Swap endian
for (var i = 0; i < 16; i++) {
// Shortcuts
var offset_i = offset + i;
var M_offset_i = M[offset_i];
// Swap
M[offset_i] = (
(((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) |
(((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00)
);
}
// Shortcut
var H = this._hash.words;
var hl = _hl.words;
var hr = _hr.words;
var zl = _zl.words;
var zr = _zr.words;
var sl = _sl.words;
var sr = _sr.words;
// Working variables
var al, bl, cl, dl, el;
var ar, br, cr, dr, er;
ar = al = H[0];
br = bl = H[1];
cr = cl = H[2];
dr = dl = H[3];
er = el = H[4];
// Computation
var t;
for (var i = 0; i < 80; i += 1) {
t = (al + M[offset+zl[i]])|0;
if (i<16){
t += f1(bl,cl,dl) + hl[0];
} else if (i<32) {
t += f2(bl,cl,dl) + hl[1];
} else if (i<48) {
t += f3(bl,cl,dl) + hl[2];
} else if (i<64) {
t += f4(bl,cl,dl) + hl[3];
} else {// if (i<80) {
t += f5(bl,cl,dl) + hl[4];
}
t = t|0;
t = rotl(t,sl[i]);
t = (t+el)|0;
al = el;
el = dl;
dl = rotl(cl, 10);
cl = bl;
bl = t;
t = (ar + M[offset+zr[i]])|0;
if (i<16){
t += f5(br,cr,dr) + hr[0];
} else if (i<32) {
t += f4(br,cr,dr) + hr[1];
} else if (i<48) {
t += f3(br,cr,dr) + hr[2];
} else if (i<64) {
t += f2(br,cr,dr) + hr[3];
} else {// if (i<80) {
t += f1(br,cr,dr) + hr[4];
}
t = t|0;
t = rotl(t,sr[i]) ;
t = (t+er)|0;
ar = er;
er = dr;
dr = rotl(cr, 10);
cr = br;
br = t;
}
// Intermediate hash value
t = (H[1] + cl + dr)|0;
H[1] = (H[2] + dl + er)|0;
H[2] = (H[3] + el + ar)|0;
H[3] = (H[4] + al + br)|0;
H[4] = (H[0] + bl + cr)|0;
H[0] = t;
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = (
(((nBitsTotal << 8) | (nBitsTotal >>> 24)) & 0x00ff00ff) |
(((nBitsTotal << 24) | (nBitsTotal >>> 8)) & 0xff00ff00)
);
data.sigBytes = (dataWords.length + 1) * 4;
// Hash final blocks
this._process();
// Shortcuts
var hash = this._hash;
var H = hash.words;
// Swap endian
for (var i = 0; i < 5; i++) {
// Shortcut
var H_i = H[i];
// Swap
H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) |
(((H_i << 24) | (H_i >>> 8)) & 0xff00ff00);
}
// Return final computed hash
return hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
}
});
function f1(x, y, z) {
return ((x) ^ (y) ^ (z));
}
function f2(x, y, z) {
return (((x)&(y)) | ((~x)&(z)));
}
function f3(x, y, z) {
return (((x) | (~(y))) ^ (z));
}
function f4(x, y, z) {
return (((x) & (z)) | ((y)&(~(z))));
}
function f5(x, y, z) {
return ((x) ^ ((y) |(~(z))));
}
function rotl(x,n) {
return (x<<n) | (x>>>(32-n));
}
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.RIPEMD160('message');
* var hash = CryptoJS.RIPEMD160(wordArray);
*/
C.RIPEMD160 = Hasher._createHelper(RIPEMD160);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacRIPEMD160(message, key);
*/
C.HmacRIPEMD160 = Hasher._createHmacHelper(RIPEMD160);
}(Math));
return CryptoJS.RIPEMD160;
}));
},{"./core":22}],46:[function(require,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_algo = C.algo;
// Reusable object
var W = [];
/**
* SHA-1 hash algorithm.
*/
var SHA1 = C_algo.SHA1 = Hasher.extend({
_doReset: function () {
this._hash = new WordArray.init([
0x67452301, 0xefcdab89,
0x98badcfe, 0x10325476,
0xc3d2e1f0
]);
},
_doProcessBlock: function (M, offset) {
// Shortcut
var H = this._hash.words;
// Working variables
var a = H[0];
var b = H[1];
var c = H[2];
var d = H[3];
var e = H[4];
// Computation
for (var i = 0; i < 80; i++) {
if (i < 16) {
W[i] = M[offset + i] | 0;
} else {
var n = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16];
W[i] = (n << 1) | (n >>> 31);
}
var t = ((a << 5) | (a >>> 27)) + e + W[i];
if (i < 20) {
t += ((b & c) | (~b & d)) + 0x5a827999;
} else if (i < 40) {
t += (b ^ c ^ d) + 0x6ed9eba1;
} else if (i < 60) {
t += ((b & c) | (b & d) | (c & d)) - 0x70e44324;
} else /* if (i < 80) */ {
t += (b ^ c ^ d) - 0x359d3e2a;
}
e = d;
d = c;
c = (b << 30) | (b >>> 2);
b = a;
a = t;
}
// Intermediate hash value
H[0] = (H[0] + a) | 0;
H[1] = (H[1] + b) | 0;
H[2] = (H[2] + c) | 0;
H[3] = (H[3] + d) | 0;
H[4] = (H[4] + e) | 0;
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal;
data.sigBytes = dataWords.length * 4;
// Hash final blocks
this._process();
// Return final computed hash
return this._hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
}
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA1('message');
* var hash = CryptoJS.SHA1(wordArray);
*/
C.SHA1 = Hasher._createHelper(SHA1);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA1(message, key);
*/
C.HmacSHA1 = Hasher._createHmacHelper(SHA1);
}());
return CryptoJS.SHA1;
}));
},{"./core":22}],47:[function(require,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"), require("./sha256"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./sha256"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var C_algo = C.algo;
var SHA256 = C_algo.SHA256;
/**
* SHA-224 hash algorithm.
*/
var SHA224 = C_algo.SHA224 = SHA256.extend({
_doReset: function () {
this._hash = new WordArray.init([
0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939,
0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4
]);
},
_doFinalize: function () {
var hash = SHA256._doFinalize.call(this);
hash.sigBytes -= 4;
return hash;
}
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA224('message');
* var hash = CryptoJS.SHA224(wordArray);
*/
C.SHA224 = SHA256._createHelper(SHA224);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA224(message, key);
*/
C.HmacSHA224 = SHA256._createHmacHelper(SHA224);
}());
return CryptoJS.SHA224;
}));
},{"./core":22,"./sha256":48}],48:[function(require,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function (Math) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_algo = C.algo;
// Initialization and round constants tables
var H = [];
var K = [];
// Compute constants
(function () {
function isPrime(n) {
var sqrtN = Math.sqrt(n);
for (var factor = 2; factor <= sqrtN; factor++) {
if (!(n % factor)) {
return false;
}
}
return true;
}
function getFractionalBits(n) {
return ((n - (n | 0)) * 0x100000000) | 0;
}
var n = 2;
var nPrime = 0;
while (nPrime < 64) {
if (isPrime(n)) {
if (nPrime < 8) {
H[nPrime] = getFractionalBits(Math.pow(n, 1 / 2));
}
K[nPrime] = getFractionalBits(Math.pow(n, 1 / 3));
nPrime++;
}
n++;
}
}());
// Reusable object
var W = [];
/**
* SHA-256 hash algorithm.
*/
var SHA256 = C_algo.SHA256 = Hasher.extend({
_doReset: function () {
this._hash = new WordArray.init(H.slice(0));
},
_doProcessBlock: function (M, offset) {
// Shortcut
var H = this._hash.words;
// Working variables
var a = H[0];
var b = H[1];
var c = H[2];
var d = H[3];
var e = H[4];
var f = H[5];
var g = H[6];
var h = H[7];
// Computation
for (var i = 0; i < 64; i++) {
if (i < 16) {
W[i] = M[offset + i] | 0;
} else {
var gamma0x = W[i - 15];
var gamma0 = ((gamma0x << 25) | (gamma0x >>> 7)) ^
((gamma0x << 14) | (gamma0x >>> 18)) ^
(gamma0x >>> 3);
var gamma1x = W[i - 2];
var gamma1 = ((gamma1x << 15) | (gamma1x >>> 17)) ^
((gamma1x << 13) | (gamma1x >>> 19)) ^
(gamma1x >>> 10);
W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16];
}
var ch = (e & f) ^ (~e & g);
var maj = (a & b) ^ (a & c) ^ (b & c);
var sigma0 = ((a << 30) | (a >>> 2)) ^ ((a << 19) | (a >>> 13)) ^ ((a << 10) | (a >>> 22));
var sigma1 = ((e << 26) | (e >>> 6)) ^ ((e << 21) | (e >>> 11)) ^ ((e << 7) | (e >>> 25));
var t1 = h + sigma1 + ch + K[i] + W[i];
var t2 = sigma0 + maj;
h = g;
g = f;
f = e;
e = (d + t1) | 0;
d = c;
c = b;
b = a;
a = (t1 + t2) | 0;
}
// Intermediate hash value
H[0] = (H[0] + a) | 0;
H[1] = (H[1] + b) | 0;
H[2] = (H[2] + c) | 0;
H[3] = (H[3] + d) | 0;
H[4] = (H[4] + e) | 0;
H[5] = (H[5] + f) | 0;
H[6] = (H[6] + g) | 0;
H[7] = (H[7] + h) | 0;
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal;
data.sigBytes = dataWords.length * 4;
// Hash final blocks
this._process();
// Return final computed hash
return this._hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
}
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA256('message');
* var hash = CryptoJS.SHA256(wordArray);
*/
C.SHA256 = Hasher._createHelper(SHA256);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA256(message, key);
*/
C.HmacSHA256 = Hasher._createHmacHelper(SHA256);
}(Math));
return CryptoJS.SHA256;
}));
},{"./core":22}],49:[function(require,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"), require("./x64-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./x64-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function (Math) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_x64 = C.x64;
var X64Word = C_x64.Word;
var C_algo = C.algo;
// Constants tables
var RHO_OFFSETS = [];
var PI_INDEXES = [];
var ROUND_CONSTANTS = [];
// Compute Constants
(function () {
// Compute rho offset constants
var x = 1, y = 0;
for (var t = 0; t < 24; t++) {
RHO_OFFSETS[x + 5 * y] = ((t + 1) * (t + 2) / 2) % 64;
var newX = y % 5;
var newY = (2 * x + 3 * y) % 5;
x = newX;
y = newY;
}
// Compute pi index constants
for (var x = 0; x < 5; x++) {
for (var y = 0; y < 5; y++) {
PI_INDEXES[x + 5 * y] = y + ((2 * x + 3 * y) % 5) * 5;
}
}
// Compute round constants
var LFSR = 0x01;
for (var i = 0; i < 24; i++) {
var roundConstantMsw = 0;
var roundConstantLsw = 0;
for (var j = 0; j < 7; j++) {
if (LFSR & 0x01) {
var bitPosition = (1 << j) - 1;
if (bitPosition < 32) {
roundConstantLsw ^= 1 << bitPosition;
} else /* if (bitPosition >= 32) */ {
roundConstantMsw ^= 1 << (bitPosition - 32);
}
}
// Compute next LFSR
if (LFSR & 0x80) {
// Primitive polynomial over GF(2): x^8 + x^6 + x^5 + x^4 + 1
LFSR = (LFSR << 1) ^ 0x71;
} else {
LFSR <<= 1;
}
}
ROUND_CONSTANTS[i] = X64Word.create(roundConstantMsw, roundConstantLsw);
}
}());
// Reusable objects for temporary values
var T = [];
(function () {
for (var i = 0; i < 25; i++) {
T[i] = X64Word.create();
}
}());
/**
* SHA-3 hash algorithm.
*/
var SHA3 = C_algo.SHA3 = Hasher.extend({
/**
* Configuration options.
*
* @property {number} outputLength
* The desired number of bits in the output hash.
* Only values permitted are: 224, 256, 384, 512.
* Default: 512
*/
cfg: Hasher.cfg.extend({
outputLength: 512
}),
_doReset: function () {
var state = this._state = []
for (var i = 0; i < 25; i++) {
state[i] = new X64Word.init();
}
this.blockSize = (1600 - 2 * this.cfg.outputLength) / 32;
},
_doProcessBlock: function (M, offset) {
// Shortcuts
var state = this._state;
var nBlockSizeLanes = this.blockSize / 2;
// Absorb
for (var i = 0; i < nBlockSizeLanes; i++) {
// Shortcuts
var M2i = M[offset + 2 * i];
var M2i1 = M[offset + 2 * i + 1];
// Swap endian
M2i = (
(((M2i << 8) | (M2i >>> 24)) & 0x00ff00ff) |
(((M2i << 24) | (M2i >>> 8)) & 0xff00ff00)
);
M2i1 = (
(((M2i1 << 8) | (M2i1 >>> 24)) & 0x00ff00ff) |
(((M2i1 << 24) | (M2i1 >>> 8)) & 0xff00ff00)
);
// Absorb message into state
var lane = state[i];
lane.high ^= M2i1;
lane.low ^= M2i;
}
// Rounds
for (var round = 0; round < 24; round++) {
// Theta
for (var x = 0; x < 5; x++) {
// Mix column lanes
var tMsw = 0, tLsw = 0;
for (var y = 0; y < 5; y++) {
var lane = state[x + 5 * y];
tMsw ^= lane.high;
tLsw ^= lane.low;
}
// Temporary values
var Tx = T[x];
Tx.high = tMsw;
Tx.low = tLsw;
}
for (var x = 0; x < 5; x++) {
// Shortcuts
var Tx4 = T[(x + 4) % 5];
var Tx1 = T[(x + 1) % 5];
var Tx1Msw = Tx1.high;
var Tx1Lsw = Tx1.low;
// Mix surrounding columns
var tMsw = Tx4.high ^ ((Tx1Msw << 1) | (Tx1Lsw >>> 31));
var tLsw = Tx4.low ^ ((Tx1Lsw << 1) | (Tx1Msw >>> 31));
for (var y = 0; y < 5; y++) {
var lane = state[x + 5 * y];
lane.high ^= tMsw;
lane.low ^= tLsw;
}
}
// Rho Pi
for (var laneIndex = 1; laneIndex < 25; laneIndex++) {
// Shortcuts
var lane = state[laneIndex];
var laneMsw = lane.high;
var laneLsw = lane.low;
var rhoOffset = RHO_OFFSETS[laneIndex];
// Rotate lanes
if (rhoOffset < 32) {
var tMsw = (laneMsw << rhoOffset) | (laneLsw >>> (32 - rhoOffset));
var tLsw = (laneLsw << rhoOffset) | (laneMsw >>> (32 - rhoOffset));
} else /* if (rhoOffset >= 32) */ {
var tMsw = (laneLsw << (rhoOffset - 32)) | (laneMsw >>> (64 - rhoOffset));
var tLsw = (laneMsw << (rhoOffset - 32)) | (laneLsw >>> (64 - rhoOffset));
}
// Transpose lanes
var TPiLane = T[PI_INDEXES[laneIndex]];
TPiLane.high = tMsw;
TPiLane.low = tLsw;
}
// Rho pi at x = y = 0
var T0 = T[0];
var state0 = state[0];
T0.high = state0.high;
T0.low = state0.low;
// Chi
for (var x = 0; x < 5; x++) {
for (var y = 0; y < 5; y++) {
// Shortcuts
var laneIndex = x + 5 * y;
var lane = state[laneIndex];
var TLane = T[laneIndex];
var Tx1Lane = T[((x + 1) % 5) + 5 * y];
var Tx2Lane = T[((x + 2) % 5) + 5 * y];
// Mix rows
lane.high = TLane.high ^ (~Tx1Lane.high & Tx2Lane.high);
lane.low = TLane.low ^ (~Tx1Lane.low & Tx2Lane.low);
}
}
// Iota
var lane = state[0];
var roundConstant = ROUND_CONSTANTS[round];
lane.high ^= roundConstant.high;
lane.low ^= roundConstant.low;;
}
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
var blockSizeBits = this.blockSize * 32;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x1 << (24 - nBitsLeft % 32);
dataWords[((Math.ceil((nBitsLeft + 1) / blockSizeBits) * blockSizeBits) >>> 5) - 1] |= 0x80;
data.sigBytes = dataWords.length * 4;
// Hash final blocks
this._process();
// Shortcuts
var state = this._state;
var outputLengthBytes = this.cfg.outputLength / 8;
var outputLengthLanes = outputLengthBytes / 8;
// Squeeze
var hashWords = [];
for (var i = 0; i < outputLengthLanes; i++) {
// Shortcuts
var lane = state[i];
var laneMsw = lane.high;
var laneLsw = lane.low;
// Swap endian
laneMsw = (
(((laneMsw << 8) | (laneMsw >>> 24)) & 0x00ff00ff) |
(((laneMsw << 24) | (laneMsw >>> 8)) & 0xff00ff00)
);
laneLsw = (
(((laneLsw << 8) | (laneLsw >>> 24)) & 0x00ff00ff) |
(((laneLsw << 24) | (laneLsw >>> 8)) & 0xff00ff00)
);
// Squeeze state to retrieve hash
hashWords.push(laneLsw);
hashWords.push(laneMsw);
}
// Return final computed hash
return new WordArray.init(hashWords, outputLengthBytes);
},
clone: function () {
var clone = Hasher.clone.call(this);
var state = clone._state = this._state.slice(0);
for (var i = 0; i < 25; i++) {
state[i] = state[i].clone();
}
return clone;
}
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA3('message');
* var hash = CryptoJS.SHA3(wordArray);
*/
C.SHA3 = Hasher._createHelper(SHA3);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA3(message, key);
*/
C.HmacSHA3 = Hasher._createHmacHelper(SHA3);
}(Math));
return CryptoJS.SHA3;
}));
},{"./core":22,"./x64-core":53}],50:[function(require,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"), require("./x64-core"), require("./sha512"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./x64-core", "./sha512"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_x64 = C.x64;
var X64Word = C_x64.Word;
var X64WordArray = C_x64.WordArray;
var C_algo = C.algo;
var SHA512 = C_algo.SHA512;
/**
* SHA-384 hash algorithm.
*/
var SHA384 = C_algo.SHA384 = SHA512.extend({
_doReset: function () {
this._hash = new X64WordArray.init([
new X64Word.init(0xcbbb9d5d, 0xc1059ed8), new X64Word.init(0x629a292a, 0x367cd507),
new X64Word.init(0x9159015a, 0x3070dd17), new X64Word.init(0x152fecd8, 0xf70e5939),
new X64Word.init(0x67332667, 0xffc00b31), new X64Word.init(0x8eb44a87, 0x68581511),
new X64Word.init(0xdb0c2e0d, 0x64f98fa7), new X64Word.init(0x47b5481d, 0xbefa4fa4)
]);
},
_doFinalize: function () {
var hash = SHA512._doFinalize.call(this);
hash.sigBytes -= 16;
return hash;
}
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA384('message');
* var hash = CryptoJS.SHA384(wordArray);
*/
C.SHA384 = SHA512._createHelper(SHA384);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA384(message, key);
*/
C.HmacSHA384 = SHA512._createHmacHelper(SHA384);
}());
return CryptoJS.SHA384;
}));
},{"./core":22,"./sha512":51,"./x64-core":53}],51:[function(require,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"), require("./x64-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./x64-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Hasher = C_lib.Hasher;
var C_x64 = C.x64;
var X64Word = C_x64.Word;
var X64WordArray = C_x64.WordArray;
var C_algo = C.algo;
function X64Word_create() {
return X64Word.create.apply(X64Word, arguments);
}
// Constants
var K = [
X64Word_create(0x428a2f98, 0xd728ae22), X64Word_create(0x71374491, 0x23ef65cd),
X64Word_create(0xb5c0fbcf, 0xec4d3b2f), X64Word_create(0xe9b5dba5, 0x8189dbbc),
X64Word_create(0x3956c25b, 0xf348b538), X64Word_create(0x59f111f1, 0xb605d019),
X64Word_create(0x923f82a4, 0xaf194f9b), X64Word_create(0xab1c5ed5, 0xda6d8118),
X64Word_create(0xd807aa98, 0xa3030242), X64Word_create(0x12835b01, 0x45706fbe),
X64Word_create(0x243185be, 0x4ee4b28c), X64Word_create(0x550c7dc3, 0xd5ffb4e2),
X64Word_create(0x72be5d74, 0xf27b896f), X64Word_create(0x80deb1fe, 0x3b1696b1),
X64Word_create(0x9bdc06a7, 0x25c71235), X64Word_create(0xc19bf174, 0xcf692694),
X64Word_create(0xe49b69c1, 0x9ef14ad2), X64Word_create(0xefbe4786, 0x384f25e3),
X64Word_create(0x0fc19dc6, 0x8b8cd5b5), X64Word_create(0x240ca1cc, 0x77ac9c65),
X64Word_create(0x2de92c6f, 0x592b0275), X64Word_create(0x4a7484aa, 0x6ea6e483),
X64Word_create(0x5cb0a9dc, 0xbd41fbd4), X64Word_create(0x76f988da, 0x831153b5),
X64Word_create(0x983e5152, 0xee66dfab), X64Word_create(0xa831c66d, 0x2db43210),
X64Word_create(0xb00327c8, 0x98fb213f), X64Word_create(0xbf597fc7, 0xbeef0ee4),
X64Word_create(0xc6e00bf3, 0x3da88fc2), X64Word_create(0xd5a79147, 0x930aa725),
X64Word_create(0x06ca6351, 0xe003826f), X64Word_create(0x14292967, 0x0a0e6e70),
X64Word_create(0x27b70a85, 0x46d22ffc), X64Word_create(0x2e1b2138, 0x5c26c926),
X64Word_create(0x4d2c6dfc, 0x5ac42aed), X64Word_create(0x53380d13, 0x9d95b3df),
X64Word_create(0x650a7354, 0x8baf63de), X64Word_create(0x766a0abb, 0x3c77b2a8),
X64Word_create(0x81c2c92e, 0x47edaee6), X64Word_create(0x92722c85, 0x1482353b),
X64Word_create(0xa2bfe8a1, 0x4cf10364), X64Word_create(0xa81a664b, 0xbc423001),
X64Word_create(0xc24b8b70, 0xd0f89791), X64Word_create(0xc76c51a3, 0x0654be30),
X64Word_create(0xd192e819, 0xd6ef5218), X64Word_create(0xd6990624, 0x5565a910),
X64Word_create(0xf40e3585, 0x5771202a), X64Word_create(0x106aa070, 0x32bbd1b8),
X64Word_create(0x19a4c116, 0xb8d2d0c8), X64Word_create(0x1e376c08, 0x5141ab53),
X64Word_create(0x2748774c, 0xdf8eeb99), X64Word_create(0x34b0bcb5, 0xe19b48a8),
X64Word_create(0x391c0cb3, 0xc5c95a63), X64Word_create(0x4ed8aa4a, 0xe3418acb),
X64Word_create(0x5b9cca4f, 0x7763e373), X64Word_create(0x682e6ff3, 0xd6b2b8a3),
X64Word_create(0x748f82ee, 0x5defb2fc), X64Word_create(0x78a5636f, 0x43172f60),
X64Word_create(0x84c87814, 0xa1f0ab72), X64Word_create(0x8cc70208, 0x1a6439ec),
X64Word_create(0x90befffa, 0x23631e28), X64Word_create(0xa4506ceb, 0xde82bde9),
X64Word_create(0xbef9a3f7, 0xb2c67915), X64Word_create(0xc67178f2, 0xe372532b),
X64Word_create(0xca273ece, 0xea26619c), X64Word_create(0xd186b8c7, 0x21c0c207),
X64Word_create(0xeada7dd6, 0xcde0eb1e), X64Word_create(0xf57d4f7f, 0xee6ed178),
X64Word_create(0x06f067aa, 0x72176fba), X64Word_create(0x0a637dc5, 0xa2c898a6),
X64Word_create(0x113f9804, 0xbef90dae), X64Word_create(0x1b710b35, 0x131c471b),
X64Word_create(0x28db77f5, 0x23047d84), X64Word_create(0x32caab7b, 0x40c72493),
X64Word_create(0x3c9ebe0a, 0x15c9bebc), X64Word_create(0x431d67c4, 0x9c100d4c),
X64Word_create(0x4cc5d4be, 0xcb3e42b6), X64Word_create(0x597f299c, 0xfc657e2a),
X64Word_create(0x5fcb6fab, 0x3ad6faec), X64Word_create(0x6c44198c, 0x4a475817)
];
// Reusable objects
var W = [];
(function () {
for (var i = 0; i < 80; i++) {
W[i] = X64Word_create();
}
}());
/**
* SHA-512 hash algorithm.
*/
var SHA512 = C_algo.SHA512 = Hasher.extend({
_doReset: function () {
this._hash = new X64WordArray.init([
new X64Word.init(0x6a09e667, 0xf3bcc908), new X64Word.init(0xbb67ae85, 0x84caa73b),
new X64Word.init(0x3c6ef372, 0xfe94f82b), new X64Word.init(0xa54ff53a, 0x5f1d36f1),
new X64Word.init(0x510e527f, 0xade682d1), new X64Word.init(0x9b05688c, 0x2b3e6c1f),
new X64Word.init(0x1f83d9ab, 0xfb41bd6b), new X64Word.init(0x5be0cd19, 0x137e2179)
]);
},
_doProcessBlock: function (M, offset) {
// Shortcuts
var H = this._hash.words;
var H0 = H[0];
var H1 = H[1];
var H2 = H[2];
var H3 = H[3];
var H4 = H[4];
var H5 = H[5];
var H6 = H[6];
var H7 = H[7];
var H0h = H0.high;
var H0l = H0.low;
var H1h = H1.high;
var H1l = H1.low;
var H2h = H2.high;
var H2l = H2.low;
var H3h = H3.high;
var H3l = H3.low;
var H4h = H4.high;
var H4l = H4.low;
var H5h = H5.high;
var H5l = H5.low;
var H6h = H6.high;
var H6l = H6.low;
var H7h = H7.high;
var H7l = H7.low;
// Working variables
var ah = H0h;
var al = H0l;
var bh = H1h;
var bl = H1l;
var ch = H2h;
var cl = H2l;
var dh = H3h;
var dl = H3l;
var eh = H4h;
var el = H4l;
var fh = H5h;
var fl = H5l;
var gh = H6h;
var gl = H6l;
var hh = H7h;
var hl = H7l;
// Rounds
for (var i = 0; i < 80; i++) {
// Shortcut
var Wi = W[i];
// Extend message
if (i < 16) {
var Wih = Wi.high = M[offset + i * 2] | 0;
var Wil = Wi.low = M[offset + i * 2 + 1] | 0;
} else {
// Gamma0
var gamma0x = W[i - 15];
var gamma0xh = gamma0x.high;
var gamma0xl = gamma0x.low;
var gamma0h = ((gamma0xh >>> 1) | (gamma0xl << 31)) ^ ((gamma0xh >>> 8) | (gamma0xl << 24)) ^ (gamma0xh >>> 7);
var gamma0l = ((gamma0xl >>> 1) | (gamma0xh << 31)) ^ ((gamma0xl >>> 8) | (gamma0xh << 24)) ^ ((gamma0xl >>> 7) | (gamma0xh << 25));
// Gamma1
var gamma1x = W[i - 2];
var gamma1xh = gamma1x.high;
var gamma1xl = gamma1x.low;
var gamma1h = ((gamma1xh >>> 19) | (gamma1xl << 13)) ^ ((gamma1xh << 3) | (gamma1xl >>> 29)) ^ (gamma1xh >>> 6);
var gamma1l = ((gamma1xl >>> 19) | (gamma1xh << 13)) ^ ((gamma1xl << 3) | (gamma1xh >>> 29)) ^ ((gamma1xl >>> 6) | (gamma1xh << 26));
// W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]
var Wi7 = W[i - 7];
var Wi7h = Wi7.high;
var Wi7l = Wi7.low;
var Wi16 = W[i - 16];
var Wi16h = Wi16.high;
var Wi16l = Wi16.low;
var Wil = gamma0l + Wi7l;
var Wih = gamma0h + Wi7h + ((Wil >>> 0) < (gamma0l >>> 0) ? 1 : 0);
var Wil = Wil + gamma1l;
var Wih = Wih + gamma1h + ((Wil >>> 0) < (gamma1l >>> 0) ? 1 : 0);
var Wil = Wil + Wi16l;
var Wih = Wih + Wi16h + ((Wil >>> 0) < (Wi16l >>> 0) ? 1 : 0);
Wi.high = Wih;
Wi.low = Wil;
}
var chh = (eh & fh) ^ (~eh & gh);
var chl = (el & fl) ^ (~el & gl);
var majh = (ah & bh) ^ (ah & ch) ^ (bh & ch);
var majl = (al & bl) ^ (al & cl) ^ (bl & cl);
var sigma0h = ((ah >>> 28) | (al << 4)) ^ ((ah << 30) | (al >>> 2)) ^ ((ah << 25) | (al >>> 7));
var sigma0l = ((al >>> 28) | (ah << 4)) ^ ((al << 30) | (ah >>> 2)) ^ ((al << 25) | (ah >>> 7));
var sigma1h = ((eh >>> 14) | (el << 18)) ^ ((eh >>> 18) | (el << 14)) ^ ((eh << 23) | (el >>> 9));
var sigma1l = ((el >>> 14) | (eh << 18)) ^ ((el >>> 18) | (eh << 14)) ^ ((el << 23) | (eh >>> 9));
// t1 = h + sigma1 + ch + K[i] + W[i]
var Ki = K[i];
var Kih = Ki.high;
var Kil = Ki.low;
var t1l = hl + sigma1l;
var t1h = hh + sigma1h + ((t1l >>> 0) < (hl >>> 0) ? 1 : 0);
var t1l = t1l + chl;
var t1h = t1h + chh + ((t1l >>> 0) < (chl >>> 0) ? 1 : 0);
var t1l = t1l + Kil;
var t1h = t1h + Kih + ((t1l >>> 0) < (Kil >>> 0) ? 1 : 0);
var t1l = t1l + Wil;
var t1h = t1h + Wih + ((t1l >>> 0) < (Wil >>> 0) ? 1 : 0);
// t2 = sigma0 + maj
var t2l = sigma0l + majl;
var t2h = sigma0h + majh + ((t2l >>> 0) < (sigma0l >>> 0) ? 1 : 0);
// Update working variables
hh = gh;
hl = gl;
gh = fh;
gl = fl;
fh = eh;
fl = el;
el = (dl + t1l) | 0;
eh = (dh + t1h + ((el >>> 0) < (dl >>> 0) ? 1 : 0)) | 0;
dh = ch;
dl = cl;
ch = bh;
cl = bl;
bh = ah;
bl = al;
al = (t1l + t2l) | 0;
ah = (t1h + t2h + ((al >>> 0) < (t1l >>> 0) ? 1 : 0)) | 0;
}
// Intermediate hash value
H0l = H0.low = (H0l + al);
H0.high = (H0h + ah + ((H0l >>> 0) < (al >>> 0) ? 1 : 0));
H1l = H1.low = (H1l + bl);
H1.high = (H1h + bh + ((H1l >>> 0) < (bl >>> 0) ? 1 : 0));
H2l = H2.low = (H2l + cl);
H2.high = (H2h + ch + ((H2l >>> 0) < (cl >>> 0) ? 1 : 0));
H3l = H3.low = (H3l + dl);
H3.high = (H3h + dh + ((H3l >>> 0) < (dl >>> 0) ? 1 : 0));
H4l = H4.low = (H4l + el);
H4.high = (H4h + eh + ((H4l >>> 0) < (el >>> 0) ? 1 : 0));
H5l = H5.low = (H5l + fl);
H5.high = (H5h + fh + ((H5l >>> 0) < (fl >>> 0) ? 1 : 0));
H6l = H6.low = (H6l + gl);
H6.high = (H6h + gh + ((H6l >>> 0) < (gl >>> 0) ? 1 : 0));
H7l = H7.low = (H7l + hl);
H7.high = (H7h + hh + ((H7l >>> 0) < (hl >>> 0) ? 1 : 0));
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 30] = Math.floor(nBitsTotal / 0x100000000);
dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 31] = nBitsTotal;
data.sigBytes = dataWords.length * 4;
// Hash final blocks
this._process();
// Convert hash to 32-bit word array before returning
var hash = this._hash.toX32();
// Return final computed hash
return hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
},
blockSize: 1024/32
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA512('message');
* var hash = CryptoJS.SHA512(wordArray);
*/
C.SHA512 = Hasher._createHelper(SHA512);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA512(message, key);
*/
C.HmacSHA512 = Hasher._createHmacHelper(SHA512);
}());
return CryptoJS.SHA512;
}));
},{"./core":22,"./x64-core":53}],52:[function(require,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"), require("./enc-base64"), require("./md5"), require("./evpkdf"), require("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var BlockCipher = C_lib.BlockCipher;
var C_algo = C.algo;
// Permuted Choice 1 constants
var PC1 = [
57, 49, 41, 33, 25, 17, 9, 1,
58, 50, 42, 34, 26, 18, 10, 2,
59, 51, 43, 35, 27, 19, 11, 3,
60, 52, 44, 36, 63, 55, 47, 39,
31, 23, 15, 7, 62, 54, 46, 38,
30, 22, 14, 6, 61, 53, 45, 37,
29, 21, 13, 5, 28, 20, 12, 4
];
// Permuted Choice 2 constants
var PC2 = [
14, 17, 11, 24, 1, 5,
3, 28, 15, 6, 21, 10,
23, 19, 12, 4, 26, 8,
16, 7, 27, 20, 13, 2,
41, 52, 31, 37, 47, 55,
30, 40, 51, 45, 33, 48,
44, 49, 39, 56, 34, 53,
46, 42, 50, 36, 29, 32
];
// Cumulative bit shift constants
var BIT_SHIFTS = [1, 2, 4, 6, 8, 10, 12, 14, 15, 17, 19, 21, 23, 25, 27, 28];
// SBOXes and round permutation constants
var SBOX_P = [
{
0x0: 0x808200,
0x10000000: 0x8000,
0x20000000: 0x808002,
0x30000000: 0x2,
0x40000000: 0x200,
0x50000000: 0x808202,
0x60000000: 0x800202,
0x70000000: 0x800000,
0x80000000: 0x202,
0x90000000: 0x800200,
0xa0000000: 0x8200,
0xb0000000: 0x808000,
0xc0000000: 0x8002,
0xd0000000: 0x800002,
0xe0000000: 0x0,
0xf0000000: 0x8202,
0x8000000: 0x0,
0x18000000: 0x808202,
0x28000000: 0x8202,
0x38000000: 0x8000,
0x48000000: 0x808200,
0x58000000: 0x200,
0x68000000: 0x808002,
0x78000000: 0x2,
0x88000000: 0x800200,
0x98000000: 0x8200,
0xa8000000: 0x808000,
0xb8000000: 0x800202,
0xc8000000: 0x800002,
0xd8000000: 0x8002,
0xe8000000: 0x202,
0xf8000000: 0x800000,
0x1: 0x8000,
0x10000001: 0x2,
0x20000001: 0x808200,
0x30000001: 0x800000,
0x40000001: 0x808002,
0x50000001: 0x8200,
0x60000001: 0x200,
0x70000001: 0x800202,
0x80000001: 0x808202,
0x90000001: 0x808000,
0xa0000001: 0x800002,
0xb0000001: 0x8202,
0xc0000001: 0x202,
0xd0000001: 0x800200,
0xe0000001: 0x8002,
0xf0000001: 0x0,
0x8000001: 0x808202,
0x18000001: 0x808000,
0x28000001: 0x800000,
0x38000001: 0x200,
0x48000001: 0x8000,
0x58000001: 0x800002,
0x68000001: 0x2,
0x78000001: 0x8202,
0x88000001: 0x8002,
0x98000001: 0x800202,
0xa8000001: 0x202,
0xb8000001: 0x808200,
0xc8000001: 0x800200,
0xd8000001: 0x0,
0xe8000001: 0x8200,
0xf8000001: 0x808002
},
{
0x0: 0x40084010,
0x1000000: 0x4000,
0x2000000: 0x80000,
0x3000000: 0x40080010,
0x4000000: 0x40000010,
0x5000000: 0x40084000,
0x6000000: 0x40004000,
0x7000000: 0x10,
0x8000000: 0x84000,
0x9000000: 0x40004010,
0xa000000: 0x40000000,
0xb000000: 0x84010,
0xc000000: 0x80010,
0xd000000: 0x0,
0xe000000: 0x4010,
0xf000000: 0x40080000,
0x800000: 0x40004000,
0x1800000: 0x84010,
0x2800000: 0x10,
0x3800000: 0x40004010,
0x4800000: 0x40084010,
0x5800000: 0x40000000,
0x6800000: 0x80000,
0x7800000: 0x40080010,
0x8800000: 0x80010,
0x9800000: 0x0,
0xa800000: 0x4000,
0xb800000: 0x40080000,
0xc800000: 0x40000010,
0xd800000: 0x84000,
0xe800000: 0x40084000,
0xf800000: 0x4010,
0x10000000: 0x0,
0x11000000: 0x40080010,
0x12000000: 0x40004010,
0x13000000: 0x40084000,
0x14000000: 0x40080000,
0x15000000: 0x10,
0x16000000: 0x84010,
0x17000000: 0x4000,
0x18000000: 0x4010,
0x19000000: 0x80000,
0x1a000000: 0x80010,
0x1b000000: 0x40000010,
0x1c000000: 0x84000,
0x1d000000: 0x40004000,
0x1e000000: 0x40000000,
0x1f000000: 0x40084010,
0x10800000: 0x84010,
0x11800000: 0x80000,
0x12800000: 0x40080000,
0x13800000: 0x4000,
0x14800000: 0x40004000,
0x15800000: 0x40084010,
0x16800000: 0x10,
0x17800000: 0x40000000,
0x18800000: 0x40084000,
0x19800000: 0x40000010,
0x1a800000: 0x40004010,
0x1b800000: 0x80010,
0x1c800000: 0x0,
0x1d800000: 0x4010,
0x1e800000: 0x40080010,
0x1f800000: 0x84000
},
{
0x0: 0x104,
0x100000: 0x0,
0x200000: 0x4000100,
0x300000: 0x10104,
0x400000: 0x10004,
0x500000: 0x4000004,
0x600000: 0x4010104,
0x700000: 0x4010000,
0x800000: 0x4000000,
0x900000: 0x4010100,
0xa00000: 0x10100,
0xb00000: 0x4010004,
0xc00000: 0x4000104,
0xd00000: 0x10000,
0xe00000: 0x4,
0xf00000: 0x100,
0x80000: 0x4010100,
0x180000: 0x4010004,
0x280000: 0x0,
0x380000: 0x4000100,
0x480000: 0x4000004,
0x580000: 0x10000,
0x680000: 0x10004,
0x780000: 0x104,
0x880000: 0x4,
0x980000: 0x100,
0xa80000: 0x4010000,
0xb80000: 0x10104,
0xc80000: 0x10100,
0xd80000: 0x4000104,
0xe80000: 0x4010104,
0xf80000: 0x4000000,
0x1000000: 0x4010100,
0x1100000: 0x10004,
0x1200000: 0x10000,
0x1300000: 0x4000100,
0x1400000: 0x100,
0x1500000: 0x4010104,
0x1600000: 0x4000004,
0x1700000: 0x0,
0x1800000: 0x4000104,
0x1900000: 0x4000000,
0x1a00000: 0x4,
0x1b00000: 0x10100,
0x1c00000: 0x4010000,
0x1d00000: 0x104,
0x1e00000: 0x10104,
0x1f00000: 0x4010004,
0x1080000: 0x4000000,
0x1180000: 0x104,
0x1280000: 0x4010100,
0x1380000: 0x0,
0x1480000: 0x10004,
0x1580000: 0x4000100,
0x1680000: 0x100,
0x1780000: 0x4010004,
0x1880000: 0x10000,
0x1980000: 0x4010104,
0x1a80000: 0x10104,
0x1b80000: 0x4000004,
0x1c80000: 0x4000104,
0x1d80000: 0x4010000,
0x1e80000: 0x4,
0x1f80000: 0x10100
},
{
0x0: 0x80401000,
0x10000: 0x80001040,
0x20000: 0x401040,
0x30000: 0x80400000,
0x40000: 0x0,
0x50000: 0x401000,
0x60000: 0x80000040,
0x70000: 0x400040,
0x80000: 0x80000000,
0x90000: 0x400000,
0xa0000: 0x40,
0xb0000: 0x80001000,
0xc0000: 0x80400040,
0xd0000: 0x1040,
0xe0000: 0x1000,
0xf0000: 0x80401040,
0x8000: 0x80001040,
0x18000: 0x40,
0x28000: 0x80400040,
0x38000: 0x80001000,
0x48000: 0x401000,
0x58000: 0x80401040,
0x68000: 0x0,
0x78000: 0x80400000,
0x88000: 0x1000,
0x98000: 0x80401000,
0xa8000: 0x400000,
0xb8000: 0x1040,
0xc8000: 0x80000000,
0xd8000: 0x400040,
0xe8000: 0x401040,
0xf8000: 0x80000040,
0x100000: 0x400040,
0x110000: 0x401000,
0x120000: 0x80000040,
0x130000: 0x0,
0x140000: 0x1040,
0x150000: 0x80400040,
0x160000: 0x80401000,
0x170000: 0x80001040,
0x180000: 0x80401040,
0x190000: 0x80000000,
0x1a0000: 0x80400000,
0x1b0000: 0x401040,
0x1c0000: 0x80001000,
0x1d0000: 0x400000,
0x1e0000: 0x40,
0x1f0000: 0x1000,
0x108000: 0x80400000,
0x118000: 0x80401040,
0x128000: 0x0,
0x138000: 0x401000,
0x148000: 0x400040,
0x158000: 0x80000000,
0x168000: 0x80001040,
0x178000: 0x40,
0x188000: 0x80000040,
0x198000: 0x1000,
0x1a8000: 0x80001000,
0x1b8000: 0x80400040,
0x1c8000: 0x1040,
0x1d8000: 0x80401000,
0x1e8000: 0x400000,
0x1f8000: 0x401040
},
{
0x0: 0x80,
0x1000: 0x1040000,
0x2000: 0x40000,
0x3000: 0x20000000,
0x4000: 0x20040080,
0x5000: 0x1000080,
0x6000: 0x21000080,
0x7000: 0x40080,
0x8000: 0x1000000,
0x9000: 0x20040000,
0xa000: 0x20000080,
0xb000: 0x21040080,
0xc000: 0x21040000,
0xd000: 0x0,
0xe000: 0x1040080,
0xf000: 0x21000000,
0x800: 0x1040080,
0x1800: 0x21000080,
0x2800: 0x80,
0x3800: 0x1040000,
0x4800: 0x40000,
0x5800: 0x20040080,
0x6800: 0x21040000,
0x7800: 0x20000000,
0x8800: 0x20040000,
0x9800: 0x0,
0xa800: 0x21040080,
0xb800: 0x1000080,
0xc800: 0x20000080,
0xd800: 0x21000000,
0xe800: 0x1000000,
0xf800: 0x40080,
0x10000: 0x40000,
0x11000: 0x80,
0x12000: 0x20000000,
0x13000: 0x21000080,
0x14000: 0x1000080,
0x15000: 0x21040000,
0x16000: 0x20040080,
0x17000: 0x1000000,
0x18000: 0x21040080,
0x19000: 0x21000000,
0x1a000: 0x1040000,
0x1b000: 0x20040000,
0x1c000: 0x40080,
0x1d000: 0x20000080,
0x1e000: 0x0,
0x1f000: 0x1040080,
0x10800: 0x21000080,
0x11800: 0x1000000,
0x12800: 0x1040000,
0x13800: 0x20040080,
0x14800: 0x20000000,
0x15800: 0x1040080,
0x16800: 0x80,
0x17800: 0x21040000,
0x18800: 0x40080,
0x19800: 0x21040080,
0x1a800: 0x0,
0x1b800: 0x21000000,
0x1c800: 0x1000080,
0x1d800: 0x40000,
0x1e800: 0x20040000,
0x1f800: 0x20000080
},
{
0x0: 0x10000008,
0x100: 0x2000,
0x200: 0x10200000,
0x300: 0x10202008,
0x400: 0x10002000,
0x500: 0x200000,
0x600: 0x200008,
0x700: 0x10000000,
0x800: 0x0,
0x900: 0x10002008,
0xa00: 0x202000,
0xb00: 0x8,
0xc00: 0x10200008,
0xd00: 0x202008,
0xe00: 0x2008,
0xf00: 0x10202000,
0x80: 0x10200000,
0x180: 0x10202008,
0x280: 0x8,
0x380: 0x200000,
0x480: 0x202008,
0x580: 0x10000008,
0x680: 0x10002000,
0x780: 0x2008,
0x880: 0x200008,
0x980: 0x2000,
0xa80: 0x10002008,
0xb80: 0x10200008,
0xc80: 0x0,
0xd80: 0x10202000,
0xe80: 0x202000,
0xf80: 0x10000000,
0x1000: 0x10002000,
0x1100: 0x10200008,
0x1200: 0x10202008,
0x1300: 0x2008,
0x1400: 0x200000,
0x1500: 0x10000000,
0x1600: 0x10000008,
0x1700: 0x202000,
0x1800: 0x202008,
0x1900: 0x0,
0x1a00: 0x8,
0x1b00: 0x10200000,
0x1c00: 0x2000,
0x1d00: 0x10002008,
0x1e00: 0x10202000,
0x1f00: 0x200008,
0x1080: 0x8,
0x1180: 0x202000,
0x1280: 0x200000,
0x1380: 0x10000008,
0x1480: 0x10002000,
0x1580: 0x2008,
0x1680: 0x10202008,
0x1780: 0x10200000,
0x1880: 0x10202000,
0x1980: 0x10200008,
0x1a80: 0x2000,
0x1b80: 0x202008,
0x1c80: 0x200008,
0x1d80: 0x0,
0x1e80: 0x10000000,
0x1f80: 0x10002008
},
{
0x0: 0x100000,
0x10: 0x2000401,
0x20: 0x400,
0x30: 0x100401,
0x40: 0x2100401,
0x50: 0x0,
0x60: 0x1,
0x70: 0x2100001,
0x80: 0x2000400,
0x90: 0x100001,
0xa0: 0x2000001,
0xb0: 0x2100400,
0xc0: 0x2100000,
0xd0: 0x401,
0xe0: 0x100400,
0xf0: 0x2000000,
0x8: 0x2100001,
0x18: 0x0,
0x28: 0x2000401,
0x38: 0x2100400,
0x48: 0x100000,
0x58: 0x2000001,
0x68: 0x2000000,
0x78: 0x401,
0x88: 0x100401,
0x98: 0x2000400,
0xa8: 0x2100000,
0xb8: 0x100001,
0xc8: 0x400,
0xd8: 0x2100401,
0xe8: 0x1,
0xf8: 0x100400,
0x100: 0x2000000,
0x110: 0x100000,
0x120: 0x2000401,
0x130: 0x2100001,
0x140: 0x100001,
0x150: 0x2000400,
0x160: 0x2100400,
0x170: 0x100401,
0x180: 0x401,
0x190: 0x2100401,
0x1a0: 0x100400,
0x1b0: 0x1,
0x1c0: 0x0,
0x1d0: 0x2100000,
0x1e0: 0x2000001,
0x1f0: 0x400,
0x108: 0x100400,
0x118: 0x2000401,
0x128: 0x2100001,
0x138: 0x1,
0x148: 0x2000000,
0x158: 0x100000,
0x168: 0x401,
0x178: 0x2100400,
0x188: 0x2000001,
0x198: 0x2100000,
0x1a8: 0x0,
0x1b8: 0x2100401,
0x1c8: 0x100401,
0x1d8: 0x400,
0x1e8: 0x2000400,
0x1f8: 0x100001
},
{
0x0: 0x8000820,
0x1: 0x20000,
0x2: 0x8000000,
0x3: 0x20,
0x4: 0x20020,
0x5: 0x8020820,
0x6: 0x8020800,
0x7: 0x800,
0x8: 0x8020000,
0x9: 0x8000800,
0xa: 0x20800,
0xb: 0x8020020,
0xc: 0x820,
0xd: 0x0,
0xe: 0x8000020,
0xf: 0x20820,
0x80000000: 0x800,
0x80000001: 0x8020820,
0x80000002: 0x8000820,
0x80000003: 0x8000000,
0x80000004: 0x8020000,
0x80000005: 0x20800,
0x80000006: 0x20820,
0x80000007: 0x20,
0x80000008: 0x8000020,
0x80000009: 0x820,
0x8000000a: 0x20020,
0x8000000b: 0x8020800,
0x8000000c: 0x0,
0x8000000d: 0x8020020,
0x8000000e: 0x8000800,
0x8000000f: 0x20000,
0x10: 0x20820,
0x11: 0x8020800,
0x12: 0x20,
0x13: 0x800,
0x14: 0x8000800,
0x15: 0x8000020,
0x16: 0x8020020,
0x17: 0x20000,
0x18: 0x0,
0x19: 0x20020,
0x1a: 0x8020000,
0x1b: 0x8000820,
0x1c: 0x8020820,
0x1d: 0x20800,
0x1e: 0x820,
0x1f: 0x8000000,
0x80000010: 0x20000,
0x80000011: 0x800,
0x80000012: 0x8020020,
0x80000013: 0x20820,
0x80000014: 0x20,
0x80000015: 0x8020000,
0x80000016: 0x8000000,
0x80000017: 0x8000820,
0x80000018: 0x8020820,
0x80000019: 0x8000020,
0x8000001a: 0x8000800,
0x8000001b: 0x0,
0x8000001c: 0x20800,
0x8000001d: 0x820,
0x8000001e: 0x20020,
0x8000001f: 0x8020800
}
];
// Masks that select the SBOX input
var SBOX_MASK = [
0xf8000001, 0x1f800000, 0x01f80000, 0x001f8000,
0x0001f800, 0x00001f80, 0x000001f8, 0x8000001f
];
/**
* DES block cipher algorithm.
*/
var DES = C_algo.DES = BlockCipher.extend({
_doReset: function () {
// Shortcuts
var key = this._key;
var keyWords = key.words;
// Select 56 bits according to PC1
var keyBits = [];
for (var i = 0; i < 56; i++) {
var keyBitPos = PC1[i] - 1;
keyBits[i] = (keyWords[keyBitPos >>> 5] >>> (31 - keyBitPos % 32)) & 1;
}
// Assemble 16 subkeys
var subKeys = this._subKeys = [];
for (var nSubKey = 0; nSubKey < 16; nSubKey++) {
// Create subkey
var subKey = subKeys[nSubKey] = [];
// Shortcut
var bitShift = BIT_SHIFTS[nSubKey];
// Select 48 bits according to PC2
for (var i = 0; i < 24; i++) {
// Select from the left 28 key bits
subKey[(i / 6) | 0] |= keyBits[((PC2[i] - 1) + bitShift) % 28] << (31 - i % 6);
// Select from the right 28 key bits
subKey[4 + ((i / 6) | 0)] |= keyBits[28 + (((PC2[i + 24] - 1) + bitShift) % 28)] << (31 - i % 6);
}
// Since each subkey is applied to an expanded 32-bit input,
// the subkey can be broken into 8 values scaled to 32-bits,
// which allows the key to be used without expansion
subKey[0] = (subKey[0] << 1) | (subKey[0] >>> 31);
for (var i = 1; i < 7; i++) {
subKey[i] = subKey[i] >>> ((i - 1) * 4 + 3);
}
subKey[7] = (subKey[7] << 5) | (subKey[7] >>> 27);
}
// Compute inverse subkeys
var invSubKeys = this._invSubKeys = [];
for (var i = 0; i < 16; i++) {
invSubKeys[i] = subKeys[15 - i];
}
},
encryptBlock: function (M, offset) {
this._doCryptBlock(M, offset, this._subKeys);
},
decryptBlock: function (M, offset) {
this._doCryptBlock(M, offset, this._invSubKeys);
},
_doCryptBlock: function (M, offset, subKeys) {
// Get input
this._lBlock = M[offset];
this._rBlock = M[offset + 1];
// Initial permutation
exchangeLR.call(this, 4, 0x0f0f0f0f);
exchangeLR.call(this, 16, 0x0000ffff);
exchangeRL.call(this, 2, 0x33333333);
exchangeRL.call(this, 8, 0x00ff00ff);
exchangeLR.call(this, 1, 0x55555555);
// Rounds
for (var round = 0; round < 16; round++) {
// Shortcuts
var subKey = subKeys[round];
var lBlock = this._lBlock;
var rBlock = this._rBlock;
// Feistel function
var f = 0;
for (var i = 0; i < 8; i++) {
f |= SBOX_P[i][((rBlock ^ subKey[i]) & SBOX_MASK[i]) >>> 0];
}
this._lBlock = rBlock;
this._rBlock = lBlock ^ f;
}
// Undo swap from last round
var t = this._lBlock;
this._lBlock = this._rBlock;
this._rBlock = t;
// Final permutation
exchangeLR.call(this, 1, 0x55555555);
exchangeRL.call(this, 8, 0x00ff00ff);
exchangeRL.call(this, 2, 0x33333333);
exchangeLR.call(this, 16, 0x0000ffff);
exchangeLR.call(this, 4, 0x0f0f0f0f);
// Set output
M[offset] = this._lBlock;
M[offset + 1] = this._rBlock;
},
keySize: 64/32,
ivSize: 64/32,
blockSize: 64/32
});
// Swap bits across the left and right words
function exchangeLR(offset, mask) {
var t = ((this._lBlock >>> offset) ^ this._rBlock) & mask;
this._rBlock ^= t;
this._lBlock ^= t << offset;
}
function exchangeRL(offset, mask) {
var t = ((this._rBlock >>> offset) ^ this._lBlock) & mask;
this._lBlock ^= t;
this._rBlock ^= t << offset;
}
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.DES.encrypt(message, key, cfg);
* var plaintext = CryptoJS.DES.decrypt(ciphertext, key, cfg);
*/
C.DES = BlockCipher._createHelper(DES);
/**
* Triple-DES block cipher algorithm.
*/
var TripleDES = C_algo.TripleDES = BlockCipher.extend({
_doReset: function () {
// Shortcuts
var key = this._key;
var keyWords = key.words;
// Create DES instances
this._des1 = DES.createEncryptor(WordArray.create(keyWords.slice(0, 2)));
this._des2 = DES.createEncryptor(WordArray.create(keyWords.slice(2, 4)));
this._des3 = DES.createEncryptor(WordArray.create(keyWords.slice(4, 6)));
},
encryptBlock: function (M, offset) {
this._des1.encryptBlock(M, offset);
this._des2.decryptBlock(M, offset);
this._des3.encryptBlock(M, offset);
},
decryptBlock: function (M, offset) {
this._des3.decryptBlock(M, offset);
this._des2.encryptBlock(M, offset);
this._des1.decryptBlock(M, offset);
},
keySize: 192/32,
ivSize: 64/32,
blockSize: 64/32
});
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.TripleDES.encrypt(message, key, cfg);
* var plaintext = CryptoJS.TripleDES.decrypt(ciphertext, key, cfg);
*/
C.TripleDES = BlockCipher._createHelper(TripleDES);
}());
return CryptoJS.TripleDES;
}));
},{"./cipher-core":21,"./core":22,"./enc-base64":23,"./evpkdf":25,"./md5":30}],53:[function(require,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function (undefined) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var X32WordArray = C_lib.WordArray;
/**
* x64 namespace.
*/
var C_x64 = C.x64 = {};
/**
* A 64-bit word.
*/
var X64Word = C_x64.Word = Base.extend({
/**
* Initializes a newly created 64-bit word.
*
* @param {number} high The high 32 bits.
* @param {number} low The low 32 bits.
*
* @example
*
* var x64Word = CryptoJS.x64.Word.create(0x00010203, 0x04050607);
*/
init: function (high, low) {
this.high = high;
this.low = low;
}
/**
* Bitwise NOTs this word.
*
* @return {X64Word} A new x64-Word object after negating.
*
* @example
*
* var negated = x64Word.not();
*/
// not: function () {
// var high = ~this.high;
// var low = ~this.low;
// return X64Word.create(high, low);
// },
/**
* Bitwise ANDs this word with the passed word.
*
* @param {X64Word} word The x64-Word to AND with this word.
*
* @return {X64Word} A new x64-Word object after ANDing.
*
* @example
*
* var anded = x64Word.and(anotherX64Word);
*/
// and: function (word) {
// var high = this.high & word.high;
// var low = this.low & word.low;
// return X64Word.create(high, low);
// },
/**
* Bitwise ORs this word with the passed word.
*
* @param {X64Word} word The x64-Word to OR with this word.
*
* @return {X64Word} A new x64-Word object after ORing.
*
* @example
*
* var ored = x64Word.or(anotherX64Word);
*/
// or: function (word) {
// var high = this.high | word.high;
// var low = this.low | word.low;
// return X64Word.create(high, low);
// },
/**
* Bitwise XORs this word with the passed word.
*
* @param {X64Word} word The x64-Word to XOR with this word.
*
* @return {X64Word} A new x64-Word object after XORing.
*
* @example
*
* var xored = x64Word.xor(anotherX64Word);
*/
// xor: function (word) {
// var high = this.high ^ word.high;
// var low = this.low ^ word.low;
// return X64Word.create(high, low);
// },
/**
* Shifts this word n bits to the left.
*
* @param {number} n The number of bits to shift.
*
* @return {X64Word} A new x64-Word object after shifting.
*
* @example
*
* var shifted = x64Word.shiftL(25);
*/
// shiftL: function (n) {
// if (n < 32) {
// var high = (this.high << n) | (this.low >>> (32 - n));
// var low = this.low << n;
// } else {
// var high = this.low << (n - 32);
// var low = 0;
// }
// return X64Word.create(high, low);
// },
/**
* Shifts this word n bits to the right.
*
* @param {number} n The number of bits to shift.
*
* @return {X64Word} A new x64-Word object after shifting.
*
* @example
*
* var shifted = x64Word.shiftR(7);
*/
// shiftR: function (n) {
// if (n < 32) {
// var low = (this.low >>> n) | (this.high << (32 - n));
// var high = this.high >>> n;
// } else {
// var low = this.high >>> (n - 32);
// var high = 0;
// }
// return X64Word.create(high, low);
// },
/**
* Rotates this word n bits to the left.
*
* @param {number} n The number of bits to rotate.
*
* @return {X64Word} A new x64-Word object after rotating.
*
* @example
*
* var rotated = x64Word.rotL(25);
*/
// rotL: function (n) {
// return this.shiftL(n).or(this.shiftR(64 - n));
// },
/**
* Rotates this word n bits to the right.
*
* @param {number} n The number of bits to rotate.
*
* @return {X64Word} A new x64-Word object after rotating.
*
* @example
*
* var rotated = x64Word.rotR(7);
*/
// rotR: function (n) {
// return this.shiftR(n).or(this.shiftL(64 - n));
// },
/**
* Adds this word with the passed word.
*
* @param {X64Word} word The x64-Word to add with this word.
*
* @return {X64Word} A new x64-Word object after adding.
*
* @example
*
* var added = x64Word.add(anotherX64Word);
*/
// add: function (word) {
// var low = (this.low + word.low) | 0;
// var carry = (low >>> 0) < (this.low >>> 0) ? 1 : 0;
// var high = (this.high + word.high + carry) | 0;
// return X64Word.create(high, low);
// }
});
/**
* An array of 64-bit words.
*
* @property {Array} words The array of CryptoJS.x64.Word objects.
* @property {number} sigBytes The number of significant bytes in this word array.
*/
var X64WordArray = C_x64.WordArray = Base.extend({
/**
* Initializes a newly created word array.
*
* @param {Array} words (Optional) An array of CryptoJS.x64.Word objects.
* @param {number} sigBytes (Optional) The number of significant bytes in the words.
*
* @example
*
* var wordArray = CryptoJS.x64.WordArray.create();
*
* var wordArray = CryptoJS.x64.WordArray.create([
* CryptoJS.x64.Word.create(0x00010203, 0x04050607),
* CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f)
* ]);
*
* var wordArray = CryptoJS.x64.WordArray.create([
* CryptoJS.x64.Word.create(0x00010203, 0x04050607),
* CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f)
* ], 10);
*/
init: function (words, sigBytes) {
words = this.words = words || [];
if (sigBytes != undefined) {
this.sigBytes = sigBytes;
} else {
this.sigBytes = words.length * 8;
}
},
/**
* Converts this 64-bit word array to a 32-bit word array.
*
* @return {CryptoJS.lib.WordArray} This word array's data as a 32-bit word array.
*
* @example
*
* var x32WordArray = x64WordArray.toX32();
*/
toX32: function () {
// Shortcuts
var x64Words = this.words;
var x64WordsLength = x64Words.length;
// Convert
var x32Words = [];
for (var i = 0; i < x64WordsLength; i++) {
var x64Word = x64Words[i];
x32Words.push(x64Word.high);
x32Words.push(x64Word.low);
}
return X32WordArray.create(x32Words, this.sigBytes);
},
/**
* Creates a copy of this word array.
*
* @return {X64WordArray} The clone.
*
* @example
*
* var clone = x64WordArray.clone();
*/
clone: function () {
var clone = Base.clone.call(this);
// Clone "words" array
var words = clone.words = this.words.slice(0);
// Clone each X64Word object
var wordsLength = words.length;
for (var i = 0; i < wordsLength; i++) {
words[i] = words[i].clone();
}
return clone;
}
});
}());
return CryptoJS;
}));
},{"./core":22}],54:[function(require,module,exports){
/** @license MIT License (c) copyright 2013-2014 original author or authors */
/**
* Collection of helper functions for wrapping and executing 'traditional'
* synchronous functions in a promise interface.
*
* @author Brian Cavalier
* @contributor Renato Zannon
*/
(function(define) {
define(function(require) {
var when = require('./when');
var attempt = when['try'];
var _liftAll = require('./lib/liftAll');
var _apply = require('./lib/apply')(when.Promise);
var slice = Array.prototype.slice;
return {
lift: lift,
liftAll: liftAll,
call: attempt,
apply: apply,
compose: compose
};
/**
* Takes a function and an optional array of arguments (that might be promises),
* and calls the function. The return value is a promise whose resolution
* depends on the value returned by the function.
* @param {function} f function to be called
* @param {Array} [args] array of arguments to func
* @returns {Promise} promise for the return value of func
*/
function apply(f, args) {
// slice args just in case the caller passed an Arguments instance
return _apply(f, this, args == null ? [] : slice.call(args));
}
/**
* Takes a 'regular' function and returns a version of that function that
* returns a promise instead of a plain value, and handles thrown errors by
* returning a rejected promise. Also accepts a list of arguments to be
* prepended to the new function, as does Function.prototype.bind.
*
* The resulting function is promise-aware, in the sense that it accepts
* promise arguments, and waits for their resolution.
* @param {Function} f function to be bound
* @param {...*} [args] arguments to be prepended for the new function @deprecated
* @returns {Function} a promise-returning function
*/
function lift(f /*, args... */) {
var args = arguments.length > 1 ? slice.call(arguments, 1) : [];
return function() {
return _apply(f, this, args.concat(slice.call(arguments)));
};
}
/**
* Lift all the functions/methods on src
* @param {object|function} src source whose functions will be lifted
* @param {function?} combine optional function for customizing the lifting
* process. It is passed dst, the lifted function, and the property name of
* the original function on src.
* @param {(object|function)?} dst option destination host onto which to place lifted
* functions. If not provided, liftAll returns a new object.
* @returns {*} If dst is provided, returns dst with lifted functions as
* properties. If dst not provided, returns a new object with lifted functions.
*/
function liftAll(src, combine, dst) {
return _liftAll(lift, combine, dst, src);
}
/**
* Composes multiple functions by piping their return values. It is
* transparent to whether the functions return 'regular' values or promises:
* the piped argument is always a resolved value. If one of the functions
* throws or returns a rejected promise, the composed promise will be also
* rejected.
*
* The arguments (or promises to arguments) given to the returned function (if
* any), are passed directly to the first function on the 'pipeline'.
* @param {Function} f the function to which the arguments will be passed
* @param {...Function} [funcs] functions that will be composed, in order
* @returns {Function} a promise-returning composition of the functions
*/
function compose(f /*, funcs... */) {
var funcs = slice.call(arguments, 1);
return function() {
var thisArg = this;
var args = slice.call(arguments);
var firstPromise = attempt.apply(thisArg, [f].concat(args));
return when.reduce(funcs, function(arg, func) {
return func.call(thisArg, arg);
}, firstPromise);
};
}
});
})(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); });
},{"./lib/apply":58,"./lib/liftAll":70,"./when":78}],55:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2014 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
(function(define) { 'use strict';
define(function (require) {
var makePromise = require('./makePromise');
var Scheduler = require('./Scheduler');
var async = require('./env').asap;
return makePromise({
scheduler: new Scheduler(async)
});
});
})(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); });
},{"./Scheduler":56,"./env":68,"./makePromise":71}],56:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2014 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
(function(define) { 'use strict';
define(function() {
// Credit to Twisol (https://github.com/Twisol) for suggesting
// this type of extensible queue + trampoline approach for next-tick conflation.
/**
* Async task scheduler
* @param {function} async function to schedule a single async function
* @constructor
*/
function Scheduler(async) {
this._async = async;
this._running = false;
this._queue = this;
this._queueLen = 0;
this._afterQueue = {};
this._afterQueueLen = 0;
var self = this;
this.drain = function() {
self._drain();
};
}
/**
* Enqueue a task
* @param {{ run:function }} task
*/
Scheduler.prototype.enqueue = function(task) {
this._queue[this._queueLen++] = task;
this.run();
};
/**
* Enqueue a task to run after the main task queue
* @param {{ run:function }} task
*/
Scheduler.prototype.afterQueue = function(task) {
this._afterQueue[this._afterQueueLen++] = task;
this.run();
};
Scheduler.prototype.run = function() {
if (!this._running) {
this._running = true;
this._async(this.drain);
}
};
/**
* Drain the handler queue entirely, and then the after queue
*/
Scheduler.prototype._drain = function() {
var i = 0;
for (; i < this._queueLen; ++i) {
this._queue[i].run();
this._queue[i] = void 0;
}
this._queueLen = 0;
this._running = false;
for (i = 0; i < this._afterQueueLen; ++i) {
this._afterQueue[i].run();
this._afterQueue[i] = void 0;
}
this._afterQueueLen = 0;
};
return Scheduler;
});
}(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
},{}],57:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2014 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
(function(define) { 'use strict';
define(function() {
/**
* Custom error type for promises rejected by promise.timeout
* @param {string} message
* @constructor
*/
function TimeoutError (message) {
Error.call(this);
this.message = message;
this.name = TimeoutError.name;
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, TimeoutError);
}
}
TimeoutError.prototype = Object.create(Error.prototype);
TimeoutError.prototype.constructor = TimeoutError;
return TimeoutError;
});
}(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
},{}],58:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2014 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
(function(define) { 'use strict';
define(function() {
makeApply.tryCatchResolve = tryCatchResolve;
return makeApply;
function makeApply(Promise, call) {
if(arguments.length < 2) {
call = tryCatchResolve;
}
return apply;
function apply(f, thisArg, args) {
var p = Promise._defer();
var l = args.length;
var params = new Array(l);
callAndResolve({ f:f, thisArg:thisArg, args:args, params:params, i:l-1, call:call }, p._handler);
return p;
}
function callAndResolve(c, h) {
if(c.i < 0) {
return call(c.f, c.thisArg, c.params, h);
}
var handler = Promise._handler(c.args[c.i]);
handler.fold(callAndResolveNext, c, void 0, h);
}
function callAndResolveNext(c, x, h) {
c.params[c.i] = x;
c.i -= 1;
callAndResolve(c, h);
}
}
function tryCatchResolve(f, thisArg, args, resolver) {
try {
resolver.resolve(f.apply(thisArg, args));
} catch(e) {
resolver.reject(e);
}
}
});
}(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
},{}],59:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2014 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
(function(define) { 'use strict';
define(function(require) {
var state = require('../state');
var applier = require('../apply');
return function array(Promise) {
var applyFold = applier(Promise);
var toPromise = Promise.resolve;
var all = Promise.all;
var ar = Array.prototype.reduce;
var arr = Array.prototype.reduceRight;
var slice = Array.prototype.slice;
// Additional array combinators
Promise.any = any;
Promise.some = some;
Promise.settle = settle;
Promise.map = map;
Promise.filter = filter;
Promise.reduce = reduce;
Promise.reduceRight = reduceRight;
/**
* When this promise fulfills with an array, do
* onFulfilled.apply(void 0, array)
* @param {function} onFulfilled function to apply
* @returns {Promise} promise for the result of applying onFulfilled
*/
Promise.prototype.spread = function(onFulfilled) {
return this.then(all).then(function(array) {
return onFulfilled.apply(this, array);
});
};
return Promise;
/**
* One-winner competitive race.
* Return a promise that will fulfill when one of the promises
* in the input array fulfills, or will reject when all promises
* have rejected.
* @param {array} promises
* @returns {Promise} promise for the first fulfilled value
*/
function any(promises) {
var p = Promise._defer();
var resolver = p._handler;
var l = promises.length>>>0;
var pending = l;
var errors = [];
for (var h, x, i = 0; i < l; ++i) {
x = promises[i];
if(x === void 0 && !(i in promises)) {
--pending;
continue;
}
h = Promise._handler(x);
if(h.state() > 0) {
resolver.become(h);
Promise._visitRemaining(promises, i, h);
break;
} else {
h.visit(resolver, handleFulfill, handleReject);
}
}
if(pending === 0) {
resolver.reject(new RangeError('any(): array must not be empty'));
}
return p;
function handleFulfill(x) {
/*jshint validthis:true*/
errors = null;
this.resolve(x); // this === resolver
}
function handleReject(e) {
/*jshint validthis:true*/
if(this.resolved) { // this === resolver
return;
}
errors.push(e);
if(--pending === 0) {
this.reject(errors);
}
}
}
/**
* N-winner competitive race
* Return a promise that will fulfill when n input promises have
* fulfilled, or will reject when it becomes impossible for n
* input promises to fulfill (ie when promises.length - n + 1
* have rejected)
* @param {array} promises
* @param {number} n
* @returns {Promise} promise for the earliest n fulfillment values
*
* @deprecated
*/
function some(promises, n) {
/*jshint maxcomplexity:7*/
var p = Promise._defer();
var resolver = p._handler;
var results = [];
var errors = [];
var l = promises.length>>>0;
var nFulfill = 0;
var nReject;
var x, i; // reused in both for() loops
// First pass: count actual array items
for(i=0; i<l; ++i) {
x = promises[i];
if(x === void 0 && !(i in promises)) {
continue;
}
++nFulfill;
}
// Compute actual goals
n = Math.max(n, 0);
nReject = (nFulfill - n + 1);
nFulfill = Math.min(n, nFulfill);
if(n > nFulfill) {
resolver.reject(new RangeError('some(): array must contain at least '
+ n + ' item(s), but had ' + nFulfill));
} else if(nFulfill === 0) {
resolver.resolve(results);
}
// Second pass: observe each array item, make progress toward goals
for(i=0; i<l; ++i) {
x = promises[i];
if(x === void 0 && !(i in promises)) {
continue;
}
Promise._handler(x).visit(resolver, fulfill, reject, resolver.notify);
}
return p;
function fulfill(x) {
/*jshint validthis:true*/
if(this.resolved) { // this === resolver
return;
}
results.push(x);
if(--nFulfill === 0) {
errors = null;
this.resolve(results);
}
}
function reject(e) {
/*jshint validthis:true*/
if(this.resolved) { // this === resolver
return;
}
errors.push(e);
if(--nReject === 0) {
results = null;
this.reject(errors);
}
}
}
/**
* Apply f to the value of each promise in a list of promises
* and return a new list containing the results.
* @param {array} promises
* @param {function(x:*, index:Number):*} f mapping function
* @returns {Promise}
*/
function map(promises, f) {
return Promise._traverse(f, promises);
}
/**
* Filter the provided array of promises using the provided predicate. Input may
* contain promises and values
* @param {Array} promises array of promises and values
* @param {function(x:*, index:Number):boolean} predicate filtering predicate.
* Must return truthy (or promise for truthy) for items to retain.
* @returns {Promise} promise that will fulfill with an array containing all items
* for which predicate returned truthy.
*/
function filter(promises, predicate) {
var a = slice.call(promises);
return Promise._traverse(predicate, a).then(function(keep) {
return filterSync(a, keep);
});
}
function filterSync(promises, keep) {
// Safe because we know all promises have fulfilled if we've made it this far
var l = keep.length;
var filtered = new Array(l);
for(var i=0, j=0; i<l; ++i) {
if(keep[i]) {
filtered[j++] = Promise._handler(promises[i]).value;
}
}
filtered.length = j;
return filtered;
}
/**
* Return a promise that will always fulfill with an array containing
* the outcome states of all input promises. The returned promise
* will never reject.
* @param {Array} promises
* @returns {Promise} promise for array of settled state descriptors
*/
function settle(promises) {
return all(promises.map(settleOne));
}
function settleOne(p) {
var h = Promise._handler(p);
if(h.state() === 0) {
return toPromise(p).then(state.fulfilled, state.rejected);
}
h._unreport();
return state.inspect(h);
}
/**
* Traditional reduce function, similar to `Array.prototype.reduce()`, but
* input may contain promises and/or values, and reduceFunc
* may return either a value or a promise, *and* initialValue may
* be a promise for the starting value.
* @param {Array|Promise} promises array or promise for an array of anything,
* may contain a mix of promises and values.
* @param {function(accumulated:*, x:*, index:Number):*} f reduce function
* @returns {Promise} that will resolve to the final reduced value
*/
function reduce(promises, f /*, initialValue */) {
return arguments.length > 2 ? ar.call(promises, liftCombine(f), arguments[2])
: ar.call(promises, liftCombine(f));
}
/**
* Traditional reduce function, similar to `Array.prototype.reduceRight()`, but
* input may contain promises and/or values, and reduceFunc
* may return either a value or a promise, *and* initialValue may
* be a promise for the starting value.
* @param {Array|Promise} promises array or promise for an array of anything,
* may contain a mix of promises and values.
* @param {function(accumulated:*, x:*, index:Number):*} f reduce function
* @returns {Promise} that will resolve to the final reduced value
*/
function reduceRight(promises, f /*, initialValue */) {
return arguments.length > 2 ? arr.call(promises, liftCombine(f), arguments[2])
: arr.call(promises, liftCombine(f));
}
function liftCombine(f) {
return function(z, x, i) {
return applyFold(f, void 0, [z,x,i]);
};
}
};
});
}(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
},{"../apply":58,"../state":72}],60:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2014 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
(function(define) { 'use strict';
define(function() {
return function flow(Promise) {
var resolve = Promise.resolve;
var reject = Promise.reject;
var origCatch = Promise.prototype['catch'];
/**
* Handle the ultimate fulfillment value or rejection reason, and assume
* responsibility for all errors. If an error propagates out of result
* or handleFatalError, it will be rethrown to the host, resulting in a
* loud stack track on most platforms and a crash on some.
* @param {function?} onResult
* @param {function?} onError
* @returns {undefined}
*/
Promise.prototype.done = function(onResult, onError) {
this._handler.visit(this._handler.receiver, onResult, onError);
};
/**
* Add Error-type and predicate matching to catch. Examples:
* promise.catch(TypeError, handleTypeError)
* .catch(predicate, handleMatchedErrors)
* .catch(handleRemainingErrors)
* @param onRejected
* @returns {*}
*/
Promise.prototype['catch'] = Promise.prototype.otherwise = function(onRejected) {
if (arguments.length < 2) {
return origCatch.call(this, onRejected);
}
if(typeof onRejected !== 'function') {
return this.ensure(rejectInvalidPredicate);
}
return origCatch.call(this, createCatchFilter(arguments[1], onRejected));
};
/**
* Wraps the provided catch handler, so that it will only be called
* if the predicate evaluates truthy
* @param {?function} handler
* @param {function} predicate
* @returns {function} conditional catch handler
*/
function createCatchFilter(handler, predicate) {
return function(e) {
return evaluatePredicate(e, predicate)
? handler.call(this, e)
: reject(e);
};
}
/**
* Ensures that onFulfilledOrRejected will be called regardless of whether
* this promise is fulfilled or rejected. onFulfilledOrRejected WILL NOT
* receive the promises' value or reason. Any returned value will be disregarded.
* onFulfilledOrRejected may throw or return a rejected promise to signal
* an additional error.
* @param {function} handler handler to be called regardless of
* fulfillment or rejection
* @returns {Promise}
*/
Promise.prototype['finally'] = Promise.prototype.ensure = function(handler) {
if(typeof handler !== 'function') {
return this;
}
return this.then(function(x) {
return runSideEffect(handler, this, identity, x);
}, function(e) {
return runSideEffect(handler, this, reject, e);
});
};
function runSideEffect (handler, thisArg, propagate, value) {
var result = handler.call(thisArg);
return maybeThenable(result)
? propagateValue(result, propagate, value)
: propagate(value);
}
function propagateValue (result, propagate, x) {
return resolve(result).then(function () {
return propagate(x);
});
}
/**
* Recover from a failure by returning a defaultValue. If defaultValue
* is a promise, it's fulfillment value will be used. If defaultValue is
* a promise that rejects, the returned promise will reject with the
* same reason.
* @param {*} defaultValue
* @returns {Promise} new promise
*/
Promise.prototype['else'] = Promise.prototype.orElse = function(defaultValue) {
return this.then(void 0, function() {
return defaultValue;
});
};
/**
* Shortcut for .then(function() { return value; })
* @param {*} value
* @return {Promise} a promise that:
* - is fulfilled if value is not a promise, or
* - if value is a promise, will fulfill with its value, or reject
* with its reason.
*/
Promise.prototype['yield'] = function(value) {
return this.then(function() {
return value;
});
};
/**
* Runs a side effect when this promise fulfills, without changing the
* fulfillment value.
* @param {function} onFulfilledSideEffect
* @returns {Promise}
*/
Promise.prototype.tap = function(onFulfilledSideEffect) {
return this.then(onFulfilledSideEffect)['yield'](this);
};
return Promise;
};
function rejectInvalidPredicate() {
throw new TypeError('catch predicate must be a function');
}
function evaluatePredicate(e, predicate) {
return isError(predicate) ? e instanceof predicate : predicate(e);
}
function isError(predicate) {
return predicate === Error
|| (predicate != null && predicate.prototype instanceof Error);
}
function maybeThenable(x) {
return (typeof x === 'object' || typeof x === 'function') && x !== null;
}
function identity(x) {
return x;
}
});
}(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
},{}],61:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2014 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
/** @author Jeff Escalante */
(function(define) { 'use strict';
define(function() {
return function fold(Promise) {
Promise.prototype.fold = function(f, z) {
var promise = this._beget();
this._handler.fold(function(z, x, to) {
Promise._handler(z).fold(function(x, z, to) {
to.resolve(f.call(this, z, x));
}, x, this, to);
}, z, promise._handler.receiver, promise._handler);
return promise;
};
return Promise;
};
});
}(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
},{}],62:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2014 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
(function(define) { 'use strict';
define(function(require) {
var inspect = require('../state').inspect;
return function inspection(Promise) {
Promise.prototype.inspect = function() {
return inspect(Promise._handler(this));
};
return Promise;
};
});
}(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
},{"../state":72}],63:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2014 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
(function(define) { 'use strict';
define(function() {
return function generate(Promise) {
var resolve = Promise.resolve;
Promise.iterate = iterate;
Promise.unfold = unfold;
return Promise;
/**
* @deprecated Use github.com/cujojs/most streams and most.iterate
* Generate a (potentially infinite) stream of promised values:
* x, f(x), f(f(x)), etc. until condition(x) returns true
* @param {function} f function to generate a new x from the previous x
* @param {function} condition function that, given the current x, returns
* truthy when the iterate should stop
* @param {function} handler function to handle the value produced by f
* @param {*|Promise} x starting value, may be a promise
* @return {Promise} the result of the last call to f before
* condition returns true
*/
function iterate(f, condition, handler, x) {
return unfold(function(x) {
return [x, f(x)];
}, condition, handler, x);
}
/**
* @deprecated Use github.com/cujojs/most streams and most.unfold
* Generate a (potentially infinite) stream of promised values
* by applying handler(generator(seed)) iteratively until
* condition(seed) returns true.
* @param {function} unspool function that generates a [value, newSeed]
* given a seed.
* @param {function} condition function that, given the current seed, returns
* truthy when the unfold should stop
* @param {function} handler function to handle the value produced by unspool
* @param x {*|Promise} starting value, may be a promise
* @return {Promise} the result of the last value produced by unspool before
* condition returns true
*/
function unfold(unspool, condition, handler, x) {
return resolve(x).then(function(seed) {
return resolve(condition(seed)).then(function(done) {
return done ? seed : resolve(unspool(seed)).spread(next);
});
});
function next(item, newSeed) {
return resolve(handler(item)).then(function() {
return unfold(unspool, condition, handler, newSeed);
});
}
}
};
});
}(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
},{}],64:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2014 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
(function(define) { 'use strict';
define(function() {
return function progress(Promise) {
/**
* @deprecated
* Register a progress handler for this promise
* @param {function} onProgress
* @returns {Promise}
*/
Promise.prototype.progress = function(onProgress) {
return this.then(void 0, void 0, onProgress);
};
return Promise;
};
});
}(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
},{}],65:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2014 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
(function(define) { 'use strict';
define(function(require) {
var env = require('../env');
var TimeoutError = require('../TimeoutError');
function setTimeout(f, ms, x, y) {
return env.setTimer(function() {
f(x, y, ms);
}, ms);
}
return function timed(Promise) {
/**
* Return a new promise whose fulfillment value is revealed only
* after ms milliseconds
* @param {number} ms milliseconds
* @returns {Promise}
*/
Promise.prototype.delay = function(ms) {
var p = this._beget();
this._handler.fold(handleDelay, ms, void 0, p._handler);
return p;
};
function handleDelay(ms, x, h) {
setTimeout(resolveDelay, ms, x, h);
}
function resolveDelay(x, h) {
h.resolve(x);
}
/**
* Return a new promise that rejects after ms milliseconds unless
* this promise fulfills earlier, in which case the returned promise
* fulfills with the same value.
* @param {number} ms milliseconds
* @param {Error|*=} reason optional rejection reason to use, defaults
* to a TimeoutError if not provided
* @returns {Promise}
*/
Promise.prototype.timeout = function(ms, reason) {
var p = this._beget();
var h = p._handler;
var t = setTimeout(onTimeout, ms, reason, p._handler);
this._handler.visit(h,
function onFulfill(x) {
env.clearTimer(t);
this.resolve(x); // this = h
},
function onReject(x) {
env.clearTimer(t);
this.reject(x); // this = h
},
h.notify);
return p;
};
function onTimeout(reason, h, ms) {
var e = typeof reason === 'undefined'
? new TimeoutError('timed out after ' + ms + 'ms')
: reason;
h.reject(e);
}
return Promise;
};
});
}(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
},{"../TimeoutError":57,"../env":68}],66:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2014 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
(function(define) { 'use strict';
define(function(require) {
var setTimer = require('../env').setTimer;
var format = require('../format');
return function unhandledRejection(Promise) {
var logError = noop;
var logInfo = noop;
var localConsole;
if(typeof console !== 'undefined') {
// Alias console to prevent things like uglify's drop_console option from
// removing console.log/error. Unhandled rejections fall into the same
// category as uncaught exceptions, and build tools shouldn't silence them.
localConsole = console;
logError = typeof localConsole.error !== 'undefined'
? function (e) { localConsole.error(e); }
: function (e) { localConsole.log(e); };
logInfo = typeof localConsole.info !== 'undefined'
? function (e) { localConsole.info(e); }
: function (e) { localConsole.log(e); };
}
Promise.onPotentiallyUnhandledRejection = function(rejection) {
enqueue(report, rejection);
};
Promise.onPotentiallyUnhandledRejectionHandled = function(rejection) {
enqueue(unreport, rejection);
};
Promise.onFatalRejection = function(rejection) {
enqueue(throwit, rejection.value);
};
var tasks = [];
var reported = [];
var running = null;
function report(r) {
if(!r.handled) {
reported.push(r);
logError('Potentially unhandled rejection [' + r.id + '] ' + format.formatError(r.value));
}
}
function unreport(r) {
var i = reported.indexOf(r);
if(i >= 0) {
reported.splice(i, 1);
logInfo('Handled previous rejection [' + r.id + '] ' + format.formatObject(r.value));
}
}
function enqueue(f, x) {
tasks.push(f, x);
if(running === null) {
running = setTimer(flush, 0);
}
}
function flush() {
running = null;
while(tasks.length > 0) {
tasks.shift()(tasks.shift());
}
}
return Promise;
};
function throwit(e) {
throw e;
}
function noop() {}
});
}(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
},{"../env":68,"../format":69}],67:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2014 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
(function(define) { 'use strict';
define(function() {
return function addWith(Promise) {
/**
* Returns a promise whose handlers will be called with `this` set to
* the supplied receiver. Subsequent promises derived from the
* returned promise will also have their handlers called with receiver
* as `this`. Calling `with` with undefined or no arguments will return
* a promise whose handlers will again be called in the usual Promises/A+
* way (no `this`) thus safely undoing any previous `with` in the
* promise chain.
*
* WARNING: Promises returned from `with`/`withThis` are NOT Promises/A+
* compliant, specifically violating 2.2.5 (http://promisesaplus.com/#point-41)
*
* @param {object} receiver `this` value for all handlers attached to
* the returned promise.
* @returns {Promise}
*/
Promise.prototype['with'] = Promise.prototype.withThis = function(receiver) {
var p = this._beget();
var child = p._handler;
child.receiver = receiver;
this._handler.chain(child, receiver);
return p;
};
return Promise;
};
});
}(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
},{}],68:[function(require,module,exports){
(function (process){
/** @license MIT License (c) copyright 2010-2014 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
/*global process,document,setTimeout,clearTimeout,MutationObserver,WebKitMutationObserver*/
(function(define) { 'use strict';
define(function(require) {
/*jshint maxcomplexity:6*/
// Sniff "best" async scheduling option
// Prefer process.nextTick or MutationObserver, then check for
// setTimeout, and finally vertx, since its the only env that doesn't
// have setTimeout
var MutationObs;
var capturedSetTimeout = typeof setTimeout !== 'undefined' && setTimeout;
// Default env
var setTimer = function(f, ms) { return setTimeout(f, ms); };
var clearTimer = function(t) { return clearTimeout(t); };
var asap = function (f) { return capturedSetTimeout(f, 0); };
// Detect specific env
if (isNode()) { // Node
asap = function (f) { return process.nextTick(f); };
} else if (MutationObs = hasMutationObserver()) { // Modern browser
asap = initMutationObserver(MutationObs);
} else if (!capturedSetTimeout) { // vert.x
var vertxRequire = require;
var vertx = vertxRequire('vertx');
setTimer = function (f, ms) { return vertx.setTimer(ms, f); };
clearTimer = vertx.cancelTimer;
asap = vertx.runOnLoop || vertx.runOnContext;
}
return {
setTimer: setTimer,
clearTimer: clearTimer,
asap: asap
};
function isNode () {
return typeof process !== 'undefined' && process !== null &&
typeof process.nextTick === 'function';
}
function hasMutationObserver () {
return (typeof MutationObserver === 'function' && MutationObserver) ||
(typeof WebKitMutationObserver === 'function' && WebKitMutationObserver);
}
function initMutationObserver(MutationObserver) {
var scheduled;
var node = document.createTextNode('');
var o = new MutationObserver(run);
o.observe(node, { characterData: true });
function run() {
var f = scheduled;
scheduled = void 0;
f();
}
var i = 0;
return function (f) {
scheduled = f;
node.data = (i ^= 1);
};
}
});
}(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
}).call(this,require('_process'))
},{"_process":1}],69:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2014 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
(function(define) { 'use strict';
define(function() {
return {
formatError: formatError,
formatObject: formatObject,
tryStringify: tryStringify
};
/**
* Format an error into a string. If e is an Error and has a stack property,
* it's returned. Otherwise, e is formatted using formatObject, with a
* warning added about e not being a proper Error.
* @param {*} e
* @returns {String} formatted string, suitable for output to developers
*/
function formatError(e) {
var s = typeof e === 'object' && e !== null && e.stack ? e.stack : formatObject(e);
return e instanceof Error ? s : s + ' (WARNING: non-Error used)';
}
/**
* Format an object, detecting "plain" objects and running them through
* JSON.stringify if possible.
* @param {Object} o
* @returns {string}
*/
function formatObject(o) {
var s = String(o);
if(s === '[object Object]' && typeof JSON !== 'undefined') {
s = tryStringify(o, s);
}
return s;
}
/**
* Try to return the result of JSON.stringify(x). If that fails, return
* defaultValue
* @param {*} x
* @param {*} defaultValue
* @returns {String|*} JSON.stringify(x) or defaultValue
*/
function tryStringify(x, defaultValue) {
try {
return JSON.stringify(x);
} catch(e) {
return defaultValue;
}
}
});
}(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
},{}],70:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2014 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
(function(define) { 'use strict';
define(function() {
return function liftAll(liftOne, combine, dst, src) {
if(typeof combine === 'undefined') {
combine = defaultCombine;
}
return Object.keys(src).reduce(function(dst, key) {
var f = src[key];
return typeof f === 'function' ? combine(dst, liftOne(f), key) : dst;
}, typeof dst === 'undefined' ? defaultDst(src) : dst);
};
function defaultCombine(o, f, k) {
o[k] = f;
return o;
}
function defaultDst(src) {
return typeof src === 'function' ? src.bind() : Object.create(src);
}
});
}(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
},{}],71:[function(require,module,exports){
(function (process){
/** @license MIT License (c) copyright 2010-2014 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
(function(define) { 'use strict';
define(function() {
return function makePromise(environment) {
var tasks = environment.scheduler;
var emitRejection = initEmitRejection();
var objectCreate = Object.create ||
function(proto) {
function Child() {}
Child.prototype = proto;
return new Child();
};
/**
* Create a promise whose fate is determined by resolver
* @constructor
* @returns {Promise} promise
* @name Promise
*/
function Promise(resolver, handler) {
this._handler = resolver === Handler ? handler : init(resolver);
}
/**
* Run the supplied resolver
* @param resolver
* @returns {Pending}
*/
function init(resolver) {
var handler = new Pending();
try {
resolver(promiseResolve, promiseReject, promiseNotify);
} catch (e) {
promiseReject(e);
}
return handler;
/**
* Transition from pre-resolution state to post-resolution state, notifying
* all listeners of the ultimate fulfillment or rejection
* @param {*} x resolution value
*/
function promiseResolve (x) {
handler.resolve(x);
}
/**
* Reject this promise with reason, which will be used verbatim
* @param {Error|*} reason rejection reason, strongly suggested
* to be an Error type
*/
function promiseReject (reason) {
handler.reject(reason);
}
/**
* @deprecated
* Issue a progress event, notifying all progress listeners
* @param {*} x progress event payload to pass to all listeners
*/
function promiseNotify (x) {
handler.notify(x);
}
}
// Creation
Promise.resolve = resolve;
Promise.reject = reject;
Promise.never = never;
Promise._defer = defer;
Promise._handler = getHandler;
/**
* Returns a trusted promise. If x is already a trusted promise, it is
* returned, otherwise returns a new trusted Promise which follows x.
* @param {*} x
* @return {Promise} promise
*/
function resolve(x) {
return isPromise(x) ? x
: new Promise(Handler, new Async(getHandler(x)));
}
/**
* Return a reject promise with x as its reason (x is used verbatim)
* @param {*} x
* @returns {Promise} rejected promise
*/
function reject(x) {
return new Promise(Handler, new Async(new Rejected(x)));
}
/**
* Return a promise that remains pending forever
* @returns {Promise} forever-pending promise.
*/
function never() {
return foreverPendingPromise; // Should be frozen
}
/**
* Creates an internal {promise, resolver} pair
* @private
* @returns {Promise}
*/
function defer() {
return new Promise(Handler, new Pending());
}
// Transformation and flow control
/**
* Transform this promise's fulfillment value, returning a new Promise
* for the transformed result. If the promise cannot be fulfilled, onRejected
* is called with the reason. onProgress *may* be called with updates toward
* this promise's fulfillment.
* @param {function=} onFulfilled fulfillment handler
* @param {function=} onRejected rejection handler
* @param {function=} onProgress @deprecated progress handler
* @return {Promise} new promise
*/
Promise.prototype.then = function(onFulfilled, onRejected, onProgress) {
var parent = this._handler;
var state = parent.join().state();
if ((typeof onFulfilled !== 'function' && state > 0) ||
(typeof onRejected !== 'function' && state < 0)) {
// Short circuit: value will not change, simply share handler
return new this.constructor(Handler, parent);
}
var p = this._beget();
var child = p._handler;
parent.chain(child, parent.receiver, onFulfilled, onRejected, onProgress);
return p;
};
/**
* If this promise cannot be fulfilled due to an error, call onRejected to
* handle the error. Shortcut for .then(undefined, onRejected)
* @param {function?} onRejected
* @return {Promise}
*/
Promise.prototype['catch'] = function(onRejected) {
return this.then(void 0, onRejected);
};
/**
* Creates a new, pending promise of the same type as this promise
* @private
* @returns {Promise}
*/
Promise.prototype._beget = function() {
return begetFrom(this._handler, this.constructor);
};
function begetFrom(parent, Promise) {
var child = new Pending(parent.receiver, parent.join().context);
return new Promise(Handler, child);
}
// Array combinators
Promise.all = all;
Promise.race = race;
Promise._traverse = traverse;
/**
* Return a promise that will fulfill when all promises in the
* input array have fulfilled, or will reject when one of the
* promises rejects.
* @param {array} promises array of promises
* @returns {Promise} promise for array of fulfillment values
*/
function all(promises) {
return traverseWith(snd, null, promises);
}
/**
* Array<Promise<X>> -> Promise<Array<f(X)>>
* @private
* @param {function} f function to apply to each promise's value
* @param {Array} promises array of promises
* @returns {Promise} promise for transformed values
*/
function traverse(f, promises) {
return traverseWith(tryCatch2, f, promises);
}
function traverseWith(tryMap, f, promises) {
var handler = typeof f === 'function' ? mapAt : settleAt;
var resolver = new Pending();
var pending = promises.length >>> 0;
var results = new Array(pending);
for (var i = 0, x; i < promises.length && !resolver.resolved; ++i) {
x = promises[i];
if (x === void 0 && !(i in promises)) {
--pending;
continue;
}
traverseAt(promises, handler, i, x, resolver);
}
if(pending === 0) {
resolver.become(new Fulfilled(results));
}
return new Promise(Handler, resolver);
function mapAt(i, x, resolver) {
if(!resolver.resolved) {
traverseAt(promises, settleAt, i, tryMap(f, x, i), resolver);
}
}
function settleAt(i, x, resolver) {
results[i] = x;
if(--pending === 0) {
resolver.become(new Fulfilled(results));
}
}
}
function traverseAt(promises, handler, i, x, resolver) {
if (maybeThenable(x)) {
var h = getHandlerMaybeThenable(x);
var s = h.state();
if (s === 0) {
h.fold(handler, i, void 0, resolver);
} else if (s > 0) {
handler(i, h.value, resolver);
} else {
resolver.become(h);
visitRemaining(promises, i+1, h);
}
} else {
handler(i, x, resolver);
}
}
Promise._visitRemaining = visitRemaining;
function visitRemaining(promises, start, handler) {
for(var i=start; i<promises.length; ++i) {
markAsHandled(getHandler(promises[i]), handler);
}
}
function markAsHandled(h, handler) {
if(h === handler) {
return;
}
var s = h.state();
if(s === 0) {
h.visit(h, void 0, h._unreport);
} else if(s < 0) {
h._unreport();
}
}
/**
* Fulfill-reject competitive race. Return a promise that will settle
* to the same state as the earliest input promise to settle.
*
* WARNING: The ES6 Promise spec requires that race()ing an empty array
* must return a promise that is pending forever. This implementation
* returns a singleton forever-pending promise, the same singleton that is
* returned by Promise.never(), thus can be checked with ===
*
* @param {array} promises array of promises to race
* @returns {Promise} if input is non-empty, a promise that will settle
* to the same outcome as the earliest input promise to settle. if empty
* is empty, returns a promise that will never settle.
*/
function race(promises) {
if(typeof promises !== 'object' || promises === null) {
return reject(new TypeError('non-iterable passed to race()'));
}
// Sigh, race([]) is untestable unless we return *something*
// that is recognizable without calling .then() on it.
return promises.length === 0 ? never()
: promises.length === 1 ? resolve(promises[0])
: runRace(promises);
}
function runRace(promises) {
var resolver = new Pending();
var i, x, h;
for(i=0; i<promises.length; ++i) {
x = promises[i];
if (x === void 0 && !(i in promises)) {
continue;
}
h = getHandler(x);
if(h.state() !== 0) {
resolver.become(h);
visitRemaining(promises, i+1, h);
break;
} else {
h.visit(resolver, resolver.resolve, resolver.reject);
}
}
return new Promise(Handler, resolver);
}
// Promise internals
// Below this, everything is @private
/**
* Get an appropriate handler for x, without checking for cycles
* @param {*} x
* @returns {object} handler
*/
function getHandler(x) {
if(isPromise(x)) {
return x._handler.join();
}
return maybeThenable(x) ? getHandlerUntrusted(x) : new Fulfilled(x);
}
/**
* Get a handler for thenable x.
* NOTE: You must only call this if maybeThenable(x) == true
* @param {object|function|Promise} x
* @returns {object} handler
*/
function getHandlerMaybeThenable(x) {
return isPromise(x) ? x._handler.join() : getHandlerUntrusted(x);
}
/**
* Get a handler for potentially untrusted thenable x
* @param {*} x
* @returns {object} handler
*/
function getHandlerUntrusted(x) {
try {
var untrustedThen = x.then;
return typeof untrustedThen === 'function'
? new Thenable(untrustedThen, x)
: new Fulfilled(x);
} catch(e) {
return new Rejected(e);
}
}
/**
* Handler for a promise that is pending forever
* @constructor
*/
function Handler() {}
Handler.prototype.when
= Handler.prototype.become
= Handler.prototype.notify // deprecated
= Handler.prototype.fail
= Handler.prototype._unreport
= Handler.prototype._report
= noop;
Handler.prototype._state = 0;
Handler.prototype.state = function() {
return this._state;
};
/**
* Recursively collapse handler chain to find the handler
* nearest to the fully resolved value.
* @returns {object} handler nearest the fully resolved value
*/
Handler.prototype.join = function() {
var h = this;
while(h.handler !== void 0) {
h = h.handler;
}
return h;
};
Handler.prototype.chain = function(to, receiver, fulfilled, rejected, progress) {
this.when({
resolver: to,
receiver: receiver,
fulfilled: fulfilled,
rejected: rejected,
progress: progress
});
};
Handler.prototype.visit = function(receiver, fulfilled, rejected, progress) {
this.chain(failIfRejected, receiver, fulfilled, rejected, progress);
};
Handler.prototype.fold = function(f, z, c, to) {
this.when(new Fold(f, z, c, to));
};
/**
* Handler that invokes fail() on any handler it becomes
* @constructor
*/
function FailIfRejected() {}
inherit(Handler, FailIfRejected);
FailIfRejected.prototype.become = function(h) {
h.fail();
};
var failIfRejected = new FailIfRejected();
/**
* Handler that manages a queue of consumers waiting on a pending promise
* @constructor
*/
function Pending(receiver, inheritedContext) {
Promise.createContext(this, inheritedContext);
this.consumers = void 0;
this.receiver = receiver;
this.handler = void 0;
this.resolved = false;
}
inherit(Handler, Pending);
Pending.prototype._state = 0;
Pending.prototype.resolve = function(x) {
this.become(getHandler(x));
};
Pending.prototype.reject = function(x) {
if(this.resolved) {
return;
}
this.become(new Rejected(x));
};
Pending.prototype.join = function() {
if (!this.resolved) {
return this;
}
var h = this;
while (h.handler !== void 0) {
h = h.handler;
if (h === this) {
return this.handler = cycle();
}
}
return h;
};
Pending.prototype.run = function() {
var q = this.consumers;
var handler = this.handler;
this.handler = this.handler.join();
this.consumers = void 0;
for (var i = 0; i < q.length; ++i) {
handler.when(q[i]);
}
};
Pending.prototype.become = function(handler) {
if(this.resolved) {
return;
}
this.resolved = true;
this.handler = handler;
if(this.consumers !== void 0) {
tasks.enqueue(this);
}
if(this.context !== void 0) {
handler._report(this.context);
}
};
Pending.prototype.when = function(continuation) {
if(this.resolved) {
tasks.enqueue(new ContinuationTask(continuation, this.handler));
} else {
if(this.consumers === void 0) {
this.consumers = [continuation];
} else {
this.consumers.push(continuation);
}
}
};
/**
* @deprecated
*/
Pending.prototype.notify = function(x) {
if(!this.resolved) {
tasks.enqueue(new ProgressTask(x, this));
}
};
Pending.prototype.fail = function(context) {
var c = typeof context === 'undefined' ? this.context : context;
this.resolved && this.handler.join().fail(c);
};
Pending.prototype._report = function(context) {
this.resolved && this.handler.join()._report(context);
};
Pending.prototype._unreport = function() {
this.resolved && this.handler.join()._unreport();
};
/**
* Wrap another handler and force it into a future stack
* @param {object} handler
* @constructor
*/
function Async(handler) {
this.handler = handler;
}
inherit(Handler, Async);
Async.prototype.when = function(continuation) {
tasks.enqueue(new ContinuationTask(continuation, this));
};
Async.prototype._report = function(context) {
this.join()._report(context);
};
Async.prototype._unreport = function() {
this.join()._unreport();
};
/**
* Handler that wraps an untrusted thenable and assimilates it in a future stack
* @param {function} then
* @param {{then: function}} thenable
* @constructor
*/
function Thenable(then, thenable) {
Pending.call(this);
tasks.enqueue(new AssimilateTask(then, thenable, this));
}
inherit(Pending, Thenable);
/**
* Handler for a fulfilled promise
* @param {*} x fulfillment value
* @constructor
*/
function Fulfilled(x) {
Promise.createContext(this);
this.value = x;
}
inherit(Handler, Fulfilled);
Fulfilled.prototype._state = 1;
Fulfilled.prototype.fold = function(f, z, c, to) {
runContinuation3(f, z, this, c, to);
};
Fulfilled.prototype.when = function(cont) {
runContinuation1(cont.fulfilled, this, cont.receiver, cont.resolver);
};
var errorId = 0;
/**
* Handler for a rejected promise
* @param {*} x rejection reason
* @constructor
*/
function Rejected(x) {
Promise.createContext(this);
this.id = ++errorId;
this.value = x;
this.handled = false;
this.reported = false;
this._report();
}
inherit(Handler, Rejected);
Rejected.prototype._state = -1;
Rejected.prototype.fold = function(f, z, c, to) {
to.become(this);
};
Rejected.prototype.when = function(cont) {
if(typeof cont.rejected === 'function') {
this._unreport();
}
runContinuation1(cont.rejected, this, cont.receiver, cont.resolver);
};
Rejected.prototype._report = function(context) {
tasks.afterQueue(new ReportTask(this, context));
};
Rejected.prototype._unreport = function() {
if(this.handled) {
return;
}
this.handled = true;
tasks.afterQueue(new UnreportTask(this));
};
Rejected.prototype.fail = function(context) {
this.reported = true;
emitRejection('unhandledRejection', this);
Promise.onFatalRejection(this, context === void 0 ? this.context : context);
};
function ReportTask(rejection, context) {
this.rejection = rejection;
this.context = context;
}
ReportTask.prototype.run = function() {
if(!this.rejection.handled && !this.rejection.reported) {
this.rejection.reported = true;
emitRejection('unhandledRejection', this.rejection) ||
Promise.onPotentiallyUnhandledRejection(this.rejection, this.context);
}
};
function UnreportTask(rejection) {
this.rejection = rejection;
}
UnreportTask.prototype.run = function() {
if(this.rejection.reported) {
emitRejection('rejectionHandled', this.rejection) ||
Promise.onPotentiallyUnhandledRejectionHandled(this.rejection);
}
};
// Unhandled rejection hooks
// By default, everything is a noop
Promise.createContext
= Promise.enterContext
= Promise.exitContext
= Promise.onPotentiallyUnhandledRejection
= Promise.onPotentiallyUnhandledRejectionHandled
= Promise.onFatalRejection
= noop;
// Errors and singletons
var foreverPendingHandler = new Handler();
var foreverPendingPromise = new Promise(Handler, foreverPendingHandler);
function cycle() {
return new Rejected(new TypeError('Promise cycle'));
}
// Task runners
/**
* Run a single consumer
* @constructor
*/
function ContinuationTask(continuation, handler) {
this.continuation = continuation;
this.handler = handler;
}
ContinuationTask.prototype.run = function() {
this.handler.join().when(this.continuation);
};
/**
* Run a queue of progress handlers
* @constructor
*/
function ProgressTask(value, handler) {
this.handler = handler;
this.value = value;
}
ProgressTask.prototype.run = function() {
var q = this.handler.consumers;
if(q === void 0) {
return;
}
for (var c, i = 0; i < q.length; ++i) {
c = q[i];
runNotify(c.progress, this.value, this.handler, c.receiver, c.resolver);
}
};
/**
* Assimilate a thenable, sending it's value to resolver
* @param {function} then
* @param {object|function} thenable
* @param {object} resolver
* @constructor
*/
function AssimilateTask(then, thenable, resolver) {
this._then = then;
this.thenable = thenable;
this.resolver = resolver;
}
AssimilateTask.prototype.run = function() {
var h = this.resolver;
tryAssimilate(this._then, this.thenable, _resolve, _reject, _notify);
function _resolve(x) { h.resolve(x); }
function _reject(x) { h.reject(x); }
function _notify(x) { h.notify(x); }
};
function tryAssimilate(then, thenable, resolve, reject, notify) {
try {
then.call(thenable, resolve, reject, notify);
} catch (e) {
reject(e);
}
}
/**
* Fold a handler value with z
* @constructor
*/
function Fold(f, z, c, to) {
this.f = f; this.z = z; this.c = c; this.to = to;
this.resolver = failIfRejected;
this.receiver = this;
}
Fold.prototype.fulfilled = function(x) {
this.f.call(this.c, this.z, x, this.to);
};
Fold.prototype.rejected = function(x) {
this.to.reject(x);
};
Fold.prototype.progress = function(x) {
this.to.notify(x);
};
// Other helpers
/**
* @param {*} x
* @returns {boolean} true iff x is a trusted Promise
*/
function isPromise(x) {
return x instanceof Promise;
}
/**
* Test just enough to rule out primitives, in order to take faster
* paths in some code
* @param {*} x
* @returns {boolean} false iff x is guaranteed *not* to be a thenable
*/
function maybeThenable(x) {
return (typeof x === 'object' || typeof x === 'function') && x !== null;
}
function runContinuation1(f, h, receiver, next) {
if(typeof f !== 'function') {
return next.become(h);
}
Promise.enterContext(h);
tryCatchReject(f, h.value, receiver, next);
Promise.exitContext();
}
function runContinuation3(f, x, h, receiver, next) {
if(typeof f !== 'function') {
return next.become(h);
}
Promise.enterContext(h);
tryCatchReject3(f, x, h.value, receiver, next);
Promise.exitContext();
}
/**
* @deprecated
*/
function runNotify(f, x, h, receiver, next) {
if(typeof f !== 'function') {
return next.notify(x);
}
Promise.enterContext(h);
tryCatchReturn(f, x, receiver, next);
Promise.exitContext();
}
function tryCatch2(f, a, b) {
try {
return f(a, b);
} catch(e) {
return reject(e);
}
}
/**
* Return f.call(thisArg, x), or if it throws return a rejected promise for
* the thrown exception
*/
function tryCatchReject(f, x, thisArg, next) {
try {
next.become(getHandler(f.call(thisArg, x)));
} catch(e) {
next.become(new Rejected(e));
}
}
/**
* Same as above, but includes the extra argument parameter.
*/
function tryCatchReject3(f, x, y, thisArg, next) {
try {
f.call(thisArg, x, y, next);
} catch(e) {
next.become(new Rejected(e));
}
}
/**
* @deprecated
* Return f.call(thisArg, x), or if it throws, *return* the exception
*/
function tryCatchReturn(f, x, thisArg, next) {
try {
next.notify(f.call(thisArg, x));
} catch(e) {
next.notify(e);
}
}
function inherit(Parent, Child) {
Child.prototype = objectCreate(Parent.prototype);
Child.prototype.constructor = Child;
}
function snd(x, y) {
return y;
}
function noop() {}
function initEmitRejection() {
/*global process, self, CustomEvent*/
if(typeof process !== 'undefined' && process !== null
&& typeof process.emit === 'function') {
// Returning falsy here means to call the default
// onPotentiallyUnhandledRejection API. This is safe even in
// browserify since process.emit always returns falsy in browserify:
// https://github.com/defunctzombie/node-process/blob/master/browser.js#L40-L46
return function(type, rejection) {
return type === 'unhandledRejection'
? process.emit(type, rejection.value, rejection)
: process.emit(type, rejection);
};
} else if(typeof self !== 'undefined' && typeof CustomEvent === 'function') {
return (function(noop, self, CustomEvent) {
var hasCustomEvent = false;
try {
var ev = new CustomEvent('unhandledRejection');
hasCustomEvent = ev instanceof CustomEvent;
} catch (e) {}
return !hasCustomEvent ? noop : function(type, rejection) {
var ev = new CustomEvent(type, {
detail: {
reason: rejection.value,
key: rejection
},
bubbles: false,
cancelable: true
});
return !self.dispatchEvent(ev);
};
}(noop, self, CustomEvent));
}
return noop;
}
return Promise;
};
});
}(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
}).call(this,require('_process'))
},{"_process":1}],72:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2014 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
(function(define) { 'use strict';
define(function() {
return {
pending: toPendingState,
fulfilled: toFulfilledState,
rejected: toRejectedState,
inspect: inspect
};
function toPendingState() {
return { state: 'pending' };
}
function toRejectedState(e) {
return { state: 'rejected', reason: e };
}
function toFulfilledState(x) {
return { state: 'fulfilled', value: x };
}
function inspect(handler) {
var state = handler.state();
return state === 0 ? toPendingState()
: state > 0 ? toFulfilledState(handler.value)
: toRejectedState(handler.value);
}
});
}(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
},{}],73:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2014 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
(function(define) { 'use strict';
define(function(require) {
var PromiseMonitor = require('./monitor/PromiseMonitor');
var ConsoleReporter = require('./monitor/ConsoleReporter');
var promiseMonitor = new PromiseMonitor(new ConsoleReporter());
return function(Promise) {
return promiseMonitor.monitor(Promise);
};
});
}(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
},{"./monitor/ConsoleReporter":74,"./monitor/PromiseMonitor":75}],74:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2014 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
(function(define) { 'use strict';
define(function(require) {
var error = require('./error');
var unhandledRejectionsMsg = '[promises] Unhandled rejections: ';
var allHandledMsg = '[promises] All previously unhandled rejections have now been handled';
function ConsoleReporter() {
this._previouslyReported = false;
}
ConsoleReporter.prototype = initDefaultLogging();
ConsoleReporter.prototype.log = function(traces) {
if(traces.length === 0) {
if(this._previouslyReported) {
this._previouslyReported = false;
this.msg(allHandledMsg);
}
return;
}
this._previouslyReported = true;
this.groupStart(unhandledRejectionsMsg + traces.length);
try {
this._log(traces);
} finally {
this.groupEnd();
}
};
ConsoleReporter.prototype._log = function(traces) {
for(var i=0; i<traces.length; ++i) {
this.warn(error.format(traces[i]));
}
};
function initDefaultLogging() {
/*jshint maxcomplexity:7*/
var log, warn, groupStart, groupEnd;
if(typeof console === 'undefined') {
log = warn = consoleNotAvailable;
} else {
// Alias console to prevent things like uglify's drop_console option from
// removing console.log/error. Unhandled rejections fall into the same
// category as uncaught exceptions, and build tools shouldn't silence them.
var localConsole = console;
if(typeof localConsole.error === 'function'
&& typeof localConsole.dir === 'function') {
warn = function(s) {
localConsole.error(s);
};
log = function(s) {
localConsole.log(s);
};
if(typeof localConsole.groupCollapsed === 'function') {
groupStart = function(s) {
localConsole.groupCollapsed(s);
};
groupEnd = function() {
localConsole.groupEnd();
};
}
} else {
// IE8 has console.log and JSON, so we can make a
// reasonably useful warn() from those.
// Credit to webpro (https://github.com/webpro) for this idea
if (typeof localConsole.log ==='function'
&& typeof JSON !== 'undefined') {
log = warn = function (x) {
if(typeof x !== 'string') {
try {
x = JSON.stringify(x);
} catch(e) {}
}
localConsole.log(x);
};
}
}
}
return {
msg: log,
warn: warn,
groupStart: groupStart || warn,
groupEnd: groupEnd || consoleNotAvailable
};
}
function consoleNotAvailable() {}
return ConsoleReporter;
});
}(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
},{"./error":77}],75:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2014 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
(function(define) { 'use strict';
define(function(require) {
var defaultStackJumpSeparator = 'from execution context:';
var defaultStackFilter = /[\s\(\/\\](node|module|timers)\.js:|when([\/\\]{1,2}(lib|monitor|es6-shim)[\/\\]{1,2}|\.js)|(new\sPromise)\b|(\b(PromiseMonitor|ConsoleReporter|Scheduler|RunHandlerTask|ProgressTask|Promise|.*Handler)\.[\w_]\w\w+\b)|\b(tryCatch\w+|getHandler\w*)\b/i;
var setTimer = require('../lib/env').setTimer;
var error = require('./error');
var executionContext = [];
function PromiseMonitor(reporter) {
this.logDelay = 0;
this.stackFilter = defaultStackFilter;
this.stackJumpSeparator = defaultStackJumpSeparator;
this.filterDuplicateFrames = true;
this._reporter = reporter;
if(typeof reporter.configurePromiseMonitor === 'function') {
reporter.configurePromiseMonitor(this);
}
this._traces = [];
this._traceTask = 0;
var self = this;
this._doLogTraces = function() {
self._logTraces();
};
}
PromiseMonitor.prototype.monitor = function(Promise) {
var self = this;
Promise.createContext = function(p, context) {
p.context = self.createContext(p, context);
};
Promise.enterContext = function(p) {
executionContext.push(p.context);
};
Promise.exitContext = function() {
executionContext.pop();
};
Promise.onPotentiallyUnhandledRejection = function(rejection, extraContext) {
return self.addTrace(rejection, extraContext);
};
Promise.onPotentiallyUnhandledRejectionHandled = function(rejection) {
return self.removeTrace(rejection);
};
Promise.onFatalRejection = function(rejection, extraContext) {
return self.fatal(rejection, extraContext);
};
return this;
};
PromiseMonitor.prototype.createContext = function(at, parentContext) {
var context = {
parent: parentContext || executionContext[executionContext.length - 1],
stack: void 0
};
error.captureStack(context, at.constructor);
return context;
};
PromiseMonitor.prototype.addTrace = function(handler, extraContext) {
var t, i;
for(i = this._traces.length-1; i >= 0; --i) {
t = this._traces[i];
if(t.handler === handler) {
break;
}
}
if(i >= 0) {
t.extraContext = extraContext;
} else {
this._traces.push({
handler: handler,
extraContext: extraContext
});
}
this.logTraces();
};
PromiseMonitor.prototype.removeTrace = function(/*handler*/) {
this.logTraces();
};
PromiseMonitor.prototype.fatal = function(handler, extraContext) {
var err = new Error();
err.stack = this._createLongTrace(handler.value, handler.context, extraContext).join('\n');
setTimer(function() {
throw err;
}, 0);
};
PromiseMonitor.prototype.logTraces = function() {
if(!this._traceTask) {
this._traceTask = setTimer(this._doLogTraces, this.logDelay);
}
};
PromiseMonitor.prototype._logTraces = function() {
this._traceTask = void 0;
this._traces = this._traces.filter(filterHandled);
this._reporter.log(this.formatTraces(this._traces));
};
PromiseMonitor.prototype.formatTraces = function(traces) {
return traces.map(function(t) {
return this._createLongTrace(t.handler.value, t.handler.context, t.extraContext);
}, this);
};
PromiseMonitor.prototype._createLongTrace = function(e, context, extraContext) {
var trace = error.parse(e) || [String(e) + ' (WARNING: non-Error used)'];
trace = filterFrames(this.stackFilter, trace, 0);
this._appendContext(trace, context);
this._appendContext(trace, extraContext);
return this.filterDuplicateFrames ? this._removeDuplicates(trace) : trace;
};
PromiseMonitor.prototype._removeDuplicates = function(trace) {
var seen = {};
var sep = this.stackJumpSeparator;
var count = 0;
return trace.reduceRight(function(deduped, line, i) {
if(i === 0) {
deduped.unshift(line);
} else if(line === sep) {
if(count > 0) {
deduped.unshift(line);
count = 0;
}
} else if(!seen[line]) {
seen[line] = true;
deduped.unshift(line);
++count;
}
return deduped;
}, []);
};
PromiseMonitor.prototype._appendContext = function(trace, context) {
trace.push.apply(trace, this._createTrace(context));
};
PromiseMonitor.prototype._createTrace = function(traceChain) {
var trace = [];
var stack;
while(traceChain) {
stack = error.parse(traceChain);
if (stack) {
stack = filterFrames(this.stackFilter, stack);
appendStack(trace, stack, this.stackJumpSeparator);
}
traceChain = traceChain.parent;
}
return trace;
};
function appendStack(trace, stack, separator) {
if (stack.length > 1) {
stack[0] = separator;
trace.push.apply(trace, stack);
}
}
function filterFrames(stackFilter, stack) {
return stack.filter(function(frame) {
return !stackFilter.test(frame);
});
}
function filterHandled(t) {
return !t.handler.handled;
}
return PromiseMonitor;
});
}(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
},{"../lib/env":68,"./error":77}],76:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2014 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
(function(define) { 'use strict';
define(function(require) {
var monitor = require('../monitor');
var Promise = require('../when').Promise;
return monitor(Promise);
});
}(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
},{"../monitor":73,"../when":78}],77:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2014 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
(function(define) { 'use strict';
define(function() {
var parse, captureStack, format;
if(Error.captureStackTrace) {
// Use Error.captureStackTrace if available
parse = function(e) {
return e && e.stack && e.stack.split('\n');
};
format = formatAsString;
captureStack = Error.captureStackTrace;
} else {
// Otherwise, do minimal feature detection to determine
// how to capture and format reasonable stacks.
parse = function(e) {
var stack = e && e.stack && e.stack.split('\n');
if(stack && e.message) {
stack.unshift(e.message);
}
return stack;
};
(function() {
var e = new Error();
if(typeof e.stack !== 'string') {
format = formatAsString;
captureStack = captureSpiderMonkeyStack;
} else {
format = formatAsErrorWithStack;
captureStack = useStackDirectly;
}
}());
}
function captureSpiderMonkeyStack(host) {
try {
throw new Error();
} catch(err) {
host.stack = err.stack;
}
}
function useStackDirectly(host) {
host.stack = new Error().stack;
}
function formatAsString(longTrace) {
return join(longTrace);
}
function formatAsErrorWithStack(longTrace) {
var e = new Error();
e.stack = formatAsString(longTrace);
return e;
}
// About 5-10x faster than String.prototype.join o_O
function join(a) {
var sep = false;
var s = '';
for(var i=0; i< a.length; ++i) {
if(sep) {
s += '\n' + a[i];
} else {
s+= a[i];
sep = true;
}
}
return s;
}
return {
parse: parse,
format: format,
captureStack: captureStack
};
});
}(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
},{}],78:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2014 original author or authors */
/**
* Promises/A+ and when() implementation
* when is part of the cujoJS family of libraries (http://cujojs.com/)
* @author Brian Cavalier
* @author John Hann
* @version 3.7.2
*/
(function(define) { 'use strict';
define(function (require) {
var timed = require('./lib/decorators/timed');
var array = require('./lib/decorators/array');
var flow = require('./lib/decorators/flow');
var fold = require('./lib/decorators/fold');
var inspect = require('./lib/decorators/inspect');
var generate = require('./lib/decorators/iterate');
var progress = require('./lib/decorators/progress');
var withThis = require('./lib/decorators/with');
var unhandledRejection = require('./lib/decorators/unhandledRejection');
var TimeoutError = require('./lib/TimeoutError');
var Promise = [array, flow, fold, generate, progress,
inspect, withThis, timed, unhandledRejection]
.reduce(function(Promise, feature) {
return feature(Promise);
}, require('./lib/Promise'));
var apply = require('./lib/apply')(Promise);
// Public API
when.promise = promise; // Create a pending promise
when.resolve = Promise.resolve; // Create a resolved promise
when.reject = Promise.reject; // Create a rejected promise
when.lift = lift; // lift a function to return promises
when['try'] = attempt; // call a function and return a promise
when.attempt = attempt; // alias for when.try
when.iterate = Promise.iterate; // DEPRECATED (use cujojs/most streams) Generate a stream of promises
when.unfold = Promise.unfold; // DEPRECATED (use cujojs/most streams) Generate a stream of promises
when.join = join; // Join 2 or more promises
when.all = all; // Resolve a list of promises
when.settle = settle; // Settle a list of promises
when.any = lift(Promise.any); // One-winner race
when.some = lift(Promise.some); // Multi-winner race
when.race = lift(Promise.race); // First-to-settle race
when.map = map; // Array.map() for promises
when.filter = filter; // Array.filter() for promises
when.reduce = lift(Promise.reduce); // Array.reduce() for promises
when.reduceRight = lift(Promise.reduceRight); // Array.reduceRight() for promises
when.isPromiseLike = isPromiseLike; // Is something promise-like, aka thenable
when.Promise = Promise; // Promise constructor
when.defer = defer; // Create a {promise, resolve, reject} tuple
// Error types
when.TimeoutError = TimeoutError;
/**
* Get a trusted promise for x, or by transforming x with onFulfilled
*
* @param {*} x
* @param {function?} onFulfilled callback to be called when x is
* successfully fulfilled. If promiseOrValue is an immediate value, callback
* will be invoked immediately.
* @param {function?} onRejected callback to be called when x is
* rejected.
* @param {function?} onProgress callback to be called when progress updates
* are issued for x. @deprecated
* @returns {Promise} a new promise that will fulfill with the return
* value of callback or errback or the completion value of promiseOrValue if
* callback and/or errback is not supplied.
*/
function when(x, onFulfilled, onRejected, onProgress) {
var p = Promise.resolve(x);
if (arguments.length < 2) {
return p;
}
return p.then(onFulfilled, onRejected, onProgress);
}
/**
* Creates a new promise whose fate is determined by resolver.
* @param {function} resolver function(resolve, reject, notify)
* @returns {Promise} promise whose fate is determine by resolver
*/
function promise(resolver) {
return new Promise(resolver);
}
/**
* Lift the supplied function, creating a version of f that returns
* promises, and accepts promises as arguments.
* @param {function} f
* @returns {Function} version of f that returns promises
*/
function lift(f) {
return function() {
for(var i=0, l=arguments.length, a=new Array(l); i<l; ++i) {
a[i] = arguments[i];
}
return apply(f, this, a);
};
}
/**
* Call f in a future turn, with the supplied args, and return a promise
* for the result.
* @param {function} f
* @returns {Promise}
*/
function attempt(f /*, args... */) {
/*jshint validthis:true */
for(var i=0, l=arguments.length-1, a=new Array(l); i<l; ++i) {
a[i] = arguments[i+1];
}
return apply(f, this, a);
}
/**
* Creates a {promise, resolver} pair, either or both of which
* may be given out safely to consumers.
* @return {{promise: Promise, resolve: function, reject: function, notify: function}}
*/
function defer() {
return new Deferred();
}
function Deferred() {
var p = Promise._defer();
function resolve(x) { p._handler.resolve(x); }
function reject(x) { p._handler.reject(x); }
function notify(x) { p._handler.notify(x); }
this.promise = p;
this.resolve = resolve;
this.reject = reject;
this.notify = notify;
this.resolver = { resolve: resolve, reject: reject, notify: notify };
}
/**
* Determines if x is promise-like, i.e. a thenable object
* NOTE: Will return true for *any thenable object*, and isn't truly
* safe, since it may attempt to access the `then` property of x (i.e.
* clever/malicious getters may do weird things)
* @param {*} x anything
* @returns {boolean} true if x is promise-like
*/
function isPromiseLike(x) {
return x && typeof x.then === 'function';
}
/**
* Return a promise that will resolve only once all the supplied arguments
* have resolved. The resolution value of the returned promise will be an array
* containing the resolution values of each of the arguments.
* @param {...*} arguments may be a mix of promises and values
* @returns {Promise}
*/
function join(/* ...promises */) {
return Promise.all(arguments);
}
/**
* Return a promise that will fulfill once all input promises have
* fulfilled, or reject when any one input promise rejects.
* @param {array|Promise} promises array (or promise for an array) of promises
* @returns {Promise}
*/
function all(promises) {
return when(promises, Promise.all);
}
/**
* Return a promise that will always fulfill with an array containing
* the outcome states of all input promises. The returned promise
* will only reject if `promises` itself is a rejected promise.
* @param {array|Promise} promises array (or promise for an array) of promises
* @returns {Promise} promise for array of settled state descriptors
*/
function settle(promises) {
return when(promises, Promise.settle);
}
/**
* Promise-aware array map function, similar to `Array.prototype.map()`,
* but input array may contain promises or values.
* @param {Array|Promise} promises array of anything, may contain promises and values
* @param {function(x:*, index:Number):*} mapFunc map function which may
* return a promise or value
* @returns {Promise} promise that will fulfill with an array of mapped values
* or reject if any input promise rejects.
*/
function map(promises, mapFunc) {
return when(promises, function(promises) {
return Promise.map(promises, mapFunc);
});
}
/**
* Filter the provided array of promises using the provided predicate. Input may
* contain promises and values
* @param {Array|Promise} promises array of promises and values
* @param {function(x:*, index:Number):boolean} predicate filtering predicate.
* Must return truthy (or promise for truthy) for items to retain.
* @returns {Promise} promise that will fulfill with an array containing all items
* for which predicate returned truthy.
*/
function filter(promises, predicate) {
return when(promises, function(promises) {
return Promise.filter(promises, predicate);
});
}
return when;
});
})(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); });
},{"./lib/Promise":55,"./lib/TimeoutError":57,"./lib/apply":58,"./lib/decorators/array":59,"./lib/decorators/flow":60,"./lib/decorators/fold":61,"./lib/decorators/inspect":62,"./lib/decorators/iterate":63,"./lib/decorators/progress":64,"./lib/decorators/timed":65,"./lib/decorators/unhandledRejection":66,"./lib/decorators/with":67}],79:[function(require,module,exports){
/**
* Module dependencies.
*/
var global = (function() { return this; })();
/**
* WebSocket constructor.
*/
var WebSocket = global.WebSocket || global.MozWebSocket;
/**
* Module exports.
*/
module.exports = WebSocket ? ws : null;
/**
* WebSocket constructor.
*
* The third `opts` options object gets ignored in web browsers, since it's
* non-standard, and throws a TypeError if passed to the constructor.
* See: https://github.com/einaros/ws/issues/227
*
* @param {String} uri
* @param {Array} protocols (optional)
* @param {Object) opts (optional)
* @api public
*/
function ws(uri, protocols, opts) {
var instance;
if (protocols) {
instance = new WebSocket(uri, protocols);
} else {
instance = new WebSocket(uri);
}
return instance;
}
if (WebSocket) ws.prototype = WebSocket.prototype;
},{}],80:[function(require,module,exports){
module.exports={
"name": "autobahn",
"version": "0.9.7",
"description": "An implementation of The Web Application Messaging Protocol (WAMP).",
"main": "index.js",
"scripts": {
"test": "nodeunit test/test.js"
},
"dependencies": {
"when": ">= 2.8.0",
"ws": ">= 0.4.31",
"crypto-js": ">= 3.1.2-2"
},
"devDependencies": {
"browserify": ">= 3.28.1",
"nodeunit": ">= 0.8.6"
},
"repository": {
"type": "git",
"url": "git://github.com/crossbario/autobahn-js.git"
},
"keywords": [
"WAMP",
"WebSocket",
"RPC",
"PubSub"
],
"author": "Tavendo GmbH",
"license": "MIT"
}
},{}]},{},[4])(4)
}); | Dynalon/autobahn-js | test/detectenvironment/autobahn.js | JavaScript | mit | 441,739 |
#include <cstdio>
#include <string>
#include <cstdlib>
#include <iostream>
#include <sstream>
using namespace std;
int main(int argc, char **argv)
{
/* Method 1 ไฝฟ็จsprintf */
char buf[20];
sprintf(buf, "%d", 123);
string s1(buf);
cout << "s1 = " << s1 << endl;
/* Method 2 ไฝฟ็จstringstream */
stringstream ss;
ss << 123;
string s2 = ss.str();
s2.push_back('c');
cout << "s2 = " << s2 << endl;
return 0;
}
| krystism/leetcode | algorithms/CountandSay/itos.cpp | C++ | mit | 423 |
package com.example.android.gesturesdemo;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
} | TelerikAcademy/Mobile-Applications-for-Android | Topics/resources/14. Gestures/demos/GesturesDemo/app/src/androidTest/java/com/example/android/gesturesdemo/ApplicationTest.java | Java | mit | 355 |
require File.dirname(__FILE__) + '/../spec_helper'
require File.dirname(__FILE__) + '/../fixtures/class'
describe "self in a metaclass body (class << obj)" do
it "is TrueClass for true" do
class << true; self; end.should == TrueClass
end
it "is FalseClass for false" do
class << false; self; end.should == FalseClass
end
it "is NilClass for nil" do
class << nil; self; end.should == NilClass
end
it "raises a TypeError for numbers" do
lambda { class << 1; self; end }.should raise_error(TypeError)
end
it "raises a TypeError for symbols" do
lambda { class << :symbol; self; end }.should raise_error(TypeError)
end
it "is a singleton Class instance" do
cls = class << mock('x'); self; end
cls.is_a?(Class).should == true
cls.should_not equal(Object)
end
deviates_on(:rubinius) do
it "is a MetaClass instance" do
cls = class << mock('x'); self; end
cls.is_a?(MetaClass).should == true
end
it "has the object's class as superclass" do
cls = class << "blah"; self; end
cls.superclass.should == String
end
end
end
describe "A constant on a metaclass" do
before(:each) do
@object = Object.new
class << @object
CONST = self
end
end
it "can be accessed after the metaclass body is reopened" do
class << @object
CONST.should == self
end
end
it "can be accessed via self::CONST" do
class << @object
self::CONST.should == self
end
end
it "can be accessed via const_get" do
class << @object
const_get(:CONST).should == self
end
end
it "is not defined on the object's class" do
@object.class.const_defined?(:CONST).should be_false
end
it "is not defined in the metaclass opener's scope" do
class << @object
CONST
end
lambda { CONST }.should raise_error(NameError)
end
it "cannot be accessed via object::CONST" do
lambda do
@object::CONST
end.should raise_error(TypeError)
end
it "raises a NameError for anonymous_module::CONST" do
@object = Class.new
class << @object
CONST = 100
end
lambda do
@object::CONST
end.should raise_error(NameError)
end
it "appears in the metaclass constant list" do
constants = class << @object; constants; end
constants.should include("CONST")
end
it "does not appear in the object's class constant list" do
@object.class.constants.should_not include("CONST")
end
it "is not preserved when the object is duped" do
@object = @object.dup
lambda do
class << @object; CONST; end
end.should raise_error(NameError)
end
it "is preserved when the object is cloned" do
@object = @object.clone
class << @object
CONST.should_not be_nil
end
end
end
| ujihisa/rubyspec | language/metaclass_spec.rb | Ruby | mit | 2,812 |
๏ปฟ// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Light3D.cs" company="Helix Toolkit">
// Copyright (c) 2014 Helix Toolkit contributors
// </copyright>
// <summary>
// Direction of the light.
// It applies to Directional Light and to Spot Light,
// for all other lights it is ignored.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace HelixToolkit.Wpf.SharpDX
{
using System;
using System.Windows;
using System.Windows.Media.Media3D;
using global::SharpDX;
using global::SharpDX.Direct3D11;
using Matrix = global::SharpDX.Matrix;
public enum LightType : ushort
{
Ambient = 1, Directional = 2, Point = 3, Spot = 4,
}
public interface ILight3D
{
}
public abstract class Light3D : Model3D, ILight3D, IDisposable
{
public static readonly DependencyProperty DirectionProperty =
DependencyProperty.Register("Direction", typeof(Vector3), typeof(Light3D), new UIPropertyMetadata(new Vector3()));
public static readonly DependencyProperty DirectionTransformProperty =
DependencyProperty.Register("DirectionTransform", typeof(Transform3D), typeof(Light3D), new UIPropertyMetadata(Transform3D.Identity, DirectionTransformPropertyChanged));
public static readonly DependencyProperty ColorProperty =
DependencyProperty.Register("Color", typeof(Color4), typeof(Light3D), new UIPropertyMetadata(new Color4(0.2f, 0.2f, 0.2f, 1.0f), ColorChanged));
public LightType LightType { get; protected set; }
public Light3D()
{
}
~Light3D()
{
}
private static void ColorChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((Light3D)d).OnColorChanged(e);
}
protected virtual void OnColorChanged(DependencyPropertyChangedEventArgs e) { }
/// <summary>
/// Direction of the light.
/// It applies to Directional Light and to Spot Light,
/// for all other lights it is ignored.
/// </summary>
public Vector3 Direction
{
get { return (Vector3)this.GetValue(DirectionProperty); }
set { this.SetValue(DirectionProperty, value); }
}
/// <summary>
/// Transforms the Direction Vector of the Light.
/// </summary>
public Transform3D DirectionTransform
{
get { return (Transform3D)this.GetValue(DirectionTransformProperty); }
set { this.SetValue(DirectionTransformProperty, value); }
}
/// <summary>
/// Color of the light.
/// For simplicity, this color applies to the diffuse and specular properties of the light.
/// </summary>
public Color4 Color
{
get { return (Color4)this.GetValue(ColorProperty); }
set { this.SetValue(ColorProperty, value); }
}
/// <summary>
///
/// </summary>
private static void DirectionTransformPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (e.NewValue != null)
{
var trafo = ((Transform3D)e.NewValue).Value;
((Light3D)d).Direction = new Vector3((float)trafo.OffsetX, (float)trafo.OffsetY, (float)trafo.OffsetZ);
}
}
/// <summary>
/// Number of lights in the scene
/// </summary>
public static int LightCount
{
get { return lightCount; }
internal set
{
lightCount = value;
if (value == 0)
{
lightDirections = new Vector4[maxLights];
lightPositions = new Vector4[maxLights];
lightAtt = new Vector4[maxLights];
lightSpots = new Vector4[maxLights];
lightColors = new Color4[maxLights];
lightTypes = new int[maxLights];
lightViewMatrices = new Matrix[maxLights];
lightProjMatrices = new Matrix[maxLights];
}
}
}
/// <summary>
/// The lighting model.
/// </summary>
public static class Model
{
//PhongPerVertex,
//BlinnPhongPerVertex,
public static readonly RenderTechnique RenderPhong = Techniques.RenderPhong;
public static readonly RenderTechnique RenderBlinnPhong = Techniques.RenderBlinn;
public static readonly RenderTechnique RenderColors = Techniques.RenderColors;
}
public Matrix LightViewMatrix
{
get { return lightViewMatrices[this.lightIndex]; }
internal set { lightViewMatrices[this.lightIndex] = value; }
}
public Matrix LightProjectionMatrix
{
get { return lightProjMatrices[this.lightIndex]; }
internal set { lightProjMatrices[this.lightIndex] = value; }
}
/// <summary>
/// Light Type.
/// </summary>
public enum Type : int
{
Ambient = 0,
Directional = 1,
Point = 2,
Spot = 3,
}
public override void Attach(IRenderHost host)
{
this.renderTechnique = host.RenderTechnique;
base.Attach(host);
if (this.LightType != LightType.Ambient)
{
this.lightIndex = lightCount++;
lightCount = lightCount % maxLights;
if (host.IsShadowMapEnabled)
{
this.mLightView = this.effect.GetVariableByName("mLightView").AsMatrix();
this.mLightProj = this.effect.GetVariableByName("mLightProj").AsMatrix();
}
}
}
public override void Detach()
{
if (this.LightType != LightType.Ambient)
{
// "turn-off" the light
lightColors[lightIndex] = new Color4(0, 0, 0, 0);
}
base.Detach();
}
public override void Dispose()
{
this.Detach();
}
protected const int maxLights = 16;
protected static int lightCount = 0;
protected static Vector4[] lightDirections = new Vector4[maxLights];
protected static Vector4[] lightPositions = new Vector4[maxLights];
protected static Vector4[] lightAtt = new Vector4[maxLights];
protected static Vector4[] lightSpots = new Vector4[maxLights];
protected static Color4[] lightColors = new Color4[maxLights];
protected static int[] lightTypes = new int[maxLights];
protected static Matrix[] lightViewMatrices = new Matrix[maxLights];
protected static Matrix[] lightProjMatrices = new Matrix[maxLights];
protected EffectVectorVariable vLightDir;
protected EffectVectorVariable vLightPos;
protected EffectVectorVariable vLightColor;
protected EffectVectorVariable vLightAtt;
protected EffectVectorVariable vLightSpot;
protected EffectMatrixVariable mLightView;
protected EffectMatrixVariable mLightProj;
protected EffectScalarVariable iLightType;
protected int lightIndex = 0;
}
public abstract class PointLightBase3D : Light3D
{
public static readonly DependencyProperty AttenuationProperty =
DependencyProperty.Register("Attenuation", typeof(Vector3), typeof(PointLightBase3D), new UIPropertyMetadata(new Vector3(1.0f, 0.0f, 0.0f)));
public static readonly DependencyProperty RangeProperty =
DependencyProperty.Register("Range", typeof(double), typeof(PointLightBase3D), new UIPropertyMetadata(1000.0));
/// <summary>
/// The position of the model in world space.
/// </summary>
public Point3D Position
{
get { return (Point3D)this.GetValue(PositionProperty); }
private set { this.SetValue(PositionPropertyKey, value); }
}
private static readonly DependencyPropertyKey PositionPropertyKey =
DependencyProperty.RegisterReadOnly("Position", typeof(Point3D), typeof(PointLightBase3D), new UIPropertyMetadata(new Point3D()));
public static readonly DependencyProperty PositionProperty = PositionPropertyKey.DependencyProperty;
protected override void OnTransformChanged(DependencyPropertyChangedEventArgs e)
{
base.OnTransformChanged(e);
this.Position = this.modelMatrix.TranslationVector.ToPoint3D();
}
/// <summary>
/// Attenuation coefficients:
/// X = constant attenuation,
/// Y = linar attenuation,
/// Z = quadratic attenuation.
/// For details see: http://msdn.microsoft.com/en-us/library/windows/desktop/bb172279(v=vs.85).aspx
/// </summary>
public Vector3 Attenuation
{
get { return (Vector3)this.GetValue(AttenuationProperty); }
set { this.SetValue(AttenuationProperty, value); }
}
/// <summary>
/// Range of this light. This is the maximum distance
/// of a pixel being lit by this light.
/// For details see: http://msdn.microsoft.com/en-us/library/windows/desktop/bb172279(v=vs.85).aspx
/// </summary>
public double Range
{
get { return (double)this.GetValue(RangeProperty); }
set { this.SetValue(RangeProperty, value); }
}
}
} | lcouz/helix-toolkit | Source/HelixToolkit.Wpf.SharpDX/Model/Lights3D/Light3D.cs | C# | mit | 10,093 |
import React from 'react';
import { dummyDate } from '../../../.storybook/helpers';
import { BuildEnvironmentSection } from './BuildEnvironmentSection';
export default {
title: 'admin/info/BuildEnvironmentSection',
component: BuildEnvironmentSection,
decorators: [
(fn) => <div className='rc-old'>{fn()}</div>,
],
};
const info = {
compile: {
platform: 'info.compile.platform',
arch: 'info.compile.arch',
osRelease: 'info.compile.osRelease',
nodeVersion: 'info.compile.nodeVersion',
date: dummyDate,
},
};
export const _default = () => <BuildEnvironmentSection info={info} />;
| Sing-Li/Rocket.Chat | client/admin/info/BuildEnvironmentSection.stories.js | JavaScript | mit | 599 |
<?php
class wfWAF {
const AUTH_COOKIE = 'wfwaf-authcookie';
/**
* @var wfWAF
*/
private static $instance;
private $blacklistedParams;
private $whitelistedParams;
private $variables = array();
/**
* @return wfWAF
*/
public static function getInstance() {
return self::$instance;
}
/**
* @param wfWAF $instance
*/
public static function setInstance($instance) {
self::$instance = $instance;
}
protected $rulesFile;
protected $trippedRules = array();
protected $failedRules = array();
protected $scores = array();
protected $scoresXSS = array();
protected $failScores = array();
protected $rules = array();
/**
* @var wfWAFRequestInterface
*/
private $request;
/**
* @var wfWAFStorageInterface
*/
private $storageEngine;
/**
* @var wfWAFEventBus
*/
private $eventBus;
private $debug = array();
private $disabledRules;
private $publicKey = '-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzovUDp/qu7r6LT5d8dLL
H/87aRrCjUd6XtnG+afAPVfMKNp4u4L+UuYfw1RfpfquP/zLMGdfmJCUp/oJywkW
Rkqo+y7pDuqIFQ59dHvizmYQRvaZgvincBDpey5Ek9AFfB9fqYYnH9+eQw8eLdQi
h6Zsh8RsuxFM2BW6JD9Km7L5Lyxw9jU+lye7I3ICYtUOVxc3n3bJT2SiIwHK57pW
g/asJEUDiYQzsaa90YPOLdf1Ysz2rkgnCduQaEGz/RPhgUrmZfKwq8puEmkh7Yee
auEa+7b+FGTKs7dUo2BNGR7OVifK4GZ8w/ajS0TelhrSRi3BBQCGXLzUO/UURUAh
1QIDAQAB
-----END PUBLIC KEY-----';
/**
* @param wfWAFRequestInterface $request
* @param wfWAFStorageInterface $storageEngine
* @param wfWAFEventBus $eventBus
* @param string|null $rulesFile
*/
public function __construct($request, $storageEngine, $eventBus = null, $rulesFile = null) {
$this->setRequest($request);
$this->setStorageEngine($storageEngine);
$this->setEventBus($eventBus ? $eventBus : new wfWAFEventBus);
$this->setCompiledRulesFile($rulesFile === null ? WFWAF_PATH . 'rules.php' : $rulesFile);
}
public function isReadOnly() {
$storage = $this->getStorageEngine();
if ($storage instanceof wfWAFStorageFile) {
return !wfWAFStorageFile::allowFileWriting();
}
return false;
}
public function getGlobal($global) {
if (wfWAFUtils::strpos($global, '.') === false) {
return null;
}
list($prefix, $_global) = explode('.', $global);
switch ($prefix) {
case 'request':
$method = "get" . ucfirst($_global);
if (method_exists('wfWAFRequestInterface', $method)) {
return call_user_func(array(
$this->getRequest(),
$method,
));
}
break;
case 'server':
$key = wfWAFUtils::strtoupper($_global);
if (isset($_SERVER) && array_key_exists($key, $_SERVER)) {
return $_SERVER[$key];
}
break;
}
return null;
}
/**
*
*/
public function runCron() {
if (!wfWAFStorageFile::allowFileWriting()) { return false; }
if ((
$this->getStorageEngine()->getConfig('attackDataNextInterval', null) === null ||
$this->getStorageEngine()->getConfig('attackDataNextInterval', time() + 0xffff) <= time()
) &&
$this->getStorageEngine()->hasPreviousAttackData(microtime(true) - (60 * 5))
) {
$this->sendAttackData();
}
$cron = $this->getStorageEngine()->getConfig('cron');
if (is_array($cron)) {
/** @var wfWAFCronEvent $event */
foreach ($cron as $index => $event) {
$event->setWaf($this);
if ($event->isInPast()) {
$event->fire();
$newEvent = $event->reschedule();
if ($newEvent instanceof wfWAFCronEvent && $newEvent !== $event) {
$cron[$index] = $newEvent;
} else {
unset($cron[$index]);
}
}
}
}
$this->getStorageEngine()->setConfig('cron', $cron);
}
/**
*
*/
public function run() {
$this->loadRules();
if ($this->isDisabled()) {
$this->eventBus->wafDisabled();
return;
}
$this->runMigrations();
$request = $this->getRequest();
if ($request->getBody('wfwaf-false-positive-verified') && $this->currentUserCanWhitelist() &&
wfWAFUtils::hash_equals($request->getBody('wfwaf-false-positive-nonce'), $this->getAuthCookieValue('nonce', ''))
) {
$urlParams = wfWAFUtils::json_decode($request->getBody('wfwaf-false-positive-params'), true);
if (is_array($urlParams) && $urlParams) {
$whitelistCount = 0;
foreach ($urlParams as $urlParam) {
$path = isset($urlParam['path']) ? $urlParam['path'] : false;
$paramKey = isset($urlParam['paramKey']) ? $urlParam['paramKey'] : false;
$ruleID = isset($urlParam['ruleID']) ? $urlParam['ruleID'] : false;
if ($path && $paramKey && $ruleID) {
$this->whitelistRuleForParam($path, $paramKey, $ruleID, array(
'timestamp' => time(),
'description' => 'Whitelisted by via false positive dialog',
'ip' => $request->getIP(),
));
$whitelistCount++;
}
}
exit("Successfully whitelisted $whitelistCount params.");
}
}
$ip = $this->getRequest()->getIP();
if ($this->isIPBlocked($ip)) {
$this->eventBus->prevBlocked($ip);
$e = new wfWAFBlockException();
$e->setRequest($this->getRequest());
$e->setFailedRules(array('blocked'));
$this->blockAction($e);
}
try {
$this->eventBus->beforeRunRules();
$this->runRules();
$this->eventBus->afterRunRules();
} catch (wfWAFAllowException $e) {
// Do nothing
$this->eventBus->allow($ip, $e);
} catch (wfWAFBlockException $e) {
$this->eventBus->block($ip, $e);
$this->blockAction($e);
} catch (wfWAFBlockXSSException $e) {
$this->eventBus->blockXSS($ip, $e);
$this->blockXSSAction($e);
} catch (wfWAFBlockSQLiException $e) {
$this->eventBus->blockSQLi($ip, $e);
$this->blockAction($e);
} catch (wfWAFLogException $e) {
$this->eventBus->log($ip, $e);
$this->logAction($e);
}
$this->runCron();
// Check if this is signed request and update ruleset.
$ping = $this->getRequest()->getBody('ping');
$pingResponse = $this->getRequest()->getBody('ping_response');
$wfIP = $this->isWordfenceIP($this->getRequest()->getIP());
$pingIsApiKey = wfWAFUtils::hash_equals($ping, sha1($this->getStorageEngine()->getConfig('apiKey')));
if ($ping && $pingResponse && $pingIsApiKey &&
$this->verifySignedRequest($this->getRequest()->getBody('signature'), $this->getStorageEngine()->getConfig('apiKey'))
) {
// $this->updateRuleSet(base64_decode($this->getRequest()->body('ping')));
$event = new wfWAFCronFetchRulesEvent(time() - 2);
$event->setWaf($this);
$event->fire();
header('Content-type: text/plain');
$pingResponse = preg_replace('/[a-zA-Z0-9]/', '', $this->getRequest()->getBody('ping_response'));
exit('Success: ' . sha1($this->getStorageEngine()->getConfig('apiKey') . $pingResponse));
}
}
/**
*
*/
public function loadRules() {
if (file_exists($this->getCompiledRulesFile())) {
// Acquire lock on this file so we're not including it while it's being written in another process.
$handle = fopen($this->getCompiledRulesFile(), 'r');
flock($handle, LOCK_SH);
/** @noinspection PhpIncludeInspection */
include $this->getCompiledRulesFile();
flock($handle, LOCK_UN);
fclose($handle);
}
}
/**
* @throws wfWAFAllowException|wfWAFBlockException|wfWAFBlockXSSException
*/
public function runRules() {
/**
* @var int $ruleID
* @var wfWAFRule $rule
*/
foreach ($this->getRules() as $ruleID => $rule) {
if (!$this->isRuleDisabled($ruleID)) {
$rule->evaluate();
}
}
$blockActions = array();
foreach ($this->failedRules as $paramKey => $categories) {
foreach ($categories as $category => $failedRules) {
foreach ($failedRules as $failedRule) {
/**
* @var wfWAFRule $rule
* @var wfWAFRuleComparisonFailure $failedComparison
*/
$rule = $failedRule['rule'];
$failedComparison = $failedRule['failedComparison'];
$action = $failedRule['action'];
$score = $rule->getScore();
if ($failedComparison->hasMultiplier()) {
$score *= $failedComparison->getMultiplier();
}
if (!isset($this->failScores[$category])) {
$this->failScores[$category] = 100;
}
if (!isset($this->scores[$paramKey][$category])) {
$this->scores[$paramKey][$category] = 0;
}
$this->scores[$paramKey][$category] += $score;
if ($this->scores[$paramKey][$category] >= $this->failScores[$category]) {
$blockActions[$category] = array(
'paramKey' => $paramKey,
'score' => $this->scores[$paramKey][$category],
'action' => $action,
'rule' => $rule,
'failedComparison' => $failedComparison,
);
}
$this->debug[] = sprintf("%s tripped %s for %s->%s('%s'). Score %d/%d", $paramKey, $action,
$category, $failedComparison->getAction(), $failedComparison->getExpected(),
$this->scores[$paramKey][$category], $this->failScores[$category]);
}
}
}
uasort($blockActions, array($this, 'sortBlockActions'));
foreach ($blockActions as $blockAction) {
call_user_func(array($this, $blockAction['action']), $blockAction['rule'], $blockAction['failedComparison'], false);
}
}
/**
* @param array $a
* @param array $b
* @return int
*/
private function sortBlockActions($a, $b) {
if ($a['score'] == $b['score']) {
return 0;
}
return ($a['score'] > $b['score']) ? -1 : 1;
}
protected function runMigrations() {
$currentVersion = $this->getStorageEngine()->getConfig('version');
if (!$currentVersion || version_compare($currentVersion, WFWAF_VERSION) === -1) {
if (!$currentVersion) {
$cron = array(
new wfWAFCronFetchRulesEvent(time() +
(86400 * ($this->getStorageEngine()->getConfig('isPaid') ? .5 : 7))),
new wfWAFCronFetchIPListEvent(time() + 86400),
new wfWAFCronFetchBlacklistPrefixesEvent(time() + 7200),
);
$this->getStorageEngine()->setConfig('cron', $cron);
}
// Any migrations to newer versions go here.
if ($currentVersion === '1.0.0') {
$cron = $this->getStorageEngine()->getConfig('cron');
if (is_array($cron)) {
$cron[] = new wfWAFCronFetchIPListEvent(time() + 86400);
}
$this->getStorageEngine()->setConfig('cron', $cron);
}
if (version_compare($currentVersion, '1.0.2') === -1) {
$event = new wfWAFCronFetchRulesEvent(time() - 2);
$event->setWaf($this);
$event->fire();
}
if (version_compare($currentVersion, '1.0.3') === -1) {
$this->getStorageEngine()->purgeIPBlocks();
$cron = $this->getStorageEngine()->getConfig('cron');
if (is_array($cron)) {
$cron[] = new wfWAFCronFetchBlacklistPrefixesEvent(time() + 7200);
}
$this->getStorageEngine()->setConfig('cron', $cron);
$event = new wfWAFCronFetchBlacklistPrefixesEvent(time() - 2);
$event->setWaf($this);
$event->fire();
}
$this->getStorageEngine()->setConfig('version', WFWAF_VERSION);
}
}
/**
* @param wfWAFRule $rule
*/
public function tripRule($rule) {
$this->trippedRules[] = $rule;
$action = $rule->getAction();
$scores = $rule->getScore();
$categories = $rule->getCategory();
if (is_array($categories)) {
for ($i = 0; $i < count($categories); $i++) {
if (is_array($action) && !empty($action[$i])) {
$a = $action[$i];
} else {
$a = $action;
}
if ($this->isAllowedAction($a)) {
$r = clone $rule;
$r->setScore($scores[$i]);
$r->setCategory($categories[$i]);
/** @var wfWAFRuleComparisonFailure $failed */
foreach ($r->getComparisonGroup()->getFailedComparisons() as $failed) {
call_user_func(array($this, $a), $r, $failed);
}
}
}
} else {
if ($this->isAllowedAction($action)) {
/** @var wfWAFRuleComparisonFailure $failed */
foreach ($rule->getComparisonGroup()->getFailedComparisons() as $failed) {
call_user_func(array($this, $action), $rule, $failed);
}
}
}
}
/**
* @return bool
*/
public function isInLearningMode() {
return $this->getStorageEngine()->isInLearningMode();
}
/**
* @return bool
*/
public function isDisabled() {
return $this->getStorageEngine()->isDisabled() || !WFWAF_ENABLED;
}
public function hasOpenSSL() {
return function_exists('openssl_verify');
}
/**
* @param string $signature
* @param string $data
* @return bool
*/
public function verifySignedRequest($signature, $data) {
if (!$this->hasOpenSSL()) {
return false;
}
$valid = openssl_verify($data, $signature, $this->getPublicKey(), OPENSSL_ALGO_SHA1);
return $valid === 1;
}
/**
* @param string $hash
* @param string $data
* @return bool
*/
public function verifyHashedRequest($hash, $data) {
if ($this->hasOpenSSL()) {
return false;
}
return wfWAFUtils::hash_equals($hash,
wfWAFUtils::hash_hmac('sha1', $data, $this->getStorageEngine()->getConfig('apiKey')));
}
/**
* @param string $ip
* @return bool
*/
public function isWordfenceIP($ip) {
if (preg_match('/69.46.36.(\d+)/', $ip, $matches)) {
return $matches[1] >= 1 && $matches[1] <= 32;
}
return false;
}
/**
* @return array
*/
public function getMalwareSignatures() {
try {
$encoded = $this->getStorageEngine()->getConfig('filePatterns');
if (empty($encoded)) {
return array();
}
$authKey = $this->getStorageEngine()->getConfig('authKey');
$encoded = base64_decode($encoded);
$paddedKey = wfWAFUtils::substr(str_repeat($authKey, ceil(strlen($encoded) / strlen($authKey))), 0, strlen($encoded));
$json = $encoded ^ $paddedKey;
$signatures = wfWAFUtils::json_decode($json, true);
if (!is_array($signatures)) {
return array();
}
return $signatures;
}
catch (Exception $e) {
//Ignore
}
return array();
}
/**
* @param array $signatures
* @param bool $updateLastUpdatedTimestamp
*/
public function setMalwareSignatures($signatures, $updateLastUpdatedTimestamp = true) {
try {
if (!is_array($signatures)) {
$signatures = array();
}
$authKey = $this->getStorageEngine()->getConfig('authKey');
$json = wfWAFUtils::json_encode($signatures);
$paddedKey = wfWAFUtils::substr(str_repeat($authKey, ceil(strlen($json) / strlen($authKey))), 0, strlen($json));
$payload = $json ^ $paddedKey;
$this->getStorageEngine()->setConfig('filePatterns', base64_encode($payload));
if ($updateLastUpdatedTimestamp) {
$this->getStorageEngine()->setConfig('signaturesLastUpdated', is_int($updateLastUpdatedTimestamp) ? $updateLastUpdatedTimestamp : time());
}
}
catch (Exception $e) {
//Ignore
}
}
/**
* @return array
*/
public function getMalwareSignatureCommonStrings() {
try {
$encoded = $this->getStorageEngine()->getConfig('filePatternCommonStrings');
if (empty($encoded)) {
return array();
}
//Grab the list of words
$authKey = $this->getStorageEngine()->getConfig('authKey');
$encoded = base64_decode($encoded);
$paddedKey = wfWAFUtils::substr(str_repeat($authKey, ceil(strlen($encoded) / strlen($authKey))), 0, strlen($encoded));
$json = $encoded ^ $paddedKey;
$commonStrings = wfWAFUtils::json_decode($json, true);
if (!is_array($commonStrings)) {
return array();
}
//Grab the list of indexes
$json = $this->getStorageEngine()->getConfig('filePatternIndexes');
if (empty($json)) {
return array();
}
$signatureIndexes = wfWAFUtils::json_decode($json, true);
if (!is_array($signatureIndexes)) {
return array();
}
//Reconcile the list of indexes and transform into a list of words
$signatureCommonWords = array();
foreach ($signatureIndexes as $indexSet) {
$entry = array();
foreach ($indexSet as $i) {
if (isset($commonStrings[$i])) {
$entry[] = &$commonStrings[$i];
}
}
$signatureCommonWords[] = $entry;
}
return $signatureCommonWords;
}
catch (Exception $e) {
//Ignore
}
return array();
}
/**
* @param array $commonStrings
* @param array $signatureIndexes
*/
public function setMalwareSignatureCommonStrings($commonStrings, $signatureIndexes) {
try {
if (!is_array($commonStrings)) {
$commonStrings = array();
}
if (!is_array($signatureIndexes)) {
$signatureIndexes = array();
}
$authKey = $this->getStorageEngine()->getConfig('authKey');
$json = wfWAFUtils::json_encode($commonStrings);
$paddedKey = wfWAFUtils::substr(str_repeat($authKey, ceil(strlen($json) / strlen($authKey))), 0, strlen($json));
$payload = $json ^ $paddedKey;
$this->getStorageEngine()->setConfig('filePatternCommonStrings', base64_encode($payload));
$payload = wfWAFUtils::json_encode($signatureIndexes);
$this->getStorageEngine()->setConfig('filePatternIndexes', $payload);
}
catch (Exception $e) {
//Ignore
}
}
/**
* @param $rules
* @param bool|int $updateLastUpdatedTimestamp
* @throws wfWAFBuildRulesException
*/
public function updateRuleSet($rules, $updateLastUpdatedTimestamp = true) {
try {
if (is_string($rules)) {
$ruleString = $rules;
$parser = new wfWAFRuleParser(new wfWAFRuleLexer($rules), $this);
$rules = $parser->parse();
}
if (!is_writable($this->getCompiledRulesFile())) {
throw new wfWAFBuildRulesException('Rules file not writable.');
}
wfWAFStorageFile::atomicFilePutContents($this->getCompiledRulesFile(), sprintf(<<<PHP
<?php
if (!defined('WFWAF_VERSION')) {
exit('Access denied');
}
/*
This file is generated automatically. Any changes made will be lost.
*/
%s?>
PHP
, $this->buildRuleSet($rules)), 'rules');
if (!empty($ruleString) && !WFWAF_DEBUG) {
wfWAFStorageFile::atomicFilePutContents($this->getStorageEngine()->getRulesDSLCacheFile(), $ruleString, 'rules');
}
if ($updateLastUpdatedTimestamp) {
$this->getStorageEngine()->setConfig('rulesLastUpdated',
is_int($updateLastUpdatedTimestamp) ? $updateLastUpdatedTimestamp : time());
}
} catch (wfWAFBuildRulesException $e) {
// Do something.
throw $e;
}
}
/**
* @param string $rules
* @return string
* @throws wfWAFException
*/
public function buildRuleSet($rules) {
if (is_string($rules)) {
$parser = new wfWAFRuleParser(new wfWAFRuleLexer($rules), $this);
$rules = $parser->parse();
}
if (!array_key_exists('rules', $rules) || !is_array($rules['rules'])) {
throw new wfWAFBuildRulesException('Invalid rule format passed to buildRuleSet.');
}
$exportedCode = '';
if (isset($rules['scores']) && is_array($rules['scores'])) {
foreach ($rules['scores'] as $category => $score) {
$exportedCode .= sprintf("\$this->failScores[%s] = %d;\n", var_export($category, true), $score);
}
$exportedCode .= "\n";
}
if (isset($rules['variables']) && is_array($rules['variables'])) {
foreach ($rules['variables'] as $var => $value) {
$exportedCode .= sprintf("\$this->variables[%s] = %s;\n", var_export($var, true),
($value instanceof wfWAFRuleVariable) ? $value->render() : var_export($value, true));
}
$exportedCode .= "\n";
}
foreach (array('blacklistedParams', 'whitelistedParams') as $key) {
if (isset($rules[$key]) && is_array($rules[$key])) {
/** @var wfWAFRuleParserURLParam $urlParam */
foreach ($rules[$key] as $urlParam) {
if ($urlParam->getConditional()) {
$exportedCode .= sprintf("\$this->{$key}[%s][] = array(\n%s => %s,\n%s => %s,\n%s => %s\n);\n", var_export($urlParam->getParam(), true),
var_export('url', true), var_export($urlParam->getUrl(), true),
var_export('rules', true), var_export($urlParam->getRules(), true),
var_export('conditional', true), $urlParam->getConditional()->render());
}
else {
if ($urlParam->getRules()) {
$url = array(
'url' => $urlParam->getUrl(),
'rules' => $urlParam->getRules(),
);
} else {
$url = $urlParam->getUrl();
}
$exportedCode .= sprintf("\$this->{$key}[%s][] = %s;\n", var_export($urlParam->getParam(), true),
var_export($url, true));
}
}
$exportedCode .= "\n";
}
}
/** @var wfWAFRule $rule */
foreach ($rules['rules'] as $rule) {
$rule->setWAF($this);
$exportedCode .= sprintf(<<<HTML
\$this->rules[%d] = %s;
HTML
,
$rule->getRuleID(),
$rule->render()
);
}
return $exportedCode;
}
/**
* @param $rules
* @return wfWAFRuleComparisonGroup
* @throws wfWAFBuildRulesException
*/
protected function _buildRuleSet($rules) {
$ruleGroup = new wfWAFRuleComparisonGroup();
foreach ($rules as $rule) {
if (!array_key_exists('type', $rule)) {
throw new wfWAFBuildRulesException('Invalid rule: type not set.');
}
switch ($rule['type']) {
case 'comparison_group':
if (!array_key_exists('comparisons', $rule) || !is_array($rule['comparisons'])) {
throw new wfWAFBuildRulesException('Invalid rule format passed to _buildRuleSet.');
}
$ruleGroup->add($this->_buildRuleSet($rule['comparisons']));
break;
case 'comparison':
if (array_key_exists('parameter', $rule)) {
$rule['parameters'] = array($rule['parameter']);
}
foreach (array('action', 'expected', 'parameters') as $ruleRequirement) {
if (!array_key_exists($ruleRequirement, $rule)) {
throw new wfWAFBuildRulesException("Invalid rule: $ruleRequirement not set.");
}
}
$ruleGroup->add(new wfWAFRuleComparison($this, $rule['action'], $rule['expected'], $rule['parameters']));
break;
case 'operator':
if (!array_key_exists('operator', $rule)) {
throw new wfWAFBuildRulesException('Invalid rule format passed to _buildRuleSet. operator not passed.');
}
$ruleGroup->add(new wfWAFRuleLogicalOperator($rule['operator']));
break;
default:
throw new wfWAFBuildRulesException("Invalid rule type [{$rule['type']}] passed to _buildRuleSet.");
}
}
return $ruleGroup;
}
public function isRuleDisabled($ruleID) {
if ($this->disabledRules === null) {
$this->disabledRules = $this->getStorageEngine()->getConfig('disabledRules');
if (!is_array($this->disabledRules)) {
$this->disabledRules = array();
}
}
return !empty($this->disabledRules[$ruleID]);
}
/**
* @param wfWAFRule $rule
* @param wfWAFRuleComparisonFailure $failedComparison
* @throws wfWAFBlockException
*/
public function fail($rule, $failedComparison) {
$category = $rule->getCategory();
$paramKey = $failedComparison->getParamKey();
$this->failedRules[$paramKey][$category][] = array(
'rule' => $rule,
'failedComparison' => $failedComparison,
'action' => 'block',
);
}
/**
* @param wfWAFRule $rule
* @param wfWAFRuleComparisonFailure $failedComparison
* @throws wfWAFBlockException
*/
public function failXSS($rule, $failedComparison) {
$category = $rule->getCategory();
$paramKey = $failedComparison->getParamKey();
$this->failedRules[$paramKey][$category][] = array(
'rule' => $rule,
'failedComparison' => $failedComparison,
'action' => 'blockXSS',
);
}
/**
* @param wfWAFRule $rule
* @param wfWAFRuleComparisonFailure $failedComparison
* @throws wfWAFBlockException
*/
public function failSQLi($rule, $failedComparison) {
$category = $rule->getCategory();
$paramKey = $failedComparison->getParamKey();
$this->failedRules[$paramKey][$category][] = array(
'rule' => $rule,
'failedComparison' => $failedComparison,
'action' => 'blockSQLi',
);
}
/**
* @param wfWAFRule $rule
* @param wfWAFRuleComparisonFailure $failedComparison
* @throws wfWAFAllowException
*/
public function allow($rule, $failedComparison) {
// Exclude this request from further blocking
$e = new wfWAFAllowException();
$e->setFailedRules(array($rule));
$e->setParamKey($failedComparison->getParamKey());
$e->setParamValue($failedComparison->getParamValue());
$e->setRequest($this->getRequest());
throw $e;
}
/**
* @param wfWAFRule $rule
* @param wfWAFRuleComparisonFailure $failedComparison
* @param bool $updateFailedRules
* @throws wfWAFBlockException
*/
public function block($rule, $failedComparison, $updateFailedRules = true) {
$paramKey = $failedComparison->getParamKey();
$category = $rule->getCategory();
if ($updateFailedRules) {
$this->failedRules[$paramKey][$category][] = array(
'rule' => $rule,
'failedComparison' => $failedComparison,
'action' => 'block',
);
}
$e = new wfWAFBlockException();
$e->setFailedRules(array($rule));
$e->setParamKey($failedComparison->getParamKey());
$e->setParamValue($failedComparison->getParamValue());
$e->setRequest($this->getRequest());
throw $e;
}
/**
* @param wfWAFRule $rule
* @param wfWAFRuleComparisonFailure $failedComparison
* @param bool $updateFailedRules
* @throws wfWAFBlockXSSException
*/
public function blockXSS($rule, $failedComparison, $updateFailedRules = true) {
$paramKey = $failedComparison->getParamKey();
$category = $rule->getCategory();
if ($updateFailedRules) {
$this->failedRules[$paramKey][$category][] = array(
'rule' => $rule,
'failedComparison' => $failedComparison,
'action' => 'blockXSS',
);
}
$e = new wfWAFBlockXSSException();
$e->setFailedRules(array($rule));
$e->setParamKey($failedComparison->getParamKey());
$e->setParamValue($failedComparison->getParamValue());
$e->setRequest($this->getRequest());
throw $e;
}
/**
* @param wfWAFRule $rule
* @param wfWAFRuleComparisonFailure $failedComparison
* @param bool $updateFailedRules
* @throws wfWAFBlockSQLiException
*/
public function blockSQLi($rule, $failedComparison, $updateFailedRules = true) {
// Verify the param looks like SQLi to help reduce false positives.
if (!wfWAFSQLiParser::testForSQLi($failedComparison->getParamValue())) {
return;
}
$paramKey = $failedComparison->getParamKey();
$category = $rule->getCategory();
if ($updateFailedRules) {
$this->failedRules[$paramKey][$category][] = array(
'rule' => $rule,
'failedComparison' => $failedComparison,
'action' => 'blockXSS',
);
}
$e = new wfWAFBlockSQLiException();
$e->setFailedRules(array($rule));
$e->setParamKey($failedComparison->getParamKey());
$e->setParamValue($failedComparison->getParamValue());
$e->setRequest($this->getRequest());
throw $e;
}
/**
* @todo Hook up $httpCode
* @param wfWAFBlockException $e
* @param int $httpCode
*/
public function blockAction($e, $httpCode = 403, $redirect = false, $template = null) {
$this->getStorageEngine()->logAttack($e->getFailedRules(), $e->getParamKey(), $e->getParamValue(), $e->getRequest(), $e->getRequest()->getMetadata());
if ($redirect) {
wfWAFUtils::redirect($redirect); // exits and emits no cache headers
}
if ($httpCode == 503) {
wfWAFUtils::statusHeader(503);
wfWAFUtils::doNotCache();
if ($secsToGo = $e->getRequest()->getMetadata('503Time')) {
header('Retry-After: ' . $secsToGo);
}
exit($this->getUnavailableMessage($e->getRequest()->getMetadata('503Reason'), $template));
}
header('HTTP/1.0 403 Forbidden');
wfWAFUtils::doNotCache();
exit($this->getBlockedMessage($template));
}
/**
* @todo Hook up $httpCode
* @param wfWAFBlockXSSException $e
* @param int $httpCode
*/
public function blockXSSAction($e, $httpCode = 403, $redirect = false) {
$this->getStorageEngine()->logAttack($e->getFailedRules(), $e->getParamKey(), $e->getParamValue(), $e->getRequest(), $e->getRequest()->getMetadata());
if ($redirect) {
wfWAFUtils::redirect($redirect); // exits and emits no cache headers
}
if ($httpCode == 503) {
wfWAFUtils::statusHeader(503);
wfWAFUtils::doNotCache();
if ($secsToGo = $e->getRequest()->getMetadata('503Time')) {
header('Retry-After: ' . $secsToGo);
}
exit($this->getUnavailableMessage($e->getRequest()->getMetadata('503Reason')));
}
header('HTTP/1.0 403 Forbidden');
wfWAFUtils::doNotCache();
exit($this->getBlockedMessage());
}
public function logAction($e) {
$this->getStorageEngine()->logAttack(array('logged'), $e->getParamKey(), $e->getParamValue(), $this->getRequest());
}
/**
* @return string
*/
public function getBlockedMessage($template = null) {
if ($template === null) {
if ($this->currentUserCanWhitelist()) {
$template = '403-roadblock';
}
else {
$template = '403';
}
}
try {
$homeURL = wfWAF::getInstance()->getStorageEngine()->getConfig('homeURL');
$siteURL = wfWAF::getInstance()->getStorageEngine()->getConfig('siteURL');
}
catch (Exception $e) {
//Do nothing
}
return wfWAFView::create($template, array(
'waf' => $this,
'homeURL' => $homeURL,
'siteURL' => $siteURL,
))->render();
}
/**
* @return string
*/
public function getUnavailableMessage($reason = '', $template = null) {
if ($template === null) { $template = '503'; }
try {
$homeURL = wfWAF::getInstance()->getStorageEngine()->getConfig('homeURL');
$siteURL = wfWAF::getInstance()->getStorageEngine()->getConfig('siteURL');
}
catch (Exception $e) {
//Do nothing
}
return wfWAFView::create($template, array(
'waf' => $this,
'reason' => $reason,
'homeURL' => $homeURL,
'siteURL' => $siteURL,
))->render();
}
/**
*
*/
public function whitelistFailedRules() {
foreach ($this->failedRules as $paramKey => $categories) {
foreach ($categories as $category => $failedRules) {
foreach ($failedRules as $failedRule) {
/**
* @var wfWAFRule $rule
* @var wfWAFRuleComparisonFailure $failedComparison
*/
$rule = $failedRule['rule'];
if ($rule->getWhitelist()) {
$failedComparison = $failedRule['failedComparison'];
$data = array(
'timestamp' => time(),
'description' => 'Whitelisted while in Learning Mode.',
'ip' => $this->getRequest()->getIP(),
);
if (function_exists('get_current_user_id')) {
$data['userID'] = get_current_user_id();
}
$this->whitelistRuleForParam($this->getRequest()->getPath(), $failedComparison->getParamKey(),
$rule->getRuleID(), $data);
}
}
}
}
}
/**
* @param string $path
* @param string $paramKey
* @param int $ruleID
* @param array $data
*/
public function whitelistRuleForParam($path, $paramKey, $ruleID, $data = array()) {
if ($this->isParamKeyURLBlacklisted($ruleID, $paramKey, $path)) {
return;
}
$whitelist = $this->getStorageEngine()->getConfig('whitelistedURLParams');
if (!is_array($whitelist)) {
$whitelist = array();
}
if (is_array($ruleID)) {
foreach ($ruleID as $id) {
$whitelist[base64_encode($path) . "|" . base64_encode($paramKey)][$id] = $data;
}
} else {
$whitelist[base64_encode($path) . "|" . base64_encode($paramKey)][$ruleID] = $data;
}
$this->getStorageEngine()->setConfig('whitelistedURLParams', $whitelist);
}
/**
* @param int $ruleID
* @param string $urlPath
* @param string $paramKey
* @return bool
*/
public function isRuleParamWhitelisted($ruleID, $urlPath, $paramKey) {
if ($this->isParamKeyURLBlacklisted($ruleID, $paramKey, $urlPath)) {
return false;
}
if (is_array($this->whitelistedParams) && array_key_exists($paramKey, $this->whitelistedParams)
&& is_array($this->whitelistedParams[$paramKey])
) {
foreach ($this->whitelistedParams[$paramKey] as $urlRegex) {
if (is_array($urlRegex)) {
if (!in_array($ruleID, $urlRegex['rules'])) {
continue;
}
if (isset($urlRegex['conditional']) && !$urlRegex['conditional']->evaluate()) {
continue;
}
$urlRegex = $urlRegex['url'];
}
if (preg_match($urlRegex, $urlPath)) {
return true;
}
}
}
$whitelistKey = base64_encode($urlPath) . "|" . base64_encode($paramKey);
$whitelist = $this->getStorageEngine()->getConfig('whitelistedURLParams', array());
if (!is_array($whitelist)) {
$whitelist = array();
}
if (array_key_exists($whitelistKey, $whitelist)) {
foreach (array('all', $ruleID) as $key) {
if (array_key_exists($key, $whitelist[$whitelistKey])) {
$ruleData = $whitelist[$whitelistKey][$key];
if (is_array($ruleData) && array_key_exists('disabled', $ruleData)) {
return !$ruleData['disabled'];
} else if ($ruleData) {
return true;
}
}
}
}
return false;
}
/**
*
*/
public function sendAttackData() {
if ($this->getStorageEngine()->getConfig('attackDataKey', false) === false) {
$this->getStorageEngine()->setConfig('attackDataKey', mt_rand(0, 0xfff));
}
if (!$this->getStorageEngine()->getConfig('other_WFNet', true)) {
$this->getStorageEngine()->truncateAttackData();
$this->getStorageEngine()->unsetConfig('attackDataNextInterval');
return;
}
$request = new wfWAFHTTP();
try {
$response = wfWAFHTTP::get(
sprintf(WFWAF_API_URL_SEC . "waf-rules/%d.txt", $this->getStorageEngine()->getConfig('attackDataKey')),
$request);
if ($response instanceof wfWAFHTTPResponse) {
if ($response->getBody() === 'ok') {
$request = new wfWAFHTTP();
$request->setHeaders(array(
'Content-Type' => 'application/json',
));
$response = wfWAFHTTP::post(WFWAF_API_URL_SEC . "?" . http_build_query(array(
'action' => 'send_waf_attack_data',
'k' => $this->getStorageEngine()->getConfig('apiKey'),
's' => $this->getStorageEngine()->getConfig('siteURL') ? $this->getStorageEngine()->getConfig('siteURL') :
sprintf('%s://%s/', $this->getRequest()->getProtocol(), rawurlencode($this->getRequest()->getHost())),
'h' => $this->getStorageEngine()->getConfig('homeURL') ? $this->getStorageEngine()->getConfig('homeURL') :
sprintf('%s://%s/', $this->getRequest()->getProtocol(), rawurlencode($this->getRequest()->getHost())),
't' => microtime(true),
), null, '&'), $this->getStorageEngine()->getAttackData(), $request);
if ($response instanceof wfWAFHTTPResponse && $response->getBody()) {
$jsonData = wfWAFUtils::json_decode($response->getBody(), true);
if (is_array($jsonData) && array_key_exists('success', $jsonData)) {
$this->getStorageEngine()->truncateAttackData();
$this->getStorageEngine()->unsetConfig('attackDataNextInterval');
}
if (array_key_exists('data', $jsonData) && array_key_exists('watchedIPList', $jsonData['data'])) {
$this->getStorageEngine()->setConfig('watchedIPs', $jsonData['data']['watchedIPList']);
}
}
} else if (is_string($response->getBody()) && preg_match('/next check in: ([0-9]+)/', $response->getBody(), $matches)) {
$this->getStorageEngine()->setConfig('attackDataNextInterval', time() + $matches[1]);
if ($this->getStorageEngine()->isAttackDataFull()) {
$this->getStorageEngine()->truncateAttackData();
}
}
// Could be that the server is down, so hold off on sending data for a little while.
} else {
$this->getStorageEngine()->setConfig('attackDataNextInterval', time() + 7200);
}
} catch (wfWAFHTTPTransportException $e) {
error_log($e->getMessage());
}
}
/**
* @param string $action
* @return array
*/
public function isAllowedAction($action) {
static $actions;
if (!isset($actions)) {
$actions = array_flip($this->getAllowedActions());
}
return array_key_exists($action, $actions);
}
/**
* @return array
*/
public function getAllowedActions() {
return array('fail', 'allow', 'block', 'failXSS', 'blockXSS', 'failSQLi', 'blockSQLi');
}
/**
*
*/
public function uninstall() {
@unlink($this->getCompiledRulesFile());
$this->getStorageEngine()->uninstall();
}
/**
* @param int $ruleID
* @param string $paramKey
* @param string $urlPath
* @return bool
*/
public function isParamKeyURLBlacklisted($ruleID, $paramKey, $urlPath) {
if (is_array($this->blacklistedParams) && array_key_exists($paramKey, $this->blacklistedParams)
&& is_array($this->blacklistedParams[$paramKey])
) {
foreach ($this->blacklistedParams[$paramKey] as $urlRegex) {
if (is_array($urlRegex)) {
if (!in_array($ruleID, $urlRegex['rules'])) {
continue;
}
if (isset($urlRegex['conditional']) && !$urlRegex['conditional']->evaluate()) {
continue;
}
$urlRegex = $urlRegex['url'];
}
if (preg_match($urlRegex, $urlPath)) {
return true;
}
}
}
return false;
}
/**
* @return bool
*/
public function currentUserCanWhitelist() {
if ($authCookie = $this->parseAuthCookie()) {
return $authCookie['role'] === 'administrator';
}
return false;
}
/**
* @param string|null $cookieVal
* @return bool
*/
public function parseAuthCookie($cookieVal = null) {
if ($cookieVal === null) {
$cookieName = $this->getAuthCookieName();
$cookieVal = !empty($_COOKIE[$cookieName]) && is_string($_COOKIE[$cookieName]) ? $_COOKIE[$cookieName] : '';
}
$pieces = explode('|', $cookieVal);
if (count($pieces) !== 3) {
return false;
}
list($userID, $role, $signature) = $pieces;
if (wfWAFUtils::hash_equals($signature, $this->getAuthCookieValue($userID, $role))) {
return array(
'userID' => $userID,
'role' => $role,
);
}
return false;
}
/**
* @param int|string $userID
* @param string $role
* @return bool|string
*/
public function getAuthCookieValue($userID, $role) {
$algo = function_exists('hash') ? 'sha256' : 'sha1';
return wfWAFUtils::hash_hmac($algo, $userID . $role . floor(time() / 43200), $this->getStorageEngine()->getConfig('authKey'));
}
/**
* @param string $action
* @return bool|string
*/
public function createNonce($action) {
$userInfo = $this->parseAuthCookie();
if ($userInfo === false) {
$userInfo = array('userID' => 0, 'role' => ''); // Use an empty user like WordPress would
}
$userID = $userInfo['userID'];
$role = $userInfo['role'];
$algo = function_exists('hash') ? 'sha256' : 'sha1';
return wfWAFUtils::hash_hmac($algo, $action . $userID . $role . floor(time() / 43200), $this->getStorageEngine()->getConfig('authKey'));
}
/**
* @param string $nonce
* @param string $action
* @return bool
*/
public function verifyNonce($nonce, $action) {
if (empty($nonce)) {
return false;
}
return wfWAFUtils::hash_equals($nonce, $this->createNonce($action));
}
/**
* @param string|null $host
* @return string
*/
public function getAuthCookieName($host = null) {
if ($host === null) {
$host = $this->getRequest()->getHost();
}
return self::AUTH_COOKIE . '-' . md5($host);
}
/**
* @return string
*/
public function getCompiledRulesFile() {
return $this->rulesFile;
}
/**
* @param string $rulesFile
*/
public function setCompiledRulesFile($rulesFile) {
$this->rulesFile = $rulesFile;
}
/**
* @param $ip
* @return mixed
*/
public function isIPBlocked($ip) {
return $this->getStorageEngine()->isIPBlocked($ip);
}
/**
* @param wfWAFRequest $request
* @return bool|array false if it should not be blocked, otherwise an array defining the context for the final action
*/
public function willPerformFinalAction($request) {
return false;
}
/**
* @return array
*/
public function getTrippedRules() {
return $this->trippedRules;
}
/**
* @return array
*/
public function getTrippedRuleIDs() {
$ret = array();
/** @var wfWAFRule $rule */
foreach ($this->getTrippedRules() as $rule) {
$ret[] = $rule->getRuleID();
}
return $ret;
}
public function showBench() {
return sprintf("Bench: %f seconds\n\n", microtime(true) - $this->getRequest()->getTimestamp());
}
public function debug() {
return join("\n", $this->debug) . "\n\n" . $this->showBench();
// $debug = '';
// /** @var wfWAFRule $rule */
// foreach ($this->trippedRules as $rule) {
// $debug .= $rule->debug();
// }
// return $debug;
}
/**
* @return array
*/
public function getScores() {
return $this->scores;
}
/**
* @param string $var
* @return null
*/
public function getVariable($var) {
if (array_key_exists($var, $this->variables)) {
return $this->variables[$var];
}
return null;
}
/**
* @return wfWAFRequestInterface
*/
public function getRequest() {
return $this->request;
}
/**
* @param wfWAFRequestInterface $request
*/
public function setRequest($request) {
$this->request = $request;
}
/**
* @return wfWAFStorageInterface
*/
public function getStorageEngine() {
return $this->storageEngine;
}
/**
* @param wfWAFStorageInterface $storageEngine
*/
public function setStorageEngine($storageEngine) {
$this->storageEngine = $storageEngine;
}
/**
* @return wfWAFEventBus
*/
public function getEventBus() {
return $this->eventBus;
}
/**
* @param wfWAFEventBus $eventBus
*/
public function setEventBus($eventBus) {
$this->eventBus = $eventBus;
}
/**
* @return array
*/
public function getRules() {
return $this->rules;
}
/**
* @param array $rules
*/
public function setRules($rules) {
$this->rules = $rules;
}
/**
* @param int $ruleID
* @return null|wfWAFRule
*/
public function getRule($ruleID) {
$rules = $this->getRules();
if (is_array($rules) && array_key_exists($ruleID, $rules)) {
return $rules[$ruleID];
}
return null;
}
/**
* @return string
*/
public function getPublicKey() {
return $this->publicKey;
}
/**
* @param string $publicKey
*/
public function setPublicKey($publicKey) {
$this->publicKey = $publicKey;
}
/**
* @return array
*/
public function getFailedRules() {
return $this->failedRules;
}
}
/**
* Serialized for use with the WAF cron.
*/
abstract class wfWAFCronEvent {
abstract public function fire();
abstract public function reschedule();
protected $fireTime;
private $waf;
/**
* @param int $fireTime
*/
public function __construct($fireTime) {
$this->setFireTime($fireTime);
}
/**
* @param int|null $time
* @return bool
*/
public function isInPast($time = null) {
if ($time === null) {
$time = time();
}
return $this->getFireTime() <= $time;
}
public function __sleep() {
return array('fireTime');
}
/**
* @return mixed
*/
public function getFireTime() {
return $this->fireTime;
}
/**
* @param mixed $fireTime
*/
public function setFireTime($fireTime) {
$this->fireTime = $fireTime;
}
/**
* @return wfWAF
*/
public function getWaf() {
return $this->waf;
}
/**
* @param wfWAF $waf
*/
public function setWaf($waf) {
$this->waf = $waf;
}
}
class wfWAFCronFetchRulesEvent extends wfWAFCronEvent {
/**
* @var wfWAFHTTPResponse
*/
private $response;
public function fire() {
$waf = $this->getWaf();
if (!$waf) {
return false;
}
$success = true;
$guessSiteURL = sprintf('%s://%s/', $waf->getRequest()->getProtocol(), $waf->getRequest()->getHost());
try {
$this->response = wfWAFHTTP::get(WFWAF_API_URL_SEC . "?" . http_build_query(array(
'action' => 'get_waf_rules',
'k' => $waf->getStorageEngine()->getConfig('apiKey'),
's' => $waf->getStorageEngine()->getConfig('siteURL') ? $waf->getStorageEngine()->getConfig('siteURL') : $guessSiteURL,
'h' => $waf->getStorageEngine()->getConfig('homeURL') ? $waf->getStorageEngine()->getConfig('homeURL') : $guessSiteURL,
'openssl' => $waf->hasOpenSSL() ? 1 : 0,
'betaFeed' => (int) $waf->getStorageEngine()->getConfig('betaThreatDefenseFeed'),
), null, '&'));
if ($this->response) {
$jsonData = wfWAFUtils::json_decode($this->response->getBody(), true);
if (is_array($jsonData)) {
if ($waf->hasOpenSSL() &&
isset($jsonData['data']['signature']) &&
isset($jsonData['data']['rules']) &&
$waf->verifySignedRequest(base64_decode($jsonData['data']['signature']), $jsonData['data']['rules'])
) {
$waf->updateRuleSet(base64_decode($jsonData['data']['rules']),
isset($jsonData['data']['timestamp']) ? $jsonData['data']['timestamp'] : true);
if (array_key_exists('premiumCount', $jsonData['data'])) {
$waf->getStorageEngine()->setConfig('premiumCount', $jsonData['data']['premiumCount']);
}
} else if (!$waf->hasOpenSSL() &&
isset($jsonData['data']['hash']) &&
isset($jsonData['data']['rules']) &&
$waf->verifyHashedRequest($jsonData['data']['hash'], $jsonData['data']['rules'])
) {
$waf->updateRuleSet(base64_decode($jsonData['data']['rules']),
isset($jsonData['data']['timestamp']) ? $jsonData['data']['timestamp'] : true);
if (array_key_exists('premiumCount', $jsonData['data'])) {
$waf->getStorageEngine()->setConfig('premiumCount', $jsonData['data']['premiumCount']);
}
}
else {
$success = false;
}
}
else {
$success = false;
}
}
else {
$success = false;
}
$this->response = wfWAFHTTP::get(WFWAF_API_URL_SEC . "?" . http_build_query(array(
'action' => 'get_malware_signatures',
'k' => $waf->getStorageEngine()->getConfig('apiKey'),
's' => $waf->getStorageEngine()->getConfig('siteURL') ? $waf->getStorageEngine()->getConfig('siteURL') : $guessSiteURL,
'h' => $waf->getStorageEngine()->getConfig('homeURL') ? $waf->getStorageEngine()->getConfig('homeURL') : $guessSiteURL,
'openssl' => $waf->hasOpenSSL() ? 1 : 0,
'betaFeed' => (int) $waf->getStorageEngine()->getConfig('betaThreatDefenseFeed'),
), null, '&'));
if ($this->response) {
$jsonData = wfWAFUtils::json_decode($this->response->getBody(), true);
if (is_array($jsonData)) {
if ($waf->hasOpenSSL() &&
isset($jsonData['data']['signature']) &&
isset($jsonData['data']['signatures']) &&
$waf->verifySignedRequest(base64_decode($jsonData['data']['signature']), $jsonData['data']['signatures'])
) {
$waf->setMalwareSignatures(wfWAFUtils::json_decode(base64_decode($jsonData['data']['signatures'])),
isset($jsonData['data']['timestamp']) ? $jsonData['data']['timestamp'] : true);
if (array_key_exists('premiumCount', $jsonData['data'])) {
$waf->getStorageEngine()->setConfig('signaturePremiumCount', $jsonData['data']['premiumCount']);
}
if (array_key_exists('commonStringsSignature', $jsonData['data']) &&
array_key_exists('commonStrings', $jsonData['data']) &&
array_key_exists('signatureIndexes', $jsonData['data']) &&
$waf->verifySignedRequest(base64_decode($jsonData['data']['commonStringsSignature']), $jsonData['data']['commonStrings'] . $jsonData['data']['signatureIndexes'])
) {
$waf->setMalwareSignatureCommonStrings(wfWAFUtils::json_decode(base64_decode($jsonData['data']['commonStrings'])), wfWAFUtils::json_decode(base64_decode($jsonData['data']['signatureIndexes'])));
}
} else if (!$waf->hasOpenSSL() &&
isset($jsonData['data']['hash']) &&
isset($jsonData['data']['signatures']) &&
$waf->verifyHashedRequest($jsonData['data']['hash'], $jsonData['data']['signatures'])
) {
$waf->setMalwareSignatures(wfWAFUtils::json_decode(base64_decode($jsonData['data']['signatures'])),
isset($jsonData['data']['timestamp']) ? $jsonData['data']['timestamp'] : true);
if (array_key_exists('premiumCount', $jsonData['data'])) {
$waf->getStorageEngine()->setConfig('signaturePremiumCount', $jsonData['data']['premiumCount']);
}
if (array_key_exists('commonStringsHash', $jsonData['data']) &&
array_key_exists('commonStrings', $jsonData['data']) &&
array_key_exists('signatureIndexes', $jsonData['data']) &&
$waf->verifyHashedRequest($jsonData['data']['commonStringsHash'], $jsonData['data']['commonStrings'] . $jsonData['data']['signatureIndexes'])
) {
$waf->setMalwareSignatureCommonStrings(wfWAFUtils::json_decode(base64_decode($jsonData['data']['commonStrings'])), wfWAFUtils::json_decode(base64_decode($jsonData['data']['signatureIndexes'])));
}
}
else {
$success = false;
}
}
else {
$success = false;
}
}
else {
$success = false;
}
} catch (wfWAFHTTPTransportException $e) {
error_log($e->getMessage());
$success = false;
} catch (wfWAFBuildRulesException $e) {
error_log($e->getMessage());
$success = false;
}
return $success;
}
/**
* @return wfWAFCronEvent|bool
*/
public function reschedule() {
$waf = $this->getWaf();
if (!$waf) {
return false;
}
$newEvent = new self(time() + (86400 * ($waf->getStorageEngine()->getConfig('isPaid') ? .5 : 7)));
if ($this->response) {
$headers = $this->response->getHeaders();
if (isset($headers['Expires'])) {
$timestamp = strtotime($headers['Expires']);
// Make sure it's at least 2 hours ahead.
if ($timestamp && $timestamp > (time() + 7200)) {
$newEvent->setFireTime($timestamp);
}
}
}
return $newEvent;
}
}
class wfWAFCronFetchIPListEvent extends wfWAFCronEvent {
public function fire() {
$waf = $this->getWaf();
if (!$waf) {
return;
}
$guessSiteURL = sprintf('%s://%s/', $waf->getRequest()->getProtocol(), $waf->getRequest()->getHost());
try {
//Watch List
$request = new wfWAFHTTP();
$request->setHeaders(array(
'Content-Type' => 'application/json',
));
$response = wfWAFHTTP::post(WFWAF_API_URL_SEC . "?" . http_build_query(array(
'action' => 'send_waf_attack_data',
'k' => $waf->getStorageEngine()->getConfig('apiKey'),
's' => $waf->getStorageEngine()->getConfig('siteURL') ? $waf->getStorageEngine()->getConfig('siteURL') : $guessSiteURL,
'h' => $waf->getStorageEngine()->getConfig('homeURL') ? $waf->getStorageEngine()->getConfig('homeURL') : $guessSiteURL,
't' => microtime(true),
), null, '&'), '[]', $request);
if ($response instanceof wfWAFHTTPResponse && $response->getBody()) {
$jsonData = wfWAFUtils::json_decode($response->getBody(), true);
if (array_key_exists('data', $jsonData) && array_key_exists('watchedIPList', $jsonData['data'])) {
$waf->getStorageEngine()->setConfig('watchedIPs', $jsonData['data']['watchedIPList']);
}
}
} catch (wfWAFHTTPTransportException $e) {
error_log($e->getMessage());
}
}
/**
* @return wfWAFCronEvent|bool
*/
public function reschedule() {
$waf = $this->getWaf();
if (!$waf) {
return false;
}
$newEvent = new self(time() + 86400);
return $newEvent;
}
}
class wfWAFCronFetchBlacklistPrefixesEvent extends wfWAFCronEvent {
public function fire() {
$waf = $this->getWaf();
if (!$waf) {
return;
}
$guessSiteURL = sprintf('%s://%s/', $waf->getRequest()->getProtocol(), $waf->getRequest()->getHost());
try {
if ($waf->getStorageEngine()->getConfig('isPaid')) {
$request = new wfWAFHTTP();
$response = wfWAFHTTP::get(WFWAF_API_URL_SEC . 'blacklist-prefixes.bin' . "?" . http_build_query(array(
'k' => $waf->getStorageEngine()->getConfig('apiKey'),
's' => $waf->getStorageEngine()->getConfig('siteURL') ? $waf->getStorageEngine()->getConfig('siteURL') : $guessSiteURL,
'h' => $waf->getStorageEngine()->getConfig('homeURL') ? $waf->getStorageEngine()->getConfig('homeURL') : $guessSiteURL,
't' => microtime(true),
), null, '&'), $request);
if ($response instanceof wfWAFHTTPResponse && $response->getBody()) {
$waf->getStorageEngine()->setConfig('blockedPrefixes', base64_encode($response->getBody()));
$waf->getStorageEngine()->setConfig('blacklistAllowedCache', '');
}
}
$waf->getStorageEngine()->vacuum();
} catch (wfWAFHTTPTransportException $e) {
error_log($e->getMessage());
}
}
/**
* @return wfWAFCronEvent|bool
*/
public function reschedule() {
$waf = $this->getWaf();
if (!$waf) {
return false;
}
$newEvent = new self(time() + 7200);
return $newEvent;
}
}
class wfWAFEventBus implements wfWAFObserver {
private $observers = array();
/**
* @param wfWAFObserver $observer
* @throws wfWAFEventBusException
*/
public function attach($observer) {
if (!($observer instanceof wfWAFObserver)) {
throw new wfWAFEventBusException('Observer supplied to wfWAFEventBus::attach must implement wfWAFObserver');
}
$this->observers[] = $observer;
}
/**
* @param wfWAFObserver $observer
*/
public function detach($observer) {
$key = array_search($observer, $this->observers, true);
if ($key !== false) {
unset($this->observers[$key]);
}
}
public function prevBlocked($ip) {
/** @var wfWAFObserver $observer */
foreach ($this->observers as $observer) {
$observer->prevBlocked($ip);
}
}
public function block($ip, $exception) {
/** @var wfWAFObserver $observer */
foreach ($this->observers as $observer) {
$observer->block($ip, $exception);
}
}
public function allow($ip, $exception) {
/** @var wfWAFObserver $observer */
foreach ($this->observers as $observer) {
$observer->allow($ip, $exception);
}
}
public function blockXSS($ip, $exception) {
/** @var wfWAFObserver $observer */
foreach ($this->observers as $observer) {
$observer->blockXSS($ip, $exception);
}
}
public function blockSQLi($ip, $exception) {
/** @var wfWAFObserver $observer */
foreach ($this->observers as $observer) {
$observer->blockSQLi($ip, $exception);
}
}
public function log($ip, $exception) {
/** @var wfWAFObserver $observer */
foreach ($this->observers as $observer) {
$observer->log($ip, $exception);
}
}
public function wafDisabled() {
/** @var wfWAFObserver $observer */
foreach ($this->observers as $observer) {
$observer->wafDisabled();
}
}
public function beforeRunRules() {
/** @var wfWAFObserver $observer */
foreach ($this->observers as $observer) {
$observer->beforeRunRules();
}
}
public function afterRunRules() {
/** @var wfWAFObserver $observer */
foreach ($this->observers as $observer) {
$observer->afterRunRules();
}
}
}
interface wfWAFObserver {
public function prevBlocked($ip);
public function block($ip, $exception);
public function allow($ip, $exception);
public function blockXSS($ip, $exception);
public function blockSQLi($ip, $exception);
public function log($ip, $exception);
public function wafDisabled();
public function beforeRunRules();
public function afterRunRules();
}
class wfWAFBaseObserver implements wfWAFObserver {
public function prevBlocked($ip) {
}
public function block($ip, $exception) {
}
public function allow($ip, $exception) {
}
public function blockXSS($ip, $exception) {
}
public function blockSQLi($ip, $exception) {
}
public function log($ip, $exception) {
}
public function wafDisabled() {
}
public function beforeRunRules() {
}
public function afterRunRules() {
}
}
class wfWAFException extends Exception {
}
class wfWAFRunException extends Exception {
/** @var array */
private $failedRules;
/** @var string */
private $paramKey;
/** @var string */
private $paramValue;
/** @var wfWAFRequestInterface */
private $request;
/**
* @return array
*/
public function getFailedRules() {
return $this->failedRules;
}
/**
* @param array $failedRules
*/
public function setFailedRules($failedRules) {
$this->failedRules = $failedRules;
}
/**
* @return string
*/
public function getParamKey() {
return $this->paramKey;
}
/**
* @param string $paramKey
*/
public function setParamKey($paramKey) {
$this->paramKey = $paramKey;
}
/**
* @return string
*/
public function getParamValue() {
return $this->paramValue;
}
/**
* @param string $paramValue
*/
public function setParamValue($paramValue) {
$this->paramValue = $paramValue;
}
/**
* @return wfWAFRequestInterface
*/
public function getRequest() {
return $this->request;
}
/**
* @param wfWAFRequestInterface $request
*/
public function setRequest($request) {
$this->request = $request;
}
}
class wfWAFAllowException extends wfWAFRunException {
}
class wfWAFBlockException extends wfWAFRunException {
}
class wfWAFBlockXSSException extends wfWAFRunException {
}
class wfWAFBlockSQLiException extends wfWAFRunException {
}
class wfWAFLogException extends wfWAFRunException {
}
class wfWAFBuildRulesException extends wfWAFException {
}
class wfWAFEventBusException extends wfWAFException {
}
| creolab/creolab.hr | public/app/plugins/wordfence/vendor/wordfence/wf-waf/src/lib/waf.php | PHP | mit | 56,460 |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "ะฝะพะปั", ONE: "ะพะดะธะฝ", TWO: "ะดะฒะฐ", FEW: "ะฝะตัะบะพะปัะบะพ", MANY: "ะผะฝะพะณะพ", OTHER: "ะดััะณะธะต"};
function getDecimals(n) {
n = n + '';
var i = n.indexOf('.');
return (i == -1) ? 0 : n.length - i - 1;
}
function getVF(n, opt_precision) {
var v = opt_precision;
if (undefined === v) {
v = Math.min(getDecimals(n), 3);
}
var base = Math.pow(10, v);
var f = ((n * base) | 0) % base;
return {v: v, f: f};
}
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"ะดะพ ะฟะพะปัะดะฝั",
"ะฟะพัะปะต ะฟะพะปัะดะฝั"
],
"DAY": [
"ะะพัะบัะตัะตะฝัะต",
"ะะพะฝะตะดะตะปัะฝะธะบ",
"ะัะพัะฝะธะบ",
"ะกัะตะดะฐ",
"ะงะตัะฒะตัะณ",
"ะะฐัะฝะธัะฐ",
"ะกัะฑะฑะพัะฐ"
],
"ERANAMES": [
"ะะพ ะ ะพะถะดะตััะฒะฐ ะฅัะธััะพะฒะฐ",
"ะะฐัะตะน ะญัั"
],
"ERAS": [
"BC",
"AD"
],
"FIRSTDAYOFWEEK": 6,
"MONTH": [
"ะฏะฝะฒะฐัั",
"ะคะตะฒัะฐะปั",
"ะะฐัั",
"ะะฟัะตะปั",
"ะะฐะน",
"ะัะฝั",
"ะัะปั",
"ะะฒะณััั",
"ะกะตะฝััะฑัั",
"ะะบััะฑัั",
"ะะพัะฑัั",
"ะะตะบะฐะฑัั"
],
"SHORTDAY": [
"ะั",
"ะะฝ",
"ะั",
"ะกั",
"ะงั",
"ะั",
"ะกะฑ"
],
"SHORTMONTH": [
"ะฏะฝะฒ",
"ะคะตะฒ",
"ะะฐัั",
"ะะฟั",
"ะะฐะน",
"ะัะฝ",
"ะัะป",
"ะะฒะณ",
"ะกะตะฝ",
"ะะบั",
"ะะพั",
"ะะตะบ"
],
"STANDALONEMONTH": [
"ะฏะฝะฒะฐัั",
"ะคะตะฒัะฐะปั",
"ะะฐัั",
"ะะฟัะตะปั",
"ะะฐะน",
"ะัะฝั",
"ะัะปั",
"ะะฒะณััั",
"ะกะตะฝััะฑัั",
"ะะบััะฑัั",
"ะะพัะฑัั",
"ะะตะบะฐะฑัั"
],
"WEEKENDRANGE": [
5,
6
],
"fullDate": "EEEE, MMMM d, y",
"longDate": "MMMM d, y",
"medium": "MMM d, y h:mm:ss a",
"mediumDate": "MMM d, y",
"mediumTime": "h:mm:ss a",
"short": "d.m.yy h:mm a",
"shortDate": "d.m.yy",
"shortTime": "h:mm a"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "ะ ",
"DECIMAL_SEP": ".",
"GROUP_SEP": ",",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "-\u00a4",
"negSuf": "",
"posPre": "\u00a4",
"posSuf": ""
}
]
},
"id": "ru",
"localeID": "ru",
"pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]);
| dwalin93/OSeM-Projekt | dist/translations/angular/angular-locale_ru.js | JavaScript | mit | 3,049 |
# Write your code below!
my_first_symbol = :anyvalidsymbol
| ummahusla/codecademy-exercise-answers | Language Skills/Ruby/Unit 06 Hashes and Symbols/01 Hashes and Symbols/02 The Many Faces of Symbols/07 Symbol Syntax.rb | Ruby | mit | 59 |
namespace MvcLocalization.WebApp.Infrastructure
{
/// <summary>
/// Enumeration for all cookie keys
/// </summary>
public enum CookieKey
{
/// <summary>
/// CookieKey to access the prefered language
/// </summary>
UserLanguage
}
} | Code-Inside/Samples | 2011/mvclocalization/MvcLocalization.WebApp/Infrastructure/CookieKey.cs | C# | mit | 286 |
๏ปฟ// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System.Collections.Generic;
using Microsoft.Common.Core.Imaging;
using Microsoft.Languages.Editor.Completions;
using Microsoft.R.Core.AST;
using Microsoft.R.Core.AST.DataTypes;
using Microsoft.R.Core.AST.Scopes;
namespace Microsoft.R.Editor.Completions.Providers {
/// <summary>
/// Provides list of functions and variables applicable to the current scope and
/// the caret position. Enumerates variables and function that appear before the
/// current caret position as well as those declared in outer scopes.
/// </summary>
public sealed class UserVariablesCompletionProvider : IRCompletionListProvider {
private readonly object _functionGlyph;
private readonly object _variableGlyph;
public UserVariablesCompletionProvider(IImageService imageService) {
_functionGlyph = imageService.GetImage(ImageType.Method);
_variableGlyph = imageService.GetImage(ImageType.Variable);
}
#region IRCompletionListProvider
public bool AllowSorting { get; } = true;
public IReadOnlyCollection<ICompletionEntry> GetEntries(IRIntellisenseContext context, string prefixFilter = null) {
var completions = new List<ICompletionEntry>();
var ast = context.AstRoot;
// First try simple scope like in 'for(x in 1:10) x|'
IScope scope = ast.GetNodeOfTypeFromPosition<SimpleScope>(context.Position, includeEnd: true);
// If not found, look for the regular scope
scope = scope ?? ast.GetNodeOfTypeFromPosition<IScope>(context.Position);
var variables = scope.GetApplicableVariables(context.Position);
foreach (var v in variables) {
var f = v.Value as RFunction;
var completion = new EditorCompletionEntry(v.Name.RemoveBackticks(), v.Name.BacktickName(), string.Empty, f != null ? _functionGlyph : _variableGlyph);
completions.Add(completion);
}
return completions;
}
#endregion
}
}
| AlexanderSher/RTVS | src/R/Editor/Impl/Completions/Providers/UserVariablesCompletionProvider.cs | C# | mit | 2,218 |
# coding: utf-8
require 'date'
require File.expand_path('../../spec_helper', __FILE__)
describe "ListItemDigestor" do
before do
@list_item_digestor = Sevendigital::ListItemDigestor.new(Sevendigital::Client.new(nil))
end
it "should not digest from invalid xml but throw up (exception)" do
xml_response = <<XML
<foo id="123">
<bar>test</bar>
</foo>
XML
running {@list_item_digestor.from_xml_doc(xml_response)}.should raise_error(Sevendigital::DigestiveProblem)
end
it "should digest list item xml and populate available properties" do
xml_response = load_sample_object_xml("list_item_release")
list_item = @list_item_digestor.from_xml_string(xml_response)
list_item.id.should == 123456
list_item.type.should == :release
list_item.release.id.should == 1136112
list_item.release.title.should == "Collapse Into Now"
list_item.release.artist.id.should == 590
list_item.release.artist.name.should == "R.E.M."
list_item.release.artist.appears_as == "R.E.M."
list_item.release.artist.url.should == "http://www.7digital.com/artists/r-e-m"
list_item.release.url.should == "http://www.7digital.com/artists/r-e-m/collapse-into-now?partner=123"
list_item.release.image.should == "http://cdn.7static.com/static/img/sleeveart/00/011/361/0001136112_50.jpg"
list_item.release.explicit_content == false
end
it "should not digest unknown list item xml but throw up (exception) " do
xml_response = <<XML
<listItem id="123">
<type>track</type>
<track id="1136112">
</track>
</release>
XML
running {@list_item_digestor.from_xml_doc(xml_response)}.should raise_error(Sevendigital::DigestiveProblem)
end
it "should digest xml containing list of list items and return an array" do
xml_response = load_sample_object_xml("list_item_list")
list_items = @list_item_digestor.list_from_xml_string(xml_response)
list_items[0].id.should == 1879539
list_items[0].release.id.should == 1879539
list_items[1].id.should == 1879543
list_items[1].release.id.should == 1879543
list_items.size.should == 2
end
it "should digest xml containing empty list of list items and return an empty array" do
xml_response = <<XML
<listItems>
</listItems>
XML
releases = @list_item_digestor.list_from_xml_string(xml_response)
releases.size.should == 0
end
end
| filip7d/7digital | spec/digestion_tract/list_item_digestor_spec.rb | Ruby | mit | 2,414 |
๏ปฟnamespace Serenity {
/**
* A mixin that can be applied to a DataGrid for tree functionality
*/
export class TreeGridMixin<TItem> {
private dataGrid: DataGrid<TItem, any>;
private getId: (item: TItem) => any;
constructor(private options: TreeGridMixinOptions<TItem>) {
var dg = this.dataGrid = options.grid;
var idProperty = (dg as any).getIdProperty();
var getId = this.getId = (item: TItem) => (item as any)[idProperty];
dg.element.find('.grid-container').on('click', e => {
if ($(e.target).hasClass('s-TreeToggle')) {
var src = dg.slickGrid.getCellFromEvent(e);
if (src.cell >= 0 &&
src.row >= 0) {
SlickTreeHelper.toggleClick<TItem>(e, src.row, src.row, dg.view, getId);
}
}
});
var oldViewFilter = (dg as any).onViewFilter;
(dg as any).onViewFilter = function (item: TItem) {
if (!oldViewFilter.apply(this, [item]))
return false;
return SlickTreeHelper.filterById(item, dg.view, options.getParentId);
};
var oldProcessData = (dg as any).onViewProcessData;
(dg as any).onViewProcessData = function (response: ListResponse<TItem>) {
response = oldProcessData.apply(this, [response]);
response.Entities = TreeGridMixin.applyTreeOrdering(response.Entities, getId, options.getParentId);
SlickTreeHelper.setIndents(response.Entities, getId, options.getParentId,
(options.initialCollapse && options.initialCollapse()) || false);
return response;
};
if (options.toggleField) {
var col = Q.tryFirst(dg['allColumns'] || dg.slickGrid.getColumns() || [], x => x.field == options.toggleField);
if (col) {
col.format = SlickFormatting.treeToggle(() => dg.view, getId,
col.format || (ctx => Q.htmlEncode(ctx.value)));
col.formatter = SlickHelper.convertToFormatter(col.format);
}
}
}
/**
* Expands / collapses all rows in a grid automatically
*/
toggleAll(): void {
SlickTreeHelper.setCollapsed(this.dataGrid.view.getItems(),
!this.dataGrid.view.getItems().every(x => (x as any)._collapsed == true));
this.dataGrid.view.setItems(this.dataGrid.view.getItems(), true);
}
collapseAll(): void {
SlickTreeHelper.setCollapsed(this.dataGrid.view.getItems(), true);
this.dataGrid.view.setItems(this.dataGrid.view.getItems(), true);
}
expandAll(): void {
SlickTreeHelper.setCollapsed(this.dataGrid.view.getItems(), false);
this.dataGrid.view.setItems(this.dataGrid.view.getItems(), true);
}
/**
* Reorders a set of items so that parents comes before their children.
* This method is required for proper tree ordering, as it is not so easy to perform with SQL.
* @param items list of items to be ordered
* @param getId a delegate to get ID of a record (must return same ID with grid identity field)
* @param getParentId a delegate to get parent ID of a record
*/
static applyTreeOrdering<TItem>(items: TItem[], getId: (item: TItem) => any, getParentId: (item: TItem) => any): TItem[] {
var result: TItem[] = [];
var byId = Q.toGrouping(items, getId);
var byParentId = Q.toGrouping(items, getParentId);
var visited = {};
function takeChildren(theParentId: any) {
if (visited[theParentId])
return;
visited[theParentId] = true;
for (var child of (byParentId[theParentId] || [])) {
result.push(child);
takeChildren(getId(child));
}
}
for (var item of items)
{
var parentId = getParentId(item);
if (parentId == null ||
!((byId[parentId] || []).length)) {
result.push(item);
takeChildren(getId(item));
}
}
return result;
}
}
export interface TreeGridMixinOptions<TItem> {
// data grid object
grid: Serenity.DataGrid<TItem, any>;
// a function to get parent id
getParentId: (item: TItem) => any;
// where should the toggle button be placed
toggleField: string;
// a delegate that should return initial collapsing state
initialCollapse?: () => boolean;
}
}
| rolembergfilho/Serenity | Serenity.Scripts/CoreLib/UI/DataGrid/TreeGridMixin.ts | TypeScript | mit | 5,052 |
var _ = require('../util.js');
function simpleDiff(now, old){
var nlen = now.length;
var olen = old.length;
if(nlen !== olen){
return true;
}
for(var i = 0; i < nlen ; i++){
if(now[i] !== old[i]) return true;
}
return false
}
function equals(a,b){
return a === b;
}
// array1 - old array
// array2 - new array
function ld(array1, array2, equalFn){
var n = array1.length;
var m = array2.length;
var equalFn = equalFn || equals;
var matrix = [];
for(var i = 0; i <= n; i++){
matrix.push([i]);
}
for(var j=1;j<=m;j++){
matrix[0][j]=j;
}
for(var i = 1; i <= n; i++){
for(var j = 1; j <= m; j++){
if(equalFn(array1[i-1], array2[j-1])){
matrix[i][j] = matrix[i-1][j-1];
}else{
matrix[i][j] = Math.min(
matrix[i-1][j]+1, //delete
matrix[i][j-1]+1//add
)
}
}
}
return matrix;
}
// arr2 - new array
// arr1 - old array
function diffArray(arr2, arr1, diff, diffFn) {
if(!diff) return simpleDiff(arr2, arr1);
var matrix = ld(arr1, arr2, diffFn)
var n = arr1.length;
var i = n;
var m = arr2.length;
var j = m;
var edits = [];
var current = matrix[i][j];
while(i>0 || j>0){
// the last line
if (i === 0) {
edits.unshift(3);
j--;
continue;
}
// the last col
if (j === 0) {
edits.unshift(2);
i--;
continue;
}
var northWest = matrix[i - 1][j - 1];
var west = matrix[i - 1][j];
var north = matrix[i][j - 1];
var min = Math.min(north, west, northWest);
if (min === west) {
edits.unshift(2); //delete
i--;
current = west;
} else if (min === northWest ) {
if (northWest === current) {
edits.unshift(0); //no change
} else {
edits.unshift(1); //update
current = northWest;
}
i--;
j--;
} else {
edits.unshift(3); //add
j--;
current = north;
}
}
var LEAVE = 0;
var ADD = 3;
var DELELE = 2;
var UPDATE = 1;
var n = 0;m=0;
var steps = [];
var step = {index: null, add:0, removed:[]};
for(var i=0;i<edits.length;i++){
if(edits[i] > 0 ){ // NOT LEAVE
if(step.index === null){
step.index = m;
}
} else { //LEAVE
if(step.index != null){
steps.push(step)
step = {index: null, add:0, removed:[]};
}
}
switch(edits[i]){
case LEAVE:
n++;
m++;
break;
case ADD:
step.add++;
m++;
break;
case DELELE:
step.removed.push(arr1[n])
n++;
break;
case UPDATE:
step.add++;
step.removed.push(arr1[n])
n++;
m++;
break;
}
}
if(step.index != null){
steps.push(step)
}
return steps
}
// diffObject
// ----
// test if obj1 deepEqual obj2
function diffObject( now, last, diff ){
if(!diff){
for( var j in now ){
if( last[j] !== now[j] ) return true
}
for( var n in last ){
if(last[n] !== now[n]) return true;
}
}else{
var nKeys = _.keys(now);
var lKeys = _.keys(last);
/**
* [description]
* @param {[type]} a [description]
* @param {[type]} b){ return now[b] [description]
* @return {[type]} [description]
*/
return diffArray(nKeys, lKeys, diff, function(a, b){
return now[b] === last[a];
});
}
return false;
}
module.exports = {
diffArray: diffArray,
diffObject: diffObject
} | zyy7259/regular-strap | third/regular/src/helper/diff.js | JavaScript | mit | 3,523 |
import os from 'os';
import debug from 'debug';
import baseGetOptions from './base';
import { GeneralError } from '../../errors/runtime';
import { stat, readFile } from '../promisified-functions';
import renderTemplate from '../../utils/render-template';
import { RUNTIME_ERRORS } from '../../errors/types';
import WARNING_MESSAGES from '../../notifications/warning-message';
import { Dictionary } from '../../configuration/interfaces';
const DEBUG_LOGGER = debug('testcafe:utils:get-options:ssl');
const MAX_PATH_LENGTH: Dictionary<number> = {
'Linux': 4096,
'Windows_NT': 260,
'Darwin': 1024,
};
const OS_MAX_PATH_LENGTH = MAX_PATH_LENGTH[os.type()];
const OPTIONS_SEPARATOR = ';';
const FILE_OPTION_NAMES = ['cert', 'key', 'pfx'];
export default async function (optionString: string): Promise<Dictionary<string | boolean | number>> {
return baseGetOptions(optionString, {
optionsSeparator: OPTIONS_SEPARATOR,
async onOptionParsed (key: string, value: string) {
if (!FILE_OPTION_NAMES.includes(key) || value.length > OS_MAX_PATH_LENGTH)
return value;
try {
await stat(value);
}
catch (error) {
DEBUG_LOGGER(renderTemplate(WARNING_MESSAGES.cannotFindSSLCertFile, value, key, error.stack));
return value;
}
try {
return await readFile(value);
}
catch (error) {
throw new GeneralError(RUNTIME_ERRORS.cannotReadSSLCertFile, key, value, error.stack);
}
},
});
}
| VasilyStrelyaev/testcafe | src/utils/get-options/ssl.ts | TypeScript | mit | 1,626 |
!((document, $) => {
'use strict';
var keys = {
ARROWS: [37, 38, 39, 40],
ARROW_LEFT: 37,
ARROW_UP: 38,
ARROW_RIGHT: 39,
ARROW_DOWN: 40,
ENTER: 13,
SPACE: 32,
PAGE_UP: 33,
PAGE_DOWN: 34
};
/**
@param {Object} startTab - The tab to start searching from.
@param {Object} $list - A list of nav buttons as a jQuery object.
@param {Object} key - The triggering key code.
@returns {Object} - The tab to the left or right of `startTab`.
*/
function findAdjacentTab(startTab, $list, key) {
var dir =
(key === keys.ARROW_LEFT || key === keys.ARROW_UP) ? 'prev' : 'next';
var adjacentTab = (dir === 'prev') ?
$(startTab.parentNode)
.prev()[0] :
$(startTab.parentNode)
.next()[0];
if (!adjacentTab) {
var allTabs = $list.find('.tabs__nav-item');
if (dir === 'prev') {
adjacentTab = allTabs[allTabs.length - 1];
}
else {
adjacentTab = allTabs[0];
}
}
return $(adjacentTab)
.find('.tabs__nav-trigger')[0];
}
/**
@param {Object} newActive - Tab to be made active.
@param {Object} $list - A list of nav buttons as a jQuery object.
@returns {undefined}
*/
function setActiveAndInactive(newActive, $list) {
$list.find('.tabs__nav-item')
.each(function () {
var assocPanelID = $(this)
.find('.tabs__nav-trigger')
.first()
.attr('aria-controls');
var anchor = $(this)
.find('.tabs__nav-trigger')[0];
if (this !== newActive.parentNode) {
$(this)
.removeClass('is-active');
anchor.tabIndex = -1;
anchor.setAttribute('aria-selected', 'false');
$('#' + assocPanelID)
.removeClass('is-current')
.attr('aria-hidden', 'true');
}
else {
$(this)
.addClass('is-active');
anchor.tabIndex = 0;
anchor.setAttribute('aria-selected', 'true');
$('#' + assocPanelID)
.addClass('is-current')
.removeAttr('aria-hidden');
}
});
}
var $allTabGroups = $('.tabs');
$allTabGroups.each(function () {
var $tabs = $(this);
var $navlist = $tabs.find('.tabs__navlist');
$navlist.on('keydown', '.tabs__nav-item .tabs__nav-trigger',
function (keyVent) {
var which = keyVent.which;
var target = keyVent.target;
if ($.inArray(which, keys.ARROWS) > -1) {
var adjacentTab = findAdjacentTab(target, $navlist, which);
if (adjacentTab) {
keyVent.preventDefault();
adjacentTab.focus();
setActiveAndInactive(adjacentTab, $navlist);
}
}
else if (which === keys.ENTER || which === keys.SPACE) {
keyVent.preventDefault();
target.click();
}
else if (which === keys.PAGE_DOWN) {
keyVent.preventDefault();
var assocPanel = $('#' + this.getAttribute('aria-controls'));
if (assocPanel) {
assocPanel.focus();
}
}
}
);
// Click support
$navlist.on('click', '.tabs__nav-item .tabs__nav-trigger', function () {
var currentTarget =
$navlist.find('.tabs__nav-item.is-active .tabs__nav-trigger')[0];
if (currentTarget !== $(this)[0]) {
var eventData = {
'previousTarget': currentTarget,
'newTarget': $(this)[0]
};
var event = new CustomEvent('rb.tabs.tabChanged', {
detail: eventData
});
$(this)[0].dispatchEvent(event);
}
setActiveAndInactive(this, $navlist);
});
});
$(document.body)
.on('keydown', '.tabs__panel', function (e) {
if (e.which === keys.PAGE_UP) {
e.preventDefault();
var $navlist = $(this)
.closest('.tabs')
.find('.tabs__navlist');
var activeTab = $navlist
.find('.tabs__nav-item.is-active .tabs__nav-trigger')[0];
if (activeTab) {
activeTab.focus();
}
}
});
})(document, jQuery);
| cehfisher/a11y-style-guide | src/global/js/tabs.js | JavaScript | mit | 4,138 |
#define CATCH_CONFIG_MAIN // This tells Catch to provide a main()
#include "catch.hpp"
#include <memory>
#include <vector>
#include "tclap/ValueArg.h"
#include "Simulation.hpp"
TEST_CASE("The Simulation can be constructed without command line parsing", "[Simulation]") {
std::unique_ptr<warped::Simulation> s;
REQUIRE_NOTHROW((s = decltype(s){new warped::Simulation {"", 100}}));
}
| wilseypa/warped2 | test/test_Simulation.cpp | C++ | mit | 397 |
package net.coding.program.common.enter;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import net.coding.program.Global;
import net.coding.program.R;
import net.coding.program.common.MyImageGetter;
import net.coding.program.message.EmojiFragment;
/**
* Created by chaochen on 14-10-31.
*/
public class EnterEmojiLayout extends EnterLayout {
private CheckBox checkBoxEmoji;
private View emojiKeyboardLayout;
private LinearLayout emojiKeyboardIndicator;
private EmojiPagerAdapter mEmojiPagerAdapter;
private MonkeyPagerAdapter mMonkeyPagerAdapter;
private View selectEmoji;
private View selectMonkey;
private MyImageGetter myImageGetter;
private FragmentActivity mActivity;
private int rootViewHigh = 0;
private final View rootView;
public static enum EmojiType {
Default, SmallOnly
}
public EnterEmojiLayout(FragmentActivity activity, View.OnClickListener sendTextOnClick, Type type) {
this(activity, sendTextOnClick, type, EmojiType.Default);
}
public EnterEmojiLayout(FragmentActivity activity, View.OnClickListener sendTextOnClick, Type type, EmojiType emojiType) {
super(activity, sendTextOnClick, type);
mActivity = activity;
myImageGetter = new MyImageGetter(activity);
checkBoxEmoji = (CheckBox) activity.findViewById(R.id.popEmoji);
checkBoxEmoji.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
content.requestFocus();
if (checkBoxEmoji.isChecked()) {
rootViewHigh = rootView.getHeight();
final int bottomHigh = Global.dpToPx(100); // ๅบ้จ่ๆๆ้ฎ้ซๅบฆ๏ผnexus5ๆฏ73dp๏ผไปฅ้ฒไธไธ๏ผๆไปฅ่ฎพๅคงไธ็น
int rootParentHigh = rootView.getRootView().getHeight();
if (rootParentHigh - rootViewHigh > bottomHigh) {
// ่ฏดๆ้ฎ็ๅทฒ็ปๅผนๅบๆฅไบ๏ผ็ญ้ฎ็ๆถๅคฑๅๅ่ฎพ็ฝฎ emoji keyboard ๅฏ่ง
Global.popSoftkeyboard(mActivity, content, false);
// ้ญ
ๆๆๆบ็ rootView ๆ ่ฎบ่พๅ
ฅๆณๆฏๅฆๅผนๅบ้ซๅบฆ้ฝๆฏไธๅ็๏ผๅชๅฅฝๆไธชๅปถๆถๅ่ฟไธชไบ
rootView.postDelayed(new Runnable() {
@Override
public void run() {
rootView.setLayoutParams(rootView.getLayoutParams());
}
}, 50);
} else {
emojiKeyboardLayout.setVisibility(View.VISIBLE);
rootViewHigh = 0;
}
} else {
Global.popSoftkeyboard(mActivity, content, true);
emojiKeyboardLayout.setVisibility(View.GONE);
}
}
});
rootView = mActivity.findViewById(android.R.id.content);
rootView.getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
if (rootViewHigh == 0) {
return;
}
int high = rootView.getHeight();
if (high >= rootViewHigh) {
emojiKeyboardLayout.setVisibility(View.VISIBLE);
rootViewHigh = 0;
}
}
}
);
emojiKeyboardLayout = activity.findViewById(R.id.emojiKeyboardLayout);
final ViewPager viewPager = (ViewPager) activity.findViewById(R.id.viewPager);
mEmojiPagerAdapter = new EmojiPagerAdapter(activity.getSupportFragmentManager());
mMonkeyPagerAdapter = new MonkeyPagerAdapter(activity.getSupportFragmentManager());
emojiKeyboardIndicator = (LinearLayout) mActivity.findViewById(R.id.emojiKeyboardIndicator);
viewPager.setOnPageChangeListener(pageChange);
selectEmoji = mActivity.findViewById(R.id.selectEmoji);
selectEmoji.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setIndicatorCount(emojiIcons.length);
if (viewPager.getAdapter() != mEmojiPagerAdapter) {
viewPager.setAdapter(mEmojiPagerAdapter);
pageChange.resetPos();
}
setPressEmojiType(EmojiFragment.Type.Small);
}
});
selectMonkey = mActivity.findViewById(R.id.selectMonkey);
if (emojiType == EmojiType.SmallOnly) {
selectMonkey.setVisibility(View.INVISIBLE);
mActivity.findViewById(R.id.selectMonkeyDivideLine).setVisibility(View.INVISIBLE);
}
selectMonkey.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setIndicatorCount(monkeyIcons.length);
if (viewPager.getAdapter() != mMonkeyPagerAdapter) {
viewPager.setAdapter(mMonkeyPagerAdapter);
pageChange.resetPos();
}
setPressEmojiType(EmojiFragment.Type.Big);
}
});
selectEmoji.performClick();
content.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
emojiKeyboardLayout.setVisibility(View.GONE);
checkBoxEmoji.setChecked(false);
}
});
content.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
emojiKeyboardLayout.setVisibility(View.GONE);
checkBoxEmoji.setChecked(false);
return false;
}
});
}
class PageChangeListener extends ViewPager.SimpleOnPageChangeListener {
int oldPos = 0;
public void resetPos() {
oldPos = 0;
}
@Override
public void onPageSelected(int position) {
View oldPoint = emojiKeyboardIndicator.getChildAt(oldPos);
View newPoint = emojiKeyboardIndicator.getChildAt(position);
oldPoint.setBackgroundResource(R.drawable.ic_point_normal);
newPoint.setBackgroundResource(R.drawable.ic_point_select);
oldPos = position;
}
}
PageChangeListener pageChange = new PageChangeListener();
public EnterEmojiLayout(FragmentActivity activity, View.OnClickListener sendTextOnClick) {
this(activity, sendTextOnClick, Type.Default);
}
public boolean isEmojiKeyboardShowing() {
return emojiKeyboardLayout.getVisibility() == View.VISIBLE;
}
public void closeEmojiKeyboard() {
emojiKeyboardLayout.setVisibility(View.GONE);
checkBoxEmoji.setChecked(false);
}
@Override
public void hide() {
closeEmojiKeyboard();
super.hide();
}
private void setIndicatorCount(int count) {
emojiKeyboardIndicator.removeAllViews();
int pointWidth = mActivity.getResources().getDimensionPixelSize(R.dimen.point_width);
int pointMargin = mActivity.getResources().getDimensionPixelSize(R.dimen.point_margin);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(pointWidth, pointWidth);
lp.leftMargin = pointWidth;
lp.rightMargin = pointMargin;
for (int i = 0; i < count; ++i) {
View pointView = mActivity.getLayoutInflater().inflate(R.layout.common_point, null);
emojiKeyboardIndicator.addView(pointView, lp);
}
emojiKeyboardIndicator.getChildAt(0).setBackgroundResource(R.drawable.ic_point_select);
}
private void setPressEmojiType(EmojiFragment.Type type) {
final int colorNormal = 0xffffffff;
final int colorPress = 0xffe8e8e8;
if (type == EmojiFragment.Type.Small) {
selectEmoji.setBackgroundColor(colorPress);
selectMonkey.setBackgroundColor(colorNormal);
} else {
selectEmoji.setBackgroundColor(colorNormal);
selectMonkey.setBackgroundColor(colorPress);
}
}
static String emojiIcons[][] = {{
"smiley",
"heart_eyes",
"pensive",
"flushed",
"grin",
"kissing_heart",
"wink",
"angry",
"disappointed",
"disappointed_relieved",
"sob",
"stuck_out_tongue_closed_eyes",
"rage",
"persevere",
"unamused",
"smile",
"mask",
"kissing_face",
"sweat",
"joy",
"ic_keyboard_delete"
}, {
"blush",
"cry",
"stuck_out_tongue_winking_eye",
"fearful",
"cold_sweat",
"dizzy_face",
"smirk",
"scream",
"sleepy",
"confounded",
"relieved",
"smiling_imp",
"ghost",
"santa",
"dog",
"pig",
"cat",
"a00001",
"a00002",
"facepunch",
"ic_keyboard_delete"
}, {
"fist",
"v",
"muscle",
"clap",
"point_left",
"point_up_2",
"point_right",
"point_down",
"ok_hand",
"heart",
"broken_heart",
"sunny",
"moon",
"star2",
"zap",
"cloud",
"lips",
"rose",
"coffee",
"birthday",
"ic_keyboard_delete"
}, {
"clock10",
"beer",
"mag",
"iphone",
"house",
"car",
"gift",
"soccer",
"bomb",
"gem",
"alien",
"my100",
"money_with_wings",
"video_game",
"hankey",
"sos",
"zzz",
"microphone",
"umbrella",
"book",
"ic_keyboard_delete"}
};
static String monkeyIcons[][] = new String[][]{{
"coding_emoji_01",
"coding_emoji_02",
"coding_emoji_03",
"coding_emoji_04",
"coding_emoji_05",
"coding_emoji_06",
"coding_emoji_07",
"coding_emoji_08"
}, {
"coding_emoji_09",
"coding_emoji_10",
"coding_emoji_11",
"coding_emoji_12",
"coding_emoji_13",
"coding_emoji_14",
"coding_emoji_15",
"coding_emoji_16"
}, {
"coding_emoji_17",
"coding_emoji_18",
"coding_emoji_19",
"coding_emoji_20",
"coding_emoji_21",
"coding_emoji_22",
"coding_emoji_23",
"coding_emoji_24"
}, {
"coding_emoji_35",
"coding_emoji_26",
"coding_emoji_27",
"coding_emoji_28",
"coding_emoji_29",
"coding_emoji_30",
"coding_emoji_31",
"coding_emoji_32",
}, {
"coding_emoji_33",
"coding_emoji_34",
"coding_emoji_35",
"coding_emoji_36"
}};
class EmojiPagerAdapter extends FragmentStatePagerAdapter {
EmojiPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int i) {
EmojiFragment fragment = new EmojiFragment();
fragment.init(emojiIcons[i], myImageGetter, EnterEmojiLayout.this, EmojiFragment.Type.Small);
return fragment;
}
@Override
public int getCount() {
return emojiIcons.length;
}
}
;
class MonkeyPagerAdapter extends FragmentStatePagerAdapter {
MonkeyPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int i) {
EmojiFragment fragment = new EmojiFragment();
fragment.init(monkeyIcons[i], myImageGetter, EnterEmojiLayout.this, EmojiFragment.Type.Big);
return fragment;
}
@Override
public int getCount() {
return monkeyIcons.length;
}
}
;
}
| CodeHunter2006/Coding-Android | app/src/main/java/net/coding/program/common/enter/EnterEmojiLayout.java | Java | mit | 13,033 |
@extends('layouts._two_columns_left_sidebar')
@section('sidebar')
@include('forum._sidebar')
@stop
@section('content')
<section class="forum">
<h1>Forum</h1>
@if(Input::has('tags'))
<div class="tags">Threads tagged with {{ Input::get('tags') }}.</div>
@else
<div class="tags">All threads</div>
@endif
@if($threads->count() > 0)
@foreach($threads as $thread)
@include('forum._thread_summary')
@endforeach
@else
<div>
There are currently no threads for the selected category.
</div>
@endif
</section>
@stop
| svenhaveman/laravelio | app/views/forum/_index.blade.php | PHP | mit | 681 |
๏ปฟusing Machine.Specifications;
using ShopifySharp.Tests.Test_Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ShopifySharp.Tests
{
[Subject(typeof(ShopifyCustomerService))]
public class When_updating_a_customer
{
Establish context = () =>
{
_Service = new ShopifyCustomerService(Utils.MyShopifyUrl, Utils.AccessToken);
//Create a customer to update
_Customer = _Service.CreateAsync(CustomerCreation.CreateValidCustomer()).Await().AsTask.Result;
//Change the customer's email address
_Customer.Email = "test-update@example.com";
};
Because of = () =>
{
_Customer = _Service.UpdateAsync(_Customer).Await().AsTask.Result;
};
It should_update_the_customer = () =>
{
_Customer.Email.Equals("test-update@example.com").ShouldBeTrue();
};
Cleanup after = () =>
{
_Service.DeleteAsync(_Customer.Id.Value).Await();
};
static ShopifyCustomerService _Service;
static ShopifyCustomer _Customer;
}
}
| Yitzchok/ShopifySharp | ShopifySharp.Tests/ShopifyCustomerService Tests/When_updating_a_customer.cs | C# | mit | 1,202 |
<div><?=$dontexist?></div>
| lucidphp/template | tests/Fixures/view/error.php | PHP | mit | 27 |
<?php
return [
'loggingin' => 'Aan het inloggen',
'signin_below' => 'Log hier onder in:',
'welcome' => 'Welkom bij Voyager. De missende admin voor Laravel',
];
| handiwijoyo/voyager | publishable/lang/nl/login.php | PHP | mit | 181 |
import pytest
from collections import namedtuple
import jenkinsapi
from jenkinsapi.plugins import Plugins
from jenkinsapi.utils.requester import Requester
from jenkinsapi.jenkins import Jenkins
from jenkinsapi.jenkinsbase import JenkinsBase
from jenkinsapi.job import Job
from jenkinsapi.custom_exceptions import JenkinsAPIException
DATA = {}
TWO_JOBS_DATA = {
'jobs': [
{'name': 'job_one',
'url': 'http://localhost:8080/job/job_one',
'color': 'blue'},
{'name': 'job_two',
'url': 'http://localhost:8080/job/job_two',
'color': 'blue'},
]
}
MULTIBRANCH_JOBS_DATA = {
'jobs': [
{'name': 'multibranch-repo/master',
'url': 'http://localhost:8080/job/multibranch-repo/job/master',
'color': 'blue'},
{'name': 'multibranch-repo/develop',
'url': 'http://localhost:8080/job/multibranch-repo/job/develop',
'color': 'blue'},
]
}
SCAN_MULTIBRANCH_PIPELINE_LOG = """
Started by timer
[Fri Jul 05 06:46:00 CEST 2019] Starting branch indexing...
Connecting to https://stash.macq.eu using Jenkins/****** (jenkins-ldap)
Repository type: Git
Looking up internal/base for branches
Checking branch master from internal/base
'Jenkinsfile' found
Met criteria
No changes detected: master (still at 26d4d8a673f57a957fd5a23f5adfe0be02089294)
1 branches were processed
Looking up internal/base for pull requests
0 pull requests were processed
[Fri Jul 05 06:46:01 CEST 2019] Finished branch indexing. Indexing took 1.1 sec
Finished: SUCCESS
"""
@pytest.fixture(scope='function')
def jenkins(monkeypatch):
def fake_poll(cls, tree=None): # pylint: disable=unused-argument
return {}
monkeypatch.setattr(Jenkins, '_poll', fake_poll)
return Jenkins('http://localhost:8080',
username='foouser', password='foopassword')
def test__clone(jenkins):
cloned = jenkins._clone()
assert id(cloned) != id(jenkins)
assert cloned == jenkins
def test_stored_passwords(jenkins):
assert jenkins.requester.password == 'foopassword'
assert jenkins.requester.username == 'foouser'
def test_reload(monkeypatch):
class FakeResponse(object):
status_code = 200
text = '{}'
def fake_get_url(
url, # pylint: disable=unused-argument
params=None, # pylint: disable=unused-argument
headers=None, # pylint: disable=unused-argument
allow_redirects=True, # pylint: disable=unused-argument
stream=False): # pylint: disable=unused-argument
return FakeResponse()
monkeypatch.setattr(Requester, 'get_url', fake_get_url)
mock_requester = Requester(username='foouser', password='foopassword')
jenkins = Jenkins(
'http://localhost:8080/',
username='foouser', password='foopassword',
requester=mock_requester)
jenkins.poll()
def test_get_jobs_list(monkeypatch):
def fake_jenkins_poll(cls, tree=None): # pylint: disable=unused-argument
return TWO_JOBS_DATA
def fake_job_poll(cls, tree=None): # pylint: disable=unused-argument
return {}
monkeypatch.setattr(JenkinsBase, '_poll', fake_jenkins_poll)
monkeypatch.setattr(Jenkins, '_poll', fake_jenkins_poll)
monkeypatch.setattr(Job, '_poll', fake_job_poll)
jenkins = Jenkins('http://localhost:8080/',
username='foouser', password='foopassword')
for idx, job_name in enumerate(jenkins.get_jobs_list()):
assert job_name == TWO_JOBS_DATA['jobs'][idx]['name']
for idx, job_name in enumerate(jenkins.jobs.keys()):
assert job_name == TWO_JOBS_DATA['jobs'][idx]['name']
def test_create_new_job_fail(mocker, monkeypatch):
def fake_jenkins_poll(cls, tree=None): # pylint: disable=unused-argument
return TWO_JOBS_DATA
def fake_job_poll(cls, tree=None): # pylint: disable=unused-argument
return {}
monkeypatch.setattr(JenkinsBase, '_poll', fake_jenkins_poll)
monkeypatch.setattr(Jenkins, '_poll', fake_jenkins_poll)
monkeypatch.setattr(Job, '_poll', fake_job_poll)
mock_requester = Requester(username='foouser', password='foopassword')
mock_requester.post_xml_and_confirm_status = mocker.MagicMock(
return_value=''
)
jenkins = Jenkins('http://localhost:8080/',
username='foouser', password='foopassword',
requester=mock_requester)
with pytest.raises(JenkinsAPIException) as ar:
jenkins.create_job('job_new', None)
assert 'Job XML config cannot be empty' in str(ar.value)
def test_create_multibranch_pipeline_job(mocker, monkeypatch):
def fake_jenkins_poll(cls, tree=None): # pylint: disable=unused-argument
# return multibranch jobs and other jobs.
# create_multibranch_pipeline_job is supposed to filter out the MULTIBRANCH jobs
return {
'jobs': TWO_JOBS_DATA['jobs'] + MULTIBRANCH_JOBS_DATA['jobs']
}
def fake_job_poll(cls, tree=None): # pylint: disable=unused-argument
return {}
monkeypatch.setattr(JenkinsBase, '_poll', fake_jenkins_poll)
monkeypatch.setattr(Jenkins, '_poll', fake_jenkins_poll)
monkeypatch.setattr(Job, '_poll', fake_job_poll)
mock_requester = Requester(username='foouser', password='foopassword')
mock_requester.post_xml_and_confirm_status = mocker.MagicMock(
return_value=''
)
mock_requester.post_and_confirm_status = mocker.MagicMock(
return_value=''
)
get_response = namedtuple('get_response', 'text')
mock_requester.get_url = mocker.MagicMock(
return_value=get_response(text=SCAN_MULTIBRANCH_PIPELINE_LOG)
)
jenkins = Jenkins('http://localhost:8080/',
username='foouser', password='foopassword',
requester=mock_requester)
jobs = jenkins.create_multibranch_pipeline_job("multibranch-repo", "multibranch-xml-content")
for idx, job_instance in enumerate(jobs):
assert job_instance.name == MULTIBRANCH_JOBS_DATA['jobs'][idx]['name']
# make sure we didn't get more jobs.
assert len(MULTIBRANCH_JOBS_DATA['jobs']) == len(jobs)
def test_get_jenkins_obj_from_url(mocker, monkeypatch):
def fake_jenkins_poll(cls, tree=None): # pylint: disable=unused-argument
return TWO_JOBS_DATA
def fake_job_poll(cls, tree=None): # pylint: disable=unused-argument
return {}
monkeypatch.setattr(JenkinsBase, '_poll', fake_jenkins_poll)
monkeypatch.setattr(Jenkins, '_poll', fake_jenkins_poll)
monkeypatch.setattr(Job, '_poll', fake_job_poll)
mock_requester = Requester(username='foouser', password='foopassword')
mock_requester.post_xml_and_confirm_status = mocker.MagicMock(
return_value=''
)
jenkins = Jenkins('http://localhost:8080/',
username='foouser', password='foopassword',
requester=mock_requester)
new_jenkins = jenkins.get_jenkins_obj_from_url('http://localhost:8080/')
assert new_jenkins == jenkins
new_jenkins = jenkins.get_jenkins_obj_from_url('http://localhost:8080/foo')
assert new_jenkins != jenkins
def test_get_jenkins_obj(mocker, monkeypatch):
def fake_jenkins_poll(cls, tree=None): # pylint: disable=unused-argument
return TWO_JOBS_DATA
def fake_job_poll(cls, tree=None): # pylint: disable=unused-argument
return {}
monkeypatch.setattr(JenkinsBase, '_poll', fake_jenkins_poll)
monkeypatch.setattr(Jenkins, '_poll', fake_jenkins_poll)
monkeypatch.setattr(Job, '_poll', fake_job_poll)
mock_requester = Requester(username='foouser', password='foopassword')
mock_requester.post_xml_and_confirm_status = mocker.MagicMock(
return_value=''
)
jenkins = Jenkins('http://localhost:8080/',
username='foouser', password='foopassword',
requester=mock_requester)
new_jenkins = jenkins.get_jenkins_obj()
assert new_jenkins == jenkins
def test_get_version(monkeypatch):
class MockResponse(object):
def __init__(self):
self.headers = {}
self.headers['X-Jenkins'] = '1.542'
def fake_poll(cls, tree=None): # pylint: disable=unused-argument
return {}
monkeypatch.setattr(Jenkins, '_poll', fake_poll)
def fake_get(cls, *arga, **kwargs): # pylint: disable=unused-argument
return MockResponse()
monkeypatch.setattr(Requester, 'get_and_confirm_status', fake_get)
jenkins = Jenkins('http://foobar:8080/',
username='foouser', password='foopassword')
assert jenkins.version == '1.542'
def test_get_version_nonexistent(mocker):
class MockResponse(object):
status_code = 200
headers = {}
text = '{}'
mock_requester = Requester(username='foouser', password='foopassword')
mock_requester.get_url = mocker.MagicMock(
return_value=MockResponse()
)
jenkins = Jenkins('http://localhost:8080',
username='foouser', password='foopassword',
requester=mock_requester)
assert jenkins.version == '0.0'
def test_get_master_data(mocker):
class MockResponse(object):
status_code = 200
headers = {}
text = '{}'
mock_requester = Requester(username='foouser', password='foopassword')
mock_requester.get_url = mocker.MagicMock(
return_value=MockResponse()
)
jenkins = Jenkins('http://localhost:808',
username='foouser', password='foopassword',
requester=mock_requester)
jenkins.get_data = mocker.MagicMock(
return_value={
"busyExecutors": 59,
"totalExecutors": 75
}
)
data = jenkins.get_master_data()
assert data['busyExecutors'] == 59
assert data['totalExecutors'] == 75
def test_get_create_url(monkeypatch):
def fake_poll(cls, tree=None): # pylint: disable=unused-argument
return {}
monkeypatch.setattr(Jenkins, '_poll', fake_poll)
# Jenkins URL w/o slash
jenkins = Jenkins('http://localhost:8080',
username='foouser', password='foopassword')
assert jenkins.get_create_url() == 'http://localhost:8080/createItem'
# Jenkins URL w/ slash
jenkins = Jenkins('http://localhost:8080/',
username='foouser', password='foopassword')
assert jenkins.get_create_url() == 'http://localhost:8080/createItem'
def test_has_plugin(monkeypatch):
def fake_poll(cls, tree=None): # pylint: disable=unused-argument
return {}
monkeypatch.setattr(Jenkins, '_poll', fake_poll)
def fake_plugin_poll(cls, tree=None): # pylint: disable=unused-argument
return {
'plugins': [
{
'deleted': False, 'hasUpdate': True, 'downgradable': False,
'dependencies': [{}, {}, {}, {}],
'longName': 'Jenkins Subversion Plug-in', 'active': True,
'shortName': 'subversion', 'backupVersion': None,
'url': 'http://wiki.jenkins-ci.org/'
'display/JENKINS/Subversion+Plugin',
'enabled': True, 'pinned': False, 'version': '1.45',
'supportsDynamicLoad': 'MAYBE', 'bundled': True
}
]
}
monkeypatch.setattr(Plugins, '_poll', fake_plugin_poll)
jenkins = Jenkins('http://localhost:8080/',
username='foouser', password='foopassword')
assert jenkins.has_plugin('subversion') is True
def test_get_use_auth_cookie(mocker, monkeypatch):
COOKIE_VALUE = 'FAKE_COOKIE'
def fake_opener(redirect_handler): # pylint: disable=unused-argument
mock_response = mocker.MagicMock()
mock_response.cookie = COOKIE_VALUE
mock_opener = mocker.MagicMock()
mock_opener.open.return_value = mock_response
return mock_opener
def fake_poll(cls, tree=None): # pylint: disable=unused-argument
return {}
monkeypatch.setattr(Jenkins, '_poll', fake_poll)
monkeypatch.setattr(Requester, 'AUTH_COOKIE', None)
monkeypatch.setattr(jenkinsapi.jenkins, 'build_opener', fake_opener)
jenkins = Jenkins('http://localhost:8080',
username='foouser', password='foopassword')
jenkins.use_auth_cookie()
assert Requester.AUTH_COOKIE == COOKIE_VALUE
| salimfadhley/jenkinsapi | jenkinsapi_tests/unittests/test_jenkins.py | Python | mit | 12,493 |
# -*- coding: utf-8 -*-
""" S3 Logging Facility
@copyright: (c) 2014 Sahana Software Foundation
@license: MIT
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.
"""
import logging
import sys
from gluon import current
# =============================================================================
class S3Log(object):
"""
Simple global logging facility, called like:
current.log.error("Something went wrong", value="Example")
gives:
2014-02-16 11:58:41 S3LOG ERROR: Something went wrong: Example
Configurable in 000_config.py (set up in models/00_db.py)
- to include caller details (file name, line number, function name):
2014-02-16 11:58:23 (applications/eden/modules/s3/s3rest.py 477 __init__)
ERROR: Something went wrong: Example
- to write to console (sys.stderr), to a log file, or both.
Configuration see modules/s3cfg.py.
"""
def __init__(self):
"""
Constructor
"""
settings = current.deployment_settings
log_level = settings.get_log_level()
if log_level is None:
self.critical = \
self.error = \
self.warning = \
self.info = \
self.debug = self.ignore
self.log_level = 100
else:
try:
level = getattr(logging, log_level.upper())
except AttributeError:
raise SyntaxError("Invalid settings.log.level: %s" % log_level)
self.log_level = level
self.critical = self._critical \
if level <= logging.CRITICAL else self.ignore
self.error = self._error \
if level <= logging.ERROR else self.ignore
self.warning = self._warning \
if level <= logging.WARNING else self.ignore
self.info = self._info \
if level <= logging.INFO else self.ignore
self.debug = self._debug \
if level <= logging.DEBUG else self.ignore
self.configure_logger()
# -------------------------------------------------------------------------
@classmethod
def setup(cls):
"""
Set up current.log
"""
if hasattr(current, "log"):
return
current.log = cls()
return
# -------------------------------------------------------------------------
def configure_logger(self):
"""
Configure output handlers
"""
if hasattr(current, "log"):
return
settings = current.deployment_settings
console = settings.get_log_console()
logfile = settings.get_log_logfile()
if not console and not logfile:
# No point to log without output channel
self.critical = \
self.error = \
self.warning = \
self.info = \
self.debug = self.ignore
return
logger = logging.getLogger(__name__)
logger.propagate = False
logger.setLevel(self.log_level)
logger.handlers = []
m_format = "%(asctime)s %(caller)s %(levelname)s: %(message)s"
d_format = "%Y-%m-%d %H:%M:%S"
formatter = logging.Formatter(m_format, d_format)
# Set up console handler
if console:
console_handler = logging.StreamHandler(sys.stderr)
console_handler.setFormatter(formatter)
console_handler.setLevel(self.log_level)
logger.addHandler(console_handler)
# Set up log file handler
if logfile:
from logging.handlers import RotatingFileHandler
MAXBYTES = 1048576
logfile_handler = RotatingFileHandler(logfile,
maxBytes = MAXBYTES,
backupCount = 3)
logfile_handler.setFormatter(formatter)
logfile_handler.setLevel(self.log_level)
logger.addHandler(logfile_handler)
return
# -------------------------------------------------------------------------
@staticmethod
def ignore(message, value=None):
"""
Dummy to ignore messages below minimum severity level
"""
return
# -------------------------------------------------------------------------
@staticmethod
def recorder():
"""
Return a recording facility for log messages
"""
return S3LogRecorder()
# -------------------------------------------------------------------------
@staticmethod
def _log(severity, message, value=None):
"""
Log a message
@param severity: the severity of the message
@param message: the message
@param value: message suffix (optional)
"""
logger = logging.getLogger(__name__)
logger.propagate = False
msg = "%s: %s" % (message, value) if value else message
extra = {"caller": "S3LOG"}
if current.deployment_settings.get_log_caller_info():
caller = logger.findCaller()
if caller:
extra = {"caller": "(%s %s %s)" % caller}
logger.log(severity, msg, extra=extra)
return
# -------------------------------------------------------------------------
@classmethod
def _critical(cls, message, value=None):
"""
Log a critical message (highest severity level),
called via current.log.critical()
@param message: the message
@param value: message suffix (optional)
"""
cls._log(logging.CRITICAL, message, value=value)
# -------------------------------------------------------------------------
@classmethod
def _error(cls, message, value=None):
"""
Log an error message,
called via current.log.error()
@param message: the message
@param value: message suffix (optional)
"""
cls._log(logging.ERROR, message, value=value)
# -------------------------------------------------------------------------
@classmethod
def _warning(cls, message, value=None):
"""
Log a warning message,
called via current.log.warning()
@param message: the message
@param value: message suffix (optional)
"""
cls._log(logging.WARNING, message, value=value)
# -------------------------------------------------------------------------
@classmethod
def _info(cls, message, value=None):
"""
Log an general info message,
called via current.log.info()
@param message: the message
@param value: message suffix (optional)
"""
cls._log(logging.INFO, message, value=value)
# -------------------------------------------------------------------------
@classmethod
def _debug(cls, message, value=None):
"""
Log a detailed debug message (lowest severity level),
called via current.log.debug()
@param message: the message
@param value: message suffix (optional)
"""
cls._log(logging.DEBUG, message, value=value)
# =============================================================================
class S3LogRecorder(object):
"""
S3Log recorder, simple facility to record log messages for tests
Start:
recorder = current.log.recorder()
Read out messages:
messages = recorder.read()
Stop recording:
recorder.stop()
Re-start recording:
recorder.listen()
Clear messages buffer:
recorder.clear()
"""
def __init__(self):
self.handler = None
self.strbuf = None
self.listen()
# -------------------------------------------------------------------------
def listen(self):
""" Start recording S3Log messages """
if self.handler is not None:
return
strbuf = self.strbuf
if strbuf is None:
try:
from cStringIO import StringIO
except:
from StringIO import StringIO
strbuf = StringIO()
handler = logging.StreamHandler(strbuf)
logger = logging.getLogger(__name__)
logger.addHandler(handler)
self.handler = handler
self.strbuf = strbuf
return
# -------------------------------------------------------------------------
def read(self):
""" Read out recorded S3Log messages """
strbuf = self.strbuf
if strbuf is None:
return ""
handler = self.handler
if handler is not None:
handler.flush()
return strbuf.getvalue()
# -------------------------------------------------------------------------
def stop(self):
""" Stop recording S3Log messages (and return the messages) """
handler = self.handler
if handler is not None:
logger = logging.getLogger(__name__)
logger.removeHandler(handler)
handler.close()
self.handler = None
strbuf = self.strbuf
if strbuf is not None:
return strbuf.getvalue()
else:
return ""
# -------------------------------------------------------------------------
def clear(self):
""" Clear the messages buffer """
if self.handler is not None:
on = True
self.stop()
else:
on = False
strbuf = self.strbuf
if strbuf is not None:
strbuf.close()
self.strbuf = None
if on:
self.listen()
# END =========================================================================
| devinbalkind/eden | modules/s3log.py | Python | mit | 11,312 |
#region Copyright
//
// DotNetNukeยฎ - http://www.dotnetnuke.com
// Copyright (c) 2002-2017
// by DotNetNuke Corporation
//
// 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.
#endregion
#region Usings
using DotNetNuke.Entities.Modules;
#endregion
namespace DotNetNuke.Modules.Groups
{
public class GroupsSettingsBase : ModuleSettingsBase
{
}
} | SCullman/Dnn.Platform | DNN Platform/Modules/Groups/GroupsSettingsBase.cs | C# | mit | 1,381 |
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace AnalyseForTime
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new NNAnalyseForm());
}
}
} | luosz/ai-algorithmplatform | AIAlgorithmPlatform/2007/algorithm/nearestNeighbor/AnalyseForTime/Program.cs | C# | mit | 489 |
/*
* ExpandedResWindow.java Jul 14, 2004
*
* Copyright (c) 2004 Stan Salvador
* stansalvador@hotmail.com
*/
package com.fastdtw.dtw.window;
import com.fastdtw.dtw.WarpPath;
import com.fastdtw.matrix.ColMajorCell;
import com.fastdtw.timeseries.PAA;
import com.fastdtw.timeseries.TimeSeries;
public final class ExpandedResWindow extends SearchWindow
{
public ExpandedResWindow(TimeSeries tsI, TimeSeries tsJ, PAA shrunkI, PAA shrunkJ,
WarpPath shrunkWarpPath, int searchRadius)
{
// Initialize the private data in the super class.
super(tsI.size(), tsJ.size());
// Variables to keep track of the current location of the higher resolution projected path.
int currentI = shrunkWarpPath.minI();
int currentJ = shrunkWarpPath.minJ();
// Variables to keep track of the last part of the low-resolution warp path that was evaluated
// (to determine direction).
int lastWarpedI = Integer.MAX_VALUE;
int lastWarpedJ = Integer.MAX_VALUE;
// For each part of the low-resolution warp path, project that path to the higher resolution by filling in the
// path's corresponding cells at the higher resolution.
for (int w=0; w<shrunkWarpPath.size(); w++)
{
final ColMajorCell currentCell = shrunkWarpPath.get(w);
final int warpedI = currentCell.getCol();
final int warpedJ = currentCell.getRow();
final int blockISize = shrunkI.aggregatePtSize(warpedI);
final int blockJSize = shrunkJ.aggregatePtSize(warpedJ);
// If the path moved up or diagonally, then the next cell's values on the J axis will be larger.
if (warpedJ > lastWarpedJ)
currentJ += shrunkJ.aggregatePtSize(lastWarpedJ);
// If the path moved up or diagonally, then the next cell's values on the J axis will be larger.
if (warpedI > lastWarpedI)
currentI += shrunkI.aggregatePtSize(lastWarpedI);
// If a diagonal move was performed, add 2 cells to the edges of the 2 blocks in the projected path to create
// a continuous path (path with even width...avoid a path of boxes connected only at their corners).
// |_|_|x|x| then mark |_|_|x|x|
// ex: projected path: |_|_|x|x| --2 more cells-> |_|X|x|x|
// |x|x|_|_| (X's) |x|x|X|_|
// |x|x|_|_| |x|x|_|_|
if ((warpedJ>lastWarpedJ) && (warpedI>lastWarpedI))
{
super.markVisited(currentI-1, currentJ);
super.markVisited(currentI, currentJ-1);
}
// Fill in the cells that are created by a projection from the cell in the low-resolution warp path to a
// higher resolution.
for (int x=0; x<blockISize; x++)
{
super.markVisited(currentI+x, currentJ);
super.markVisited(currentI+x, currentJ+blockJSize-1);
}
// Record the last position in the warp path so the direction of the path can be determined when the next
// position of the path is evaluated.
lastWarpedI = warpedI;
lastWarpedJ = warpedJ;
}
// Expand the size of the projected warp path by the specified width.
super.expandWindow(searchRadius);
}
}
| davidmoten/fastdtw | src/main/java/com/fastdtw/dtw/window/ExpandedResWindow.java | Java | mit | 3,499 |
/**
*
*/
package jkit.io.csv;
/**
* The context of an csv event.
*
* @author Joschi <josua.krause@googlemail.com>
*/
public interface CSVContext {
/**
* Getter.
*
* @return The csv reader.
*/
CSVReader reader();
/**
* Getter.
*
* @return The name of the current column.
*/
String colName();
/**
* Getter.
*
* @return The name of the current row.
*/
String rowName();
/**
* Getter.
*
* @return The current row.
*/
int row();
/**
* Getter.
*
* @return The current column.
*/
int col();
}
| JosuaKrause/BusVis | src/main/java/jkit/io/csv/CSVContext.java | Java | mit | 586 |
๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Net.CommandLine;
namespace EasyNetQ.Tests.Tasks.Tasks
{
public class TestSimpleService : ICommandLineTask, IDisposable
{
private IBus bus;
public Task Run(CancellationToken cancellationToken)
{
bus = RabbitHutch.CreateBus("host=localhost", x => x.Register<IEasyNetQLogger>(_ => new NoDebugLogger()));
bus.Respond<TestRequestMessage, TestResponseMessage>(HandleRequest);
bus.RespondAsync<TestAsyncRequestMessage, TestAsyncResponseMessage>(HandleAsyncRequest);
Console.WriteLine("Waiting to service requests");
Console.WriteLine("Press enter to stop");
Console.ReadLine();
return Task.FromResult(0);
}
private static Task<TestAsyncResponseMessage> HandleAsyncRequest(TestAsyncRequestMessage request)
{
Console.Out.WriteLine("Got aysnc request '{0}'", request.Text);
return RunDelayed(1000, () =>
{
Console.Out.WriteLine("Sending response");
return new TestAsyncResponseMessage { Text = request.Text + " ... completed." };
});
}
public static TestResponseMessage HandleRequest(TestRequestMessage request)
{
// Console.WriteLine("Handling request: {0}", request.Text);
if (request.CausesServerToTakeALongTimeToRespond)
{
Console.Out.WriteLine("Taking a long time to respond...");
Thread.Sleep(5000);
Console.Out.WriteLine("... responding");
}
if (request.CausesExceptionInServer)
{
if (request.ExceptionInServerMessage != null)
throw new SomeRandomException(request.ExceptionInServerMessage);
throw new SomeRandomException("Something terrible has just happened!");
}
return new TestResponseMessage { Id = request.Id, Text = request.Text + " all done!" };
}
private static Task<T> RunDelayed<T>(int millisecondsDelay, Func<T> func)
{
if (func == null)
{
throw new ArgumentNullException("func");
}
if (millisecondsDelay < 0)
{
throw new ArgumentOutOfRangeException("millisecondsDelay");
}
var taskCompletionSource = new TaskCompletionSource<T>();
var timer = new Timer(self =>
{
((Timer)self).Dispose();
try
{
var result = func();
taskCompletionSource.SetResult(result);
}
catch (Exception exception)
{
taskCompletionSource.SetException(exception);
}
});
timer.Change(millisecondsDelay, millisecondsDelay);
return taskCompletionSource.Task;
}
public void Dispose()
{
bus.Dispose();
Console.WriteLine("Shut down complete");
}
}
[Serializable]
public class SomeRandomException : Exception
{
//
// For guidelines regarding the creation of new exception types, see
// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpgenref/html/cpconerrorraisinghandlingguidelines.asp
// and
// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dncscol/html/csharp07192001.asp
//
public SomeRandomException() { }
public SomeRandomException(string message) : base(message) { }
public SomeRandomException(string message, Exception inner) : base(message, inner) { }
protected SomeRandomException(
SerializationInfo info,
StreamingContext context) : base(info, context)
{ }
}
}
| Ascendon/EasyNetQ | Source/EasyNetQ.Tests.Tasks/Tasks/TestSimpleService.cs | C# | mit | 4,089 |
๏ปฟusing System;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
using System.ComponentModel.Design;
using System.ComponentModel.Composition;
using Microsoft.MIDebugEngine;
using Microsoft.Win32;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Utilities;
using Microsoft.VisualStudio.Text.Editor;
using VisualRust.Options;
using MICore;
using VisualRust.ProjectSystem.FileSystemMirroring.Package.Registration;
using VisualRust.ProjectSystem.FileSystemMirroring.Shell;
using System.Collections.Generic;
using VisualRust.ProjectSystem;
#if VS14
using Microsoft.VisualStudio.ProjectSystem.Utilities;
#else
using Microsoft.VisualStudio.ProjectSystem.VS;
#endif
namespace VisualRust
{
/// <summary>
/// This is the class that implements the package exposed by this assembly.
///
/// The minimum requirement for a class to be considered a valid package for Visual Studio
/// is to implement the IVsPackage interface and register itself with the shell.
/// This package uses the helper classes defined inside the Managed Package Framework (MPF)
/// to do it: it derives from the Package class that provides the implementation of the
/// IVsPackage interface and uses the registration attributes defined in the framework to
/// register itself and its components with the shell.
/// </summary>
// This attribute tells the PkgDef creation utility (CreatePkgDef.exe) that this class is
// a package.
[PackageRegistration(UseManagedResourcesOnly = true)]
// This attribute is used to register the information needed to show this package
// in the Help/About dialog of Visual Studio.
[InstalledProductRegistration("#110", "#112", "0.2.0", IconResourceID = 400)]
[ProvideLanguageService(typeof(RustLanguage), "Rust", 100,
CodeSense = true,
DefaultToInsertSpaces = true,
EnableCommenting = true,
MatchBraces = true,
MatchBracesAtCaret = true,
ShowCompletion = false,
ShowMatchingBrace = true,
QuickInfo = false,
AutoOutlining = true,
ShowSmartIndent = true,
EnableLineNumbers = true,
EnableFormatSelection = true,
SupportCopyPasteOfHTML = false
)]
[ProvideLanguageExtension(typeof(RustLanguage), ".rs")]
[Guid(GuidList.guidVisualRustPkgString)]
[ProvideOptionPage(typeof(RustOptionsPage), "Visual Rust", "General", 110, 113, true)]
[ProvideOptionPage(typeof(DebuggingOptionsPage), "Visual Rust", "Debugging", 110, 114, true)]
[ProvideProfile(typeof(RustOptionsPage), "Visual Rust", "General", 110, 113, true)]
[ProvideDebugEngine("Rust GDB", typeof(AD7ProgramProvider), typeof(AD7Engine), EngineConstants.EngineId)]
[ProvideMenuResource("Menus.ctmenu", 1)]
[ProvideCpsProjectFactory(GuidList.CpsProjectFactoryGuidString, "Rust", "rsproj")]
[ProjectTypeRegistration(GuidList.CpsProjectFactoryGuidString, "Rust", "Rust Project Files (*.rsproj);*.rsproj", "rsproj", "Rust", PossibleProjectExtensions = "rsproj")]
[ProvideProjectFileGenerator(typeof(RustProjectFileGenerator), GuidList.CpsProjectFactoryGuidString, FileNames = "Cargo.toml", DisplayGeneratorFilter = 300)]
// TODO: not sure what DeveloperActivity actually does
[DeveloperActivity("Rust", GuidList.guidVisualRustPkgString, sortPriority: 40)]
public class VisualRustPackage : Package, IOleCommandTarget
{
private IOleCommandTarget packageCommandTarget;
private Dictionary<IVsProjectGenerator, uint> _projectFileGenerators;
internal static VisualRustPackage Instance { get; private set; }
public const string UniqueCapability = "VisualRust";
/// <summary>
/// Default constructor of the package.
/// Inside this method you can place any initialization code that does not require
/// any Visual Studio service because at this point the package object is created but
/// not sited yet inside Visual Studio environment. The place to do all the other
/// initialization is the Initialize method.
/// </summary>
public VisualRustPackage()
{
Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering constructor for: {0}", this.ToString()));
//Microsoft.VisualStudioTools.UIThread.InitializeAndAlwaysInvokeToCurrentThread();
}
/////////////////////////////////////////////////////////////////////////////
// Overridden Package Implementation
#region Package Members
/// <summary>
/// Initialization of the package; this method is called right after the package is sited, so this is the place
/// where you can put all the initialization code that rely on services provided by VisualStudio.
/// </summary>
///
protected override void Initialize()
{
base.Initialize();
RegisterProjectFileGenerator(new RustProjectFileGenerator());
ProjectIconProvider.LoadProjectImages();
packageCommandTarget = GetService(typeof(IOleCommandTarget)) as IOleCommandTarget;
Instance = this;
Racer.RacerSingleton.Init();
}
private void RegisterProjectFileGenerator(IVsProjectGenerator projectFileGenerator)
{
var registerProjectGenerators = GetService(typeof(SVsRegisterProjectTypes)) as IVsRegisterProjectGenerators;
if (registerProjectGenerators == null)
{
throw new InvalidOperationException(typeof(SVsRegisterProjectTypes).FullName);
}
uint cookie;
Guid riid = projectFileGenerator.GetType().GUID;
registerProjectGenerators.RegisterProjectGenerator(ref riid, projectFileGenerator, out cookie);
if (_projectFileGenerators == null)
{
_projectFileGenerators = new Dictionary<IVsProjectGenerator, uint>();
}
_projectFileGenerators[projectFileGenerator] = cookie;
}
private void UnregisterProjectFileGenerators(Dictionary<IVsProjectGenerator, uint> projectFileGenerators)
{
try
{
IVsRegisterProjectGenerators registerProjectGenerators = GetService(typeof(SVsRegisterProjectTypes)) as IVsRegisterProjectGenerators;
if (registerProjectGenerators != null)
{
foreach (var projectFileGenerator in projectFileGenerators)
{
try
{
registerProjectGenerators.UnregisterProjectGenerator(projectFileGenerator.Value);
}
finally
{
(projectFileGenerator.Key as IDisposable)?.Dispose();
}
}
}
}
catch (Exception e)
{
Debug.Fail(String.Format(CultureInfo.InvariantCulture, "Failed to dispose project file generator for package {0}\n{1}", GetType().FullName, e.Message));
}
}
int IOleCommandTarget.Exec(ref Guid cmdGroup, uint nCmdID, uint nCmdExecOpt, IntPtr pvaIn, IntPtr pvaOut)
{
if (cmdGroup == GuidList.VisualRustCommandSet)
{
switch (nCmdID)
{
case 1:
return VRDebugExec(nCmdExecOpt, pvaIn, pvaOut);
default:
return VSConstants.E_NOTIMPL;
}
}
return packageCommandTarget.Exec(cmdGroup, nCmdID, nCmdExecOpt, pvaIn, pvaOut);
}
int IOleCommandTarget.QueryStatus(ref Guid cmdGroup, uint cCmds, OLECMD[] prgCmds, IntPtr pCmdText)
{
if (cmdGroup == GuidList.VisualRustCommandSet)
{
switch (prgCmds[0].cmdID)
{
case 1:
prgCmds[0].cmdf |= (uint)(OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_ENABLED | OLECMDF.OLECMDF_INVISIBLE);
return VSConstants.S_OK;
default:
Debug.Fail("Unknown command id");
return VSConstants.E_NOTIMPL;
}
}
return packageCommandTarget.QueryStatus(ref cmdGroup, cCmds, prgCmds, pCmdText);
}
private int VRDebugExec(uint nCmdExecOpt, IntPtr pvaIn, IntPtr pvaOut)
{
int hr;
if (IsQueryParameterList(pvaIn, pvaOut, nCmdExecOpt))
{
Marshal.GetNativeVariantForObject("$", pvaOut);
return VSConstants.S_OK;
}
string arguments;
hr = EnsureString(pvaIn, out arguments);
if (hr != VSConstants.S_OK)
return hr;
if (string.IsNullOrWhiteSpace(arguments))
throw new ArgumentException("Expected an MI command to execute (ex: Debug.VRDebugExec info sharedlibrary)");
VRDebugExecAsync(arguments);
return VSConstants.S_OK;
}
private async void VRDebugExecAsync(string command)
{
var commandWindow = (IVsCommandWindow)GetService(typeof(SVsCommandWindow));
string results = null;
try
{
results = await MIDebugCommandDispatcher.ExecuteCommand(command);
}
catch (Exception e)
{
if (e.InnerException != null)
e = e.InnerException;
UnexpectedMIResultException miException = e as UnexpectedMIResultException;
string message;
if (miException != null && miException.MIError != null)
message = miException.MIError;
else
message = e.Message;
commandWindow.Print(string.Format("Error: {0}\r\n", message));
return;
}
if (results.Length > 0)
{
// Make sure that we are printing whole lines
if (!results.EndsWith("\n") && !results.EndsWith("\r\n"))
{
results = results + "\n";
}
commandWindow.Print(results);
}
}
static private bool IsQueryParameterList(System.IntPtr pvaIn, System.IntPtr pvaOut, uint nCmdexecopt)
{
ushort lo = (ushort)(nCmdexecopt & (uint)0xffff);
ushort hi = (ushort)(nCmdexecopt >> 16);
if (lo == (ushort)OLECMDEXECOPT.OLECMDEXECOPT_SHOWHELP)
{
if (hi == Microsoft.VisualStudio.Shell.VsMenus.VSCmdOptQueryParameterList)
{
if (pvaOut != IntPtr.Zero)
{
return true;
}
}
}
return false;
}
static private int EnsureString(IntPtr pvaIn, out string arguments)
{
arguments = null;
if (pvaIn == IntPtr.Zero)
{
// No arguments.
return VSConstants.E_INVALIDARG;
}
object vaInObject = Marshal.GetObjectForNativeVariant(pvaIn);
if (vaInObject == null || vaInObject.GetType() != typeof(string))
{
return VSConstants.E_INVALIDARG;
}
arguments = vaInObject as string;
return VSConstants.S_OK;
}
protected override void Dispose(bool disposing)
{
ProjectIconProvider.Close();
if (!disposing)
{
base.Dispose(false);
return;
}
if (_projectFileGenerators != null)
{
var projectFileGenerators = _projectFileGenerators;
_projectFileGenerators = null;
UnregisterProjectFileGenerators(projectFileGenerators);
}
base.Dispose(true);
}
#endregion
}
}
| PistonDevelopers/VisualRust | src/VisualRust/VisualRustPackage.cs | C# | mit | 12,355 |
# frozen_string_literal: true
require 'test_helper'
class SearchControllerTest < ActionController::TestCase
test 'should get index' do
get :index
assert_response :success
assert_not_nil assigns(:results)
end
test 'should search by site' do
site = Post.last.site
get :index, params: { site: site.site_name }
assert_response :success
assert_not_nil assigns(:results)
assert_equal(assigns(:results), assigns(:results).select { |p| p.site_id == site.id })
end
test 'should search by reputation' do
get :index, params: { user_rep_direction: '>=', user_reputation: 10 }
assert_response :success
assert_not_nil assigns(:results)
assert_equal(assigns(:results), assigns(:results).select { |p| p.user_reputation >= 10 })
end
test 'should search by reputation with graph' do
get :index, params: { user_rep_direction: '>=', user_reputation: 10, option: 'graph' }
assert_response :success
assert_not_nil assigns(:results)
assert_equal(assigns(:results), assigns(:results).select { |p| p.user_reputation >= 10 })
end
test 'should search by false positive' do
get :index, params: { feedback: 'false positive' }
assert_response :success
end
test 'should search by false positive with graph' do
get :index, params: { feedback: 'false positive', option: 'graph' }
assert_response :success
end
test 'should search by regex' do
sign_in User.first
get :index, params: { title: 'foo', title_is_regex: true, title_is_inverse_regex: true }
assert_response :success
end
test 'should search by not autoflagged' do
get :index, params: { autoflagged: 'No' }
assert_response :success
assert_not_nil assigns(:results)
end
end
| Charcoal-SE/metasmoke | test/controllers/search_controller_test.rb | Ruby | cc0-1.0 | 1,744 |
<?php
/**
* CodeIgniter
*
* An open source application development framework for PHP 5.1.6 or newer
*
* @package CodeIgniter
* @author ExpressionEngine Dev Team
* @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
* @license http://codeigniter.com/user_guide/license.html
* @link http://codeigniter.com
* @since Version 1.0
* @filesource
*/
// ------------------------------------------------------------------------
/**
* Image Manipulation class
*
* @package CodeIgniter
* @subpackage Libraries
* @category Image_lib
* @author ExpressionEngine Dev Team
* @link http://codeigniter.com/user_guide/libraries/image_lib.html
*/
define('FILE_READ_MODE', 0644);
define('FILE_WRITE_MODE', 0666);
define('DIR_READ_MODE', 0755);
define('DIR_WRITE_MODE', 0777);
define('FOPEN_READ', 'rb');
define('FOPEN_READ_WRITE', 'r+b');
define('FOPEN_WRITE_CREATE_DESTRUCTIVE', 'wb'); // truncates existing file data, use with care
define('FOPEN_READ_WRITE_CREATE_DESTRUCTIVE', 'w+b'); // truncates existing file data, use with care
define('FOPEN_WRITE_CREATE', 'ab');
define('FOPEN_READ_WRITE_CREATE', 'a+b');
define('FOPEN_WRITE_CREATE_STRICT', 'xb');
define('FOPEN_READ_WRITE_CREATE_STRICT', 'x+b');
class Image_lib {
var $image_library = 'gd2'; // Can be: imagemagick, netpbm, gd, gd2
var $library_path = '';
var $dynamic_output = FALSE; // Whether to send to browser or write to disk
var $source_image = '';
var $new_image = '';
var $width = '';
var $height = '';
var $quality = '90';
var $create_thumb = FALSE;
var $thumb_marker = '_thumb';
var $maintain_ratio = TRUE; // Whether to maintain aspect ratio when resizing or use hard values
var $master_dim = 'auto'; // auto, height, or width. Determines what to use as the master dimension
var $rotation_angle = '';
var $x_axis = '';
var $y_axis = '';
// Watermark Vars
var $wm_text = ''; // Watermark text if graphic is not used
var $wm_type = 'text'; // Type of watermarking. Options: text/overlay
var $wm_x_transp = 4;
var $wm_y_transp = 4;
var $wm_overlay_path = ''; // Watermark image path
var $wm_font_path = ''; // TT font
var $wm_font_size = 17; // Font size (different versions of GD will either use points or pixels)
var $wm_vrt_alignment = 'B'; // Vertical alignment: T M B
var $wm_hor_alignment = 'C'; // Horizontal alignment: L R C
var $wm_padding = 0; // Padding around text
var $wm_hor_offset = 0; // Lets you push text to the right
var $wm_vrt_offset = 0; // Lets you push text down
var $wm_font_color = '#ffffff'; // Text color
var $wm_shadow_color = ''; // Dropshadow color
var $wm_shadow_distance = 2; // Dropshadow distance
var $wm_opacity = 50; // Image opacity: 1 - 100 Only works with image
// Private Vars
var $source_folder = '';
var $dest_folder = '';
var $mime_type = '';
var $orig_width = '';
var $orig_height = '';
var $image_type = '';
var $size_str = '';
var $full_src_path = '';
var $full_dst_path = '';
var $create_fnc = 'imagecreatetruecolor';
var $copy_fnc = 'imagecopyresampled';
var $error_msg = array();
var $wm_use_drop_shadow = FALSE;
var $wm_use_truetype = FALSE;
/**
* Constructor
*
* @param string
* @return void
*/
public function __construct($props = array())
{
if (count($props) > 0)
{
$this->initialize($props);
}
//log_message('debug', "Image Lib Class Initialized");
}
// --------------------------------------------------------------------
/**
* Initialize image properties
*
* Resets values in case this class is used in a loop
*
* @access public
* @return void
*/
function clear()
{
$props = array('source_folder', 'dest_folder', 'source_image', 'full_src_path', 'full_dst_path', 'new_image', 'image_type', 'size_str', 'quality', 'orig_width', 'orig_height', 'width', 'height', 'rotation_angle', 'x_axis', 'y_axis', 'create_fnc', 'copy_fnc', 'wm_overlay_path', 'wm_use_truetype', 'dynamic_output', 'wm_font_size', 'wm_text', 'wm_vrt_alignment', 'wm_hor_alignment', 'wm_padding', 'wm_hor_offset', 'wm_vrt_offset', 'wm_font_color', 'wm_use_drop_shadow', 'wm_shadow_color', 'wm_shadow_distance', 'wm_opacity');
foreach ($props as $val)
{
$this->$val = '';
}
// special consideration for master_dim
$this->master_dim = 'auto';
}
// --------------------------------------------------------------------
/**
* initialize image preferences
*
* @access public
* @param array
* @return bool
*/
function initialize($props = array())
{
/*
* Convert array elements into class variables
*/
if (count($props) > 0)
{
foreach ($props as $key => $val)
{
$this->$key = $val;
}
}
/*
* Is there a source image?
*
* If not, there's no reason to continue
*
*/
if ($this->source_image == '')
{
$this->set_error('imglib_source_image_required');
return FALSE;
}
/*
* Is getimagesize() Available?
*
* We use it to determine the image properties (width/height).
* Note: We need to figure out how to determine image
* properties using ImageMagick and NetPBM
*
*/
if ( ! function_exists('getimagesize'))
{
$this->set_error('imglib_gd_required_for_props');
return FALSE;
}
$this->image_library = strtolower($this->image_library);
/*
* Set the full server path
*
* The source image may or may not contain a path.
* Either way, we'll try use realpath to generate the
* full server path in order to more reliably read it.
*
*/
if (function_exists('realpath') AND @realpath($this->source_image) !== FALSE)
{
$full_source_path = str_replace("\\", "/", realpath($this->source_image));
}
else
{
$full_source_path = $this->source_image;
}
$x = explode('/', $full_source_path);
$this->source_image = end($x);
$this->source_folder = str_replace($this->source_image, '', $full_source_path);
// Set the Image Properties
if ( ! $this->get_image_properties($this->source_folder.$this->source_image))
{
return FALSE;
}
/*
* Assign the "new" image name/path
*
* If the user has set a "new_image" name it means
* we are making a copy of the source image. If not
* it means we are altering the original. We'll
* set the destination filename and path accordingly.
*
*/
if ($this->new_image == '')
{
$this->dest_image = $this->source_image;
$this->dest_folder = $this->source_folder;
}
else
{
if (strpos($this->new_image, '/') === FALSE AND strpos($this->new_image, '\\') === FALSE)
{
$this->dest_folder = $this->source_folder;
$this->dest_image = $this->new_image;
}
else
{
if (function_exists('realpath') AND @realpath($this->new_image) !== FALSE)
{
$full_dest_path = str_replace("\\", "/", realpath($this->new_image));
}
else
{
$full_dest_path = $this->new_image;
}
// Is there a file name?
if ( ! preg_match("#\.(jpg|jpeg|gif|png)$#i", $full_dest_path))
{
$this->dest_folder = $full_dest_path.'/';
$this->dest_image = $this->source_image;
}
else
{
$x = explode('/', $full_dest_path);
$this->dest_image = end($x);
$this->dest_folder = str_replace($this->dest_image, '', $full_dest_path);
}
}
}
/*
* Compile the finalized filenames/paths
*
* We'll create two master strings containing the
* full server path to the source image and the
* full server path to the destination image.
* We'll also split the destination image name
* so we can insert the thumbnail marker if needed.
*
*/
if ($this->create_thumb === FALSE OR $this->thumb_marker == '')
{
$this->thumb_marker = '';
}
$xp = $this->explode_name($this->dest_image);
$filename = $xp['name'];
$file_ext = $xp['ext'];
$this->full_src_path = $this->source_folder.$this->source_image;
$this->full_dst_path = $this->dest_folder.$filename.$this->thumb_marker.$file_ext;
/*
* Should we maintain image proportions?
*
* When creating thumbs or copies, the target width/height
* might not be in correct proportion with the source
* image's width/height. We'll recalculate it here.
*
*/
if ($this->maintain_ratio === TRUE && ($this->width != '' AND $this->height != ''))
{
$this->image_reproportion();
}
/*
* Was a width and height specified?
*
* If the destination width/height was
* not submitted we will use the values
* from the actual file
*
*/
if ($this->width == '')
$this->width = $this->orig_width;
if ($this->height == '')
$this->height = $this->orig_height;
// Set the quality
$this->quality = trim(str_replace("%", "", $this->quality));
if ($this->quality == '' OR $this->quality == 0 OR ! is_numeric($this->quality))
$this->quality = 90;
// Set the x/y coordinates
$this->x_axis = ($this->x_axis == '' OR ! is_numeric($this->x_axis)) ? 0 : $this->x_axis;
$this->y_axis = ($this->y_axis == '' OR ! is_numeric($this->y_axis)) ? 0 : $this->y_axis;
// Watermark-related Stuff...
if ($this->wm_font_color != '')
{
if (strlen($this->wm_font_color) == 6)
{
$this->wm_font_color = '#'.$this->wm_font_color;
}
}
if ($this->wm_shadow_color != '')
{
if (strlen($this->wm_shadow_color) == 6)
{
$this->wm_shadow_color = '#'.$this->wm_shadow_color;
}
}
if ($this->wm_overlay_path != '')
{
$this->wm_overlay_path = str_replace("\\", "/", realpath($this->wm_overlay_path));
}
if ($this->wm_shadow_color != '')
{
$this->wm_use_drop_shadow = TRUE;
}
if ($this->wm_font_path != '')
{
$this->wm_use_truetype = TRUE;
}
return TRUE;
}
// --------------------------------------------------------------------
/**
* Image Resize
*
* This is a wrapper function that chooses the proper
* resize function based on the protocol specified
*
* @access public
* @return bool
*/
function resize()
{
$protocol = 'image_process_'.$this->image_library;
if (preg_match('/gd2$/i', $protocol))
{
$protocol = 'image_process_gd';
}
return $this->$protocol('resize');
}
// --------------------------------------------------------------------
/**
* Image Crop
*
* This is a wrapper function that chooses the proper
* cropping function based on the protocol specified
*
* @access public
* @return bool
*/
function crop()
{
$protocol = 'image_process_'.$this->image_library;
if (preg_match('/gd2$/i', $protocol))
{
$protocol = 'image_process_gd';
}
return $this->$protocol('crop');
}
// --------------------------------------------------------------------
/**
* Image Rotate
*
* This is a wrapper function that chooses the proper
* rotation function based on the protocol specified
*
* @access public
* @return bool
*/
function rotate()
{
// Allowed rotation values
$degs = array(90, 180, 270, 'vrt', 'hor');
if ($this->rotation_angle == '' OR ! in_array($this->rotation_angle, $degs))
{
$this->set_error('imglib_rotation_angle_required');
return FALSE;
}
// Reassign the width and height
if ($this->rotation_angle == 90 OR $this->rotation_angle == 270)
{
$this->width = $this->orig_height;
$this->height = $this->orig_width;
}
else
{
$this->width = $this->orig_width;
$this->height = $this->orig_height;
}
// Choose resizing function
if ($this->image_library == 'imagemagick' OR $this->image_library == 'netpbm')
{
$protocol = 'image_process_'.$this->image_library;
return $this->$protocol('rotate');
}
if ($this->rotation_angle == 'hor' OR $this->rotation_angle == 'vrt')
{
return $this->image_mirror_gd();
}
else
{
return $this->image_rotate_gd();
}
}
// --------------------------------------------------------------------
/**
* Image Process Using GD/GD2
*
* This function will resize or crop
*
* @access public
* @param string
* @return bool
*/
function image_process_gd($action = 'resize')
{
$v2_override = FALSE;
// If the target width/height match the source, AND if the new file name is not equal to the old file name
// we'll simply make a copy of the original with the new name... assuming dynamic rendering is off.
if ($this->dynamic_output === FALSE)
{
if ($this->orig_width == $this->width AND $this->orig_height == $this->height)
{
if ($this->source_image != $this->new_image)
{
if (@copy($this->full_src_path, $this->full_dst_path))
{
@chmod($this->full_dst_path, FILE_WRITE_MODE);
}
}
return TRUE;
}
}
// Let's set up our values based on the action
if ($action == 'crop')
{
// Reassign the source width/height if cropping
$this->orig_width = $this->width;
$this->orig_height = $this->height;
// GD 2.0 has a cropping bug so we'll test for it
if ($this->gd_version() !== FALSE)
{
$gd_version = str_replace('0', '', $this->gd_version());
$v2_override = ($gd_version == 2) ? TRUE : FALSE;
}
}
else
{
// If resizing the x/y axis must be zero
$this->x_axis = 0;
$this->y_axis = 0;
}
// Create the image handle
if ( ! ($src_img = $this->image_create_gd()))
{
return FALSE;
}
// Create The Image
//
// old conditional which users report cause problems with shared GD libs who report themselves as "2.0 or greater"
// it appears that this is no longer the issue that it was in 2004, so we've removed it, retaining it in the comment
// below should that ever prove inaccurate.
//
// if ($this->image_library == 'gd2' AND function_exists('imagecreatetruecolor') AND $v2_override == FALSE)
if ($this->image_library == 'gd2' AND function_exists('imagecreatetruecolor'))
{
$create = 'imagecreatetruecolor';
$copy = 'imagecopyresampled';
}
else
{
$create = 'imagecreate';
$copy = 'imagecopyresized';
}
$dst_img = $create($this->width, $this->height);
if ($this->image_type == 3) // png we can actually preserve transparency
{
imagealphablending($dst_img, FALSE);
imagesavealpha($dst_img, TRUE);
}
$copy($dst_img, $src_img, 0, 0, $this->x_axis, $this->y_axis, $this->width, $this->height, $this->orig_width, $this->orig_height);
// Show the image
if ($this->dynamic_output == TRUE)
{
$this->image_display_gd($dst_img);
}
else
{
// Or save it
if ( ! $this->image_save_gd($dst_img))
{
return FALSE;
}
}
// Kill the file handles
imagedestroy($dst_img);
imagedestroy($src_img);
// Set the file to 777
@chmod($this->full_dst_path, FILE_WRITE_MODE);
return TRUE;
}
// --------------------------------------------------------------------
/**
* Image Process Using ImageMagick
*
* This function will resize, crop or rotate
*
* @access public
* @param string
* @return bool
*/
function image_process_imagemagick($action = 'resize')
{
// Do we have a vaild library path?
if ($this->library_path == '')
{
$this->set_error('imglib_libpath_invalid');
return FALSE;
}
if ( ! preg_match("/convert$/i", $this->library_path))
{
$this->library_path = rtrim($this->library_path, '/').'/';
$this->library_path .= 'convert';
}
// Execute the command
$cmd = $this->library_path." -quality ".$this->quality;
if ($action == 'crop')
{
$cmd .= " -crop ".$this->width."x".$this->height."+".$this->x_axis."+".$this->y_axis." \"$this->full_src_path\" \"$this->full_dst_path\" 2>&1";
}
elseif ($action == 'rotate')
{
switch ($this->rotation_angle)
{
case 'hor' : $angle = '-flop';
break;
case 'vrt' : $angle = '-flip';
break;
default : $angle = '-rotate '.$this->rotation_angle;
break;
}
$cmd .= " ".$angle." \"$this->full_src_path\" \"$this->full_dst_path\" 2>&1";
}
else // Resize
{
$cmd .= " -resize ".$this->width."x".$this->height." \"$this->full_src_path\" \"$this->full_dst_path\" 2>&1";
}
$retval = 1;
@exec($cmd, $output, $retval);
// Did it work?
if ($retval > 0)
{
$this->set_error('imglib_image_process_failed');
return FALSE;
}
// Set the file to 777
@chmod($this->full_dst_path, FILE_WRITE_MODE);
return TRUE;
}
// --------------------------------------------------------------------
/**
* Image Process Using NetPBM
*
* This function will resize, crop or rotate
*
* @access public
* @param string
* @return bool
*/
function image_process_netpbm($action = 'resize')
{
if ($this->library_path == '')
{
$this->set_error('imglib_libpath_invalid');
return FALSE;
}
// Build the resizing command
switch ($this->image_type)
{
case 1 :
$cmd_in = 'giftopnm';
$cmd_out = 'ppmtogif';
break;
case 2 :
$cmd_in = 'jpegtopnm';
$cmd_out = 'ppmtojpeg';
break;
case 3 :
$cmd_in = 'pngtopnm';
$cmd_out = 'ppmtopng';
break;
}
if ($action == 'crop')
{
$cmd_inner = 'pnmcut -left '.$this->x_axis.' -top '.$this->y_axis.' -width '.$this->width.' -height '.$this->height;
}
elseif ($action == 'rotate')
{
switch ($this->rotation_angle)
{
case 90 : $angle = 'r270';
break;
case 180 : $angle = 'r180';
break;
case 270 : $angle = 'r90';
break;
case 'vrt' : $angle = 'tb';
break;
case 'hor' : $angle = 'lr';
break;
}
$cmd_inner = 'pnmflip -'.$angle.' ';
}
else // Resize
{
$cmd_inner = 'pnmscale -xysize '.$this->width.' '.$this->height;
}
$cmd = $this->library_path.$cmd_in.' '.$this->full_src_path.' | '.$cmd_inner.' | '.$cmd_out.' > '.$this->dest_folder.'netpbm.tmp';
$retval = 1;
@exec($cmd, $output, $retval);
// Did it work?
if ($retval > 0)
{
$this->set_error('imglib_image_process_failed');
return FALSE;
}
// With NetPBM we have to create a temporary image.
// If you try manipulating the original it fails so
// we have to rename the temp file.
copy ($this->dest_folder.'netpbm.tmp', $this->full_dst_path);
unlink ($this->dest_folder.'netpbm.tmp');
@chmod($this->full_dst_path, FILE_WRITE_MODE);
return TRUE;
}
// --------------------------------------------------------------------
/**
* Image Rotate Using GD
*
* @access public
* @return bool
*/
function image_rotate_gd()
{
// Create the image handle
if ( ! ($src_img = $this->image_create_gd()))
{
return FALSE;
}
// Set the background color
// This won't work with transparent PNG files so we are
// going to have to figure out how to determine the color
// of the alpha channel in a future release.
$white = imagecolorallocate($src_img, 255, 255, 255);
// Rotate it!
$dst_img = imagerotate($src_img, $this->rotation_angle, $white);
// Save the Image
if ($this->dynamic_output == TRUE)
{
$this->image_display_gd($dst_img);
}
else
{
// Or save it
if ( ! $this->image_save_gd($dst_img))
{
return FALSE;
}
}
// Kill the file handles
imagedestroy($dst_img);
imagedestroy($src_img);
// Set the file to 777
@chmod($this->full_dst_path, FILE_WRITE_MODE);
return TRUE;
}
// --------------------------------------------------------------------
/**
* Create Mirror Image using GD
*
* This function will flip horizontal or vertical
*
* @access public
* @return bool
*/
function image_mirror_gd()
{
if ( ! $src_img = $this->image_create_gd())
{
return FALSE;
}
$width = $this->orig_width;
$height = $this->orig_height;
if ($this->rotation_angle == 'hor')
{
for ($i = 0; $i < $height; $i++)
{
$left = 0;
$right = $width-1;
while ($left < $right)
{
$cl = imagecolorat($src_img, $left, $i);
$cr = imagecolorat($src_img, $right, $i);
imagesetpixel($src_img, $left, $i, $cr);
imagesetpixel($src_img, $right, $i, $cl);
$left++;
$right--;
}
}
}
else
{
for ($i = 0; $i < $width; $i++)
{
$top = 0;
$bot = $height-1;
while ($top < $bot)
{
$ct = imagecolorat($src_img, $i, $top);
$cb = imagecolorat($src_img, $i, $bot);
imagesetpixel($src_img, $i, $top, $cb);
imagesetpixel($src_img, $i, $bot, $ct);
$top++;
$bot--;
}
}
}
// Show the image
if ($this->dynamic_output == TRUE)
{
$this->image_display_gd($src_img);
}
else
{
// Or save it
if ( ! $this->image_save_gd($src_img))
{
return FALSE;
}
}
// Kill the file handles
imagedestroy($src_img);
// Set the file to 777
@chmod($this->full_dst_path, FILE_WRITE_MODE);
return TRUE;
}
// --------------------------------------------------------------------
/**
* Image Watermark
*
* This is a wrapper function that chooses the type
* of watermarking based on the specified preference.
*
* @access public
* @param string
* @return bool
*/
function watermark()
{
if ($this->wm_type == 'overlay')
{
return $this->overlay_watermark();
}
else
{
return $this->text_watermark();
}
}
// --------------------------------------------------------------------
/**
* Watermark - Graphic Version
*
* @access public
* @return bool
*/
function overlay_watermark()
{
if ( ! function_exists('imagecolortransparent'))
{
$this->set_error('imglib_gd_required');
return FALSE;
}
// Fetch source image properties
$this->get_image_properties();
// Fetch watermark image properties
$props = $this->get_image_properties($this->wm_overlay_path, TRUE);
$wm_img_type = $props['image_type'];
$wm_width = $props['width'];
$wm_height = $props['height'];
// Create two image resources
$wm_img = $this->image_create_gd($this->wm_overlay_path, $wm_img_type);
$src_img = $this->image_create_gd($this->full_src_path);
// Reverse the offset if necessary
// When the image is positioned at the bottom
// we don't want the vertical offset to push it
// further down. We want the reverse, so we'll
// invert the offset. Same with the horizontal
// offset when the image is at the right
$this->wm_vrt_alignment = strtoupper(substr($this->wm_vrt_alignment, 0, 1));
$this->wm_hor_alignment = strtoupper(substr($this->wm_hor_alignment, 0, 1));
if ($this->wm_vrt_alignment == 'B')
$this->wm_vrt_offset = $this->wm_vrt_offset * -1;
if ($this->wm_hor_alignment == 'R')
$this->wm_hor_offset = $this->wm_hor_offset * -1;
// Set the base x and y axis values
$x_axis = $this->wm_hor_offset + $this->wm_padding;
$y_axis = $this->wm_vrt_offset + $this->wm_padding;
// Set the vertical position
switch ($this->wm_vrt_alignment)
{
case 'T':
break;
case 'M': $y_axis += ($this->orig_height / 2) - ($wm_height / 2);
break;
case 'B': $y_axis += $this->orig_height - $wm_height;
break;
}
// Set the horizontal position
switch ($this->wm_hor_alignment)
{
case 'L':
break;
case 'C': $x_axis += ($this->orig_width / 2) - ($wm_width / 2);
break;
case 'R': $x_axis += $this->orig_width - $wm_width;
break;
}
// Build the finalized image
if ($wm_img_type == 3 AND function_exists('imagealphablending'))
{
@imagealphablending($src_img, TRUE);
}
// Set RGB values for text and shadow
$rgba = imagecolorat($wm_img, $this->wm_x_transp, $this->wm_y_transp);
$alpha = ($rgba & 0x7F000000) >> 24;
// make a best guess as to whether we're dealing with an image with alpha transparency or no/binary transparency
if ($alpha > 0)
{
// copy the image directly, the image's alpha transparency being the sole determinant of blending
imagecopy($src_img, $wm_img, $x_axis, $y_axis, 0, 0, $wm_width, $wm_height);
}
else
{
// set our RGB value from above to be transparent and merge the images with the specified opacity
imagecolortransparent($wm_img, imagecolorat($wm_img, $this->wm_x_transp, $this->wm_y_transp));
imagecopymerge($src_img, $wm_img, $x_axis, $y_axis, 0, 0, $wm_width, $wm_height, $this->wm_opacity);
}
// Output the image
if ($this->dynamic_output == TRUE)
{
$this->image_display_gd($src_img);
}
else
{
if ( ! $this->image_save_gd($src_img))
{
return FALSE;
}
}
imagedestroy($src_img);
imagedestroy($wm_img);
return TRUE;
}
// --------------------------------------------------------------------
/**
* Watermark - Text Version
*
* @access public
* @return bool
*/
function text_watermark()
{
if ( ! ($src_img = $this->image_create_gd()))
{
return FALSE;
}
if ($this->wm_use_truetype == TRUE AND ! file_exists($this->wm_font_path))
{
$this->set_error('imglib_missing_font');
return FALSE;
}
// Fetch source image properties
$this->get_image_properties();
// Set RGB values for text and shadow
$this->wm_font_color = str_replace('#', '', $this->wm_font_color);
$this->wm_shadow_color = str_replace('#', '', $this->wm_shadow_color);
$R1 = hexdec(substr($this->wm_font_color, 0, 2));
$G1 = hexdec(substr($this->wm_font_color, 2, 2));
$B1 = hexdec(substr($this->wm_font_color, 4, 2));
$R2 = hexdec(substr($this->wm_shadow_color, 0, 2));
$G2 = hexdec(substr($this->wm_shadow_color, 2, 2));
$B2 = hexdec(substr($this->wm_shadow_color, 4, 2));
$txt_color = imagecolorclosest($src_img, $R1, $G1, $B1);
$drp_color = imagecolorclosest($src_img, $R2, $G2, $B2);
// Reverse the vertical offset
// When the image is positioned at the bottom
// we don't want the vertical offset to push it
// further down. We want the reverse, so we'll
// invert the offset. Note: The horizontal
// offset flips itself automatically
if ($this->wm_vrt_alignment == 'B')
$this->wm_vrt_offset = $this->wm_vrt_offset * -1;
if ($this->wm_hor_alignment == 'R')
$this->wm_hor_offset = $this->wm_hor_offset * -1;
// Set font width and height
// These are calculated differently depending on
// whether we are using the true type font or not
if ($this->wm_use_truetype == TRUE)
{
if ($this->wm_font_size == '')
$this->wm_font_size = '17';
$fontwidth = $this->wm_font_size-($this->wm_font_size/4);
$fontheight = $this->wm_font_size;
$this->wm_vrt_offset += $this->wm_font_size;
}
else
{
$fontwidth = imagefontwidth($this->wm_font_size);
$fontheight = imagefontheight($this->wm_font_size);
}
// Set base X and Y axis values
$x_axis = $this->wm_hor_offset + $this->wm_padding;
$y_axis = $this->wm_vrt_offset + $this->wm_padding;
// Set verticle alignment
if ($this->wm_use_drop_shadow == FALSE)
$this->wm_shadow_distance = 0;
$this->wm_vrt_alignment = strtoupper(substr($this->wm_vrt_alignment, 0, 1));
$this->wm_hor_alignment = strtoupper(substr($this->wm_hor_alignment, 0, 1));
switch ($this->wm_vrt_alignment)
{
case "T" :
break;
case "M": $y_axis += ($this->orig_height/2)+($fontheight/2);
break;
case "B": $y_axis += ($this->orig_height - $fontheight - $this->wm_shadow_distance - ($fontheight/2));
break;
}
$x_shad = $x_axis + $this->wm_shadow_distance;
$y_shad = $y_axis + $this->wm_shadow_distance;
// Set horizontal alignment
switch ($this->wm_hor_alignment)
{
case "L":
break;
case "R":
if ($this->wm_use_drop_shadow)
$x_shad += ($this->orig_width - $fontwidth*strlen($this->wm_text));
$x_axis += ($this->orig_width - $fontwidth*strlen($this->wm_text));
break;
case "C":
if ($this->wm_use_drop_shadow)
$x_shad += floor(($this->orig_width - $fontwidth*strlen($this->wm_text))/2);
$x_axis += floor(($this->orig_width -$fontwidth*strlen($this->wm_text))/2);
break;
}
// Add the text to the source image
if ($this->wm_use_truetype)
{
if ($this->wm_use_drop_shadow)
imagettftext($src_img, $this->wm_font_size, 0, $x_shad, $y_shad, $drp_color, $this->wm_font_path, $this->wm_text);
imagettftext($src_img, $this->wm_font_size, 0, $x_axis, $y_axis, $txt_color, $this->wm_font_path, $this->wm_text);
}
else
{
if ($this->wm_use_drop_shadow)
imagestring($src_img, $this->wm_font_size, $x_shad, $y_shad, $this->wm_text, $drp_color);
imagestring($src_img, $this->wm_font_size, $x_axis, $y_axis, $this->wm_text, $txt_color);
}
// Output the final image
if ($this->dynamic_output == TRUE)
{
$this->image_display_gd($src_img);
}
else
{
$this->image_save_gd($src_img);
}
imagedestroy($src_img);
return TRUE;
}
// --------------------------------------------------------------------
/**
* Create Image - GD
*
* This simply creates an image resource handle
* based on the type of image being processed
*
* @access public
* @param string
* @return resource
*/
function image_create_gd($path = '', $image_type = '')
{
if ($path == '')
$path = $this->full_src_path;
if ($image_type == '')
$image_type = $this->image_type;
switch ($image_type)
{
case 1 :
if ( ! function_exists('imagecreatefromgif'))
{
$this->set_error(array('imglib_unsupported_imagecreate', 'imglib_gif_not_supported'));
return FALSE;
}
return imagecreatefromgif($path);
break;
case 2 :
if ( ! function_exists('imagecreatefromjpeg'))
{
$this->set_error(array('imglib_unsupported_imagecreate', 'imglib_jpg_not_supported'));
return FALSE;
}
return imagecreatefromjpeg($path);
break;
case 3 :
if ( ! function_exists('imagecreatefrompng'))
{
$this->set_error(array('imglib_unsupported_imagecreate', 'imglib_png_not_supported'));
return FALSE;
}
return imagecreatefrompng($path);
break;
}
$this->set_error(array('imglib_unsupported_imagecreate'));
return FALSE;
}
// --------------------------------------------------------------------
/**
* Write image file to disk - GD
*
* Takes an image resource as input and writes the file
* to the specified destination
*
* @access public
* @param resource
* @return bool
*/
function image_save_gd($resource)
{
switch ($this->image_type)
{
case 1 :
if ( ! function_exists('imagegif'))
{
$this->set_error(array('imglib_unsupported_imagecreate', 'imglib_gif_not_supported'));
return FALSE;
}
if ( ! @imagegif($resource, $this->full_dst_path))
{
$this->set_error('imglib_save_failed');
return FALSE;
}
break;
case 2 :
if ( ! function_exists('imagejpeg'))
{
$this->set_error(array('imglib_unsupported_imagecreate', 'imglib_jpg_not_supported'));
return FALSE;
}
if ( ! @imagejpeg($resource, $this->full_dst_path, $this->quality))
{
$this->set_error('imglib_save_failed');
return FALSE;
}
break;
case 3 :
if ( ! function_exists('imagepng'))
{
$this->set_error(array('imglib_unsupported_imagecreate', 'imglib_png_not_supported'));
return FALSE;
}
if ( ! @imagepng($resource, $this->full_dst_path))
{
$this->set_error('imglib_save_failed');
return FALSE;
}
break;
default :
$this->set_error(array('imglib_unsupported_imagecreate'));
return FALSE;
break;
}
return TRUE;
}
// --------------------------------------------------------------------
/**
* Dynamically outputs an image
*
* @access public
* @param resource
* @return void
*/
function image_display_gd($resource)
{
header("Content-Disposition: filename={$this->source_image};");
header("Content-Type: {$this->mime_type}");
header('Content-Transfer-Encoding: binary');
header('Last-Modified: '.gmdate('D, d M Y H:i:s', time()).' GMT');
switch ($this->image_type)
{
case 1 : imagegif($resource);
break;
case 2 : imagejpeg($resource, '', $this->quality);
break;
case 3 : imagepng($resource);
break;
default : echo 'Unable to display the image';
break;
}
}
// --------------------------------------------------------------------
/**
* Re-proportion Image Width/Height
*
* When creating thumbs, the desired width/height
* can end up warping the image due to an incorrect
* ratio between the full-sized image and the thumb.
*
* This function lets us re-proportion the width/height
* if users choose to maintain the aspect ratio when resizing.
*
* @access public
* @return void
*/
function image_reproportion()
{
if ( ! is_numeric($this->width) OR ! is_numeric($this->height) OR $this->width == 0 OR $this->height == 0)
return;
if ( ! is_numeric($this->orig_width) OR ! is_numeric($this->orig_height) OR $this->orig_width == 0 OR $this->orig_height == 0)
return;
$new_width = ceil($this->orig_width*$this->height/$this->orig_height);
$new_height = ceil($this->width*$this->orig_height/$this->orig_width);
$ratio = (($this->orig_height/$this->orig_width) - ($this->height/$this->width));
if ($this->master_dim != 'width' AND $this->master_dim != 'height')
{
$this->master_dim = ($ratio < 0) ? 'width' : 'height';
}
if (($this->width != $new_width) AND ($this->height != $new_height))
{
if ($this->master_dim == 'height')
{
$this->width = $new_width;
}
else
{
$this->height = $new_height;
}
}
}
// --------------------------------------------------------------------
/**
* Get image properties
*
* A helper function that gets info about the file
*
* @access public
* @param string
* @return mixed
*/
function get_image_properties($path = '', $return = FALSE)
{
// For now we require GD but we should
// find a way to determine this using IM or NetPBM
if ($path == '')
$path = $this->full_src_path;
if ( ! file_exists($path))
{
$this->set_error('imglib_invalid_path');
return FALSE;
}
$vals = @getimagesize($path);
$types = array(1 => 'gif', 2 => 'jpeg', 3 => 'png');
$mime = (isset($types[$vals['2']])) ? 'image/'.$types[$vals['2']] : 'image/jpg';
if ($return == TRUE)
{
$v['width'] = $vals['0'];
$v['height'] = $vals['1'];
$v['image_type'] = $vals['2'];
$v['size_str'] = $vals['3'];
$v['mime_type'] = $mime;
return $v;
}
$this->orig_width = $vals['0'];
$this->orig_height = $vals['1'];
$this->image_type = $vals['2'];
$this->size_str = $vals['3'];
$this->mime_type = $mime;
return TRUE;
}
// --------------------------------------------------------------------
/**
* Size calculator
*
* This function takes a known width x height and
* recalculates it to a new size. Only one
* new variable needs to be known
*
* $props = array(
* 'width' => $width,
* 'height' => $height,
* 'new_width' => 40,
* 'new_height' => ''
* );
*
* @access public
* @param array
* @return array
*/
function size_calculator($vals)
{
if ( ! is_array($vals))
{
return;
}
$allowed = array('new_width', 'new_height', 'width', 'height');
foreach ($allowed as $item)
{
if ( ! isset($vals[$item]) OR $vals[$item] == '')
$vals[$item] = 0;
}
if ($vals['width'] == 0 OR $vals['height'] == 0)
{
return $vals;
}
if ($vals['new_width'] == 0)
{
$vals['new_width'] = ceil($vals['width']*$vals['new_height']/$vals['height']);
}
elseif ($vals['new_height'] == 0)
{
$vals['new_height'] = ceil($vals['new_width']*$vals['height']/$vals['width']);
}
return $vals;
}
// --------------------------------------------------------------------
/**
* Explode source_image
*
* This is a helper function that extracts the extension
* from the source_image. This function lets us deal with
* source_images with multiple periods, like: my.cool.jpg
* It returns an associative array with two elements:
* $array['ext'] = '.jpg';
* $array['name'] = 'my.cool';
*
* @access public
* @param array
* @return array
*/
function explode_name($source_image)
{
$ext = strrchr($source_image, '.');
$name = ($ext === FALSE) ? $source_image : substr($source_image, 0, -strlen($ext));
return array('ext' => $ext, 'name' => $name);
}
// --------------------------------------------------------------------
/**
* Is GD Installed?
*
* @access public
* @return bool
*/
function gd_loaded()
{
if ( ! extension_loaded('gd'))
{
if ( ! dl('gd.so'))
{
return FALSE;
}
}
return TRUE;
}
// --------------------------------------------------------------------
/**
* Get GD version
*
* @access public
* @return mixed
*/
function gd_version()
{
if (function_exists('gd_info'))
{
$gd_version = @gd_info();
$gd_version = preg_replace("/\D/", "", $gd_version['GD Version']);
return $gd_version;
}
return FALSE;
}
// --------------------------------------------------------------------
/**
* Set error message
*
* @access public
* @param string
* @return void
*/
function set_error($msg)
{
if (is_array($msg))
{
foreach ($msg as $val)
{
$this->error_msg[] = lang($val);
//log_message('error', $msg);
}
}
else
{
$this->error_msg[] = lang($msg);
//log_message('error', $msg);
}
}
// --------------------------------------------------------------------
/**
* Show error messages
*
* @access public
* @param string
* @return string
*/
function display_errors($open = '<p>', $close = '</p>')
{
$str = '';
foreach ($this->error_msg as $val)
{
$str .= $open.$val.$close;
}
return $str;
}
}
// END Image_lib Class
/* End of file Image_lib.php */
/* Location: ./system/libraries/Image_lib.php */ | qurantools/kurancalis-mobile | ionic/qurantools/www/assets/libs/file-manager/Image_lib.php | PHP | cc0-1.0 | 37,779 |
package p;
public class A {
Object o= new SomeClass().a;
}
| maxeler/eclipse | eclipse.jdt.ui/org.eclipse.jdt.ui.tests.refactoring/resources/MoveInnerToTopLevel/test34/out/A.java | Java | epl-1.0 | 62 |
/*******************************************************************************
* Copyright (c) 2004 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.report.engine.layout.pdf;
import java.util.Iterator;
import java.util.List;
import org.eclipse.birt.report.engine.api.EngineException;
import org.eclipse.birt.report.engine.api.IReportRunnable;
import org.eclipse.birt.report.engine.nLayout.area.impl.ContainerArea;
import org.eclipse.birt.report.engine.nLayout.area.impl.PageArea;
import org.eclipse.birt.report.engine.nLayout.area.impl.TableArea;
public class PDFTableGroupLMTest extends PDFLayoutTest
{
/**
* Test case for bugzilla bug <a
* href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=173601">173601</a> :
* [regression]Group should begin from the second page when setting group page break before to always[0001]
*
* @throws EngineException
*/
public void testGroupPageBreakBeforeAways() throws EngineException
{
String designFile = "org/eclipse/birt/report/engine/layout/pdf/173601.xml"; //$NON-NLS-1$
IReportRunnable report = openReportDesign( designFile );
List pageAreas = getPageAreas( report );
assertEquals( 2, pageAreas.size( ) );
PageArea pageArea = (PageArea)pageAreas.get( 0 );
ContainerArea body = (ContainerArea)pageArea.getBody( );
assertTrue(body.getChildrenCount( )==1);
Iterator iter = body.getChildren( );
TableArea table = (TableArea) iter.next( );
assertTrue(table.getChildrenCount( )==1);
pageArea = (PageArea)pageAreas.get( 1 );
body = (ContainerArea)pageArea.getBody( );
assertTrue(body.getChildrenCount( )==1);
iter = body.getChildren( );
table = (TableArea) iter.next( );
assertTrue(table.getChildrenCount( )==2);
iter = table.getChildren( );
iter.next( );//table header row
ContainerArea group = (ContainerArea)iter.next( );
assertTrue(group.getChildrenCount( )==6);
}
}
| sguan-actuate/birt | engine/org.eclipse.birt.report.engine.tests/test/org/eclipse/birt/report/engine/layout/pdf/PDFTableGroupLMTest.java | Java | epl-1.0 | 2,291 |
package org.eclipse.incquery.examples.cps.m2t.proto.distributed.generated.hosts;
import org.eclipse.incquery.examples.cps.m2t.proto.distributed.general.applications.Application;
import org.eclipse.incquery.examples.cps.m2t.proto.distributed.general.communicationlayer.CommunicationNetwork;
import org.eclipse.incquery.examples.cps.m2t.proto.distributed.general.hosts.BaseHost;
// Add imports for applications
import org.eclipse.incquery.examples.cps.m2t.proto.distributed.generated.applications.IBMSystemStorageApplication;
import com.google.common.collect.Lists;
public class Host152661025 extends BaseHost {
public Host152661025(CommunicationNetwork network) {
super(network);
// Add Applications of Host
applications = Lists.<Application>newArrayList(
new IBMSystemStorageApplication(this)
);
}
}
| lunkpeter/incquery-examples-cps | prototypes/org.eclipse.incquery.examples.cps.m2t.proto.distributed/src/org/eclipse/incquery/examples/cps/m2t/proto/distributed/generated/hosts/Host152661025.java | Java | epl-1.0 | 822 |
/*******************************************************************************
* Copyright (c) 2010 Oak Ridge National Laboratory.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
******************************************************************************/
package org.csstudio.archive.engine.server.html;
import java.io.PrintWriter;
import java.time.Instant;
import javax.servlet.http.HttpServletResponse;
import org.csstudio.archive.vtype.TimestampHelper;
/** Helper for creating uniform HTML pages for a servlet response.
* @author Kay Kasemir
*/
@SuppressWarnings("nls")
public class HTMLWriter
{
final protected static String BACKGROUND = "images/blueback.jpg"; //$NON-NLS-1$
final protected static String RED_FONT = "<font color='#ff0000'>"; //$NON-NLS-1$
final protected static String CLOSE_FONT = "</font>"; //$NON-NLS-1$
/** Writer */
final private PrintWriter html;
/** Helper for marking every other table line */
private boolean odd_table_line = true;
/** @return HTML Writer with start of HTML page.
* @param resp Response for which to create the writer
* @param title HTML title
* @throws Exception on error
*/
public HTMLWriter(final HttpServletResponse resp, final String title)
throws Exception
{
resp.setContentType("text/html");
html = resp.getWriter();
text("<html>");
text("<head>");
text("<title>" + title + "</title>");
text("<script type=\"text/javascript\" src=\"/sorttable.js\"></script>\n");
text("</head>");
text("<body background='" + BACKGROUND + "'>");
text("<blockquote>");
h1(title);
}
/** Add end of HTML page. */
public void close()
{
text("<p>");
text("<hr width='50%' align='left'>");
text("<a href=\"/main\">-Main-</a> ");
text("<a href=\"/groups\">-Groups-</a> ");
text("<a href=\"/disconnected\">-Disconnected-</a> ");
text("<a href=\"/version.html\">-Version-</a> ");
text("<address>");
text(TimestampHelper.format(Instant.now()));
text(" <i>(Use web browser's Reload to refresh this page)</i>");
text("</address>");
text("</blockquote>");
text("</body>");
text("</html>");
html.close();
}
/** Add text to HTML */
protected void text(final String text)
{
html.println(text);
}
/** Add header */
protected void h1(final String text)
{
text("<h1>" + text + "</h1>");
}
/** Add header */
protected void h2(final String text)
{
text("<h2>" + text + "</h2>");
}
/** Start a table.
* <p>
* The intial column header might span more than one column.
* In fact, it might be the only columns header.
* Otherwise, the remaining column headers each span one column.
*
* @param initial_colspan Number of columns for the first header.
* @param header Headers for all the columns
* @see #tableLine(String[])
* @see #closeTable()
*/
protected void openTable(final int initial_colspan, final String headers[])
{
text("<table border='0' class='sortable'>");
text("<thead>");
text(" <tr bgcolor='#FFCC66'>");
text(" <th align='center' colspan='" + initial_colspan + "'>" +
headers[0] + "</th>");
for (int i=1; i<headers.length; ++i)
text(" <th align='center'>" + headers[i] + "</th>");
text(" </tr>");
text("</thead>");
text("<tbody>");
odd_table_line = true;
}
/** One table line.
* @param columns Text for each column.
* Count must match the colspan of openTable
* @see #openTable(int, String[])
*/
protected void tableLine(final String[] columns)
{
text(" <tr>");
boolean first = true;
for (String column : columns)
{
if (first)
{
first = false;
if (odd_table_line)
text(" <th align='left' valign='top'>" + column + "</th>");
else
text(" <th align='left' valign='top' bgcolor='#DFDFFF'>" + column + "</th>");
}
else
{
if (odd_table_line)
text(" <td align='center' valign='top'>" + column + "</td>");
else
text(" <td align='center' valign='top' bgcolor='#DFDFFF'>" + column + "</td>");
}
}
text(" </tr>");
odd_table_line = !odd_table_line;
}
/** Close a table */
protected void closeTable()
{
text("</tbody>");
text("</table>");
}
/** Create HTML for a link
* @param url Linked URL
* @param text Text to display
* @return HTML for the link
*/
public static String makeLink(final String url, final String text)
{
return "<a href=\"" + url + "\">" + text + "</a>";
}
/** @return HTML for red text */
public static String makeRedText(final String text)
{
return RED_FONT + text + CLOSE_FONT;
}
}
| css-iter/cs-studio | applications/archive/archive-plugins/org.csstudio.archive.engine/src/org/csstudio/archive/engine/server/html/HTMLWriter.java | Java | epl-1.0 | 5,450 |
/*
* Copyright (c) 2012-2018 Red Hat, Inc.
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
*/
package org.eclipse.che.api.installer.server.impl;
import static org.eclipse.che.api.installer.server.DtoConverter.asDto;
import static org.eclipse.che.api.installer.server.InstallerRegistryService.TOTAL_ITEMS_COUNT_HEADER;
import com.google.common.reflect.TypeToken;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import javax.ws.rs.core.UriBuilder;
import org.eclipse.che.api.core.ApiException;
import org.eclipse.che.api.core.BadRequestException;
import org.eclipse.che.api.core.ConflictException;
import org.eclipse.che.api.core.NotFoundException;
import org.eclipse.che.api.core.Page;
import org.eclipse.che.api.core.rest.HttpJsonRequestFactory;
import org.eclipse.che.api.core.rest.HttpJsonResponse;
import org.eclipse.che.api.installer.server.InstallerRegistry;
import org.eclipse.che.api.installer.server.InstallerRegistryService;
import org.eclipse.che.api.installer.server.exception.IllegalInstallerKeyException;
import org.eclipse.che.api.installer.server.exception.InstallerAlreadyExistsException;
import org.eclipse.che.api.installer.server.exception.InstallerException;
import org.eclipse.che.api.installer.server.exception.InstallerNotFoundException;
import org.eclipse.che.api.installer.shared.dto.InstallerDto;
import org.eclipse.che.api.installer.shared.model.Installer;
import org.eclipse.che.commons.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Remote implementation of the {@link InstallerRegistry}.
*
* <p>It is designed to fetch data from remote {@link InstallerRegistryService} which is configured
* by registry.installer.remote property.
*
* @author Sergii Leshchenko
* @author Anatolii Bazko
*/
@Singleton
public class RemoteInstallerRegistry implements InstallerRegistry {
private static final Logger LOG = LoggerFactory.getLogger(RemoteInstallerRegistry.class);
private String registryServiceUrl;
private final HttpJsonRequestFactory requestFactory;
@Inject
public RemoteInstallerRegistry(
@Nullable @Named("che.installer.registry.remote") String remoteInstallerUrl,
HttpJsonRequestFactory requestFactory) {
this.requestFactory = requestFactory;
if (remoteInstallerUrl != null) {
try {
new URL(remoteInstallerUrl);
this.registryServiceUrl =
UriBuilder.fromUri(remoteInstallerUrl)
.path(InstallerRegistryService.class)
.build()
.toString();
} catch (MalformedURLException e) {
LOG.warn("Configured 'che.installer.registry.remote' is invalid URL.");
this.registryServiceUrl = null;
}
}
}
@Override
public void add(Installer installer) throws InstallerException {
checkConfiguration();
try {
requestFactory
.fromUrl(
UriBuilder.fromUri(registryServiceUrl)
.path(InstallerRegistryService.class, "add")
.build()
.toString())
.setBody(asDto(installer))
.usePostMethod()
.request();
} catch (ConflictException e) {
throw new InstallerAlreadyExistsException(e.getMessage(), e);
} catch (IOException | ApiException e) {
throw new InstallerException(e.getMessage(), e);
}
}
@Override
public void update(Installer installer) throws InstallerException {
checkConfiguration();
try {
requestFactory
.fromUrl(
UriBuilder.fromUri(registryServiceUrl)
.path(InstallerRegistryService.class, "update")
.build()
.toString())
.setBody(asDto(installer))
.usePutMethod()
.request();
} catch (NotFoundException e) {
throw new InstallerNotFoundException(e.getMessage(), e);
} catch (IOException | ApiException e) {
throw new InstallerException(e.getMessage(), e);
}
}
@Override
public void remove(String installerKey) throws InstallerException {
checkConfiguration();
try {
requestFactory
.fromUrl(
UriBuilder.fromUri(registryServiceUrl)
.path(InstallerRegistryService.class, "remove")
.build(installerKey)
.toString())
.useDeleteMethod()
.request();
} catch (IOException | ApiException e) {
throw new InstallerException(e.getMessage(), e);
}
}
@Override
public Installer getInstaller(String installerKey) throws InstallerException {
checkConfiguration();
try {
return requestFactory
.fromUrl(
UriBuilder.fromUri(registryServiceUrl)
.path(InstallerRegistryService.class, "getInstaller")
.build(installerKey)
.toString())
.useGetMethod()
.request()
.asDto(InstallerDto.class);
} catch (NotFoundException e) {
throw new InstallerNotFoundException(e.getMessage(), e);
} catch (BadRequestException e) {
throw new IllegalInstallerKeyException(e.getMessage(), e);
} catch (IOException | ApiException e) {
throw new InstallerException(e.getMessage(), e);
}
}
@Override
public List<String> getVersions(String id) throws InstallerException {
checkConfiguration();
try {
@SuppressWarnings("unchecked")
List<String> result =
requestFactory
.fromUrl(
UriBuilder.fromUri(registryServiceUrl)
.path(InstallerRegistryService.class, "getVersions")
.build(id)
.toString())
.useGetMethod()
.request()
.as(List.class, new TypeToken<List<String>>() {}.getType());
return result;
} catch (NotFoundException e) {
throw new InstallerNotFoundException(e.getMessage(), e);
} catch (IOException | ApiException e) {
throw new InstallerException(e.getMessage(), e);
}
}
@Override
public Page<? extends Installer> getInstallers(int maxItems, int skipCount)
throws InstallerException {
checkConfiguration();
try {
HttpJsonResponse response =
requestFactory
.fromUrl(
UriBuilder.fromUri(registryServiceUrl)
.path(InstallerRegistryService.class, "getInstallers")
.queryParam("maxItems", maxItems)
.queryParam("skipCount", skipCount)
.build()
.toString())
.useGetMethod()
.request();
int totalCount = -1;
List<String> totalItemsCountHeader = response.getHeaders().get(TOTAL_ITEMS_COUNT_HEADER);
if (totalItemsCountHeader != null && !totalItemsCountHeader.isEmpty()) {
totalCount = Integer.valueOf(totalItemsCountHeader.get(0));
}
return new Page<>(response.asList(InstallerDto.class), skipCount, maxItems, totalCount);
} catch (BadRequestException e) {
throw new IllegalArgumentException(e);
} catch (IOException | ApiException e) {
throw new InstallerException(e.getMessage(), e);
}
}
@Override
public List<Installer> getOrderedInstallers(List<String> installerKeys)
throws InstallerException {
checkConfiguration();
try {
return new ArrayList<>(
requestFactory
.fromUrl(
UriBuilder.fromUri(registryServiceUrl)
.path(InstallerRegistryService.class, "getOrderedInstallers")
.build()
.toString())
.usePostMethod()
.setBody(installerKeys)
.request()
.asList(InstallerDto.class));
} catch (NotFoundException e) {
throw new InstallerNotFoundException(e.getMessage(), e);
} catch (BadRequestException e) {
throw new IllegalInstallerKeyException(e.getMessage(), e);
} catch (IOException | ApiException e) {
throw new InstallerException(e.getMessage(), e);
}
}
public boolean isConfigured() {
return registryServiceUrl != null;
}
private void checkConfiguration() {
if (!isConfigured()) {
throw new IllegalStateException("Remote installer registry is not configured.");
}
}
}
| akervern/che | wsmaster/che-core-api-installer/src/main/java/org/eclipse/che/api/installer/server/impl/RemoteInstallerRegistry.java | Java | epl-1.0 | 8,795 |
/*******************************************************************************
* Copyright (c) 2000, 2008 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.wst.jsdt.internal.ui.search;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IPath;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IWorkingSet;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.dialogs.IWorkingSetSelectionDialog;
import org.eclipse.wst.jsdt.core.IJsGlobalScopeContainer;
import org.eclipse.wst.jsdt.core.IIncludePathEntry;
import org.eclipse.wst.jsdt.core.IJavaScriptElement;
import org.eclipse.wst.jsdt.core.IJavaScriptProject;
import org.eclipse.wst.jsdt.core.IPackageFragment;
import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
import org.eclipse.wst.jsdt.core.IType;
import org.eclipse.wst.jsdt.core.JavaScriptCore;
import org.eclipse.wst.jsdt.core.JavaScriptModelException;
import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
import org.eclipse.wst.jsdt.core.search.SearchEngine;
import org.eclipse.wst.jsdt.internal.corext.util.Messages;
import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
import org.eclipse.wst.jsdt.internal.ui.browsing.LogicalPackage;
import org.eclipse.wst.jsdt.ui.JavaScriptUI;
public class JavaSearchScopeFactory {
public static final int JRE= IJavaScriptSearchScope.SYSTEM_LIBRARIES;
public static final int LIBS= IJavaScriptSearchScope.APPLICATION_LIBRARIES;
public static final int PROJECTS= IJavaScriptSearchScope.REFERENCED_PROJECTS;
public static final int SOURCES= IJavaScriptSearchScope.SOURCES;
public static final int ALL= JRE | LIBS | PROJECTS | SOURCES;
public static final int NO_PROJ= JRE | LIBS | SOURCES;
public static final int NO_JRE= LIBS | PROJECTS | SOURCES;
public static final int NO_JRE_NO_PROJ= LIBS | PROJECTS | SOURCES;
private static JavaSearchScopeFactory fgInstance;
private final IJavaScriptSearchScope EMPTY_SCOPE= SearchEngine.createJavaSearchScope(new IJavaScriptElement[] {});
private JavaSearchScopeFactory() {
}
public static JavaSearchScopeFactory getInstance() {
if (fgInstance == null)
fgInstance= new JavaSearchScopeFactory();
return fgInstance;
}
public IWorkingSet[] queryWorkingSets() throws JavaScriptModelException, InterruptedException {
Shell shell= JavaScriptPlugin.getActiveWorkbenchShell();
if (shell == null)
return null;
IWorkingSetSelectionDialog dialog= PlatformUI.getWorkbench().getWorkingSetManager().createWorkingSetSelectionDialog(shell, true);
if (dialog.open() != Window.OK) {
throw new InterruptedException();
}
IWorkingSet[] workingSets= dialog.getSelection();
if (workingSets.length > 0)
return workingSets;
return null; // 'no working set' selected
}
public IJavaScriptSearchScope createJavaSearchScope(IWorkingSet[] workingSets, boolean includeJRE) {
return createJavaSearchScope(workingSets, includeJRE ? ALL : NO_JRE);
}
public IJavaScriptSearchScope createJavaSearchScope(IWorkingSet[] workingSets, int includeMask) {
if (workingSets == null || workingSets.length < 1)
return EMPTY_SCOPE;
Set javaElements= new HashSet(workingSets.length * 10);
for (int i= 0; i < workingSets.length; i++) {
IWorkingSet workingSet= workingSets[i];
if (workingSet.isEmpty() && workingSet.isAggregateWorkingSet()) {
return createWorkspaceScope(includeMask);
}
addJavaElements(javaElements, workingSet);
}
return createJavaSearchScope(javaElements, includeMask);
}
public IJavaScriptSearchScope createJavaSearchScope(IWorkingSet workingSet, boolean includeJRE) {
return createJavaSearchScope(workingSet, includeJRE ? NO_PROJ : NO_JRE_NO_PROJ);
}
public IJavaScriptSearchScope createJavaSearchScope(IWorkingSet workingSet, int includeMask) {
Set javaElements= new HashSet(10);
if (workingSet.isEmpty() && workingSet.isAggregateWorkingSet()) {
return createWorkspaceScope(includeMask);
}
addJavaElements(javaElements, workingSet);
return createJavaSearchScope(javaElements, includeMask);
}
public IJavaScriptSearchScope createJavaSearchScope(IResource[] resources, boolean includeJRE) {
return createJavaSearchScope(resources, includeJRE ? NO_PROJ : NO_JRE_NO_PROJ);
}
public IJavaScriptSearchScope createJavaSearchScope(IResource[] resources, int includeMask) {
if (resources == null)
return EMPTY_SCOPE;
Set javaElements= new HashSet(resources.length);
addJavaElements(javaElements, resources);
return createJavaSearchScope(javaElements, includeMask);
}
public IJavaScriptSearchScope createJavaSearchScope(ISelection selection, boolean includeJRE) {
return createJavaSearchScope(selection, includeJRE ? NO_PROJ : NO_JRE_NO_PROJ);
}
public IJavaScriptSearchScope createJavaSearchScope(ISelection selection, int includeMask) {
return createJavaSearchScope(getJavaElements(selection), includeMask);
}
public IJavaScriptSearchScope createJavaProjectSearchScope(String[] projectNames, boolean includeJRE) {
return createJavaProjectSearchScope(projectNames, includeJRE ? NO_PROJ : NO_JRE_NO_PROJ);
}
public IJavaScriptSearchScope createJavaProjectSearchScope(String[] projectNames, int includeMask) {
ArrayList res= new ArrayList();
IWorkspaceRoot root= ResourcesPlugin.getWorkspace().getRoot();
for (int i= 0; i < projectNames.length; i++) {
IJavaScriptProject project= JavaScriptCore.create(root.getProject(projectNames[i]));
if (project.exists()) {
res.add(project);
}
}
return createJavaSearchScope(res, includeMask);
}
public IJavaScriptSearchScope createJavaProjectSearchScope(IJavaScriptProject project, boolean includeJRE) {
return createJavaProjectSearchScope(project, includeJRE ? NO_PROJ : NO_JRE_NO_PROJ);
}
public IJavaScriptSearchScope createJavaProjectSearchScope(IJavaScriptProject project, int includeMask) {
return SearchEngine.createJavaSearchScope(new IJavaScriptElement[] { project }, getSearchFlags(includeMask));
}
public IJavaScriptSearchScope createJavaProjectSearchScope(IEditorInput editorInput, boolean includeJRE) {
return createJavaProjectSearchScope(editorInput, includeJRE ? ALL : NO_JRE);
}
public IJavaScriptSearchScope createJavaProjectSearchScope(IEditorInput editorInput, int includeMask) {
IJavaScriptElement elem= JavaScriptUI.getEditorInputJavaElement(editorInput);
if (elem != null) {
IJavaScriptProject project= elem.getJavaScriptProject();
if (project != null) {
return createJavaProjectSearchScope(project, includeMask);
}
}
return EMPTY_SCOPE;
}
public String getWorkspaceScopeDescription(boolean includeJRE) {
return includeJRE ? SearchMessages.WorkspaceScope : SearchMessages.WorkspaceScopeNoJRE;
}
public String getWorkspaceScopeDescription(int includeMask) {
return getWorkspaceScopeDescription((includeMask & JRE) != 0);
}
public String getProjectScopeDescription(String[] projectNames, int includeMask) {
if (projectNames.length == 0) {
return SearchMessages.JavaSearchScopeFactory_undefined_projects;
}
boolean includeJRE= (includeMask & JRE) != 0;
String scopeDescription;
if (projectNames.length == 1) {
String label= includeJRE ? SearchMessages.EnclosingProjectScope : SearchMessages.EnclosingProjectScopeNoJRE;
scopeDescription= Messages.format(label, projectNames[0]);
} else if (projectNames.length == 2) {
String label= includeJRE ? SearchMessages.EnclosingProjectsScope2 : SearchMessages.EnclosingProjectsScope2NoJRE;
scopeDescription= Messages.format(label, new String[] { projectNames[0], projectNames[1]});
} else {
String label= includeJRE ? SearchMessages.EnclosingProjectsScope : SearchMessages.EnclosingProjectsScopeNoJRE;
scopeDescription= Messages.format(label, new String[] { projectNames[0], projectNames[1]});
}
return scopeDescription;
}
public String getProjectScopeDescription(IJavaScriptProject project, boolean includeJRE) {
if (includeJRE) {
return Messages.format(SearchMessages.ProjectScope, project.getElementName());
} else {
return Messages.format(SearchMessages.ProjectScopeNoJRE, project.getElementName());
}
}
public String getProjectScopeDescription(IEditorInput editorInput, boolean includeJRE) {
IJavaScriptElement elem= JavaScriptUI.getEditorInputJavaElement(editorInput);
if (elem != null) {
IJavaScriptProject project= elem.getJavaScriptProject();
if (project != null) {
return getProjectScopeDescription(project, includeJRE);
}
}
return Messages.format(SearchMessages.ProjectScope, ""); //$NON-NLS-1$
}
public String getHierarchyScopeDescription(IType type) {
return Messages.format(SearchMessages.HierarchyScope, new String[] { type.getElementName() });
}
public String getSelectionScopeDescription(IJavaScriptElement[] javaElements, int includeMask) {
return getSelectionScopeDescription(javaElements, (includeMask & JRE) != 0);
}
public String getSelectionScopeDescription(IJavaScriptElement[] javaElements, boolean includeJRE) {
if (javaElements.length == 0) {
return SearchMessages.JavaSearchScopeFactory_undefined_selection;
}
String scopeDescription;
if (javaElements.length == 1) {
String label= includeJRE ? SearchMessages.SingleSelectionScope : SearchMessages.SingleSelectionScopeNoJRE;
scopeDescription= Messages.format(label, javaElements[0].getElementName());
} else if (javaElements.length == 1) {
String label= includeJRE ? SearchMessages.DoubleSelectionScope : SearchMessages.DoubleSelectionScopeNoJRE;
scopeDescription= Messages.format(label, new String[] { javaElements[0].getElementName(), javaElements[1].getElementName()});
} else {
String label= includeJRE ? SearchMessages.SelectionScope : SearchMessages.SelectionScopeNoJRE;
scopeDescription= Messages.format(label, new String[] { javaElements[0].getElementName(), javaElements[1].getElementName()});
}
return scopeDescription;
}
public String getWorkingSetScopeDescription(IWorkingSet[] workingSets, int includeMask) {
return getWorkingSetScopeDescription(workingSets, (includeMask & JRE) != 0);
}
public String getWorkingSetScopeDescription(IWorkingSet[] workingSets, boolean includeJRE) {
if (workingSets.length == 0) {
return SearchMessages.JavaSearchScopeFactory_undefined_workingsets;
}
if (workingSets.length == 1) {
String label= includeJRE ? SearchMessages.SingleWorkingSetScope : SearchMessages.SingleWorkingSetScopeNoJRE;
return Messages.format(label, workingSets[0].getLabel());
}
Arrays.sort(workingSets, new WorkingSetComparator());
if (workingSets.length == 2) {
String label= includeJRE ? SearchMessages.DoubleWorkingSetScope : SearchMessages.DoubleWorkingSetScopeNoJRE;
return Messages.format(label, new String[] { workingSets[0].getLabel(), workingSets[1].getLabel()});
}
String label= includeJRE ? SearchMessages.WorkingSetsScope : SearchMessages.WorkingSetsScopeNoJRE;
return Messages.format(label, new String[] { workingSets[0].getLabel(), workingSets[1].getLabel()});
}
public IProject[] getProjects(IJavaScriptSearchScope scope) {
IPath[] paths= scope.enclosingProjectsAndJars();
HashSet temp= new HashSet();
for (int i= 0; i < paths.length; i++) {
IResource resource= ResourcesPlugin.getWorkspace().getRoot().findMember(paths[i]);
if (resource != null && resource.getType() == IResource.PROJECT)
temp.add(resource);
}
return (IProject[]) temp.toArray(new IProject[temp.size()]);
}
public IJavaScriptElement[] getJavaElements(ISelection selection) {
if (selection instanceof IStructuredSelection && !selection.isEmpty()) {
return getJavaElements(((IStructuredSelection)selection).toArray());
} else {
return new IJavaScriptElement[0];
}
}
private IJavaScriptElement[] getJavaElements(Object[] elements) {
if (elements.length == 0)
return new IJavaScriptElement[0];
Set result= new HashSet(elements.length);
for (int i= 0; i < elements.length; i++) {
Object selectedElement= elements[i];
if (selectedElement instanceof IJavaScriptElement) {
addJavaElements(result, (IJavaScriptElement) selectedElement);
} else if (selectedElement instanceof IResource) {
addJavaElements(result, (IResource) selectedElement);
} else if (selectedElement instanceof LogicalPackage) {
addJavaElements(result, (LogicalPackage) selectedElement);
} else if (selectedElement instanceof IWorkingSet) {
IWorkingSet ws= (IWorkingSet)selectedElement;
addJavaElements(result, ws);
} else if (selectedElement instanceof IAdaptable) {
IResource resource= (IResource) ((IAdaptable) selectedElement).getAdapter(IResource.class);
if (resource != null)
addJavaElements(result, resource);
}
}
return (IJavaScriptElement[]) result.toArray(new IJavaScriptElement[result.size()]);
}
public IJavaScriptSearchScope createJavaSearchScope(IJavaScriptElement[] javaElements, boolean includeJRE) {
return createJavaSearchScope(javaElements, includeJRE ? NO_PROJ : NO_JRE_NO_PROJ);
}
public IJavaScriptSearchScope createJavaSearchScope(IJavaScriptElement[] javaElements, int includeMask) {
if (javaElements.length == 0)
return EMPTY_SCOPE;
return SearchEngine.createJavaSearchScope(javaElements, getSearchFlags(includeMask));
}
private IJavaScriptSearchScope createJavaSearchScope(Collection javaElements, int includeMask) {
if (javaElements.isEmpty())
return EMPTY_SCOPE;
IJavaScriptElement[] elementArray= (IJavaScriptElement[]) javaElements.toArray(new IJavaScriptElement[javaElements.size()]);
return SearchEngine.createJavaSearchScope(elementArray, getSearchFlags(includeMask));
}
private static int getSearchFlags(int includeMask) {
return includeMask;
}
private void addJavaElements(Set javaElements, IResource[] resources) {
for (int i= 0; i < resources.length; i++)
addJavaElements(javaElements, resources[i]);
}
private void addJavaElements(Set javaElements, IResource resource) {
IJavaScriptElement javaElement= (IJavaScriptElement)resource.getAdapter(IJavaScriptElement.class);
if (javaElement == null)
// not a Java resource
return;
if (javaElement.getElementType() == IJavaScriptElement.PACKAGE_FRAGMENT) {
// add other possible package fragments
try {
addJavaElements(javaElements, ((IFolder)resource).members());
} catch (CoreException ex) {
// don't add elements
}
}
javaElements.add(javaElement);
}
private void addJavaElements(Set javaElements, IJavaScriptElement javaElement) {
javaElements.add(javaElement);
}
private void addJavaElements(Set javaElements, IWorkingSet workingSet) {
if (workingSet == null)
return;
if (workingSet.isAggregateWorkingSet() && workingSet.isEmpty()) {
try {
IJavaScriptProject[] projects= JavaScriptCore.create(ResourcesPlugin.getWorkspace().getRoot()).getJavaScriptProjects();
javaElements.addAll(Arrays.asList(projects));
} catch (JavaScriptModelException e) {
JavaScriptPlugin.log(e);
}
return;
}
IAdaptable[] elements= workingSet.getElements();
for (int i= 0; i < elements.length; i++) {
IJavaScriptElement javaElement=(IJavaScriptElement) elements[i].getAdapter(IJavaScriptElement.class);
if (javaElement != null) {
addJavaElements(javaElements, javaElement);
continue;
}
IResource resource= (IResource)elements[i].getAdapter(IResource.class);
if (resource != null) {
addJavaElements(javaElements, resource);
}
// else we don't know what to do with it, ignore.
}
}
private void addJavaElements(Set javaElements, LogicalPackage selectedElement) {
IPackageFragment[] packages= selectedElement.getFragments();
for (int i= 0; i < packages.length; i++)
addJavaElements(javaElements, packages[i]);
}
public IJavaScriptSearchScope createWorkspaceScope(boolean includeJRE) {
return createWorkspaceScope(includeJRE ? ALL : NO_JRE);
}
public IJavaScriptSearchScope createWorkspaceScope(int includeMask) {
if ((includeMask & NO_PROJ) != NO_PROJ) {
try {
IJavaScriptProject[] projects= JavaScriptCore.create(ResourcesPlugin.getWorkspace().getRoot()).getJavaScriptProjects();
return SearchEngine.createJavaSearchScope(projects, getSearchFlags(includeMask));
} catch (JavaScriptModelException e) {
// ignore, use workspace scope instead
}
}
return SearchEngine.createWorkspaceScope();
}
public boolean isInsideJRE(IJavaScriptElement element) {
IPackageFragmentRoot root= (IPackageFragmentRoot) element.getAncestor(IJavaScriptElement.PACKAGE_FRAGMENT_ROOT);
if (root != null) {
try {
IIncludePathEntry entry= root.getRawIncludepathEntry();
if (entry.getEntryKind() == IIncludePathEntry.CPE_CONTAINER) {
IJsGlobalScopeContainer container= JavaScriptCore.getJsGlobalScopeContainer(entry.getPath(), root.getJavaScriptProject());
return container != null && container.getKind() == IJsGlobalScopeContainer.K_DEFAULT_SYSTEM;
}
return false;
} catch (JavaScriptModelException e) {
JavaScriptPlugin.log(e);
}
}
return true; // include JRE in doubt
}
}
| boniatillo-com/PhaserEditor | source/thirdparty/jsdt/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/JavaSearchScopeFactory.java | Java | epl-1.0 | 18,056 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.protobuf;
import java.io.IOException;
import java.io.OutputStream;
public interface MessageBuffer<B, MB extends MessageBuffer> extends PBMessage<B, MB> {
public int serializedSizeUnframed();
public int serializedSizeFramed();
public Buffer toUnframedBuffer();
public Buffer toFramedBuffer();
public byte[] toUnframedByteArray();
public byte[] toFramedByteArray();
public void writeUnframed(CodedOutputStream output) throws java.io.IOException;
public void writeFramed(CodedOutputStream output) throws java.io.IOException;
public void writeUnframed(OutputStream output) throws IOException;
public void writeFramed(OutputStream output) throws java.io.IOException;
}
| Mark-Booth/daq-eclipse | uk.ac.diamond.org.apache.activemq/org/apache/activemq/protobuf/MessageBuffer.java | Java | epl-1.0 | 1,583 |
/***********************************************************************
* Copyright (c) 2004 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
***********************************************************************/
package org.eclipse.birt.chart.event;
import org.eclipse.birt.chart.device.IDeviceRenderer;
import org.eclipse.birt.chart.exception.ChartException;
import org.eclipse.birt.chart.model.attribute.Image;
import org.eclipse.birt.chart.model.attribute.Location;
import org.eclipse.birt.chart.model.attribute.Position;
/**
* A rendering event type for rendering Image object.
*/
public class ImageRenderEvent extends PrimitiveRenderEvent
{
private static final long serialVersionUID = -5467310111862210812L;
protected transient Image img;
protected transient Location loc;
protected Position pos;
protected int width = -1;
protected int height = -1;
protected boolean stretch = false;
/**
* The constructor.
*/
public ImageRenderEvent( Object oSource )
{
super( oSource );
}
/**
* Sets the location of the image.
*/
public void setLocation( Location loc )
{
this.loc = loc;
}
/**
* Sets the content of the image.
*/
public void setImage( Image img )
{
this.img = img;
}
/**
* Sets the position of the image.
*/
public void setPosition( Position pos )
{
this.pos = pos;
}
/**
* @return Returns the location of the image.
*/
public Location getLocation( )
{
return loc;
}
/**
* @return Returns the content of the image.
*/
public Image getImage( )
{
return img;
}
/**
* @return Returns the position of the image.
*/
public Position getPosition( )
{
return pos;
}
/**
* Sets the width hint of the image.
*/
public void setWidth( int width )
{
this.width = width;
}
/**
* Sets the height hint of the image.
*/
public void setHeight( int height )
{
this.height = height;
}
/**
* @return Returns the width hint of the image.
*/
public int getWidth( )
{
return width;
}
/**
* @return Returns the height hint of the image.
*/
public int getHeight( )
{
return height;
}
/**
* Sets if stretch the image.
*/
public void setStretch( boolean val )
{
this.stretch = val;
}
/**
* @return Returns if stretch the image.
*/
public boolean isStretch( )
{
return stretch;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.chart.event.PrimitiveRenderEvent#copy()
*/
public PrimitiveRenderEvent copy( ) throws ChartException
{
ImageRenderEvent ire = new ImageRenderEvent( source );
if ( loc != null )
{
ire.setLocation( loc.copyInstance( ) );
}
if ( img != null )
{
ire.setImage( goFactory.copyOf( img ) );
}
ire.setPosition( pos );
ire.setWidth( width );
ire.setHeight( height );
ire.setStretch( stretch );
return ire;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.chart.event.PrimitiveRenderEvent#fill(org.eclipse.birt.chart.device.IDeviceRenderer)
*/
public void fill( IDeviceRenderer idr ) throws ChartException
{
draw( idr );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.chart.event.PrimitiveRenderEvent#draw(org.eclipse.birt.chart.device.IDeviceRenderer)
*/
public void draw( IDeviceRenderer idr ) throws ChartException
{
idr.drawImage( this );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.chart.event.ChartEvent#reset()
*/
public void reset( )
{
this.loc = null;
this.pos = null;
}
}
| sguan-actuate/birt | chart/org.eclipse.birt.chart.engine/src/org/eclipse/birt/chart/event/ImageRenderEvent.java | Java | epl-1.0 | 3,737 |
//selection: 6, 29, 6, 36
package invalid;
class PartString {
void bar() {
System.out.println("Charlie Chaplin");
}
void use() {
bar();
}
}
| maxeler/eclipse | eclipse.jdt.ui/org.eclipse.jdt.ui.tests.refactoring/resources/IntroduceParameter/invalid/PartString.java | Java | epl-1.0 | 149 |
/**
* Copyright (c) 2010-2020 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.binding.lifx.internal.fields;
import java.nio.ByteBuffer;
import org.eclipse.jdt.annotation.NonNullByDefault;
/**
* A pseudo-uint64 field. Bytes will be stored directly in a long value, so
* unexpected values will likely be shown if exposed to users. Most bit-level
* operations should still work (addition, multiplication, shifting, etc).
*
* @author Tim Buckley
*/
@NonNullByDefault
public class UInt64Field extends Field<Long> {
@Override
public int defaultLength() {
return 8;
}
@Override
public Long value(ByteBuffer bytes) {
return bytes.getLong();
}
@Override
protected ByteBuffer bytesInternal(Long value) {
return ByteBuffer.allocate(8).putLong(value);
}
}
| openhab/openhab2 | bundles/org.openhab.binding.lifx/src/main/java/org/openhab/binding/lifx/internal/fields/UInt64Field.java | Java | epl-1.0 | 1,139 |
package com.oa.service.impl;
import com.oa.common.BaseServiceImpl;
import com.oa.service.IToolsTableService;
/**
* ยนยคยพรยฑรญservice
* @author Administrator
*
*/
public class ToolsTableServiceImpl extends BaseServiceImpl implements
IToolsTableService {
}
| Adlinde/MyAndroidDemo | EasyOA/src/com/oa/service/impl/ToolsTableServiceImpl.java | Java | epl-1.0 | 259 |
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | Copyright held by original author
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 2 of the License, or (at your
option) any later version.
OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with OpenFOAM; if not, write to the Free Software Foundation,
Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Class
regionCoupleFvPatch
Description
Region couple patch coupled two mesh regions for a solution in the same
linear system.
Author
Hrvoje Jasak, Wikki Ltd. All rights reserved
SourceFiles
regionCoupleFvPatch.C
\*---------------------------------------------------------------------------*/
#ifndef regionCoupleFvPatch_H
#define regionCoupleFvPatch_H
#include "coupledFvPatch.H"
#include "regionCoupleLduInterface.H"
#include "regionCouplePolyPatch.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
class fvMesh;
/*---------------------------------------------------------------------------*\
Class regionCoupleFvPatch Declaration
\*---------------------------------------------------------------------------*/
class regionCoupleFvPatch
:
public coupledFvPatch,
public regionCoupleLduInterface
{
// Private Data
//- Reference to polyPatch
const regionCouplePolyPatch& rcPolyPatch_;
//- Transfer buffer
mutable labelField transferBuffer_;
protected:
// Protected Member functions
//- Make patch weighting factors
virtual void makeWeights(scalarField&) const;
//- Make patch face - neighbour cell distances
virtual void makeDeltaCoeffs(scalarField&) const;
//- Return contents of transfer buffer
const labelField& transferBuffer() const
{
return transferBuffer_;
}
public:
//- Runtime type information
TypeName(regionCouplePolyPatch::typeName_());
// Constructors
//- Construct from components
regionCoupleFvPatch(const polyPatch& patch, const fvBoundaryMesh& bm)
:
coupledFvPatch(patch, bm),
rcPolyPatch_(refCast<const regionCouplePolyPatch>(patch)),
transferBuffer_()
{}
// Destructor
virtual ~regionCoupleFvPatch()
{}
// Member functions
//- Return true if coupled
virtual bool coupled() const;
//- Return shadow patch index
int shadowIndex() const
{
return rcPolyPatch_.shadowIndex();
}
//- Return shadow region
const fvMesh& shadowRegion() const;
//- Return shadow patch
const regionCoupleFvPatch& shadow() const;
//- Interpolate face field
template<class Type>
tmp<Field<Type> > interpolate(const Field<Type>& pf) const
{
return rcPolyPatch_.interpolate(pf);
}
template<class Type>
tmp<Field<Type> > interpolate(const tmp<Field<Type> >& tpf) const
{
return rcPolyPatch_.interpolate(tpf);
}
//- Return delta (P to N) vectors across coupled patch
virtual tmp<vectorField> delta() const;
// Interface transfer functions
//- Return the values of the given internal data adjacent to
// the interface as a field
virtual tmp<labelField> interfaceInternalField
(
const unallocLabelList& internalData
) const;
//- Initialise interface data transfer
virtual void initTransfer
(
const Pstream::commsTypes commsType,
const unallocLabelList& interfaceData
) const;
//- Transfer and return neighbour field
virtual tmp<labelField> transfer
(
const Pstream::commsTypes commsType,
const unallocLabelList& interfaceData
) const;
//- Initialise transfer of internal field adjacent to the interface
virtual void initInternalFieldTransfer
(
const Pstream::commsTypes commsType,
const unallocLabelList& iF
) const;
//- Return neighbour field
virtual tmp<labelField> internalFieldTransfer
(
const Pstream::commsTypes commsType,
const unallocLabelList& internalData
) const;
};
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace Foam
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#endif
// ************************************************************************* //
| CFDEMproject/OpenFOAM-1.6-ext | src/finiteVolume/fvMesh/fvPatches/constraint/regionCouple/regionCoupleFvPatch.H | C++ | gpl-2.0 | 5,542 |
// Copyright 2016 Dolphin Emulator Project
// Licensed under GPLv2+
// Refer to the license.txt file included.
#include "VideoBackends/Vulkan/ShaderCompiler.h"
#include "VideoBackends/Vulkan/VulkanContext.h"
#include <cstddef>
#include <cstdlib>
#include <fstream>
#include <memory>
#include <string>
// glslang includes
#include "GlslangToSpv.h"
#include "ShaderLang.h"
#include "disassemble.h"
#include "Common/FileUtil.h"
#include "Common/Logging/Log.h"
#include "Common/MsgHandler.h"
#include "Common/StringUtil.h"
#include "VideoCommon/VideoConfig.h"
namespace Vulkan
{
namespace ShaderCompiler
{
// Registers itself for cleanup via atexit
bool InitializeGlslang();
// Resource limits used when compiling shaders
static const TBuiltInResource* GetCompilerResourceLimits();
// Compile a shader to SPIR-V via glslang
static bool CompileShaderToSPV(SPIRVCodeVector* out_code, EShLanguage stage,
const char* stage_filename, const char* source_code,
size_t source_code_length, const char* header, size_t header_length);
// Copy GLSL source code to a SPIRVCodeVector, for use with VK_NV_glsl_shader.
static void CopyGLSLToSPVVector(SPIRVCodeVector* out_code, const char* stage_filename,
const char* source_code, size_t source_code_length,
const char* header, size_t header_length);
// Regarding the UBO bind points, we subtract one from the binding index because
// the OpenGL backend requires UBO #0 for non-block uniforms (at least on NV).
// This allows us to share the same shaders but use bind point #0 in the Vulkan
// backend. None of the Vulkan-specific shaders use UBOs, instead they use push
// constants, so when/if the GL backend moves to uniform blocks completely this
// subtraction can be removed.
static const char SHADER_HEADER[] = R"(
// Target GLSL 4.5.
#version 450 core
#define ATTRIBUTE_LOCATION(x) layout(location = x)
#define FRAGMENT_OUTPUT_LOCATION(x) layout(location = x)
#define FRAGMENT_OUTPUT_LOCATION_INDEXED(x, y) layout(location = x, index = y)
#define UBO_BINDING(packing, x) layout(packing, set = 0, binding = (x - 1))
#define SAMPLER_BINDING(x) layout(set = 1, binding = x)
#define SSBO_BINDING(x) layout(set = 2, binding = x)
#define TEXEL_BUFFER_BINDING(x) layout(set = 2, binding = x)
#define VARYING_LOCATION(x) layout(location = x)
#define FORCE_EARLY_Z layout(early_fragment_tests) in
// hlsl to glsl function translation
#define float2 vec2
#define float3 vec3
#define float4 vec4
#define uint2 uvec2
#define uint3 uvec3
#define uint4 uvec4
#define int2 ivec2
#define int3 ivec3
#define int4 ivec4
#define frac fract
#define lerp mix
// These were changed in Vulkan
#define gl_VertexID gl_VertexIndex
#define gl_InstanceID gl_InstanceIndex
)";
static const char COMPUTE_SHADER_HEADER[] = R"(
// Target GLSL 4.5.
#version 450 core
// All resources are packed into one descriptor set for compute.
#define UBO_BINDING(packing, x) layout(packing, set = 0, binding = (0 + x))
#define SAMPLER_BINDING(x) layout(set = 0, binding = (1 + x))
#define TEXEL_BUFFER_BINDING(x) layout(set = 0, binding = (5 + x))
#define IMAGE_BINDING(format, x) layout(format, set = 0, binding = (7 + x))
// hlsl to glsl function translation
#define float2 vec2
#define float3 vec3
#define float4 vec4
#define uint2 uvec2
#define uint3 uvec3
#define uint4 uvec4
#define int2 ivec2
#define int3 ivec3
#define int4 ivec4
#define frac fract
#define lerp mix
)";
bool CompileShaderToSPV(SPIRVCodeVector* out_code, EShLanguage stage, const char* stage_filename,
const char* source_code, size_t source_code_length, const char* header,
size_t header_length)
{
if (!InitializeGlslang())
return false;
std::unique_ptr<glslang::TShader> shader = std::make_unique<glslang::TShader>(stage);
std::unique_ptr<glslang::TProgram> program;
glslang::TShader::ForbidInclude includer;
EProfile profile = ECoreProfile;
EShMessages messages =
static_cast<EShMessages>(EShMsgDefault | EShMsgSpvRules | EShMsgVulkanRules);
int default_version = 450;
std::string full_source_code;
const char* pass_source_code = source_code;
int pass_source_code_length = static_cast<int>(source_code_length);
if (header_length > 0)
{
full_source_code.reserve(header_length + source_code_length);
full_source_code.append(header, header_length);
full_source_code.append(source_code, source_code_length);
pass_source_code = full_source_code.c_str();
pass_source_code_length = static_cast<int>(full_source_code.length());
}
shader->setStringsWithLengths(&pass_source_code, &pass_source_code_length, 1);
auto DumpBadShader = [&](const char* msg) {
static int counter = 0;
std::string filename = StringFromFormat(
"%sbad_%s_%04i.txt", File::GetUserPath(D_DUMP_IDX).c_str(), stage_filename, counter++);
std::ofstream stream;
File::OpenFStream(stream, filename, std::ios_base::out);
if (stream.good())
{
stream << full_source_code << std::endl;
stream << msg << std::endl;
stream << "Shader Info Log:" << std::endl;
stream << shader->getInfoLog() << std::endl;
stream << shader->getInfoDebugLog() << std::endl;
if (program)
{
stream << "Program Info Log:" << std::endl;
stream << program->getInfoLog() << std::endl;
stream << program->getInfoDebugLog() << std::endl;
}
}
PanicAlert("%s (written to %s)", msg, filename.c_str());
};
if (!shader->parse(GetCompilerResourceLimits(), default_version, profile, false, true, messages,
includer))
{
DumpBadShader("Failed to parse shader");
return false;
}
// Even though there's only a single shader, we still need to link it to generate SPV
program = std::make_unique<glslang::TProgram>();
program->addShader(shader.get());
if (!program->link(messages))
{
DumpBadShader("Failed to link program");
return false;
}
glslang::TIntermediate* intermediate = program->getIntermediate(stage);
if (!intermediate)
{
DumpBadShader("Failed to generate SPIR-V");
return false;
}
spv::SpvBuildLogger logger;
glslang::GlslangToSpv(*intermediate, *out_code, &logger);
// Write out messages
// Temporary: skip if it contains "Warning, version 450 is not yet complete; most version-specific
// features are present, but some are missing."
if (strlen(shader->getInfoLog()) > 108)
WARN_LOG(VIDEO, "Shader info log: %s", shader->getInfoLog());
if (strlen(shader->getInfoDebugLog()) > 0)
WARN_LOG(VIDEO, "Shader debug info log: %s", shader->getInfoDebugLog());
if (strlen(program->getInfoLog()) > 25)
WARN_LOG(VIDEO, "Program info log: %s", program->getInfoLog());
if (strlen(program->getInfoDebugLog()) > 0)
WARN_LOG(VIDEO, "Program debug info log: %s", program->getInfoDebugLog());
std::string spv_messages = logger.getAllMessages();
if (!spv_messages.empty())
WARN_LOG(VIDEO, "SPIR-V conversion messages: %s", spv_messages.c_str());
// Dump source code of shaders out to file if enabled.
if (g_ActiveConfig.iLog & CONF_SAVESHADERS)
{
static int counter = 0;
std::string filename = StringFromFormat("%s%s_%04i.txt", File::GetUserPath(D_DUMP_IDX).c_str(),
stage_filename, counter++);
std::ofstream stream;
File::OpenFStream(stream, filename, std::ios_base::out);
if (stream.good())
{
stream << full_source_code << std::endl;
stream << "Shader Info Log:" << std::endl;
stream << shader->getInfoLog() << std::endl;
stream << shader->getInfoDebugLog() << std::endl;
stream << "Program Info Log:" << std::endl;
stream << program->getInfoLog() << std::endl;
stream << program->getInfoDebugLog() << std::endl;
stream << "SPIR-V conversion messages: " << std::endl;
stream << spv_messages;
stream << "SPIR-V:" << std::endl;
spv::Disassemble(stream, *out_code);
}
}
return true;
}
void CopyGLSLToSPVVector(SPIRVCodeVector* out_code, const char* stage_filename,
const char* source_code, size_t source_code_length, const char* header,
size_t header_length)
{
std::string full_source_code;
if (header_length > 0)
{
full_source_code.reserve(header_length + source_code_length);
full_source_code.append(header, header_length);
full_source_code.append(source_code, source_code_length);
}
else
{
full_source_code.append(source_code, source_code_length);
}
if (g_ActiveConfig.iLog & CONF_SAVESHADERS)
{
static int counter = 0;
std::string filename = StringFromFormat("%s%s_%04i.txt", File::GetUserPath(D_DUMP_IDX).c_str(),
stage_filename, counter++);
std::ofstream stream;
File::OpenFStream(stream, filename, std::ios_base::out);
if (stream.good())
stream << full_source_code << std::endl;
}
size_t padding = full_source_code.size() % 4;
if (padding != 0)
full_source_code.append(4 - padding, '\n');
out_code->resize(full_source_code.size() / 4);
std::memcpy(out_code->data(), full_source_code.c_str(), full_source_code.size());
}
bool InitializeGlslang()
{
static bool glslang_initialized = false;
if (glslang_initialized)
return true;
if (!glslang::InitializeProcess())
{
PanicAlert("Failed to initialize glslang shader compiler");
return false;
}
std::atexit([]() { glslang::FinalizeProcess(); });
glslang_initialized = true;
return true;
}
const TBuiltInResource* GetCompilerResourceLimits()
{
static const TBuiltInResource limits = {/* .MaxLights = */ 32,
/* .MaxClipPlanes = */ 6,
/* .MaxTextureUnits = */ 32,
/* .MaxTextureCoords = */ 32,
/* .MaxVertexAttribs = */ 64,
/* .MaxVertexUniformComponents = */ 4096,
/* .MaxVaryingFloats = */ 64,
/* .MaxVertexTextureImageUnits = */ 32,
/* .MaxCombinedTextureImageUnits = */ 80,
/* .MaxTextureImageUnits = */ 32,
/* .MaxFragmentUniformComponents = */ 4096,
/* .MaxDrawBuffers = */ 32,
/* .MaxVertexUniformVectors = */ 128,
/* .MaxVaryingVectors = */ 8,
/* .MaxFragmentUniformVectors = */ 16,
/* .MaxVertexOutputVectors = */ 16,
/* .MaxFragmentInputVectors = */ 15,
/* .MinProgramTexelOffset = */ -8,
/* .MaxProgramTexelOffset = */ 7,
/* .MaxClipDistances = */ 8,
/* .MaxComputeWorkGroupCountX = */ 65535,
/* .MaxComputeWorkGroupCountY = */ 65535,
/* .MaxComputeWorkGroupCountZ = */ 65535,
/* .MaxComputeWorkGroupSizeX = */ 1024,
/* .MaxComputeWorkGroupSizeY = */ 1024,
/* .MaxComputeWorkGroupSizeZ = */ 64,
/* .MaxComputeUniformComponents = */ 1024,
/* .MaxComputeTextureImageUnits = */ 16,
/* .MaxComputeImageUniforms = */ 8,
/* .MaxComputeAtomicCounters = */ 8,
/* .MaxComputeAtomicCounterBuffers = */ 1,
/* .MaxVaryingComponents = */ 60,
/* .MaxVertexOutputComponents = */ 64,
/* .MaxGeometryInputComponents = */ 64,
/* .MaxGeometryOutputComponents = */ 128,
/* .MaxFragmentInputComponents = */ 128,
/* .MaxImageUnits = */ 8,
/* .MaxCombinedImageUnitsAndFragmentOutputs = */ 8,
/* .MaxCombinedShaderOutputResources = */ 8,
/* .MaxImageSamples = */ 0,
/* .MaxVertexImageUniforms = */ 0,
/* .MaxTessControlImageUniforms = */ 0,
/* .MaxTessEvaluationImageUniforms = */ 0,
/* .MaxGeometryImageUniforms = */ 0,
/* .MaxFragmentImageUniforms = */ 8,
/* .MaxCombinedImageUniforms = */ 8,
/* .MaxGeometryTextureImageUnits = */ 16,
/* .MaxGeometryOutputVertices = */ 256,
/* .MaxGeometryTotalOutputComponents = */ 1024,
/* .MaxGeometryUniformComponents = */ 1024,
/* .MaxGeometryVaryingComponents = */ 64,
/* .MaxTessControlInputComponents = */ 128,
/* .MaxTessControlOutputComponents = */ 128,
/* .MaxTessControlTextureImageUnits = */ 16,
/* .MaxTessControlUniformComponents = */ 1024,
/* .MaxTessControlTotalOutputComponents = */ 4096,
/* .MaxTessEvaluationInputComponents = */ 128,
/* .MaxTessEvaluationOutputComponents = */ 128,
/* .MaxTessEvaluationTextureImageUnits = */ 16,
/* .MaxTessEvaluationUniformComponents = */ 1024,
/* .MaxTessPatchComponents = */ 120,
/* .MaxPatchVertices = */ 32,
/* .MaxTessGenLevel = */ 64,
/* .MaxViewports = */ 16,
/* .MaxVertexAtomicCounters = */ 0,
/* .MaxTessControlAtomicCounters = */ 0,
/* .MaxTessEvaluationAtomicCounters = */ 0,
/* .MaxGeometryAtomicCounters = */ 0,
/* .MaxFragmentAtomicCounters = */ 8,
/* .MaxCombinedAtomicCounters = */ 8,
/* .MaxAtomicCounterBindings = */ 1,
/* .MaxVertexAtomicCounterBuffers = */ 0,
/* .MaxTessControlAtomicCounterBuffers = */ 0,
/* .MaxTessEvaluationAtomicCounterBuffers = */ 0,
/* .MaxGeometryAtomicCounterBuffers = */ 0,
/* .MaxFragmentAtomicCounterBuffers = */ 1,
/* .MaxCombinedAtomicCounterBuffers = */ 1,
/* .MaxAtomicCounterBufferSize = */ 16384,
/* .MaxTransformFeedbackBuffers = */ 4,
/* .MaxTransformFeedbackInterleavedComponents = */ 64,
/* .MaxCullDistances = */ 8,
/* .MaxCombinedClipAndCullDistances = */ 8,
/* .MaxSamples = */ 4,
/* .limits = */ {
/* .nonInductiveForLoops = */ 1,
/* .whileLoops = */ 1,
/* .doWhileLoops = */ 1,
/* .generalUniformIndexing = */ 1,
/* .generalAttributeMatrixVectorIndexing = */ 1,
/* .generalVaryingIndexing = */ 1,
/* .generalSamplerIndexing = */ 1,
/* .generalVariableIndexing = */ 1,
/* .generalConstantMatrixVectorIndexing = */ 1,
}};
return &limits;
}
bool CompileVertexShader(SPIRVCodeVector* out_code, const char* source_code,
size_t source_code_length)
{
if (g_vulkan_context->SupportsNVGLSLExtension())
{
CopyGLSLToSPVVector(out_code, "vs", source_code, source_code_length, SHADER_HEADER,
sizeof(SHADER_HEADER) - 1);
return true;
}
return CompileShaderToSPV(out_code, EShLangVertex, "vs", source_code, source_code_length,
SHADER_HEADER, sizeof(SHADER_HEADER) - 1);
}
bool CompileGeometryShader(SPIRVCodeVector* out_code, const char* source_code,
size_t source_code_length)
{
if (g_vulkan_context->SupportsNVGLSLExtension())
{
CopyGLSLToSPVVector(out_code, "gs", source_code, source_code_length, SHADER_HEADER,
sizeof(SHADER_HEADER) - 1);
return true;
}
return CompileShaderToSPV(out_code, EShLangGeometry, "gs", source_code, source_code_length,
SHADER_HEADER, sizeof(SHADER_HEADER) - 1);
}
bool CompileFragmentShader(SPIRVCodeVector* out_code, const char* source_code,
size_t source_code_length)
{
if (g_vulkan_context->SupportsNVGLSLExtension())
{
CopyGLSLToSPVVector(out_code, "ps", source_code, source_code_length, SHADER_HEADER,
sizeof(SHADER_HEADER) - 1);
return true;
}
return CompileShaderToSPV(out_code, EShLangFragment, "ps", source_code, source_code_length,
SHADER_HEADER, sizeof(SHADER_HEADER) - 1);
}
bool CompileComputeShader(SPIRVCodeVector* out_code, const char* source_code,
size_t source_code_length)
{
if (g_vulkan_context->SupportsNVGLSLExtension())
{
CopyGLSLToSPVVector(out_code, "cs", source_code, source_code_length, COMPUTE_SHADER_HEADER,
sizeof(COMPUTE_SHADER_HEADER) - 1);
return true;
}
return CompileShaderToSPV(out_code, EShLangCompute, "cs", source_code, source_code_length,
COMPUTE_SHADER_HEADER, sizeof(COMPUTE_SHADER_HEADER) - 1);
}
} // namespace ShaderCompiler
} // namespace Vulkan
| linkmauve/dolphin | Source/Core/VideoBackends/Vulkan/ShaderCompiler.cpp | C++ | gpl-2.0 | 19,541 |
#include "disk.h"
#include <sstream>
#include <string>
#include "log.h"
std::string chrn_to_string(unsigned char* chrn) {
std::ostringstream oss;
oss << static_cast<int>(chrn[0]) << "-"
<< static_cast<int>(chrn[1]) << "-"
<< static_cast<int>(chrn[2]) << "-"
<< static_cast<int>(chrn[3]);
return oss.str();
}
void t_sector::setSizes(unsigned int size, unsigned int total_size) {
size_ = size;
total_size_ = total_size;
weak_read_version_ = 0;
weak_versions_ = 1;
if (size_ > 0 && size_ <= total_size_) weak_versions_ = total_size_ / size_;
LOG_DEBUG("weak_versions_ = " << weak_versions_ << " for " << chrn_to_string(CHRN));
}
| ColinPitrat/caprice32 | src/disk.cpp | C++ | gpl-2.0 | 661 |
๏ปฟusing System;
using System.Collections.Generic;
using System.Text;
using datatool;
using System.Drawing;
namespace Maptool
{
public class Map
{
private List<Entity> entities;
public Bitmap Terrain;
public Bitmap Heightmap;
public int Width;
public int Height;
public List<Entity> Entities
{
get { return entities; }
}
public Map()
{
this.entities = new List<Entity>();
this.Terrain = new Bitmap(200, 200);
this.Heightmap = new Bitmap(200, 200);
this.Width = 200;
this.Height = 200;
}
/**
* Saves a map
**/
public bool Save(string filename)
{
string o = "";
foreach (Entity ent in entities) {
if (ent is ZoneEntity) {
o += Tools.Zone.saveConfig(ent) + "\n";
} else if (ent is LightEntity) {
o += Tools.Light.saveConfig(ent) + "\n";
} else if (ent is ObjectEntity) {
o += Tools.Object.saveConfig(ent) + "\n";
}
}
System.IO.File.WriteAllText(filename, o);
string basename = System.IO.Path.GetDirectoryName(filename);
this.Terrain.Save(basename + "\\terrain.png", System.Drawing.Imaging.ImageFormat.Png);
this.Heightmap.Save(basename + "\\heightmap.png", System.Drawing.Imaging.ImageFormat.Png);
return true;
}
/**
* Load
**/
public bool Load(string filename)
{
ConfuseReader rdr = new ConfuseReader();
string input = System.IO.File.ReadAllText(filename);
ConfuseSection parsed = rdr.Parse(input);
this.Width = parsed.get_int("width", 200);
this.Height = parsed.get_int("height", 200);
this.entities = new List<Entity>();
foreach (ConfuseSection sect in parsed.subsections) {
Entity ent = null;
if (sect.name == "zone") {
ent = Tools.Zone.loadConfig(sect);
} else if (sect.name == "light") {
ent = Tools.Light.loadConfig(sect);
} else if (sect.name == "object") {
ent = Tools.Object.loadConfig(sect);
}
if (ent == null) continue;
if (ent.Type == null) continue;
entities.Add(ent);
}
string basename = System.IO.Path.GetDirectoryName(filename);
// Load terrain
if (System.IO.File.Exists(basename + "\\terrain.png")) {
this.Terrain = new Bitmap(basename + "\\terrain.png");
} else {
this.Terrain = new Bitmap(this.Width, this.Height);
}
// Load heightmap
if (System.IO.File.Exists(basename + "\\heightmap.png")) {
this.Heightmap = new Bitmap(basename + "\\heightmap.png");
} else {
this.Heightmap = new Bitmap(this.Width, this.Height);
}
return true;
}
}
}
| enjgine/chaotic-rage | maptool/Map.cs | C# | gpl-2.0 | 3,356 |
// 2003-05-01 Petur Runolfsson <peturr02@ru.is>
// Copyright (C) 2001, 2002, 2003 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 2, or (at your option)
// any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING. If not, write to the Free
// Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307,
// USA.
// As a special exception, you may use this file as part of a free software
// library without restriction. Specifically, if other files instantiate
// templates or use macros or inline functions from this file, or you compile
// this file and link it with other files to produce an executable, this
// file does not by itself cause the resulting executable to be covered by
// the GNU General Public License. This exception does not however
// invalidate any other reasons why the executable file might be covered by
// the GNU General Public License.
#include <sstream>
#include <iostream>
// libstdc++/5268
void test04()
{
std::wstringbuf b1;
std::wcout.rdbuf( &b1 );
std::wcout << L"hello\n";
std::wcout.rdbuf(NULL);
}
int main()
{
test04();
return 0;
}
| unofficial-opensource-apple/gcc_40 | libstdc++-v3/testsuite/27_io/objects/wchar_t/5268.cc | C++ | gpl-2.0 | 1,659 |
export function isOffline( state ) {
return ( state.application.connectionState === 'OFFLINE' )
}
export function isOnline( state ) {
return ( state.application.connectionState === 'ONLINE' )
}
| Kimsangcheon/wp-calypso | client/state/application/selectors.js | JavaScript | gpl-2.0 | 199 |
<?php
/**
* Braintree Class Instance template
*
* @package Braintree
* @subpackage Utility
* @copyright 2014 Braintree, a division of PayPal, Inc.
*/
/**
* abstract instance template for various objects
*
* @package Braintree
* @subpackage Utility
* @copyright 2014 Braintree, a division of PayPal, Inc.
* @abstract
*/
abstract class Braintree_Instance
{
/**
*
* @param array $aAttribs
*/
public function __construct($attributes)
{
if (!empty($attributes)) {
$this->_initializeFromArray($attributes);
}
}
/**
* returns private/nonexistent instance properties
* @access public
* @param var $name property name
* @return mixed contents of instance properties
*/
public function __get($name)
{
if (array_key_exists($name, $this->_attributes)) {
return $this->_attributes[$name];
} else {
trigger_error('Undefined property on ' . get_class($this) . ': ' . $name, E_USER_NOTICE);
return null;
}
}
/**
* used by isset() and empty()
* @access public
* @param string $name property name
* @return boolean
*/
public function __isset($name)
{
return array_key_exists($name, $this->_attributes);
}
/**
* create a printable representation of the object as:
* ClassName[property=value, property=value]
* @return var
*/
public function __toString()
{
$objOutput = Braintree_Util::implodeAssociativeArray($this->_attributes);
return get_class($this) .'['.$objOutput.']';
}
/**
* initializes instance properties from the keys/values of an array
* @ignore
* @access protected
* @param <type> $aAttribs array of properties to set - single level
* @return none
*/
private function _initializeFromArray($attributes)
{
$this->_attributes = $attributes;
}
}
| fitmoo/drupal_store_ftm | sites/all/modules/custom/commerce_braintree/braintree_php/lib/Braintree/Instance.php | PHP | gpl-2.0 | 1,980 |
/** @file
* Shared Folders: Host service entry points.
*/
/*
* Copyright (C) 2006-2010 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*/
#include <VBox/shflsvc.h>
#include "shfl.h"
#include "mappings.h"
#include "shflhandle.h"
#include "vbsf.h"
#include <iprt/alloc.h>
#include <iprt/string.h>
#include <iprt/assert.h>
#include <VBox/vmm/ssm.h>
#include <VBox/vmm/pdmifs.h>
#define SHFL_SSM_VERSION_FOLDERNAME_UTF16 2
#define SHFL_SSM_VERSION 3
/* Shared Folders Host Service.
*
* Shared Folders map a host file system to guest logical filesystem.
* A mapping represents 'host name'<->'guest name' translation and a root
* identifier to be used to access this mapping.
* Examples: "C:\WINNT"<->"F:", "C:\WINNT\System32"<->"/mnt/host/system32".
*
* Therefore, host name and guest name are strings interpreted
* only by host service and guest client respectively. Host name is
* passed to guest only for informational purpose. Guest may for example
* display the string or construct volume label out of the string.
*
* Root identifiers are unique for whole guest life,
* that is until next guest reset/fresh start.
* 32 bit value incremented for each new mapping is used.
*
* Mapping strings are taken from VM XML configuration on VM startup.
* The service DLL takes mappings during initialization. There is
* also API for changing mappings at runtime.
*
* Current mappings and root identifiers are saved when VM is saved.
*
* Guest may use any of these mappings. Full path information
* about an object on a mapping consists of the root identifier and
* a full path of object.
*
* Guest IFS connects to the service and calls SHFL_FN_QUERY_MAP
* function which returns current mappings. For guest convenience,
* removed mappings also returned with REMOVED flag and new mappings
* are marked with NEW flag.
*
* To access host file system guest just forwards file system calls
* to the service, and specifies full paths or handles for objects.
*
*
*/
PVBOXHGCMSVCHELPERS g_pHelpers;
static PPDMLED pStatusLed = NULL;
static DECLCALLBACK(int) svcUnload (void *)
{
int rc = VINF_SUCCESS;
Log(("svcUnload\n"));
return rc;
}
static DECLCALLBACK(int) svcConnect (void *, uint32_t u32ClientID, void *pvClient)
{
int rc = VINF_SUCCESS;
NOREF(u32ClientID);
NOREF(pvClient);
Log(("SharedFolders host service: connected, u32ClientID = %u\n", u32ClientID));
return rc;
}
static DECLCALLBACK(int) svcDisconnect (void *, uint32_t u32ClientID, void *pvClient)
{
int rc = VINF_SUCCESS;
SHFLCLIENTDATA *pClient = (SHFLCLIENTDATA *)pvClient;
Log(("SharedFolders host service: disconnected, u32ClientID = %u\n", u32ClientID));
vbsfDisconnect(pClient);
return rc;
}
/** @note We only save as much state as required to access the shared folder again after restore.
* All I/O requests pending at the time of saving will never be completed or result in errors.
* (file handles no longer valid etc)
* This works as designed at the moment. A full state save would be difficult and not always possible
* as the contents of a shared folder might change in between save and restore.
*/
static DECLCALLBACK(int) svcSaveState(void *, uint32_t u32ClientID, void *pvClient, PSSMHANDLE pSSM)
{
#ifndef UNITTEST /* Read this as not yet tested */
SHFLCLIENTDATA *pClient = (SHFLCLIENTDATA *)pvClient;
Log(("SharedFolders host service: saving state, u32ClientID = %u\n", u32ClientID));
int rc = SSMR3PutU32(pSSM, SHFL_SSM_VERSION);
AssertRCReturn(rc, rc);
rc = SSMR3PutU32(pSSM, SHFL_MAX_MAPPINGS);
AssertRCReturn(rc, rc);
/* Save client structure length & contents */
rc = SSMR3PutU32(pSSM, sizeof(*pClient));
AssertRCReturn(rc, rc);
rc = SSMR3PutMem(pSSM, pClient, sizeof(*pClient));
AssertRCReturn(rc, rc);
/* Save all the active mappings. */
for (int i=0;i<SHFL_MAX_MAPPINGS;i++)
{
/* Mapping are saved in the order of increasing root handle values. */
MAPPING *pFolderMapping = vbsfMappingGetByRoot(i);
rc = SSMR3PutU32(pSSM, pFolderMapping? pFolderMapping->cMappings: 0);
AssertRCReturn(rc, rc);
rc = SSMR3PutBool(pSSM, pFolderMapping? pFolderMapping->fValid: false);
AssertRCReturn(rc, rc);
if (pFolderMapping && pFolderMapping->fValid)
{
uint32_t len;
len = strlen(pFolderMapping->pszFolderName);
rc = SSMR3PutU32(pSSM, len);
AssertRCReturn(rc, rc);
rc = SSMR3PutStrZ(pSSM, pFolderMapping->pszFolderName);
AssertRCReturn(rc, rc);
len = ShflStringSizeOfBuffer(pFolderMapping->pMapName);
rc = SSMR3PutU32(pSSM, len);
AssertRCReturn(rc, rc);
rc = SSMR3PutMem(pSSM, pFolderMapping->pMapName, len);
AssertRCReturn(rc, rc);
rc = SSMR3PutBool(pSSM, pFolderMapping->fHostCaseSensitive);
AssertRCReturn(rc, rc);
rc = SSMR3PutBool(pSSM, pFolderMapping->fGuestCaseSensitive);
AssertRCReturn(rc, rc);
}
}
#endif
return VINF_SUCCESS;
}
static DECLCALLBACK(int) svcLoadState(void *, uint32_t u32ClientID, void *pvClient, PSSMHANDLE pSSM)
{
#ifndef UNITTEST /* Read this as not yet tested */
uint32_t nrMappings;
SHFLCLIENTDATA *pClient = (SHFLCLIENTDATA *)pvClient;
uint32_t len, version;
Log(("SharedFolders host service: loading state, u32ClientID = %u\n", u32ClientID));
int rc = SSMR3GetU32(pSSM, &version);
AssertRCReturn(rc, rc);
if ( version > SHFL_SSM_VERSION
|| version < SHFL_SSM_VERSION_FOLDERNAME_UTF16)
return VERR_SSM_UNSUPPORTED_DATA_UNIT_VERSION;
rc = SSMR3GetU32(pSSM, &nrMappings);
AssertRCReturn(rc, rc);
if (nrMappings != SHFL_MAX_MAPPINGS)
return VERR_SSM_DATA_UNIT_FORMAT_CHANGED;
/* Restore the client data (flags + path delimiter at the moment) */
rc = SSMR3GetU32(pSSM, &len);
AssertRCReturn(rc, rc);
if (len != sizeof(*pClient))
return VERR_SSM_DATA_UNIT_FORMAT_CHANGED;
rc = SSMR3GetMem(pSSM, pClient, sizeof(*pClient));
AssertRCReturn(rc, rc);
/* We don't actually (fully) restore the state; we simply check if the current state is as we it expect it to be. */
for (int i=0;i<SHFL_MAX_MAPPINGS;i++)
{
/* Load the saved mapping description and try to find it in the mappings. */
MAPPING mapping;
memset (&mapping, 0, sizeof (mapping));
/* restore the folder mapping counter. */
rc = SSMR3GetU32(pSSM, &mapping.cMappings);
AssertRCReturn(rc, rc);
rc = SSMR3GetBool(pSSM, &mapping.fValid);
AssertRCReturn(rc, rc);
if (mapping.fValid)
{
uint32_t cbFolderName;
char *pszFolderName;
uint32_t cbMapName;
PSHFLSTRING pMapName;
/* Load the host path name. */
rc = SSMR3GetU32(pSSM, &cbFolderName);
AssertRCReturn(rc, rc);
if (version == SHFL_SSM_VERSION_FOLDERNAME_UTF16)
{
PSHFLSTRING pFolderName = (PSHFLSTRING)RTMemAlloc(cbFolderName);
AssertReturn(pFolderName != NULL, VERR_NO_MEMORY);
rc = SSMR3GetMem(pSSM, pFolderName, cbFolderName);
AssertRCReturn(rc, rc);
rc = RTUtf16ToUtf8(pFolderName->String.ucs2, &pszFolderName);
RTMemFree(pFolderName);
AssertRCReturn(rc, rc);
}
else
{
pszFolderName = (char*)RTStrAlloc(cbFolderName + 1);
AssertReturn(pszFolderName, VERR_NO_MEMORY);
rc = SSMR3GetStrZ(pSSM, pszFolderName, cbFolderName + 1);
AssertRCReturn(rc, rc);
mapping.pszFolderName = pszFolderName;
}
/* Load the map name. */
rc = SSMR3GetU32(pSSM, &cbMapName);
AssertRCReturn(rc, rc);
pMapName = (PSHFLSTRING)RTMemAlloc(cbMapName);
AssertReturn(pMapName != NULL, VERR_NO_MEMORY);
rc = SSMR3GetMem(pSSM, pMapName, cbMapName);
AssertRCReturn(rc, rc);
rc = SSMR3GetBool(pSSM, &mapping.fHostCaseSensitive);
AssertRCReturn(rc, rc);
rc = SSMR3GetBool(pSSM, &mapping.fGuestCaseSensitive);
AssertRCReturn(rc, rc);
mapping.pszFolderName = pszFolderName;
mapping.pMapName = pMapName;
/* 'i' is the root handle of the saved mapping. */
rc = vbsfMappingLoaded (&mapping, i);
RTMemFree(pMapName);
RTStrFree(pszFolderName);
AssertRCReturn(rc, rc);
}
}
Log(("SharedFolders host service: successfully loaded state\n"));
#endif
return VINF_SUCCESS;
}
static DECLCALLBACK(void) svcCall (void *, VBOXHGCMCALLHANDLE callHandle, uint32_t u32ClientID, void *pvClient, uint32_t u32Function, uint32_t cParms, VBOXHGCMSVCPARM paParms[])
{
int rc = VINF_SUCCESS;
Log(("SharedFolders host service: svcCall: u32ClientID = %u, fn = %u, cParms = %u, pparms = %p\n", u32ClientID, u32Function, cParms, paParms));
SHFLCLIENTDATA *pClient = (SHFLCLIENTDATA *)pvClient;
bool fAsynchronousProcessing = false;
#ifdef DEBUG
uint32_t i;
for (i = 0; i < cParms; i++)
{
/** @todo parameters other than 32 bit */
Log((" pparms[%d]: type %u, value %u\n", i, paParms[i].type, paParms[i].u.uint32));
}
#endif
switch (u32Function)
{
case SHFL_FN_QUERY_MAPPINGS:
{
Log(("SharedFolders host service: svcCall: SHFL_FN_QUERY_MAPPINGS\n"));
/* Verify parameter count and types. */
if (cParms != SHFL_CPARMS_QUERY_MAPPINGS)
{
rc = VERR_INVALID_PARAMETER;
}
else if ( paParms[0].type != VBOX_HGCM_SVC_PARM_32BIT /* flags */
|| paParms[1].type != VBOX_HGCM_SVC_PARM_32BIT /* numberOfMappings */
|| paParms[2].type != VBOX_HGCM_SVC_PARM_PTR /* mappings */
)
{
rc = VERR_INVALID_PARAMETER;
}
else
{
/* Fetch parameters. */
uint32_t fu32Flags = paParms[0].u.uint32;
uint32_t cMappings = paParms[1].u.uint32;
SHFLMAPPING *pMappings = (SHFLMAPPING *)paParms[2].u.pointer.addr;
uint32_t cbMappings = paParms[2].u.pointer.size;
/* Verify parameters values. */
if ( (fu32Flags & ~SHFL_MF_MASK) != 0
|| cbMappings / sizeof (SHFLMAPPING) != cMappings
)
{
rc = VERR_INVALID_PARAMETER;
}
else
{
/* Execute the function. */
if (fu32Flags & SHFL_MF_UTF8)
pClient->fu32Flags |= SHFL_CF_UTF8;
if (fu32Flags & SHFL_MF_AUTOMOUNT)
pClient->fu32Flags |= SHFL_MF_AUTOMOUNT;
rc = vbsfMappingsQuery(pClient, pMappings, &cMappings);
if (RT_SUCCESS(rc))
{
/* Report that there are more mappings to get if
* handed in buffer is too small. */
if (paParms[1].u.uint32 < cMappings)
rc = VINF_BUFFER_OVERFLOW;
/* Update parameters. */
paParms[1].u.uint32 = cMappings;
}
}
}
} break;
case SHFL_FN_QUERY_MAP_NAME:
{
Log(("SharedFolders host service: svcCall: SHFL_FN_QUERY_MAP_NAME\n"));
/* Verify parameter count and types. */
if (cParms != SHFL_CPARMS_QUERY_MAP_NAME)
{
rc = VERR_INVALID_PARAMETER;
}
else if ( paParms[0].type != VBOX_HGCM_SVC_PARM_32BIT /* Root. */
|| paParms[1].type != VBOX_HGCM_SVC_PARM_PTR /* Name. */
)
{
rc = VERR_INVALID_PARAMETER;
}
else
{
/* Fetch parameters. */
SHFLROOT root = (SHFLROOT)paParms[0].u.uint32;
SHFLSTRING *pString = (SHFLSTRING *)paParms[1].u.pointer.addr;
/* Verify parameters values. */
if (!ShflStringIsValid(pString, paParms[1].u.pointer.size))
{
rc = VERR_INVALID_PARAMETER;
}
else
{
/* Execute the function. */
rc = vbsfMappingsQueryName(pClient, root, pString);
if (RT_SUCCESS(rc))
{
/* Update parameters.*/
; /* None. */
}
}
}
} break;
case SHFL_FN_CREATE:
{
Log(("SharedFolders host service: svcCall: SHFL_FN_CREATE\n"));
/* Verify parameter count and types. */
if (cParms != SHFL_CPARMS_CREATE)
{
rc = VERR_INVALID_PARAMETER;
}
else if ( paParms[0].type != VBOX_HGCM_SVC_PARM_32BIT /* root */
|| paParms[1].type != VBOX_HGCM_SVC_PARM_PTR /* path */
|| paParms[2].type != VBOX_HGCM_SVC_PARM_PTR /* parms */
)
{
Log(("SharedFolders host service: Invalid parameters types\n"));
rc = VERR_INVALID_PARAMETER;
}
else
{
/* Fetch parameters. */
SHFLROOT root = (SHFLROOT)paParms[0].u.uint32;
SHFLSTRING *pPath = (SHFLSTRING *)paParms[1].u.pointer.addr;
uint32_t cbPath = paParms[1].u.pointer.size;
SHFLCREATEPARMS *pParms = (SHFLCREATEPARMS *)paParms[2].u.pointer.addr;
uint32_t cbParms = paParms[2].u.pointer.size;
/* Verify parameters values. */
if ( !ShflStringIsValid(pPath, cbPath)
|| (cbParms != sizeof (SHFLCREATEPARMS))
)
{
AssertMsgFailed (("Invalid parameters cbPath or cbParms (%x, %x - expected >=%x, %x)\n",
cbPath, cbParms, sizeof(SHFLSTRING), sizeof (SHFLCREATEPARMS)));
rc = VERR_INVALID_PARAMETER;
}
else
{
/* Execute the function. */
rc = vbsfCreate (pClient, root, pPath, cbPath, pParms);
if (RT_SUCCESS(rc))
{
/* Update parameters.*/
; /* none */
}
}
}
break;
}
case SHFL_FN_CLOSE:
{
Log(("SharedFolders host service: svcCall: SHFL_FN_CLOSE\n"));
/* Verify parameter count and types. */
if (cParms != SHFL_CPARMS_CLOSE)
{
rc = VERR_INVALID_PARAMETER;
}
else if ( paParms[0].type != VBOX_HGCM_SVC_PARM_32BIT /* root */
|| paParms[1].type != VBOX_HGCM_SVC_PARM_64BIT /* handle */
)
{
rc = VERR_INVALID_PARAMETER;
}
else
{
/* Fetch parameters. */
SHFLROOT root = (SHFLROOT)paParms[0].u.uint32;
SHFLHANDLE Handle = paParms[1].u.uint64;
/* Verify parameters values. */
if (Handle == SHFL_HANDLE_ROOT)
{
rc = VERR_INVALID_PARAMETER;
}
else
if (Handle == SHFL_HANDLE_NIL)
{
AssertMsgFailed(("Invalid handle!\n"));
rc = VERR_INVALID_HANDLE;
}
else
{
/* Execute the function. */
rc = vbsfClose (pClient, root, Handle);
if (RT_SUCCESS(rc))
{
/* Update parameters.*/
; /* none */
}
}
}
break;
}
/** Read object content. */
case SHFL_FN_READ:
Log(("SharedFolders host service: svcCall: SHFL_FN_READ\n"));
/* Verify parameter count and types. */
if (cParms != SHFL_CPARMS_READ)
{
rc = VERR_INVALID_PARAMETER;
}
else
if ( paParms[0].type != VBOX_HGCM_SVC_PARM_32BIT /* root */
|| paParms[1].type != VBOX_HGCM_SVC_PARM_64BIT /* handle */
|| paParms[2].type != VBOX_HGCM_SVC_PARM_64BIT /* offset */
|| paParms[3].type != VBOX_HGCM_SVC_PARM_32BIT /* count */
|| paParms[4].type != VBOX_HGCM_SVC_PARM_PTR /* buffer */
)
{
rc = VERR_INVALID_PARAMETER;
}
else
{
/* Fetch parameters. */
SHFLROOT root = (SHFLROOT)paParms[0].u.uint32;
SHFLHANDLE Handle = paParms[1].u.uint64;
uint64_t offset = paParms[2].u.uint64;
uint32_t count = paParms[3].u.uint32;
uint8_t *pBuffer = (uint8_t *)paParms[4].u.pointer.addr;
/* Verify parameters values. */
if ( Handle == SHFL_HANDLE_ROOT
|| count > paParms[4].u.pointer.size
)
{
rc = VERR_INVALID_PARAMETER;
}
else
if (Handle == SHFL_HANDLE_NIL)
{
AssertMsgFailed(("Invalid handle!\n"));
rc = VERR_INVALID_HANDLE;
}
else
{
/* Execute the function. */
if (pStatusLed)
{
Assert(pStatusLed->u32Magic == PDMLED_MAGIC);
pStatusLed->Asserted.s.fReading = pStatusLed->Actual.s.fReading = 1;
}
rc = vbsfRead (pClient, root, Handle, offset, &count, pBuffer);
if (pStatusLed)
pStatusLed->Actual.s.fReading = 0;
if (RT_SUCCESS(rc))
{
/* Update parameters.*/
paParms[3].u.uint32 = count;
}
else
{
paParms[3].u.uint32 = 0; /* nothing read */
}
}
}
break;
/** Write new object content. */
case SHFL_FN_WRITE:
Log(("SharedFolders host service: svcCall: SHFL_FN_WRITE\n"));
/* Verify parameter count and types. */
if (cParms != SHFL_CPARMS_WRITE)
{
rc = VERR_INVALID_PARAMETER;
}
else
if ( paParms[0].type != VBOX_HGCM_SVC_PARM_32BIT /* root */
|| paParms[1].type != VBOX_HGCM_SVC_PARM_64BIT /* handle */
|| paParms[2].type != VBOX_HGCM_SVC_PARM_64BIT /* offset */
|| paParms[3].type != VBOX_HGCM_SVC_PARM_32BIT /* count */
|| paParms[4].type != VBOX_HGCM_SVC_PARM_PTR /* buffer */
)
{
rc = VERR_INVALID_PARAMETER;
}
else
{
/* Fetch parameters. */
SHFLROOT root = (SHFLROOT)paParms[0].u.uint32;
SHFLHANDLE Handle = paParms[1].u.uint64;
uint64_t offset = paParms[2].u.uint64;
uint32_t count = paParms[3].u.uint32;
uint8_t *pBuffer = (uint8_t *)paParms[4].u.pointer.addr;
/* Verify parameters values. */
if ( Handle == SHFL_HANDLE_ROOT
|| count > paParms[4].u.pointer.size
)
{
rc = VERR_INVALID_PARAMETER;
}
else
if (Handle == SHFL_HANDLE_NIL)
{
AssertMsgFailed(("Invalid handle!\n"));
rc = VERR_INVALID_HANDLE;
}
else
{
/* Execute the function. */
if (pStatusLed)
{
Assert(pStatusLed->u32Magic == PDMLED_MAGIC);
pStatusLed->Asserted.s.fWriting = pStatusLed->Actual.s.fWriting = 1;
}
rc = vbsfWrite (pClient, root, Handle, offset, &count, pBuffer);
if (pStatusLed)
pStatusLed->Actual.s.fWriting = 0;
if (RT_SUCCESS(rc))
{
/* Update parameters.*/
paParms[3].u.uint32 = count;
}
else
{
paParms[3].u.uint32 = 0; /* nothing read */
}
}
}
break;
/** Lock/unlock a range in the object. */
case SHFL_FN_LOCK:
Log(("SharedFolders host service: svcCall: SHFL_FN_LOCK\n"));
/* Verify parameter count and types. */
if (cParms != SHFL_CPARMS_LOCK)
{
rc = VERR_INVALID_PARAMETER;
}
else
if ( paParms[0].type != VBOX_HGCM_SVC_PARM_32BIT /* root */
|| paParms[1].type != VBOX_HGCM_SVC_PARM_64BIT /* handle */
|| paParms[2].type != VBOX_HGCM_SVC_PARM_64BIT /* offset */
|| paParms[3].type != VBOX_HGCM_SVC_PARM_64BIT /* length */
|| paParms[4].type != VBOX_HGCM_SVC_PARM_32BIT /* flags */
)
{
rc = VERR_INVALID_PARAMETER;
}
else
{
/* Fetch parameters. */
SHFLROOT root = (SHFLROOT)paParms[0].u.uint32;
SHFLHANDLE Handle = paParms[1].u.uint64;
uint64_t offset = paParms[2].u.uint64;
uint64_t length = paParms[3].u.uint64;
uint32_t flags = paParms[4].u.uint32;
/* Verify parameters values. */
if (Handle == SHFL_HANDLE_ROOT)
{
rc = VERR_INVALID_PARAMETER;
}
else
if (Handle == SHFL_HANDLE_NIL)
{
AssertMsgFailed(("Invalid handle!\n"));
rc = VERR_INVALID_HANDLE;
}
else if (flags & SHFL_LOCK_WAIT)
{
/* @todo This should be properly implemented by the shared folders service.
* The service thread must never block. If an operation requires
* blocking, it must be processed by another thread and when it is
* completed, the another thread must call
*
* g_pHelpers->pfnCallComplete (callHandle, rc);
*
* The operation is async.
* fAsynchronousProcessing = true;
*/
/* Here the operation must be posted to another thread. At the moment it is not implemented.
* Until it is implemented, try to perform the operation without waiting.
*/
flags &= ~SHFL_LOCK_WAIT;
/* Execute the function. */
if ((flags & SHFL_LOCK_MODE_MASK) == SHFL_LOCK_CANCEL)
rc = vbsfUnlock(pClient, root, Handle, offset, length, flags);
else
rc = vbsfLock(pClient, root, Handle, offset, length, flags);
if (RT_SUCCESS(rc))
{
/* Update parameters.*/
/* none */
}
}
else
{
/* Execute the function. */
if ((flags & SHFL_LOCK_MODE_MASK) == SHFL_LOCK_CANCEL)
rc = vbsfUnlock(pClient, root, Handle, offset, length, flags);
else
rc = vbsfLock(pClient, root, Handle, offset, length, flags);
if (RT_SUCCESS(rc))
{
/* Update parameters.*/
/* none */
}
}
}
break;
/** List object content. */
case SHFL_FN_LIST:
{
Log(("SharedFolders host service: svcCall: SHFL_FN_LIST\n"));
/* Verify parameter count and types. */
if (cParms != SHFL_CPARMS_LIST)
{
rc = VERR_INVALID_PARAMETER;
}
else
if ( paParms[0].type != VBOX_HGCM_SVC_PARM_32BIT /* root */
|| paParms[1].type != VBOX_HGCM_SVC_PARM_64BIT /* handle */
|| paParms[2].type != VBOX_HGCM_SVC_PARM_32BIT /* flags */
|| paParms[3].type != VBOX_HGCM_SVC_PARM_32BIT /* cb */
|| paParms[4].type != VBOX_HGCM_SVC_PARM_PTR /* pPath */
|| paParms[5].type != VBOX_HGCM_SVC_PARM_PTR /* buffer */
|| paParms[6].type != VBOX_HGCM_SVC_PARM_32BIT /* resumePoint */
|| paParms[7].type != VBOX_HGCM_SVC_PARM_32BIT /* cFiles (out) */
)
{
rc = VERR_INVALID_PARAMETER;
}
else
{
/* Fetch parameters. */
SHFLROOT root = (SHFLROOT)paParms[0].u.uint32;
SHFLHANDLE Handle = paParms[1].u.uint64;
uint32_t flags = paParms[2].u.uint32;
uint32_t length = paParms[3].u.uint32;
SHFLSTRING *pPath = (paParms[4].u.pointer.size == 0) ? 0 : (SHFLSTRING *)paParms[4].u.pointer.addr;
uint8_t *pBuffer = (uint8_t *)paParms[5].u.pointer.addr;
uint32_t resumePoint = paParms[6].u.uint32;
uint32_t cFiles = 0;
/* Verify parameters values. */
if ( (length < sizeof (SHFLDIRINFO))
|| length > paParms[5].u.pointer.size
|| !ShflStringIsValidOrNull(pPath, paParms[4].u.pointer.size)
)
{
rc = VERR_INVALID_PARAMETER;
}
else
{
if (pStatusLed)
{
Assert(pStatusLed->u32Magic == PDMLED_MAGIC);
pStatusLed->Asserted.s.fReading = pStatusLed->Actual.s.fReading = 1;
}
/* Execute the function. */
rc = vbsfDirList (pClient, root, Handle, pPath, flags, &length, pBuffer, &resumePoint, &cFiles);
if (pStatusLed)
pStatusLed->Actual.s.fReading = 0;
if (rc == VERR_NO_MORE_FILES && cFiles != 0)
rc = VINF_SUCCESS; /* Successfully return these files. */
if (RT_SUCCESS(rc))
{
/* Update parameters.*/
paParms[3].u.uint32 = length;
paParms[6].u.uint32 = resumePoint;
paParms[7].u.uint32 = cFiles;
}
else
{
paParms[3].u.uint32 = 0; /* nothing read */
paParms[6].u.uint32 = 0;
paParms[7].u.uint32 = cFiles;
}
}
}
break;
}
/* Read symlink destination */
case SHFL_FN_READLINK:
{
Log(("SharedFolders host service: svcCall: SHFL_FN_READLINK\n"));
/* Verify parameter count and types. */
if (cParms != SHFL_CPARMS_READLINK)
{
rc = VERR_INVALID_PARAMETER;
}
else
if ( paParms[0].type != VBOX_HGCM_SVC_PARM_32BIT /* root */
|| paParms[1].type != VBOX_HGCM_SVC_PARM_PTR /* path */
|| paParms[2].type != VBOX_HGCM_SVC_PARM_PTR /* buffer */
)
{
rc = VERR_INVALID_PARAMETER;
}
else
{
/* Fetch parameters. */
SHFLROOT root = (SHFLROOT)paParms[0].u.uint32;
SHFLSTRING *pPath = (SHFLSTRING *)paParms[1].u.pointer.addr;
uint32_t cbPath = paParms[1].u.pointer.size;
uint8_t *pBuffer = (uint8_t *)paParms[2].u.pointer.addr;
uint32_t cbBuffer = paParms[2].u.pointer.size;
/* Verify parameters values. */
if (!ShflStringIsValidOrNull(pPath, paParms[1].u.pointer.size))
{
rc = VERR_INVALID_PARAMETER;
}
else
{
/* Execute the function. */
rc = vbsfReadLink (pClient, root, pPath, cbPath, pBuffer, cbBuffer);
if (RT_SUCCESS(rc))
{
/* Update parameters.*/
; /* none */
}
}
}
break;
}
/* Legacy interface */
case SHFL_FN_MAP_FOLDER_OLD:
{
Log(("SharedFolders host service: svcCall: SHFL_FN_MAP_FOLDER_OLD\n"));
/* Verify parameter count and types. */
if (cParms != SHFL_CPARMS_MAP_FOLDER_OLD)
{
rc = VERR_INVALID_PARAMETER;
}
else if ( paParms[0].type != VBOX_HGCM_SVC_PARM_PTR /* path */
|| paParms[1].type != VBOX_HGCM_SVC_PARM_32BIT /* root */
|| paParms[2].type != VBOX_HGCM_SVC_PARM_32BIT /* delimiter */
)
{
rc = VERR_INVALID_PARAMETER;
}
else
{
/* Fetch parameters. */
PSHFLSTRING pszMapName = (PSHFLSTRING)paParms[0].u.pointer.addr;
SHFLROOT root = (SHFLROOT)paParms[1].u.uint32;
RTUTF16 delimiter = (RTUTF16)paParms[2].u.uint32;
/* Verify parameters values. */
if (!ShflStringIsValid(pszMapName, paParms[0].u.pointer.size))
{
rc = VERR_INVALID_PARAMETER;
}
else
{
/* Execute the function. */
rc = vbsfMapFolder (pClient, pszMapName, delimiter, false, &root);
if (RT_SUCCESS(rc))
{
/* Update parameters.*/
paParms[1].u.uint32 = root;
}
}
}
break;
}
case SHFL_FN_MAP_FOLDER:
{
Log(("SharedFolders host service: svcCall: SHFL_FN_MAP_FOLDER\n"));
if (BIT_FLAG(pClient->fu32Flags, SHFL_CF_UTF8))
Log(("SharedFolders host service: request to map folder '%s'\n",
((PSHFLSTRING)paParms[0].u.pointer.addr)->String.utf8));
else
Log(("SharedFolders host service: request to map folder '%ls'\n",
((PSHFLSTRING)paParms[0].u.pointer.addr)->String.ucs2));
/* Verify parameter count and types. */
if (cParms != SHFL_CPARMS_MAP_FOLDER)
{
rc = VERR_INVALID_PARAMETER;
}
else if ( paParms[0].type != VBOX_HGCM_SVC_PARM_PTR /* path */
|| paParms[1].type != VBOX_HGCM_SVC_PARM_32BIT /* root */
|| paParms[2].type != VBOX_HGCM_SVC_PARM_32BIT /* delimiter */
|| paParms[3].type != VBOX_HGCM_SVC_PARM_32BIT /* fCaseSensitive */
)
{
rc = VERR_INVALID_PARAMETER;
}
else
{
/* Fetch parameters. */
PSHFLSTRING pszMapName = (PSHFLSTRING)paParms[0].u.pointer.addr;
SHFLROOT root = (SHFLROOT)paParms[1].u.uint32;
RTUTF16 delimiter = (RTUTF16)paParms[2].u.uint32;
bool fCaseSensitive = !!paParms[3].u.uint32;
/* Verify parameters values. */
if (!ShflStringIsValid(pszMapName, paParms[0].u.pointer.size))
{
rc = VERR_INVALID_PARAMETER;
}
else
{
/* Execute the function. */
rc = vbsfMapFolder (pClient, pszMapName, delimiter, fCaseSensitive, &root);
if (RT_SUCCESS(rc))
{
/* Update parameters.*/
paParms[1].u.uint32 = root;
}
}
}
Log(("SharedFolders host service: map operation result %Rrc\n", rc));
if (RT_SUCCESS(rc))
Log(("SharedFolders host service: mapped to handle %d\n", paParms[1].u.uint32));
break;
}
case SHFL_FN_UNMAP_FOLDER:
{
Log(("SharedFolders host service: svcCall: SHFL_FN_UNMAP_FOLDER\n"));
Log(("SharedFolders host service: request to unmap folder handle %u\n",
paParms[0].u.uint32));
/* Verify parameter count and types. */
if (cParms != SHFL_CPARMS_UNMAP_FOLDER)
{
rc = VERR_INVALID_PARAMETER;
}
else if ( paParms[0].type != VBOX_HGCM_SVC_PARM_32BIT /* root */
)
{
rc = VERR_INVALID_PARAMETER;
}
else
{
/* Fetch parameters. */
SHFLROOT root = (SHFLROOT)paParms[0].u.uint32;
/* Execute the function. */
rc = vbsfUnmapFolder (pClient, root);
if (RT_SUCCESS(rc))
{
/* Update parameters.*/
/* nothing */
}
}
Log(("SharedFolders host service: unmap operation result %Rrc\n", rc));
break;
}
/** Query/set object information. */
case SHFL_FN_INFORMATION:
{
Log(("SharedFolders host service: svcCall: SHFL_FN_INFORMATION\n"));
/* Verify parameter count and types. */
if (cParms != SHFL_CPARMS_INFORMATION)
{
rc = VERR_INVALID_PARAMETER;
}
else
if ( paParms[0].type != VBOX_HGCM_SVC_PARM_32BIT /* root */
|| paParms[1].type != VBOX_HGCM_SVC_PARM_64BIT /* handle */
|| paParms[2].type != VBOX_HGCM_SVC_PARM_32BIT /* flags */
|| paParms[3].type != VBOX_HGCM_SVC_PARM_32BIT /* cb */
|| paParms[4].type != VBOX_HGCM_SVC_PARM_PTR /* buffer */
)
{
rc = VERR_INVALID_PARAMETER;
}
else
{
/* Fetch parameters. */
SHFLROOT root = (SHFLROOT)paParms[0].u.uint32;
SHFLHANDLE Handle = paParms[1].u.uint64;
uint32_t flags = paParms[2].u.uint32;
uint32_t length = paParms[3].u.uint32;
uint8_t *pBuffer = (uint8_t *)paParms[4].u.pointer.addr;
/* Verify parameters values. */
if (length > paParms[4].u.pointer.size)
{
rc = VERR_INVALID_PARAMETER;
}
else
{
/* Execute the function. */
if (flags & SHFL_INFO_SET)
rc = vbsfSetFSInfo (pClient, root, Handle, flags, &length, pBuffer);
else /* SHFL_INFO_GET */
rc = vbsfQueryFSInfo (pClient, root, Handle, flags, &length, pBuffer);
if (RT_SUCCESS(rc))
{
/* Update parameters.*/
paParms[3].u.uint32 = length;
}
else
{
paParms[3].u.uint32 = 0; /* nothing read */
}
}
}
break;
}
/** Remove or rename object */
case SHFL_FN_REMOVE:
{
Log(("SharedFolders host service: svcCall: SHFL_FN_REMOVE\n"));
/* Verify parameter count and types. */
if (cParms != SHFL_CPARMS_REMOVE)
{
rc = VERR_INVALID_PARAMETER;
}
else if ( paParms[0].type != VBOX_HGCM_SVC_PARM_32BIT /* root */
|| paParms[1].type != VBOX_HGCM_SVC_PARM_PTR /* path */
|| paParms[2].type != VBOX_HGCM_SVC_PARM_32BIT /* flags */
)
{
rc = VERR_INVALID_PARAMETER;
}
else
{
/* Fetch parameters. */
SHFLROOT root = (SHFLROOT)paParms[0].u.uint32;
SHFLSTRING *pPath = (SHFLSTRING *)paParms[1].u.pointer.addr;
uint32_t cbPath = paParms[1].u.pointer.size;
uint32_t flags = paParms[2].u.uint32;
/* Verify parameters values. */
if (!ShflStringIsValid(pPath, cbPath))
{
rc = VERR_INVALID_PARAMETER;
}
else
{
/* Execute the function. */
rc = vbsfRemove (pClient, root, pPath, cbPath, flags);
if (RT_SUCCESS(rc))
{
/* Update parameters.*/
; /* none */
}
}
}
break;
}
case SHFL_FN_RENAME:
{
Log(("SharedFolders host service: svcCall: SHFL_FN_RENAME\n"));
/* Verify parameter count and types. */
if (cParms != SHFL_CPARMS_RENAME)
{
rc = VERR_INVALID_PARAMETER;
}
else if ( paParms[0].type != VBOX_HGCM_SVC_PARM_32BIT /* root */
|| paParms[1].type != VBOX_HGCM_SVC_PARM_PTR /* src */
|| paParms[2].type != VBOX_HGCM_SVC_PARM_PTR /* dest */
|| paParms[3].type != VBOX_HGCM_SVC_PARM_32BIT /* flags */
)
{
rc = VERR_INVALID_PARAMETER;
}
else
{
/* Fetch parameters. */
SHFLROOT root = (SHFLROOT)paParms[0].u.uint32;
SHFLSTRING *pSrc = (SHFLSTRING *)paParms[1].u.pointer.addr;
SHFLSTRING *pDest = (SHFLSTRING *)paParms[2].u.pointer.addr;
uint32_t flags = paParms[3].u.uint32;
/* Verify parameters values. */
if ( !ShflStringIsValid(pSrc, paParms[1].u.pointer.size)
|| !ShflStringIsValid(pDest, paParms[2].u.pointer.size)
)
{
rc = VERR_INVALID_PARAMETER;
}
else
{
/* Execute the function. */
rc = vbsfRename (pClient, root, pSrc, pDest, flags);
if (RT_SUCCESS(rc))
{
/* Update parameters.*/
; /* none */
}
}
}
break;
}
case SHFL_FN_FLUSH:
{
Log(("SharedFolders host service: svcCall: SHFL_FN_FLUSH\n"));
/* Verify parameter count and types. */
if (cParms != SHFL_CPARMS_FLUSH)
{
rc = VERR_INVALID_PARAMETER;
}
else
if ( paParms[0].type != VBOX_HGCM_SVC_PARM_32BIT /* root */
|| paParms[1].type != VBOX_HGCM_SVC_PARM_64BIT /* handle */
)
{
rc = VERR_INVALID_PARAMETER;
}
else
{
/* Fetch parameters. */
SHFLROOT root = (SHFLROOT)paParms[0].u.uint32;
SHFLHANDLE Handle = paParms[1].u.uint64;
/* Verify parameters values. */
if (Handle == SHFL_HANDLE_ROOT)
{
rc = VERR_INVALID_PARAMETER;
}
else
if (Handle == SHFL_HANDLE_NIL)
{
AssertMsgFailed(("Invalid handle!\n"));
rc = VERR_INVALID_HANDLE;
}
else
{
/* Execute the function. */
rc = vbsfFlush (pClient, root, Handle);
if (RT_SUCCESS(rc))
{
/* Nothing to do */
}
}
}
} break;
case SHFL_FN_SET_UTF8:
{
pClient->fu32Flags |= SHFL_CF_UTF8;
rc = VINF_SUCCESS;
break;
}
case SHFL_FN_SYMLINK:
{
Log(("SharedFolders host service: svnCall: SHFL_FN_SYMLINK\n"));
/* Verify parameter count and types. */
if (cParms != SHFL_CPARMS_SYMLINK)
{
rc = VERR_INVALID_PARAMETER;
}
else if ( paParms[0].type != VBOX_HGCM_SVC_PARM_32BIT /* root */
|| paParms[1].type != VBOX_HGCM_SVC_PARM_PTR /* newPath */
|| paParms[2].type != VBOX_HGCM_SVC_PARM_PTR /* oldPath */
|| paParms[3].type != VBOX_HGCM_SVC_PARM_PTR /* info */
)
{
rc = VERR_INVALID_PARAMETER;
}
else
{
/* Fetch parameters. */
SHFLROOT root = (SHFLROOT)paParms[0].u.uint32;
SHFLSTRING *pNewPath = (SHFLSTRING *)paParms[1].u.pointer.addr;
SHFLSTRING *pOldPath = (SHFLSTRING *)paParms[2].u.pointer.addr;
SHFLFSOBJINFO *pInfo = (SHFLFSOBJINFO *)paParms[3].u.pointer.addr;
uint32_t cbInfo = paParms[3].u.pointer.size;
/* Verify parameters values. */
if ( !ShflStringIsValid(pNewPath, paParms[1].u.pointer.size)
|| !ShflStringIsValid(pOldPath, paParms[2].u.pointer.size)
|| (cbInfo != sizeof(SHFLFSOBJINFO))
)
{
rc = VERR_INVALID_PARAMETER;
}
else
{
/* Execute the function. */
rc = vbsfSymlink (pClient, root, pNewPath, pOldPath, pInfo);
if (RT_SUCCESS(rc))
{
/* Update parameters.*/
; /* none */
}
}
}
}
break;
case SHFL_FN_SET_SYMLINKS:
{
pClient->fu32Flags |= SHFL_CF_SYMLINKS;
rc = VINF_SUCCESS;
break;
}
default:
{
rc = VERR_NOT_IMPLEMENTED;
break;
}
}
LogFlow(("SharedFolders host service: svcCall: rc=%Rrc\n", rc));
if ( !fAsynchronousProcessing
|| RT_FAILURE (rc))
{
/* Complete the operation if it was unsuccessful or
* it was processed synchronously.
*/
g_pHelpers->pfnCallComplete (callHandle, rc);
}
LogFlow(("\n")); /* Add a new line to differentiate between calls more easily. */
}
/*
* We differentiate between a function handler for the guest (svcCall) and one
* for the host. The guest is not allowed to add or remove mappings for obvious
* security reasons.
*/
static DECLCALLBACK(int) svcHostCall (void *, uint32_t u32Function, uint32_t cParms, VBOXHGCMSVCPARM paParms[])
{
int rc = VINF_SUCCESS;
Log(("svcHostCall: fn = %d, cParms = %d, pparms = %d\n", u32Function, cParms, paParms));
#ifdef DEBUG
uint32_t i;
for (i = 0; i < cParms; i++)
{
/** @todo parameters other than 32 bit */
Log((" pparms[%d]: type %d value %d\n", i, paParms[i].type, paParms[i].u.uint32));
}
#endif
switch (u32Function)
{
case SHFL_FN_ADD_MAPPING:
{
Log(("SharedFolders host service: svcCall: SHFL_FN_ADD_MAPPING\n"));
LogRel(("SharedFolders host service: adding host mapping\n"));
/* Verify parameter count and types. */
if ( (cParms != SHFL_CPARMS_ADD_MAPPING)
)
{
rc = VERR_INVALID_PARAMETER;
}
else if ( paParms[0].type != VBOX_HGCM_SVC_PARM_PTR /* host folder name */
|| paParms[1].type != VBOX_HGCM_SVC_PARM_PTR /* guest map name */
|| paParms[2].type != VBOX_HGCM_SVC_PARM_32BIT /* fFlags */
)
{
rc = VERR_INVALID_PARAMETER;
}
else
{
/* Fetch parameters. */
SHFLSTRING *pFolderName = (SHFLSTRING *)paParms[0].u.pointer.addr;
SHFLSTRING *pMapName = (SHFLSTRING *)paParms[1].u.pointer.addr;
uint32_t fFlags = paParms[2].u.uint32;
/* Verify parameters values. */
if ( !ShflStringIsValid(pFolderName, paParms[0].u.pointer.size)
|| !ShflStringIsValid(pMapName, paParms[1].u.pointer.size)
)
{
rc = VERR_INVALID_PARAMETER;
}
else
{
LogRel((" Host path '%ls', map name '%ls', %s, automount=%s, create_symlinks=%s\n",
((SHFLSTRING *)paParms[0].u.pointer.addr)->String.ucs2,
((SHFLSTRING *)paParms[1].u.pointer.addr)->String.ucs2,
RT_BOOL(fFlags & SHFL_ADD_MAPPING_F_WRITABLE) ? "writable" : "read-only",
RT_BOOL(fFlags & SHFL_ADD_MAPPING_F_AUTOMOUNT) ? "true" : "false",
RT_BOOL(fFlags & SHFL_ADD_MAPPING_F_CREATE_SYMLINKS) ? "true" : "false"));
/* Execute the function. */
rc = vbsfMappingsAdd(pFolderName, pMapName,
RT_BOOL(fFlags & SHFL_ADD_MAPPING_F_WRITABLE),
RT_BOOL(fFlags & SHFL_ADD_MAPPING_F_AUTOMOUNT),
RT_BOOL(fFlags & SHFL_ADD_MAPPING_F_CREATE_SYMLINKS));
if (RT_SUCCESS(rc))
{
/* Update parameters.*/
; /* none */
}
}
}
if (RT_FAILURE(rc))
LogRel(("SharedFolders host service: adding host mapping failed with rc=%Rrc\n", rc));
break;
}
case SHFL_FN_REMOVE_MAPPING:
{
Log(("SharedFolders host service: svcCall: SHFL_FN_REMOVE_MAPPING\n"));
LogRel(("SharedFolders host service: removing host mapping '%ls'\n",
((SHFLSTRING *)paParms[0].u.pointer.addr)->String.ucs2));
/* Verify parameter count and types. */
if (cParms != SHFL_CPARMS_REMOVE_MAPPING)
{
rc = VERR_INVALID_PARAMETER;
}
else if ( paParms[0].type != VBOX_HGCM_SVC_PARM_PTR /* folder name */
)
{
rc = VERR_INVALID_PARAMETER;
}
else
{
/* Fetch parameters. */
SHFLSTRING *pString = (SHFLSTRING *)paParms[0].u.pointer.addr;
/* Verify parameters values. */
if (!ShflStringIsValid(pString, paParms[0].u.pointer.size))
{
rc = VERR_INVALID_PARAMETER;
}
else
{
/* Execute the function. */
rc = vbsfMappingsRemove (pString);
if (RT_SUCCESS(rc))
{
/* Update parameters.*/
; /* none */
}
}
}
if (RT_FAILURE(rc))
LogRel(("SharedFolders host service: removing host mapping failed with rc=%Rrc\n", rc));
break;
}
case SHFL_FN_SET_STATUS_LED:
{
Log(("SharedFolders host service: svcCall: SHFL_FN_SET_STATUS_LED\n"));
/* Verify parameter count and types. */
if (cParms != SHFL_CPARMS_SET_STATUS_LED)
{
rc = VERR_INVALID_PARAMETER;
}
else if ( paParms[0].type != VBOX_HGCM_SVC_PARM_PTR /* folder name */
)
{
rc = VERR_INVALID_PARAMETER;
}
else
{
/* Fetch parameters. */
PPDMLED pLed = (PPDMLED)paParms[0].u.pointer.addr;
uint32_t cbLed = paParms[0].u.pointer.size;
/* Verify parameters values. */
if ( (cbLed != sizeof (PDMLED))
)
{
rc = VERR_INVALID_PARAMETER;
}
else
{
/* Execute the function. */
pStatusLed = pLed;
rc = VINF_SUCCESS;
}
}
break;
}
default:
rc = VERR_NOT_IMPLEMENTED;
break;
}
LogFlow(("SharedFolders host service: svcHostCall ended with rc=%Rrc\n", rc));
return rc;
}
extern "C" DECLCALLBACK(DECLEXPORT(int)) VBoxHGCMSvcLoad (VBOXHGCMSVCFNTABLE *ptable)
{
int rc = VINF_SUCCESS;
Log(("SharedFolders host service: VBoxHGCMSvcLoad: ptable = %p\n", ptable));
if (!VALID_PTR(ptable))
{
LogRelFunc(("SharedFolders host service: bad value of ptable (%p)\n", ptable));
rc = VERR_INVALID_PARAMETER;
}
else
{
Log(("SharedFolders host service: VBoxHGCMSvcLoad: ptable->cbSize = %u, ptable->u32Version = 0x%08X\n",
ptable->cbSize, ptable->u32Version));
if ( ptable->cbSize != sizeof (VBOXHGCMSVCFNTABLE)
|| ptable->u32Version != VBOX_HGCM_SVC_VERSION)
{
LogRelFunc(("SharedFolders host service: version mismatch while loading: ptable->cbSize = %u (should be %u), ptable->u32Version = 0x%08X (should be 0x%08X)\n",
ptable->cbSize, sizeof (VBOXHGCMSVCFNTABLE), ptable->u32Version, VBOX_HGCM_SVC_VERSION));
rc = VERR_VERSION_MISMATCH;
}
else
{
g_pHelpers = ptable->pHelpers;
ptable->cbClient = sizeof (SHFLCLIENTDATA);
ptable->pfnUnload = svcUnload;
ptable->pfnConnect = svcConnect;
ptable->pfnDisconnect = svcDisconnect;
ptable->pfnCall = svcCall;
ptable->pfnHostCall = svcHostCall;
ptable->pfnSaveState = svcSaveState;
ptable->pfnLoadState = svcLoadState;
ptable->pvService = NULL;
}
/* Init handle table */
rc = vbsfInitHandleTable();
AssertRC(rc);
vbsfMappingInit();
}
return rc;
}
| pombredanne/VirtualBox-OSE | src/VBox/HostServices/SharedFolders/service.cpp | C++ | gpl-2.0 | 53,249 |
/*
* Copyright (c) 2007, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.graal.jtt.bytecode;
import com.oracle.graal.jtt.*;
import org.junit.*;
/*
*/
public class BC_newarray extends JTTTest {
@SuppressWarnings("all")
public static int test(int a) {
if (new boolean[3] == null) {
return -1;
}
if (new char[3] == null) {
return -1;
}
if (new float[3] == null) {
return -1;
}
if (new double[3] == null) {
return -1;
}
if (new byte[3] == null) {
return -1;
}
if (new short[3] == null) {
return -1;
}
if (new int[3] == null) {
return -1;
}
if (new long[3] == null) {
return -1;
}
return a;
}
@Test
public void run0() throws Throwable {
runTest("test", 0);
}
@Test
public void run1() throws Throwable {
runTest("test", 1);
}
}
| arodchen/MaxSim | graal/graal/com.oracle.graal.jtt/src/com/oracle/graal/jtt/bytecode/BC_newarray.java | Java | gpl-2.0 | 2,018 |
<?php
/**
* The template used for displaying page content in page.php
*
* @package Suits
* @since Suits 1.0
*/
?>
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<header class="entry-header">
<?php if ( has_post_thumbnail() && ! post_password_required() ) : ?>
<div class="entry-thumbnail">
<?php the_post_thumbnail(); ?>
</div>
<?php endif; ?>
<h1 class="entry-title"><?php the_title(); ?></h1>
</header><!-- .entry-header -->
<div class="entry-content">
<?php the_content(); ?>
<?php wp_link_pages( array( 'before' => '<div class="page-links"><span class="page-links-title">' . __( 'Pages:', 'suits' ) . '</span>', 'after' => '</div>', 'link_before' => '<span>', 'link_after' => '</span>' ) ); ?>
</div><!-- .entry-content -->
<?php if ( current_user_can( 'edit_post', get_the_ID() ) ) : ?>
<footer class="entry-meta">
<?php edit_post_link( __( 'Edit', 'suits' ), '<span class="edit-link">', '</span>' ); ?>
</footer><!-- .entry-meta -->
<?php endif; ?>
</article><!-- #post -->
| KylePreston/Soft-Hills-Website | wp-content/themes/suits/content-page.php | PHP | gpl-2.0 | 1,031 |
<?php /**
* @file
* Contains \Drupal\view_mode_selector\Plugin\Field\FieldWidget\ViewModeSelectorIcons.
*/
namespace Drupal\view_mode_selector\Plugin\Field\FieldWidget;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Renderer;
/**
* @FieldWidget(
* id = "view_mode_selector_icons",
* label = @Translation("Icons"),
* field_types = {"view_mode_selector"}
* )
*/
class ViewModeSelectorIcons extends ViewModeSelectorRadios {
/**
* {@inheritdoc}
*/
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$element = parent::formElement($items, $delta, $element, $form, $form_state);
/** @var \Drupal\field\Entity\FieldConfig $field */
$field = $items->getFieldDefinition();
$entity_type = $field->getTargetEntityTypeId();
$bundle = $field->getTargetBundle();
$settings = $this->getFieldSettings();
$element['#attached'] = [
'library' => [
'view_mode_selector/widget_styles',
],
];
foreach (array_keys($this->viewModes) as $view_mode) {
$output = [];
if(isset($settings['view_modes'][$view_mode]['icon']) && $settings['view_modes'][$view_mode]['icon']) {
$icon = \Drupal::entityManager()
->getStorage('file')
->load($settings['view_modes'][$view_mode]['icon'][0]);
if (!$icon) {
continue;
}
$render = [
'#theme' => 'image',
'#uri' => $icon->getFileUri(),
'#alt' => t('Sample original image'),
'#title' => $this->viewModes[$view_mode],
];
$output[] = \Drupal::service('renderer')->render($render);
} elseif (\Drupal::moduleHandler()->moduleExists('ds') && isset($ds_view_modes[$view_mode])) {
// When Display Suite is installed we can show a nice preview.
// @todo integrate with DS regions
// $layout = $ds_view_modes[$view_mode]['layout'];
//
// // Create a new empty entity for the preview.
// $entity_properties = ['type' => $entity_bundle, 'id' => FALSE];
// $entity = entity_create($entity_type, $entity_properties);
// $entity_view = entity_view($entity_type, [$entity], $view_mode);
//
// // Render one field containing a placeholder <div> in every region.
// foreach ($layout['settings']['regions'] as $region_settings) {
// foreach ($region_settings as $field) {
// $entity_view[$entity_type][0][$field] = [
// '#type' => 'html_tag',
// '#tag' => 'div',
// '#value' => '',
// '#attributes' => ['class' => 'placeholder'],
// '#field_name' => $field,
// ];
//
// continue;
// }
// }
//
// // Disable contextual links.
// $entity_view[$entity_type][0]['#contextual_links'] = FALSE;
//
// // Render the preview.
// $output[] = drupal_render($entity_view);
} else {
$element['value'][$view_mode]['#attributes']['class'][] = 'no-preview';
}
if (!$settings['view_modes'][$view_mode]['hide_title']) {
$output[] = '<small>' . $this->viewModes[$view_mode] . '</small>';
}
// Use the generated markup as our label value.
$element['value']['#options'][$view_mode] = implode($output, '');
}
return $element;
}
}
| sanjuacom/sanjua | modules/view_mode_selector/src/Plugin/Field/FieldWidget/ViewModeSelectorIcons.php | PHP | gpl-2.0 | 3,447 |
<?php
/**
* Handles the IPv4/IPv6 to long transformation for text plain
*/
declare(strict_types=1);
namespace PhpMyAdmin\Plugins\Transformations\Input;
use PhpMyAdmin\FieldMetadata;
use PhpMyAdmin\Plugins\IOTransformationsPlugin;
use PhpMyAdmin\Utils\FormatConverter;
use function __;
use function htmlspecialchars;
/**
* Handles the IPv4/IPv6 to long transformation for text plain
*/
class Text_Plain_Iptolong extends IOTransformationsPlugin
{
/**
* Gets the transformation description of the plugin
*/
public static function getInfo(): string
{
return __('Converts an Internet network address in (IPv4/IPv6) format into a long integer.');
}
/**
* Does the actual work of each specific transformations plugin.
*
* @param string $buffer text to be transformed. a binary string containing
* an IP address, as returned from MySQL's INET6_ATON
* function
* @param array $options transformation options
* @param FieldMetadata $meta meta information
*
* @return string IP address
*/
public function applyTransformation($buffer, array $options = [], ?FieldMetadata $meta = null)
{
return (string) FormatConverter::ipToLong($buffer);
}
/**
* Returns the html for input field to override default textarea.
* Note: Return empty string if default textarea is required.
*
* @param array $column column details
* @param int $row_id row number
* @param string $column_name_appendix the name attribute
* @param array $options transformation options
* @param string $value Current field value
* @param string $text_dir text direction
* @param int $tabindex tab index
* @param int $tabindex_for_value offset for the values tabindex
* @param int $idindex id index
*
* @return string the html for input field
*/
public function getInputHtml(
array $column,
$row_id,
$column_name_appendix,
array $options,
$value,
$text_dir,
$tabindex,
$tabindex_for_value,
$idindex
) {
$html = '';
$val = '';
if (! empty($value)) {
$val = FormatConverter::longToIp($value);
if ($value !== $val) {
$html = '<input type="hidden" name="fields_prev' . $column_name_appendix
. '" value="' . htmlspecialchars($val) . '"/>';
}
}
return $html . '<input type="text" name="fields' . $column_name_appendix . '"'
. ' value="' . htmlspecialchars($val) . '"'
. ' size="40"'
. ' dir="' . $text_dir . '"'
. ' class="transform_IPToLong"'
. ' id="field_' . $idindex . '_3"'
. ' tabindex="' . ($tabindex + $tabindex_for_value) . '" />';
}
/* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */
/**
* Gets the transformation name of the plugin
*/
public static function getName(): string
{
return 'IPv4/IPv6 To Long';
}
/**
* Gets the plugin`s MIME type
*/
public static function getMIMEType(): string
{
return 'Text';
}
/**
* Gets the plugin`s MIME subtype
*/
public static function getMIMESubtype(): string
{
return 'Plain';
}
}
| phpmyadmin/composer | libraries/classes/Plugins/Transformations/Input/Text_Plain_Iptolong.php | PHP | gpl-2.0 | 3,556 |
<?php
/**
* Part of joomla330 project.
*
* @copyright Copyright (C) 2016 LYRASOFT. All rights reserved.
* @license GNU General Public License version 2 or later.
*/
namespace Windwalker\System\Installer;
/**
* Class WindwalkerInstaller
*
* @since 1.0
*/
class WindwalkerInstaller
{
/**
* The bin file content.
*
* @var string
*/
static protected $binFile = <<<BIN
#!/usr/bin/env php
<?php
include_once dirname(__DIR__) . '/libraries/windwalker/bin/windwalker.php';
BIN;
/**
* createBinFile
*
* @param string $root
*
* @return void
*/
public static function createBinFile($root)
{
file_put_contents($root . '/bin/windwalker', static::$binFile);
}
/**
* copyConfigFile
*
* @param string $root
*
* @return void
*/
public static function copyConfigFile($root)
{
$configPath = $root . '/libraries/windwalker/config.dist.json';
if (! is_file($configPath))
{
copy($configPath, $root . '/libraries/windwalker/config.json');
}
}
/**
* createBundleDir
*
* @param string $root
*
* @return bool
*/
public static function createBundleDir($root)
{
$bundlesDir = $root . '/libraries/windwalker-bundles';
if (! is_dir($bundlesDir))
{
mkdir($bundlesDir);
file_put_contents($bundlesDir . '/index.html', '<!DOCTYPE html><title></title>');
return true;
}
return false;
}
/**
* install
*
* @param string $root
*
* @return void
*/
public static function install($root)
{
static::createBinFile($root);
static::copyConfigFile($root);
static::createBundleDir($root);
}
}
| FaySie/005_design_joomla | libraries/windwalker/src/System/Installer/WindwalkerInstaller.php | PHP | gpl-2.0 | 1,593 |
<?php
include_once('../../config/symbini.php');
include_once($serverRoot.'/config/dbconnection.php');
header("Content-Type: text/html; charset=".$charset);
header("Cache-Control: no-cache, must-revalidate");
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
$con = MySQLiConnectionFactory::getCon('readonly');
//get the q parameter from URL
$sqlFrag = $con->real_escape_string($_REQUEST['sql']);
$clid = $con->real_escape_string($_REQUEST['clid']);
$responseStr = '-1';
if($sqlFrag && $clid && $isAdmin || (array_key_exists("ClAdmin",$userRights) && in_array($clid,$userRights["ClAdmin"]))){
$responseStr = '0';
$sql = "SELECT * FROM omoccurrences o WHERE ".$sqlFrag." limit 1";
$result = $con->query($sql);
if($result){
$responseStr = "1";
}
if($result) $result->close();
}
if(!($con === false)) $con->close();
echo $responseStr;
?> | seltmann/Symbiota | checklists/rpc/testsql.php | PHP | gpl-2.0 | 869 |
<?php
/**
* Welcome Screen Class
* Sets up the welcome screen page, hides the menu item
* and contains the screen content.
*/
class Storefront_Welcome {
/**
* Constructor
* Sets up the welcome screen
*/
public function __construct() {
add_action( 'admin_menu', array( $this, 'storefront_welcome_register_menu' ) );
add_action( 'load-themes.php', array( $this, 'storefront_activation_admin_notice' ) );
add_action( 'storefront_welcome', array( $this, 'storefront_welcome_intro' ), 10 );
add_action( 'storefront_welcome', array( $this, 'storefront_welcome_getting_started' ), 20 );
add_action( 'storefront_welcome', array( $this, 'storefront_welcome_addons' ), 30 );
add_action( 'storefront_welcome', array( $this, 'storefront_welcome_who' ), 40 );
} // end constructor
/**
* Adds an admin notice upon successful activation.
* @since 1.0.3
*/
public function storefront_activation_admin_notice() {
global $pagenow;
if ( is_admin() && 'themes.php' == $pagenow && isset( $_GET['activated'] ) ) { // input var okay
add_action( 'admin_notices', array( $this, 'storefront_welcome_admin_notice' ), 99 );
}
}
/**
* Display an admin notice linking to the welcome screen
* @since 1.0.3
*/
public function storefront_welcome_admin_notice() {
?>
<div class="updated fade">
<p><?php echo sprintf( esc_html__( 'Thanks for choosing Storefront! You can read hints and tips on how get the most out of your new theme on the %swelcome screen%s.', 'storefront' ), '<a href="' . esc_url( admin_url( 'themes.php?page=storefront-welcome' ) ) . '">', '</a>' ); ?></p>
<p><a href="<?php echo esc_url( admin_url( 'themes.php?page=storefront-welcome' ) ); ?>" class="button" style="text-decoration: none;"><?php _e( 'Get started with Storefront', 'storefront' ); ?></a></p>
</div>
<?php
}
/**
* Creates the dashboard page
* @see add_theme_page()
* @since 1.0.0
*/
public function storefront_welcome_register_menu() {
add_theme_page( 'Storefront', 'Storefront', 'read', 'storefront-welcome', array( $this, 'storefront_welcome_screen' ) );
}
/**
* The welcome screen
* @since 1.0.0
*/
public function storefront_welcome_screen() {
require_once( ABSPATH . 'wp-load.php' );
require_once( ABSPATH . 'wp-admin/admin.php' );
require_once( ABSPATH . 'wp-admin/admin-header.php' );
?>
<div class="wrap about-wrap">
<?php
/**
* @hooked storefront_welcome_intro - 10
* @hooked storefront_welcome_getting_started - 20
* @hooked storefront_welcome_addons - 30
* @hooked storefront_welcome_who - 40
*/
do_action( 'storefront_welcome' ); ?>
</div>
<?php
}
/**
* Welcome screen intro
* @since 1.0.0
*/
public function storefront_welcome_intro() {
$storefront = wp_get_theme( 'storefront' );
?>
<div class="feature-section col two-col" style="margin-bottom: 1.618em; overflow: hidden;">
<div class="col-1">
<h1 style="margin-right: 0;"><?php echo '<strong>Storefront</strong> <sup style="font-weight: bold; font-size: 50%; padding: 5px 10px; color: #666; background: #fff;">' . esc_attr( $storefront['Version'] ) . '</sup>'; ?></h1>
<p style="font-size: 1.2em;"><?php _e( 'Awesome! You\'ve decided to use Storefront to enrich your WooCommerce store design.', 'storefront' ); ?></p>
<p><?php _e( 'Whether you\'re a store owner, WordPress developer, or both - we hope you enjoy Storefront\'s deep integration with WooCommerce core (including several popular WooCommerce extensions), plus the flexible design and extensible codebase that this theme provides.', 'storefront' ); ?>
</div>
<div class="col-2 last-feature">
<img src="<?php echo esc_url( get_template_directory_uri() ) . '/screenshot.png'; ?>" class="image-50" width="440" />
</div>
</div>
<hr />
<?php
}
/**
* Welcome screen about section
* @since 1.0.0
*/
public function storefront_welcome_who() {
?>
<div class="feature-section col three-col" style="margin-bottom: 1.618em; padding-top: 1.618em; overflow: hidden;">
<div class="col-1">
<img src="<?php echo esc_url( get_template_directory_uri() ) . '/images/welcome/woothemes.png'; ?>" class="image-50" width="440" />
<h4><?php _e( 'Who are WooThemes?', 'storefront' ); ?></h4>
<p><?php _e( 'WooCommerce creators WooThemes is an international team of WordPress superstars building products for a passionate community of hundreds of thousands of users.', 'storefront' ); ?></p>
<p><a href="http://woothemes.com" class="button"><?php _e( 'Visit WooThemes', 'storefront' ); ?></a></p>
</div>
<?php if ( ! class_exists( 'WooCommerce' ) ) { ?>
<div class="col-2">
<img src="<?php echo esc_url( get_template_directory_uri() ) . '/images/welcome/woocommerce.png'; ?>" class="image-50" width="440" />
<h4><?php _e( 'What is WooCommerce?', 'storefront' ); ?></h4>
<p><?php _e( 'WooCommerce is the most popular WordPress eCommerce plugin. Packed full of intuitive features and surrounded by a thriving community - it\'s the perfect solution for building an online store with WordPress.', 'storefront' ); ?></p>
<p><a href="<?php echo esc_url( wp_nonce_url( self_admin_url( 'update.php?action=install-plugin&plugin=woocommerce' ), 'install-plugin_woocommerce' ) ); ?>" class="button button-primary"><?php _e( 'Download & Install WooCommerce', 'storefront' ); ?></a></p>
<p><a href="http://docs.woothemes.com/documentation/plugins/woocommerce/" class="button"><?php _e( 'View WooCommerce Documentation', 'storefront' ); ?></a></p>
</div>
<?php } ?>
<div class="col-3 last-feature">
<img src="<?php echo esc_url( get_template_directory_uri() ) . '/images/welcome/github.png'; ?>" class="image-50" width="440" />
<h4><?php _e( 'Can I Contribute?', 'storefront' ); ?></h4>
<p><?php _e( 'Found a bug? Want to contribute a patch or create a new feature? GitHub is the place to go! Or would you like to translate Storefront in to your language? Get involved at Transifex.', 'storefront' ); ?></p>
<p><a href="http://github.com/woothemes/storefront/" class="button"><?php _e( 'Storefront at GitHub', 'storefront' ); ?></a> <a href="https://www.transifex.com/projects/p/storefront-1/" class="button"><?php _e( 'Storefront at Transifex', 'storefront' ); ?></a></p>
</div>
</div>
<hr style="clear: both;">
<?php
}
/**
* Welcome screen getting started section
* @since 1.0.0
*/
public function storefront_welcome_getting_started() {
// get theme customizer url
$url = admin_url() . 'customize.php?';
$url .= 'url=' . urlencode( site_url() . '?storefront-customizer=true' );
$url .= '&return=' . urlencode( admin_url() . 'themes.php?page=storefront-welcome' );
$url .= '&storefront-customizer=true';
?>
<div class="feature-section col two-col" style="margin-bottom: 1.618em; padding-top: 1.618em; overflow: hidden;">
<h2><?php _e( 'Using Storefront', 'storefront' ); ?> <div class="dashicons dashicons-lightbulb"></div></h2>
<p><?php _e( 'We\'ve purposely kept Storefront lean & mean so configuration is a breeze. Here are some common theme-setup tasks:', 'storefront' ); ?></p>
<div class="col-1">
<?php if ( ! class_exists( 'WooCommerce' ) ) { ?>
<h4><?php _e( 'Install WooCommerce' ,'storefront' ); ?></h4>
<p><?php _e( 'Although Storefront works fine as a standard WordPress theme, it really shines when used for an online store. Install WooCommerce and start selling now.', 'storefront' ); ?></p>
<p><a href="<?php echo esc_url( wp_nonce_url( self_admin_url( 'update.php?action=install-plugin&plugin=woocommerce' ), 'install-plugin_woocommerce' ) ); ?>" class="button"><?php _e( 'Install WooCommerce', 'storefront' ); ?></a></p>
<?php } ?>
<h4><?php _e( 'Configure menu locations' ,'storefront' ); ?></h4>
<p><?php _e( 'Storefront includes two menu locations for primary and secondary navigation. The primary navigation is perfect for your key pages like the shop and product categories. The secondary navigation is better suited to lower traffic pages such as terms and conditions.', 'storefront' ); ?></p>
<p><a href="<?php echo esc_url( self_admin_url( 'nav-menus.php' ) ); ?>" class="button"><?php _e( 'Configure menus', 'storefront' ); ?></a></p>
<h4><?php _e( 'Create a color scheme' ,'storefront' ); ?></h4>
<p><?php _e( 'Using the WordPress Customizer you can tweak Storefront\'s appearance to match your brand.', 'storefront' ); ?></p>
<p><a href="<?php echo esc_url( $url ); ?>" class="button"><?php _e( 'Open the Customizer', 'storefront' ); ?></a></p>
</div>
<div class="col-2 last-feature">
<h4><?php _e( 'Configure homepage template', 'storefront' ); ?></h4>
<p><?php _e( 'Storefront includes a homepage template that displays a selection of products from your store.', 'storefront' ); ?></p>
<p><?php echo sprintf( esc_html__( 'To set this up you will need to create a new page and assign the "Homepage" template to it. You can then set that as a static homepage in the %sReading%s settings.', 'storefront' ), '<a href="' . esc_url( self_admin_url( 'options-reading.php' ) ) . '">', '</a>' ); ?></p>
<p><?php echo sprintf( esc_html__( 'Once set up you can toggle and re-order the homepage components using the %sHomepage Control%s plugin.', 'storefront' ), '<a href="https://wordpress.org/plugins/homepage-control/">', '</a>' ); ?></p>
<h4><?php _e( 'Add your logo', 'storefront' ); ?></h4>
<p><?php echo sprintf( esc_html__( 'Activate %sJetpack%s to enable a custom logo option in the Customizer.', 'storefront' ), '<a href="https://wordpress.org/plugins/jetpack/">', '</a>' ); ?></p>
<h4><?php _e( 'View documentation', 'storefront' ); ?></h4>
<p><?php _e( 'You can read detailed information on Storefronts features and how to develop on top of it in the documentation.', 'storefront' ); ?></p>
<p><a href="http://docs.woothemes.com/documentation/themes/storefront/" class="button"><?php _e( 'View documentation', 'storefront' ); ?></a></p>
</div>
</div>
<hr style="clear: both;">
<?php
}
/**
* Welcome screen add ons
* @since 1.0.0
*/
public function storefront_welcome_addons() {
?>
<div id="add-ons" class="feature-section col three-col" style="padding-top: 1.618em; clear: both;">
<h2><?php _e( 'Enhance your site', 'storefront' ); ?> <div class="dashicons dashicons-admin-plugins"></div></h2>
<p>
<?php _e( 'Below you will find a selection of hand-picked WooCommerce and Storefront extensions that could help improve your online store. Each WooCommerce extension integrates seamlessly with Storefront for enhanced performance.', 'storefront' ); ?>
</p>
<div class="col-1">
<h4><?php _e( 'Storefront Extensions', 'storefront' ); ?></h4>
<img src="<?php echo esc_url( get_template_directory_uri() ) . '/images/welcome/designer.jpg'; ?>" class="image-50" width="440" />
<h4><?php _e( 'Storefront Designer', 'storefront' ); ?></h4>
<p><?php _e( 'Adds a bunch of additional appearance settings allowing you to further tweak and perfect your Storefront design by changing the header layout, button styles, typographical schemes/scales and more.', 'storefront' ); ?></p>
<p style="margin-bottom: 2.618em;"><a href="https://www.woothemes.com/products/storefront-designer?utm_source=product&utm_medium=upsell&utm_campaign=storefrontaddons" class="button"><?php _e( 'Buy now', 'storefront' ); ?></a></p>
<img src="<?php echo esc_url( get_template_directory_uri() ) . '/images/welcome/wc-customiser.png'; ?>" class="image-50" width="440" />
<h4><?php _e( 'Storefront WooCommerce Customiser', 'storefront' ); ?></h4>
<p><?php _e( 'Gives you further control over the look and feel of your shop. Change the product archive and single layouts, toggle various shop components, enable a distraction free checkout design and more.', 'storefront' ); ?></p>
<p style="margin-bottom: 2.618em;"><a href="https://www.woothemes.com/products/storefront-woocommerce-customizer?utm_source=product&utm_medium=upsell&utm_campaign=storefrontaddons" class="button"><?php _e( 'Buy now', 'storefront' ); ?></a></p>
<img src="<?php echo esc_url( get_template_directory_uri() ) . '/images/welcome/hero.png'; ?>" class="image-50" width="440" />
<h4><?php _e( 'Storefront Parallax Hero', 'storefront' ); ?></h4>
<p><?php _e( 'Adds a parallax hero component to your homepage. Easily change the colors / copy and give your visitors a warm welcome!', 'storefront' ); ?></p>
<p style="margin-bottom: 2.618em;"><a href="https://www.woothemes.com/products/storefront-parallax-hero?utm_source=product&utm_medium=upsell&utm_campaign=storefrontaddons" class="button"><?php _e( 'Buy now', 'storefront' ); ?></a></p>
<p style="margin-bottom: 2.618em;"><a href="http://www.woothemes.com/product-category/storefront-extensions?utm_source=product&utm_medium=upsell&utm_campaign=storefrontaddons" class="button button-primary"><?php _e( 'View all Storefront extensions →', 'storefront' ); ?></a></p>
</div>
<div class="col-2">
<h4><?php _e( 'WooCommerce Extensions', 'storefront' ); ?></h4>
<img src="<?php echo esc_url( get_template_directory_uri() ) . '/images/welcome/bookings.png'; ?>" class="image-50" width="440" />
<h4><?php _e( 'WooCommerce Bookings', 'storefront' ); ?></h4>
<p><?php _e( 'Allows you to sell your time or date based bookings, adding a new product type to your WooCommerce site. Perfect for those wanting to offer appointments, services or rentals.', 'storefront' ); ?></p>
<p style="margin-bottom: 2.618em;"><a href="http://www.woothemes.com/products/woocommerce-bookings?utm_source=product&utm_medium=upsell&utm_campaign=storefrontaddons" class="button"><?php _e( 'Buy now', 'storefront' ); ?></a></p>
<img src="<?php echo esc_url( get_template_directory_uri() ) . '/images/welcome/smart-coupons.jpg'; ?>" class="image-50" width="440" />
<h4><?php _e( 'WooCommerce Smart Coupons', 'storefront' ); ?></h4>
<p><?php _e( 'Smart coupons provide the most comprehensive and powerful solution for discount coupons, gift certificates, store credits and vouchers. It also allows customers to buy credits for themselves or gift to others.', 'storefront' ); ?></p>
<p style="margin-bottom: 2.618em;"><a href="http://www.woothemes.com/products/smart-coupons?utm_source=product&utm_medium=upsell&utm_campaign=storefrontaddons" class="button"><?php _e( 'Buy now', 'storefront' ); ?></a></p>
<img src="<?php echo esc_url( get_template_directory_uri() ) . '/images/welcome/wishlists.png'; ?>" class="image-50" width="440" />
<h4><?php _e( 'WooCommerce Wishlists', 'storefront' ); ?></h4>
<p><?php _e( 'Allows guests and customers to create and add products to an unlimited number of Wishlists. From birthdays to weddings and everything in between, WooCommerce Wishlists are a welcome addition to any WooCommerce store.', 'storefront' ); ?></p>
<p style="margin-bottom: 2.618em;"><a href="http://www.woothemes.com/products/woocommerce-wishlists?utm_source=product&utm_medium=upsell&utm_campaign=storefrontaddons" class="button"><?php _e( 'Buy now', 'storefront' ); ?></a></p>
<p style="margin-bottom: 2.618em;"><a href="http://www.woothemes.com/product-category/woocommerce-extensions/?utm_source=product&utm_medium=upsell&utm_campaign=storefrontaddons" class="button button-primary"><?php _e( 'View all WooCommerce extensions →', 'storefront' ); ?></a></p>
</div>
<div class="col-3 last-feature">
<h4><?php _e( 'Can\'t find a feature?', 'storefront' ); ?></h4>
<p><?php echo sprintf( esc_html__( 'Please suggest and vote on ideas / feature requests at the %sStorefront Ideasboard%s. The most popular ideas will see prioritised development.', 'storefront' ), '<a href="http://ideas.woothemes.com/forums/275029-storefront">', '</a>' ); ?></p>
</div>
</div>
<hr style="clear: both;" />
<p style="font-size: 1.2em; margin: 2.618em 0;">
<?php echo sprintf( esc_html__( 'There are literally hundreds of awesome extensions available for you to use. Looking for Table Rate Shipping? Subscriptions? Product Add-ons? You can find these and more in the WooCommerce extension shop. %sGo shopping%s.', 'storefront' ), '<a href="http://www.woothemes.com/product-category/woocommerce-extensions/">', '</a>' ); ?>
</p>
<hr style="clear: both;" />
<?php
}
}
$GLOBALS['Storefront_Welcome'] = new Storefront_Welcome();
| toyo213/linehair | wp-content/themes/storefront/inc/admin/welcome-screen.php | PHP | gpl-2.0 | 16,495 |
<?php
/* Copyright 2005 Flรกvio Ribeiro
This file is part of OCOMON.
OCOMON is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
OCOMON is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Foobar; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/session_start();
include ("../../includes/include_geral.inc.php");
include ("../../includes/include_geral_II.inc.php");
//print "<script src='../../includes/javascript/ajax_request.js'></script>";
//print "<script type='text/javascript' src='../../includes/fckeditor/fckeditor.js'></script>";
$imgsPath = "../../includes/imgs/";
$hoje = date("Y-m-d H:i:s");
$hoje2 = date("d/m/Y");
print "<HTML><BODY bgcolor='".BODY_COLOR."' ".
"onLoad=\"ajaxFunction('Problema', 'showSelProbs.php', 'idLoad', 'prob=idProblema', 'area_cod=idArea', 'area_habilitada=idAreaHabilitada'); ajaxFunction('divProblema', 'showProbs.php', 'idLoad', 'prob=idProblema', 'area_cod=idArea'); ajaxFunction('divSla', 'sla_standalone.php', 'idLoad', 'numero=idSlaNumero', 'popup=idSlaNumero', 'SCHEDULED=idScheduled'); ajaxFunction('divInformacaoProblema', 'showInformacaoProb.php', 'idLoad', 'prob=idProblema', 'area_cod=idArea');\">";
$auth = new auth;
$auth->testa_user($_SESSION['s_usuario'],$_SESSION['s_nivel'],$_SESSION['s_nivel_desc'],2);
$qry_config = "SELECT * FROM config ";
$exec_config = mysql_query($qry_config) or die (TRANS('ERR_TABLE_CONFIG'));;
$row_config = mysql_fetch_array($exec_config);
$sqlSoluc = "SELECT * FROM solucoes WHERE numero = ".$_REQUEST['numero']." ";
$execSoluc = mysql_query ($sqlSoluc);
$regSoluc = mysql_num_rows($execSoluc);
if ($regSoluc >0) {
print "<script>".
"mensagem('".TRANS('MSG_ALERT_OCCO_IS_LOCKED_UP')."');".
"history.back();";
print "</script>";
exit;
}
$sqlSub = "select * from ocodeps where dep_pai = ".$_REQUEST['numero']." ";
$execSub = mysql_query ($sqlSub) or die (TRANS('MSG_ERR_NOT_RESCUE_INFO_DEPEND_OCCO').$sqlSub);
$deps = array();
while ($rowSub = mysql_fetch_array($execSub)) {
$sqlStatus = "select o.*, s.* from ocorrencias as o, `status` as s where o.numero = ".$rowSub['dep_filho']." and o.`status`=s.stat_id and s.stat_painel not in (3) ";
$execStatus = mysql_query($sqlStatus) or die (TRANS('MSG_ERR_NOT_ACCESS_CALL_SON').$sqlStatus);
$achou = mysql_num_rows ($execStatus);
if ($achou > 0) {
$deps[] = $rowSub['dep_filho'];
}
}
if(sizeof($deps)) {
$saida = "<b>".TRANS('MSG_ALERT_OCCO_NOT_LOCKED_UP').":</b><br><br>";
foreach($deps as $err) {
$saida.="Chamado <a onClick=\"javascript: popup_alerta('mostra_consulta.php?popup=true&numero=".$err."')\"><font color='blue'>".$err."</font></a><br>";
}
$saida.="<br><a align='center' onClick=\"redirect('mostra_consulta.php?numero=".$_REQUEST['numero']."');\"><img src='".ICONS_PATH."/back.png' width='16px' height='16px'> ".TRANS('TXT_RETURN')."</a>";
print "</table>";
print "<div class='alerta' id='idAlerta'><table bgcolor='#999999'><tr><td colspan='2' bgcolor='yellow'>".$saida."</td></tr></table></div>";
exit;
}
//$query = "select o.*, u.* from ocorrencias as o, usuarios as u where o.operador = u.user_id and numero=$numero";
//$query = $QRY["ocorrencias_full_ini"]." where numero in (".$numero.") order by numero";
$query = $QRY["ocorrencias_full_ini"]." where numero = ".$_REQUEST['numero']." order by numero";
$resultado = mysql_query($query);
$rowABS = mysql_fetch_array($resultado);
//print $query;
$atendimento = "";
$atendimento = $rowABS['data_atendimento'];
$query2 = "select a.*, u.* from assentamentos as a, usuarios as u where a.responsavel = u.user_id and ocorrencia='".$_REQUEST['numero']."'";
$resultado2 = mysql_query($query2);
$linhas2 = mysql_numrows($resultado2);
if (!isset($_POST['submit'])) {
if (isset($_POST['carrega'])){
$prob = $_POST['prob'];
if (isset($_POST['radio_prob'])) {
$radio_prob = $_POST['radio_prob'];
} else $radio_prob = $_POST['prob'];
$inst = $_POST['inst'];
$etiqueta = $_POST['etiqueta'];
$contato = $_POST['contato'];
$loc = $_POST['loc'];
$problema = $_POST['problema'];
$solucao = $_POST['solucao'];
$numero = $_POST['numero'];
$script_sol = $_POST['script_sol'];
} else {
$prob = $rowABS['prob_cod'];
$radio_prob = $rowABS['prob_cod'];
$inst = $rowABS['unidade_cod'];
$etiqueta = $rowABS['etiqueta'];
$contato = $rowABS['contato'];
$loc = $rowABS['setor_cod'];
$script_sol = $rowABS['oco_script_sol'];
//$problema = $_POST['problema'];
//$solucao = $_POST['solucao'];
//$numero = $_POST['numero'];
}
print "<BR><B>".TRANS('SUBTTL_CLOSING_OCCO')."</B><BR>";
print "<FORM method='POST' action='".$_SERVER['PHP_SELF']."' name='form1' onSubmit='return valida()'>";
print "<TABLE border='0' align='center' width='100%' bgcolor='".BODY_COLOR."'>";
Print "<tr>";
print "<td colspan='7'>";
print "<div id='divSla'>";
print "</div>";
print "</TD>";
Print "</tr>";
print "<input type='hidden' name='slaNumero' id='idSlaNumero' value='".$_REQUEST['numero']."'>";
print "<input type='hidden' name='SCHEDULED' id='idScheduled' value='".$rowABS['oco_scheduled']."'>";
$getPriorityDesc = "SELECT * FROM prior_atend WHERE pr_cod = '".$rowABS['oco_prior']."'";
$execGetPrior = mysql_query($getPriorityDesc);
$rowGet = mysql_fetch_array($execGetPrior);
// print "<TR>";
// print "<TD width='20%' align='left' bgcolor='". TD_COLOR."'>".TRANS('OCO_PRIORITY').":</TD>";
// print "<TD width='30%' align='left'><input class='disable' value='".$rowGet['pr_desc']."' disabled></TD>";
// print "</TR>";
print "<TR>";
print "<TD width='20%' align='left' bgcolor='".TD_COLOR."'>".TRANS('OCO_FIELD_NUMBER').":</TD>";
print "<TD width='30%' align='left' bgcolor='".BODY_COLOR."'><input class='disable' value='".$rowABS['numero']."' disabled></td>";
print "<TD width='20%' align='left' bgcolor='". TD_COLOR."'>".TRANS('OCO_PRIORITY').":</TD>";
print "<TD width='30%' align='left' bgcolor='".BODY_COLOR."'><input class='disable' value='".$rowGet['pr_desc']."' disabled></TD>";
print "</TR>";
print "<TR>";
print "<TD width='20%' align='left' bgcolor='".TD_COLOR."'>".TRANS('OCO_PROB').": ";
//print "<input type='submit' class='btPadrao' id='idBtLoadCat' title='".TRANS('LOAD_EQUIP_LOCAL')."'onClick=\"LOAD=1;\"".
//"style=\"{align:center; valign:middle; width:19px; height:19px; background-image: url('../../includes/icons/key_enter.png'); background-repeat:no-repeat;}\" value='' name='carrega'>";
print "</TD>";
//$query_problema = "SELECT * FROM problemas order by problema";
$query_problema = "SELECT * FROM problemas as p ".
"LEFT JOIN sistemas as s on p.prob_area = s.sis_id ".
"LEFT JOIN sla_solucao as sl on sl.slas_cod = p.prob_sla ".
"LEFT JOIN prob_tipo_1 as pt1 on pt1.probt1_cod = p.prob_tipo_1 ".
"LEFT JOIN prob_tipo_2 as pt2 on pt2.probt2_cod = p.prob_tipo_2 ".
"LEFT JOIN prob_tipo_3 as pt3 on pt3.probt3_cod = p.prob_tipo_3 ";
if ($rowABS['area_cod'] != -1){
$query_problema.= " WHERE (p.prob_area = ".$rowABS['area_cod']." OR (p.prob_area is null OR p.prob_area = -1)) ";
} /*else
$clausula = "";*/
$query_problema.= "GROUP BY p.problema".
" ORDER BY p.problema";
$exec_problema = mysql_query($query_problema);
print "<TD width='30%' align='left' bgcolor='".BODY_COLOR."'>";
/* print "<select class='select' name='prob' id='idProb' onChange=\"ajaxFunction('Problema', 'showProbs.php', 'prob=idProb', 'area_cod=idFieldArea')\">";
print "<option value=-1>Selecione o problema</option>";
while($row=mysql_fetch_array($exec_problema)){
print "<option value=".$row['prob_id']."";
if ($row['prob_id']== $prob) {
print " selected";
}
print ">".$row['problema']."</option>";
} // while
print "</select>";*/
print "<div id='Problema'>";
print "<input type='hidden' name='prob' id='idProblema' value='".$prob."'>";
print "</div>";
print "<div id='idLoad' class='loading'><img src='../../includes/imgs/loading.gif'></div>";
print "</TD>";
print "<TD width='20%' align='left' bgcolor='".TD_COLOR."'>".TRANS('OCO_FIELD_AREA').":</TD>";
print "<TD colspan='3' width='30%' align='left' bgcolor='".BODY_COLOR."'><input class='disable' value='".$rowABS['area']."' disabled></TD>";
print "<input type='hidden' name='fieldArea' id='idArea' value='".$rowABS['area_cod']."'></TD>";
print "<input type='hidden' name='areaHabilitada' id='idAreaHabilitada' value='sim'>";
print "</TR>";
################################################################
print "<tr><td colspan='6' ><div id='divProblema'>"; //style='{display:none}' //<td colspan='6' >
//print "<TABLE border='0' cellpadding='2' cellspacing='0' width='90%'>";
//print "<input type='hidden' name='problema' id='idProb' value='".$rowABS['problema']."'>";
//print "</table>";
print "</div></td></tr>"; //</td>
print "<tr><td colspan='6' ><div id='divInformacaoProblema'></div></td></tr>";
################################################################
print "<TR>";
print "<TD width='20%' align='left' bgcolor='".TD_COLOR."'>".TRANS('OCO_DESC').":</TD>";
print "<TD colspan='5' width='80%' align='left' bgcolor='".BODY_COLOR."'><b>".$rowABS['descricao']."</b></TD>";
print "</TR>";
print "<TR>";
print "<TD width='20%' align='left' bgcolor='".TD_COLOR."'>".TRANS('OCO_FIELD_UNIT').":</TD>";
$qryinst = "select * from instituicao order by inst_nome";
$exec_inst = mysql_query($qryinst);
print "<TD width='30%' align='left' bgcolor='".BODY_COLOR."'>";
print "<select class='select' name='inst'>";
print "<option value=-1>".TRANS('OCO_SEL_UNIT')."</option>";
while($row=mysql_fetch_array($exec_inst)){
print "<option value=".$row['inst_cod']."";
if ($row['inst_cod']== $inst) {
print " selected";
}
print ">".$row['inst_nome']."</option>";
} // while
print "</select>";
print "</TD>";
print "<TD width='20%' align='left' bgcolor='".TD_COLOR."'><a onClick=\"checa_etiqueta()\" ".
"title='".TRANS('CONS_CONFIG_EQUIP')."'><font color='#5E515B'><b>".TRANS('OCO_FIELD_TAG')."</b></font></a>".
" ".TRANS('OCO_FIELD_OF_EQUIP').":</TD>";
print "<TD colspan='3' width='30%' align='left' bgcolor='".BODY_COLOR."'>";
print "<input type='text' class='data' name='etiqueta' id='idEtiqueta' value='".$etiqueta."'>";
print "</TD>";
print "</TR>";
print "<TR>";
print "<TD width='20%' align='left' bgcolor='".TD_COLOR."'>".TRANS('OCO_CONTACT').":</TD>";
print "<TD width='30%' align='left' bgcolor='".BODY_COLOR."'><input type='text' class='text' name='contato' id='idContato' value='".$contato."'></TD>";
print "<TD width='20%' align='left' bgcolor='".TD_COLOR."'>".TRANS('COL_PHONE').":</TD>";
print "<TD colspan='3' width='30%' align='left' bgcolor='".BODY_COLOR."'>".$rowABS['telefone']."</TD>";
print "</TR>";
print "<TR>";
print "<TD width='20%' align='left' bgcolor='".TD_COLOR."'>".TRANS('OCO_FIELD_LOCAL').":</TD>";
print "<TD width='30%' align='left' bgcolor='".BODY_COLOR."'>";
print "<select class='select' name='loc' id='idLocal'>";
$qrylocal = "select * from localizacao where loc_status not in (0) order by local";
$exec_local = mysql_query($qrylocal);
print "<option value=-1>".TRANS('OCO_SEL_LOCAL')."</option>";
while($row=mysql_fetch_array($exec_local)){
print "<option value=".$row['loc_id']."";
if ($row['loc_id']== $loc) {
print " selected";
}
print ">".$row['local']."</option>";
} // while
print "</select><a onClick=\"checa_por_local()\">".
"<img title='".TRANS('CONS_EQUIP_LOCAL')."' width='15' height='15' ".
"src='".$imgsPath."consulta.gif' border='0'></a>";
print "</TD>";
print "<TD width='20%' align='left' bgcolor='".TD_COLOR."'>".TRANS('OCO_FIELD_OPERATOR').":</TD>";
print "<TD colspan='3' width='30%' align='left' bgcolor='".BODY_COLOR."'>".$rowABS['nome']."</TD>";
print "</TR>";
print "<TR>";
print "<TD width='20%' align='left' bgcolor='".TD_COLOR."'>".TRANS('OCO_FIELD_DATE_OPEN').":</TD>";
print "<TD width='30%' align='left' bgcolor='".BODY_COLOR."'>".formatDate($rowABS['data_abertura'])."</TD>";
print "<TD width='20%' align='left' bgcolor='".TD_COLOR."'>".TRANS('OCO_FIELD_STATUS').":</TD>";
print "<TD colspan='3' width='30%' align='left' bgcolor='".BODY_COLOR."'>".$rowABS['chamado_status']."</TD>";
print "</TR>";
print "<TR>";
print "<TD width='20%' align='left' bgcolor='".TD_COLOR."'>".TRANS('FIELD_DATE_CLOSING').":</TD>";
print "<TD colspan='5' width='80%' align='left' bgcolor='".BODY_COLOR."'>";
print "<INPUT type='text' class='text' name='data_fechamento' id='idData_fechamento' value='".formatDate(date("Y-m-d H:i:s"))."'>";
print "</TD>";
print "</tr>";
if ($linhas2 > 0) { //ASSENTAMENTOS DO CHAMADO
print "<tr><td colspan='6'><IMG ID='imgAssentamento' SRC='../../includes/icons/open.png' width='9' height='9' ".
"STYLE=\"{cursor: pointer;}\" onClick=\"invertView('Assentamento')\"> <b>".TRANS('THERE_IS_ARE')." <font color='red'>".$linhas2."</font>".
" ".TRANS('FIELD_NESTING_FOR_OCCO').".</b></td></tr>";
//style='{padding-left:5px;}'
print "<tr><td colspan='6'><div id='Assentamento' style='{display:none}'>"; //style='{display:none}'
print "<TABLE border='0' align='center' width='100%' bgcolor='".BODY_COLOR."'>";
$i = 0;
while ($rowAssentamento = mysql_fetch_array($resultado2)){
$printCont = $i+1;
print "<TR>";
print "<TD width='20%' bgcolor='".TD_COLOR."' valign='top'>".
"".TRANS('FIELD_NESTING')." ".$printCont." de ".$linhas2." por ".$rowAssentamento['nome']." em ".
"".formatDate($rowAssentamento['data'])."".
"</TD>";
print "<TD colspan='5' width='80%' align='left' bgcolor='".BODY_COLOR."' valign='top'>".nl2br($rowAssentamento['assentamento'])."</TD>";
print "</TR>";
$i++;
}
print "</table></div></td></tr>";
//print "</div>";
}
//------------------------------------------------------------- INICIO ALTERACAO --------------------------------------------------------------
print "<TR ID='linha_assentamento'>";
print "<TD width='20%' align='left' bgcolor='".TD_COLOR."'>".TRANS('FIELD_NESTING').":</TD>";
print "<TD colspan='5' width='80%' align='left' bgcolor='".BODY_COLOR."'>";
print "<TEXTAREA class='textarea' name='assentamento' id='idAssentamento'>".
"".TRANS('TXTAREA_OCCO_DIRECT_MODIFY')." ".$_SESSION['s_usuario']."</textarea>";
print "</TD>";
print "</tr>";
//------------------------------------------------------------- FIM ALTERACAO --------------------------------------------------------------
//------------------------------------------------------------- INICIO ALTERACAO --------------------------------------------------------------
//print "<TR>";
print "<input type='hidden' value='' name='alimenta_banco' id='alimenta_banco'>";
print "<TR ID='linha_desc_solucao'>";
//------------------------------------------------------------- FIM ALTERACAO --------------------------------------------------------------
//print "<TR>";
print "<TD width='20%' align='left' bgcolor='".TD_COLOR."'>".TRANS('COL_SCRIPT_SOLUTION').":</TD>";
print "<TD colspan='5' width='80%' align='left' bgcolor='".BODY_COLOR."'>";
$qry_script = "SELECT * FROM script_solution ORDER BY script_desc";
$exec_qry_script = mysql_query($qry_script) or die (mysql_error());
print "<select class='select_sol' name='script_sol'>";
print "<option value=null selected>".TRANS('SEL_SCRIPT')."</option>";
while ($rowScript = mysql_fetch_array($exec_qry_script)){
//print "<option value='".$rowScript['script_cod']."'>".$rowScript['script_desc']."</option>";
print "<option value=".$rowScript['script_cod']."";
if ($rowScript['script_cod']== $script_sol) {
print " selected";
}
print ">".$rowScript['script_desc']."</option>";
}
print "</select>";
print "</td>";
print "</tr>";
//------------------------------------------------------------- INICIO ALTERACAO --------------------------------------------------------------
//print "<TR>";
print "<TR ID='linha_problema'>";
//------------------------------------------------------------- FIM ALTERACAO --------------------------------------------------------------
print "<TD width='20%' align='left' bgcolor='".TD_COLOR."'>".TRANS('OCO_PROB').":</TD>";
print "<TD colspan='5' width='80%' align='left' bgcolor='".BODY_COLOR."'>";
//print "<TEXTAREA class='textarea' id='idProblema' name='problema'>Descriรงรฃo tรฉcnica do problema</textarea>";
if (!$_SESSION['s_formatBarOco']) {
print "<TEXTAREA class='textarea' name='problema' id='idDesc'>".TRANS('TXT_DESC_TEC_PROB')."</textarea>"; //oFCKeditor.Value = print noHtml($descricao);
} else
print "<script type='text/javascript' src='../../includes/fckeditor/fckeditor.js'></script>";
?>
<script type="text/javascript">
var bar = '<?php print $_SESSION['s_formatBarOco'];?>'
if (bar ==1) {
var oFCKeditor = new FCKeditor( 'problema' ) ;
oFCKeditor.BasePath = '../../includes/fckeditor/';
oFCKeditor.Value = '<?php print TRANS('TXT_DESC_TEC_PROB');?>';
oFCKeditor.ToolbarSet = 'ocomon';
oFCKeditor.Width = '570px';
oFCKeditor.Height = '100px';
oFCKeditor.Create() ;
}
</script>
<?php
print "</TD>";
print "</TR>";
//------------------------------------------------------------- INICIO ALTERACAO --------------------------------------------------------------
//print "<TR>";
print "<TR ID='linha_solucao'>";
//------------------------------------------------------------- FIM ALTERACAO --------------------------------------------------------------
print "<TD width='20%' align='left' bgcolor='".TD_COLOR."'>".TRANS('COL_TIT_SOLUTION').":</TD>";
print "<TD colspan='5' width='80%' align='left' bgcolor='".BODY_COLOR."'>";
//print "<TEXTAREA class='textarea' id='idSolucao' name='solucao'>Soluรงรฃo para este problema</textarea>";
if (!$_SESSION['s_formatBarOco']) {
print "<TEXTAREA class='textarea' name='solucao' id='idSolucao'>".TRANS('TXT_SOLUTION_PROB')."</textarea>"; //oFCKeditor.Value = print noHtml($descricao);
}
?>
<script type="text/javascript">
var bar = '<?php print $_SESSION['s_formatBarOco'];?>'
if (bar ==1) {
var oFCKeditor = new FCKeditor( 'solucao' ) ;
oFCKeditor.BasePath = '../../includes/fckeditor/';
oFCKeditor.Value = '<?php print TRANS('TXT_SOLUTION_PROB');?>';
oFCKeditor.ToolbarSet = 'ocomon';
oFCKeditor.Width = '570px';
oFCKeditor.Height = '100px';
oFCKeditor.Create() ;
}
</script>
<?php
print "</TD>";
print "</TR>";
//SE TIVER QUE JUSTIFICAR O ESTOURO DO SLA
$descricaoMinima = strlen(TRANS('TXT_JUSTIFICATION'))+5;
if ($row_config['conf_desc_sla_out']){
$qryTmp = "SELECT * FROM sla_out WHERE out_numero = ".$_REQUEST['numero']." ";
$execTmp = mysql_query($qryTmp) OR die(mysql_error());
$rowOut = mysql_fetch_array($execTmp);
if($rowOut['out_sla']==1){//CHAMADO ESTOUROU
//$descricaoMinima = strlen(TRANS('TXT_JUSTIFICATION'))+5;
print "<TR>";
print "<TD width='20%' align='left' bgcolor='".TD_COLOR."'>".TRANS('COL_JUSTIFICATION').":</TD>";
print "<TD colspan='5' width='80%' align='left' bgcolor='".BODY_COLOR."'>";
//print "<TEXTAREA class='textarea' id='idSolucao' name='solucao'>Soluรงรฃo para este problema</textarea>";
if (!$_SESSION['s_formatBarOco']) {
print "<TEXTAREA class='textarea' name='justificativa' id='idJustificativa'>".TRANS('TXT_JUSTIFICATION')."</textarea>"; //oFCKeditor.Value = print noHtml($descricao);
}
?>
<script type="text/javascript">
var bar = '<?php print $_SESSION['s_formatBarOco'];?>'
if (bar ==1) {
var oFCKeditor = new FCKeditor( 'justificativa' ) ;
oFCKeditor.BasePath = '../../includes/fckeditor/';
oFCKeditor.Value = '<?php print TRANS('TXT_JUSTIFICATION');?>';
oFCKeditor.ToolbarSet = 'ocomon';
oFCKeditor.Width = '570px';
oFCKeditor.Height = '100px';
oFCKeditor.Create() ;
}
</script>
<?php
print "</TD>";
print "</TR>";
}
}
//-----------------------------------------
$qrymail = "SELECT u.*, a.*,o.* from usuarios u, sistemas a, ocorrencias o where ".
//"u.AREA = a.sis_id and o.aberto_por = u.user_id and o.numero = ".$_GET['numero']."";
"u.AREA = a.sis_id and o.aberto_por = u.user_id and o.numero = ".$_REQUEST['numero']."";
$execmail = mysql_query($qrymail);
$rowmail = mysql_fetch_array($execmail);
if ($rowmail['sis_atende']==0){
$habilita = "checked";
} else $habilita = "disabled";
print "<tr><td bgcolor='".TD_COLOR."'>".TRANS('OCO_FIELD_SEND_MAIL_TO').":</td>".
"<td colspan='5'><input type='checkbox' value='ok' name='mailAR' checked title='".TRANS('MSG_SEND_EMAIL_AREA_ATTEND_CALL')."'>".TRANS('OCO_FIELD_AREA')." ".
"<input type='checkbox' value='ok' name='mailUS' ".$habilita."><a title='".TRANS('MSG_OPT_CALL_OPEN_USER')."'>".TRANS('OCO_FIELD_USER')."</a></td>".
"</tr>";
print "<TR>";
print "<BR>";
print "<input type='hidden' name='data_gravada' value='".date("Y-m-d H:i:s")."'>";
print "<TD colspan='3' align='center' width='50%' bgcolor='".BODY_COLOR."'>".
"<input type='submit' class='button' value='".TRANS('BT_OK')."' name='submit'>".
"<input type='hidden' name='rodou' value='sim'>".
"<input type='hidden' name='numero' value='".$_REQUEST['numero']."'>".
"<input type='hidden' name='abertopor' value='".$rowmail['user_id']."'>";
print "</TD>";
print "<TD colspan='3' align='center' width='50%' bgcolor='".BODY_COLOR."'>".
"<INPUT type='button' class='button' value='".TRANS('BT_CANCEL')."' name='desloca' ONCLICK='javascript:history.back()'>";
print "</TD>";
print "</TR>";
} else
if (isset($_POST['submit'])) {
#########################################################################################
if (isset($_POST['radio_prob'])) {
$radio_prob = $_POST['radio_prob'];
} else $radio_prob = $_POST['prob'];
$queryB = "SELECT sis_id,sistema, sis_email FROM sistemas WHERE sis_id = ".$rowABS['area_cod']."";
$sis_idB = mysql_query($queryB);
$rowSis = mysql_fetch_array($sis_idB);
$queryC = "SELECT local from localizacao where loc_id = ".$_POST['loc']."";
$loc_idC = mysql_query($queryC);
$setor = mysql_result($loc_idC,0);
$queryD = "SELECT nome from usuarios where login like '".$_SESSION['s_usuario']."'";
$loginD = mysql_query($queryD);
$nome = mysql_result($loginD,0);
##########################################################################################
//$data = datam($hoje2);
$responsavel = $_SESSION['s_uid'];
//------------------------------------------------------------- INICIO ALTERACAO --------------------------------------------------------------
//So insere a solucao no banco se o tipo do problema permitir alimentar o banco de solucoes
if(isset($_POST['alimenta_banco']) && $_POST['alimenta_banco']=="SIM"){
//--------------------------------------------------------------- FIM ALTERACAO ---------------------------------------------------------------
$query = "INSERT INTO assentamentos (ocorrencia, assentamento, data, responsavel) values (".$_POST['numero'].",";
if ($_SESSION['s_formatBarOco']) {
$query.= " '".$_POST['problema']."',";
$query.= " '".$assentamentoProb."',";
} else {
$query.= " '".noHtml($_POST['problema'])."',";
}
$query.=" '".date('Y-m-d H:i:s')."', ".$responsavel.")"; //VER 25/05/2007
$resultado = mysql_query($query) or die (TRANS('MSG_ERR_INSERT_NESTING').$query);
$query = "INSERT INTO assentamentos (ocorrencia, assentamento, data, responsavel) values (".$_POST['numero'].", ";
if ($_SESSION['s_formatBarOco']) {
$query.= " '".$_POST['solucao']."',";
} else {
$query.= " '".noHtml($_POST['solucao'])."',";
}
$query.=" '".date('Y-m-d H:i:s')."', ".$responsavel.")";
$resultado = mysql_query($query)or die (TRANS('MSG_ERR_INSERT_NESTING').$query);
$query1 = "INSERT INTO solucoes (numero, problema, solucao, data, responsavel) values (".$_POST['numero'].", ";
if ($_SESSION['s_formatBarOco']) {
$query1.= " '".$_POST['problema']."','".$_POST['solucao']."',";
} else {
$query1.= " '".noHtml($_POST['problema'])."','".noHtml($_POST['solucao'])."',";
}
$query1.=" '".date('Y-m-d H:i:s')."', ".$responsavel.")";
$resultado1 = mysql_query($query1)or die (TRANS('MSG_ERR_INSERT_SOLUTION').$query1);
//------------------------------------------------------------- INICIO ALTERACAO --------------------------------------------------------------
}else{
$query = "INSERT INTO assentamentos (ocorrencia, assentamento, data, responsavel) values (".$_POST['numero'].",'".$_POST['assentamento']."',";
$query.=" '".date('Y-m-d H:i:s')."', ".$responsavel.")";
$resultado = mysql_query($query) or die (TRANS('MSG_ERR_INSERT_NESTING').$query);
$resultado = $resultado1 = $resultado2 = 1;
}
//--------------------------------------------------------------- FIM ALTERACAO --------------------------------------------------------------- //---------------------------------------------
//JUSTIFICATIVA PARA O ESTOURO DO SLA
if(isset($_POST['justificativa']) && $row_config['conf_desc_sla_out']){
$queryJust = "INSERT INTO assentamentos (ocorrencia, assentamento, data, responsavel, tipo_assentamento) values (".$_POST['numero'].", ";
if ($_SESSION['s_formatBarOco']) {
$queryJust.= " '".$_POST['justificativa']."',";
} else {
$queryJust.= " '".noHtml($_POST['justificativa'])."',";
}
$queryJust.=" '".date('Y-m-d H:i:s')."', ".$responsavel.", 3)";
$execJust = mysql_query($queryJust)or die (TRANS('MSG_ERR_INSERT_NESTING').$queryJust);
}
//REMOVE O NรMERO DO CHAMADO DA TABELA DE CHECAGEM DO SLAS
$qryClear = "DELETE FROM sla_out WHERE out_numero = ".$_POST['numero']."";
$execClear = mysql_query($qryClear);
//----------------------------------------------
$status = 4; //encerrado
if ($atendimento==null) {
$query2 = "UPDATE ocorrencias SET status=".$status.", local=".$_POST['loc'].", problema ='".$radio_prob."', ".
"operador=".$_SESSION['s_uid'].", instituicao='".$_POST['inst']."', equipamento='".$_POST['etiqueta']."', ".
"contato='".noHtml($_POST['contato'])."', data_fechamento='".date('Y-m-d H:i:s')."', ".
"data_atendimento='".date('Y-m-d H:i:s')."', oco_script_sol=".$_POST['script_sol']." WHERE numero='".$_POST['numero']."'";
} else {
$query2 = "UPDATE ocorrencias SET status=".$status.", local=".$_POST['loc'].",problema ='".$radio_prob."', ".
"operador=".$_SESSION['s_uid'].", instituicao='".$_POST['inst']."', equipamento='".$_POST['etiqueta']."', ".
"contato='".noHtml($_POST['contato'])."', data_fechamento='".date('Y-m-d H:i:s')."', oco_script_sol=".$_POST['script_sol']." ".
"WHERE numero='".$_POST['numero']."'";
}
$resultado2 = mysql_query($query2);
if (($resultado == 0) or ($resultado1 == 0) or ($resultado2 == 0))
{
$aviso = TRANS('MSG_ERR_INSERT_DATA_SYSTEM');
print $aviso;
exit;
}
else {
$sqlDoc1 = "select * from doc_time where doc_oco = ".$_POST['numero']." and doc_user=".$_SESSION['s_uid']."";
$execDoc1 = mysql_query($sqlDoc1);
$regDoc1 = mysql_num_rows($execDoc1);
$rowDoc1 = mysql_fetch_array($execDoc1);
if ($regDoc1 >0) {
$sqlDoc = "update doc_time set doc_close=doc_close+".diff_em_segundos($_POST['data_gravada'],date("Y-m-d H:i:s"))." where doc_id = ".$rowDoc1['doc_id']."";
$execDoc =mysql_query($sqlDoc) or die (TRANS('MSG_ERR_UPDATE_TIME_DOC_CALL').'<br>').$sqlDoc;
} else {
$sqlDoc = "insert into doc_time (doc_oco, doc_open, doc_edit, doc_close, doc_user) values (".$_POST['numero'].", 0, 0, ".diff_em_segundos($_POST['data_gravada'],date("Y-m-d H:i:s"))." ,".$_SESSION['s_uid'].")";
$execDoc = mysql_query($sqlDoc) or die (TRANS('MSG_ERR_UPDATE_TIME_DOC_CALL').'<br>').$sqlDoc;
}
##ROTINAS PARA GRAVAR O TEMPO DO CHAMADO EM CADA STATUS
if ($status != $rowABS['status_cod']) { //O status foi alterado
##TRATANDO O STATUS ANTERIOR (atual) -antes da mudanรงa
//Verifica se o status 'atual' jรก foi gravado na tabela 'tempo_status' , em caso positivo, atualizo o tempo, senรฃo devo gravar ele pela primeira vez.
$sql_ts_anterior = "select * from tempo_status where ts_ocorrencia = ".$rowABS['numero']." and ts_status = ".$rowABS['status_cod']." ";
$exec_sql = mysql_query($sql_ts_anterior);
if ($exec_sql == 0) $error= " erro 1".$sql_ts_anterior;
$achou = mysql_num_rows($exec_sql);
if ($achou >0){ //esse status jรก esteve setado em outro momento
$row_ts = mysql_fetch_array($exec_sql);
// if (array_key_exists($rowABS['sistema'],$H_horarios)){ //verifica se o cรณdigo da รกrea possui carga horรกria definida no arquivo config.inc.php
// $areaT = $rowABS['sistema']; //Recebe o valor da รกrea de atendimento do chamado
// } else $areaT = 1; //Carga horรกria default definida no arquivo config.inc.php
$areaT = "";
$areaT=testaArea($areaT,$rowABS['area_cod'],$H_horarios);
$dt = new dateOpers;
$dt->setData1($row_ts['ts_data']);
$dt->setData2(date('Y-m-d H:i:s'));
$dt->tempo_valido($dt->data1,$dt->data2,$H_horarios[$areaT][0],$H_horarios[$areaT][1],$H_horarios[$areaT][2],$H_horarios[$areaT][3],"H");
$segundos = $dt->diff["sValido"]; //segundos vรกlidos
$sql_upd = "update tempo_status set ts_tempo = (ts_tempo+".$segundos.") , ts_data ='".date('Y-m-d H:i:s')."' where ts_ocorrencia = ".$rowABS['numero']." and
ts_status = ".$rowABS['status_cod']." ";
$exec_upd = mysql_query($sql_upd);
if ($exec_upd ==0) $error.= " erro 2";
} else {
$sql_ins = "insert into tempo_status (ts_ocorrencia, ts_status, ts_tempo, ts_data) values (".$rowABS['numero'].", ".$rowABS['status_cod'].", 0, '".date('Y-m-d H:i:s')."' )";
$exec_ins = mysql_query ($sql_ins);
if ($exec_ins == 0) $error.= " erro 3 ".$sql_ins;
}
}
$qryfull = $QRY["ocorrencias_full_ini"]." WHERE o.numero = ".$_POST['numero']."";
$execfull = mysql_query($qryfull) or die(TRANS('MSG_ERR_RESCUE_VARIA_SURROU').$qryfull);
$rowfull = mysql_fetch_array($execfull);
$VARS = array();
$VARS['%numero%'] = $rowfull['numero'];
$VARS['%usuario%'] = $rowfull['contato'];
$VARS['%contato%'] = $rowfull['contato'];
$VARS['%descricao%'] = $rowfull['descricao'];
$VARS['%setor%'] = $rowfull['setor'];
$VARS['%ramal%'] = $rowfull['telefone'];
$VARS['%assentamento%'] = $_POST['solucao'];
$VARS['%site%'] = "<a href='".$row_config['conf_ocomon_site']."'>".$row_config['conf_ocomon_site']."</a>";
$VARS['%area%'] = $rowfull['area'];
$VARS['%operador%'] = $rowfull['nome'];
$VARS['%problema%'] = $_POST['problema'];
$VARS['%solucao%'] = $_POST['solucao'];
$VARS['%versao%'] = VERSAO;
$qryconf = "SELECT * FROM mailconfig";
$execconf = mysql_query($qryconf) or die (TRANS('MSG_ERR_RESCUE_SEND_EMAIL'));
$rowconf = mysql_fetch_array($execconf);
if (isset($_POST['mailAR']) ){
$event = 'encerra-para-area';
$qrymsg = "SELECT * FROM msgconfig WHERE msg_event like ('".$event."')";
$execmsg = mysql_query($qrymsg) or die(TRANS('MSG_ERR_MSCONFIG'));
$rowmsg = mysql_fetch_array($execmsg);
send_mail($event, $rowSis['sis_email'], $rowconf, $rowmsg, $VARS);
//$flag = envia_email_fechamento($numero, $rowSis['sis_email'], $nome, $rowSis['sistema'], $problema, $solucao);
}
if (isset($_POST['mailUS'])) {
$event = 'encerra-para-usuario';
$qrymsg = "SELECT * FROM msgconfig WHERE msg_event like ('".$event."')";
$execmsg = mysql_query($qrymsg) or die(TRANS('MSG_ERR_MSCONFIG'));
$rowmsg = mysql_fetch_array($execmsg);
$sqlMailUs = "select * from usuarios where user_id = ".$_POST['abertopor']."";
$execMailUs = mysql_query($sqlMailUs) or die(TRANS('MSG_ERR_NOT_ACCESS_USER_SENDMAIL'));
$rowMailUs = mysql_fetch_array($execMailUs);
$qryresposta = "select u.*, a.* from usuarios u, sistemas a where u.AREA = a.sis_id and u.user_id = ".$_SESSION['s_uid']."";
$execresposta = mysql_query($qryresposta) or die (TRANS('MSG_ERR_NOT_IDENTIFY_EMAIL'));
$rowresposta = mysql_fetch_array($execresposta);
/*$flag = mail_user_encerramento($rowMailUs['email'], $rowresposta['sis_email'], $rowMailUs['nome'],$_GET['numero'],
$assentamento,OCOMON_SITE);*/
send_mail($event, $rowMailUs['email'], $rowconf, $rowmsg, $VARS);
}
$aviso = TRANS('MSG_OCCO_FINISH_SUCESS');
}
print "<script>mensagem('".$aviso."'); redirect('abertura.php');</script>";
}
?>
<script type="text/javascript">
<!--
function valida(){
var ok = validaForm('idProblema','COMBO','Problema',1);
if (ok) var ok = validaForm('idEtiqueta','INTEIROFULL','Etiqueta',0);
if (ok) var ok = validaForm('idContato','','Contato',1);
if (ok) var ok = validaForm('idLocal','COMBO','Local',1);
if (ok) var ok = validaForm('idData_fechamento','DATAHORA','Data',1);
if (ok) var ok = validaForm('idDesc','','Descriรงรฃo tรฉcnica',1);
if (ok) var ok = validaForm('idSolucao','','Soluรงรฃo',1);
if (ok) {
var justification = document.getElementById('idJustificativa');
if (justification != null){
if (ok) var ok = validaForm('idJustificativa','','Justificativa',1);
if (ok) {
if(justification.value.length <= <?php print $descricaoMinima;?>) {
alert('<?php print TRANS('ALERT_TOO_SHORT_JUSTIFICATION');?>');
ok = false;
document.form1.justificativa.focus();
}
}
}
}
return ok;
}
function popup_alerta(pagina) { //Exibe uma janela popUP
x = window.open(pagina,'Alerta','dependent=yes,width=700,height=470,scrollbars=yes,statusbar=no,resizable=yes');
x.moveTo(window.parent.screenX+50, window.parent.screenY+50);
return false
}
function checa_etiqueta(){
var inst = document.form1.inst.value;
var inv = document.form1.etiqueta.value;
if (inst=='null' || !inv){
window.alert('Os campos Unidade e etiqueta devem ser preenchidos!');
} else
popup_alerta('../../invmon/geral/mostra_consulta_inv.php?comp_inst='+inst+'&comp_inv='+inv+'&popup='+true);
return false;
}
function checa_chamados(){
var inst = document.form1.inst.value;
var inv = document.form1.etiqueta.value;
if (inst=='null' || !inv){
window.alert('Os campos Unidade e etiqueta devem ser preenchidos!');
} else
popup_alerta('../../invmon/geral/ocorrencias.php?comp_inst='+inst+'&comp_inv='+inv+'&popup='+true);
return false;
}
function checa_por_local(){
var local = document.form1.loc.value;
if (local==-1){
window.alert('O local deve ser preenchido!');
} else
popup_alerta('../../invmon/geral/mostra_consulta_comp.php?comp_local='+local+'&popup='+true);
return false;
}
</script>
<?php
//------------------------------------------------------------- INICIO ALTERACAO --------------------------------------------------------------
//So exibe os campos "solucao" e "problema" se o tipo do problema permitir alimentar o banco de solucoes
//Isso รฉ feito via javascript suprimindo o TR da pรกgina
$query_problema_banco_solucao = "SELECT * FROM problemas order by problema";
$exec_problema_banco_solucao = mysql_query($query_problema_banco_solucao);
mysql_data_seek($exec_problema_banco_solucao, 0);
?>
<script>
var alimentaSolucao = new Array();
alimentaSolucao[alimentaSolucao.length] = 0;
<?php while($row=mysql_fetch_array($exec_problema_banco_solucao)){ ?>
alimentaSolucao[<?php print $row['prob_id'] ?>] = <?php print $row['prob_alimenta_banco_solucao'] ?>;
<?php } ?>
function habilitarBancoSolucao(){
var indice = document.getElementById('idProblema').value;
if(alimentaSolucao[indice] == 1){
document.getElementById('linha_assentamento').style.display = 'none';
document.getElementById('linha_desc_solucao').style.display = '';
document.getElementById('linha_problema').style.display = '';
document.getElementById('linha_solucao').style.display = '';
document.getElementById('alimenta_banco').value = 'SIM';
}else{
document.getElementById('linha_assentamento').style.display = '';
document.getElementById('linha_desc_solucao').style.display = 'none';
document.getElementById('linha_problema').style.display = 'none';
document.getElementById('linha_solucao').style.display = 'none';
document.getElementById('alimenta_banco').value = '';
}
}
habilitarBancoSolucao();
</script>
<?php
//--------------------------------------------------------------- FIM ALTERACAO ---------------------------------------------------------------
print "</TABLE>";
print "</FORM>";
print "</body>";
print "</html>";
?>
| luizvarela/ocomon-beta | ocomon/geral/encerramentoOld.php | PHP | gpl-2.0 | 37,856 |
/* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2007, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jfreechart/index.html
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Java is a trademark or registered trademark of Sun Microsystems, Inc.
* in the United States and other countries.]
*
* --------------------------------
* StandardXYItemRendererTests.java
* --------------------------------
* (C) Copyright 2003-2007, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* $Id: StandardXYItemRendererTests.java,v 1.1.2.2 2007/03/14 10:14:30 mungady Exp $
*
* Changes
* -------
* 25-Mar-2003 : Version 1 (DG);
* 22-Oct-2003 : Added hashCode test (DG);
* 08-Oct-2004 : Strengthened test for equals() method (DG);
* 14-Mar-2007 : Added new checks in testEquals() and testCloning() (DG);
*
*/
package org.jfree.chart.renderer.xy.junit;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.jfree.chart.renderer.xy.StandardXYItemRenderer;
import org.jfree.util.UnitType;
/**
* Tests for the {@link StandardXYItemRenderer} class.
*/
public class StandardXYItemRendererTests extends TestCase {
/**
* Returns the tests as a test suite.
*
* @return The test suite.
*/
public static Test suite() {
return new TestSuite(StandardXYItemRendererTests.class);
}
/**
* Constructs a new set of tests.
*
* @param name the name of the tests.
*/
public StandardXYItemRendererTests(String name) {
super(name);
}
/**
* Test that the equals() method distinguishes all fields.
*/
public void testEquals() {
StandardXYItemRenderer r1 = new StandardXYItemRenderer();
StandardXYItemRenderer r2 = new StandardXYItemRenderer();
assertEquals(r1, r2);
r1.setBaseShapesVisible(true);
assertFalse(r1.equals(r2));
r2.setBaseShapesVisible(true);
assertTrue(r1.equals(r2));
r1.setPlotLines(false);
assertFalse(r1.equals(r2));
r2.setPlotLines(false);
assertTrue(r1.equals(r2));
r1.setPlotImages(true);
assertFalse(r1.equals(r2));
r2.setPlotImages(true);
assertTrue(r1.equals(r2));
r1.setPlotDiscontinuous(true);
assertFalse(r1.equals(r2));
r2.setPlotDiscontinuous(true);
assertTrue(r1.equals(r2));
r1.setGapThresholdType(UnitType.ABSOLUTE);
assertFalse(r1.equals(r2));
r2.setGapThresholdType(UnitType.ABSOLUTE);
assertTrue(r1.equals(r2));
r1.setGapThreshold(1.23);
assertFalse(r1.equals(r2));
r2.setGapThreshold(1.23);
assertTrue(r1.equals(r2));
r1.setLegendLine(new Line2D.Double(1.0, 2.0, 3.0, 4.0));
assertFalse(r1.equals(r2));
r2.setLegendLine(new Line2D.Double(1.0, 2.0, 3.0, 4.0));
assertTrue(r1.equals(r2));
r1.setShapesFilled(false);
assertFalse(r1.equals(r2));
r2.setShapesFilled(false);
assertTrue(r1.equals(r2));
r1.setSeriesShapesFilled(1, Boolean.TRUE);
assertFalse(r1.equals(r2));
r2.setSeriesShapesFilled(1, Boolean.TRUE);
assertTrue(r1.equals(r2));
r1.setBaseShapesFilled(false);
assertFalse(r1.equals(r2));
r2.setBaseShapesFilled(false);
assertTrue(r1.equals(r2));
r1.setDrawSeriesLineAsPath(true);
assertFalse(r1.equals(r2));
r2.setDrawSeriesLineAsPath(true);
assertTrue(r1.equals(r2));
}
/**
* Two objects that are equal are required to return the same hashCode.
*/
public void testHashcode() {
StandardXYItemRenderer r1 = new StandardXYItemRenderer();
StandardXYItemRenderer r2 = new StandardXYItemRenderer();
assertTrue(r1.equals(r2));
int h1 = r1.hashCode();
int h2 = r2.hashCode();
assertEquals(h1, h2);
}
/**
* Confirm that cloning works.
*/
public void testCloning() {
StandardXYItemRenderer r1 = new StandardXYItemRenderer();
Rectangle2D rect1 = new Rectangle2D.Double(1.0, 2.0, 3.0, 4.0);
r1.setLegendLine(rect1);
StandardXYItemRenderer r2 = null;
try {
r2 = (StandardXYItemRenderer) r1.clone();
}
catch (CloneNotSupportedException e) {
e.printStackTrace();
}
assertTrue(r1 != r2);
assertTrue(r1.getClass() == r2.getClass());
assertTrue(r1.equals(r2));
// check independence
rect1.setRect(4.0, 3.0, 2.0, 1.0);
assertFalse(r1.equals(r2));
r2.setLegendLine(new Rectangle2D.Double(4.0, 3.0, 2.0, 1.0));
assertTrue(r1.equals(r2));
r1.setSeriesShapesFilled(1, Boolean.TRUE);
assertFalse(r1.equals(r2));
r2.setSeriesShapesFilled(1, Boolean.TRUE);
assertTrue(r1.equals(r2));
}
/**
* Serialize an instance, restore it, and check for equality.
*/
public void testSerialization() {
StandardXYItemRenderer r1 = new StandardXYItemRenderer();
StandardXYItemRenderer r2 = null;
try {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
ObjectOutput out = new ObjectOutputStream(buffer);
out.writeObject(r1);
out.close();
ObjectInput in = new ObjectInputStream(
new ByteArrayInputStream(buffer.toByteArray()));
r2 = (StandardXYItemRenderer) in.readObject();
in.close();
}
catch (Exception e) {
e.printStackTrace();
}
assertEquals(r1, r2);
}
}
| nologic/nabs | client/trunk/shared/libraries/jfreechart-1.0.5/tests/org/jfree/chart/renderer/xy/junit/StandardXYItemRendererTests.java | Java | gpl-2.0 | 7,043 |
<?php
use dokuwiki\Utf8\Sort;
/**
* Plaintext authentication backend
*
* @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
* @author Andreas Gohr <andi@splitbrain.org>
* @author Chris Smith <chris@jalakai.co.uk>
* @author Jan Schumann <js@schumann-it.com>
*/
class auth_plugin_authplain extends DokuWiki_Auth_Plugin
{
/** @var array user cache */
protected $users = null;
/** @var array filter pattern */
protected $pattern = array();
/** @var bool safe version of preg_split */
protected $pregsplit_safe = false;
/**
* Constructor
*
* Carry out sanity checks to ensure the object is
* able to operate. Set capabilities.
*
* @author Christopher Smith <chris@jalakai.co.uk>
*/
public function __construct()
{
parent::__construct();
global $config_cascade;
if (!@is_readable($config_cascade['plainauth.users']['default'])) {
$this->success = false;
} else {
if (@is_writable($config_cascade['plainauth.users']['default'])) {
$this->cando['addUser'] = true;
$this->cando['delUser'] = true;
$this->cando['modLogin'] = true;
$this->cando['modPass'] = true;
$this->cando['modName'] = true;
$this->cando['modMail'] = true;
$this->cando['modGroups'] = true;
}
$this->cando['getUsers'] = true;
$this->cando['getUserCount'] = true;
$this->cando['getGroups'] = true;
}
$this->pregsplit_safe = version_compare(PCRE_VERSION, '6.7', '>=');
}
/**
* Check user+password
*
* Checks if the given user exists and the given
* plaintext password is correct
*
* @author Andreas Gohr <andi@splitbrain.org>
* @param string $user
* @param string $pass
* @return bool
*/
public function checkPass($user, $pass)
{
$userinfo = $this->getUserData($user);
if ($userinfo === false) return false;
return auth_verifyPassword($pass, $this->users[$user]['pass']);
}
/**
* Return user info
*
* Returns info about the given user needs to contain
* at least these fields:
*
* name string full name of the user
* mail string email addres of the user
* grps array list of groups the user is in
*
* @author Andreas Gohr <andi@splitbrain.org>
* @param string $user
* @param bool $requireGroups (optional) ignored by this plugin, grps info always supplied
* @return array|false
*/
public function getUserData($user, $requireGroups = true)
{
if ($this->users === null) $this->loadUserData();
return isset($this->users[$user]) ? $this->users[$user] : false;
}
/**
* Creates a string suitable for saving as a line
* in the file database
* (delimiters escaped, etc.)
*
* @param string $user
* @param string $pass
* @param string $name
* @param string $mail
* @param array $grps list of groups the user is in
* @return string
*/
protected function createUserLine($user, $pass, $name, $mail, $grps)
{
$groups = join(',', $grps);
$userline = array($user, $pass, $name, $mail, $groups);
$userline = str_replace('\\', '\\\\', $userline); // escape \ as \\
$userline = str_replace(':', '\\:', $userline); // escape : as \:
$userline = join(':', $userline)."\n";
return $userline;
}
/**
* Create a new User
*
* Returns false if the user already exists, null when an error
* occurred and true if everything went well.
*
* The new user will be added to the default group by this
* function if grps are not specified (default behaviour).
*
* @author Andreas Gohr <andi@splitbrain.org>
* @author Chris Smith <chris@jalakai.co.uk>
*
* @param string $user
* @param string $pwd
* @param string $name
* @param string $mail
* @param array $grps
* @return bool|null|string
*/
public function createUser($user, $pwd, $name, $mail, $grps = null)
{
global $conf;
global $config_cascade;
// user mustn't already exist
if ($this->getUserData($user) !== false) {
msg($this->getLang('userexists'), -1);
return false;
}
$pass = auth_cryptPassword($pwd);
// set default group if no groups specified
if (!is_array($grps)) $grps = array($conf['defaultgroup']);
// prepare user line
$userline = $this->createUserLine($user, $pass, $name, $mail, $grps);
if (!io_saveFile($config_cascade['plainauth.users']['default'], $userline, true)) {
msg($this->getLang('writefail'), -1);
return null;
}
$this->users[$user] = compact('pass', 'name', 'mail', 'grps');
return $pwd;
}
/**
* Modify user data
*
* @author Chris Smith <chris@jalakai.co.uk>
* @param string $user nick of the user to be changed
* @param array $changes array of field/value pairs to be changed (password will be clear text)
* @return bool
*/
public function modifyUser($user, $changes)
{
global $ACT;
global $config_cascade;
// sanity checks, user must already exist and there must be something to change
if (($userinfo = $this->getUserData($user)) === false) {
msg($this->getLang('usernotexists'), -1);
return false;
}
// don't modify protected users
if (!empty($userinfo['protected'])) {
msg(sprintf($this->getLang('protected'), hsc($user)), -1);
return false;
}
if (!is_array($changes) || !count($changes)) return true;
// update userinfo with new data, remembering to encrypt any password
$newuser = $user;
foreach ($changes as $field => $value) {
if ($field == 'user') {
$newuser = $value;
continue;
}
if ($field == 'pass') $value = auth_cryptPassword($value);
$userinfo[$field] = $value;
}
$userline = $this->createUserLine(
$newuser,
$userinfo['pass'],
$userinfo['name'],
$userinfo['mail'],
$userinfo['grps']
);
if (!io_replaceInFile($config_cascade['plainauth.users']['default'], '/^'.$user.':/', $userline, true)) {
msg('There was an error modifying your user data. You may need to register again.', -1);
// FIXME, io functions should be fail-safe so existing data isn't lost
$ACT = 'register';
return false;
}
if(isset($this->users[$user])) unset($this->users[$user]);
$this->users[$newuser] = $userinfo;
return true;
}
/**
* Remove one or more users from the list of registered users
*
* @author Christopher Smith <chris@jalakai.co.uk>
* @param array $users array of users to be deleted
* @return int the number of users deleted
*/
public function deleteUsers($users)
{
global $config_cascade;
if (!is_array($users) || empty($users)) return 0;
if ($this->users === null) $this->loadUserData();
$deleted = array();
foreach ($users as $user) {
// don't delete protected users
if (!empty($this->users[$user]['protected'])) {
msg(sprintf($this->getLang('protected'), hsc($user)), -1);
continue;
}
if (isset($this->users[$user])) $deleted[] = preg_quote($user, '/');
}
if (empty($deleted)) return 0;
$pattern = '/^('.join('|', $deleted).'):/';
if (!io_deleteFromFile($config_cascade['plainauth.users']['default'], $pattern, true)) {
msg($this->getLang('writefail'), -1);
return 0;
}
// reload the user list and count the difference
$count = count($this->users);
$this->loadUserData();
$count -= count($this->users);
return $count;
}
/**
* Return a count of the number of user which meet $filter criteria
*
* @author Chris Smith <chris@jalakai.co.uk>
*
* @param array $filter
* @return int
*/
public function getUserCount($filter = array())
{
if ($this->users === null) $this->loadUserData();
if (!count($filter)) return count($this->users);
$count = 0;
$this->constructPattern($filter);
foreach ($this->users as $user => $info) {
$count += $this->filter($user, $info);
}
return $count;
}
/**
* Bulk retrieval of user data
*
* @author Chris Smith <chris@jalakai.co.uk>
*
* @param int $start index of first user to be returned
* @param int $limit max number of users to be returned
* @param array $filter array of field/pattern pairs
* @return array userinfo (refer getUserData for internal userinfo details)
*/
public function retrieveUsers($start = 0, $limit = 0, $filter = array())
{
if ($this->users === null) $this->loadUserData();
Sort::ksort($this->users);
$i = 0;
$count = 0;
$out = array();
$this->constructPattern($filter);
foreach ($this->users as $user => $info) {
if ($this->filter($user, $info)) {
if ($i >= $start) {
$out[$user] = $info;
$count++;
if (($limit > 0) && ($count >= $limit)) break;
}
$i++;
}
}
return $out;
}
/**
* Retrieves groups.
* Loads complete user data into memory before searching for groups.
*
* @param int $start index of first group to be returned
* @param int $limit max number of groups to be returned
* @return array
*/
public function retrieveGroups($start = 0, $limit = 0)
{
$groups = [];
if ($this->users === null) $this->loadUserData();
foreach($this->users as $user => $info) {
$groups = array_merge($groups, array_diff($info['grps'], $groups));
}
Sort::ksort($groups);
if($limit > 0) {
return array_splice($groups, $start, $limit);
}
return array_splice($groups, $start);
}
/**
* Only valid pageid's (no namespaces) for usernames
*
* @param string $user
* @return string
*/
public function cleanUser($user)
{
global $conf;
return cleanID(str_replace(':', $conf['sepchar'], $user));
}
/**
* Only valid pageid's (no namespaces) for groupnames
*
* @param string $group
* @return string
*/
public function cleanGroup($group)
{
global $conf;
return cleanID(str_replace(':', $conf['sepchar'], $group));
}
/**
* Load all user data
*
* loads the user file into a datastructure
*
* @author Andreas Gohr <andi@splitbrain.org>
*/
protected function loadUserData()
{
global $config_cascade;
$this->users = $this->readUserFile($config_cascade['plainauth.users']['default']);
// support protected users
if (!empty($config_cascade['plainauth.users']['protected'])) {
$protected = $this->readUserFile($config_cascade['plainauth.users']['protected']);
foreach (array_keys($protected) as $key) {
$protected[$key]['protected'] = true;
}
$this->users = array_merge($this->users, $protected);
}
}
/**
* Read user data from given file
*
* ignores non existing files
*
* @param string $file the file to load data from
* @return array
*/
protected function readUserFile($file)
{
$users = array();
if (!file_exists($file)) return $users;
$lines = file($file);
foreach ($lines as $line) {
$line = preg_replace('/#.*$/', '', $line); //ignore comments
$line = trim($line);
if (empty($line)) continue;
$row = $this->splitUserData($line);
$row = str_replace('\\:', ':', $row);
$row = str_replace('\\\\', '\\', $row);
$groups = array_values(array_filter(explode(",", $row[4])));
$users[$row[0]]['pass'] = $row[1];
$users[$row[0]]['name'] = urldecode($row[2]);
$users[$row[0]]['mail'] = $row[3];
$users[$row[0]]['grps'] = $groups;
}
return $users;
}
/**
* Get the user line split into it's parts
*
* @param string $line
* @return string[]
*/
protected function splitUserData($line)
{
// due to a bug in PCRE 6.6, preg_split will fail with the regex we use here
// refer github issues 877 & 885
if ($this->pregsplit_safe) {
return preg_split('/(?<![^\\\\]\\\\)\:/', $line, 5); // allow for : escaped as \:
}
$row = array();
$piece = '';
$len = strlen($line);
for ($i=0; $i<$len; $i++) {
if ($line[$i]=='\\') {
$piece .= $line[$i];
$i++;
if ($i>=$len) break;
} elseif ($line[$i]==':') {
$row[] = $piece;
$piece = '';
continue;
}
$piece .= $line[$i];
}
$row[] = $piece;
return $row;
}
/**
* return true if $user + $info match $filter criteria, false otherwise
*
* @author Chris Smith <chris@jalakai.co.uk>
*
* @param string $user User login
* @param array $info User's userinfo array
* @return bool
*/
protected function filter($user, $info)
{
foreach ($this->pattern as $item => $pattern) {
if ($item == 'user') {
if (!preg_match($pattern, $user)) return false;
} elseif ($item == 'grps') {
if (!count(preg_grep($pattern, $info['grps']))) return false;
} else {
if (!preg_match($pattern, $info[$item])) return false;
}
}
return true;
}
/**
* construct a filter pattern
*
* @param array $filter
*/
protected function constructPattern($filter)
{
$this->pattern = array();
foreach ($filter as $item => $pattern) {
$this->pattern[$item] = '/'.str_replace('/', '\/', $pattern).'/i'; // allow regex characters
}
}
}
| mprins/dokuwiki | lib/plugins/authplain/auth.php | PHP | gpl-2.0 | 14,957 |
/*
* Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.graalvm.compiler.nodes.spi;
import org.graalvm.compiler.graph.iterators.NodeIterable;
import org.graalvm.compiler.nodes.FixedNodeInterface;
import org.graalvm.compiler.nodes.FrameState;
/**
* Interface for nodes which have {@link FrameState} nodes as input.
*/
public interface NodeWithState extends FixedNodeInterface {
default NodeIterable<FrameState> states() {
return asNode().inputs().filter(FrameState.class);
}
}
| md-5/jdk10 | src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.nodes/src/org/graalvm/compiler/nodes/spi/NodeWithState.java | Java | gpl-2.0 | 1,512 |
<?php
// $Id: box.tpl.php,v 1.3 2007/12/16 21:01:45 goba Exp $
/**
* @file box.tpl.php
*
* Theme implementation to display a box.
*
* Available variables:
* - $title: Box title.
* - $content: Box content.
*
* @see template_preprocess()
*/
?>
<div id="comment-form-wrapper">
<h3 id="comment-form-title"><?php print $title ?></h3>
<div class="content"><?php print $content ?></div>
</div>
| fourkitchens/2009.drupalcampaustin.com | sites/all/themes/drupalcampaustin/templates/box-comment_form.tpl.php | PHP | gpl-2.0 | 402 |
/* ----------------------------------------------------------------------
This is the
โโโ โโโ โโโโโโโ โโโโโโโ โโโโโโโ โโโ โโโโโโโโโโโโโโโโโโโโ
โโโ โโโโโโโโโโโ โโโโโโโโ โโโโโโโโ โโโ โโโโโโโโโโโโโโโโโโโโ
โโโ โโโโโโ โโโโโโโ โโโโโโโ โโโโโโโโโโโโ โโโ โโโโโโโโ
โโโ โโโโโโ โโโโโโ โโโโโโ โโโโโโโโโโโ โโโ โโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโ โโโ โโโโโโโโ
โโโโโโโโโโโ โโโโโโโ โโโโโโโ โโโโโโโ โโโ โโโ โโโ โโโโโโโโยฎ
DEM simulation engine, released by
DCS Computing Gmbh, Linz, Austria
http://www.dcs-computing.com, office@dcs-computing.com
LIGGGHTSยฎ is part of CFDEMยฎproject:
http://www.liggghts.com | http://www.cfdem.com
Core developer and main author:
Christoph Kloss, christoph.kloss@dcs-computing.com
LIGGGHTSยฎ is open-source, distributed under the terms of the GNU Public
License, version 2 or later. It is distributed in the hope that it will
be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. You should have
received a copy of the GNU General Public License along with LIGGGHTSยฎ.
If not, see http://www.gnu.org/licenses . See also top-level README
and LICENSE files.
LIGGGHTSยฎ and CFDEMยฎ are registered trade marks of DCS Computing GmbH,
the producer of the LIGGGHTSยฎ software and the CFDEMยฎcoupling software
See http://www.cfdem.com/terms-trademark-policy for details.
-------------------------------------------------------------------------
Contributing author and copyright for this file:
This file is from LAMMPS
LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator
http://lammps.sandia.gov, Sandia National Laboratories
Steve Plimpton, sjplimp@sandia.gov
Copyright (2003) Sandia Corporation. Under the terms of Contract
DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains
certain rights in this software. This software is distributed under
the GNU General Public License.
------------------------------------------------------------------------- */
// Park/Miller RNG
#include "math.h"
#include "random_park.h"
#include "error.h"
using namespace LAMMPS_NS;
#define IA 16807
#define IM 2147483647
#define AM (1.0/IM)
#define IQ 127773
#define IR 2836
/* ---------------------------------------------------------------------- */
RanPark::RanPark(LAMMPS *lmp, int seed_init) : Pointers(lmp)
{
if (seed_init <= 0)
error->one(FLERR,"Invalid seed for Park random # generator");
seed = seed_init;
save = 0;
}
/* ----------------------------------------------------------------------
uniform RN
------------------------------------------------------------------------- */
double RanPark::uniform()
{
int k = seed/IQ;
seed = IA*(seed-k*IQ) - IR*k;
if (seed < 0) seed += IM;
double ans = AM*seed;
return ans;
}
/* ----------------------------------------------------------------------
gaussian RN
------------------------------------------------------------------------- */
double RanPark::gaussian()
{
double first,v1,v2,rsq,fac;
if (!save) {
int again = 1;
while (again) {
v1 = 2.0*uniform()-1.0;
v2 = 2.0*uniform()-1.0;
rsq = v1*v1 + v2*v2;
if (rsq < 1.0 && rsq != 0.0) again = 0;
}
fac = sqrt(-2.0*log(rsq)/rsq);
second = v1*fac;
first = v2*fac;
save = 1;
} else {
first = second;
save = 0;
}
return first;
}
/* ---------------------------------------------------------------------- */
void RanPark::reset(int seed_init)
{
if (seed_init <= 0)
error->all(FLERR,"Invalid seed for Park random # generator");
seed = seed_init;
save = 0;
}
/* ----------------------------------------------------------------------
reset the seed based on atom coords and ibase = caller seed
use hash function, treating user seed and coords as sequence of input ints
this is Jenkins One-at-a-time hash, see Wikipedia entry on hash tables
------------------------------------------------------------------------- */
void RanPark::reset(int ibase, double *coord)
{
int i;
char *str = (char *) &ibase;
int n = sizeof(int);
unsigned int hash = 0;
for (i = 0; i < n; i++) {
hash += str[i];
hash += (hash << 10);
hash ^= (hash >> 6);
}
str = (char *) coord;
n = 3 * sizeof(double);
for (i = 0; i < n; i++) {
hash += str[i];
hash += (hash << 10);
hash ^= (hash >> 6);
}
hash += (hash << 3);
hash ^= (hash >> 11);
hash += (hash << 15);
// keep 31 bits of unsigned int as new seed
// do not allow seed = 0, since will cause hang in gaussian()
seed = hash & 0x7ffffff;
if (!seed) seed = 1;
// warm up the RNG
for (i = 0; i < 5; i++) uniform();
save = 0;
}
/* ---------------------------------------------------------------------- */
int RanPark::state()
{
return seed;
}
| dineshram2010/Enhanced-Heat-Exchanger-Design-using-Constructal-Networks | src/random_park.cpp | C++ | gpl-2.0 | 5,560 |
# -*- coding: utf-8 -*-
"""
***************************************************************************
ProcessingResults.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************
"""
__author__ = 'Victor Olaya'
__date__ = 'August 2012'
__copyright__ = '(C) 2012, Victor Olaya'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'
from qgis.PyQt.QtCore import QObject, pyqtSignal
class ProcessingResults(QObject):
resultAdded = pyqtSignal()
results = []
def addResult(self, icon, name, result):
self.results.append(Result(icon, name, result))
self.resultAdded.emit()
def getResults(self):
return self.results
class Result:
def __init__(self, icon, name, filename):
self.icon = icon
self.name = name
self.filename = filename
resultsList = ProcessingResults()
| medspx/QGIS | python/plugins/processing/core/ProcessingResults.py | Python | gpl-2.0 | 1,611 |
/* -*- mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: t -*- */
/* AbiSource
*
* Copyright (C) 2007 Philippe Milot <PhilMilot@gmail.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*/
// Class definition include
#include <OXMLi_StreamListener.h>
// Internal includes
#include <OXMLi_Types.h>
#include <OXMLi_ListenerState.h>
#include <OXMLi_ListenerState_Common.h>
#include <OXMLi_ListenerState_MainDocument.h>
#include <OXMLi_ListenerState_Styles.h>
#include <OXMLi_ListenerState_HdrFtr.h>
#include <OXMLi_ListenerState_Theme.h>
#include <OXMLi_ListenerState_DocSettings.h>
#include <OXMLi_ListenerState_Numbering.h>
#include <OXMLi_ListenerState_Table.h>
#include <OXMLi_ListenerState_Field.h>
#include <OXMLi_ListenerState_Footnote.h>
#include <OXMLi_ListenerState_Endnote.h>
#include <OXMLi_ListenerState_Image.h>
#include <OXMLi_ListenerState_Textbox.h>
#include <OXMLi_ListenerState_Valid.h>
// AbiWord includes
#include <ut_types.h>
#include <ut_assert.h>
OXMLi_StreamListener::OXMLi_StreamListener() :
m_pElemStack(new OXMLi_ElementStack()),
m_pSectStack(new OXMLi_SectionStack()),
m_context(new OXMLi_ContextVector()),
m_parseStatus(UT_OK),
m_namespaces(new OXMLi_Namespace_Common())
{
clearStates();
}
OXMLi_StreamListener::~OXMLi_StreamListener()
{
DELETEP(m_pElemStack);
DELETEP(m_pSectStack);
DELETEP(m_namespaces);
DELETEP(m_context);
clearStates();
}
void OXMLi_StreamListener::setupStates(OXML_PartType type, const char * partId)
{
OXMLi_ListenerState * state = NULL;
m_namespaces->reset();
//this has to be the first pushed state since it checks the validity of the input
state = new OXMLi_ListenerState_Valid();
this->pushState(state);
switch (type) {
case DOCUMENT_PART:
state = new OXMLi_ListenerState_MainDocument();
this->pushState(state);
state = new OXMLi_ListenerState_Common();
this->pushState(state);
state = new OXMLi_ListenerState_Field();
this->pushState(state);
state = new OXMLi_ListenerState_Table();
this->pushState(state);
//the ordering is important here: image has to come before textbox
//because both image and textbox are children of <shape> and
//rqst->handle flag is only set in textbox, image only sniffs.
state = new OXMLi_ListenerState_Image();
this->pushState(state);
state = new OXMLi_ListenerState_Textbox();
this->pushState(state);
break;
case STYLES_PART:
state = new OXMLi_ListenerState_Styles();
this->pushState(state);
state = new OXMLi_ListenerState_Common();
this->pushState(state);
state = new OXMLi_ListenerState_Table();
this->pushState(state);
break;
case THEME_PART:
state = new OXMLi_ListenerState_Theme();
this->pushState(state);
break;
case DOCSETTINGS_PART:
state = new OXMLi_ListenerState_DocSettings();
this->pushState(state);
break;
case FOOTER_PART: //fall through
case HEADER_PART:
state = new OXMLi_ListenerState_HdrFtr(partId);
this->pushState(state);
state = new OXMLi_ListenerState_Common();
this->pushState(state);
state = new OXMLi_ListenerState_Field();
this->pushState(state);
break;
case FOOTNOTES_PART:
state = new OXMLi_ListenerState_Footnote();
this->pushState(state);
state = new OXMLi_ListenerState_Common();
this->pushState(state);
break;
case ENDNOTES_PART:
state = new OXMLi_ListenerState_Endnote();
this->pushState(state);
state = new OXMLi_ListenerState_Common();
this->pushState(state);
break;
case NUMBERING_PART:
state = new OXMLi_ListenerState_Numbering();
this->pushState(state);
state = new OXMLi_ListenerState_Common();
this->pushState(state);
break;
default:
return; //Nothing else is supported at the moment
}
}
void OXMLi_StreamListener::pushState(OXMLi_ListenerState* s)
{
UT_return_if_fail(s != NULL);
s->setListener(this);
m_states.push_back(s);
}
void OXMLi_StreamListener::popState()
{
UT_return_if_fail(!m_states.empty())
DELETEP(m_states.back());
m_states.pop_back();
}
void OXMLi_StreamListener::clearStates()
{
while (!m_states.empty())
{
DELETEP(m_states.back());
m_states.pop_back();
}
}
void OXMLi_StreamListener::startElement (const gchar* pName, const gchar** ppAtts)
{
UT_return_if_fail(!m_states.empty() || m_parseStatus == UT_OK);
std::map<std::string, std::string>* atts = m_namespaces->processAttributes(pName, ppAtts);
std::string name = m_namespaces->processName(pName);
OXMLi_StartElementRequest rqst = { name, atts, m_pElemStack, m_pSectStack, m_context, false, false };
std::list<OXMLi_ListenerState*>::iterator it=m_states.begin();
do {
(*it)->startElement(&rqst);
++it;
if(!rqst.valid)
{
xxx_UT_DEBUGMSG(("FRT:Invalid startElement request: [%s]\n", rqst.pName.c_str()));
}
} while ( this->getStatus() == UT_OK && it!=m_states.end() && !rqst.handled);
m_context->push_back(name);
}
void OXMLi_StreamListener::endElement (const gchar* pName)
{
UT_return_if_fail(!m_states.empty() || m_parseStatus == UT_OK);
m_context->pop_back();
std::string name = m_namespaces->processName(pName);
OXMLi_EndElementRequest rqst = { name, m_pElemStack, m_pSectStack, m_context, false, false };
std::list<OXMLi_ListenerState*>::iterator it=m_states.begin();
do {
(*it)->endElement(&rqst);
++it;
if(!rqst.valid)
{
xxx_UT_DEBUGMSG(("FRT:Invalid endElement request: [%s]\n", rqst.pName.c_str()));
}
} while ( this->getStatus() == UT_OK && it!=m_states.end() && !rqst.handled);
}
void OXMLi_StreamListener::charData (const gchar* pBuffer, int length)
{
UT_return_if_fail(!m_states.empty() || m_parseStatus == UT_OK);
OXMLi_CharDataRequest rqst = { pBuffer, length, m_pElemStack, m_context, false, false };
std::list<OXMLi_ListenerState*>::iterator it=m_states.begin();
do {
(*it)->charData(&rqst);
++it;
if(!rqst.valid)
{
UT_DEBUGMSG(("FRT:Invalid charData request\n"));
}
} while ( this->getStatus() == UT_OK && it!=m_states.end() && !rqst.handled);
}
| Distrotech/abiword | plugins/openxml/imp/xp/OXMLi_StreamListener.cpp | C++ | gpl-2.0 | 6,589 |
<?php
/**
* The Template for displaying all single posts.
*
* @package WordPress
* @subpackage Corporate WPExplorer Theme
* @since Corporate 1.0
*/
get_header(); ?>
<?php while ( have_posts() ) : the_post(); ?>
<div id="primary" class="content-area clr">
<div id="content" class="site-content left-content clr" role="main">
<article>
<header class="page-header clr">
<h1 class="page-header-title"><?php the_title(); ?></h1>
</header><!-- .page-header -->
<div class="entry clr">
<?php the_content(); ?>
</div><!-- .entry -->
<footer class="entry-footer">
<?php edit_post_link( __( 'Edit Post', 'wpex' ), '<span class="edit-link clr">', '</span>' ); ?>
</footer><!-- .entry-footer -->
</article>
<?php
// Comments
if ( get_theme_mod( 'wpex_staff_comments') ) {
comments_template();
} ?>
<?php wp_link_pages( array( 'before' => '<div class="page-links clr">', 'after' => '</div>', 'link_before' => '<span>', 'link_after' => '</span>' ) ); ?>
</div><!-- #content -->
<?php get_sidebar(); ?>
</div><!-- #primary -->
<?php endwhile; ?>
<?php get_footer(); ?> | wuxuejian/xzluomen | wp-content/themes/wpex-corporate/single-staff.php | PHP | gpl-2.0 | 1,133 |
<?php
/*
* @version $Id: networkportinjection.class.php 777 2013-07-17 07:53:45Z yllen $
LICENSE
This file is part of the datainjection plugin.
Datainjection plugin is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
Datainjection plugin is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with datainjection. If not, see <http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------
@package datainjection
@author the datainjection plugin team
@copyright Copyright (c) 2010-2013 Datainjection plugin team
@license GPLv2+
http://www.gnu.org/licenses/gpl.txt
@link https://forge.indepnet.net/projects/datainjection
@link http://www.glpi-project.org/
@since 2009
---------------------------------------------------------------------- */
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
class PluginDatainjectionNetworkportInjection extends NetworkPort
implements PluginDatainjectionInjectionInterface {
static function getTable() {
$parenttype = get_parent_class();
return $parenttype::getTable();
}
function isPrimaryType() {
return false;
}
function connectedTo() {
global $CFG_GLPI;
return $CFG_GLPI["networkport_types"];
}
/**
* @see plugins/datainjection/inc/PluginDatainjectionInjectionInterface::getOptions()
**/
function getOptions($primary_type='') {
$tab = Search::getOptions(get_parent_class($this));
$tab[4]['checktype'] = 'mac';
//To manage vlans : relies on a CommonDBRelation object !
$tab[51]['name'] = sprintf(__('%1$s: %2$s'), __('Connected to'), __('Device name'));
$tab[51]['field'] = 'netname';
$tab[51]['table'] = getTableForItemType('NetworkPort');
$tab[51]['linkfield'] = "netname";
$tab[51]['injectable'] = true;
$tab[51]['displaytype'] = 'text';
$tab[51]['checktype'] = 'text';
$tab[52]['name'] = sprintf(__('%1$s: %2$s'), __('Connected to'), __('Port number'));
$tab[52]['field'] = 'netport';
$tab[52]['table'] = getTableForItemType('NetworkPort');
$tab[52]['linkfield'] = "netport";
$tab[52]['injectable'] = true;
$tab[52]['displaytype'] = 'text';
$tab[52]['checktype'] = 'text';
$tab[53]['name'] = sprintf(__('%1$s: %2$s'), __('Connected to'),
__('Port MAC address', 'datainjection'));
$tab[53]['field'] = 'netmac';
$tab[53]['table'] = getTableForItemType('NetworkPort');
$tab[53]['linkfield'] = "netmac";
$tab[53]['injectable'] = true;
$tab[53]['displaytype'] = 'text';
$tab[53]['checktype'] = 'text';
//To manage vlans : relies on a CommonDBRelation object !
$tab[100]['name'] = __('VLAN');
$tab[100]['field'] = 'name';
$tab[100]['table'] = getTableForItemType('Vlan');
$tab[100]['linkfield'] = getForeignKeyFieldForTable($tab[100]['table']);
$tab[100]['displaytype'] = 'relation';
$tab[100]['relationclass'] = 'NetworkPort_Vlan';
$tab[100]['storevaluein'] = $tab[100]['linkfield'];
$blacklist = PluginDatainjectionCommonInjectionLib::getBlacklistedOptions(get_parent_class($this));
$notimportable = array(20, 21);
$options['ignore_fields'] = array_merge($blacklist, $notimportable);
$options['displaytype'] = array("dropdown" => array(9),
"multiline_text" => array(16),
"instantiation_type" => array(87));
return PluginDatainjectionCommonInjectionLib::addToSearchOptions($tab, $options, $this);
}
/**
* @param $primary_type
* @param $values
**/
function addSpecificNeededFields($primary_type,$values) {
if (isset($values[$primary_type]['instantiation_type'])) {
$fields['instantiation_type'] = $values[$primary_type]['instantiation_type'];
} else {
$fields['instantiation_type'] = "NetworkPortEthernet";
}
return $fields;
}
/**
* @param $info array
* @param $option array
**/
function showAdditionalInformation($info=array(), $option=array()) {
$name = "info[".$option['linkfield']."]";
switch ($option['displaytype']) {
case 'instantiation_type' :
$instantiations = array();
$class = get_parent_class($this);
foreach ($class::getNetworkPortInstantiations() as $inst_type) {
if (call_user_func(array($inst_type, 'canCreate'))) {
$instantiations[$inst_type] = call_user_func(array($inst_type, 'getTypeName'));
}
}
Dropdown::showFromArray('instantiation_type', $instantiations,
array('value' => 'NetworkPortEthernet'));
break;
default:
break;
}
}
/**
* @see plugins/datainjection/inc/PluginDatainjectionInjectionInterface::addOrUpdateObject()
**/
function addOrUpdateObject($values=array(), $options=array()) {
$lib = new PluginDatainjectionCommonInjectionLib($this, $values, $options);
$lib->processAddOrUpdate();
return $lib->getInjectionResults();
}
/**
* @param $fields_toinject array
* @param $options array
**/
function checkPresent($fields_toinject=array(), $options=array()) {
return $this->getUnicityRequest($fields_toinject['NetworkPort'], $options['checks']);
}
/**
* @param $fields_toinject
* @param $options
**/
function checkParameters($fields_toinject, $options) {
$fields_tocheck = array();
switch ($options['checks']['port_unicity']) {
case PluginDatainjectionCommonInjectionLib::UNICITY_NETPORT_LOGICAL_NUMBER :
$fields_tocheck = array('logical_number');
break;
case PluginDatainjectionCommonInjectionLib::UNICITY_NETPORT_LOGICAL_NUMBER_MAC :
$fields_tocheck = array('logical_number', 'mac');
break;
case PluginDatainjectionCommonInjectionLib::UNICITY_NETPORT_LOGICAL_NUMBER_NAME :
$fields_tocheck = array('logical_number', 'name');
break;
case PluginDatainjectionCommonInjectionLib::UNICITY_NETPORT_LOGICAL_NUMBER_NAME_MAC :
$fields_tocheck = array('logical_number', 'mac', 'name');
break;
case PluginDatainjectionCommonInjectionLib::UNICITY_NETPORT_MACADDRESS :
$fields_tocheck = array('mac');
break;
case PluginDatainjectionCommonInjectionLib::UNICITY_NETPORT_NAME :
$fields_tocheck = array('name');
break;
}
$check_status = true;
foreach ($fields_tocheck as $field) {
if (!isset($fields_toinject[$field])
|| ($fields_toinject[$field] == PluginDatainjectionCommonInjectionLib::EMPTY_VALUE)) {
$check_status = false;
}
}
return $check_status;
}
/**
* Build where sql request to look for a network port
*
* @param $fields_toinject array the fields to insert into DB
* @param $options array
*
* @return the sql where clause
**/
function getUnicityRequest($fields_toinject=array(), $options=array()) {
$where = "";
switch ($options['port_unicity']) {
case PluginDatainjectionCommonInjectionLib::UNICITY_NETPORT_LOGICAL_NUMBER :
$where .= " AND `logical_number` = '".(isset ($fields_toinject["logical_number"])
? $fields_toinject["logical_number"] : '')."'";
break;
case PluginDatainjectionCommonInjectionLib::UNICITY_NETPORT_LOGICAL_NUMBER_MAC :
$where .= " AND `logical_number` = '".(isset ($fields_toinject["logical_number"])
? $fields_toinject["logical_number"] : '')."'
AND `mac` = '".(isset ($fields_toinject["mac"])
? $fields_toinject["mac"] : '')."'";
break;
case PluginDatainjectionCommonInjectionLib::UNICITY_NETPORT_LOGICAL_NUMBER_NAME :
$where .= " AND `logical_number` = '".(isset ($fields_toinject["logical_number"])
? $fields_toinject["logical_number"] : '')."'
AND `name` = '".(isset ($fields_toinject["name"])
? $fields_toinject["name"] : '')."'";
break;
case PluginDatainjectionCommonInjectionLib::UNICITY_NETPORT_LOGICAL_NUMBER_NAME_MAC :
$where .= " AND `logical_number` = '".(isset ($fields_toinject["logical_number"])
? $fields_toinject["logical_number"] : '')."'
AND `name` = '".(isset ($fields_toinject["name"])
? $fields_toinject["name"] : '')."'
AND `mac` = '".(isset ($fields_toinject["mac"])
? $fields_toinject["mac"] : '')."'";
break;
case PluginDatainjectionCommonInjectionLib::UNICITY_NETPORT_MACADDRESS :
$where .= " AND `mac` = '".(isset ($fields_toinject["mac"])
? $fields_toinject["mac"] : '')."'";
break;
case PluginDatainjectionCommonInjectionLib::UNICITY_NETPORT_NAME :
$where .= " AND `name` = '".(isset ($fields_toinject["name"])
? $fields_toinject["name"] : '')."'";
break;
}
return $where;
}
/**
* Check if at least mac or ip is defined otherwise block import
*
* @param $values array the values to inject
*
* @return true if check ok, false if not ok
**/
function lastCheck($values=array()) {
if ((!isset($values['NetworkPort']['name']) || empty($values['NetworkPort']['name']))
&& (!isset($values['NetworkPort']['mac']) || empty($values['NetworkPort']['mac']))
&& (!isset($values['NetworkPort']['instantiation_type'])
|| empty($values['NetworkPort']['instantiation_type']))) {
return false;
}
return true;
}
/**
* @param $values
* @param $add (true by default)
* @param $rights array
**/
function processAfterInsertOrUpdate($values, $add=true, $rights=array()) {
global $DB;
//Should the port be connected to another one ?
$use_name = (isset ($values['NetworkPort']["netname"])
|| !empty ($values['NetworkPort']["netname"]));
$use_logical_number = (isset ($values['NetworkPort']["netport"])
|| !empty ($values['NetworkPort']["netport"]));
$use_mac = (isset ($values['NetworkPort']["netmac"])
|| !empty ($values['NetworkPort']["netmac"]));
if (!$use_name && !$use_logical_number && !$use_mac) {
return false;
}
// Find port in database
$sql = "SELECT `glpi_networkports`.`id`
FROM `glpi_networkports`, `glpi_networkequipments`
WHERE `glpi_networkports`.`itemtype`='NetworkEquipment'
AND `glpi_networkports`.`items_id` = `glpi_networkequipments`.`id`
AND `glpi_networkequipments`.`is_template` = '0'
AND `glpi_networkequipments`.`entities_id`
= '".$values['NetworkPort']["entities_id"]."'";
if ($use_name) {
$sql .= " AND `glpi_networkequipments`.`name` = '".$values['NetworkPort']["netname"]."'";
}
if ($use_logical_number) {
$sql .= " AND `glpi_networkports`.`logical_number` = '".$values['NetworkPort']["netport"]."'";
}
if ($use_mac){
$sql .= " AND `glpi_networkports`.`mac` = '".$values['NetworkPort']["netmac"]."'";
}
$res = $DB->query($sql);
//if at least one parameter is given
$nb = $DB->numrows($res);
if ($nb == 1) {
//Get data for this port
$netport = $DB->fetch_array($res);
$netport_netport = new NetworkPort_NetworkPort();
//If this port already connected to another one ?
if (!$netport_netport->getOppositeContact($netport['id'])) {
//No, add a new port to port connection
$tmp['networkports_id_1'] = $values['NetworkPort']['id'];
$tmp['networkports_id_2'] = $netport['id'];
$netport_netport->add($tmp);
}
} //TODO add injection warning if no port found or more than one
}
}
?> | euqip/glpi-smartcities | plugins/datainjection/inc/networkportinjection.class.php | PHP | gpl-2.0 | 13,483 |