diff --git "a/000000.jsonl" "b/000000.jsonl" --- "a/000000.jsonl" +++ "b/000000.jsonl" @@ -1,88 +1,18 @@ -{"repo": "ib/xarchiver", "pr_number": 174, "title": "Don't make empty 'NEWS' or 'AUTHORS' files", "state": "closed", "merged_at": null, "additions": 2, "deletions": 4, "files_changed": ["autogen.sh"], "files_before": {"autogen.sh": "#!/bin/sh\n\ntest \"$BASH\" && set -o pipefail\n\necho > AUTHORS\necho > NEWS\nmkdir m4\n\necho -n \"Creating the build system... \"\n\nintltoolize --copy --force --automake || exit\nlibtoolize --copy --force --quiet || exit\naclocal || exit\nautoheader || exit\nautomake --copy --force-missing --add-missing --gnu 2>&1 | sed \"/installing/d\" || exit\nautoconf -Wno-obsolete || exit\n\necho \"done.\"\n\n# clean up in order to keep repository small\n# (will be needed if 'make dist' is used though)\nrm AUTHORS NEWS INSTALL aclocal.m4 intltool-extract.in intltool-merge.in intltool-update.in\nrm -f config.h.in~ configure~\nrm -r autom4te.cache m4\n"}, "files_after": {"autogen.sh": "#!/bin/sh\n\ntest \"$BASH\" && set -o pipefail\n\nmkdir m4\n\necho -n \"Creating the build system... \"\n\nintltoolize --copy --force --automake || exit\nlibtoolize --copy --force --quiet || exit\naclocal || exit\nautoheader || exit\nautomake --copy --force-missing --add-missing --gnu 2>&1 | sed \"/installing/d\" || exit\nautoconf -Wno-obsolete || exit\n\necho \"done.\"\n\n# clean up in order to keep repository small\n# (will be needed if 'make dist' is used though)\nrm INSTALL aclocal.m4 intltool-extract.in intltool-merge.in intltool-update.in\nrm -f config.h.in~ configure~\nrm -r autom4te.cache m4\n"}} -{"repo": "collectiveidea/migration_test_helper", "pr_number": 6, "title": "Rails 3.1 fixes", "state": "closed", "merged_at": null, "additions": 17, "deletions": 21, "files_changed": ["init.rb", "lib/migration_test_helper.rb", "test/helper.rb", "test/migration_test_helper_test.rb"], "files_before": {"init.rb": "if RAILS_ENV == 'test'\n require 'migration_test_helper'\n require 'test/unit'\n Test::Unit::TestCase.class_eval do\n include MigrationTestHelper\n end\nend\n", "lib/migration_test_helper.rb": "#--\n# Copyright (c) 2007 Micah Alles, Patrick Bacon, David Crosby\n# \n# Permission is hereby granted, free of charge, to any person obtaining\n# a copy of this software and associated documentation files (the\n# \"Software\"), to deal in the Software without restriction, including\n# without limitation the rights to use, copy, modify, merge, publish,\n# distribute, sublicense, and/or sell copies of the Software, and to\n# permit persons to whom the Software is furnished to do so, subject to\n# the following conditions:\n# \n# The above copyright notice and this permission notice shall be\n# included in all copies or substantial portions of the Software.\n# \n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n#++\n\nrequire 'test/unit/assertions'\n\nmodule MigrationTestHelper \n def self.migration_dir\n @migration_dir || File.expand_path(RAILS_ROOT + '/db/migrate')\n end\n\n #\n # sets the directory in which the migrations reside to be run with migrate\n #\n def self.migration_dir=(new_dir)\n @migration_dir = new_dir\n end\n\n #\n # verifies the schema exactly matches the one specified (schema_info does not have to be specified)\n # \n # assert_schema do |s|\n # s.table :dogs do |t|\n # t.column :id, :integer, :default => 2\n # t.column :name, :string\n # end\n # end\n #\n def assert_schema\n schema = Schema.new\n yield schema\n schema.verify\n end\n\n #\n # verifies a single table exactly matches the one specified\n # \n # assert_table :dogs do |t|\n # t.column :id, :integer, :default => 2\n # t.column :name, :string\n # end\n #\n def assert_table(name)\n table = Table.new(name)\n yield table\n table.verify\n end\n\n #\n # drops all tables in the database\n # \n def drop_all_tables\n ActiveRecord::Base.connection.tables.each do |table|\n ActiveRecord::Base.connection.drop_table(table)\n end\n end\n\n #\n # executes your migrations\n #\n # migrate # same as rake db:migrate\n #\n # Options are:\n # * :version - version to migrate to (same as VERSION=.. option to rake db:migrate)\n # * :verbose - print migration status messages to STDOUT, defaults to false\n # \n def migrate(opts={})\n old_verbose = ActiveRecord::Migration.verbose\n ActiveRecord::Migration.verbose = opts[:verbose].nil? ? false : opts[:verbose]\n version = opts[:version] ? opts[:version].to_i : nil\n ActiveRecord::Migrator.migrate(MigrationTestHelper.migration_dir, version)\n ensure\n ActiveRecord::Migration.verbose = old_verbose\n end\n\n module Connection #:nodoc:\n def conn\n ActiveRecord::Base.connection\n end\n end\n\n class Schema\n include Connection\n include Test::Unit::Assertions\n\n def initialize #:nodoc:\n @tables = []\n end\n\n def table(name)\n table = Table.new(name)\n yield table\n table.verify\n @tables << table\n end\n\n def verify #:nodoc:\n actual_tables = conn.tables.reject {|t| t == 'schema_info' || t == 'schema_migrations'}\n expected_tables = @tables.map {|t| t.name }\n assert_equal expected_tables.sort, actual_tables.sort, 'wrong tables in schema'\n end\n end\n\n class Table\n include Connection\n include Test::Unit::Assertions\n attr_reader :name\n\n def initialize(name) #:nodoc:\n @name = name.to_s\n @columns = []\n @indexes = []\n assert conn.tables.include?(@name), \"table <#{@name}> not found in schema\"\n end\n\n def column(colname,type,options={})\n colname = colname.to_s\n @columns << colname\n col = conn.columns(name).find {|c| c.name == colname }\n assert_not_nil col, \"column <#{colname}> not found in table <#{self.name}>\"\n assert_equal type, col.type, \"wrong type for column <#{colname}> in table <#{name}>\"\n options.each do |k,v|\n k = k.to_sym; actual = col.send(k); actual = actual.is_a?(String) ? actual.sub(/'$/,'').sub(/^'/,'') : actual\n assert_equal v, actual, \"column <#{colname}> in table <#{name}> has wrong :#{k}\"\n end\n end\n\n def index(column_name, options = {})\n @indexes << \"name <#{options[:name]}> columns <#{Array(column_name).join(\",\")}> unique <#{options[:unique] == true}>\" \n end\n\n def verify #:nodoc:\n actual_columns = conn.columns(name).map {|c| c.name }\n assert_equal @columns.sort, actual_columns.sort, \"wrong columns for table: <#{name}>\"\n\n actual_indexes = conn.indexes(@name).collect { |i| \"name <#{i.name}> columns <#{i.columns.join(\",\")}> unique <#{i.unique}>\" }\n assert_equal @indexes.sort, actual_indexes.sort, \"wrong indexes for table: <#{name}>\"\n end\n \n def method_missing(type, *columns)\n options = columns.extract_options!\n columns.each do |colname|\n column colname, type, options\n end\n end\n end\nend\n", "test/helper.rb": "ENV[\"RAILS_ENV\"] = \"test\"\nrequire File.expand_path(File.dirname(__FILE__) + '/../../../../config/environment')\nrequire 'logger'\nrequire 'fileutils'\nrequire 'test_help'\n\nplugin_path = RAILS_ROOT + \"/vendor/plugins/migration_test_helper\"\n\nconfig_location = File.expand_path(plugin_path + \"/test/config/database.yml\")\n\nconfig = YAML::load(ERB.new(IO.read(config_location)).result)\nActiveRecord::Base.logger = Logger.new(plugin_path + \"/test/log/test.log\")\nActiveRecord::Base.establish_connection(config['test'])\n\nTest::Unit::TestCase.fixture_path = plugin_path + \"/test/fixtures/\"\n\n$LOAD_PATH.unshift(Test::Unit::TestCase.fixture_path)\n\nclass Test::Unit::TestCase\n include FileUtils\n def plugin_path(path)\n File.expand_path(File.dirname(__FILE__) + '/../' + path) \n end\n\n def load_default_schema\n ActiveRecord::Migration.suppress_messages do\n schema_file = plugin_path(\"/test/db/schema.rb\")\n load(schema_file) if File.exist?(schema_file)\n end\n end\n\n def migration_test_path\n File.expand_path(RAILS_ROOT + \"/test/migration\")\n end\n\n def run_in_rails_root(command)\n cd RAILS_ROOT do\n @output = `#{command}`\n end\n end\n\n def check_output(string_or_regexp)\n assert_not_nil @output, \"No output collected\"\n case string_or_regexp\n when String\n assert_match(/#{Regexp.escape(string_or_regexp)}/, @output)\n when Regexp\n assert_match(string_or_regexp, @output)\n else\n raise \"Can't check output using oddball object #{string_or_regexp.inspect}\"\n end\n end\n \n def rm_migration_test_path\n rm_rf migration_test_path\n end\n\n def self.should(behave,&block)\n return unless running_in_foundry\n @context ||= nil\n @context_setup ||= nil\n context_string = @context.nil? ? '' : @context + ' '\n mname = \"test #{context_string}should #{behave}\"\n context_setup = @context_setup\n if block_given?\n define_method(mname) do\n instance_eval(&context_setup) unless context_setup.nil?\n instance_eval(&block)\n end \n else\n puts \">>> UNIMPLEMENTED CASE: #{name.sub(/Test$/,'')} should #{behave}\"\n end\n end\n\nend\n", "test/migration_test_helper_test.rb": "require File.expand_path(File.dirname(__FILE__) + '/helper') \n\nclass MigrationTestHelperTest < Test::Unit::TestCase\n\n def setup\n load_default_schema\n MigrationTestHelper.migration_dir = plugin_path('test/db/migrate_good')\n end\n\n #\n # HELPERS\n #\n def see_failure(pattern='')\n err = assert_raise(Test::Unit::AssertionFailedError) do\n yield\n end\n assert_match(/#{pattern}/mi, err.message) \n end\n\n def see_no_failure\n assert_nothing_raised do\n yield\n end\n end\n\n def declare_columns_on_table(t)\n t.column :id, :integer\n t.column :tail, :string, :default => 'top dog', :limit => 187\n end\n \n #\n # TESTS\n #\n def test_assert_schema_should_not_fail_if_schema_is_matched\n see_no_failure do\n assert_schema do |s|\n s.table :dogs do |t|\n\t declare_columns_on_table(t)\n\t t.index :tail, :name => 'index_tail_on_dogs'\n end\n\n end\n end\n end\n\n def test_assert_schema_should_fail_if_a_table_is_not_specified\n see_failure 'wrong tables in schema.*dogs' do\n assert_schema do |s|\n end\n end\n end\n\n def test_assert_schema_should_fail_if_a_table_is_not_found\n see_failure 'table not found in schema' do\n assert_schema do |s|\n s.table :things do |t|\n t.column :id, :integer\n end\n end\n end\n end\n\n def test_assert_schema_should_fail_if_a_column_is_not_specified\n see_failure 'wrong columns for table.*dogs.*tail' do\n assert_schema do |s|\n s.table :dogs do |t|\n t.column :id, :integer\n end\n end\n end\n end\n\n def test_assert_schema_should_fail_if_a_column_is_not_found\n see_failure 'column not found in table ' do\n assert_schema do |s|\n s.table :dogs do |t|\n t.column :id, :integer\n t.column :tail, :string\n t.column :legs, :integer\n end\n end\n end\n end\n\n def test_assert_schema_should_fail_if_wrong_options_not_specified\n see_failure 'column in table has wrong :default' do\n assert_table :dogs do |t|\n t.column :id, :integer\n t.column :tail, :string, :default => \"blah\"\n end\n end\n end\n\n def test_assert_table_should_not_fail_if_table_is_matched\n see_no_failure do\n assert_table :dogs do |t|\n declare_columns_on_table(t)\n\tt.index :tail, :name => 'index_tail_on_dogs'\n end\n end\n end\n\n def test_assert_table_should_fail_if_a_table_is_not_found\n see_failure 'table not found in schema' do\n assert_table :things do |t|\n t.column :id, :integer\n end\n end\n end\n\n def test_assert_table_should_fail_if_a_column_is_not_specified\n see_failure 'wrong columns for table.*dogs.*tail' do\n assert_table :dogs do |t|\n t.column :id, :integer\n end\n end\n end\n\n def test_assert_table_should_fail_if_a_column_is_not_found\n see_failure 'column not found in table ' do\n assert_table :dogs do |t|\n t.column :id, :integer\n t.column :tail, :string\n t.column :legs, :integer\n end\n end\n end\n\n def test_assert_table_should_fail_if_wrong_options_not_specified\n see_failure 'column in table has wrong :default' do\n assert_table :dogs do |t|\n t.column :id, :integer\n t.column :tail, :string, :default => \"blah\"\n end\n end\n end\n\n def test_assert_table_should_fail_if_an_index_is_not_specified\n see_failure 'wrong indexes for table: ' do\n assert_table :dogs do |t|\n declare_columns_on_table(t)\n end\n end\n end\n\n def test_assert_schema_should_fail_if_a_column_in_an_index_is_not_found\n see_failure 'wrong indexes for table: ' do\n assert_table :dogs do |t|\n declare_columns_on_table(t)\n\tt.index :legs, :name => 'index_legs_on_dogs'\n end\n end\n end\n\n def test_assert_schema_should_fail_if_wrong_options_on_an_index\n see_failure 'wrong indexes for table: ' do\n assert_table :dogs do |t|\n declare_columns_on_table(t)\n\tt.index :tail, :name => 'index_tail_on_dogs', :unique => true\n end\n end\n end\n\n def test_should_drop_all_tables\n assert_equal ['dogs','schema_info'].sort, ActiveRecord::Base.connection.tables.sort\n drop_all_tables\n assert_equal [], ActiveRecord::Base.connection.tables\n drop_all_tables\n assert_equal [], ActiveRecord::Base.connection.tables\n end\n\n def test_should_migrate_to_highest_version\n drop_all_tables\n assert_schema do |s|\n end\n\n migrate :version => 1\n\n assert_schema do |s|\n s.table :top_dogs do |t|\n t.column :id, :integer\n t.column :name, :string\n end\n end\n\n migrate :version => 2\n\n assert_schema do |s|\n s.table :top_dogs do |t|\n t.column :id, :integer\n t.column :name, :string\n end\n s.table :bottom_dogs do |t|\n t.column :id, :integer\n t.column :name, :string\n t.column :sick, :boolean\n end\n end\n\n migrate :version => 3\n\n assert_schema do |s|\n s.table :top_dogs do |t|\n t.column :id, :integer\n t.column :name, :string\n end\n s.table :bottom_dogs do |t|\n t.column :id, :integer\n t.column :name, :string\n t.column :sick, :boolean\n end\n s.table :cats do |t|\n t.column :id, :integer\n t.column :lives, :integer\n end\n end\n\n migrate :version => 0\n\n assert_schema do |s|\n end\n\n migrate\n\n assert_schema do |s|\n s.table :top_dogs do |t|\n t.column :id, :integer\n t.column :name, :string\n end\n s.table :bottom_dogs do |t|\n t.column :id, :integer\n t.column :name, :string\n t.column :sick, :boolean\n end\n s.table :cats do |t|\n t.column :id, :integer\n t.column :lives, :integer\n end\n end\n end\n\n def test_should_have_default_migration_dir_set\n MigrationTestHelper.migration_dir = nil\n assert_equal File.expand_path(RAILS_ROOT + '/db/migrate'), MigrationTestHelper.migration_dir, \n \"wrong default migration dir\"\n \n end\n\n def test_should_raise_error_if_migration_fails\n MigrationTestHelper.migration_dir = plugin_path('test/db/migrate_bad')\n drop_all_tables\n err = assert_raise RuntimeError do\n migrate\n end\n assert_match(//i, err.message) \n end\nend\n\n"}, "files_after": {"init.rb": "if Rails.env.test?\n require 'migration_test_helper'\n require 'test/unit'\n Test::Unit::TestCase.class_eval do\n include MigrationTestHelper\n end\nend\n", "lib/migration_test_helper.rb": "#--\n# Copyright (c) 2007 Micah Alles, Patrick Bacon, David Crosby\n# \n# Permission is hereby granted, free of charge, to any person obtaining\n# a copy of this software and associated documentation files (the\n# \"Software\"), to deal in the Software without restriction, including\n# without limitation the rights to use, copy, modify, merge, publish,\n# distribute, sublicense, and/or sell copies of the Software, and to\n# permit persons to whom the Software is furnished to do so, subject to\n# the following conditions:\n# \n# The above copyright notice and this permission notice shall be\n# included in all copies or substantial portions of the Software.\n# \n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n#++\n\nrequire 'test/unit/assertions'\n\nmodule MigrationTestHelper \n def self.migration_dir\n @migration_dir || File.expand_path(Rails.root.to_s + '/db/migrate')\n end\n\n #\n # sets the directory in which the migrations reside to be run with migrate\n #\n def self.migration_dir=(new_dir)\n @migration_dir = new_dir\n end\n\n #\n # verifies the schema exactly matches the one specified (schema_info does not have to be specified)\n # \n # assert_schema do |s|\n # s.table :dogs do |t|\n # t.column :id, :integer, :default => 2\n # t.column :name, :string\n # end\n # end\n #\n def assert_schema\n schema = Schema.new\n yield schema\n schema.verify\n end\n\n #\n # verifies a single table exactly matches the one specified\n # \n # assert_table :dogs do |t|\n # t.column :id, :integer, :default => 2\n # t.column :name, :string\n # end\n #\n def assert_table(name)\n table = Table.new(name)\n yield table\n table.verify\n end\n\n #\n # drops all tables in the database\n # \n def drop_all_tables\n ActiveRecord::Base.connection.tables.each do |table|\n ActiveRecord::Base.connection.drop_table(table)\n end\n end\n\n #\n # executes your migrations\n #\n # migrate # same as rake db:migrate\n #\n # Options are:\n # * :version - version to migrate to (same as VERSION=.. option to rake db:migrate)\n # * :verbose - print migration status messages to STDOUT, defaults to false\n # \n def migrate(opts={})\n old_verbose = ActiveRecord::Migration.verbose\n ActiveRecord::Migration.verbose = opts[:verbose].nil? ? false : opts[:verbose]\n version = opts[:version] ? opts[:version].to_i : nil\n ActiveRecord::Migrator.migrate(MigrationTestHelper.migration_dir, version)\n ensure\n ActiveRecord::Migration.verbose = old_verbose\n end\n\n module Connection #:nodoc:\n def conn\n ActiveRecord::Base.connection\n end\n end\n\n class Schema\n include Connection\n include Test::Unit::Assertions\n\n def initialize #:nodoc:\n @tables = []\n end\n\n def table(name)\n table = Table.new(name)\n yield table\n table.verify\n @tables << table\n end\n\n def verify #:nodoc:\n actual_tables = conn.tables.reject {|t| t == 'schema_info' || t == 'schema_migrations'}\n expected_tables = @tables.map {|t| t.name }\n assert_equal expected_tables.sort, actual_tables.sort, 'wrong tables in schema'\n end\n end\n\n class Table\n include Connection\n include Test::Unit::Assertions\n attr_reader :name\n\n def initialize(name) #:nodoc:\n @name = name.to_s\n @columns = []\n @indexes = []\n assert conn.tables.include?(@name), \"table <#{@name}> not found in schema\"\n end\n\n def column(colname,type,options={})\n colname = colname.to_s\n @columns << colname\n col = conn.columns(name).find {|c| c.name == colname }\n assert_not_nil col, \"column <#{colname}> not found in table <#{self.name}>\"\n assert_equal type, col.type, \"wrong type for column <#{colname}> in table <#{name}>\"\n options.each do |k,v|\n k = k.to_sym; actual = col.send(k); actual = actual.is_a?(String) ? actual.sub(/'$/,'').sub(/^'/,'') : actual\n assert_equal v, actual, \"column <#{colname}> in table <#{name}> has wrong :#{k}\"\n end\n end\n\n def index(column_name, options = {})\n @indexes << \"name <#{options[:name]}> columns <#{Array(column_name).join(\",\")}> unique <#{options[:unique] == true}>\" \n end\n\n def verify #:nodoc:\n actual_columns = conn.columns(name).map {|c| c.name }\n assert_equal @columns.sort, actual_columns.sort, \"wrong columns for table: <#{name}>\"\n\n actual_indexes = conn.indexes(@name).collect { |i| \"name <#{i.name}> columns <#{i.columns.join(\",\")}> unique <#{i.unique}>\" }\n assert_equal @indexes.sort, actual_indexes.sort, \"wrong indexes for table: <#{name}>\"\n end\n \n def method_missing(type, *columns)\n options = columns.extract_options!\n columns.each do |colname|\n column colname, type, options\n end\n end\n end\nend\n", "test/helper.rb": "ENV[\"RAILS_ENV\"] = \"test\"\nrequire File.expand_path(File.dirname(__FILE__) + '/../../../../config/environment')\nrequire 'logger'\nrequire 'fileutils'\nrequire 'rails/test_help'\n\nplugin_path = Rails.root.to_s + \"/vendor/plugins/migration_test_helper\"\n\nconfig_location = File.expand_path(plugin_path + \"/test/config/database.yml\")\n\nconfig = YAML::load(ERB.new(IO.read(config_location)).result)\nActiveRecord::Base.logger = Logger.new(plugin_path + \"/test/log/test.log\")\nActiveRecord::Base.establish_connection(config['test'])\n\nActiveSupport::TestCase.fixture_path = plugin_path + \"/test/fixtures/\"\n\n$LOAD_PATH.unshift(ActiveSupport::TestCase.fixture_path)\n\nclass Test::Unit::TestCase\n include FileUtils\n def plugin_path(path)\n File.expand_path(File.dirname(__FILE__) + '/../' + path) \n end\n\n def load_default_schema\n ActiveRecord::Migration.suppress_messages do\n schema_file = plugin_path(\"/test/db/schema.rb\")\n load(schema_file) if File.exist?(schema_file)\n end\n end\n\n def migration_test_path\n File.expand_path(RAILS_ROOT + \"/test/migration\")\n end\n\n def run_in_rails_root(command)\n cd RAILS_ROOT do\n @output = `#{command}`\n end\n end\n\n def check_output(string_or_regexp)\n assert_not_nil @output, \"No output collected\"\n case string_or_regexp\n when String\n assert_match(/#{Regexp.escape(string_or_regexp)}/, @output)\n when Regexp\n assert_match(string_or_regexp, @output)\n else\n raise \"Can't check output using oddball object #{string_or_regexp.inspect}\"\n end\n end\n \n def rm_migration_test_path\n rm_rf migration_test_path\n end\n\n def self.should(behave,&block)\n return unless running_in_foundry\n @context ||= nil\n @context_setup ||= nil\n context_string = @context.nil? ? '' : @context + ' '\n mname = \"test #{context_string}should #{behave}\"\n context_setup = @context_setup\n if block_given?\n define_method(mname) do\n instance_eval(&context_setup) unless context_setup.nil?\n instance_eval(&block)\n end \n else\n puts \">>> UNIMPLEMENTED CASE: #{name.sub(/Test$/,'')} should #{behave}\"\n end\n end\n\nend\n", "test/migration_test_helper_test.rb": "require File.expand_path(File.dirname(__FILE__) + '/helper') \n\nclass MigrationTestHelperTest < Test::Unit::TestCase\n\n def setup\n load_default_schema\n MigrationTestHelper.migration_dir = plugin_path('test/db/migrate_good')\n end\n\n #\n # HELPERS\n #\n def see_failure(pattern='')\n err = assert_raise(Test::Unit::AssertionFailedError) do\n yield\n end\n assert_match(/#{pattern}/mi, err.message) \n end\n\n def see_no_failure\n assert_nothing_raised do\n yield\n end\n end\n\n def declare_columns_on_table(t)\n t.column :id, :integer\n t.column :tail, :string, :default => 'top dog', :limit => 187\n end\n \n #\n # TESTS\n #\n def test_assert_schema_should_not_fail_if_schema_is_matched\n see_no_failure do\n assert_schema do |s|\n s.table :dogs do |t|\n\t declare_columns_on_table(t)\n\t t.index :tail, :name => 'index_tail_on_dogs'\n end\n\n end\n end\n end\n\n def test_assert_schema_should_fail_if_a_table_is_not_specified\n see_failure 'wrong tables in schema.*dogs' do\n assert_schema do |s|\n end\n end\n end\n\n def test_assert_schema_should_fail_if_a_table_is_not_found\n see_failure 'table not found in schema' do\n assert_schema do |s|\n s.table :things do |t|\n t.column :id, :integer\n end\n end\n end\n end\n\n def test_assert_schema_should_fail_if_a_column_is_not_specified\n see_failure 'wrong columns for table.*dogs.*tail' do\n assert_schema do |s|\n s.table :dogs do |t|\n t.column :id, :integer\n end\n end\n end\n end\n\n def test_assert_schema_should_fail_if_a_column_is_not_found\n see_failure 'column not found in table ' do\n assert_schema do |s|\n s.table :dogs do |t|\n t.column :id, :integer\n t.column :tail, :string\n t.column :legs, :integer\n end\n end\n end\n end\n\n def test_assert_schema_should_fail_if_wrong_options_not_specified\n see_failure 'column in table has wrong :default' do\n assert_table :dogs do |t|\n t.column :id, :integer\n t.column :tail, :string, :default => \"blah\"\n end\n end\n end\n\n def test_assert_table_should_not_fail_if_table_is_matched\n see_no_failure do\n assert_table :dogs do |t|\n declare_columns_on_table(t)\n\tt.index :tail, :name => 'index_tail_on_dogs'\n end\n end\n end\n\n def test_assert_table_should_fail_if_a_table_is_not_found\n see_failure 'table not found in schema' do\n assert_table :things do |t|\n t.column :id, :integer\n end\n end\n end\n\n def test_assert_table_should_fail_if_a_column_is_not_specified\n see_failure 'wrong columns for table.*dogs.*tail' do\n assert_table :dogs do |t|\n t.column :id, :integer\n end\n end\n end\n\n def test_assert_table_should_fail_if_a_column_is_not_found\n see_failure 'column not found in table ' do\n assert_table :dogs do |t|\n t.column :id, :integer\n t.column :tail, :string\n t.column :legs, :integer\n end\n end\n end\n\n def test_assert_table_should_fail_if_wrong_options_not_specified\n see_failure 'column in table has wrong :default' do\n assert_table :dogs do |t|\n t.column :id, :integer\n t.column :tail, :string, :default => \"blah\"\n end\n end\n end\n\n def test_assert_table_should_fail_if_an_index_is_not_specified\n see_failure 'wrong indexes for table: ' do\n assert_table :dogs do |t|\n declare_columns_on_table(t)\n end\n end\n end\n\n def test_assert_schema_should_fail_if_a_column_in_an_index_is_not_found\n see_failure 'wrong indexes for table: ' do\n assert_table :dogs do |t|\n declare_columns_on_table(t)\n\tt.index :legs, :name => 'index_legs_on_dogs'\n end\n end\n end\n\n def test_assert_schema_should_fail_if_wrong_options_on_an_index\n see_failure 'wrong indexes for table: ' do\n assert_table :dogs do |t|\n declare_columns_on_table(t)\n\tt.index :tail, :name => 'index_tail_on_dogs', :unique => true\n end\n end\n end\n\n def test_should_drop_all_tables\n assert_equal ['dogs','schema_migrations'].sort, ActiveRecord::Base.connection.tables.sort\n drop_all_tables\n assert_equal [], ActiveRecord::Base.connection.tables\n drop_all_tables\n assert_equal [], ActiveRecord::Base.connection.tables\n end\n\n def test_should_migrate_to_highest_version\n drop_all_tables\n assert_schema do |s|\n end\n\n migrate :version => 1\n\n assert_schema do |s|\n s.table :top_dogs do |t|\n t.column :id, :integer\n t.column :name, :string\n end\n end\n\n migrate :version => 2\n\n assert_schema do |s|\n s.table :top_dogs do |t|\n t.column :id, :integer\n t.column :name, :string\n end\n s.table :bottom_dogs do |t|\n t.column :id, :integer\n t.column :name, :string\n t.column :sick, :boolean\n end\n end\n\n migrate :version => 3\n\n assert_schema do |s|\n s.table :top_dogs do |t|\n t.column :id, :integer\n t.column :name, :string\n end\n s.table :bottom_dogs do |t|\n t.column :id, :integer\n t.column :name, :string\n t.column :sick, :boolean\n end\n s.table :cats do |t|\n t.column :id, :integer\n t.column :lives, :integer\n end\n end\n\n migrate :version => 0\n\n assert_schema do |s|\n end\n\n migrate\n\n assert_schema do |s|\n s.table :top_dogs do |t|\n t.column :id, :integer\n t.column :name, :string\n end\n s.table :bottom_dogs do |t|\n t.column :id, :integer\n t.column :name, :string\n t.column :sick, :boolean\n end\n s.table :cats do |t|\n t.column :id, :integer\n t.column :lives, :integer\n end\n end\n end\n\n def test_should_have_default_migration_dir_set\n MigrationTestHelper.migration_dir = nil\n assert_equal File.expand_path(Rails.root.to_s + '/db/migrate'), MigrationTestHelper.migration_dir, \n \"wrong default migration dir\"\n \n end\n\n def test_should_raise_error_if_migration_fails\n MigrationTestHelper.migration_dir = plugin_path('test/db/migrate_bad')\n drop_all_tables\n err = assert_raise StandardError do\n migrate\n end\n assert_match(//i, err.message) \n end\nend\n\n"}} -{"repo": "mixtli/net-snmp", "pr_number": 13, "title": "Fix password length for utf-8 encoded chars (http://zargony.com/2009/07/...", "state": "open", "merged_at": null, "additions": 7, "deletions": 3, "files_changed": ["lib/net/snmp/session.rb", "lib/net/snmp/wrapper.rb"], "files_before": {"lib/net/snmp/session.rb": "require 'thread'\nrequire 'forwardable'\nrequire 'pp'\nmodule Net\n module SNMP\n class Session\n # == SNMP Session\n #\n # Provides API for interacting with a host with snmp\n extend Forwardable\n include Net::SNMP::Debug\n attr_accessor :struct, :callback, :requests, :peername, :community\n attr_reader :version\n def_delegator :@struct, :pointer\n #@sessions = []\n @lock = Mutex.new\n @sessions = {}\n\n class << self\n attr_accessor :sessions, :lock\n\n # Open a new session. Accepts a block which yields the session.\n #\n # Net::SNMP::Session.open(:peername => 'test.net-snmp.org', :community => 'public') do |sess|\n # pdu = sess.get([\"sysDescr.0\"])\n # pdu.print\n # end\n # Options:\n # * +peername+ - hostname\n # * +community+ - snmp community string. Default is public\n # * +version+ - snmp version. Possible values include 1, '2c', and 3. Default is 1.\n # * +timeout+ - snmp timeout in seconds\n # * +retries+ - snmp retries. default = 5\n # * +security_level+ - SNMPv3 only. default = Net::SNMP::Constants::SNMP_SEC_LEVEL_NOAUTH\n # * +auth_protocol+ - SNMPv3 only. default is nil (usmNoAuthProtocol). Possible values include :md5, :sha1, and nil\n # * +priv_protocol+ - SNMPv3 only. default is nil (usmNoPrivProtocol). Possible values include :des, :aes, and nil\n # * +context+ - SNMPv3 only.\n # * +username+ - SNMPv3 only.\n # * +auth_password+ - SNMPv3 only.\n # * +priv_password+ - SNMPv3 only. \n # Returns:\n # Net::SNMP::Session\n def open(options = {})\n session = new(options)\n if Net::SNMP::thread_safe\n Net::SNMP::Session.lock.synchronize {\n Net::SNMP::Session.sessions[session.sessid] = session\n }\n else\n Net::SNMP::Session.sessions[session.sessid] = session\n end\n if block_given?\n yield session\n end\n session\n end\n end\n\n def initialize(options = {})\n @timeout = options[:timeout] || 1\n @retries = options[:retries] || 5\n @requests = {}\n @peername = options[:peername] || 'localhost'\n @peername = \"#{@peername}:#{options[:port]}\" if options[:port]\n @community = options[:community] || \"public\"\n options[:community_len] = @community.length\n @version = options[:version] || 1\n options[:version] ||= Constants::SNMP_VERSION_1\n @version = options[:version] || 1\n #self.class.sessions << self\n @sess = Wrapper::SnmpSession.new(nil)\n Wrapper.snmp_sess_init(@sess.pointer)\n #options.each_pair {|k,v| ptr.send(\"#{k}=\", v)}\n @sess.community = FFI::MemoryPointer.from_string(@community)\n @sess.community_len = @community.length\n @sess.peername = FFI::MemoryPointer.from_string(@peername)\n #@sess.remote_port = options[:port] || 162\n @sess.version = case options[:version].to_s\n when '1'\n Constants::SNMP_VERSION_1\n when '2', '2c'\n Constants::SNMP_VERSION_2c\n when '3'\n Constants::SNMP_VERSION_3\n else\n Constants::SNMP_VERSION_1\n end\n debug \"setting timeout = #{@timeout} retries = #{@retries}\"\n @sess.timeout = @timeout * 1000000\n @sess.retries = @retries\n\n if @sess.version == Constants::SNMP_VERSION_3\n @sess.securityLevel = options[:security_level] || Constants::SNMP_SEC_LEVEL_NOAUTH\n @sess.securityAuthProto = case options[:auth_protocol]\n when :sha1\n OID.new(\"1.3.6.1.6.3.10.1.1.3\").pointer\n when :md5\n OID.new(\"1.3.6.1.6.3.10.1.1.2\").pointer\n when nil\n OID.new(\"1.3.6.1.6.3.10.1.1.1\").pointer\n end\n @sess.securityPrivProto = case options[:priv_protocol]\n when :aes\n OID.new(\"1.3.6.1.6.3.10.1.2.4\").pointer\n when :des\n OID.new(\"1.3.6.1.6.3.10.1.2.2\").pointer\n when nil\n OID.new(\"1.3.6.1.6.3.10.1.2.1\").pointer\n end\n \n @sess.securityAuthProtoLen = 10\n @sess.securityAuthKeyLen = Constants::USM_AUTH_KU_LEN\n\n @sess.securityPrivProtoLen = 10\n @sess.securityPrivKeyLen = Constants::USM_PRIV_KU_LEN\n\n\n if options[:context]\n @sess.contextName = FFI::MemoryPointer.from_string(options[:context])\n @sess.contextNameLen = options[:context].length\n end\n\n # Do not generate_Ku, unless we're Auth or AuthPriv\n unless @sess.securityLevel == Constants::SNMP_SEC_LEVEL_NOAUTH\n options[:auth_password] ||= options[:password] # backward compatability\n if options[:username].nil? or options[:auth_password].nil?\n raise Net::SNMP::Error.new \"SecurityLevel requires username and password\"\n end\n if options[:username]\n @sess.securityName = FFI::MemoryPointer.from_string(options[:username])\n @sess.securityNameLen = options[:username].length\n end\n\n auth_len_ptr = FFI::MemoryPointer.new(:size_t)\n auth_len_ptr.write_int(Constants::USM_AUTH_KU_LEN)\n auth_key_result = Wrapper.generate_Ku(@sess.securityAuthProto,\n @sess.securityAuthProtoLen,\n options[:auth_password],\n options[:auth_password].length,\n @sess.securityAuthKey,\n auth_len_ptr)\n @sess.securityAuthKeyLen = auth_len_ptr.read_int\n\n if @sess.securityLevel == Constants::SNMP_SEC_LEVEL_AUTHPRIV\n priv_len_ptr = FFI::MemoryPointer.new(:size_t)\n priv_len_ptr.write_int(Constants::USM_PRIV_KU_LEN)\n\n # NOTE I know this is handing off the AuthProto, but generates a proper\n # key for encryption, and using PrivProto does not.\n priv_key_result = Wrapper.generate_Ku(@sess.securityAuthProto,\n @sess.securityAuthProtoLen,\n options[:priv_password],\n options[:priv_password].length,\n @sess.securityPrivKey,\n priv_len_ptr)\n @sess.securityPrivKeyLen = priv_len_ptr.read_int\n end\n\n unless auth_key_result == Constants::SNMPERR_SUCCESS and priv_key_result == Constants::SNMPERR_SUCCESS\n Wrapper.snmp_perror(\"netsnmp\")\n end\n end\n end\n # General callback just takes the pdu, calls the session callback if any, then the request specific callback.\n\n @struct = Wrapper.snmp_sess_open(@sess.pointer)\n end\n\n\n # Close the snmp session and free associated resources.\n def close\n if Net::SNMP.thread_safe\n self.class.lock.synchronize {\n Wrapper.snmp_sess_close(@struct)\n self.class.sessions.delete(self.sessid)\n }\n else\n Wrapper.snmp_sess_close(@struct)\n self.class.sessions.delete(self.sessid)\n end\n end\n\n # Issue an SNMP GET Request.\n # See #send_pdu\n def get(oidlist, options = {}, &block)\n pdu = PDU.new(Constants::SNMP_MSG_GET)\n oidlist = [oidlist] unless oidlist.kind_of?(Array)\n oidlist.each do |oid|\n pdu.add_varbind(:oid => oid)\n end\n send_pdu(pdu, options, &block)\n end\n\n # Issue an SNMP GETNEXT Request\n # See #send_pdu\n def get_next(oidlist, options = {}, &block)\n pdu = PDU.new(Constants::SNMP_MSG_GETNEXT)\n oidlist = [oidlist] unless oidlist.kind_of?(Array)\n oidlist.each do |oid|\n pdu.add_varbind(:oid => oid)\n end\n send_pdu(pdu, options, &block)\n end\n\n # Issue an SNMP GETBULK Request\n # See #send_pdu\n def get_bulk(oidlist, options = {}, &block)\n pdu = PDU.new(Constants::SNMP_MSG_GETBULK)\n oidlist = [oidlist] unless oidlist.kind_of?(Array)\n oidlist.each do |oid|\n pdu.add_varbind(:oid => oid)\n end\n pdu.non_repeaters = options[:non_repeaters] || 0\n pdu.max_repetitions = options[:max_repetitions] || 10\n send_pdu(pdu, options, &block)\n end\n\n\n # Issue an SNMP Set Request\n # See #send_pdu\n def set(oidlist, options = {}, &block)\n pdu = PDU.new(Constants::SNMP_MSG_SET)\n oidlist.each do |oid|\n pdu.add_varbind(:oid => oid[0], :type => oid[1], :value => oid[2])\n end\n send_pdu(pdu, options, &block)\n end\n\n # Proxy getters to the C struct representing the session\n def method_missing(m, *args)\n if @struct.respond_to?(m)\n @struct.send(m, *args)\n else\n super\n end\n end\n\n def default_max_repeaters\n # We could do something based on transport here. 25 seems safe\n 25\n end\n\n # Raise a NET::SNMP::Error with the session attached\n def error(msg, options = {})\n #Wrapper.snmp_sess_perror(msg, @sess.pointer)\n err = Error.new({:session => self}.merge(options))\n err.print\n raise err, msg\n end\n \n\n # Check the session for SNMP responses from asynchronous SNMP requests\n # This method will check for new responses and call the associated\n # response callbacks.\n # +timeout+ A timeout of nil indicates a poll and will return immediately.\n # A value of false will block until data is available. Otherwise, pass\n # the number of seconds to block.\n # Returns the number of file descriptors handled.\n def select(timeout = nil)\n fdset = FFI::MemoryPointer.new(:pointer, Net::SNMP::Inline.fd_setsize / 8)\n num_fds = FFI::MemoryPointer.new(:int)\n tv_sec = timeout ? timeout.round : 0\n tv_usec = timeout ? (timeout - timeout.round) * 1000000 : 0\n tval = Wrapper::TimeVal.new(:tv_sec => tv_sec, :tv_usec => tv_usec)\n block = FFI::MemoryPointer.new(:int)\n if timeout.nil?\n block.write_int(0)\n else\n block.write_int(1)\n end\n\n Wrapper.snmp_sess_select_info(@struct, num_fds, fdset, tval.pointer, block )\n tv = (timeout == false ? nil : tval)\n #debug \"Calling select #{Time.now}\"\n num_ready = FFI::LibC.select(num_fds.read_int, fdset, nil, nil, tv)\n #debug \"Done select #{Time.now}\"\n if num_ready > 0\n Wrapper.snmp_sess_read(@struct, fdset)\n elsif num_ready == 0\n Wrapper.snmp_sess_timeout(@struct)\n elsif num_ready == -1\n # error. check snmp_error?\n error(\"select\")\n else\n error(\"wtf is wrong with select?\")\n end\n num_ready\n end\n\n alias :poll :select\n\n\n # Issue repeated getnext requests on each oid passed in until\n # the result is no longer a child. Returns a hash with the numeric\n # oid strings as keys.\n # XXX work in progress. only works synchronously (except with EM + fibers).\n # Need to do better error checking and use getbulk when avaiable.\n def walk(oidlist, options = {})\n oidlist = [oidlist] unless oidlist.kind_of?(Array)\n oidlist = oidlist.map {|o| o.kind_of?(OID) ? o : OID.new(o)}\n all_results = {}\n base_list = oidlist\n while(!oidlist.empty? && pdu = get_next(oidlist, options))\n debug \"===============================================================\"\n debug \"base_list = #{base_list}\"\n prev_base = base_list.dup\n oidlist = []\n #print_errors\n #pdu.print_errors\n pdu.varbinds.each_with_index do |vb, i|\n if prev_base[i].parent_of?(vb.oid) && vb.object_type != Constants::SNMP_ENDOFMIBVIEW\n # Still in subtree. Store results and add next oid to list\n debug \"adding #{vb.oid} to oidlist\"\n all_results[vb.oid.to_s] = vb.value\n oidlist << vb.oid\n else\n # End of subtree. Don't add to list or results\n debug \"End of subtree\"\n base_list.delete_at(i)\n debug \"not adding #{vb.oid}\"\n end\n # If get a pdu error, we can only tell the first failing varbind,\n # So we remove it and resend all the rest\n if pdu.error? && pdu.errindex == i + 1\n oidlist.pop # remove the bad oid\n debug \"caught error\"\n if pdu.varbinds.size > i+1\n # recram rest of oids on list\n ((i+1)..pdu.varbinds.size).each do |j|\n debug \"j = #{j}\"\n debug \"adding #{j} = #{prev_list[j]}\"\n oidlist << prev_list[j]\n end\n # delete failing oid from base_list\n base_list.delete_at(i)\n end\n break\n end\n end\n end\n if block_given?\n yield all_results\n end\n all_results\n end\n\n\n # Given a list of columns (e.g ['ifIndex', 'ifDescr'], will return a hash with\n # the indexes as keys and hashes as values.\n # puts sess.get_columns(['ifIndex', 'ifDescr']).inspect\n # {'1' => {'ifIndex' => '1', 'ifDescr' => 'lo0'}, '2' => {'ifIndex' => '2', 'ifDescr' => 'en0'}}\n def columns(columns, options = {})\n columns = columns.map {|c| c.kind_of?(OID) ? c : OID.new(c)}\n walk_hash = walk(columns, options)\n results = {}\n walk_hash.each do |k, v|\n oid = OID.new(k)\n results[oid.index] ||= {}\n results[oid.index][oid.node.label] = v\n end\n if block_given?\n yield results\n end\n results\n end\n\n # table('ifEntry'). You must pass the direct parent entry. Calls columns with all\n # columns in +table_name+\n def table(table_name, &blk)\n column_names = MIB::Node.get_node(table_name).children.collect {|c| c.oid }\n results = columns(column_names)\n if block_given?\n yield results\n end\n results\n end\n\n # Send a PDU\n # +pdu+ The Net::SNMP::PDU object to send. Usually created by Session.get, Session.getnext, etc.\n # +callback+ An optional callback. It should take two parameters, status and response_pdu.\n # If no +callback+ is given, the call will block until the response is available and will return\n # the response pdu. If an error occurs, a Net::SNMP::Error will be thrown.\n # If +callback+ is passed, the PDU will be sent and +send_pdu+ will return immediately. You must\n # then call Session.select to invoke the callback. This is usually done in some sort of event loop.\n # See Net::SNMP::Dispatcher.\n #\n # If you're running inside eventmachine and have fibers (ruby 1.9, jruby, etc), sychronous calls will\n # actually run asynchronously behind the scenes. Just run Net::SNMP::Dispatcher.fiber_loop in your\n # reactor.\n #\n # pdu = Net::SNMP::PDU.new(Constants::SNMP_MSG_GET)\n # pdu.add_varbind(:oid => 'sysDescr.0')\n # session.send_pdu(pdu) do |status, pdu|\n # if status == :success\n # pdu.print\n # elsif status == :timeout\n # puts \"Timed Out\"\n # else\n # puts \"A problem occurred\"\n # end\n # end\n # session.select(false) #block until data is ready. Callback will be called.\n # begin\n # result = session.send_pdu(pdu)\n # puts result.inspect\n # rescue Net::SNMP::Error => e\n # puts e.message\n # end\n def send_pdu(pdu, options = {}, &callback)\n if options[:blocking]\n return send_pdu_blocking(pdu)\n end\n if block_given?\n @requests[pdu.reqid] = callback\n debug \"calling async_send\"\n if Wrapper.snmp_sess_async_send(@struct, pdu.pointer, sess_callback, nil) == 0\n error(\"snmp_get async failed\")\n end\n #pdu.free\n nil\n else\n if defined?(EM) && EM.reactor_running? && defined?(Fiber)\n f = Fiber.current\n send_pdu pdu do | op, response_pdu |\n #pdu.free\n f.resume([op, response_pdu])\n end\n op, result = Fiber.yield\n case op\n when :timeout\n raise TimeoutError.new, \"timeout\"\n when :send_failed\n error \"send failed\"\n when :success\n result\n when :connect, :disconnect\n nil #does this ever happen?\n else\n error \"unknown operation #{op}\"\n end\n else\n send_pdu_blocking(pdu)\n end\n end\n end\n\n def send_pdu_blocking(pdu)\n response_ptr = FFI::MemoryPointer.new(:pointer)\n if [Constants::SNMP_MSG_TRAP, Constants::SNMP_MSG_TRAP2].include?(pdu.command)\n status = Wrapper.snmp_sess_send(@struct, pdu.pointer)\n if status == 0\n error(\"snmp_sess_send\")\n end\n else\n status = Wrapper.snmp_sess_synch_response(@struct, pdu.pointer, response_ptr)\n unless status == Constants::STAT_SUCCESS\n error(\"snmp_sess_synch_response\", :status => status)\n end\n end\n if [Constants::SNMP_MSG_TRAP, Constants::SNMP_MSG_TRAP2].include?(pdu.command)\n 1\n else\n PDU.new(response_ptr.read_pointer)\n end\n end\n\n def errno\n get_error\n @errno\n end\n\n # The SNMP Session error code\n def snmp_err\n get_error\n @snmp_err\n end\n\n # The SNMP Session error message\n def error_message\n get_error\n @snmp_msg\n end\n\n def print_errors\n puts \"errno: #{errno}, snmp_err: #{@snmp_err}, message: #{@snmp_msg}\"\n end\n private\n def sess_callback\n @sess_callback ||= FFI::Function.new(:int, [:int, :pointer, :int, :pointer, :pointer]) do |operation, session, reqid, pdu_ptr, magic|\n debug \"in callback #{operation.inspect} #{session.inspect}\"\n op = case operation\n when Constants::NETSNMP_CALLBACK_OP_RECEIVED_MESSAGE\n :success\n when Constants::NETSNMP_CALLBACK_OP_TIMED_OUT\n :timeout\n when Constants::NETSNMP_CALLBACK_OP_SEND_FAILED\n :send_failed\n when Constants::NETSNMP_CALLBACK_OP_CONNECT\n :connect\n when Constants::NETSNMP_CALLBACK_OP_DISCONNECT\n :disconnect\n else\n error \"Invalid PDU Operation\"\n end\n\n if @requests[reqid]\n pdu = PDU.new(pdu_ptr)\n callback_return = @requests[reqid].call(op, pdu)\n @requests.delete(reqid)\n callback_return == false ? 0 : 1 #if callback returns false (failure), pass it on. otherwise return 1 (success)\n else\n 0# Do what here? Can this happen? Maybe request timed out and was deleted?\n end\n end\n end\n def get_error\n errno_ptr = FFI::MemoryPointer.new(:int)\n snmp_err_ptr = FFI::MemoryPointer.new(:int)\n msg_ptr = FFI::MemoryPointer.new(:pointer)\n Wrapper.snmp_sess_error(@struct.pointer, errno_ptr, snmp_err_ptr, msg_ptr)\n @errno = errno_ptr.read_int\n @snmp_err = snmp_err_ptr.read_int\n @snmp_msg = msg_ptr.read_pointer.read_string\n end\n\n\n end\n end\nend\n\n\n", "lib/net/snmp/wrapper.rb": "module Net\nmodule SNMP\nmodule Wrapper\n extend NiceFFI::Library\n ffi_lib \"libnetsnmp\"\n #ffi_lib \"netsnmp\"\n typedef :u_long, :oid\n\n class Counter64 < NiceFFI::Struct\n layout(\n :high, :u_long,\n :low, :u_long\n )\n end\n\n class TimeVal < NiceFFI::Struct\n layout(:tv_sec, :long, :tv_usec, :long)\n end\n def self.print_timeval(tv)\n puts \"tv_sec = #{tv.tv_sec}, tv_usec = #{tv.tv_usec} \"\n end\n\n\n class NetsnmpVardata < FFI::Union\n layout(\n :integer, :pointer,\n :string, :pointer,\n :objid, :pointer,\n :bitstring, :pointer,\n :counter64, :pointer,\n :float, :pointer,\n :double, :pointer\n )\n end\n\n def self.print_varbind(v)\n puts \"---------------------VARBIND------------------------\"\n puts %{\n name_length #{v.name_length}\n name #{v.name.read_array_of_long(v.name_length).join(\".\")}\n type = #{v.type}\n\n }\n end\n # puts \"Vardata size = #{NetsnmpVardata.size}\"\n class VariableList < NiceFFI::Struct\n layout(\n :next_variable, :pointer,\n :name, :pointer,\n :name_length, :size_t,\n :type, :u_char,\n :val, NetsnmpVardata,\n :val_len, :size_t,\n :name_loc, [:oid, Net::SNMP::MAX_OID_LEN],\n :buf, [:u_char, 40],\n :data, :pointer,\n :dataFreeHook, callback([ :pointer ], :void),\n :index, :int\n ) \n end\n \n #puts \"VariableList size = #{VariableList.size}\"\n\n def self.print_pdu(p)\n puts \"--------------PDU---------------\"\n puts %{\n version = #{p.version}\n command = #{p.command}\n errstat = #{p.errstat}\n errindex = #{p.errindex}\n }\n v = p.variables.pointer\n puts \"-----VARIABLES------\"\n while !v.null? do\n var = VariableList.new v\n print_varbind(var)\n v = var.next_variable\n end\n \n end\n class SnmpPdu < NiceFFI::Struct\n layout(\n :version, :long,\n :command, :int,\n :reqid, :long,\n :msgid, :long,\n :transid, :long,\n :sessid, :long,\n :errstat, :long,\n :errindex, :long,\n :time, :u_long,\n :flags, :u_long,\n :securityModel, :int,\n :securityLevel, :int,\n :msgParseModel, :int,\n :transport_data, :pointer,\n :transport_data_length, :int,\n :tDomain, :pointer,\n :tDomainLen, :size_t,\n :variables, VariableList.typed_pointer,\n :community, :pointer,\n :community_len, :size_t,\n :enterprise, :pointer,\n :enterprise_length, :size_t,\n :trap_type, :long,\n :specific_type, :long,\n :agent_addr, [:uchar, 4],\n :contextEngineID, :pointer,\n :contextEngineIDLen, :size_t,\n :contextName, :pointer,\n :contextNameLen, :size_t,\n :securityEngineID, :pointer,\n :securityEngineIDLen, :size_t,\n :securityName, :pointer,\n :securityNameLen, :size_t,\n :priority, :int,\n :range_subid, :int,\n :securityStateRef, :pointer\n )\n\n end\n # puts \"snmppdu size = #{SnmpPdu.size}\"\n callback(:snmp_callback, [ :int, :pointer, :int, :pointer, :pointer ], :int)\n callback(:netsnmp_callback, [ :int, :pointer, :int, :pointer, :pointer ], :int)\n def self.print_session(s)\n puts \"-------------------SESSION---------------------\"\n puts %{\n peername = #{s.peername.read_string}\n community = #{s.community.read_string(s.community_len)}\n s_errno = #{s.s_errno}\n s_snmp_errno = #{s.s_snmp_errno}\n securityAuthKey = #{s.securityAuthKey.to_ptr.read_string}\n\n }\n end\n class SnmpSession < NiceFFI::Struct\n layout(\n :version, :long,\n :retries, :int,\n :timeout, :long,\n :flags, :u_long,\n :subsession, :pointer,\n :next, :pointer,\n :peername, :pointer,\n :remote_port, :u_short,\n :localname, :pointer,\n :local_port, :u_short,\n :authenticator, callback([ :pointer, :pointer, :pointer, :uint ], :pointer),\n :callback, :netsnmp_callback,\n :callback_magic, :pointer,\n :s_errno, :int,\n :s_snmp_errno, :int,\n :sessid, :long,\n :community, :pointer,\n :community_len, :size_t,\n :rcvMsgMaxSize, :size_t,\n :sndMsgMaxSize, :size_t,\n :isAuthoritative, :u_char,\n :contextEngineID, :pointer,\n :contextEngineIDLen, :size_t,\n :engineBoots, :u_int,\n :engineTime, :u_int,\n :contextName, :pointer,\n :contextNameLen, :size_t,\n :securityEngineID, :pointer,\n :securityEngineIDLen, :size_t,\n :securityName, :pointer,\n :securityNameLen, :size_t,\n :securityAuthProto, :pointer,\n :securityAuthProtoLen, :size_t,\n :securityAuthKey, [:u_char, 32],\n :securityAuthKeyLen, :size_t,\n :securityAuthLocalKey, :pointer,\n :securityAuthLocalKeyLen, :size_t,\n :securityPrivProto, :pointer,\n :securityPrivProtoLen, :size_t,\n :securityPrivKey, [:u_char, 32],\n :securityPrivKeyLen, :size_t,\n :securityPrivLocalKey, :pointer,\n :securityPrivLocalKeyLen, :size_t,\n :securityModel, :int,\n :securityLevel, :int,\n :paramName, :pointer,\n :securityInfo, :pointer,\n :myvoid, :pointer\n )\n end\n class Tree < NiceFFI::Struct\n layout(\n :child_list, :pointer,\n :next_peer, :pointer,\n :next, :pointer,\n :parent, :pointer,\n :label, :string,\n :subid, :u_long,\n :modid, :int,\n :number_modules, :int,\n :module_list, :pointer,\n :tc_index, :int,\n :type, :int,\n :access, :int,\n :status, :int,\n :enums, :pointer,\n :ranges, :pointer,\n :indexes, :pointer,\n :augments, :pointer,\n :varbinds, :pointer,\n :hint, :pointer,\n :units, :pointer,\n :printomat, callback([:pointer, :pointer, :pointer, :int, :pointer, :pointer, :pointer, :pointer], :int),\n :printer, callback([:pointer, :pointer, :pointer, :pointer, :pointer], :void),\n :description, :pointer,\n :reference, :pointer,\n :reported, :int,\n :defaultValue, :pointer\n )\n end\n class IndexList < NiceFFI::Struct\n layout(\n :next, :pointer,\n :ilabel, :pointer,\n :isimplied, :char\n )\n end\n\n\n# puts \"snmp_session size = #{SnmpSession.size}\"\n attach_function :snmp_open, [ :pointer ], SnmpSession.typed_pointer\n attach_function :snmp_errstring, [:int], :string\n attach_function :snmp_close, [ :pointer ], :int\n attach_function :snmp_close_sessions, [ ], :int\n attach_function :snmp_send, [ :pointer, :pointer ], :int\n attach_function :snmp_async_send, [ :pointer, :pointer, :netsnmp_callback, :pointer ], :int\n attach_function :snmp_read, [ :pointer ], :void\n attach_function :snmp_free_pdu, [ :pointer ], :void\n attach_function :snmp_free_var, [ :pointer ], :void\n attach_function :snmp_free_varbind, [ :pointer ], :void\n attach_function :snmp_select_info, [ :pointer, :pointer, :pointer, :pointer ], :int\n attach_function :snmp_timeout, [ ], :void\n\n attach_function :snmp_get_next_msgid, [ ], :long\n attach_function :snmp_get_next_reqid, [ ], :long\n attach_function :snmp_get_next_sessid, [ ], :long\n attach_function :snmp_get_next_transid, [ ], :long\n attach_function :snmp_oid_compare, [ :pointer, :uint, :pointer, :uint ], :int\n attach_function :snmp_oid_ncompare, [ :pointer, :uint, :pointer, :uint, :uint ], :int\n attach_function :snmp_oidtree_compare, [ :pointer, :uint, :pointer, :uint ], :int\n attach_function :snmp_oidsubtree_compare, [ :pointer, :uint, :pointer, :uint ], :int\n attach_function :netsnmp_oid_compare_ll, [ :pointer, :uint, :pointer, :uint, :pointer ], :int\n attach_function :netsnmp_oid_equals, [ :pointer, :uint, :pointer, :uint ], :int\n# attach_function :netsnmp_oid_tree_equals, [ :pointer, :uint, :pointer, :uint ], :int\n attach_function :netsnmp_oid_is_subtree, [ :pointer, :uint, :pointer, :uint ], :int\n attach_function :netsnmp_oid_find_prefix, [ :pointer, :uint, :pointer, :uint ], :int\n attach_function :netsnmp_transport_open_client, [:string, :pointer], :pointer\n attach_function :init_snmp, [ :string ], :void\n attach_function :snmp_pdu_build, [ :pointer, :pointer, :pointer ], :pointer\n attach_function :snmpv3_parse, [ :pointer, :pointer, :pointer, :pointer, :pointer ], :int\n attach_function :snmpv3_packet_build, [ :pointer, :pointer, :pointer, :pointer, :pointer, :uint ], :int\n# attach_function :snmpv3_packet_rbuild, [ :pointer, :pointer, :pointer, :pointer, :pointer, :uint ], :int\n attach_function :snmpv3_make_report, [ :pointer, :int ], :int\n attach_function :snmpv3_get_report_type, [ :pointer ], :int\n attach_function :snmp_pdu_parse, [ :pointer, :pointer, :pointer ], :int\n attach_function :snmpv3_scopedPDU_parse, [ :pointer, :pointer, :pointer ], :pointer\n attach_function :snmp_store, [ :string ], :void\n attach_function :snmp_shutdown, [ :string ], :void\n attach_function :snmp_pdu_add_variable, [ :pointer, :pointer, :uint, :u_char, :pointer, :size_t ], :pointer\n attach_function :snmp_varlist_add_variable, [ :pointer, :pointer, :uint, :u_char, :pointer, :uint ], :pointer\n attach_function :snmp_add_var, [ :pointer, :pointer, :uint, :char, :string ], :int\n attach_function :snmp_duplicate_objid, [ :pointer, :uint ], :pointer\n attach_function :snmp_increment_statistic, [ :int ], :u_int\n attach_function :snmp_increment_statistic_by, [ :int, :int ], :u_int\n attach_function :snmp_get_statistic, [ :int ], :u_int\n attach_function :snmp_init_statistics, [ ], :void\n attach_function :create_user_from_session, [ :pointer ], :int\n # attach_function :snmp_get_fd_for_session, [ :pointer ], :int\n attach_function :snmp_open_ex, [ :pointer, callback([ :pointer, :pointer, :pointer, :int ], :int), callback([ :pointer, :pointer, :pointer, :uint ], :int), callback([ :pointer, :pointer, :int ], :int), callback([ :pointer, :pointer, :pointer, :pointer ], :int), callback([ :pointer, :pointer, :pointer, :pointer, :pointer ], :int), callback([ :pointer, :uint ], :int) ], :pointer\n attach_function :snmp_set_do_debugging, [ :int ], :void\n attach_function :snmp_get_do_debugging, [ ], :int\n attach_function :snmp_error, [ :pointer, :pointer, :pointer, :pointer ], :void\n attach_function :snmp_sess_init, [ :pointer ], :void\n attach_function :snmp_sess_open, [ :pointer ], SnmpSession.typed_pointer\n attach_function :snmp_sess_pointer, [ :pointer ], :pointer\n attach_function :snmp_sess_session, [ :pointer ], SnmpSession.typed_pointer\n attach_function :snmp_sess_transport, [ :pointer ], :pointer\n attach_function :snmp_sess_transport_set, [ :pointer, :pointer ], :void\n attach_function :snmp_sess_add_ex, [ :pointer, :pointer, callback([ :pointer, :pointer, :pointer, :int ], :int), callback([ :pointer, :pointer, :pointer, :uint ], :int), callback([ :pointer, :pointer, :int ], :int), callback([ :pointer, :pointer, :pointer, :pointer ], :int), callback([ :pointer, :pointer, :pointer, :pointer, :pointer ], :int), callback([ :pointer, :uint ], :int), callback([ :pointer, :pointer, :uint ], :pointer) ], :pointer\n attach_function :snmp_sess_add, [ :pointer, :pointer, callback([ :pointer, :pointer, :pointer, :int ], :int), callback([ :pointer, :pointer, :int ], :int) ], :pointer\n attach_function :snmp_add, [ :pointer, :pointer, callback([ :pointer, :pointer, :pointer, :int ], :int), callback([ :pointer, :pointer, :int ], :int) ], :pointer\n attach_function :snmp_add_full, [ :pointer, :pointer, callback([ :pointer, :pointer, :pointer, :int ], :int), callback([ :pointer, :pointer, :pointer, :uint ], :int), callback([ :pointer, :pointer, :int ], :int), callback([ :pointer, :pointer, :pointer, :pointer ], :int), callback([ :pointer, :pointer, :pointer, :pointer, :pointer ], :int), callback([ :pointer, :uint ], :int), callback([ :pointer, :pointer, :uint ], :pointer) ], :pointer\n attach_function :snmp_sess_send, [ :pointer, :pointer ], :int\n attach_function :snmp_sess_async_send, [ :pointer, :pointer, :snmp_callback, :pointer ], :int\n attach_function :snmp_sess_select_info, [ :pointer, :pointer, :pointer, :pointer, :pointer ], :int\n attach_function :snmp_sess_read, [ :pointer, :pointer ], :int\n attach_function :snmp_sess_timeout, [ :pointer ], :void\n attach_function :snmp_sess_close, [ :pointer ], :int\n attach_function :snmp_sess_error, [ :pointer, :pointer, :pointer, :pointer ], :void\n attach_function :netsnmp_sess_log_error, [ :int, :string, :pointer ], :void\n attach_function :snmp_sess_perror, [ :string, :pointer ], :void\n attach_function :snmp_pdu_type, [ :int ], :string\n\n\n \n attach_function :asn_check_packet, [ :pointer, :uint ], :int\n attach_function :asn_parse_int, [ :pointer, :pointer, :pointer, :pointer, :uint ], :pointer\n attach_function :asn_build_int, [ :pointer, :pointer, :u_char, :pointer, :uint ], :pointer\n attach_function :asn_parse_unsigned_int, [ :pointer, :pointer, :pointer, :pointer, :uint ], :pointer\n attach_function :asn_build_unsigned_int, [ :pointer, :pointer, :u_char, :pointer, :uint ], :pointer\n attach_function :asn_parse_string, [ :pointer, :pointer, :pointer, :pointer, :pointer ], :pointer\n attach_function :asn_build_string, [ :pointer, :pointer, :u_char, :pointer, :uint ], :pointer\n attach_function :asn_parse_header, [ :pointer, :pointer, :pointer ], :pointer\n attach_function :asn_parse_sequence, [ :pointer, :pointer, :pointer, :u_char, :string ], :pointer\n attach_function :asn_build_header, [ :pointer, :pointer, :u_char, :uint ], :pointer\n attach_function :asn_build_sequence, [ :pointer, :pointer, :u_char, :uint ], :pointer\n attach_function :asn_parse_length, [ :pointer, :pointer ], :pointer\n attach_function :asn_build_length, [ :pointer, :pointer, :uint ], :pointer\n attach_function :asn_parse_objid, [ :pointer, :pointer, :pointer, :pointer, :pointer ], :pointer\n attach_function :asn_build_objid, [ :pointer, :pointer, :u_char, :pointer, :uint ], :pointer\n attach_function :asn_parse_null, [ :pointer, :pointer, :pointer ], :pointer\n attach_function :asn_build_null, [ :pointer, :pointer, :u_char ], :pointer\n attach_function :asn_parse_bitstring, [ :pointer, :pointer, :pointer, :pointer, :pointer ], :pointer\n attach_function :asn_build_bitstring, [ :pointer, :pointer, :u_char, :pointer, :uint ], :pointer\n attach_function :asn_parse_unsigned_int64, [ :pointer, :pointer, :pointer, :pointer, :uint ], :pointer\n attach_function :asn_build_unsigned_int64, [ :pointer, :pointer, :u_char, :pointer, :uint ], :pointer\n attach_function :asn_parse_signed_int64, [ :pointer, :pointer, :pointer, :pointer, :uint ], :pointer\n attach_function :asn_build_signed_int64, [ :pointer, :pointer, :u_char, :pointer, :uint ], :pointer\n attach_function :asn_build_float, [ :pointer, :pointer, :u_char, :pointer, :uint ], :pointer\n attach_function :asn_parse_float, [ :pointer, :pointer, :pointer, :pointer, :uint ], :pointer\n attach_function :asn_build_double, [ :pointer, :pointer, :u_char, :pointer, :uint ], :pointer\n attach_function :asn_parse_double, [ :pointer, :pointer, :pointer, :pointer, :uint ], :pointer\n\n attach_function :snmp_pdu_create, [:int], SnmpPdu.typed_pointer\n attach_function :get_node,[:string, :pointer, :pointer], :int\n attach_function :read_objid, [:string, :pointer, :pointer], :int\n attach_function :snmp_add_null_var, [:pointer, :pointer, :size_t], :pointer\n attach_function :snmp_sess_synch_response, [:pointer, :pointer, :pointer], :int\n attach_function :snmp_synch_response, [:pointer, :pointer, :pointer], :int\n attach_function :snmp_parse_oid, [:string, :pointer, :pointer], :pointer\n attach_function :snmp_api_errstring, [ :int ], :string\n attach_function :snmp_perror, [ :string ], :void\n attach_function :snmp_set_detail, [ :string ], :void\n \n attach_function :snmp_select_info, [:pointer, :pointer, :pointer, :pointer], :int\n attach_function :snmp_read, [:pointer], :void\n attach_function :generate_Ku, [:pointer, :int, :string, :int, :pointer, :pointer], :int\n\n\n\n # MIB functions\n attach_function :netsnmp_init_mib, [], :void\n attach_function :read_all_mibs, [], :void\n attach_function :add_mibdir, [:string], :int\n attach_function :read_mib, [:string], Tree.typed_pointer\n attach_function :netsnmp_read_module, [:string], Tree.typed_pointer\n attach_function :snmp_set_save_descriptions, [:int], :void\n\n attach_function :get_tree_head, [], Tree.typed_pointer\n attach_function :get_tree, [:pointer, :int, :pointer], Tree.typed_pointer\n #attach_function :send_easy_trap, [:int, :int], :void\n #attach_function :send_trap_vars, [:int, :int, :pointer], :void\n #attach_function :send_v2trap, [:pointer], :void\n\n def self.get_fd_set\n FFI::MemoryPointer.new(:pointer, 128)\n end\n \n\nend\nend\nend\n\n\n#module RubyWrapper\n# extend FFI::Library\n# ffi_lib FFI::CURRENT_PROCESS\n# attach_function :rb_thread_select, [:int, :pointer, :pointer, :pointer, :pointer], :int\n#end\n\n\n\nmodule FFI\n module LibC\n extend FFI::Library\n ffi_lib [FFI::CURRENT_PROCESS, 'c']\n\n typedef :pointer, :FILE\n typedef :uint32, :in_addr_t\n typedef :uint16, :in_port_t\n\n class Timeval < FFI::Struct\n layout :tv_sec, :time_t,\n :tv_usec, :suseconds_t\n end\n\n # Standard IO functions\n #@blocking = true # some undocumented voodoo that tells the next attach_function to release the GIL\n attach_function :select, [:int, :pointer, :pointer, :pointer, :pointer], :int\n attach_variable :errno, :int\n attach_function :malloc, [:size_t], :pointer\n attach_function :free, [:pointer], :void\n end\nend\n\n"}, "files_after": {"lib/net/snmp/session.rb": "require 'thread'\nrequire 'forwardable'\nrequire 'pp'\nmodule Net\n module SNMP\n class Session\n # == SNMP Session\n #\n # Provides API for interacting with a host with snmp\n extend Forwardable\n include Net::SNMP::Debug\n attr_accessor :struct, :callback, :requests, :peername, :community\n attr_reader :version\n def_delegator :@struct, :pointer\n #@sessions = []\n @lock = Mutex.new\n @sessions = {}\n\n class << self\n attr_accessor :sessions, :lock\n\n # Open a new session. Accepts a block which yields the session.\n #\n # Net::SNMP::Session.open(:peername => 'test.net-snmp.org', :community => 'public') do |sess|\n # pdu = sess.get([\"sysDescr.0\"])\n # pdu.print\n # end\n # Options:\n # * +peername+ - hostname\n # * +community+ - snmp community string. Default is public\n # * +version+ - snmp version. Possible values include 1, '2c', and 3. Default is 1.\n # * +timeout+ - snmp timeout in seconds\n # * +retries+ - snmp retries. default = 5\n # * +security_level+ - SNMPv3 only. default = Net::SNMP::Constants::SNMP_SEC_LEVEL_NOAUTH\n # * +auth_protocol+ - SNMPv3 only. default is nil (usmNoAuthProtocol). Possible values include :md5, :sha1, and nil\n # * +priv_protocol+ - SNMPv3 only. default is nil (usmNoPrivProtocol). Possible values include :des, :aes, and nil\n # * +context+ - SNMPv3 only.\n # * +username+ - SNMPv3 only.\n # * +auth_password+ - SNMPv3 only.\n # * +priv_password+ - SNMPv3 only. \n # Returns:\n # Net::SNMP::Session\n def open(options = {})\n session = new(options)\n if Net::SNMP::thread_safe\n Net::SNMP::Session.lock.synchronize {\n Net::SNMP::Session.sessions[session.sessid] = session\n }\n else\n Net::SNMP::Session.sessions[session.sessid] = session\n end\n if block_given?\n yield session\n end\n session\n end\n end\n\n def initialize(options = {})\n @timeout = options[:timeout] || 1\n @retries = options[:retries] || 5\n @requests = {}\n @peername = options[:peername] || 'localhost'\n @peername = \"#{@peername}:#{options[:port]}\" if options[:port]\n @community = options[:community] || \"public\"\n options[:community_len] = @community.length\n @version = options[:version] || 1\n options[:version] ||= Constants::SNMP_VERSION_1\n @version = options[:version] || 1\n #self.class.sessions << self\n @sess = Wrapper::SnmpSession.new(nil)\n Wrapper.snmp_sess_init(@sess.pointer)\n #options.each_pair {|k,v| ptr.send(\"#{k}=\", v)}\n @sess.community = FFI::MemoryPointer.from_string(@community)\n @sess.community_len = @community.length\n @sess.peername = FFI::MemoryPointer.from_string(@peername)\n #@sess.remote_port = options[:port] || 162\n @sess.version = case options[:version].to_s\n when '1'\n Constants::SNMP_VERSION_1\n when '2', '2c'\n Constants::SNMP_VERSION_2c\n when '3'\n Constants::SNMP_VERSION_3\n else\n Constants::SNMP_VERSION_1\n end\n debug \"setting timeout = #{@timeout} retries = #{@retries}\"\n @sess.timeout = @timeout * 1000000\n @sess.retries = @retries\n\n if @sess.version == Constants::SNMP_VERSION_3\n @sess.securityLevel = options[:security_level] || Constants::SNMP_SEC_LEVEL_NOAUTH\n @sess.securityAuthProto = case options[:auth_protocol]\n when :sha1\n OID.new(\"1.3.6.1.6.3.10.1.1.3\").pointer\n when :md5\n OID.new(\"1.3.6.1.6.3.10.1.1.2\").pointer\n when nil\n OID.new(\"1.3.6.1.6.3.10.1.1.1\").pointer\n end\n @sess.securityPrivProto = case options[:priv_protocol]\n when :aes\n OID.new(\"1.3.6.1.6.3.10.1.2.4\").pointer\n when :des\n OID.new(\"1.3.6.1.6.3.10.1.2.2\").pointer\n when nil\n OID.new(\"1.3.6.1.6.3.10.1.2.1\").pointer\n end\n \n @sess.securityAuthProtoLen = 10\n @sess.securityAuthKeyLen = Constants::USM_AUTH_KU_LEN\n\n @sess.securityPrivProtoLen = 10\n @sess.securityPrivKeyLen = Constants::USM_PRIV_KU_LEN\n\n\n if options[:context]\n @sess.contextName = FFI::MemoryPointer.from_string(options[:context])\n @sess.contextNameLen = options[:context].length\n end\n\n # Do not generate_Ku, unless we're Auth or AuthPriv\n unless @sess.securityLevel == Constants::SNMP_SEC_LEVEL_NOAUTH\n options[:auth_password] ||= options[:password] # backward compatability\n if options[:username].nil? or options[:auth_password].nil?\n raise Net::SNMP::Error.new \"SecurityLevel requires username and password\"\n end\n if options[:username]\n @sess.securityName = FFI::MemoryPointer.from_string(options[:username])\n @sess.securityNameLen = options[:username].length\n end\n\n auth_len_ptr = FFI::MemoryPointer.new(:size_t)\n auth_len_ptr.write_int(Constants::USM_AUTH_KU_LEN)\n auth_key_result = Wrapper.generate_Ku(@sess.securityAuthProto,\n @sess.securityAuthProtoLen,\n options[:auth_password],\n options[:auth_password].bytesize,\n @sess.securityAuthKey,\n auth_len_ptr)\n @sess.securityAuthKeyLen = auth_len_ptr.read_int\n\n if @sess.securityLevel == Constants::SNMP_SEC_LEVEL_AUTHPRIV\n priv_len_ptr = FFI::MemoryPointer.new(:size_t)\n priv_len_ptr.write_int(Constants::USM_PRIV_KU_LEN)\n\n # NOTE I know this is handing off the AuthProto, but generates a proper\n # key for encryption, and using PrivProto does not.\n priv_key_result = Wrapper.generate_Ku(@sess.securityAuthProto,\n @sess.securityAuthProtoLen,\n options[:priv_password],\n options[:priv_password].bytesize,\n @sess.securityPrivKey,\n priv_len_ptr)\n @sess.securityPrivKeyLen = priv_len_ptr.read_int\n end\n\n unless auth_key_result == Constants::SNMPERR_SUCCESS and priv_key_result == Constants::SNMPERR_SUCCESS\n Wrapper.snmp_perror(\"netsnmp\")\n end\n end\n end\n # General callback just takes the pdu, calls the session callback if any, then the request specific callback.\n\n @struct = Wrapper.snmp_sess_open(@sess.pointer)\n end\n\n\n # Close the snmp session and free associated resources.\n def close\n if Net::SNMP.thread_safe\n self.class.lock.synchronize {\n Wrapper..shutdown_usm()\n\t Wrapper.snmp_sess_close(@struct)\n self.class.sessions.delete(self.sessid)\n }\n else\n Wrapper.shutdown_usm()\n Wrapper.snmp_sess_close(@struct)\n self.class.sessions.delete(self.sessid)\n end\n end\n\n # Issue an SNMP GET Request.\n # See #send_pdu\n def get(oidlist, options = {}, &block)\n pdu = PDU.new(Constants::SNMP_MSG_GET)\n oidlist = [oidlist] unless oidlist.kind_of?(Array)\n oidlist.each do |oid|\n pdu.add_varbind(:oid => oid)\n end\n send_pdu(pdu, options, &block)\n end\n\n # Issue an SNMP GETNEXT Request\n # See #send_pdu\n def get_next(oidlist, options = {}, &block)\n pdu = PDU.new(Constants::SNMP_MSG_GETNEXT)\n oidlist = [oidlist] unless oidlist.kind_of?(Array)\n oidlist.each do |oid|\n pdu.add_varbind(:oid => oid)\n end\n send_pdu(pdu, options, &block)\n end\n\n # Issue an SNMP GETBULK Request\n # See #send_pdu\n def get_bulk(oidlist, options = {}, &block)\n pdu = PDU.new(Constants::SNMP_MSG_GETBULK)\n oidlist = [oidlist] unless oidlist.kind_of?(Array)\n oidlist.each do |oid|\n pdu.add_varbind(:oid => oid)\n end\n pdu.non_repeaters = options[:non_repeaters] || 0\n pdu.max_repetitions = options[:max_repetitions] || 10\n send_pdu(pdu, options, &block)\n end\n\n\n # Issue an SNMP Set Request\n # See #send_pdu\n def set(oidlist, options = {}, &block)\n pdu = PDU.new(Constants::SNMP_MSG_SET)\n oidlist.each do |oid|\n pdu.add_varbind(:oid => oid[0], :type => oid[1], :value => oid[2])\n end\n send_pdu(pdu, options, &block)\n end\n\n # Proxy getters to the C struct representing the session\n def method_missing(m, *args)\n if @struct.respond_to?(m)\n @struct.send(m, *args)\n else\n super\n end\n end\n\n def default_max_repeaters\n # We could do something based on transport here. 25 seems safe\n 25\n end\n\n # Raise a NET::SNMP::Error with the session attached\n def error(msg, options = {})\n #Wrapper.snmp_sess_perror(msg, @sess.pointer)\n err = Error.new({:session => self}.merge(options))\n err.print\n raise err, msg\n end\n \n\n # Check the session for SNMP responses from asynchronous SNMP requests\n # This method will check for new responses and call the associated\n # response callbacks.\n # +timeout+ A timeout of nil indicates a poll and will return immediately.\n # A value of false will block until data is available. Otherwise, pass\n # the number of seconds to block.\n # Returns the number of file descriptors handled.\n def select(timeout = nil)\n fdset = FFI::MemoryPointer.new(:pointer, Net::SNMP::Inline.fd_setsize / 8)\n num_fds = FFI::MemoryPointer.new(:int)\n tv_sec = timeout ? timeout.round : 0\n tv_usec = timeout ? (timeout - timeout.round) * 1000000 : 0\n tval = Wrapper::TimeVal.new(:tv_sec => tv_sec, :tv_usec => tv_usec)\n block = FFI::MemoryPointer.new(:int)\n if timeout.nil?\n block.write_int(0)\n else\n block.write_int(1)\n end\n\n Wrapper.snmp_sess_select_info(@struct, num_fds, fdset, tval.pointer, block )\n tv = (timeout == false ? nil : tval)\n #debug \"Calling select #{Time.now}\"\n num_ready = FFI::LibC.select(num_fds.read_int, fdset, nil, nil, tv)\n #debug \"Done select #{Time.now}\"\n if num_ready > 0\n Wrapper.snmp_sess_read(@struct, fdset)\n elsif num_ready == 0\n Wrapper.snmp_sess_timeout(@struct)\n elsif num_ready == -1\n # error. check snmp_error?\n error(\"select\")\n else\n error(\"wtf is wrong with select?\")\n end\n num_ready\n end\n\n alias :poll :select\n\n\n # Issue repeated getnext requests on each oid passed in until\n # the result is no longer a child. Returns a hash with the numeric\n # oid strings as keys.\n # XXX work in progress. only works synchronously (except with EM + fibers).\n # Need to do better error checking and use getbulk when avaiable.\n def walk(oidlist, options = {})\n oidlist = [oidlist] unless oidlist.kind_of?(Array)\n oidlist = oidlist.map {|o| o.kind_of?(OID) ? o : OID.new(o)}\n all_results = {}\n base_list = oidlist\n while(!oidlist.empty? && pdu = get_next(oidlist, options))\n debug \"===============================================================\"\n debug \"base_list = #{base_list}\"\n prev_base = base_list.dup\n oidlist = []\n #print_errors\n #pdu.print_errors\n pdu.varbinds.each_with_index do |vb, i|\n if prev_base[i].parent_of?(vb.oid) && vb.object_type != Constants::SNMP_ENDOFMIBVIEW\n # Still in subtree. Store results and add next oid to list\n debug \"adding #{vb.oid} to oidlist\"\n all_results[vb.oid.to_s] = vb.value\n oidlist << vb.oid\n else\n # End of subtree. Don't add to list or results\n debug \"End of subtree\"\n base_list.delete_at(i)\n debug \"not adding #{vb.oid}\"\n end\n # If get a pdu error, we can only tell the first failing varbind,\n # So we remove it and resend all the rest\n if pdu.error? && pdu.errindex == i + 1\n oidlist.pop # remove the bad oid\n debug \"caught error\"\n if pdu.varbinds.size > i+1\n # recram rest of oids on list\n ((i+1)..pdu.varbinds.size).each do |j|\n debug \"j = #{j}\"\n debug \"adding #{j} = #{prev_list[j]}\"\n oidlist << prev_list[j]\n end\n # delete failing oid from base_list\n base_list.delete_at(i)\n end\n break\n end\n end\n end\n if block_given?\n yield all_results\n end\n all_results\n end\n\n\n # Given a list of columns (e.g ['ifIndex', 'ifDescr'], will return a hash with\n # the indexes as keys and hashes as values.\n # puts sess.get_columns(['ifIndex', 'ifDescr']).inspect\n # {'1' => {'ifIndex' => '1', 'ifDescr' => 'lo0'}, '2' => {'ifIndex' => '2', 'ifDescr' => 'en0'}}\n def columns(columns, options = {})\n columns = columns.map {|c| c.kind_of?(OID) ? c : OID.new(c)}\n walk_hash = walk(columns, options)\n results = {}\n walk_hash.each do |k, v|\n oid = OID.new(k)\n results[oid.index] ||= {}\n results[oid.index][oid.node.label] = v\n end\n if block_given?\n yield results\n end\n results\n end\n\n # table('ifEntry'). You must pass the direct parent entry. Calls columns with all\n # columns in +table_name+\n def table(table_name, &blk)\n column_names = MIB::Node.get_node(table_name).children.collect {|c| c.oid }\n results = columns(column_names)\n if block_given?\n yield results\n end\n results\n end\n\n # Send a PDU\n # +pdu+ The Net::SNMP::PDU object to send. Usually created by Session.get, Session.getnext, etc.\n # +callback+ An optional callback. It should take two parameters, status and response_pdu.\n # If no +callback+ is given, the call will block until the response is available and will return\n # the response pdu. If an error occurs, a Net::SNMP::Error will be thrown.\n # If +callback+ is passed, the PDU will be sent and +send_pdu+ will return immediately. You must\n # then call Session.select to invoke the callback. This is usually done in some sort of event loop.\n # See Net::SNMP::Dispatcher.\n #\n # If you're running inside eventmachine and have fibers (ruby 1.9, jruby, etc), sychronous calls will\n # actually run asynchronously behind the scenes. Just run Net::SNMP::Dispatcher.fiber_loop in your\n # reactor.\n #\n # pdu = Net::SNMP::PDU.new(Constants::SNMP_MSG_GET)\n # pdu.add_varbind(:oid => 'sysDescr.0')\n # session.send_pdu(pdu) do |status, pdu|\n # if status == :success\n # pdu.print\n # elsif status == :timeout\n # puts \"Timed Out\"\n # else\n # puts \"A problem occurred\"\n # end\n # end\n # session.select(false) #block until data is ready. Callback will be called.\n # begin\n # result = session.send_pdu(pdu)\n # puts result.inspect\n # rescue Net::SNMP::Error => e\n # puts e.message\n # end\n def send_pdu(pdu, options = {}, &callback)\n if options[:blocking]\n return send_pdu_blocking(pdu)\n end\n if block_given?\n @requests[pdu.reqid] = callback\n debug \"calling async_send\"\n if Wrapper.snmp_sess_async_send(@struct, pdu.pointer, sess_callback, nil) == 0\n error(\"snmp_get async failed\")\n end\n #pdu.free\n nil\n else\n if defined?(EM) && EM.reactor_running? && defined?(Fiber)\n f = Fiber.current\n send_pdu pdu do | op, response_pdu |\n #pdu.free\n f.resume([op, response_pdu])\n end\n op, result = Fiber.yield\n case op\n when :timeout\n raise TimeoutError.new, \"timeout\"\n when :send_failed\n error \"send failed\"\n when :success\n result\n when :connect, :disconnect\n nil #does this ever happen?\n else\n error \"unknown operation #{op}\"\n end\n else\n send_pdu_blocking(pdu)\n end\n end\n end\n\n def send_pdu_blocking(pdu)\n response_ptr = FFI::MemoryPointer.new(:pointer)\n if [Constants::SNMP_MSG_TRAP, Constants::SNMP_MSG_TRAP2].include?(pdu.command)\n status = Wrapper.snmp_sess_send(@struct, pdu.pointer)\n if status == 0\n error(\"snmp_sess_send\")\n end\n else\n status = Wrapper.snmp_sess_synch_response(@struct, pdu.pointer, response_ptr)\n unless status == Constants::STAT_SUCCESS\n error(\"snmp_sess_synch_response\", :status => status)\n end\n end\n if [Constants::SNMP_MSG_TRAP, Constants::SNMP_MSG_TRAP2].include?(pdu.command)\n 1\n else\n PDU.new(response_ptr.read_pointer)\n end\n end\n\n def errno\n get_error\n @errno\n end\n\n # The SNMP Session error code\n def snmp_err\n get_error\n @snmp_err\n end\n\n # The SNMP Session error message\n def error_message\n get_error\n @snmp_msg\n end\n\n def print_errors\n puts \"errno: #{errno}, snmp_err: #{@snmp_err}, message: #{@snmp_msg}\"\n end\n private\n def sess_callback\n @sess_callback ||= FFI::Function.new(:int, [:int, :pointer, :int, :pointer, :pointer]) do |operation, session, reqid, pdu_ptr, magic|\n debug \"in callback #{operation.inspect} #{session.inspect}\"\n op = case operation\n when Constants::NETSNMP_CALLBACK_OP_RECEIVED_MESSAGE\n :success\n when Constants::NETSNMP_CALLBACK_OP_TIMED_OUT\n :timeout\n when Constants::NETSNMP_CALLBACK_OP_SEND_FAILED\n :send_failed\n when Constants::NETSNMP_CALLBACK_OP_CONNECT\n :connect\n when Constants::NETSNMP_CALLBACK_OP_DISCONNECT\n :disconnect\n else\n error \"Invalid PDU Operation\"\n end\n\n if @requests[reqid]\n pdu = PDU.new(pdu_ptr)\n callback_return = @requests[reqid].call(op, pdu)\n @requests.delete(reqid)\n callback_return == false ? 0 : 1 #if callback returns false (failure), pass it on. otherwise return 1 (success)\n else\n 0# Do what here? Can this happen? Maybe request timed out and was deleted?\n end\n end\n end\n def get_error\n errno_ptr = FFI::MemoryPointer.new(:int)\n snmp_err_ptr = FFI::MemoryPointer.new(:int)\n msg_ptr = FFI::MemoryPointer.new(:pointer)\n Wrapper.snmp_sess_error(@struct.pointer, errno_ptr, snmp_err_ptr, msg_ptr)\n @errno = errno_ptr.read_int\n @snmp_err = snmp_err_ptr.read_int\n @snmp_msg = msg_ptr.read_pointer.read_string\n end\n\n\n end\n end\nend\n\n\n", "lib/net/snmp/wrapper.rb": "module Net\nmodule SNMP\nmodule Wrapper\n extend NiceFFI::Library\n ffi_lib \"libnetsnmp\"\n #ffi_lib \"netsnmp\"\n typedef :u_long, :oid\n\n class Counter64 < NiceFFI::Struct\n layout(\n :high, :u_long,\n :low, :u_long\n )\n end\n\n class TimeVal < NiceFFI::Struct\n layout(:tv_sec, :long, :tv_usec, :long)\n end\n def self.print_timeval(tv)\n puts \"tv_sec = #{tv.tv_sec}, tv_usec = #{tv.tv_usec} \"\n end\n\n\n class NetsnmpVardata < FFI::Union\n layout(\n :integer, :pointer,\n :string, :pointer,\n :objid, :pointer,\n :bitstring, :pointer,\n :counter64, :pointer,\n :float, :pointer,\n :double, :pointer\n )\n end\n\n def self.print_varbind(v)\n puts \"---------------------VARBIND------------------------\"\n puts %{\n name_length #{v.name_length}\n name #{v.name.read_array_of_long(v.name_length).join(\".\")}\n type = #{v.type}\n\n }\n end\n # puts \"Vardata size = #{NetsnmpVardata.size}\"\n class VariableList < NiceFFI::Struct\n layout(\n :next_variable, :pointer,\n :name, :pointer,\n :name_length, :size_t,\n :type, :u_char,\n :val, NetsnmpVardata,\n :val_len, :size_t,\n :name_loc, [:oid, Net::SNMP::MAX_OID_LEN],\n :buf, [:u_char, 40],\n :data, :pointer,\n :dataFreeHook, callback([ :pointer ], :void),\n :index, :int\n ) \n end\n \n #puts \"VariableList size = #{VariableList.size}\"\n\n def self.print_pdu(p)\n puts \"--------------PDU---------------\"\n puts %{\n version = #{p.version}\n command = #{p.command}\n errstat = #{p.errstat}\n errindex = #{p.errindex}\n }\n v = p.variables.pointer\n puts \"-----VARIABLES------\"\n while !v.null? do\n var = VariableList.new v\n print_varbind(var)\n v = var.next_variable\n end\n \n end\n class SnmpPdu < NiceFFI::Struct\n layout(\n :version, :long,\n :command, :int,\n :reqid, :long,\n :msgid, :long,\n :transid, :long,\n :sessid, :long,\n :errstat, :long,\n :errindex, :long,\n :time, :u_long,\n :flags, :u_long,\n :securityModel, :int,\n :securityLevel, :int,\n :msgParseModel, :int,\n :transport_data, :pointer,\n :transport_data_length, :int,\n :tDomain, :pointer,\n :tDomainLen, :size_t,\n :variables, VariableList.typed_pointer,\n :community, :pointer,\n :community_len, :size_t,\n :enterprise, :pointer,\n :enterprise_length, :size_t,\n :trap_type, :long,\n :specific_type, :long,\n :agent_addr, [:uchar, 4],\n :contextEngineID, :pointer,\n :contextEngineIDLen, :size_t,\n :contextName, :pointer,\n :contextNameLen, :size_t,\n :securityEngineID, :pointer,\n :securityEngineIDLen, :size_t,\n :securityName, :pointer,\n :securityNameLen, :size_t,\n :priority, :int,\n :range_subid, :int,\n :securityStateRef, :pointer\n )\n\n end\n # puts \"snmppdu size = #{SnmpPdu.size}\"\n callback(:snmp_callback, [ :int, :pointer, :int, :pointer, :pointer ], :int)\n callback(:netsnmp_callback, [ :int, :pointer, :int, :pointer, :pointer ], :int)\n def self.print_session(s)\n puts \"-------------------SESSION---------------------\"\n puts %{\n peername = #{s.peername.read_string}\n community = #{s.community.read_string(s.community_len)}\n s_errno = #{s.s_errno}\n s_snmp_errno = #{s.s_snmp_errno}\n securityAuthKey = #{s.securityAuthKey.to_ptr.read_string}\n\n }\n end\n class SnmpSession < NiceFFI::Struct\n layout(\n :version, :long,\n :retries, :int,\n :timeout, :long,\n :flags, :u_long,\n :subsession, :pointer,\n :next, :pointer,\n :peername, :pointer,\n :remote_port, :u_short,\n :localname, :pointer,\n :local_port, :u_short,\n :authenticator, callback([ :pointer, :pointer, :pointer, :uint ], :pointer),\n :callback, :netsnmp_callback,\n :callback_magic, :pointer,\n :s_errno, :int,\n :s_snmp_errno, :int,\n :sessid, :long,\n :community, :pointer,\n :community_len, :size_t,\n :rcvMsgMaxSize, :size_t,\n :sndMsgMaxSize, :size_t,\n :isAuthoritative, :u_char,\n :contextEngineID, :pointer,\n :contextEngineIDLen, :size_t,\n :engineBoots, :u_int,\n :engineTime, :u_int,\n :contextName, :pointer,\n :contextNameLen, :size_t,\n :securityEngineID, :pointer,\n :securityEngineIDLen, :size_t,\n :securityName, :pointer,\n :securityNameLen, :size_t,\n :securityAuthProto, :pointer,\n :securityAuthProtoLen, :size_t,\n :securityAuthKey, [:u_char, 32],\n :securityAuthKeyLen, :size_t,\n :securityAuthLocalKey, :pointer,\n :securityAuthLocalKeyLen, :size_t,\n :securityPrivProto, :pointer,\n :securityPrivProtoLen, :size_t,\n :securityPrivKey, [:u_char, 32],\n :securityPrivKeyLen, :size_t,\n :securityPrivLocalKey, :pointer,\n :securityPrivLocalKeyLen, :size_t,\n :securityModel, :int,\n :securityLevel, :int,\n :paramName, :pointer,\n :securityInfo, :pointer,\n :myvoid, :pointer\n )\n end\n class Tree < NiceFFI::Struct\n layout(\n :child_list, :pointer,\n :next_peer, :pointer,\n :next, :pointer,\n :parent, :pointer,\n :label, :string,\n :subid, :u_long,\n :modid, :int,\n :number_modules, :int,\n :module_list, :pointer,\n :tc_index, :int,\n :type, :int,\n :access, :int,\n :status, :int,\n :enums, :pointer,\n :ranges, :pointer,\n :indexes, :pointer,\n :augments, :pointer,\n :varbinds, :pointer,\n :hint, :pointer,\n :units, :pointer,\n :printomat, callback([:pointer, :pointer, :pointer, :int, :pointer, :pointer, :pointer, :pointer], :int),\n :printer, callback([:pointer, :pointer, :pointer, :pointer, :pointer], :void),\n :description, :pointer,\n :reference, :pointer,\n :reported, :int,\n :defaultValue, :pointer\n )\n end\n class IndexList < NiceFFI::Struct\n layout(\n :next, :pointer,\n :ilabel, :pointer,\n :isimplied, :char\n )\n end\n\n\n# puts \"snmp_session size = #{SnmpSession.size}\"\n attach_function :snmp_open, [ :pointer ], SnmpSession.typed_pointer\n attach_function :snmp_errstring, [:int], :string\n attach_function :snmp_close, [ :pointer ], :int\n attach_function :snmp_close_sessions, [ ], :int\n attach_function :snmp_send, [ :pointer, :pointer ], :int\n attach_function :snmp_async_send, [ :pointer, :pointer, :netsnmp_callback, :pointer ], :int\n attach_function :snmp_read, [ :pointer ], :void\n attach_function :snmp_free_pdu, [ :pointer ], :void\n attach_function :snmp_free_var, [ :pointer ], :void\n attach_function :snmp_free_varbind, [ :pointer ], :void\n attach_function :snmp_select_info, [ :pointer, :pointer, :pointer, :pointer ], :int\n attach_function :snmp_timeout, [ ], :void\n\n attach_function :snmp_get_next_msgid, [ ], :long\n attach_function :snmp_get_next_reqid, [ ], :long\n attach_function :snmp_get_next_sessid, [ ], :long\n attach_function :snmp_get_next_transid, [ ], :long\n attach_function :snmp_oid_compare, [ :pointer, :uint, :pointer, :uint ], :int\n attach_function :snmp_oid_ncompare, [ :pointer, :uint, :pointer, :uint, :uint ], :int\n attach_function :snmp_oidtree_compare, [ :pointer, :uint, :pointer, :uint ], :int\n attach_function :snmp_oidsubtree_compare, [ :pointer, :uint, :pointer, :uint ], :int\n attach_function :netsnmp_oid_compare_ll, [ :pointer, :uint, :pointer, :uint, :pointer ], :int\n attach_function :netsnmp_oid_equals, [ :pointer, :uint, :pointer, :uint ], :int\n# attach_function :netsnmp_oid_tree_equals, [ :pointer, :uint, :pointer, :uint ], :int\n attach_function :netsnmp_oid_is_subtree, [ :pointer, :uint, :pointer, :uint ], :int\n attach_function :netsnmp_oid_find_prefix, [ :pointer, :uint, :pointer, :uint ], :int\n attach_function :netsnmp_transport_open_client, [:string, :pointer], :pointer\n attach_function :init_snmp, [ :string ], :void\n attach_function :snmp_pdu_build, [ :pointer, :pointer, :pointer ], :pointer\n attach_function :snmpv3_parse, [ :pointer, :pointer, :pointer, :pointer, :pointer ], :int\n attach_function :snmpv3_packet_build, [ :pointer, :pointer, :pointer, :pointer, :pointer, :uint ], :int\n# attach_function :snmpv3_packet_rbuild, [ :pointer, :pointer, :pointer, :pointer, :pointer, :uint ], :int\n attach_function :snmpv3_make_report, [ :pointer, :int ], :int\n attach_function :snmpv3_get_report_type, [ :pointer ], :int\n attach_function :snmp_pdu_parse, [ :pointer, :pointer, :pointer ], :int\n attach_function :snmpv3_scopedPDU_parse, [ :pointer, :pointer, :pointer ], :pointer\n attach_function :snmp_store, [ :string ], :void\n attach_function :snmp_shutdown, [ :string ], :void\n attach_function :snmp_pdu_add_variable, [ :pointer, :pointer, :uint, :u_char, :pointer, :size_t ], :pointer\n attach_function :snmp_varlist_add_variable, [ :pointer, :pointer, :uint, :u_char, :pointer, :uint ], :pointer\n attach_function :snmp_add_var, [ :pointer, :pointer, :uint, :char, :string ], :int\n attach_function :snmp_duplicate_objid, [ :pointer, :uint ], :pointer\n attach_function :snmp_increment_statistic, [ :int ], :u_int\n attach_function :snmp_increment_statistic_by, [ :int, :int ], :u_int\n attach_function :snmp_get_statistic, [ :int ], :u_int\n attach_function :snmp_init_statistics, [ ], :void\n attach_function :create_user_from_session, [ :pointer ], :int\n # attach_function :snmp_get_fd_for_session, [ :pointer ], :int\n attach_function :snmp_open_ex, [ :pointer, callback([ :pointer, :pointer, :pointer, :int ], :int), callback([ :pointer, :pointer, :pointer, :uint ], :int), callback([ :pointer, :pointer, :int ], :int), callback([ :pointer, :pointer, :pointer, :pointer ], :int), callback([ :pointer, :pointer, :pointer, :pointer, :pointer ], :int), callback([ :pointer, :uint ], :int) ], :pointer\n attach_function :snmp_set_do_debugging, [ :int ], :void\n attach_function :snmp_get_do_debugging, [ ], :int\n attach_function :snmp_error, [ :pointer, :pointer, :pointer, :pointer ], :void\n attach_function :snmp_sess_init, [ :pointer ], :void\n attach_function :snmp_sess_open, [ :pointer ], SnmpSession.typed_pointer\n attach_function :snmp_sess_pointer, [ :pointer ], :pointer\n attach_function :snmp_sess_session, [ :pointer ], SnmpSession.typed_pointer\n attach_function :snmp_sess_transport, [ :pointer ], :pointer\n attach_function :snmp_sess_transport_set, [ :pointer, :pointer ], :void\n attach_function :snmp_sess_add_ex, [ :pointer, :pointer, callback([ :pointer, :pointer, :pointer, :int ], :int), callback([ :pointer, :pointer, :pointer, :uint ], :int), callback([ :pointer, :pointer, :int ], :int), callback([ :pointer, :pointer, :pointer, :pointer ], :int), callback([ :pointer, :pointer, :pointer, :pointer, :pointer ], :int), callback([ :pointer, :uint ], :int), callback([ :pointer, :pointer, :uint ], :pointer) ], :pointer\n attach_function :snmp_sess_add, [ :pointer, :pointer, callback([ :pointer, :pointer, :pointer, :int ], :int), callback([ :pointer, :pointer, :int ], :int) ], :pointer\n attach_function :snmp_add, [ :pointer, :pointer, callback([ :pointer, :pointer, :pointer, :int ], :int), callback([ :pointer, :pointer, :int ], :int) ], :pointer\n attach_function :snmp_add_full, [ :pointer, :pointer, callback([ :pointer, :pointer, :pointer, :int ], :int), callback([ :pointer, :pointer, :pointer, :uint ], :int), callback([ :pointer, :pointer, :int ], :int), callback([ :pointer, :pointer, :pointer, :pointer ], :int), callback([ :pointer, :pointer, :pointer, :pointer, :pointer ], :int), callback([ :pointer, :uint ], :int), callback([ :pointer, :pointer, :uint ], :pointer) ], :pointer\n attach_function :snmp_sess_send, [ :pointer, :pointer ], :int\n attach_function :snmp_sess_async_send, [ :pointer, :pointer, :snmp_callback, :pointer ], :int\n attach_function :snmp_sess_select_info, [ :pointer, :pointer, :pointer, :pointer, :pointer ], :int\n attach_function :snmp_sess_read, [ :pointer, :pointer ], :int\n attach_function :snmp_sess_timeout, [ :pointer ], :void\n attach_function :snmp_sess_close, [ :pointer ], :int\n attach_function :snmp_sess_error, [ :pointer, :pointer, :pointer, :pointer ], :void\n attach_function :netsnmp_sess_log_error, [ :int, :string, :pointer ], :void\n attach_function :snmp_sess_perror, [ :string, :pointer ], :void\n attach_function :snmp_pdu_type, [ :int ], :string\n\n\n \n attach_function :asn_check_packet, [ :pointer, :uint ], :int\n attach_function :asn_parse_int, [ :pointer, :pointer, :pointer, :pointer, :uint ], :pointer\n attach_function :asn_build_int, [ :pointer, :pointer, :u_char, :pointer, :uint ], :pointer\n attach_function :asn_parse_unsigned_int, [ :pointer, :pointer, :pointer, :pointer, :uint ], :pointer\n attach_function :asn_build_unsigned_int, [ :pointer, :pointer, :u_char, :pointer, :uint ], :pointer\n attach_function :asn_parse_string, [ :pointer, :pointer, :pointer, :pointer, :pointer ], :pointer\n attach_function :asn_build_string, [ :pointer, :pointer, :u_char, :pointer, :uint ], :pointer\n attach_function :asn_parse_header, [ :pointer, :pointer, :pointer ], :pointer\n attach_function :asn_parse_sequence, [ :pointer, :pointer, :pointer, :u_char, :string ], :pointer\n attach_function :asn_build_header, [ :pointer, :pointer, :u_char, :uint ], :pointer\n attach_function :asn_build_sequence, [ :pointer, :pointer, :u_char, :uint ], :pointer\n attach_function :asn_parse_length, [ :pointer, :pointer ], :pointer\n attach_function :asn_build_length, [ :pointer, :pointer, :uint ], :pointer\n attach_function :asn_parse_objid, [ :pointer, :pointer, :pointer, :pointer, :pointer ], :pointer\n attach_function :asn_build_objid, [ :pointer, :pointer, :u_char, :pointer, :uint ], :pointer\n attach_function :asn_parse_null, [ :pointer, :pointer, :pointer ], :pointer\n attach_function :asn_build_null, [ :pointer, :pointer, :u_char ], :pointer\n attach_function :asn_parse_bitstring, [ :pointer, :pointer, :pointer, :pointer, :pointer ], :pointer\n attach_function :asn_build_bitstring, [ :pointer, :pointer, :u_char, :pointer, :uint ], :pointer\n attach_function :asn_parse_unsigned_int64, [ :pointer, :pointer, :pointer, :pointer, :uint ], :pointer\n attach_function :asn_build_unsigned_int64, [ :pointer, :pointer, :u_char, :pointer, :uint ], :pointer\n attach_function :asn_parse_signed_int64, [ :pointer, :pointer, :pointer, :pointer, :uint ], :pointer\n attach_function :asn_build_signed_int64, [ :pointer, :pointer, :u_char, :pointer, :uint ], :pointer\n attach_function :asn_build_float, [ :pointer, :pointer, :u_char, :pointer, :uint ], :pointer\n attach_function :asn_parse_float, [ :pointer, :pointer, :pointer, :pointer, :uint ], :pointer\n attach_function :asn_build_double, [ :pointer, :pointer, :u_char, :pointer, :uint ], :pointer\n attach_function :asn_parse_double, [ :pointer, :pointer, :pointer, :pointer, :uint ], :pointer\n\n attach_function :snmp_pdu_create, [:int], SnmpPdu.typed_pointer\n attach_function :get_node,[:string, :pointer, :pointer], :int\n attach_function :read_objid, [:string, :pointer, :pointer], :int\n attach_function :snmp_add_null_var, [:pointer, :pointer, :size_t], :pointer\n attach_function :snmp_sess_synch_response, [:pointer, :pointer, :pointer], :int\n attach_function :snmp_synch_response, [:pointer, :pointer, :pointer], :int\n attach_function :snmp_parse_oid, [:string, :pointer, :pointer], :pointer\n attach_function :snmp_api_errstring, [ :int ], :string\n attach_function :snmp_perror, [ :string ], :void\n attach_function :snmp_set_detail, [ :string ], :void\n \n attach_function :snmp_select_info, [:pointer, :pointer, :pointer, :pointer], :int\n attach_function :snmp_read, [:pointer], :void\n attach_function :generate_Ku, [:pointer, :int, :string, :int, :pointer, :pointer], :int\n\n\n\n # MIB functions\n attach_function :netsnmp_init_mib, [], :void\n attach_function :read_all_mibs, [], :void\n attach_function :add_mibdir, [:string], :int\n attach_function :read_mib, [:string], Tree.typed_pointer\n attach_function :netsnmp_read_module, [:string], Tree.typed_pointer\n attach_function :snmp_set_save_descriptions, [:int], :void\n\n attach_function :get_tree_head, [], Tree.typed_pointer\n attach_function :get_tree, [:pointer, :int, :pointer], Tree.typed_pointer\n #attach_function :send_easy_trap, [:int, :int], :void\n #attach_function :send_trap_vars, [:int, :int, :pointer], :void\n #attach_function :send_v2trap, [:pointer], :void\n \n attach_function :shutdown_usm, [], :void\n\n def self.get_fd_set\n FFI::MemoryPointer.new(:pointer, 128)\n end\n \n\nend\nend\nend\n\n\n#module RubyWrapper\n# extend FFI::Library\n# ffi_lib FFI::CURRENT_PROCESS\n# attach_function :rb_thread_select, [:int, :pointer, :pointer, :pointer, :pointer], :int\n#end\n\n\n\nmodule FFI\n module LibC\n extend FFI::Library\n ffi_lib [FFI::CURRENT_PROCESS, 'c']\n\n typedef :pointer, :FILE\n typedef :uint32, :in_addr_t\n typedef :uint16, :in_port_t\n\n class Timeval < FFI::Struct\n layout :tv_sec, :time_t,\n :tv_usec, :suseconds_t\n end\n\n # Standard IO functions\n #@blocking = true # some undocumented voodoo that tells the next attach_function to release the GIL\n attach_function :select, [:int, :pointer, :pointer, :pointer, :pointer], :int\n attach_variable :errno, :int\n attach_function :malloc, [:size_t], :pointer\n attach_function :free, [:pointer], :void\n end\nend\n\n"}} -{"repo": "dpavlin/android-command-line", "pr_number": 4, "title": "add adb shell command to pull wildcard files, watch the '()' containing filenames", "state": "closed", "merged_at": "2019-12-02T16:56:30Z", "additions": 1, "deletions": 1, "files_changed": ["adb-pull-wildcard.sh"], "files_before": {"adb-pull-wildcard.sh": "#!/bin/sh -e\n\ntest -z \"$1\" && echo \"usage: $0 /sdcard/DCIM/Camera/*20121111*\" && exit 1\n\nls $1 | tr -d '\\r' | xargs -i sh -c 'echo {} ; adb pull {} .'\n\n"}, "files_after": {"adb-pull-wildcard.sh": "#!/bin/sh -e\n\ntest -z \"$1\" && echo \"usage: $0 /sdcard/DCIM/Camera/*20121111*\" && exit 1\n\nadb shell ls \"$1\" | tr -d '\\r' | xargs -i sh -c 'echo \"{}\" ; adb pull \"{}\" .'\n\n"}} -{"repo": "michaeldwan/michaeldwan.com", "pr_number": 1, "title": "Update plugins", "state": "closed", "merged_at": null, "additions": 10, "deletions": 13, "files_changed": ["source/_plugins/alias_generator.rb", "source/_plugins/ext.rb"], "files_before": {"source/_plugins/alias_generator.rb": "# Alias Generator for Posts.\n#\n# Generates redirect pages for posts with aliases set in the YAML Front Matter.\n#\n# Place the full path of the alias (place to redirect from) inside the\n# destination post's YAML Front Matter. One or more aliases may be given.\n#\n# Example Post Configuration:\n#\n# ---\n# layout: post\n# title: \"How I Keep Limited Pressing Running\"\n# alias: /post/6301645915/how-i-keep-limited-pressing-running/index.html\n# ---\n#\n# Example Post Configuration:\n#\n# ---\n# layout: post\n# title: \"How I Keep Limited Pressing Running\"\n# alias: [/first-alias/index.html, /second-alias/index.html]\n# ---\n#\n# Author: Thomas Mango\n# Site: http://thomasmango.com\n# Plugin Source: http://github.com/tsmango/jekyll_alias_generator\n# Site Source: http://github.com/tsmango/thomasmango.com\n# PLugin License: MIT\n\nmodule Jekyll\n\n class AliasGenerator < Generator\n\n def generate(site)\n @site = site\n\n process_posts\n process_pages\n end\n\n def process_posts\n @site.posts.each do |post|\n generate_aliases(post.url, post.data['alias'])\n end\n end\n\n def process_pages\n @site.pages.each do |page|\n generate_aliases(page.destination('').gsub(/index\\.(html|htm)$/, ''), page.data['alias'])\n end\n end\n\n def generate_aliases(destination_path, aliases)\n alias_paths ||= Array.new\n alias_paths << aliases\n alias_paths.compact!\n\n alias_paths.flatten.each do |alias_path|\n alias_path = alias_path.to_s\n\n alias_dir = File.extname(alias_path).empty? ? alias_path : File.dirname(alias_path)\n alias_file = File.extname(alias_path).empty? ? \"index.html\" : File.basename(alias_path)\n\n fs_path_to_dir = File.join(@site.dest, alias_dir)\n alias_index_path = File.join(alias_dir, alias_file)\n\n FileUtils.mkdir_p(fs_path_to_dir)\n\n File.open(File.join(fs_path_to_dir, alias_file), 'w') do |file|\n file.write(alias_template(destination_path))\n end\n\n (alias_index_path.split('/').size + 1).times do |sections|\n @site.static_files << Jekyll::AliasFile.new(@site, @site.dest, alias_index_path.split('/')[0, sections].join('/'), '')\n end\n end\n end\n\n def alias_template(destination_path)\n <<-EOF\n \n \n \n \n \n \n \n \n EOF\n end\n end\n\n class AliasFile < StaticFile\n require 'set'\n\n def destination(dest)\n File.join(dest, @dir)\n end\n\n def modified?\n return false\n end\n\n def write(dest)\n return true\n end\n end\nend\n", "source/_plugins/ext.rb": "require \"jekyll-assets\"\nrequire \"jekyll-assets/compass\"\n"}, "files_after": {"source/_plugins/alias_generator.rb": "# Alias Generator for Posts.\n#\n# Generates redirect pages for posts with aliases set in the YAML Front Matter.\n#\n# Place the full path of the alias (place to redirect from) inside the\n# destination post's YAML Front Matter. One or more aliases may be given.\n#\n# Example Post Configuration:\n#\n# ---\n# layout: post\n# title: \"How I Keep Limited Pressing Running\"\n# alias: /post/6301645915/how-i-keep-limited-pressing-running/index.html\n# ---\n#\n# Example Post Configuration:\n#\n# ---\n# layout: post\n# title: \"How I Keep Limited Pressing Running\"\n# alias: [/first-alias/index.html, /second-alias/index.html]\n# ---\n#\n# Author: Thomas Mango\n# Site: http://thomasmango.com\n# Plugin Source: http://github.com/tsmango/jekyll_alias_generator\n# Site Source: http://github.com/tsmango/tsmango.github.com\n# Plugin License: MIT\n\nmodule Jekyll\n\n class AliasGenerator < Generator\n\n def generate(site)\n @site = site\n\n process_posts\n process_pages\n end\n\n def process_posts\n @site.posts.docs.each do |post|\n generate_aliases(post.url, post.data['alias'])\n end\n end\n\n def process_pages\n @site.pages.each do |page|\n generate_aliases(page.destination('').gsub(/index\\.(html|htm)$/, ''), page.data['alias'])\n end\n end\n\n def generate_aliases(destination_path, aliases)\n alias_paths ||= Array.new\n alias_paths << aliases\n alias_paths.compact!\n\n alias_paths.flatten.each do |alias_path|\n alias_path = File.join('/', alias_path.to_s)\n\n alias_dir = File.extname(alias_path).empty? ? alias_path : File.dirname(alias_path)\n alias_file = File.extname(alias_path).empty? ? \"index.html\" : File.basename(alias_path)\n\n fs_path_to_dir = File.join(@site.dest, alias_dir)\n alias_sections = alias_dir.split('/')[1..-1]\n\n FileUtils.mkdir_p(fs_path_to_dir)\n\n File.open(File.join(fs_path_to_dir, alias_file), 'w') do |file|\n file.write(alias_template(destination_path))\n end\n\n alias_sections.size.times do |sections|\n @site.static_files << Jekyll::AliasFile.new(@site, @site.dest, alias_sections[0, sections + 1].join('/'), '')\n end\n @site.static_files << Jekyll::AliasFile.new(@site, @site.dest, alias_dir, alias_file)\n end\n end\n\n def alias_template(destination_path)\n <<-EOF\n \n \n \n \n \n \n \n \n EOF\n end\n end\n\n class AliasFile < StaticFile\n require 'set'\n\n def modified?\n return false\n end\n\n def write(dest)\n return true\n end\n end\nend\n", "source/_plugins/ext.rb": "require \"jekyll-assets\"\nrequire \"compass\"\n"}} -{"repo": "zaius/bright", "pr_number": 2, "title": "Update bright.c", "state": "open", "merged_at": null, "additions": 1, "deletions": 1, "files_changed": ["bright.c"], "files_before": {"bright.c": "/*\n * Copyright (c) 2010, David Kelso \n *\n * Permission to use, copy, modify, and/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n */\n\n#include \n\n// How far the brightness should move with each step.\n#define JUMP 0xa\n\nint main(int argc, char *argv[]) {\n unsigned int value, location[3];\n int success;\n char command[100];\n FILE *fp;\n\n if (geteuid()) {\n printf(\"Must be root\\n\");\n return 1;\n }\n\n if (argc != 2) {\n printf(\"One argument required: ++ or --\\n\");\n return 1;\n }\n\n // Get the PCI location of the VGA adapter\n fp = popen(\"lspci | grep VGA\", \"r\");\n success = fscanf(fp, \"%20d:%2d.%1d VGA\", &location[0], &location[1], &location[2]);\n pclose(fp);\n\n if (!success) {\n printf(\"lspci couldn't find your vga adapter\\n\");\n return 1;\n }\n\n\n // Get the existing value of the brightness\n snprintf(command, sizeof command, \"setpci -s %02d:%02d.%01d F4.B\", \n location[0], location[1], location[2]);\n fp = popen(command, \"r\");\n success = fscanf(fp, \"%x\", &value);\n pclose(fp);\n\n if (!success) {\n printf(\"setpci didn't work\\n\");\n return 1;\n }\n\n // Increase of decrease the existing brightness value\n if (strcmp(argv[1], \"++\") == 0) {\n value += JUMP;\n if (value > 0xff) value = 0xff;\n } else if (strcmp(argv[1], \"--\") == 0) {\n if (value < JUMP) value = 0;\n else value -= JUMP;\n } else {\n printf(\"++ to increase, -- to decrease\\n\");\n return 1;\n }\n\n // Set the new brightness value\n snprintf(command, sizeof command, \"setpci -s %02d:%02d.%01d F4.B=%x\", \n location[0], location[1], location[2], value);\n system(command);\n\n return 0;\n}\n"}, "files_after": {"bright.c": "/*\n * Copyright (c) 2010, David Kelso \n *\n * Permission to use, copy, modify, and/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n */\n\n#include \n\n// How far the brightness should move with each step.\n#define JUMP 0xa\n\nint main(int argc, char *argv[]) {\n unsigned int value, location[3];\n int success;\n char command[100];\n FILE *fp;\n\n if (geteuid()) {\n printf(\"Must be root\\n\");\n return 1;\n }\n\n if (argc != 2) {\n printf(\"One argument required: ++ or --\\n\");\n return 1;\n }\n\n // Get the PCI location of the VGA adapter\n fp = popen(\"lspci | grep VGA\", \"r\");\n success = fscanf(fp, \"%20d:%2d.%1d VGA\", &location[0], &location[1], &location[2]);\n pclose(fp);\n\n if (!success) {\n printf(\"lspci couldn't find your vga adapter\\n\");\n return 1;\n }\n\n\n // Get the existing value of the brightness\n snprintf(command, sizeof command, \"setpci -s %02d:%02d.%01d F4.B\", \n location[0], location[1], location[2]);\n fp = popen(command, \"r\");\n success = fscanf(fp, \"%x\", &value);\n pclose(fp);\n\n if (!success) {\n printf(\"setpci didn't work\\n\");\n return 1;\n }\n\n // Increase or decrease the existing brightness value\n if (strcmp(argv[1], \"++\") == 0) {\n value += JUMP;\n if (value > 0xff) value = 0xff;\n } else if (strcmp(argv[1], \"--\") == 0) {\n if (value < JUMP) value = 0;\n else value -= JUMP;\n } else {\n printf(\"++ to increase, -- to decrease\\n\");\n return 1;\n }\n\n // Set the new brightness value\n snprintf(command, sizeof command, \"setpci -s %02d:%02d.%01d F4.B=%x\", \n location[0], location[1], location[2], value);\n system(command);\n\n return 0;\n}\n"}} -{"repo": "olkarls/has_permalink", "pr_number": 18, "title": "Don't autofix for the Objects own ID", "state": "open", "merged_at": null, "additions": 5, "deletions": 1, "files_changed": ["lib/has_permalink.rb"], "files_before": {"lib/has_permalink.rb": "require 'friendly_url'\n\nmodule HasPermalink\n require 'railtie' if defined?(Rails) && Rails.version >= \"3\"\n\n def has_permalink(generate_from = :title, auto_fix_duplication = false)\n unless included_modules.include? InstanceMethods\n class_attribute :generate_from\n class_attribute :auto_fix_duplication\n extend ClassMethods\n include InstanceMethods\n end\n\n self.generate_from = generate_from\n self.auto_fix_duplication = auto_fix_duplication\n before_validation :generate_permalink\n end\n\n module ClassMethods\n # Makes it possible to generate permalinks for\n # all instances of self:\n #\n # Product.generate_permalinks\n #\n def generate_permalinks\n self.all.each do |item|\n item.generate_permalink\n item.save\n end\n end\n end\n\n module InstanceMethods\n include FriendlyUrl\n\n # Generate permalink for the instance if the permalink is empty or nil.\n def generate_permalink\n self.permalink = fix_duplication(normalize(self.send(generate_from))) if permalink.blank?\n end\n\n # Generate permalink for the instance and overwrite any existing value.\n def generate_permalink!\n self.permalink = fix_duplication(normalize(self.send(generate_from)))\n end\n\n # Override to send permalink as params[:id]\n def to_param\n permalink\n end\n\n private\n\n # Autofix duplication of permalinks\n def fix_duplication(permalink)\n if auto_fix_duplication\n n = self.class.where([\"permalink = ?\", permalink]).count\n\n if n > 0\n links = self.class.where([\"permalink LIKE ?\", \"#{permalink}%\"]).order(\"id\")\n\n number = 0\n\n links.each_with_index do |link, index|\n if link.permalink =~ /#{permalink}-\\d*\\.?\\d+?$/\n new_number = link.permalink.match(/-(\\d*\\.?\\d+?)$/)[1].to_i\n number = new_number if new_number > number\n end\n end\n resolve_duplication(permalink, number + 1)\n else\n permalink\n end\n else\n permalink\n end\n end\n\n def resolve_duplication(permalink, number)\n \"#{permalink}-#{number}\"\n end\n end\nend\n\nActiveRecord::Base.send :extend, HasPermalink\n"}, "files_after": {"lib/has_permalink.rb": "require 'friendly_url'\n\nmodule HasPermalink\n require 'railtie' if defined?(Rails) && Rails.version >= \"3\"\n\n def has_permalink(generate_from = :title, auto_fix_duplication = false)\n unless included_modules.include? InstanceMethods\n class_attribute :generate_from\n class_attribute :auto_fix_duplication\n extend ClassMethods\n include InstanceMethods\n end\n\n self.generate_from = generate_from\n self.auto_fix_duplication = auto_fix_duplication\n before_validation :generate_permalink\n end\n\n module ClassMethods\n # Makes it possible to generate permalinks for\n # all instances of self:\n #\n # Product.generate_permalinks\n #\n def generate_permalinks\n self.all.each do |item|\n item.generate_permalink\n item.save\n end\n end\n end\n\n module InstanceMethods\n include FriendlyUrl\n\n # Generate permalink for the instance if the permalink is empty or nil.\n def generate_permalink\n self.permalink = fix_duplication(normalize(self.send(generate_from))) if permalink.blank?\n end\n\n # Generate permalink for the instance and overwrite any existing value.\n def generate_permalink!\n self.permalink = fix_duplication(normalize(self.send(generate_from)))\n end\n\n # Override to send permalink as params[:id]\n def to_param\n permalink\n end\n\n private\n\n # Autofix duplication of permalinks\n def fix_duplication(permalink)\n if auto_fix_duplication\n n = if id.present?\n self.class.where([\"permalink = ? AND id != ?\", permalink, id]).count\n else\n self.class.where([\"permalink = ?\", permalink]).count\n end\n\n if n > 0\n links = self.class.where([\"permalink LIKE ?\", \"#{permalink}%\"]).order(\"id\")\n\n number = 0\n\n links.each_with_index do |link, index|\n if link.permalink =~ /#{permalink}-\\d*\\.?\\d+?$/\n new_number = link.permalink.match(/-(\\d*\\.?\\d+?)$/)[1].to_i\n number = new_number if new_number > number\n end\n end\n resolve_duplication(permalink, number + 1)\n else\n permalink\n end\n else\n permalink\n end\n end\n\n def resolve_duplication(permalink, number)\n \"#{permalink}-#{number}\"\n end\n end\nend\n\nActiveRecord::Base.send :extend, HasPermalink\n"}} -{"repo": "collegeman/stringtotime", "pr_number": 2, "title": "Streamline the java StringToTime code", "state": "open", "merged_at": null, "additions": 1125, "deletions": 789, "files_changed": ["src/main/java/com/clutch/dates/DateEditor.java", "src/main/java/com/clutch/dates/StringToTime.java", "src/main/java/com/clutch/dates/StringToTimeException.java", "src/test/java/com/clutch/dates/StringToTimeTest.java"], "files_before": {"src/main/java/com/clutch/dates/DateEditor.java": "package com.clutch.dates;\n\nimport java.beans.PropertyEditorSupport;\nimport java.util.Date;\n\nimport org.springframework.beans.PropertyEditorRegistrar;\nimport org.springframework.beans.PropertyEditorRegistry;\n\npublic class DateEditor extends PropertyEditorSupport implements PropertyEditorRegistrar {\n\n\t@Override\n\tpublic void setAsText(String text) throws IllegalArgumentException {\n\t\tObject date = StringToTime.date(text);\n\t\tif (!Boolean.FALSE.equals(date))\n\t\t\tsetValue((Date) date);\n\t\telse\n\t\t\tthrow new IllegalArgumentException(String.format(\"[%s] is not a date.\", text));\n\t}\n\n//\t@Override\n\tpublic void registerCustomEditors(PropertyEditorRegistry registry) {\n\t\tregistry.registerCustomEditor(Date.class, new DateEditor());\n\t\tregistry.registerCustomEditor(Date.class, new DateEditor());\n\t}\n\t\n}\n", "src/main/java/com/clutch/dates/StringToTime.java": "package com.clutch.dates;\n\nimport java.text.ParseException;\nimport java.text.SimpleDateFormat;\nimport java.util.Calendar;\nimport java.util.Date;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\nimport org.apache.commons.logging.Log;\nimport org.apache.commons.logging.LogFactory;\n\n/**\n * A Java implementation of the PHP function strtotime(String, int): accepts various expressions of time\n * in String format, and instantiates a {@link java.util.Date} object. \n * \n *

\n * There are two ways to use StringToTime to parse dates: \n *

    \n *
  • static methods ({@link #time(Object)}, {@link #date(Object)}, {@link #cal(Object)})
  • \n *
  • creating an instance of StringToTime with {@link #StringToTime(Object)}
  • \n *
\n *

\n * \n *

The static methods provide a UNIX-style timestamp, a {@link java.util.Date} instance, or a \n * {@link java.util.Calendar} instance. In the event the time expression provided is invalid, \n * these methods return Boolean.FALSE.

\n * \n *

Instances of StringToTime inherit from {@link java.util.Date}; so, when instantiated\n * with an expression that the algorithm recognizes, the resulting instance of StringToTime\n * can be passed to any method or caller requiring a {@link java.util.Date} object. Unlike the static methods,\n * attempting to create a StringToTime instance with an invalid expression of time \n * results in a {@link StringToTimeException}.

\n * \n *

Valid expressions of time

\n * \n *

All expressions are case-insensitive.

\n * \n *
    \n *
  • now (equal to new Date())
  • \n *
  • today (equal to StringToTime(\"00:00:00.000\"))
  • \n *
  • midnight (equal to StringToTime(\"00:00:00.000 +24 hours\"))
  • \n *
  • morning or this morning (by default, equal toStringToTime(\"07:00:00.000\"))
  • \n *
  • noon (by default, equal to StringToTime(\"12:00:00.000\")
  • \n *
  • afternoon or this afternoon (by default, equal to StringToTime(\"13:00:00.000\")
  • \n *
  • evening or this evening (by default, equal to StringToTime(\"17:00:00.000\")
  • \n *
  • tonight (by default, equal to StringToTime(\"20:00:00.000\")
  • \n *
  • tomorrow (by default, equal to StringToTime(\"now +24 hours\"))
  • \n *
  • tomorrow morning (by default, equal to StringToTime(\"morning +24 hours\"))
  • \n *
  • noon tomorrow or tomorrow noon (by default, equal to StringToTime(\"noon +24 hours\"))
  • \n *
  • tomorrow afternoon (by default, equal to StringToTime(\"afternoon +24 hours\"))
  • \n *
  • yesterday (by default, equal to StringToTime(\"now -24 hours\"))
  • \n *
  • all the permutations of yesterday and morning, noon, afternoon, and evening
  • \n *
  • October 26, 1981 or Oct 26, 1981
  • \n *
  • October 26 or Oct 26
  • \n *
  • 26 October 1981
  • \n *
  • 26 Oct 1981
  • \n *
  • 26 Oct 81
  • \n *
  • 10/26/1981 or 10-26-1981
  • \n *
  • 10/26/81 or 10-26-81
  • \n *
  • 1981/10/26 or 1981-10-26
  • \n *
  • 10/26 or 10-26
  • \n *
\n * \n * @author Aaron Collegeman acollegeman@clutch-inc.com\n * @since JRE 1.5.0\n * @see http://us3.php.net/manual/en/function.strtotime.php\n */\npublic class StringToTime extends Date {\n\n\tprivate static final long serialVersionUID = 7889493424407815134L;\n\n\tprivate static final Log log = LogFactory.getLog(StringToTime.class);\n\t\n\t// default SimpleDateFormat string is the standard MySQL date format\n\tprivate static final String defaultSimpleDateFormat = \"yyyy-MM-dd HH:mm:ss.SSS\";\n\t\n\t// An expression of time (hour)(:(minute))?((:(second))(.(millisecond))?)?( *(am?|pm?))?(RFC 822 time zone|general time zone)?\n\tprivate static final String timeExpr = \"(\\\\d{1,2})(:(\\\\d{1,2}))?(:(\\\\d{1,2})(\\\\.(\\\\d{1,3}))?)?( *(am?|pm?))?( *\\\\-\\\\d{4}|[a-z]{3}|[a-z ]+)?\";\n\t\n\t/** Patterns and formats recognized by the algorithm; first match wins, so insert most specific patterns first. */\n\tprivate static final PatternAndFormat[] known = {\n\t\t\n\t\t// TODO: ISO 8601 and derivatives\n\t\t\n\t\t// just the year\n\t\tnew PatternAndFormat(\n\t\t\tPattern.compile(\"\\\\d{4}\"),\n\t\t\tnew Format(FormatType.YEAR)\n\t\t),\n\t\t\n\t\t// decrement, e.g., -1 day\n\t\tnew PatternAndFormat(\n\t\t\tPattern.compile(\"\\\\-( *\\\\d{1,} +[^ ]+){1,}\", Pattern.CASE_INSENSITIVE),\n\t\t\tnew Format(FormatType.DECREMENT)\n\t\t),\n\t\t\n\t\t// increment, e.g., +1 day\n\t\tnew PatternAndFormat(\n\t\t\tPattern.compile(\"\\\\+?( *\\\\d{1,} +[^ ]+){1,}\", Pattern.CASE_INSENSITIVE),\n\t\t\tnew Format(FormatType.INCREMENT)\n\t\t),\n\t\t\n\t\t// e.g., October 26 and Oct 26\n\t\tnew PatternAndFormat(\n\t\t\tPattern.compile(\"([a-z]+) +(\\\\d{1,2})\", Pattern.CASE_INSENSITIVE),\n\t\t\tnew Format(FormatType.MONTH_AND_DATE)\n\t\t),\n\t\t\n\t\t// e.g., 26 October 1981, or 26 Oct 1981, or 26 Oct 81\n\t\tnew PatternAndFormat(\n\t\t\tPattern.compile(\"\\\\d{1,2} +[a-z]+ +(\\\\d{2}|\\\\d{4})\", Pattern.CASE_INSENSITIVE),\n\t\t\tnew Format(\"d MMM y\")\t\n\t\t),\n\t\t\n\t\t// now or today\n\t\tnew PatternAndFormat(\n\t\t\tPattern.compile(\"(midnight|now|today|(this +)?(morning|afternoon|evening)|tonight|noon( +tomorrow)?|tomorrow|tomorrow +(morning|afternoon|evening|night|noon)?|yesterday|yesterday +(morning|afternoon|evening|night)?)\", Pattern.CASE_INSENSITIVE),\n\t\t\tnew Format(FormatType.WORD)\n\t\t),\n\t\t\n\t\t// time, 24-hour and 12-hour\n\t\tnew PatternAndFormat(\n\t\t\tPattern.compile(timeExpr, Pattern.CASE_INSENSITIVE),\n\t\t\tnew Format(FormatType.TIME)\n\t\t),\n\t\t\n\t\t// e.g., October 26, 1981 or Oct 26, 1981\n\t\tnew PatternAndFormat(\n\t\t\tPattern.compile(\"[a-z]+ +\\\\d{1,2} *, *(\\\\d{2}|\\\\d{4})\", Pattern.CASE_INSENSITIVE),\n\t\t\tnew Format(\"MMM d, y\")\n\t\t),\n\t\t\n\t\t// e.g., 10/26/1981 or 10/26/81\n\t\tnew PatternAndFormat(\n\t\t\tPattern.compile(\"\\\\d{1,2}/\\\\d{1,2}/\\\\d{2,4}\"),\n\t\t\tnew Format(\"M/d/y\")\n\t\t),\n\t\t\n\t\t// e.g., 10-26-1981 or 10-26-81\n\t\tnew PatternAndFormat(\n\t\t\tPattern.compile(\"\\\\d{1,2}\\\\-\\\\d{1,2}\\\\-\\\\d{2,4}\"),\n\t\t\tnew Format(\"M-d-y\")\n\t\t),\n\t\t\n\t\t// e.g., 10/26 or 10-26\n\t\tnew PatternAndFormat(\n\t\t\tPattern.compile(\"(\\\\d{1,2})(/|\\\\-)(\\\\d{1,2})\"),\n\t\t\tnew Format(FormatType.MONTH_AND_DATE_WITH_SLASHES)\n\t\t),\n\t\t\n\t\t// e.g., 1981/10/26\n\t\tnew PatternAndFormat(\n\t\t\tPattern.compile(\"\\\\d{4}/\\\\d{1,2}/\\\\d{1,2}\"),\n\t\t\tnew Format(\"y/M/d\")\n\t\t),\n\t\t\n\t\t// e.g., 1981-10-26\n\t\tnew PatternAndFormat(\n\t\t\tPattern.compile(\"\\\\d{4}\\\\-\\\\d{1,2}\\\\-\\\\d{1,2}\"),\n\t\t\tnew Format(\"y-M-d\")\n\t\t),\n\t\t\n\t\t// e.g., October or Oct\n\t\tnew PatternAndFormat(\n\t\t\tPattern.compile(\"(Jan(uary)?|Feb(ruary)?|Mar(ch)?|Apr(il)?|May|Jun(e)?|Jul(y)?|Aug(ust)?|Sep(tember)?|Oct(ober)?|Nov(ember)?|Dec(ember)?)\", Pattern.CASE_INSENSITIVE),\n\t\t\tnew Format(FormatType.MONTH)\n\t\t),\n\t\t\n\t\t// e.g., Tuesday or Tue\n\t\tnew PatternAndFormat(\n\t\t\tPattern.compile(\"(Sun(day)?|Mon(day)?|Tue(sday)?|Wed(nesday)?|Thu(rsday)?|Fri(day)?|Sat(urday)?)\", Pattern.CASE_INSENSITIVE),\n\t\t\tnew Format(FormatType.DAY_OF_WEEK)\n\t\t),\n\t\t\t\t\n\t\t// next, e.g., next Tuesday\n\t\tnew PatternAndFormat(\n\t\t\tPattern.compile(\"next +(.*)\", Pattern.CASE_INSENSITIVE),\n\t\t\tnew Format(FormatType.NEXT)\n\t\t),\n\t\t\n\t\t// last, e.g., last Tuesday\n\t\tnew PatternAndFormat(\n\t\t\tPattern.compile(\"last +(.*)\", Pattern.CASE_INSENSITIVE),\n\t\t\tnew Format(FormatType.LAST)\n\t\t),\n\t\t\n\t\t// compound statement\n\t\tnew PatternAndFormat(\n\t\t\tPattern.compile(\"(.*) +(((\\\\+|\\\\-){1}.*)|\"+timeExpr+\")$\", Pattern.CASE_INSENSITIVE),\n\t\t\tnew Format(FormatType.COMPOUND)\n\t\t)\n\t\t\n\t\t\n\t};\n\t\n\t/** Date/Time string parsed */\n\tprivate Object dateTimeString;\n\t\n\t/** The format to use in {@link #toString()) */\n\tprivate String simpleDateFormat;\n\t\n\t/** The {@link java.util.Date} interpreted from {@link #dateTimeString}, or {@link java.lang.Boolean} false */\n\tprivate Object date;\n\t\n\t\n\tpublic StringToTime() {\n\t\tsuper();\n\t\tthis.date = new Date(this.getTime());\n\t}\n\t\n\tpublic StringToTime(Date date) {\n\t\tsuper(date.getTime());\n\t\tthis.date = new Date(this.getTime());\n\t}\n\t\n\tpublic StringToTime(Object dateTimeString) {\n\t\tthis(dateTimeString, new Date(), defaultSimpleDateFormat);\n\t}\n\t\n\tpublic StringToTime(Object dateTimeString, String simpleDateFormat) {\n\t\tthis(dateTimeString, new Date(), simpleDateFormat);\n\t}\n\t\n\tpublic StringToTime(Object dateTimeString, Date now) {\n\t\tthis(dateTimeString, now, defaultSimpleDateFormat);\n\t}\n\t\n\tpublic StringToTime(Object dateTimeString, Long now) {\n\t\tthis(dateTimeString, new Date(now), defaultSimpleDateFormat);\n\t}\n\t\n\tpublic StringToTime(Object dateTimeString, Integer now) {\n\t\tthis(dateTimeString, new Date(new Long(now)), defaultSimpleDateFormat);\n\t}\n\t\n\tpublic StringToTime(Object dateTimeString, Date now, String simpleDateFormat) {\n\t\tsuper(0);\n\t\tassert dateTimeString != null;\n assert now != null;\n assert simpleDateFormat != null;\n\t\t\n\t\tthis.dateTimeString = dateTimeString;\n\t\tthis.simpleDateFormat = simpleDateFormat;\n\t\t\n\t\tdate = StringToTime.date(dateTimeString, now);\n\t\tif (!Boolean.FALSE.equals(date))\n\t\t\tsetTime(((Date) date).getTime());\n\t\telse\n\t\t\tthrow new StringToTimeException(dateTimeString);\n\t}\n\t\n\t/**\n\t * @return {@link java.util.Date#getTime()}\n\t */\n\tpublic long getTime() {\n\t\treturn super.getTime();\n\t}\n\t\n\t/**\n\t * @return Calendar set to timestamp {@link java.util.Date#getTime()}\n\t */\n\tpublic Calendar getCal() {\n\t\tCalendar cal = Calendar.getInstance();\n\t\tcal.setTimeInMillis(super.getTime());\n\t\treturn cal;\n\t}\n\t\n\t/**\n\t * @param simpleDateFormat\n\t * @see {@link SimpleDateFormat}\n\t * @return Date formatted according to simpleDateFormat\n\t */\n\tpublic String format(String simpleDateFormat) {\n\t\treturn new SimpleDateFormat(simpleDateFormat).format(this);\n\t}\n\t\n\t/**\n\t * @return If {@link #simpleDateFormat} provided in constructor, then attempts to format date\n\t * accordingly; otherwise, returns the String value of {@link java.util.Date#getTime()}.\n\t */\n\tpublic String toString() {\n\t\tif (simpleDateFormat != null)\n\t\t\treturn new SimpleDateFormat(simpleDateFormat).format(this);\n\t\telse\n\t\t\treturn new SimpleDateFormat(\"yyyy/dd/MM\").format(this); //String.valueOf(super.getTime());\n\t}\n\t\n\t\n\t/**\n\t * A single parameter version of {@link #time(String, Date)}, passing a new instance of {@link java.util.Date} as the\n\t * second parameter.\n\t * @param dateTimeString\n\t * @return A {@link java.lang.Long} timestamp representative of dateTimeString, or {@link java.lang.Boolean} false.\n\t * @see #time(String, Date)\n\t */\n\tpublic static Object time(Object dateTimeString) {\n\t\treturn time(dateTimeString, new Date());\n\t}\n\t\n\t/**\n\t * Parse dateTimeString and produce a timestamp. \n\t * @param dateTimeString\n\t * @param now \n\t * @return
    \n\t *
  • If equal to "now", return the number of milliseconds since January 1, 1970 or the value of now.
  • \n\t *
  • If an incremental or decremental statement, e.g., +1 hour or -1 week, or a composite thereof, e.g., +1 hour 1 minute 1 second,\n\t * returns a date equal to the increment/decrement plus the value of now.\n\t *
\n\t */\n\tpublic static Object time(Object dateTimeString, Date now) {\n\t\ttry {\n\t\t\tif (dateTimeString == null)\n\t\t\t\treturn Boolean.FALSE;\n\t\t\telse {\n\t\t\t\tString trimmed = String.valueOf(dateTimeString).trim();\n\t\t\t\tfor(PatternAndFormat paf : known) {\n\t\t\t\t\tMatcher m = paf.matches(trimmed);\n\t\t\t\t\tif (m.matches()) {\n\t\t\t\t\t\tLong time = paf.parse(trimmed, now, m);\n\t\t\t\t\t\t//System.out.println(String.format(\"[%s] triggered format [%s]: %s\", dateTimeString, paf.f, new Date(time)));\n\t\t\t\t\t\tif (log.isDebugEnabled())\n\t\t\t\t\t\t\tlog.debug(String.format(\"[%s] triggered format [%s]: %s\", dateTimeString, paf.f, new Date(time)));\n\t\t\t\t\t\treturn time;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t// no match\n\t\t\t\tif (log.isDebugEnabled())\n\t\t\t\t\tlog.debug(String.format(\"Unrecognized date/time string [%s]\", dateTimeString));\n\t\t\t\treturn Boolean.FALSE;\n\t\t\t}\n\t\t} catch (Exception e) { // thrown by various features of the parser\n\t\t\tif (!Boolean.parseBoolean(System.getProperty(StringToTime.class+\".EXCEPTION_ON_PARSE_FAILURE\", \"false\"))) {\n\t\t\t\tif (log.isDebugEnabled())\n\t\t\t\t\tlog.debug(String.format(\"Failed to parse [%s] into a java.util.Date instance\", dateTimeString));\n\t\t\t\treturn Boolean.FALSE;\n\t\t\t}\n\t\t\telse\n\t\t\t\tthrow new StringToTimeException(dateTimeString, e);\n\t\t}\n\t}\n\t\n\tprivate static ParserResult getParserResult(String trimmedDateTimeString, Date now) throws ParseException {\n\t\tfor(PatternAndFormat paf : known) {\n\t\t\tMatcher m = paf.matches(trimmedDateTimeString);\n\t\t\tif (m.matches()) {\n\t\t\t\tlog.debug(String.format(\"Date/time string [%s] triggered format [%s]\", trimmedDateTimeString, paf.f));\n\t\t\t\treturn new ParserResult(paf.parse(trimmedDateTimeString, now, m), paf.f.type);\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn null;\n\t}\n\t\n\tpublic static Object date(Object dateTimeString) {\n\t\treturn date(dateTimeString, new Date());\n\t}\n\t\n\tpublic static Object date(Object dateTimeString, Date now) {\n\t\tObject time = time(dateTimeString, now);\n\t\treturn (Boolean.FALSE.equals(time)) ? Boolean.FALSE : new Date((Long) time);\n\t}\n\t\n\tpublic static Object cal(Object dateTimeString) {\n\t\treturn cal(dateTimeString, new Date());\n\t}\n\t\n\tpublic static Object cal(Object dateTimeString, Date now) {\n\t\tObject date = date(dateTimeString, now);\n\t\tif (Boolean.FALSE.equals(date))\n\t\t\treturn Boolean.FALSE;\n\t\telse {\n\t\t\tCalendar cal = Calendar.getInstance();\n\t\t\tcal.setTime((Date) date);\n\t\t\treturn cal;\n\t\t}\n\t}\n\t\n\tprivate static class PatternAndFormat {\n\t\tpublic Pattern p;\n\t\tpublic Format f;\n\t\t\n\t\tpublic PatternAndFormat(Pattern p, Format f) {\n\t\t\tthis.p = p;\n\t\t\tthis.f = f;\n\t\t}\n\t\t\n\t\tpublic Matcher matches(String dateTimeString) {\n\t\t\treturn p.matcher(dateTimeString);\n\t\t}\n\t\t\n\t\tpublic Long parse(String dateTimeString, Date now, Matcher m) throws ParseException {\n\t\t\treturn f.parse(dateTimeString, now, m).getTime();\n\t\t}\n\t}\n\t\n\tprivate static class ParserResult {\n\t\tpublic FormatType type;\n\t\tpublic Long timestamp;\n\t\t\n\t\tpublic ParserResult(Long timestamp, FormatType type) {\n\t\t\tthis.timestamp = timestamp;\n\t\t\tthis.type = type;\n\t\t}\n\t}\n\t\n\tprivate static class Format {\n\t\t\n\t\tprivate static Pattern unit = Pattern.compile(\"(\\\\d{1,}) +(s(ec(ond)?)?|mo(n(th)?)?|(hour|hr?)|d(ay)?|(w(eek)?|wk)|m(in(ute)?)?|(y(ear)?|yr))s?\");\n\t\t\n\t\tprivate static Pattern removeExtraSpaces = Pattern.compile(\" +\");\n\t\t\n\t\tprivate static Map translateDayOfWeek = new HashMap();\n\t\t\n\t\tstatic {\n\t\t\ttranslateDayOfWeek.put(\"sunday\", 1);\n\t\t\ttranslateDayOfWeek.put(\"sun\", 1);\n\t\t\ttranslateDayOfWeek.put(\"monday\", 2);\n\t\t\ttranslateDayOfWeek.put(\"mon\", 2);\n\t\t\ttranslateDayOfWeek.put(\"tuesday\", 3);\n\t\t\ttranslateDayOfWeek.put(\"tue\", 3);\n\t\t\ttranslateDayOfWeek.put(\"wednesday\", 4);\n\t\t\ttranslateDayOfWeek.put(\"wed\", 4);\n\t\t\ttranslateDayOfWeek.put(\"thursday\", 5);\n\t\t\ttranslateDayOfWeek.put(\"thu\", 5);\n\t\t\ttranslateDayOfWeek.put(\"friday\", 6);\n\t\t\ttranslateDayOfWeek.put(\"fri\", 6);\n\t\t\ttranslateDayOfWeek.put(\"saturday\", 7);\n\t\t\ttranslateDayOfWeek.put(\"sat\", 7);\n\t\t}\n\t\t\n\t\tprivate String sdf;\n\t\t\n\t\tprivate FormatType type;\n\t\t\n\t\tpublic Format(FormatType type) {\n\t\t\tthis.type = type;\n\t\t}\n\t\t\n\t\tpublic Format(String sdf) {\n\t\t\tthis.sdf = sdf;\n\t\t}\n\t\t\n\t\tpublic String toString() {\n\t\t\tif (sdf != null)\n\t\t\t\treturn sdf;\n\t\t\telse\n\t\t\t\treturn type.toString();\n\t\t}\n\t\t \n\t\tpublic Date parse(String dateTimeString, Date now, Matcher m) throws ParseException {\n\t\t\tif (sdf != null)\n\t\t\t\treturn new SimpleDateFormat(sdf).parse(dateTimeString);\n\t\t\telse {\n\t\t\t\tdateTimeString = removeExtraSpaces.matcher(dateTimeString).replaceAll(\" \").toLowerCase();\n\t\t\t\t\n\t\t\t\ttry {\n\t\t\t\t\tCalendar cal = Calendar.getInstance();\n\t\t\t\t\tcal.setTime(now);\n\t\t\t\t\t\n\t\t\t\t\t// word expressions, e.g., \"now\" and \"today\" and \"tonight\"\n\t\t\t\t\tif (type == FormatType.WORD) {\n\t\t\t\t\t\tif (\"now\".equals(dateTimeString))\n\t\t\t\t\t\t\treturn (now != null ? now : new Date());\n\t\t\t\t\t\t\n\t\t\t\t\t\telse if (\"today\".equals(dateTimeString)) {\n\t\t\t\t\t\t\tcal.set(Calendar.HOUR_OF_DAY, 0);\n\t\t\t\t\t\t\tcal.set(Calendar.MINUTE, 0);\n\t\t\t\t\t\t\tcal.set(Calendar.SECOND, 0);\n\t\t\t\t\t\t\tcal.set(Calendar.MILLISECOND, 0);\n\t\t\t\t\t\t\treturn new Date(cal.getTimeInMillis());\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\telse if (\"morning\".equals(dateTimeString) || \"this morning\".equals(dateTimeString)) {\n\t\t\t\t\t\t\t// by default, this morning begins at 07:00:00.000\n\t\t\t\t\t\t\tint thisMorningBeginsAt = Integer.parseInt(System.getProperty(StringToTime.class+\".THIS_MORNING_BEGINS_AT\", \"7\"));\n\t\t\t\t\t\t\tcal.set(Calendar.HOUR_OF_DAY, thisMorningBeginsAt);\n\t\t\t\t\t\t\tcal.set(Calendar.MINUTE, 0);\n\t\t\t\t\t\t\tcal.set(Calendar.SECOND, 0);\n\t\t\t\t\t\t\tcal.set(Calendar.MILLISECOND, 0);\n\t\t\t\t\t\t\treturn new Date(cal.getTimeInMillis());\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\telse if (\"noon\".equals(dateTimeString)) {\n\t\t\t\t\t\t\t// noon is 12:00:00.000\n\t\t\t\t\t\t\tcal.set(Calendar.HOUR_OF_DAY, 12);\n\t\t\t\t\t\t\tcal.set(Calendar.MINUTE, 0);\n\t\t\t\t\t\t\tcal.set(Calendar.SECOND, 0);\n\t\t\t\t\t\t\tcal.set(Calendar.MILLISECOND, 0);\n\t\t\t\t\t\t\treturn new Date(cal.getTimeInMillis());\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\telse if (\"afternoon\".equals(dateTimeString) || \"this afternoon\".equals(dateTimeString)) {\n\t\t\t\t\t\t\t// by default, this afternoon begins at 13:00:00.000\n\t\t\t\t\t\t\tint thisAfternoonBeginsAt = Integer.parseInt(System.getProperty(StringToTime.class+\".THIS_AFTERNOON_BEGINS_AT\", \"13\"));\n\t\t\t\t\t\t\tcal.set(Calendar.HOUR_OF_DAY, thisAfternoonBeginsAt);\n\t\t\t\t\t\t\tcal.set(Calendar.MINUTE, 0);\n\t\t\t\t\t\t\tcal.set(Calendar.SECOND, 0);\n\t\t\t\t\t\t\tcal.set(Calendar.MILLISECOND, 0);\n\t\t\t\t\t\t\treturn new Date(cal.getTimeInMillis());\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\telse if (\"evening\".equals(dateTimeString) || \"this evening\".equals(dateTimeString)) {\n\t\t\t\t\t\t\t// by default, this evening begins at 17:00:00.000\n\t\t\t\t\t\t\tint thisEveningBeginsAt = Integer.parseInt(System.getProperty(StringToTime.class+\".THIS_EVENING_BEGINS_AT\", \"17\"));\n\t\t\t\t\t\t\tcal.set(Calendar.HOUR_OF_DAY, thisEveningBeginsAt);\n\t\t\t\t\t\t\tcal.set(Calendar.MINUTE, 0);\n\t\t\t\t\t\t\tcal.set(Calendar.SECOND, 0);\n\t\t\t\t\t\t\tcal.set(Calendar.MILLISECOND, 0);\n\t\t\t\t\t\t\treturn new Date(cal.getTimeInMillis());\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\telse if (\"tonight\".equals(dateTimeString)) {\n\t\t\t\t\t\t\t// by default, tonight begins at 20:00:00.000\n\t\t\t\t\t\t\tint tonightBeginsAt = Integer.parseInt(System.getProperty(StringToTime.class+\".TONIGHT_BEGINS_AT\", \"20\"));\n\t\t\t\t\t\t\tcal.set(Calendar.HOUR_OF_DAY, tonightBeginsAt);\n\t\t\t\t\t\t\tcal.set(Calendar.MINUTE, 0);\n\t\t\t\t\t\t\tcal.set(Calendar.SECOND, 0);\n\t\t\t\t\t\t\tcal.set(Calendar.MILLISECOND, 0);\n\t\t\t\t\t\t\treturn new Date(cal.getTimeInMillis());\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\telse if (\"midnight\".equals(dateTimeString)) {\n\t\t\t\t\t\t\treturn new StringToTime(\"00:00:00 +24 hours\", now);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\telse if (\"tomorrow\".equals(dateTimeString)) {\n\t\t\t\t\t\t\treturn new StringToTime(\"now +24 hours\", now);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\telse if (\"tomorrow morning\".equals(dateTimeString)) {\n\t\t\t\t\t\t\treturn new StringToTime(\"morning +24 hours\", now);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\telse if (\"tomorrow noon\".equals(dateTimeString) || \"noon tomorrow\".equals(dateTimeString)) {\n\t\t\t\t\t\t\treturn new StringToTime(\"noon +24 hours\", now);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\telse if (\"tomorrow afternoon\".equals(dateTimeString)) {\n\t\t\t\t\t\t\treturn new StringToTime(\"afternoon +24 hours\", now);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\telse if (\"tomorrow evening\".equals(dateTimeString)) {\n\t\t\t\t\t\t\treturn new StringToTime(\"evening +24 hours\", now);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\telse if (\"tomorrow night\".equals(dateTimeString)) {\n\t\t\t\t\t\t\treturn new StringToTime(\"tonight +24 hours\", now);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\telse if (\"yesterday\".equals(dateTimeString)) {\n\t\t\t\t\t\t\treturn new StringToTime(\"now -24 hours\", now);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\telse if (\"yesterday morning\".equals(dateTimeString)) {\n\t\t\t\t\t\t\treturn new StringToTime(\"morning -24 hours\", now);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\telse if (\"yesterday noon\".equals(dateTimeString) || \"noon yesterday\".equals(dateTimeString)) {\n\t\t\t\t\t\t\treturn new StringToTime(\"noon -24 hours\", now);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\telse if (\"yesterday afternoon\".equals(dateTimeString)) {\n\t\t\t\t\t\t\treturn new StringToTime(\"afternoon -24 hours\", now);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\telse if (\"yesterday evening\".equals(dateTimeString)) {\n\t\t\t\t\t\t\treturn new StringToTime(\"evening -24 hours\", now);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\telse if (\"yesterday night\".equals(dateTimeString)) {\n\t\t\t\t\t\t\treturn new StringToTime(\"tonight -24 hours\", now);\n\t\t\t\t\t\t}\n \t\t\t\t\t\t\n \t\t\t\t\t\t\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tthrow new ParseException(String.format(\"Unrecognized date word: %s\", dateTimeString), 0);\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\t// time expressions, 24-hour and 12-hour\n\t\t\t\t\telse if (type == FormatType.TIME) {\n\t\t\t\t\t\t// An expression of time (hour)(:(minute))?((:(second))(.(millisecond))?)?( *(am?|pm?))?(RFC 822 time zone|general time zone)?\n\t\t\t\t\t\tString hour = m.group(1);\n\t\t\t\t\t\tString min = m.group(3);\n\t\t\t\t\t\tString sec = m.group(5);\n\t\t\t\t\t\tString ms = m.group(7);\n\t\t\t\t\t\tString amOrPm = m.group(8);\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (hour != null) {\n\t\t\t\t\t\t\tif (amOrPm != null)\n\t\t\t\t\t\t\t\tcal.set(Calendar.HOUR, new Integer(hour));\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tcal.set(Calendar.HOUR_OF_DAY, new Integer(hour));\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tcal.set(Calendar.HOUR, 0);\n\t\t\t\t\t\t\n\t\t\t\t\t\tcal.set(Calendar.MINUTE, (min != null ? new Integer(min) : 0));\n\t\t\t\t\t\tcal.set(Calendar.SECOND, (sec != null ? new Integer(sec) : 0));\n\t\t\t\t\t\tcal.set(Calendar.MILLISECOND, (ms != null ? new Integer(ms) : 0));\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (amOrPm != null)\n\t\t\t\t\t\t\tcal.set(Calendar.AM_PM, (amOrPm.equals(\"a\") || amOrPm.equals(\"am\") ? Calendar.AM : Calendar.PM));\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\treturn new Date(cal.getTimeInMillis());\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\t// increments\n\t\t\t\t\telse if (type == FormatType.INCREMENT || type == FormatType.DECREMENT) {\n\t\t\t\t\t\tMatcher units = unit.matcher(dateTimeString);\n\t\t\t\t\t\twhile (units.find()) {\n\t\t\t\t\t\t\tInteger val = new Integer(units.group(1)) * (type == FormatType.DECREMENT ? -1 : 1);\n\t\t\t\t\t\t\tString u = units.group(2);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t// second\n\t\t\t\t\t\t\tif (\"s\".equals(u) || \"sec\".equals(u) || \"second\".equals(u))\n\t\t\t\t\t\t\t\tcal.set(Calendar.SECOND, cal.get(Calendar.SECOND)+val);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t// minute\n\t\t\t\t\t\t\telse if (\"m\".equals(u) || \"min\".equals(u) || \"minute\".equals(u))\n\t\t\t\t\t\t\t\tcal.set(Calendar.MINUTE, cal.get(Calendar.MINUTE)+val);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t// hour\n\t\t\t\t\t\t\telse if (\"h\".equals(u) || \"hr\".equals(u) || \"hour\".equals(u))\n\t\t\t\t\t\t\t\tcal.set(Calendar.HOUR_OF_DAY, cal.get(Calendar.HOUR_OF_DAY)+val);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t// day\n\t\t\t\t\t\t\telse if (\"d\".equals(u) || \"day\".equals(u))\n\t\t\t\t\t\t\t\tcal.set(Calendar.DATE, cal.get(Calendar.DATE)+val);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t// week\n\t\t\t\t\t\t\telse if (\"w\".equals(u) || \"wk\".equals(u) || \"week\".equals(u))\n\t\t\t\t\t\t\t\tcal.set(Calendar.WEEK_OF_YEAR, cal.get(Calendar.WEEK_OF_YEAR)+val);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t// month\n\t\t\t\t\t\t\telse if (\"mo\".equals(u) || \"mon\".equals(u) || \"month\".equals(u))\n\t\t\t\t\t\t\t\tcal.set(Calendar.MONTH, cal.get(Calendar.MONTH)+val);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t// year\n\t\t\t\t\t\t\telse if (\"y\".equals(u) || \"yr\".equals(u) || \"year\".equals(u))\n\t\t\t\t\t\t\t\tcal.set(Calendar.YEAR, cal.get(Calendar.YEAR)+val);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tthrow new IllegalArgumentException(String.format(\"Unrecognized %s unit: [%s]\", type, u));\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\treturn new Date(cal.getTimeInMillis());\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\t// compound expressions\n\t\t\t\t\telse if (type == FormatType.COMPOUND) {\n\t\t\t\t\t\tObject date = StringToTime.date(m.group(1), now);\n\t\t\t\t\t\tif (!Boolean.FALSE.equals(date))\n\t\t\t\t\t\t\treturn (Date) StringToTime.date(m.group(2), (Date) date);\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tthrow new IllegalArgumentException(String.format(\"Couldn't parse %s, so couldn't compound with %s\", m.group(1), m.group(2)));\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\t// month of the year\n\t\t\t\t\telse if (type == FormatType.MONTH) {\n\t\t\t\t\t\tCalendar ref = Calendar.getInstance();\n\t\t\t\t\t\tref.setTime(new SimpleDateFormat(\"MMM d, y\").parse(String.format(\"%s 1, 1970\", m.group(1))));\n\t\t\t\t\t\tcal.set(Calendar.MONTH, ref.get(Calendar.MONTH));\n\t\t\t\t\t\t\n\t\t\t\t\t\treturn new Date(cal.getTimeInMillis());\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\t// day of week\n\t\t\t\t\telse if (type == FormatType.DAY_OF_WEEK) {\n\t\t\t\t\t\tInteger ref = translateDayOfWeek.get(dateTimeString);\n\t\t\t\t\t\tif (cal.get(Calendar.DAY_OF_WEEK) >= ref)\n\t\t\t\t\t\t\tcal.set(Calendar.WEEK_OF_YEAR, cal.get(Calendar.WEEK_OF_YEAR)+1);\n\t\t\t\t\t\tcal.set(Calendar.DAY_OF_WEEK, ref);\n\t\t\t\t\t\t\n\t\t\t\t\t\treturn new Date(cal.getTimeInMillis());\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\t// month and day with slashes\n\t\t\t\t\telse if (type == FormatType.MONTH_AND_DATE_WITH_SLASHES) {\n\t\t\t\t\t\tCalendar ref = Calendar.getInstance();\n\t\t\t\t\t\tref.setTime(new SimpleDateFormat(\"M/d/y\").parse(String.format(\"%s/%s/1970\", m.group(1), m.group(3))));\n\t\t\t\t\t\tcal.set(Calendar.MONTH, ref.get(Calendar.MONTH));\n\t\t\t\t\t\tcal.set(Calendar.DATE, ref.get(Calendar.DATE));\n\t\t\t\t\t\t\n\t\t\t\t\t\treturn new Date(cal.getTimeInMillis());\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\t// month and day long-hand\n\t\t\t\t\telse if (type == FormatType.MONTH_AND_DATE) {\n\t\t\t\t\t\tCalendar ref = Calendar.getInstance();\n\t\t\t\t\t\tref.setTime(new SimpleDateFormat(\"MMM d, y\").parse(String.format(\"%s %s, 1970\", m.group(1), m.group(2))));\n\t\t\t\t\t\tcal.set(Calendar.MONTH, ref.get(Calendar.MONTH));\n\t\t\t\t\t\tcal.set(Calendar.DATE, ref.get(Calendar.DATE));\n\t\t\t\t\t\t\n\t\t\t\t\t\treturn new Date(cal.getTimeInMillis());\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\t// next X\n\t\t\t\t\telse if (type == FormatType.NEXT) {\n\t\t\t\t\t\t// Format types MONTH and DAY_OF_WEEK both return future dates, so no additional processing is needed\n\t\t\t\t\t\tString expr = m.group(1);\n\t\t\t\t\t\tParserResult parsed = StringToTime.getParserResult(expr, now);\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (parsed != null && ( FormatType.MONTH.equals(parsed.type) || FormatType.DAY_OF_WEEK.equals(parsed.type) || FormatType.MONTH_AND_DATE.equals(parsed.type)) ) \n\t\t\t\t\t\t\treturn new Date(parsed.timestamp);\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tif (\"week\".equals(expr)) \n\t\t\t\t\t\t\t\tcal.set(Calendar.WEEK_OF_YEAR, cal.get(Calendar.WEEK_OF_YEAR)+1);\n\t\t\t\t\t\t\telse if (\"month\".equals(expr)) \n\t\t\t\t\t\t\t\tcal.set(Calendar.MONTH, cal.get(Calendar.MONTH)+1);\n\t\t\t\t\t\t\telse if (\"year\".equals(expr))\n\t\t\t\t\t\t\t\tcal.set(Calendar.YEAR, cal.get(Calendar.YEAR)+1);\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tthrow new IllegalArgumentException(String.format(\"Invalid expression of time: %s\", dateTimeString));\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\treturn new Date(cal.getTimeInMillis());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\t// last X\n\t\t\t\t\telse if (type == FormatType.LAST) {\n\t\t\t\t\t\tString expr = m.group(1);\n\t\t\t\t\t\tParserResult parsed = StringToTime.getParserResult(expr, now);\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (parsed != null && (FormatType.MONTH.equals(parsed.type) || FormatType.MONTH_AND_DATE.equals(parsed.type))) {\n\t\t\t\t\t\t\treturn new StringToTime(\"-1 year\", new Date(parsed.timestamp));\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\n\t\t\t\t\t\telse if (parsed != null && FormatType.DAY_OF_WEEK.equals(parsed.type)) {\n\t\t\t\t\t\t\treturn new StringToTime(\"-1 week\", new Date(parsed.timestamp));\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tif (\"week\".equals(expr)) \n\t\t\t\t\t\t\t\tcal.set(Calendar.WEEK_OF_YEAR, cal.get(Calendar.WEEK_OF_YEAR)-1);\n\t\t\t\t\t\t\telse if (\"month\".equals(expr)) \n\t\t\t\t\t\t\t\tcal.set(Calendar.MONTH, cal.get(Calendar.MONTH)-1);\n\t\t\t\t\t\t\telse if (\"year\".equals(expr))\n\t\t\t\t\t\t\t\tcal.set(Calendar.YEAR, cal.get(Calendar.YEAR)-1);\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tthrow new IllegalArgumentException(String.format(\"Invalid expression of time: %s\", dateTimeString));\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\treturn new Date(cal.getTimeInMillis());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\t// year\n\t\t\t\t\telse if (type == FormatType.YEAR) {\n\t\t\t\t\t\tcal.set(Calendar.YEAR, new Integer(m.group(0)));\n\t\t\t\t\t\treturn new Date(cal.getTimeInMillis());\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\t// unimplemented format type\n\t\t\t\t\telse\n\t\t\t\t\t\tthrow new IllegalStateException(String.format(\"Unimplemented FormatType: %s\", type));\n\t\t\t\t} catch (ParseException e) {\n\t\t\t\t\tthrow e;\n\t\t\t\t} catch (IllegalStateException e) {\n\t\t\t\t\tthrow e;\n\t\t\t\t} catch (IllegalArgumentException e) {\n\t\t\t\t\tthrow e;\n\t\t\t\t} catch (Exception e) {\n\t\t\t\t\tthrow new RuntimeException(String.format(\"Unknown failure in string-to-time conversion: %s\", e.getMessage()), e);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprivate enum FormatType {\n\t\tCOMPOUND,\n\t\tMONTH_AND_DATE_WITH_SLASHES,\n\t\tMONTH_AND_DATE,\n\t\tMONTH,\n\t\tDAY_OF_WEEK,\n\t\tNEXT,\n\t\tLAST,\n\t\tINCREMENT,\n\t\tDECREMENT,\n\t\tWORD,\n\t\tTIME,\n\t\tYEAR\n\t}\n\t\n}\n", "src/main/java/com/clutch/dates/StringToTimeException.java": "package com.clutch.dates;\n\npublic class StringToTimeException extends RuntimeException {\n\t\n\tprivate static final long serialVersionUID = -3777846121104246071L;\n\n\tpublic StringToTimeException(Object dateTimeString) {\n\t\tsuper(String.format(\"Failed to parse [%s] into a java.util.Date\", dateTimeString));\n\t}\n\t\n\tpublic StringToTimeException(Object dateTimeString, Throwable cause) {\n\t\tsuper(String.format(\"Failed to parse [%s] into a java.util.Date\", dateTimeString), cause);\n\t}\n\n}\n", "src/test/java/com/clutch/dates/StringToTimeTest.java": "package com.clutch.dates;\n\nimport java.text.SimpleDateFormat;\nimport java.util.Calendar;\nimport java.util.Date;\nimport java.util.GregorianCalendar;\n\nimport junit.framework.TestCase;\n\nimport org.springframework.beans.BeanWrapper;\nimport org.springframework.beans.BeanWrapperImpl;\n\npublic class StringToTimeTest extends TestCase {\n\n\tpublic void testMySqlDateFormat() {\n\t\tDate now = new Date();\n\t\tCalendar cal = Calendar.getInstance();\n\t\tcal.setTime(now);\n\t\t\n\t\tcal.set(Calendar.MONTH, Calendar.OCTOBER);\n\t\tcal.set(Calendar.DATE, 26);\n\t\tcal.set(Calendar.YEAR, 1981);\n\t\tcal.set(Calendar.HOUR_OF_DAY, 15);\n\t\tcal.set(Calendar.MINUTE, 26);\n\t\tcal.set(Calendar.SECOND, 3);\n\t\tcal.set(Calendar.MILLISECOND, 435);\n\t\t\n\t\tassertEquals(new Date(cal.getTimeInMillis()), new StringToTime(\"1981-10-26 15:26:03.435\", now));\n\t}\n\t\n\t/* FIXME\n\tpublic void testISO8601() {\n\t\tDate now = new Date();\n\t\tCalendar cal = Calendar.getInstance();\n\t\tcal.setTime(now);\n\t\t\n\t\tcal.set(Calendar.MONTH, Calendar.OCTOBER);\n\t\tcal.set(Calendar.DATE, 26);\n\t\tcal.set(Calendar.YEAR, 1981);\n\t\tcal.set(Calendar.HOUR_OF_DAY, 15);\n\t\tcal.set(Calendar.MINUTE, 25);\n\t\tcal.set(Calendar.SECOND, 2);\n\t\tcal.set(Calendar.MILLISECOND, 435);\n\t\t\n\t\tassertEquals(new Date(cal.getTimeInMillis()), new StringToTime(\"1981-10-26T15:26:03.435ZEST\", now));\n\t}\n\t*/\n\t\n\tpublic void test1200Seconds() {\n\t\tDate now = new Date();\n\t\tCalendar cal = Calendar.getInstance();\n\t\tcal.setTime(now);\n\t\t\n\t\tcal.set(Calendar.SECOND, cal.get(Calendar.SECOND)+1200);\n\t\tassertTrue(new Date(cal.getTimeInMillis()).equals(new StringToTime(\"+1200 s\", now)));\n\t\tassertFalse(new Date(cal.getTimeInMillis()).equals(new StringToTime(\"+1 s\", now)));\n\t}\n\t\n\tpublic void testVariousExpressionsOfTimeOfDay() {\n\t\tDate now = new Date();\n\t\tCalendar cal = Calendar.getInstance();\n\t\tcal.setTime(now);\n\t\t\n\t\tcal.set(Calendar.HOUR_OF_DAY, 23);\n\t\tcal.set(Calendar.MINUTE, 59);\n\t\tcal.set(Calendar.SECOND, 59);\n\t\tcal.set(Calendar.MILLISECOND, 0);\n\t\tassertEquals(new Date(cal.getTimeInMillis()), new StringToTime(\"11:59:59 PM\", now));\n\t\tassertEquals(new Date(cal.getTimeInMillis()), new StringToTime(\"23:59:59\", now));\n\t\t\n\t\tcal.set(Calendar.SECOND, 0);\n\t\tassertEquals(new Date(cal.getTimeInMillis()), new StringToTime(\"23:59\", now));\n\t\tassertEquals(new Date(cal.getTimeInMillis()), new StringToTime(\"11:59 PM\", now));\n\t\t\n\t\tcal.set(Calendar.MILLISECOND, 123);\n\t\tassertEquals(new Date(cal.getTimeInMillis()), new StringToTime(\"23:59:00.123\"));\n\t\t\n\t\tcal.set(Calendar.MONTH, Calendar.OCTOBER);\n\t\tcal.set(Calendar.DATE, 26);\n\t\tcal.set(Calendar.YEAR, 1981);\n\t\tcal.set(Calendar.HOUR_OF_DAY, 15);\n\t\tcal.set(Calendar.MINUTE, 27);\n\t\tcal.set(Calendar.SECOND, 0);\n\t\tcal.set(Calendar.MILLISECOND, 0);\n\t\tassertEquals(new Date(cal.getTimeInMillis()), new StringToTime(\"October 26, 1981 3:27:00 PM\", now));\n\t\t\n\t\tcal.set(Calendar.HOUR, 5);\n\t\tcal.set(Calendar.MINUTE, 0);\n\t\tcal.set(Calendar.SECOND, 0);\n\t\tcal.set(Calendar.AM_PM, Calendar.PM);\n\t\tassertEquals(new Date(cal.getTimeInMillis()), new StringToTime(\"10/26/81 5PM\", now));\n\t\t\n\t\tcal.setTime(now);\n\t\tcal.set(Calendar.DATE, cal.get(Calendar.DATE)+1);\n\t\tcal.set(Calendar.HOUR, 5);\n\t\tcal.set(Calendar.MINUTE, 0);\n\t\tcal.set(Calendar.SECOND, 0);\n\t\tcal.set(Calendar.MILLISECOND, 0);\n\t\tcal.set(Calendar.AM_PM, Calendar.PM);\n\t\tassertEquals(new Date(cal.getTimeInMillis()), new StringToTime(\"tomorrow 5PM\", now));\n\t\t\n\t\tcal.set(Calendar.DATE, cal.get(Calendar.DATE)-2);\n\t\tassertEquals(new Date(cal.getTimeInMillis()), new StringToTime(\"yesterday 5PM\", now));\n\t\tassertEquals(new StringToTime(\"yesterday evening\", now), new StringToTime(\"yesterday 5PM\", now));\n\t}\n\t\n\tpublic void testStaticMethods() {\n\t\tDate now = new Date();\n\t\t\n\t\t// timestamp\n\t\tLong time = (Long) StringToTime.time(\"now\", now);\n\t\tassertEquals(new Date(now.getTime()), new Date(time));\n\t\t\n\t\t// calendar\n\t\tCalendar cal = (Calendar) StringToTime.cal(\"now\", now);\n\t\tassertEquals(new Date(now.getTime()), new Date(cal.getTimeInMillis()));\n\t\t\n\t\t// date\n\t\tDate date = (Date) StringToTime.date(\"now\", now);\n\t\tassertEquals(new Date(now.getTime()), date);\n\t}\n\n\tpublic void testInstancePattern() {\n\t\tStringToTime date = new StringToTime(\"26 October 1981\");\n\t\tBeanWrapper bean = new BeanWrapperImpl(date);\n\t\tCalendar cal = new GregorianCalendar(1981, Calendar.OCTOBER, 26);\n\t\tLong myBirthday = cal.getTimeInMillis();\n\t\t\n\t\t// string value of the StringToTime object is the timestamp\n\t\tassertEquals(myBirthday, new Long(date.getTime()));\n\t\t\n\t\t// formatting controlled by constructor\n\t\tdate = new StringToTime(\"26 October 1981\", \"d MMM yyyy\");\n\t\tassertEquals(\"26 Oct 1981\", date.toString());\n\t\tdate = new StringToTime(\"26 October 1981\", \"M/d/yy\");\n\t\tassertEquals(\"10/26/81\", date.toString());\n\t\t\n\t\t// time property\n\t\tassertEquals(myBirthday, bean.getPropertyValue(\"time\"));\n\t\t\n\t\t// date property\n\t\tDate now = new Date(myBirthday);\n\t\tassertEquals(now, date);\n\t\t\n\t\t// calendar property\n\t\tassertEquals(cal, bean.getPropertyValue(\"cal\"));\n\t\t\n\t\t// format on demand\n\t\tassertEquals(\"October 26, 1981\", date.format(\"MMMM d, yyyy\"));\n\t}\n\t\n\tpublic void testNow() {\n\t\tDate now = new Date();\n\t\tassertEquals(new Date(now.getTime()), new StringToTime(\"now\", now));\n\t}\n\t\n\tpublic void testToday() {\n\t\tDate now = new Date();\n\t\tassertEquals(new StringToTime(\"00:00:00.000\", now), new StringToTime(\"today\", now));\n\t}\n\t\n\tpublic void testThisMorning() {\n\t\tDate now = new Date();\n\t\tassertEquals(new StringToTime(\"07:00:00.000\", now), new StringToTime(\"this morning\", now));\n\t\tassertEquals(new StringToTime(\"morning\", now), new StringToTime(\"this morning\", now));\n\t}\n\t\n\tpublic void testNoon() {\n\t\tDate now = new Date();\n\t\tassertEquals(new StringToTime(\"12:00:00.000\", now), new StringToTime(\"noon\", now));\n\t}\n\t\n\tpublic void testThisAfternoon() {\n\t\tDate now = new Date();\n\t\tassertEquals(new StringToTime(\"13:00:00.000\", now), new StringToTime(\"this afternoon\", now));\n\t\tassertEquals(new StringToTime(\"afternoon\", now), new StringToTime(\"this afternoon\", now));\n\t}\n\t\n\tpublic void testThisEvening() {\n\t\tDate now = new Date();\n\t\tassertEquals(new StringToTime(\"17:00:00.000\", now), new StringToTime(\"this evening\", now));\n\t\tassertEquals(new StringToTime(\"evening\", now), new StringToTime(\"this evening\", now));\n\t}\n\t\n\tpublic void testTonight() {\n\t\tDate now = new Date();\n\t\tassertEquals(StringToTime.time(\"20:00:00.000\", now), StringToTime.time(\"tonight\", now));\n\t}\n\t\n\tpublic void testIncrements() {\n\t\tDate now = new Date();\n\t\t\n\t\tCalendar cal = Calendar.getInstance();\n\t\tcal.setTime(now);\n\t\tcal.set(Calendar.HOUR_OF_DAY, cal.get(Calendar.HOUR_OF_DAY)+1);\n\t\tassertEquals(cal.getTimeInMillis(), StringToTime.time(\"+1 hour\", now));\n\t\t\n\t\tcal.setTime(now);\n\t\tcal.set(Calendar.WEEK_OF_YEAR, cal.get(Calendar.WEEK_OF_YEAR)+52);\n\t\tassertEquals(cal.getTimeInMillis(), StringToTime.time(\"+52 weeks\", now));\n\t\t\n\t\tassertEquals(new StringToTime(\"1 year\", now), new StringToTime(\"+1 year\", now));\n\t\t\n\t\tassertEquals(new StringToTime(\"+1 year\", now), new StringToTime(\"+12 months\", now));\n\t\t\n\t\tassertEquals(new StringToTime(\"+1 year 6 months\", now), new StringToTime(\"+18 months\", now));\n\t\t\n\t\tassertEquals(new StringToTime(\"12 months 1 day 60 seconds\", now), new StringToTime(\"1 year 24 hours 1 minute\", now));\n\t}\n\t\n\tpublic void testDecrements() {\n\t\tDate now = new Date();\n\t\t\n\t\tCalendar cal = Calendar.getInstance();\n\t\tcal.setTime(now);\n\t\tcal.set(Calendar.HOUR_OF_DAY, cal.get(Calendar.HOUR_OF_DAY)-1);\n\t\tassertEquals(new Date(cal.getTimeInMillis()), new StringToTime(\"-1 hour\", now));\n\t}\n\t\n\tpublic void testTomorrow() {\n\t\tDate now = new Date();\n\t\tCalendar cal = Calendar.getInstance();\n\t\tcal.setTime(now);\n\t\tcal.set(Calendar.DATE, cal.get(Calendar.DATE)+1);\n\t\tassertEquals(new Date(cal.getTimeInMillis()), new StringToTime(\"tomorrow\", now));\n\t\tassertEquals(new StringToTime(\"now +24 hours\", now), new StringToTime(\"tomorrow\", now));\n\t}\n\t\n\tpublic void testTomorrowMorning() {\n\t\tDate now = new Date();\n\t\tassertEquals(new StringToTime(\"this morning +24 hours\", now), new StringToTime(\"tomorrow morning\", now));\n\t}\n\t\n\tpublic void testTomorrowNoon() {\n\t\tDate now = new Date();\n\t\tassertEquals(new StringToTime(\"noon +24 hours\", now), new StringToTime(\"tomorrow noon\", now));\n\t\tassertEquals(new StringToTime(\"noon +24 hours\", now), new StringToTime(\"noon tomorrow\", now));\n\t}\n\t\n\tpublic void testTomorrowAfternoon() {\n\t\tDate now = new Date();\n\t\tassertEquals(new StringToTime(\"this afternoon +24 hours\", now), new StringToTime(\"tomorrow afternoon\", now));\n\t}\n\t\n\tpublic void testTomorrowEvening() {\n\t\tDate now = new Date();\n\t\tassertEquals(new StringToTime(\"this evening +24 hours\", now), new StringToTime(\"tomorrow evening\", now));\n\t}\n\t\n\tpublic void testTomorrowNight() {\n\t\tDate now = new Date();\n\t\tassertEquals(new StringToTime(\"tonight +24 hours\", now), new StringToTime(\"tomorrow night\", now));\n\t}\n\t\n\t// e.g., October 26, 1981, or Oct 26, 1981, or 26 October 1981, or 26 Oct 1981, or 26 Oct 81\n\tpublic void testLongHand() throws Exception {\n\t\tassertEquals(new SimpleDateFormat(\"M/d/y\").parse(\"10/26/1981\"), new StringToTime(\"October 26, 1981\"));\n\t\tassertEquals(new SimpleDateFormat(\"M/d/y\").parse(\"10/26/1981\"), new StringToTime(\"Oct 26, 1981\"));\n\t\t\n\t\tassertEquals(new SimpleDateFormat(\"M/d/y\").parse(\"10/26/1981\"), new StringToTime(\"26 October 1981\"));\n\t\tassertEquals(new SimpleDateFormat(\"M/d/y\").parse(\"10/26/1981\"), new StringToTime(\"26 Oct 1981\"));\n\t\tassertEquals(new SimpleDateFormat(\"M/d/y\").parse(\"10/26/1981\"), new StringToTime(\"26 Oct 81\"));\n\t\t\n\t\tassertEquals(new SimpleDateFormat(\"M/d/y\").parse(\"10/26/1981\"), new StringToTime(\"26 october 1981\"));\n\t\tassertEquals(new SimpleDateFormat(\"M/d/y\").parse(\"10/26/1981\"), new StringToTime(\"26 oct 1981\"));\n\t\tassertEquals(new SimpleDateFormat(\"M/d/y\").parse(\"10/26/1981\"), new StringToTime(\"26 oct 81\"));\n\t\t\n\t\tassertEquals(new SimpleDateFormat(\"M/d/y\").parse(\"1/1/2000\"), new StringToTime(\"1 Jan 2000\"));\n\t\tassertEquals(new SimpleDateFormat(\"M/d/y\").parse(\"1/1/2000\"), new StringToTime(\"1 Jan 00\"));\n\t\t\n\t\tassertEquals(new SimpleDateFormat(\"M/d/y\").parse(\"1/1/2000\"), new StringToTime(\"1 jan 2000\"));\n\t\tassertEquals(new SimpleDateFormat(\"M/d/y\").parse(\"1/1/2000\"), new StringToTime(\"1 jan 00\"));\n\t}\n\t\n\t// e.g., 10/26/1981 or 10/26/81\n\tpublic void testWithSlahesMonthFirst() throws Exception {\n\t\tassertEquals(new SimpleDateFormat(\"M/d/y\").parse(\"10/26/1981\"), new StringToTime(\"10/26/1981\"));\n\t\tassertEquals(new SimpleDateFormat(\"M/d/y\").parse(\"10/26/1981\"), new StringToTime(\"10/26/81\"));\n\t}\n\n\t// e.g., 1981/10/26\n\tpublic void testWithSlashesYearFirst() throws Exception {\n\t\tassertEquals(new SimpleDateFormat(\"M/d/y\").parse(\"10/26/1981\"), new StringToTime(\"1981/10/26\"));\n\t}\n\t\n\t// e.g., October 26 and Oct 26\n\tpublic void testMonthAndDate() throws Exception {\n\t\tDate now = new Date();\n\t\tCalendar cal = Calendar.getInstance();\n\t\tcal.set(Calendar.MONTH, Calendar.OCTOBER);\n\t\tcal.set(Calendar.DATE, 26);\n\t\tassertEquals(new Date(cal.getTimeInMillis()), new StringToTime(\"October 26\", now));\n\t\tassertEquals(new StringToTime(\"Oct 26\", now), new StringToTime(\"October 26\", now));\n\t}\n\t\n\t// e.g., 10/26\n\tpublic void testWithSlahesMonthAndDate() throws Exception {\n\t\tCalendar cal = Calendar.getInstance();\n\t\tcal.set(Calendar.MONTH, Calendar.OCTOBER);\n\t\tcal.set(Calendar.DATE, 26);\n\t\tassertEquals(new Date(cal.getTimeInMillis()), new StringToTime(\"10/26\"));\n\t}\n\t\n\t// e.g., October or Oct\n\tpublic void testMonth() throws Exception {\n\t\tDate now = new Date();\n\t\t\n\t\tassertEquals(new StringToTime(\"October\", now), new StringToTime(\"Oct\", now));\n\t\t\n\t\tCalendar cal = Calendar.getInstance();\n\t\tcal.setTime(now);\n\t\t\n\t\t// it should be this year\n\t\tassertEquals(cal.get(Calendar.YEAR), new StringToTime(\"January\", now).getCal().get(Calendar.YEAR));\n assertEquals(cal.get(Calendar.YEAR), new StringToTime(\"December\", now).getCal().get(Calendar.YEAR));\n\t}\n\t\n\tpublic void testDayOfWeek() throws Exception {\n\t\tDate now = new Date();\n\t\tassertEquals(StringToTime.date(\"Friday\", now), StringToTime.date(\"Fri\", now));\n\t\t\n\t\tCalendar cal = Calendar.getInstance();\n\t\tcal.setTime(now);\n\t\t\n\t\t// if today's day of the week is greater than or equal to our test day of the week (Wednesday)\n\t\tif (cal.get(Calendar.DAY_OF_WEEK) >= 3) // then the day of the week on the date returned should be next week\n\t\t\tassertEquals(cal.get(Calendar.WEEK_OF_YEAR)+1, new StringToTime(\"Wednesday\", now).getCal().get(Calendar.WEEK_OF_YEAR));\n\t\telse // otherwise, it should be this year\n\t\t\tassertEquals(cal.get(Calendar.WEEK_OF_YEAR), new StringToTime(\"Wednesday\", now).getCal().get(Calendar.WEEK_OF_YEAR));\n\t}\n\t\n\tpublic void testNext() {\n\t\tDate now = new Date();\n\t\tassertEquals(new StringToTime(\"next January 15\", now), new StringToTime(\"Jan 15\", now));\n\t\tassertEquals(new StringToTime(\"next Dec\", now), new StringToTime(\"December\", now));\n\t\tassertEquals(new StringToTime(\"next Sunday\", now), new StringToTime(\"Sun\", now));\n\t\tassertEquals(new StringToTime(\"next Sat\", now), new StringToTime(\"Saturday\", now));\n\t}\n\t\n\tpublic void testLast() {\n\t\tDate now = new Date();\n\t\tassertEquals(new StringToTime(\"last January 15\", now), new StringToTime(\"Jan 15 -1 year\", now));\n\t\tassertEquals(new StringToTime(\"last Dec\", now), new StringToTime(\"December -1 year\", now));\n\t\tassertEquals(new StringToTime(\"last Sunday\", now), new StringToTime(\"Sun -1 week\", now));\n\t\tassertEquals(new StringToTime(\"last Sat\", now), new StringToTime(\"Saturday -1 week\", now));\n\t}\n\t\n\t\n\t\n}\n"}, "files_after": {"src/main/java/com/clutch/dates/StringToTime.java": "package com.clutch.dates;\n\nimport java.text.ParseException;\nimport java.text.SimpleDateFormat;\nimport java.util.Calendar;\nimport java.util.Date;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\nimport org.joda.time.DateTime;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport ch.qos.logback.classic.Level;\n\nimport com.google.common.base.Preconditions;\nimport com.google.common.base.Strings;\nimport com.google.common.base.Throwables;\n\n/**\n * A Java implementation of the PHP function strtotime(String, int): accepts\n * various expressions of time\n * in String format, and returns a timestamp or {@link DateTime}\n * object.\n * \n *

Valid expressions of time

\n * \n *

\n * All expressions are case-insensitive.\n *

\n * \n *
    \n *
  • now (equal to new Date())
  • \n *
  • today (equal to StringToTime(\"00:00:00.000\"))
  • \n *
  • midnight (equal to\n * StringToTime(\"00:00:00.000 +24 hours\"))
  • \n *
  • morning or this morning (by default, equal to\n * StringToTime(\"07:00:00.000\"))
  • \n *
  • noon (by default, equal to\n * StringToTime(\"12:00:00.000\")
  • \n *
  • afternoon or this afternoon (by default, equal\n * to StringToTime(\"13:00:00.000\")
  • \n *
  • evening or this evening (by default, equal to\n * StringToTime(\"17:00:00.000\")
  • \n *
  • tonight (by default, equal to\n * StringToTime(\"20:00:00.000\")
  • \n *
  • tomorrow (by default, equal to\n * StringToTime(\"now +24 hours\"))
  • \n *
  • tomorrow morning (by default, equal to\n * StringToTime(\"morning +24 hours\"))
  • \n *
  • noon tomorrow or tomorrow noon (by default,\n * equal to StringToTime(\"noon +24 hours\"))
  • \n *
  • tomorrow afternoon (by default, equal to\n * StringToTime(\"afternoon +24 hours\"))
  • \n *
  • yesterday (by default, equal to\n * StringToTime(\"now -24 hours\"))
  • \n *
  • all the permutations of yesterday and morning,\n * noon, afternoon, and evening
  • \n *
  • October 26, 1981 or Oct 26, 1981
  • \n *
  • October 26 or Oct 26
  • \n *
  • 26 October 1981
  • \n *
  • 26 Oct 1981
  • \n *
  • 26 Oct 81
  • \n *
  • 10/26/1981 or 10-26-1981
  • \n *
  • 10/26/81 or 10-26-81
  • \n *
  • 1981/10/26 or 1981-10-26
  • \n *
  • 10/26 or 10-26
  • \n *
\n * \n * @author Aaron Collegeman acollegeman@clutch-inc.com\n * @since JRE 1.5.0\n * @see http://us3.php.net/manual/en/function.strtotime.php\n */\npublic class StringToTime {\n\n\t/**\n\t * Parse {@code string} and return a {@link DateTime} object.\n\t * \n\t * @param string\n\t * @return the corresponding DateTime\n\t */\n\tpublic static DateTime parseDateTime(String string) {\n\t\treturn new DateTime(parseLong(string));\n\t}\n\n\t/**\n\t * Parse {@code string} and return a timestamp with millisecond precision.\n\t * \n\t * @param string\n\t * @return the corresponding timestamp\n\t */\n\tpublic static long parseLong(String string) {\n\t\treturn parseLong(string, new Date());\n\t}\n\t\n\tprotected static DateTime parseDateTime(String string, Date now){\n\t\treturn new DateTime(parseLong(string, now));\n\t}\n\n\t/**\n\t * Parse {@code string} relative to {@code now} and return a timestamp with\n\t * millisecond precision.\n\t * \n\t * @param string\n\t * @param now\n\t * @return the corresponding timestamp\n\t */\n\tprotected static long parseLong(String string, Date now) {\n\t\tPreconditions.checkArgument(!Strings.isNullOrEmpty(string));\n\t\ttry {\n\t\t\tfor (PatternAndFormat paf : known) {\n\t\t\t\tMatcher m = paf.matches(string);\n\t\t\t\tif(m.matches()) {\n\t\t\t\t\tLong time = paf.parse(string, now, m);\n\t\t\t\t\tlog.debug(String.format(\"{} triggered format {}: {}\",\n\t\t\t\t\t\t\tstring, paf.f, new Date(time)));\n\t\t\t\t\treturn time;\n\t\t\t\t}\n\t\t\t}\n\t\t\tlog.debug(String.format(\"Unrecognized date/time string {}\", string));\n\t\t\tthrow new ParseException(\"Unrecognized date/time string '\" + string\n\t\t\t\t\t+ \"'\", 0);\n\t\t}\n\t\tcatch (Exception e) { // thrown by various features of the parser\n\t\t\tthrow Throwables.propagate(e);\n\t\t}\n\t}\n\n\t/**\n\t * Return the parse result.\n\t * \n\t * @param trimmedDateTimeString\n\t * @param now\n\t * @return\n\t * @throws ParseException\n\t */\n\tprivate static ParserResult getParserResult(String trimmedDateTimeString,\n\t\t\tDate now) throws ParseException {\n\t\tfor (PatternAndFormat paf : known) {\n\t\t\tMatcher m = paf.matches(trimmedDateTimeString);\n\t\t\tif(m.matches()) {\n\t\t\t\tlog.debug(String.format(\n\t\t\t\t\t\t\"Date/time string [%s] triggered format [%s]\",\n\t\t\t\t\t\ttrimmedDateTimeString, paf.f));\n\t\t\t\treturn new ParserResult(\n\t\t\t\t\t\tpaf.parse(trimmedDateTimeString, now, m), paf.f.type);\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}\n\n\tprivate static final Logger log = LoggerFactory\n\t\t\t.getLogger(StringToTime.class);\n\tstatic {\n\t\t// Set to Level.DEBUG to see information about string parsing logic\n\t\t((ch.qos.logback.classic.Logger) log).setLevel(Level.INFO);\n\t}\n\n\t// An expression of time (hour)(:(minute))?((:(second))(.(millisecond))?)?(\n\t// *(am?|pm?))?(RFC 822 time zone|general time zone)?\n\tprivate static final String timeExpr = \"(\\\\d{1,2})(:(\\\\d{1,2}))?(:(\\\\d{1,2})(\\\\.(\\\\d{1,3}))?)?( *(am?|pm?))?( *\\\\-\\\\d{4}|[a-z]{3}|[a-z ]+)?\";\n\n\t/**\n\t * Patterns and formats recognized by the algorithm; first match wins, so\n\t * insert most specific patterns first.\n\t */\n\tprivate static final PatternAndFormat[] known = {\n\n\t\t\t// TODO: ISO 8601 and derivatives\n\n\t\t\t// just the year\n\t\t\tnew PatternAndFormat(Pattern.compile(\"\\\\d{4}\"), new Format(\n\t\t\t\t\tFormatType.YEAR)),\n\n\t\t\t// decrement, e.g., -1 day\n\t\t\tnew PatternAndFormat(Pattern.compile(\"\\\\-( *\\\\d{1,} +[^ ]+){1,}\",\n\t\t\t\t\tPattern.CASE_INSENSITIVE), new Format(FormatType.DECREMENT)),\n\n\t\t\t// increment, e.g., +1 day\n\t\t\tnew PatternAndFormat(Pattern.compile(\"\\\\+?( *\\\\d{1,} +[^ ]+){1,}\",\n\t\t\t\t\tPattern.CASE_INSENSITIVE), new Format(FormatType.INCREMENT)),\n\n\t\t\t// e.g., October 26 and Oct 26\n\t\t\tnew PatternAndFormat(Pattern.compile(\"([a-z]+) +(\\\\d{1,2})\",\n\t\t\t\t\tPattern.CASE_INSENSITIVE), new Format(\n\t\t\t\t\tFormatType.MONTH_AND_DATE)),\n\n\t\t\t// e.g., 26 October 1981, or 26 Oct 1981, or 26 Oct 81\n\t\t\tnew PatternAndFormat(Pattern.compile(\n\t\t\t\t\t\"\\\\d{1,2} +[a-z]+ +(\\\\d{2}|\\\\d{4})\",\n\t\t\t\t\tPattern.CASE_INSENSITIVE), new Format(\"d MMM y\")),\n\n\t\t\t// now or today\n\t\t\tnew PatternAndFormat(\n\t\t\t\t\tPattern.compile(\n\t\t\t\t\t\t\t\"(midnight|now|today|(this +)?(morning|afternoon|evening)|tonight|noon( +tomorrow)?|tomorrow|tomorrow +(morning|afternoon|evening|night|noon)?|yesterday|yesterday +(morning|afternoon|evening|night)?)\",\n\t\t\t\t\t\t\tPattern.CASE_INSENSITIVE), new Format(\n\t\t\t\t\t\t\tFormatType.WORD)),\n\n\t\t\t// time, 24-hour and 12-hour\n\t\t\tnew PatternAndFormat(Pattern.compile(timeExpr,\n\t\t\t\t\tPattern.CASE_INSENSITIVE), new Format(FormatType.TIME)),\n\n\t\t\t// e.g., October 26, 1981 or Oct 26, 1981\n\t\t\tnew PatternAndFormat(Pattern.compile(\n\t\t\t\t\t\"[a-z]+ +\\\\d{1,2} *, *(\\\\d{2}|\\\\d{4})\",\n\t\t\t\t\tPattern.CASE_INSENSITIVE), new Format(\"MMM d, y\")),\n\n\t\t\t// e.g., 10/26/1981 or 10/26/81\n\t\t\tnew PatternAndFormat(Pattern.compile(\"\\\\d{1,2}/\\\\d{1,2}/\\\\d{2,4}\"),\n\t\t\t\t\tnew Format(\"M/d/y\")),\n\n\t\t\t// e.g., 10-26-1981 or 10-26-81\n\t\t\tnew PatternAndFormat(\n\t\t\t\t\tPattern.compile(\"\\\\d{1,2}\\\\-\\\\d{1,2}\\\\-\\\\d{2,4}\"),\n\t\t\t\t\tnew Format(\"M-d-y\")),\n\n\t\t\t// e.g., 10/26 or 10-26\n\t\t\tnew PatternAndFormat(\n\t\t\t\t\tPattern.compile(\"(\\\\d{1,2})(/|\\\\-)(\\\\d{1,2})\"), new Format(\n\t\t\t\t\t\t\tFormatType.MONTH_AND_DATE_WITH_SLASHES)),\n\n\t\t\t// e.g., 1981/10/26\n\t\t\tnew PatternAndFormat(Pattern.compile(\"\\\\d{4}/\\\\d{1,2}/\\\\d{1,2}\"),\n\t\t\t\t\tnew Format(\"y/M/d\")),\n\n\t\t\t// e.g., 1981-10-26\n\t\t\tnew PatternAndFormat(\n\t\t\t\t\tPattern.compile(\"\\\\d{4}\\\\-\\\\d{1,2}\\\\-\\\\d{1,2}\"),\n\t\t\t\t\tnew Format(\"y-M-d\")),\n\n\t\t\t// e.g., October or Oct\n\t\t\tnew PatternAndFormat(\n\t\t\t\t\tPattern.compile(\n\t\t\t\t\t\t\t\"(Jan(uary)?|Feb(ruary)?|Mar(ch)?|Apr(il)?|May|Jun(e)?|Jul(y)?|Aug(ust)?|Sep(tember)?|Oct(ober)?|Nov(ember)?|Dec(ember)?)\",\n\t\t\t\t\t\t\tPattern.CASE_INSENSITIVE), new Format(\n\t\t\t\t\t\t\tFormatType.MONTH)),\n\n\t\t\t// e.g., Tuesday or Tue\n\t\t\tnew PatternAndFormat(\n\t\t\t\t\tPattern.compile(\n\t\t\t\t\t\t\t\"(Sun(day)?|Mon(day)?|Tue(sday)?|Wed(nesday)?|Thu(rsday)?|Fri(day)?|Sat(urday)?)\",\n\t\t\t\t\t\t\tPattern.CASE_INSENSITIVE), new Format(\n\t\t\t\t\t\t\tFormatType.DAY_OF_WEEK)),\n\n\t\t\t// next, e.g., next Tuesday\n\t\t\tnew PatternAndFormat(Pattern.compile(\"next +(.*)\",\n\t\t\t\t\tPattern.CASE_INSENSITIVE), new Format(FormatType.NEXT)),\n\n\t\t\t// last, e.g., last Tuesday\n\t\t\tnew PatternAndFormat(Pattern.compile(\"last +(.*)\",\n\t\t\t\t\tPattern.CASE_INSENSITIVE), new Format(FormatType.LAST)),\n\n\t\t\t// compound statement\n\t\t\tnew PatternAndFormat(Pattern.compile(\"(.*) +(((\\\\+|\\\\-){1}.*)|\"\n\t\t\t\t\t+ timeExpr + \")$\", Pattern.CASE_INSENSITIVE), new Format(\n\t\t\t\t\tFormatType.COMPOUND))\n\n\t};\n\n\tprivate static class Format {\n\n\t\tprivate static Pattern unit = Pattern\n\t\t\t\t.compile(\"(\\\\d{1,}) +(s(ec(ond)?)?|mo(n(th)?)?|(hour|hr?)|d(ay)?|(w(eek)?|wk)|m(in(ute)?)?|(y(ear)?|yr))s?\");\n\n\t\tprivate static Pattern removeExtraSpaces = Pattern.compile(\" +\");\n\n\t\tprivate static Map translateDayOfWeek = new HashMap();\n\n\t\tstatic {\n\t\t\ttranslateDayOfWeek.put(\"sunday\", 1);\n\t\t\ttranslateDayOfWeek.put(\"sun\", 1);\n\t\t\ttranslateDayOfWeek.put(\"monday\", 2);\n\t\t\ttranslateDayOfWeek.put(\"mon\", 2);\n\t\t\ttranslateDayOfWeek.put(\"tuesday\", 3);\n\t\t\ttranslateDayOfWeek.put(\"tue\", 3);\n\t\t\ttranslateDayOfWeek.put(\"wednesday\", 4);\n\t\t\ttranslateDayOfWeek.put(\"wed\", 4);\n\t\t\ttranslateDayOfWeek.put(\"thursday\", 5);\n\t\t\ttranslateDayOfWeek.put(\"thu\", 5);\n\t\t\ttranslateDayOfWeek.put(\"friday\", 6);\n\t\t\ttranslateDayOfWeek.put(\"fri\", 6);\n\t\t\ttranslateDayOfWeek.put(\"saturday\", 7);\n\t\t\ttranslateDayOfWeek.put(\"sat\", 7);\n\t\t}\n\n\t\tprivate String sdf;\n\n\t\tprivate FormatType type;\n\n\t\tpublic Format(FormatType type) {\n\t\t\tthis.type = type;\n\t\t}\n\n\t\tpublic Format(String sdf) {\n\t\t\tthis.sdf = sdf;\n\t\t}\n\n\t\tpublic Date parse(String dateTimeString, Date now, Matcher m)\n\t\t\t\tthrows ParseException {\n\t\t\tif(sdf != null)\n\t\t\t\treturn new SimpleDateFormat(sdf).parse(dateTimeString);\n\t\t\telse {\n\t\t\t\tdateTimeString = removeExtraSpaces.matcher(dateTimeString)\n\t\t\t\t\t\t.replaceAll(\" \").toLowerCase();\n\n\t\t\t\ttry {\n\t\t\t\t\tCalendar cal = Calendar.getInstance();\n\t\t\t\t\tcal.setTime(now);\n\n\t\t\t\t\t// word expressions, e.g., \"now\" and \"today\" and \"tonight\"\n\t\t\t\t\tif(type == FormatType.WORD) {\n\t\t\t\t\t\tif(\"now\".equalsIgnoreCase(dateTimeString))\n\t\t\t\t\t\t\treturn (now != null ? now : new Date());\n\n\t\t\t\t\t\telse if(\"today\".equalsIgnoreCase(dateTimeString)) {\n\t\t\t\t\t\t\tcal.set(Calendar.HOUR_OF_DAY, 0);\n\t\t\t\t\t\t\tcal.set(Calendar.MINUTE, 0);\n\t\t\t\t\t\t\tcal.set(Calendar.SECOND, 0);\n\t\t\t\t\t\t\tcal.set(Calendar.MILLISECOND, 0);\n\t\t\t\t\t\t\treturn new Date(cal.getTimeInMillis());\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\telse if(\"morning\".equalsIgnoreCase(dateTimeString)\n\t\t\t\t\t\t\t\t|| \"this morning\"\n\t\t\t\t\t\t\t\t\t\t.equalsIgnoreCase(dateTimeString)) {\n\t\t\t\t\t\t\t// by default, this morning begins at 07:00:00.000\n\t\t\t\t\t\t\tint thisMorningBeginsAt = Integer.parseInt(System\n\t\t\t\t\t\t\t\t\t.getProperty(StringToTime.class\n\t\t\t\t\t\t\t\t\t\t\t+ \".THIS_MORNING_BEGINS_AT\", \"7\"));\n\t\t\t\t\t\t\tcal.set(Calendar.HOUR_OF_DAY, thisMorningBeginsAt);\n\t\t\t\t\t\t\tcal.set(Calendar.MINUTE, 0);\n\t\t\t\t\t\t\tcal.set(Calendar.SECOND, 0);\n\t\t\t\t\t\t\tcal.set(Calendar.MILLISECOND, 0);\n\t\t\t\t\t\t\treturn new Date(cal.getTimeInMillis());\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\telse if(\"noon\".equalsIgnoreCase(dateTimeString)) {\n\t\t\t\t\t\t\t// noon is 12:00:00.000\n\t\t\t\t\t\t\tcal.set(Calendar.HOUR_OF_DAY, 12);\n\t\t\t\t\t\t\tcal.set(Calendar.MINUTE, 0);\n\t\t\t\t\t\t\tcal.set(Calendar.SECOND, 0);\n\t\t\t\t\t\t\tcal.set(Calendar.MILLISECOND, 0);\n\t\t\t\t\t\t\treturn new Date(cal.getTimeInMillis());\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\telse if(\"afternoon\".equalsIgnoreCase(dateTimeString)\n\t\t\t\t\t\t\t\t|| \"this afternoon\"\n\t\t\t\t\t\t\t\t\t\t.equalsIgnoreCase(dateTimeString)) {\n\t\t\t\t\t\t\t// by default, this afternoon begins at 13:00:00.000\n\t\t\t\t\t\t\tint thisAfternoonBeginsAt = Integer\n\t\t\t\t\t\t\t\t\t.parseInt(System\n\t\t\t\t\t\t\t\t\t\t\t.getProperty(\n\t\t\t\t\t\t\t\t\t\t\t\t\tStringToTime.class\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t+ \".THIS_AFTERNOON_BEGINS_AT\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\"13\"));\n\t\t\t\t\t\t\tcal.set(Calendar.HOUR_OF_DAY, thisAfternoonBeginsAt);\n\t\t\t\t\t\t\tcal.set(Calendar.MINUTE, 0);\n\t\t\t\t\t\t\tcal.set(Calendar.SECOND, 0);\n\t\t\t\t\t\t\tcal.set(Calendar.MILLISECOND, 0);\n\t\t\t\t\t\t\treturn new Date(cal.getTimeInMillis());\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\telse if(\"evening\".equalsIgnoreCase(dateTimeString)\n\t\t\t\t\t\t\t\t|| \"this evening\"\n\t\t\t\t\t\t\t\t\t\t.equalsIgnoreCase(dateTimeString)) {\n\t\t\t\t\t\t\t// by default, this evening begins at 17:00:00.000\n\t\t\t\t\t\t\tint thisEveningBeginsAt = Integer.parseInt(System\n\t\t\t\t\t\t\t\t\t.getProperty(StringToTime.class\n\t\t\t\t\t\t\t\t\t\t\t+ \".THIS_EVENING_BEGINS_AT\", \"17\"));\n\t\t\t\t\t\t\tcal.set(Calendar.HOUR_OF_DAY, thisEveningBeginsAt);\n\t\t\t\t\t\t\tcal.set(Calendar.MINUTE, 0);\n\t\t\t\t\t\t\tcal.set(Calendar.SECOND, 0);\n\t\t\t\t\t\t\tcal.set(Calendar.MILLISECOND, 0);\n\t\t\t\t\t\t\treturn new Date(cal.getTimeInMillis());\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\telse if(\"tonight\".equalsIgnoreCase(dateTimeString)) {\n\t\t\t\t\t\t\t// by default, tonight begins at 20:00:00.000\n\t\t\t\t\t\t\tint tonightBeginsAt = Integer.parseInt(System\n\t\t\t\t\t\t\t\t\t.getProperty(StringToTime.class\n\t\t\t\t\t\t\t\t\t\t\t+ \".TONIGHT_BEGINS_AT\", \"20\"));\n\t\t\t\t\t\t\tcal.set(Calendar.HOUR_OF_DAY, tonightBeginsAt);\n\t\t\t\t\t\t\tcal.set(Calendar.MINUTE, 0);\n\t\t\t\t\t\t\tcal.set(Calendar.SECOND, 0);\n\t\t\t\t\t\t\tcal.set(Calendar.MILLISECOND, 0);\n\t\t\t\t\t\t\treturn new Date(cal.getTimeInMillis());\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\telse if(\"midnight\".equalsIgnoreCase(dateTimeString)) {\n\t\t\t\t\t\t\treturn new Date(\n\t\t\t\t\t\t\t\t\tparseLong(\"00:00:00 +24 hours\", now));\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\telse if(\"tomorrow\".equalsIgnoreCase(dateTimeString)) {\n\t\t\t\t\t\t\treturn new Date(parseLong(\"now +24 hours\", now));\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\telse if(\"tomorrow morning\"\n\t\t\t\t\t\t\t\t.equalsIgnoreCase(dateTimeString)) {\n\t\t\t\t\t\t\treturn new Date(parseLong(\"morning +24 hours\", now));\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\telse if(\"tomorrow noon\"\n\t\t\t\t\t\t\t\t.equalsIgnoreCase(dateTimeString)\n\t\t\t\t\t\t\t\t|| \"noon tomorrow\"\n\t\t\t\t\t\t\t\t\t\t.equalsIgnoreCase(dateTimeString)) {\n\t\t\t\t\t\t\treturn new Date(parseLong(\"noon +24 hours\", now));\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\telse if(\"tomorrow afternoon\"\n\t\t\t\t\t\t\t\t.equalsIgnoreCase(dateTimeString)) {\n\t\t\t\t\t\t\treturn new Date(parseLong(\"afternoon +24 hours\",\n\t\t\t\t\t\t\t\t\tnow));\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\telse if(\"tomorrow evening\"\n\t\t\t\t\t\t\t\t.equalsIgnoreCase(dateTimeString)) {\n\t\t\t\t\t\t\treturn new Date(parseLong(\"evening +24 hours\", now));\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\telse if(\"tomorrow night\"\n\t\t\t\t\t\t\t\t.equalsIgnoreCase(dateTimeString)) {\n\t\t\t\t\t\t\treturn new Date(parseLong(\"tonight +24 hours\", now));\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\telse if(\"yesterday\".equalsIgnoreCase(dateTimeString)) {\n\t\t\t\t\t\t\treturn new Date(parseLong(\"now -24 hours\", now));\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\telse if(\"yesterday morning\"\n\t\t\t\t\t\t\t\t.equalsIgnoreCase(dateTimeString)) {\n\t\t\t\t\t\t\treturn new Date(parseLong(\"morning -24 hours\", now));\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\telse if(\"yesterday noon\"\n\t\t\t\t\t\t\t\t.equalsIgnoreCase(dateTimeString)\n\t\t\t\t\t\t\t\t|| \"noon yesterday\"\n\t\t\t\t\t\t\t\t\t\t.equalsIgnoreCase(dateTimeString)) {\n\t\t\t\t\t\t\treturn new Date(parseLong(\"noon -24 hours\", now));\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\telse if(\"yesterday afternoon\"\n\t\t\t\t\t\t\t\t.equalsIgnoreCase(dateTimeString)) {\n\t\t\t\t\t\t\treturn new Date(parseLong(\"afternoon -24 hours\",\n\t\t\t\t\t\t\t\t\tnow));\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\telse if(\"yesterday evening\"\n\t\t\t\t\t\t\t\t.equalsIgnoreCase(dateTimeString)) {\n\t\t\t\t\t\t\treturn new Date(parseLong(\"evening -24 hours\", now));\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\telse if(\"yesterday night\"\n\t\t\t\t\t\t\t\t.equalsIgnoreCase(dateTimeString)) {\n\t\t\t\t\t\t\treturn new Date(parseLong(\"tonight -24 hours\", now));\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tthrow new ParseException(String.format(\n\t\t\t\t\t\t\t\t\t\"Unrecognized date word: %s\",\n\t\t\t\t\t\t\t\t\tdateTimeString), 0);\n\t\t\t\t\t}\n\n\t\t\t\t\t// time expressions, 24-hour and 12-hour\n\t\t\t\t\telse if(type == FormatType.TIME) {\n\t\t\t\t\t\t// An expression of time\n\t\t\t\t\t\t// (hour)(:(minute))?((:(second))(.(millisecond))?)?(\n\t\t\t\t\t\t// *(am?|pm?))?(RFC 822 time zone|general time zone)?\n\t\t\t\t\t\tString hour = m.group(1);\n\t\t\t\t\t\tString min = m.group(3);\n\t\t\t\t\t\tString sec = m.group(5);\n\t\t\t\t\t\tString ms = m.group(7);\n\t\t\t\t\t\tString amOrPm = m.group(8);\n\n\t\t\t\t\t\tif(hour != null) {\n\t\t\t\t\t\t\tif(amOrPm != null)\n\t\t\t\t\t\t\t\tcal.set(Calendar.HOUR, new Integer(hour));\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tcal.set(Calendar.HOUR_OF_DAY, new Integer(hour));\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tcal.set(Calendar.HOUR, 0);\n\n\t\t\t\t\t\tcal.set(Calendar.MINUTE,\n\t\t\t\t\t\t\t\t(min != null ? new Integer(min) : 0));\n\t\t\t\t\t\tcal.set(Calendar.SECOND,\n\t\t\t\t\t\t\t\t(sec != null ? new Integer(sec) : 0));\n\t\t\t\t\t\tcal.set(Calendar.MILLISECOND,\n\t\t\t\t\t\t\t\t(ms != null ? new Integer(ms) : 0));\n\n\t\t\t\t\t\tif(amOrPm != null)\n\t\t\t\t\t\t\tcal.set(Calendar.AM_PM,\n\t\t\t\t\t\t\t\t\t(amOrPm.equalsIgnoreCase(\"a\")\n\t\t\t\t\t\t\t\t\t\t\t|| amOrPm.equalsIgnoreCase(\"am\") ? Calendar.AM\n\t\t\t\t\t\t\t\t\t\t\t: Calendar.PM));\n\n\t\t\t\t\t\treturn new Date(cal.getTimeInMillis());\n\t\t\t\t\t}\n\n\t\t\t\t\t// increments\n\t\t\t\t\telse if(type == FormatType.INCREMENT\n\t\t\t\t\t\t\t|| type == FormatType.DECREMENT) {\n\t\t\t\t\t\tMatcher units = unit.matcher(dateTimeString);\n\t\t\t\t\t\twhile (units.find()) {\n\t\t\t\t\t\t\tInteger val = new Integer(units.group(1))\n\t\t\t\t\t\t\t\t\t* (type == FormatType.DECREMENT ? -1 : 1);\n\t\t\t\t\t\t\tString u = units.group(2);\n\n\t\t\t\t\t\t\t// second\n\t\t\t\t\t\t\tif(\"s\".equalsIgnoreCase(u)\n\t\t\t\t\t\t\t\t\t|| \"sec\".equalsIgnoreCase(u)\n\t\t\t\t\t\t\t\t\t|| \"second\".equalsIgnoreCase(u))\n\t\t\t\t\t\t\t\tcal.set(Calendar.SECOND,\n\t\t\t\t\t\t\t\t\t\tcal.get(Calendar.SECOND) + val);\n\n\t\t\t\t\t\t\t// minute\n\t\t\t\t\t\t\telse if(\"m\".equalsIgnoreCase(u)\n\t\t\t\t\t\t\t\t\t|| \"min\".equalsIgnoreCase(u)\n\t\t\t\t\t\t\t\t\t|| \"minute\".equalsIgnoreCase(u))\n\t\t\t\t\t\t\t\tcal.set(Calendar.MINUTE,\n\t\t\t\t\t\t\t\t\t\tcal.get(Calendar.MINUTE) + val);\n\n\t\t\t\t\t\t\t// hour\n\t\t\t\t\t\t\telse if(\"h\".equalsIgnoreCase(u)\n\t\t\t\t\t\t\t\t\t|| \"hr\".equalsIgnoreCase(u)\n\t\t\t\t\t\t\t\t\t|| \"hour\".equalsIgnoreCase(u))\n\t\t\t\t\t\t\t\tcal.set(Calendar.HOUR_OF_DAY,\n\t\t\t\t\t\t\t\t\t\tcal.get(Calendar.HOUR_OF_DAY) + val);\n\n\t\t\t\t\t\t\t// day\n\t\t\t\t\t\t\telse if(\"d\".equalsIgnoreCase(u)\n\t\t\t\t\t\t\t\t\t|| \"day\".equalsIgnoreCase(u))\n\t\t\t\t\t\t\t\tcal.set(Calendar.DATE, cal.get(Calendar.DATE)\n\t\t\t\t\t\t\t\t\t\t+ val);\n\n\t\t\t\t\t\t\t// week\n\t\t\t\t\t\t\telse if(\"w\".equalsIgnoreCase(u)\n\t\t\t\t\t\t\t\t\t|| \"wk\".equalsIgnoreCase(u)\n\t\t\t\t\t\t\t\t\t|| \"week\".equalsIgnoreCase(u))\n\t\t\t\t\t\t\t\tcal.set(Calendar.WEEK_OF_YEAR,\n\t\t\t\t\t\t\t\t\t\tcal.get(Calendar.WEEK_OF_YEAR) + val);\n\n\t\t\t\t\t\t\t// month\n\t\t\t\t\t\t\telse if(\"mo\".equalsIgnoreCase(u)\n\t\t\t\t\t\t\t\t\t|| \"mon\".equalsIgnoreCase(u)\n\t\t\t\t\t\t\t\t\t|| \"month\".equalsIgnoreCase(u))\n\t\t\t\t\t\t\t\tcal.set(Calendar.MONTH, cal.get(Calendar.MONTH)\n\t\t\t\t\t\t\t\t\t\t+ val);\n\n\t\t\t\t\t\t\t// year\n\t\t\t\t\t\t\telse if(\"y\".equalsIgnoreCase(u)\n\t\t\t\t\t\t\t\t\t|| \"yr\".equalsIgnoreCase(u)\n\t\t\t\t\t\t\t\t\t|| \"year\".equalsIgnoreCase(u))\n\t\t\t\t\t\t\t\tcal.set(Calendar.YEAR, cal.get(Calendar.YEAR)\n\t\t\t\t\t\t\t\t\t\t+ val);\n\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\t\t\t\t\tString.format(\n\t\t\t\t\t\t\t\t\t\t\t\t\"Unrecognized %s unit: [%s]\",\n\t\t\t\t\t\t\t\t\t\t\t\ttype, u));\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn new Date(cal.getTimeInMillis());\n\t\t\t\t\t}\n\n\t\t\t\t\t// compound expressions\n\t\t\t\t\telse if(type == FormatType.COMPOUND) {\n\t\t\t\t\t\treturn new Date(parseLong(m.group(2), new Date(\n\t\t\t\t\t\t\t\tparseLong(m.group(1), now))));\n\t\t\t\t\t}\n\n\t\t\t\t\t// month of the year\n\t\t\t\t\telse if(type == FormatType.MONTH) {\n\t\t\t\t\t\tCalendar ref = Calendar.getInstance();\n\t\t\t\t\t\tref.setTime(new SimpleDateFormat(\"MMM d, y\")\n\t\t\t\t\t\t\t\t.parse(String.format(\"%s 1, 1970\", m.group(1))));\n\t\t\t\t\t\tcal.set(Calendar.MONTH, ref.get(Calendar.MONTH));\n\n\t\t\t\t\t\treturn new Date(cal.getTimeInMillis());\n\t\t\t\t\t}\n\n\t\t\t\t\t// day of week\n\t\t\t\t\telse if(type == FormatType.DAY_OF_WEEK) {\n\t\t\t\t\t\tInteger ref = translateDayOfWeek.get(dateTimeString);\n\t\t\t\t\t\tif(cal.get(Calendar.DAY_OF_WEEK) >= ref)\n\t\t\t\t\t\t\tcal.set(Calendar.WEEK_OF_YEAR,\n\t\t\t\t\t\t\t\t\tcal.get(Calendar.WEEK_OF_YEAR) + 1);\n\t\t\t\t\t\tcal.set(Calendar.DAY_OF_WEEK, ref);\n\n\t\t\t\t\t\treturn new Date(cal.getTimeInMillis());\n\t\t\t\t\t}\n\n\t\t\t\t\t// month and day with slashes\n\t\t\t\t\telse if(type == FormatType.MONTH_AND_DATE_WITH_SLASHES) {\n\t\t\t\t\t\tCalendar ref = Calendar.getInstance();\n\t\t\t\t\t\tref.setTime(new SimpleDateFormat(\"M/d/y\").parse(String\n\t\t\t\t\t\t\t\t.format(\"%s/%s/1970\", m.group(1), m.group(3))));\n\t\t\t\t\t\tcal.set(Calendar.MONTH, ref.get(Calendar.MONTH));\n\t\t\t\t\t\tcal.set(Calendar.DATE, ref.get(Calendar.DATE));\n\n\t\t\t\t\t\treturn new Date(cal.getTimeInMillis());\n\t\t\t\t\t}\n\n\t\t\t\t\t// month and day long-hand\n\t\t\t\t\telse if(type == FormatType.MONTH_AND_DATE) {\n\t\t\t\t\t\tCalendar ref = Calendar.getInstance();\n\t\t\t\t\t\tref.setTime(new SimpleDateFormat(\"MMM d, y\")\n\t\t\t\t\t\t\t\t.parse(String.format(\"%s %s, 1970\", m.group(1),\n\t\t\t\t\t\t\t\t\t\tm.group(2))));\n\t\t\t\t\t\tcal.set(Calendar.MONTH, ref.get(Calendar.MONTH));\n\t\t\t\t\t\tcal.set(Calendar.DATE, ref.get(Calendar.DATE));\n\n\t\t\t\t\t\treturn new Date(cal.getTimeInMillis());\n\t\t\t\t\t}\n\n\t\t\t\t\t// next X\n\t\t\t\t\telse if(type == FormatType.NEXT) {\n\t\t\t\t\t\t// Format types MONTH and DAY_OF_WEEK both return future\n\t\t\t\t\t\t// dates, so no additional processing is needed\n\t\t\t\t\t\tString expr = m.group(1);\n\t\t\t\t\t\tParserResult parsed = StringToTime.getParserResult(\n\t\t\t\t\t\t\t\texpr, now);\n\n\t\t\t\t\t\tif(parsed != null\n\t\t\t\t\t\t\t\t&& (FormatType.MONTH.equals(parsed.type)\n\t\t\t\t\t\t\t\t\t\t|| FormatType.DAY_OF_WEEK\n\t\t\t\t\t\t\t\t\t\t\t\t.equals(parsed.type) || FormatType.MONTH_AND_DATE\n\t\t\t\t\t\t\t\t\t\t\t.equals(parsed.type)))\n\t\t\t\t\t\t\treturn new Date(parsed.timestamp);\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tif(\"week\".equalsIgnoreCase(expr))\n\t\t\t\t\t\t\t\tcal.set(Calendar.WEEK_OF_YEAR,\n\t\t\t\t\t\t\t\t\t\tcal.get(Calendar.WEEK_OF_YEAR) + 1);\n\t\t\t\t\t\t\telse if(\"month\".equalsIgnoreCase(expr))\n\t\t\t\t\t\t\t\tcal.set(Calendar.MONTH,\n\t\t\t\t\t\t\t\t\t\tcal.get(Calendar.MONTH) + 1);\n\t\t\t\t\t\t\telse if(\"year\".equalsIgnoreCase(expr))\n\t\t\t\t\t\t\t\tcal.set(Calendar.YEAR,\n\t\t\t\t\t\t\t\t\t\tcal.get(Calendar.YEAR) + 1);\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\t\t\t\t\tString.format(\n\t\t\t\t\t\t\t\t\t\t\t\t\"Invalid expression of time: %s\",\n\t\t\t\t\t\t\t\t\t\t\t\tdateTimeString));\n\n\t\t\t\t\t\t\treturn new Date(cal.getTimeInMillis());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// last X\n\t\t\t\t\telse if(type == FormatType.LAST) {\n\t\t\t\t\t\tString expr = m.group(1);\n\t\t\t\t\t\tParserResult parsed = StringToTime.getParserResult(\n\t\t\t\t\t\t\t\texpr, now);\n\n\t\t\t\t\t\tif(parsed != null\n\t\t\t\t\t\t\t\t&& (FormatType.MONTH.equals(parsed.type) || FormatType.MONTH_AND_DATE\n\t\t\t\t\t\t\t\t\t\t.equals(parsed.type))) {\n\t\t\t\t\t\t\treturn new Date(parseLong(\"-1 year\", new Date(\n\t\t\t\t\t\t\t\t\tparsed.timestamp)));\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\telse if(parsed != null\n\t\t\t\t\t\t\t\t&& FormatType.DAY_OF_WEEK.equals(parsed.type)) {\n\t\t\t\t\t\t\treturn new Date(parseLong(\"-1 week\", new Date(\n\t\t\t\t\t\t\t\t\tparsed.timestamp)));\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tif(\"week\".equalsIgnoreCase(expr))\n\t\t\t\t\t\t\t\tcal.set(Calendar.WEEK_OF_YEAR,\n\t\t\t\t\t\t\t\t\t\tcal.get(Calendar.WEEK_OF_YEAR) - 1);\n\t\t\t\t\t\t\telse if(\"month\".equalsIgnoreCase(expr))\n\t\t\t\t\t\t\t\tcal.set(Calendar.MONTH,\n\t\t\t\t\t\t\t\t\t\tcal.get(Calendar.MONTH) - 1);\n\t\t\t\t\t\t\telse if(\"year\".equalsIgnoreCase(expr))\n\t\t\t\t\t\t\t\tcal.set(Calendar.YEAR,\n\t\t\t\t\t\t\t\t\t\tcal.get(Calendar.YEAR) - 1);\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\t\t\t\t\tString.format(\n\t\t\t\t\t\t\t\t\t\t\t\t\"Invalid expression of time: %s\",\n\t\t\t\t\t\t\t\t\t\t\t\tdateTimeString));\n\n\t\t\t\t\t\t\treturn new Date(cal.getTimeInMillis());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// year\n\t\t\t\t\telse if(type == FormatType.YEAR) {\n\t\t\t\t\t\tcal.set(Calendar.YEAR, new Integer(m.group(0)));\n\t\t\t\t\t\treturn new Date(cal.getTimeInMillis());\n\t\t\t\t\t}\n\n\t\t\t\t\t// unimplemented format type\n\t\t\t\t\telse\n\t\t\t\t\t\tthrow new IllegalStateException(String.format(\n\t\t\t\t\t\t\t\t\"Unimplemented FormatType: %s\", type));\n\t\t\t\t}\n\t\t\t\tcatch (ParseException e) {\n\t\t\t\t\tthrow e;\n\t\t\t\t}\n\t\t\t\tcatch (IllegalStateException e) {\n\t\t\t\t\tthrow e;\n\t\t\t\t}\n\t\t\t\tcatch (IllegalArgumentException e) {\n\t\t\t\t\tthrow e;\n\t\t\t\t}\n\t\t\t\tcatch (Exception e) {\n\t\t\t\t\tthrow new RuntimeException(String.format(\n\t\t\t\t\t\t\t\"Unknown failure in string-to-time conversion: %s\",\n\t\t\t\t\t\t\te.getMessage()), e);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\tif(sdf != null)\n\t\t\t\treturn sdf;\n\t\t\telse\n\t\t\t\treturn type.toString();\n\t\t}\n\t}\n\n\tprivate enum FormatType {\n\t\tCOMPOUND,\n\t\tMONTH_AND_DATE_WITH_SLASHES,\n\t\tMONTH_AND_DATE,\n\t\tMONTH,\n\t\tDAY_OF_WEEK,\n\t\tNEXT,\n\t\tLAST,\n\t\tINCREMENT,\n\t\tDECREMENT,\n\t\tWORD,\n\t\tTIME,\n\t\tYEAR\n\t}\n\n\tprivate static class ParserResult {\n\t\tpublic FormatType type;\n\t\tpublic Long timestamp;\n\n\t\tpublic ParserResult(Long timestamp, FormatType type) {\n\t\t\tthis.timestamp = timestamp;\n\t\t\tthis.type = type;\n\t\t}\n\t}\n\n\tprivate static class PatternAndFormat {\n\t\tpublic Pattern p;\n\t\tpublic Format f;\n\n\t\tpublic PatternAndFormat(Pattern p, Format f) {\n\t\t\tthis.p = p;\n\t\t\tthis.f = f;\n\t\t}\n\n\t\tpublic Matcher matches(String dateTimeString) {\n\t\t\treturn p.matcher(dateTimeString);\n\t\t}\n\n\t\tpublic Long parse(String dateTimeString, Date now, Matcher m)\n\t\t\t\tthrows ParseException {\n\t\t\treturn f.parse(dateTimeString, now, m).getTime();\n\t\t}\n\t}\n\n}\n", "src/test/java/com/clutch/dates/StringToTimeTest.java": "package com.clutch.dates;\n\nimport java.text.SimpleDateFormat;\nimport java.util.Calendar;\nimport java.util.Date;\n\nimport org.junit.Assert;\nimport org.junit.Test;\n\npublic class StringToTimeTest {\n\n\t@Test\n\tpublic void testMySqlDateFormat() {\n\t\tCalendar cal = Calendar.getInstance();\n\t\tcal.set(Calendar.MONTH, Calendar.OCTOBER);\n\t\tcal.set(Calendar.DATE, 26);\n\t\tcal.set(Calendar.YEAR, 1981);\n\t\tcal.set(Calendar.HOUR_OF_DAY, 15);\n\t\tcal.set(Calendar.MINUTE, 26);\n\t\tcal.set(Calendar.SECOND, 3);\n\t\tcal.set(Calendar.MILLISECOND, 435);\n\n\t\tAssert.assertEquals(new Date(cal.getTimeInMillis()), StringToTime\n\t\t\t\t.parseDateTime(\"1981-10-26 15:26:03.435\").toDate());\n\t}\n\n\t/*\n\t * FIXME\n\t * \n\t * @Test public void testISO8601() {\n\t * Date now = new Date();\n\t * Calendar cal = Calendar.getInstance();\n\t * cal.setTime(now);\n\t * \n\t * cal.set(Calendar.MONTH, Calendar.OCTOBER);\n\t * cal.set(Calendar.DATE, 26);\n\t * cal.set(Calendar.YEAR, 1981);\n\t * cal.set(Calendar.HOUR_OF_DAY, 15);\n\t * cal.set(Calendar.MINUTE, 25);\n\t * cal.set(Calendar.SECOND, 2);\n\t * cal.set(Calendar.MILLISECOND, 435);\n\t * \n\t * Assert.assertEquals(new Date(cal.getTimeInMillis()), new\n\t * StringToTime(\"1981-10-26T15:26:03.435ZEST\", now).toDate());\n\t * }\n\t */\n\n\t@Test\n\tpublic void test1200Seconds() {\n\t\tDate now = new Date();\n\t\tCalendar cal = Calendar.getInstance();\n\t\tcal.setTime(now);\n\n\t\tcal.set(Calendar.SECOND, cal.get(Calendar.SECOND) + 1200);\n\t\tAssert.assertTrue(new Date(cal.getTimeInMillis()).equals(StringToTime\n\t\t\t\t.parseDateTime(\"+1200 s\", now).toDate()));\n\t\tAssert.assertFalse(new Date(cal.getTimeInMillis()).equals(StringToTime\n\t\t\t\t.parseDateTime(\"+1 s\", now).toDate()));\n\t}\n\n\t@Test\n\tpublic void testVariousExpressionsOfTimeOfDay() {\n\t\tDate now = new Date();\n\t\tCalendar cal = Calendar.getInstance();\n\t\tcal.setTime(now);\n\n\t\tcal.set(Calendar.HOUR_OF_DAY, 23);\n\t\tcal.set(Calendar.MINUTE, 59);\n\t\tcal.set(Calendar.SECOND, 59);\n\t\tcal.set(Calendar.MILLISECOND, 0);\n\t\tAssert.assertEquals(new Date(cal.getTimeInMillis()), StringToTime\n\t\t\t\t.parseDateTime(\"11:59:59 PM\", now).toDate());\n\t\tAssert.assertEquals(new Date(cal.getTimeInMillis()), StringToTime\n\t\t\t\t.parseDateTime(\"23:59:59\", now).toDate());\n\n\t\tcal.set(Calendar.SECOND, 0);\n\t\tAssert.assertEquals(new Date(cal.getTimeInMillis()), StringToTime\n\t\t\t\t.parseDateTime(\"23:59\", now).toDate());\n\t\tAssert.assertEquals(new Date(cal.getTimeInMillis()), StringToTime\n\t\t\t\t.parseDateTime(\"11:59 PM\", now).toDate());\n\n\t\tcal.set(Calendar.MILLISECOND, 123);\n\t\tAssert.assertEquals(new Date(cal.getTimeInMillis()),\n\t\t\t\tStringToTime.parseDateTime(\"23:59:00.123\"));\n\n\t\tcal.set(Calendar.MONTH, Calendar.OCTOBER);\n\t\tcal.set(Calendar.DATE, 26);\n\t\tcal.set(Calendar.YEAR, 1981);\n\t\tcal.set(Calendar.HOUR_OF_DAY, 15);\n\t\tcal.set(Calendar.MINUTE, 27);\n\t\tcal.set(Calendar.SECOND, 0);\n\t\tcal.set(Calendar.MILLISECOND, 0);\n\t\tAssert.assertEquals(new Date(cal.getTimeInMillis()), StringToTime\n\t\t\t\t.parseDateTime(\"October 26, 1981 3:27:00 PM\", now).toDate());\n\n\t\tcal.set(Calendar.HOUR, 5);\n\t\tcal.set(Calendar.MINUTE, 0);\n\t\tcal.set(Calendar.SECOND, 0);\n\t\tcal.set(Calendar.AM_PM, Calendar.PM);\n\t\tAssert.assertEquals(new Date(cal.getTimeInMillis()), StringToTime\n\t\t\t\t.parseDateTime(\"10/26/81 5PM\", now).toDate());\n\n\t\tcal.setTime(now);\n\t\tcal.set(Calendar.DATE, cal.get(Calendar.DATE) + 1);\n\t\tcal.set(Calendar.HOUR, 5);\n\t\tcal.set(Calendar.MINUTE, 0);\n\t\tcal.set(Calendar.SECOND, 0);\n\t\tcal.set(Calendar.MILLISECOND, 0);\n\t\tcal.set(Calendar.AM_PM, Calendar.PM);\n\t\tAssert.assertEquals(new Date(cal.getTimeInMillis()), StringToTime\n\t\t\t\t.parseDateTime(\"tomorrow 5PM\", now).toDate());\n\n\t\tcal.set(Calendar.DATE, cal.get(Calendar.DATE) - 2);\n\t\tAssert.assertEquals(new Date(cal.getTimeInMillis()), StringToTime\n\t\t\t\t.parseDateTime(\"yesterday 5PM\", now).toDate());\n\t\tAssert.assertEquals(StringToTime\n\t\t\t\t.parseDateTime(\"yesterday evening\", now).toDate(), StringToTime\n\t\t\t\t.parseDateTime(\"yesterday 5PM\", now).toDate());\n\t}\n\n\t@Test\n\tpublic void testNow() {\n\t\tDate now = new Date();\n\t\tAssert.assertEquals(new Date(now.getTime()), StringToTime\n\t\t\t\t.parseDateTime(\"now\", now).toDate());\n\t}\n\n\t@Test\n\tpublic void testToday() {\n\t\tDate now = new Date();\n\t\tAssert.assertEquals(StringToTime.parseDateTime(\"00:00:00.000\", now)\n\t\t\t\t.toDate(), StringToTime.parseDateTime(\"today\", now).toDate());\n\t}\n\n\t@Test\n\tpublic void testThisMorning() {\n\t\tDate now = new Date();\n\t\tAssert.assertEquals(StringToTime.parseDateTime(\"07:00:00.000\", now)\n\t\t\t\t.toDate(), StringToTime.parseDateTime(\"this morning\", now)\n\t\t\t\t.toDate());\n\t\tAssert.assertEquals(\n\t\t\t\tStringToTime.parseDateTime(\"morning\", now).toDate(),\n\t\t\t\tStringToTime.parseDateTime(\"this morning\", now).toDate());\n\t}\n\n\t@Test\n\tpublic void testNoon() {\n\t\tDate now = new Date();\n\t\tAssert.assertEquals(StringToTime.parseDateTime(\"12:00:00.000\", now)\n\t\t\t\t.toDate(), StringToTime.parseDateTime(\"noon\", now).toDate());\n\t}\n\n\t@Test\n\tpublic void testThisAfternoon() {\n\t\tDate now = new Date();\n\t\tAssert.assertEquals(StringToTime.parseDateTime(\"13:00:00.000\", now)\n\t\t\t\t.toDate(), StringToTime.parseDateTime(\"this afternoon\", now)\n\t\t\t\t.toDate());\n\t\tAssert.assertEquals(StringToTime.parseDateTime(\"afternoon\", now)\n\t\t\t\t.toDate(), StringToTime.parseDateTime(\"this afternoon\", now)\n\t\t\t\t.toDate());\n\t}\n\n\t@Test\n\tpublic void testThisEvening() {\n\t\tDate now = new Date();\n\t\tAssert.assertEquals(StringToTime.parseDateTime(\"17:00:00.000\", now)\n\t\t\t\t.toDate(), StringToTime.parseDateTime(\"this evening\", now)\n\t\t\t\t.toDate());\n\t\tAssert.assertEquals(\n\t\t\t\tStringToTime.parseDateTime(\"evening\", now).toDate(),\n\t\t\t\tStringToTime.parseDateTime(\"this evening\", now).toDate());\n\t}\n\n\t@Test\n\tpublic void testTonight() {\n\t\tDate now = new Date();\n\t\tAssert.assertEquals(StringToTime.parseDateTime(\"20:00:00.000\", now)\n\t\t\t\t.toDate(), StringToTime.parseDateTime(\"tonight\", now).toDate());\n\t}\n\n\t@Test\n\tpublic void testIncrements() {\n\t\tDate now = new Date();\n\n\t\tCalendar cal = Calendar.getInstance();\n\t\tcal.setTime(now);\n\t\tcal.set(Calendar.HOUR_OF_DAY, cal.get(Calendar.HOUR_OF_DAY) + 1);\n\t\tAssert.assertEquals(cal.getTimeInMillis(),\n\t\t\t\tStringToTime.parseDateTime(\"+1 hour\", now).toDate());\n\n\t\tcal.setTime(now);\n\t\tcal.set(Calendar.WEEK_OF_YEAR, cal.get(Calendar.WEEK_OF_YEAR) + 52);\n\t\tAssert.assertEquals(cal.getTimeInMillis(),\n\t\t\t\tStringToTime.parseDateTime(\"+52 weeks\", now).toDate());\n\n\t\tAssert.assertEquals(StringToTime.parseDateTime(\"1 year\", now).toDate(),\n\t\t\t\tStringToTime.parseDateTime(\"+1 year\", now).toDate());\n\n\t\tAssert.assertEquals(\n\t\t\t\tStringToTime.parseDateTime(\"+1 year\", now).toDate(),\n\t\t\t\tStringToTime.parseDateTime(\"+12 months\", now).toDate());\n\n\t\tAssert.assertEquals(StringToTime.parseDateTime(\"+1 year 6 months\", now)\n\t\t\t\t.toDate(), StringToTime.parseDateTime(\"+18 months\", now)\n\t\t\t\t.toDate());\n\n\t\tAssert.assertEquals(\n\t\t\t\tStringToTime.parseDateTime(\"12 months 1 day 60 seconds\", now)\n\t\t\t\t\t\t.toDate(),\n\t\t\t\tStringToTime.parseDateTime(\"1 year 24 hours 1 minute\", now)\n\t\t\t\t\t\t.toDate());\n\t}\n\n\t@Test\n\tpublic void testDecrements() {\n\t\tDate now = new Date();\n\n\t\tCalendar cal = Calendar.getInstance();\n\t\tcal.setTime(now);\n\t\tcal.set(Calendar.HOUR_OF_DAY, cal.get(Calendar.HOUR_OF_DAY) - 1);\n\t\tAssert.assertEquals(new Date(cal.getTimeInMillis()), StringToTime\n\t\t\t\t.parseDateTime(\"-1 hour\", now).toDate());\n\t}\n\n\t@Test\n\tpublic void testTomorrow() {\n\t\tDate now = new Date();\n\t\tCalendar cal = Calendar.getInstance();\n\t\tcal.setTime(now);\n\t\tcal.set(Calendar.DATE, cal.get(Calendar.DATE) + 1);\n\t\tAssert.assertEquals(new Date(cal.getTimeInMillis()), StringToTime\n\t\t\t\t.parseDateTime(\"tomorrow\", now).toDate());\n\t\tAssert.assertEquals(StringToTime.parseDateTime(\"now +24 hours\", now)\n\t\t\t\t.toDate(), StringToTime.parseDateTime(\"tomorrow\", now).toDate());\n\t}\n\n\t@Test\n\tpublic void testTomorrowMorning() {\n\t\tDate now = new Date();\n\t\tAssert.assertEquals(\n\t\t\t\tStringToTime.parseDateTime(\"this morning +24 hours\", now)\n\t\t\t\t\t\t.toDate(),\n\t\t\t\tStringToTime.parseDateTime(\"tomorrow morning\", now).toDate());\n\t}\n\n\t@Test\n\tpublic void testTomorrowNoon() {\n\t\tDate now = new Date();\n\t\tAssert.assertEquals(StringToTime.parseDateTime(\"noon +24 hours\", now)\n\t\t\t\t.toDate(), StringToTime.parseDateTime(\"tomorrow noon\", now)\n\t\t\t\t.toDate());\n\t\tAssert.assertEquals(StringToTime.parseDateTime(\"noon +24 hours\", now)\n\t\t\t\t.toDate(), StringToTime.parseDateTime(\"noon tomorrow\", now)\n\t\t\t\t.toDate());\n\t}\n\n\t@Test\n\tpublic void testTomorrowAfternoon() {\n\t\tDate now = new Date();\n\t\tAssert.assertEquals(\n\t\t\t\tStringToTime.parseDateTime(\"this afternoon +24 hours\", now)\n\t\t\t\t\t\t.toDate(),\n\t\t\t\tStringToTime.parseDateTime(\"tomorrow afternoon\", now).toDate());\n\t}\n\n\t@Test\n\tpublic void testTomorrowEvening() {\n\t\tDate now = new Date();\n\t\tAssert.assertEquals(\n\t\t\t\tStringToTime.parseDateTime(\"this evening +24 hours\", now)\n\t\t\t\t\t\t.toDate(),\n\t\t\t\tStringToTime.parseDateTime(\"tomorrow evening\", now).toDate());\n\t}\n\n\t@Test\n\tpublic void testTomorrowNight() {\n\t\tDate now = new Date();\n\t\tAssert.assertEquals(StringToTime\n\t\t\t\t.parseDateTime(\"tonight +24 hours\", now).toDate(), StringToTime\n\t\t\t\t.parseDateTime(\"tomorrow night\", now).toDate());\n\t}\n\n\t// e.g., October 26, 1981, or Oct 26, 1981, or 26 October 1981, or 26 Oct\n\t// 1981, or 26 Oct 81\n\t@Test\n\tpublic void testLongHand() throws Exception {\n\t\tAssert.assertEquals(new SimpleDateFormat(\"M/d/y\").parse(\"10/26/1981\"),\n\t\t\t\tStringToTime.parseDateTime(\"October 26, 1981\"));\n\t\tAssert.assertEquals(new SimpleDateFormat(\"M/d/y\").parse(\"10/26/1981\"),\n\t\t\t\tStringToTime.parseDateTime(\"Oct 26, 1981\"));\n\n\t\tAssert.assertEquals(new SimpleDateFormat(\"M/d/y\").parse(\"10/26/1981\"),\n\t\t\t\tStringToTime.parseDateTime(\"26 October 1981\"));\n\t\tAssert.assertEquals(new SimpleDateFormat(\"M/d/y\").parse(\"10/26/1981\"),\n\t\t\t\tStringToTime.parseDateTime(\"26 Oct 1981\"));\n\t\tAssert.assertEquals(new SimpleDateFormat(\"M/d/y\").parse(\"10/26/1981\"),\n\t\t\t\tStringToTime.parseDateTime(\"26 Oct 81\"));\n\n\t\tAssert.assertEquals(new SimpleDateFormat(\"M/d/y\").parse(\"10/26/1981\"),\n\t\t\t\tStringToTime.parseDateTime(\"26 october 1981\"));\n\t\tAssert.assertEquals(new SimpleDateFormat(\"M/d/y\").parse(\"10/26/1981\"),\n\t\t\t\tStringToTime.parseDateTime(\"26 oct 1981\"));\n\t\tAssert.assertEquals(new SimpleDateFormat(\"M/d/y\").parse(\"10/26/1981\"),\n\t\t\t\tStringToTime.parseDateTime(\"26 oct 81\"));\n\n\t\tAssert.assertEquals(new SimpleDateFormat(\"M/d/y\").parse(\"1/1/2000\"),\n\t\t\t\tStringToTime.parseDateTime(\"1 Jan 2000\"));\n\t\tAssert.assertEquals(new SimpleDateFormat(\"M/d/y\").parse(\"1/1/2000\"),\n\t\t\t\tStringToTime.parseDateTime(\"1 Jan 00\"));\n\n\t\tAssert.assertEquals(new SimpleDateFormat(\"M/d/y\").parse(\"1/1/2000\"),\n\t\t\t\tStringToTime.parseDateTime(\"1 jan 2000\"));\n\t\tAssert.assertEquals(new SimpleDateFormat(\"M/d/y\").parse(\"1/1/2000\"),\n\t\t\t\tStringToTime.parseDateTime(\"1 jan 00\"));\n\t}\n\n\t// e.g., 10/26/1981 or 10/26/81\n\t@Test\n\tpublic void testWithSlahesMonthFirst() throws Exception {\n\t\tAssert.assertEquals(new SimpleDateFormat(\"M/d/y\").parse(\"10/26/1981\"),\n\t\t\t\tStringToTime.parseDateTime(\"10/26/1981\"));\n\t\tAssert.assertEquals(new SimpleDateFormat(\"M/d/y\").parse(\"10/26/1981\"),\n\t\t\t\tStringToTime.parseDateTime(\"10/26/81\"));\n\t}\n\n\t// e.g., 1981/10/26\n\t@Test\n\tpublic void testWithSlashesYearFirst() throws Exception {\n\t\tAssert.assertEquals(new SimpleDateFormat(\"M/d/y\").parse(\"10/26/1981\"),\n\t\t\t\tStringToTime.parseDateTime(\"1981/10/26\"));\n\t}\n\n\t// e.g., October 26 and Oct 26\n\t@Test\n\tpublic void testMonthAndDate() throws Exception {\n\t\tDate now = new Date();\n\t\tCalendar cal = Calendar.getInstance();\n\t\tcal.set(Calendar.MONTH, Calendar.OCTOBER);\n\t\tcal.set(Calendar.DATE, 26);\n\t\tAssert.assertEquals(new Date(cal.getTimeInMillis()), StringToTime\n\t\t\t\t.parseDateTime(\"October 26\", now).toDate());\n\t\tAssert.assertEquals(StringToTime.parseDateTime(\"Oct 26\", now).toDate(),\n\t\t\t\tStringToTime.parseDateTime(\"October 26\", now).toDate());\n\t}\n\n\t// e.g., 10/26\n\t@Test\n\tpublic void testWithSlahesMonthAndDate() throws Exception {\n\t\tCalendar cal = Calendar.getInstance();\n\t\tcal.set(Calendar.MONTH, Calendar.OCTOBER);\n\t\tcal.set(Calendar.DATE, 26);\n\t\tAssert.assertEquals(new Date(cal.getTimeInMillis()), StringToTime\n\t\t\t\t.parseDateTime(\"10/26\").toDate());\n\t}\n\n\t// e.g., October or Oct\n\t@Test\n\tpublic void testMonth() throws Exception {\n\t\tDate now = new Date();\n\n\t\tAssert.assertEquals(\n\t\t\t\tStringToTime.parseDateTime(\"October\", now).toDate(),\n\t\t\t\tStringToTime.parseDateTime(\"Oct\", now));\n\n\t\tCalendar cal = Calendar.getInstance();\n\t\tcal.setTime(now);\n\n\t\tCalendar cal2 = Calendar.getInstance();\n\n\t\t// it should be this year\n\t\tcal2.setTime(StringToTime.parseDateTime(\"January\", now).toDate());\n\t\tAssert.assertEquals(cal.get(Calendar.YEAR), cal2.get(Calendar.YEAR));\n\t\tcal2.setTime(StringToTime.parseDateTime(\"December\", now).toDate());\n\t\tAssert.assertEquals(cal.get(Calendar.YEAR), cal2.get(Calendar.YEAR));\n\t}\n\n\t@Test\n\tpublic void testDayOfWeek() throws Exception {\n\t\tDate now = new Date();\n\t\tAssert.assertEquals(StringToTime.parseDateTime(\"Friday\", now).toDate(),\n\t\t\t\tStringToTime.parseDateTime(\"Fri\", now).toDate());\n\n\t\tCalendar cal = Calendar.getInstance();\n\t\tcal.setTime(now);\n\n\t\t// if today's day of the week is greater than or equal to our test day\n\t\t// of the week (Wednesday)\n\t\tCalendar cal2 = Calendar.getInstance();\n\t\tif(cal.get(Calendar.DAY_OF_WEEK) >= 3) {// then the day of the week on\n\t\t\t\t\t\t\t\t\t\t\t\t// the date returned should be\n\t\t\t\t\t\t\t\t\t\t\t\t// next week\n\t\t\tcal2.setTime(StringToTime.parseDateTime(\"Wednesday\", now).toDate());\n\t\t\tAssert.assertEquals(cal.get(Calendar.WEEK_OF_YEAR) + 1,\n\t\t\t\t\tcal2.get(Calendar.WEEK_OF_YEAR));\n\t\t}\n\t\telse {\n\t\t\t// otherwise, it should be this year\n\t\t\tcal2.setTime(StringToTime.parseDateTime(\"Wednesday\", now).toDate());\n\t\t\tAssert.assertEquals(cal.get(Calendar.WEEK_OF_YEAR),\n\t\t\t\t\tcal2.get(Calendar.WEEK_OF_YEAR));\n\t\t}\n\t}\n\n\t@Test\n\tpublic void testNext() {\n\t\tDate now = new Date();\n\t\tAssert.assertEquals(StringToTime.parseDateTime(\"next January 15\", now)\n\t\t\t\t.toDate(), StringToTime.parseDateTime(\"Jan 15\", now).toDate());\n\t\tAssert.assertEquals(StringToTime.parseDateTime(\"next Dec\", now)\n\t\t\t\t.toDate(), StringToTime.parseDateTime(\"December\", now).toDate());\n\t\tAssert.assertEquals(StringToTime.parseDateTime(\"next Sunday\", now)\n\t\t\t\t.toDate(), StringToTime.parseDateTime(\"Sun\", now).toDate());\n\t\tAssert.assertEquals(StringToTime.parseDateTime(\"next Sat\", now)\n\t\t\t\t.toDate(), StringToTime.parseDateTime(\"Saturday\", now).toDate());\n\t}\n\n\t@Test\n\tpublic void testLast() {\n\t\tDate now = new Date();\n\t\tAssert.assertEquals(StringToTime.parseDateTime(\"last January 15\", now)\n\t\t\t\t.toDate(), StringToTime.parseDateTime(\"Jan 15 -1 year\", now)\n\t\t\t\t.toDate());\n\t\tAssert.assertEquals(StringToTime.parseDateTime(\"last Dec\", now)\n\t\t\t\t.toDate(), StringToTime.parseDateTime(\"December -1 year\", now)\n\t\t\t\t.toDate());\n\t\tAssert.assertEquals(StringToTime.parseDateTime(\"last Sunday\", now)\n\t\t\t\t.toDate(), StringToTime.parseDateTime(\"Sun -1 week\", now)\n\t\t\t\t.toDate());\n\t\tAssert.assertEquals(StringToTime.parseDateTime(\"last Sat\", now)\n\t\t\t\t.toDate(), StringToTime.parseDateTime(\"Saturday -1 week\", now)\n\t\t\t\t.toDate());\n\t}\n\n}\n"}} -{"repo": "nbarbey/TomograPy", "pr_number": 1, "title": "Converts to Rust and adds modern features", "state": "closed", "merged_at": "2023-09-28T19:47:41Z", "additions": 2784, "deletions": 4852, "files_changed": ["exemples/test_bpj.py", "exemples/test_siddon_cgs_secchi.py", "exemples/test_siddon_cor1.py", "exemples/test_siddon_lo.py", "exemples/test_siddon_secchi.py", "exemples/test_siddon_secchi_dt.py", "exemples/test_siddon_secchi_mask.py", "exemples/test_siddon_simu.py", "exemples/test_siddon_simu_dt.py", "exemples/test_siddon_simu_dt_lo.py", "exemples/test_siddon_simu_lo.py", "exemples/test_siddon_simu_sun.py", "exemples/test_thomson_simu.py", "experiments.py", "experiments_dottest.py", "experiments_filtered_bpj.py", "experiments_multi_view.py", "experiments_only_bpj.py", "experiments_single_view.py", "experiments_solar.py", "python/tomograpy/__init__.py", "python/tomograpy/coordinates.py", "python/tomograpy/third.py"], "files_before": {"exemples/test_bpj.py": "#!/usr/bin/env python\n\n\"\"\"\nSmall projection test to compare with IDL tomograpy.\n\"\"\"\n\nimport numpy as np\nimport tomograpy\nim = tomograpy.centered_stack(0.0016, 32, n_images=1, radius=200., fill=0.)\ncube = tomograpy.centered_cubic_map(3, 256, fill=1.)\nP = tomograpy.lo(im.header, cube.header, obstacle=\"sun\")\nim[:] = (P * cube.ravel()).reshape(im.shape)\n", "exemples/test_siddon_cgs_secchi.py": "#!/usr/bin/env python\nimport numpy as np\nimport os\nimport copy\nimport time\nimport tomograpy\nimport fitsarray as fa\nimport lo\nimport scipy.sparse.linalg as spl\n# data \npath = os.path.join(os.getenv('HOME'), 'data', '171dec08')\nobsrvtry = 'STEREO_A'\ntime_window = ['2008-12-01T00:00:00.000', '2008-12-03T00:00:00.000']\n# one image every time_step seconds\ntime_step = 4 * 3600.\ndata = tomograpy.secchi.read_data(path, bin_factor=4,\n obsrvtry=obsrvtry,\n time_window=time_window, \n time_step=time_step)\n# cube\nshape = 3 * (128,)\nheader = {'CRPIX1':64., 'CRPIX2':64., 'CRPIX3':64.,\n 'CDELT1':0.0234375, 'CDELT2':0.0234375, 'CDELT3':0.0234375,\n 'CRVAL1':0., 'CRVAL2':0., 'CRVAL3':0.,}\ncube = fa.zeros(shape, header=header)\n# model\nP = tomograpy.lo(data.header, cube.header)\nD = [lo.diff(cube.shape, axis=i) for i in xrange(cube.ndim)]\nhypers = cube.ndim * (1e0, )\n# inversion\nt = time.time()\nA = P.T * P + np.sum([h * d.T * d for h, d in zip(hypers, D)])\nb = P.T * data.flatten()\n#callback = lo.iterative.CallbackFactory(verbose=True)\n#x, info = spl.bicgstab(A, b, maxiter=100, callback=callback)\nx, info = lo.acg(P, data.flatten(), D, hypers, maxiter=100,)\nsol = cube.copy()\nsol[:] = x.reshape(cube.shape)\nprint(time.time() - t)\n", "exemples/test_siddon_cor1.py": "#!/usr/bin/env python\nimport numpy as np\nimport os\nimport copy\nimport time\nimport tomograpy\nimport fitsarray as fa\nimport lo\n\n# data \npath = os.path.join(os.getenv('HOME'), 'data', 'tomograpy., 'cor1')\n#obsrvtry = 'SOHO '\n#instrume = 'LASCO '\ntime_window = ['2009/09/01 00:00:00.000', '2009/09/15 00:00:00.000']\ntime_step = 8 * 3600. # one image every time_step seconds\ndata = tomograpy.solar.read_data(path, bin_factor=8,\n #time_window=time_window, \n #time_step=time_step\n )\n# errors in data ...\ndata.header['BITPIX'][:] = -64\ndata[np.isnan(data)] = 0.\ndata.header['RSUN'] /= 16.\n# cube\nshape = np.asarray(3 * (128. ,))\ncrpix = shape / 2.\ncdelt = 6. / shape\ncrval = np.zeros(3)\nheader = {'CRPIX1':crpix[0], 'CRPIX2':crpix[1], 'CRPIX3':crpix[2],\n 'CDELT1':cdelt[0], 'CDELT2':cdelt[1], 'CDELT3':cdelt[2],\n 'CRVAL1':0., 'CRVAL2':0., 'CRVAL3':0.,}\ncube = fa.zeros(shape, header=header)\nt = time.time()\ncube = tomograpy.backprojector(data, cube, obstacle=\"sun\")\nprint(\"backprojection time : \" + str(time.time() - t))\n\n# inversion\nt = time.time()\nu = .5\nkwargs={\n \"obj_rmin\":1.5,\n \"obj_rmax\":3.,\n \"data_rmin\":1.5,\n \"data_rmax\":2.5,\n \"mask_negative\":True\n}\nP, D, obj_mask, data_mask = tomograpy.models.thomson(data, cube, u, **kwargs)\n# bpj\nb = data.flatten()\nbpj = (P.T * b).reshape(cube.shape)\nhypers = 1e3 * np.ones(3)\nsol = lo.acg(P, b, D, hypers, maxiter=100, tol=1e-6)\nprint(\"inversion time : %f\" % (time.time() - t))\n# reshape solution\nsol.resize(cube.shape)\nsol = fa.asfitsarray(sol, header=cube.header)\n# reproject solution\nreproj = P * sol.ravel()\nreproj.resize(data.shape)\n", "exemples/test_siddon_lo.py": "#!/bin/env python\nimport numpy as np\nimport os\nimport copy\nimport time\nimport tomograpy\nimport fitsarray as fa\n# data \npath = os.path.join(os.getenv('HOME'), 'data', '171dec08')\nobsrvtry = 'STEREO_A'\ntime_window = ['2008-12-01T00:00:00.000', '2008-12-03T00:00:00.000']\ntime_step = 4 * 3600. # one image every time_step seconds\ndata = tomograpy.secchi.read_data(path, bin_factor=4,\n obsrvtry=obsrvtry,\n time_window=time_window, \n time_step=time_step)\n# cube\nshape = 3 * (128,)\nheader = dict()\nfor i in xrange(1, 4):\n header['CRPIX' + str(i)] = 64.\n header['CDELT' + str(i)] = 0.0234375\n header['CRVAL' + str(i)] = 0.\ncube = fa.zeros(shape, header=header, dtype=np.float32)\nP = tomograpy.sun_lo(data.header, cube.header)\nt = time.time()\nfbp = (P.T * data.flatten()).reshape(cube.shape)\nprint(\"backprojection time : \" + str(time.time() - t))\n\nt = time.time()\nfbp0 = tomograpy.backprojector_sun(data, cube)\nprint(\"backprojection time : \" + str(time.time() - t))\n\n#assert np.all(fbp == fbp0)\n", "exemples/test_siddon_secchi.py": "#!/usr/bin/env python\nimport numpy as np\nimport os\nimport copy\nimport time\nimport tomograpy\nimport fitsarray as fa\n# data \npath = os.path.join(os.getenv('HOME'), 'data', 'tomograpy., '171dec08')\nobsrvtry = 'STEREO_A'\ntime_window = ['2008-12-01T00:00:00.000', '2008-12-15T00:00:00.000']\ntime_step = 8 * 3600. # one image every time_step seconds\ndata = tomograpy.solar.read_data(path, bin_factor=8,\n obsrvtry=obsrvtry,\n time_window=time_window, \n time_step=time_step)\n# map\ncube = tomograpy.centered_cubic_map(3, 128, fill=0.)\nt = time.time()\ncube = tomograpy.backprojector(data, cube, obstacle=\"sun\")\nprint(\"backprojection time : \" + str(time.time() - t))\n", "exemples/test_siddon_secchi_dt.py": "#!/usr/bin/env python\nimport os\nimport time\nimport numpy as np\nimport lo\nimport tomograpy\nfrom tomograpy.solar import read_data\n# data\nobsrvtry = ('STEREO_A', 'STEREO_B')\ndata = tomograpy.solar.concatenate(\n [read_data(os.path.join(os.getenv('HOME'), 'data', 'tomograpy., '171dec08'), \n bin_factor=4,\n obsrvtry=obs,\n time_window=['2008-12-01T00:00:00.000', \n '2008-12-15T00:00:00.000'],\n time_step= 4 * 3600.\n )\n for obs in obsrvtry])\ndata = tomograpy.solar.sort_data_array(data)\n# scale A and B images\n# the ratio of sensitivity between EUVI A and B\ncalibration_ba = {171:0.902023, 195:0.974536, 284:0.958269, 304:1.05954}\nfor i in xrange(data.shape[-1]):\n if data.header['OBSRVTRY'][i] == 'STEREO_B':\n data[..., i] /= calibration_ba[data.header['WAVELNTH'][i]]\n\n# make sure it is 64 bits data\ndata.header['BITPIX'][:] = -64\n# cube\nshape = 3 * (128,)\nheader = {'CRPIX1':64.,\n 'CRPIX2':64.,\n 'CRPIX3':64.,\n 'CDELT1':0.0234375,\n 'CDELT2':0.0234375,\n 'CDELT3':0.0234375,\n 'CRVAL1':0.,\n 'CRVAL2':0.,\n 'CRVAL3':0.,}\ncube = tomograpy.fa.zeros(shape, header=header)\n# model\nkwargs = {'obj_rmin':1., 'obj_rmax':1.4, 'data_rmax':1.3,\n 'mask_negative':True, 'dt_min':100}\nP, D, obj_mask, data_mask = tomograpy.models.stsrt(data, cube, **kwargs)\n# apply mask to data\ndata *= (1 - data_mask)\n# hyperparameters\nhypers = (1e-1, 1e-1, 1e-1, 1e6)\n# test time for one projection\nt = time.time()\nu = P.T * data.ravel()\nprint(\"maximal time : %f\" % ((time.time() - t) * 100))\n# inversion\nt = time.time()\nb = data.ravel()\n#sol = lo.acg(P, b, D, hypers, maxiter=100)\nsol = lo.rls(P, b, D, hypers, maxiter=100)\n# reshape result\nfsol = tomograpy.fa.asfitsarray(sol.reshape(obj_mask.shape), header=header)\nprint(time.time() - t)\nfsol.tofits('stsrt_test.fits')\n", "exemples/test_siddon_secchi_mask.py": "#!/usr/bin/env python\nimport os\nimport time\nimport numpy as np\nimport lo\nimport tomograpy\nfrom tomograpy.solar import read_data\n# data\ndata = read_data(os.path.join(os.getenv('HOME'), 'data', 'tomograpy., '171dec08'),\n bin_factor=4.,\n time_window=['2008-12-01T00:00:00.000',\n '2008-12-15T00:00:00.000'],\n time_step=8 * 3600.\n )\ndata = tomograpy.solar.sort_data_array(data)\n# scale A and B images\n# the ratio of sensitivity between EUVI A and B\ncalibration_ba = {171:0.902023, 195:0.974536, 284:0.958269, 304:1.05954}\nfor i in xrange(data.shape[-1]):\n if data.header[i]['OBSRVTRY'] == 'STEREO_B':\n data[..., i] /= calibration_ba[data.header[i]['WAVELNTH']]\n\n # make sure it is 64 bits data\n data.header[i]['BITPIX'] = -64\n\n# cube\ncube = tomograpy.centered_cubic_map(3, 64, fill=0.)\n# model\nkwargs = {'obj_rmin':1., 'obj_rmax':1.5, 'data_rmin':1., 'data_rmax':1.3,\n 'mask_negative':False, 'mask_nan':True}\nP, D, obj_mask, data_mask = tomograpy.models.srt(data, cube, **kwargs)\n# apply mask to data\ndata *= (1 - data_mask)\ndata[np.isnan(data)] = 0.\n# hyperparameters\nhypers = cube.ndim * (1e0, )\n# inversion\n# expected time\nb = data.ravel()\nb[np.isnan(b)] = 0.\nt = time.time()\nbpj = P.T * b\nprint((time.time() - t) * 4 * 100 )\n# real time\nt = time.time()\nsol = lo.acg(P, b, D, hypers, maxiter=100)\nprint(time.time() - t)\n# reshape result\nfsol = tomograpy.fa.asfitsarray(sol.reshape(cube.shape), header=cube.header)\ntomograpy.path = os.path.join(os.getenv('HOME'), 'data', 'tomograpy.)\nfsol.tofits(os.path.join(tomograpy.path, \"output\", \"test_tomograpy.secchi_mask.fits\"))\n", "exemples/test_siddon_simu.py": "#!/usr/bin/env python\nimport time\nimport numpy as np\nimport tomograpy\n# object\nobject_header = tomograpy.centered_cubic_map_header(3, 128)\nobj = tomograpy.simu.object_from_header(object_header, fill=1.)\n# data\nradius = 200.\na = tomograpy.fov(object_header, radius)\ndata = tomograpy.centered_stack(a, 128, n_images=60, radius=200., max_lon=np.pi)\n# projection\nt = time.time()\ndata = tomograpy.projector(data, obj)\nprint(\"projection time : \" + str(time.time() - t))\n# backprojection\nt = time.time()\ndata[:] = 1.\nobj0 = tomograpy.simu.object_from_header(object_header, fill=0.)\nobj0 = tomograpy.backprojector(data, obj0)\nprint(\"backprojection time : \" + str(time.time() - t))\n\nobj1 = tomograpy.simu.object_from_header(object_header, fill=0.)\nobj1 = tomograpy.backprojector(data, obj1)\n", "exemples/test_siddon_simu_dt.py": "#!/usr/bin/env python\nimport time\nimport numpy as np\nimport tomograpy\n# object\nobj = tomograpy.centered_cubic_map(3, 128, fill=1.)\n# number of images\nn = 20\n# reshape object for 4d model\nobj4 = obj.reshape(obj.shape + (1,)).repeat(n, axis=-1)\nobj4.header['NAXIS'] = 4\nobj4.header['NAXIS4'] = obj4.shape[3]\nobj4.header['CRVAL4'] = 0.\n\n# data \nradius = 200\na = tomograpy.fov(obj.header, radius)\ndata = tomograpy.centered_stack(a, 128, n_images=n, radius=radius,\n max_lon=np.pi)\ndata[:] = np.zeros(data.shape)\n# projection\nt = time.time()\ndata = tomograpy.projector4d(data, obj4)\nprint(\"projection time : \" + str(time.time() - t))\n# backprojection\nx0 = obj4.copy()\nx0[:] = 0.\nt = time.time()\nx0 = tomograpy.backprojector4d(data, x0)\nprint(\"backprojection time : \" + str(time.time() - t))\n", "exemples/test_siddon_simu_dt_lo.py": "#!/usr/bin/env python\nimport time\nimport numpy as np\nimport tomograpy\nimport lo\n# object\nobj = tomograpy.centered_cubic_map(3, 64, fill=1.)\n# number of images\nn = 64\n# reshape object for 4d model\nobj4 = obj[..., np.newaxis].repeat(n, axis=-1)\nobj4.header['NAXIS'] = 4\nobj4.header['NAXIS4'] = obj4.shape[3]\nobj4.header['CRVAL4'] = 0.\n\n# data \nradius = 200\na = tomograpy.fov(obj.header, radius)\ndata1 = tomograpy.centered_stack(a, 64, n_images=n/2, radius=radius,\n max_lon=np.pi, fill=0.)\ndata2 = tomograpy.centered_stack(a, 64, n_images=n/2, radius=radius,\n min_lon=np.pi / 2., max_lon=1.5 * np.pi, fill=0.)\ndata = tomograpy.solar.concatenate((data1, data2))\n\n# times\nDT = 1000.\ndt_min = 100.\ndates = np.arange(n / 2) * DT / 2.\ndates = np.concatenate(2 * (dates, ))\ndates = [time.strftime('%Y-%m-%dT%H:%M:%S', time.localtime((t))) for t in dates]\nfor i in xrange(len(data.header)):\n data.header[i]['DATE_OBS'] = dates[i]\n\ndata = tomograpy.solar.sort_data_array(data)\n\n# projection\nt = time.time()\ndata = tomograpy.projector4d(data, obj4, obstacle=\"sun\")\nprint(\"projection time : \" + str(time.time() - t))\n# backprojection\nx0 = obj4.copy()\nx0[:] = 0.\nt = time.time()\nx0 = tomograpy.backprojector4d(data, x0, obstacle=\"sun\")\nprint(\"backprojection time : \" + str(time.time() - t))\n\n# model\nkwargs = {'obj_rmin':1., #'obj_rmax':1.3,\n 'mask_negative':False, 'dt_min':100}\nP, D, obj_mask, data_mask = tomograpy.models.stsrt(data, obj, **kwargs)\n# hyperparameters\nhypers = (1e-1, 1e-1, 1e-1, 1e3)\n# test time for one projection\nb = data.ravel()\nt = time.time()\nu = P.T * b\nprint(\"time with index grouping : %f\" % ((time.time() - t)))\n# inversion\nt = time.time()\nsol = lo.acg(P, b, D, hypers, tol=1e-10, maxiter=100)\n# reshape result\nfsol = tomograpy.fa.asfitsarray(sol.reshape(obj_mask.shape), header=obj4.header)\nprint(time.time() - t)\n#fsol.tofits('stsrt_test.fits')\n", "exemples/test_siddon_simu_lo.py": "#!/usr/bin/env python\nimport time\nimport numpy as np\nimport tomograpy\nimport lo\n# object\nobj = tomograpy.centered_cubic_map(3, 32)\nobj[:] = tomograpy.phantom.shepp_logan(obj.shape)\n# data\nradius = 200.\na = tomograpy.fov(obj.header, radius)\ndata = tomograpy.centered_stack(a, 128, n_images=60, radius=radius,\n max_lon=np.pi)\n# projector\nP = tomograpy.lo(data.header, obj.header)\n# projection\nt = time.time()\ndata = tomograpy.projector(data, obj)\nprint(\"projection time : \" + str(time.time() - t))\n# data\ny = data.flatten()\n# backprojection\nt = time.time()\nx0 = P.T * y\nbpj = x0.reshape(obj.shape)\nprint(\"projection time : \" + str(time.time() - t))\n# priors\nDs = [lo.diff(obj.shape, axis=i) for i in xrange(3)]\n# inversion using scipy.sparse.linalg\nt = time.time()\nsol = lo.acg(P, y, Ds, 1e-2 * np.ones(3), maxiter=100, tol=1e-20)\nsol = sol.reshape(bpj.shape)\nprint(\"inversion time : \" + str(time.time() - t))\n", "exemples/test_siddon_simu_sun.py": "#!/usr/bin/env python\nimport time\nimport numpy as np\nimport tomograpy\n# object\nobj = tomograpy.centered_cubic_map(3, 128, fill=1.)\n# data\nradius = 200.\na = tomograpy.fov(obj.header, radius)\ndata = tomograpy.centered_stack(a, 128, n_images=17, radius=200., max_lon=np.pi)\n# projection\nt = time.time()\ndata = tomograpy.projector(data, obj, obstacle=\"sun\")\nprint(\"projection time : \" + str(time.time() - t))\n# backprojection\nobj0 = tomograpy.centered_cubic_map(3, 128, fill=0.)\nt = time.time()\nobj0 = tomograpy.backprojector(data, obj0, obstacle=\"sun\")\nprint(\"backprojection time : \" + str(time.time() - t))\n", "exemples/test_thomson_simu.py": "#!/usr/bin/env python\nimport time\nimport numpy as np\nimport tomograpy\nimport lo\n# object\nobj = tomograpy.centered_cubic_map(10, 64)\nobj[:] = tomograpy.phantom.shepp_logan(obj.shape)\n# data \nradius = 200\na = tomograpy.fov(obj, radius)\ndata = tomograpy.centered_stack(a, 128, n_images=60, radius=radius, max_lon=np.pi)\n# model\nkwargs = {\"pb\":\"pb\", \"obj_rmin\":1.5, \"data_rmin\":1.5}\nP, D, obj_mask, data_mask = tomograpy.models.thomson(data, obj, u=.5, **kwargs)\n# projection\nt = time.time()\ndata[:] = (P * obj.ravel()).reshape(data.shape)\nprint(\"projection time : \" + str(time.time() - t))\n# data\n# backprojection\nt = time.time()\nx0 = P.T * data.ravel()\nbpj = x0.reshape(obj.shape)\nprint(\"backprojection time : \" + str(time.time() - t))\n# inversion using scipy.sparse.linalg\nt = time.time()\nsol = lo.acg(P, data.ravel(), D, 1e-3 * np.ones(3), maxiter=100, tol=1e-8)\nsol = sol.reshape(obj.shape)\nprint(\"inversion time : \" + str(time.time() - t))\n"}, "files_after": {"experiments.py": "import matplotlib.pyplot as plt\nimport numpy as np\nimport pylops\n\nfrom tomograpy import project_3d, backproject_3d\n\nif __name__ == \"__main__\":\n print(\"Test started\")\n\n img_size = 50\n cube_size = 50\n x, y = np.meshgrid(np.arange(img_size, dtype=np.float32), np.arange(img_size, dtype=np.float32))\n z = np.zeros((img_size, img_size), dtype=np.float32) + 3\n densities = np.ones((cube_size, cube_size, cube_size), dtype=np.float32)\n # densities[1, 4, 1] = 100\n densities[2, 2, 2] = 5\n densities[8, 8, 2] = 8\n densities[10:30, 10:30, 0:30] = 3\n mask = np.ones((cube_size, cube_size, cube_size), dtype=bool)\n\n #b = (0.5, 0.5, 0.5)\n b = (0, 0, 0)\n #b = (1E-8, 1E-8, 1E-8)\n #b = (1, 1, 1)\n #b = (10, 10, 10)\n delta = (1, 1, 1)\n #unit_normal = (-1.0, -1E-8, -1E-8)\n #unit_normal = (1.0, 1E-8, 1E-8)\n #unit_normal = (-1, 0, 0)\n #unit_normal = (-1/np.sqrt(3), -1/np.sqrt(3), -1/np.sqrt(3))\n\n\n unit_normal = (1E-7, 1E-7, -1.0)\n path_distance = 500\n\n result = project_3d(x, y, z, densities, mask, b, delta, unit_normal, path_distance)\n # print(result)\n\n import pylops\n\n def forward(densities):\n return project_3d(x, y, z, densities.reshape((cube_size, cube_size, cube_size)).astype(np.float32),\n mask, b, delta, unit_normal, path_distance).reshape((img_size**2))\n\n def backward(image):\n return backproject_3d(x, y, z, image.reshape((img_size, img_size)).astype(np.float32),\n np.zeros_like(densities, dtype=np.float32),\n mask, b, delta, unit_normal, path_distance, True).reshape((cube_size**3))\n\n def test_forward(xarr):\n print(xarr)\n return forward(xarr)\n\n from pylops.basicoperators import FunctionOperator\n\n op = pylops.FunctionOperator(forward, backward, img_size**2, cube_size**3)\n out = op @ densities.reshape((cube_size**3))\n\n fig, ax = plt.subplots()\n ax.imshow(out.reshape((img_size, img_size)))\n fig.show()\n # print(out.shape)\n # image = 2*np.ones((5, 5), dtype=np.float32)\n # image[2, 2] = 10\n\n image = out.reshape((img_size, img_size))\n\n\n import xarray as xr\n\n da = xr.DataArray(\n data=image.reshape((img_size*img_size)),\n dims = [\"x\"],\n coords = dict(\n lon=([\"x\"], x.reshape((img_size*img_size)))\n ),\n # dims=[\"x\", \"y\"],\n # coords=dict(\n # lon=([\"x\", \"y\"], x.reshape((img_size*img_size))),\n # lat=([\"x\", \"y\"], y.reshape((img_size*img_size))),\n # ),\n attrs=dict(\n description=\"Ambient temperature.\",\n units=\"degC\",\n ),\n )\n\n\n xinv = op / image.reshape((img_size*img_size))\n\n # xinv = pylops.optimization.leastsquares.regularized_inversion(\n # op, image.reshape((img_size*img_size)), [], **dict(damp=0, iter_lim=10, show=True, atol=1E-8, btol=1E-8)\n # )[0]\n # print(xinv.reshape((10, 10, 10)))\n\n fig, axs = plt.subplots(ncols=2, nrows=3, figsize=(10, 14))\n im = axs[0, 0].imshow(densities[:, :, 2], vmin=0, vmax=3)\n axs[0, 0].set_title(\"Input density slice\")\n fig.colorbar(im)\n\n im = axs[1, 0].imshow(xinv.reshape((cube_size, cube_size, cube_size))[:, :, 2], vmin=0, vmax=3)\n axs[1, 0].set_title(\"Reconstructed density slice\")\n fig.colorbar(im)\n\n im = axs[2, 0].imshow(densities[:, :, 2] - xinv.reshape((cube_size, cube_size, cube_size))[:, :, 2], vmin=-3, vmax=3, cmap='seismic')\n axs[2, 0].set_title(\"Input - reconstruction\")\n fig.colorbar(im)\n\n im = axs[1, 1].imshow(image, vmin=0, vmax=100)\n axs[1, 1].set_title(\"Image used in reconstruction\")\n fig.colorbar(im)\n\n axs[0, 1].set_axis_off()\n axs[2, 1].set_axis_off()\n plt.show()\n # BACKPROJECT\n # image = 2*np.ones((15, 15), dtype=np.float32)\n # result = backproject_3d(x, y, z, image,\n # np.zeros_like(densities, dtype=np.float32),\n # mask, b, delta, unit_normal, path_distance, True)\n # print(\"cube\", result)\n #\n # import matplotlib as mpl\n # import matplotlib.pyplot as plt\n #\n # mpl.use('macosx')\n #\n # fig = plt.figure()\n # ax = fig.add_subplot(projection='3d')\n # x, y, z = np.where(result > 1)\n # ax.scatter(x, y, z)\n #\n # plt.show(block=True)\n\n print(\"Test ended\")", "experiments_dottest.py": "import matplotlib.pyplot as plt\nimport numpy as np\nimport pylops\nfrom datetime import datetime\n\nfrom tomograpy import project_3d, backproject_3d\nfrom pylops.basicoperators import FunctionOperator\nfrom pylops import LinearOperator, lsqr\n\n\ndef z_rotation_matrix_3d(angle):\n return np.array([[[np.cos(angle), np.sin(angle), 0],\n [-np.sin(angle), np.cos(angle), 0],\n [0, 0, 1]]])\n\n\nif __name__ == \"__main__\":\n print(\"Test started\")\n start_time = datetime.now()\n\n angles = np.linspace(0, np.pi, 14)\n\n radius = 300\n\n img_size = 20\n cube_size = 20\n densities = np.zeros((cube_size, cube_size, cube_size), dtype=np.float32)\n densities[3:-3, 3:-3, 3:-3] = 100\n densities[7:-7, 7:-7, 7:-7] = 0\n # densities = np.random.randint(0, 100, (cube_size, cube_size, cube_size)).astype(np.float32)\n # densities[5, 5, :] = 0\n\n mask = np.ones((cube_size, cube_size, cube_size), dtype=bool)\n\n b = (0, 0, 0)\n b = (-cube_size / 2, -cube_size / 2, -cube_size / 2)\n\n delta = (1.0, 1.0, 1.0)\n path_distance = 500.0\n\n norms, xs, ys, zs, ds, imgs = [], [], [], [], [], []\n for angle in angles:\n t_angle = -angle + np.pi/2\n\n img_x = np.arange(img_size) - img_size / 2\n img_y = np.zeros((img_size, img_size))\n img_z = np.arange(img_size) - img_size / 2\n img_x, img_z = np.meshgrid(img_x, img_z)\n\n img_x, img_y, img_z = img_x.flatten(), img_y.flatten(), img_z.flatten()\n\n R = z_rotation_matrix_3d(t_angle)\n coords = (R @ np.stack([img_x, img_y, img_z]))[0]\n img_x, img_y, img_z = coords[0], coords[1], coords[2]\n img_x = radius * np.cos(angle) + img_x\n img_y = radius * np.sin(angle) + img_y\n\n xx = img_x.reshape((img_size, img_size)).astype(np.float32)\n yy = -img_y.reshape((img_size, img_size)).astype(np.float32)\n zz = img_z.reshape((img_size, img_size)).astype(np.float32)\n\n v1 = np.array([xx[0, 1] - xx[0, 0], yy[0, 1] - yy[0, 0], zz[0, 1] - zz[0, 0]])\n v2 = np.array([xx[1, 0] - xx[0, 0], yy[1, 0] - yy[0, 0], zz[1, 0] - zz[0, 0]])\n v1 = v1 / np.linalg.norm(v1)\n v2 = v2 / np.linalg.norm(v2)\n normal = np.cross(v1, v2)\n normal = normal / np.linalg.norm(normal)\n\n norm = normal\n norm[norm == 0] = 1E-6\n norms.append(norm)\n print(np.rad2deg(angle), np.rad2deg(t_angle), norm)\n\n d = 500\n img = project_3d(xx, yy, zz, densities, mask, b, delta, norm, d)\n xs.append(xx)\n ys.append(yy)\n zs.append(zz)\n ds.append(d)\n imgs.append(img.astype(np.float32))\n imgs = np.array(imgs)\n\n # show\n for angle, img in zip(angles, imgs):\n fig, ax = plt.subplots()\n im = ax.imshow(img)\n fig.colorbar(im)\n fig.savefig(f\"/Users/jhughes/Desktop/projection_dots/{int(np.rad2deg(angle)):03d}.png\")\n plt.close()\n\n\n class Tomo(LinearOperator):\n def __init__(self, xs, ys, zs, norms, ds, b, delta, model_shape, mask, dtype=None):\n self.xs = xs\n self.ys = ys\n self.zs = zs\n self.norms = norms\n self.ds = ds\n self.b = b\n self.delta = delta\n self.model_shape = model_shape\n self.mask = mask\n super().__init__(dtype=np.dtype(dtype),\n dims=self.model_shape,\n dimsd=(1, self.xs[0].shape[0], self.xs[0].shape[1]))\n # dimsd=(len(self.xs), self.xs[0].shape[0], self.xs[0].shape[1]))\n #\n # def _matvec(self, densities):\n # return np.array([project_3d(x, y, z, densities.reshape(self.model_shape).astype(np.float32),\n # self.mask, self.b, self.delta, norm, d)\n # for x, y, z, norm, d in zip(self.xs, self.ys, self.zs, self.norms, self.ds)]).flatten()\n #\n # def _rmatvec(self, imgs):\n # densitiesi = np.zeros(self.model_shape, dtype=np.float32)\n # for i, img in enumerate(imgs.reshape(len(self.xs), self.xs[0].shape[0], self.xs[0].shape[1])):\n # # densitiesi += backproject_3d(self.xs[i], self.ys[i], self.zs[i], img,\n # # densitiesi,\n # # self.mask, self.b, self.delta, self.norms[i], self.ds[i], True)\n # densitiesi = backproject_3d(self.xs[i], self.ys[i], self.zs[i], img,\n # densitiesi,\n # self.mask, self.b, self.delta, self.norms[i], self.ds[i], True)\n # # return ((densitiesi - np.sum(img)) / (len(self.xs)-1)).astype(np.float32)\n # return densitiesi / (cube_size - 1) / (len(self.xs) / 2 + 1)#/ len(self.xs) #/ densitiesi.shape[0] / len(self.xs)\n # #return densitiesi.flatten().astype(np.float32)\n\n def _matvec(self, densities):\n # return np.array([project_3d(x, y, z, densities.reshape(self.model_shape).astype(np.float32),\n # self.mask, self.b, self.delta, norm, d)\n # for x, y, z, norm, d in zip(self.xs, self.ys, self.zs, self.norms, self.ds)]).flatten()\n i = 0\n return project_3d(self.xs[i], self.ys[i], self.zs[i], densities.reshape(self.model_shape).astype(np.float32), self.mask, self.b, self.delta, self.norms[i], self.ds[i]).flatten()\n\n def _rmatvec(self, imgs):\n densitiesi = np.zeros(self.model_shape, dtype=np.float32)\n for i, img in enumerate(imgs.reshape(1, self.xs[0].shape[0], self.xs[0].shape[1])):\n # densitiesi += backproject_3d(self.xs[i], self.ys[i], self.zs[i], img,\n # densitiesi,\n # self.mask, self.b, self.delta, self.norms[i], self.ds[i], True)\n # if i == 0:\n densitiesi += backproject_3d(self.xs[i], self.ys[i], self.zs[i], img,\n np.zeros_like(densitiesi).astype(np.float32),\n self.mask, self.b, self.delta, self.norms[i], self.ds[i], True)\n # return ((densitiesi - np.sum(img)) / (len(self.xs)-1)).astype(np.float32)\n #return (densitiesi / (cube_size - 1)).flatten() #/ densitiesi.shape[0] / len(self.xs)\n return densitiesi.flatten().astype(np.float32)\n\n print(len(xs))\n op = Tomo(xs, ys, zs, norms, ds, b, delta, densities.shape, mask, dtype=np.float32)\n\n proj = op @ densities.flatten()\n densities_bpj = op.H @ proj.flatten()\n proj2 = op @ densities_bpj.flatten()\n densities_bpj2 = op.H @ proj2.flatten()\n print(np.where(proj == -999))\n\n #print(np.conj(proj).T @ (op @ densities))\n\n print(\"maxs\", np.max(proj), np.max(proj2))\n print(\"pcts\", np.nanpercentile(densities, 95), np.nanpercentile(densities_bpj, 95), np.nanpercentile(densities_bpj2, 95))\n print(\"close\", np.allclose(densities_bpj, densities_bpj2))\n\n fig, axs = plt.subplots(ncols=2)\n im = axs[0].imshow(proj.reshape((img_size, img_size)), vmin=0, vmax=1300)\n fig.colorbar(im)\n im = axs[1].imshow(proj2.reshape((img_size, img_size))/ (cube_size-1))#, vmin=0, vmax=1300)\n fig.colorbar(im)\n fig.savefig(\"/Users/jhughes/Desktop/projection_dots/comparison.png\")\n\n fig, axs = plt.subplots(ncols=3)\n im = axs[0].imshow(densities.reshape((cube_size, cube_size, cube_size))[0], vmin=0, vmax=100)\n fig.colorbar(im)\n im = axs[1].imshow(densities_bpj.reshape((cube_size, cube_size, cube_size))[0])# , vmin=0, vmax=100)\n fig.colorbar(im)\n im = axs[2].imshow(densities_bpj2.reshape((cube_size, cube_size, cube_size))[0])# , vmin=0, vmax=100)\n fig.colorbar(im)\n fig.savefig(\"/Users/jhughes/Desktop/projection_dots/comparison_dense.png\")\n\n\n from pylops.utils import dottest\n _ = dottest(op, 400, 8000, atol=0.1, complexflag=0, verb=True)\n\n model = pylops.optimization.basic.lsqr(op, imgs[0].flatten(), niter=10, show=True)[0]\n #\n # model = model.reshape(densities.shape)\n #\n # limit = np.nanpercentile(model, 95)\n #\n # for i in range(cube_size):\n # fig, axs = plt.subplots(ncols=2)\n # im = axs[0].imshow(densities[:, :, i], vmin=0, vmax=150)#, vmin=0, vmax=5)\n # fig.colorbar(im)\n # im = axs[1].imshow(model[:, :, i], vmin=0, vmax=limit)\n # fig.colorbar(im)\n # fig.show()\n # fig.savefig(f\"/Users/jhughes/Desktop/projection_dots/test_{i:03d}.png\")\n", "experiments_filtered_bpj.py": "import matplotlib.pyplot as plt\nimport numpy as np\nimport pylops\nimport scipy.fftpack as fp\nfrom tomograpy import project_3d, backproject_3d\n\n\ndef z_rotation_matrix_3d(angle):\n return np.array([[[np.cos(angle), np.sin(angle), 0],\n [-np.sin(angle), np.cos(angle), 0],\n [0, 0, 1]]])\n\n\nangles = np.linspace(0, 2*np.pi, 50)\n\nradius = 500\n\nimg_size = 100\ncube_size = 100\n# x, y = np.meshgrid(np.arange(img_size, dtype=np.float32), np.arange(img_size, dtype=np.float32))\n# z = np.zeros((img_size, img_size), dtype=np.float32)\ndensities = np.zeros((cube_size, cube_size, cube_size), dtype=np.float32)\n# densities[1:30, 1:30, 1:30] = 25\n# densities[80:90, 80:90, 80:90] = 5\ndensities[10:-10, 10:-10, 10:-10] = 100\ndensities[30:-30, 30:-30, 30:-30] = 0\n\n\n# densities[2, 2, 2] = 5\n# densities[8, 8, 2] = 8\n# densities[10:30, 10:30, 0:30] = 3\nmask = np.ones((cube_size, cube_size, cube_size), dtype=bool)\n\nb = (0, 0, 0)\nb = (-cube_size / 2, -cube_size / 2, -cube_size / 2)\n\ndelta = (1.0, 1.0, 1.0)\n# unit_normal = (1E-7, 1E-7, 1.0)\npath_distance = 500.0\n\ntotal = np.zeros_like(densities)\n\nfor angle in angles:\n t_angle = -angle + np.pi / 2 # np.deg2rad(np.abs(90*np.cos(angle)))\n\n img_x = np.arange(img_size) - img_size / 2\n img_y = np.zeros((img_size, img_size))\n img_z = np.arange(img_size) - img_size / 2\n img_x, img_z = np.meshgrid(img_x, img_z)\n\n img_x, img_y, img_z = img_x.flatten(), img_y.flatten(), img_z.flatten()\n\n R = z_rotation_matrix_3d(t_angle)\n coords = (R @ np.stack([img_x, img_y, img_z]))[0]\n img_x, img_y, img_z = coords[0], coords[1], coords[2]\n img_x = radius * np.cos(angle) + img_x # - img_size/2\n img_y = radius * np.sin(angle) + img_y # - img_size/2\n\n xx = img_x.reshape((img_size, img_size)).astype(np.float32)\n yy = -img_y.reshape((img_size, img_size)).astype(np.float32)\n zz = img_z.reshape((img_size, img_size)).astype(np.float32)\n\n v1 = np.array([xx[0, 1] - xx[0, 0], yy[0, 1] - yy[0, 0], zz[0, 1] - zz[0, 0]])\n v2 = np.array([xx[1, 0] - xx[0, 0], yy[1, 0] - yy[0, 0], zz[1, 0] - zz[0, 0]])\n v1 = v1 / np.linalg.norm(v1)\n v2 = v2 / np.linalg.norm(v2)\n normal = np.cross(v1, v2)\n normal = normal / np.linalg.norm(normal)\n\n norm = normal # R @ np.array([1E-7, 1E-7, -1.0])\n norm[norm == 0] = 1E-6\n print(np.rad2deg(angle), np.rad2deg(t_angle), norm)\n\n proj = project_3d(xx, yy, zz, densities, mask, b, delta, norm, path_distance)\n\n fig, ax = plt.subplots()\n im = ax.imshow(proj, origin='lower')\n fig.colorbar(im)\n fig.savefig(f\"/Users/jhughes/Desktop/projection_bpj/proj_{angle:0.3f}.png\")\n plt.close()\n\n # FILTERING\n # (w, h) = proj.shape\n # half_w, half_h = int(w / 2), int(h / 2)\n #\n # F1 = fp.fft2(proj.astype(float))\n # F2 = fp.fftshift(F1)\n #\n # # high pass filter\n # n = 10\n # F2[half_w - n:half_w + n + 1, half_h - n:half_h + n + 1] = 0\n # proj = fp.ifft2(fp.ifftshift(F2)).real\n\n result = backproject_3d(xx, yy, zz, proj.astype(np.float32),\n np.zeros_like(densities, dtype=np.float32),\n mask, b, delta, norm, path_distance, True)\n print(result.shape)\n\n scaling = densities.shape[0]\n result = result / scaling\n\n total += result\n# ((result - np.sum(proj)) / (len(self.xs)-1)).astype(np.float32)\n#result = result - np.sum(proj)\n\n# # Scale result to make sure that fbp(A, A(x)) == x holds at least\n# # to some approximation. In limited experiments, this is true for\n# # this version of FBP up to 1%.\n# # *Note*: For some reason, we do not have to scale with respect to\n# # the pixel dimension that is orthogonal to the rotation axis (`u`\n# # or horizontal pixel dimension). Hence, we only scale with the\n# # other pixel dimension (`v` or vertical pixel dimension).\n# vg, pg = A.astra_compat_vg, A.astra_compat_pg\n#\n# pixel_height = (pg.det_size[0] / pg.det_shape[0])\n# voxel_volume = np.prod(np.array(vg.size / np.array(vg.shape)))\n# scaling = (np.pi / pg.num_angles) * pixel_height / voxel_volume\n#\n# rec *= scaling\n# pixel_height = proj.size / proj.shape[0]\n# voxel_volume = np.prod(densities.size / np.array(densities.shape))\n# scaling = (np.pi / 1) * pixel_height / voxel_volume\n\ntotal /= len(angles)\n\nfor i in range(cube_size):\n fig, axs = plt.subplots(ncols=2)\n im = axs[0].imshow(densities[i, :, :], origin='lower', vmin=0, vmax=150)\n fig.colorbar(im)\n\n im = axs[1].imshow(total[i, :, :], origin='lower')#, vmin=0, vmax=150)\n fig.colorbar(im)\n fig.savefig(f\"/Users/jhughes/Desktop/projection_bpj/{i:03d}.png\")\n plt.close()\n", "experiments_multi_view.py": "import matplotlib.pyplot as plt\nimport numpy as np\nimport pylops\nfrom datetime import datetime\n\nfrom tomograpy import project_3d, backproject_3d\nfrom pylops.basicoperators import FunctionOperator\nfrom pylops import LinearOperator, lsqr\n\n\ndef z_rotation_matrix_3d(angle):\n return np.array([[[np.cos(angle), np.sin(angle), 0],\n [-np.sin(angle), np.cos(angle), 0],\n [0, 0, 1]]])\n\n\nif __name__ == \"__main__\":\n print(\"Test started\")\n start_time = datetime.now()\n\n angles = np.linspace(0, np.pi, 14) + np.pi/60\n\n radius = 300\n\n img_size = 100\n cube_size = 100\n # x, y = np.meshgrid(np.arange(img_size, dtype=np.float32), np.arange(img_size, dtype=np.float32))\n # z = np.zeros((img_size, img_size), dtype=np.float32)\n densities = np.zeros((cube_size, cube_size, cube_size), dtype=np.float32)\n # densities[1:30, 1:30, 1:30] = 25\n # densities[80:90, 80:90, 80:90] = 5\n densities[30:-30, 30:-30, 30:-30] = 100\n densities[40:-40, 40:-40, 40:-40] = 0\n\n # densities[2, 2, 2] = 5\n # densities[8, 8, 2] = 8\n # densities[10:30, 10:30, 0:30] = 3\n mask = np.ones((cube_size, cube_size, cube_size), dtype=bool)\n\n b = (0, 0, 0)\n b = (-cube_size / 2, -cube_size / 2, -cube_size / 2)\n\n delta = (1.0, 1.0, 1.0)\n # delta = (0.5, 0.5, 0.5)\n # unit_normal = (1E-7, 1E-7, 1.0)\n path_distance = 500.0\n\n norms, xs, ys, zs, ds, imgs = [], [], [], [], [], []\n #angles = np.array([0, 30])\n for angle in angles:\n t_angle = -angle + np.pi/2 #np.deg2rad(np.abs(90*np.cos(angle)))\n\n img_x = np.arange(img_size) - img_size / 2\n img_y = np.zeros((img_size, img_size))\n img_z = np.arange(img_size) - img_size / 2\n img_x, img_z = np.meshgrid(img_x, img_z)\n\n img_x, img_y, img_z = img_x.flatten(), img_y.flatten(), img_z.flatten()\n\n R = z_rotation_matrix_3d(t_angle)\n coords = (R @ np.stack([img_x, img_y, img_z]))[0]\n img_x, img_y, img_z = coords[0], coords[1], coords[2]\n img_x = radius * np.cos(angle) + img_x # - img_size/2\n img_y = radius * np.sin(angle) + img_y # - img_size/2\n\n xx = img_x.reshape((img_size, img_size)).astype(np.float32)\n yy = -img_y.reshape((img_size, img_size)).astype(np.float32)\n zz = img_z.reshape((img_size, img_size)).astype(np.float32)\n\n v1 = np.array([xx[0, 1] - xx[0, 0], yy[0, 1] - yy[0, 0], zz[0, 1] - zz[0, 0]])\n v2 = np.array([xx[1, 0] - xx[0, 0], yy[1, 0] - yy[0, 0], zz[1, 0] - zz[0, 0]])\n v1 = v1 / np.linalg.norm(v1)\n v2 = v2 / np.linalg.norm(v2)\n normal = np.cross(v1, v2)\n normal = normal / np.linalg.norm(normal)\n\n norm = normal # R @ np.array([1E-7, 1E-7, -1.0])\n norm[norm == 0] = 1E-6\n norms.append(norm)\n print(np.rad2deg(angle), np.rad2deg(t_angle), norm)\n\n d = 500\n img = project_3d(xx, yy, zz, densities, mask, b, delta, norm, d)\n xs.append(xx)\n ys.append(yy)\n zs.append(zz)\n ds.append(d)\n imgs.append(img.astype(np.float32))\n imgs = np.array(imgs)\n\n # show\n for angle, img in zip(angles, imgs):\n fig, ax = plt.subplots()\n im = ax.imshow(img)\n fig.colorbar(im)\n fig.savefig(f\"/Users/jhughes/Desktop/projection_test/{int(np.rad2deg(angle)):03d}.png\")\n plt.close()\n #\n # model = np.zeros(densities.shape, dtype=np.float32)\n # for i, img in enumerate(imgs.reshape(len(xs), xs[0].shape[0], xs[0].shape[1])):\n # model = backproject_3d(xs[i], ys[i], zs[i], img,\n # model,\n # mask, b, delta, norms[i], ds[i], True)\n # total = np.sum(img)\n # print(total, img.shape, imgs.shape)\n # model = ((model - total) / (len(imgs) - 1)).astype(np.float32)\n\n # # # 3d plot\n # fig = plt.figure()\n # ax = fig.add_subplot(projection='3d')\n #\n # n = 100\n #\n # for x, y, z in zip(xs, ys, zs):\n # ax.scatter(x, y, z)\n #\n # # for norm, sx, sy in zip(norms, shift_xs, shift_ys):\n # # print(\"TEST\", norm)\n # # ax.plot([0+sx, 100*norm[0]+sx], [0, 100*norm[1]], [0+sy, sy+100*norm[2]])\n #\n # ax.set_xlabel('X Label')\n # ax.set_ylabel('Y Label')\n # ax.set_zlabel('Z Label')\n #\n # plt.show()\n\n\n class Tomo(LinearOperator):\n def __init__(self, xs, ys, zs, norms, ds, b, delta, model_shape, mask, dtype=None):\n self.xs = xs\n self.ys = ys\n self.zs = zs\n self.norms = norms\n self.ds = ds\n self.b = b\n self.delta = delta\n self.model_shape = model_shape\n self.mask = mask\n super().__init__(dtype=np.dtype(dtype),\n dims=self.model_shape,\n dimsd=(len(self.xs), self.xs[0].shape[0], self.xs[0].shape[1]))\n\n def _matvec(self, densities):\n return np.array([project_3d(x, y, z, densities.reshape(self.model_shape).astype(np.float32),\n self.mask, self.b, self.delta, norm, d)\n for x, y, z, norm, d in zip(self.xs, self.ys, self.zs, self.norms, self.ds)]).flatten()\n\n def _rmatvec(self, imgs):\n densitiesi = np.zeros(self.model_shape, dtype=np.float32)\n for i, img in enumerate(imgs.reshape(len(self.xs), self.xs[0].shape[0], self.xs[0].shape[1])):\n # densitiesi += backproject_3d(self.xs[i], self.ys[i], self.zs[i], img,\n # densitiesi,\n # self.mask, self.b, self.delta, self.norms[i], self.ds[i], True)\n densitiesi += backproject_3d(self.xs[i], self.ys[i], self.zs[i], img,\n np.zeros_like(densitiesi).astype(np.float32),\n self.mask, self.b, self.delta, self.norms[i], self.ds[i], True)\n # return ((densitiesi - np.sum(img)) / (len(self.xs)-1)).astype(np.float32)\n return densitiesi.flatten().astype(np.float32) #/ densitiesi.shape[0] / len(self.xs)\n #return densitiesi.flatten().astype(np.float32)\n\n print(len(xs))\n op = Tomo(xs, ys, zs, norms, ds, b, delta, densities.shape, mask, dtype=np.float32)\n\n from pylops.utils import dottest\n # # print(op.dims)\n _ = dottest(op, 140000, 1000000, atol=0.1, complexflag=0, verb=True)\n\n Dop = [\n pylops.FirstDerivative(\n (cube_size, cube_size, cube_size), axis=0, edge=False, kind=\"backward\", dtype=np.float32\n ),\n pylops.FirstDerivative(\n (cube_size, cube_size, cube_size), axis=1, edge=False, kind=\"backward\", dtype=np.float32\n ),\n pylops.FirstDerivative(\n (cube_size, cube_size, cube_size), axis=2, edge=False, kind=\"backward\", dtype=np.float32\n )\n ]\n #\n # # TV\n # mu = 1.5\n # lamda = [0.1, 0.1, 0.1]\n # niter_out = 2\n # niter_in = 1\n #\n # model = pylops.optimization.sparsity.splitbregman(\n # op,\n # imgs.ravel(),\n # Dop,\n # niter_outer=niter_out,\n # niter_inner=niter_in,\n # mu=mu,\n # epsRL1s=lamda,\n # tol=1e-4,\n # tau=1.0,\n # show=True,\n # **dict(iter_lim=5, damp=1e-4)\n # )[0]\n\n # model = op / imgs.flatten()\n # model = pylops.optimization.leastsquares.regularized_inversion(\n # op, imgs.flatten(), Dop, **dict(iter_lim=10, show=True, atol=1E-8, btol=1E-8)\n # )[0]\n #\n # model = pylops.optimization.basic.lsqr(op, imgs.flatten(), x0=np.random.rand(*densities.flatten().shape).astype(np.float32),\n # niter=100, show=True, damp=0)[0]\n model = pylops.optimization.basic.lsqr(op, imgs.flatten(), niter=10, show=True)[0]#, x0 = np.random.randint(0, 30, densities.shape))[0] # x0=densities.flatten() + 50 * np.random.rand(*densities.flatten().shape).astype(np.float32) - 25)[0]\n # niter=100, show=True, damp=0)[0]\n #model = pylops.optimization.basic.lsqr(op, imgs.flatten(), x0=densities.flatten(), niter=10, show=True)[0]\n # model = pylops.optimization.basic.lsqr(op, imgs.flatten(), niter=1, show=True)[0]\n\n # from pylops.optimization.cls_sparsity import FISTA\n #\n # fistasolver = FISTA(op)\n #\n # model = fistasolver.solve(imgs.flatten(), niter=2, show=True)[0]\n\n #model = pylops.optimization.basic.cgls(op, imgs.flatten(), niter=10, show=True)[0]\n model = model.reshape(densities.shape)\n\n limit = 150 # np.nanpercentile(model, 95)\n\n for i in range(cube_size):\n fig, axs = plt.subplots(ncols=2)\n im = axs[0].imshow(densities[:, :, i], vmin=0, vmax=150)#, vmin=0, vmax=5)\n fig.colorbar(im)\n im = axs[1].imshow(model[:, :, i], vmin=0, vmax=limit)\n fig.colorbar(im)\n fig.show()\n fig.savefig(f\"/Users/jhughes/Desktop/projection_test/test_{i:03d}.png\")\n\n # fig, axs = plt.subplots(ncols=2)\n # axs[0].imshow(densities[:, :, 2], vmin=0, vmax=10)\n # axs[1].imshow(model[:, :, 2], vmin=0, vmax=10)\n # fig.show()\n # fig.savefig(\"/Users/jhughes/Desktop/projection_test/reconstruction_0.png\")\n #\n # fig, axs = plt.subplots(ncols=2)\n # axs[0].imshow(densities[:, :, 10], vmin=0, vmax=10)\n # axs[1].imshow(model[:, :, 10], vmin=0, vmax=10)\n # fig.show()\n # fig.savefig(\"/Users/jhughes/Desktop/projection_test/reconstruction_1.png\")\n #\n #\n # fig, axs = plt.subplots(ncols=2)\n # axs[0].imshow(densities[:, :, 30], vmin=0, vmax=10)\n # axs[1].imshow(model[:, :, 30], vmin=0, vmax=10)\n # fig.show()\n # fig.savefig(\"/Users/jhughes/Desktop/projection_test/reconstruction_2.png\")\n #\n #\n # fig, axs = plt.subplots(ncols=2)\n # axs[0].imshow(densities[:, :, 40], vmin=0, vmax=10)\n # axs[1].imshow(model[:, :, 40], vmin=0, vmax=10)\n # fig.show()\n # fig.savefig(\"/Users/jhughes/Desktop/projection_test/reconstruction_3.png\")\n\n end_time = datetime.now()\n print(end_time - start_time)\n", "experiments_only_bpj.py": "import matplotlib.pyplot as plt\nimport numpy as np\nimport pylops\n\nfrom tomograpy import project_3d, backproject_3d\n\n\ndef z_rotation_matrix_3d(angle):\n return np.array([[[np.cos(angle), np.sin(angle), 0],\n [-np.sin(angle), np.cos(angle), 0],\n [0, 0, 1]]])\n\n\nangles = np.linspace(0, np.pi, 14) + np.pi/60\n\nradius = 300\n\nimg_size = 100\ncube_size = 100\n# x, y = np.meshgrid(np.arange(img_size, dtype=np.float32), np.arange(img_size, dtype=np.float32))\n# z = np.zeros((img_size, img_size), dtype=np.float32)\ndensities = np.zeros((cube_size, cube_size, cube_size), dtype=np.float32)\n# densities[1:30, 1:30, 1:30] = 25\n# densities[80:90, 80:90, 80:90] = 5\ndensities[30:-30, 30:-30, 30:-30] = 100\ndensities[40:-40, 40:-40, 40:-40] = 0\n\n\n# densities[2, 2, 2] = 5\n# densities[8, 8, 2] = 8\n# densities[10:30, 10:30, 0:30] = 3\nmask = np.ones((cube_size, cube_size, cube_size), dtype=bool)\n\nb = (0, 0, 0)\nb = (-cube_size / 2, -cube_size / 2, -cube_size / 2)\n\ndelta = (1.0, 1.0, 1.0)\n# unit_normal = (1E-7, 1E-7, 1.0)\npath_distance = 500.0\n\ntotal = np.zeros_like(densities)\n\nfor angle in angles:\n t_angle = -angle + np.pi / 2 # np.deg2rad(np.abs(90*np.cos(angle)))\n\n img_x = np.arange(img_size) - img_size / 2\n img_y = np.zeros((img_size, img_size))\n img_z = np.arange(img_size) - img_size / 2\n img_x, img_z = np.meshgrid(img_x, img_z)\n\n img_x, img_y, img_z = img_x.flatten(), img_y.flatten(), img_z.flatten()\n\n R = z_rotation_matrix_3d(t_angle)\n coords = (R @ np.stack([img_x, img_y, img_z]))[0]\n img_x, img_y, img_z = coords[0], coords[1], coords[2]\n img_x = radius * np.cos(angle) + img_x # - img_size/2\n img_y = radius * np.sin(angle) + img_y # - img_size/2\n\n xx = img_x.reshape((img_size, img_size)).astype(np.float32)\n yy = -img_y.reshape((img_size, img_size)).astype(np.float32)\n zz = img_z.reshape((img_size, img_size)).astype(np.float32)\n\n v1 = np.array([xx[0, 1] - xx[0, 0], yy[0, 1] - yy[0, 0], zz[0, 1] - zz[0, 0]])\n v2 = np.array([xx[1, 0] - xx[0, 0], yy[1, 0] - yy[0, 0], zz[1, 0] - zz[0, 0]])\n v1 = v1 / np.linalg.norm(v1)\n v2 = v2 / np.linalg.norm(v2)\n normal = np.cross(v1, v2)\n normal = normal / np.linalg.norm(normal)\n\n norm = normal # R @ np.array([1E-7, 1E-7, -1.0])\n norm[norm == 0] = 1E-6\n print(np.rad2deg(angle), np.rad2deg(t_angle), norm)\n\n proj = project_3d(xx, yy, zz, densities, mask, b, delta, norm, path_distance)\n\n fig, ax = plt.subplots()\n im = ax.imshow(proj, origin='lower')\n fig.colorbar(im)\n fig.savefig(f\"/Users/jhughes/Desktop/projection_bpj/proj_{angle:0.3f}.png\")\n plt.close()\n\n result = backproject_3d(xx, yy, zz, proj.astype(np.float32),\n np.zeros_like(densities, dtype=np.float32),\n mask, b, delta, norm, path_distance, True)\n print(result.shape)\n\n scaling = densities.shape[0]\n result = result / scaling\n\n total += result\n# ((result - np.sum(proj)) / (len(self.xs)-1)).astype(np.float32)\n#result = result - np.sum(proj)\n\n# # Scale result to make sure that fbp(A, A(x)) == x holds at least\n# # to some approximation. In limited experiments, this is true for\n# # this version of FBP up to 1%.\n# # *Note*: For some reason, we do not have to scale with respect to\n# # the pixel dimension that is orthogonal to the rotation axis (`u`\n# # or horizontal pixel dimension). Hence, we only scale with the\n# # other pixel dimension (`v` or vertical pixel dimension).\n# vg, pg = A.astra_compat_vg, A.astra_compat_pg\n#\n# pixel_height = (pg.det_size[0] / pg.det_shape[0])\n# voxel_volume = np.prod(np.array(vg.size / np.array(vg.shape)))\n# scaling = (np.pi / pg.num_angles) * pixel_height / voxel_volume\n#\n# rec *= scaling\n# pixel_height = proj.size / proj.shape[0]\n# voxel_volume = np.prod(densities.size / np.array(densities.shape))\n# scaling = (np.pi / 1) * pixel_height / voxel_volume\n\ntotal /= len(angles)\n\nfor i in range(cube_size):\n fig, axs = plt.subplots(ncols=2)\n im = axs[0].imshow(densities[i, :, :], origin='lower', vmin=0, vmax=150)\n fig.colorbar(im)\n\n im = axs[1].imshow(total[i, :, :], origin='lower', vmin=0, vmax=150)\n fig.colorbar(im)\n fig.savefig(f\"/Users/jhughes/Desktop/projection_bpj/{i:03d}.png\")\n plt.close()\n", "experiments_single_view.py": "import matplotlib.pyplot as plt\nimport numpy as np\nimport pylops\n\nfrom tomograpy import project_3d, backproject_3d\n\n\ndef z_rotation_matrix_3d(angle):\n return np.array([[[np.cos(angle), np.sin(angle), 0],\n [-np.sin(angle), np.cos(angle), 0],\n [0, 0, 1]]])\n\nangle = np.pi/2\nradius = 100\n\nimg_size = 100\ncube_size = 100\n# x, y = np.meshgrid(np.arange(img_size, dtype=np.float32), np.arange(img_size, dtype=np.float32))\n# z = np.zeros((img_size, img_size), dtype=np.float32)\ndensities = np.zeros((cube_size, cube_size, cube_size), dtype=np.float32)\ndensities[1:30, 1:30, 1:30] = 25\ndensities[80:90, 80:90, 80:90] = 5\n\n# densities[2, 2, 2] = 5\n# densities[8, 8, 2] = 8\n# densities[10:30, 10:30, 0:30] = 3\nmask = np.ones((cube_size, cube_size, cube_size), dtype=bool)\n\nb = (0, 0, 0)\nb = (-cube_size / 2, -cube_size / 2, -cube_size / 2)\n\ndelta = (1.0, 1.0, 1.0)\n#unit_normal = (1E-7, 1E-7, 1.0)\npath_distance = 500.0\n\nt_angle = -angle + np.pi / 2 # np.deg2rad(np.abs(90*np.cos(angle)))\n\nimg_x = np.arange(img_size) - img_size / 2\nimg_y = np.zeros((img_size, img_size))\nimg_z = np.arange(img_size) - img_size / 2\nimg_x, img_z = np.meshgrid(img_x, img_z)\n\nimg_x, img_y, img_z = img_x.flatten(), img_y.flatten(), img_z.flatten()\n\nR = z_rotation_matrix_3d(t_angle)\ncoords = (R @ np.stack([img_x, img_y, img_z]))[0]\nimg_x, img_y, img_z = coords[0], coords[1], coords[2]\nimg_x = radius * np.cos(angle) + img_x # - img_size/2\nimg_y = radius * np.sin(angle) + img_y # - img_size/2\n\nxx = img_x.reshape((img_size, img_size)).astype(np.float32)\nyy = -img_y.reshape((img_size, img_size)).astype(np.float32)\nzz = img_z.reshape((img_size, img_size)).astype(np.float32)\n\nv1 = np.array([xx[0, 1] - xx[0, 0], yy[0, 1] - yy[0, 0], zz[0, 1] - zz[0, 0]])\nv2 = np.array([xx[1, 0] - xx[0, 0], yy[1, 0] - yy[0, 0], zz[1, 0] - zz[0, 0]])\nv1 = v1 / np.linalg.norm(v1)\nv2 = v2 / np.linalg.norm(v2)\nnormal = np.cross(v1, v2)\nnormal = normal / np.linalg.norm(normal)\n\nnorm = normal # R @ np.array([1E-7, 1E-7, -1.0])\nnorm[norm == 0] = 1E-6\nprint(np.rad2deg(angle), np.rad2deg(t_angle), norm)\n\nproj = project_3d(xx, yy, zz, densities, mask, b, delta, norm, path_distance)\n\nfig, ax = plt.subplots()\nim = ax.imshow(proj, origin='lower')\nfig.colorbar(im)\nfig.savefig(\"/Users/jhughes/Desktop/projection_test2/proj.png\")\nplt.close()\n\nresult = backproject_3d(xx, yy, zz, proj.astype(np.float32),\n np.zeros_like(densities, dtype=np.float32),\n mask, b, delta, norm, path_distance, True)\nprint(result.shape)\n# ((result - np.sum(proj)) / (len(self.xs)-1)).astype(np.float32)\n#result = result - np.sum(proj)\n\n# # Scale result to make sure that fbp(A, A(x)) == x holds at least\n# # to some approximation. In limited experiments, this is true for\n# # this version of FBP up to 1%.\n# # *Note*: For some reason, we do not have to scale with respect to\n# # the pixel dimension that is orthogonal to the rotation axis (`u`\n# # or horizontal pixel dimension). Hence, we only scale with the\n# # other pixel dimension (`v` or vertical pixel dimension).\n# vg, pg = A.astra_compat_vg, A.astra_compat_pg\n#\n# pixel_height = (pg.det_size[0] / pg.det_shape[0])\n# voxel_volume = np.prod(np.array(vg.size / np.array(vg.shape)))\n# scaling = (np.pi / pg.num_angles) * pixel_height / voxel_volume\n#\n# rec *= scaling\n# pixel_height = proj.size / proj.shape[0]\n# voxel_volume = np.prod(densities.size / np.array(densities.shape))\n# scaling = (np.pi / 1) * pixel_height / voxel_volume\nscaling = densities.shape[0]\nresult = result / scaling\n\nfor i in range(cube_size):\n fig, axs = plt.subplots(ncols=2)\n im = axs[0].imshow(densities[i, :, :], origin='lower')\n fig.colorbar(im)\n\n im = axs[1].imshow(result[i, :, :], origin='lower')\n fig.colorbar(im)\n fig.savefig(f\"/Users/jhughes/Desktop/projection_test2/{i:03d}.png\")\n plt.close()\n", "experiments_solar.py": "import matplotlib.pyplot as plt\nimport numpy as np\nimport pylops\nfrom datetime import datetime\nfrom glob import glob\nfrom astropy.io import fits\nimport os\nfrom itertools import chain\nfrom tomograpy import project_3d, backproject_3d\nfrom pylops.basicoperators import FunctionOperator\nfrom pylops import LinearOperator, lsqr\nfrom skimage.transform import resize\n\n\ndef z_rotation_matrix_3d(angle):\n return np.array([[[np.cos(angle), np.sin(angle), 0],\n [-np.sin(angle), np.cos(angle), 0],\n [0, 0, 1]]])\n\n\nif __name__ == \"__main__\":\n print(\"Test started\")\n start_time = datetime.now()\n\n angles = list(chain(range(70, 80), range(130, 140)))\n rad_angles = np.deg2rad(angles)\n\n path = \"/Users/jhughes/Desktop/data/synthetic COMPLETE data/1 degree/\"\n filenames = glob(path + \"*.fits\")\n loaded_imgs = {np.deg2rad(angle): fits.open(os.path.join(path + f\"comp_wl_284_ang_{angle}.fits\"))[0].data for angle in angles}\n\n radius = 300\n\n img_size = 100\n cube_size = 100\n\n densities = np.zeros((cube_size, cube_size, cube_size), dtype=np.float32)\n mask = np.ones((cube_size, cube_size, cube_size), dtype=bool)\n\n b = (0, 0, 0)\n b = (-cube_size / 2, -cube_size / 2, -cube_size / 2)\n\n delta = (1.0, 1.0, 1.0)\n path_distance = 500.0\n\n norms, xs, ys, zs, ds, imgs = [], [], [], [], [], []\n #angles = np.array([0, 30])\n for angle in rad_angles:\n t_angle = -angle + np.pi/2 #np.deg2rad(np.abs(90*np.cos(angle)))\n\n img_x = np.arange(img_size) - img_size / 2\n img_y = np.zeros((img_size, img_size))\n img_z = np.arange(img_size) - img_size / 2\n img_x, img_z = np.meshgrid(img_x, img_z)\n\n img_x, img_y, img_z = img_x.flatten(), img_y.flatten(), img_z.flatten()\n\n R = z_rotation_matrix_3d(t_angle)\n coords = (R @ np.stack([img_x, img_y, img_z]))[0]\n img_x, img_y, img_z = coords[0], coords[1], coords[2]\n img_x = radius * np.cos(angle) + img_x # - img_size/2\n img_y = radius * np.sin(angle) + img_y # - img_size/2\n\n xx = img_x.reshape((img_size, img_size)).astype(np.float32)\n yy = -img_y.reshape((img_size, img_size)).astype(np.float32)\n zz = img_z.reshape((img_size, img_size)).astype(np.float32)\n\n v1 = np.array([xx[0, 1] - xx[0, 0], yy[0, 1] - yy[0, 0], zz[0, 1] - zz[0, 0]])\n v2 = np.array([xx[1, 0] - xx[0, 0], yy[1, 0] - yy[0, 0], zz[1, 0] - zz[0, 0]])\n v1 = v1 / np.linalg.norm(v1)\n v2 = v2 / np.linalg.norm(v2)\n normal = np.cross(v1, v2)\n normal = normal / np.linalg.norm(normal)\n\n norm = normal # R @ np.array([1E-7, 1E-7, -1.0])\n norm[norm == 0] = 1E-6\n norms.append(norm)\n print(np.rad2deg(angle), np.rad2deg(t_angle), norm)\n\n d = 500\n img = resize(loaded_imgs[angle], (img_size, img_size)) #project_3d(xx, yy, zz, densities, mask, b, delta, norm, d)\n xs.append(xx)\n ys.append(yy)\n zs.append(zz)\n ds.append(d)\n imgs.append(img.astype(np.float32))\n imgs = np.array(imgs)\n\n # show\n for angle, img in zip(rad_angles, imgs):\n fig, ax = plt.subplots()\n im = ax.imshow(img)\n fig.colorbar(im)\n fig.savefig(f\"/Users/jhughes/Desktop/projection_solar/{int(np.rad2deg(angle)):03d}.png\")\n plt.close()\n #\n # model = np.zeros(densities.shape, dtype=np.float32)\n # for i, img in enumerate(imgs.reshape(len(xs), xs[0].shape[0], xs[0].shape[1])):\n # model = backproject_3d(xs[i], ys[i], zs[i], img,\n # model,\n # mask, b, delta, norms[i], ds[i], True)\n # total = np.sum(img)\n # print(total, img.shape, imgs.shape)\n # model = ((model - total) / (len(imgs) - 1)).astype(np.float32)\n\n # # # 3d plot\n # fig = plt.figure()\n # ax = fig.add_subplot(projection='3d')\n #\n # n = 100\n #\n # for x, y, z in zip(xs, ys, zs):\n # ax.scatter(x, y, z)\n #\n # # for norm, sx, sy in zip(norms, shift_xs, shift_ys):\n # # print(\"TEST\", norm)\n # # ax.plot([0+sx, 100*norm[0]+sx], [0, 100*norm[1]], [0+sy, sy+100*norm[2]])\n #\n # ax.set_xlabel('X Label')\n # ax.set_ylabel('Y Label')\n # ax.set_zlabel('Z Label')\n #\n # plt.show()\n\n\n class Tomo(LinearOperator):\n def __init__(self, xs, ys, zs, norms, ds, b, delta, model_shape, mask, dtype=None):\n self.xs = xs\n self.ys = ys\n self.zs = zs\n self.norms = norms\n self.ds = ds\n self.b = b\n self.delta = delta\n self.model_shape = model_shape\n self.mask = mask\n super().__init__(dtype=np.dtype(dtype),\n dims=self.model_shape,\n dimsd=(len(self.xs), self.xs[0].shape[0], self.xs[0].shape[1]))\n\n def _matvec(self, densities):\n return np.array([project_3d(x, y, z, densities.reshape(self.model_shape).astype(np.float32),\n self.mask, self.b, self.delta, norm, d)\n for x, y, z, norm, d in zip(self.xs, self.ys, self.zs, self.norms, self.ds)]).flatten()\n\n def _rmatvec(self, imgs):\n densitiesi = np.zeros(self.model_shape, dtype=np.float32)\n for i, img in enumerate(imgs.reshape(len(self.xs), self.xs[0].shape[0], self.xs[0].shape[1])):\n # densitiesi += backproject_3d(self.xs[i], self.ys[i], self.zs[i], img,\n # densitiesi,\n # self.mask, self.b, self.delta, self.norms[i], self.ds[i], True)\n densitiesi += backproject_3d(self.xs[i], self.ys[i], self.zs[i], img,\n np.zeros_like(densitiesi).astype(np.float32),\n self.mask, self.b, self.delta, self.norms[i], self.ds[i], True)\n # return ((densitiesi - np.sum(img)) / (len(self.xs)-1)).astype(np.float32)\n return densitiesi.flatten().astype(np.float32) #/ densitiesi.shape[0] / len(self.xs)\n #return densitiesi.flatten().astype(np.float32)\n\n print(len(xs))\n op = Tomo(xs, ys, zs, norms, ds, b, delta, densities.shape, mask, dtype=np.float32)\n\n Dop = [\n pylops.FirstDerivative(\n (cube_size, cube_size, cube_size), axis=0, edge=False, kind=\"backward\", dtype=np.float32\n ),\n pylops.FirstDerivative(\n (cube_size, cube_size, cube_size), axis=1, edge=False, kind=\"backward\", dtype=np.float32\n ),\n pylops.FirstDerivative(\n (cube_size, cube_size, cube_size), axis=2, edge=False, kind=\"backward\", dtype=np.float32\n )\n ]\n #\n # # TV\n # mu = 1.5\n # lamda = [0.1, 0.1, 0.1]\n # niter_out = 2\n # niter_in = 1\n #\n # model = pylops.optimization.sparsity.splitbregman(\n # op,\n # imgs.ravel(),\n # Dop,\n # niter_outer=niter_out,\n # niter_inner=niter_in,\n # mu=mu,\n # epsRL1s=lamda,\n # tol=1e-4,\n # tau=1.0,\n # show=True,\n # **dict(iter_lim=5, damp=1e-4)\n # )[0]\n\n # model = op / imgs.flatten()\n # model = pylops.optimization.leastsquares.regularized_inversion(\n # op, imgs.flatten(), Dop, **dict(iter_lim=10, show=True, atol=1E-8, btol=1E-8)\n # )[0]\n #\n # model = pylops.optimization.basic.lsqr(op, imgs.flatten(), x0=np.random.rand(*densities.flatten().shape).astype(np.float32),\n # niter=100, show=True, damp=0)[0]\n model = pylops.optimization.basic.lsqr(op, imgs.flatten(), niter=3, show=True)[0]#, x0 = np.random.randint(0, 30, densities.shape))[0] # x0=densities.flatten() + 50 * np.random.rand(*densities.flatten().shape).astype(np.float32) - 25)[0]\n # niter=100, show=True, damp=0)[0]\n #model = pylops.optimization.basic.lsqr(op, imgs.flatten(), x0=densities.flatten(), niter=10, show=True)[0]\n # model = pylops.optimization.basic.lsqr(op, imgs.flatten(), niter=1, show=True)[0]\n\n # from pylops.optimization.cls_sparsity import FISTA\n #\n # fistasolver = FISTA(op)\n #\n # model = fistasolver.solve(imgs.flatten(), niter=2, show=True)[0]\n\n #model = pylops.optimization.basic.cgls(op, imgs.flatten(), niter=10, show=True)[0]\n model = model.reshape(densities.shape)\n\n np.save(\"/Users/jhughes/Desktop/projection_solar/cube.npy\", model)\n limit = np.nanpercentile(model, 95)\n\n for i in range(cube_size):\n fig, ax = plt.subplots()\n im = ax.imshow(model[:, :, i], vmin=0, vmax=limit)\n fig.colorbar(im)\n fig.show()\n fig.savefig(f\"/Users/jhughes/Desktop/projection_solar/test_{i:03d}.png\")\n\n reconstructions = op @ model.flatten()\n reconstructions = reconstructions.reshape((len(xs), img_size, img_size))\n\n for i, angle in enumerate(rad_angles):\n fig, axs = plt.subplots(ncols=2)\n im = axs[0].imshow(imgs[i])\n fig.colorbar(im)\n im = axs[1].imshow(reconstructions[i])\n fig.colorbar(im)\n fig.show()\n fig.savefig(f\"/Users/jhughes/Desktop/projection_solar/recon_{np.rad2deg(angle)}.png\")\n\n\n\n end_time = datetime.now()\n print(end_time - start_time)\n", "python/tomograpy/__init__.py": "from .tomograpy import *\nfrom . import third\n\n\n__doc__ = tomograpy.__doc__\nif hasattr(tomograpy, \"__all__\"):\n __all__ = tomograpy.__all__\n", "python/tomograpy/coordinates.py": "", "python/tomograpy/third.py": "import numpy as np\n\ndef print_hello(name):\n print(f\"hello {name}\")\n\n"}} -{"repo": "commandprompt/PL-php", "pr_number": 6, "title": "fix postgresql 9.4 / php 5.5 issues", "state": "open", "merged_at": null, "additions": 5, "deletions": 2, "files_changed": ["plphp.c", "plphp_io.c", "plphp_spi.c"], "files_before": {"plphp.c": "/**********************************************************************\n * plphp.c - PHP as a procedural language for PostgreSQL\n *\n * This software is copyright (c) Command Prompt Inc.\n *\n * The author hereby grants permission to use, copy, modify,\n * distribute, and license this software and its documentation for any\n * purpose, provided that existing copyright notices are retained in\n * all copies and that this notice is included verbatim in any\n * distributions. No written agreement, license, or royalty fee is\n * required for any of the authorized uses. Modifications to this\n * software may be copyrighted by their author and need not follow the\n * licensing terms described here, provided that the new terms are\n * clearly indicated on the first page of each file where they apply.\n *\n * IN NO EVENT SHALL THE AUTHOR OR DISTRIBUTORS BE LIABLE TO ANY PARTY\n * FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES\n * ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY\n * DERIVATIVES THEREOF, EVEN IF THE AUTHOR HAVE BEEN ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * THE AUTHOR AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES,\n * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND\n * NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN \"AS IS\" BASIS,\n * AND THE AUTHOR AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE\n * MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n *\n * IDENTIFICATION\n *\t\t$Id$\n *********************************************************************\n */\n\n\n/* Package configuration generated by autoconf */\n#include \"config.h\"\n\n/* First round of undefs, to eliminate collision between plphp and postgresql\n * definitions\n */\n \n#undef PACKAGE_BUGREPORT\n#undef PACKAGE_NAME\n#undef PACKAGE_STRING\n#undef PACKAGE_TARNAME\n#undef PACKAGE_VERSION\n\n/* PostgreSQL stuff */\n#include \"postgres.h\"\n#include \"access/heapam.h\"\n#include \"access/transam.h\"\n\n#include \"catalog/catversion.h\"\n#include \"catalog/pg_language.h\"\n#include \"catalog/pg_proc.h\"\n#include \"catalog/pg_type.h\"\n\n#include \"commands/trigger.h\"\n#include \"fmgr.h\"\n#include \"funcapi.h\"\t\t\t/* needed for SRF support */\n#include \"lib/stringinfo.h\"\n\n#include \"utils/array.h\"\n#include \"utils/builtins.h\"\n#include \"utils/elog.h\"\n#include \"utils/lsyscache.h\"\n#include \"utils/memutils.h\"\n#include \"utils/rel.h\"\n#include \"utils/syscache.h\"\n#include \"utils/typcache.h\"\n\n/*\n * These are defined again in php.h, so undef them to avoid some\n * cpp warnings.\n */\n#undef PACKAGE_BUGREPORT\n#undef PACKAGE_NAME\n#undef PACKAGE_STRING\n#undef PACKAGE_TARNAME\n#undef PACKAGE_VERSION\n\n/* PHP stuff */\n#include \"php.h\"\n\n#include \"php_variables.h\"\n#include \"php_globals.h\"\n#include \"zend_hash.h\"\n#include \"zend_modules.h\"\n\n#include \"php_ini.h\"\t\t\t/* needed for INI_HARDCODED */\n#include \"php_main.h\"\n\n/* Our own stuff */\n#include \"plphp_io.h\"\n#include \"plphp_spi.h\"\n\n/* system stuff */\n#if HAVE_FCNTL_H\n#include \n#endif\n#if HAVE_UNISTD_H\n#include \n#endif\n\n#define INI_HARDCODED(name,value) \\\n\t\tzend_alter_ini_entry(name, sizeof(name), value, strlen(value), \\\n\t\t\t\t\t\t\t PHP_INI_SYSTEM, PHP_INI_STAGE_ACTIVATE);\n\n/* Check for PostgreSQL version */\n#if (CATALOG_VERSION_NO >= 200709301)\n#define PG_VERSION_83_COMPAT\n#endif\n#if (CATALOG_VERSION_NO >= 200611241)\n#define PG_VERSION_82_COMPAT\n#endif\n/* We only support 8.1 and above */\n#if (CATALOG_VERSION_NO >= 200510211)\n#define PG_VERSION_81_COMPAT\n#else\n#error \"Unsupported PostgreSQL version\"\n#endif\n\n#undef DEBUG_PLPHP_MEMORY\n\n#ifdef DEBUG_PLPHP_MEMORY\n#define REPORT_PHP_MEMUSAGE(where) \\\n\telog(NOTICE, \"PHP mem usage: %s: %u\", where, AG(allocated_memory));\n#else\n#define REPORT_PHP_MEMUSAGE(a) \n#endif\n\n/* PostgreSQL starting from v 8.2 requires this define\n * for all modules.\n */\n#ifdef PG_VERSION_82_COMPAT\nPG_MODULE_MAGIC;\n#else\n/* Supress warnings on 8.1 and below */\n#define ReleaseTupleDesc(tupdesc) \n#endif\n\n/* PHP 5.2 and earlier do not contain these definitions */\n#ifndef Z_SET_ISREF_P\n#define Z_SET_ISREF_P(foo) (foo)->is_ref = 1\n#define Z_UNSET_ISREF_P(foo) (foo)->is_ref = 0\n#endif\n\n/* 8.2 compatibility */\n#ifndef TYPTYPE_PSEUDO\n#define TYPTYPE_PSEUDO 'p'\n#define TYPTYPE_COMPOSITE 'c'\n#endif\n\n/* Check the argument type to expect to accept an initial value */\n#define IS_ARGMODE_OUT(mode) ((mode) == PROARGMODE_OUT || \\\n(mode) == PROARGMODE_TABLE)\n/*\n * Return types. Why on earth is this a bitmask? Beats me.\n * We should have separate flags instead.\n */\ntypedef enum pl_type\n{\n\tPL_TUPLE = 1 << 0,\n\tPL_ARRAY = 1 << 1,\n\tPL_PSEUDO = 1 << 2\n} pl_type;\n\n/*\n * The information we cache about loaded procedures.\n *\n * \"proname\" is the name of the function, given by the user.\n *\n * fn_xmin and fn_cmin are used to know when a function has been redefined and\n * needs to be recompiled.\n *\n * trusted indicates whether the function was created with a trusted handler.\n *\n * ret_type is a weird bitmask that indicates whether this function returns a\n * tuple, an array or a pseudotype. ret_oid is the Oid of the return type.\n * retset indicates whether the function was declared to return a set.\n *\n * arg_argmode indicates whether the argument is IN, OUT or both. It follows\n * values in pg_proc.proargmodes.\n *\n * n_out_args - total number of OUT or INOUT arguments.\n * arg_out_tupdesc is a tuple descriptor of the tuple constructed for OUT args.\n *\n * XXX -- maybe this thing needs to be rethought.\n */\ntypedef struct plphp_proc_desc\n{\n\tchar\t *proname;\n\tTransactionId fn_xmin;\n\tCommandId\tfn_cmin;\n\tbool\t\ttrusted;\n\tpl_type\t\tret_type;\n\tOid\t\t\tret_oid;\t\t/* Oid of returning type */\n\tbool\t\tretset;\n\tFmgrInfo\tresult_in_func;\n\tOid\t\t\tresult_typioparam;\n\tint\t\t\tn_out_args;\n\tint\t\t\tn_total_args;\n\tint\t\t\tn_mixed_args;\n\tFmgrInfo\targ_out_func[FUNC_MAX_ARGS];\n\tOid\t\t\targ_typioparam[FUNC_MAX_ARGS];\n\tchar\t\targ_typtype[FUNC_MAX_ARGS];\n\tchar\t\targ_argmode[FUNC_MAX_ARGS];\n\tTupleDesc\targs_out_tupdesc;\n} plphp_proc_desc;\n\n/*\n * Global data\n */\nstatic bool plphp_first_call = true;\nstatic zval *plphp_proc_array = NULL;\n\n/* for PHP write/flush */\nstatic StringInfo currmsg = NULL;\n\n/*\n * for PHP <-> Postgres error message passing\n *\n * XXX -- it would be much better if we could save errcontext,\n * errhint, etc as well.\n */\nstatic char *error_msg = NULL;\n/*\n * Forward declarations\n */\nstatic void plphp_init_all(void);\nvoid\t\tplphp_init(void);\n\nPG_FUNCTION_INFO_V1(plphp_call_handler);\nDatum plphp_call_handler(PG_FUNCTION_ARGS);\n\nPG_FUNCTION_INFO_V1(plphp_validator);\nDatum plphp_validator(PG_FUNCTION_ARGS);\n\nstatic Datum plphp_trigger_handler(FunctionCallInfo fcinfo,\n\t\t\t\t\t\t\t\t plphp_proc_desc *desc\n\t\t\t\t\t\t\t\t TSRMLS_DC);\nstatic Datum plphp_func_handler(FunctionCallInfo fcinfo,\n\t\t\t\t\t\t\t plphp_proc_desc *desc\n\t\t\t\t\t\t\t\tTSRMLS_DC);\nstatic Datum plphp_srf_handler(FunctionCallInfo fcinfo,\n\t\t\t\t\t\t \t plphp_proc_desc *desc\n\t\t\t\t\t\t\t TSRMLS_DC);\n\nstatic plphp_proc_desc *plphp_compile_function(Oid fnoid, bool is_trigger TSRMLS_DC);\nstatic zval *plphp_call_php_func(plphp_proc_desc *desc,\n\t\t\t\t\t\t\t\t FunctionCallInfo fcinfo\n\t\t\t\t\t\t\t\t TSRMLS_DC);\nstatic zval *plphp_call_php_trig(plphp_proc_desc *desc,\n\t\t\t\t\t\t\t\t FunctionCallInfo fcinfo, zval *trigdata\n\t\t\t\t\t\t\t\t TSRMLS_DC);\n\nstatic void plphp_error_cb(int type, const char *filename, const uint lineno,\n\t\t\t\t\t\t\t\t const char *fmt, va_list args);\nstatic bool is_valid_php_identifier(char *name);\n\n/*\n * FIXME -- this comment is quite misleading actually, which is not surprising\n * since it came verbatim from PL/pgSQL. Rewrite memory handling here someday\n * and remove it.\n *\n * This routine is a crock, and so is everyplace that calls it. The problem\n * is that the cached form of plphp functions/queries is allocated permanently\n * (mostly via malloc()) and never released until backend exit. Subsidiary\n * data structures such as fmgr info records therefore must live forever\n * as well. A better implementation would store all this stuff in a per-\n * function memory context that could be reclaimed at need. In the meantime,\n * fmgr_info_cxt must be called specifying TopMemoryContext so that whatever\n * it might allocate, and whatever the eventual function might allocate using\n * fn_mcxt, will live forever too.\n */\nstatic void\nperm_fmgr_info(Oid functionId, FmgrInfo *finfo)\n{\n\tfmgr_info_cxt(functionId, finfo, TopMemoryContext);\n}\n\n/*\n * sapi_plphp_write\n * \t\tCalled when PHP wants to write something to stdout.\n *\n * We just save the output in a StringInfo until the next Flush call.\n */\nstatic int\nsapi_plphp_write(const char *str, uint str_length TSRMLS_DC)\n{\n\tif (currmsg == NULL)\n\t\tcurrmsg = makeStringInfo();\n\n\tappendStringInfoString(currmsg, str);\n\n\treturn str_length;\n}\n\n/*\n * sapi_plphp_flush\n * \t\tCalled when PHP wants to flush stdout.\n *\n * The stupid PHP implementation calls write and follows with a Flush right\n * away -- a good implementation would write several times and flush when the\n * message is complete. To make the output look reasonable in Postgres, we\n * skip the flushing if the accumulated message does not end in a newline.\n */\nstatic void\nsapi_plphp_flush(void *sth)\n{\n\tif (currmsg != NULL)\n\t{\n\t\tAssert(currmsg->data != NULL);\n\n\t\tif (currmsg->data[currmsg->len - 1] == '\\n')\n\t\t{\n\t\t\t/*\n\t\t\t * remove the trailing newline because elog() inserts another\n\t\t\t * one\n\t\t\t */\n\t\t\tcurrmsg->data[currmsg->len - 1] = '\\0';\n\t\t}\n\t\telog(LOG, \"%s\", currmsg->data);\n\n\t\tpfree(currmsg->data);\n\t\tpfree(currmsg);\n\t\tcurrmsg = NULL;\n\t}\n\telse\n\t\telog(LOG, \"attempting to flush a NULL message\");\n}\n\nstatic int\nsapi_plphp_send_headers(sapi_headers_struct *sapi_headers TSRMLS_DC)\n{\n\treturn 1;\n}\n\nstatic void\nphp_plphp_log_messages(char *message)\n{\n\telog(LOG, \"plphp: %s\", message);\n}\n\n\nstatic sapi_module_struct plphp_sapi_module = {\n\t\"plphp\",\t\t\t\t\t/* name */\n\t\"PL/php PostgreSQL Handler\",/* pretty name */\n\n\tNULL,\t\t\t\t\t\t/* startup */\n\tphp_module_shutdown_wrapper,/* shutdown */\n\n\tNULL,\t\t\t\t\t\t/* activate */\n\tNULL,\t\t\t\t\t\t/* deactivate */\n\n\tsapi_plphp_write,\t\t\t/* unbuffered write */\n\tsapi_plphp_flush,\t\t\t/* flush */\n\tNULL,\t\t\t\t\t\t/* stat */\n\tNULL,\t\t\t\t\t\t/* getenv */\n\n\tphp_error,\t\t\t\t\t/* sapi_error(int, const char *, ...) */\n\n\tNULL,\t\t\t\t\t\t/* header handler */\n\tsapi_plphp_send_headers,\t/* send headers */\n\tNULL,\t\t\t\t\t\t/* send header */\n\n\tNULL,\t\t\t\t\t\t/* read POST */\n\tNULL,\t\t\t\t\t\t/* read cookies */\n\n\tNULL,\t\t\t\t\t\t/* register server variables */\n\tphp_plphp_log_messages,\t\t/* log message */\n\n\tNULL,\t\t\t\t\t\t/* Block interrupts */\n\tNULL,\t\t\t\t\t\t/* Unblock interrupts */\n\tSTANDARD_SAPI_MODULE_PROPERTIES\n};\n\n/*\n * plphp_init_all()\t\t- Initialize all\n *\n * XXX This is called each time a function is invoked.\n */\nstatic void\nplphp_init_all(void)\n{\n\t/* Execute postmaster-startup safe initialization */\n\tif (plphp_first_call)\n\t\tplphp_init();\n\n\t/*\n\t * Any other initialization that must be done each time a new\n\t * backend starts -- currently none.\n\t */\n}\n\n/*\n * This function must not be static, so that it can be used in\n * preload_libraries. If it is, it will be called by postmaster;\n * otherwise it will be called by each backend the first time a\n * function is called.\n */\nvoid\nplphp_init(void)\n{\n\tTSRMLS_FETCH();\n\t/* Do initialization only once */\n\tif (!plphp_first_call)\n\t\treturn;\n\n\t/*\n\t * Need a Pg try/catch block to prevent an initialization-\n\t * failure from bringing the whole server down.\n\t */\n\tPG_TRY();\n\t{\n\t\tzend_try\n\t\t{\n\t\t\t/*\n\t\t\t * XXX This is a hack -- we are replacing the error callback in an\n\t\t\t * invasive manner that should not be expected to work on future PHP\n\t\t\t * releases.\n\t\t\t */\n\t\t\tzend_error_cb = plphp_error_cb;\n\n\t\t\t/* Omit HTML tags from output */\n\t\t\tplphp_sapi_module.phpinfo_as_text = 1;\n\t\t\tsapi_startup(&plphp_sapi_module);\n\n\t\t\tif (php_module_startup(&plphp_sapi_module, NULL, 0) == FAILURE)\n\t\t\t\telog(ERROR, \"php_module_startup call failed\");\n\n\t\t\t/* php_module_startup changed it, so put it back */\n\t\t\tzend_error_cb = plphp_error_cb;\n\n\t\t\t/*\n\t\t\t * FIXME -- Figure out what this comment is supposed to mean:\n\t\t\t *\n\t\t\t * There is no way to see if we must call zend_ini_deactivate()\n\t\t\t * since we cannot check if EG(ini_directives) has been initialised\n\t\t\t * because the executor's constructor does not initialize it.\n\t\t\t * Apart from that there seems no need for zend_ini_deactivate() yet.\n\t\t\t * So we error out.\n\t\t\t */\n\n\t\t\t/* Init procedure cache */\n\t\t\tMAKE_STD_ZVAL(plphp_proc_array);\n\t\t\tarray_init(plphp_proc_array);\n\n\t\t\tzend_register_functions(\n#if PHP_MAJOR_VERSION == 5\n\t\t\t\t\t\t\t\t\tNULL,\n#endif\n\t\t\t\t\t\t\t\t\tspi_functions, NULL,\n\t\t\t\t\t\t\t\t\tMODULE_PERSISTENT TSRMLS_CC);\n\n\t\t\tPG(during_request_startup) = true;\n\n\t\t\t/* Set some defaults */\n\t\t\tSG(options) |= SAPI_OPTION_NO_CHDIR;\n\n\t\t\t/* Hard coded defaults which cannot be overwritten in the ini file */\n\t\t\tINI_HARDCODED(\"register_argc_argv\", \"0\");\n\t\t\tINI_HARDCODED(\"html_errors\", \"0\");\n\t\t\tINI_HARDCODED(\"implicit_flush\", \"1\");\n\t\t\tINI_HARDCODED(\"max_execution_time\", \"0\");\n\t\t\tINI_HARDCODED(\"max_input_time\", \"-1\");\n\n\t\t\t/*\n\t\t\t * Set memory limit to ridiculously high value. This helps the\n\t\t\t * server not to crash, because the PHP allocator has the really\n\t\t\t * stupid idea of calling exit() if the limit is exceeded.\n\t\t\t */\n\t\t\t{\n\t\t\t\tchar\tlimit[15];\n\n\t\t\t\tsnprintf(limit, sizeof(limit), \"%d\", 1 << 30);\n\t\t\t\tINI_HARDCODED(\"memory_limit\", limit);\n\t\t\t}\n\n\t\t\t/* tell the engine we're in non-html mode */\n\t\t\tzend_uv.html_errors = false;\n\n\t\t\t/* not initialized but needed for several options */\n\t\t\tCG(in_compilation) = false;\n\n\t\t\tEG(uninitialized_zval_ptr) = NULL;\n\n\t\t\tif (php_request_startup(TSRMLS_C) == FAILURE)\n\t\t\t{\n\t\t\t\tSG(headers_sent) = 1;\n\t\t\t\tSG(request_info).no_headers = 1;\n\t\t\t\t/* Use Postgres log */\n\t\t\t\telog(ERROR, \"php_request_startup call failed\");\n\t\t\t}\n\n\t\t\tCG(interactive) = false;\n\t\t\tPG(during_request_startup) = true;\n\n\t\t\t/* Register the resource for SPI_result */\n\t\t\tSPIres_rtype = zend_register_list_destructors_ex(php_SPIresult_destroy,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t NULL, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \"SPI result\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 0);\n\n\t\t\t/* Ok, we're done */\n\t\t\tplphp_first_call = false;\n\t\t}\n\t\tzend_catch\n\t\t{\n\t\t\tplphp_first_call = true;\n\t\t\tif (error_msg)\n\t\t\t{\n\t\t\t\tchar\tstr[1024];\n\n\t\t\t\tstrncpy(str, error_msg, sizeof(str));\n\t\t\t\tpfree(error_msg);\n\t\t\t\terror_msg = NULL;\n\t\t\t\telog(ERROR, \"fatal error during PL/php initialization: %s\",\n\t\t\t\t\t str);\n\t\t\t}\n\t\t\telse\n\t\t\t\telog(ERROR, \"fatal error during PL/php initialization\");\n\t\t}\n\t\tzend_end_try();\n\t}\n\tPG_CATCH();\n\t{\n\t\tPG_RE_THROW();\n\t}\n\tPG_END_TRY();\n}\n\n/*\n * plphp_call_handler\n *\n * The visible function of the PL interpreter. The PostgreSQL function manager\n * and trigger manager call this function for execution of php procedures.\n */\nDatum\nplphp_call_handler(PG_FUNCTION_ARGS)\n{\n\tDatum\t\tretval;\n\tTSRMLS_FETCH();\n\n\t/* Initialize interpreter */\n\tplphp_init_all();\n\n\tPG_TRY();\n\t{\n\t\t/* Connect to SPI manager */\n\t\tif (SPI_connect() != SPI_OK_CONNECT)\n\t\t\tereport(ERROR,\n\t\t\t\t\t(errcode(ERRCODE_CONNECTION_FAILURE),\n\t\t\t\t\t errmsg(\"could not connect to SPI manager\")));\n\n\t\tzend_try\n\t\t{\n\t\t\tplphp_proc_desc *desc;\n\n\t\t\t/* Clean up SRF state */\n\t\t\tcurrent_fcinfo = NULL;\n\n\t\t\t/* Redirect to the appropiate handler */\n\t\t\tif (CALLED_AS_TRIGGER(fcinfo))\n\t\t\t{\n\t\t\t\tdesc = plphp_compile_function(fcinfo->flinfo->fn_oid, true TSRMLS_CC);\n\n\t\t\t\t/* Activate PHP safe mode if needed */\n\t\t\t\tPG(safe_mode) = desc->trusted;\n\n\t\t\t\tretval = plphp_trigger_handler(fcinfo, desc TSRMLS_CC);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tdesc = plphp_compile_function(fcinfo->flinfo->fn_oid, false TSRMLS_CC);\n\n\t\t\t\t/* Activate PHP safe mode if needed */\n\t\t\t\tPG(safe_mode) = desc->trusted;\n\n\t\t\t\tif (desc->retset)\n\t\t\t\t\tretval = plphp_srf_handler(fcinfo, desc TSRMLS_CC);\n\t\t\t\telse\n\t\t\t\t\tretval = plphp_func_handler(fcinfo, desc TSRMLS_CC);\n\t\t\t}\n\t\t}\n\t\tzend_catch\n\t\t{\n\t\t\tREPORT_PHP_MEMUSAGE(\"reporting error\");\n\t\t\tif (error_msg)\n\t\t\t{\n\t\t\t\tchar\tstr[1024];\n\n\t\t\t\tstrncpy(str, error_msg, sizeof(str));\n\t\t\t\tpfree(error_msg);\n\t\t\t\terror_msg = NULL;\n\t\t\t\telog(ERROR, \"%s\", str);\n\t\t\t}\n\t\t\telse\n\t\t\t\telog(ERROR, \"fatal error\");\n\n\t\t\t/* not reached, but keep compiler quiet */\n\t\t\treturn 0;\n\t\t}\n\t\tzend_end_try();\n\t}\n\tPG_CATCH();\n\t{\n\t\tPG_RE_THROW();\n\t}\n\tPG_END_TRY();\n\n\treturn retval;\n}\n\n/*\n * plphp_validator\n *\n * \t\tValidator function for checking the function's syntax at creation\n * \t\ttime\n */\nDatum\nplphp_validator(PG_FUNCTION_ARGS)\n{\n\tOid\t\t\t\tfuncoid = PG_GETARG_OID(0);\n\tForm_pg_proc\tprocForm;\n\tHeapTuple\t\tprocTup;\n\tchar\t\t\ttmpname[32];\n\tchar\t\t\tfuncname[NAMEDATALEN];\n\tchar\t\t *tmpsrc = NULL,\n\t\t\t\t *prosrc;\n\tDatum\t\t\tprosrcdatum;\n\n\n\tTSRMLS_FETCH();\n\t/* Initialize interpreter */\n\tplphp_init_all();\n\n\tPG_TRY();\n\t{\n\t\tbool\t\t\tisnull;\n\t\t/* Grab the pg_proc tuple */\n\t\tprocTup = SearchSysCache(PROCOID,\n\t\t\t\t\t\t\t\t ObjectIdGetDatum(funcoid),\n\t\t\t\t\t\t\t\t 0, 0, 0);\n\t\tif (!HeapTupleIsValid(procTup))\n\t\t\telog(ERROR, \"cache lookup failed for function %u\", funcoid);\n\n\t\tprocForm = (Form_pg_proc) GETSTRUCT(procTup);\n\n\t\t/* Get the function source code */\n\t\tprosrcdatum = SysCacheGetAttr(PROCOID,\n\t\t\t\t\t\t\t\t\t procTup,\n\t\t\t\t\t\t\t\t\t Anum_pg_proc_prosrc,\n\t\t\t\t\t\t\t\t\t &isnull);\n\t\tif (isnull)\n\t\t\telog(ERROR, \"cache lookup yielded NULL prosrc\");\n\t\tprosrc = DatumGetCString(DirectFunctionCall1(textout,\n\t\t\t\t\t\t\t\t\t\t\t\t\t prosrcdatum));\n\n\t\t/* Get the function name, for the error message */\n\t\tStrNCpy(funcname, NameStr(procForm->proname), NAMEDATALEN);\n\n\t\t/* Let go of the pg_proc tuple */\n\t\tReleaseSysCache(procTup);\n\n\t\t/* Create a PHP function creation statement */\n\t\tsnprintf(tmpname, sizeof(tmpname), \"plphp_temp_%u\", funcoid);\n\t\ttmpsrc = (char *) palloc(strlen(prosrc) +\n\t\t\t\t\t\t\t\t strlen(tmpname) +\n\t\t\t\t\t\t\t\t strlen(\"function ($args, $argc){ } \"));\n\t\tsprintf(tmpsrc, \"function %s($args, $argc){%s}\",\n\t\t\t\ttmpname, prosrc);\n\n\t\tpfree(prosrc);\n\n\t\tzend_try\n\t\t{\n\t\t\t/*\n\t\t\t * Delete the function from the PHP function table, just in case it\n\t\t\t * already existed. This is quite unlikely, but still.\n\t\t\t */\n\t\t\tzend_hash_del(CG(function_table), tmpname, strlen(tmpname) + 1);\n\n\t\t\t/*\n\t\t\t * Let the user see the fireworks. If the function doesn't validate,\n\t\t\t * the ERROR will be raised and the function will not be created.\n\t\t\t */\n\t\t\tif (zend_eval_string(tmpsrc, NULL,\n\t\t\t\t\t\t\t\t \"plphp function temp source\" TSRMLS_CC) == FAILURE)\n\t\t\t\telog(ERROR, \"function \\\"%s\\\" does not validate\", funcname);\n\n\t\t\tpfree(tmpsrc);\n\t\t\ttmpsrc = NULL;\n\n\t\t\t/* Delete the newly-created function from the PHP function table. */\n\t\t\tzend_hash_del(CG(function_table), tmpname, strlen(tmpname) + 1);\n\t\t}\n\t\tzend_catch\n\t\t{\n\t\t\tif (tmpsrc != NULL)\n\t\t\t\tpfree(tmpsrc);\n\n\t\t\tif (error_msg)\n\t\t\t{\n\t\t\t\tchar\tstr[1024];\n\n\t\t\t\tStrNCpy(str, error_msg, sizeof(str));\n\t\t\t\tpfree(error_msg);\n\t\t\t\terror_msg = NULL;\n\t\t\t\telog(ERROR, \"function \\\"%s\\\" does not validate: %s\", funcname, str);\n\t\t\t}\n\t\t\telse\n\t\t\t\telog(ERROR, \"fatal error\");\n\n\t\t\t/* not reached, but keep compiler quiet */\n\t\t\treturn 0;\n\t\t}\n\t\tzend_end_try();\n\n\t\t/* The result of a validator is ignored */\n\t\tPG_RETURN_VOID();\n\t}\n\tPG_CATCH();\n\t{\n\t\tPG_RE_THROW();\n\t}\n\tPG_END_TRY();\n}\n\n/*\n * plphp_get_function_tupdesc\n *\n * \t\tReturns a TupleDesc of the function's return type.\n */\nstatic TupleDesc\nplphp_get_function_tupdesc(Oid result_type, Node *rsinfo)\n{\n\tif (result_type == RECORDOID)\n\t{\n\t\tReturnSetInfo *rs = (ReturnSetInfo *) rsinfo;\n\t\t/* We must get the information from call context */\n\t\tif (!rsinfo || !IsA(rsinfo, ReturnSetInfo) || rs->expectedDesc == NULL)\n\t\t\tereport(ERROR,\n\t\t\t\t\t(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),\n\t\t\t\t\t errmsg(\"function returning record called in context \"\n\t\t\t\t\t\t\t\"that cannot accept type record\")));\n\t\treturn rs->expectedDesc;\n\t}\n\telse\n\t\t/* ordinary composite type */\n\t\treturn lookup_rowtype_tupdesc(result_type, -1);\n}\n\n\n/*\n * Build the $_TD array for the trigger function.\n */\nstatic zval *\nplphp_trig_build_args(FunctionCallInfo fcinfo)\n{\n\tTriggerData\t *tdata;\n\tTupleDesc\t\ttupdesc;\n\tzval\t\t *retval;\n\tint\t\t\t\ti;\n\n\tMAKE_STD_ZVAL(retval);\n\tarray_init(retval);\n\n\ttdata = (TriggerData *) fcinfo->context;\n\ttupdesc = tdata->tg_relation->rd_att;\n\n\t/* The basic variables */\n\tadd_assoc_string(retval, \"name\", tdata->tg_trigger->tgname, 1);\n add_assoc_long(retval, \"relid\", tdata->tg_relation->rd_id);\n\tadd_assoc_string(retval, \"relname\", SPI_getrelname(tdata->tg_relation), 1);\n\tadd_assoc_string(retval, \"schemaname\", SPI_getnspname(tdata->tg_relation), 1);\n\n\t/* EVENT */\n\tif (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))\n\t\tadd_assoc_string(retval, \"event\", \"INSERT\", 1);\n\telse if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))\n\t\tadd_assoc_string(retval, \"event\", \"DELETE\", 1);\n\telse if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))\n\t\tadd_assoc_string(retval, \"event\", \"UPDATE\", 1);\n\telse\n\t\telog(ERROR, \"unknown firing event for trigger function\");\n\n\t/* NEW and OLD as appropiate */\n\tif (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))\n\t{\n\t\tif (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))\n\t\t{\n\t\t\tzval\t *hashref;\n\n\t\t\thashref = plphp_build_tuple_argument(tdata->tg_trigtuple, tupdesc);\n\t\t\tadd_assoc_zval(retval, \"new\", hashref);\n\t\t}\n\t\telse if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))\n\t\t{\n\t\t\tzval\t *hashref;\n\n\t\t\thashref = plphp_build_tuple_argument(tdata->tg_trigtuple, tupdesc);\n\t\t\tadd_assoc_zval(retval, \"old\", hashref);\n\t\t}\n\t\telse if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))\n\t\t{\n\t\t\tzval\t *hashref;\n\n\t\t\thashref = plphp_build_tuple_argument(tdata->tg_newtuple, tupdesc);\n\t\t\tadd_assoc_zval(retval, \"new\", hashref);\n\n\t\t\thashref = plphp_build_tuple_argument(tdata->tg_trigtuple, tupdesc);\n\t\t\tadd_assoc_zval(retval, \"old\", hashref);\n\t\t}\n\t\telse\n\t\t\telog(ERROR, \"unknown firing event for trigger function\");\n\t}\n\n\t/* ARGC and ARGS */\n\tadd_assoc_long(retval, \"argc\", tdata->tg_trigger->tgnargs);\n\n\tif (tdata->tg_trigger->tgnargs > 0)\n\t{\n\t\tzval\t *hashref;\n\n\t\tMAKE_STD_ZVAL(hashref);\n\t\tarray_init(hashref);\n\n\t\tfor (i = 0; i < tdata->tg_trigger->tgnargs; i++)\n\t\t\tadd_index_string(hashref, i, tdata->tg_trigger->tgargs[i], 1);\n\n\t\tzend_hash_update(retval->value.ht, \"args\", strlen(\"args\") + 1,\n\t\t\t\t\t\t (void *) &hashref, sizeof(zval *), NULL);\n\t}\n\n\t/* WHEN */\n\tif (TRIGGER_FIRED_BEFORE(tdata->tg_event))\n\t\tadd_assoc_string(retval, \"when\", \"BEFORE\", 1);\n\telse if (TRIGGER_FIRED_AFTER(tdata->tg_event))\n\t\tadd_assoc_string(retval, \"when\", \"AFTER\", 1);\n\telse\n\t\telog(ERROR, \"unknown firing time for trigger function\");\n\n\t/* LEVEL */\n\tif (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))\n\t\tadd_assoc_string(retval, \"level\", \"ROW\", 1);\n\telse if (TRIGGER_FIRED_FOR_STATEMENT(tdata->tg_event))\n\t\tadd_assoc_string(retval, \"level\", \"STATEMENT\", 1);\n\telse\n\t\telog(ERROR, \"unknown firing level for trigger function\");\n\n\treturn retval;\n}\n\n/*\n * plphp_trigger_handler\n * \t\tHandler for trigger function calls\n */\nstatic Datum\nplphp_trigger_handler(FunctionCallInfo fcinfo, plphp_proc_desc *desc TSRMLS_DC)\n{\n\tDatum\t\tretval = 0;\n\tchar\t *srv;\n\tzval\t *phpret,\n\t\t\t *zTrigData;\n\tTriggerData *trigdata;\n\n\tREPORT_PHP_MEMUSAGE(\"going to build the trigger arg\");\n\n\tzTrigData = plphp_trig_build_args(fcinfo);\n\n\tREPORT_PHP_MEMUSAGE(\"going to call the trigger function\");\n\n\tphpret = plphp_call_php_trig(desc, fcinfo, zTrigData TSRMLS_CC);\n\tif (!phpret)\n\t\telog(ERROR, \"error during execution of function %s\", desc->proname);\n\n\tREPORT_PHP_MEMUSAGE(\"trigger called, going to build the return value\");\n\n\t/*\n\t * Disconnect from SPI manager and then create the return values datum (if\n\t * the input function does a palloc for it this must not be allocated in\n\t * the SPI memory context because SPI_finish would free it).\n\t */\n\tif (SPI_finish() != SPI_OK_FINISH)\n\t\tereport(ERROR,\n\t\t\t\t(errcode(ERRCODE_CONNECTION_DOES_NOT_EXIST),\n\t\t\t\t errmsg(\"could not disconnect from SPI manager\")));\n\n\ttrigdata = (TriggerData *) fcinfo->context;\n\n\tif (zTrigData->type != IS_ARRAY)\n\t\telog(ERROR, \"$_TD is not an array\");\n\t\t\t \n\t/*\n\t * In a BEFORE trigger, compute the return value. In an AFTER trigger\n\t * it'll be ignored, so don't bother.\n\t */\n\tif (TRIGGER_FIRED_BEFORE(trigdata->tg_event))\n\t{\n\t\tswitch (phpret->type)\n\t\t{\n\t\t\tcase IS_STRING:\n\t\t\t\tsrv = phpret->value.str.val;\n\t\t\t\tif (strcasecmp(srv, \"SKIP\") == 0)\n\t\t\t\t{\n\t\t\t\t\t/* do nothing */\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\telse if (strcasecmp(srv, \"MODIFY\") == 0)\n\t\t\t\t{\n\t\t\t\t\tif (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event) ||\n\t\t\t\t\t\tTRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))\n\t\t\t\t\t\tretval = PointerGetDatum(plphp_modify_tuple(zTrigData,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttrigdata));\n\t\t\t\t\telse if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))\n\t\t\t\t\t\tereport(ERROR,\n\t\t\t\t\t\t\t\t(errcode(ERRCODE_SYNTAX_ERROR),\n\t\t\t\t\t\t\t\t errmsg(\"on delete trigger can not modify the the return tuple\")));\n\t\t\t\t\telse\n\t\t\t\t\t\telog(ERROR, \"unknown event in trigger function\");\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tereport(ERROR,\n\t\t\t\t\t\t\t(errcode(ERRCODE_SYNTAX_ERROR),\n\t\t\t\t\t\t\t errmsg(\"expected trigger function to return NULL, 'SKIP' or 'MODIFY'\")));\n\t\t\t\tbreak;\n\t\t\tcase IS_NULL:\n\t\t\t\tif (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event) ||\n\t\t\t\t\tTRIGGER_FIRED_BY_DELETE(trigdata->tg_event))\n\t\t\t\t\tretval = (Datum) trigdata->tg_trigtuple;\n\t\t\t\telse if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))\n\t\t\t\t\tretval = (Datum) trigdata->tg_newtuple;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tereport(ERROR,\n\t\t\t\t\t\t(errcode(ERRCODE_SYNTAX_ERROR),\n\t\t\t\t\t\t errmsg(\"expected trigger function to return NULL, 'SKIP' or 'MODIFY'\")));\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tREPORT_PHP_MEMUSAGE(\"freeing some variables\");\n\n\tzval_dtor(zTrigData);\n\tzval_dtor(phpret);\n\n\tFREE_ZVAL(phpret);\n\tFREE_ZVAL(zTrigData);\n\n\tREPORT_PHP_MEMUSAGE(\"trigger call done\");\n\n\treturn retval;\n}\n\n/*\n * plphp_func_handler\n * \t\tHandler for regular function calls\n */\nstatic Datum\nplphp_func_handler(FunctionCallInfo fcinfo, plphp_proc_desc *desc TSRMLS_DC)\n{\n\tzval\t *phpret = NULL;\n\tDatum\t\tretval;\n\tchar\t *retvalbuffer = NULL;\n\n\t/* SRFs are handled separately */\n\tAssert(!desc->retset);\n\n\t/* Call the PHP function. */\n\tphpret = plphp_call_php_func(desc, fcinfo TSRMLS_CC);\n\tif (!phpret)\n\t\telog(ERROR, \"error during execution of function %s\", desc->proname);\n\n\tREPORT_PHP_MEMUSAGE(\"function invoked\");\n\n\t/* Basic datatype checks */\n\tif ((desc->ret_type & PL_ARRAY) && phpret->type != IS_ARRAY)\n\t\tereport(ERROR,\n\t\t\t\t(errcode(ERRCODE_DATATYPE_MISMATCH),\n\t\t\t\t errmsg(\"function declared to return array must return an array\")));\n\tif ((desc->ret_type & PL_TUPLE) && phpret->type != IS_ARRAY)\n\t\tereport(ERROR,\n\t\t\t\t(errcode(ERRCODE_DATATYPE_MISMATCH),\n\t\t\t\t errmsg(\"function declared to return tuple must return an array\")));\n\n\t/*\n\t * Disconnect from SPI manager and then create the return values datum (if\n\t * the input function does a palloc for it this must not be allocated in\n\t * the SPI memory context because SPI_finish would free it).\n\t */\n\tif (SPI_finish() != SPI_OK_FINISH)\n\t\tereport(ERROR,\n\t\t\t\t(errcode(ERRCODE_CONNECTION_DOES_NOT_EXIST),\n\t\t\t\t errmsg(\"could not disconnect from SPI manager\")));\n\tretval = (Datum) 0;\n\n\tif (desc->ret_type & PL_PSEUDO)\n\t{\n\t\tHeapTuple\tretTypeTup;\n\t\tForm_pg_type retTypeStruct;\n\n\t\tretTypeTup = SearchSysCache(TYPEOID,\n\t\t\t\t\t\t\t\t\tObjectIdGetDatum(get_fn_expr_rettype(fcinfo->flinfo)),\n\t\t\t\t\t\t\t\t\t0, 0, 0);\n\t\tretTypeStruct = (Form_pg_type) GETSTRUCT(retTypeTup);\n\t\tperm_fmgr_info(retTypeStruct->typinput, &(desc->result_in_func));\n\t\tdesc->result_typioparam = retTypeStruct->typelem;\n\t\tReleaseSysCache(retTypeTup);\n\t}\n\n\tif (phpret)\n\t{\n\t\tswitch (Z_TYPE_P(phpret))\n\t\t{\n\t\t\tcase IS_NULL:\n\t\t\t\tfcinfo->isnull = true;\n\t\t\t\tbreak;\n\t\t\tcase IS_BOOL:\n\t\t\tcase IS_DOUBLE:\n\t\t\tcase IS_LONG:\n\t\t\tcase IS_STRING:\n\t\t\t\tretvalbuffer = plphp_zval_get_cstring(phpret, false, false);\n\t\t\t\tretval = CStringGetDatum(retvalbuffer);\n\t\t\t\tbreak;\n\t\t\tcase IS_ARRAY:\n\t\t\t\tif (desc->ret_type & PL_ARRAY)\n\t\t\t\t{\n\t\t\t\t\tretvalbuffer = plphp_convert_to_pg_array(phpret);\n\t\t\t\t\tretval = CStringGetDatum(retvalbuffer);\n\t\t\t\t}\n\t\t\t\telse if (desc->ret_type & PL_TUPLE)\n\t\t\t\t{\n\t\t\t\t\tTupleDesc\ttd;\n\t\t\t\t\tHeapTuple\ttup;\n\n\t\t\t\t\tif (desc->ret_type & PL_PSEUDO)\n\t\t\t\t\t\ttd = plphp_get_function_tupdesc(desc->ret_oid,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tfcinfo->resultinfo);\n\t\t\t\t\telse\n\t\t\t\t\t\ttd = lookup_rowtype_tupdesc(desc->ret_oid, (int32) -1);\n\n\t\t\t\t\tif (!td)\n\t\t\t\t\t\telog(ERROR, \"no TupleDesc info available\");\n\n\t\t\t\t\ttup = plphp_htup_from_zval(phpret, td);\n\t\t\t\t\tretval = HeapTupleGetDatum(tup);\n\t\t\t\t\tReleaseTupleDesc(td);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\t/* FIXME -- should return the thing as a string? */\n\t\t\t\t\telog(ERROR, \"this plphp function cannot return arrays\");\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\telog(WARNING,\n\t\t\t\t\t \"plphp functions cannot return type %i\",\n\t\t\t\t\t phpret->type);\n\t\t\t\tfcinfo->isnull = true;\n\t\t\t\tbreak;\n\t\t}\n\t}\n\telse\n\t{\n\t\tfcinfo->isnull = true;\n\t\tretval = (Datum) 0;\n\t}\n\n\tif (!fcinfo->isnull && !(desc->ret_type & PL_TUPLE))\n\t{\n\t\tretval = FunctionCall3(&desc->result_in_func,\n\t\t\t\t\t\t\t PointerGetDatum(retvalbuffer),\n\t\t\t\t\t\t\t ObjectIdGetDatum(desc->result_typioparam),\n\t\t\t\t\t\t\t Int32GetDatum(-1));\n\t\tpfree(retvalbuffer);\n\t}\n\n\tREPORT_PHP_MEMUSAGE(\"finished calling user function\");\n\n\treturn retval;\n}\n\n/*\n * plphp_srf_handler\n * \t\tInvoke a SRF\n */\nstatic Datum\nplphp_srf_handler(FunctionCallInfo fcinfo, plphp_proc_desc *desc TSRMLS_DC)\n{\n\tReturnSetInfo *rsi = (ReturnSetInfo *) fcinfo->resultinfo;\n\tTupleDesc\ttupdesc;\n\tzval\t *phpret;\n\tMemoryContext\toldcxt;\n\n\tAssert(desc->retset);\n\n\tcurrent_fcinfo = fcinfo;\n\tcurrent_tuplestore = NULL;\n\n\t/* Check context before allowing the call to go through */\n\tif (!rsi || !IsA(rsi, ReturnSetInfo) ||\n\t\t(rsi->allowedModes & SFRM_Materialize) == 0 ||\n\t\trsi->expectedDesc == NULL)\n\t\tereport(ERROR,\n\t\t\t\t(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),\n\t\t\t\t errmsg(\"set-valued function called in context that \"\n\t\t\t\t\t\t\"cannot accept a set\")));\n\n\t/*\n\t * Fetch the function's tuple descriptor. This will return NULL in the\n\t * case of a scalar return type, in which case we will copy the TupleDesc\n\t * from the ReturnSetInfo.\n\t */\n\tget_call_result_type(fcinfo, NULL, &tupdesc);\n\tif (tupdesc == NULL)\n\t\ttupdesc = rsi->expectedDesc;\n\n\t/*\n\t * If the expectedDesc is NULL, bail out, because most likely it's using\n\t * IN/OUT parameters.\n\t */\n\tif (tupdesc == NULL)\n\t\tereport(ERROR,\n\t\t\t\t(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),\n\t\t\t\t errmsg(\"cannot use IN/OUT parameters in PL/php\")));\n\n\toldcxt = MemoryContextSwitchTo(rsi->econtext->ecxt_per_query_memory);\n\n\t/* This context is reset once per row in return_next */\n\tcurrent_memcxt = AllocSetContextCreate(CurTransactionContext,\n\t\t\t\t\t\t\t\t\t\t \"PL/php SRF context\",\n\t\t\t\t\t\t\t\t\t\t ALLOCSET_DEFAULT_MINSIZE,\n\t\t\t\t\t\t\t\t\t\t ALLOCSET_DEFAULT_INITSIZE,\n\t\t\t\t\t\t\t\t\t\t ALLOCSET_DEFAULT_MAXSIZE);\n\n\t/* Tuple descriptor and AttInMetadata for return_next */\n\tcurrent_tupledesc = CreateTupleDescCopy(tupdesc);\n\tcurrent_attinmeta = TupleDescGetAttInMetadata(current_tupledesc);\n\n\t/*\n\t * Call the PHP function. The user code must call return_next, which will\n\t * create and populate the tuplestore appropiately.\n\t */\n\tphpret = plphp_call_php_func(desc, fcinfo TSRMLS_CC);\n\n\t/* We don't use the return value */\n\tzval_dtor(phpret);\n\n\t/* Close the SPI connection */\n\tif (SPI_finish() != SPI_OK_FINISH)\n\t\tereport(ERROR,\n\t\t\t\t(errcode(ERRCODE_CONNECTION_DOES_NOT_EXIST),\n\t\t\t\t errmsg(\"could not disconnect from SPI manager\")));\n\n\t/* Now prepare the return values. */\n\trsi->returnMode = SFRM_Materialize;\n\n\tif (current_tuplestore)\n\t{\n\t\trsi->setResult = current_tuplestore;\n\t\trsi->setDesc = current_tupledesc;\n\t}\n\n\tMemoryContextDelete(current_memcxt);\n\tcurrent_memcxt = NULL;\n\tcurrent_tupledesc = NULL;\n\tcurrent_attinmeta = NULL;\n\n\tMemoryContextSwitchTo(oldcxt);\n\n\t/* All done */\n\treturn (Datum) 0;\n}\n\n/*\n * plphp_compile_function\n *\n * \t\tCompile (or hopefully just look up) function\n */\nstatic plphp_proc_desc *\nplphp_compile_function(Oid fnoid, bool is_trigger TSRMLS_DC)\n{\n\tHeapTuple\tprocTup;\n\tForm_pg_proc procStruct;\n\tchar\t\tinternal_proname[64];\n\tplphp_proc_desc *prodesc = NULL;\n\tint\t\t\ti;\n\tchar\t *pointer = NULL;\n\n\t/*\n\t * We'll need the pg_proc tuple in any case... \n\t */\n\tprocTup = SearchSysCache(PROCOID, ObjectIdGetDatum(fnoid), 0, 0, 0);\n\tif (!HeapTupleIsValid(procTup))\n\t\telog(ERROR, \"cache lookup failed for function %u\", fnoid);\n\tprocStruct = (Form_pg_proc) GETSTRUCT(procTup);\n\n\t/*\n\t * Build our internal procedure name from the function's Oid\n\t */\n\tif (is_trigger)\n\t\tsnprintf(internal_proname, sizeof(internal_proname),\n\t\t\t\t \"plphp_proc_%u_trigger\", fnoid);\n\telse\n\t\tsnprintf(internal_proname, sizeof(internal_proname),\n\t\t\t\t \"plphp_proc_%u\", fnoid);\n\n\t/*\n\t * Look up the internal proc name in the hashtable\n\t */\n\tpointer = plphp_zval_get_cstring(plphp_array_get_elem(plphp_proc_array,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t internal_proname),\n\t\t\t\t\t\t\t\t\t false, true);\n\tif (pointer)\n\t{\n\t\tbool uptodate;\n\t\tsscanf(pointer, \"%p\", &prodesc);\n\n#ifdef PG_VERSION_83_COMPAT\n\t\t/* PostgreSQL 8.3 doesn't allow calling GetCmin if a tuple doesn't\n\t\t * originate from the current transaction.\n\t\t */\n\t\tuptodate =\n\t\t\t(prodesc->fn_xmin == HeapTupleHeaderGetXmin(procTup->t_data) &&\n\t\t\t prodesc->fn_cmin == HeapTupleHeaderGetRawCommandId(procTup->t_data));\n\n#else\n\t\tuptodate =\n\t\t\t(prodesc->fn_xmin == HeapTupleHeaderGetXmin(procTup->t_data) &&\n\t\t\t prodesc->fn_cmin == HeapTupleHeaderGetCmin(procTup->t_data));\n\n#endif\n\n\n\t\t/* We need to delete the old entry */\n\t\tif (!uptodate)\n\t\t{\n\t\t\t/*\n\t\t\t * FIXME -- use a per-function memory context and fix this\n\t\t\t * stuff for good\n\t\t\t */\n\t\t\tfree(prodesc->proname);\n\t\t\tfree(prodesc);\n\t\t\tprodesc = NULL;\n\t\t}\n\t}\n\n\tif (prodesc == NULL)\n\t{\n\t\tHeapTuple\tlangTup;\n\t\tForm_pg_language langStruct;\n\t\tDatum\t\tprosrcdatum;\n\t\tbool\t\tisnull;\n\t\tchar\t *proc_source;\n\t\tchar\t *complete_proc_source;\n\t\tchar\t *pointer = NULL;\n\t\tchar\t *aliases = NULL;\n\t\tchar\t *out_aliases = NULL;\n\t\tchar\t *out_return_str = NULL;\n\t\tint16\ttyplen;\n\t\tchar\ttypbyval,\n\t\t\t\ttypalign,\n\t\t\t\ttyptype,\n\t\t\t\ttypdelim;\n\t\tOid\t\ttypioparam,\n\t\t\t\ttypinput,\n\t\t\t\ttypoutput;\n\t\t/*\n\t\t * Allocate a new procedure description block\n\t\t */\n\t\tprodesc = (plphp_proc_desc *) malloc(sizeof(plphp_proc_desc));\n\t\tif (!prodesc)\n\t\t\tereport(ERROR,\n\t\t\t\t\t(errcode(ERRCODE_OUT_OF_MEMORY),\n\t\t\t\t\t errmsg(\"out of memory\")));\n\n\t\tMemSet(prodesc, 0, sizeof(plphp_proc_desc));\n\t\tprodesc->proname = strdup(internal_proname);\n\t\tif (!prodesc->proname)\n\t\t{\n\t\t\tfree(prodesc);\n\t\t\tereport(ERROR,\n\t\t\t\t\t(errcode(ERRCODE_OUT_OF_MEMORY),\n\t\t\t\t\t errmsg(\"out of memory\")));\n\t\t}\n\n\t\tprodesc->fn_xmin = HeapTupleHeaderGetXmin(procTup->t_data);\n\n#ifdef PG_VERSION_83_COMPAT\n\t\t/* PostgreSQL 8.3 doesn't allow calling GetCmin if a tuple doesn't\n\t\t * originate from the current transaction.\n\t\t */\n\t\tprodesc->fn_cmin = HeapTupleHeaderGetRawCommandId(procTup->t_data);\n\n#else\n\t\tprodesc->fn_cmin = HeapTupleHeaderGetCmin(procTup->t_data);\n\n#endif\n\n\t\t/*\n\t\t * Look up the pg_language tuple by Oid\n\t\t */\n\t\tlangTup = SearchSysCache(LANGOID,\n\t\t\t\t\t\t\t\t ObjectIdGetDatum(procStruct->prolang),\n\t\t\t\t\t\t\t\t 0, 0, 0);\n\t\tif (!HeapTupleIsValid(langTup))\n\t\t{\n\t\t\tfree(prodesc->proname);\n\t\t\tfree(prodesc);\n\t\t\telog(ERROR, \"cache lookup failed for language %u\",\n\t\t\t\t\t procStruct->prolang);\n\t\t}\n\t\tlangStruct = (Form_pg_language) GETSTRUCT(langTup);\n\t\tprodesc->trusted = langStruct->lanpltrusted;\n\t\tReleaseSysCache(langTup);\n\n\t\t/*\n\t\t * Get the required information for input conversion of the return\n\t\t * value, and output conversion of the procedure's arguments.\n\t\t */\n\t\tif (!is_trigger)\n\t\t{\n\t\t\tchar **argnames;\n\t\t\tchar *argmodes;\n\t\t\tOid *argtypes;\n\t\t\tint32\talias_str_end,\n\t\t\t\t\tout_str_end;\n\n\t\t\ttyptype = get_typtype(procStruct->prorettype);\n\t\t\tget_type_io_data(procStruct->prorettype,\n\t\t\t\t\t\t\t IOFunc_input,\n\t\t\t\t\t\t\t &typlen,\n\t\t\t\t\t\t\t &typbyval,\n\t\t\t\t\t\t\t &typalign,\n\t\t\t\t\t\t\t &typdelim,\n\t\t\t\t\t\t\t &typioparam,\n\t\t\t\t\t\t\t &typinput);\n\n\t\t\t/*\n\t\t\t * Disallow pseudotype result, except:\n\t\t\t * VOID, RECORD, ANYELEMENT or ANYARRAY\n\t\t\t */\n\t\t\tif (typtype == TYPTYPE_PSEUDO)\n\t\t\t{\n\t\t\t\tif ((procStruct->prorettype == VOIDOID) ||\n\t\t\t\t\t(procStruct->prorettype == RECORDOID) ||\n\t\t\t\t\t(procStruct->prorettype == ANYELEMENTOID) ||\n\t\t\t\t\t(procStruct->prorettype == ANYARRAYOID))\n\t\t\t\t{\n\t\t\t\t\t/* okay */\n\t\t\t\t\tprodesc->ret_type |= PL_PSEUDO;\n\t\t\t\t}\n\t\t\t\telse if (procStruct->prorettype == TRIGGEROID)\n\t\t\t\t{\n\t\t\t\t\tfree(prodesc->proname);\n\t\t\t\t\tfree(prodesc);\n\t\t\t\t\tereport(ERROR,\n\t\t\t\t\t\t\t(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),\n\t\t\t\t\t\t\t errmsg(\"trigger functions may only be called \"\n\t\t\t\t\t\t\t\t\t\"as triggers\")));\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tfree(prodesc->proname);\n\t\t\t\t\tfree(prodesc);\n\t\t\t\t\tereport(ERROR,\n\t\t\t\t\t\t\t(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),\n\t\t\t\t\t\t\t errmsg(\"plphp functions cannot return type %s\",\n\t\t\t\t\t\t\t\t\tformat_type_be(procStruct->prorettype))));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tprodesc->ret_oid = procStruct->prorettype;\n\t\t\tprodesc->retset = procStruct->proretset;\n\n\t\t\tif (typtype == TYPTYPE_COMPOSITE ||\n\t\t\t\tprocStruct->prorettype == RECORDOID)\n\t\t\t{\n\t\t\t\tprodesc->ret_type |= PL_TUPLE;\n\t\t\t}\n\n\t\t\tif (procStruct->prorettype == ANYARRAYOID)\n\t\t\t\tprodesc->ret_type |= PL_ARRAY;\n\t\t\telse\n\t\t\t{\n\t\t\t\t/* function returns a normal (declared) array */\n\t\t\t\tif (typlen == -1 && get_element_type(procStruct->prorettype))\n\t\t\t\t\tprodesc->ret_type |= PL_ARRAY;\n\t\t\t}\n\n\t\t\tperm_fmgr_info(typinput, &(prodesc->result_in_func));\n\t\t\tprodesc->result_typioparam = typioparam;\n\n\t\t\t/* Deal with named arguments, OUT, IN/OUT and TABLE arguments */\n\n\t\t\tprodesc->n_total_args = get_func_arg_info(procTup, &argtypes, \n\t\t\t\t\t\t\t\t\t\t\t \t\t &argnames, &argmodes);\n\t\t\tprodesc->n_out_args = 0;\n\t\t\tprodesc->n_mixed_args = 0;\n\t\t\t\n\t\t\tprodesc->args_out_tupdesc = NULL;\n\t\t\tout_return_str = NULL;\n\t\t\talias_str_end = out_str_end = 0;\n\n\t\t\t/* Count the number of OUT arguments. Need to do this out of the\n\t\t\t * main loop, to correctly determine the object to return for OUT args\n\t\t */\n\t\t\tif (argmodes)\n\t\t\t\tfor (i = 0; i < prodesc->n_total_args; i++)\n\t\t\t\t{\n\t\t\t\t\tswitch(argmodes[i])\n\t\t\t\t\t{\n\t\t\t\t\t\tcase PROARGMODE_OUT: \n\t\t\t\t\t\t\tprodesc->n_out_args++;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase PROARGMODE_INOUT: \n\t\t\t\t\t\t\tprodesc->n_mixed_args++;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase PROARGMODE_IN:\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase PROARGMODE_TABLE:\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase PROARGMODE_VARIADIC:\n\t\t\t\t\t\t\telog(ERROR, \"VARIADIC arguments are not supported\");\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\telog(ERROR, \"Unsupported type %c for argument no %d\",\n\t\t\t\t\t\t\t\t argmodes[i], i);\n\t\t\t\t\t}\t\t\t\t\t\n\t\t\t\t\tprodesc->arg_argmode[i] = argmodes[i];\n\t\t\t\t}\n\t\t\telse\n\t\t\t\tMemSet(prodesc->arg_argmode, PROARGMODE_IN,\n\t\t\t\t \t prodesc->n_total_args);\n\n\t\t\t/* Allocate memory for argument names unless all of them are OUT*/\n\t\t\tif (argnames && prodesc->n_total_args > 0)\n\t\t\t\taliases = palloc((NAMEDATALEN + 32) * prodesc->n_total_args);\n\t\t\t\n\t\t\t/* Main argument processing loop. */\n\t\t\tfor (i = 0; i < prodesc->n_total_args; i++)\n\t\t\t{\n\t\t\t\tprodesc->arg_typtype[i] = get_typtype(argtypes[i]);\n\t\t\t\tif (prodesc->arg_typtype[i] != TYPTYPE_COMPOSITE)\n\t\t\t\t{\t\t\t\t\t\t\t\n\t\t\t\t\tget_type_io_data(argtypes[i],\n\t\t\t\t\t\t\t\t\t IOFunc_output,\n\t\t\t\t\t\t\t\t\t &typlen,\n\t\t\t\t\t\t\t\t\t &typbyval,\n\t\t\t\t\t\t\t\t\t &typalign,\n\t\t\t\t\t\t\t\t\t &typdelim,\n\t\t\t\t\t\t\t\t\t &typioparam,\n\t\t\t\t\t\t\t\t\t &typoutput);\n\t\t\t\t\tperm_fmgr_info(typoutput, &(prodesc->arg_out_func[i]));\n\t\t\t\t\tprodesc->arg_typioparam[i] = typioparam;\n\t\t\t\t}\n\t\t\t\tif (aliases && argnames[i][0] != '\\0')\n\t\t\t\t{\n\t\t\t\t\tif (!is_valid_php_identifier(argnames[i]))\n\t\t\t\t\t\telog(ERROR, \"\\\"%s\\\" can not be used as a PHP variable name\",\n\t\t\t\t\t\t\t argnames[i]);\n\t\t\t\t\t/* Deal with argument name */\n\t\t\t\t\talias_str_end += snprintf(aliases + alias_str_end,\n\t\t\t\t\t\t\t\t\t\t \t NAMEDATALEN + 32,\n\t\t\t\t\t\t\t\t \t\t \t \" $%s = &$args[%d];\", \n\t\t\t\t\t\t\t\t\t\t\t argnames[i], i);\n\t\t\t\t}\n\t\t\t\tif ((prodesc->arg_argmode[i] == PROARGMODE_OUT ||\n\t\t\t\t\t prodesc->arg_argmode[i] == PROARGMODE_INOUT) && !prodesc->retset)\n\t\t\t\t{\n\t\t\t\t\t/* Initialiazation for OUT arguments aliases */\n\t\t\t\t\tif (!out_return_str)\n\t\t\t\t\t{\n\t\t\t\t\t\t/* Generate return statment for a single OUT argument */\n\t\t\t\t\t\tout_return_str = palloc(NAMEDATALEN + 32);\n\t\t\t\t\t\tif (prodesc->n_out_args + prodesc->n_mixed_args == 1)\n\t\t\t\t\t\t\tsnprintf(out_return_str, NAMEDATALEN + 32,\n\t\t\t\t\t\t\t\t\t \"return $args[%d];\", i);\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t/* PL/PHP deals with multiple OUT arguments by\n\t\t\t\t\t\t\t * internally creating an array of references to them.\n\t\t\t\t\t\t\t * E.g. out_fn(a out integer, b out integer )\n\t\t\t\t\t\t\t * translates into:\n\t\t\t\t\t\t\t * $_plphp_ret_out_fn_1234=array(a => $&a,b => $&b);\n\t\t\t\t\t\t\t */\n\t\t\t\t\t\t\tchar plphp_ret_array_name[NAMEDATALEN + 16];\n\n\t\t\t\t\t\t\tint array_namelen = snprintf(plphp_ret_array_name,\n\t\t\t\t\t\t\t \t\t\t\t\t\t \t NAMEDATALEN + 16,\n\t\t\t\t\t\t\t\t\t \t\t\t\t \t \"_plphp_ret_%s\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t \t internal_proname);\n\n\t\t\t\t\t\t\tsnprintf(out_return_str, array_namelen + 16,\n\t\t\t\t\t\t\t\t\t\"return $%s;\", plphp_ret_array_name);\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t/* 2 NAMEDATALEN for argument names, additional\n\t\t\t\t\t\t\t * 16 bytes per each argument for assignment string,\n\t\t\t\t\t\t\t * additional 16 bytes for the 'array' prefix string.\n\t\t\t\t\t\t\t */\t\t\n\t\t\t\t\t\t\tout_aliases = palloc(array_namelen +\n\t\t\t\t\t\t\t\t\t\t\t\t (prodesc->n_out_args + \n\t\t\t\t\t\t\t\t\t\t\t\t prodesc->n_mixed_args) *\n\t\t\t\t\t\t\t\t\t\t\t\t (2*NAMEDATALEN + 16) + 16);\n\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tout_str_end = snprintf(out_aliases,\n\t\t\t\t\t\t\t \t\t\t\t\t array_namelen +\n\t\t\t\t\t\t\t\t\t\t\t\t (2 * NAMEDATALEN + 16) + 16,\n\t\t\t\t\t\t\t\t\t\t\t\t \"$%s = array(&$args[%d]\", \n\t\t\t\t\t\t\t\t\t\t\t\t plphp_ret_array_name, i);\n\t\t\t\t\t\t\t\t\t\t\t\t \n\t\t\t\t\t\t}\n\t\t\t\t\t} \n\t\t\t\t\telse if (out_aliases)\n\t\t\t\t\t{\n\t\t\t\t\t /* Add new elements to the array of aliases for OUT args */\n\t\t\t\t\t\tAssert(prodesc->n_out_args + prodesc->n_mixed_args > 1);\n\t\t\t\t\t\tout_str_end += snprintf(out_aliases+out_str_end,\n\t\t\t\t\t\t\t\t\t\t\t\t2 * NAMEDATALEN + 16,\n\t\t\t\t\t\t\t\t\t\t\t\t\",&$args[%d]\", i);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (aliases)\n\t\t\t\tstrcat(aliases, \" \");\n\t\t\tif (out_aliases)\n\t\t\t\tstrcat(out_aliases, \")\");\n\t\t}\n\n\t\t/*\n\t\t * Create the text of the PHP function. We do not use the same\n\t\t * function name, because that would prevent function overloading.\n\t\t * Sadly this also prevents PL/php functions from calling each other\n\t\t * easily.\n\t\t */\n\t\tprosrcdatum = SysCacheGetAttr(PROCOID, procTup,\n\t\t\t\t\t\t\t\t\t Anum_pg_proc_prosrc, &isnull);\n\t\tif (isnull)\n\t\t\telog(ERROR, \"cache lookup yielded NULL prosrc\");\n\n\t\tproc_source = DatumGetCString(DirectFunctionCall1(textout,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t prosrcdatum));\n\n\t\t/* Create the procedure in the interpreter */\n\t\tcomplete_proc_source =\n\t\t\t(char *) palloc(strlen(proc_source) +\n\t\t\t\t\t\t\tstrlen(internal_proname) +\n\t\t\t\t\t\t\t(aliases ? strlen(aliases) : 0) + \n\t\t\t\t\t\t\t(out_aliases ? strlen(out_aliases) : 0) +\n\t\t\t\t\t\t\tstrlen(\"function ($args, $argc){ } \") + 32 +\n\t\t\t\t\t\t\t(out_return_str ? strlen(out_return_str) : 0));\n\n\t\t/* XXX Is this usage of sprintf safe? */\n\t\tif (is_trigger)\n\t\t\tsprintf(complete_proc_source, \"function %s($_TD){%s}\",\n\t\t\t\t\tinternal_proname, proc_source);\n\t\telse\n\t\t\tsprintf(complete_proc_source, \n\t\t\t\t\t\"function %s($args, $argc){%s %s;%s; %s}\",\n\t\t\t\t\tinternal_proname, \n\t\t\t\t\taliases ? aliases : \"\",\n\t\t\t\t\tout_aliases ? out_aliases : \"\",\n\t\t\t\t\tproc_source, \n\t\t\t\t\tout_return_str? out_return_str : \"\");\n\t\t\t\t\t\n\t\telog(LOG, \"complete_proc_source = %s\",\n\t\t\t\t \t complete_proc_source);\n\t\t\t\t\n\t\tzend_hash_del(CG(function_table), prodesc->proname,\n\t\t\t\t\t strlen(prodesc->proname) + 1);\n\n\t\tpointer = (char *) palloc(64);\n\t\tsprintf(pointer, \"%p\", (void *) prodesc);\n\t\tadd_assoc_string(plphp_proc_array, internal_proname,\n\t\t\t\t\t\t (char *) pointer, 1);\n\n\t\tif (zend_eval_string(complete_proc_source, NULL,\n\t\t\t\t\t\t\t \"plphp function source\" TSRMLS_CC) == FAILURE)\n\t\t{\n\t\t\t/* the next compilation will blow it up */\n\t\t\tprodesc->fn_xmin = InvalidTransactionId;\n\t\t\telog(ERROR, \"unable to compile function \\\"%s\\\"\",\n\t\t\t\t\t prodesc->proname);\n\t\t}\n\n\t\tif (aliases)\n\t\t\tpfree(aliases);\n\t\tif (out_aliases)\n\t\t\tpfree(out_aliases);\n\t\tif (out_return_str)\n\t\t\tpfree(out_return_str);\n\t\tpfree(complete_proc_source);\n\t}\n\n\tReleaseSysCache(procTup);\n\n\treturn prodesc;\n}\n\n/*\n * plphp_func_build_args\n * \t\tBuild a PHP array representing the arguments to the function\n */\nstatic zval *\nplphp_func_build_args(plphp_proc_desc *desc, FunctionCallInfo fcinfo TSRMLS_DC)\n{\n\tzval\t *retval;\n\tint\t\t\ti,j;\n\n\tMAKE_STD_ZVAL(retval);\n\tarray_init(retval);\n\n\t/* \n\t * The first var iterates over every argument, the second one - over the \n\t * IN or INOUT ones only\n\t */\n\tfor (i = 0, j = 0; i < desc->n_total_args; \n\t\t (j = IS_ARGMODE_OUT(desc->arg_argmode[i]) ? j : j + 1), i++)\n\t{\n\t\t/* Assing NULLs to OUT or TABLE arguments initially */\n\t\tif (IS_ARGMODE_OUT(desc->arg_argmode[i]))\n\t\t{\n\t\t\tadd_next_index_unset(retval);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (desc->arg_typtype[i] == TYPTYPE_PSEUDO)\n\t\t{\n\t\t\tHeapTuple\ttypeTup;\n\t\t\tForm_pg_type typeStruct;\n\n\t\t\ttypeTup = SearchSysCache(TYPEOID,\n\t\t\t\t\t\t\t\t\t ObjectIdGetDatum(get_fn_expr_argtype\n\t\t\t\t\t\t\t\t\t\t\t\t\t (fcinfo->flinfo, j)),\n\t\t\t\t\t\t\t\t\t 0, 0, 0);\n\t\t\ttypeStruct = (Form_pg_type) GETSTRUCT(typeTup);\n\t\t\tperm_fmgr_info(typeStruct->typoutput,\n\t\t\t\t\t\t &(desc->arg_out_func[i]));\n\t\t\tdesc->arg_typioparam[i] = typeStruct->typelem;\n\t\t\tReleaseSysCache(typeTup);\n\t\t}\n\n\t\tif (desc->arg_typtype[i] == TYPTYPE_COMPOSITE)\n\t\t{\n\t\t\tif (fcinfo->argnull[j])\n\t\t\t\tadd_next_index_unset(retval);\n\t\t\telse\n\t\t\t{\n\t\t\t\tHeapTupleHeader\ttd;\n\t\t\t\tOid\t\t\t\ttupType;\n\t\t\t\tint32\t\t\ttupTypmod;\n\t\t\t\tTupleDesc\t\ttupdesc;\n\t\t\t\tHeapTupleData\ttmptup;\n\t\t\t\tzval\t\t *hashref;\n\n\t\t\t\ttd = DatumGetHeapTupleHeader(fcinfo->arg[j]);\n\n\t\t\t\t/* Build a temporary HeapTuple control structure */\n\t\t\t\ttmptup.t_len = HeapTupleHeaderGetDatumLength(td);\n\t\t\t\ttmptup.t_data = DatumGetHeapTupleHeader(fcinfo->arg[j]);\n\n\t\t\t\t/* Extract rowtype info and find a tupdesc */\n\t\t\t\ttupType = HeapTupleHeaderGetTypeId(tmptup.t_data);\n\t\t\t\ttupTypmod = HeapTupleHeaderGetTypMod(tmptup.t_data);\n\t\t\t\ttupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);\n\n\t\t\t\t/* Build the PHP hash */\n\t\t\t\thashref = plphp_build_tuple_argument(&tmptup, tupdesc);\n\t\t\t\tzend_hash_next_index_insert(retval->value.ht,\n\t\t\t\t\t\t\t\t\t\t\t(void *) &hashref,\n\t\t\t\t\t\t\t\t\t\t\tsizeof(zval *), NULL);\n\t\t\t\t/* Finally release the acquired tupledesc */\n\t\t\t\tReleaseTupleDesc(tupdesc);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (fcinfo->argnull[j])\n\t\t\t\tadd_next_index_unset(retval);\n\t\t\telse\n\t\t\t{\n\t\t\t\tchar\t *tmp;\n\n\t\t\t\t/*\n\t\t\t\t * TODO room for improvement here: instead of going through the\n\t\t\t\t * output function, figure out if we can just use the native\n\t\t\t\t * representation to pass to PHP.\n\t\t\t\t */\n\n\t\t\t\ttmp =\n\t\t\t\t\tDatumGetCString(FunctionCall3\n\t\t\t\t\t\t\t\t\t(&(desc->arg_out_func[i]),\n\t\t\t\t\t\t\t\t\t fcinfo->arg[j],\n\t\t\t\t\t\t\t\t\t ObjectIdGetDatum(desc->arg_typioparam[i]),\n\t\t\t\t\t\t\t\t\t Int32GetDatum(-1)));\n\t\t\t\t/*\n\t\t\t\t * FIXME -- this is bogus. Not every value starting with { is\n\t\t\t\t * an array. Figure out a better method for detecting arrays.\n\t\t\t\t */\n\t\t\t\tif (tmp[0] == '{')\n\t\t\t\t{\n\t\t\t\t\tzval\t *hashref;\n\n\t\t\t\t\thashref = plphp_convert_from_pg_array(tmp TSRMLS_CC);\n\t\t\t\t\tzend_hash_next_index_insert(retval->value.ht,\n\t\t\t\t\t\t\t\t\t\t\t\t(void *) &hashref,\n\t\t\t\t\t\t\t\t\t\t\t\tsizeof(zval *), NULL);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tadd_next_index_string(retval, tmp, 1);\n\n\t\t\t\t/*\n\t\t\t\t * FIXME - figure out which parameters are passed by\n\t\t\t\t * reference and need freeing\n\t\t\t\t */\n\t\t\t\t/* pfree(tmp); */\n\t\t\t}\n\t\t}\n\t}\n\n\treturn retval;\n}\n\n/*\n * plphp_call_php_func\n * \t\tBuild the function argument array and call the PHP function.\n *\n * We use a private PHP symbol table, so that we can easily destroy everything\n * used during the execution of the function. We use it to collect the\n * arguments' zvals as well. We exclude the return value, because it will be\n * used by the caller -- it must be freed there!\n */\nstatic zval *\nplphp_call_php_func(plphp_proc_desc *desc, FunctionCallInfo fcinfo TSRMLS_DC)\n{\n\tzval\t *retval;\n\tzval\t *args;\n\tzval\t *argc;\n\tzval\t *funcname;\n\tzval\t **params[2];\n\tchar\t\tcall[64];\n\tHashTable *orig_symbol_table;\n\tHashTable *symbol_table;\n\n\tREPORT_PHP_MEMUSAGE(\"going to build function args\");\n\n\tALLOC_HASHTABLE(symbol_table);\n\tzend_hash_init(symbol_table, 0, NULL, ZVAL_PTR_DTOR, 0);\n\n\t/*\n\t * Build the function arguments. Save a pointer to each new zval in our\n\t * private symbol table, so that we can clean up easily later.\n\t */\n\targs = plphp_func_build_args(desc, fcinfo TSRMLS_CC);\n\tzend_hash_update(symbol_table, \"args\", strlen(\"args\") + 1,\n\t\t\t\t\t (void *) &args, sizeof(zval *), NULL);\n\n\tREPORT_PHP_MEMUSAGE(\"args built. Now the rest ...\");\n\n\tMAKE_STD_ZVAL(argc);\n\tZVAL_LONG(argc, desc->n_total_args);\n\tzend_hash_update(symbol_table, \"argc\", strlen(\"argc\") + 1,\n\t\t\t\t\t (void *) &argc, sizeof(zval *), NULL);\n\n\tparams[0] = &args;\n\tparams[1] = &argc;\n\n\t/* Build the internal function name, and save for later cleaning */\n\tsprintf(call, \"plphp_proc_%u\", fcinfo->flinfo->fn_oid);\n\tMAKE_STD_ZVAL(funcname);\n\tZVAL_STRING(funcname, call, 1);\n\tzend_hash_update(symbol_table, \"funcname\", strlen(\"funcname\") + 1,\n\t\t\t\t\t (void *) &funcname, sizeof(zval *), NULL);\n\n\tREPORT_PHP_MEMUSAGE(\"going to call the function\");\n\n\torig_symbol_table = EG(active_symbol_table);\n\tEG(active_symbol_table) = symbol_table;\n\n\tsaved_symbol_table = EG(active_symbol_table);\n\n\t/* XXX: why no_separation param is 1 is this call ? */\n\tif (call_user_function_ex(CG(function_table), NULL, funcname, &retval,\n\t\t\t\t\t\t\t 2, params, 1, symbol_table TSRMLS_CC) == FAILURE)\n\t\telog(ERROR, \"could not call function \\\"%s\\\"\", call);\n\n\tREPORT_PHP_MEMUSAGE(\"going to free some vars\");\n\n\tsaved_symbol_table = NULL;\n\n\t/* Return to the original symbol table, and clean our private one */\n\tEG(active_symbol_table) = orig_symbol_table;\n\tzend_hash_clean(symbol_table);\n\n\tREPORT_PHP_MEMUSAGE(\"function call done\");\n\n\treturn retval;\n}\n\n/*\n * plphp_call_php_trig\n * \t\tBuild trigger argument array and call the PHP function as a\n * \t\ttrigger.\n *\n * Note we don't need to change the symbol table here like we do in\n * plphp_call_php_func, because we do manual cleaning of each zval used.\n */\nstatic zval *\nplphp_call_php_trig(plphp_proc_desc *desc, FunctionCallInfo fcinfo,\n\t\t\t\t\tzval *trigdata TSRMLS_DC)\n{\n\tzval\t *retval;\n\tzval\t *funcname;\n\tchar\t\tcall[64];\n\tzval\t **params[1];\n\n\tparams[0] = &trigdata;\n\n\t/* Build the internal function name, and save for later cleaning */\n\tsprintf(call, \"plphp_proc_%u_trigger\", fcinfo->flinfo->fn_oid);\n\tMAKE_STD_ZVAL(funcname);\n\tZVAL_STRING(funcname, call, 0);\n\n\t/*\n\t * HACK: mark trigdata as a reference, so it won't be copied in\n\t * call_user_function_ex. This way the user function will be able to \n\t * modify it, in order to change NEW.\n\t */\n\tZ_SET_ISREF_P(trigdata);\n\n\tif (call_user_function_ex(CG(function_table), NULL, funcname, &retval,\n\t\t\t\t\t\t\t 1, params, 1, NULL TSRMLS_CC) == FAILURE)\n\t\telog(ERROR, \"could not call function \\\"%s\\\"\", call);\n\n\tFREE_ZVAL(funcname);\n\n\t/* Return to the original state */\n\tZ_UNSET_ISREF_P(trigdata);\n\n\treturn retval;\n}\n\n/*\n * plphp_error_cb\n *\n * A callback for PHP error handling. This is called when the php_error or\n * zend_error function is invoked in our code. Ideally this function should\n * clean up the PHP state after an ERROR, but zend_try blocks do not seem\n * to work as I'd expect. So for now, we degrade the error to WARNING and \n * continue executing in the hope that the system doesn't crash later.\n *\n * Note that we do clean up some PHP state by hand but it doesn't seem to\n * work as expected either.\n */\nvoid\nplphp_error_cb(int type, const char *filename, const uint lineno,\n\t \t\t const char *fmt, va_list args)\n{\n\tchar\tstr[1024];\n\tint\t\televel;\n\n\tvsnprintf(str, 1024, fmt, args);\n\n\t/*\n\t * PHP error classification is a bitmask, so this conversion is a bit\n\t * bogus. However, most calls to php_error() use a single bit.\n\t * Whenever more than one is used, we will default to ERROR, so this is\n\t * safe, if a bit excessive.\n\t *\n\t * XXX -- I wonder whether we should promote the WARNINGs to errors as\n\t * well. PHP has a really stupid way of continuing execution in presence\n\t * of severe problems that I don't see why we should maintain.\n\t */\n\tswitch (type)\n\t{\n\t\tcase E_ERROR:\n\t\tcase E_CORE_ERROR:\n\t\tcase E_COMPILE_ERROR:\n\t\tcase E_USER_ERROR:\n\t\tcase E_PARSE:\n\t\t\televel = ERROR;\n\t\t\tbreak;\n\t\tcase E_WARNING:\n\t\tcase E_CORE_WARNING:\n\t\tcase E_COMPILE_WARNING:\n\t\tcase E_USER_WARNING:\n\t\tcase E_STRICT:\n\t\t\televel = WARNING;\n\t\t\tbreak;\n\t\tcase E_NOTICE:\n\t\tcase E_USER_NOTICE:\n\t\t\televel = NOTICE;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\televel = ERROR;\n\t\t\tbreak;\n\t}\n\n\tREPORT_PHP_MEMUSAGE(\"reporting error\");\n\n\t/*\n\t * If this is a severe problem, we need to make PHP aware of it, so first\n\t * save the error message and then bail out of the PHP block. With luck,\n\t * this will be trapped by a zend_try/zend_catch block outwards in PL/php\n\t * code, which would translate it to a Postgres elog(ERROR), leaving\n\t * everything in a consistent state.\n\t *\n\t * For this to work, there must be a try/catch block covering every place\n\t * where PHP may raise an error!\n\t */\n\tif (elevel >= ERROR)\n\t{\n\t\tif (lineno != 0)\n\t\t{\n\t\t\tchar\tmsgline[1024];\n\t\t\tsnprintf(msgline, sizeof(msgline), \"%s at line %d\", str, lineno);\n\t\t\terror_msg = pstrdup(msgline);\n\t\t}\n\t\telse\n\t\t\terror_msg = pstrdup(str);\n\n\t\tzend_bailout();\n\t}\n\n\tereport(elevel,\n\t\t\t(errmsg(\"plphp: %s\", str)));\n}\n\n/* Check if the name can be a valid PHP variable name */\nstatic bool \nis_valid_php_identifier(char *name)\n{\n\tint \tlen,\n\t\t\ti;\n\t\n\tAssert(name);\n\n\tlen = strlen(name);\n\n\t/* Should start from the letter */\n\tif (!isalpha(name[0]))\n\t\treturn false;\n\tfor (i = 1; i < len; i++)\n\t{\n\t\t/* Only letters, digits and underscores are allowed */\n\t\tif (!isalpha(name[i]) && !isdigit(name[i]) && name[i] != '_')\n\t\t\treturn false;\n\t}\n\treturn true;\n}\n\n/*\n * vim:ts=4:sw=4:cino=(0\n */\n", "plphp_io.c": "/**********************************************************************\n * plphp_io.c\n *\n * Support functions for PL/php -- mainly functions to convert stuff\n * from the PHP representation to PostgreSQL representation and vice\n * versa, either text or binary representations.\n *\n * $Id$\n *\n **********************************************************************/\n\n#include \"postgres.h\"\n#include \"plphp_io.h\"\n\n#include \"catalog/pg_type.h\"\n#include \"executor/spi.h\"\n#include \"funcapi.h\"\n#include \"lib/stringinfo.h\"\n#include \"utils/lsyscache.h\"\n#include \"utils/rel.h\"\n#include \"utils/syscache.h\"\n#include \"utils/memutils.h\"\n\n/*\n * plphp_zval_from_tuple\n *\t\t Build a PHP hash from a tuple.\n */\nzval *\nplphp_zval_from_tuple(HeapTuple tuple, TupleDesc tupdesc)\n{\n\tint\t\t\ti;\n\tchar\t *attname = NULL;\n\tzval\t *array;\n\n\tMAKE_STD_ZVAL(array);\n\tarray_init(array);\n\n\tfor (i = 0; i < tupdesc->natts; i++)\n\t{\n\t\tchar *attdata;\n\n\t\t/* Get the attribute name */\n\t\tattname = tupdesc->attrs[i]->attname.data;\n\n\t\t/* and get its value */\n\t\tif ((attdata = SPI_getvalue(tuple, tupdesc, i + 1)) != NULL)\n\t\t{\n\t\t\t/* \"true\" means strdup the string */\n\t\t\tadd_assoc_string(array, attname, attdata, true);\n\t\t\tpfree(attdata);\n\t\t}\n\t\telse\n\t\t\tadd_assoc_null(array, attname);\n\t}\n\treturn array;\n}\n\n/*\n * plphp_htup_from_zval\n * \t\tBuild a HeapTuple from a zval (which must be an array) and a TupleDesc.\n *\n * The return HeapTuple is allocated in the current memory context and must\n * be freed by the caller.\n *\n * If zval doesn't contain any of the element names from the TupleDesc,\n * build a tuple from the first N elements. This allows us to accept\n * arrays in form array(1,2,3) as the result of functions with OUT arguments.\n * XXX -- possible optimization: keep the memory context created and only\n * reset it between calls.\n */\nHeapTuple\nplphp_htup_from_zval(zval *val, TupleDesc tupdesc)\n{\n\tMemoryContext\toldcxt;\n\tMemoryContext\ttmpcxt;\n\tHeapTuple\t\tret;\n\tAttInMetadata *attinmeta;\n\tHashPosition\tpos;\n\tzval\t\t **element;\n\tchar\t\t **values;\n\tint\t\t\t\ti;\n\tbool\t\t\tallempty = true;\n\n\ttmpcxt = AllocSetContextCreate(TopTransactionContext,\n\t\t\t\t\t\t\t\t \"htup_from_zval cxt\",\n\t\t\t\t\t\t\t\t ALLOCSET_DEFAULT_MINSIZE,\n\t\t\t\t\t\t\t\t ALLOCSET_DEFAULT_INITSIZE,\n\t\t\t\t\t\t\t\t ALLOCSET_DEFAULT_MAXSIZE);\n\toldcxt = MemoryContextSwitchTo(tmpcxt);\n\n\tvalues = (char **) palloc(tupdesc->natts * sizeof(char *));\n\n\tfor (i = 0; i < tupdesc->natts; i++)\n\t{\n\t\tchar *key = SPI_fname(tupdesc, i + 1);\n\t\tzval *scalarval = plphp_array_get_elem(val, key);\n\n\t\tvalues[i] = plphp_zval_get_cstring(scalarval, true, true);\n\t\t/* \n\t\t * Reset the flag is even one of the keys actually exists,\n\t\t * even if it is NULL.\n\t\t */\n\t\tif (scalarval != NULL)\n\t\t\tallempty = false;\n\t}\n\t/* None of the names from the tuple exists,\n\t * try to get 1st N array elements and assign them to the tuple\n\t */\n\tif (allempty)\n\t\tfor (i = 0, \n\t\t\t zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(val), &pos);\n\t\t\t (zend_hash_get_current_data_ex(Z_ARRVAL_P(val), \n\t\t\t\t\t\t\t\t\t\t (void **) &element,\n\t\t\t\t\t\t\t\t\t\t\t&pos) == SUCCESS) && \n\t\t\t(i < tupdesc->natts);\n\t\t\tzend_hash_move_forward_ex(Z_ARRVAL_P(val), &pos), i++)\n\t\t\tvalues[i] = plphp_zval_get_cstring(element[0], true, true);\n\n\tattinmeta = TupleDescGetAttInMetadata(tupdesc);\n\n\tMemoryContextSwitchTo(oldcxt);\n\tret = BuildTupleFromCStrings(attinmeta, values);\n\n\tMemoryContextDelete(tmpcxt);\n\n\treturn ret;\n}\n\n\n/* plphp_srf_htup_from_zval\n * \t\tBuild a tuple from a zval and a TupleDesc, for a SRF.\n *\n * Like above, but we don't use the names of the array attributes;\n * rather we build the tuple in order. Also, we get a MemoryContext\n * from the caller and just clean it at return, rather than building it each\n * time.\n */\nHeapTuple\nplphp_srf_htup_from_zval(zval *val, AttInMetadata *attinmeta,\n\t\t\t\t\t\t MemoryContext cxt)\n{\n\tMemoryContext\toldcxt;\n\tHeapTuple\t\tret;\n\tHashPosition\tpos;\n\tchar\t\t **values;\n\tzval\t\t **element;\n\tint\t\t\t\ti = 0;\n\n\toldcxt = MemoryContextSwitchTo(cxt);\n\n\t/*\n\t * Use palloc0 to initialize values to NULL, just in case the user does\n\t * not pass all needed attributes\n\t */\n\tvalues = (char **) palloc0(attinmeta->tupdesc->natts * sizeof(char *));\n\n\t/*\n\t * If the input zval is an array, build a tuple using each element as an\n\t * attribute. Exception: if the return tuple has a single element and\n\t * it's an array type, use the whole array as a single value.\n\t *\n\t * If the input zval is a scalar, use it as an element directly.\n\t */\n\tif (Z_TYPE_P(val) == IS_ARRAY)\n\t{\n\t\tif (attinmeta->tupdesc->natts == 1)\n\t\t{\n\t\t\t/* Is it an array? */\n\t\t\tif (attinmeta->tupdesc->attrs[0]->attndims != 0 ||\n\t\t\t\t!OidIsValid(get_element_type(attinmeta->tupdesc->attrs[0]->atttypid)))\n\t\t\t{\n\t\t\t\tzend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(val), &pos);\n\t\t\t\tzend_hash_get_current_data_ex(Z_ARRVAL_P(val),\n\t\t\t\t\t\t\t\t\t\t\t (void **) &element,\n\t\t\t\t\t\t\t\t\t\t\t &pos);\n\t\t\t\tvalues[0] = plphp_zval_get_cstring(element[0], true, true);\n\t\t\t}\n\t\t\telse\n\t\t\t\tvalues[0] = plphp_zval_get_cstring(val, true, true);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t/*\n\t\t\t * Ok, it's an array and the return tuple has more than one\n\t\t\t * attribute, so scan each array element.\n\t\t\t */\n\t\t\tfor (zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(val), &pos);\n\t\t\t\t zend_hash_get_current_data_ex(Z_ARRVAL_P(val),\n\t\t\t\t\t\t\t\t\t\t\t (void **) &element,\n\t\t\t\t\t\t\t\t\t\t\t &pos) == SUCCESS;\n\t\t\t\t zend_hash_move_forward_ex(Z_ARRVAL_P(val), &pos))\n\t\t\t{\n\t\t\t\t/* avoid overrunning the palloc'ed chunk */\n\t\t\t\tif (i >= attinmeta->tupdesc->natts)\n\t\t\t\t{\n\t\t\t\t\telog(WARNING, \"more elements in array than attributes in return type\");\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tvalues[i++] = plphp_zval_get_cstring(element[0], true, true);\n\t\t\t}\n\t\t}\n\t}\n\telse\n\t{\n\t\t/* The passed zval is not an array -- use as the only attribute */\n\t\tif (attinmeta->tupdesc->natts != 1)\n\t\t\tereport(ERROR,\n\t\t\t\t\t(errmsg(\"returned array does not correspond to \"\n\t\t\t\t\t\t\t\"declared return value\")));\n\n\t\tvalues[0] = plphp_zval_get_cstring(val, true, true);\n\t}\n\n\tMemoryContextSwitchTo(oldcxt);\n\n\tret = BuildTupleFromCStrings(attinmeta, values);\n\n\tMemoryContextReset(cxt);\n\n\treturn ret;\n}\n\n/*\n * plphp_convert_to_pg_array\n * \t\tConvert a zval into a Postgres text array representation.\n *\n * The return value is palloc'ed in the current memory context and\n * must be freed by the caller.\n */\nchar *\nplphp_convert_to_pg_array(zval *array)\n{\n\tint\t\t\tarr_size;\n\tzval\t **element;\n\tint\t\t\ti = 0;\n\tHashPosition \tpos;\n\tStringInfoData\tstr;\n\t\n\tinitStringInfo(&str);\n\n\tarr_size = zend_hash_num_elements(Z_ARRVAL_P(array));\n\n\tappendStringInfoChar(&str, '{');\n\tif (Z_TYPE_P(array) == IS_ARRAY)\n\t{\n\t\tfor (zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(array), &pos);\n\t\t\t zend_hash_get_current_data_ex(Z_ARRVAL_P(array),\n\t\t\t\t\t\t\t\t\t\t (void **) &element,\n\t\t\t\t\t\t\t\t\t\t &pos) == SUCCESS;\n\t\t\t zend_hash_move_forward_ex(Z_ARRVAL_P(array), &pos))\n\t\t{\n\t\t\tchar *tmp;\n\n\t\t\tswitch (Z_TYPE_P(element[0]))\n\t\t\t{\n\t\t\t\tcase IS_LONG:\n\t\t\t\t\tappendStringInfo(&str, \"%li\", element[0]->value.lval);\n\t\t\t\t\tbreak;\n\t\t\t\tcase IS_DOUBLE:\n\t\t\t\t\tappendStringInfo(&str, \"%f\", element[0]->value.dval);\n\t\t\t\t\tbreak;\n\t\t\t\tcase IS_STRING:\n\t\t\t\t\tappendStringInfo(&str, \"\\\"%s\\\"\", element[0]->value.str.val);\n\t\t\t\t\tbreak;\n\t\t\t\tcase IS_ARRAY:\n\t\t\t\t\ttmp = plphp_convert_to_pg_array(element[0]);\n\t\t\t\t\tappendStringInfo(&str, \"%s\", tmp);\n\t\t\t\t\tpfree(tmp);\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\telog(ERROR, \"unrecognized element type %d\",\n\t\t\t\t\t\t Z_TYPE_P(element[0]));\n\t\t\t}\n\n\t\t\tif (i != arr_size - 1)\n\t\t\t\tappendStringInfoChar(&str, ',');\n\t\t\ti++;\n\t\t}\n\t}\n\n\tappendStringInfoChar(&str, '}');\n\n\treturn str.data;\n}\n\n/*\n * plphp_convert_from_pg_array\n * \t\tConvert a Postgres text array representation to a PHP array\n * \t\t(zval type thing).\n *\n * FIXME -- does not work if there are embedded {'s in the input value.\n *\n * FIXME -- does not correctly quote/dequote the values\n */\nzval *\nplphp_convert_from_pg_array(char *input TSRMLS_DC)\n{\n\tzval\t *retval = NULL;\n\tint\t\t\ti;\n\tStringInfoData str;\n\t\n\tinitStringInfo(&str);\n\n\tMAKE_STD_ZVAL(retval);\n\tarray_init(retval);\n\n\tfor (i = 0; i < strlen(input); i++)\n\t{\n\t\tif (input[i] == '{')\n\t\t\tappendStringInfoString(&str, \"array(\");\n\t\telse if (input[i] == '}')\n\t\t\tappendStringInfoChar(&str, ')');\n\t\telse\n\t\t\tappendStringInfoChar(&str, input[i]);\n\t}\n\tappendStringInfoChar(&str, ';');\n\n\tif (zend_eval_string(str.data, retval,\n\t\t\t\t\t\t \"plphp array input parameter\" TSRMLS_CC) == FAILURE)\n\t\telog(ERROR, \"plphp: convert to internal representation failure\");\n\n\tpfree(str.data);\n\n\treturn retval;\n}\n\n/*\n * plphp_array_get_elem\n * \t\tReturn a pointer to the array element with the given key\n */\nzval *\nplphp_array_get_elem(zval *array, char *key)\n{\n\tzval\t **element;\n\n\tif (!array)\n\t\telog(ERROR, \"passed zval is not a valid pointer\");\n\tif (Z_TYPE_P(array) != IS_ARRAY)\n\t\telog(ERROR, \"passed zval is not an array\");\n\n\tif (zend_symtable_find(array->value.ht,\n\t\t\t\t\t \t key,\n\t\t\t\t\t strlen(key) + 1,\n\t\t\t\t\t (void **) &element) != SUCCESS)\n\t\treturn NULL;\n\n\treturn element[0];\n}\n\n/*\n * zval_get_cstring\n *\t\tGet a C-string representation of a zval.\n *\n * All return values, except those that are NULL, are palloc'ed in the current\n * memory context and must be freed by the caller.\n *\n * If the do_array parameter is false, then array values will not be converted\n * and an error will be raised instead.\n *\n * If the null_ok parameter is true, we will return NULL for a NULL zval.\n * Otherwise we raise an error.\n */\nchar *\nplphp_zval_get_cstring(zval *val, bool do_array, bool null_ok)\n{\n\tchar *ret;\n\n\tif (!val)\n\t{\n\t\tif (null_ok)\n\t\t\treturn NULL;\n\t\telse\n\t\t\telog(ERROR, \"invalid zval pointer\");\n\t}\n\n\tswitch (Z_TYPE_P(val))\n\t{\n\t\tcase IS_NULL:\n\t\t\treturn NULL;\n\t\tcase IS_LONG:\n\t\t\tret = palloc(64);\n\t\t\tsnprintf(ret, 64, \"%ld\", Z_LVAL_P(val));\n\t\t\tbreak;\n\t\tcase IS_DOUBLE:\n\t\t\tret = palloc(64);\n\t\t\tsnprintf(ret, 64, \"%f\", Z_DVAL_P(val));\n\t\t\tbreak;\n\t\tcase IS_BOOL:\n\t\t\tret = palloc(8);\n\t\t\tsnprintf(ret, 8, \"%s\", Z_BVAL_P(val) ? \"true\": \"false\");\n\t\t\tbreak;\n\t\tcase IS_STRING:\n\t\t\tret = palloc(Z_STRLEN_P(val) + 1);\n\t\t\tsnprintf(ret, Z_STRLEN_P(val) + 1, \"%s\", \n\t\t\t\t\t Z_STRVAL_P(val));\n\t\t\tbreak;\n\t\tcase IS_ARRAY:\n\t\t\tif (!do_array)\n\t\t\t\telog(ERROR, \"can't stringize array value\");\n\t\t\tret = plphp_convert_to_pg_array(val);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\t/* keep compiler quiet */\n\t\t\tret = NULL;\n\t\t\telog(ERROR, \"can't stringize value of type %d\", val->type);\n\t}\n\n\treturn ret;\n}\n\n/*\n * plphp_build_tuple_argument\n *\n * Build a PHP array from all attributes of a given tuple\n */\nzval *\nplphp_build_tuple_argument(HeapTuple tuple, TupleDesc tupdesc)\n{\n\tint\t\t\ti;\n\tzval\t *output;\n\tDatum\t\tattr;\n\tbool\t\tisnull;\n\tchar\t *attname;\n\tchar\t *outputstr;\n\tHeapTuple\ttypeTup;\n\tOid\t\t\ttypoutput;\n\tOid\t\t\ttypioparam;\n\n\tMAKE_STD_ZVAL(output);\n\tarray_init(output);\n\n\tfor (i = 0; i < tupdesc->natts; i++)\n\t{\n\t\t/* Ignore dropped attributes */\n\t\tif (tupdesc->attrs[i]->attisdropped)\n\t\t\tcontinue;\n\n\t\t/* Get the attribute name */\n\t\tattname = tupdesc->attrs[i]->attname.data;\n\n\t\t/* Get the attribute value */\n\t\tattr = heap_getattr(tuple, i + 1, tupdesc, &isnull);\n\n\t\t/* If it is null, set it to undef in the hash. */\n\t\tif (isnull)\n\t\t{\n\t\t\tadd_next_index_unset(output);\n\t\t\tcontinue;\n\t\t}\n\n\t\t/*\n\t\t * Lookup the attribute type in the syscache for the output function\n\t\t */\n\t\ttypeTup = SearchSysCache(TYPEOID,\n\t\t\t\t\t\t\t\t ObjectIdGetDatum(tupdesc->attrs[i]->atttypid),\n\t\t\t\t\t\t\t\t 0, 0, 0);\n\t\tif (!HeapTupleIsValid(typeTup))\n\t\t{\n\t\t\telog(ERROR, \"cache lookup failed for type %u\",\n\t\t\t\t tupdesc->attrs[i]->atttypid);\n\t\t}\n\n\t\ttypoutput = ((Form_pg_type) GETSTRUCT(typeTup))->typoutput;\n\t\ttypioparam = getTypeIOParam(typeTup);\n\t\tReleaseSysCache(typeTup);\n\n\t\t/* Append the attribute name and the value to the list. */\n\t\toutputstr =\n\t\t\tDatumGetCString(OidFunctionCall3(typoutput, attr,\n\t\t\t\t\t\t\t\t\t\t\t ObjectIdGetDatum(typioparam),\n\t\t\t\t\t\t\t\t\t\t\t Int32GetDatum(tupdesc->attrs[i]->atttypmod)));\n\t\tadd_assoc_string(output, attname, outputstr, 1);\n\t\tpfree(outputstr);\n\t}\n\n\treturn output;\n}\n\n/*\n * plphp_modify_tuple\n * \t\tReturn the modified NEW tuple, for use as return value in a BEFORE\n * \t\ttrigger. outdata must point to the $_TD variable from the PHP\n * \t\tfunction.\n *\n * The tuple will be allocated in the current memory context and must be freed\n * by the caller.\n *\n * XXX Possible optimization: make this a global context that is not deleted,\n * but only reset each time this function is called. (Think about triggers\n * calling other triggers though).\n */\nHeapTuple\nplphp_modify_tuple(zval *outdata, TriggerData *tdata)\n{\n\tTupleDesc\ttupdesc;\n\tHeapTuple\trettuple;\n\tzval\t *newtup;\n\tzval\t **element;\n\tchar\t **vals;\n\tint\t\t\ti;\n\tAttInMetadata *attinmeta;\n\tMemoryContext tmpcxt,\n\t\t\t\t oldcxt;\n\n\ttmpcxt = AllocSetContextCreate(CurTransactionContext,\n\t\t\t\t\t\t\t\t \"PL/php NEW context\",\n\t\t\t\t\t\t\t\t ALLOCSET_DEFAULT_MINSIZE,\n\t\t\t\t\t\t\t\t ALLOCSET_DEFAULT_INITSIZE,\n\t\t\t\t\t\t\t\t ALLOCSET_DEFAULT_MAXSIZE);\n\n\toldcxt = MemoryContextSwitchTo(tmpcxt);\n\n\t/* Fetch \"new\" from $_TD */\n\tif (zend_hash_find(outdata->value.ht,\n\t\t\t\t\t \"new\", strlen(\"new\") + 1,\n\t\t\t\t\t (void **) &element) != SUCCESS)\n\t\telog(ERROR, \"$_TD['new'] not found\");\n\n\tif (Z_TYPE_P(element[0]) != IS_ARRAY)\n\t\telog(ERROR, \"$_TD['new'] must be an array\");\n\tnewtup = element[0];\n\n\t/* Fetch the tupledesc and metadata */\n\ttupdesc = tdata->tg_relation->rd_att;\n\tattinmeta = TupleDescGetAttInMetadata(tupdesc);\n\n\ti = zend_hash_num_elements(Z_ARRVAL_P(newtup));\n\n\tif (tupdesc->natts > i)\n\t\tereport(ERROR,\n\t\t\t\t(errmsg(\"insufficient number of keys in $_TD['new']\"),\n\t\t\t\t errdetail(\"At least %d expected, %d found.\",\n\t\t\t\t\t\t tupdesc->natts, i)));\n\n\tvals = (char **) palloc(tupdesc->natts * sizeof(char *));\n\n\t/*\n\t * For each attribute in the tupledesc, get its value from newtup and put\n\t * it in an array of cstrings.\n\t */\n\tfor (i = 0; i < tupdesc->natts; i++)\n\t{\n\t\tzval **element;\n\t\tchar *attname = NameStr(tupdesc->attrs[i]->attname);\n\n\t\t/* Fetch the attribute value from the zval */\n\t\tif (zend_symtable_find(newtup->value.ht, attname, strlen(attname) + 1,\n\t\t\t\t\t\t \t (void **) &element) != SUCCESS)\n\t\t\telog(ERROR, \"$_TD['new'] does not contain attribute \\\"%s\\\"\",\n\t\t\t\t attname);\n\n\t\tvals[i] = plphp_zval_get_cstring(element[0], true, true);\n\t}\n\n\t/* Return to the original context so that the new tuple will survive */\n\tMemoryContextSwitchTo(oldcxt);\n\n\t/* Build the tuple */\n\trettuple = BuildTupleFromCStrings(attinmeta, vals);\n\n\t/* Free the memory used */\n\tMemoryContextDelete(tmpcxt);\n\n\treturn rettuple;\n}\n\n/*\n * vim:ts=4:sw=4:cino=(0\n */\n", "plphp_spi.c": "/**********************************************************************\n * plphp_spi.c - SPI-related functions for PL/php.\n *\n * This software is copyright (c) Command Prompt Inc.\n *\n * The author hereby grants permission to use, copy, modify,\n * distribute, and license this software and its documentation for any\n * purpose, provided that existing copyright notices are retained in\n * all copies and that this notice is included verbatim in any\n * distributions. No written agreement, license, or royalty fee is\n * required for any of the authorized uses. Modifications to this\n * software may be copyrighted by their author and need not follow the\n * licensing terms described here, provided that the new terms are\n * clearly indicated on the first page of each file where they apply.\n *\n * IN NO EVENT SHALL THE AUTHOR OR DISTRIBUTORS BE LIABLE TO ANY PARTY\n * FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES\n * ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY\n * DERIVATIVES THEREOF, EVEN IF THE AUTHOR HAVE BEEN ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * THE AUTHOR AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES,\n * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND\n * NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN \"AS IS\" BASIS,\n * AND THE AUTHOR AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE\n * MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n *\n * IDENTIFICATION\n *\t\t$Id$\n *********************************************************************\n */\n\n#include \"postgres.h\"\n#include \"plphp_spi.h\"\n#include \"plphp_io.h\"\n\n/* PHP stuff */\n#include \"php.h\"\n\n/* PostgreSQL stuff */\n#include \"access/xact.h\"\n#include \"miscadmin.h\"\n\n#undef DEBUG_PLPHP_MEMORY\n\n#ifdef DEBUG_PLPHP_MEMORY\n#define REPORT_PHP_MEMUSAGE(where) \\\n\telog(NOTICE, \"PHP mem usage: \u00ab%s\u00bb: %u\", where, AG(allocated_memory));\n#else\n#define REPORT_PHP_MEMUSAGE(a) \n#endif\n\n/* resource type Id for SPIresult */\nint SPIres_rtype;\n\n/* SPI function table */\nzend_function_entry spi_functions[] =\n{\n\tZEND_FE(spi_exec, NULL)\n\tZEND_FE(spi_fetch_row, NULL)\n\tZEND_FE(spi_processed, NULL)\n\tZEND_FE(spi_status, NULL)\n\tZEND_FE(spi_rewind, NULL)\n\tZEND_FE(pg_raise, NULL)\n\tZEND_FE(return_next, NULL)\n\t{NULL, NULL, NULL}\n};\n\n/* SRF support: */\nFunctionCallInfo current_fcinfo = NULL;\nTupleDesc current_tupledesc = NULL;\nAttInMetadata *current_attinmeta = NULL;\nMemoryContext current_memcxt = NULL;\nTuplestorestate *current_tuplestore = NULL;\n\n\n/* A symbol table to save for return_next for the RETURNS TABLE case */\nHashTable *saved_symbol_table;\n\nstatic zval *get_table_arguments(AttInMetadata *attinmeta);\n\n/*\n * spi_exec\n * \t\tPL/php equivalent to SPI_exec().\n *\n * This function creates and return a PHP resource which describes the result\n * of a user-specified query. If the query returns tuples, it's possible to\n * retrieve them by using spi_fetch_row.\n *\n * Receives one or two arguments. The mandatory first argument is the query\n * text. The optional second argument is the tuple limit.\n *\n * Note that just like PL/Perl, we start a subtransaction before invoking the\n * SPI call, and automatically roll it back if the call fails.\n */\nZEND_FUNCTION(spi_exec)\n{\n\tchar\t *query;\n\tint\t\t\tquery_len;\n\tlong\t\tstatus;\n\tlong\t\tlimit;\n\tphp_SPIresult *SPIres;\n\tint\t\t\tspi_id;\n\tMemoryContext oldcontext = CurrentMemoryContext;\n\tResourceOwner oldowner = CurrentResourceOwner;\n\n\tREPORT_PHP_MEMUSAGE(\"spi_exec called\");\n\n\tif ((ZEND_NUM_ARGS() > 2) || (ZEND_NUM_ARGS() < 1))\n\t\tWRONG_PARAM_COUNT;\n\n\t/* Parse arguments */\n\tif (ZEND_NUM_ARGS() == 2)\n\t{\n\t\tif (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"sl\",\n\t\t\t\t\t\t\t\t &query, &query_len, &limit) == FAILURE)\n\t\t{\n\t\t\tzend_error(E_WARNING, \"Can not parse parameters in %s\",\n\t\t\t\t\t get_active_function_name(TSRMLS_C));\n\t\t\tRETURN_FALSE;\n\t\t}\n\t}\n\telse if (ZEND_NUM_ARGS() == 1)\n\t{\n\t\tif (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"s\",\n\t\t\t\t\t\t\t\t &query, &query_len) == FAILURE)\n\t\t{\n\t\t\tzend_error(E_WARNING, \"Can not parse parameters in %s\",\n\t\t\t\t\t get_active_function_name(TSRMLS_C));\n\t\t\tRETURN_FALSE;\n\t\t}\n\t\tlimit = 0;\n\t}\n\telse\n\t{\n\t\tzend_error(E_WARNING, \"Incorrect number of parameters to %s\",\n\t\t\t\t get_active_function_name(TSRMLS_C));\n\t\tRETURN_FALSE;\n\t}\n\n\tBeginInternalSubTransaction(NULL);\n\tMemoryContextSwitchTo(oldcontext);\n\n\t/* Call SPI */\n\tPG_TRY();\n\t{\n\t\tstatus = SPI_exec(query, limit);\n\n\t\tReleaseCurrentSubTransaction();\n\t\tMemoryContextSwitchTo(oldcontext);\n\t\tCurrentResourceOwner = oldowner;\n\n\t\t/*\n\t\t * AtEOSubXact_SPI() should not have popped any SPI context, but just\n\t\t * in case it did, make sure we remain connected.\n\t\t */\n\t\tSPI_restore_connection();\n\t}\n\tPG_CATCH();\n\t{\n\t\tErrorData\t*edata;\n\n\t\t/* Save error info */\n\t\tMemoryContextSwitchTo(oldcontext);\n\t\tedata = CopyErrorData();\n\t\tFlushErrorState();\n\n\t\t/* Abort the inner trasaction */\n\t\tRollbackAndReleaseCurrentSubTransaction();\n\t\tMemoryContextSwitchTo(oldcontext);\n\t\tCurrentResourceOwner = oldowner;\n\n\t\t/*\n\t\t * If AtEOSubXact_SPI() popped any SPI context of the subxact, it will\n\t\t * have left us in a disconnected state. We need this hack to return\n\t\t * to connected state.\n\t\t */\n\t\tSPI_restore_connection();\n\n\t\t/* bail PHP out */\n\t\tzend_error(E_ERROR, \"%s\", strdup(edata->message));\n\n\t\t/* Can't get here, but keep compiler quiet */\n\t\treturn;\n\t}\n\tPG_END_TRY();\n\n\t/* This malloc'ed chunk is freed in php_SPIresult_destroy */\n\tSPIres = (php_SPIresult *) malloc(sizeof(php_SPIresult));\n\tif (!SPIres)\n\t\tereport(ERROR,\n\t\t\t\t(errcode(ERRCODE_OUT_OF_MEMORY),\n\t\t\t\t errmsg(\"out of memory\")));\n\n\t/* Prepare the return resource */\n\tSPIres->SPI_processed = SPI_processed;\n\tif (status == SPI_OK_SELECT)\n\t\tSPIres->SPI_tuptable = SPI_tuptable;\n\telse\n\t\tSPIres->SPI_tuptable = NULL;\n\tSPIres->current_row = 0;\n\tSPIres->status = status;\n\n\tREPORT_PHP_MEMUSAGE(\"spi_exec: creating resource\");\n\n\t/* Register the resource to PHP so it will be able to free it */\n\tspi_id = ZEND_REGISTER_RESOURCE(return_value, (void *) SPIres,\n\t\t\t\t\t \t\t\t\tSPIres_rtype);\n\n\tREPORT_PHP_MEMUSAGE(\"spi_exec: returning\");\n\n\tRETURN_RESOURCE(spi_id);\n}\n\n/*\n * spi_fetch_row\n * \t\tGrab a row from a SPI result (from spi_exec).\n *\n * This function receives a resource Id and returns a PHP hash representing the\n * next tuple in the result, or false if no tuples remain.\n *\n * XXX Apparently this is leaking memory. How do we tell PHP to free the tuple\n * once the user is done with it?\n */\nZEND_FUNCTION(spi_fetch_row)\n{\n\tzval\t *row = NULL;\n\tzval\t **z_spi = NULL;\n\tphp_SPIresult\t*SPIres;\n\n\tREPORT_PHP_MEMUSAGE(\"spi_fetch_row: called\");\n\n\tif (ZEND_NUM_ARGS() != 1)\n\t\tWRONG_PARAM_COUNT;\n\n\tif (zend_get_parameters_ex(1, &z_spi) == FAILURE)\n\t{\n\t\tzend_error(E_WARNING, \"Can not parse parameters in %s\",\n\t\t\t\t get_active_function_name(TSRMLS_C));\n\t\tRETURN_FALSE;\n\t}\n\tif (z_spi == NULL)\n\t{\n\t\tzend_error(E_WARNING, \"Could not get SPI resource in %s\",\n\t\t\t\t get_active_function_name(TSRMLS_C));\n\t\tRETURN_FALSE;\n\t}\n\n\tZEND_FETCH_RESOURCE(SPIres, php_SPIresult *, z_spi, -1, \"SPI result\",\n\t\t\t\t\t\tSPIres_rtype);\n\n\tif (SPIres->status != SPI_OK_SELECT)\n\t{\n\t\tzend_error(E_WARNING, \"SPI status is not good\");\n\t\tRETURN_FALSE;\n\t}\n\n\tif (SPIres->current_row < SPIres->SPI_processed)\n\t{\n\t\trow = plphp_zval_from_tuple(SPIres->SPI_tuptable->vals[SPIres->current_row],\n\t\t\t \t\t\t\t\t\tSPIres->SPI_tuptable->tupdesc);\n\t\tSPIres->current_row++;\n\n\t\t*return_value = *row;\n\n\t\tzval_copy_ctor(return_value);\n\t\tzval_dtor(row);\n\t\tFREE_ZVAL(row);\n\n\t}\n\telse\n\t\tRETURN_FALSE;\n\n\tREPORT_PHP_MEMUSAGE(\"spi_fetch_row: finish\");\n}\n\n/*\n * spi_processed\n * \t\tReturn the number of tuples returned in a spi_exec call.\n */\nZEND_FUNCTION(spi_processed)\n{\n\tzval\t **z_spi = NULL;\n\tphp_SPIresult\t*SPIres;\n\n\tREPORT_PHP_MEMUSAGE(\"spi_processed: start\");\n\n\tif (ZEND_NUM_ARGS() != 1)\n\t\tWRONG_PARAM_COUNT;\n\n\tif (zend_get_parameters_ex(1, &z_spi) == FAILURE)\n\t{\n\t\tzend_error(E_WARNING, \"Cannot parse parameters in %s\",\n\t\t\t\t get_active_function_name(TSRMLS_C));\n\t\tRETURN_FALSE;\n\t}\n\tif (z_spi == NULL)\n\t{\n\t\tzend_error(E_WARNING, \"Could not get SPI resource in %s\",\n\t\t\t\t get_active_function_name(TSRMLS_C));\n\t\tRETURN_FALSE;\n\t}\n\n\tZEND_FETCH_RESOURCE(SPIres, php_SPIresult *, z_spi, -1, \"SPI result\",\n\t\t\t\t\t\tSPIres_rtype);\n\n\tREPORT_PHP_MEMUSAGE(\"spi_processed: finish\");\n\n\tRETURN_LONG(SPIres->SPI_processed);\n}\n\n/*\n * spi_status\n * \t\tReturn the status returned by a previous spi_exec call, as a string.\n */\nZEND_FUNCTION(spi_status)\n{\n\tzval\t **z_spi = NULL;\n\tphp_SPIresult\t*SPIres;\n\n\tREPORT_PHP_MEMUSAGE(\"spi_status: start\");\n\n\tif (ZEND_NUM_ARGS() != 1)\n\t\tWRONG_PARAM_COUNT;\n\n\tif (zend_get_parameters_ex(1, &z_spi) == FAILURE)\n\t{\n\t\tzend_error(E_WARNING, \"Cannot parse parameters in %s\",\n\t\t\t\t get_active_function_name(TSRMLS_C));\n\t\tRETURN_FALSE;\n\t}\n\tif (z_spi == NULL)\n\t{\n\t\tzend_error(E_WARNING, \"Could not get SPI resource in %s\",\n\t\t\t\t get_active_function_name(TSRMLS_C));\n\t\tRETURN_FALSE;\n\t}\n\n\tZEND_FETCH_RESOURCE(SPIres, php_SPIresult *, z_spi, -1, \"SPI result\",\n\t\t\t\t\t\tSPIres_rtype);\n\n\tREPORT_PHP_MEMUSAGE(\"spi_status: finish\");\n\n\t/*\n\t * XXX The cast is wrong, but we use it to prevent a compiler warning.\n\t * Note that the second parameter to RETURN_STRING is \"duplicate\", so\n\t * we are returning a copy of the string anyway.\n\t */\n\tRETURN_STRING((char *) SPI_result_code_string(SPIres->status), true);\n}\n\n/*\n * spi_rewind\n * \t\tResets the internal counter for spi_fetch_row, so the next\n * \t\tspi_fetch_row call will start fetching from the beginning.\n */\nZEND_FUNCTION(spi_rewind)\n{\n\tzval\t **z_spi = NULL;\n\tphp_SPIresult\t*SPIres;\n\n\tif (ZEND_NUM_ARGS() != 1)\n\t\tWRONG_PARAM_COUNT;\n\n\tif (zend_get_parameters_ex(1, &z_spi) == FAILURE)\n\t{\n\t\tzend_error(E_WARNING, \"Cannot parse parameters in %s\",\n\t\t\t\t get_active_function_name(TSRMLS_C));\n\t\tRETURN_FALSE;\n\t}\n\tif (z_spi == NULL)\n\t{\n\t\tzend_error(E_WARNING, \"Could not get SPI resource in %s\",\n\t\t\t\t get_active_function_name(TSRMLS_C));\n\t\tRETURN_FALSE;\n\t}\n\n\tZEND_FETCH_RESOURCE(SPIres, php_SPIresult *, z_spi, -1, \"SPI result\",\n\t\t\t\t\t\tSPIres_rtype);\n\n\tSPIres->current_row = 0;\n\n\tRETURN_NULL();\n}\n/*\n * pg_raise\n * User-callable function for sending messages to the Postgres log.\n */\nZEND_FUNCTION(pg_raise)\n{\n\tchar *level = NULL,\n\t\t\t *message = NULL;\n\tint level_len,\n\t\t\t\tmessage_len,\n\t\t\t\televel = 0;\n\n\tif (ZEND_NUM_ARGS() != 2)\n\t{\n\t\tereport(ERROR,\n\t\t\t\t(errcode(ERRCODE_SYNTAX_ERROR),\n\t\t\t\t errmsg(\"wrong number of arguments to %s\", \"pg_raise\")));\n\t}\n\n\tif (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"ss\",\n\t\t\t\t\t\t\t &level, &level_len,\n\t\t\t\t\t\t\t &message, &message_len) == FAILURE)\n\t{\n\t\tzend_error(E_WARNING, \"cannot parse parameters in %s\",\n\t\t\t\t get_active_function_name(TSRMLS_C));\n\t}\n\n\tif (strcasecmp(level, \"ERROR\") == 0)\n\t\televel = E_ERROR;\n\telse if (strcasecmp(level, \"WARNING\") == 0)\n\t\televel = E_WARNING;\n\telse if (strcasecmp(level, \"NOTICE\") == 0)\n\t\televel = E_NOTICE;\n\telse\n\t\tzend_error(E_ERROR, \"incorrect log level\");\n\n\tzend_error(elevel, \"%s\", message);\n}\n\n/*\n * return_next\n * \t\tAdd a tuple to the current tuplestore\n */\nZEND_FUNCTION(return_next)\n{\n\tMemoryContext\toldcxt;\n\tzval\t *param;\n\tHeapTuple\ttup;\n\tReturnSetInfo *rsi;\n\t\n\t/*\n\t * Disallow use of return_next inside non-SRF functions\n\t */\n\tif (current_fcinfo == NULL || current_fcinfo->flinfo == NULL || \n\t\t!current_fcinfo->flinfo->fn_retset)\n\t\tereport(ERROR,\n\t\t\t\t(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),\n\t\t\t\t errmsg(\"cannot use return_next in functions not declared to \"\n\t\t\t\t\t\t\"return a set\")));\n\n\trsi = (ReturnSetInfo *) current_fcinfo->resultinfo;\n\n\tAssert(current_tupledesc != NULL);\n\tAssert(rsi != NULL);\n\t\n\tif (ZEND_NUM_ARGS() > 1)\n\t\tereport(ERROR,\n\t\t\t\t(errcode(ERRCODE_SYNTAX_ERROR),\n\t\t\t\t errmsg(\"wrong number of arguments to %s\", \"return_next\")));\n\n\tif (ZEND_NUM_ARGS() == 0)\n\t{\n\t\t/* \n\t\t * Called from the function declared with RETURNS TABLE \n\t */\n\t\tparam = get_table_arguments(current_attinmeta);\n\t}\n\telse if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"z\",\n\t\t\t\t\t\t\t ¶m) == FAILURE)\n\t{\n\t\tzend_error(E_WARNING, \"cannot parse parameters in %s\",\n\t\t\t\t get_active_function_name(TSRMLS_C));\n\t}\n\n\t/* Use the per-query context so that the tuplestore survives */\n\toldcxt = MemoryContextSwitchTo(rsi->econtext->ecxt_per_query_memory);\n\n\t/* Form the tuple */\n\ttup = plphp_srf_htup_from_zval(param, current_attinmeta, current_memcxt);\n\n\t/* First call? Create the tuplestore. */\n\tif (!current_tuplestore)\n\t\tcurrent_tuplestore = tuplestore_begin_heap(true, false, work_mem);\n\n\t/* Save the tuple and clean up */\n\ttuplestore_puttuple(current_tuplestore, tup);\n\theap_freetuple(tup);\n\n\tMemoryContextSwitchTo(oldcxt);\n}\n\n/*\n * php_SPIresult_destroy\n * \t\tFree the resources allocated by a spi_exec call.\n *\n * This is automatically called when the resource goes out of scope\n * or is overwritten by another resource.\n */\nvoid\nphp_SPIresult_destroy(zend_rsrc_list_entry *rsrc TSRMLS_DC)\n{\n\tphp_SPIresult *res = (php_SPIresult *) rsrc->ptr;\n\n\tif (res->SPI_tuptable != NULL)\n\t\tSPI_freetuptable(res->SPI_tuptable);\n\n\tfree(res);\n}\n\n/* Return an array of TABLE argument values for return_next */\nstatic\nzval *get_table_arguments(AttInMetadata *attinmeta)\n{\n\tzval *retval = NULL;\n\tint\t\ti;\n\t\n\tMAKE_STD_ZVAL(retval);\n\tarray_init(retval);\n\n\tAssert(attinmeta->tupdesc);\n\tAssert(saved_symbol_table != NULL);\n\t/* Extract OUT argument names */\n\tfor (i = 0; i < attinmeta->tupdesc->natts; i++)\n\t{\n\t\tzval \t**val;\n\t\tchar \t*attname;\n\n\t\tAssert(!attinmeta->tupdesc->attrs[i]->attisdropped);\n\n\t\tattname = NameStr(attinmeta->tupdesc->attrs[i]->attname);\n\n\t\tif (zend_hash_find(saved_symbol_table, \n\t\t\t\t\t\t attname, strlen(attname) + 1,\n\t\t\t\t\t\t (void **)&val) == SUCCESS)\n\n\t\t\tadd_next_index_zval(retval, *val);\n\t\telse\n\t\t\tadd_next_index_unset(retval);\n\t} \n\treturn retval;\n}\n\n\n/*\n * vim:ts=4:sw=4:cino=(0\n */\n"}, "files_after": {"plphp.c": "/**********************************************************************\n * plphp.c - PHP as a procedural language for PostgreSQL\n *\n * This software is copyright (c) Command Prompt Inc.\n *\n * The author hereby grants permission to use, copy, modify,\n * distribute, and license this software and its documentation for any\n * purpose, provided that existing copyright notices are retained in\n * all copies and that this notice is included verbatim in any\n * distributions. No written agreement, license, or royalty fee is\n * required for any of the authorized uses. Modifications to this\n * software may be copyrighted by their author and need not follow the\n * licensing terms described here, provided that the new terms are\n * clearly indicated on the first page of each file where they apply.\n *\n * IN NO EVENT SHALL THE AUTHOR OR DISTRIBUTORS BE LIABLE TO ANY PARTY\n * FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES\n * ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY\n * DERIVATIVES THEREOF, EVEN IF THE AUTHOR HAVE BEEN ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * THE AUTHOR AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES,\n * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND\n * NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN \"AS IS\" BASIS,\n * AND THE AUTHOR AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE\n * MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n *\n * IDENTIFICATION\n *\t\t$Id$\n *********************************************************************\n */\n\n\n/* Package configuration generated by autoconf */\n#include \"config.h\"\n\n/* First round of undefs, to eliminate collision between plphp and postgresql\n * definitions\n */\n \n#undef PACKAGE_BUGREPORT\n#undef PACKAGE_NAME\n#undef PACKAGE_STRING\n#undef PACKAGE_TARNAME\n#undef PACKAGE_VERSION\n\n/* PostgreSQL stuff */\n#include \"postgres.h\"\n#include \"access/heapam.h\"\n#include \"access/transam.h\"\n#include \"access/htup_details.h\"\n\n#include \"catalog/catversion.h\"\n#include \"catalog/pg_language.h\"\n#include \"catalog/pg_proc.h\"\n#include \"catalog/pg_type.h\"\n\n#include \"commands/trigger.h\"\n#include \"fmgr.h\"\n#include \"funcapi.h\"\t\t\t/* needed for SRF support */\n#include \"lib/stringinfo.h\"\n\n#include \"utils/array.h\"\n#include \"utils/builtins.h\"\n#include \"utils/elog.h\"\n#include \"utils/lsyscache.h\"\n#include \"utils/memutils.h\"\n#include \"utils/rel.h\"\n#include \"utils/syscache.h\"\n#include \"utils/typcache.h\"\n\n/*\n * These are defined again in php.h, so undef them to avoid some\n * cpp warnings.\n */\n#undef PACKAGE_BUGREPORT\n#undef PACKAGE_NAME\n#undef PACKAGE_STRING\n#undef PACKAGE_TARNAME\n#undef PACKAGE_VERSION\n\n/* PHP stuff */\n#include \"php.h\"\n\n#include \"php_variables.h\"\n#include \"php_globals.h\"\n#include \"zend_hash.h\"\n#include \"zend_modules.h\"\n\n#include \"php_ini.h\"\t\t\t/* needed for INI_HARDCODED */\n#include \"php_main.h\"\n\n/* Our own stuff */\n#include \"plphp_io.h\"\n#include \"plphp_spi.h\"\n\n/* system stuff */\n#if HAVE_FCNTL_H\n#include \n#endif\n#if HAVE_UNISTD_H\n#include \n#endif\n\n#define INI_HARDCODED(name,value) \\\n\t\tzend_alter_ini_entry(name, sizeof(name), value, strlen(value), \\\n\t\t\t\t\t\t\t PHP_INI_SYSTEM, PHP_INI_STAGE_ACTIVATE);\n\n/* Check for PostgreSQL version */\n#if (CATALOG_VERSION_NO >= 200709301)\n#define PG_VERSION_83_COMPAT\n#endif\n#if (CATALOG_VERSION_NO >= 200611241)\n#define PG_VERSION_82_COMPAT\n#endif\n/* We only support 8.1 and above */\n#if (CATALOG_VERSION_NO >= 200510211)\n#define PG_VERSION_81_COMPAT\n#else\n#error \"Unsupported PostgreSQL version\"\n#endif\n\n#undef DEBUG_PLPHP_MEMORY\n\n#ifdef DEBUG_PLPHP_MEMORY\n#define REPORT_PHP_MEMUSAGE(where) \\\n\telog(NOTICE, \"PHP mem usage: %s: %u\", where, AG(allocated_memory));\n#else\n#define REPORT_PHP_MEMUSAGE(a) \n#endif\n\n/* PostgreSQL starting from v 8.2 requires this define\n * for all modules.\n */\n#ifdef PG_VERSION_82_COMPAT\nPG_MODULE_MAGIC;\n#else\n/* Supress warnings on 8.1 and below */\n#define ReleaseTupleDesc(tupdesc) \n#endif\n\n/* PHP 5.2 and earlier do not contain these definitions */\n#ifndef Z_SET_ISREF_P\n#define Z_SET_ISREF_P(foo) (foo)->is_ref = 1\n#define Z_UNSET_ISREF_P(foo) (foo)->is_ref = 0\n#endif\n\n/* 8.2 compatibility */\n#ifndef TYPTYPE_PSEUDO\n#define TYPTYPE_PSEUDO 'p'\n#define TYPTYPE_COMPOSITE 'c'\n#endif\n\n/* Check the argument type to expect to accept an initial value */\n#define IS_ARGMODE_OUT(mode) ((mode) == PROARGMODE_OUT || \\\n(mode) == PROARGMODE_TABLE)\n/*\n * Return types. Why on earth is this a bitmask? Beats me.\n * We should have separate flags instead.\n */\ntypedef enum pl_type\n{\n\tPL_TUPLE = 1 << 0,\n\tPL_ARRAY = 1 << 1,\n\tPL_PSEUDO = 1 << 2\n} pl_type;\n\n/*\n * The information we cache about loaded procedures.\n *\n * \"proname\" is the name of the function, given by the user.\n *\n * fn_xmin and fn_cmin are used to know when a function has been redefined and\n * needs to be recompiled.\n *\n * trusted indicates whether the function was created with a trusted handler.\n *\n * ret_type is a weird bitmask that indicates whether this function returns a\n * tuple, an array or a pseudotype. ret_oid is the Oid of the return type.\n * retset indicates whether the function was declared to return a set.\n *\n * arg_argmode indicates whether the argument is IN, OUT or both. It follows\n * values in pg_proc.proargmodes.\n *\n * n_out_args - total number of OUT or INOUT arguments.\n * arg_out_tupdesc is a tuple descriptor of the tuple constructed for OUT args.\n *\n * XXX -- maybe this thing needs to be rethought.\n */\ntypedef struct plphp_proc_desc\n{\n\tchar\t *proname;\n\tTransactionId fn_xmin;\n\tCommandId\tfn_cmin;\n\tbool\t\ttrusted;\n\tpl_type\t\tret_type;\n\tOid\t\t\tret_oid;\t\t/* Oid of returning type */\n\tbool\t\tretset;\n\tFmgrInfo\tresult_in_func;\n\tOid\t\t\tresult_typioparam;\n\tint\t\t\tn_out_args;\n\tint\t\t\tn_total_args;\n\tint\t\t\tn_mixed_args;\n\tFmgrInfo\targ_out_func[FUNC_MAX_ARGS];\n\tOid\t\t\targ_typioparam[FUNC_MAX_ARGS];\n\tchar\t\targ_typtype[FUNC_MAX_ARGS];\n\tchar\t\targ_argmode[FUNC_MAX_ARGS];\n\tTupleDesc\targs_out_tupdesc;\n} plphp_proc_desc;\n\n/*\n * Global data\n */\nstatic bool plphp_first_call = true;\nstatic zval *plphp_proc_array = NULL;\n\n/* for PHP write/flush */\nstatic StringInfo currmsg = NULL;\n\n/*\n * for PHP <-> Postgres error message passing\n *\n * XXX -- it would be much better if we could save errcontext,\n * errhint, etc as well.\n */\nstatic char *error_msg = NULL;\n/*\n * Forward declarations\n */\nstatic void plphp_init_all(void);\nvoid\t\tplphp_init(void);\n\nPG_FUNCTION_INFO_V1(plphp_call_handler);\nDatum plphp_call_handler(PG_FUNCTION_ARGS);\n\nPG_FUNCTION_INFO_V1(plphp_validator);\nDatum plphp_validator(PG_FUNCTION_ARGS);\n\nstatic Datum plphp_trigger_handler(FunctionCallInfo fcinfo,\n\t\t\t\t\t\t\t\t plphp_proc_desc *desc\n\t\t\t\t\t\t\t\t TSRMLS_DC);\nstatic Datum plphp_func_handler(FunctionCallInfo fcinfo,\n\t\t\t\t\t\t\t plphp_proc_desc *desc\n\t\t\t\t\t\t\t\tTSRMLS_DC);\nstatic Datum plphp_srf_handler(FunctionCallInfo fcinfo,\n\t\t\t\t\t\t \t plphp_proc_desc *desc\n\t\t\t\t\t\t\t TSRMLS_DC);\n\nstatic plphp_proc_desc *plphp_compile_function(Oid fnoid, bool is_trigger TSRMLS_DC);\nstatic zval *plphp_call_php_func(plphp_proc_desc *desc,\n\t\t\t\t\t\t\t\t FunctionCallInfo fcinfo\n\t\t\t\t\t\t\t\t TSRMLS_DC);\nstatic zval *plphp_call_php_trig(plphp_proc_desc *desc,\n\t\t\t\t\t\t\t\t FunctionCallInfo fcinfo, zval *trigdata\n\t\t\t\t\t\t\t\t TSRMLS_DC);\n\nstatic void plphp_error_cb(int type, const char *filename, const uint lineno,\n\t\t\t\t\t\t\t\t const char *fmt, va_list args);\nstatic bool is_valid_php_identifier(char *name);\n\n/*\n * FIXME -- this comment is quite misleading actually, which is not surprising\n * since it came verbatim from PL/pgSQL. Rewrite memory handling here someday\n * and remove it.\n *\n * This routine is a crock, and so is everyplace that calls it. The problem\n * is that the cached form of plphp functions/queries is allocated permanently\n * (mostly via malloc()) and never released until backend exit. Subsidiary\n * data structures such as fmgr info records therefore must live forever\n * as well. A better implementation would store all this stuff in a per-\n * function memory context that could be reclaimed at need. In the meantime,\n * fmgr_info_cxt must be called specifying TopMemoryContext so that whatever\n * it might allocate, and whatever the eventual function might allocate using\n * fn_mcxt, will live forever too.\n */\nstatic void\nperm_fmgr_info(Oid functionId, FmgrInfo *finfo)\n{\n\tfmgr_info_cxt(functionId, finfo, TopMemoryContext);\n}\n\n/*\n * sapi_plphp_write\n * \t\tCalled when PHP wants to write something to stdout.\n *\n * We just save the output in a StringInfo until the next Flush call.\n */\nstatic int\nsapi_plphp_write(const char *str, uint str_length TSRMLS_DC)\n{\n\tif (currmsg == NULL)\n\t\tcurrmsg = makeStringInfo();\n\n\tappendStringInfoString(currmsg, str);\n\n\treturn str_length;\n}\n\n/*\n * sapi_plphp_flush\n * \t\tCalled when PHP wants to flush stdout.\n *\n * The stupid PHP implementation calls write and follows with a Flush right\n * away -- a good implementation would write several times and flush when the\n * message is complete. To make the output look reasonable in Postgres, we\n * skip the flushing if the accumulated message does not end in a newline.\n */\nstatic void\nsapi_plphp_flush(void *sth)\n{\n\tif (currmsg != NULL)\n\t{\n\t\tAssert(currmsg->data != NULL);\n\n\t\tif (currmsg->data[currmsg->len - 1] == '\\n')\n\t\t{\n\t\t\t/*\n\t\t\t * remove the trailing newline because elog() inserts another\n\t\t\t * one\n\t\t\t */\n\t\t\tcurrmsg->data[currmsg->len - 1] = '\\0';\n\t\t}\n\t\telog(LOG, \"%s\", currmsg->data);\n\n\t\tpfree(currmsg->data);\n\t\tpfree(currmsg);\n\t\tcurrmsg = NULL;\n\t}\n\telse\n\t\telog(LOG, \"attempting to flush a NULL message\");\n}\n\nstatic int\nsapi_plphp_send_headers(sapi_headers_struct *sapi_headers TSRMLS_DC)\n{\n\treturn 1;\n}\n\nstatic void\nphp_plphp_log_messages(char *message)\n{\n\telog(LOG, \"plphp: %s\", message);\n}\n\n\nstatic sapi_module_struct plphp_sapi_module = {\n\t\"plphp\",\t\t\t\t\t/* name */\n\t\"PL/php PostgreSQL Handler\",/* pretty name */\n\n\tNULL,\t\t\t\t\t\t/* startup */\n\tphp_module_shutdown_wrapper,/* shutdown */\n\n\tNULL,\t\t\t\t\t\t/* activate */\n\tNULL,\t\t\t\t\t\t/* deactivate */\n\n\tsapi_plphp_write,\t\t\t/* unbuffered write */\n\tsapi_plphp_flush,\t\t\t/* flush */\n\tNULL,\t\t\t\t\t\t/* stat */\n\tNULL,\t\t\t\t\t\t/* getenv */\n\n\tphp_error,\t\t\t\t\t/* sapi_error(int, const char *, ...) */\n\n\tNULL,\t\t\t\t\t\t/* header handler */\n\tsapi_plphp_send_headers,\t/* send headers */\n\tNULL,\t\t\t\t\t\t/* send header */\n\n\tNULL,\t\t\t\t\t\t/* read POST */\n\tNULL,\t\t\t\t\t\t/* read cookies */\n\n\tNULL,\t\t\t\t\t\t/* register server variables */\n\tphp_plphp_log_messages,\t\t/* log message */\n\n\tNULL,\t\t\t\t\t\t/* Block interrupts */\n\tNULL,\t\t\t\t\t\t/* Unblock interrupts */\n\tSTANDARD_SAPI_MODULE_PROPERTIES\n};\n\n/*\n * plphp_init_all()\t\t- Initialize all\n *\n * XXX This is called each time a function is invoked.\n */\nstatic void\nplphp_init_all(void)\n{\n\t/* Execute postmaster-startup safe initialization */\n\tif (plphp_first_call)\n\t\tplphp_init();\n\n\t/*\n\t * Any other initialization that must be done each time a new\n\t * backend starts -- currently none.\n\t */\n}\n\n/*\n * This function must not be static, so that it can be used in\n * preload_libraries. If it is, it will be called by postmaster;\n * otherwise it will be called by each backend the first time a\n * function is called.\n */\nvoid\nplphp_init(void)\n{\n\tTSRMLS_FETCH();\n\t/* Do initialization only once */\n\tif (!plphp_first_call)\n\t\treturn;\n\n\t/*\n\t * Need a Pg try/catch block to prevent an initialization-\n\t * failure from bringing the whole server down.\n\t */\n\tPG_TRY();\n\t{\n\t\tzend_try\n\t\t{\n\t\t\t/*\n\t\t\t * XXX This is a hack -- we are replacing the error callback in an\n\t\t\t * invasive manner that should not be expected to work on future PHP\n\t\t\t * releases.\n\t\t\t */\n\t\t\tzend_error_cb = plphp_error_cb;\n\n\t\t\t/* Omit HTML tags from output */\n\t\t\tplphp_sapi_module.phpinfo_as_text = 1;\n\t\t\tsapi_startup(&plphp_sapi_module);\n\n\t\t\tif (php_module_startup(&plphp_sapi_module, NULL, 0) == FAILURE)\n\t\t\t\telog(ERROR, \"php_module_startup call failed\");\n\n\t\t\t/* php_module_startup changed it, so put it back */\n\t\t\tzend_error_cb = plphp_error_cb;\n\n\t\t\t/*\n\t\t\t * FIXME -- Figure out what this comment is supposed to mean:\n\t\t\t *\n\t\t\t * There is no way to see if we must call zend_ini_deactivate()\n\t\t\t * since we cannot check if EG(ini_directives) has been initialised\n\t\t\t * because the executor's constructor does not initialize it.\n\t\t\t * Apart from that there seems no need for zend_ini_deactivate() yet.\n\t\t\t * So we error out.\n\t\t\t */\n\n\t\t\t/* Init procedure cache */\n\t\t\tMAKE_STD_ZVAL(plphp_proc_array);\n\t\t\tarray_init(plphp_proc_array);\n\n\t\t\tzend_register_functions(\n#if PHP_MAJOR_VERSION == 5\n\t\t\t\t\t\t\t\t\tNULL,\n#endif\n\t\t\t\t\t\t\t\t\tspi_functions, NULL,\n\t\t\t\t\t\t\t\t\tMODULE_PERSISTENT TSRMLS_CC);\n\n\t\t\tPG(during_request_startup) = true;\n\n\t\t\t/* Set some defaults */\n\t\t\tSG(options) |= SAPI_OPTION_NO_CHDIR;\n\n\t\t\t/* Hard coded defaults which cannot be overwritten in the ini file */\n\t\t\tINI_HARDCODED(\"register_argc_argv\", \"0\");\n\t\t\tINI_HARDCODED(\"html_errors\", \"0\");\n\t\t\tINI_HARDCODED(\"implicit_flush\", \"1\");\n\t\t\tINI_HARDCODED(\"max_execution_time\", \"0\");\n\t\t\tINI_HARDCODED(\"max_input_time\", \"-1\");\n\n\t\t\t/*\n\t\t\t * Set memory limit to ridiculously high value. This helps the\n\t\t\t * server not to crash, because the PHP allocator has the really\n\t\t\t * stupid idea of calling exit() if the limit is exceeded.\n\t\t\t */\n\t\t\t{\n\t\t\t\tchar\tlimit[15];\n\n\t\t\t\tsnprintf(limit, sizeof(limit), \"%d\", 1 << 30);\n\t\t\t\tINI_HARDCODED(\"memory_limit\", limit);\n\t\t\t}\n\n\t\t\t/* tell the engine we're in non-html mode */\n\t\t\tzend_uv.html_errors = false;\n\n\t\t\t/* not initialized but needed for several options */\n\t\t\tCG(in_compilation) = false;\n\n\t\t\tEG(uninitialized_zval_ptr) = NULL;\n\n\t\t\tif (php_request_startup(TSRMLS_C) == FAILURE)\n\t\t\t{\n\t\t\t\tSG(headers_sent) = 1;\n\t\t\t\tSG(request_info).no_headers = 1;\n\t\t\t\t/* Use Postgres log */\n\t\t\t\telog(ERROR, \"php_request_startup call failed\");\n\t\t\t}\n\n\t\t\tCG(interactive) = false;\n\t\t\tPG(during_request_startup) = true;\n\n\t\t\t/* Register the resource for SPI_result */\n\t\t\tSPIres_rtype = zend_register_list_destructors_ex(php_SPIresult_destroy,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t NULL, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \"SPI result\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 0);\n\n\t\t\t/* Ok, we're done */\n\t\t\tplphp_first_call = false;\n\t\t}\n\t\tzend_catch\n\t\t{\n\t\t\tplphp_first_call = true;\n\t\t\tif (error_msg)\n\t\t\t{\n\t\t\t\tchar\tstr[1024];\n\n\t\t\t\tstrncpy(str, error_msg, sizeof(str));\n\t\t\t\tpfree(error_msg);\n\t\t\t\terror_msg = NULL;\n\t\t\t\telog(ERROR, \"fatal error during PL/php initialization: %s\",\n\t\t\t\t\t str);\n\t\t\t}\n\t\t\telse\n\t\t\t\telog(ERROR, \"fatal error during PL/php initialization\");\n\t\t}\n\t\tzend_end_try();\n\t}\n\tPG_CATCH();\n\t{\n\t\tPG_RE_THROW();\n\t}\n\tPG_END_TRY();\n}\n\n/*\n * plphp_call_handler\n *\n * The visible function of the PL interpreter. The PostgreSQL function manager\n * and trigger manager call this function for execution of php procedures.\n */\nDatum\nplphp_call_handler(PG_FUNCTION_ARGS)\n{\n\tDatum\t\tretval;\n\tTSRMLS_FETCH();\n\n\t/* Initialize interpreter */\n\tplphp_init_all();\n\n\tPG_TRY();\n\t{\n\t\t/* Connect to SPI manager */\n\t\tif (SPI_connect() != SPI_OK_CONNECT)\n\t\t\tereport(ERROR,\n\t\t\t\t\t(errcode(ERRCODE_CONNECTION_FAILURE),\n\t\t\t\t\t errmsg(\"could not connect to SPI manager\")));\n\n\t\tzend_try\n\t\t{\n\t\t\tplphp_proc_desc *desc;\n\n\t\t\t/* Clean up SRF state */\n\t\t\tcurrent_fcinfo = NULL;\n\n\t\t\t/* Redirect to the appropiate handler */\n\t\t\tif (CALLED_AS_TRIGGER(fcinfo))\n\t\t\t{\n\t\t\t\tdesc = plphp_compile_function(fcinfo->flinfo->fn_oid, true TSRMLS_CC);\n\n\t\t\t\t/* Activate PHP safe mode if needed */\n\t\t\t\t//PG(safe_mode) = desc->trusted;\n\n\t\t\t\tretval = plphp_trigger_handler(fcinfo, desc TSRMLS_CC);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tdesc = plphp_compile_function(fcinfo->flinfo->fn_oid, false TSRMLS_CC);\n\n\t\t\t\t/* Activate PHP safe mode if needed */\n\t\t\t\t//PG(safe_mode) = desc->trusted;\n\n\t\t\t\tif (desc->retset)\n\t\t\t\t\tretval = plphp_srf_handler(fcinfo, desc TSRMLS_CC);\n\t\t\t\telse\n\t\t\t\t\tretval = plphp_func_handler(fcinfo, desc TSRMLS_CC);\n\t\t\t}\n\t\t}\n\t\tzend_catch\n\t\t{\n\t\t\tREPORT_PHP_MEMUSAGE(\"reporting error\");\n\t\t\tif (error_msg)\n\t\t\t{\n\t\t\t\tchar\tstr[1024];\n\n\t\t\t\tstrncpy(str, error_msg, sizeof(str));\n\t\t\t\tpfree(error_msg);\n\t\t\t\terror_msg = NULL;\n\t\t\t\telog(ERROR, \"%s\", str);\n\t\t\t}\n\t\t\telse\n\t\t\t\telog(ERROR, \"fatal error\");\n\n\t\t\t/* not reached, but keep compiler quiet */\n\t\t\treturn 0;\n\t\t}\n\t\tzend_end_try();\n\t}\n\tPG_CATCH();\n\t{\n\t\tPG_RE_THROW();\n\t}\n\tPG_END_TRY();\n\n\treturn retval;\n}\n\n/*\n * plphp_validator\n *\n * \t\tValidator function for checking the function's syntax at creation\n * \t\ttime\n */\nDatum\nplphp_validator(PG_FUNCTION_ARGS)\n{\n\tOid\t\t\t\tfuncoid = PG_GETARG_OID(0);\n\tForm_pg_proc\tprocForm;\n\tHeapTuple\t\tprocTup;\n\tchar\t\t\ttmpname[32];\n\tchar\t\t\tfuncname[NAMEDATALEN];\n\tchar\t\t *tmpsrc = NULL,\n\t\t\t\t *prosrc;\n\tDatum\t\t\tprosrcdatum;\n\n\n\tTSRMLS_FETCH();\n\t/* Initialize interpreter */\n\tplphp_init_all();\n\n\tPG_TRY();\n\t{\n\t\tbool\t\t\tisnull;\n\t\t/* Grab the pg_proc tuple */\n\t\tprocTup = SearchSysCache(PROCOID,\n\t\t\t\t\t\t\t\t ObjectIdGetDatum(funcoid),\n\t\t\t\t\t\t\t\t 0, 0, 0);\n\t\tif (!HeapTupleIsValid(procTup))\n\t\t\telog(ERROR, \"cache lookup failed for function %u\", funcoid);\n\n\t\tprocForm = (Form_pg_proc) GETSTRUCT(procTup);\n\n\t\t/* Get the function source code */\n\t\tprosrcdatum = SysCacheGetAttr(PROCOID,\n\t\t\t\t\t\t\t\t\t procTup,\n\t\t\t\t\t\t\t\t\t Anum_pg_proc_prosrc,\n\t\t\t\t\t\t\t\t\t &isnull);\n\t\tif (isnull)\n\t\t\telog(ERROR, \"cache lookup yielded NULL prosrc\");\n\t\tprosrc = DatumGetCString(DirectFunctionCall1(textout,\n\t\t\t\t\t\t\t\t\t\t\t\t\t prosrcdatum));\n\n\t\t/* Get the function name, for the error message */\n\t\tStrNCpy(funcname, NameStr(procForm->proname), NAMEDATALEN);\n\n\t\t/* Let go of the pg_proc tuple */\n\t\tReleaseSysCache(procTup);\n\n\t\t/* Create a PHP function creation statement */\n\t\tsnprintf(tmpname, sizeof(tmpname), \"plphp_temp_%u\", funcoid);\n\t\ttmpsrc = (char *) palloc(strlen(prosrc) +\n\t\t\t\t\t\t\t\t strlen(tmpname) +\n\t\t\t\t\t\t\t\t strlen(\"function ($args, $argc){ } \"));\n\t\tsprintf(tmpsrc, \"function %s($args, $argc){%s}\",\n\t\t\t\ttmpname, prosrc);\n\n\t\tpfree(prosrc);\n\n\t\tzend_try\n\t\t{\n\t\t\t/*\n\t\t\t * Delete the function from the PHP function table, just in case it\n\t\t\t * already existed. This is quite unlikely, but still.\n\t\t\t */\n\t\t\tzend_hash_del(CG(function_table), tmpname, strlen(tmpname) + 1);\n\n\t\t\t/*\n\t\t\t * Let the user see the fireworks. If the function doesn't validate,\n\t\t\t * the ERROR will be raised and the function will not be created.\n\t\t\t */\n\t\t\tif (zend_eval_string(tmpsrc, NULL,\n\t\t\t\t\t\t\t\t \"plphp function temp source\" TSRMLS_CC) == FAILURE)\n\t\t\t\telog(ERROR, \"function \\\"%s\\\" does not validate\", funcname);\n\n\t\t\tpfree(tmpsrc);\n\t\t\ttmpsrc = NULL;\n\n\t\t\t/* Delete the newly-created function from the PHP function table. */\n\t\t\tzend_hash_del(CG(function_table), tmpname, strlen(tmpname) + 1);\n\t\t}\n\t\tzend_catch\n\t\t{\n\t\t\tif (tmpsrc != NULL)\n\t\t\t\tpfree(tmpsrc);\n\n\t\t\tif (error_msg)\n\t\t\t{\n\t\t\t\tchar\tstr[1024];\n\n\t\t\t\tStrNCpy(str, error_msg, sizeof(str));\n\t\t\t\tpfree(error_msg);\n\t\t\t\terror_msg = NULL;\n\t\t\t\telog(ERROR, \"function \\\"%s\\\" does not validate: %s\", funcname, str);\n\t\t\t}\n\t\t\telse\n\t\t\t\telog(ERROR, \"fatal error\");\n\n\t\t\t/* not reached, but keep compiler quiet */\n\t\t\treturn 0;\n\t\t}\n\t\tzend_end_try();\n\n\t\t/* The result of a validator is ignored */\n\t\tPG_RETURN_VOID();\n\t}\n\tPG_CATCH();\n\t{\n\t\tPG_RE_THROW();\n\t}\n\tPG_END_TRY();\n}\n\n/*\n * plphp_get_function_tupdesc\n *\n * \t\tReturns a TupleDesc of the function's return type.\n */\nstatic TupleDesc\nplphp_get_function_tupdesc(Oid result_type, Node *rsinfo)\n{\n\tif (result_type == RECORDOID)\n\t{\n\t\tReturnSetInfo *rs = (ReturnSetInfo *) rsinfo;\n\t\t/* We must get the information from call context */\n\t\tif (!rsinfo || !IsA(rsinfo, ReturnSetInfo) || rs->expectedDesc == NULL)\n\t\t\tereport(ERROR,\n\t\t\t\t\t(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),\n\t\t\t\t\t errmsg(\"function returning record called in context \"\n\t\t\t\t\t\t\t\"that cannot accept type record\")));\n\t\treturn rs->expectedDesc;\n\t}\n\telse\n\t\t/* ordinary composite type */\n\t\treturn lookup_rowtype_tupdesc(result_type, -1);\n}\n\n\n/*\n * Build the $_TD array for the trigger function.\n */\nstatic zval *\nplphp_trig_build_args(FunctionCallInfo fcinfo)\n{\n\tTriggerData\t *tdata;\n\tTupleDesc\t\ttupdesc;\n\tzval\t\t *retval;\n\tint\t\t\t\ti;\n\n\tMAKE_STD_ZVAL(retval);\n\tarray_init(retval);\n\n\ttdata = (TriggerData *) fcinfo->context;\n\ttupdesc = tdata->tg_relation->rd_att;\n\n\t/* The basic variables */\n\tadd_assoc_string(retval, \"name\", tdata->tg_trigger->tgname, 1);\n add_assoc_long(retval, \"relid\", tdata->tg_relation->rd_id);\n\tadd_assoc_string(retval, \"relname\", SPI_getrelname(tdata->tg_relation), 1);\n\tadd_assoc_string(retval, \"schemaname\", SPI_getnspname(tdata->tg_relation), 1);\n\n\t/* EVENT */\n\tif (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))\n\t\tadd_assoc_string(retval, \"event\", \"INSERT\", 1);\n\telse if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))\n\t\tadd_assoc_string(retval, \"event\", \"DELETE\", 1);\n\telse if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))\n\t\tadd_assoc_string(retval, \"event\", \"UPDATE\", 1);\n\telse\n\t\telog(ERROR, \"unknown firing event for trigger function\");\n\n\t/* NEW and OLD as appropiate */\n\tif (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))\n\t{\n\t\tif (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))\n\t\t{\n\t\t\tzval\t *hashref;\n\n\t\t\thashref = plphp_build_tuple_argument(tdata->tg_trigtuple, tupdesc);\n\t\t\tadd_assoc_zval(retval, \"new\", hashref);\n\t\t}\n\t\telse if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))\n\t\t{\n\t\t\tzval\t *hashref;\n\n\t\t\thashref = plphp_build_tuple_argument(tdata->tg_trigtuple, tupdesc);\n\t\t\tadd_assoc_zval(retval, \"old\", hashref);\n\t\t}\n\t\telse if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))\n\t\t{\n\t\t\tzval\t *hashref;\n\n\t\t\thashref = plphp_build_tuple_argument(tdata->tg_newtuple, tupdesc);\n\t\t\tadd_assoc_zval(retval, \"new\", hashref);\n\n\t\t\thashref = plphp_build_tuple_argument(tdata->tg_trigtuple, tupdesc);\n\t\t\tadd_assoc_zval(retval, \"old\", hashref);\n\t\t}\n\t\telse\n\t\t\telog(ERROR, \"unknown firing event for trigger function\");\n\t}\n\n\t/* ARGC and ARGS */\n\tadd_assoc_long(retval, \"argc\", tdata->tg_trigger->tgnargs);\n\n\tif (tdata->tg_trigger->tgnargs > 0)\n\t{\n\t\tzval\t *hashref;\n\n\t\tMAKE_STD_ZVAL(hashref);\n\t\tarray_init(hashref);\n\n\t\tfor (i = 0; i < tdata->tg_trigger->tgnargs; i++)\n\t\t\tadd_index_string(hashref, i, tdata->tg_trigger->tgargs[i], 1);\n\n\t\tzend_hash_update(retval->value.ht, \"args\", strlen(\"args\") + 1,\n\t\t\t\t\t\t (void *) &hashref, sizeof(zval *), NULL);\n\t}\n\n\t/* WHEN */\n\tif (TRIGGER_FIRED_BEFORE(tdata->tg_event))\n\t\tadd_assoc_string(retval, \"when\", \"BEFORE\", 1);\n\telse if (TRIGGER_FIRED_AFTER(tdata->tg_event))\n\t\tadd_assoc_string(retval, \"when\", \"AFTER\", 1);\n\telse\n\t\telog(ERROR, \"unknown firing time for trigger function\");\n\n\t/* LEVEL */\n\tif (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))\n\t\tadd_assoc_string(retval, \"level\", \"ROW\", 1);\n\telse if (TRIGGER_FIRED_FOR_STATEMENT(tdata->tg_event))\n\t\tadd_assoc_string(retval, \"level\", \"STATEMENT\", 1);\n\telse\n\t\telog(ERROR, \"unknown firing level for trigger function\");\n\n\treturn retval;\n}\n\n/*\n * plphp_trigger_handler\n * \t\tHandler for trigger function calls\n */\nstatic Datum\nplphp_trigger_handler(FunctionCallInfo fcinfo, plphp_proc_desc *desc TSRMLS_DC)\n{\n\tDatum\t\tretval = 0;\n\tchar\t *srv;\n\tzval\t *phpret,\n\t\t\t *zTrigData;\n\tTriggerData *trigdata;\n\n\tREPORT_PHP_MEMUSAGE(\"going to build the trigger arg\");\n\n\tzTrigData = plphp_trig_build_args(fcinfo);\n\n\tREPORT_PHP_MEMUSAGE(\"going to call the trigger function\");\n\n\tphpret = plphp_call_php_trig(desc, fcinfo, zTrigData TSRMLS_CC);\n\tif (!phpret)\n\t\telog(ERROR, \"error during execution of function %s\", desc->proname);\n\n\tREPORT_PHP_MEMUSAGE(\"trigger called, going to build the return value\");\n\n\t/*\n\t * Disconnect from SPI manager and then create the return values datum (if\n\t * the input function does a palloc for it this must not be allocated in\n\t * the SPI memory context because SPI_finish would free it).\n\t */\n\tif (SPI_finish() != SPI_OK_FINISH)\n\t\tereport(ERROR,\n\t\t\t\t(errcode(ERRCODE_CONNECTION_DOES_NOT_EXIST),\n\t\t\t\t errmsg(\"could not disconnect from SPI manager\")));\n\n\ttrigdata = (TriggerData *) fcinfo->context;\n\n\tif (zTrigData->type != IS_ARRAY)\n\t\telog(ERROR, \"$_TD is not an array\");\n\t\t\t \n\t/*\n\t * In a BEFORE trigger, compute the return value. In an AFTER trigger\n\t * it'll be ignored, so don't bother.\n\t */\n\tif (TRIGGER_FIRED_BEFORE(trigdata->tg_event))\n\t{\n\t\tswitch (phpret->type)\n\t\t{\n\t\t\tcase IS_STRING:\n\t\t\t\tsrv = phpret->value.str.val;\n\t\t\t\tif (strcasecmp(srv, \"SKIP\") == 0)\n\t\t\t\t{\n\t\t\t\t\t/* do nothing */\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\telse if (strcasecmp(srv, \"MODIFY\") == 0)\n\t\t\t\t{\n\t\t\t\t\tif (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event) ||\n\t\t\t\t\t\tTRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))\n\t\t\t\t\t\tretval = PointerGetDatum(plphp_modify_tuple(zTrigData,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttrigdata));\n\t\t\t\t\telse if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))\n\t\t\t\t\t\tereport(ERROR,\n\t\t\t\t\t\t\t\t(errcode(ERRCODE_SYNTAX_ERROR),\n\t\t\t\t\t\t\t\t errmsg(\"on delete trigger can not modify the the return tuple\")));\n\t\t\t\t\telse\n\t\t\t\t\t\telog(ERROR, \"unknown event in trigger function\");\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tereport(ERROR,\n\t\t\t\t\t\t\t(errcode(ERRCODE_SYNTAX_ERROR),\n\t\t\t\t\t\t\t errmsg(\"expected trigger function to return NULL, 'SKIP' or 'MODIFY'\")));\n\t\t\t\tbreak;\n\t\t\tcase IS_NULL:\n\t\t\t\tif (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event) ||\n\t\t\t\t\tTRIGGER_FIRED_BY_DELETE(trigdata->tg_event))\n\t\t\t\t\tretval = (Datum) trigdata->tg_trigtuple;\n\t\t\t\telse if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))\n\t\t\t\t\tretval = (Datum) trigdata->tg_newtuple;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tereport(ERROR,\n\t\t\t\t\t\t(errcode(ERRCODE_SYNTAX_ERROR),\n\t\t\t\t\t\t errmsg(\"expected trigger function to return NULL, 'SKIP' or 'MODIFY'\")));\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tREPORT_PHP_MEMUSAGE(\"freeing some variables\");\n\n\tzval_dtor(zTrigData);\n\tzval_dtor(phpret);\n\n\tFREE_ZVAL(phpret);\n\tFREE_ZVAL(zTrigData);\n\n\tREPORT_PHP_MEMUSAGE(\"trigger call done\");\n\n\treturn retval;\n}\n\n/*\n * plphp_func_handler\n * \t\tHandler for regular function calls\n */\nstatic Datum\nplphp_func_handler(FunctionCallInfo fcinfo, plphp_proc_desc *desc TSRMLS_DC)\n{\n\tzval\t *phpret = NULL;\n\tDatum\t\tretval;\n\tchar\t *retvalbuffer = NULL;\n\n\t/* SRFs are handled separately */\n\tAssert(!desc->retset);\n\n\t/* Call the PHP function. */\n\tphpret = plphp_call_php_func(desc, fcinfo TSRMLS_CC);\n\tif (!phpret)\n\t\telog(ERROR, \"error during execution of function %s\", desc->proname);\n\n\tREPORT_PHP_MEMUSAGE(\"function invoked\");\n\n\t/* Basic datatype checks */\n\tif ((desc->ret_type & PL_ARRAY) && phpret->type != IS_ARRAY)\n\t\tereport(ERROR,\n\t\t\t\t(errcode(ERRCODE_DATATYPE_MISMATCH),\n\t\t\t\t errmsg(\"function declared to return array must return an array\")));\n\tif ((desc->ret_type & PL_TUPLE) && phpret->type != IS_ARRAY)\n\t\tereport(ERROR,\n\t\t\t\t(errcode(ERRCODE_DATATYPE_MISMATCH),\n\t\t\t\t errmsg(\"function declared to return tuple must return an array\")));\n\n\t/*\n\t * Disconnect from SPI manager and then create the return values datum (if\n\t * the input function does a palloc for it this must not be allocated in\n\t * the SPI memory context because SPI_finish would free it).\n\t */\n\tif (SPI_finish() != SPI_OK_FINISH)\n\t\tereport(ERROR,\n\t\t\t\t(errcode(ERRCODE_CONNECTION_DOES_NOT_EXIST),\n\t\t\t\t errmsg(\"could not disconnect from SPI manager\")));\n\tretval = (Datum) 0;\n\n\tif (desc->ret_type & PL_PSEUDO)\n\t{\n\t\tHeapTuple\tretTypeTup;\n\t\tForm_pg_type retTypeStruct;\n\n\t\tretTypeTup = SearchSysCache(TYPEOID,\n\t\t\t\t\t\t\t\t\tObjectIdGetDatum(get_fn_expr_rettype(fcinfo->flinfo)),\n\t\t\t\t\t\t\t\t\t0, 0, 0);\n\t\tretTypeStruct = (Form_pg_type) GETSTRUCT(retTypeTup);\n\t\tperm_fmgr_info(retTypeStruct->typinput, &(desc->result_in_func));\n\t\tdesc->result_typioparam = retTypeStruct->typelem;\n\t\tReleaseSysCache(retTypeTup);\n\t}\n\n\tif (phpret)\n\t{\n\t\tswitch (Z_TYPE_P(phpret))\n\t\t{\n\t\t\tcase IS_NULL:\n\t\t\t\tfcinfo->isnull = true;\n\t\t\t\tbreak;\n\t\t\tcase IS_BOOL:\n\t\t\tcase IS_DOUBLE:\n\t\t\tcase IS_LONG:\n\t\t\tcase IS_STRING:\n\t\t\t\tretvalbuffer = plphp_zval_get_cstring(phpret, false, false);\n\t\t\t\tretval = CStringGetDatum(retvalbuffer);\n\t\t\t\tbreak;\n\t\t\tcase IS_ARRAY:\n\t\t\t\tif (desc->ret_type & PL_ARRAY)\n\t\t\t\t{\n\t\t\t\t\tretvalbuffer = plphp_convert_to_pg_array(phpret);\n\t\t\t\t\tretval = CStringGetDatum(retvalbuffer);\n\t\t\t\t}\n\t\t\t\telse if (desc->ret_type & PL_TUPLE)\n\t\t\t\t{\n\t\t\t\t\tTupleDesc\ttd;\n\t\t\t\t\tHeapTuple\ttup;\n\n\t\t\t\t\tif (desc->ret_type & PL_PSEUDO)\n\t\t\t\t\t\ttd = plphp_get_function_tupdesc(desc->ret_oid,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tfcinfo->resultinfo);\n\t\t\t\t\telse\n\t\t\t\t\t\ttd = lookup_rowtype_tupdesc(desc->ret_oid, (int32) -1);\n\n\t\t\t\t\tif (!td)\n\t\t\t\t\t\telog(ERROR, \"no TupleDesc info available\");\n\n\t\t\t\t\ttup = plphp_htup_from_zval(phpret, td);\n\t\t\t\t\tretval = HeapTupleGetDatum(tup);\n\t\t\t\t\tReleaseTupleDesc(td);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\t/* FIXME -- should return the thing as a string? */\n\t\t\t\t\telog(ERROR, \"this plphp function cannot return arrays\");\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\telog(WARNING,\n\t\t\t\t\t \"plphp functions cannot return type %i\",\n\t\t\t\t\t phpret->type);\n\t\t\t\tfcinfo->isnull = true;\n\t\t\t\tbreak;\n\t\t}\n\t}\n\telse\n\t{\n\t\tfcinfo->isnull = true;\n\t\tretval = (Datum) 0;\n\t}\n\n\tif (!fcinfo->isnull && !(desc->ret_type & PL_TUPLE))\n\t{\n\t\tretval = FunctionCall3(&desc->result_in_func,\n\t\t\t\t\t\t\t PointerGetDatum(retvalbuffer),\n\t\t\t\t\t\t\t ObjectIdGetDatum(desc->result_typioparam),\n\t\t\t\t\t\t\t Int32GetDatum(-1));\n\t\tpfree(retvalbuffer);\n\t}\n\n\tREPORT_PHP_MEMUSAGE(\"finished calling user function\");\n\n\treturn retval;\n}\n\n/*\n * plphp_srf_handler\n * \t\tInvoke a SRF\n */\nstatic Datum\nplphp_srf_handler(FunctionCallInfo fcinfo, plphp_proc_desc *desc TSRMLS_DC)\n{\n\tReturnSetInfo *rsi = (ReturnSetInfo *) fcinfo->resultinfo;\n\tTupleDesc\ttupdesc;\n\tzval\t *phpret;\n\tMemoryContext\toldcxt;\n\n\tAssert(desc->retset);\n\n\tcurrent_fcinfo = fcinfo;\n\tcurrent_tuplestore = NULL;\n\n\t/* Check context before allowing the call to go through */\n\tif (!rsi || !IsA(rsi, ReturnSetInfo) ||\n\t\t(rsi->allowedModes & SFRM_Materialize) == 0 ||\n\t\trsi->expectedDesc == NULL)\n\t\tereport(ERROR,\n\t\t\t\t(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),\n\t\t\t\t errmsg(\"set-valued function called in context that \"\n\t\t\t\t\t\t\"cannot accept a set\")));\n\n\t/*\n\t * Fetch the function's tuple descriptor. This will return NULL in the\n\t * case of a scalar return type, in which case we will copy the TupleDesc\n\t * from the ReturnSetInfo.\n\t */\n\tget_call_result_type(fcinfo, NULL, &tupdesc);\n\tif (tupdesc == NULL)\n\t\ttupdesc = rsi->expectedDesc;\n\n\t/*\n\t * If the expectedDesc is NULL, bail out, because most likely it's using\n\t * IN/OUT parameters.\n\t */\n\tif (tupdesc == NULL)\n\t\tereport(ERROR,\n\t\t\t\t(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),\n\t\t\t\t errmsg(\"cannot use IN/OUT parameters in PL/php\")));\n\n\toldcxt = MemoryContextSwitchTo(rsi->econtext->ecxt_per_query_memory);\n\n\t/* This context is reset once per row in return_next */\n\tcurrent_memcxt = AllocSetContextCreate(CurTransactionContext,\n\t\t\t\t\t\t\t\t\t\t \"PL/php SRF context\",\n\t\t\t\t\t\t\t\t\t\t ALLOCSET_DEFAULT_MINSIZE,\n\t\t\t\t\t\t\t\t\t\t ALLOCSET_DEFAULT_INITSIZE,\n\t\t\t\t\t\t\t\t\t\t ALLOCSET_DEFAULT_MAXSIZE);\n\n\t/* Tuple descriptor and AttInMetadata for return_next */\n\tcurrent_tupledesc = CreateTupleDescCopy(tupdesc);\n\tcurrent_attinmeta = TupleDescGetAttInMetadata(current_tupledesc);\n\n\t/*\n\t * Call the PHP function. The user code must call return_next, which will\n\t * create and populate the tuplestore appropiately.\n\t */\n\tphpret = plphp_call_php_func(desc, fcinfo TSRMLS_CC);\n\n\t/* We don't use the return value */\n\tzval_dtor(phpret);\n\n\t/* Close the SPI connection */\n\tif (SPI_finish() != SPI_OK_FINISH)\n\t\tereport(ERROR,\n\t\t\t\t(errcode(ERRCODE_CONNECTION_DOES_NOT_EXIST),\n\t\t\t\t errmsg(\"could not disconnect from SPI manager\")));\n\n\t/* Now prepare the return values. */\n\trsi->returnMode = SFRM_Materialize;\n\n\tif (current_tuplestore)\n\t{\n\t\trsi->setResult = current_tuplestore;\n\t\trsi->setDesc = current_tupledesc;\n\t}\n\n\tMemoryContextDelete(current_memcxt);\n\tcurrent_memcxt = NULL;\n\tcurrent_tupledesc = NULL;\n\tcurrent_attinmeta = NULL;\n\n\tMemoryContextSwitchTo(oldcxt);\n\n\t/* All done */\n\treturn (Datum) 0;\n}\n\n/*\n * plphp_compile_function\n *\n * \t\tCompile (or hopefully just look up) function\n */\nstatic plphp_proc_desc *\nplphp_compile_function(Oid fnoid, bool is_trigger TSRMLS_DC)\n{\n\tHeapTuple\tprocTup;\n\tForm_pg_proc procStruct;\n\tchar\t\tinternal_proname[64];\n\tplphp_proc_desc *prodesc = NULL;\n\tint\t\t\ti;\n\tchar\t *pointer = NULL;\n\n\t/*\n\t * We'll need the pg_proc tuple in any case... \n\t */\n\tprocTup = SearchSysCache(PROCOID, ObjectIdGetDatum(fnoid), 0, 0, 0);\n\tif (!HeapTupleIsValid(procTup))\n\t\telog(ERROR, \"cache lookup failed for function %u\", fnoid);\n\tprocStruct = (Form_pg_proc) GETSTRUCT(procTup);\n\n\t/*\n\t * Build our internal procedure name from the function's Oid\n\t */\n\tif (is_trigger)\n\t\tsnprintf(internal_proname, sizeof(internal_proname),\n\t\t\t\t \"plphp_proc_%u_trigger\", fnoid);\n\telse\n\t\tsnprintf(internal_proname, sizeof(internal_proname),\n\t\t\t\t \"plphp_proc_%u\", fnoid);\n\n\t/*\n\t * Look up the internal proc name in the hashtable\n\t */\n\tpointer = plphp_zval_get_cstring(plphp_array_get_elem(plphp_proc_array,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t internal_proname),\n\t\t\t\t\t\t\t\t\t false, true);\n\tif (pointer)\n\t{\n\t\tbool uptodate;\n\t\tsscanf(pointer, \"%p\", &prodesc);\n\n#ifdef PG_VERSION_83_COMPAT\n\t\t/* PostgreSQL 8.3 doesn't allow calling GetCmin if a tuple doesn't\n\t\t * originate from the current transaction.\n\t\t */\n\t\tuptodate =\n\t\t\t(prodesc->fn_xmin == HeapTupleHeaderGetXmin(procTup->t_data) &&\n\t\t\t prodesc->fn_cmin == HeapTupleHeaderGetRawCommandId(procTup->t_data));\n\n#else\n\t\tuptodate =\n\t\t\t(prodesc->fn_xmin == HeapTupleHeaderGetXmin(procTup->t_data) &&\n\t\t\t prodesc->fn_cmin == HeapTupleHeaderGetCmin(procTup->t_data));\n\n#endif\n\n\n\t\t/* We need to delete the old entry */\n\t\tif (!uptodate)\n\t\t{\n\t\t\t/*\n\t\t\t * FIXME -- use a per-function memory context and fix this\n\t\t\t * stuff for good\n\t\t\t */\n\t\t\tfree(prodesc->proname);\n\t\t\tfree(prodesc);\n\t\t\tprodesc = NULL;\n\t\t}\n\t}\n\n\tif (prodesc == NULL)\n\t{\n\t\tHeapTuple\tlangTup;\n\t\tForm_pg_language langStruct;\n\t\tDatum\t\tprosrcdatum;\n\t\tbool\t\tisnull;\n\t\tchar\t *proc_source;\n\t\tchar\t *complete_proc_source;\n\t\tchar\t *pointer = NULL;\n\t\tchar\t *aliases = NULL;\n\t\tchar\t *out_aliases = NULL;\n\t\tchar\t *out_return_str = NULL;\n\t\tint16\ttyplen;\n\t\tchar\ttypbyval,\n\t\t\t\ttypalign,\n\t\t\t\ttyptype,\n\t\t\t\ttypdelim;\n\t\tOid\t\ttypioparam,\n\t\t\t\ttypinput,\n\t\t\t\ttypoutput;\n\t\t/*\n\t\t * Allocate a new procedure description block\n\t\t */\n\t\tprodesc = (plphp_proc_desc *) malloc(sizeof(plphp_proc_desc));\n\t\tif (!prodesc)\n\t\t\tereport(ERROR,\n\t\t\t\t\t(errcode(ERRCODE_OUT_OF_MEMORY),\n\t\t\t\t\t errmsg(\"out of memory\")));\n\n\t\tMemSet(prodesc, 0, sizeof(plphp_proc_desc));\n\t\tprodesc->proname = strdup(internal_proname);\n\t\tif (!prodesc->proname)\n\t\t{\n\t\t\tfree(prodesc);\n\t\t\tereport(ERROR,\n\t\t\t\t\t(errcode(ERRCODE_OUT_OF_MEMORY),\n\t\t\t\t\t errmsg(\"out of memory\")));\n\t\t}\n\n\t\tprodesc->fn_xmin = HeapTupleHeaderGetXmin(procTup->t_data);\n\n#ifdef PG_VERSION_83_COMPAT\n\t\t/* PostgreSQL 8.3 doesn't allow calling GetCmin if a tuple doesn't\n\t\t * originate from the current transaction.\n\t\t */\n\t\tprodesc->fn_cmin = HeapTupleHeaderGetRawCommandId(procTup->t_data);\n\n#else\n\t\tprodesc->fn_cmin = HeapTupleHeaderGetCmin(procTup->t_data);\n\n#endif\n\n\t\t/*\n\t\t * Look up the pg_language tuple by Oid\n\t\t */\n\t\tlangTup = SearchSysCache(LANGOID,\n\t\t\t\t\t\t\t\t ObjectIdGetDatum(procStruct->prolang),\n\t\t\t\t\t\t\t\t 0, 0, 0);\n\t\tif (!HeapTupleIsValid(langTup))\n\t\t{\n\t\t\tfree(prodesc->proname);\n\t\t\tfree(prodesc);\n\t\t\telog(ERROR, \"cache lookup failed for language %u\",\n\t\t\t\t\t procStruct->prolang);\n\t\t}\n\t\tlangStruct = (Form_pg_language) GETSTRUCT(langTup);\n\t\tprodesc->trusted = langStruct->lanpltrusted;\n\t\tReleaseSysCache(langTup);\n\n\t\t/*\n\t\t * Get the required information for input conversion of the return\n\t\t * value, and output conversion of the procedure's arguments.\n\t\t */\n\t\tif (!is_trigger)\n\t\t{\n\t\t\tchar **argnames;\n\t\t\tchar *argmodes;\n\t\t\tOid *argtypes;\n\t\t\tint32\talias_str_end,\n\t\t\t\t\tout_str_end;\n\n\t\t\ttyptype = get_typtype(procStruct->prorettype);\n\t\t\tget_type_io_data(procStruct->prorettype,\n\t\t\t\t\t\t\t IOFunc_input,\n\t\t\t\t\t\t\t &typlen,\n\t\t\t\t\t\t\t &typbyval,\n\t\t\t\t\t\t\t &typalign,\n\t\t\t\t\t\t\t &typdelim,\n\t\t\t\t\t\t\t &typioparam,\n\t\t\t\t\t\t\t &typinput);\n\n\t\t\t/*\n\t\t\t * Disallow pseudotype result, except:\n\t\t\t * VOID, RECORD, ANYELEMENT or ANYARRAY\n\t\t\t */\n\t\t\tif (typtype == TYPTYPE_PSEUDO)\n\t\t\t{\n\t\t\t\tif ((procStruct->prorettype == VOIDOID) ||\n\t\t\t\t\t(procStruct->prorettype == RECORDOID) ||\n\t\t\t\t\t(procStruct->prorettype == ANYELEMENTOID) ||\n\t\t\t\t\t(procStruct->prorettype == ANYARRAYOID))\n\t\t\t\t{\n\t\t\t\t\t/* okay */\n\t\t\t\t\tprodesc->ret_type |= PL_PSEUDO;\n\t\t\t\t}\n\t\t\t\telse if (procStruct->prorettype == TRIGGEROID)\n\t\t\t\t{\n\t\t\t\t\tfree(prodesc->proname);\n\t\t\t\t\tfree(prodesc);\n\t\t\t\t\tereport(ERROR,\n\t\t\t\t\t\t\t(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),\n\t\t\t\t\t\t\t errmsg(\"trigger functions may only be called \"\n\t\t\t\t\t\t\t\t\t\"as triggers\")));\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tfree(prodesc->proname);\n\t\t\t\t\tfree(prodesc);\n\t\t\t\t\tereport(ERROR,\n\t\t\t\t\t\t\t(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),\n\t\t\t\t\t\t\t errmsg(\"plphp functions cannot return type %s\",\n\t\t\t\t\t\t\t\t\tformat_type_be(procStruct->prorettype))));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tprodesc->ret_oid = procStruct->prorettype;\n\t\t\tprodesc->retset = procStruct->proretset;\n\n\t\t\tif (typtype == TYPTYPE_COMPOSITE ||\n\t\t\t\tprocStruct->prorettype == RECORDOID)\n\t\t\t{\n\t\t\t\tprodesc->ret_type |= PL_TUPLE;\n\t\t\t}\n\n\t\t\tif (procStruct->prorettype == ANYARRAYOID)\n\t\t\t\tprodesc->ret_type |= PL_ARRAY;\n\t\t\telse\n\t\t\t{\n\t\t\t\t/* function returns a normal (declared) array */\n\t\t\t\tif (typlen == -1 && get_element_type(procStruct->prorettype))\n\t\t\t\t\tprodesc->ret_type |= PL_ARRAY;\n\t\t\t}\n\n\t\t\tperm_fmgr_info(typinput, &(prodesc->result_in_func));\n\t\t\tprodesc->result_typioparam = typioparam;\n\n\t\t\t/* Deal with named arguments, OUT, IN/OUT and TABLE arguments */\n\n\t\t\tprodesc->n_total_args = get_func_arg_info(procTup, &argtypes, \n\t\t\t\t\t\t\t\t\t\t\t \t\t &argnames, &argmodes);\n\t\t\tprodesc->n_out_args = 0;\n\t\t\tprodesc->n_mixed_args = 0;\n\t\t\t\n\t\t\tprodesc->args_out_tupdesc = NULL;\n\t\t\tout_return_str = NULL;\n\t\t\talias_str_end = out_str_end = 0;\n\n\t\t\t/* Count the number of OUT arguments. Need to do this out of the\n\t\t\t * main loop, to correctly determine the object to return for OUT args\n\t\t */\n\t\t\tif (argmodes)\n\t\t\t\tfor (i = 0; i < prodesc->n_total_args; i++)\n\t\t\t\t{\n\t\t\t\t\tswitch(argmodes[i])\n\t\t\t\t\t{\n\t\t\t\t\t\tcase PROARGMODE_OUT: \n\t\t\t\t\t\t\tprodesc->n_out_args++;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase PROARGMODE_INOUT: \n\t\t\t\t\t\t\tprodesc->n_mixed_args++;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase PROARGMODE_IN:\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase PROARGMODE_TABLE:\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase PROARGMODE_VARIADIC:\n\t\t\t\t\t\t\telog(ERROR, \"VARIADIC arguments are not supported\");\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\telog(ERROR, \"Unsupported type %c for argument no %d\",\n\t\t\t\t\t\t\t\t argmodes[i], i);\n\t\t\t\t\t}\t\t\t\t\t\n\t\t\t\t\tprodesc->arg_argmode[i] = argmodes[i];\n\t\t\t\t}\n\t\t\telse\n\t\t\t\tMemSet(prodesc->arg_argmode, PROARGMODE_IN,\n\t\t\t\t \t prodesc->n_total_args);\n\n\t\t\t/* Allocate memory for argument names unless all of them are OUT*/\n\t\t\tif (argnames && prodesc->n_total_args > 0)\n\t\t\t\taliases = palloc((NAMEDATALEN + 32) * prodesc->n_total_args);\n\t\t\t\n\t\t\t/* Main argument processing loop. */\n\t\t\tfor (i = 0; i < prodesc->n_total_args; i++)\n\t\t\t{\n\t\t\t\tprodesc->arg_typtype[i] = get_typtype(argtypes[i]);\n\t\t\t\tif (prodesc->arg_typtype[i] != TYPTYPE_COMPOSITE)\n\t\t\t\t{\t\t\t\t\t\t\t\n\t\t\t\t\tget_type_io_data(argtypes[i],\n\t\t\t\t\t\t\t\t\t IOFunc_output,\n\t\t\t\t\t\t\t\t\t &typlen,\n\t\t\t\t\t\t\t\t\t &typbyval,\n\t\t\t\t\t\t\t\t\t &typalign,\n\t\t\t\t\t\t\t\t\t &typdelim,\n\t\t\t\t\t\t\t\t\t &typioparam,\n\t\t\t\t\t\t\t\t\t &typoutput);\n\t\t\t\t\tperm_fmgr_info(typoutput, &(prodesc->arg_out_func[i]));\n\t\t\t\t\tprodesc->arg_typioparam[i] = typioparam;\n\t\t\t\t}\n\t\t\t\tif (aliases && argnames[i][0] != '\\0')\n\t\t\t\t{\n\t\t\t\t\tif (!is_valid_php_identifier(argnames[i]))\n\t\t\t\t\t\telog(ERROR, \"\\\"%s\\\" can not be used as a PHP variable name\",\n\t\t\t\t\t\t\t argnames[i]);\n\t\t\t\t\t/* Deal with argument name */\n\t\t\t\t\talias_str_end += snprintf(aliases + alias_str_end,\n\t\t\t\t\t\t\t\t\t\t \t NAMEDATALEN + 32,\n\t\t\t\t\t\t\t\t \t\t \t \" $%s = &$args[%d];\", \n\t\t\t\t\t\t\t\t\t\t\t argnames[i], i);\n\t\t\t\t}\n\t\t\t\tif ((prodesc->arg_argmode[i] == PROARGMODE_OUT ||\n\t\t\t\t\t prodesc->arg_argmode[i] == PROARGMODE_INOUT) && !prodesc->retset)\n\t\t\t\t{\n\t\t\t\t\t/* Initialiazation for OUT arguments aliases */\n\t\t\t\t\tif (!out_return_str)\n\t\t\t\t\t{\n\t\t\t\t\t\t/* Generate return statment for a single OUT argument */\n\t\t\t\t\t\tout_return_str = palloc(NAMEDATALEN + 32);\n\t\t\t\t\t\tif (prodesc->n_out_args + prodesc->n_mixed_args == 1)\n\t\t\t\t\t\t\tsnprintf(out_return_str, NAMEDATALEN + 32,\n\t\t\t\t\t\t\t\t\t \"return $args[%d];\", i);\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t/* PL/PHP deals with multiple OUT arguments by\n\t\t\t\t\t\t\t * internally creating an array of references to them.\n\t\t\t\t\t\t\t * E.g. out_fn(a out integer, b out integer )\n\t\t\t\t\t\t\t * translates into:\n\t\t\t\t\t\t\t * $_plphp_ret_out_fn_1234=array(a => $&a,b => $&b);\n\t\t\t\t\t\t\t */\n\t\t\t\t\t\t\tchar plphp_ret_array_name[NAMEDATALEN + 16];\n\n\t\t\t\t\t\t\tint array_namelen = snprintf(plphp_ret_array_name,\n\t\t\t\t\t\t\t \t\t\t\t\t\t \t NAMEDATALEN + 16,\n\t\t\t\t\t\t\t\t\t \t\t\t\t \t \"_plphp_ret_%s\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t \t internal_proname);\n\n\t\t\t\t\t\t\tsnprintf(out_return_str, array_namelen + 16,\n\t\t\t\t\t\t\t\t\t\"return $%s;\", plphp_ret_array_name);\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t/* 2 NAMEDATALEN for argument names, additional\n\t\t\t\t\t\t\t * 16 bytes per each argument for assignment string,\n\t\t\t\t\t\t\t * additional 16 bytes for the 'array' prefix string.\n\t\t\t\t\t\t\t */\t\t\n\t\t\t\t\t\t\tout_aliases = palloc(array_namelen +\n\t\t\t\t\t\t\t\t\t\t\t\t (prodesc->n_out_args + \n\t\t\t\t\t\t\t\t\t\t\t\t prodesc->n_mixed_args) *\n\t\t\t\t\t\t\t\t\t\t\t\t (2*NAMEDATALEN + 16) + 16);\n\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tout_str_end = snprintf(out_aliases,\n\t\t\t\t\t\t\t \t\t\t\t\t array_namelen +\n\t\t\t\t\t\t\t\t\t\t\t\t (2 * NAMEDATALEN + 16) + 16,\n\t\t\t\t\t\t\t\t\t\t\t\t \"$%s = array(&$args[%d]\", \n\t\t\t\t\t\t\t\t\t\t\t\t plphp_ret_array_name, i);\n\t\t\t\t\t\t\t\t\t\t\t\t \n\t\t\t\t\t\t}\n\t\t\t\t\t} \n\t\t\t\t\telse if (out_aliases)\n\t\t\t\t\t{\n\t\t\t\t\t /* Add new elements to the array of aliases for OUT args */\n\t\t\t\t\t\tAssert(prodesc->n_out_args + prodesc->n_mixed_args > 1);\n\t\t\t\t\t\tout_str_end += snprintf(out_aliases+out_str_end,\n\t\t\t\t\t\t\t\t\t\t\t\t2 * NAMEDATALEN + 16,\n\t\t\t\t\t\t\t\t\t\t\t\t\",&$args[%d]\", i);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (aliases)\n\t\t\t\tstrcat(aliases, \" \");\n\t\t\tif (out_aliases)\n\t\t\t\tstrcat(out_aliases, \")\");\n\t\t}\n\n\t\t/*\n\t\t * Create the text of the PHP function. We do not use the same\n\t\t * function name, because that would prevent function overloading.\n\t\t * Sadly this also prevents PL/php functions from calling each other\n\t\t * easily.\n\t\t */\n\t\tprosrcdatum = SysCacheGetAttr(PROCOID, procTup,\n\t\t\t\t\t\t\t\t\t Anum_pg_proc_prosrc, &isnull);\n\t\tif (isnull)\n\t\t\telog(ERROR, \"cache lookup yielded NULL prosrc\");\n\n\t\tproc_source = DatumGetCString(DirectFunctionCall1(textout,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t prosrcdatum));\n\n\t\t/* Create the procedure in the interpreter */\n\t\tcomplete_proc_source =\n\t\t\t(char *) palloc(strlen(proc_source) +\n\t\t\t\t\t\t\tstrlen(internal_proname) +\n\t\t\t\t\t\t\t(aliases ? strlen(aliases) : 0) + \n\t\t\t\t\t\t\t(out_aliases ? strlen(out_aliases) : 0) +\n\t\t\t\t\t\t\tstrlen(\"function ($args, $argc){ } \") + 32 +\n\t\t\t\t\t\t\t(out_return_str ? strlen(out_return_str) : 0));\n\n\t\t/* XXX Is this usage of sprintf safe? */\n\t\tif (is_trigger)\n\t\t\tsprintf(complete_proc_source, \"function %s($_TD){%s}\",\n\t\t\t\t\tinternal_proname, proc_source);\n\t\telse\n\t\t\tsprintf(complete_proc_source, \n\t\t\t\t\t\"function %s($args, $argc){%s %s;%s; %s}\",\n\t\t\t\t\tinternal_proname, \n\t\t\t\t\taliases ? aliases : \"\",\n\t\t\t\t\tout_aliases ? out_aliases : \"\",\n\t\t\t\t\tproc_source, \n\t\t\t\t\tout_return_str? out_return_str : \"\");\n\t\t\t\t\t\n\t\telog(LOG, \"complete_proc_source = %s\",\n\t\t\t\t \t complete_proc_source);\n\t\t\t\t\n\t\tzend_hash_del(CG(function_table), prodesc->proname,\n\t\t\t\t\t strlen(prodesc->proname) + 1);\n\n\t\tpointer = (char *) palloc(64);\n\t\tsprintf(pointer, \"%p\", (void *) prodesc);\n\t\tadd_assoc_string(plphp_proc_array, internal_proname,\n\t\t\t\t\t\t (char *) pointer, 1);\n\n\t\tif (zend_eval_string(complete_proc_source, NULL,\n\t\t\t\t\t\t\t \"plphp function source\" TSRMLS_CC) == FAILURE)\n\t\t{\n\t\t\t/* the next compilation will blow it up */\n\t\t\tprodesc->fn_xmin = InvalidTransactionId;\n\t\t\telog(ERROR, \"unable to compile function \\\"%s\\\"\",\n\t\t\t\t\t prodesc->proname);\n\t\t}\n\n\t\tif (aliases)\n\t\t\tpfree(aliases);\n\t\tif (out_aliases)\n\t\t\tpfree(out_aliases);\n\t\tif (out_return_str)\n\t\t\tpfree(out_return_str);\n\t\tpfree(complete_proc_source);\n\t}\n\n\tReleaseSysCache(procTup);\n\n\treturn prodesc;\n}\n\n/*\n * plphp_func_build_args\n * \t\tBuild a PHP array representing the arguments to the function\n */\nstatic zval *\nplphp_func_build_args(plphp_proc_desc *desc, FunctionCallInfo fcinfo TSRMLS_DC)\n{\n\tzval\t *retval;\n\tint\t\t\ti,j;\n\n\tMAKE_STD_ZVAL(retval);\n\tarray_init(retval);\n\n\t/* \n\t * The first var iterates over every argument, the second one - over the \n\t * IN or INOUT ones only\n\t */\n\tfor (i = 0, j = 0; i < desc->n_total_args; \n\t\t (j = IS_ARGMODE_OUT(desc->arg_argmode[i]) ? j : j + 1), i++)\n\t{\n\t\t/* Assing NULLs to OUT or TABLE arguments initially */\n\t\tif (IS_ARGMODE_OUT(desc->arg_argmode[i]))\n\t\t{\n\t\t\tadd_next_index_unset(retval);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (desc->arg_typtype[i] == TYPTYPE_PSEUDO)\n\t\t{\n\t\t\tHeapTuple\ttypeTup;\n\t\t\tForm_pg_type typeStruct;\n\n\t\t\ttypeTup = SearchSysCache(TYPEOID,\n\t\t\t\t\t\t\t\t\t ObjectIdGetDatum(get_fn_expr_argtype\n\t\t\t\t\t\t\t\t\t\t\t\t\t (fcinfo->flinfo, j)),\n\t\t\t\t\t\t\t\t\t 0, 0, 0);\n\t\t\ttypeStruct = (Form_pg_type) GETSTRUCT(typeTup);\n\t\t\tperm_fmgr_info(typeStruct->typoutput,\n\t\t\t\t\t\t &(desc->arg_out_func[i]));\n\t\t\tdesc->arg_typioparam[i] = typeStruct->typelem;\n\t\t\tReleaseSysCache(typeTup);\n\t\t}\n\n\t\tif (desc->arg_typtype[i] == TYPTYPE_COMPOSITE)\n\t\t{\n\t\t\tif (fcinfo->argnull[j])\n\t\t\t\tadd_next_index_unset(retval);\n\t\t\telse\n\t\t\t{\n\t\t\t\tHeapTupleHeader\ttd;\n\t\t\t\tOid\t\t\t\ttupType;\n\t\t\t\tint32\t\t\ttupTypmod;\n\t\t\t\tTupleDesc\t\ttupdesc;\n\t\t\t\tHeapTupleData\ttmptup;\n\t\t\t\tzval\t\t *hashref;\n\n\t\t\t\ttd = DatumGetHeapTupleHeader(fcinfo->arg[j]);\n\n\t\t\t\t/* Build a temporary HeapTuple control structure */\n\t\t\t\ttmptup.t_len = HeapTupleHeaderGetDatumLength(td);\n\t\t\t\ttmptup.t_data = DatumGetHeapTupleHeader(fcinfo->arg[j]);\n\n\t\t\t\t/* Extract rowtype info and find a tupdesc */\n\t\t\t\ttupType = HeapTupleHeaderGetTypeId(tmptup.t_data);\n\t\t\t\ttupTypmod = HeapTupleHeaderGetTypMod(tmptup.t_data);\n\t\t\t\ttupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);\n\n\t\t\t\t/* Build the PHP hash */\n\t\t\t\thashref = plphp_build_tuple_argument(&tmptup, tupdesc);\n\t\t\t\tzend_hash_next_index_insert(retval->value.ht,\n\t\t\t\t\t\t\t\t\t\t\t(void *) &hashref,\n\t\t\t\t\t\t\t\t\t\t\tsizeof(zval *), NULL);\n\t\t\t\t/* Finally release the acquired tupledesc */\n\t\t\t\tReleaseTupleDesc(tupdesc);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (fcinfo->argnull[j])\n\t\t\t\tadd_next_index_unset(retval);\n\t\t\telse\n\t\t\t{\n\t\t\t\tchar\t *tmp;\n\n\t\t\t\t/*\n\t\t\t\t * TODO room for improvement here: instead of going through the\n\t\t\t\t * output function, figure out if we can just use the native\n\t\t\t\t * representation to pass to PHP.\n\t\t\t\t */\n\n\t\t\t\ttmp =\n\t\t\t\t\tDatumGetCString(FunctionCall3\n\t\t\t\t\t\t\t\t\t(&(desc->arg_out_func[i]),\n\t\t\t\t\t\t\t\t\t fcinfo->arg[j],\n\t\t\t\t\t\t\t\t\t ObjectIdGetDatum(desc->arg_typioparam[i]),\n\t\t\t\t\t\t\t\t\t Int32GetDatum(-1)));\n\t\t\t\t/*\n\t\t\t\t * FIXME -- this is bogus. Not every value starting with { is\n\t\t\t\t * an array. Figure out a better method for detecting arrays.\n\t\t\t\t */\n\t\t\t\tif (tmp[0] == '{')\n\t\t\t\t{\n\t\t\t\t\tzval\t *hashref;\n\n\t\t\t\t\thashref = plphp_convert_from_pg_array(tmp TSRMLS_CC);\n\t\t\t\t\tzend_hash_next_index_insert(retval->value.ht,\n\t\t\t\t\t\t\t\t\t\t\t\t(void *) &hashref,\n\t\t\t\t\t\t\t\t\t\t\t\tsizeof(zval *), NULL);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tadd_next_index_string(retval, tmp, 1);\n\n\t\t\t\t/*\n\t\t\t\t * FIXME - figure out which parameters are passed by\n\t\t\t\t * reference and need freeing\n\t\t\t\t */\n\t\t\t\t/* pfree(tmp); */\n\t\t\t}\n\t\t}\n\t}\n\n\treturn retval;\n}\n\n/*\n * plphp_call_php_func\n * \t\tBuild the function argument array and call the PHP function.\n *\n * We use a private PHP symbol table, so that we can easily destroy everything\n * used during the execution of the function. We use it to collect the\n * arguments' zvals as well. We exclude the return value, because it will be\n * used by the caller -- it must be freed there!\n */\nstatic zval *\nplphp_call_php_func(plphp_proc_desc *desc, FunctionCallInfo fcinfo TSRMLS_DC)\n{\n\tzval\t *retval;\n\tzval\t *args;\n\tzval\t *argc;\n\tzval\t *funcname;\n\tzval\t **params[2];\n\tchar\t\tcall[64];\n\tHashTable *orig_symbol_table;\n\tHashTable *symbol_table;\n\n\tREPORT_PHP_MEMUSAGE(\"going to build function args\");\n\n\tALLOC_HASHTABLE(symbol_table);\n\tzend_hash_init(symbol_table, 0, NULL, ZVAL_PTR_DTOR, 0);\n\n\t/*\n\t * Build the function arguments. Save a pointer to each new zval in our\n\t * private symbol table, so that we can clean up easily later.\n\t */\n\targs = plphp_func_build_args(desc, fcinfo TSRMLS_CC);\n\tzend_hash_update(symbol_table, \"args\", strlen(\"args\") + 1,\n\t\t\t\t\t (void *) &args, sizeof(zval *), NULL);\n\n\tREPORT_PHP_MEMUSAGE(\"args built. Now the rest ...\");\n\n\tMAKE_STD_ZVAL(argc);\n\tZVAL_LONG(argc, desc->n_total_args);\n\tzend_hash_update(symbol_table, \"argc\", strlen(\"argc\") + 1,\n\t\t\t\t\t (void *) &argc, sizeof(zval *), NULL);\n\n\tparams[0] = &args;\n\tparams[1] = &argc;\n\n\t/* Build the internal function name, and save for later cleaning */\n\tsprintf(call, \"plphp_proc_%u\", fcinfo->flinfo->fn_oid);\n\tMAKE_STD_ZVAL(funcname);\n\tZVAL_STRING(funcname, call, 1);\n\tzend_hash_update(symbol_table, \"funcname\", strlen(\"funcname\") + 1,\n\t\t\t\t\t (void *) &funcname, sizeof(zval *), NULL);\n\n\tREPORT_PHP_MEMUSAGE(\"going to call the function\");\n\n\torig_symbol_table = EG(active_symbol_table);\n\tEG(active_symbol_table) = symbol_table;\n\n\tsaved_symbol_table = EG(active_symbol_table);\n\n\t/* XXX: why no_separation param is 1 is this call ? */\n\tif (call_user_function_ex(CG(function_table), NULL, funcname, &retval,\n\t\t\t\t\t\t\t 2, params, 1, symbol_table TSRMLS_CC) == FAILURE)\n\t\telog(ERROR, \"could not call function \\\"%s\\\"\", call);\n\n\tREPORT_PHP_MEMUSAGE(\"going to free some vars\");\n\n\tsaved_symbol_table = NULL;\n\n\t/* Return to the original symbol table, and clean our private one */\n\tEG(active_symbol_table) = orig_symbol_table;\n\tzend_hash_clean(symbol_table);\n\n\tREPORT_PHP_MEMUSAGE(\"function call done\");\n\n\treturn retval;\n}\n\n/*\n * plphp_call_php_trig\n * \t\tBuild trigger argument array and call the PHP function as a\n * \t\ttrigger.\n *\n * Note we don't need to change the symbol table here like we do in\n * plphp_call_php_func, because we do manual cleaning of each zval used.\n */\nstatic zval *\nplphp_call_php_trig(plphp_proc_desc *desc, FunctionCallInfo fcinfo,\n\t\t\t\t\tzval *trigdata TSRMLS_DC)\n{\n\tzval\t *retval;\n\tzval\t *funcname;\n\tchar\t\tcall[64];\n\tzval\t **params[1];\n\n\tparams[0] = &trigdata;\n\n\t/* Build the internal function name, and save for later cleaning */\n\tsprintf(call, \"plphp_proc_%u_trigger\", fcinfo->flinfo->fn_oid);\n\tMAKE_STD_ZVAL(funcname);\n\tZVAL_STRING(funcname, call, 0);\n\n\t/*\n\t * HACK: mark trigdata as a reference, so it won't be copied in\n\t * call_user_function_ex. This way the user function will be able to \n\t * modify it, in order to change NEW.\n\t */\n\tZ_SET_ISREF_P(trigdata);\n\n\tif (call_user_function_ex(CG(function_table), NULL, funcname, &retval,\n\t\t\t\t\t\t\t 1, params, 1, NULL TSRMLS_CC) == FAILURE)\n\t\telog(ERROR, \"could not call function \\\"%s\\\"\", call);\n\n\tFREE_ZVAL(funcname);\n\n\t/* Return to the original state */\n\tZ_UNSET_ISREF_P(trigdata);\n\n\treturn retval;\n}\n\n/*\n * plphp_error_cb\n *\n * A callback for PHP error handling. This is called when the php_error or\n * zend_error function is invoked in our code. Ideally this function should\n * clean up the PHP state after an ERROR, but zend_try blocks do not seem\n * to work as I'd expect. So for now, we degrade the error to WARNING and \n * continue executing in the hope that the system doesn't crash later.\n *\n * Note that we do clean up some PHP state by hand but it doesn't seem to\n * work as expected either.\n */\nvoid\nplphp_error_cb(int type, const char *filename, const uint lineno,\n\t \t\t const char *fmt, va_list args)\n{\n\tchar\tstr[1024];\n\tint\t\televel;\n\n\tvsnprintf(str, 1024, fmt, args);\n\n\t/*\n\t * PHP error classification is a bitmask, so this conversion is a bit\n\t * bogus. However, most calls to php_error() use a single bit.\n\t * Whenever more than one is used, we will default to ERROR, so this is\n\t * safe, if a bit excessive.\n\t *\n\t * XXX -- I wonder whether we should promote the WARNINGs to errors as\n\t * well. PHP has a really stupid way of continuing execution in presence\n\t * of severe problems that I don't see why we should maintain.\n\t */\n\tswitch (type)\n\t{\n\t\tcase E_ERROR:\n\t\tcase E_CORE_ERROR:\n\t\tcase E_COMPILE_ERROR:\n\t\tcase E_USER_ERROR:\n\t\tcase E_PARSE:\n\t\t\televel = ERROR;\n\t\t\tbreak;\n\t\tcase E_WARNING:\n\t\tcase E_CORE_WARNING:\n\t\tcase E_COMPILE_WARNING:\n\t\tcase E_USER_WARNING:\n\t\tcase E_STRICT:\n\t\t\televel = WARNING;\n\t\t\tbreak;\n\t\tcase E_NOTICE:\n\t\tcase E_USER_NOTICE:\n\t\t\televel = NOTICE;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\televel = ERROR;\n\t\t\tbreak;\n\t}\n\n\tREPORT_PHP_MEMUSAGE(\"reporting error\");\n\n\t/*\n\t * If this is a severe problem, we need to make PHP aware of it, so first\n\t * save the error message and then bail out of the PHP block. With luck,\n\t * this will be trapped by a zend_try/zend_catch block outwards in PL/php\n\t * code, which would translate it to a Postgres elog(ERROR), leaving\n\t * everything in a consistent state.\n\t *\n\t * For this to work, there must be a try/catch block covering every place\n\t * where PHP may raise an error!\n\t */\n\tif (elevel >= ERROR)\n\t{\n\t\tif (lineno != 0)\n\t\t{\n\t\t\tchar\tmsgline[1024];\n\t\t\tsnprintf(msgline, sizeof(msgline), \"%s at line %d\", str, lineno);\n\t\t\terror_msg = pstrdup(msgline);\n\t\t}\n\t\telse\n\t\t\terror_msg = pstrdup(str);\n\n\t\tzend_bailout();\n\t}\n\n\tereport(elevel,\n\t\t\t(errmsg(\"plphp: %s\", str)));\n}\n\n/* Check if the name can be a valid PHP variable name */\nstatic bool \nis_valid_php_identifier(char *name)\n{\n\tint \tlen,\n\t\t\ti;\n\t\n\tAssert(name);\n\n\tlen = strlen(name);\n\n\t/* Should start from the letter */\n\tif (!isalpha(name[0]))\n\t\treturn false;\n\tfor (i = 1; i < len; i++)\n\t{\n\t\t/* Only letters, digits and underscores are allowed */\n\t\tif (!isalpha(name[i]) && !isdigit(name[i]) && name[i] != '_')\n\t\t\treturn false;\n\t}\n\treturn true;\n}\n\n/*\n * vim:ts=4:sw=4:cino=(0\n */\n", "plphp_io.c": "/**********************************************************************\n * plphp_io.c\n *\n * Support functions for PL/php -- mainly functions to convert stuff\n * from the PHP representation to PostgreSQL representation and vice\n * versa, either text or binary representations.\n *\n * $Id$\n *\n **********************************************************************/\n\n#include \"postgres.h\"\n#include \"plphp_io.h\"\n\n#include \"catalog/pg_type.h\"\n#include \"executor/spi.h\"\n#include \"funcapi.h\"\n#include \"lib/stringinfo.h\"\n#include \"utils/lsyscache.h\"\n#include \"utils/rel.h\"\n#include \"utils/syscache.h\"\n#include \"utils/memutils.h\"\n#include \"access/htup_details.h\"\n\n/*\n * plphp_zval_from_tuple\n *\t\t Build a PHP hash from a tuple.\n */\nzval *\nplphp_zval_from_tuple(HeapTuple tuple, TupleDesc tupdesc)\n{\n\tint\t\t\ti;\n\tchar\t *attname = NULL;\n\tzval\t *array;\n\n\tMAKE_STD_ZVAL(array);\n\tarray_init(array);\n\n\tfor (i = 0; i < tupdesc->natts; i++)\n\t{\n\t\tchar *attdata;\n\n\t\t/* Get the attribute name */\n\t\tattname = tupdesc->attrs[i]->attname.data;\n\n\t\t/* and get its value */\n\t\tif ((attdata = SPI_getvalue(tuple, tupdesc, i + 1)) != NULL)\n\t\t{\n\t\t\t/* \"true\" means strdup the string */\n\t\t\tadd_assoc_string(array, attname, attdata, true);\n\t\t\tpfree(attdata);\n\t\t}\n\t\telse\n\t\t\tadd_assoc_null(array, attname);\n\t}\n\treturn array;\n}\n\n/*\n * plphp_htup_from_zval\n * \t\tBuild a HeapTuple from a zval (which must be an array) and a TupleDesc.\n *\n * The return HeapTuple is allocated in the current memory context and must\n * be freed by the caller.\n *\n * If zval doesn't contain any of the element names from the TupleDesc,\n * build a tuple from the first N elements. This allows us to accept\n * arrays in form array(1,2,3) as the result of functions with OUT arguments.\n * XXX -- possible optimization: keep the memory context created and only\n * reset it between calls.\n */\nHeapTuple\nplphp_htup_from_zval(zval *val, TupleDesc tupdesc)\n{\n\tMemoryContext\toldcxt;\n\tMemoryContext\ttmpcxt;\n\tHeapTuple\t\tret;\n\tAttInMetadata *attinmeta;\n\tHashPosition\tpos;\n\tzval\t\t **element;\n\tchar\t\t **values;\n\tint\t\t\t\ti;\n\tbool\t\t\tallempty = true;\n\n\ttmpcxt = AllocSetContextCreate(TopTransactionContext,\n\t\t\t\t\t\t\t\t \"htup_from_zval cxt\",\n\t\t\t\t\t\t\t\t ALLOCSET_DEFAULT_MINSIZE,\n\t\t\t\t\t\t\t\t ALLOCSET_DEFAULT_INITSIZE,\n\t\t\t\t\t\t\t\t ALLOCSET_DEFAULT_MAXSIZE);\n\toldcxt = MemoryContextSwitchTo(tmpcxt);\n\n\tvalues = (char **) palloc(tupdesc->natts * sizeof(char *));\n\n\tfor (i = 0; i < tupdesc->natts; i++)\n\t{\n\t\tchar *key = SPI_fname(tupdesc, i + 1);\n\t\tzval *scalarval = plphp_array_get_elem(val, key);\n\n\t\tvalues[i] = plphp_zval_get_cstring(scalarval, true, true);\n\t\t/* \n\t\t * Reset the flag is even one of the keys actually exists,\n\t\t * even if it is NULL.\n\t\t */\n\t\tif (scalarval != NULL)\n\t\t\tallempty = false;\n\t}\n\t/* None of the names from the tuple exists,\n\t * try to get 1st N array elements and assign them to the tuple\n\t */\n\tif (allempty)\n\t\tfor (i = 0, \n\t\t\t zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(val), &pos);\n\t\t\t (zend_hash_get_current_data_ex(Z_ARRVAL_P(val), \n\t\t\t\t\t\t\t\t\t\t (void **) &element,\n\t\t\t\t\t\t\t\t\t\t\t&pos) == SUCCESS) && \n\t\t\t(i < tupdesc->natts);\n\t\t\tzend_hash_move_forward_ex(Z_ARRVAL_P(val), &pos), i++)\n\t\t\tvalues[i] = plphp_zval_get_cstring(element[0], true, true);\n\n\tattinmeta = TupleDescGetAttInMetadata(tupdesc);\n\n\tMemoryContextSwitchTo(oldcxt);\n\tret = BuildTupleFromCStrings(attinmeta, values);\n\n\tMemoryContextDelete(tmpcxt);\n\n\treturn ret;\n}\n\n\n/* plphp_srf_htup_from_zval\n * \t\tBuild a tuple from a zval and a TupleDesc, for a SRF.\n *\n * Like above, but we don't use the names of the array attributes;\n * rather we build the tuple in order. Also, we get a MemoryContext\n * from the caller and just clean it at return, rather than building it each\n * time.\n */\nHeapTuple\nplphp_srf_htup_from_zval(zval *val, AttInMetadata *attinmeta,\n\t\t\t\t\t\t MemoryContext cxt)\n{\n\tMemoryContext\toldcxt;\n\tHeapTuple\t\tret;\n\tHashPosition\tpos;\n\tchar\t\t **values;\n\tzval\t\t **element;\n\tint\t\t\t\ti = 0;\n\n\toldcxt = MemoryContextSwitchTo(cxt);\n\n\t/*\n\t * Use palloc0 to initialize values to NULL, just in case the user does\n\t * not pass all needed attributes\n\t */\n\tvalues = (char **) palloc0(attinmeta->tupdesc->natts * sizeof(char *));\n\n\t/*\n\t * If the input zval is an array, build a tuple using each element as an\n\t * attribute. Exception: if the return tuple has a single element and\n\t * it's an array type, use the whole array as a single value.\n\t *\n\t * If the input zval is a scalar, use it as an element directly.\n\t */\n\tif (Z_TYPE_P(val) == IS_ARRAY)\n\t{\n\t\tif (attinmeta->tupdesc->natts == 1)\n\t\t{\n\t\t\t/* Is it an array? */\n\t\t\tif (attinmeta->tupdesc->attrs[0]->attndims != 0 ||\n\t\t\t\t!OidIsValid(get_element_type(attinmeta->tupdesc->attrs[0]->atttypid)))\n\t\t\t{\n\t\t\t\tzend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(val), &pos);\n\t\t\t\tzend_hash_get_current_data_ex(Z_ARRVAL_P(val),\n\t\t\t\t\t\t\t\t\t\t\t (void **) &element,\n\t\t\t\t\t\t\t\t\t\t\t &pos);\n\t\t\t\tvalues[0] = plphp_zval_get_cstring(element[0], true, true);\n\t\t\t}\n\t\t\telse\n\t\t\t\tvalues[0] = plphp_zval_get_cstring(val, true, true);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t/*\n\t\t\t * Ok, it's an array and the return tuple has more than one\n\t\t\t * attribute, so scan each array element.\n\t\t\t */\n\t\t\tfor (zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(val), &pos);\n\t\t\t\t zend_hash_get_current_data_ex(Z_ARRVAL_P(val),\n\t\t\t\t\t\t\t\t\t\t\t (void **) &element,\n\t\t\t\t\t\t\t\t\t\t\t &pos) == SUCCESS;\n\t\t\t\t zend_hash_move_forward_ex(Z_ARRVAL_P(val), &pos))\n\t\t\t{\n\t\t\t\t/* avoid overrunning the palloc'ed chunk */\n\t\t\t\tif (i >= attinmeta->tupdesc->natts)\n\t\t\t\t{\n\t\t\t\t\telog(WARNING, \"more elements in array than attributes in return type\");\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tvalues[i++] = plphp_zval_get_cstring(element[0], true, true);\n\t\t\t}\n\t\t}\n\t}\n\telse\n\t{\n\t\t/* The passed zval is not an array -- use as the only attribute */\n\t\tif (attinmeta->tupdesc->natts != 1)\n\t\t\tereport(ERROR,\n\t\t\t\t\t(errmsg(\"returned array does not correspond to \"\n\t\t\t\t\t\t\t\"declared return value\")));\n\n\t\tvalues[0] = plphp_zval_get_cstring(val, true, true);\n\t}\n\n\tMemoryContextSwitchTo(oldcxt);\n\n\tret = BuildTupleFromCStrings(attinmeta, values);\n\n\tMemoryContextReset(cxt);\n\n\treturn ret;\n}\n\n/*\n * plphp_convert_to_pg_array\n * \t\tConvert a zval into a Postgres text array representation.\n *\n * The return value is palloc'ed in the current memory context and\n * must be freed by the caller.\n */\nchar *\nplphp_convert_to_pg_array(zval *array)\n{\n\tint\t\t\tarr_size;\n\tzval\t **element;\n\tint\t\t\ti = 0;\n\tHashPosition \tpos;\n\tStringInfoData\tstr;\n\t\n\tinitStringInfo(&str);\n\n\tarr_size = zend_hash_num_elements(Z_ARRVAL_P(array));\n\n\tappendStringInfoChar(&str, '{');\n\tif (Z_TYPE_P(array) == IS_ARRAY)\n\t{\n\t\tfor (zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(array), &pos);\n\t\t\t zend_hash_get_current_data_ex(Z_ARRVAL_P(array),\n\t\t\t\t\t\t\t\t\t\t (void **) &element,\n\t\t\t\t\t\t\t\t\t\t &pos) == SUCCESS;\n\t\t\t zend_hash_move_forward_ex(Z_ARRVAL_P(array), &pos))\n\t\t{\n\t\t\tchar *tmp;\n\n\t\t\tswitch (Z_TYPE_P(element[0]))\n\t\t\t{\n\t\t\t\tcase IS_LONG:\n\t\t\t\t\tappendStringInfo(&str, \"%li\", element[0]->value.lval);\n\t\t\t\t\tbreak;\n\t\t\t\tcase IS_DOUBLE:\n\t\t\t\t\tappendStringInfo(&str, \"%f\", element[0]->value.dval);\n\t\t\t\t\tbreak;\n\t\t\t\tcase IS_STRING:\n\t\t\t\t\tappendStringInfo(&str, \"\\\"%s\\\"\", element[0]->value.str.val);\n\t\t\t\t\tbreak;\n\t\t\t\tcase IS_ARRAY:\n\t\t\t\t\ttmp = plphp_convert_to_pg_array(element[0]);\n\t\t\t\t\tappendStringInfo(&str, \"%s\", tmp);\n\t\t\t\t\tpfree(tmp);\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\telog(ERROR, \"unrecognized element type %d\",\n\t\t\t\t\t\t Z_TYPE_P(element[0]));\n\t\t\t}\n\n\t\t\tif (i != arr_size - 1)\n\t\t\t\tappendStringInfoChar(&str, ',');\n\t\t\ti++;\n\t\t}\n\t}\n\n\tappendStringInfoChar(&str, '}');\n\n\treturn str.data;\n}\n\n/*\n * plphp_convert_from_pg_array\n * \t\tConvert a Postgres text array representation to a PHP array\n * \t\t(zval type thing).\n *\n * FIXME -- does not work if there are embedded {'s in the input value.\n *\n * FIXME -- does not correctly quote/dequote the values\n */\nzval *\nplphp_convert_from_pg_array(char *input TSRMLS_DC)\n{\n\tzval\t *retval = NULL;\n\tint\t\t\ti;\n\tStringInfoData str;\n\t\n\tinitStringInfo(&str);\n\n\tMAKE_STD_ZVAL(retval);\n\tarray_init(retval);\n\n\tfor (i = 0; i < strlen(input); i++)\n\t{\n\t\tif (input[i] == '{')\n\t\t\tappendStringInfoString(&str, \"array(\");\n\t\telse if (input[i] == '}')\n\t\t\tappendStringInfoChar(&str, ')');\n\t\telse\n\t\t\tappendStringInfoChar(&str, input[i]);\n\t}\n\tappendStringInfoChar(&str, ';');\n\n\tif (zend_eval_string(str.data, retval,\n\t\t\t\t\t\t \"plphp array input parameter\" TSRMLS_CC) == FAILURE)\n\t\telog(ERROR, \"plphp: convert to internal representation failure\");\n\n\tpfree(str.data);\n\n\treturn retval;\n}\n\n/*\n * plphp_array_get_elem\n * \t\tReturn a pointer to the array element with the given key\n */\nzval *\nplphp_array_get_elem(zval *array, char *key)\n{\n\tzval\t **element;\n\n\tif (!array)\n\t\telog(ERROR, \"passed zval is not a valid pointer\");\n\tif (Z_TYPE_P(array) != IS_ARRAY)\n\t\telog(ERROR, \"passed zval is not an array\");\n\n\tif (zend_symtable_find(array->value.ht,\n\t\t\t\t\t \t key,\n\t\t\t\t\t strlen(key) + 1,\n\t\t\t\t\t (void **) &element) != SUCCESS)\n\t\treturn NULL;\n\n\treturn element[0];\n}\n\n/*\n * zval_get_cstring\n *\t\tGet a C-string representation of a zval.\n *\n * All return values, except those that are NULL, are palloc'ed in the current\n * memory context and must be freed by the caller.\n *\n * If the do_array parameter is false, then array values will not be converted\n * and an error will be raised instead.\n *\n * If the null_ok parameter is true, we will return NULL for a NULL zval.\n * Otherwise we raise an error.\n */\nchar *\nplphp_zval_get_cstring(zval *val, bool do_array, bool null_ok)\n{\n\tchar *ret;\n\n\tif (!val)\n\t{\n\t\tif (null_ok)\n\t\t\treturn NULL;\n\t\telse\n\t\t\telog(ERROR, \"invalid zval pointer\");\n\t}\n\n\tswitch (Z_TYPE_P(val))\n\t{\n\t\tcase IS_NULL:\n\t\t\treturn NULL;\n\t\tcase IS_LONG:\n\t\t\tret = palloc(64);\n\t\t\tsnprintf(ret, 64, \"%ld\", Z_LVAL_P(val));\n\t\t\tbreak;\n\t\tcase IS_DOUBLE:\n\t\t\tret = palloc(64);\n\t\t\tsnprintf(ret, 64, \"%f\", Z_DVAL_P(val));\n\t\t\tbreak;\n\t\tcase IS_BOOL:\n\t\t\tret = palloc(8);\n\t\t\tsnprintf(ret, 8, \"%s\", Z_BVAL_P(val) ? \"true\": \"false\");\n\t\t\tbreak;\n\t\tcase IS_STRING:\n\t\t\tret = palloc(Z_STRLEN_P(val) + 1);\n\t\t\tsnprintf(ret, Z_STRLEN_P(val) + 1, \"%s\", \n\t\t\t\t\t Z_STRVAL_P(val));\n\t\t\tbreak;\n\t\tcase IS_ARRAY:\n\t\t\tif (!do_array)\n\t\t\t\telog(ERROR, \"can't stringize array value\");\n\t\t\tret = plphp_convert_to_pg_array(val);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\t/* keep compiler quiet */\n\t\t\tret = NULL;\n\t\t\telog(ERROR, \"can't stringize value of type %d\", val->type);\n\t}\n\n\treturn ret;\n}\n\n/*\n * plphp_build_tuple_argument\n *\n * Build a PHP array from all attributes of a given tuple\n */\nzval *\nplphp_build_tuple_argument(HeapTuple tuple, TupleDesc tupdesc)\n{\n\tint\t\t\ti;\n\tzval\t *output;\n\tDatum\t\tattr;\n\tbool\t\tisnull;\n\tchar\t *attname;\n\tchar\t *outputstr;\n\tHeapTuple\ttypeTup;\n\tOid\t\t\ttypoutput;\n\tOid\t\t\ttypioparam;\n\n\tMAKE_STD_ZVAL(output);\n\tarray_init(output);\n\n\tfor (i = 0; i < tupdesc->natts; i++)\n\t{\n\t\t/* Ignore dropped attributes */\n\t\tif (tupdesc->attrs[i]->attisdropped)\n\t\t\tcontinue;\n\n\t\t/* Get the attribute name */\n\t\tattname = tupdesc->attrs[i]->attname.data;\n\n\t\t/* Get the attribute value */\n\t\tattr = heap_getattr(tuple, i + 1, tupdesc, &isnull);\n\n\t\t/* If it is null, set it to undef in the hash. */\n\t\tif (isnull)\n\t\t{\n\t\t\tadd_next_index_unset(output);\n\t\t\tcontinue;\n\t\t}\n\n\t\t/*\n\t\t * Lookup the attribute type in the syscache for the output function\n\t\t */\n\t\ttypeTup = SearchSysCache(TYPEOID,\n\t\t\t\t\t\t\t\t ObjectIdGetDatum(tupdesc->attrs[i]->atttypid),\n\t\t\t\t\t\t\t\t 0, 0, 0);\n\t\tif (!HeapTupleIsValid(typeTup))\n\t\t{\n\t\t\telog(ERROR, \"cache lookup failed for type %u\",\n\t\t\t\t tupdesc->attrs[i]->atttypid);\n\t\t}\n\n\t\ttypoutput = ((Form_pg_type) GETSTRUCT(typeTup))->typoutput;\n\t\ttypioparam = getTypeIOParam(typeTup);\n\t\tReleaseSysCache(typeTup);\n\n\t\t/* Append the attribute name and the value to the list. */\n\t\toutputstr =\n\t\t\tDatumGetCString(OidFunctionCall3(typoutput, attr,\n\t\t\t\t\t\t\t\t\t\t\t ObjectIdGetDatum(typioparam),\n\t\t\t\t\t\t\t\t\t\t\t Int32GetDatum(tupdesc->attrs[i]->atttypmod)));\n\t\tadd_assoc_string(output, attname, outputstr, 1);\n\t\tpfree(outputstr);\n\t}\n\n\treturn output;\n}\n\n/*\n * plphp_modify_tuple\n * \t\tReturn the modified NEW tuple, for use as return value in a BEFORE\n * \t\ttrigger. outdata must point to the $_TD variable from the PHP\n * \t\tfunction.\n *\n * The tuple will be allocated in the current memory context and must be freed\n * by the caller.\n *\n * XXX Possible optimization: make this a global context that is not deleted,\n * but only reset each time this function is called. (Think about triggers\n * calling other triggers though).\n */\nHeapTuple\nplphp_modify_tuple(zval *outdata, TriggerData *tdata)\n{\n\tTupleDesc\ttupdesc;\n\tHeapTuple\trettuple;\n\tzval\t *newtup;\n\tzval\t **element;\n\tchar\t **vals;\n\tint\t\t\ti;\n\tAttInMetadata *attinmeta;\n\tMemoryContext tmpcxt,\n\t\t\t\t oldcxt;\n\n\ttmpcxt = AllocSetContextCreate(CurTransactionContext,\n\t\t\t\t\t\t\t\t \"PL/php NEW context\",\n\t\t\t\t\t\t\t\t ALLOCSET_DEFAULT_MINSIZE,\n\t\t\t\t\t\t\t\t ALLOCSET_DEFAULT_INITSIZE,\n\t\t\t\t\t\t\t\t ALLOCSET_DEFAULT_MAXSIZE);\n\n\toldcxt = MemoryContextSwitchTo(tmpcxt);\n\n\t/* Fetch \"new\" from $_TD */\n\tif (zend_hash_find(outdata->value.ht,\n\t\t\t\t\t \"new\", strlen(\"new\") + 1,\n\t\t\t\t\t (void **) &element) != SUCCESS)\n\t\telog(ERROR, \"$_TD['new'] not found\");\n\n\tif (Z_TYPE_P(element[0]) != IS_ARRAY)\n\t\telog(ERROR, \"$_TD['new'] must be an array\");\n\tnewtup = element[0];\n\n\t/* Fetch the tupledesc and metadata */\n\ttupdesc = tdata->tg_relation->rd_att;\n\tattinmeta = TupleDescGetAttInMetadata(tupdesc);\n\n\ti = zend_hash_num_elements(Z_ARRVAL_P(newtup));\n\n\tif (tupdesc->natts > i)\n\t\tereport(ERROR,\n\t\t\t\t(errmsg(\"insufficient number of keys in $_TD['new']\"),\n\t\t\t\t errdetail(\"At least %d expected, %d found.\",\n\t\t\t\t\t\t tupdesc->natts, i)));\n\n\tvals = (char **) palloc(tupdesc->natts * sizeof(char *));\n\n\t/*\n\t * For each attribute in the tupledesc, get its value from newtup and put\n\t * it in an array of cstrings.\n\t */\n\tfor (i = 0; i < tupdesc->natts; i++)\n\t{\n\t\tzval **element;\n\t\tchar *attname = NameStr(tupdesc->attrs[i]->attname);\n\n\t\t/* Fetch the attribute value from the zval */\n\t\tif (zend_symtable_find(newtup->value.ht, attname, strlen(attname) + 1,\n\t\t\t\t\t\t \t (void **) &element) != SUCCESS)\n\t\t\telog(ERROR, \"$_TD['new'] does not contain attribute \\\"%s\\\"\",\n\t\t\t\t attname);\n\n\t\tvals[i] = plphp_zval_get_cstring(element[0], true, true);\n\t}\n\n\t/* Return to the original context so that the new tuple will survive */\n\tMemoryContextSwitchTo(oldcxt);\n\n\t/* Build the tuple */\n\trettuple = BuildTupleFromCStrings(attinmeta, vals);\n\n\t/* Free the memory used */\n\tMemoryContextDelete(tmpcxt);\n\n\treturn rettuple;\n}\n\n/*\n * vim:ts=4:sw=4:cino=(0\n */\n", "plphp_spi.c": "/**********************************************************************\n * plphp_spi.c - SPI-related functions for PL/php.\n *\n * This software is copyright (c) Command Prompt Inc.\n *\n * The author hereby grants permission to use, copy, modify,\n * distribute, and license this software and its documentation for any\n * purpose, provided that existing copyright notices are retained in\n * all copies and that this notice is included verbatim in any\n * distributions. No written agreement, license, or royalty fee is\n * required for any of the authorized uses. Modifications to this\n * software may be copyrighted by their author and need not follow the\n * licensing terms described here, provided that the new terms are\n * clearly indicated on the first page of each file where they apply.\n *\n * IN NO EVENT SHALL THE AUTHOR OR DISTRIBUTORS BE LIABLE TO ANY PARTY\n * FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES\n * ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY\n * DERIVATIVES THEREOF, EVEN IF THE AUTHOR HAVE BEEN ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * THE AUTHOR AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES,\n * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND\n * NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN \"AS IS\" BASIS,\n * AND THE AUTHOR AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE\n * MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n *\n * IDENTIFICATION\n *\t\t$Id$\n *********************************************************************\n */\n\n#include \"postgres.h\"\n#include \"plphp_spi.h\"\n#include \"plphp_io.h\"\n\n/* PHP stuff */\n#include \"php.h\"\n\n/* PostgreSQL stuff */\n#include \"access/xact.h\"\n#include \"access/htup_details.h\"\n#include \"miscadmin.h\"\n\n#undef DEBUG_PLPHP_MEMORY\n\n#ifdef DEBUG_PLPHP_MEMORY\n#define REPORT_PHP_MEMUSAGE(where) \\\n\telog(NOTICE, \"PHP mem usage: \u00ab%s\u00bb: %u\", where, AG(allocated_memory));\n#else\n#define REPORT_PHP_MEMUSAGE(a) \n#endif\n\n/* resource type Id for SPIresult */\nint SPIres_rtype;\n\n/* SPI function table */\nzend_function_entry spi_functions[] =\n{\n\tZEND_FE(spi_exec, NULL)\n\tZEND_FE(spi_fetch_row, NULL)\n\tZEND_FE(spi_processed, NULL)\n\tZEND_FE(spi_status, NULL)\n\tZEND_FE(spi_rewind, NULL)\n\tZEND_FE(pg_raise, NULL)\n\tZEND_FE(return_next, NULL)\n\t{NULL, NULL, NULL}\n};\n\n/* SRF support: */\nFunctionCallInfo current_fcinfo = NULL;\nTupleDesc current_tupledesc = NULL;\nAttInMetadata *current_attinmeta = NULL;\nMemoryContext current_memcxt = NULL;\nTuplestorestate *current_tuplestore = NULL;\n\n\n/* A symbol table to save for return_next for the RETURNS TABLE case */\nHashTable *saved_symbol_table;\n\nstatic zval *get_table_arguments(AttInMetadata *attinmeta);\n\n/*\n * spi_exec\n * \t\tPL/php equivalent to SPI_exec().\n *\n * This function creates and return a PHP resource which describes the result\n * of a user-specified query. If the query returns tuples, it's possible to\n * retrieve them by using spi_fetch_row.\n *\n * Receives one or two arguments. The mandatory first argument is the query\n * text. The optional second argument is the tuple limit.\n *\n * Note that just like PL/Perl, we start a subtransaction before invoking the\n * SPI call, and automatically roll it back if the call fails.\n */\nZEND_FUNCTION(spi_exec)\n{\n\tchar\t *query;\n\tint\t\t\tquery_len;\n\tlong\t\tstatus;\n\tlong\t\tlimit;\n\tphp_SPIresult *SPIres;\n\tint\t\t\tspi_id;\n\tMemoryContext oldcontext = CurrentMemoryContext;\n\tResourceOwner oldowner = CurrentResourceOwner;\n\n\tREPORT_PHP_MEMUSAGE(\"spi_exec called\");\n\n\tif ((ZEND_NUM_ARGS() > 2) || (ZEND_NUM_ARGS() < 1))\n\t\tWRONG_PARAM_COUNT;\n\n\t/* Parse arguments */\n\tif (ZEND_NUM_ARGS() == 2)\n\t{\n\t\tif (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"sl\",\n\t\t\t\t\t\t\t\t &query, &query_len, &limit) == FAILURE)\n\t\t{\n\t\t\tzend_error(E_WARNING, \"Can not parse parameters in %s\",\n\t\t\t\t\t get_active_function_name(TSRMLS_C));\n\t\t\tRETURN_FALSE;\n\t\t}\n\t}\n\telse if (ZEND_NUM_ARGS() == 1)\n\t{\n\t\tif (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"s\",\n\t\t\t\t\t\t\t\t &query, &query_len) == FAILURE)\n\t\t{\n\t\t\tzend_error(E_WARNING, \"Can not parse parameters in %s\",\n\t\t\t\t\t get_active_function_name(TSRMLS_C));\n\t\t\tRETURN_FALSE;\n\t\t}\n\t\tlimit = 0;\n\t}\n\telse\n\t{\n\t\tzend_error(E_WARNING, \"Incorrect number of parameters to %s\",\n\t\t\t\t get_active_function_name(TSRMLS_C));\n\t\tRETURN_FALSE;\n\t}\n\n\tBeginInternalSubTransaction(NULL);\n\tMemoryContextSwitchTo(oldcontext);\n\n\t/* Call SPI */\n\tPG_TRY();\n\t{\n\t\tstatus = SPI_exec(query, limit);\n\n\t\tReleaseCurrentSubTransaction();\n\t\tMemoryContextSwitchTo(oldcontext);\n\t\tCurrentResourceOwner = oldowner;\n\n\t\t/*\n\t\t * AtEOSubXact_SPI() should not have popped any SPI context, but just\n\t\t * in case it did, make sure we remain connected.\n\t\t */\n\t\tSPI_restore_connection();\n\t}\n\tPG_CATCH();\n\t{\n\t\tErrorData\t*edata;\n\n\t\t/* Save error info */\n\t\tMemoryContextSwitchTo(oldcontext);\n\t\tedata = CopyErrorData();\n\t\tFlushErrorState();\n\n\t\t/* Abort the inner trasaction */\n\t\tRollbackAndReleaseCurrentSubTransaction();\n\t\tMemoryContextSwitchTo(oldcontext);\n\t\tCurrentResourceOwner = oldowner;\n\n\t\t/*\n\t\t * If AtEOSubXact_SPI() popped any SPI context of the subxact, it will\n\t\t * have left us in a disconnected state. We need this hack to return\n\t\t * to connected state.\n\t\t */\n\t\tSPI_restore_connection();\n\n\t\t/* bail PHP out */\n\t\tzend_error(E_ERROR, \"%s\", strdup(edata->message));\n\n\t\t/* Can't get here, but keep compiler quiet */\n\t\treturn;\n\t}\n\tPG_END_TRY();\n\n\t/* This malloc'ed chunk is freed in php_SPIresult_destroy */\n\tSPIres = (php_SPIresult *) malloc(sizeof(php_SPIresult));\n\tif (!SPIres)\n\t\tereport(ERROR,\n\t\t\t\t(errcode(ERRCODE_OUT_OF_MEMORY),\n\t\t\t\t errmsg(\"out of memory\")));\n\n\t/* Prepare the return resource */\n\tSPIres->SPI_processed = SPI_processed;\n\tif (status == SPI_OK_SELECT)\n\t\tSPIres->SPI_tuptable = SPI_tuptable;\n\telse\n\t\tSPIres->SPI_tuptable = NULL;\n\tSPIres->current_row = 0;\n\tSPIres->status = status;\n\n\tREPORT_PHP_MEMUSAGE(\"spi_exec: creating resource\");\n\n\t/* Register the resource to PHP so it will be able to free it */\n\tspi_id = ZEND_REGISTER_RESOURCE(return_value, (void *) SPIres,\n\t\t\t\t\t \t\t\t\tSPIres_rtype);\n\n\tREPORT_PHP_MEMUSAGE(\"spi_exec: returning\");\n\n\tRETURN_RESOURCE(spi_id);\n}\n\n/*\n * spi_fetch_row\n * \t\tGrab a row from a SPI result (from spi_exec).\n *\n * This function receives a resource Id and returns a PHP hash representing the\n * next tuple in the result, or false if no tuples remain.\n *\n * XXX Apparently this is leaking memory. How do we tell PHP to free the tuple\n * once the user is done with it?\n */\nZEND_FUNCTION(spi_fetch_row)\n{\n\tzval\t *row = NULL;\n\tzval\t **z_spi = NULL;\n\tphp_SPIresult\t*SPIres;\n\n\tREPORT_PHP_MEMUSAGE(\"spi_fetch_row: called\");\n\n\tif (ZEND_NUM_ARGS() != 1)\n\t\tWRONG_PARAM_COUNT;\n\n\tif (zend_get_parameters_ex(1, &z_spi) == FAILURE)\n\t{\n\t\tzend_error(E_WARNING, \"Can not parse parameters in %s\",\n\t\t\t\t get_active_function_name(TSRMLS_C));\n\t\tRETURN_FALSE;\n\t}\n\tif (z_spi == NULL)\n\t{\n\t\tzend_error(E_WARNING, \"Could not get SPI resource in %s\",\n\t\t\t\t get_active_function_name(TSRMLS_C));\n\t\tRETURN_FALSE;\n\t}\n\n\tZEND_FETCH_RESOURCE(SPIres, php_SPIresult *, z_spi, -1, \"SPI result\",\n\t\t\t\t\t\tSPIres_rtype);\n\n\tif (SPIres->status != SPI_OK_SELECT)\n\t{\n\t\tzend_error(E_WARNING, \"SPI status is not good\");\n\t\tRETURN_FALSE;\n\t}\n\n\tif (SPIres->current_row < SPIres->SPI_processed)\n\t{\n\t\trow = plphp_zval_from_tuple(SPIres->SPI_tuptable->vals[SPIres->current_row],\n\t\t\t \t\t\t\t\t\tSPIres->SPI_tuptable->tupdesc);\n\t\tSPIres->current_row++;\n\n\t\t*return_value = *row;\n\n\t\tzval_copy_ctor(return_value);\n\t\tzval_dtor(row);\n\t\tFREE_ZVAL(row);\n\n\t}\n\telse\n\t\tRETURN_FALSE;\n\n\tREPORT_PHP_MEMUSAGE(\"spi_fetch_row: finish\");\n}\n\n/*\n * spi_processed\n * \t\tReturn the number of tuples returned in a spi_exec call.\n */\nZEND_FUNCTION(spi_processed)\n{\n\tzval\t **z_spi = NULL;\n\tphp_SPIresult\t*SPIres;\n\n\tREPORT_PHP_MEMUSAGE(\"spi_processed: start\");\n\n\tif (ZEND_NUM_ARGS() != 1)\n\t\tWRONG_PARAM_COUNT;\n\n\tif (zend_get_parameters_ex(1, &z_spi) == FAILURE)\n\t{\n\t\tzend_error(E_WARNING, \"Cannot parse parameters in %s\",\n\t\t\t\t get_active_function_name(TSRMLS_C));\n\t\tRETURN_FALSE;\n\t}\n\tif (z_spi == NULL)\n\t{\n\t\tzend_error(E_WARNING, \"Could not get SPI resource in %s\",\n\t\t\t\t get_active_function_name(TSRMLS_C));\n\t\tRETURN_FALSE;\n\t}\n\n\tZEND_FETCH_RESOURCE(SPIres, php_SPIresult *, z_spi, -1, \"SPI result\",\n\t\t\t\t\t\tSPIres_rtype);\n\n\tREPORT_PHP_MEMUSAGE(\"spi_processed: finish\");\n\n\tRETURN_LONG(SPIres->SPI_processed);\n}\n\n/*\n * spi_status\n * \t\tReturn the status returned by a previous spi_exec call, as a string.\n */\nZEND_FUNCTION(spi_status)\n{\n\tzval\t **z_spi = NULL;\n\tphp_SPIresult\t*SPIres;\n\n\tREPORT_PHP_MEMUSAGE(\"spi_status: start\");\n\n\tif (ZEND_NUM_ARGS() != 1)\n\t\tWRONG_PARAM_COUNT;\n\n\tif (zend_get_parameters_ex(1, &z_spi) == FAILURE)\n\t{\n\t\tzend_error(E_WARNING, \"Cannot parse parameters in %s\",\n\t\t\t\t get_active_function_name(TSRMLS_C));\n\t\tRETURN_FALSE;\n\t}\n\tif (z_spi == NULL)\n\t{\n\t\tzend_error(E_WARNING, \"Could not get SPI resource in %s\",\n\t\t\t\t get_active_function_name(TSRMLS_C));\n\t\tRETURN_FALSE;\n\t}\n\n\tZEND_FETCH_RESOURCE(SPIres, php_SPIresult *, z_spi, -1, \"SPI result\",\n\t\t\t\t\t\tSPIres_rtype);\n\n\tREPORT_PHP_MEMUSAGE(\"spi_status: finish\");\n\n\t/*\n\t * XXX The cast is wrong, but we use it to prevent a compiler warning.\n\t * Note that the second parameter to RETURN_STRING is \"duplicate\", so\n\t * we are returning a copy of the string anyway.\n\t */\n\tRETURN_STRING((char *) SPI_result_code_string(SPIres->status), true);\n}\n\n/*\n * spi_rewind\n * \t\tResets the internal counter for spi_fetch_row, so the next\n * \t\tspi_fetch_row call will start fetching from the beginning.\n */\nZEND_FUNCTION(spi_rewind)\n{\n\tzval\t **z_spi = NULL;\n\tphp_SPIresult\t*SPIres;\n\n\tif (ZEND_NUM_ARGS() != 1)\n\t\tWRONG_PARAM_COUNT;\n\n\tif (zend_get_parameters_ex(1, &z_spi) == FAILURE)\n\t{\n\t\tzend_error(E_WARNING, \"Cannot parse parameters in %s\",\n\t\t\t\t get_active_function_name(TSRMLS_C));\n\t\tRETURN_FALSE;\n\t}\n\tif (z_spi == NULL)\n\t{\n\t\tzend_error(E_WARNING, \"Could not get SPI resource in %s\",\n\t\t\t\t get_active_function_name(TSRMLS_C));\n\t\tRETURN_FALSE;\n\t}\n\n\tZEND_FETCH_RESOURCE(SPIres, php_SPIresult *, z_spi, -1, \"SPI result\",\n\t\t\t\t\t\tSPIres_rtype);\n\n\tSPIres->current_row = 0;\n\n\tRETURN_NULL();\n}\n/*\n * pg_raise\n * User-callable function for sending messages to the Postgres log.\n */\nZEND_FUNCTION(pg_raise)\n{\n\tchar *level = NULL,\n\t\t\t *message = NULL;\n\tint level_len,\n\t\t\t\tmessage_len,\n\t\t\t\televel = 0;\n\n\tif (ZEND_NUM_ARGS() != 2)\n\t{\n\t\tereport(ERROR,\n\t\t\t\t(errcode(ERRCODE_SYNTAX_ERROR),\n\t\t\t\t errmsg(\"wrong number of arguments to %s\", \"pg_raise\")));\n\t}\n\n\tif (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"ss\",\n\t\t\t\t\t\t\t &level, &level_len,\n\t\t\t\t\t\t\t &message, &message_len) == FAILURE)\n\t{\n\t\tzend_error(E_WARNING, \"cannot parse parameters in %s\",\n\t\t\t\t get_active_function_name(TSRMLS_C));\n\t}\n\n\tif (strcasecmp(level, \"ERROR\") == 0)\n\t\televel = E_ERROR;\n\telse if (strcasecmp(level, \"WARNING\") == 0)\n\t\televel = E_WARNING;\n\telse if (strcasecmp(level, \"NOTICE\") == 0)\n\t\televel = E_NOTICE;\n\telse\n\t\tzend_error(E_ERROR, \"incorrect log level\");\n\n\tzend_error(elevel, \"%s\", message);\n}\n\n/*\n * return_next\n * \t\tAdd a tuple to the current tuplestore\n */\nZEND_FUNCTION(return_next)\n{\n\tMemoryContext\toldcxt;\n\tzval\t *param;\n\tHeapTuple\ttup;\n\tReturnSetInfo *rsi;\n\t\n\t/*\n\t * Disallow use of return_next inside non-SRF functions\n\t */\n\tif (current_fcinfo == NULL || current_fcinfo->flinfo == NULL || \n\t\t!current_fcinfo->flinfo->fn_retset)\n\t\tereport(ERROR,\n\t\t\t\t(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),\n\t\t\t\t errmsg(\"cannot use return_next in functions not declared to \"\n\t\t\t\t\t\t\"return a set\")));\n\n\trsi = (ReturnSetInfo *) current_fcinfo->resultinfo;\n\n\tAssert(current_tupledesc != NULL);\n\tAssert(rsi != NULL);\n\t\n\tif (ZEND_NUM_ARGS() > 1)\n\t\tereport(ERROR,\n\t\t\t\t(errcode(ERRCODE_SYNTAX_ERROR),\n\t\t\t\t errmsg(\"wrong number of arguments to %s\", \"return_next\")));\n\n\tif (ZEND_NUM_ARGS() == 0)\n\t{\n\t\t/* \n\t\t * Called from the function declared with RETURNS TABLE \n\t */\n\t\tparam = get_table_arguments(current_attinmeta);\n\t}\n\telse if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"z\",\n\t\t\t\t\t\t\t ¶m) == FAILURE)\n\t{\n\t\tzend_error(E_WARNING, \"cannot parse parameters in %s\",\n\t\t\t\t get_active_function_name(TSRMLS_C));\n\t}\n\n\t/* Use the per-query context so that the tuplestore survives */\n\toldcxt = MemoryContextSwitchTo(rsi->econtext->ecxt_per_query_memory);\n\n\t/* Form the tuple */\n\ttup = plphp_srf_htup_from_zval(param, current_attinmeta, current_memcxt);\n\n\t/* First call? Create the tuplestore. */\n\tif (!current_tuplestore)\n\t\tcurrent_tuplestore = tuplestore_begin_heap(true, false, work_mem);\n\n\t/* Save the tuple and clean up */\n\ttuplestore_puttuple(current_tuplestore, tup);\n\theap_freetuple(tup);\n\n\tMemoryContextSwitchTo(oldcxt);\n}\n\n/*\n * php_SPIresult_destroy\n * \t\tFree the resources allocated by a spi_exec call.\n *\n * This is automatically called when the resource goes out of scope\n * or is overwritten by another resource.\n */\nvoid\nphp_SPIresult_destroy(zend_rsrc_list_entry *rsrc TSRMLS_DC)\n{\n\tphp_SPIresult *res = (php_SPIresult *) rsrc->ptr;\n\n\tif (res->SPI_tuptable != NULL)\n\t\tSPI_freetuptable(res->SPI_tuptable);\n\n\tfree(res);\n}\n\n/* Return an array of TABLE argument values for return_next */\nstatic\nzval *get_table_arguments(AttInMetadata *attinmeta)\n{\n\tzval *retval = NULL;\n\tint\t\ti;\n\t\n\tMAKE_STD_ZVAL(retval);\n\tarray_init(retval);\n\n\tAssert(attinmeta->tupdesc);\n\tAssert(saved_symbol_table != NULL);\n\t/* Extract OUT argument names */\n\tfor (i = 0; i < attinmeta->tupdesc->natts; i++)\n\t{\n\t\tzval \t**val;\n\t\tchar \t*attname;\n\n\t\tAssert(!attinmeta->tupdesc->attrs[i]->attisdropped);\n\n\t\tattname = NameStr(attinmeta->tupdesc->attrs[i]->attname);\n\n\t\tif (zend_hash_find(saved_symbol_table, \n\t\t\t\t\t\t attname, strlen(attname) + 1,\n\t\t\t\t\t\t (void **)&val) == SUCCESS)\n\n\t\t\tadd_next_index_zval(retval, *val);\n\t\telse\n\t\t\tadd_next_index_unset(retval);\n\t} \n\treturn retval;\n}\n\n\n/*\n * vim:ts=4:sw=4:cino=(0\n */\n"}} -{"repo": "binarylogic/coercionlogic", "pr_number": 1, "title": "Fix: require the correct file", "state": "open", "merged_at": null, "additions": 1, "deletions": 1, "files_changed": ["lib/coercionlogic.rb"], "files_before": {"lib/coercionlogic.rb": "require 'activerecord'\n\nmodule Coercionlogic\n def write_attribute_with_coercion(attr_name, value)\n value = nil if value.is_a?(String) && value.blank?\n write_attribute_without_coercion(attr_name, value)\n end\nend\n\nActiveRecord::Base.class_eval do\n include Coercionlogic\n alias_method_chain :write_attribute, :coercion\nend"}, "files_after": {"lib/coercionlogic.rb": "require 'active_record'\n\nmodule Coercionlogic\n def write_attribute_with_coercion(attr_name, value)\n value = nil if value.is_a?(String) && value.blank?\n write_attribute_without_coercion(attr_name, value)\n end\nend\n\nActiveRecord::Base.class_eval do\n include Coercionlogic\n alias_method_chain :write_attribute, :coercion\nend"}} -{"repo": "Skarabaeus/ImageColorPicker", "pr_number": 6, "title": "Unbind load event on destroy", "state": "open", "merged_at": null, "additions": 3, "deletions": 1, "files_changed": ["dist/jquery.ImageColorPicker.js", "dist/jquery.ImageColorPicker.min.js", "src/ImageColorPicker.js"], "files_before": {"dist/jquery.ImageColorPicker.js": "/*!\n* jQuery ImageColorPicker Plugin v0.2\n* http://github.com/Skarabaeus/ImageColorPicker\n*\n* Copyright 2010, Stefan Siebel\n* Licensed under the MIT license.\n* http://github.com/Skarabaeus/ImageColorPicker/MIT-LICENSE.txt\n* \n* Released under the MIT\n*\n* Date: Tue May 17 11:20:16 2011 -0700\n*/\n(function(){\nvar uiImageColorPicker = function(){\n\n\tvar _d2h = function(d) {\n\t\tvar result;\n\t\tif (! isNaN( parseInt(d) ) ) {\n\t\t\tresult = parseInt(d).toString(16);\n\t\t} else {\n\t\t\tresult = d;\n\t\t}\n\n\t\tif (result.length === 1) {\n\t\t\tresult = \"0\" + result;\n\t\t}\n\t\treturn result;\n\t};\n\n\tvar _h2d = function(h) {\n\t\treturn parseInt(h,16);\n\t};\n\n\tvar _createImageColorPicker = function(widget) {\n\t\t// store 2D context in widget for later access\n\t\twidget.ctx = null;\n\n\t\t// rgb\n\t\twidget.color = [0, 0, 0];\n\n\t\t// create additional DOM elements.\n\t\twidget.$canvas = $('');\n\n\t\t// add them to the DOM\n\t\twidget.element.wrap('
');\n\t\twidget.$wrapper = widget.element.parent();\n\t\twidget.$wrapper.append(widget.$canvas);\n\n\t\tif (typeof(widget.$canvas.get(0).getContext) === 'function') { // FF, Chrome, ...\n\t\t\twidget.ctx = widget.$canvas.get(0).getContext('2d');\n\n\t\t// this does not work yet!\n\t\t} else {\n\t\t\twidget.destroy();\n\t\t\tif (console) {\n\t\t\t\tconsole.log(\"ImageColor Picker: Can't get canvas context. Use \"\n\t\t\t\t\t+ \"Firefox, Chrome or include excanvas to your project.\");\n\t\t\t}\n\n\t\t}\n\n\t\t// draw the image in the canvas\n\t\tvar img = new Image();\n\t\timg.src = widget.element.attr(\"src\");\n\t\twidget.$canvas.attr(\"width\", img.width);\n\t\twidget.$canvas.attr(\"height\", img.height);\n\t\twidget.ctx.drawImage(img, 0, 0);\n\n\t\t// get the image data.\n\t\ttry {\n\t\t\ttry {\n\t\t\t\twidget.imageData = widget.ctx.getImageData(0, 0, img.width, img.height);\n\t\t\t} catch (e1) {\n\t\t\t\tnetscape.security.PrivilegeManager.enablePrivilege(\"UniversalBrowserRead\");\n\t\t\t\twidget.imageData = widget.ctx.getImageData(0, 0, img.width, img.height);\n\t\t\t}\n\t\t} catch (e2) {\n\t\t\twidget.destroy();\n\t\t\tif (console) {\n\t\t\t\tconsole.log(\"ImageColor Picker: Unable to access image data. \"\n\t\t\t\t\t+ \"This could be either due \"\n\t\t\t\t\t+ \"to the browser you are using (IE doesn't work) or image and script \"\n\t\t\t\t\t+ \"are saved on different servers or you run the script locally. \");\n\t\t\t}\n\t\t}\n\n\t\t// hide the original image\n\t\twidget.element.hide();\n\n\t\t// for usage in events\n\t\tvar that = widget;\n\n\t\twidget.$canvas.bind(\"mousemove\", function(e){\n var point = imageCoordinates( that, e.pageX, e.pageY );\n var color = lookupColor( that.imageData, point );\n\n updateCurrentColor( that, color.red, color.green, color.blue );\n\t\t});\n\n\t\twidget.$canvas.bind(\"click\", function(e){\n var point = imageCoordinates( that, e.pageX, e.pageY );\n var color = lookupColor( that.imageData, point );\n\n updateSelectedColor( that, color.red, color.green, color.blue );\n\t\t\tthat._trigger(\"afterColorSelected\", 0, that.selectedColor());\n\t\t});\n\n\t\twidget.$canvas.bind(\"mouseleave\", function(e){\n\t\t\tupdateCurrentColor(that, 255, 255, 255);\n\t\t});\n\n\t\t// hope that helps to prevent memory leaks\n\t\t$(window).unload(function(e){\n\t\t\tthat.destroy();\n\t\t});\n\t};\n\n // for pageX and pageY, determine image coordinates using offset\n var imageCoordinates = function( widget, pageX, pageY ) {\n var offset = widget.$canvas.offset();\n\n return { x: Math.round( pageX - offset.left ),\n y: Math.round( pageY - offset.top ) };\n }\n\n // lookup color values for point [x,y] location in image\n var lookupColor = function( imageData, point) {\n var pixel = ((point.y * imageData.width) + point.x) * 4;\n\n return { red: imageData.data[pixel],\n green: imageData.data[(pixel + 1)],\n blue: imageData.data[(pixel + 2)] }\n\n }\n\n\tvar updateCurrentColor = function(widget, red, green, blue) {\n\t\tvar c = widget.ctx;\n\t\tvar canvasWidth = widget.$canvas.attr(\"width\");\n\t\tvar canvasHeight = widget.$canvas.attr(\"height\");\n\n\t\t// draw current Color\n\t\tc.fillStyle = \"rgb(\" + red + \",\" + green + \",\" + blue + \")\";\n\t\tc.fillRect (canvasWidth - 62, canvasHeight - 32, 30, 30);\n\n\t\t// draw border\n\t\tc.lineWidth = \"3\"\n\t\tc.lineJoin = \"round\";\n\t\tc.strokeRect (canvasWidth - 62, canvasHeight - 32, 30, 30);\n\t}\n\n\tvar updateSelectedColor = function(widget, red, green, blue) {\n\t\tvar c = widget.ctx;\n\t\tvar canvasWidth = widget.$canvas.attr(\"width\");\n\t\tvar canvasHeight = widget.$canvas.attr(\"height\");\n\n\t\t// draw current Color\n\t\tc.fillStyle = \"rgb(\" + red + \",\" + green + \",\" + blue + \")\";\n\t\tc.fillRect (canvasWidth - 32, canvasHeight - 32, 30, 30);\n\n\t\t// draw border\n\t\tc.lineWidth = \"3\"\n\t\tc.lineJoin = \"round\";\n\t\tc.strokeRect (canvasWidth - 32, canvasHeight - 32, 30, 30);\n\n\t\t// set new selected color\n\t\tvar newColor = [red, green, blue];\n\t\twidget.color = newColor;\n\t}\n\n\treturn {\n\t\t// default options\n\t\toptions: {\n\n\t\t},\n\n\t\t_create: function() {\n\t\t\tif (this.element.get(0).tagName.toLowerCase() === 'img') {\n\t\t\t\tif (this.element.get(0).complete) {\n\t\t\t\t\t_createImageColorPicker(this);\n\t\t\t\t} else {\n\t\t\t\t\tthis.element.bind('load', { that: this }, function(e){\n\t\t\t\t\t\tvar that = e.data.that;\n\t\t\t\t\t\t_createImageColorPicker(that);\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\n\t\tdestroy: function() {\n\t\t\t// default destroy\n\t\t\t$.Widget.prototype.destroy.apply(this, arguments);\n\n\t\t\t// remove possible large array with pixel data\n\t\t\tthis.imageData = null;\n\n\t\t\t// remove additional elements\n\t\t\tthis.$canvas.remove();\n\t\t\tthis.element.unwrap();\n\t\t\tthis.element.show();\n\t\t},\n\n\t\tselectedColor: function() {\n\t\t\treturn \"#\" + _d2h(this.color[0]) + _d2h(this.color[1]) + _d2h(this.color[2]);\n\t\t}\n\n\t};\n}();\n\t$.widget(\"ui.ImageColorPicker\", uiImageColorPicker);\n})();\n", "dist/jquery.ImageColorPicker.min.js": "/*!\n* jQuery ImageColorPicker Plugin v0.2\n* http://github.com/Skarabaeus/ImageColorPicker\n*\n* Copyright 2010, Stefan Siebel\n* Licensed under the MIT license.\n* http://github.com/Skarabaeus/ImageColorPicker/MIT-LICENSE.txt\n* \n* Released under the MIT\n*\n* Date: Tue May 17 11:20:16 2011 -0700\n*/\n(function(){var n=function(){var g=function(a){a=isNaN(parseInt(a))?a:parseInt(a).toString(16);if(a.length===1)a=\"0\"+a;return a},k=function(a){a.ctx=null;a.color=[0,0,0];a.$canvas=$('');a.element.wrap('
');a.$wrapper=a.element.parent();a.$wrapper.append(a.$canvas);if(typeof a.$canvas.get(0).getContext===\"function\")a.ctx=a.$canvas.get(0).getContext(\"2d\");else{a.destroy();console&&console.log(\"ImageColor Picker: Can't get canvas context. Use Firefox, Chrome or include excanvas to your project.\")}var c=\nnew Image;c.src=a.element.attr(\"src\");a.$canvas.attr(\"width\",c.width);a.$canvas.attr(\"height\",c.height);a.ctx.drawImage(c,0,0);try{try{a.imageData=a.ctx.getImageData(0,0,c.width,c.height)}catch(d){netscape.security.PrivilegeManager.enablePrivilege(\"UniversalBrowserRead\");a.imageData=a.ctx.getImageData(0,0,c.width,c.height)}}catch(e){a.destroy();console&&console.log(\"ImageColor Picker: Unable to access image data. This could be either due to the browser you are using (IE doesn't work) or image and script are saved on different servers or you run the script locally. \")}a.element.hide();\na.$canvas.bind(\"mousemove\",function(b){b=h(a,b.pageX,b.pageY);b=i(a.imageData,b);j(a,b.red,b.green,b.blue)});a.$canvas.bind(\"click\",function(b){b=h(a,b.pageX,b.pageY);b=i(a.imageData,b);m(a,b.red,b.green,b.blue);a._trigger(\"afterColorSelected\",0,a.selectedColor())});a.$canvas.bind(\"mouseleave\",function(){j(a,255,255,255)});$(window).unload(function(){a.destroy()})},h=function(a,c,d){a=a.$canvas.offset();return{x:Math.round(c-a.left),y:Math.round(d-a.top)}},i=function(a,c){c=(c.y*a.width+c.x)*4;return{red:a.data[c],\ngreen:a.data[c+1],blue:a.data[c+2]}},j=function(a,c,d,e){var b=a.ctx,f=a.$canvas.attr(\"width\");a=a.$canvas.attr(\"height\");b.fillStyle=\"rgb(\"+c+\",\"+d+\",\"+e+\")\";b.fillRect(f-62,a-32,30,30);b.lineWidth=\"3\";b.lineJoin=\"round\";b.strokeRect(f-62,a-32,30,30)},m=function(a,c,d,e){var b=a.ctx,f=a.$canvas.attr(\"width\"),l=a.$canvas.attr(\"height\");b.fillStyle=\"rgb(\"+c+\",\"+d+\",\"+e+\")\";b.fillRect(f-32,l-32,30,30);b.lineWidth=\"3\";b.lineJoin=\"round\";b.strokeRect(f-32,l-32,30,30);a.color=[c,d,e]};return{options:{},\n_create:function(){if(this.element.get(0).tagName.toLowerCase()===\"img\")this.element.get(0).complete?k(this):this.element.bind(\"load\",{that:this},function(a){k(a.data.that)})},destroy:function(){$.Widget.prototype.destroy.apply(this,arguments);this.imageData=null;this.$canvas.remove();this.element.unwrap();this.element.show()},selectedColor:function(){return\"#\"+g(this.color[0])+g(this.color[1])+g(this.color[2])}}}();$.widget(\"ui.ImageColorPicker\",n)})();\n", "src/ImageColorPicker.js": "var uiImageColorPicker = function(){\n\n\tvar _d2h = function(d) {\n\t\tvar result;\n\t\tif (! isNaN( parseInt(d) ) ) {\n\t\t\tresult = parseInt(d).toString(16);\n\t\t} else {\n\t\t\tresult = d;\n\t\t}\n\n\t\tif (result.length === 1) {\n\t\t\tresult = \"0\" + result;\n\t\t}\n\t\treturn result;\n\t};\n\n\tvar _h2d = function(h) {\n\t\treturn parseInt(h,16);\n\t};\n\n\tvar _createImageColorPicker = function(widget) {\n\t\t// store 2D context in widget for later access\n\t\twidget.ctx = null;\n\n\t\t// rgb\n\t\twidget.color = [0, 0, 0];\n\n\t\t// create additional DOM elements.\n\t\twidget.$canvas = $('');\n\n\t\t// add them to the DOM\n\t\twidget.element.wrap('
');\n\t\twidget.$wrapper = widget.element.parent();\n\t\twidget.$wrapper.append(widget.$canvas);\n\n\t\tif (typeof(widget.$canvas.get(0).getContext) === 'function') { // FF, Chrome, ...\n\t\t\twidget.ctx = widget.$canvas.get(0).getContext('2d');\n\n\t\t// this does not work yet!\n\t\t} else {\n\t\t\twidget.destroy();\n\t\t\tif (console) {\n\t\t\t\tconsole.log(\"ImageColor Picker: Can't get canvas context. Use \"\n\t\t\t\t\t+ \"Firefox, Chrome or include excanvas to your project.\");\n\t\t\t}\n\n\t\t}\n\n\t\t// draw the image in the canvas\n\t\tvar img = new Image();\n\t\timg.src = widget.element.attr(\"src\");\n\t\twidget.$canvas.attr(\"width\", img.width);\n\t\twidget.$canvas.attr(\"height\", img.height);\n\t\twidget.ctx.drawImage(img, 0, 0);\n\n\t\t// get the image data.\n\t\ttry {\n\t\t\ttry {\n\t\t\t\twidget.imageData = widget.ctx.getImageData(0, 0, img.width, img.height);\n\t\t\t} catch (e1) {\n\t\t\t\tnetscape.security.PrivilegeManager.enablePrivilege(\"UniversalBrowserRead\");\n\t\t\t\twidget.imageData = widget.ctx.getImageData(0, 0, img.width, img.height);\n\t\t\t}\n\t\t} catch (e2) {\n\t\t\twidget.destroy();\n\t\t\tif (console) {\n\t\t\t\tconsole.log(\"ImageColor Picker: Unable to access image data. \"\n\t\t\t\t\t+ \"This could be either due \"\n\t\t\t\t\t+ \"to the browser you are using (IE doesn't work) or image and script \"\n\t\t\t\t\t+ \"are saved on different servers or you run the script locally. \");\n\t\t\t}\n\t\t}\n\n\t\t// hide the original image\n\t\twidget.element.hide();\n\n\t\t// for usage in events\n\t\tvar that = widget;\n\n\t\twidget.$canvas.bind(\"mousemove\", function(e){\n var point = imageCoordinates( that, e.pageX, e.pageY );\n var color = lookupColor( that.imageData, point );\n\n updateCurrentColor( that, color.red, color.green, color.blue );\n\t\t});\n\n\t\twidget.$canvas.bind(\"click\", function(e){\n var point = imageCoordinates( that, e.pageX, e.pageY );\n var color = lookupColor( that.imageData, point );\n\n updateSelectedColor( that, color.red, color.green, color.blue );\n\t\t\tthat._trigger(\"afterColorSelected\", 0, that.selectedColor());\n\t\t});\n\n\t\twidget.$canvas.bind(\"mouseleave\", function(e){\n\t\t\tupdateCurrentColor(that, 255, 255, 255);\n\t\t});\n\n\t\t// hope that helps to prevent memory leaks\n\t\t$(window).unload(function(e){\n\t\t\tthat.destroy();\n\t\t});\n\t};\n\n // for pageX and pageY, determine image coordinates using offset\n var imageCoordinates = function( widget, pageX, pageY ) {\n var offset = widget.$canvas.offset();\n\n return { x: Math.round( pageX - offset.left ),\n y: Math.round( pageY - offset.top ) };\n }\n\n // lookup color values for point [x,y] location in image\n var lookupColor = function( imageData, point) {\n var pixel = ((point.y * imageData.width) + point.x) * 4;\n\n return { red: imageData.data[pixel],\n green: imageData.data[(pixel + 1)],\n blue: imageData.data[(pixel + 2)] }\n\n }\n\n\tvar updateCurrentColor = function(widget, red, green, blue) {\n\t\tvar c = widget.ctx;\n\t\tvar canvasWidth = widget.$canvas.attr(\"width\");\n\t\tvar canvasHeight = widget.$canvas.attr(\"height\");\n\n\t\t// draw current Color\n\t\tc.fillStyle = \"rgb(\" + red + \",\" + green + \",\" + blue + \")\";\n\t\tc.fillRect (canvasWidth - 62, canvasHeight - 32, 30, 30);\n\n\t\t// draw border\n\t\tc.lineWidth = \"3\"\n\t\tc.lineJoin = \"round\";\n\t\tc.strokeRect (canvasWidth - 62, canvasHeight - 32, 30, 30);\n\t}\n\n\tvar updateSelectedColor = function(widget, red, green, blue) {\n\t\tvar c = widget.ctx;\n\t\tvar canvasWidth = widget.$canvas.attr(\"width\");\n\t\tvar canvasHeight = widget.$canvas.attr(\"height\");\n\n\t\t// draw current Color\n\t\tc.fillStyle = \"rgb(\" + red + \",\" + green + \",\" + blue + \")\";\n\t\tc.fillRect (canvasWidth - 32, canvasHeight - 32, 30, 30);\n\n\t\t// draw border\n\t\tc.lineWidth = \"3\"\n\t\tc.lineJoin = \"round\";\n\t\tc.strokeRect (canvasWidth - 32, canvasHeight - 32, 30, 30);\n\n\t\t// set new selected color\n\t\tvar newColor = [red, green, blue];\n\t\twidget.color = newColor;\n\t}\n\n\treturn {\n\t\t// default options\n\t\toptions: {\n\n\t\t},\n\n\t\t_create: function() {\n\t\t\tif (this.element.get(0).tagName.toLowerCase() === 'img') {\n\t\t\t\tif (this.element.get(0).complete) {\n\t\t\t\t\t_createImageColorPicker(this);\n\t\t\t\t} else {\n\t\t\t\t\tthis.element.bind('load', { that: this }, function(e){\n\t\t\t\t\t\tvar that = e.data.that;\n\t\t\t\t\t\t_createImageColorPicker(that);\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\n\t\tdestroy: function() {\n\t\t\t// default destroy\n\t\t\t$.Widget.prototype.destroy.apply(this, arguments);\n\n\t\t\t// remove possible large array with pixel data\n\t\t\tthis.imageData = null;\n\n\t\t\t// remove additional elements\n\t\t\tthis.$canvas.remove();\n\t\t\tthis.element.unwrap();\n\t\t\tthis.element.show();\n\t\t},\n\n\t\tselectedColor: function() {\n\t\t\treturn \"#\" + _d2h(this.color[0]) + _d2h(this.color[1]) + _d2h(this.color[2]);\n\t\t}\n\n\t};\n}();\n"}, "files_after": {"dist/jquery.ImageColorPicker.js": "/*!\n* jQuery ImageColorPicker Plugin v0.2\n* http://github.com/Skarabaeus/ImageColorPicker\n*\n* Copyright 2010, Stefan Siebel\n* Licensed under the MIT license.\n* http://github.com/Skarabaeus/ImageColorPicker/MIT-LICENSE.txt\n* \n* Released under the MIT\n*\n* Date: Tue May 17 11:20:16 2011 -0700\n*/\n(function(){\nvar uiImageColorPicker = function(){\n\n\tvar _d2h = function(d) {\n\t\tvar result;\n\t\tif (! isNaN( parseInt(d) ) ) {\n\t\t\tresult = parseInt(d).toString(16);\n\t\t} else {\n\t\t\tresult = d;\n\t\t}\n\n\t\tif (result.length === 1) {\n\t\t\tresult = \"0\" + result;\n\t\t}\n\t\treturn result;\n\t};\n\n\tvar _h2d = function(h) {\n\t\treturn parseInt(h,16);\n\t};\n\n\tvar _createImageColorPicker = function(widget) {\n\t\t// store 2D context in widget for later access\n\t\twidget.ctx = null;\n\n\t\t// rgb\n\t\twidget.color = [0, 0, 0];\n\n\t\t// create additional DOM elements.\n\t\twidget.$canvas = $('');\n\n\t\t// add them to the DOM\n\t\twidget.element.wrap('
');\n\t\twidget.$wrapper = widget.element.parent();\n\t\twidget.$wrapper.append(widget.$canvas);\n\n\t\tif (typeof(widget.$canvas.get(0).getContext) === 'function') { // FF, Chrome, ...\n\t\t\twidget.ctx = widget.$canvas.get(0).getContext('2d');\n\n\t\t// this does not work yet!\n\t\t} else {\n\t\t\twidget.destroy();\n\t\t\tif (console) {\n\t\t\t\tconsole.log(\"ImageColor Picker: Can't get canvas context. Use \"\n\t\t\t\t\t+ \"Firefox, Chrome or include excanvas to your project.\");\n\t\t\t}\n\n\t\t}\n\n\t\t// draw the image in the canvas\n\t\tvar img = new Image();\n\t\timg.src = widget.element.attr(\"src\");\n\t\twidget.$canvas.attr(\"width\", img.width);\n\t\twidget.$canvas.attr(\"height\", img.height);\n\t\twidget.ctx.drawImage(img, 0, 0);\n\n\t\t// get the image data.\n\t\ttry {\n\t\t\ttry {\n\t\t\t\twidget.imageData = widget.ctx.getImageData(0, 0, img.width, img.height);\n\t\t\t} catch (e1) {\n\t\t\t\tnetscape.security.PrivilegeManager.enablePrivilege(\"UniversalBrowserRead\");\n\t\t\t\twidget.imageData = widget.ctx.getImageData(0, 0, img.width, img.height);\n\t\t\t}\n\t\t} catch (e2) {\n\t\t\twidget.destroy();\n\t\t\tif (console) {\n\t\t\t\tconsole.log(\"ImageColor Picker: Unable to access image data. \"\n\t\t\t\t\t+ \"This could be either due \"\n\t\t\t\t\t+ \"to the browser you are using (IE doesn't work) or image and script \"\n\t\t\t\t\t+ \"are saved on different servers or you run the script locally. \");\n\t\t\t}\n\t\t}\n\n\t\t// hide the original image\n\t\twidget.element.hide();\n\n\t\t// for usage in events\n\t\tvar that = widget;\n\n\t\twidget.$canvas.bind(\"mousemove\", function(e){\n var point = imageCoordinates( that, e.pageX, e.pageY );\n var color = lookupColor( that.imageData, point );\n\n updateCurrentColor( that, color.red, color.green, color.blue );\n\t\t});\n\n\t\twidget.$canvas.bind(\"click\", function(e){\n var point = imageCoordinates( that, e.pageX, e.pageY );\n var color = lookupColor( that.imageData, point );\n\n updateSelectedColor( that, color.red, color.green, color.blue );\n\t\t\tthat._trigger(\"afterColorSelected\", 0, that.selectedColor());\n\t\t});\n\n\t\twidget.$canvas.bind(\"mouseleave\", function(e){\n\t\t\tupdateCurrentColor(that, 255, 255, 255);\n\t\t});\n\n\t\t// hope that helps to prevent memory leaks\n\t\t$(window).unload(function(e){\n\t\t\tthat.destroy();\n\t\t});\n\t};\n\n // for pageX and pageY, determine image coordinates using offset\n var imageCoordinates = function( widget, pageX, pageY ) {\n var offset = widget.$canvas.offset();\n\n return { x: Math.round( pageX - offset.left ),\n y: Math.round( pageY - offset.top ) };\n }\n\n // lookup color values for point [x,y] location in image\n var lookupColor = function( imageData, point) {\n var pixel = ((point.y * imageData.width) + point.x) * 4;\n\n return { red: imageData.data[pixel],\n green: imageData.data[(pixel + 1)],\n blue: imageData.data[(pixel + 2)] }\n\n }\n\n\tvar updateCurrentColor = function(widget, red, green, blue) {\n\t\tvar c = widget.ctx;\n\t\tvar canvasWidth = widget.$canvas.attr(\"width\");\n\t\tvar canvasHeight = widget.$canvas.attr(\"height\");\n\n\t\t// draw current Color\n\t\tc.fillStyle = \"rgb(\" + red + \",\" + green + \",\" + blue + \")\";\n\t\tc.fillRect (canvasWidth - 62, canvasHeight - 32, 30, 30);\n\n\t\t// draw border\n\t\tc.lineWidth = \"3\"\n\t\tc.lineJoin = \"round\";\n\t\tc.strokeRect (canvasWidth - 62, canvasHeight - 32, 30, 30);\n\t}\n\n\tvar updateSelectedColor = function(widget, red, green, blue) {\n\t\tvar c = widget.ctx;\n\t\tvar canvasWidth = widget.$canvas.attr(\"width\");\n\t\tvar canvasHeight = widget.$canvas.attr(\"height\");\n\n\t\t// draw current Color\n\t\tc.fillStyle = \"rgb(\" + red + \",\" + green + \",\" + blue + \")\";\n\t\tc.fillRect (canvasWidth - 32, canvasHeight - 32, 30, 30);\n\n\t\t// draw border\n\t\tc.lineWidth = \"3\"\n\t\tc.lineJoin = \"round\";\n\t\tc.strokeRect (canvasWidth - 32, canvasHeight - 32, 30, 30);\n\n\t\t// set new selected color\n\t\tvar newColor = [red, green, blue];\n\t\twidget.color = newColor;\n\t}\n\n\treturn {\n\t\t// default options\n\t\toptions: {\n\n\t\t},\n\n\t\t_create: function() {\n\t\t\tif (this.element.get(0).tagName.toLowerCase() === 'img') {\n\t\t\t\tif (this.element.get(0).complete) {\n\t\t\t\t\t_createImageColorPicker(this);\n\t\t\t\t} else {\n\t\t\t\t\tthis.element.bind('load', { that: this }, function(e){\n\t\t\t\t\t\tvar that = e.data.that;\n\t\t\t\t\t\t_createImageColorPicker(that);\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\n\t\tdestroy: function() {\n\t\t\t// default destroy\n\t\t\t$.Widget.prototype.destroy.apply(this, arguments);\n\n\t\t\t// remove possible large array with pixel data\n\t\t\tthis.imageData = null;\n\n\t\t\t// remove additional elements\n\t\t\tthis.$canvas.remove();\n\t\t\tthis.element.unbind('load');\n\t\t\tthis.element.unwrap();\n\t\t\tthis.element.show();\n\t\t},\n\n\t\tselectedColor: function() {\n\t\t\treturn \"#\" + _d2h(this.color[0]) + _d2h(this.color[1]) + _d2h(this.color[2]);\n\t\t}\n\n\t};\n}();\n\t$.widget(\"ui.ImageColorPicker\", uiImageColorPicker);\n})();\n", "dist/jquery.ImageColorPicker.min.js": "/*!\n* jQuery ImageColorPicker Plugin v0.2\n* http://github.com/Skarabaeus/ImageColorPicker\n*\n* Copyright 2010, Stefan Siebel\n* Licensed under the MIT license.\n* http://github.com/Skarabaeus/ImageColorPicker/MIT-LICENSE.txt\n* \n* Released under the MIT\n*\n* Date: Tue May 17 11:20:16 2011 -0700\n*/\n(function(){var n=function(){var g=function(a){a=isNaN(parseInt(a))?a:parseInt(a).toString(16);if(a.length===1)a=\"0\"+a;return a},k=function(a){a.ctx=null;a.color=[0,0,0];a.$canvas=$('');a.element.wrap('
');a.$wrapper=a.element.parent();a.$wrapper.append(a.$canvas);if(typeof a.$canvas.get(0).getContext===\"function\")a.ctx=a.$canvas.get(0).getContext(\"2d\");else{a.destroy();console&&console.log(\"ImageColor Picker: Can't get canvas context. Use Firefox, Chrome or include excanvas to your project.\")}var c=\nnew Image;c.src=a.element.attr(\"src\");a.$canvas.attr(\"width\",c.width);a.$canvas.attr(\"height\",c.height);a.ctx.drawImage(c,0,0);try{try{a.imageData=a.ctx.getImageData(0,0,c.width,c.height)}catch(d){netscape.security.PrivilegeManager.enablePrivilege(\"UniversalBrowserRead\");a.imageData=a.ctx.getImageData(0,0,c.width,c.height)}}catch(e){a.destroy();console&&console.log(\"ImageColor Picker: Unable to access image data. This could be either due to the browser you are using (IE doesn't work) or image and script are saved on different servers or you run the script locally. \")}a.element.hide();\na.$canvas.bind(\"mousemove\",function(b){b=h(a,b.pageX,b.pageY);b=i(a.imageData,b);j(a,b.red,b.green,b.blue)});a.$canvas.bind(\"click\",function(b){b=h(a,b.pageX,b.pageY);b=i(a.imageData,b);m(a,b.red,b.green,b.blue);a._trigger(\"afterColorSelected\",0,a.selectedColor())});a.$canvas.bind(\"mouseleave\",function(){j(a,255,255,255)});$(window).unload(function(){a.destroy()})},h=function(a,c,d){a=a.$canvas.offset();return{x:Math.round(c-a.left),y:Math.round(d-a.top)}},i=function(a,c){c=(c.y*a.width+c.x)*4;return{red:a.data[c],\ngreen:a.data[c+1],blue:a.data[c+2]}},j=function(a,c,d,e){var b=a.ctx,f=a.$canvas.attr(\"width\");a=a.$canvas.attr(\"height\");b.fillStyle=\"rgb(\"+c+\",\"+d+\",\"+e+\")\";b.fillRect(f-62,a-32,30,30);b.lineWidth=\"3\";b.lineJoin=\"round\";b.strokeRect(f-62,a-32,30,30)},m=function(a,c,d,e){var b=a.ctx,f=a.$canvas.attr(\"width\"),l=a.$canvas.attr(\"height\");b.fillStyle=\"rgb(\"+c+\",\"+d+\",\"+e+\")\";b.fillRect(f-32,l-32,30,30);b.lineWidth=\"3\";b.lineJoin=\"round\";b.strokeRect(f-32,l-32,30,30);a.color=[c,d,e]};return{options:{},\n_create:function(){if(this.element.get(0).tagName.toLowerCase()===\"img\")this.element.get(0).complete?k(this):this.element.bind(\"load\",{that:this},function(a){k(a.data.that)})},destroy:function(){$.Widget.prototype.destroy.apply(this,arguments);this.imageData=null;this.$canvas.remove();this.element.unbind('load');this.element.unwrap();this.element.show()},selectedColor:function(){return\"#\"+g(this.color[0])+g(this.color[1])+g(this.color[2])}}}();$.widget(\"ui.ImageColorPicker\",n)})();\n", "src/ImageColorPicker.js": "var uiImageColorPicker = function(){\n\n\tvar _d2h = function(d) {\n\t\tvar result;\n\t\tif (! isNaN( parseInt(d) ) ) {\n\t\t\tresult = parseInt(d).toString(16);\n\t\t} else {\n\t\t\tresult = d;\n\t\t}\n\n\t\tif (result.length === 1) {\n\t\t\tresult = \"0\" + result;\n\t\t}\n\t\treturn result;\n\t};\n\n\tvar _h2d = function(h) {\n\t\treturn parseInt(h,16);\n\t};\n\n\tvar _createImageColorPicker = function(widget) {\n\t\t// store 2D context in widget for later access\n\t\twidget.ctx = null;\n\n\t\t// rgb\n\t\twidget.color = [0, 0, 0];\n\n\t\t// create additional DOM elements.\n\t\twidget.$canvas = $('');\n\n\t\t// add them to the DOM\n\t\twidget.element.wrap('
');\n\t\twidget.$wrapper = widget.element.parent();\n\t\twidget.$wrapper.append(widget.$canvas);\n\n\t\tif (typeof(widget.$canvas.get(0).getContext) === 'function') { // FF, Chrome, ...\n\t\t\twidget.ctx = widget.$canvas.get(0).getContext('2d');\n\n\t\t// this does not work yet!\n\t\t} else {\n\t\t\twidget.destroy();\n\t\t\tif (console) {\n\t\t\t\tconsole.log(\"ImageColor Picker: Can't get canvas context. Use \"\n\t\t\t\t\t+ \"Firefox, Chrome or include excanvas to your project.\");\n\t\t\t}\n\n\t\t}\n\n\t\t// draw the image in the canvas\n\t\tvar img = new Image();\n\t\timg.src = widget.element.attr(\"src\");\n\t\twidget.$canvas.attr(\"width\", img.width);\n\t\twidget.$canvas.attr(\"height\", img.height);\n\t\twidget.ctx.drawImage(img, 0, 0);\n\n\t\t// get the image data.\n\t\ttry {\n\t\t\ttry {\n\t\t\t\twidget.imageData = widget.ctx.getImageData(0, 0, img.width, img.height);\n\t\t\t} catch (e1) {\n\t\t\t\tnetscape.security.PrivilegeManager.enablePrivilege(\"UniversalBrowserRead\");\n\t\t\t\twidget.imageData = widget.ctx.getImageData(0, 0, img.width, img.height);\n\t\t\t}\n\t\t} catch (e2) {\n\t\t\twidget.destroy();\n\t\t\tif (console) {\n\t\t\t\tconsole.log(\"ImageColor Picker: Unable to access image data. \"\n\t\t\t\t\t+ \"This could be either due \"\n\t\t\t\t\t+ \"to the browser you are using (IE doesn't work) or image and script \"\n\t\t\t\t\t+ \"are saved on different servers or you run the script locally. \");\n\t\t\t}\n\t\t}\n\n\t\t// hide the original image\n\t\twidget.element.hide();\n\n\t\t// for usage in events\n\t\tvar that = widget;\n\n\t\twidget.$canvas.bind(\"mousemove\", function(e){\n var point = imageCoordinates( that, e.pageX, e.pageY );\n var color = lookupColor( that.imageData, point );\n\n updateCurrentColor( that, color.red, color.green, color.blue );\n\t\t});\n\n\t\twidget.$canvas.bind(\"click\", function(e){\n var point = imageCoordinates( that, e.pageX, e.pageY );\n var color = lookupColor( that.imageData, point );\n\n updateSelectedColor( that, color.red, color.green, color.blue );\n\t\t\tthat._trigger(\"afterColorSelected\", 0, that.selectedColor());\n\t\t});\n\n\t\twidget.$canvas.bind(\"mouseleave\", function(e){\n\t\t\tupdateCurrentColor(that, 255, 255, 255);\n\t\t});\n\n\t\t// hope that helps to prevent memory leaks\n\t\t$(window).unload(function(e){\n\t\t\tthat.destroy();\n\t\t});\n\t};\n\n // for pageX and pageY, determine image coordinates using offset\n var imageCoordinates = function( widget, pageX, pageY ) {\n var offset = widget.$canvas.offset();\n\n return { x: Math.round( pageX - offset.left ),\n y: Math.round( pageY - offset.top ) };\n }\n\n // lookup color values for point [x,y] location in image\n var lookupColor = function( imageData, point) {\n var pixel = ((point.y * imageData.width) + point.x) * 4;\n\n return { red: imageData.data[pixel],\n green: imageData.data[(pixel + 1)],\n blue: imageData.data[(pixel + 2)] }\n\n }\n\n\tvar updateCurrentColor = function(widget, red, green, blue) {\n\t\tvar c = widget.ctx;\n\t\tvar canvasWidth = widget.$canvas.attr(\"width\");\n\t\tvar canvasHeight = widget.$canvas.attr(\"height\");\n\n\t\t// draw current Color\n\t\tc.fillStyle = \"rgb(\" + red + \",\" + green + \",\" + blue + \")\";\n\t\tc.fillRect (canvasWidth - 62, canvasHeight - 32, 30, 30);\n\n\t\t// draw border\n\t\tc.lineWidth = \"3\"\n\t\tc.lineJoin = \"round\";\n\t\tc.strokeRect (canvasWidth - 62, canvasHeight - 32, 30, 30);\n\t}\n\n\tvar updateSelectedColor = function(widget, red, green, blue) {\n\t\tvar c = widget.ctx;\n\t\tvar canvasWidth = widget.$canvas.attr(\"width\");\n\t\tvar canvasHeight = widget.$canvas.attr(\"height\");\n\n\t\t// draw current Color\n\t\tc.fillStyle = \"rgb(\" + red + \",\" + green + \",\" + blue + \")\";\n\t\tc.fillRect (canvasWidth - 32, canvasHeight - 32, 30, 30);\n\n\t\t// draw border\n\t\tc.lineWidth = \"3\"\n\t\tc.lineJoin = \"round\";\n\t\tc.strokeRect (canvasWidth - 32, canvasHeight - 32, 30, 30);\n\n\t\t// set new selected color\n\t\tvar newColor = [red, green, blue];\n\t\twidget.color = newColor;\n\t}\n\n\treturn {\n\t\t// default options\n\t\toptions: {\n\n\t\t},\n\n\t\t_create: function() {\n\t\t\tif (this.element.get(0).tagName.toLowerCase() === 'img') {\n\t\t\t\tif (this.element.get(0).complete) {\n\t\t\t\t\t_createImageColorPicker(this);\n\t\t\t\t} else {\n\t\t\t\t\tthis.element.bind('load', { that: this }, function(e){\n\t\t\t\t\t\tvar that = e.data.that;\n\t\t\t\t\t\t_createImageColorPicker(that);\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\n\t\tdestroy: function() {\n\t\t\t// default destroy\n\t\t\t$.Widget.prototype.destroy.apply(this, arguments);\n\n\t\t\t// remove possible large array with pixel data\n\t\t\tthis.imageData = null;\n\n\t\t\t// remove additional elements\n\t\t\tthis.$canvas.remove();\n\t\t\tthis.element.unbind('load');\n\t\t\tthis.element.unwrap();\n\t\t\tthis.element.show();\n\t\t},\n\n\t\tselectedColor: function() {\n\t\t\treturn \"#\" + _d2h(this.color[0]) + _d2h(this.color[1]) + _d2h(this.color[2]);\n\t\t}\n\n\t};\n}();\n"}} -{"repo": "Fantomas42/easy-extract", "pr_number": 2, "title": "Handle spaces by quoting the command string instead of escaping", "state": "closed", "merged_at": null, "additions": 10, "deletions": 10, "files_changed": ["easy_extract/__init__.py", "easy_extract/archive.py", "easy_extract/archives/hj_split.py", "easy_extract/archives/media.py", "easy_extract/archives/rar.py", "easy_extract/archives/seven_zip.py", "easy_extract/archives/xtm.py"], "files_before": {"easy_extract/__init__.py": "\"\"\"easy_extract module\"\"\"\n__version__ = '0.1.2'\n__license__ = 'GPL'\n\n__author__ = 'Fantomas42'\n__email__ = 'fantomas42@gmail.com'\n\n__url__ = 'https://github.com/Fantomas42/easy-extract'\n", "easy_extract/archive.py": "\"\"\"Archive collection modules\"\"\"\nimport os\n\nCHAR_TO_ESCAPE = (' ', '(', ')', '*', \"'\", '\"', '&')\n\n\nclass BaseFileCollection(object):\n \"\"\"Base file collection\"\"\"\n\n def __init__(self, name, path='.', filenames=[]):\n self.name = name\n self.path = path\n self.filenames = filenames\n\n @property\n def files(self):\n return self.filenames\n\n def escape_filename(self, filename):\n \"\"\"Escape a filename\"\"\"\n for char in CHAR_TO_ESCAPE:\n filename = filename.replace(char, '\\%s' % char)\n return filename\n\n def get_path_filename(self, filename):\n \"\"\"Concatenate path and filename\"\"\"\n return os.path.join(self.path, filename)\n\n def get_command_filename(self, filename):\n \"\"\"Convert filename for command line\"\"\"\n return self.escape_filename(self.get_path_filename(filename))\n\n def remove(self):\n \"\"\"Remove all files collection\"\"\"\n return os.system('rm -f %s' % ' '.join(\n [self.get_command_filename(f) for f in self.files]))\n\n\nclass MedKit(BaseFileCollection):\n \"\"\"MedKit is collection of par2 files\"\"\"\n\n def __init__(self, name, path='.', filenames=[]):\n super(MedKit, self).__init__(name, path, filenames)\n self.medkits = []\n self.find_medkits(self.filenames)\n\n @property\n def files(self):\n return self.medkits\n\n def is_medkit_file(self, filename):\n \"\"\"Check if the filename is a medkit\"\"\"\n return bool(filename.startswith(self.name) and\n filename.lower().endswith('.par2'))\n\n def find_medkits(self, filenames=[]):\n \"\"\"Find files for building the medkit\"\"\"\n for filename in filenames:\n if self.is_medkit_file(filename) and filename not in self.medkits:\n self.medkits.append(filename)\n self.medkits.sort()\n\n def check_and_repair(self, silent=False):\n \"\"\"Check and repair with medkits\"\"\"\n if self.medkits:\n options = silent and '-qq' or ''\n root_medkit = self.get_command_filename(self.medkits[0])\n extra_kits = '%s*' % self.get_command_filename(self.name)\n command = 'par2 r %s %s %s' % (options, root_medkit, extra_kits)\n result = os.system(command)\n return bool(not result)\n return False\n\n\nclass Archive(MedKit):\n \"\"\"Archive is a collection of archive files and a MedKit\"\"\"\n archive_type = 'undefined'\n ALLOWED_EXTENSIONS = []\n\n def __init__(self, name, path='.', filenames=[]):\n super(Archive, self).__init__(name, path, filenames)\n self.archives = []\n self.find_archives(self.filenames)\n\n @property\n def files(self):\n return self.archives + self.medkits\n\n @classmethod\n def is_archive_file(cls, filename):\n \"\"\"Check if the filename is allowed for the Archive\"\"\"\n for regext in cls.ALLOWED_EXTENSIONS:\n if regext.search(filename):\n return regext.split(filename)[0]\n return False\n\n def find_archives(self, filenames=[]):\n \"\"\"Find files for building the archive\"\"\"\n for filename in filenames:\n if (filename.startswith(self.name) and\n self.is_archive_file(filename) and\n filename not in self.archives):\n self.archives.append(filename)\n self.archives.sort()\n\n def extract(self, repair=True):\n \"\"\"Extract the archive and do integrity checking\"\"\"\n extraction = self._extract()\n\n if not extraction and repair:\n if self.check_and_repair():\n extraction = self._extract()\n\n return extraction\n\n def _extract(self):\n \"\"\"Extract the archive\"\"\"\n raise NotImplementedError\n\n def __str__(self):\n if self.medkits:\n return '%s (%i %s archives, %i par2 files)' % (\n self.name, len(self.archives),\n self.archive_type, len(self.medkits))\n return '%s (%i %s archives)' % (\n self.name, len(self.archives), self.archive_type)\n", "easy_extract/archives/hj_split.py": "\"\"\"HJ Split archive format\"\"\"\nimport os\nimport re\n\nfrom easy_extract.archive import Archive\n\nEXTENSIONS = [re.compile('\\.\\d{3}$', re.I)]\n\n\nclass HJSplitArchive(Archive):\n \"\"\"The HJ Split format\"\"\"\n archive_type = 'hj-split'\n ALLOWED_EXTENSIONS = EXTENSIONS\n\n def _extract(self):\n new_filename = self.escape_filename(self.name)\n first_archive = self.get_command_filename(self.archives[0])\n\n print 'Extracting %s...' % new_filename\n\n os.system('cat %s > %s' % (first_archive, new_filename))\n\n for archive in self.archives[1:]:\n archive = self.get_command_filename(archive)\n os.system('cat %s >> %s' % (archive, new_filename))\n\n return True\n\n def remove(self):\n pass\n", "easy_extract/archives/media.py": "\"\"\"Media archive file format\"\"\"\nimport os\nimport re\n\nfrom easy_extract.archive import Archive\n\nRAW_EXTENSIONS = ['\\.AVI', '\\.OGG', '\\.OGV',\n '\\.MP4', '\\.MPG', '\\.MPEG',\n '\\.MKV', '\\.M4V']\n\nEXTENSIONS = [re.compile('%s$' % ext, re.I) for ext in RAW_EXTENSIONS]\n\n\nclass MediaArchive(Archive):\n \"\"\"The Rar format Archive\"\"\"\n archive_type = 'media'\n ALLOWED_EXTENSIONS = EXTENSIONS\n\n def _extract(self):\n first_archive = self.get_command_filename(self.archives[0])\n return not os.system('synoindex -a %s' % first_archive)\n\n def remove(self):\n pass\n", "easy_extract/archives/rar.py": "\"\"\"Rar archive format\"\"\"\nimport os\nimport re\n\nfrom easy_extract.archive import Archive\n\nEXTENSIONS = [re.compile('\\.r\\d{2}$', re.I),\n re.compile('\\.part\\d+\\.rar$', re.I),\n re.compile('\\.rar$', re.I)]\n\n\nclass RarArchive(Archive):\n \"\"\"The Rar format Archive\"\"\"\n archive_type = 'rar'\n ALLOWED_EXTENSIONS = EXTENSIONS\n\n def _extract(self):\n if '%s.rar' % self.name in self.archives:\n first_archive = self.get_command_filename('%s.rar' % self.name)\n else:\n first_archive = self.get_command_filename(self.archives[0])\n\n return not os.system('unrar e -o+ %s' % first_archive)\n", "easy_extract/archives/seven_zip.py": "\"\"\"7zip archive format\"\"\"\nimport os\nimport re\n\nfrom easy_extract.archive import Archive\n\nRAW_EXTENSIONS = ['\\.ARJ', '\\.CAB', '\\.CHM', '\\.CPIO',\n '\\.DMG', '\\.HFS', '\\.LZH', '\\.LZMA',\n '\\.NSIS', '\\.UDF', '\\.WIM', '\\.XAR',\n '\\.Z', '\\.ZIP', '\\.GZIP', '\\.TAR']\n\nEXTENSIONS = [re.compile('%s$' % ext, re.I) for ext in RAW_EXTENSIONS]\n\n\nclass SevenZipArchive(Archive):\n \"\"\"The 7z unarchiver is used for many formats\"\"\"\n archive_type = '7zip'\n ALLOWED_EXTENSIONS = EXTENSIONS\n\n def _extract(self):\n first_archive = self.get_command_filename(self.archives[0])\n return not os.system('7z e -y %s' % first_archive)\n", "easy_extract/archives/xtm.py": "\"\"\"Xtm archive format\"\"\"\nimport os\nimport re\n\nfrom easy_extract.archive import Archive\n\nEXTENSIONS = [re.compile('\\.\\d{3}\\.xtm$', re.I),\n re.compile('\\.xtm$', re.I)]\n\n\nclass XtmArchive(Archive):\n \"\"\"The XTM archive format\"\"\"\n archive_type = 'xtm'\n ALLOWED_EXTENSIONS = EXTENSIONS\n\n def _extract(self):\n new_filename = self.escape_filename(self.name)\n first_archive = self.get_command_filename(self.archives[0])\n\n print 'Extracting %s...' % new_filename\n\n os.system('dd if=%s skip=1 ibs=104 status=noxfer > %s 2>/dev/null' %\n (first_archive, new_filename))\n\n for archive in self.archives[1:]:\n archive = self.get_command_filename(archive)\n os.system('cat %s >> %s' % (archive, new_filename))\n\n return True\n\n def remove(self):\n pass\n"}, "files_after": {"easy_extract/__init__.py": "\"\"\"easy_extract module\"\"\"\n__version__ = '0.1.3'\n__license__ = 'GPL'\n\n__author__ = 'Fantomas42'\n__email__ = 'fantomas42@gmail.com'\n\n__url__ = 'https://github.com/Fantomas42/easy-extract'\n", "easy_extract/archive.py": "\"\"\"Archive collection modules\"\"\"\nimport os\n\nCHAR_TO_ESCAPE = ('(', ')', '*', \"'\", '\"', '&')\n\n\nclass BaseFileCollection(object):\n \"\"\"Base file collection\"\"\"\n\n def __init__(self, name, path='.', filenames=[]):\n self.name = name\n self.path = path\n self.filenames = filenames\n\n @property\n def files(self):\n return self.filenames\n\n def escape_filename(self, filename):\n \"\"\"Escape a filename\"\"\"\n for char in CHAR_TO_ESCAPE:\n filename = filename.replace(char, '\\%s' % char)\n return filename\n\n def get_path_filename(self, filename):\n \"\"\"Concatenate path and filename\"\"\"\n return os.path.join(self.path, filename)\n\n def get_command_filename(self, filename):\n \"\"\"Convert filename for command line\"\"\"\n return self.escape_filename(self.get_path_filename(filename))\n\n def remove(self):\n \"\"\"Remove all files collection\"\"\"\n return os.system('rm -f %s' % ' '.join(\n [self.get_command_filename(f) for f in self.files]))\n\n\nclass MedKit(BaseFileCollection):\n \"\"\"MedKit is collection of par2 files\"\"\"\n\n def __init__(self, name, path='.', filenames=[]):\n super(MedKit, self).__init__(name, path, filenames)\n self.medkits = []\n self.find_medkits(self.filenames)\n\n @property\n def files(self):\n return self.medkits\n\n def is_medkit_file(self, filename):\n \"\"\"Check if the filename is a medkit\"\"\"\n return bool(filename.startswith(self.name) and\n filename.lower().endswith('.par2'))\n\n def find_medkits(self, filenames=[]):\n \"\"\"Find files for building the medkit\"\"\"\n for filename in filenames:\n if self.is_medkit_file(filename) and filename not in self.medkits:\n self.medkits.append(filename)\n self.medkits.sort()\n\n def check_and_repair(self, silent=False):\n \"\"\"Check and repair with medkits\"\"\"\n if self.medkits:\n options = silent and '-qq' or ''\n root_medkit = self.get_command_filename(self.medkits[0])\n extra_kits = '%s*' % self.get_command_filename(self.name)\n command = 'par2 r %s %s %s' % (options, root_medkit, extra_kits)\n result = os.system(command)\n return bool(not result)\n return False\n\n\nclass Archive(MedKit):\n \"\"\"Archive is a collection of archive files and a MedKit\"\"\"\n archive_type = 'undefined'\n ALLOWED_EXTENSIONS = []\n\n def __init__(self, name, path='.', filenames=[]):\n super(Archive, self).__init__(name, path, filenames)\n self.archives = []\n self.find_archives(self.filenames)\n\n @property\n def files(self):\n return self.archives + self.medkits\n\n @classmethod\n def is_archive_file(cls, filename):\n \"\"\"Check if the filename is allowed for the Archive\"\"\"\n for regext in cls.ALLOWED_EXTENSIONS:\n if regext.search(filename):\n return regext.split(filename)[0]\n return False\n\n def find_archives(self, filenames=[]):\n \"\"\"Find files for building the archive\"\"\"\n for filename in filenames:\n if (filename.startswith(self.name) and\n self.is_archive_file(filename) and\n filename not in self.archives):\n self.archives.append(filename)\n self.archives.sort()\n\n def extract(self, repair=True):\n \"\"\"Extract the archive and do integrity checking\"\"\"\n extraction = self._extract()\n\n if not extraction and repair:\n if self.check_and_repair():\n extraction = self._extract()\n\n return extraction\n\n def _extract(self):\n \"\"\"Extract the archive\"\"\"\n raise NotImplementedError\n\n def __str__(self):\n if self.medkits:\n return '%s (%i %s archives, %i par2 files)' % (\n self.name, len(self.archives),\n self.archive_type, len(self.medkits))\n return '%s (%i %s archives)' % (\n self.name, len(self.archives), self.archive_type)\n", "easy_extract/archives/hj_split.py": "\"\"\"HJ Split archive format\"\"\"\nimport os\nimport re\n\nfrom easy_extract.archive import Archive\n\nEXTENSIONS = [re.compile('\\.\\d{3}$', re.I)]\n\n\nclass HJSplitArchive(Archive):\n \"\"\"The HJ Split format\"\"\"\n archive_type = 'hj-split'\n ALLOWED_EXTENSIONS = EXTENSIONS\n\n def _extract(self):\n new_filename = self.escape_filename(self.name)\n first_archive = self.get_command_filename(self.archives[0])\n\n print 'Extracting %s...' % new_filename\n\n os.system('cat \"%s\" > \"%s\"' % (first_archive, new_filename))\n\n for archive in self.archives[1:]:\n archive = self.get_command_filename(archive)\n os.system('cat \"%s\" >> \"%s\"' % (archive, new_filename))\n\n return True\n\n def remove(self):\n pass\n", "easy_extract/archives/media.py": "\"\"\"Media archive file format\"\"\"\nimport os\nimport re\n\nfrom easy_extract.archive import Archive\n\nRAW_EXTENSIONS = ['\\.AVI', '\\.OGG', '\\.OGV',\n '\\.MP4', '\\.MPG', '\\.MPEG',\n '\\.MKV', '\\.M4V']\n\nEXTENSIONS = [re.compile('%s$' % ext, re.I) for ext in RAW_EXTENSIONS]\n\n\nclass MediaArchive(Archive):\n \"\"\"The Rar format Archive\"\"\"\n archive_type = 'media'\n ALLOWED_EXTENSIONS = EXTENSIONS\n\n def _extract(self):\n first_archive = self.get_command_filename(self.archives[0])\n return not os.system('synoindex -a \"%s\"' % first_archive)\n\n def remove(self):\n pass\n", "easy_extract/archives/rar.py": "\"\"\"Rar archive format\"\"\"\nimport os\nimport re\n\nfrom easy_extract.archive import Archive\n\nEXTENSIONS = [re.compile('\\.r\\d{2}$', re.I),\n re.compile('\\.part\\d+\\.rar$', re.I),\n re.compile('\\.rar$', re.I)]\n\n\nclass RarArchive(Archive):\n \"\"\"The Rar format Archive\"\"\"\n archive_type = 'rar'\n ALLOWED_EXTENSIONS = EXTENSIONS\n\n def _extract(self):\n if '%s.rar' % self.name in self.archives:\n first_archive = self.get_command_filename('%s.rar' % self.name)\n else:\n first_archive = self.get_command_filename(self.archives[0])\n\n return not os.system('unrar e -o+ \"%s\"' % first_archive)\n", "easy_extract/archives/seven_zip.py": "\"\"\"7zip archive format\"\"\"\nimport os\nimport re\n\nfrom easy_extract.archive import Archive\n\nRAW_EXTENSIONS = ['\\.ARJ', '\\.CAB', '\\.CHM', '\\.CPIO',\n '\\.DMG', '\\.HFS', '\\.LZH', '\\.LZMA',\n '\\.NSIS', '\\.UDF', '\\.WIM', '\\.XAR',\n '\\.Z', '\\.ZIP', '\\.GZIP', '\\.TAR']\n\nEXTENSIONS = [re.compile('%s$' % ext, re.I) for ext in RAW_EXTENSIONS]\n\n\nclass SevenZipArchive(Archive):\n \"\"\"The 7z unarchiver is used for many formats\"\"\"\n archive_type = '7zip'\n ALLOWED_EXTENSIONS = EXTENSIONS\n\n def _extract(self):\n first_archive = self.get_command_filename(self.archives[0])\n return not os.system('7z e -y \"%s\"' % first_archive)\n", "easy_extract/archives/xtm.py": "\"\"\"Xtm archive format\"\"\"\nimport os\nimport re\n\nfrom easy_extract.archive import Archive\n\nEXTENSIONS = [re.compile('\\.\\d{3}\\.xtm$', re.I),\n re.compile('\\.xtm$', re.I)]\n\n\nclass XtmArchive(Archive):\n \"\"\"The XTM archive format\"\"\"\n archive_type = 'xtm'\n ALLOWED_EXTENSIONS = EXTENSIONS\n\n def _extract(self):\n new_filename = self.escape_filename(self.name)\n first_archive = self.get_command_filename(self.archives[0])\n\n print 'Extracting %s...' % new_filename\n\n os.system('dd if=\"%s\" skip=1 ibs=104 status=noxfer > \"%s\" 2>/dev/null'\n % (first_archive, new_filename))\n\n for archive in self.archives[1:]:\n archive = self.get_command_filename(archive)\n os.system('cat \"%s\" >> \"%s\"' % (archive, new_filename))\n\n return True\n\n def remove(self):\n pass\n"}} -{"repo": "benlaurie/lucre", "pr_number": 3, "title": "make include folder and various bug-fixes", "state": "closed", "merged_at": null, "additions": 14, "deletions": 1, "files_changed": ["src/bankimp.cpp"], "files_before": {"src/bankimp.cpp": "#include \"bank.h\"\n#include \n\nstatic BIO *dout;\nstatic BIO *mout;\n\nconst char _NL[]=\"\\n\";\n\nvoid SetDumper(BIO *out)\n {\n dout=out;\n if(!mout)\n\tmout=out;\n }\n\nvoid SetDumper(FILE *f)\n {\n BIO *out=BIO_new(BIO_s_file());\n assert(out);\n BIO_set_fp(out,f,BIO_NOCLOSE);\n SetDumper(out);\n }\n\nvoid SetMonitor(BIO *out)\n { mout=out; }\n\nvoid SetMonitor(FILE *f)\n {\n BIO *out=BIO_new(BIO_s_file());\n assert(out);\n BIO_set_fp(out,f,BIO_NOCLOSE);\n SetMonitor(out);\n }\n\nBIGNUM *ReadNumber(BIO *in,const char *szTitle)\n {\n char szLine[10240];\n unsigned char aucBN[1024];\n int nTLen=strlen(szTitle);\n\n BIO_gets(in,szLine,sizeof szLine-1);\n if(strncmp(szLine,szTitle,nTLen))\n\t{\n\tfprintf(stderr,\"Got %s, expected %s\\n\",szLine,szTitle);\n\tassert(!\"Unexpected input\");\n\treturn NULL;\n\t}\n BIGNUM *bn=BN_new();\n\n int n=strcspn(szLine+nTLen,\"\\r\\n\");\n szLine[nTLen+n]='\\0';\n if(n&1)\n\t{\n\tmemmove(szLine+nTLen+1,szLine+nTLen,n+1);\n\tszLine[nTLen]='0';\n\t}\n\n for(n=0 ; szLine[nTLen+n*2] ; ++n)\n\t{\n\tint h;\n\n\tsscanf(&szLine[nTLen+n*2],\"%02x\",&h);\n\taucBN[n]=(unsigned char)h;\n\t}\n\t\n BN_bin2bn(aucBN,n,bn);\n\n return bn;\n }\n\nvoid DumpNumber(BIO *out,const char *szTitle,const BIGNUM *bn,\n\t\tconst char *szTrailer)\n {\n if(!out)\n\treturn;\n BIO_puts(out,szTitle);\n if(!bn)\n\tBIO_puts(out,\"(null)\");\n else\n\tBN_print(out,bn);\n BIO_puts(out,szTrailer);\n }\n\nvoid DumpNumber(const char *szTitle,const BIGNUM *bn,const char *szTrailer)\n { DumpNumber(dout,szTitle,bn,szTrailer); }\n\nvoid HexDump(BIO *out,const char *szTitle,const unsigned char *acBuf,\n\t int nLength)\n {\n if(!out)\n\treturn;\n BIO_puts(out,szTitle);\n for(int n=0 ; n < nLength ; ++n)\n\t{\n\tchar buf[3];\n\tsprintf(buf,\"%02X\",acBuf[n]);\n\tBIO_puts(out,buf);\n\t}\n BIO_puts(out,\"\\n\");\n }\n\nvoid HexDump(const char *szTitle,const unsigned char *acBuf,int nLength)\n { HexDump(dout,szTitle,acBuf,nLength); }\n\nPublicBank::PublicBank(Bank &bank)\n {\n m_pDH=DH_new();\n m_pDH->g=BN_dup(bank.g());\n m_pDH->p=BN_dup(bank.p());\n m_pDH->pub_key=BN_dup(bank.pub_key());\n }\n\nvoid Bank::cb(int n, int, void */*arg*/)\n {\n if(!mout)\n\treturn;\n\n char c='*';\n\n if (n == 0) c='.';\n if (n == 1) c='+';\n if (n == 2) c='*';\n if (n == 3) c='\\n';\n BIO_write(mout,&c,1);\n BIO_flush(mout);\n }\n\n/*const*/ BIGNUM *Bank::SignRequest(PublicCoinRequest &req)\n {\n InitCTX();\n\n BIGNUM *BtoA=BN_new();\n BN_mod_exp(BtoA,req.Request(),priv_key(),p(),m_ctx);\n DumpNumber(\"B->A= \",BtoA);\n\n return BtoA;\n }\n\nboolean Bank::Verify(Coin &coin)\n {\n InitCTX();\n\n BIGNUM *t=BN_new();\n if(!coin.GenerateCoinNumber(t,*this))\n\treturn false;\n BN_mod_exp(t,t,priv_key(),p(),m_ctx);\n DumpNumber(\"y^k= \",t);\n\n BN_sub(t,t,coin.Signature());\n boolean bRet=BN_is_zero(t);\n\n BN_free(t);\n\n return bRet;\n }\n\nvoid Bank::WriteBIO(BIO *bio)\n {\n PublicBank::WriteBIO(bio);\n DumpNumber(bio,\"private=\",priv_key());\n }\n\nvoid Bank::ReadBIO(BIO *bio)\n {\n PublicBank::ReadBIO(bio);\n m_pDH->priv_key=ReadNumber(bio,\"private=\");\n }\n\nvoid PublicBank::WriteBIO(BIO *bio)\n {\n DumpNumber(bio,\"g=\",g());\n DumpNumber(bio,\"p=\",p());\n DumpNumber(bio,\"public=\",pub_key());\n }\n\nvoid PublicBank::ReadBIO(BIO *bio)\n {\n m_pDH=DH_new();\n\n m_pDH->g=ReadNumber(bio,\"g=\");\n m_pDH->p=ReadNumber(bio,\"p=\");\n m_pDH->pub_key=ReadNumber(bio,\"public=\");\n\n Dump();\n }\n\nvoid UnsignedCoin::WriteBIO(BIO *bio)\n {\n DumpNumber(bio,\"id=\",m_bnCoinID);\n }\n\nvoid UnsignedCoin::ReadBIO(BIO *bio)\n {\n m_bnCoinID=ReadNumber(bio,\"id=\");\n }\n\nvoid Coin::WriteBIO(BIO *bio)\n {\n UnsignedCoin::WriteBIO(bio);\n DumpNumber(bio,\"signature=\",m_bnCoinSignature);\n }\n\nvoid Coin::ReadBIO(BIO *bio)\n {\n UnsignedCoin::ReadBIO(bio);\n m_bnCoinSignature=ReadNumber(bio,\"signature=\");\n Dump();\n }\n\nvoid PublicCoinRequest::WriteBIO(BIO *bio)\n {\n DumpNumber(bio,\"request=\",m_bnCoinRequest);\n }\n\nvoid PublicCoinRequest::ReadBIO(BIO *bio)\n {\n m_bnCoinRequest=ReadNumber(bio,\"request=\");\n }\n\nvoid CoinRequest::WriteBIO(BIO *bio)\n {\n PublicCoinRequest::WriteBIO(bio);\n m_coin.WriteBIO(bio);\n DumpNumber(bio,\"blinding=\",m_bnBlindingFactor);\n }\n\nvoid CoinRequest::ReadBIO(BIO *bio)\n {\n PublicCoinRequest::ReadBIO(bio);\n m_coin.ReadBIO(bio);\n m_bnBlindingFactor=ReadNumber(bio,\"blinding=\");\n\n Dump();\n }\n\n"}, "files_after": {"src/bankimp.cpp": "\n#ifdef __APPLE__\n#pragma GCC diagnostic ignored \"-Wdeprecated-declarations\"\n#endif\n\n#include \"bank.h\"\n#include \n\n#ifdef _WIN32\n#include \n#endif\n\nstatic BIO *dout;\nstatic BIO *mout;\n\nconst char _NL[]=\"\\n\";\n\nvoid SetDumper(BIO *out)\n {\n dout=out;\n if(!mout)\n\tmout=out;\n }\n\nvoid SetDumper(FILE *f)\n {\n BIO *out=BIO_new(BIO_s_file());\n assert(out);\n BIO_set_fp(out,f,BIO_NOCLOSE);\n SetDumper(out);\n }\n\nvoid SetMonitor(BIO *out)\n { mout=out; }\n\nvoid SetMonitor(FILE *f)\n {\n BIO *out=BIO_new(BIO_s_file());\n assert(out);\n BIO_set_fp(out,f,BIO_NOCLOSE);\n SetMonitor(out);\n }\n\nBIGNUM *ReadNumber(BIO *in,const char *szTitle)\n {\n char szLine[10240];\n unsigned char aucBN[1024];\n int nTLen=strlen(szTitle);\n\n BIO_gets(in,szLine,sizeof szLine-1);\n if(strncmp(szLine,szTitle,nTLen))\n\t{\n\tfprintf(stderr,\"Got %s, expected %s\\n\",szLine,szTitle);\n\tassert(!\"Unexpected input\");\n\treturn NULL;\n\t}\n BIGNUM *bn=BN_new();\n\n int n=strcspn(szLine+nTLen,\"\\r\\n\");\n szLine[nTLen+n]='\\0';\n if(n&1)\n\t{\n\tmemmove(szLine+nTLen+1,szLine+nTLen,n+1);\n\tszLine[nTLen]='0';\n\t}\n\n for(n=0 ; szLine[nTLen+n*2] ; ++n)\n\t{\n\tint h;\n\n\tsscanf(&szLine[nTLen+n*2],\"%02x\",&h);\n\taucBN[n]=(unsigned char)h;\n\t}\n\t\n BN_bin2bn(aucBN,n,bn);\n\n return bn;\n }\n\nvoid DumpNumber(BIO *out,const char *szTitle,const BIGNUM *bn,\n\t\tconst char *szTrailer)\n {\n if(!out)\n\treturn;\n BIO_puts(out,szTitle);\n if(!bn)\n\tBIO_puts(out,\"(null)\");\n else\n\tBN_print(out,bn);\n BIO_puts(out,szTrailer);\n }\n\nvoid DumpNumber(const char *szTitle,const BIGNUM *bn,const char *szTrailer)\n { DumpNumber(dout,szTitle,bn,szTrailer); }\n\nvoid HexDump(BIO *out,const char *szTitle,const unsigned char *acBuf,\n\t int nLength)\n {\n if(!out)\n\treturn;\n BIO_puts(out,szTitle);\n for(int n=0 ; n < nLength ; ++n)\n\t{\n\tchar buf[3];\n\tsprintf(buf,\"%02X\",acBuf[n]);\n\tBIO_puts(out,buf);\n\t}\n BIO_puts(out,\"\\n\");\n }\n\nvoid HexDump(const char *szTitle,const unsigned char *acBuf,int nLength)\n { HexDump(dout,szTitle,acBuf,nLength); }\n\nPublicBank::PublicBank(Bank &bank)\n {\n m_pDH=DH_new();\n m_pDH->g=BN_dup(bank.g());\n m_pDH->p=BN_dup(bank.p());\n m_pDH->pub_key=BN_dup(bank.pub_key());\n }\n\nvoid Bank::cb(int n, int, void * /*arg*/)\n {\n if(!mout)\n\treturn;\n\n char c='*';\n\n if (n == 0) c='.';\n if (n == 1) c='+';\n if (n == 2) c='*';\n if (n == 3) c='\\n';\n BIO_write(mout,&c,1);\n BIO_flush(mout);\n }\n\n/*const*/ BIGNUM *Bank::SignRequest(PublicCoinRequest &req)\n {\n InitCTX();\n\n BIGNUM *BtoA=BN_new();\n BN_mod_exp(BtoA,req.Request(),priv_key(),p(),m_ctx);\n DumpNumber(\"B->A= \",BtoA);\n\n return BtoA;\n }\n\nboolean Bank::Verify(Coin &coin)\n {\n InitCTX();\n\n BIGNUM *t=BN_new();\n if(!coin.GenerateCoinNumber(t,*this))\n\treturn false;\n BN_mod_exp(t,t,priv_key(),p(),m_ctx);\n DumpNumber(\"y^k= \",t);\n\n BN_sub(t,t,coin.Signature());\n boolean bRet=BN_is_zero(t);\n\n BN_free(t);\n\n return bRet;\n }\n\nvoid Bank::WriteBIO(BIO *bio)\n {\n PublicBank::WriteBIO(bio);\n DumpNumber(bio,\"private=\",priv_key());\n }\n\nvoid Bank::ReadBIO(BIO *bio)\n {\n PublicBank::ReadBIO(bio);\n m_pDH->priv_key=ReadNumber(bio,\"private=\");\n }\n\nvoid PublicBank::WriteBIO(BIO *bio)\n {\n DumpNumber(bio,\"g=\",g());\n DumpNumber(bio,\"p=\",p());\n DumpNumber(bio,\"public=\",pub_key());\n }\n\nvoid PublicBank::ReadBIO(BIO *bio)\n {\n m_pDH=DH_new();\n\n m_pDH->g=ReadNumber(bio,\"g=\");\n m_pDH->p=ReadNumber(bio,\"p=\");\n m_pDH->pub_key=ReadNumber(bio,\"public=\");\n\n Dump();\n }\n\nvoid UnsignedCoin::WriteBIO(BIO *bio)\n {\n DumpNumber(bio,\"id=\",m_bnCoinID);\n }\n\nvoid UnsignedCoin::ReadBIO(BIO *bio)\n {\n m_bnCoinID=ReadNumber(bio,\"id=\");\n }\n\nvoid Coin::WriteBIO(BIO *bio)\n {\n UnsignedCoin::WriteBIO(bio);\n DumpNumber(bio,\"signature=\",m_bnCoinSignature);\n }\n\nvoid Coin::ReadBIO(BIO *bio)\n {\n UnsignedCoin::ReadBIO(bio);\n m_bnCoinSignature=ReadNumber(bio,\"signature=\");\n Dump();\n }\n\nvoid PublicCoinRequest::WriteBIO(BIO *bio)\n {\n DumpNumber(bio,\"request=\",m_bnCoinRequest);\n }\n\nvoid PublicCoinRequest::ReadBIO(BIO *bio)\n {\n m_bnCoinRequest=ReadNumber(bio,\"request=\");\n }\n\nvoid CoinRequest::WriteBIO(BIO *bio)\n {\n PublicCoinRequest::WriteBIO(bio);\n m_coin.WriteBIO(bio);\n DumpNumber(bio,\"blinding=\",m_bnBlindingFactor);\n }\n\nvoid CoinRequest::ReadBIO(BIO *bio)\n {\n PublicCoinRequest::ReadBIO(bio);\n m_coin.ReadBIO(bio);\n m_bnBlindingFactor=ReadNumber(bio,\"blinding=\");\n\n Dump();\n }\n\n"}} -{"repo": "xxx/acts_as_archive", "pr_number": 3, "title": "adding fix to return the correct datetimestamp for rails generator", "state": "closed", "merged_at": "2014-09-01T22:45:52Z", "additions": 5, "deletions": 4, "files_changed": ["lib/acts_as_archive/migration.rb"], "files_before": {"lib/acts_as_archive/migration.rb": "module ActsAsArchive\n module Migration\n \n def self.included(base)\n unless base.included_modules.include?(InstanceMethods)\n base.send :extend, ClassMethods\n base.class_eval do\n class < 'file', :timeout => 120, :location => Dir.tmpdir\n\n base_uri 'http://api.themoviedb.org/2.1'\n format :json\n \n def initialize(key, lang = 'en')\n @api_key = key\n @default_lang = lang\n end\n \n def search(query, lang = @default_lang)\n data = self.class.get(method_url('Movie.search', lang, query))\n \n result_or_empty_array(data, Movie)\n end\n\n # Read more about the parameters that can be passed to this method here:\n # http://api.themoviedb.org/2.1/methods/Movie.browse\n def browse(params = {}, lang = @default_lang)\n data = self.class.get(method_url('Movie.browse', lang), :query => {:order => \"asc\", :order_by => \"title\"}.merge(params))\n \n result_or_empty_array(data, Movie)\n end\n \n def search_person(query, lang = @default_lang)\n data = self.class.get(method_url('Person.search', lang, query))\n \n result_or_empty_array(data, Person)\n end\n \n def imdb_lookup(imdb_id, lang = @default_lang)\n data = self.class.get(method_url('Movie.imdbLookup', lang, imdb_id)).parsed_response\n if data.class != Array || data.first == \"Nothing found.\"\n nil\n else\n Movie.new(data.first, self)\n end\n end\n \n def get_info(id, lang = @default_lang)\n data = self.class.get(method_url('Movie.getInfo', lang, id)).parsed_response\n Movie.new(data.first, self)\n end\n\n def get_file_info(file, lang=@default_lang)\n hash = TMDBParty::MovieHasher.compute_hash(file)\n bytesize = file.size\n data = self.class.get(method_url('Media.getInfo', lang, hash, bytesize))\n\n result_or_empty_array(data, Movie)\n end\n\n def get_person(id, lang = @default_lang)\n data = self.class.get(method_url('Person.getInfo', lang, id)).parsed_response\n Person.new(data.first, self)\n end\n \n def get_genres(lang = @default_lang)\n data = self.class.get(method_url('Genres.getList', lang)).parsed_response\n data[1..-1].collect { |genre| Genre.new(genre) } # Skips the first, see spec/fixtures/genres_results.json\n end\n \n private\n\n def result_or_empty_array(data, klass)\n data = data.parsed_response\n if data.class != Array || data.first == \"Nothing found.\"\n []\n else\n data.collect { |object| klass.new(object, self) }\n end\n end\n\n def method_url(method, lang, *args)\n url = [method, lang, self.class.format, @api_key]\n url += args.collect{ |a| URI.escape(a.to_s) }\n '/' + url.join('/')\n end\n end\nend\n", "lib/tmdb_party/cast_member.rb": "module TMDBParty\n class CastMember\n include Attributes\n attr_reader :tmdb\n attributes :name, :url, :job, :department\n attributes :id, :type => Integer\n \n def initialize(values, tmdb)\n @tmdb = tmdb\n self.attributes = values\n end\n \n def character_name\n read_attribute('character')\n end\n \n def image_url\n read_attribute('profile')\n end\n \n def person\n tmdb.get_person(id)\n end\n \n def self.parse(data, tmdb)\n return unless data\n if data.is_a?(Array)\n data.collect do |person|\n CastMember.new(person, tmdb)\n end\n else\n [CastMember.new(data, tmdb)]\n end\n end\n end\nend", "lib/tmdb_party/category.rb": "module TMDBParty\n class Category\n include Attributes\n attributes :name, :url\n \n def initialize(values)\n self.attributes = values\n end\n \n def self.parse(data)\n return unless data\n data = data[\"category\"]\n if data.is_a?(Array)\n data.collect do |category|\n Category.new(category)\n end\n else\n [Category.new(data)]\n end\n end\n end\nend\n", "lib/tmdb_party/genre.rb": "module TMDBParty\n class Genre\n include Attributes\n attributes :id, :type => Integer\n attributes :name, :url\n \n def initialize(values)\n self.attributes = values\n end\n \n def self.parse(data)\n return unless data\n if data.is_a?(Array)\n data.collect do |g|\n Genre.new(g)\n end\n else\n [Genre.new(data)]\n end\n end\n end\nend\n", "lib/tmdb_party/movie.rb": "module TMDBParty\n class Movie\n include Attributes\n attr_reader :tmdb\n \n attributes :name, :overview, :id, :imdb_id, :movie_type, :url, :alternative_title, :translated, :certification\n attributes :released\n attributes :id, :popularity, :type => Integer\n attributes :score, :type => Float\n \n attributes :tagline, :lazy => :get_info!\n attributes :posters, :backdrops, :lazy => :get_info!, :type => Image\n attributes :homepage, :lazy => :get_info!\n attributes :trailer, :lazy => :get_info!\n attributes :runtime, :lazy => :get_info!, :type => Integer\n attributes :genres, :lazy => :get_info!, :type => Genre\n attributes :countries, :lazy => :get_info!, :type => Country\n attributes :studios, :lazy => :get_info!, :type => Studio\n \n alias_method :translated?, :translated\n \n def initialize(values, tmdb)\n @tmdb = tmdb\n self.attributes = values\n end\n \n def get_info!\n movie = tmdb.get_info(self.id)\n @attributes.merge!(movie.attributes) if movie\n @loaded = true\n end\n\n def cast\n # TODO: This needs refactoring\n CastMember.parse(read_or_load_attribute('cast', nil, :get_info!), tmdb)\n end\n\n def language\n read_attribute('language').downcase.to_sym\n end\n\n def last_modified_at\n # Date from TMDB is always in MST, but no timezone is present in date string\n Time.parse(read_attribute('last_modified_at') + ' MST')\n end\n\n def directors\n find_cast('Directing')\n end\n\n def actors\n find_cast('Actors')\n end\n\n def writers\n find_cast('Writing')\n end\n\n def producers\n find_cast('Production')\n end\n \n private\n \n def find_cast(type)\n return [] unless cast\n guys = cast.select{|c| c.department == type}\n end\n\n end\n \nend", "lib/tmdb_party/person.rb": "module TMDBParty\n class Person\n include Attributes\n attr_reader :tmdb\n attributes :id, :popularity, :type => Integer\n attributes :score, :type => Float\n attributes :name, :url, :biography\n \n attributes :birthplace, :birthday, :lazy => :get_info!\n \n def initialize(values, tmdb)\n @tmdb = tmdb\n self.attributes = values\n end\n \n def biography\n # HTTParty does not parse the encoded hexadecimal properly. It does not consider 000F to be a hex, but 000f is\n # A bug has been submitted about this\n read_attribute('biography').gsub(\"\\\\n\", \"\\n\").gsub(/\\\\u([0-9A-F]{4})/) { [$1.hex].pack(\"U\") }\n end\n \n \n def get_info!\n person = tmdb.get_person(self.id)\n @attributes.merge!(person.attributes) if person\n @loaded = true\n end\n end\nend", "lib/tmdb_party/studio.rb": "module TMDBParty\n class Studio\n include Attributes\n attributes :name, :url\n \n def self.parse(data)\n return unless data\n if data.is_a?(Array)\n data.map { |row| Studio.new(row) }\n else\n [Studio.new(data)]\n end\n end\n \n def initialize(attributes)\n self.attributes = attributes\n end\n end\nend", "lib/tmdb_party/video.rb": "module TMDBParty\n class Video\n attr_reader :url\n \n def initialize(url)\n @url = url\n end\n \n def self.parse(data)\n return unless data\n if data.is_a?(Array)\n data.collect do |url|\n Video.new(url)\n end\n else\n Video.new(data)\n end\n end\n end\nend"}, "files_after": {"lib/tmdb_party.rb": "require 'httparty'\n\n%w[extras/httparty_icebox extras/attributes entity video genre person image country studio cast_member movie extras/movie_hasher].each do |class_name|\n require \"tmdb_party/#{class_name}\"\nend\n\nmodule TMDBParty\n class Base\n include HTTParty\n include HTTParty::Icebox\n cache :store => 'file', :timeout => 120, :location => Dir.tmpdir\n\n base_uri 'http://api.themoviedb.org/2.1'\n format :json\n \n def initialize(key, lang = 'en')\n @api_key = key\n @default_lang = lang\n end\n \n def search(query, lang = @default_lang)\n data = self.class.get(method_url('Movie.search', lang, query))\n \n result_or_empty_array(data, Movie)\n end\n\n # Read more about the parameters that can be passed to this method here:\n # http://api.themoviedb.org/2.1/methods/Movie.browse\n def browse(params = {}, lang = @default_lang)\n data = self.class.get(method_url('Movie.browse', lang), :query => {:order => \"asc\", :order_by => \"title\"}.merge(params))\n \n result_or_empty_array(data, Movie)\n end\n \n def search_person(query, lang = @default_lang)\n data = self.class.get(method_url('Person.search', lang, query))\n \n result_or_empty_array(data, Person)\n end\n \n def imdb_lookup(imdb_id, lang = @default_lang)\n data = self.class.get(method_url('Movie.imdbLookup', lang, imdb_id)).parsed_response\n if data.class != Array || data.first == \"Nothing found.\"\n nil\n else\n Movie.new(data.first, self)\n end\n end\n \n def get_info(id, lang = @default_lang)\n data = self.class.get(method_url('Movie.getInfo', lang, id)).parsed_response\n Movie.new(data.first, self)\n end\n\n def get_file_info(file, lang=@default_lang)\n hash = TMDBParty::MovieHasher.compute_hash(file)\n bytesize = file.size\n data = self.class.get(method_url('Media.getInfo', lang, hash, bytesize))\n\n result_or_empty_array(data, Movie)\n end\n\n def get_person(id, lang = @default_lang)\n data = self.class.get(method_url('Person.getInfo', lang, id)).parsed_response\n Person.new(data.first, self)\n end\n \n def get_genres(lang = @default_lang)\n data = self.class.get(method_url('Genres.getList', lang)).parsed_response\n data[1..-1].collect { |genre| Genre.new(genre) } # Skips the first, see spec/fixtures/genres_results.json\n end\n \n private\n\n def result_or_empty_array(data, klass)\n data = data.parsed_response\n if data.class != Array || data.first == \"Nothing found.\"\n []\n else\n data.collect { |object| klass.new(object, self) }\n end\n end\n\n def method_url(method, lang, *args)\n url = [method, lang, self.class.format, @api_key]\n url += args.collect{ |a| URI.escape(a.to_s) }\n '/' + url.join('/')\n end\n end\nend\n", "lib/tmdb_party/cast_member.rb": "module TMDBParty\n class CastMember < Entity\n attr_reader :tmdb\n attributes :name, :url, :job, :department\n attributes :id, :type => Integer\n \n def character_name\n read_attribute('character')\n end\n \n def image_url\n read_attribute('profile')\n end\n \n def person\n tmdb.get_person(id)\n end\n end\nend\n", "lib/tmdb_party/category.rb": "module TMDBParty\n class Category < Entity\n attributes :name, :url\n end\nend\n", "lib/tmdb_party/entity.rb": "module TMDBParty\n class Entity\n include Attributes\n def initialize(values, tmdb=nil)\n @tmdb = tmdb\n self.attributes = values\n end\n\n def self.parse(data, tmdb=nil)\n return unless data\n if data.is_a?(Array)\n data.collect do |person|\n self.new(person, tmdb)\n end\n else\n [self.new(data, tmdb)]\n end\n end\n end\nend\n", "lib/tmdb_party/genre.rb": "module TMDBParty\n class Genre < Entity\n attributes :id, :type => Integer\n attributes :name, :url\n end\nend\n", "lib/tmdb_party/movie.rb": "module TMDBParty\n class Movie < Entity\n attr_reader :tmdb\n \n attributes :name, :overview, :id, :imdb_id, :movie_type, :url, :alternative_title, :translated, :certification\n attributes :released\n attributes :id, :popularity, :type => Integer\n attributes :score, :type => Float\n \n attributes :tagline, :lazy => :get_info!\n attributes :posters, :backdrops, :lazy => :get_info!, :type => Image\n attributes :homepage, :lazy => :get_info!\n attributes :trailer, :lazy => :get_info!\n attributes :runtime, :lazy => :get_info!, :type => Integer\n attributes :genres, :lazy => :get_info!, :type => Genre\n attributes :countries, :lazy => :get_info!, :type => Country\n attributes :studios, :lazy => :get_info!, :type => Studio\n \n alias_method :translated?, :translated\n \n def get_info!\n movie = tmdb.get_info(self.id)\n @attributes.merge!(movie.attributes) if movie\n @loaded = true\n end\n\n def cast\n # TODO: This needs refactoring\n CastMember.parse(read_or_load_attribute('cast', nil, :get_info!), tmdb)\n end\n\n def language\n read_attribute('language').downcase.to_sym\n end\n\n def last_modified_at\n # Date from TMDB is always in MST, but no timezone is present in date string\n Time.parse(read_attribute('last_modified_at') + ' MST')\n end\n\n def directors\n find_cast('Directing')\n end\n\n def actors\n find_cast('Actors')\n end\n\n def writers\n find_cast('Writing')\n end\n\n def producers\n find_cast('Production')\n end\n \n private\n \n def find_cast(type)\n return [] unless cast\n guys = cast.select{|c| c.department == type}\n end\n\n end\n \nend\n", "lib/tmdb_party/person.rb": "module TMDBParty\n class Person < Entity\n attr_reader :tmdb\n attributes :id, :popularity, :type => Integer\n attributes :score, :type => Float\n attributes :name, :url, :biography\n \n attributes :birthplace, :birthday, :lazy => :get_info!\n \n def biography\n # HTTParty does not parse the encoded hexadecimal properly. It does not consider 000F to be a hex, but 000f is\n # A bug has been submitted about this\n read_attribute('biography').gsub(\"\\\\n\", \"\\n\").gsub(/\\\\u([0-9A-F]{4})/) { [$1.hex].pack(\"U\") }\n end\n \n \n def get_info!\n person = tmdb.get_person(self.id)\n @attributes.merge!(person.attributes) if person\n @loaded = true\n end\n end\nend\n", "lib/tmdb_party/studio.rb": "module TMDBParty\n class Studio < Entity\n attributes :name, :url\n end\nend\n", "lib/tmdb_party/video.rb": "module TMDBParty\n class Video < Entity\n attr_reader :url\n \n def initialize(url)\n super\n @url = url\n end\n end\nend\n"}} -{"repo": "rawwell/django", "pr_number": 1, "title": "0.90 bugfixes Need to check security parameters", "state": "open", "merged_at": null, "additions": 83, "deletions": 35, "files_changed": ["django/bin/compile-messages.py", "django/core/db/backends/postgresql.py", "django/core/handlers/modpython.py", "django/core/meta/__init__.py", "django/core/meta/fields.py"], "files_before": {"django/bin/compile-messages.py": "#!/usr/bin/env python\n\nimport optparse\nimport os\nimport sys\n\ntry:\n set\nexcept NameError:\n from sets import Set as set # For Python 2.3\n\n\ndef compile_messages(locale=None):\n basedirs = (os.path.join('conf', 'locale'), 'locale')\n if os.environ.get('DJANGO_SETTINGS_MODULE'):\n from django.conf import settings\n basedirs += settings.LOCALE_PATHS\n\n # Gather existing directories.\n basedirs = set(map(os.path.abspath, filter(os.path.isdir, basedirs)))\n\n if not basedirs:\n print \"This script should be run from the Django SVN tree or your project or app tree, or with the settings module specified.\"\n sys.exit(1)\n\n for basedir in basedirs:\n if locale:\n basedir = os.path.join(basedir, locale, 'LC_MESSAGES')\n compile_messages_in_dir(basedir)\n\ndef compile_messages_in_dir(basedir):\n for dirpath, dirnames, filenames in os.walk(basedir):\n for f in filenames:\n if f.endswith('.po'):\n sys.stderr.write('processing file %s in %s\\n' % (f, dirpath))\n pf = os.path.splitext(os.path.join(dirpath, f))[0]\n # Store the names of the .mo and .po files in an environment\n # variable, rather than doing a string replacement into the\n # command, so that we can take advantage of shell quoting, to\n # quote any malicious characters/escaping.\n # See http://cyberelk.net/tim/articles/cmdline/ar01s02.html\n os.environ['djangocompilemo'] = pf + '.mo'\n os.environ['djangocompilepo'] = pf + '.po'\n if sys.platform == 'win32': # Different shell-variable syntax\n cmd = 'msgfmt --check-format -o \"%djangocompilemo%\" \"%djangocompilepo%\"'\n else:\n cmd = 'msgfmt --check-format -o \"$djangocompilemo\" \"$djangocompilepo\"'\n os.system(cmd)\n\ndef main():\n parser = optparse.OptionParser()\n parser.add_option('-l', '--locale', dest='locale',\n help=\"The locale to process. Default is to process all.\")\n parser.add_option('--settings',\n help='Python path to settings module, e.g. \"myproject.settings\". If provided, all LOCALE_PATHS will be processed. If this isn\\'t provided, the DJANGO_SETTINGS_MODULE environment variable will be checked as well.')\n options, args = parser.parse_args()\n if len(args):\n parser.error(\"This program takes no arguments\")\n if options.settings:\n os.environ['DJANGO_SETTINGS_MODULE'] = options.settings\n compile_messages(options.locale)\n\nif __name__ == \"__main__\":\n main()\n", "django/core/handlers/modpython.py": "import os\nfrom pprint import pformat\n\nfrom django import http\nfrom django.core import signals\nfrom django.core.handlers.base import BaseHandler\nfrom django.dispatch import dispatcher\nfrom django.utils import datastructures\nfrom django.utils.encoding import force_unicode, smart_str\n\n# NOTE: do *not* import settings (or any module which eventually imports\n# settings) until after ModPythonHandler has been called; otherwise os.environ\n# won't be set up correctly (with respect to settings).\n\nclass ModPythonRequest(http.HttpRequest):\n def __init__(self, req):\n self._req = req\n self.path = force_unicode(req.uri)\n\n def __repr__(self):\n # Since this is called as part of error handling, we need to be very\n # robust against potentially malformed input.\n try:\n get = pformat(self.GET)\n except:\n get = ''\n try:\n post = pformat(self.POST)\n except:\n post = ''\n try:\n cookies = pformat(self.COOKIES)\n except:\n cookies = ''\n try:\n meta = pformat(self.META)\n except:\n meta = ''\n return smart_str(u'' %\n (self.path, unicode(get), unicode(post),\n unicode(cookies), unicode(meta)))\n\n def get_full_path(self):\n return '%s%s' % (self.path, self._req.args and ('?' + self._req.args) or '')\n\n def is_secure(self):\n try:\n return self._req.is_https()\n except AttributeError:\n # mod_python < 3.2.10 doesn't have req.is_https().\n return self._req.subprocess_env.get('HTTPS', '').lower() in ('on', '1')\n\n def _load_post_and_files(self):\n \"Populates self._post and self._files\"\n if 'content-type' in self._req.headers_in and self._req.headers_in['content-type'].startswith('multipart'):\n self._post, self._files = http.parse_file_upload(self._req.headers_in, self.raw_post_data)\n else:\n self._post, self._files = http.QueryDict(self.raw_post_data, encoding=self._encoding), datastructures.MultiValueDict()\n\n def _get_request(self):\n if not hasattr(self, '_request'):\n self._request = datastructures.MergeDict(self.POST, self.GET)\n return self._request\n\n def _get_get(self):\n if not hasattr(self, '_get'):\n self._get = http.QueryDict(self._req.args, encoding=self._encoding)\n return self._get\n\n def _set_get(self, get):\n self._get = get\n\n def _get_post(self):\n if not hasattr(self, '_post'):\n self._load_post_and_files()\n return self._post\n\n def _set_post(self, post):\n self._post = post\n\n def _get_cookies(self):\n if not hasattr(self, '_cookies'):\n self._cookies = http.parse_cookie(self._req.headers_in.get('cookie', ''))\n return self._cookies\n\n def _set_cookies(self, cookies):\n self._cookies = cookies\n\n def _get_files(self):\n if not hasattr(self, '_files'):\n self._load_post_and_files()\n return self._files\n\n def _get_meta(self):\n \"Lazy loader that returns self.META dictionary\"\n if not hasattr(self, '_meta'):\n self._meta = {\n 'AUTH_TYPE': self._req.ap_auth_type,\n 'CONTENT_LENGTH': self._req.clength, # This may be wrong\n 'CONTENT_TYPE': self._req.content_type, # This may be wrong\n 'GATEWAY_INTERFACE': 'CGI/1.1',\n 'PATH_INFO': self._req.path_info,\n 'PATH_TRANSLATED': None, # Not supported\n 'QUERY_STRING': self._req.args,\n 'REMOTE_ADDR': self._req.connection.remote_ip,\n 'REMOTE_HOST': None, # DNS lookups not supported\n 'REMOTE_IDENT': self._req.connection.remote_logname,\n 'REMOTE_USER': self._req.user,\n 'REQUEST_METHOD': self._req.method,\n 'SCRIPT_NAME': None, # Not supported\n 'SERVER_NAME': self._req.server.server_hostname,\n 'SERVER_PORT': self._req.server.port,\n 'SERVER_PROTOCOL': self._req.protocol,\n 'SERVER_SOFTWARE': 'mod_python'\n }\n for key, value in self._req.headers_in.items():\n key = 'HTTP_' + key.upper().replace('-', '_')\n self._meta[key] = value\n return self._meta\n\n def _get_raw_post_data(self):\n try:\n return self._raw_post_data\n except AttributeError:\n self._raw_post_data = self._req.read()\n return self._raw_post_data\n\n def _get_method(self):\n return self.META['REQUEST_METHOD'].upper()\n\n GET = property(_get_get, _set_get)\n POST = property(_get_post, _set_post)\n COOKIES = property(_get_cookies, _set_cookies)\n FILES = property(_get_files)\n META = property(_get_meta)\n REQUEST = property(_get_request)\n raw_post_data = property(_get_raw_post_data)\n method = property(_get_method)\n\nclass ModPythonHandler(BaseHandler):\n request_class = ModPythonRequest\n\n def __call__(self, req):\n # mod_python fakes the environ, and thus doesn't process SetEnv. This fixes that\n os.environ.update(req.subprocess_env)\n\n # now that the environ works we can see the correct settings, so imports\n # that use settings now can work\n from django.conf import settings\n\n # if we need to set up middleware, now that settings works we can do it now.\n if self._request_middleware is None:\n self.load_middleware()\n\n dispatcher.send(signal=signals.request_started)\n try:\n try:\n request = self.request_class(req)\n except UnicodeDecodeError:\n response = http.HttpResponseBadRequest()\n else:\n response = self.get_response(request)\n\n # Apply response middleware\n for middleware_method in self._response_middleware:\n response = middleware_method(request, response)\n response = self.apply_response_fixes(request, response)\n finally:\n dispatcher.send(signal=signals.request_finished)\n\n # Convert our custom HttpResponse object back into the mod_python req.\n req.content_type = response['Content-Type']\n for key, value in response.items():\n if key != 'content-type':\n req.headers_out[str(key)] = str(value)\n for c in response.cookies.values():\n req.headers_out.add('Set-Cookie', c.output(header=''))\n req.status = response.status_code\n try:\n for chunk in response:\n req.write(chunk)\n finally:\n response.close()\n\n return 0 # mod_python.apache.OK\n\ndef handler(req):\n # mod_python hooks into this function.\n return ModPythonHandler()(req)\n"}, "files_after": {"django/bin/compile-messages.py": "#!/usr/bin/python\n\nimport os\nimport sys\nimport getopt\n\nbasedir = None\n\nif os.path.isdir(os.path.join('conf', 'locale')):\n basedir = os.path.abspath(os.path.join('conf', 'locale'))\nelif os.path.isdir('locale'):\n basedir = os.path.abspath('locale')\nelse:\n print \"this script should be run from the django svn tree or your project or app tree\"\n sys.exit(1)\n\nfor (dirpath, dirnames, filenames) in os.walk(basedir):\n for file in filenames:\n if file.endswith('.po'):\n sys.stderr.write('processing file %s in %s\\n' % (file, dirpath))\n pf = os.path.splitext(os.path.join(dirpath, file))[0]\n # Store the names of the .mo and .po files in an environment\n # variable, rather than doing a string replacement into the\n # command, so that we can take advantage of shell quoting, to\n # quote any malicious characters/escaping.\n # See http://cyberelk.net/tim/articles/cmdline/ar01s02.html\n os.environ['djangocompilemo'] = pf + '.mo'\n os.environ['djangocompilepo'] = pf + '.po'\n cmd = 'msgfmt -o \"$djangocompilemo\" \"$djangocompilepo\"'\n os.system(cmd)\n\n", "django/core/db/backends/postgresql.py": "\"\"\"\nPostgreSQL database backend for Django.\n\nRequires psycopg 1: http://initd.org/projects/psycopg1\n\"\"\"\n\nfrom django.core.db import base, typecasts\nimport psycopg as Database\n\nDatabaseError = Database.DatabaseError\n\ndef smart_basestring(s, charset):\n if isinstance(s, unicode):\n return s.encode(charset)\n return s\n\nclass UnicodeCursorWrapper(object):\n \"\"\"\n A thin wrapper around psycopg cursors that allows them to accept Unicode\n strings as params.\n\n This is necessary because psycopg doesn't apply any DB quoting to\n parameters that are Unicode strings. If a param is Unicode, this will\n convert it to a bytestring using DEFAULT_CHARSET before passing it to\n psycopg.\n \"\"\"\n def __init__(self, cursor, charset):\n self.cursor = cursor\n self.charset = charset\n\n def execute(self, sql, params=()):\n return self.cursor.execute(sql, [smart_basestring(p, self.charset) for p in params])\n\n def executemany(self, sql, param_list):\n new_param_list = [tuple([smart_basestring(p, self.charset) for p in params]) for params in param_list]\n return self.cursor.executemany(sql, new_param_list)\n\n def __getattr__(self, attr):\n if self.__dict__.has_key(attr):\n return self.__dict__[attr]\n else:\n return getattr(self.cursor, attr)\n\nclass DatabaseWrapper:\n def __init__(self):\n self.connection = None\n self.queries = []\n\n def cursor(self):\n from django.conf.settings import DATABASE_USER, DATABASE_NAME, DATABASE_HOST, DATABASE_PORT, DATABASE_PASSWORD, DEBUG, DEFAULT_CHARSET, TIME_ZONE\n if self.connection is None:\n if DATABASE_NAME == '':\n from django.core.exceptions import ImproperlyConfigured\n raise ImproperlyConfigured, \"You need to specify DATABASE_NAME in your Django settings file.\"\n conn_string = \"dbname=%s\" % DATABASE_NAME\n if DATABASE_USER:\n conn_string = \"user=%s %s\" % (DATABASE_USER, conn_string)\n if DATABASE_PASSWORD:\n conn_string += \" password='%s'\" % DATABASE_PASSWORD\n if DATABASE_HOST:\n conn_string += \" host=%s\" % DATABASE_HOST\n if DATABASE_PORT:\n conn_string += \" port=%s\" % DATABASE_PORT\n self.connection = Database.connect(conn_string)\n self.connection.set_isolation_level(1) # make transactions transparent to all cursors\n cursor = self.connection.cursor()\n cursor.execute(\"SET TIME ZONE %s\", [TIME_ZONE])\n cursor = UnicodeCursorWrapper(cursor, DEFAULT_CHARSET)\n if DEBUG:\n return base.CursorDebugWrapper(cursor, self)\n return cursor\n\n def commit(self):\n return self.connection.commit()\n\n def rollback(self):\n if self.connection:\n return self.connection.rollback()\n\n def close(self):\n if self.connection is not None:\n self.connection.close()\n self.connection = None\n\n def quote_name(self, name):\n if name.startswith('\"') and name.endswith('\"'):\n return name # Quoting once is enough.\n return '\"%s\"' % name\n\ndef dictfetchone(cursor):\n \"Returns a row from the cursor as a dict\"\n return cursor.dictfetchone()\n\ndef dictfetchmany(cursor, number):\n \"Returns a certain number of rows from a cursor as a dict\"\n return cursor.dictfetchmany(number)\n\ndef dictfetchall(cursor):\n \"Returns all rows from a cursor as a dict\"\n return cursor.dictfetchall()\n\ndef get_last_insert_id(cursor, table_name, pk_name):\n cursor.execute(\"SELECT CURRVAL('%s_%s_seq')\" % (table_name, pk_name))\n return cursor.fetchone()[0]\n\ndef get_date_extract_sql(lookup_type, table_name):\n # lookup_type is 'year', 'month', 'day'\n # http://www.postgresql.org/docs/8.0/static/functions-datetime.html#FUNCTIONS-DATETIME-EXTRACT\n return \"EXTRACT('%s' FROM %s)\" % (lookup_type, table_name)\n\ndef get_date_trunc_sql(lookup_type, field_name):\n # lookup_type is 'year', 'month', 'day'\n # http://www.postgresql.org/docs/8.0/static/functions-datetime.html#FUNCTIONS-DATETIME-TRUNC\n return \"DATE_TRUNC('%s', %s)\" % (lookup_type, field_name)\n\ndef get_limit_offset_sql(limit, offset=None):\n sql = \"LIMIT %s\" % limit\n if offset and offset != 0:\n sql += \" OFFSET %s\" % offset\n return sql\n\ndef get_random_function_sql():\n return \"RANDOM()\"\n\ndef get_table_list(cursor):\n \"Returns a list of table names in the current database.\"\n cursor.execute(\"\"\"\n SELECT c.relname\n FROM pg_catalog.pg_class c\n LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace\n WHERE c.relkind IN ('r', 'v', '')\n AND n.nspname NOT IN ('pg_catalog', 'pg_toast')\n AND pg_catalog.pg_table_is_visible(c.oid)\"\"\")\n return [row[0] for row in cursor.fetchall()]\n\ndef get_relations(cursor, table_name):\n \"\"\"\n Returns a dictionary of {field_index: (field_index_other_table, other_table)}\n representing all relationships to the given table. Indexes are 0-based.\n \"\"\"\n cursor.execute(\"\"\"\n SELECT con.conkey, con.confkey, c2.relname\n FROM pg_constraint con, pg_class c1, pg_class c2\n WHERE c1.oid = con.conrelid\n AND c2.oid = con.confrelid\n AND c1.relname = %s\n AND con.contype = 'f'\"\"\", [table_name])\n relations = {}\n for row in cursor.fetchall():\n try:\n # row[0] and row[1] are like \"{2}\", so strip the curly braces.\n relations[int(row[0][1:-1]) - 1] = (int(row[1][1:-1]) - 1, row[2])\n except ValueError:\n continue\n return relations\n\n# Register these custom typecasts, because Django expects dates/times to be\n# in Python's native (standard-library) datetime/time format, whereas psycopg\n# use mx.DateTime by default.\ntry:\n Database.register_type(Database.new_type((1082,), \"DATE\", typecasts.typecast_date))\nexcept AttributeError:\n raise Exception, \"You appear to be using psycopg version 2, which isn't supported yet, because it's still in beta. Use psycopg version 1 instead: http://initd.org/projects/psycopg1\"\nDatabase.register_type(Database.new_type((1083,1266), \"TIME\", typecasts.typecast_time))\nDatabase.register_type(Database.new_type((1114,1184), \"TIMESTAMP\", typecasts.typecast_timestamp))\nDatabase.register_type(Database.new_type((16,), \"BOOLEAN\", typecasts.typecast_boolean))\n\nOPERATOR_MAPPING = {\n 'exact': '=',\n 'iexact': 'ILIKE',\n 'contains': 'LIKE',\n 'icontains': 'ILIKE',\n 'ne': '!=',\n 'gt': '>',\n 'gte': '>=',\n 'lt': '<',\n 'lte': '<=',\n 'startswith': 'LIKE',\n 'endswith': 'LIKE',\n 'istartswith': 'ILIKE',\n 'iendswith': 'ILIKE',\n}\n\n# This dictionary maps Field objects to their associated PostgreSQL column\n# types, as strings. Column-type strings can contain format strings; they'll\n# be interpolated against the values of Field.__dict__ before being output.\n# If a column type is set to None, it won't be included in the output.\nDATA_TYPES = {\n 'AutoField': 'serial',\n 'BooleanField': 'boolean',\n 'CharField': 'varchar(%(maxlength)s)',\n 'CommaSeparatedIntegerField': 'varchar(%(maxlength)s)',\n 'DateField': 'date',\n 'DateTimeField': 'timestamp with time zone',\n 'EmailField': 'varchar(75)',\n 'FileField': 'varchar(100)',\n 'FilePathField': 'varchar(100)',\n 'FloatField': 'numeric(%(max_digits)s, %(decimal_places)s)',\n 'ImageField': 'varchar(100)',\n 'IntegerField': 'integer',\n 'IPAddressField': 'inet',\n 'ManyToManyField': None,\n 'NullBooleanField': 'boolean',\n 'OneToOneField': 'integer',\n 'PhoneNumberField': 'varchar(20)',\n 'PositiveIntegerField': 'integer CHECK (%(column)s >= 0)',\n 'PositiveSmallIntegerField': 'smallint CHECK (%(column)s >= 0)',\n 'SlugField': 'varchar(50)',\n 'SmallIntegerField': 'smallint',\n 'TextField': 'text',\n 'TimeField': 'time',\n 'URLField': 'varchar(200)',\n 'USStateField': 'varchar(2)',\n}\n\n# Maps type codes to Django Field types.\nDATA_TYPES_REVERSE = {\n 16: 'BooleanField',\n 21: 'SmallIntegerField',\n 23: 'IntegerField',\n 25: 'TextField',\n 869: 'IPAddressField',\n 1043: 'CharField',\n 1082: 'DateField',\n 1083: 'TimeField',\n 1114: 'DateTimeField',\n 1184: 'DateTimeField',\n 1266: 'TimeField',\n 1700: 'FloatField',\n}\n", "django/core/handlers/modpython.py": "from django.core.handlers.base import BaseHandler\nfrom django.utils import datastructures, httpwrappers\nfrom pprint import pformat\nimport os\n\n# NOTE: do *not* import settings (or any module which eventually imports\n# settings) until after ModPythonHandler has been called; otherwise os.environ\n# won't be set up correctly (with respect to settings).\n\nclass ModPythonRequest(httpwrappers.HttpRequest):\n def __init__(self, req):\n self._req = req\n self.path = req.uri\n\n def __repr__(self):\n return '' % \\\n (self.path, pformat(self.GET), pformat(self.POST), pformat(self.COOKIES),\n pformat(self.META), pformat(self.user))\n\n def get_full_path(self):\n return '%s%s' % (self.path, self._req.args and ('?' + self._req.args) or '')\n\n def _load_post_and_files(self):\n \"Populates self._post and self._files\"\n if self._req.headers_in.has_key('content-type') and self._req.headers_in['content-type'].startswith('multipart'):\n self._post, self._files = httpwrappers.parse_file_upload(self._req.headers_in, self.raw_post_data)\n else:\n self._post, self._files = httpwrappers.QueryDict(self.raw_post_data), datastructures.MultiValueDict()\n\n def _get_request(self):\n if not hasattr(self, '_request'):\n self._request = datastructures.MergeDict(self.POST, self.GET)\n return self._request\n\n def _get_get(self):\n if not hasattr(self, '_get'):\n self._get = httpwrappers.QueryDict(self._req.args)\n return self._get\n\n def _set_get(self, get):\n self._get = get\n\n def _get_post(self):\n if not hasattr(self, '_post'):\n self._load_post_and_files()\n return self._post\n\n def _set_post(self, post):\n self._post = post\n\n def _get_cookies(self):\n if not hasattr(self, '_cookies'):\n self._cookies = httpwrappers.parse_cookie(self._req.headers_in.get('cookie', ''))\n return self._cookies\n\n def _set_cookies(self, cookies):\n self._cookies = cookies\n\n def _get_files(self):\n if not hasattr(self, '_files'):\n self._load_post_and_files()\n return self._files\n\n def _get_meta(self):\n \"Lazy loader that returns self.META dictionary\"\n if not hasattr(self, '_meta'):\n self._meta = {\n 'AUTH_TYPE': self._req.ap_auth_type,\n 'CONTENT_LENGTH': self._req.clength, # This may be wrong\n 'CONTENT_TYPE': self._req.content_type, # This may be wrong\n 'GATEWAY_INTERFACE': 'CGI/1.1',\n 'PATH_INFO': self._req.path_info,\n 'PATH_TRANSLATED': None, # Not supported\n 'QUERY_STRING': self._req.args,\n 'REMOTE_ADDR': self._req.connection.remote_ip,\n 'REMOTE_HOST': None, # DNS lookups not supported\n 'REMOTE_IDENT': self._req.connection.remote_logname,\n 'REMOTE_USER': self._req.user,\n 'REQUEST_METHOD': self._req.method,\n 'SCRIPT_NAME': None, # Not supported\n 'SERVER_NAME': self._req.server.server_hostname,\n 'SERVER_PORT': self._req.server.port,\n 'SERVER_PROTOCOL': self._req.protocol,\n 'SERVER_SOFTWARE': 'mod_python'\n }\n for key, value in self._req.headers_in.items():\n key = 'HTTP_' + key.upper().replace('-', '_')\n self._meta[key] = value\n return self._meta\n\n def _get_raw_post_data(self):\n try:\n return self._raw_post_data\n except AttributeError:\n self._raw_post_data = self._req.read()\n return self._raw_post_data\n\n def _get_user(self):\n if not hasattr(self, '_user'):\n from django.models.auth import users\n try:\n user_id = self.session[users.SESSION_KEY]\n if not user_id:\n raise ValueError\n self._user = users.get_object(pk=user_id)\n except (AttributeError, KeyError, ValueError, users.UserDoesNotExist):\n from django.parts.auth import anonymoususers\n self._user = anonymoususers.AnonymousUser()\n return self._user\n\n def _set_user(self, user):\n self._user = user\n\n GET = property(_get_get, _set_get)\n POST = property(_get_post, _set_post)\n COOKIES = property(_get_cookies, _set_cookies)\n FILES = property(_get_files)\n META = property(_get_meta)\n REQUEST = property(_get_request)\n raw_post_data = property(_get_raw_post_data)\n user = property(_get_user, _set_user)\n\nclass ModPythonHandler(BaseHandler):\n def __call__(self, req):\n # mod_python fakes the environ, and thus doesn't process SetEnv. This fixes that\n os.environ.update(req.subprocess_env)\n\n # now that the environ works we can see the correct settings, so imports\n # that use settings now can work\n from django.conf import settings\n from django.core import db\n\n # if we need to set up middleware, now that settings works we can do it now.\n if self._request_middleware is None:\n self.load_middleware()\n\n try:\n request = ModPythonRequest(req)\n response = self.get_response(req.uri, request)\n # Apply response middleware\n for middleware_method in self._response_middleware:\n response = middleware_method(request, response)\n finally:\n db.db.close()\n\n # Convert our custom HttpResponse object back into the mod_python req.\n populate_apache_request(response, req)\n return 0 # mod_python.apache.OK\n\ndef populate_apache_request(http_response, mod_python_req):\n \"Populates the mod_python request object with an HttpResponse\"\n from django.conf import settings\n mod_python_req.content_type = http_response['Content-Type']\n for key, value in http_response.headers.items():\n if key != 'Content-Type':\n mod_python_req.headers_out[key] = value\n for c in http_response.cookies.values():\n mod_python_req.headers_out.add('Set-Cookie', c.output(header=''))\n mod_python_req.status = http_response.status_code\n mod_python_req.write(http_response.get_content_as_string(settings.DEFAULT_CHARSET))\n\ndef handler(req):\n # mod_python hooks into this function.\n return ModPythonHandler()(req)\n", "django/core/meta/__init__.py": "from django.conf import settings\nfrom django.core import formfields, validators\nfrom django.core import db\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.core.meta.fields import *\nfrom django.utils.functional import curry\nfrom django.utils.text import capfirst\nimport copy, datetime, os, re, sys, types\n\n# Admin stages.\nADD, CHANGE, BOTH = 1, 2, 3\n\n# Size of each \"chunk\" for get_iterator calls.\n# Larger values are slightly faster at the expense of more storage space.\nGET_ITERATOR_CHUNK_SIZE = 100\n\n# Prefix (in Python path style) to location of models.\nMODEL_PREFIX = 'django.models'\n\n# Methods on models with the following prefix will be removed and\n# converted to module-level functions.\nMODEL_FUNCTIONS_PREFIX = '_module_'\n\n# Methods on models with the following prefix will be removed and\n# converted to manipulator methods.\nMANIPULATOR_FUNCTIONS_PREFIX = '_manipulator_'\n\nLOOKUP_SEPARATOR = '__'\n\n####################\n# HELPER FUNCTIONS #\n####################\n\n# Django currently supports two forms of ordering.\n# Form 1 (deprecated) example:\n# order_by=(('pub_date', 'DESC'), ('headline', 'ASC'), (None, 'RANDOM'))\n# Form 2 (new-style) example:\n# order_by=('-pub_date', 'headline', '?')\n# Form 1 is deprecated and will no longer be supported for Django's first\n# official release. The following code converts from Form 1 to Form 2.\n\nLEGACY_ORDERING_MAPPING = {'ASC': '_', 'DESC': '-_', 'RANDOM': '?'}\n\ndef handle_legacy_orderlist(order_list):\n if not order_list or isinstance(order_list[0], basestring):\n return order_list\n else:\n import warnings\n new_order_list = [LEGACY_ORDERING_MAPPING[j.upper()].replace('_', str(i)) for i, j in order_list]\n warnings.warn(\"%r ordering syntax is deprecated. Use %r instead.\" % (order_list, new_order_list), DeprecationWarning)\n return new_order_list\n\ndef orderfield2column(f, opts):\n try:\n return opts.get_field(f, False).column\n except FieldDoesNotExist:\n return f\n\ndef orderlist2sql(order_list, opts, prefix=''):\n if prefix.endswith('.'):\n prefix = db.db.quote_name(prefix[:-1]) + '.'\n output = []\n for f in handle_legacy_orderlist(order_list):\n if f.startswith('-'):\n output.append('%s%s DESC' % (prefix, db.db.quote_name(orderfield2column(f[1:], opts))))\n elif f == '?':\n output.append(db.get_random_function_sql())\n else:\n output.append('%s%s ASC' % (prefix, db.db.quote_name(orderfield2column(f, opts))))\n return ', '.join(output)\n\ndef get_module(app_label, module_name):\n return __import__('%s.%s.%s' % (MODEL_PREFIX, app_label, module_name), '', '', [''])\n\ndef get_app(app_label):\n return __import__('%s.%s' % (MODEL_PREFIX, app_label), '', '', [''])\n\n_installed_models_cache = None\ndef get_installed_models():\n \"\"\"\n Returns a list of installed \"models\" packages, such as foo.models,\n ellington.news.models, etc. This does NOT include django.models.\n \"\"\"\n global _installed_models_cache\n if _installed_models_cache is not None:\n return _installed_models_cache\n _installed_models_cache = []\n for a in settings.INSTALLED_APPS:\n try:\n _installed_models_cache.append(__import__(a + '.models', '', '', ['']))\n except ImportError:\n pass\n return _installed_models_cache\n\n_installed_modules_cache = None\ndef get_installed_model_modules(core_models=None):\n \"\"\"\n Returns a list of installed models, such as django.models.core,\n ellington.news.models.news, foo.models.bar, etc.\n \"\"\"\n global _installed_modules_cache\n if _installed_modules_cache is not None:\n return _installed_modules_cache\n _installed_modules_cache = []\n\n # django.models is a special case.\n for submodule in (core_models or []):\n _installed_modules_cache.append(__import__('django.models.%s' % submodule, '', '', ['']))\n for m in get_installed_models():\n for submodule in getattr(m, '__all__', []):\n mod = __import__('django.models.%s' % submodule, '', '', [''])\n try:\n mod._MODELS\n except AttributeError:\n pass # Skip model modules that don't actually have models in them.\n else:\n _installed_modules_cache.append(mod)\n return _installed_modules_cache\n\nclass LazyDate:\n \"\"\"\n Use in limit_choices_to to compare the field to dates calculated at run time\n instead of when the model is loaded. For example::\n\n ... limit_choices_to = {'date__gt' : meta.LazyDate(days=-3)} ...\n\n which will limit the choices to dates greater than three days ago.\n \"\"\"\n def __init__(self, **kwargs):\n self.delta = datetime.timedelta(**kwargs)\n\n def __str__(self):\n return str(self.__get_value__())\n\n def __repr__(self):\n return \"\" % self.delta\n\n def __get_value__(self):\n return datetime.datetime.now() + self.delta\n\n################\n# MAIN CLASSES #\n################\n\nclass FieldDoesNotExist(Exception):\n pass\n\nclass BadKeywordArguments(Exception):\n pass\n\nclass Options:\n def __init__(self, module_name='', verbose_name='', verbose_name_plural='', db_table='',\n fields=None, ordering=None, unique_together=None, admin=None, has_related_links=False,\n where_constraints=None, object_name=None, app_label=None,\n exceptions=None, permissions=None, get_latest_by=None,\n order_with_respect_to=None, module_constants=None):\n\n # Save the original function args, for use by copy(). Note that we're\n # NOT using copy.deepcopy(), because that would create a new copy of\n # everything in memory, and it's better to conserve memory. Of course,\n # this comes with the important gotcha that changing any attribute of\n # this object will change its value in self._orig_init_args, so we\n # need to be careful not to do that. In practice, we can pull this off\n # because Options are generally read-only objects, and __init__() is\n # the only place where its attributes are manipulated.\n\n # locals() is used purely for convenience, so we don't have to do\n # something verbose like this:\n # self._orig_init_args = {\n # 'module_name': module_name,\n # 'verbose_name': verbose_name,\n # ...\n # }\n self._orig_init_args = locals()\n del self._orig_init_args['self'] # because we don't care about it.\n\n # Move many-to-many related fields from self.fields into self.many_to_many.\n self.fields, self.many_to_many = [], []\n for field in (fields or []):\n if field.rel and isinstance(field.rel, ManyToMany):\n self.many_to_many.append(field)\n else:\n self.fields.append(field)\n self.module_name, self.verbose_name = module_name, verbose_name\n self.verbose_name_plural = verbose_name_plural or verbose_name + 's'\n self.db_table, self.has_related_links = db_table, has_related_links\n self.ordering = ordering or []\n self.unique_together = unique_together or []\n self.where_constraints = where_constraints or []\n self.exceptions = exceptions or []\n self.permissions = permissions or []\n self.object_name, self.app_label = object_name, app_label\n self.get_latest_by = get_latest_by\n if order_with_respect_to:\n self.order_with_respect_to = self.get_field(order_with_respect_to)\n self.ordering = ('_order',)\n else:\n self.order_with_respect_to = None\n self.module_constants = module_constants or {}\n self.admin = admin\n\n # Calculate one_to_one_field.\n self.one_to_one_field = None\n for f in self.fields:\n if isinstance(f.rel, OneToOne):\n self.one_to_one_field = f\n break\n # Cache the primary-key field.\n self.pk = None\n for f in self.fields:\n if f.primary_key:\n self.pk = f\n break\n # If a primary_key field hasn't been specified, add an\n # auto-incrementing primary-key ID field automatically.\n if self.pk is None:\n self.fields.insert(0, AutoField(name='id', verbose_name='ID', primary_key=True))\n self.pk = self.fields[0]\n # Cache whether this has an AutoField.\n self.has_auto_field = False\n for f in self.fields:\n is_auto = isinstance(f, AutoField)\n if is_auto and self.has_auto_field:\n raise AssertionError, \"A model can't have more than one AutoField.\"\n elif is_auto:\n self.has_auto_field = True\n\n def __repr__(self):\n return '' % self.module_name\n\n def copy(self, **kwargs):\n args = self._orig_init_args.copy()\n args.update(kwargs)\n return self.__class__(**args)\n\n def get_model_module(self):\n return get_module(self.app_label, self.module_name)\n\n def get_content_type_id(self):\n \"Returns the content-type ID for this object type.\"\n if not hasattr(self, '_content_type_id'):\n mod = get_module('core', 'contenttypes')\n self._content_type_id = mod.get_object(python_module_name__exact=self.module_name, package__label__exact=self.app_label).id\n return self._content_type_id\n\n def get_field(self, name, many_to_many=True):\n \"\"\"\n Returns the requested field by name. Raises FieldDoesNotExist on error.\n \"\"\"\n to_search = many_to_many and (self.fields + self.many_to_many) or self.fields\n for f in to_search:\n if f.name == name:\n return f\n raise FieldDoesNotExist, \"name=%s\" % name\n\n def get_order_sql(self, table_prefix=''):\n \"Returns the full 'ORDER BY' clause for this object, according to self.ordering.\"\n if not self.ordering: return ''\n pre = table_prefix and (table_prefix + '.') or ''\n return 'ORDER BY ' + orderlist2sql(self.ordering, self, pre)\n\n def get_add_permission(self):\n return 'add_%s' % self.object_name.lower()\n\n def get_change_permission(self):\n return 'change_%s' % self.object_name.lower()\n\n def get_delete_permission(self):\n return 'delete_%s' % self.object_name.lower()\n\n def get_rel_object_method_name(self, rel_opts, rel_field):\n # This method encapsulates the logic that decides what name to give a\n # method that retrieves related many-to-one objects. Usually it just\n # uses the lower-cased object_name, but if the related object is in\n # another app, its app_label is appended.\n #\n # Examples:\n #\n # # Normal case -- a related object in the same app.\n # # This method returns \"choice\".\n # Poll.get_choice_list()\n #\n # # A related object in a different app.\n # # This method returns \"lcom_bestofaward\".\n # Place.get_lcom_bestofaward_list() # \"lcom_bestofaward\"\n rel_obj_name = rel_field.rel.related_name or rel_opts.object_name.lower()\n if self.app_label != rel_opts.app_label:\n rel_obj_name = '%s_%s' % (rel_opts.app_label, rel_obj_name)\n return rel_obj_name\n\n def get_all_related_objects(self):\n try: # Try the cache first.\n return self._all_related_objects\n except AttributeError:\n module_list = get_installed_model_modules()\n rel_objs = []\n for mod in module_list:\n for klass in mod._MODELS:\n for f in klass._meta.fields:\n if f.rel and self == f.rel.to:\n rel_objs.append((klass._meta, f))\n if self.has_related_links:\n # Manually add RelatedLink objects, which are a special case.\n relatedlinks = get_module('relatedlinks', 'relatedlinks')\n # Note that the copy() is very important -- otherwise any\n # subsequently loaded object with related links will override this\n # relationship we're adding.\n link_field = copy.copy(relatedlinks.RelatedLink._meta.get_field('object_id'))\n link_field.rel = ManyToOne(self.get_model_module().Klass, 'id',\n num_in_admin=3, min_num_in_admin=3, edit_inline=TABULAR,\n lookup_overrides={\n 'content_type__package__label__exact': self.app_label,\n 'content_type__python_module_name__exact': self.module_name,\n })\n rel_objs.append((relatedlinks.RelatedLink._meta, link_field))\n self._all_related_objects = rel_objs\n return rel_objs\n\n def get_inline_related_objects(self):\n return [(a, b) for a, b in self.get_all_related_objects() if b.rel.edit_inline]\n\n def get_all_related_many_to_many_objects(self):\n module_list = get_installed_model_modules()\n rel_objs = []\n for mod in module_list:\n for klass in mod._MODELS:\n try:\n for f in klass._meta.many_to_many:\n if f.rel and self == f.rel.to:\n rel_objs.append((klass._meta, f))\n raise StopIteration\n except StopIteration:\n continue\n return rel_objs\n\n def get_ordered_objects(self):\n \"Returns a list of Options objects that are ordered with respect to this object.\"\n if not hasattr(self, '_ordered_objects'):\n objects = []\n for klass in get_app(self.app_label)._MODELS:\n opts = klass._meta\n if opts.order_with_respect_to and opts.order_with_respect_to.rel \\\n and self == opts.order_with_respect_to.rel.to:\n objects.append(opts)\n self._ordered_objects = objects\n return self._ordered_objects\n\n def has_field_type(self, field_type):\n \"\"\"\n Returns True if this object's admin form has at least one of the given\n field_type (e.g. FileField).\n \"\"\"\n if not hasattr(self, '_field_types'):\n self._field_types = {}\n if not self._field_types.has_key(field_type):\n try:\n # First check self.fields.\n for f in self.fields:\n if isinstance(f, field_type):\n raise StopIteration\n # Failing that, check related fields.\n for rel_obj, rel_field in self.get_inline_related_objects():\n for f in rel_obj.fields:\n if isinstance(f, field_type):\n raise StopIteration\n except StopIteration:\n self._field_types[field_type] = True\n else:\n self._field_types[field_type] = False\n return self._field_types[field_type]\n\ndef _reassign_globals(function_dict, extra_globals, namespace):\n new_functions = {}\n for k, v in function_dict.items():\n # Get the code object.\n code = v.func_code\n # Recreate the function, but give it access to extra_globals and the\n # given namespace's globals, too.\n new_globals = {'__builtins__': __builtins__, 'db': db.db, 'datetime': datetime}\n new_globals.update(extra_globals.__dict__)\n func = types.FunctionType(code, globals=new_globals, name=k, argdefs=v.func_defaults)\n func.__dict__.update(v.__dict__)\n setattr(namespace, k, func)\n # For all of the custom functions that have been added so far, give\n # them access to the new function we've just created.\n for new_k, new_v in new_functions.items():\n new_v.func_globals[k] = func\n new_functions[k] = func\n\n# Calculate the module_name using a poor-man's pluralization.\nget_module_name = lambda class_name: class_name.lower() + 's'\n\n# Calculate the verbose_name by converting from InitialCaps to \"lowercase with spaces\".\nget_verbose_name = lambda class_name: re.sub('([A-Z])', ' \\\\1', class_name).lower().strip()\n\nclass ModelBase(type):\n \"Metaclass for all models\"\n def __new__(cls, name, bases, attrs):\n # If this isn't a subclass of Model, don't do anything special.\n if not bases:\n return type.__new__(cls, name, bases, attrs)\n\n try:\n meta_attrs = attrs.pop('META').__dict__\n del meta_attrs['__module__']\n del meta_attrs['__doc__']\n except KeyError:\n meta_attrs = {}\n\n # Gather all attributes that are Field instances.\n fields = []\n for obj_name, obj in attrs.items():\n if isinstance(obj, Field):\n obj.set_name(obj_name)\n fields.append(obj)\n del attrs[obj_name]\n\n # Sort the fields in the order that they were created. The\n # \"creation_counter\" is needed because metaclasses don't preserve the\n # attribute order.\n fields.sort(lambda x, y: x.creation_counter - y.creation_counter)\n\n # If this model is a subclass of another model, create an Options\n # object by first copying the base class's _meta and then updating it\n # with the overrides from this class.\n replaces_module = None\n if bases[0] != Model:\n field_names = [f.name for f in fields]\n remove_fields = meta_attrs.pop('remove_fields', [])\n for f in bases[0]._meta._orig_init_args['fields']:\n if f.name not in field_names and f.name not in remove_fields:\n fields.insert(0, f)\n if meta_attrs.has_key('replaces_module'):\n # Set the replaces_module variable for now. We can't actually\n # do anything with it yet, because the module hasn't yet been\n # created.\n replaces_module = meta_attrs.pop('replaces_module').split('.')\n # Pass any Options overrides to the base's Options instance, and\n # simultaneously remove them from attrs. When this is done, attrs\n # will be a dictionary of custom methods, plus __module__.\n meta_overrides = {'fields': fields, 'module_name': get_module_name(name), 'verbose_name': get_verbose_name(name)}\n for k, v in meta_attrs.items():\n if not callable(v) and k != '__module__':\n meta_overrides[k] = meta_attrs.pop(k)\n opts = bases[0]._meta.copy(**meta_overrides)\n opts.object_name = name\n del meta_overrides\n else:\n opts = Options(\n module_name = meta_attrs.pop('module_name', get_module_name(name)),\n # If the verbose_name wasn't given, use the class name,\n # converted from InitialCaps to \"lowercase with spaces\".\n verbose_name = meta_attrs.pop('verbose_name', get_verbose_name(name)),\n verbose_name_plural = meta_attrs.pop('verbose_name_plural', ''),\n db_table = meta_attrs.pop('db_table', ''),\n fields = fields,\n ordering = meta_attrs.pop('ordering', None),\n unique_together = meta_attrs.pop('unique_together', None),\n admin = meta_attrs.pop('admin', None),\n has_related_links = meta_attrs.pop('has_related_links', False),\n where_constraints = meta_attrs.pop('where_constraints', None),\n object_name = name,\n app_label = meta_attrs.pop('app_label', None),\n exceptions = meta_attrs.pop('exceptions', None),\n permissions = meta_attrs.pop('permissions', None),\n get_latest_by = meta_attrs.pop('get_latest_by', None),\n order_with_respect_to = meta_attrs.pop('order_with_respect_to', None),\n module_constants = meta_attrs.pop('module_constants', None),\n )\n\n if meta_attrs != {}:\n raise TypeError, \"'class META' got invalid attribute(s): %s\" % ','.join(meta_attrs.keys())\n\n # Dynamically create the module that will contain this class and its\n # associated helper functions.\n if replaces_module is not None:\n new_mod = get_module(*replaces_module)\n else:\n new_mod = types.ModuleType(opts.module_name)\n\n # Collect any/all custom class methods and module functions, and move\n # them to a temporary holding variable. We'll deal with them later.\n if replaces_module is not None:\n # Initialize these values to the base class' custom_methods and\n # custom_functions.\n custom_methods = dict([(k, v) for k, v in new_mod.Klass.__dict__.items() if hasattr(v, 'custom')])\n custom_functions = dict([(k, v) for k, v in new_mod.__dict__.items() if hasattr(v, 'custom')])\n else:\n custom_methods, custom_functions = {}, {}\n manipulator_methods = {}\n for k, v in attrs.items():\n if k in ('__module__', '__init__', '_overrides', '__doc__'):\n continue # Skip the important stuff.\n assert callable(v), \"%r is an invalid model parameter.\" % k\n # Give the function a function attribute \"custom\" to designate that\n # it's a custom function/method.\n v.custom = True\n if k.startswith(MODEL_FUNCTIONS_PREFIX):\n custom_functions[k[len(MODEL_FUNCTIONS_PREFIX):]] = v\n elif k.startswith(MANIPULATOR_FUNCTIONS_PREFIX):\n manipulator_methods[k[len(MANIPULATOR_FUNCTIONS_PREFIX):]] = v\n else:\n custom_methods[k] = v\n del attrs[k]\n\n # Create the module-level ObjectDoesNotExist exception.\n dne_exc_name = '%sDoesNotExist' % name\n does_not_exist_exception = types.ClassType(dne_exc_name, (ObjectDoesNotExist,), {})\n # Explicitly set its __module__ because it will initially (incorrectly)\n # be set to the module the code is being executed in.\n does_not_exist_exception.__module__ = MODEL_PREFIX + '.' + opts.module_name\n setattr(new_mod, dne_exc_name, does_not_exist_exception)\n\n # Create other exceptions.\n for exception_name in opts.exceptions:\n exc = types.ClassType(exception_name, (Exception,), {})\n exc.__module__ = MODEL_PREFIX + '.' + opts.module_name # Set this explicitly, as above.\n setattr(new_mod, exception_name, exc)\n\n # Create any module-level constants, if applicable.\n for k, v in opts.module_constants.items():\n setattr(new_mod, k, v)\n\n # Create the default class methods.\n attrs['__init__'] = curry(method_init, opts)\n attrs['__eq__'] = curry(method_eq, opts)\n attrs['save'] = curry(method_save, opts)\n attrs['save'].alters_data = True\n attrs['delete'] = curry(method_delete, opts)\n attrs['delete'].alters_data = True\n\n if opts.order_with_respect_to:\n attrs['get_next_in_order'] = curry(method_get_next_in_order, opts, opts.order_with_respect_to)\n attrs['get_previous_in_order'] = curry(method_get_previous_in_order, opts, opts.order_with_respect_to)\n\n for f in opts.fields:\n # If the object has a relationship to itself, as designated by\n # RECURSIVE_RELATIONSHIP_CONSTANT, create that relationship formally.\n if f.rel and f.rel.to == RECURSIVE_RELATIONSHIP_CONSTANT:\n f.rel.to = opts\n f.name = f.name or (f.rel.to.object_name.lower() + '_' + f.rel.to.pk.name)\n f.verbose_name = f.verbose_name or f.rel.to.verbose_name\n f.rel.field_name = f.rel.field_name or f.rel.to.pk.name\n # Add \"get_thingie\" methods for many-to-one related objects.\n # EXAMPLES: Choice.get_poll(), Story.get_dateline()\n if isinstance(f.rel, ManyToOne):\n func = curry(method_get_many_to_one, f)\n func.__doc__ = \"Returns the associated `%s.%s` object.\" % (f.rel.to.app_label, f.rel.to.module_name)\n attrs['get_%s' % f.name] = func\n\n for f in opts.many_to_many:\n # Add \"get_thingie\" methods for many-to-many related objects.\n # EXAMPLES: Poll.get_site_list(), Story.get_byline_list()\n func = curry(method_get_many_to_many, f)\n func.__doc__ = \"Returns a list of associated `%s.%s` objects.\" % (f.rel.to.app_label, f.rel.to.module_name)\n attrs['get_%s_list' % f.rel.singular] = func\n # Add \"set_thingie\" methods for many-to-many related objects.\n # EXAMPLES: Poll.set_sites(), Story.set_bylines()\n func = curry(method_set_many_to_many, f)\n func.__doc__ = \"Resets this object's `%s.%s` list to the given list of IDs. Note that it doesn't check whether the given IDs are valid.\" % (f.rel.to.app_label, f.rel.to.module_name)\n func.alters_data = True\n attrs['set_%s' % f.name] = func\n\n # Create the class, because we need it to use in currying.\n new_class = type.__new__(cls, name, bases, attrs)\n\n # Give the class a docstring -- its definition.\n if new_class.__doc__ is None:\n new_class.__doc__ = \"%s.%s(%s)\" % (opts.module_name, name, \", \".join([f.name for f in opts.fields]))\n\n # Create the standard, module-level API helper functions such\n # as get_object() and get_list().\n new_mod.get_object = curry(function_get_object, opts, new_class, does_not_exist_exception)\n new_mod.get_object.__doc__ = \"Returns the %s object matching the given parameters.\" % name\n\n new_mod.get_list = curry(function_get_list, opts, new_class)\n new_mod.get_list.__doc__ = \"Returns a list of %s objects matching the given parameters.\" % name\n\n new_mod.get_iterator = curry(function_get_iterator, opts, new_class)\n new_mod.get_iterator.__doc__ = \"Returns an iterator of %s objects matching the given parameters.\" % name\n\n new_mod.get_values = curry(function_get_values, opts, new_class)\n new_mod.get_values.__doc__ = \"Returns a list of dictionaries matching the given parameters.\"\n\n new_mod.get_values_iterator = curry(function_get_values_iterator, opts, new_class)\n new_mod.get_values_iterator.__doc__ = \"Returns an iterator of dictionaries matching the given parameters.\"\n\n new_mod.get_count = curry(function_get_count, opts)\n new_mod.get_count.__doc__ = \"Returns the number of %s objects matching the given parameters.\" % name\n\n new_mod._get_sql_clause = curry(function_get_sql_clause, opts)\n\n new_mod.get_in_bulk = curry(function_get_in_bulk, opts, new_class)\n new_mod.get_in_bulk.__doc__ = \"Returns a dictionary of ID -> %s for the %s objects with IDs in the given id_list.\" % (name, name)\n\n if opts.get_latest_by:\n new_mod.get_latest = curry(function_get_latest, opts, new_class, does_not_exist_exception)\n\n for f in opts.fields:\n if f.choices:\n # Add \"get_thingie_display\" method to get human-readable value.\n func = curry(method_get_display_value, f)\n setattr(new_class, 'get_%s_display' % f.name, func)\n if isinstance(f, DateField) or isinstance(f, DateTimeField):\n # Add \"get_next_by_thingie\" and \"get_previous_by_thingie\" methods\n # for all DateFields and DateTimeFields that cannot be null.\n # EXAMPLES: Poll.get_next_by_pub_date(), Poll.get_previous_by_pub_date()\n if not f.null:\n setattr(new_class, 'get_next_by_%s' % f.name, curry(method_get_next_or_previous, new_mod.get_object, opts, f, True))\n setattr(new_class, 'get_previous_by_%s' % f.name, curry(method_get_next_or_previous, new_mod.get_object, opts, f, False))\n # Add \"get_thingie_list\" for all DateFields and DateTimeFields.\n # EXAMPLE: polls.get_pub_date_list()\n func = curry(function_get_date_list, opts, f)\n func.__doc__ = \"Returns a list of days, months or years (as datetime.datetime objects) in which %s objects are available. The first parameter ('kind') must be one of 'year', 'month' or 'day'.\" % name\n setattr(new_mod, 'get_%s_list' % f.name, func)\n\n elif isinstance(f, FileField):\n setattr(new_class, 'get_%s_filename' % f.name, curry(method_get_file_filename, f))\n setattr(new_class, 'get_%s_url' % f.name, curry(method_get_file_url, f))\n setattr(new_class, 'get_%s_size' % f.name, curry(method_get_file_size, f))\n func = curry(method_save_file, f)\n func.alters_data = True\n setattr(new_class, 'save_%s_file' % f.name, func)\n if isinstance(f, ImageField):\n # Add get_BLAH_width and get_BLAH_height methods, but only\n # if the image field doesn't have width and height cache\n # fields.\n if not f.width_field:\n setattr(new_class, 'get_%s_width' % f.name, curry(method_get_image_width, f))\n if not f.height_field:\n setattr(new_class, 'get_%s_height' % f.name, curry(method_get_image_height, f))\n\n # Add the class itself to the new module we've created.\n new_mod.__dict__[name] = new_class\n\n # Add \"Klass\" -- a shortcut reference to the class.\n new_mod.__dict__['Klass'] = new_class\n\n # Add the Manipulators.\n new_mod.__dict__['AddManipulator'] = get_manipulator(opts, new_class, manipulator_methods, add=True)\n new_mod.__dict__['ChangeManipulator'] = get_manipulator(opts, new_class, manipulator_methods, change=True)\n\n # Now that we have references to new_mod and new_class, we can add\n # any/all extra class methods to the new class. Note that we could\n # have just left the extra methods in attrs (above), but that would\n # have meant that any code within the extra methods would *not* have\n # access to module-level globals, such as get_list(), db, etc.\n # In order to give these methods access to those globals, we have to\n # deconstruct the method getting its raw \"code\" object, then recreating\n # the function with a new \"globals\" dictionary.\n #\n # To complicate matters more, because each method is manually assigned\n # a \"globals\" value, that \"globals\" value does NOT include the methods\n # that haven't been created yet. For instance, if there are two custom\n # methods, foo() and bar(), and foo() is created first, it won't have\n # bar() within its globals(). This is a problem because sometimes\n # custom methods/functions refer to other custom methods/functions. To\n # solve this problem, we keep track of the new functions created (in\n # the new_functions variable) and manually append each new function to\n # the func_globals() of all previously-created functions. So, by the\n # end of the loop, all functions will \"know\" about all the other\n # functions.\n _reassign_globals(custom_methods, new_mod, new_class)\n _reassign_globals(custom_functions, new_mod, new_mod)\n _reassign_globals(manipulator_methods, new_mod, new_mod.__dict__['AddManipulator'])\n _reassign_globals(manipulator_methods, new_mod, new_mod.__dict__['ChangeManipulator'])\n\n if hasattr(new_class, 'get_absolute_url'):\n new_class.get_absolute_url = curry(get_absolute_url, opts, new_class.get_absolute_url)\n\n # Get a reference to the module the class is in, and dynamically add\n # the new module to it.\n app_package = sys.modules.get(new_class.__module__)\n if replaces_module is not None:\n app_label = replaces_module[0]\n else:\n app_package.__dict__[opts.module_name] = new_mod\n app_label = app_package.__name__[app_package.__name__.rfind('.')+1:]\n\n # Populate the _MODELS member on the module the class is in.\n # Example: django.models.polls will have a _MODELS member that will\n # contain this list:\n # [, ]\n # Don't do this if replaces_module is set.\n app_package.__dict__.setdefault('_MODELS', []).append(new_class)\n\n # Cache the app label.\n opts.app_label = app_label\n\n # If the db_table wasn't provided, use the app_label + module_name.\n if not opts.db_table:\n opts.db_table = \"%s_%s\" % (app_label, opts.module_name)\n new_class._meta = opts\n\n # Set the __file__ attribute to the __file__ attribute of its package,\n # because they're technically from the same file. Note: if we didn't\n # set this, sys.modules would think this module was built-in.\n try:\n new_mod.__file__ = app_package.__file__\n except AttributeError:\n # 'module' object has no attribute '__file__', which means the\n # class was probably being entered via the interactive interpreter.\n pass\n\n # Add the module's entry to sys.modules -- for instance,\n # \"django.models.polls.polls\". Note that \"django.models.polls\" has already\n # been added automatically.\n sys.modules.setdefault('%s.%s.%s' % (MODEL_PREFIX, app_label, opts.module_name), new_mod)\n\n # If this module replaces another one, get a reference to the other\n # module's parent, and replace the other module with the one we've just\n # created.\n if replaces_module is not None:\n old_app = get_app(replaces_module[0])\n setattr(old_app, replaces_module[1], new_mod)\n for i, model in enumerate(old_app._MODELS):\n if model._meta.module_name == replaces_module[1]:\n # Replace the appropriate member of the old app's _MODELS\n # data structure.\n old_app._MODELS[i] = new_class\n # Replace all relationships to the old class with\n # relationships to the new one.\n for rel_opts, rel_field in model._meta.get_all_related_objects():\n rel_field.rel.to = opts\n for rel_opts, rel_field in model._meta.get_all_related_many_to_many_objects():\n rel_field.rel.to = opts\n break\n\n return new_class\n\nclass Model:\n __metaclass__ = ModelBase\n\n def __repr__(self):\n return '<%s object>' % self.__class__.__name__\n\n############################################\n# HELPER FUNCTIONS (CURRIED MODEL METHODS) #\n############################################\n\n# CORE METHODS #############################\n\ndef method_init(opts, self, *args, **kwargs):\n if kwargs:\n for f in opts.fields:\n if isinstance(f.rel, ManyToOne):\n try:\n # Assume object instance was passed in.\n rel_obj = kwargs.pop(f.name)\n except KeyError:\n try:\n # Object instance wasn't passed in -- must be an ID.\n val = kwargs.pop(f.attname)\n except KeyError:\n val = f.get_default()\n else:\n # Special case: You can pass in \"None\" for related objects if it's allowed.\n if rel_obj is None and f.null:\n val = None\n else:\n try:\n val = getattr(rel_obj, f.rel.field_name)\n except AttributeError:\n raise TypeError, \"Invalid value: %r should be a %s instance, not a %s\" % (f.name, f.rel.to, type(rel_obj))\n setattr(self, f.attname, val)\n else:\n val = kwargs.pop(f.attname, f.get_default())\n setattr(self, f.attname, val)\n if kwargs:\n raise TypeError, \"'%s' is an invalid keyword argument for this function\" % kwargs.keys()[0]\n for i, arg in enumerate(args):\n setattr(self, opts.fields[i].attname, arg)\n\ndef method_eq(opts, self, other):\n return isinstance(other, self.__class__) and getattr(self, opts.pk.attname) == getattr(other, opts.pk.attname)\n\ndef method_save(opts, self):\n # Run any pre-save hooks.\n if hasattr(self, '_pre_save'):\n self._pre_save()\n non_pks = [f for f in opts.fields if not f.primary_key]\n cursor = db.db.cursor()\n\n # First, try an UPDATE. If that doesn't update anything, do an INSERT.\n pk_val = getattr(self, opts.pk.attname)\n pk_set = bool(pk_val)\n record_exists = True\n if pk_set:\n # Determine whether a record with the primary key already exists.\n cursor.execute(\"SELECT 1 FROM %s WHERE %s=%%s LIMIT 1\" % \\\n (db.db.quote_name(opts.db_table), db.db.quote_name(opts.pk.column)), [pk_val])\n # If it does already exist, do an UPDATE.\n if cursor.fetchone():\n db_values = [f.get_db_prep_save(f.pre_save(getattr(self, f.attname), False)) for f in non_pks]\n cursor.execute(\"UPDATE %s SET %s WHERE %s=%%s\" % \\\n (db.db.quote_name(opts.db_table),\n ','.join(['%s=%%s' % db.db.quote_name(f.column) for f in non_pks]),\n db.db.quote_name(opts.pk.attname)),\n db_values + [pk_val])\n else:\n record_exists = False\n if not pk_set or not record_exists:\n field_names = [db.db.quote_name(f.column) for f in opts.fields if not isinstance(f, AutoField)]\n placeholders = ['%s'] * len(field_names)\n db_values = [f.get_db_prep_save(f.pre_save(getattr(self, f.attname), True)) for f in opts.fields if not isinstance(f, AutoField)]\n if opts.order_with_respect_to:\n field_names.append(db.db.quote_name('_order'))\n # TODO: This assumes the database supports subqueries.\n placeholders.append('(SELECT COUNT(*) FROM %s WHERE %s = %%s)' % \\\n (db.db.quote_name(opts.db_table), db.db.quote_name(opts.order_with_respect_to.column)))\n db_values.append(getattr(self, opts.order_with_respect_to.attname))\n cursor.execute(\"INSERT INTO %s (%s) VALUES (%s)\" % \\\n (db.db.quote_name(opts.db_table), ','.join(field_names),\n ','.join(placeholders)), db_values)\n if opts.has_auto_field:\n setattr(self, opts.pk.attname, db.get_last_insert_id(cursor, opts.db_table, opts.pk.column))\n db.db.commit()\n # Run any post-save hooks.\n if hasattr(self, '_post_save'):\n self._post_save()\n\ndef method_delete(opts, self):\n assert getattr(self, opts.pk.attname) is not None, \"%r can't be deleted because it doesn't have an ID.\"\n # Run any pre-delete hooks.\n if hasattr(self, '_pre_delete'):\n self._pre_delete()\n cursor = db.db.cursor()\n for rel_opts, rel_field in opts.get_all_related_objects():\n rel_opts_name = opts.get_rel_object_method_name(rel_opts, rel_field)\n if isinstance(rel_field.rel, OneToOne):\n try:\n sub_obj = getattr(self, 'get_%s' % rel_opts_name)()\n except ObjectDoesNotExist:\n pass\n else:\n sub_obj.delete()\n else:\n for sub_obj in getattr(self, 'get_%s_list' % rel_opts_name)():\n sub_obj.delete()\n for rel_opts, rel_field in opts.get_all_related_many_to_many_objects():\n cursor.execute(\"DELETE FROM %s WHERE %s=%%s\" % \\\n (db.db.quote_name(rel_field.get_m2m_db_table(rel_opts)),\n db.db.quote_name(self._meta.object_name.lower() + '_id')), [getattr(self, opts.pk.attname)])\n for f in opts.many_to_many:\n cursor.execute(\"DELETE FROM %s WHERE %s=%%s\" % \\\n (db.db.quote_name(f.get_m2m_db_table(opts)),\n db.db.quote_name(self._meta.object_name.lower() + '_id')),\n [getattr(self, opts.pk.attname)])\n cursor.execute(\"DELETE FROM %s WHERE %s=%%s\" % \\\n (db.db.quote_name(opts.db_table), db.db.quote_name(opts.pk.column)),\n [getattr(self, opts.pk.attname)])\n db.db.commit()\n setattr(self, opts.pk.attname, None)\n for f in opts.fields:\n if isinstance(f, FileField) and getattr(self, f.attname):\n file_name = getattr(self, 'get_%s_filename' % f.name)()\n # If the file exists and no other object of this type references it,\n # delete it from the filesystem.\n if os.path.exists(file_name) and not opts.get_model_module().get_list(**{'%s__exact' % f.name: getattr(self, f.name)}):\n os.remove(file_name)\n # Run any post-delete hooks.\n if hasattr(self, '_post_delete'):\n self._post_delete()\n\ndef method_get_next_in_order(opts, order_field, self):\n if not hasattr(self, '_next_in_order_cache'):\n self._next_in_order_cache = opts.get_model_module().get_object(order_by=('_order',),\n where=['%s > (SELECT %s FROM %s WHERE %s=%%s)' % \\\n (db.db.quote_name('_order'), db.db.quote_name('_order'),\n db.db.quote_name(opts.db_table), db.db.quote_name(opts.pk.column)),\n '%s=%%s' % db.db.quote_name(order_field.column)], limit=1,\n params=[getattr(self, opts.pk.attname), getattr(self, order_field.attname)])\n return self._next_in_order_cache\n\ndef method_get_previous_in_order(opts, order_field, self):\n if not hasattr(self, '_previous_in_order_cache'):\n self._previous_in_order_cache = opts.get_model_module().get_object(order_by=('-_order',),\n where=['%s < (SELECT %s FROM %s WHERE %s=%%s)' % \\\n (db.db.quote_name('_order'), db.db.quote_name('_order'),\n db.db.quote_name(opts.db_table), db.db.quote_name(opts.pk.column)),\n '%s=%%s' % db.db.quote_name(order_field.column)], limit=1,\n params=[getattr(self, opts.pk.attname), getattr(self, order_field.attname)])\n return self._previous_in_order_cache\n\n# RELATIONSHIP METHODS #####################\n\n# Example: Story.get_dateline()\ndef method_get_many_to_one(field_with_rel, self):\n cache_var = field_with_rel.get_cache_name()\n if not hasattr(self, cache_var):\n val = getattr(self, field_with_rel.attname)\n mod = field_with_rel.rel.to.get_model_module()\n if val is None:\n raise getattr(mod, '%sDoesNotExist' % field_with_rel.rel.to.object_name)\n retrieved_obj = mod.get_object(**{'%s__exact' % field_with_rel.rel.field_name: val})\n setattr(self, cache_var, retrieved_obj)\n return getattr(self, cache_var)\n\n# Handles getting many-to-many related objects.\n# Example: Poll.get_site_list()\ndef method_get_many_to_many(field_with_rel, self):\n rel = field_with_rel.rel.to\n cache_var = '_%s_cache' % field_with_rel.name\n if not hasattr(self, cache_var):\n mod = rel.get_model_module()\n sql = \"SELECT %s FROM %s a, %s b WHERE a.%s = b.%s AND b.%s = %%s %s\" % \\\n (','.join(['a.%s' % db.db.quote_name(f.column) for f in rel.fields]),\n db.db.quote_name(rel.db_table),\n db.db.quote_name(field_with_rel.get_m2m_db_table(self._meta)),\n db.db.quote_name(rel.pk.column),\n db.db.quote_name(rel.object_name.lower() + '_id'),\n db.db.quote_name(self._meta.object_name.lower() + '_id'), rel.get_order_sql('a'))\n cursor = db.db.cursor()\n cursor.execute(sql, [getattr(self, self._meta.pk.attname)])\n setattr(self, cache_var, [getattr(mod, rel.object_name)(*row) for row in cursor.fetchall()])\n return getattr(self, cache_var)\n\n# Handles setting many-to-many relationships.\n# Example: Poll.set_sites()\ndef method_set_many_to_many(rel_field, self, id_list):\n current_ids = [obj.id for obj in method_get_many_to_many(rel_field, self)]\n ids_to_add, ids_to_delete = dict([(i, 1) for i in id_list]), []\n for current_id in current_ids:\n if current_id in id_list:\n del ids_to_add[current_id]\n else:\n ids_to_delete.append(current_id)\n ids_to_add = ids_to_add.keys()\n # Now ids_to_add is a list of IDs to add, and ids_to_delete is a list of IDs to delete.\n if not ids_to_delete and not ids_to_add:\n return False # No change\n rel = rel_field.rel.to\n m2m_table = rel_field.get_m2m_db_table(self._meta)\n cursor = db.db.cursor()\n this_id = getattr(self, self._meta.pk.attname)\n if ids_to_delete:\n sql = \"DELETE FROM %s WHERE %s = %%s AND %s IN (%s)\" % \\\n (db.db.quote_name(m2m_table),\n db.db.quote_name(self._meta.object_name.lower() + '_id'),\n db.db.quote_name(rel.object_name.lower() + '_id'), ','.join(map(str, ids_to_delete)))\n cursor.execute(sql, [this_id])\n if ids_to_add:\n sql = \"INSERT INTO %s (%s, %s) VALUES (%%s, %%s)\" % \\\n (db.db.quote_name(m2m_table),\n db.db.quote_name(self._meta.object_name.lower() + '_id'),\n db.db.quote_name(rel.object_name.lower() + '_id'))\n cursor.executemany(sql, [(this_id, i) for i in ids_to_add])\n db.db.commit()\n try:\n delattr(self, '_%s_cache' % rel_field.name) # clear cache, if it exists\n except AttributeError:\n pass\n return True\n\n# Handles related-object retrieval.\n# Examples: Poll.get_choice(), Poll.get_choice_list(), Poll.get_choice_count()\ndef method_get_related(method_name, rel_mod, rel_field, self, **kwargs):\n if self._meta.has_related_links and rel_mod.Klass._meta.module_name == 'relatedlinks':\n kwargs['object_id__exact'] = getattr(self, rel_field.rel.field_name)\n else:\n kwargs['%s__%s__exact' % (rel_field.name, rel_field.rel.to.pk.name)] = getattr(self, rel_field.rel.field_name)\n kwargs.update(rel_field.rel.lookup_overrides)\n return getattr(rel_mod, method_name)(**kwargs)\n\n# Handles adding related objects.\n# Example: Poll.add_choice()\ndef method_add_related(rel_obj, rel_mod, rel_field, self, *args, **kwargs):\n init_kwargs = dict(zip([f.attname for f in rel_obj.fields if f != rel_field and not isinstance(f, AutoField)], args))\n init_kwargs.update(kwargs)\n for f in rel_obj.fields:\n if isinstance(f, AutoField):\n init_kwargs[f.attname] = None\n init_kwargs[rel_field.name] = self\n obj = rel_mod.Klass(**init_kwargs)\n obj.save()\n return obj\n\n# Handles related many-to-many object retrieval.\n# Examples: Album.get_song(), Album.get_song_list(), Album.get_song_count()\ndef method_get_related_many_to_many(method_name, opts, rel_mod, rel_field, self, **kwargs):\n kwargs['%s__%s__exact' % (rel_field.name, opts.pk.name)] = getattr(self, opts.pk.attname)\n return getattr(rel_mod, method_name)(**kwargs)\n\n# Handles setting many-to-many related objects.\n# Example: Album.set_songs()\ndef method_set_related_many_to_many(rel_opts, rel_field, self, id_list):\n id_list = map(int, id_list) # normalize to integers\n rel = rel_field.rel.to\n m2m_table = rel_field.get_m2m_db_table(rel_opts)\n this_id = getattr(self, self._meta.pk.attname)\n cursor = db.db.cursor()\n cursor.execute(\"DELETE FROM %s WHERE %s = %%s\" % \\\n (db.db.quote_name(m2m_table),\n db.db.quote_name(rel.object_name.lower() + '_id')), [this_id])\n sql = \"INSERT INTO %s (%s, %s) VALUES (%%s, %%s)\" % \\\n (db.db.quote_name(m2m_table),\n db.db.quote_name(rel.object_name.lower() + '_id'),\n db.db.quote_name(rel_opts.object_name.lower() + '_id'))\n cursor.executemany(sql, [(this_id, i) for i in id_list])\n db.db.commit()\n\n# ORDERING METHODS #########################\n\ndef method_set_order(ordered_obj, self, id_list):\n cursor = db.db.cursor()\n # Example: \"UPDATE poll_choices SET _order = %s WHERE poll_id = %s AND id = %s\"\n sql = \"UPDATE %s SET %s = %%s WHERE %s = %%s AND %s = %%s\" % \\\n (db.db.quote_name(ordered_obj.db_table), db.db.quote_name('_order'),\n db.db.quote_name(ordered_obj.order_with_respect_to.column),\n db.db.quote_name(ordered_obj.pk.column))\n rel_val = getattr(self, ordered_obj.order_with_respect_to.rel.field_name)\n cursor.executemany(sql, [(i, rel_val, j) for i, j in enumerate(id_list)])\n db.db.commit()\n\ndef method_get_order(ordered_obj, self):\n cursor = db.db.cursor()\n # Example: \"SELECT id FROM poll_choices WHERE poll_id = %s ORDER BY _order\"\n sql = \"SELECT %s FROM %s WHERE %s = %%s ORDER BY %s\" % \\\n (db.db.quote_name(ordered_obj.pk.column),\n db.db.quote_name(ordered_obj.db_table),\n db.db.quote_name(ordered_obj.order_with_respect_to.column),\n db.db.quote_name('_order'))\n rel_val = getattr(self, ordered_obj.order_with_respect_to.rel.field_name)\n cursor.execute(sql, [rel_val])\n return [r[0] for r in cursor.fetchall()]\n\n# DATE-RELATED METHODS #####################\n\ndef method_get_next_or_previous(get_object_func, opts, field, is_next, self, **kwargs):\n op = is_next and '>' or '<'\n kwargs.setdefault('where', []).append('(%s %s %%s OR (%s = %%s AND %s %s %%s))' % \\\n (db.db.quote_name(field.column), op, db.db.quote_name(field.column),\n db.db.quote_name(opts.pk.column), op))\n param = str(getattr(self, field.attname))\n kwargs.setdefault('params', []).extend([param, param, getattr(self, opts.pk.attname)])\n kwargs['order_by'] = [(not is_next and '-' or '') + field.name, (not is_next and '-' or '') + opts.pk.name]\n kwargs['limit'] = 1\n return get_object_func(**kwargs)\n\n# CHOICE-RELATED METHODS ###################\n\ndef method_get_display_value(field, self):\n value = getattr(self, field.attname)\n return dict(field.choices).get(value, value)\n\n# FILE-RELATED METHODS #####################\n\ndef method_get_file_filename(field, self):\n return os.path.join(settings.MEDIA_ROOT, getattr(self, field.attname))\n\ndef method_get_file_url(field, self):\n if getattr(self, field.attname): # value is not blank\n import urlparse\n return urlparse.urljoin(settings.MEDIA_URL, getattr(self, field.attname)).replace('\\\\', '/')\n return ''\n\ndef method_get_file_size(field, self):\n return os.path.getsize(method_get_file_filename(field, self))\n\ndef method_save_file(field, self, filename, raw_contents):\n directory = field.get_directory_name()\n try: # Create the date-based directory if it doesn't exist.\n os.makedirs(os.path.join(settings.MEDIA_ROOT, directory))\n except OSError: # Directory probably already exists.\n pass\n filename = field.get_filename(filename)\n\n # If the filename already exists, keep adding an underscore to the name of\n # the file until the filename doesn't exist.\n while os.path.exists(os.path.join(settings.MEDIA_ROOT, filename)):\n try:\n dot_index = filename.rindex('.')\n except ValueError: # filename has no dot\n filename += '_'\n else:\n filename = filename[:dot_index] + '_' + filename[dot_index:]\n\n # Write the file to disk.\n setattr(self, field.attname, filename)\n fp = open(getattr(self, 'get_%s_filename' % field.name)(), 'wb')\n fp.write(raw_contents)\n fp.close()\n\n # Save the width and/or height, if applicable.\n if isinstance(field, ImageField) and (field.width_field or field.height_field):\n from django.utils.images import get_image_dimensions\n width, height = get_image_dimensions(getattr(self, 'get_%s_filename' % field.name)())\n if field.width_field:\n setattr(self, field.width_field, width)\n if field.height_field:\n setattr(self, field.height_field, height)\n\n # Save the object, because it has changed.\n self.save()\n\n# IMAGE FIELD METHODS ######################\n\ndef method_get_image_width(field, self):\n return _get_image_dimensions(field, self)[0]\n\ndef method_get_image_height(field, self):\n return _get_image_dimensions(field, self)[1]\n\ndef _get_image_dimensions(field, self):\n cachename = \"__%s_dimensions_cache\" % field.name\n if not hasattr(self, cachename):\n from django.utils.images import get_image_dimensions\n fname = getattr(self, \"get_%s_filename\" % field.name)()\n setattr(self, cachename, get_image_dimensions(fname))\n return getattr(self, cachename)\n\n##############################################\n# HELPER FUNCTIONS (CURRIED MODEL FUNCTIONS) #\n##############################################\n\ndef get_absolute_url(opts, func, self):\n return settings.ABSOLUTE_URL_OVERRIDES.get('%s.%s' % (opts.app_label, opts.module_name), func)(self)\n\ndef _get_where_clause(lookup_type, table_prefix, field_name, value):\n if table_prefix.endswith('.'):\n table_prefix = db.db.quote_name(table_prefix[:-1])+'.'\n field_name = db.db.quote_name(field_name)\n try:\n return '%s%s %s %%s' % (table_prefix, field_name, db.OPERATOR_MAPPING[lookup_type])\n except KeyError:\n pass\n if lookup_type == 'in':\n return '%s%s IN (%s)' % (table_prefix, field_name, ','.join(['%s' for v in value]))\n elif lookup_type == 'range':\n return '%s%s BETWEEN %%s AND %%s' % (table_prefix, field_name)\n elif lookup_type in ('year', 'month', 'day'):\n return \"%s = %%s\" % db.get_date_extract_sql(lookup_type, table_prefix + field_name)\n elif lookup_type == 'isnull':\n return \"%s%s IS %sNULL\" % (table_prefix, field_name, (not value and 'NOT ' or ''))\n raise TypeError, \"Got invalid lookup_type: %s\" % repr(lookup_type)\n\ndef function_get_object(opts, klass, does_not_exist_exception, **kwargs):\n obj_list = function_get_list(opts, klass, **kwargs)\n if len(obj_list) < 1:\n raise does_not_exist_exception, \"%s does not exist for %s\" % (opts.object_name, kwargs)\n assert len(obj_list) == 1, \"get_object() returned more than one %s -- it returned %s! Lookup parameters were %s\" % (opts.object_name, len(obj_list), kwargs)\n return obj_list[0]\n\ndef _get_cached_row(opts, row, index_start):\n \"Helper function that recursively returns an object with cache filled\"\n index_end = index_start + len(opts.fields)\n obj = opts.get_model_module().Klass(*row[index_start:index_end])\n for f in opts.fields:\n if f.rel and not f.null:\n rel_obj, index_end = _get_cached_row(f.rel.to, row, index_end)\n setattr(obj, f.get_cache_name(), rel_obj)\n return obj, index_end\n\ndef function_get_iterator(opts, klass, **kwargs):\n # kwargs['select'] is a dictionary, and dictionaries' key order is\n # undefined, so we convert it to a list of tuples internally.\n kwargs['select'] = kwargs.get('select', {}).items()\n\n cursor = db.db.cursor()\n select, sql, params = function_get_sql_clause(opts, **kwargs)\n cursor.execute(\"SELECT \" + (kwargs.get('distinct') and \"DISTINCT \" or \"\") + \",\".join(select) + sql, params)\n fill_cache = kwargs.get('select_related')\n index_end = len(opts.fields)\n while 1:\n rows = cursor.fetchmany(GET_ITERATOR_CHUNK_SIZE)\n if not rows:\n raise StopIteration\n for row in rows:\n if fill_cache:\n obj, index_end = _get_cached_row(opts, row, 0)\n else:\n obj = klass(*row[:index_end])\n for i, k in enumerate(kwargs['select']):\n setattr(obj, k[0], row[index_end+i])\n yield obj\n\ndef function_get_list(opts, klass, **kwargs):\n return list(function_get_iterator(opts, klass, **kwargs))\n\ndef function_get_count(opts, **kwargs):\n kwargs['order_by'] = []\n kwargs['offset'] = None\n kwargs['limit'] = None\n kwargs['select_related'] = False\n _, sql, params = function_get_sql_clause(opts, **kwargs)\n cursor = db.db.cursor()\n cursor.execute(\"SELECT COUNT(*)\" + sql, params)\n return cursor.fetchone()[0]\n\ndef function_get_values_iterator(opts, klass, **kwargs):\n # select_related and select aren't supported in get_values().\n kwargs['select_related'] = False\n kwargs['select'] = {}\n\n # 'fields' is a list of field names to fetch.\n try:\n fields = [opts.get_field(f).column for f in kwargs.pop('fields')]\n except KeyError: # Default to all fields.\n fields = [f.column for f in opts.fields]\n\n cursor = db.db.cursor()\n _, sql, params = function_get_sql_clause(opts, **kwargs)\n select = ['%s.%s' % (db.db.quote_name(opts.db_table), db.db.quote_name(f)) for f in fields]\n cursor.execute(\"SELECT \" + (kwargs.get('distinct') and \"DISTINCT \" or \"\") + \",\".join(select) + sql, params)\n while 1:\n rows = cursor.fetchmany(GET_ITERATOR_CHUNK_SIZE)\n if not rows:\n raise StopIteration\n for row in rows:\n yield dict(zip(fields, row))\n\ndef function_get_values(opts, klass, **kwargs):\n return list(function_get_values_iterator(opts, klass, **kwargs))\n\ndef _fill_table_cache(opts, select, tables, where, old_prefix, cache_tables_seen):\n \"\"\"\n Helper function that recursively populates the select, tables and where (in\n place) for fill-cache queries.\n \"\"\"\n for f in opts.fields:\n if f.rel and not f.null:\n db_table = f.rel.to.db_table\n if db_table not in cache_tables_seen:\n tables.append(db.db.quote_name(db_table))\n else: # The table was already seen, so give it a table alias.\n new_prefix = '%s%s' % (db_table, len(cache_tables_seen))\n tables.append('%s %s' % (db.db.quote_name(db_table), db.db.quote_name(new_prefix)))\n db_table = new_prefix\n cache_tables_seen.append(db_table)\n where.append('%s.%s = %s.%s' % \\\n (db.db.quote_name(old_prefix), db.db.quote_name(f.column),\n db.db.quote_name(db_table), db.db.quote_name(f.rel.get_related_field().column)))\n select.extend(['%s.%s' % (db.db.quote_name(db_table), db.db.quote_name(f2.column)) for f2 in f.rel.to.fields])\n _fill_table_cache(f.rel.to, select, tables, where, db_table, cache_tables_seen)\n\ndef _throw_bad_kwarg_error(kwarg):\n # Helper function to remove redundancy.\n raise TypeError, \"got unexpected keyword argument '%s'\" % kwarg\n\ndef _parse_lookup(kwarg_items, opts, table_count=0):\n # Helper function that handles converting API kwargs (e.g.\n # \"name__exact\": \"tom\") to SQL.\n\n # Note that there is a distinction between where and join_where. The latter\n # is specifically a list of where clauses to use for JOINs. This\n # distinction is necessary because of support for \"_or\".\n\n # table_count is used to ensure table aliases are unique.\n tables, join_where, where, params = [], [], [], []\n for kwarg, kwarg_value in kwarg_items:\n if kwarg in ('order_by', 'limit', 'offset', 'select_related', 'distinct', 'select', 'tables', 'where', 'params'):\n continue\n if kwarg_value is None:\n continue\n if kwarg == '_or':\n for val in kwarg_value:\n tables2, join_where2, where2, params2, table_count = _parse_lookup(val, opts, table_count)\n tables.extend(tables2)\n join_where.extend(join_where2)\n where.append('(%s)' % ' OR '.join(where2))\n params.extend(params2)\n continue\n lookup_list = kwarg.split(LOOKUP_SEPARATOR)\n # pk=\"value\" is shorthand for (primary key)__exact=\"value\"\n if lookup_list[-1] == 'pk':\n if opts.pk.rel:\n lookup_list = lookup_list[:-1] + [opts.pk.name, opts.pk.rel.field_name, 'exact']\n else:\n lookup_list = lookup_list[:-1] + [opts.pk.name, 'exact']\n if len(lookup_list) == 1:\n _throw_bad_kwarg_error(kwarg)\n lookup_type = lookup_list.pop()\n current_opts = opts # We'll be overwriting this, so keep a reference to the original opts.\n current_table_alias = current_opts.db_table\n param_required = False\n while lookup_list or param_required:\n table_count += 1\n try:\n # \"current\" is a piece of the lookup list. For example, in\n # choices.get_list(poll__sites__id__exact=5), lookup_list is\n # [\"polls\", \"sites\", \"id\"], and the first current is \"polls\".\n try:\n current = lookup_list.pop(0)\n except IndexError:\n # If we're here, lookup_list is empty but param_required\n # is set to True, which means the kwarg was bad.\n # Example: choices.get_list(poll__exact='foo')\n _throw_bad_kwarg_error(kwarg)\n # Try many-to-many relationships first...\n for f in current_opts.many_to_many:\n if f.name == current:\n rel_table_alias = db.db.quote_name('t%s' % table_count)\n table_count += 1\n tables.append('%s %s' % \\\n (db.db.quote_name(f.get_m2m_db_table(current_opts)), rel_table_alias))\n join_where.append('%s.%s = %s.%s' % \\\n (db.db.quote_name(current_table_alias),\n db.db.quote_name(current_opts.pk.column),\n rel_table_alias,\n db.db.quote_name(current_opts.object_name.lower() + '_id')))\n # Optimization: In the case of primary-key lookups, we\n # don't have to do an extra join.\n if lookup_list and lookup_list[0] == f.rel.to.pk.name and lookup_type == 'exact':\n where.append(_get_where_clause(lookup_type, rel_table_alias+'.',\n f.rel.to.object_name.lower()+'_id', kwarg_value))\n params.extend(f.get_db_prep_lookup(lookup_type, kwarg_value))\n lookup_list.pop()\n param_required = False\n else:\n new_table_alias = 't%s' % table_count\n tables.append('%s %s' % (db.db.quote_name(f.rel.to.db_table),\n db.db.quote_name(new_table_alias)))\n join_where.append('%s.%s = %s.%s' % \\\n (db.db.quote_name(rel_table_alias),\n db.db.quote_name(f.rel.to.object_name.lower() + '_id'),\n db.db.quote_name(new_table_alias),\n db.db.quote_name(f.rel.to.pk.column)))\n current_table_alias = new_table_alias\n param_required = True\n current_opts = f.rel.to\n raise StopIteration\n for f in current_opts.fields:\n # Try many-to-one relationships...\n if f.rel and f.name == current:\n # Optimization: In the case of primary-key lookups, we\n # don't have to do an extra join.\n if lookup_list and lookup_list[0] == f.rel.to.pk.name and lookup_type == 'exact':\n where.append(_get_where_clause(lookup_type, current_table_alias+'.', f.column, kwarg_value))\n params.extend(f.get_db_prep_lookup(lookup_type, kwarg_value))\n lookup_list.pop()\n param_required = False\n # 'isnull' lookups in many-to-one relationships are a special case,\n # because we don't want to do a join. We just want to find out\n # whether the foreign key field is NULL.\n elif lookup_type == 'isnull' and not lookup_list:\n where.append(_get_where_clause(lookup_type, current_table_alias+'.', f.column, kwarg_value))\n params.extend(f.get_db_prep_lookup(lookup_type, kwarg_value))\n else:\n new_table_alias = 't%s' % table_count\n tables.append('%s %s' % \\\n (db.db.quote_name(f.rel.to.db_table), db.db.quote_name(new_table_alias)))\n join_where.append('%s.%s = %s.%s' % \\\n (db.db.quote_name(current_table_alias), db.db.quote_name(f.column),\n db.db.quote_name(new_table_alias), db.db.quote_name(f.rel.to.pk.column)))\n current_table_alias = new_table_alias\n param_required = True\n current_opts = f.rel.to\n raise StopIteration\n # Try direct field-name lookups...\n if f.name == current:\n where.append(_get_where_clause(lookup_type, current_table_alias+'.', f.column, kwarg_value))\n params.extend(f.get_db_prep_lookup(lookup_type, kwarg_value))\n param_required = False\n raise StopIteration\n # If we haven't hit StopIteration at this point, \"current\" must be\n # an invalid lookup, so raise an exception.\n _throw_bad_kwarg_error(kwarg)\n except StopIteration:\n continue\n return tables, join_where, where, params, table_count\n\ndef function_get_sql_clause(opts, **kwargs):\n select = [\"%s.%s\" % (db.db.quote_name(opts.db_table), db.db.quote_name(f.column)) for f in opts.fields]\n tables = [opts.db_table] + (kwargs.get('tables') and kwargs['tables'][:] or [])\n tables = [db.db.quote_name(t) for t in tables]\n where = kwargs.get('where') and kwargs['where'][:] or []\n params = kwargs.get('params') and kwargs['params'][:] or []\n\n # Convert the kwargs into SQL.\n tables2, join_where2, where2, params2, _ = _parse_lookup(kwargs.items(), opts)\n tables.extend(tables2)\n where.extend(join_where2 + where2)\n params.extend(params2)\n\n # Add any additional constraints from the \"where_constraints\" parameter.\n where.extend(opts.where_constraints)\n\n # Add additional tables and WHERE clauses based on select_related.\n if kwargs.get('select_related') is True:\n _fill_table_cache(opts, select, tables, where, opts.db_table, [opts.db_table])\n\n # Add any additional SELECTs passed in via kwargs.\n if kwargs.get('select'):\n select.extend(['(%s) AS %s' % (db.db.quote_name(s[1]), db.db.quote_name(s[0])) for s in kwargs['select']])\n\n # ORDER BY clause\n order_by = []\n for f in handle_legacy_orderlist(kwargs.get('order_by', opts.ordering)):\n if f == '?': # Special case.\n order_by.append(db.get_random_function_sql())\n else:\n if f.startswith('-'):\n col_name = f[1:]\n order = \"DESC\"\n else:\n col_name = f\n order = \"ASC\"\n if \".\" in col_name:\n table_prefix, col_name = col_name.split('.', 1)\n table_prefix = db.db.quote_name(table_prefix) + '.'\n else:\n # Use the database table as a column prefix if it wasn't given,\n # and if the requested column isn't a custom SELECT.\n if \".\" not in col_name and col_name not in [k[0] for k in kwargs.get('select', [])]:\n table_prefix = db.db.quote_name(opts.db_table) + '.'\n else:\n table_prefix = ''\n order_by.append('%s%s %s' % (table_prefix, db.db.quote_name(orderfield2column(col_name, opts)), order))\n order_by = \", \".join(order_by)\n\n # LIMIT and OFFSET clauses\n if kwargs.get('limit') is not None:\n limit_sql = \" %s \" % db.get_limit_offset_sql(kwargs['limit'], kwargs.get('offset'))\n else:\n assert kwargs.get('offset') is None, \"'offset' is not allowed without 'limit'\"\n limit_sql = \"\"\n\n return select, \" FROM \" + \",\".join(tables) + (where and \" WHERE \" + \" AND \".join(where) or \"\") + (order_by and \" ORDER BY \" + order_by or \"\") + limit_sql, params\n\ndef function_get_in_bulk(opts, klass, *args, **kwargs):\n id_list = args and args[0] or kwargs['id_list']\n assert id_list != [], \"get_in_bulk() cannot be passed an empty list.\"\n kwargs['where'] = [\"%s.%s IN (%s)\" % (db.db.quote_name(opts.db_table), db.db.quote_name(opts.pk.column), \",\".join(['%s'] * len(id_list)))]\n kwargs['params'] = id_list\n obj_list = function_get_list(opts, klass, **kwargs)\n return dict([(getattr(o, opts.pk.attname), o) for o in obj_list])\n\ndef function_get_latest(opts, klass, does_not_exist_exception, **kwargs):\n kwargs['order_by'] = ('-' + opts.get_latest_by,)\n kwargs['limit'] = 1\n return function_get_object(opts, klass, does_not_exist_exception, **kwargs)\n\ndef function_get_date_list(opts, field, *args, **kwargs):\n from django.core.db.typecasts import typecast_timestamp\n kind = args and args[0] or kwargs['kind']\n assert kind in (\"month\", \"year\", \"day\"), \"'kind' must be one of 'year', 'month' or 'day'.\"\n order = 'ASC'\n if kwargs.has_key('_order'):\n order = kwargs['_order']\n del kwargs['_order']\n assert order in ('ASC', 'DESC'), \"'order' must be either 'ASC' or 'DESC'\"\n kwargs['order_by'] = [] # Clear this because it'll mess things up otherwise.\n if field.null:\n kwargs.setdefault('where', []).append('%s.%s IS NOT NULL' % \\\n (db.db.quote_name(opts.db_table), db.db.quote_name(field.column)))\n select, sql, params = function_get_sql_clause(opts, **kwargs)\n sql = 'SELECT %s %s GROUP BY 1 ORDER BY 1' % (db.get_date_trunc_sql(kind, '%s.%s' % (db.db.quote_name(opts.db_table), db.db.quote_name(field.column))), sql)\n cursor = db.db.cursor()\n cursor.execute(sql, params)\n # We have to manually run typecast_timestamp(str()) on the results, because\n # MySQL doesn't automatically cast the result of date functions as datetime\n # objects -- MySQL returns the values as strings, instead.\n return [typecast_timestamp(str(row[0])) for row in cursor.fetchall()]\n\n###################################\n# HELPER FUNCTIONS (MANIPULATORS) #\n###################################\n\ndef get_manipulator(opts, klass, extra_methods, add=False, change=False):\n \"Returns the custom Manipulator (either add or change) for the given opts.\"\n assert (add == False or change == False) and add != change, \"get_manipulator() can be passed add=True or change=True, but not both\"\n man = types.ClassType('%sManipulator%s' % (opts.object_name, add and 'Add' or 'Change'), (formfields.Manipulator,), {})\n man.__module__ = MODEL_PREFIX + '.' + opts.module_name # Set this explicitly, as above.\n man.__init__ = curry(manipulator_init, opts, add, change)\n man.save = curry(manipulator_save, opts, klass, add, change)\n for field_name_list in opts.unique_together:\n setattr(man, 'isUnique%s' % '_'.join(field_name_list), curry(manipulator_validator_unique_together, field_name_list, opts))\n for f in opts.fields:\n if f.unique_for_date:\n setattr(man, 'isUnique%sFor%s' % (f.name, f.unique_for_date), curry(manipulator_validator_unique_for_date, f, opts.get_field(f.unique_for_date), opts, 'date'))\n if f.unique_for_month:\n setattr(man, 'isUnique%sFor%s' % (f.name, f.unique_for_month), curry(manipulator_validator_unique_for_date, f, opts.get_field(f.unique_for_month), opts, 'month'))\n if f.unique_for_year:\n setattr(man, 'isUnique%sFor%s' % (f.name, f.unique_for_year), curry(manipulator_validator_unique_for_date, f, opts.get_field(f.unique_for_year), opts, 'year'))\n for k, v in extra_methods.items():\n setattr(man, k, v)\n return man\n\ndef manipulator_init(opts, add, change, self, obj_key=None):\n if change:\n assert obj_key is not None, \"ChangeManipulator.__init__() must be passed obj_key parameter.\"\n self.obj_key = obj_key\n try:\n self.original_object = opts.get_model_module().get_object(pk=obj_key)\n except ObjectDoesNotExist:\n # If the object doesn't exist, this might be a manipulator for a\n # one-to-one related object that hasn't created its subobject yet.\n # For example, this might be a Restaurant for a Place that doesn't\n # yet have restaurant information.\n if opts.one_to_one_field:\n # Sanity check -- Make sure the \"parent\" object exists.\n # For example, make sure the Place exists for the Restaurant.\n # Let the ObjectDoesNotExist exception propogate up.\n lookup_kwargs = opts.one_to_one_field.rel.limit_choices_to\n lookup_kwargs['%s__exact' % opts.one_to_one_field.rel.field_name] = obj_key\n _ = opts.one_to_one_field.rel.to.get_model_module().get_object(**lookup_kwargs)\n params = dict([(f.attname, f.get_default()) for f in opts.fields])\n params[opts.pk.attname] = obj_key\n self.original_object = opts.get_model_module().Klass(**params)\n else:\n raise\n self.fields = []\n for f in opts.fields + opts.many_to_many:\n if f.editable and not (f.primary_key and change) and (not f.rel or not f.rel.edit_inline):\n self.fields.extend(f.get_manipulator_fields(opts, self, change))\n\n # Add fields for related objects.\n for rel_opts, rel_field in opts.get_inline_related_objects():\n if change:\n count = getattr(self.original_object, 'get_%s_count' % opts.get_rel_object_method_name(rel_opts, rel_field))()\n count += rel_field.rel.num_extra_on_change\n if rel_field.rel.min_num_in_admin:\n count = max(count, rel_field.rel.min_num_in_admin)\n if rel_field.rel.max_num_in_admin:\n count = min(count, rel_field.rel.max_num_in_admin)\n else:\n count = rel_field.rel.num_in_admin\n for f in rel_opts.fields + rel_opts.many_to_many:\n if f.editable and f != rel_field and (not f.primary_key or (f.primary_key and change)):\n for i in range(count):\n self.fields.extend(f.get_manipulator_fields(rel_opts, self, change, name_prefix='%s.%d.' % (rel_opts.object_name.lower(), i), rel=True))\n\n # Add field for ordering.\n if change and opts.get_ordered_objects():\n self.fields.append(formfields.CommaSeparatedIntegerField(field_name=\"order_\"))\n\ndef manipulator_save(opts, klass, add, change, self, new_data):\n from django.utils.datastructures import DotExpandedDict\n params = {}\n for f in opts.fields:\n # Fields with auto_now_add are another special case; they should keep\n # their original value in the change stage.\n if change and getattr(f, 'auto_now_add', False):\n params[f.attname] = getattr(self.original_object, f.attname)\n else:\n params[f.attname] = f.get_manipulator_new_data(new_data)\n\n if change:\n params[opts.pk.attname] = self.obj_key\n\n # First, save the basic object itself.\n new_object = klass(**params)\n new_object.save()\n\n # Now that the object's been saved, save any uploaded files.\n for f in opts.fields:\n if isinstance(f, FileField):\n f.save_file(new_data, new_object, change and self.original_object or None, change, rel=False)\n\n # Calculate which primary fields have changed.\n if change:\n self.fields_added, self.fields_changed, self.fields_deleted = [], [], []\n for f in opts.fields:\n if not f.primary_key and str(getattr(self.original_object, f.attname)) != str(getattr(new_object, f.attname)):\n self.fields_changed.append(f.verbose_name)\n\n # Save many-to-many objects. Example: Poll.set_sites()\n for f in opts.many_to_many:\n if not f.rel.edit_inline:\n was_changed = getattr(new_object, 'set_%s' % f.name)(new_data.getlist(f.name))\n if change and was_changed:\n self.fields_changed.append(f.verbose_name)\n\n # Save many-to-one objects. Example: Add the Choice objects for a Poll.\n for rel_opts, rel_field in opts.get_inline_related_objects():\n # Create obj_list, which is a DotExpandedDict such as this:\n # [('0', {'id': ['940'], 'choice': ['This is the first choice']}),\n # ('1', {'id': ['941'], 'choice': ['This is the second choice']}),\n # ('2', {'id': [''], 'choice': ['']})]\n obj_list = DotExpandedDict(new_data.data)[rel_opts.object_name.lower()].items()\n obj_list.sort(lambda x, y: cmp(int(x[0]), int(y[0])))\n params = {}\n\n # For each related item...\n for _, rel_new_data in obj_list:\n\n # Keep track of which core=True fields were provided.\n # If all core fields were given, the related object will be saved.\n # If none of the core fields were given, the object will be deleted.\n # If some, but not all, of the fields were given, the validator would\n # have caught that.\n all_cores_given, all_cores_blank = True, True\n\n # Get a reference to the old object. We'll use it to compare the\n # old to the new, to see which fields have changed.\n if change:\n old_rel_obj = None\n if rel_new_data[rel_opts.pk.name][0]:\n try:\n old_rel_obj = getattr(self.original_object, 'get_%s' % opts.get_rel_object_method_name(rel_opts, rel_field))(**{'%s__exact' % rel_opts.pk.name: rel_new_data[rel_opts.pk.attname][0]})\n except ObjectDoesNotExist:\n pass\n\n for f in rel_opts.fields:\n if f.core and not isinstance(f, FileField) and f.get_manipulator_new_data(rel_new_data, rel=True) in (None, ''):\n all_cores_given = False\n elif f.core and not isinstance(f, FileField) and f.get_manipulator_new_data(rel_new_data, rel=True) not in (None, ''):\n all_cores_blank = False\n # If this field isn't editable, give it the same value it had\n # previously, according to the given ID. If the ID wasn't\n # given, use a default value. FileFields are also a special\n # case, because they'll be dealt with later.\n if change and (isinstance(f, FileField) or not f.editable):\n if rel_new_data.get(rel_opts.pk.attname, False) and rel_new_data[rel_opts.pk.attname][0]:\n params[f.attname] = getattr(old_rel_obj, f.attname)\n else:\n params[f.attname] = f.get_default()\n elif f == rel_field:\n params[f.attname] = getattr(new_object, rel_field.rel.field_name)\n elif add and isinstance(f, AutoField):\n params[f.attname] = None\n else:\n params[f.attname] = f.get_manipulator_new_data(rel_new_data, rel=True)\n # Related links are a special case, because we have to\n # manually set the \"content_type_id\" and \"object_id\" fields.\n if opts.has_related_links and rel_opts.module_name == 'relatedlinks':\n contenttypes_mod = get_module('core', 'contenttypes')\n params['content_type_id'] = contenttypes_mod.get_object(package__label__exact=opts.app_label, python_module_name__exact=opts.module_name).id\n params['object_id'] = new_object.id\n\n # Create the related item.\n new_rel_obj = rel_opts.get_model_module().Klass(**params)\n\n # If all the core fields were provided (non-empty), save the item.\n if all_cores_given:\n new_rel_obj.save()\n\n # Save any uploaded files.\n for f in rel_opts.fields:\n if isinstance(f, FileField) and rel_new_data.get(f.attname, False):\n f.save_file(rel_new_data, new_rel_obj, change and old_rel_obj or None, old_rel_obj is not None, rel=True)\n\n # Calculate whether any fields have changed.\n if change:\n if not old_rel_obj: # This object didn't exist before.\n self.fields_added.append('%s \"%r\"' % (rel_opts.verbose_name, new_rel_obj))\n else:\n for f in rel_opts.fields:\n if not f.primary_key and f != rel_field and str(getattr(old_rel_obj, f.attname)) != str(getattr(new_rel_obj, f.attname)):\n self.fields_changed.append('%s for %s \"%r\"' % (f.verbose_name, rel_opts.verbose_name, new_rel_obj))\n\n # Save many-to-many objects.\n for f in rel_opts.many_to_many:\n if not f.rel.edit_inline:\n was_changed = getattr(new_rel_obj, 'set_%s' % f.name)(rel_new_data[f.attname])\n if change and was_changed:\n self.fields_changed.append('%s for %s \"%s\"' % (f.verbose_name, rel_opts.verbose_name, new_rel_obj))\n\n # If, in the change stage, all of the core fields were blank and\n # the primary key (ID) was provided, delete the item.\n if change and all_cores_blank and rel_new_data.has_key(rel_opts.pk.attname) and rel_new_data[rel_opts.pk.attname][0]:\n new_rel_obj.delete()\n self.fields_deleted.append('%s \"%r\"' % (rel_opts.verbose_name, old_rel_obj))\n\n # Save the order, if applicable.\n if change and opts.get_ordered_objects():\n order = new_data['order_'] and map(int, new_data['order_'].split(',')) or []\n for rel_opts in opts.get_ordered_objects():\n getattr(new_object, 'set_%s_order' % rel_opts.object_name.lower())(order)\n return new_object\n\ndef manipulator_validator_unique_together(field_name_list, opts, self, field_data, all_data):\n from django.utils.text import get_text_list\n field_list = [opts.get_field(field_name) for field_name in field_name_list]\n if isinstance(field_list[0].rel, ManyToOne):\n kwargs = {'%s__%s__iexact' % (field_name_list[0], field_list[0].rel.field_name): field_data}\n else:\n kwargs = {'%s__iexact' % field_name_list[0]: field_data}\n for f in field_list[1:]:\n field_val = all_data.get(f.attname, None)\n if field_val is None:\n # This will be caught by another validator, assuming the field\n # doesn't have blank=True.\n return\n if isinstance(f.rel, ManyToOne):\n kwargs['%s__pk' % f.name] = field_val\n else:\n kwargs['%s__iexact' % f.name] = field_val\n mod = opts.get_model_module()\n try:\n old_obj = mod.get_object(**kwargs)\n except ObjectDoesNotExist:\n return\n if hasattr(self, 'original_object') and getattr(self.original_object, opts.pk.attname) == getattr(old_obj, opts.pk.attname):\n pass\n else:\n raise validators.ValidationError, \"%s with this %s already exists for the given %s.\" % \\\n (capfirst(opts.verbose_name), field_list[0].verbose_name, get_text_list(field_name_list[1:], 'and'))\n\ndef manipulator_validator_unique_for_date(from_field, date_field, opts, lookup_type, self, field_data, all_data):\n date_str = all_data.get(date_field.get_manipulator_field_names('')[0], None)\n mod = opts.get_model_module()\n date_val = formfields.DateField.html2python(date_str)\n if date_val is None:\n return # Date was invalid. This will be caught by another validator.\n lookup_kwargs = {'%s__year' % date_field.name: date_val.year}\n if isinstance(from_field.rel, ManyToOne):\n lookup_kwargs['%s__pk' % from_field.name] = field_data\n else:\n lookup_kwargs['%s__iexact' % from_field.name] = field_data\n if lookup_type in ('month', 'date'):\n lookup_kwargs['%s__month' % date_field.name] = date_val.month\n if lookup_type == 'date':\n lookup_kwargs['%s__day' % date_field.name] = date_val.day\n try:\n old_obj = mod.get_object(**lookup_kwargs)\n except ObjectDoesNotExist:\n return\n else:\n if hasattr(self, 'original_object') and getattr(self.original_object, opts.pk.attname) == getattr(old_obj, opts.pk.attname):\n pass\n else:\n format_string = (lookup_type == 'date') and '%B %d, %Y' or '%B %Y'\n raise validators.ValidationError, \"Please enter a different %s. The one you entered is already being used for %s.\" % \\\n (from_field.verbose_name, date_val.strftime(format_string))\n", "django/core/meta/fields.py": "from django.conf import settings\nfrom django.core import formfields, validators\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.utils.functional import curry, lazy\nfrom django.utils.text import capfirst\nfrom django.utils.translation import gettext_lazy\nimport datetime, os\n\n# Random entropy string used by \"default\" param.\nNOT_PROVIDED = 'oijpwojefiojpanv'\n\n# Values for filter_interface.\nHORIZONTAL, VERTICAL = 1, 2\n\n# The values to use for \"blank\" in SelectFields. Will be appended to the start of most \"choices\" lists.\nBLANK_CHOICE_DASH = [(\"\", \"---------\")]\nBLANK_CHOICE_NONE = [(\"\", \"None\")]\n\n# Values for Relation.edit_inline.\nTABULAR, STACKED = 1, 2\n\nRECURSIVE_RELATIONSHIP_CONSTANT = 'self'\n\n# prepares a value for use in a LIKE query\nprep_for_like_query = lambda x: str(x).replace(\"%\", \"\\%\").replace(\"_\", \"\\_\")\n\n# returns the
    class for a given radio_admin value\nget_ul_class = lambda x: 'radiolist%s' % ((x == HORIZONTAL) and ' inline' or '')\n\ndef string_concat(*strings):\n \"\"\"\"\n lazy variant of string concatenation, needed for translations that are\n constructed from multiple parts. Handles lazy strings and non-strings by\n first turning all arguments to strings, before joining them.\n \"\"\"\n return ''.join([str(el) for el in strings])\n\nstring_concat = lazy(string_concat, str)\n\ndef manipulator_valid_rel_key(f, self, field_data, all_data):\n \"Validates that the value is a valid foreign key\"\n mod = f.rel.to.get_model_module()\n try:\n mod.get_object(pk=field_data)\n except ObjectDoesNotExist:\n raise validators.ValidationError, \"Please enter a valid %s.\" % f.verbose_name\n\ndef manipulator_validator_unique(f, opts, self, field_data, all_data):\n \"Validates that the value is unique for this field.\"\n if f.rel and isinstance(f.rel, ManyToOne):\n lookup_type = 'pk'\n else:\n lookup_type = 'exact'\n try:\n old_obj = opts.get_model_module().get_object(**{'%s__%s' % (f.name, lookup_type): field_data})\n except ObjectDoesNotExist:\n return\n if hasattr(self, 'original_object') and getattr(self.original_object, opts.pk.attname) == getattr(old_obj, opts.pk.attname):\n return\n raise validators.ValidationError, \"%s with this %s already exists.\" % (capfirst(opts.verbose_name), f.verbose_name)\n\n\n# A guide to Field parameters:\n#\n# * name: The name of the field specifed in the model.\n# * attname: The attribute to use on the model object. This is the same as\n# \"name\", except in the case of ForeignKeys, where \"_id\" is\n# appended.\n# * db_column: The db_column specified in the model (or None).\n# * column: The database column for this field. This is the same as\n# \"attname\", except if db_column is specified.\n#\n# Code that introspects values, or does other dynamic things, should use\n# attname. For example, this gets the primary key value of object \"obj\":\n#\n# getattr(obj, opts.pk.attname)\n\nclass Field(object):\n\n # Designates whether empty strings fundamentally are allowed at the\n # database level.\n empty_strings_allowed = True\n\n # Tracks each time a Field instance is created. Used to retain order.\n creation_counter = 0\n\n def __init__(self, verbose_name=None, name=None, primary_key=False,\n maxlength=None, unique=False, blank=False, null=False, db_index=None,\n core=False, rel=None, default=NOT_PROVIDED, editable=True,\n prepopulate_from=None, unique_for_date=None, unique_for_month=None,\n unique_for_year=None, validator_list=None, choices=None, radio_admin=None,\n help_text='', db_column=None):\n self.name = name\n self.verbose_name = verbose_name or (name and name.replace('_', ' '))\n self.primary_key = primary_key\n self.maxlength, self.unique = maxlength, unique\n self.blank, self.null = blank, null\n self.core, self.rel, self.default = core, rel, default\n self.editable = editable\n self.validator_list = validator_list or []\n self.prepopulate_from = prepopulate_from\n self.unique_for_date, self.unique_for_month = unique_for_date, unique_for_month\n self.unique_for_year = unique_for_year\n self.choices = choices or []\n self.radio_admin = radio_admin\n self.help_text = help_text\n self.db_column = db_column\n if rel and isinstance(rel, ManyToMany):\n if rel.raw_id_admin:\n self.help_text = string_concat(self.help_text,\n gettext_lazy(' Separate multiple IDs with commas.'))\n else:\n self.help_text = string_concat(self.help_text,\n gettext_lazy(' Hold down \"Control\", or \"Command\" on a Mac, to select more than one.'))\n\n # Set db_index to True if the field has a relationship and doesn't explicitly set db_index.\n if db_index is None:\n if isinstance(rel, OneToOne) or isinstance(rel, ManyToOne):\n self.db_index = True\n else:\n self.db_index = False\n else:\n self.db_index = db_index\n\n # Increase the creation counter, and save our local copy.\n self.creation_counter = Field.creation_counter\n Field.creation_counter += 1\n\n self.attname, self.column = self.get_attname_column()\n\n def set_name(self, name):\n self.name = name\n self.verbose_name = self.verbose_name or name.replace('_', ' ')\n self.attname, self.column = self.get_attname_column()\n\n def get_attname_column(self):\n if isinstance(self.rel, ManyToOne):\n attname = '%s_id' % self.name\n else:\n attname = self.name\n column = self.db_column or attname\n return attname, column\n\n def get_cache_name(self):\n return '_%s_cache' % self.name\n\n def get_internal_type(self):\n return self.__class__.__name__\n\n def pre_save(self, value, add):\n \"Returns field's value just before saving.\"\n return value\n\n def get_db_prep_save(self, value):\n \"Returns field's value prepared for saving into a database.\"\n return value\n\n def get_db_prep_lookup(self, lookup_type, value):\n \"Returns field's value prepared for database lookup.\"\n if lookup_type in ('exact', 'gt', 'gte', 'lt', 'lte', 'ne', 'year', 'month', 'day'):\n return [value]\n elif lookup_type in ('range', 'in'):\n return value\n elif lookup_type in ('contains', 'icontains'):\n return [\"%%%s%%\" % prep_for_like_query(value)]\n elif lookup_type == 'iexact':\n return [prep_for_like_query(value)]\n elif lookup_type in ('startswith', 'istartswith'):\n return [\"%s%%\" % prep_for_like_query(value)]\n elif lookup_type in ('endswith', 'iendswith'):\n return [\"%%%s\" % prep_for_like_query(value)]\n elif lookup_type == 'isnull':\n return []\n raise TypeError, \"Field has invalid lookup: %s\" % lookup_type\n\n def has_default(self):\n \"Returns a boolean of whether this field has a default value.\"\n return self.default != NOT_PROVIDED\n\n def get_default(self):\n \"Returns the default value for this field.\"\n if self.default != NOT_PROVIDED:\n if hasattr(self.default, '__get_value__'):\n return self.default.__get_value__()\n return self.default\n if self.null:\n return None\n return \"\"\n\n def get_manipulator_field_names(self, name_prefix):\n \"\"\"\n Returns a list of field names that this object adds to the manipulator.\n \"\"\"\n return [name_prefix + self.name]\n\n def get_manipulator_fields(self, opts, manipulator, change, name_prefix='', rel=False):\n \"\"\"\n Returns a list of formfields.FormField instances for this field. It\n calculates the choices at runtime, not at compile time.\n\n name_prefix is a prefix to prepend to the \"field_name\" argument.\n rel is a boolean specifying whether this field is in a related context.\n \"\"\"\n params = {'validator_list': self.validator_list[:]}\n if self.maxlength and not self.choices: # Don't give SelectFields a maxlength parameter.\n params['maxlength'] = self.maxlength\n if isinstance(self.rel, ManyToOne):\n if self.rel.raw_id_admin:\n field_objs = self.get_manipulator_field_objs()\n params['validator_list'].append(curry(manipulator_valid_rel_key, self, manipulator))\n else:\n if self.radio_admin:\n field_objs = [formfields.RadioSelectField]\n params['choices'] = self.get_choices(include_blank=self.blank, blank_choice=BLANK_CHOICE_NONE)\n params['ul_class'] = get_ul_class(self.radio_admin)\n else:\n if self.null:\n field_objs = [formfields.NullSelectField]\n else:\n field_objs = [formfields.SelectField]\n params['choices'] = self.get_choices()\n elif self.choices:\n if self.radio_admin:\n field_objs = [formfields.RadioSelectField]\n params['choices'] = self.get_choices(include_blank=self.blank, blank_choice=BLANK_CHOICE_NONE)\n params['ul_class'] = get_ul_class(self.radio_admin)\n else:\n field_objs = [formfields.SelectField]\n params['choices'] = self.get_choices()\n else:\n field_objs = self.get_manipulator_field_objs()\n\n # Add the \"unique\" validator(s).\n for field_name_list in opts.unique_together:\n if field_name_list[0] == self.name:\n params['validator_list'].append(getattr(manipulator, 'isUnique%s' % '_'.join(field_name_list)))\n\n # Add the \"unique for...\" validator(s).\n if self.unique_for_date:\n params['validator_list'].append(getattr(manipulator, 'isUnique%sFor%s' % (self.name, self.unique_for_date)))\n if self.unique_for_month:\n params['validator_list'].append(getattr(manipulator, 'isUnique%sFor%s' % (self.name, self.unique_for_month)))\n if self.unique_for_year:\n params['validator_list'].append(getattr(manipulator, 'isUnique%sFor%s' % (self.name, self.unique_for_year)))\n if self.unique or (self.primary_key and not rel):\n params['validator_list'].append(curry(manipulator_validator_unique, self, opts, manipulator))\n\n # Only add is_required=True if the field cannot be blank. Primary keys\n # are a special case, and fields in a related context should set this\n # as False, because they'll be caught by a separate validator --\n # RequiredIfOtherFieldGiven.\n params['is_required'] = not self.blank and not self.primary_key and not rel\n\n # If this field is in a related context, check whether any other fields\n # in the related object have core=True. If so, add a validator --\n # RequiredIfOtherFieldsGiven -- to this FormField.\n if rel and not self.blank and not isinstance(self, AutoField) and not isinstance(self, FileField):\n # First, get the core fields, if any.\n core_field_names = []\n for f in opts.fields:\n if f.core and f != self:\n core_field_names.extend(f.get_manipulator_field_names(name_prefix))\n # Now, if there are any, add the validator to this FormField.\n if core_field_names:\n params['validator_list'].append(validators.RequiredIfOtherFieldsGiven(core_field_names, \"This field is required.\"))\n\n # BooleanFields (CheckboxFields) are a special case. They don't take\n # is_required or validator_list.\n if isinstance(self, BooleanField):\n del params['validator_list'], params['is_required']\n\n # Finally, add the field_names.\n field_names = self.get_manipulator_field_names(name_prefix)\n return [man(field_name=field_names[i], **params) for i, man in enumerate(field_objs)]\n\n def get_manipulator_new_data(self, new_data, rel=False):\n \"\"\"\n Given the full new_data dictionary (from the manipulator), returns this\n field's data.\n \"\"\"\n if rel:\n return new_data.get(self.name, [self.get_default()])[0]\n else:\n val = new_data.get(self.name, self.get_default())\n if not self.empty_strings_allowed and val == '' and self.null:\n val = None\n return val\n\n def get_choices(self, include_blank=True, blank_choice=BLANK_CHOICE_DASH):\n \"Returns a list of tuples used as SelectField choices for this field.\"\n first_choice = include_blank and blank_choice or []\n if self.choices:\n return first_choice + list(self.choices)\n rel_obj = self.rel.to\n return first_choice + [(getattr(x, rel_obj.pk.attname), repr(x)) for x in rel_obj.get_model_module().get_list(**self.rel.limit_choices_to)]\n\nclass AutoField(Field):\n empty_strings_allowed = False\n def __init__(self, *args, **kwargs):\n assert kwargs.get('primary_key', False) is True, \"%ss must have primary_key=True.\" % self.__class__.__name__\n Field.__init__(self, *args, **kwargs)\n\n def get_manipulator_fields(self, opts, manipulator, change, name_prefix='', rel=False):\n if not rel:\n return [] # Don't add a FormField unless it's in a related context.\n return Field.get_manipulator_fields(self, opts, manipulator, change, name_prefix, rel)\n\n def get_manipulator_field_objs(self):\n return [formfields.HiddenField]\n\n def get_manipulator_new_data(self, new_data, rel=False):\n if not rel:\n return None\n return Field.get_manipulator_new_data(self, new_data, rel)\n\nclass BooleanField(Field):\n def __init__(self, *args, **kwargs):\n kwargs['blank'] = True\n Field.__init__(self, *args, **kwargs)\n\n def get_manipulator_field_objs(self):\n return [formfields.CheckboxField]\n\nclass CharField(Field):\n def get_manipulator_field_objs(self):\n return [formfields.TextField]\n\nclass CommaSeparatedIntegerField(CharField):\n def get_manipulator_field_objs(self):\n return [formfields.CommaSeparatedIntegerField]\n\nclass DateField(Field):\n empty_strings_allowed = False\n def __init__(self, verbose_name=None, name=None, auto_now=False, auto_now_add=False, **kwargs):\n self.auto_now, self.auto_now_add = auto_now, auto_now_add\n if auto_now or auto_now_add:\n kwargs['editable'] = False\n Field.__init__(self, verbose_name, name, **kwargs)\n\n def get_db_prep_lookup(self, lookup_type, value):\n if lookup_type == 'range':\n value = [str(v) for v in value]\n else:\n value = str(value)\n return Field.get_db_prep_lookup(self, lookup_type, value)\n\n def pre_save(self, value, add):\n if self.auto_now or (self.auto_now_add and add):\n return datetime.datetime.now()\n return value\n\n def get_db_prep_save(self, value):\n # Casts dates into string format for entry into database.\n if value is not None:\n value = value.strftime('%Y-%m-%d')\n return Field.get_db_prep_save(self, value)\n\n def get_manipulator_field_objs(self):\n return [formfields.DateField]\n\nclass DateTimeField(DateField):\n def get_db_prep_save(self, value):\n # Casts dates into string format for entry into database.\n if value is not None:\n # MySQL will throw a warning if microseconds are given, because it\n # doesn't support microseconds.\n if settings.DATABASE_ENGINE == 'mysql':\n value = value.replace(microsecond=0)\n value = str(value)\n return Field.get_db_prep_save(self, value)\n\n def get_manipulator_field_objs(self):\n return [formfields.DateField, formfields.TimeField]\n\n def get_manipulator_field_names(self, name_prefix):\n return [name_prefix + self.name + '_date', name_prefix + self.name + '_time']\n\n def get_manipulator_new_data(self, new_data, rel=False):\n date_field, time_field = self.get_manipulator_field_names('')\n if rel:\n d = new_data.get(date_field, [None])[0]\n t = new_data.get(time_field, [None])[0]\n else:\n d = new_data.get(date_field, None)\n t = new_data.get(time_field, None)\n if d is not None and t is not None:\n return datetime.datetime.combine(d, t)\n return self.get_default()\n\nclass EmailField(Field):\n def get_manipulator_field_objs(self):\n return [formfields.EmailField]\n\nclass FileField(Field):\n def __init__(self, verbose_name=None, name=None, upload_to='', **kwargs):\n self.upload_to = upload_to\n Field.__init__(self, verbose_name, name, **kwargs)\n\n def get_manipulator_fields(self, opts, manipulator, change, name_prefix='', rel=False):\n field_list = Field.get_manipulator_fields(self, opts, manipulator, change, name_prefix, rel)\n\n if not self.blank:\n if rel:\n # This validator makes sure FileFields work in a related context.\n class RequiredFileField:\n def __init__(self, other_field_names, other_file_field_name):\n self.other_field_names = other_field_names\n self.other_file_field_name = other_file_field_name\n self.always_test = True\n def __call__(self, field_data, all_data):\n if not all_data.get(self.other_file_field_name, False):\n c = validators.RequiredIfOtherFieldsGiven(self.other_field_names, \"This field is required.\")\n c(field_data, all_data)\n # First, get the core fields, if any.\n core_field_names = []\n for f in opts.fields:\n if f.core and f != self:\n core_field_names.extend(f.get_manipulator_field_names(name_prefix))\n # Now, if there are any, add the validator to this FormField.\n if core_field_names:\n field_list[0].validator_list.append(RequiredFileField(core_field_names, field_list[1].field_name))\n else:\n v = validators.RequiredIfOtherFieldNotGiven(field_list[1].field_name, \"This field is required.\")\n v.always_test = True\n field_list[0].validator_list.append(v)\n field_list[0].is_required = field_list[1].is_required = False\n\n # If the raw path is passed in, validate it's under the MEDIA_ROOT.\n def isWithinMediaRoot(field_data, all_data):\n f = os.path.abspath(os.path.join(settings.MEDIA_ROOT, field_data))\n if not f.startswith(os.path.normpath(settings.MEDIA_ROOT)):\n raise validators.ValidationError, \"Enter a valid filename.\"\n field_list[1].validator_list.append(isWithinMediaRoot)\n return field_list\n\n def get_manipulator_field_objs(self):\n return [formfields.FileUploadField, formfields.HiddenField]\n\n def get_manipulator_field_names(self, name_prefix):\n return [name_prefix + self.name + '_file', name_prefix + self.name]\n\n def save_file(self, new_data, new_object, original_object, change, rel):\n upload_field_name = self.get_manipulator_field_names('')[0]\n if new_data.get(upload_field_name, False):\n if rel:\n getattr(new_object, 'save_%s_file' % self.name)(new_data[upload_field_name][0][\"filename\"], new_data[upload_field_name][0][\"content\"])\n else:\n getattr(new_object, 'save_%s_file' % self.name)(new_data[upload_field_name][\"filename\"], new_data[upload_field_name][\"content\"])\n\n def get_directory_name(self):\n return os.path.normpath(datetime.datetime.now().strftime(self.upload_to))\n\n def get_filename(self, filename):\n from django.utils.text import get_valid_filename\n f = os.path.join(self.get_directory_name(), get_valid_filename(os.path.basename(filename)))\n return os.path.normpath(f)\n\nclass FilePathField(Field):\n def __init__(self, verbose_name=None, name=None, path='', match=None, recursive=False, **kwargs):\n self.path, self.match, self.recursive = path, match, recursive\n Field.__init__(self, verbose_name, name, **kwargs)\n\n def get_manipulator_field_objs(self):\n return [curry(formfields.FilePathField, path=self.path, match=self.match, recursive=self.recursive)]\n\nclass FloatField(Field):\n empty_strings_allowed = False\n def __init__(self, verbose_name=None, name=None, max_digits=None, decimal_places=None, **kwargs):\n self.max_digits, self.decimal_places = max_digits, decimal_places\n Field.__init__(self, verbose_name, name, **kwargs)\n\n def get_manipulator_field_objs(self):\n return [curry(formfields.FloatField, max_digits=self.max_digits, decimal_places=self.decimal_places)]\n\nclass ImageField(FileField):\n def __init__(self, verbose_name=None, name=None, width_field=None, height_field=None, **kwargs):\n self.width_field, self.height_field = width_field, height_field\n FileField.__init__(self, verbose_name, name, **kwargs)\n\n def get_manipulator_field_objs(self):\n return [formfields.ImageUploadField, formfields.HiddenField]\n\n def save_file(self, new_data, new_object, original_object, change, rel):\n FileField.save_file(self, new_data, new_object, original_object, change, rel)\n # If the image has height and/or width field(s) and they haven't\n # changed, set the width and/or height field(s) back to their original\n # values.\n if change and (self.width_field or self.height_field):\n if self.width_field:\n setattr(new_object, self.width_field, getattr(original_object, self.width_field))\n if self.height_field:\n setattr(new_object, self.height_field, getattr(original_object, self.height_field))\n new_object.save()\n\nclass IntegerField(Field):\n empty_strings_allowed = False\n def get_manipulator_field_objs(self):\n return [formfields.IntegerField]\n\nclass IPAddressField(Field):\n def __init__(self, *args, **kwargs):\n kwargs['maxlength'] = 15\n Field.__init__(self, *args, **kwargs)\n\n def get_manipulator_field_objs(self):\n return [formfields.IPAddressField]\n\nclass NullBooleanField(Field):\n def __init__(self, *args, **kwargs):\n kwargs['null'] = True\n Field.__init__(self, *args, **kwargs)\n\n def get_manipulator_field_objs(self):\n return [formfields.NullBooleanField]\n\nclass PhoneNumberField(IntegerField):\n def get_manipulator_field_objs(self):\n return [formfields.PhoneNumberField]\n\nclass PositiveIntegerField(IntegerField):\n def get_manipulator_field_objs(self):\n return [formfields.PositiveIntegerField]\n\nclass PositiveSmallIntegerField(IntegerField):\n def get_manipulator_field_objs(self):\n return [formfields.PositiveSmallIntegerField]\n\nclass SlugField(Field):\n def __init__(self, *args, **kwargs):\n kwargs['maxlength'] = 50\n kwargs.setdefault('validator_list', []).append(validators.isSlug)\n # Set db_index=True unless it's been set manually.\n if not kwargs.has_key('db_index'):\n kwargs['db_index'] = True\n Field.__init__(self, *args, **kwargs)\n\n def get_manipulator_field_objs(self):\n return [formfields.TextField]\n\nclass SmallIntegerField(IntegerField):\n def get_manipulator_field_objs(self):\n return [formfields.SmallIntegerField]\n\nclass TextField(Field):\n def get_manipulator_field_objs(self):\n return [formfields.LargeTextField]\n\nclass TimeField(Field):\n empty_strings_allowed = False\n def __init__(self, verbose_name=None, name=None, auto_now=False, auto_now_add=False, **kwargs):\n self.auto_now, self.auto_now_add = auto_now, auto_now_add\n if auto_now or auto_now_add:\n kwargs['editable'] = False\n Field.__init__(self, verbose_name, name, **kwargs)\n\n def get_db_prep_lookup(self, lookup_type, value):\n if lookup_type == 'range':\n value = [str(v) for v in value]\n else:\n value = str(value)\n return Field.get_db_prep_lookup(self, lookup_type, value)\n\n def pre_save(self, value, add):\n if self.auto_now or (self.auto_now_add and add):\n return datetime.datetime.now().time()\n return value\n\n def get_db_prep_save(self, value):\n # Casts dates into string format for entry into database.\n if value is not None:\n # MySQL will throw a warning if microseconds are given, because it\n # doesn't support microseconds.\n if settings.DATABASE_ENGINE == 'mysql':\n value = value.replace(microsecond=0)\n value = str(value)\n return Field.get_db_prep_save(self, value)\n\n def get_manipulator_field_objs(self):\n return [formfields.TimeField]\n\nclass URLField(Field):\n def __init__(self, verbose_name=None, name=None, verify_exists=True, **kwargs):\n if verify_exists:\n kwargs.setdefault('validator_list', []).append(validators.isExistingURL)\n Field.__init__(self, verbose_name, name, **kwargs)\n\n def get_manipulator_field_objs(self):\n return [formfields.URLField]\n\nclass USStateField(Field):\n def get_manipulator_field_objs(self):\n return [formfields.USStateField]\n\nclass XMLField(TextField):\n def __init__(self, verbose_name=None, name=None, schema_path=None, **kwargs):\n self.schema_path = schema_path\n Field.__init__(self, verbose_name, name, **kwargs)\n\n def get_internal_type(self):\n return \"TextField\"\n\n def get_manipulator_field_objs(self):\n return [curry(formfields.XMLLargeTextField, schema_path=self.schema_path)]\n\nclass ForeignKey(Field):\n empty_strings_allowed = False\n def __init__(self, to, to_field=None, **kwargs):\n try:\n to_name = to._meta.object_name.lower()\n except AttributeError: # to._meta doesn't exist, so it must be RECURSIVE_RELATIONSHIP_CONSTANT\n assert to == 'self', \"ForeignKey(%r) is invalid. First parameter to ForeignKey must be either a model or the string %r\" % (to, RECURSIVE_RELATIONSHIP_CONSTANT)\n kwargs['verbose_name'] = kwargs.get('verbose_name', '')\n else:\n to_field = to_field or to._meta.pk.name\n kwargs['verbose_name'] = kwargs.get('verbose_name', to._meta.verbose_name)\n\n if kwargs.has_key('edit_inline_type'):\n import warnings\n warnings.warn(\"edit_inline_type is deprecated. Use edit_inline instead.\")\n kwargs['edit_inline'] = kwargs.pop('edit_inline_type')\n\n kwargs['rel'] = ManyToOne(to, to_field,\n num_in_admin=kwargs.pop('num_in_admin', 3),\n min_num_in_admin=kwargs.pop('min_num_in_admin', None),\n max_num_in_admin=kwargs.pop('max_num_in_admin', None),\n num_extra_on_change=kwargs.pop('num_extra_on_change', 1),\n edit_inline=kwargs.pop('edit_inline', False),\n related_name=kwargs.pop('related_name', None),\n limit_choices_to=kwargs.pop('limit_choices_to', None),\n lookup_overrides=kwargs.pop('lookup_overrides', None),\n raw_id_admin=kwargs.pop('raw_id_admin', False))\n Field.__init__(self, **kwargs)\n\n def get_manipulator_field_objs(self):\n rel_field = self.rel.get_related_field()\n if self.rel.raw_id_admin and not isinstance(rel_field, AutoField):\n return rel_field.get_manipulator_field_objs()\n else:\n return [formfields.IntegerField]\n\nclass ManyToManyField(Field):\n def __init__(self, to, **kwargs):\n kwargs['verbose_name'] = kwargs.get('verbose_name', to._meta.verbose_name_plural)\n kwargs['rel'] = ManyToMany(to, kwargs.pop('singular', None),\n num_in_admin=kwargs.pop('num_in_admin', 0),\n related_name=kwargs.pop('related_name', None),\n filter_interface=kwargs.pop('filter_interface', None),\n limit_choices_to=kwargs.pop('limit_choices_to', None),\n raw_id_admin=kwargs.pop('raw_id_admin', False))\n if kwargs[\"rel\"].raw_id_admin:\n kwargs.setdefault(\"validator_list\", []).append(self.isValidIDList)\n Field.__init__(self, **kwargs)\n\n def get_manipulator_field_objs(self):\n if self.rel.raw_id_admin:\n return [formfields.CommaSeparatedIntegerField]\n else:\n choices = self.get_choices(include_blank=False)\n return [curry(formfields.SelectMultipleField, size=min(max(len(choices), 5), 15), choices=choices)]\n\n def get_m2m_db_table(self, original_opts):\n \"Returns the name of the many-to-many 'join' table.\"\n return '%s_%s' % (original_opts.db_table, self.name)\n\n def isValidIDList(self, field_data, all_data):\n \"Validates that the value is a valid list of foreign keys\"\n mod = self.rel.to.get_model_module()\n try:\n pks = map(int, field_data.split(','))\n except ValueError:\n # the CommaSeparatedIntegerField validator will catch this error\n return\n objects = mod.get_in_bulk(pks)\n if len(objects) != len(pks):\n badkeys = [k for k in pks if k not in objects]\n raise validators.ValidationError, \"Please enter valid %s IDs. The value%s %r %s invalid.\" % \\\n (self.verbose_name, len(badkeys) > 1 and 's' or '',\n len(badkeys) == 1 and badkeys[0] or tuple(badkeys),\n len(badkeys) == 1 and \"is\" or \"are\")\n\nclass OneToOneField(IntegerField):\n def __init__(self, to, to_field=None, **kwargs):\n kwargs['verbose_name'] = kwargs.get('verbose_name', 'ID')\n to_field = to_field or to._meta.pk.name\n\n if kwargs.has_key('edit_inline_type'):\n import warnings\n warnings.warn(\"edit_inline_type is deprecated. Use edit_inline instead.\")\n kwargs['edit_inline'] = kwargs.pop('edit_inline_type')\n\n kwargs['rel'] = OneToOne(to, to_field,\n num_in_admin=kwargs.pop('num_in_admin', 0),\n edit_inline=kwargs.pop('edit_inline', False),\n related_name=kwargs.pop('related_name', None),\n limit_choices_to=kwargs.pop('limit_choices_to', None),\n lookup_overrides=kwargs.pop('lookup_overrides', None),\n raw_id_admin=kwargs.pop('raw_id_admin', False))\n kwargs['primary_key'] = True\n IntegerField.__init__(self, **kwargs)\n\nclass ManyToOne:\n def __init__(self, to, field_name, num_in_admin=3, min_num_in_admin=None,\n max_num_in_admin=None, num_extra_on_change=1, edit_inline=False,\n related_name=None, limit_choices_to=None, lookup_overrides=None, raw_id_admin=False):\n try:\n self.to = to._meta\n except AttributeError: # to._meta doesn't exist, so it must be RECURSIVE_RELATIONSHIP_CONSTANT\n assert to == RECURSIVE_RELATIONSHIP_CONSTANT, \"'to' must be either a model or the string '%s'\" % RECURSIVE_RELATIONSHIP_CONSTANT\n self.to = to\n self.field_name = field_name\n self.num_in_admin, self.edit_inline = num_in_admin, edit_inline\n self.min_num_in_admin, self.max_num_in_admin = min_num_in_admin, max_num_in_admin\n self.num_extra_on_change, self.related_name = num_extra_on_change, related_name\n self.limit_choices_to = limit_choices_to or {}\n self.lookup_overrides = lookup_overrides or {}\n self.raw_id_admin = raw_id_admin\n\n def get_related_field(self):\n \"Returns the Field in the 'to' object to which this relationship is tied.\"\n return self.to.get_field(self.field_name)\n\nclass ManyToMany:\n def __init__(self, to, singular=None, num_in_admin=0, related_name=None,\n filter_interface=None, limit_choices_to=None, raw_id_admin=False):\n self.to = to._meta\n self.singular = singular or to._meta.object_name.lower()\n self.num_in_admin = num_in_admin\n self.related_name = related_name\n self.filter_interface = filter_interface\n self.limit_choices_to = limit_choices_to or {}\n self.edit_inline = False\n self.raw_id_admin = raw_id_admin\n assert not (self.raw_id_admin and self.filter_interface), \"ManyToMany relationships may not use both raw_id_admin and filter_interface\"\n\nclass OneToOne(ManyToOne):\n def __init__(self, to, field_name, num_in_admin=0, edit_inline=False,\n related_name=None, limit_choices_to=None, lookup_overrides=None,\n raw_id_admin=False):\n self.to, self.field_name = to._meta, field_name\n self.num_in_admin, self.edit_inline = num_in_admin, edit_inline\n self.related_name = related_name\n self.limit_choices_to = limit_choices_to or {}\n self.lookup_overrides = lookup_overrides or {}\n self.raw_id_admin = raw_id_admin\n\nclass Admin:\n def __init__(self, fields=None, js=None, list_display=None, list_filter=None, date_hierarchy=None,\n save_as=False, ordering=None, search_fields=None, save_on_top=False, list_select_related=False):\n self.fields = fields\n self.js = js or []\n self.list_display = list_display or ['__repr__']\n self.list_filter = list_filter or []\n self.date_hierarchy = date_hierarchy\n self.save_as, self.ordering = save_as, ordering\n self.search_fields = search_fields or []\n self.save_on_top = save_on_top\n self.list_select_related = list_select_related\n\n def get_field_objs(self, opts):\n \"\"\"\n Returns self.fields, except with fields as Field objects instead of\n field names. If self.fields is None, defaults to putting every\n non-AutoField field with editable=True in a single fieldset.\n \"\"\"\n if self.fields is None:\n field_struct = ((None, {'fields': [f.name for f in opts.fields + opts.many_to_many if f.editable and not isinstance(f, AutoField)]}),)\n else:\n field_struct = self.fields\n new_fieldset_list = []\n for fieldset in field_struct:\n new_fieldset = [fieldset[0], {}]\n new_fieldset[1].update(fieldset[1])\n admin_fields = []\n for field_name_or_list in fieldset[1]['fields']:\n if isinstance(field_name_or_list, basestring):\n admin_fields.append([opts.get_field(field_name_or_list)])\n else:\n admin_fields.append([opts.get_field(field_name) for field_name in field_name_or_list])\n new_fieldset[1]['fields'] = admin_fields\n new_fieldset_list.append(new_fieldset)\n return new_fieldset_list\n"}} -{"repo": "qos-ch/cal10n", "pr_number": 6, "title": "Verify Ant Task...Take Two", "state": "closed", "merged_at": "2013-04-25T22:52:34Z", "additions": 527, "deletions": 0, "files_changed": ["cal10n-ant-task/src/main/java/ch/qos/cal10n/ant/EnumTypesElement.java", "cal10n-ant-task/src/main/java/ch/qos/cal10n/ant/StringElement.java", "cal10n-ant-task/src/main/java/ch/qos/cal10n/ant/VerifyTask.java", "cal10n-ant-task/src/test/java/ch/qos/cal10n/ant/VerifyTaskTest.java", "cal10n-ant-task/src/test/java/ch/qos/cal10n/ant/testdata/Colors.java", "cal10n-ant-task/src/test/java/ch/qos/cal10n/ant/testdata/DaysOfTheWeek.java"], "files_before": {}, "files_after": {"cal10n-ant-task/src/main/java/ch/qos/cal10n/ant/EnumTypesElement.java": "/*\n * Copyright (c) 2009 QOS.ch All rights reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\npackage ch.qos.cal10n.ant;\n\nimport org.apache.tools.ant.Task;\n\nimport java.util.LinkedList;\nimport java.util.List;\n\npublic class EnumTypesElement extends Task {\n private List enumTypes;\n\n public EnumTypesElement() {\n this.enumTypes = new LinkedList();\n }\n\n public void addEnumType(StringElement enumType) {\n this.enumTypes.add(enumType);\n }\n\n public List getEnumTypes() {\n return this.enumTypes;\n }\n}\n", "cal10n-ant-task/src/main/java/ch/qos/cal10n/ant/StringElement.java": "/*\n * Copyright (c) 2009 QOS.ch All rights reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\npackage ch.qos.cal10n.ant;\n\nimport org.apache.tools.ant.Task;\n\npublic class StringElement extends Task {\n private String str;\n\n public StringElement() {}\n\n public StringElement(String str) {\n this.str = str;\n }\n\n public void addText(String str) {\n this.str = this.getProject().replaceProperties(str);\n }\n\n public String getText() {\n return this.str;\n }\n\n @Override\n public String toString() {\n return this.str;\n }\n}\n", "cal10n-ant-task/src/main/java/ch/qos/cal10n/ant/VerifyTask.java": "/*\n * Copyright (c) 2009 QOS.ch All rights reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\npackage ch.qos.cal10n.ant;\n\nimport ch.qos.cal10n.CAL10NConstants;\nimport ch.qos.cal10n.verifier.IMessageKeyVerifier;\nimport org.apache.tools.ant.BuildException;\nimport org.apache.tools.ant.Task;\nimport org.apache.tools.ant.types.LogLevel;\nimport org.apache.tools.ant.types.Path;\nimport org.apache.tools.ant.types.Reference;\nimport org.apache.tools.ant.util.ClasspathUtils;\n\nimport java.lang.reflect.Constructor;\nimport java.text.MessageFormat;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Locale;\n\npublic class VerifyTask extends Task {\n private List enumTypes;\n private Path classpath;\n\n @Override\n public void init() throws BuildException {\n this.enumTypes = new LinkedList();\n }\n\n @Override\n public void execute() throws BuildException {\n if (this.enumTypes.isEmpty()) {\n throw new BuildException(CAL10NConstants.MISSING_ENUM_TYPES_MSG);\n }\n for (StringElement enumType : this.enumTypes) {\n IMessageKeyVerifier imcv = getMessageKeyVerifierInstance(enumType.getText());\n log(\"Checking all resource bundles for enum type [\" + enumType + \"]\", LogLevel.INFO.getLevel());\n checkAllLocales(imcv);\n }\n }\n\n public void checkAllLocales(IMessageKeyVerifier mcv) {\n String enumClassAsStr = mcv.getEnumTypeAsStr();\n String[] localeNameArray = mcv.getLocaleNames();\n\n if (localeNameArray == null || localeNameArray.length == 0) {\n String errMsg = MessageFormat.format(CAL10NConstants.MISSING_LOCALE_DATA_ANNOTATION_MESSAGE, enumClassAsStr);\n log(errMsg, LogLevel.ERR.getLevel());\n throw new BuildException(errMsg);\n }\n\n boolean failure = false;\n for (String localeName : localeNameArray) {\n Locale locale = new Locale(localeName);\n List errorList = mcv.typeIsolatedVerify(locale);\n if (errorList.size() == 0) {\n String resourceBundleName = mcv.getBaseName();\n log(\"SUCCESSFUL verification for resource bundle [\" + resourceBundleName + \"] for locale [\" + locale + \"]\", LogLevel.INFO.getLevel());\n } else {\n failure = true;\n log(\"FAILURE during verification of resource bundle for locale [\"\n + locale + \"] enum class [\" + enumClassAsStr + \"]\", LogLevel.ERR.getLevel());\n for (String error : errorList) {\n log(error, LogLevel.ERR.getLevel());\n }\n }\n }\n if (failure) {\n throw new BuildException(\"FAIL Verification of [\" + enumClassAsStr + \"] keys.\");\n }\n }\n\n IMessageKeyVerifier getMessageKeyVerifierInstance(String enumClassAsStr) {\n String errMsg = \"Failed to instantiate MessageKeyVerifier class\";\n try {\n ClassLoader classLoader = ClasspathUtils.getClassLoaderForPath(this.getProject(), this.classpath, \"cal10n.VerifyTask\");\n Class mkvClass = Class.forName(\n CAL10NConstants.MessageKeyVerifier_FQCN, true, classLoader);\n Constructor mkvCons = mkvClass.getConstructor(String.class);\n return (IMessageKeyVerifier) mkvCons.newInstance(enumClassAsStr);\n } catch (ClassNotFoundException e) {\n throw new BuildException(errMsg, e);\n } catch (NoClassDefFoundError e) {\n throw new BuildException(errMsg, e);\n } catch (Exception e) {\n throw new BuildException(errMsg, e);\n }\n }\n\n public void addClasspath(Path classpath) {\n this.classpath = classpath;\n }\n\n public void addConfiguredEnumTypes(EnumTypesElement enumTypes) {\n this.enumTypes.addAll(enumTypes.getEnumTypes());\n }\n\n public void setClasspath(Path classpath) {\n this.classpath = classpath;\n }\n\n public void setClasspathRef(Reference refId) {\n Path cp = new Path(this.getProject());\n cp.setRefid(refId);\n this.setClasspath(cp);\n }\n\n public void setEnumType(String enumType) {\n this.enumTypes.add(new StringElement(enumType));\n }\n}\n", "cal10n-ant-task/src/test/java/ch/qos/cal10n/ant/VerifyTaskTest.java": "/*\n * Copyright (c) 2009 QOS.ch All rights reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\npackage ch.qos.cal10n.ant;\n\nimport junit.framework.TestSuite;\nimport org.apache.ant.antunit.junit3.AntUnitSuite;\nimport org.apache.ant.antunit.junit4.AntUnitSuiteRunner;\nimport org.junit.runner.RunWith;\n\nimport java.io.File;\nimport java.io.UnsupportedEncodingException;\nimport java.net.URISyntaxException;\nimport java.net.URL;\nimport java.net.URLDecoder;\n\n@RunWith(AntUnitSuiteRunner.class)\npublic class VerifyTaskTest {\n public static TestSuite suite() throws URISyntaxException {\n setProperties();\n URL resource = VerifyTask.class.getResource(\"/ch/qos/cal10n/ant/VerifyTaskTest.xml\");\n File file = new File(resource.toURI());\n return new AntUnitSuite(file, VerifyTask.class);\n }\n\n /**\n * Set system properties for use in the AntUnit files.\n */\n private static void setProperties() {\n String name = VerifyTask.class.getName();\n final String resourceName = \"/\" + name.replace('.', '/') + \".class\";\n String absoluteFilePath = VerifyTask.class.getResource(resourceName).getFile();\n try {\n absoluteFilePath = URLDecoder.decode(absoluteFilePath, \"UTF-8\");\n } catch (UnsupportedEncodingException e) {\n throw new RuntimeException(\"Missing UTF-8 encoding in JVM.\", e);\n }\n String classesDir = absoluteFilePath.substring(0, absoluteFilePath.length() - resourceName.length());\n System.setProperty(\"ch.qos.cal10n.ant.VerifyTaskTest.classes.dir\", classesDir);\n }\n}\n", "cal10n-ant-task/src/test/java/ch/qos/cal10n/ant/testdata/Colors.java": "/*\n * Copyright (c) 2009 QOS.ch All rights reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\npackage ch.qos.cal10n.ant.testdata;\n\nimport ch.qos.cal10n.BaseName;\nimport ch.qos.cal10n.Locale;\nimport ch.qos.cal10n.LocaleData;\n\n@BaseName(\"colors\")\n@LocaleData({\n @Locale(\"en\"),\n @Locale(\"fr\")\n})\npublic enum Colors {\n RED,\n BLUE\n}\n", "cal10n-ant-task/src/test/java/ch/qos/cal10n/ant/testdata/DaysOfTheWeek.java": "package ch.qos.cal10n.ant.testdata;\n\nimport ch.qos.cal10n.BaseName;\nimport ch.qos.cal10n.Locale;\nimport ch.qos.cal10n.LocaleData;\n\n@BaseName(\"daysoftheweek\")\n@LocaleData({\n @Locale(\"en\"),\n @Locale(\"fr\")\n})\npublic enum DaysOfTheWeek {\n MONDAY,\n TUESDAY,\n WEDNESDAY,\n THURSDAY,\n FRIDAY,\n SATURDAY,\n SUNDAY\n}\n"}} -{"repo": "scribtex/clsi", "pr_number": 1, "title": "Update readme and config", "state": "open", "merged_at": null, "additions": 2, "deletions": 2, "files_changed": ["app/models/compile.rb"], "files_before": {"app/models/compile.rb": "class Compile\n attr_accessor :token, :user,\n :root_resource_path, :resources, \n :compiler, :output_format\n attr_reader :output_files, :log_files, :unique_id,\n :status, :error_type, :error_message,\n :bibtex_ran, :makeindex_ran\n\n POSSIBLE_COMPILER_OUTPUT_FORMATS = {\n :pdflatex => ['pdf'],\n :latex => ['dvi', 'pdf', 'ps'],\n :xelatex => ['pdf']\n }\n\n def compiler\n @compiler ||= 'pdflatex'\n end\n\n def output_format\n @output_format ||= 'pdf'\n end\n\n def initialize(attributes = {})\n self.root_resource_path = attributes[:root_resource_path] || \"main.tex\"\n self.token = attributes[:token]\n \n self.compiler = attributes[:compiler]\n self.output_format = attributes[:output_format]\n\n self.resources = []\n for resource in attributes[:resources].to_a\n self.resources << Resource.new(\n resource[:path],\n resource[:modified_date],\n resource[:content],\n resource[:url],\n self\n )\n end\n \n @output_files = []\n @log_files = []\n @status = :unprocessed\n @bibtex_ran = false\n @makeindex_ran = false\n end\n\n def compile\n @start_time = Time.now\n validate_compile\n write_resources_to_disk\n do_compile\n convert_to_output_format\n move_compiled_files_to_public_dir\n @status = :success\n rescue CLSI::CompileError => e\n @status = :failure\n @error_type = e.class.name.demodulize\n @error_message = e.message\n ensure\n move_log_files_to_public_dir\n write_response_to_public_dir\n remove_compile_directory unless PRESERVE_COMPILE_DIRECTORIES\n record_in_compile_log\n end\n\n def validate_compile\n if self.user.blank?\n self.user = User.find_by_token(self.token)\n raise CLSI::InvalidToken, 'user does not exist' if self.user.nil?\n end\n \n unless POSSIBLE_COMPILER_OUTPUT_FORMATS.has_key?(self.compiler.to_sym)\n raise CLSI::UnknownCompiler, \"#{self.compiler} is not a valid compiler\"\n end\n \n unless POSSIBLE_COMPILER_OUTPUT_FORMATS[self.compiler.to_sym].include?(self.output_format)\n raise CLSI::ImpossibleOutputFormat, \"#{self.compiler} cannot produce #{self.output_format} output\"\n end\n end\n \n def unique_id\n @unique_id ||= generate_unique_string\n end\n \n def compile_directory\n @compile_directory ||= File.join(LATEX_COMPILE_DIR, self.unique_id)\n end\n \n def to_xml\n xml = Builder::XmlMarkup.new\n xml.instruct!\n\n xml.compile do\n xml.compile_id(self.unique_id)\n \n if self.status == :failure\n xml.status('failure')\n xml.error do\n xml.type self.error_type\n xml.message self.error_message\n end\n else\n xml.status(self.status.to_s)\n end\n \n unless self.output_files.empty?\n xml.output do\n for file in self.output_files\n xml.file(:url => file.url, :type => file.type, :mimetype => file.mimetype)\n end\n end\n end\n \n unless self.log_files.empty?\n xml.logs do\n for file in self.log_files\n xml.file(:url => file.url, :type => file.type, :mimetype => file.mimetype)\n end\n end\n end\n end\n end\n \n def to_json\n hash = {\n 'compile_id' => self.unique_id,\n 'status' => self.status.to_s\n }\n \n if self.status == :failure\n hash['error'] = {\n 'type' => self.error_type,\n 'message' => self.error_message\n }\n end\n \n unless self.output_files.empty?\n hash['output_files'] = self.output_files.collect{|of| {\n 'url' => of.url,\n 'mimetype' => of.mimetype,\n 'type' => of.type\n }}\n end\n \n unless self.log_files.empty?\n hash['logs'] = self.log_files.collect{|lf| {\n 'url' => lf.url,\n 'mimetype' => lf.mimetype,\n 'type' => lf.type\n }}\n end\n \n return ({'compile' => hash}).to_json\n end\n\nprivate\n\n def write_resources_to_disk\n File.umask(0002)\n \n for resource in self.resources.to_a\n resource.write_to_disk\n end\n end\n\n def do_compile\n run_compiler\n \n aux_file_content = read_aux_files\n if aux_file_content.include? '\\\\citation' or aux_file_content.include? '\\\\bibdata' or aux_file_content.include? '\\\\bibstyle'\n modify_aux_files\n run_bibtex\n run_latex_again = true\n @bibtex_ran = true\n end\n \n if File.exist?(File.join(compile_directory, 'output.idx'))\n run_makeindex\n run_latex_again = true\n @makeindex_ran = true\n end\n\n if File.exist?(File.join(compile_directory, 'output.toc'))\n # We have a table of contents that needs to be included\n run_latex_again = true\n end\n \n if log_complains_about_references? or run_latex_again\n run_compiler\n end\n \n if log_complains_about_references?\n run_compiler\n end\n\n if log_complains_about_references?\n run_compiler\n end\n end\n\n def log_complains_about_references?\n log_content = read_log\n log_content.include?('There were undefined references') ||\n log_content.include?('There were undefined citations') ||\n log_content.include?('LaTeX Warning: Label(s) may have changed. Rerun to get cross-references right.') ||\n log_content.include?('LaTeX Warning: Citation') || # Natbib\n log_content.include?('No file output.toc') ||\n log_content.include?('Rerun LaTeX') # The longtables package\n end\n \n def run_bibtex\n bibtex_command = ['env', tex_env_variables, BIBTEX_COMMAND, \"#{compile_directory_rel_to_chroot}/output\"].flatten\n run_with_timeout(bibtex_command, BIBTEX_TIMEOUT)\n end\n \n def run_makeindex\n makeindex_command = [\n MAKEINDEX_COMMAND,\n '-o', \"#{compile_directory_rel_to_chroot}/output.ind\",\n \"#{compile_directory_rel_to_chroot}/output.idx\"\n ]\n run_with_timeout(makeindex_command, COMPILE_TIMEOUT)\n end\n \n def run_compiler\n run_with_timeout(compile_command, COMPILE_TIMEOUT)\n end\n \n def read_aux_files\n aux_file_paths = Dir.entries(self.compile_directory).reject{|e| not e.match(/\\.aux$/)}\n aux_file_paths.collect!{|p| File.join(self.compile_directory, p)}\n return aux_file_paths.collect{|p| File.read(p)}.join(\"\\n\")\n end\n \n def modify_aux_files\n aux_file_names = Dir.entries(self.compile_directory).reject{|e| not e.match(/\\.aux$/)}\n aux_file_paths = aux_file_names.collect{|n| File.join(self.compile_directory, n)}\n for aux_file in aux_file_paths\n content = File.read(aux_file)\n content.gsub!(/^\\\\@input\\{(.*)\\}$/, \"\\\\@input{#{compile_directory_rel_to_chroot}/\\\\1}\")\n File.open(aux_file, 'w') {|f|\n f.write(content)\n }\n end\n end\n \n def read_log\n log_file_path = File.join(self.compile_directory, 'output.log')\n return '' unless File.exist?(log_file_path)\n File.read(log_file_path)\n end\n \n def convert_to_output_format\n case self.compiler\n when 'pdflatex'\n input_format = 'pdf'\n when 'latex'\n input_format = 'dvi'\n when 'xelatex'\n input_format = 'pdf'\n end\n ensure_output_files_exist(input_format)\n conversion_method = \"convert_#{input_format}_to_#{self.output_format}\"\n if self.respond_to?(conversion_method, true)\n self.send(conversion_method)\n else\n raise CLSI::ImpossibleFormatConversion, \"can't convert #{input_format} to #{self.output_format}\"\n end\n end\n\n def move_compiled_files_to_public_dir\n FileUtils.mkdir_p(File.join(SERVER_PUBLIC_DIR, 'output', self.unique_id))\n \n for existing_file in find_output_files_of_type(self.output_format)\n existing_path = File.join(compile_directory, existing_file)\n relative_output_path = File.join(relative_output_dir, existing_file)\n output_path = File.join(SERVER_PUBLIC_DIR, relative_output_path)\n FileUtils.mv(existing_path, output_path)\n @output_files << OutputFile.new(:path => relative_output_path)\n end\n end\n \n def move_log_files_to_public_dir\n FileUtils.mkdir_p(output_dir)\n \n existing_log_path = File.join(compile_directory, 'output.log')\n relative_output_log_path = File.join(relative_output_dir, 'output.log')\n if File.exist?(existing_log_path)\n FileUtils.mv(existing_log_path, File.join(SERVER_PUBLIC_DIR, relative_output_log_path))\n @log_files << OutputFile.new(:path => relative_output_log_path)\n end\n end\n \n def remove_compile_directory\n FileUtils.rm_rf(self.compile_directory)\n end\n \n def write_response_to_public_dir\n FileUtils.mkdir_p(output_dir)\n File.open(File.join(output_dir, 'response.xml'), 'w') do |f|\n f.write(self.to_xml)\n end\n File.open(File.join(output_dir, 'response.json'), 'w') do |f|\n f.write(self.to_json)\n end\n end\n \n def record_in_compile_log\n CompileLog.create(\n :user => user,\n :time_taken => ((Time.now.to_f - @start_time.to_f) * 1000).to_i, # Time in milliseconds\n :bibtex_ran => @bibtex_ran,\n :makeindex_ran => @makeindex_ran\n )\n end\n \n def tex_env_variables\n root_and_relative_directories = [\n File.join(compile_directory_rel_to_chroot, File.dirname(self.root_resource_path)),\n compile_directory_rel_to_chroot\n ].join(\":\") + \":\"\n return [\n \"TEXMFOUTPUT=#{compile_directory_rel_to_chroot}\",\n \"TEXINPUTS=#{root_and_relative_directories}\",\n \"BIBINPUTS=#{root_and_relative_directories}\",\n \"BSTINPUTS=#{root_and_relative_directories}\",\n \"TEXFONTS=#{root_and_relative_directories}\",\n \"TFMFONTS=#{root_and_relative_directories}\"\n ]\n end\n \n def output_dir\n File.join(SERVER_PUBLIC_DIR, relative_output_dir)\n end\n \n def relative_output_dir\n File.join('output', self.unique_id)\n end\n \n def compile_directory_rel_to_chroot\n @compile_directory_rel_to_chroot ||= File.join(LATEX_COMPILE_DIR_RELATIVE_TO_CHROOT, self.unique_id)\n end\n \n def compile_command\n case self.compiler\n when 'pdflatex'\n command = PDFLATEX_COMMAND\n when 'latex'\n command = LATEX_COMMAND\n when 'xelatex'\n command = XELATEX_COMMAND\n else\n raise NotImplemented # Previous checking means we should never get here!\n end\n return [\"env\"] + tex_env_variables + [command, \"-interaction=batchmode\",\n \"-output-directory=#{compile_directory_rel_to_chroot}\", \"-no-shell-escape\", \n \"-jobname=output\", self.root_resource_path]\n end\n \n # Returns a list of output files of the given type. Will raise a CLSI::NoOutputFile if no output\n # files of the given type exist.\n def find_output_files_of_type(type)\n file_name = \"output.#{type}\"\n output_path = File.join(compile_directory, file_name)\n raise CLSI::NoOutputProduced, 'no compiled documents were produced' unless File.exist?(output_path)\n return [file_name]\n end\n \n def ensure_output_files_exist(type)\n find_output_files_of_type(type)\n end\n \n def convert_pdf_to_pdf\n # Nothing to do!\n end\n \n def convert_dvi_to_dvi\n # Nothing to do! \n end\n \n def convert_dvi_to_pdf\n input = File.join(compile_directory_rel_to_chroot, 'output.dvi')\n output = File.join(compile_directory_rel_to_chroot, 'output.pdf')\n\n # Note: Adding &> /dev/null to this command makes run_with_timeout return straight away before\n # command is complete, and I have no idea why. Solution: Don't add it.\n dvipdf_command = \"env TEXPICTS=#{compile_directory_rel_to_chroot} #{DVIPDF_COMMAND} \\\"#{input}\\\" \\\"#{output}\\\"\"\n run_with_timeout(dvipdf_command, DVIPDF_TIMEOUT)\n end\n \n def convert_dvi_to_ps\n input = File.join(compile_directory_rel_to_chroot, 'output.dvi')\n output = File.join(compile_directory_rel_to_chroot, 'output.ps')\n dvips_command = \"env TEXPICTS=#{compile_directory_rel_to_chroot} #{DVIPS_COMMAND} -o \\\"#{output}\\\" \\\"#{input}\\\"\"\n run_with_timeout(dvips_command, DVIPS_TIMEOUT)\n end\n \n # Everything below here is copied from the mathwiki code. It was ugly when\n # I first wrote it and it hasn't improved with time. \n # Fixing it would be good.\n def run_with_timeout(command, timeout = 10)\n start_time = Time.now\n pid = fork {\n exec(*command)\n }\n while Time.now - start_time < timeout\n if Process.waitpid(pid, Process::WNOHANG)\n Rails.logger.info \"(#{Time.now - start_time} seconds) #{command.to_a.join(' ')}\"\n return pid\n end\n sleep 0.1 if (Time.now - start_time > 0.3) # No need to check too often if it's taking a while\n end\n \n # Process never finished\n kill_process(pid)\n raise CLSI::Timeout, \"the compile took too long to run and was aborted\"\n end\n \n def kill_process(pid)\n child_pids = %x[ps -e -o 'ppid pid' | awk '$1 == #{pid} { print $2 }'].split\n child_pids.collect{|cpid| kill_process(cpid.to_i)}\n Process.kill('INT', pid)\n Process.kill('HUP', pid)\n Process.kill('KILL', pid)\n end\nend\n"}, "files_after": {"app/models/compile.rb": "class Compile\n attr_accessor :token, :user,\n :root_resource_path, :resources, \n :compiler, :output_format\n attr_reader :output_files, :log_files, :unique_id,\n :status, :error_type, :error_message,\n :bibtex_ran, :makeindex_ran\n\n POSSIBLE_COMPILER_OUTPUT_FORMATS = {\n :pdflatex => ['pdf'],\n :latex => ['dvi', 'pdf', 'ps'],\n :xelatex => ['pdf']\n }\n\n def compiler\n @compiler ||= 'pdflatex'\n end\n\n def output_format\n @output_format ||= 'pdf'\n end\n\n def initialize(attributes = {})\n self.root_resource_path = attributes[:root_resource_path] || \"main.tex\"\n self.token = attributes[:token]\n \n self.compiler = attributes[:compiler]\n self.output_format = attributes[:output_format]\n\n self.resources = []\n for resource in attributes[:resources].to_a\n self.resources << Resource.new(\n resource[:path],\n resource[:modified_date],\n resource[:content],\n resource[:url],\n self\n )\n end\n \n @output_files = []\n @log_files = []\n @status = :unprocessed\n @bibtex_ran = false\n @makeindex_ran = false\n end\n\n def compile\n @start_time = Time.now\n validate_compile\n write_resources_to_disk\n do_compile\n convert_to_output_format\n move_compiled_files_to_public_dir\n @status = :success\n rescue CLSI::CompileError => e\n @status = :failure\n @error_type = e.class.name.demodulize\n @error_message = e.message\n ensure\n move_log_files_to_public_dir\n write_response_to_public_dir\n remove_compile_directory unless PRESERVE_COMPILE_DIRECTORIES\n record_in_compile_log\n end\n\n def validate_compile\n if self.user.blank?\n self.user = User.find_by_token(self.token)\n raise CLSI::InvalidToken, 'user does not exist' if self.user.nil?\n end\n \n unless POSSIBLE_COMPILER_OUTPUT_FORMATS.has_key?(self.compiler.to_sym)\n raise CLSI::UnknownCompiler, \"#{self.compiler} is not a valid compiler\"\n end\n \n unless POSSIBLE_COMPILER_OUTPUT_FORMATS[self.compiler.to_sym].include?(self.output_format)\n raise CLSI::ImpossibleOutputFormat, \"#{self.compiler} cannot produce #{self.output_format} output\"\n end\n end\n \n def unique_id\n @unique_id ||= generate_unique_string\n end\n \n def compile_directory\n @compile_directory ||= File.join(LATEX_COMPILE_DIR, self.unique_id)\n end\n \n def to_xml\n xml = Builder::XmlMarkup.new\n xml.instruct!\n\n xml.compile do\n xml.compile_id(self.unique_id)\n \n if self.status == :failure\n xml.status('failure')\n xml.error do\n xml.type self.error_type\n xml.message self.error_message\n end\n else\n xml.status(self.status.to_s)\n end\n \n unless self.output_files.empty?\n xml.output do\n for file in self.output_files\n xml.file(:url => file.url, :type => file.type, :mimetype => file.mimetype)\n end\n end\n end\n \n unless self.log_files.empty?\n xml.logs do\n for file in self.log_files\n xml.file(:url => file.url, :type => file.type, :mimetype => file.mimetype)\n end\n end\n end\n end\n end\n \n def to_json\n hash = {\n 'compile_id' => self.unique_id,\n 'status' => self.status.to_s\n }\n \n if self.status == :failure\n hash['error'] = {\n 'type' => self.error_type,\n 'message' => self.error_message\n }\n end\n \n unless self.output_files.empty?\n hash['output_files'] = self.output_files.collect{|of| {\n 'url' => of.url,\n 'mimetype' => of.mimetype,\n 'type' => of.type\n }}\n end\n \n unless self.log_files.empty?\n hash['logs'] = self.log_files.collect{|lf| {\n 'url' => lf.url,\n 'mimetype' => lf.mimetype,\n 'type' => lf.type\n }}\n end\n \n return ({'compile' => hash}).to_json\n end\n\nprivate\n\n def write_resources_to_disk\n File.umask(0002)\n \n for resource in self.resources.to_a\n resource.write_to_disk\n end\n end\n\n def do_compile\n run_compiler\n \n aux_file_content = read_aux_files\n if aux_file_content.include? '\\\\citation' or aux_file_content.include? '\\\\bibdata' or aux_file_content.include? '\\\\bibstyle'\n modify_aux_files\n run_bibtex\n run_latex_again = true\n @bibtex_ran = true\n end\n \n if File.exist?(File.join(compile_directory, 'output.idx'))\n run_makeindex\n run_latex_again = true\n @makeindex_ran = true\n end\n\n if File.exist?(File.join(compile_directory, 'output.toc'))\n # We have a table of contents that needs to be included\n run_latex_again = true\n end\n \n if log_complains_about_references? or run_latex_again\n run_compiler\n end\n \n if log_complains_about_references?\n run_compiler\n end\n\n if log_complains_about_references?\n run_compiler\n end\n end\n\n def log_complains_about_references?\n log_content = read_log\n log_content.include?('There were undefined references') ||\n log_content.include?('There were undefined citations') ||\n log_content.include?('LaTeX Warning: Label(s) may have changed. Rerun to get cross-references right.') ||\n log_content.include?('LaTeX Warning: Citation') || # Natbib\n log_content.include?('No file output.toc') ||\n log_content.include?('Rerun LaTeX') # The longtables package\n end\n \n def run_bibtex\n bibtex_command = ['env', tex_env_variables, BIBTEX_COMMAND, \"#{compile_directory_rel_to_chroot}/output\"].flatten\n run_with_timeout(bibtex_command, BIBTEX_TIMEOUT)\n end\n \n def run_makeindex\n makeindex_command = [\n MAKEINDEX_COMMAND,\n '-o', \"#{compile_directory_rel_to_chroot}/output.ind\",\n \"#{compile_directory_rel_to_chroot}/output.idx\"\n ]\n run_with_timeout(makeindex_command, COMPILE_TIMEOUT)\n end\n \n def run_compiler\n run_with_timeout(compile_command, COMPILE_TIMEOUT)\n end\n \n def read_aux_files\n aux_file_paths = Dir.entries(self.compile_directory).reject{|e| not e.match(/\\.aux$/)}\n aux_file_paths.collect!{|p| File.join(self.compile_directory, p)}\n return aux_file_paths.collect{|p| File.read(p)}.join(\"\\n\")\n end\n \n def modify_aux_files\n aux_file_names = Dir.entries(self.compile_directory).reject{|e| not e.match(/\\.aux$/)}\n aux_file_paths = aux_file_names.collect{|n| File.join(self.compile_directory, n)}\n for aux_file in aux_file_paths\n content = File.read(aux_file)\n content.gsub!(/^\\\\@input\\{(.*)\\}$/, \"\\\\@input{#{compile_directory_rel_to_chroot}/\\\\1}\")\n File.open(aux_file, 'w') {|f|\n f.write(content)\n }\n end\n end\n \n def read_log\n log_file_path = File.join(self.compile_directory, 'output.log')\n return '' unless File.exist?(log_file_path)\n File.read(log_file_path)\n end\n \n def convert_to_output_format\n case self.compiler\n when 'pdflatex'\n input_format = 'pdf'\n when 'latex'\n input_format = 'dvi'\n when 'xelatex'\n input_format = 'pdf'\n end\n ensure_output_files_exist(input_format)\n conversion_method = \"convert_#{input_format}_to_#{self.output_format}\"\n if self.respond_to?(conversion_method, true)\n self.send(conversion_method)\n else\n raise CLSI::ImpossibleFormatConversion, \"can't convert #{input_format} to #{self.output_format}\"\n end\n end\n\n def move_compiled_files_to_public_dir\n FileUtils.mkdir_p(File.join(SERVER_PUBLIC_DIR, 'output', self.unique_id))\n \n for existing_file in find_output_files_of_type(self.output_format)\n existing_path = File.join(compile_directory, existing_file)\n relative_output_path = File.join(relative_output_dir, existing_file)\n output_path = File.join(SERVER_PUBLIC_DIR, relative_output_path)\n FileUtils.mv(existing_path, output_path)\n @output_files << OutputFile.new(:path => relative_output_path)\n end\n end\n \n def move_log_files_to_public_dir\n FileUtils.mkdir_p(output_dir)\n \n existing_log_path = File.join(compile_directory, 'output.log')\n relative_output_log_path = File.join(relative_output_dir, 'output.log')\n if File.exist?(existing_log_path)\n FileUtils.mv(existing_log_path, File.join(SERVER_PUBLIC_DIR, relative_output_log_path))\n @log_files << OutputFile.new(:path => relative_output_log_path)\n end\n end\n \n def remove_compile_directory\n FileUtils.rm_rf(self.compile_directory)\n end\n \n def write_response_to_public_dir\n FileUtils.mkdir_p(output_dir)\n File.open(File.join(output_dir, 'response.xml'), 'w') do |f|\n f.write(self.to_xml)\n end\n File.open(File.join(output_dir, 'response.json'), 'w') do |f|\n f.write(self.to_json)\n end\n end\n \n def record_in_compile_log\n CompileLog.create(\n :user => user,\n :time_taken => ((Time.now.to_f - @start_time.to_f) * 1000).to_i, # Time in milliseconds\n :bibtex_ran => @bibtex_ran,\n :makeindex_ran => @makeindex_ran\n )\n end\n \n def tex_env_variables\n root_and_relative_directories = [\n File.join(compile_directory_rel_to_chroot, File.dirname(self.root_resource_path)),\n compile_directory_rel_to_chroot\n ].join(\":\") + \":\"\n return [\n \"TEXMFOUTPUT=#{compile_directory_rel_to_chroot}\",\n \"TEXINPUTS=#{root_and_relative_directories}\",\n \"BIBINPUTS=#{root_and_relative_directories}\",\n \"BSTINPUTS=#{root_and_relative_directories}\",\n \"TEXFONTS=#{root_and_relative_directories}\",\n \"TFMFONTS=#{root_and_relative_directories}\"\n ]\n end\n \n def output_dir\n File.join(SERVER_PUBLIC_DIR, relative_output_dir)\n end\n \n def relative_output_dir\n File.join('output', self.unique_id)\n end\n \n def compile_directory_rel_to_chroot\n @compile_directory_rel_to_chroot ||= File.join(LATEX_COMPILE_DIR_RELATIVE_TO_CHROOT, self.unique_id)\n end\n \n def compile_command\n case self.compiler\n when 'pdflatex'\n command = PDFLATEX_COMMAND\n when 'latex'\n command = LATEX_COMMAND\n when 'xelatex'\n command = XELATEX_COMMAND\n else\n raise NotImplemented # Previous checking means we should never get here!\n end\n return [\"env\"] + tex_env_variables + [command, \"-interaction=batchmode\",\n \"-output-directory=#{compile_directory_rel_to_chroot}\", \"-no-shell-escape\", \n \"-jobname=output\", self.root_resource_path]\n end\n \n # Returns a list of output files of the given type. Will raise a CLSI::NoOutputFile if no output\n # files of the given type exist.\n def find_output_files_of_type(type)\n file_name = \"output.#{type}\"\n output_path = File.join(compile_directory, file_name)\n raise CLSI::NoOutputProduced, 'no compiled documents were produced' unless File.exist?(output_path)\n return [file_name]\n end\n \n def ensure_output_files_exist(type)\n find_output_files_of_type(type)\n end\n \n def convert_pdf_to_pdf\n # Nothing to do!\n end\n \n def convert_dvi_to_dvi\n # Nothing to do! \n end\n \n def convert_dvi_to_pdf\n input = File.join(compile_directory_rel_to_chroot, 'output.dvi')\n output = File.join(compile_directory_rel_to_chroot, 'output.pdf')\n\n # Note: Adding &> /dev/null to this command makes run_with_timeout return straight away before\n # command is complete, and I have no idea why. Solution: Don't add it.\n dvipdf_command = \"env TEXPICTS=#{compile_directory_rel_to_chroot} #{DVIPDF_COMMAND} -o \\\"#{output}\\\" \\\"#{input}\\\"\" \n run_with_timeout(dvipdf_command, DVIPDF_TIMEOUT)\n end\n \n def convert_dvi_to_ps\n input = File.join(compile_directory_rel_to_chroot, 'output.dvi')\n output = File.join(compile_directory_rel_to_chroot, 'output.ps')\n dvips_command = \"env TEXPICTS=#{compile_directory_rel_to_chroot} #{DVIPS_COMMAND} -o \\\"#{output}\\\" \\\"#{input}\\\"\"\n run_with_timeout(dvips_command, DVIPS_TIMEOUT)\n end\n \n # Everything below here is copied from the mathwiki code. It was ugly when\n # I first wrote it and it hasn't improved with time. \n # Fixing it would be good.\n def run_with_timeout(command, timeout = 10)\n start_time = Time.now\n pid = fork {\n exec(*command)\n }\n while Time.now - start_time < timeout\n if Process.waitpid(pid, Process::WNOHANG)\n Rails.logger.info \"(#{Time.now - start_time} seconds) #{command.to_a.join(' ')}\"\n return pid\n end\n sleep 0.1 if (Time.now - start_time > 0.3) # No need to check too often if it's taking a while\n end\n \n # Process never finished\n kill_process(pid)\n raise CLSI::Timeout, \"the compile took too long to run and was aborted\"\n end\n \n def kill_process(pid)\n child_pids = %x[ps -e -o 'ppid pid' | awk '$1 == #{pid} { print $2 }'].split\n child_pids.collect{|cpid| kill_process(cpid.to_i)}\n Process.kill('INT', pid)\n Process.kill('HUP', pid)\n Process.kill('KILL', pid)\n end\nend\n"}} -{"repo": "faustocintra/GExtenso", "pr_number": 3, "title": "Class to Module + upgrades", "state": "open", "merged_at": null, "additions": 211, "deletions": 27, "files_changed": ["GExtenso.rb"], "files_before": {"GExtenso.rb": "#!/usr/bin/env ruby\n\n##############################################################################################################\n# ATEN\u00c7\u00c3O: Este \u00e9 o meu primeiro trabalho na linguagem Ruby. A l\u00f3gica foi originalmente desenvolvida em PHP; #\n# portanto, o estilo do c\u00f3digo pode n\u00e3o agradar programadores Ruby experientes. Estou aberto a cr\u00edticas #\n# construtivas e sugest\u00f5es, para melhorar meu conhecimento na linguagem. #\n##############################################################################################################\n\n# GExtenso class file\n#\n# author Fausto Gon\u00e7alves Cintra (goncin) \n# link http://goncin.wordpress.com\n# link http://twitter.com/g0nc1n\n# license http://creativecommons.org/licenses/LGPL/2.1/deed.pt\n#\n\n# GExtenso \u00e9 uma classe que gera a representa\u00e7\u00e3o por extenso de um n\u00famero ou valor monet\u00e1rio.\n#\n# ATEN\u00c7\u00c3O: A P\u00c1GINA DE C\u00d3DIGO DESTE ARQUIVO \u00c9 UTF-8 (Unicode)!\n# \n# Sua implementa\u00e7\u00e3o foi feita como prova de conceito, utilizando:\n# * M\u00e9todos est\u00e1ticos, implementando o padr\u00e3o de projeto (\"design pattern\") SINGLETON;\n# * Chamadas recursivas a m\u00e9todos, minimizando repeti\u00e7\u00f5es e mantendo o c\u00f3digo enxuto; e\n# * Tratamento de erros por interm\u00e9dio de exce\u00e7\u00f5es.\n#\n# = EXEMPLOS DE USO =\n#\n# Para obter o extenso de um n\u00famero, utilize GExtenso.numero.\n# \n# puts GExtenso.numero(832); # oitocentos e trinta e dois\n# puts GExtenso.numero(832, GExtenso::GENERO_FEM) # oitocentas e trinta e duas\n# \n#\n# Para obter o extenso de um valor monet\u00e1rio, utilize GExtenso.moeda.\n# \n# # IMPORTANTE: veja nota sobre o par\u00e2metro 'valor' na documenta\u00e7\u00e3o do m\u00e9todo!\n#\n# puts GExtenso.moeda(15402) # cento e cinquenta e quatro reais e dois centavos\n#\n# puts GExtenso.moeda(47) # quarenta e sete centavos\n#\n# puts GExtenso.moeda(357082, 2,\n# ['peseta', 'pesetas', GExtenso::GENERO_FEM],\n# ['c\u00eantimo', 'c\u00eantimos', GExtenso::GENERO_MASC])\n# # tr\u00eas mil, quinhentas e setenta pesetas e oitenta e dois c\u00eantimos\n#\n# author Fausto Gon\u00e7alves Cintra (goncin) \n# version 0.1 2010-06-10\n \nclass GExtenso\n \n NUM_SING = 0\n NUM_PLURAL = 1\n POS_GENERO = 2\n GENERO_MASC = 0\n GENERO_FEM = 1\n \n VALOR_MAXIMO = 999999999\n \n # As unidades 1 e 2 variam em g\u00eanero, pelo que precisamos de dois conjuntos de strings (masculinas e femininas) para as unidades\n UNIDADES = {\n GENERO_MASC => {\n 1 => 'um',\n 2 => 'dois',\n 3 => 'tr\u00eas',\n 4 => 'quatro',\n 5 => 'cinco',\n 6 => 'seis',\n 7 => 'sete',\n 8 => 'oito',\n 9 => 'nove'\n },\n GENERO_FEM => {\n 1 => 'uma',\n 2 => 'duas',\n 3 => 'tr\u00eas',\n 4 => 'quatro',\n 5 => 'cinco',\n 6 => 'seis',\n 7 => 'sete',\n 8 => 'oito',\n 9 => 'nove'\n }\n }\n \n DE11A19 = {\n 11 => 'onze',\n 12 => 'doze',\n 13 => 'treze',\n 14 => 'quatorze',\n 15 => 'quinze',\n 16 => 'dezesseis',\n 17 => 'dezessete',\n 18 => 'dezoito',\n 19 => 'dezenove'\n }\n \n DEZENAS = {\n 10 => 'dez',\n 20 => 'vinte',\n 30 => 'trinta',\n 40 => 'quarenta',\n 50 => 'cinquenta',\n 60 => 'sessenta',\n 70 => 'setenta',\n 80 => 'oitenta',\n 90 => 'noventa'\n }\n \n CENTENA_EXATA = 'cem'\n \n # As centenas, com exce\u00e7\u00e3o de 'cento', tamb\u00e9m variam em g\u00eanero. Aqui tamb\u00e9m se faz\n # necess\u00e1rio dois conjuntos de strings (masculinas e femininas).\n \n CENTENAS = {\n GENERO_MASC => {\n 100 => 'cento',\n 200 => 'duzentos',\n 300 => 'trezentos',\n 400 => 'quatrocentos',\n 500 => 'quinhentos',\n 600 => 'seiscentos',\n 700 => 'setecentos',\n 800 => 'oitocentos',\n 900 => 'novecentos'\n },\n GENERO_FEM => {\n 100 => 'cento',\n 200 => 'duzentas',\n 300 => 'trezentas',\n 400 => 'quatrocentas',\n 500 => 'quinhentas',\n 600 => 'seiscentas',\n 700 => 'setecentas',\n 800 => 'oitocentas',\n 900 => 'novecentas'\n }\n }\n \n #'Mil' \u00e9 invari\u00e1vel, seja em g\u00eanero, seja em n\u00famero\n MILHAR = 'mil'\n\n MILHOES = {\n NUM_SING => 'milh\u00e3o',\n NUM_PLURAL => 'milh\u00f5es'\n }\n\n UNIDADES_ORDINAL = {\n GENERO_MASC => {\n 1 => 'primeiro',\n 2 => 'segundo',\n 3 => 'terceiro',\n 4 => 'quarto',\n 5 => 'quinto',\n 6 => 'sexto',\n 7 => 's\u00e9timo',\n 8 => 'oitavo',\n 9 => 'nono'},\n GENERO_FEM => {\n 1 => 'primeira',\n 2 => 'segunda',\n 3 => 'terceira',\n 4 => 'quarta',\n 5 => 'quinta',\n 6 => 'sexta',\n 7 => 's\u00e9tima',\n 8 => 'oitava',\n 9 => 'nona'}}\n\n DEZENAS_ORDINAL = {\n GENERO_MASC => {\n 10 => 'd\u00e9cimo',\n 20 => 'vig\u00e9simo',\n 30 => 'trig\u00e9simo',\n 40 => 'quadrag\u00e9simo',\n 50 => 'quinquag\u00e9simo',\n 60 => 'sexag\u00e9simo',\n 70 => 'septuag\u00e9simo',\n 80 => 'octog\u00e9simo',\n 90 => 'nonag\u00e9simo'},\n GENERO_FEM => {\n 10 => 'd\u00e9cima',\n 20 => 'vig\u00e9sima',\n 30 => 'trig\u00e9sima',\n 40 => 'quadrag\u00e9sima',\n 50 => 'quinquag\u00e9sima',\n 60 => 'sexag\u00e9sima',\n 70 => 'septuag\u00e9sima',\n 80 => 'octog\u00e9sima',\n 90 => 'nonag\u00e9sima'}}\n \n CENTENAS_ORDINAL = {\n GENERO_MASC => {\n 100 => 'cent\u00e9simo',\n 200 => 'ducent\u00e9simo',\n 300 => 'trecent\u00e9simo',\n 400 => 'quadringent\u00e9simo',\n 500 => 'quingent\u00e9simo',\n 600 => 'seiscent\u00e9simo',\n 700 => 'septingent\u00e9simo',\n 800 => 'octingent\u00e9simo',\n 900 => 'noningent\u00e9simo'},\n GENERO_FEM => {\n 100 => 'cent\u00e9sima',\n 200 => 'ducent\u00e9sima',\n 300 => 'trecent\u00e9sima',\n 400 => 'quadringent\u00e9sima',\n 500 => 'quingent\u00e9sima',\n 600 => 'seiscent\u00e9sima',\n 700 => 'septingent\u00e9sima',\n 800 => 'octingent\u00e9sima',\n 900 => 'noningent\u00e9sima'}}\n \n \n MILHAR_ORDINAL = {\n GENERO_MASC => {\n 1000 => 'mil\u00e9simo'},\n GENERO_FEM =>{\n 1000 => 'mil\u00e9sima'}}\n \n def self.is_int(s)\n Integer(s) != nil rescue false\n end\n \n #######################################################################################################################################\n \n def self.numero (valor, genero = GENERO_MASC)\n\n # Gera a representa\u00e7\u00e3o por extenso de um n\u00famero inteiro, maior que zero e menor ou igual a VALOR_MAXIMO.\n #\n # PAR\u00c2METROS:\n # valor (Integer) O valor num\u00e9rico cujo extenso se deseja gerar\n #\n # genero (Integer) [Opcional; valor padr\u00e3o: GExtenso::GENERO_MASC] O g\u00eanero gramatical (GExtenso::GENERO_MASC ou GExtenso::GENERO_FEM)\n # do extenso a ser gerado. Isso possibilita distinguir, por exemplo, entre 'duzentos e dois homens' e 'duzentas e duas mulheres'.\n #\n # VALOR DE RETORNO:\n # (String) O n\u00famero por extenso\n \n # ----- VALIDA\u00c7\u00c3O DOS PAR\u00c2METROS DE ENTRADA ---- \n \n if !is_int(valor)\n raise \"[Exce\u00e7\u00e3o em GExtenso.numero] Par\u00e2metro 'valor' n\u00e3o \u00e9 num\u00e9rico (recebido: '#{valor}')\"\n elsif valor <= 0\n raise \"[Exce\u00e7\u00e3o em GExtenso.numero] Par\u00e2metro 'valor' igual a ou menor que zero (recebido: '#{valor}')\"\n elsif valor > VALOR_MAXIMO\n raise '[Exce\u00e7\u00e3o em GExtenso::numero] Par\u00e2metro ''valor'' deve ser um inteiro entre 1 e ' + VALOR_MAXIMO.to_s + \" (recebido: '#{valor}')\"\n elsif genero != GENERO_MASC && genero != GENERO_FEM\n raise \"Exce\u00e7\u00e3o em GExtenso: valor incorreto para o par\u00e2metro 'genero' (recebido: '#{genero}')\"\n\n # ------------------------------------------------\n\n elsif valor >= 1 && valor <= 9\n UNIDADES[genero][valor]\n \n elsif valor == 10\n DEZENAS[valor]\n\n elsif valor >= 11 && valor <= 19\n DE11A19[valor]\n \n elsif valor >= 20 && valor <= 99\n dezena = valor - (valor % 10)\n ret = DEZENAS[dezena]\n # Chamada recursiva \u00e0 fun\u00e7\u00e3o para processar resto se este for maior que zero.\n # O conectivo 'e' \u00e9 utilizado entre dezenas e unidades.\n resto = valor - dezena\n if resto > 0\n ret += ' e ' + self.numero(resto, genero)\n end\n ret\n\n elsif valor == 100 \n CENTENA_EXATA\n\n elsif valor >= 101 && valor <= 999\n centena = valor - (valor % 100)\n ret = CENTENAS[genero][centena] # As centenas (exceto 'cento') variam em g\u00eanero\n # Chamada recursiva \u00e0 fun\u00e7\u00e3o para processar resto se este for maior que zero.\n # O conectivo 'e' \u00e9 utilizado entre centenas e dezenas.\n resto = valor - centena \n if resto > 0\n ret += ' e ' + self.numero(resto, genero)\n end\n ret\n\n elsif valor >= 1000 && valor <= 999999\n # A fun\u00e7\u00e3o 'floor' \u00e9 utilizada para encontrar o inteiro da divis\u00e3o de valor por 1000,\n # assim determinando a quantidade de milhares. O resultado \u00e9 enviado a uma chamada recursiva\n # da fun\u00e7\u00e3o. A palavra 'mil' n\u00e3o se flexiona.\n milhar = (valor / 1000).floor\n ret = self.numero(milhar, GENERO_MASC) + ' ' + MILHAR # 'Mil' \u00e9 do g\u00eanero masculino\n resto = valor % 1000\n # Chamada recursiva \u00e0 fun\u00e7\u00e3o para processar resto se este for maior que zero.\n # O conectivo 'e' \u00e9 utilizado entre milhares e n\u00fameros entre 1 e 99, bem como antes de centenas exatas.\n if resto > 0 && ((resto >= 1 && resto <= 99) || resto % 100 == 0)\n ret += ' e ' + self.numero(resto, genero)\n # Nos demais casos, ap\u00f3s o milhar \u00e9 utilizada a v\u00edrgula.\n elsif (resto > 0)\n ret += ', ' + self.numero(resto, genero)\n end\n ret\n\n elsif valor >= 100000 && valor <= VALOR_MAXIMO\n # A fun\u00e7\u00e3o 'floor' \u00e9 utilizada para encontrar o inteiro da divis\u00e3o de valor por 1000000,\n # assim determinando a quantidade de milh\u00f5es. O resultado \u00e9 enviado a uma chamada recursiva\n # da fun\u00e7\u00e3o. A palavra 'milh\u00e3o' flexiona-se no plural.\n milhoes = (valor / 1000000).floor\n ret = self.numero(milhoes, GENERO_MASC) + ' ' # Milh\u00e3o e milh\u00f5es s\u00e3o do g\u00eanero masculino\n \n # Se a o n\u00famero de milh\u00f5es for maior que 1, deve-se utilizar a forma flexionada no plural\n ret += milhoes == 1 ? MILHOES[NUM_SING] : MILHOES[NUM_PLURAL]\n\n resto = valor % 1000000\n\n # Chamada recursiva \u00e0 fun\u00e7\u00e3o para processar resto se este for maior que zero.\n # O conectivo 'e' \u00e9 utilizado entre milh\u00f5es e n\u00fameros entre 1 e 99, bem como antes de centenas exatas.\n if resto && ((resto >= 1 && resto <= 99) || resto % 100 == 0)\n ret += ' e ' + ret.numero(resto, genero)\n # Nos demais casos, ap\u00f3s o milh\u00e3o \u00e9 utilizada a v\u00edrgula.\n elsif resto > 0\n ret += ', ' + self.numero(resto, genero)\n end\n ret\n\n end\n \n end\n \n #######################################################################################################################################\n \n def self.moeda(\n valor,\n casas_decimais = 2,\n info_unidade = ['real', 'reais', GENERO_MASC],\n info_fracao = ['centavo', 'centavos', GENERO_MASC]\n ) \n \n # Gera a representa\u00e7\u00e3o por extenso de um valor monet\u00e1rio, maior que zero e menor ou igual a GExtenso::VALOR_MAXIMO.\n #\n #\n # PAR\u00c2METROS:\n # valor (Integer) O valor monet\u00e1rio cujo extenso se deseja gerar.\n # ATEN\u00c7\u00c3O: PARA EVITAR OS CONHECIDOS PROBLEMAS DE ARREDONDAMENTO COM N\u00daMEROS DE PONTO FLUTUANTE, O VALOR DEVE SER PASSADO\n # J\u00c1 DEVIDAMENTE MULTIPLICADO POR 10 ELEVADO A $casasDecimais (o que equivale, normalmente, a passar o valor com centavos\n # multiplicado por 100)\n #\n # casas_decimais (Integer) [Opcional; valor padr\u00e3o: 2] N\u00famero de casas decimais a serem consideradas como parte fracion\u00e1ria (centavos)\n #\n # info_unidade (Array) [Opcional; valor padr\u00e3o: ['real', 'reais', GExtenso::GENERO_MASC]] Fornece informa\u00e7\u00f5es sobre a moeda a ser\n # utilizada. O primeiro valor da matriz corresponde ao nome da moeda no singular, o segundo ao nome da moeda no plural e o terceiro\n # ao g\u00eanero gramatical do nome da moeda (GExtenso::GENERO_MASC ou GExtenso::GENERO_FEM)\n #\n # info_fracao (Array) [Opcional; valor padr\u00e3o: ['centavo', 'centavos', GExtenso::GENERO_MASC]] Prov\u00ea informa\u00e7\u00f5es sobre a parte fracion\u00e1ria\n # da moeda. O primeiro valor da matriz corresponde ao nome da parte fracion\u00e1ria no singular, o segundo ao nome da parte fracion\u00e1ria no plural\n # e o terceiro ao g\u00eanero gramatical da parte fracion\u00e1ria (GExtenso::GENERO_MASC ou GExtenso::GENERO_FEM)\n #\n # VALOR DE RETORNO:\n # (String) O valor monet\u00e1rio por extenso\n \n # ----- VALIDA\u00c7\u00c3O DOS PAR\u00c2METROS DE ENTRADA ----\n\n if ! self.is_int(valor)\n raise \"[Exce\u00e7\u00e3o em GExtenso.moeda] Par\u00e2metro 'valor' n\u00e3o \u00e9 num\u00e9rico (recebido: '#{valor}')\"\n\n elsif valor <= 0\n raise \"[Exce\u00e7\u00e3o em GExtenso.moeda] Par\u00e2metro valor igual a ou menor que zero (recebido: '#{valor}')\"\n\n elsif ! self.is_int(casas_decimais) || casas_decimais < 0\n raise \"[Exce\u00e7\u00e3o em GExtenso.moeda] Par\u00e2metro 'casas_decimais' n\u00e3o \u00e9 num\u00e9rico ou \u00e9 menor que zero (recebido: '#{casas_decimais}')\"\n\n elsif info_unidade.class != Array || info_unidade.length < 3\n temp = info_unidade.class == Array ? '[' + info_unidade.join(', ') + ']' : \"'#{info_unidade}'\"\n raise \"[Exce\u00e7\u00e3o em GExtenso.moeda] Par\u00e2metro 'info_unidade' n\u00e3o \u00e9 uma matriz com 3 (tr\u00eas) elementos (recebido: #{temp})\"\n \n elsif info_unidade[POS_GENERO] != GENERO_MASC && info_unidade[POS_GENERO] != GENERO_FEM\n raise \"Exce\u00e7\u00e3o em GExtenso: valor incorreto para o par\u00e2metro 'info_unidade[POS_GENERO]' (recebido: '#{info_unidade[POS_GENERO]}')\"\n\n elsif info_fracao.class != Array || info_fracao.length < 3\n temp = info_fracao.class == Array ? '[' + info_fracao.join(', ') + ']' : \"'#{info_fracao}'\"\n raise \"[Exce\u00e7\u00e3o em GExtenso.moeda] Par\u00e2metro 'info_fracao' n\u00e3o \u00e9 uma matriz com 3 (tr\u00eas) elementos (recebido: #{temp})\"\n \n elsif info_fracao[POS_GENERO] != GENERO_MASC && info_fracao[POS_GENERO] != GENERO_FEM\n raise \"[Exce\u00e7\u00e3o em GExtenso.moeda] valor incorreto para o par\u00e2metro 'info_fracao[POS_GENERO]' (recebido: '#{info_fracao[POS_GENERO]}').\"\n \n end\n\n # -----------------------------------------------\n\n ret = ''\n\n # A parte inteira do valor monet\u00e1rio corresponde ao valor passado dividido por 10 elevado a casas_decimais, desprezado o resto.\n # Assim, com o padr\u00e3o de 2 casas_decimais, o valor ser\u00e1 dividido por 100 (10^2), e o resto \u00e9 descartado utilizando-se floor().\n parte_inteira = valor.floor / (10**casas_decimais)\n\n # A parte fracion\u00e1ria ('centavos'), por seu turno, corresponder\u00e1 ao resto da divis\u00e3o do valor por 10 elevado a casas_decimais.\n # No cen\u00e1rio comum em que trabalhamos com 2 casas_decimais, ser\u00e1 o resto da divis\u00e3o do valor por 100 (10^2).\n fracao = valor % (10**casas_decimais)\n\n # O extenso para a parte_inteira somente ser\u00e1 gerado se esta for maior que zero. Para tanto, utilizamos\n # os pr\u00e9stimos do m\u00e9todo GExtenso::numero().\n if parte_inteira > 0\n ret = self.numero(parte_inteira, info_unidade[POS_GENERO]) + ' '\n ret += parte_inteira == 1 ? info_unidade[NUM_SING] : info_unidade[NUM_PLURAL]\n end\n\n # De forma semelhante, o extenso da fracao somente ser\u00e1 gerado se esta for maior que zero. */\n if fracao > 0\n # Se a parte_inteira for maior que zero, o extenso para ela j\u00e1 ter\u00e1 sido gerado. Antes de juntar os\n # centavos, precisamos colocar o conectivo 'e'.\n if parte_inteira > 0\n ret += ' e '\n end\n ret += self.numero(fracao, info_fracao[POS_GENERO]) + ' '\n ret += parte_inteira == 1 ? info_fracao[NUM_SING] : info_fracao[NUM_PLURAL]\n end\n\n ret\n\n end\n\n ######################################################################################################################################################\n def self.ordinal (valor, genero = GENERO_MASC)\n\n # Gera a representa\u00e7\u00e3o ordinal de um n\u00famero inteiro de 1 \u00e0 1000\n\n # PAR\u00c2METROS:\n # valor (Integer) O valor num\u00e9rico cujo extenso se deseja gerar\n #\n # genero (Integer) [Opcional; valor padr\u00e3o: GExtenso::GENERO_MASC] O g\u00eanero gramatical (GExtenso::GENERO_MASC ou GExtenso::GENERO_FEM)\n # do extenso a ser gerado. Isso possibilita distinguir, por exemplo, entre 'duzentos e dois homens' e 'duzentas e duas mulheres'.\n #\n # VALOR DE RETORNO:\n # (String) O n\u00famero por extenso\n \n # ----- VALIDA\u00c7\u00c3O DOS PAR\u00c2METROS DE ENTRADA ---- \n \n if !is_int(valor)\n raise \"[Exce\u00e7\u00e3o em GExtenso.numero] Par\u00e2metro 'valor' n\u00e3o \u00e9 num\u00e9rico (recebido: '#{valor}')\"\n elsif valor <= 0\n raise \"[Exce\u00e7\u00e3o em GExtenso.numero] Par\u00e2metro 'valor' igual a ou menor que zero (recebido: '#{valor}')\"\n elsif valor > VALOR_MAXIMO\n raise '[Exce\u00e7\u00e3o em GExtenso::numero] Par\u00e2metro ''valor'' deve ser um inteiro entre 1 e ' + VALOR_MAXIMO.to_s + \" (recebido: '#{valor}')\"\n elsif genero != GENERO_MASC && genero != GENERO_FEM\n raise \"Exce\u00e7\u00e3o em GExtenso: valor incorreto para o par\u00e2metro 'genero' (recebido: '#{genero}')\"\n # ------------------------------------------------\n elsif valor >= 1 && valor <= 9\n return UNIDADES_ORDINAL[genero][valor]\n elsif valor >= 10 && valor <= 99\n dezena = valor - (valor % 10)\n resto = valor - dezena\n ret = DEZENAS_ORDINAL[genero][dezena]+\" \"\n if resto > 0 then ret+= self.ordinal(resto,genero); end\n return ret\n elsif valor >= 100 && valor <= 999\n centena = valor - (valor % 100)\n resto = valor - centena \n ret = CENTENAS_ORDINAL[genero][centena]+\" \"\n if resto > 0 then ret += self.ordinal(resto, genero); end\n return ret\n elsif valor == 1000\n return MILHAR_ORDINAL[genero][valor]+\" \"\n end\n end\n\n \nend \n"}, "files_after": {"GExtenso.rb": "#!/usr/bin/env ruby\n\n##############################################################################################################\n# ATEN\u00c7\u00c3O: Este \u00e9 o meu primeiro trabalho na linguagem Ruby. A l\u00f3gica foi originalmente desenvolvida em PHP; #\n# portanto, o estilo do c\u00f3digo pode n\u00e3o agradar programadores Ruby experientes. Estou aberto a cr\u00edticas #\n# construtivas e sugest\u00f5es, para melhorar meu conhecimento na linguagem. #\n##############################################################################################################\n\n# GExtenso class file\n#\n# author Fausto Gon\u00e7alves Cintra (goncin) \n# assitente Leonardo Ostan (lostan) \n# link http://goncin.wordpress.com\n# link http://twitter.com/g0nc1n\n# license http://creativecommons.org/licenses/LGPL/2.1/deed.pt\n#\n\n# GExtenso \u00e9 uma classe que gera a representa\u00e7\u00e3o por extenso de um n\u00famero ou valor monet\u00e1rio.\n#\n# ATEN\u00c7\u00c3O: A P\u00c1GINA DE C\u00d3DIGO DESTE ARQUIVO \u00c9 UTF-8 (Unicode)!\n# \n# Sua implementa\u00e7\u00e3o foi feita como prova de conceito, utilizando:\n# * M\u00e9todos est\u00e1ticos, implementando o padr\u00e3o de projeto (\"design pattern\") SINGLETON;\n# * Chamadas recursivas a m\u00e9todos, minimizando repeti\u00e7\u00f5es e mantendo o c\u00f3digo enxuto; e\n# * Tratamento de erros por interm\u00e9dio de exce\u00e7\u00f5es.\n#\n# = EXEMPLOS DE USO =\n#\n# Para obter o extenso de um n\u00famero, utilize GExtenso.numero.\n# \n# puts GExtenso.numero(832); # oitocentos e trinta e dois\n# puts GExtenso.numero(832, GExtenso::GENERO_FEM) # oitocentas e trinta e duas\n# \n#\n# Para obter o extenso de um valor monet\u00e1rio, utilize GExtenso.moeda.\n# \n# # IMPORTANTE: veja nota sobre o par\u00e2metro 'valor' na documenta\u00e7\u00e3o do m\u00e9todo!\n#\n# puts GExtenso.moeda(15402) # cento e cinquenta e quatro reais e dois centavos\n#\n# puts GExtenso.moeda(47) # quarenta e sete centavos\n#\n# puts GExtenso.moeda(357082, 2,\n# ['peseta', 'pesetas', GExtenso::GENERO_FEM],\n# ['c\u00eantimo', 'c\u00eantimos', GExtenso::GENERO_MASC])\n# # tr\u00eas mil, quinhentas e setenta pesetas e oitenta e dois c\u00eantimos\n#\n# author Fausto Gon\u00e7alves Cintra (goncin) \n# version 0.1 2010-06-10\n \nrequire 'date'\n\nmodule Extenso\n \n NUM_SING = 0\n NUM_PLURAL = 1\n POS_GENERO = 2\n GENERO_MASC = 0\n GENERO_FEM = 1\n \n VALOR_MAXIMO = 999999999\n \n # As unidades 1 e 2 variam em g\u00eanero, pelo que precisamos de dois conjuntos de strings (masculinas e femininas) para as unidades\n UNIDADES = {\n GENERO_MASC => {\n 1 => 'um',\n 2 => 'dois',\n 3 => 'tr\u00eas',\n 4 => 'quatro',\n 5 => 'cinco',\n 6 => 'seis',\n 7 => 'sete',\n 8 => 'oito',\n 9 => 'nove'\n },\n GENERO_FEM => {\n 1 => 'uma',\n 2 => 'duas',\n 3 => 'tr\u00eas',\n 4 => 'quatro',\n 5 => 'cinco',\n 6 => 'seis',\n 7 => 'sete',\n 8 => 'oito',\n 9 => 'nove'\n }\n }\n \n DE11A19 = {\n 11 => 'onze',\n 12 => 'doze',\n 13 => 'treze',\n 14 => 'quatorze',\n 15 => 'quinze',\n 16 => 'dezesseis',\n 17 => 'dezessete',\n 18 => 'dezoito',\n 19 => 'dezenove'\n }\n \n DEZENAS = {\n 10 => 'dez',\n 20 => 'vinte',\n 30 => 'trinta',\n 40 => 'quarenta',\n 50 => 'cinquenta',\n 60 => 'sessenta',\n 70 => 'setenta',\n 80 => 'oitenta',\n 90 => 'noventa'\n }\n \n CENTENA_EXATA = 'cem'\n \n # As centenas, com exce\u00e7\u00e3o de 'cento', tamb\u00e9m variam em g\u00eanero. Aqui tamb\u00e9m se faz\n # necess\u00e1rio dois conjuntos de strings (masculinas e femininas).\n \n CENTENAS = {\n GENERO_MASC => {\n 100 => 'cento',\n 200 => 'duzentos',\n 300 => 'trezentos',\n 400 => 'quatrocentos',\n 500 => 'quinhentos',\n 600 => 'seiscentos',\n 700 => 'setecentos',\n 800 => 'oitocentos',\n 900 => 'novecentos'\n },\n GENERO_FEM => {\n 100 => 'cento',\n 200 => 'duzentas',\n 300 => 'trezentas',\n 400 => 'quatrocentas',\n 500 => 'quinhentas',\n 600 => 'seiscentas',\n 700 => 'setecentas',\n 800 => 'oitocentas',\n 900 => 'novecentas'\n }\n }\n \n #'Mil' \u00e9 invari\u00e1vel, seja em g\u00eanero, seja em n\u00famero\n MILHAR = 'mil'\n\n MILHOES = {\n NUM_SING => 'milh\u00e3o',\n NUM_PLURAL => 'milh\u00f5es'\n }\n\n UNIDADES_ORDINAL = {\n GENERO_MASC => {\n 1 => 'primeiro',\n 2 => 'segundo',\n 3 => 'terceiro',\n 4 => 'quarto',\n 5 => 'quinto',\n 6 => 'sexto',\n 7 => 's\u00e9timo',\n 8 => 'oitavo',\n 9 => 'nono'},\n GENERO_FEM => {\n 1 => 'primeira',\n 2 => 'segunda',\n 3 => 'terceira',\n 4 => 'quarta',\n 5 => 'quinta',\n 6 => 'sexta',\n 7 => 's\u00e9tima',\n 8 => 'oitava',\n 9 => 'nona'}}\n\n DEZENAS_ORDINAL = {\n GENERO_MASC => {\n 10 => 'd\u00e9cimo',\n 20 => 'vig\u00e9simo',\n 30 => 'trig\u00e9simo',\n 40 => 'quadrag\u00e9simo',\n 50 => 'quinquag\u00e9simo',\n 60 => 'sexag\u00e9simo',\n 70 => 'septuag\u00e9simo',\n 80 => 'octog\u00e9simo',\n 90 => 'nonag\u00e9simo'},\n GENERO_FEM => {\n 10 => 'd\u00e9cima',\n 20 => 'vig\u00e9sima',\n 30 => 'trig\u00e9sima',\n 40 => 'quadrag\u00e9sima',\n 50 => 'quinquag\u00e9sima',\n 60 => 'sexag\u00e9sima',\n 70 => 'septuag\u00e9sima',\n 80 => 'octog\u00e9sima',\n 90 => 'nonag\u00e9sima'}}\n \n CENTENAS_ORDINAL = {\n GENERO_MASC => {\n 100 => 'cent\u00e9simo',\n 200 => 'ducent\u00e9simo',\n 300 => 'trecent\u00e9simo',\n 400 => 'quadringent\u00e9simo',\n 500 => 'quingent\u00e9simo',\n 600 => 'seiscent\u00e9simo',\n 700 => 'septingent\u00e9simo',\n 800 => 'octingent\u00e9simo',\n 900 => 'noningent\u00e9simo'},\n GENERO_FEM => {\n 100 => 'cent\u00e9sima',\n 200 => 'ducent\u00e9sima',\n 300 => 'trecent\u00e9sima',\n 400 => 'quadringent\u00e9sima',\n 500 => 'quingent\u00e9sima',\n 600 => 'seiscent\u00e9sima',\n 700 => 'septingent\u00e9sima',\n 800 => 'octingent\u00e9sima',\n 900 => 'noningent\u00e9sima'}}\n \n \n MILHAR_ORDINAL = {\n GENERO_MASC => {\n 1000 => 'mil\u00e9simo'},\n GENERO_FEM =>{\n 1000 => 'mil\u00e9sima'}}\n \n MESES = {\n 1 => 'janeiro',\n 2 => 'fevereiro',\n 3 => 'mar\u00e7o',\n 4 => 'abril',\n 5 => 'maio',\n 6 => 'junho',\n 7 => 'julho',\n 8 => 'agosto',\n 9 => 'setembro',\n 10 =>'outubro',\n 11 =>'novembro',\n 12 =>'dezembro'}\n\n def Extenso.is_int(s)\n Integer(s) != nil rescue false\n end\n \n #######################################################################################################################################\n \n def Extenso.numero (valor, genero = GENERO_MASC)\n\n # Gera a representa\u00e7\u00e3o por extenso de um n\u00famero inteiro, maior que zero e menor ou igual a VALOR_MAXIMO.\n #\n # PAR\u00c2METROS:\n # valor (Integer) O valor num\u00e9rico cujo extenso se deseja gerar\n #\n # genero (Integer) [Opcional; valor padr\u00e3o: GExtenso::GENERO_MASC] O g\u00eanero gramatical (GExtenso::GENERO_MASC ou GExtenso::GENERO_FEM)\n # do extenso a ser gerado. Isso possibilita distinguir, por exemplo, entre 'duzentos e dois homens' e 'duzentas e duas mulheres'.\n #\n # VALOR DE RETORNO:\n # (String) O n\u00famero por extenso incluindo ponto flutuante caso exista\n \n # ----- VALIDA\u00c7\u00c3O DOS PAR\u00c2METROS DE ENTRADA ---- \n if valor < 0\n raise \"[Exce\u00e7\u00e3o em GExtenso.numero] Par\u00e2metro 'valor' igual a ou menor que zero (recebido: '#{valor}')\"\n elsif valor > VALOR_MAXIMO\n raise '[Exce\u00e7\u00e3o em GExtenso::numero] Par\u00e2metro ''valor'' deve ser um inteiro entre 1 e ' + VALOR_MAXIMO.to_s + \" (recebido: '#{valor}')\"\n elsif genero != GENERO_MASC && genero != GENERO_FEM\n raise \"Exce\u00e7\u00e3o em GExtenso: valor incorreto para o par\u00e2metro 'genero' (recebido: '#{genero}')\"\n end\n \n if (valor - Integer(valor)) == 0\n return Extenso.numero_inteiro(Integer(valor))\n else\n flutuante = valor - Integer(valor)\n flutuante = flutuante.round(3)\n zeros = (1..4).detect{|x| 1.0*flutuante*(10**x) >= 1} - 1\n zeros_str = \"\"\n (1..zeros).each {|x| zeros_str << \"zero \"}\n casas = (1..4).detect{|x| 1.0*flutuante*(10**x)%10 == 0} - 1\n return Extenso.numero_inteiro(Integer(valor)) + \" ponto \" + zeros_str + Extenso.numero_inteiro((1.0*(10**casas)*flutuante).to_i)\n end\n end\n\n def Extenso.numero_inteiro(valor, genero = GENERO_MASC) \n if valor == 0\n return \"zero\"\n elsif valor >= 1 && valor <= 9\n UNIDADES[genero][valor]\n \n elsif valor == 10\n DEZENAS[valor]\n\n elsif valor >= 11 && valor <= 19\n DE11A19[valor]\n \n elsif valor >= 20 && valor <= 99\n dezena = valor - (valor % 10)\n ret = DEZENAS[dezena]\n # Chamada recursiva \u00e0 fun\u00e7\u00e3o para processar resto se este for maior que zero.\n # O conectivo 'e' \u00e9 utilizado entre dezenas e unidades.\n resto = valor - dezena\n if resto > 0\n ret += ' e ' + Extenso.numero(resto, genero)\n end\n ret\n\n elsif valor == 100 \n CENTENA_EXATA\n\n elsif valor >= 101 && valor <= 999\n centena = valor - (valor % 100)\n ret = CENTENAS[genero][centena] # As centenas (exceto 'cento') variam em g\u00eanero\n # Chamada recursiva \u00e0 fun\u00e7\u00e3o para processar resto se este for maior que zero.\n # O conectivo 'e' \u00e9 utilizado entre centenas e dezenas.\n resto = valor - centena \n if resto > 0\n ret += ' e ' + Extenso.numero(resto, genero)\n end\n ret\n\n elsif valor >= 1000 && valor <= 999999\n # A fun\u00e7\u00e3o 'floor' \u00e9 utilizada para encontrar o inteiro da divis\u00e3o de valor por 1000,\n # assim determinando a quantidade de milhares. O resultado \u00e9 enviado a uma chamada recursiva\n # da fun\u00e7\u00e3o. A palavra 'mil' n\u00e3o se flexiona.\n milhar = (valor / 1000).floor\n ret = Extenso.numero(milhar, GENERO_MASC) + ' ' + MILHAR # 'Mil' \u00e9 do g\u00eanero masculino\n resto = valor % 1000\n # Chamada recursiva \u00e0 fun\u00e7\u00e3o para processar resto se este for maior que zero.\n # O conectivo 'e' \u00e9 utilizado entre milhares e n\u00fameros entre 1 e 99, bem como antes de centenas exatas.\n if resto > 0 && ((resto >= 1 && resto <= 99) || resto % 100 == 0)\n ret += ' e ' + Extenso.numero(resto, genero)\n # Nos demais casos, ap\u00f3s o milhar \u00e9 utilizada a v\u00edrgula.\n elsif (resto > 0)\n ret += ', ' + Extenso.numero(resto, genero)\n end\n ret\n\n elsif valor >= 100000 && valor <= VALOR_MAXIMO\n # A fun\u00e7\u00e3o 'floor' \u00e9 utilizada para encontrar o inteiro da divis\u00e3o de valor por 1000000,\n # assim determinando a quantidade de milh\u00f5es. O resultado \u00e9 enviado a uma chamada recursiva\n # da fun\u00e7\u00e3o. A palavra 'milh\u00e3o' flexiona-se no plural.\n milhoes = (valor / 1000000).floor\n ret = Extenso.numero(milhoes, GENERO_MASC) + ' ' # Milh\u00e3o e milh\u00f5es s\u00e3o do g\u00eanero masculino\n \n # Se a o n\u00famero de milh\u00f5es for maior que 1, deve-se utilizar a forma flexionada no plural\n ret += milhoes == 1 ? MILHOES[NUM_SING] : MILHOES[NUM_PLURAL]\n\n resto = valor % 1000000\n\n # Chamada recursiva \u00e0 fun\u00e7\u00e3o para processar resto se este for maior que zero.\n # O conectivo 'e' \u00e9 utilizado entre milh\u00f5es e n\u00fameros entre 1 e 99, bem como antes de centenas exatas.\n if resto && ((resto >= 1 && resto <= 99) || resto % 100 == 0)\n ret += ' e ' + Extenso.numero(resto, genero)\n # Nos demais casos, ap\u00f3s o milh\u00e3o \u00e9 utilizada a v\u00edrgula.\n elsif resto > 0\n ret += ', ' + Extenso.numero(resto, genero)\n end\n ret\n\n end\n \n end\n \n #######################################################################################################################################\n \n def Extenso.moeda(\n valor,\n casas_decimais = 2,\n info_unidade = ['real', 'reais', GENERO_MASC],\n info_fracao = ['centavo', 'centavos', GENERO_MASC]\n ) \n \n # Gera a representa\u00e7\u00e3o por extenso de um valor monet\u00e1rio, maior que zero e menor ou igual a GExtenso::VALOR_MAXIMO.\n #\n #\n # PAR\u00c2METROS:\n # valor (Integer) O valor monet\u00e1rio cujo extenso se deseja gerar.\n # ATEN\u00c7\u00c3O: PARA EVITAR OS CONHECIDOS PROBLEMAS DE ARREDONDAMENTO COM N\u00daMEROS DE PONTO FLUTUANTE, O VALOR DEVE SER PASSADO\n # J\u00c1 DEVIDAMENTE MULTIPLICADO POR 10 ELEVADO A $casasDecimais (o que equivale, normalmente, a passar o valor com centavos\n # multiplicado por 100)\n #\n # casas_decimais (Integer) [Opcional; valor padr\u00e3o: 2] N\u00famero de casas decimais a serem consideradas como parte fracion\u00e1ria (centavos)\n #\n # info_unidade (Array) [Opcional; valor padr\u00e3o: ['real', 'reais', GExtenso::GENERO_MASC]] Fornece informa\u00e7\u00f5es sobre a moeda a ser\n # utilizada. O primeiro valor da matriz corresponde ao nome da moeda no singular, o segundo ao nome da moeda no plural e o terceiro\n # ao g\u00eanero gramatical do nome da moeda (GExtenso::GENERO_MASC ou GExtenso::GENERO_FEM)\n #\n # info_fracao (Array) [Opcional; valor padr\u00e3o: ['centavo', 'centavos', GExtenso::GENERO_MASC]] Prov\u00ea informa\u00e7\u00f5es sobre a parte fracion\u00e1ria\n # da moeda. O primeiro valor da matriz corresponde ao nome da parte fracion\u00e1ria no singular, o segundo ao nome da parte fracion\u00e1ria no plural\n # e o terceiro ao g\u00eanero gramatical da parte fracion\u00e1ria (GExtenso::GENERO_MASC ou GExtenso::GENERO_FEM)\n #\n # VALOR DE RETORNO:\n # (String) O valor monet\u00e1rio por extenso\n \n # ----- VALIDA\u00c7\u00c3O DOS PAR\u00c2METROS DE ENTRADA ----\n if ! Extenso.is_int(valor)\n raise \"[Exce\u00e7\u00e3o em GExtenso.moeda] Par\u00e2metro 'valor' n\u00e3o \u00e9 num\u00e9rico (recebido: '#{valor}')\"\n\n elsif valor < 0\n raise \"[Exce\u00e7\u00e3o em GExtenso.moeda] Par\u00e2metro valor igual a ou menor que zero (recebido: '#{valor}')\"\n\n elsif ! Extenso.is_int(casas_decimais) || casas_decimais < 0\n raise \"[Exce\u00e7\u00e3o em GExtenso.moeda] Par\u00e2metro 'casas_decimais' n\u00e3o \u00e9 num\u00e9rico ou \u00e9 menor que zero (recebido: '#{casas_decimais}')\"\n\n elsif info_unidade.class != Array || info_unidade.length < 3\n temp = info_unidade.class == Array ? '[' + info_unidade.join(', ') + ']' : \"'#{info_unidade}'\"\n raise \"[Exce\u00e7\u00e3o em GExtenso.moeda] Par\u00e2metro 'info_unidade' n\u00e3o \u00e9 uma matriz com 3 (tr\u00eas) elementos (recebido: #{temp})\"\n \n elsif info_unidade[POS_GENERO] != GENERO_MASC && info_unidade[POS_GENERO] != GENERO_FEM\n raise \"Exce\u00e7\u00e3o em GExtenso: valor incorreto para o par\u00e2metro 'info_unidade[POS_GENERO]' (recebido: '#{info_unidade[POS_GENERO]}')\"\n\n elsif info_fracao.class != Array || info_fracao.length < 3\n temp = info_fracao.class == Array ? '[' + info_fracao.join(', ') + ']' : \"'#{info_fracao}'\"\n raise \"[Exce\u00e7\u00e3o em GExtenso.moeda] Par\u00e2metro 'info_fracao' n\u00e3o \u00e9 uma matriz com 3 (tr\u00eas) elementos (recebido: #{temp})\"\n \n elsif info_fracao[POS_GENERO] != GENERO_MASC && info_fracao[POS_GENERO] != GENERO_FEM\n raise \"[Exce\u00e7\u00e3o em GExtenso.moeda] valor incorreto para o par\u00e2metro 'info_fracao[POS_GENERO]' (recebido: '#{info_fracao[POS_GENERO]}').\"\n elsif valor == 0\n return \"zero reais\"\n end\n\n # -----------------------------------------------\n\n ret = ''\n\n # A parte inteira do valor monet\u00e1rio corresponde ao valor passado dividido por 10 elevado a casas_decimais, desprezado o resto.\n # Assim, com o padr\u00e3o de 2 casas_decimais, o valor ser\u00e1 dividido por 100 (10^2), e o resto \u00e9 descartado utilizando-se floor().\n parte_inteira = valor.floor / (10**casas_decimais)\n\n # A parte fracion\u00e1ria ('centavos'), por seu turno, corresponder\u00e1 ao resto da divis\u00e3o do valor por 10 elevado a casas_decimais.\n # No cen\u00e1rio comum em que trabalhamos com 2 casas_decimais, ser\u00e1 o resto da divis\u00e3o do valor por 100 (10^2).\n fracao = valor % (10**casas_decimais)\n\n # O extenso para a parte_inteira somente ser\u00e1 gerado se esta for maior que zero. Para tanto, utilizamos\n # os pr\u00e9stimos do m\u00e9todo GExtenso::numero().\n if parte_inteira > 0\n ret = Extenso.numero(parte_inteira, info_unidade[POS_GENERO]) + ' '\n ret += parte_inteira == 1 ? info_unidade[NUM_SING] : info_unidade[NUM_PLURAL]\n end\n\n # De forma semelhante, o extenso da fracao somente ser\u00e1 gerado se esta for maior que zero. */\n if fracao > 0\n # Se a parte_inteira for maior que zero, o extenso para ela j\u00e1 ter\u00e1 sido gerado. Antes de juntar os\n # centavos, precisamos colocar o conectivo 'e'.\n if parte_inteira > 0\n ret += ' e '\n end\n ret += Extenso.numero(fracao, info_fracao[POS_GENERO]) + ' '\n ret += parte_inteira == 1 ? info_fracao[NUM_SING] : info_fracao[NUM_PLURAL]\n end\n\n ret\n\n end\n######################################################################################################################################################\n def Extenso.data(data)\n # Escreve uma data por extenso\n # A variavel data \u00e9 um objeto da classe Date\n # Uso esta classe porque ela d\u00e1 suporte \u00e0 opera\u00e7\u00f5es elementares com datas e mant\u00e9m a consist\u00eancia nos sistemas que estou programando\n # VALOR DE RETORNO: \n # (String) A data escrita por extenso\n # Exemplo: GExtenso.data(Date.parse \"23/12/1983\") ==> \"vinte e tr\u00eas de dezembro de mil novecentos e oitenta e tr\u00eas\"\n %Q{#{Extenso.numero(data.day)} de #{MESES[data.month]} de #{Extenso.numero(data.year)}}\n end\n\n######################################################################################################################################################\n def Extenso.ordinal (valor, genero = GENERO_MASC)\n\n # Gera a representa\u00e7\u00e3o ordinal de um n\u00famero inteiro de 1 \u00e0 1000\n\n # PAR\u00c2METROS:\n # valor (Integer) O valor num\u00e9rico cujo extenso se deseja gerar\n #\n # genero (Integer) [Opcional; valor padr\u00e3o: GExtenso::GENERO_MASC] O g\u00eanero gramatical (GExtenso::GENERO_MASC ou GExtenso::GENERO_FEM)\n # do extenso a ser gerado. Isso possibilita distinguir, por exemplo, entre 'duzentos e dois homens' e 'duzentas e duas mulheres'.\n #\n # VALOR DE RETORNO:\n # (String) O n\u00famero por extenso\n \n # ----- VALIDA\u00c7\u00c3O DOS PAR\u00c2METROS DE ENTRADA ---- \n \n if !is_int(valor)\n raise \"[Exce\u00e7\u00e3o em GExtenso.numero] Par\u00e2metro 'valor' n\u00e3o \u00e9 num\u00e9rico (recebido: '#{valor}')\"\n elsif valor <= 0\n raise \"[Exce\u00e7\u00e3o em GExtenso.numero] Par\u00e2metro 'valor' igual a ou menor que zero (recebido: '#{valor}')\"\n elsif valor > VALOR_MAXIMO\n raise '[Exce\u00e7\u00e3o em GExtenso::numero] Par\u00e2metro ''valor'' deve ser um inteiro entre 1 e ' + VALOR_MAXIMO.to_s + \" (recebido: '#{valor}')\"\n elsif genero != GENERO_MASC && genero != GENERO_FEM\n raise \"Exce\u00e7\u00e3o em GExtenso: valor incorreto para o par\u00e2metro 'genero' (recebido: '#{genero}')\"\n # ------------------------------------------------\n elsif valor >= 1 && valor <= 9\n return UNIDADES_ORDINAL[genero][valor]\n elsif valor >= 10 && valor <= 99\n dezena = valor - (valor % 10)\n resto = valor - dezena\n ret = DEZENAS_ORDINAL[genero][dezena]+\" \"\n if resto > 0 then ret+= Extenso.ordinal(resto,genero); end\n return ret\n elsif valor >= 100 && valor <= 999\n centena = valor - (valor % 100)\n resto = valor - centena \n ret = CENTENAS_ORDINAL[genero][centena]+\" \"\n if resto > 0 then ret += Extenso.ordinal(resto, genero); end\n return ret\n elsif valor == 1000\n return MILHAR_ORDINAL[genero][valor]+\" \"\n end\n end\n\n def Extenso.moeda_real(numero)\n unit = \"R$\"\n separator = \",\"\n delimiter = \".\"\n mystring = sprintf(\"%s %.2f\",unit, numero)\n mystring = mystring.gsub(\".\",separator)\n pos = mystring.match(separator).begin(0) - 3\n while !(/[0-9]/.match(mystring[pos-1])== nil) do\n mystring.insert(pos,delimiter)\n pos-=3\n end \n return mystring\n end\n\n def Extenso.to_cash(numero)\n unit = \"R$\"\n separator = \",\"\n delimiter = \".\"\n mystring = sprintf(\"%s %.2f\",unit, numero)\n mystring = mystring.gsub(\".\",separator)\n pos = mystring.match(separator).begin(0) - 3\n while !(/[0-9]/.match(mystring[pos-1])== nil) do\n mystring.insert(pos,delimiter)\n pos-=3\n end \n return mystring << \" (\" << Extenso.moeda((numero*100).to_i) << \")\"\n end \n \nend "}} -{"repo": "pegjs/website", "pr_number": 10, "title": "Small website improvements", "state": "closed", "merged_at": null, "additions": 4, "deletions": 34, "files_changed": ["public/css/content.css", "public/js/online.js"], "files_before": {"public/css/content.css": "#content h1 { margin: 0 0 .75em 0; font-size: 200%; }\n#content h2 {\n margin: 1.5em 0 .75em 0; border-bottom: 2pt dotted silver;\n font-size: 150%;\n}\n#content h3 { margin: 1.5em 0 .5em 0; font-size: 125%; }\n#content li { margin: .5em 0; }\n#content dt { font-weight: bold; }\n#content dd { margin-top: 1em; margin-bottom: 1em; }\n#content aside.info { margin: 1em 0 1em 2em; color: gray; }\n#content pre {\n overflow: auto;\n padding: .5em 1em; border-left: 5px solid silver;\n background-color: #f0f0f0;\n}\n#content table { border-spacing: 0; }\n#content a, #content a:visited { color: #3d586c; }\n\n#content .center { text-align: center; }\n\n/* Home */\n\n#content #sidebar {\n float: right; width: 17em;\n font-size: 80%; text-align: center;\n}\n#content #sidebar a {\n font-weight: bold; text-decoration: none;\n color: #006000;\n}\n#content #sidebar a:hover { text-decoration: underline; }\n#content #sidebar a.try {\n display: block;\n padding: .75em; border-radius: .6em; -moz-border-radius: .6em;\n font-size: 140%;\n color: #e0ffe0; background-color: #499149;\n}\n#content #sidebar a.try:hover {\n text-decoration: none; background-color: #006000;\n}\n#content #sidebar .npm {\n padding: .75em; border: 1px solid #499149; border-radius: .7em; -moz-border-radius: .7em;\n font-family: \"Lucida Console\", fixed, monospace; font-size: 120%;\n color: #2c572c; background-color: #e0ffe0;\n}\n#content #sidebar .label { margin-left: 2.6em; text-align: left; color: #606060; }\n#content #sidebar #download {\n list-style: square;\n padding-left: 2em;\n color: gray;\n text-align: left;\n font-size: 120%;\n}\n#content #sidebar a.twitter { display:block; margin-top: 5em; }\n#content #sidebar .separator { color: gray; margin: 1.5em 0 1em 0; }\n\n#content #left-column { margin-right: 17em; }\n\n/* Online Version */\n\n#content .message {\n border-radius: .5em; -moz-border-radius: .5em; padding: .5em 1em;\n}\n#content .message.info { background-color: #c0ffc0; }\n#content .message.info a.download { display: block; float: right; }\n#content .message.info .size-and-time { visibility: hidden; float: right; font-size: 70%; margin: .3em 0; color: #80c080; }\n#content .message.info:hover .size-and-time { visibility: visible; }\n#content .message.error { background-color: orange; }\n#content .message.progress {\n padding-left: 40px;\n /* Spinner image generated by http://www.loadinfo.net/. */\n background: #ffff80 url(\"../img/spinner-16x16-progress.gif\") 14px center no-repeat;\n}\n#content .message.disabled { color: gray; background-color: #f0f0f0; }\n\n#content table.form { width: 100%; }\n#content table.form td, table.form th { padding: .5em 1em; }\n#content table.form td:first-child, table.form th:first-child { padding-left: 0; }\n#content table.form td:last-child, table.form th:last-child { padding-right: 0; }\n#content table.form th { text-align: left; font-weight: normal; }\n\n#content h2.suggestion { border: none; }\n#content h2.suggestion.top { margin-top: 0; }\n#content h2.suggestion .step-number {\n display: block; float: left;\n width: 1.5em;\n border-radius: .4em; -moz-border-radius: .4em;\n text-align: center;\n color: white; background-color: black;\n}\n#content h2.suggestion .step-title { margin-left: 2.5em; }\n\n#content textarea.code { width: 100%; height: 20em; font-family: \"Lucida Console\", fixed, monospace; }\n\n#content .textarea-wrapper { padding-right: 6px; }\n\n#content .tooltip { position: absolute; display: none; }\n#content .tooltip .content {\n padding: .5em 1em;\n box-shadow: .25em .25em .5em rgba(0, 0, 0, 0.25); -webkit-box-shadow: .25em .25em .5em rgba(0, 0, 0, 0.25); -moz-box-shadow: .25em .25em .5em rgba(0, 0, 0, 0.25);\n border-radius: .5em; -moz-border-radius: .5em;\n padding: .5em 1em;\n color: white; background-color: black;\n font-size: 80%;\n}\n#content .tooltip .arrow {\n height: 6px;\n background: url(\"../img/tooltip-arrow.png\") top center no-repeat;\n}\n\n#content #columns { width: 100%; height: 100%; border-spacing: 1em; }\n#content #columns td { width: 50%; }\n\n#content table.column { width: 100%; height: 100%; }\n#content table.column td { vertical-align: top; }\n/* Browsers will enlarge the |.content-height| cells to fit the contents. */\n#content table.column td.content-height { height: 1px; }\n\n#content #output-header {\n margin: 1.25em 0 0 0; border: none; padding: .25em 1.2em .25em 1.2em;\n font-size: 80%;\n color: white; background-color: silver;\n}\n#content #output {\n overflow: auto;\n max-height: 20em;\n margin: 0; padding: .5em 1em; border: 2px solid silver; border-top: none;\n background-color: #f0f0f0;\n}\n#content #output.disabled { color: gray; }\n\n#content #settings { padding: .5em 0; }\n#content #settings label { padding-right: 1em; }\n#content #settings label[for=option-optimize] { padding-left: 2em; }\n#content #parser-var { width: 15em; }\n#content #options { padding-top: 1em; }\n#content #parser-download {\n float: right;\n width: 9em;\n margin-top: 2em;\n padding: .5em; border-radius: .4em; -moz-border-radius: .4em;\n text-align: center; text-decoration: none;\n color: #e0ffe0; background-color: #499149;\n}\n#content #parser-download:hover { background-color: #006000; }\n#content #parser-download.disabled { color: #e0e0e0; background-color: gray; }\n", "public/js/online.js": "$(document).ready(function() {\n var KB = 1024;\n var MS_IN_S = 1000;\n\n var parser;\n\n var buildAndParseTimer = null;\n var parseTimer = null;\n\n var oldGrammar = null;\n var oldParserVar = null;\n var oldOptionCache = null;\n var oldOptionOptimize = null;\n var oldInput = null;\n\n function buildSizeAndTimeInfoHtml(title, size, time) {\n return $(\"\", {\n \"class\": \"size-and-time\",\n title: title,\n html: (size / KB).toPrecision(2) + \" kB, \"\n + time + \" ms, \"\n + ((size / KB) / (time / MS_IN_S)).toPrecision(2) + \" kB/s\"\n });\n }\n\n function buildErrorMessage(e) {\n return e.line !== undefined && e.column !== undefined\n ? \"Line \" + e.line + \", column \" + e.column + \": \" + e.message\n : e.message;\n }\n\n function build() {\n oldGrammar = $(\"#grammar\").val();\n oldParserVar = $(\"#parser-var\").val();\n oldOptionCache = $(\"#option-cache\").is(\":checked\");\n oldOptionOptimize = $(\"#option-optimize\").val();\n\n $('#build-message').attr(\"class\", \"message progress\").text(\"Building the parser...\");\n $(\"#input\").attr(\"disabled\", \"disabled\");\n $(\"#parse-message\").attr(\"class\", \"message disabled\").text(\"Parser not available.\");\n $(\"#output\").addClass(\"disabled\").text(\"Output not available.\");\n $(\"#parser-var\").attr(\"disabled\", \"disabled\");\n $(\"#option-cache\").attr(\"disabled\", \"disabled\");\n $(\"#option-optimize\").attr(\"disabled\", \"disabled\");\n $(\"#parser-download\").addClass(\"disabled\");\n\n try {\n var timeBefore = (new Date).getTime();\n var parserSource = PEG.buildParser($(\"#grammar\").val(), {\n cache: $(\"#option-cache\").is(\":checked\"),\n optimize: $(\"#option-optimize\").val(),\n output: \"source\"\n });\n var timeAfter = (new Date).getTime();\n\n parser = eval(parserSource);\n\n $(\"#build-message\")\n .attr(\"class\", \"message info\")\n .html(\"Parser built successfully.\")\n .append(buildSizeAndTimeInfoHtml(\n \"Parser build time and speed\",\n $(\"#grammar\").val().length,\n timeAfter - timeBefore\n ));\n var parserUrl = \"data:text/plain;charset=utf-8;base64,\"\n + Base64.encode($(\"#parser-var\").val() + \" = \" + parserSource + \";\\n\");\n $(\"#input\").removeAttr(\"disabled\");\n $(\"#parser-var\").removeAttr(\"disabled\");\n $(\"#option-cache\").removeAttr(\"disabled\");\n $(\"#option-optimize\").removeAttr(\"disabled\");\n $(\"#parser-download\").removeClass(\"disabled\").attr(\"href\", parserUrl);\n\n var result = true;\n } catch (e) {\n $(\"#build-message\").attr(\"class\", \"message error\").text(buildErrorMessage(e));\n var parserUrl = \"data:text/plain;charset=utf-8;base64,\"\n + Base64.encode(\"Parser not available.\");\n $(\"#parser-download\").attr(\"href\", parserUrl);\n\n var result = false;\n }\n\n doLayout();\n return result;\n }\n\n function parse() {\n oldInput = $(\"#input\").val();\n\n $(\"#input\").removeAttr(\"disabled\");\n $(\"#parse-message\").attr(\"class\", \"message progress\").text(\"Parsing the input...\");\n $(\"#output\").addClass(\"disabled\").text(\"Output not available.\");\n\n try {\n var timeBefore = (new Date).getTime();\n var output = parser.parse($(\"#input\").val());\n var timeAfter = (new Date).getTime();\n\n $(\"#parse-message\")\n .attr(\"class\", \"message info\")\n .text(\"Input parsed successfully.\")\n .append(buildSizeAndTimeInfoHtml(\n \"Parsing time and speed\",\n $(\"#input\").val().length,\n timeAfter - timeBefore\n ));\n $(\"#output\").removeClass(\"disabled\").text(jsDump.parse(output));\n\n var result = true;\n } catch (e) {\n $(\"#parse-message\").attr(\"class\", \"message error\").text(buildErrorMessage(e));\n\n var result = false;\n }\n\n doLayout();\n return result;\n }\n\n function buildAndParse() {\n build() && parse();\n }\n\n function scheduleBuildAndParse() {\n var nothingChanged = $(\"#grammar\").val() === oldGrammar\n && $(\"#parser-var\").val() === oldParserVar\n && $(\"#option-cache\").is(\":checked\") === oldOptionCache\n && $(\"#option-optimize\").val() === oldOptionOptimize;\n if (nothingChanged) { return; }\n\n if (buildAndParseTimer !== null) {\n clearTimeout(buildAndParseTimer);\n buildAndParseTimer = null;\n }\n if (parseTimer !== null) {\n clearTimeout(parseTimer);\n parseTimer = null;\n }\n\n buildAndParseTimer = setTimeout(function() {\n buildAndParse();\n buildAndParseTimer = null;\n }, 500);\n }\n\n function scheduleParse() {\n if ($(\"#input\").val() === oldInput) { return; }\n if (buildAndParseTimer !== null) { return; }\n\n if (parseTimer !== null) {\n clearTimeout(parseTimer);\n parseTimer = null;\n }\n\n parseTimer = setTimeout(function() {\n parse();\n parseTimer = null;\n }, 500);\n }\n\n function doLayout() {\n /*\n * This forces layout of the page so that the |#columns| table gets a chance\n * make itself smaller when the browser window shrinks.\n */\n if ($.browser.msie || $.browser.opera) {\n $(\"#left-column\").height(\"0px\");\n $(\"#right-column\").height(\"0px\");\n }\n $(\"#grammar\").height(\"0px\");\n $(\"#input\").height(\"0px\");\n\n if ($.browser.msie || $.browser.opera) {\n $(\"#left-column\").height(($(\"#left-column\").parent().innerHeight() - 2) + \"px\");\n $(\"#right-column\").height(($(\"#right-column\").parent().innerHeight() - 2) + \"px\");\n }\n\n $(\"#grammar\").height(($(\"#grammar\").parent().parent().innerHeight() - 14) + \"px\");\n $(\"#input\").height(($(\"#input\").parent().parent().innerHeight() - 14) + \"px\");\n }\n\n $(\"#grammar, #parser-var, #option-cache, #option-optimize\")\n .change(scheduleBuildAndParse)\n .mousedown(scheduleBuildAndParse)\n .mouseup(scheduleBuildAndParse)\n .click(scheduleBuildAndParse)\n .keydown(scheduleBuildAndParse)\n .keyup(scheduleBuildAndParse)\n .keypress(scheduleBuildAndParse);\n\n $(\"#input\")\n .change(scheduleParse)\n .mousedown(scheduleParse)\n .mouseup(scheduleParse)\n .click(scheduleParse)\n .keydown(scheduleParse)\n .keyup(scheduleParse)\n .keypress(scheduleParse);\n\n doLayout();\n $(window).resize(doLayout);\n\n $(\"#loader\").hide();\n $(\"#content\").show();\n\n $(\"#grammar, #parser-var, #option-cache, #option-optimize\").removeAttr(\"disabled\");\n\n $(\"#grammar, #input\").focus(function() {\n var textarea = $(this);\n\n setTimeout(function() {\n textarea.unbind(\"focus\");\n\n var tooltip = textarea.next();\n var position = textarea.position();\n\n tooltip.css({\n top: (position.top - tooltip.outerHeight() - 5) + \"px\",\n left: (position.left + textarea.outerWidth() - tooltip.outerWidth()) + \"px\"\n }).fadeTo(400, 0.8).delay(3000).fadeOut();\n }, 1000);\n });\n\n $(\"#grammar\").focus();\n\n buildAndParse();\n});\n"}, "files_after": {"public/css/content.css": "#content h1 { margin: 0 0 .75em 0; font-size: 200%; }\n#content h2 {\n margin: 1.5em 0 .75em 0; border-bottom: 2pt dotted silver;\n font-size: 150%;\n}\n#content h3 { margin: 1.5em 0 .5em 0; font-size: 125%; }\n#content li { margin: .5em 0; }\n#content dt { font-weight: bold; }\n#content dd { margin-top: 1em; margin-bottom: 1em; }\n#content aside.info { margin: 1em 0 1em 2em; color: gray; }\n#content pre {\n overflow: auto;\n padding: .5em 1em; border-left: 5px solid silver;\n background-color: #f0f0f0;\n}\n#content table { border-spacing: 0; }\n#content a, #content a:visited { color: #3d586c; }\n\n#content .center { text-align: center; }\n\n/* Home */\n\n#content #sidebar {\n float: right; width: 17em;\n font-size: 80%; text-align: center;\n}\n#content #sidebar a {\n font-weight: bold; text-decoration: none;\n color: #006000;\n}\n#content #sidebar a:hover { text-decoration: underline; }\n#content #sidebar a.try {\n display: block;\n padding: .75em; border-radius: .6em; -moz-border-radius: .6em;\n font-size: 140%;\n color: #e0ffe0; background-color: #499149;\n}\n#content #sidebar a.try:hover {\n text-decoration: none; background-color: #006000;\n}\n#content #sidebar .npm {\n padding: .75em; border: 1px solid #499149; border-radius: .7em; -moz-border-radius: .7em;\n font-family: \"Lucida Console\", fixed, monospace; font-size: 120%;\n color: #2c572c; background-color: #e0ffe0;\n}\n#content #sidebar .label { margin-left: 2.6em; text-align: left; color: #606060; }\n#content #sidebar #download {\n list-style: square;\n padding-left: 2em;\n color: gray;\n text-align: left;\n font-size: 120%;\n}\n#content #sidebar a.twitter { display:block; margin-top: 5em; }\n#content #sidebar .separator { color: gray; margin: 1.5em 0 1em 0; }\n\n#content #left-column { margin-right: 17em; }\n\n/* Online Version */\n\n#content .message {\n border-radius: .5em; -moz-border-radius: .5em; padding: .5em 1em;\n}\n#content .message.info { background-color: #c0ffc0; }\n#content .message.info a.download { display: block; float: right; }\n#content .message.info .size-and-time { visibility: hidden; float: right; font-size: 70%; margin: .3em 0; color: #80c080; }\n#content .message.info:hover .size-and-time { visibility: visible; }\n#content .message.error { background-color: orange; }\n#content .message.progress {\n padding-left: 40px;\n /* Spinner image generated by http://www.loadinfo.net/. */\n background: #ffff80 url(\"../img/spinner-16x16-progress.gif\") 14px center no-repeat;\n}\n#content .message.disabled { color: gray; background-color: #f0f0f0; }\n\n#content table.form { width: 100%; }\n#content table.form td, table.form th { padding: .5em 1em; }\n#content table.form td:first-child, table.form th:first-child { padding-left: 0; }\n#content table.form td:last-child, table.form th:last-child { padding-right: 0; }\n#content table.form th { text-align: left; font-weight: normal; }\n\n#content h2.suggestion { border: none; }\n#content h2.suggestion.top { margin-top: 0; }\n#content h2.suggestion .step-number {\n display: block; float: left;\n width: 1.5em;\n border-radius: .4em; -moz-border-radius: .4em;\n text-align: center;\n color: white; background-color: black;\n}\n#content h2.suggestion .step-title { margin-left: 2.5em; }\n\n#content textarea.code { width: 100%; height: 20em; font-family: \"Lucida Console\", fixed, monospace; }\n\n#content .textarea-wrapper { padding-right: 6px; }\n\n#content #columns { width: 100%; height: 100%; border-spacing: 1em; }\n#content #columns td { width: 50%; }\n\n#content table.column { width: 100%; height: 100%; }\n#content table.column td { vertical-align: top; }\n/* Browsers will enlarge the |.content-height| cells to fit the contents. */\n#content table.column td.content-height { height: 1px; }\n\n#content #output-header {\n margin: 1.25em 0 0 0; border: none; padding: .25em 1.2em .25em 1.2em;\n font-size: 80%;\n color: white; background-color: silver;\n}\n#content #output {\n overflow: auto;\n max-height: 20em;\n margin: 0; padding: .5em 1em; border: 2px solid silver; border-top: none;\n background-color: #f0f0f0;\n}\n#content #output.disabled { color: gray; }\n\n#content #settings { padding: .5em 0; }\n#content #settings label { padding-right: 1em; }\n#content #parser-var { width: 15em; }\n#content #options { padding-top: 1em; }\n#content #parser-download {\n float: right;\n width: 9em;\n margin-top: 2em;\n padding: .5em; border-radius: .4em; -moz-border-radius: .4em;\n text-align: center; text-decoration: none;\n color: #e0ffe0; background-color: #499149;\n}\n#content #parser-download:hover { background-color: #006000; }\n#content #parser-download.disabled { color: #e0e0e0; background-color: gray; }\n", "public/js/online.js": "$(document).ready(function() {\n var KB = 1024;\n var MS_IN_S = 1000;\n\n var parser;\n\n var buildAndParseTimer = null;\n var parseTimer = null;\n\n var oldGrammar = null;\n var oldParserVar = null;\n var oldOptionCache = null;\n var oldOptionTrackLineAndColumn = null;\n var oldInput = null;\n\n function buildSizeAndTimeInfoHtml(title, size, time) {\n return $(\"\", {\n \"class\": \"size-and-time\",\n title: title,\n html: (size / KB).toPrecision(2) + \" kB, \"\n + time + \" ms, \"\n + ((size / KB) / (time / MS_IN_S)).toPrecision(2) + \" kB/s\"\n });\n }\n\n function buildErrorMessage(e) {\n return e.line !== undefined && e.column !== undefined\n ? \"Line \" + e.line + \", column \" + e.column + \": \" + e.message\n : e.message;\n }\n\n function build() {\n oldGrammar = $(\"#grammar\").val();\n oldParserVar = $(\"#parser-var\").val();\n oldOptionCache = $(\"#option-cache\").is(\":checked\"),\n oldOptionTrackLineAndColumn = $(\"#option-track-line-and-column\").is(\":checked\")\n\n $('#build-message').attr(\"class\", \"message progress\").text(\"Building the parser...\");\n $(\"#input\").attr(\"disabled\", \"disabled\");\n $(\"#parse-message\").attr(\"class\", \"message disabled\").text(\"Parser not available.\");\n $(\"#output\").addClass(\"disabled\").text(\"Output not available.\");\n $(\"#parser-var\").attr(\"disabled\", \"disabled\");\n $(\"#option-cache\").attr(\"disabled\", \"disabled\");\n $(\"#option-track-line-and-column\").attr(\"disabled\", \"disabled\");\n $(\"#parser-download\").addClass(\"disabled\");\n\n try {\n var timeBefore = (new Date).getTime();\n parser = PEG.buildParser($(\"#grammar\").val(), {\n cache: $(\"#option-cache\").is(\":checked\"),\n trackLineAndColumn: $(\"#option-track-line-and-column\").is(\":checked\")\n });\n var timeAfter = (new Date).getTime();\n\n $(\"#build-message\")\n .attr(\"class\", \"message info\")\n .html(\"Parser built successfully.\")\n .append(buildSizeAndTimeInfoHtml(\n \"Parser build time and speed\",\n $(\"#grammar\").val().length,\n timeAfter - timeBefore\n ));\n var parserUrl = \"data:text/plain;charset=utf-8;base64,\"\n + Base64.encode($(\"#parser-var\").val() + \" = \" + parser.toSource() + \";\\n\");\n $(\"#input\").removeAttr(\"disabled\");\n $(\"#parser-var\").removeAttr(\"disabled\");\n $(\"#option-cache\").removeAttr(\"disabled\");\n $(\"#option-track-line-and-column\").removeAttr(\"disabled\");\n $(\"#parser-download\").removeClass(\"disabled\").attr(\"href\", parserUrl);\n\n var result = true;\n } catch (e) {\n $(\"#build-message\").attr(\"class\", \"message error\").text(buildErrorMessage(e));\n var parserUrl = \"data:text/plain;charset=utf-8;base64,\"\n + Base64.encode(\"Parser not available.\");\n $(\"#parser-download\").attr(\"href\", parserUrl);\n\n var result = false;\n }\n\n doLayout();\n return result;\n }\n\n function parse() {\n oldInput = $(\"#input\").val();\n\n $(\"#input\").removeAttr(\"disabled\");\n $(\"#parse-message\").attr(\"class\", \"message progress\").text(\"Parsing the input...\");\n $(\"#output\").addClass(\"disabled\").text(\"Output not available.\");\n\n try {\n var timeBefore = (new Date).getTime();\n var output = parser.parse($(\"#input\").val());\n var timeAfter = (new Date).getTime();\n\n $(\"#parse-message\")\n .attr(\"class\", \"message info\")\n .text(\"Input parsed successfully.\")\n .append(buildSizeAndTimeInfoHtml(\n \"Parsing time and speed\",\n $(\"#input\").val().length,\n timeAfter - timeBefore\n ));\n $(\"#output\").removeClass(\"disabled\").text(jsDump.parse(output));\n\n var result = true;\n } catch (e) {\n $(\"#parse-message\").attr(\"class\", \"message error\").text(buildErrorMessage(e));\n\n var result = false;\n }\n\n doLayout();\n return result;\n }\n\n function buildAndParse() {\n build() && parse();\n }\n\n function scheduleBuildAndParse() {\n var nothingChanged = $(\"#grammar\").val() === oldGrammar\n && $(\"#parser-var\").val() === oldParserVar\n && $(\"#option-cache\").is(\":checked\") === oldOptionCache\n && $(\"#option-track-line-and-column\").is(\":checked\") === oldOptionTrackLineAndColumn;\n if (nothingChanged) { return; }\n\n if (buildAndParseTimer !== null) {\n clearTimeout(buildAndParseTimer);\n buildAndParseTimer = null;\n }\n if (parseTimer !== null) {\n clearTimeout(parseTimer);\n parseTimer = null;\n }\n\n buildAndParseTimer = setTimeout(function() {\n buildAndParse();\n buildAndParseTimer = null;\n }, 500);\n }\n\n function scheduleParse() {\n if ($(\"#input\").val() === oldInput) { return; }\n if (buildAndParseTimer !== null) { return; }\n\n if (parseTimer !== null) {\n clearTimeout(parseTimer);\n parseTimer = null;\n }\n\n parseTimer = setTimeout(function() {\n parse();\n parseTimer = null;\n }, 500);\n }\n\n function doLayout() {\n /*\n * This forces layout of the page so that the |#columns| table gets a chance\n * make itself smaller when the browser window shrinks.\n */\n if ($.browser.msie || $.browser.opera) {\n $(\"#left-column\").height(\"0px\");\n $(\"#right-column\").height(\"0px\");\n }\n $(\"#grammar\").height(\"0px\");\n $(\"#input\").height(\"0px\");\n\n if ($.browser.msie || $.browser.opera) {\n $(\"#left-column\").height(($(\"#left-column\").parent().innerHeight() - 2) + \"px\");\n $(\"#right-column\").height(($(\"#right-column\").parent().innerHeight() - 2) + \"px\");\n }\n\n $(\"#grammar\").height(($(\"#grammar\").parent().parent().innerHeight() - 14) + \"px\");\n $(\"#input\").height(($(\"#input\").parent().parent().innerHeight() - 14) + \"px\");\n }\n\n $(\"#grammar, #parser-var, #option-cache, #option-track-line-and-column\")\n .change(scheduleBuildAndParse)\n .mousedown(scheduleBuildAndParse)\n .mouseup(scheduleBuildAndParse)\n .click(scheduleBuildAndParse)\n .keydown(scheduleBuildAndParse)\n .keyup(scheduleBuildAndParse)\n .keypress(scheduleBuildAndParse);\n\n $(\"#input\")\n .change(scheduleParse)\n .mousedown(scheduleParse)\n .mouseup(scheduleParse)\n .click(scheduleParse)\n .keydown(scheduleParse)\n .keyup(scheduleParse)\n .keypress(scheduleParse);\n\n doLayout();\n $(window).resize(doLayout);\n\n $(\"#loader\").hide();\n $(\"#content\").show();\n\n $(\"#grammar, #parser-var, #option-cache, #option-track-line-and-column\").removeAttr(\"disabled\");\n\n $(\"#grammar\").focus();\n\n buildAndParse();\n});\n"}} -{"repo": "billdueber/library_stdnums", "pr_number": 2, "title": "Add check for the prefix of an ISBN 13", "state": "closed", "merged_at": "2017-05-04T14:59:44Z", "additions": 14, "deletions": 2, "files_changed": ["lib/library_stdnums.rb", "spec/library_stdnums_spec.rb"], "files_before": {"lib/library_stdnums.rb": "# Static Module functions to work with library \"standard numbers\" ISSN, ISBN, and LCCN\nmodule StdNum\n\n # Helper methods common to ISBN/ISSN\n module Helpers\n\n # The pattern we use to try and find an ISBN/ISSN. Ditch everthing before the first\n # digit, then take all the digits/hyphens, optionally followed by an 'X'\n # Since the shortest possible string is 7 digits followed by a checksum digit\n # for an ISSN, we'll make sure they're at least that long. Still imperfect\n # (would fine \"5------\", for example) but should work in most cases.\n STDNUMPAT = /^.*?(\\d[\\d\\-]{6,}[xX]?)/\n\n # Extract the most likely looking number from the string. This will be the first\n # string of digits-and-hyphens-and-maybe-a-trailing-X, with the hypens removed\n # @param [String] str The string from which to extract an ISBN/ISSN\n # @return [String] The extracted identifier\n def extractNumber str\n match = STDNUMPAT.match str\n return nil unless match\n return (match[1].gsub(/\\-/, '')).upcase\n end\n\n # Same as STDNUMPAT but allowing for all numbers in the provided string\n STDNUMPAT_MULTIPLE = /.*?(\\d[\\d\\-]{6,}[xX]?)/\n\n # Extract the most likely looking numbers from the string. This will be each\n # string with digits-and-hyphens-and-maybe-a-trailing-X, with the hypens removed\n # @param [String] str The string from which to extract the ISBN/ISSNs\n # @return [Array] An array of extracted identifiers\n def extract_multiple_numbers(str)\n return [] if str == '' || str.nil?\n str.scan(STDNUMPAT_MULTIPLE).flatten.map{ |i| i.gsub(/\\-/, '').upcase }\n end\n\n # Given any string, extract what looks like the most likely ISBN/ISSN\n # of the given size(s), or nil if nothing matches at the correct size.\n # @param [String] rawnum The raw string containing (hopefully) an ISSN/ISBN\n # @param [Integer, Array, nil] valid_sizes An integer or array of integers of valid sizes\n # for this type (e.g., 10 or 13 for ISBN, 8 for ISSN)\n # @return [String,nil] the reduced and verified number, or nil if there's no match at the right size\n def reduce_to_basics rawnum, valid_sizes = nil\n return nil if rawnum.nil?\n\n num = extractNumber rawnum\n\n # Does it even look like a number?\n return nil unless num\n\n # Return what we've got if we don't care about the size\n return num unless valid_sizes\n\n # Check for valid size(s)\n [valid_sizes].flatten.each do |s|\n return num if num.size == s\n end\n\n # Didn't check out size-wise. Return nil\n return nil\n end\n end\n\n # Validate, convert, and normalize ISBNs (10-digit or 13-digit)\n module ISBN\n extend Helpers\n\n # Does it even look like an ISBN?\n def self.at_least_trying? isbn\n reduce_to_basics(isbn, [10,13]) ? true : false\n end\n\n\n # Compute check digits for 10 or 13-digit ISBNs. See algorithm at\n # http://en.wikipedia.org/wiki/International_Standard_Book_Number\n # @param [String] isbn The ISBN (we'll try to clean it up if possible)\n # @param [Boolean] preprocessed Set to true if the ISBN has already been through reduce_to_basics\n # @return [String,nil] the one-character checkdigit, or nil if it's not an ISBN string\n def self.checkdigit isbn, preprocessed = false\n isbn = reduce_to_basics isbn, [10,13] unless preprocessed\n return nil unless isbn\n\n checkdigit = 0\n if isbn.size == 10\n digits = isbn[0..8].split(//).map {|i| i.to_i}\n (1..9).each do |i|\n checkdigit += digits[i-1] * i\n end\n checkdigit = checkdigit % 11\n return 'X' if checkdigit == 10\n return checkdigit.to_s\n else # size == 13\n checkdigit = 0\n digits = isbn[0..11].split(//).map {|i| i.to_i}\n 6.times do\n checkdigit += digits.shift\n checkdigit += digits.shift * 3\n end\n check = 10 - (checkdigit % 10)\n check = 0 if check == 10\n return check.to_s\n end\n end\n\n # Check to see if the checkdigit is correct\n # @param [String] isbn The ISBN (we'll try to clean it up if possible)\n # @param [Boolean] preprocessed Set to true if the ISBN has already been through reduce_to_basics\n # @return [Boolean] Whether or not the checkdigit is correct. Sneakily, return 'nil' for\n # values that don't even look like ISBNs, and 'false' for those that look possible but\n # don't normalize / have bad checkdigits\n def self.valid? isbn, preprocessed = false\n return nil if isbn.nil?\n isbn = reduce_to_basics(isbn, [10,13]) unless preprocessed\n return nil unless isbn\n return false unless isbn[-1..-1] == self.checkdigit(isbn, true)\n return true\n end\n\n\n # For an ISBN, normalizing it is the same as converting to ISBN 13\n # and making sure it's valid\n #\n # @param [String] rawisbn The ISBN to normalize\n # @return [String, nil] the normalized (to 13 digit) ISBN, or nil on failure\n def self.normalize rawisbn\n isbn = convert_to_13 rawisbn\n if isbn\n return isbn\n else\n return nil\n end\n end\n\n # To convert to an ISBN13, throw a '978' on the front and\n # compute the checkdigit\n # We leave 13-digit numbers alone, figuring they're already ok. NO CHECKSUM CHECK IS DONE FOR 13-DIGIT ISBNS!\n # and return nil on anything that's not the right length\n # @param [String] isbn The ISBN (we'll try to clean it up if possible)\n # @return [String, nil] The converted 13-character ISBN, nil if something looks wrong, or whatever was passed in if it already looked like a 13-digit ISBN\n def self.convert_to_13 isbn\n isbn = reduce_to_basics isbn, [10,13]\n return nil unless isbn\n return nil unless valid?(isbn, true)\n return isbn if isbn.size == 13\n prefix = '978' + isbn[0..8]\n return prefix + self.checkdigit(prefix + '0', true)\n end\n\n\n # Convert to 10 if it's 13 digits and the first three digits are 978.\n # Pass through anything 10-digits, and return nil for everything else.\n # @param [String] isbn The ISBN (we'll try to clean it up if possible)\n # @return [String] The converted 10-character ISBN, nil if something looks wrong, or whatever was passed in if it already looked like a 10-digit ISBN\n def self.convert_to_10 isbn\n isbn = reduce_to_basics isbn, [10,13]\n\n # Already 10 digits? Just return\n return isbn if isbn.size == 10\n\n # Can't be converted to ISBN-10? Bail\n return nil unless isbn[0..2] == '978'\n\n prefix = isbn[3..11]\n return prefix + self.checkdigit(prefix + '0')\n end\n\n # Return an array of the ISBN13 and ISBN10 (in that order) for the passed in value. You'll\n # only get one value back if it's a 13-digit\n # ISBN that can't be converted to an ISBN10.\n # @param [String] isbn The original ISBN, in 10-character or 13-digit format\n # @return [Array, nil] Either the (one or two) normalized ISBNs, or nil if\n # it can't be recognized.\n #\n # @example Get the normalized values and index them (if valid) or original value (if not)\n # norms = StdNum::ISBN.allNormalizedValues(rawisbn)\n # doc['isbn'] = norms ? norms : [rawisbn]\n def self.allNormalizedValues isbn\n isbn = reduce_to_basics isbn, [10,13]\n return [] unless isbn\n case isbn.size\n when 10\n return [self.convert_to_13(isbn), isbn]\n when 13\n return [isbn, self.convert_to_10(isbn)].compact\n end\n end\n\n\n end\n\n # Validate and and normalize ISSNs\n module ISSN\n extend Helpers\n\n\n # Does it even look like an ISSN?\n def self.at_least_trying? issn\n return !(reduce_to_basics(issn, 8))\n end\n\n\n # Compute the checkdigit of an ISSN\n # @param [String] issn The ISSN (we'll try to clean it up if possible)\n # @param [Boolean] preprocessed Set to true if the number has already been through reduce_to_basic\n # @return [String] the one-character checkdigit\n\n def self.checkdigit issn, preprocessed = false\n issn = reduce_to_basics issn, 8 unless preprocessed\n return nil unless issn\n\n digits = issn[0..6].split(//).map {|i| i.to_i}\n checkdigit = 0\n (0..6).each do |i|\n checkdigit += digits[i] * (8 - i)\n end\n checkdigit = checkdigit % 11\n return '0' if checkdigit == 0\n checkdigit = 11 - checkdigit\n return 'X' if checkdigit == 10\n return checkdigit.to_s\n end\n\n # Check to see if the checkdigit is correct\n # @param [String] issn The ISSN (we'll try to clean it up if possible)\n # @param [Boolean] preprocessed Set to true if the number has already been through reduce_to_basic\n # @return [Boolean] Whether or not the checkdigit is correct. Sneakily, return 'nil' for\n # values that don't even look like ISBNs, and 'false' for those that look possible but\n # don't normalize / have bad checkdigits\n\n def self.valid? issn, preprocessed = false\n issn = reduce_to_basics issn, 8 unless preprocessed\n return nil unless issn\n return issn[-1..-1] == self.checkdigit(issn, true)\n end\n\n\n\n # Make sure it's valid, remove the dashes, uppercase the X, and return\n # @param [String] rawissn The ISSN to normalize\n # @return [String, nil] the normalized ISSN, or nil on failure\n def self.normalize rawissn\n issn = reduce_to_basics rawissn, 8\n if issn and valid?(issn, true)\n return issn\n else\n return nil\n end\n end\n\n\n\n end\n\n # Validate and and normalize LCCNs\n module LCCN\n\n\n # Get a string ready for processing as an LCCN\n # @param [String] str The possible lccn\n # @return [String] The munged string, ready for normalization\n\n def self.reduce_to_basic str\n rv = str.gsub(/\\s/, '') # ditch spaces\n rv.gsub!('http://lccn.loc.gov/', '') # remove URI prefix\n rv.gsub!(/\\/.*$/, '') # ditch everything after the first '/' (including the slash)\n return rv\n end\n\n # Normalize based on data at http://www.loc.gov/marc/lccn-namespace.html#syntax\n # @param [String] rawlccn The possible LCCN to normalize\n # @return [String, nil] the normalized LCCN, or nil if it looks malformed\n def self.normalize rawlccn\n lccn = reduce_to_basic(rawlccn)\n # If there's a dash in it, deal with that.\n if lccn =~ /^(.*?)\\-(.+)/\n pre = $1\n post = $2\n return nil unless post =~ /^\\d+$/ # must be all digits\n lccn = \"%s%06d\" % [pre, post.to_i]\n end\n\n if valid?(lccn, true)\n return lccn\n else\n return nil\n end\n end\n\n # The rules for validity according to http://www.loc.gov/marc/lccn-namespace.html#syntax:\n #\n # A normalized LCCN is a character string eight to twelve characters in length. (For purposes of this description characters are ordered from left to right -- \"first\" means \"leftmost\".)\n # The rightmost eight characters are always digits.\n # If the length is 9, then the first character must be alphabetic.\n # If the length is 10, then the first two characters must be either both digits or both alphabetic.\n # If the length is 11, then the first character must be alphabetic and the next two characters must be either both digits or both alphabetic.\n # If the length is 12, then the first two characters must be alphabetic and the remaining characters digits.\n #\n # @param [String] lccn The lccn to attempt to validate\n # @param [Boolean] preprocessed Set to true if the number has already been normalized\n # @return [Boolean] Whether or not the syntax seems ok\n\n def self.valid? lccn, preprocessed = false\n lccn = normalize(lccn) unless preprocessed\n return false unless lccn\n clean = lccn.gsub(/\\-/, '')\n suffix = clean[-8..-1] # \"the rightmost eight characters are always digits\"\n return false unless suffix and suffix =~ /^\\d+$/\n case clean.size # \"...is a character string eight to twelve digits in length\"\n when 8\n return true\n when 9\n return true if clean =~ /^[A-Za-z]/\n when 10\n return true if clean =~ /^\\d{2}/ or clean =~ /^[A-Za-z]{2}/\n when 11\n return true if clean =~ /^[A-Za-z](\\d{2}|[A-Za-z]{2})/\n when 12\n return true if clean =~ /^[A-Za-z]{2}\\d{2}/\n else\n return false\n end\n\n return false\n end\n\n end\n\nend\n\n", "spec/library_stdnums_spec.rb": "require 'spec_helper'\n\ndescribe \"Extract\" do\n it \"should leave a number alone\" do\n StdNum::ISBN.extractNumber('1234567').must_equal '1234567'\n end\n\n it \"should skip leading and trailing crap\" do\n StdNum::ISBN.extractNumber(' 1234567 (online)').must_equal '1234567'\n end\n\n it \"should allow hyphens\" do\n StdNum::ISBN.extractNumber(' 1-234-5').must_equal '12345'\n end\n\n it \"should return nil on a non-match\" do\n StdNum::ISBN.extractNumber('bill dueber').must_equal nil\n end\n\n it \"should allow a trailing X\" do\n StdNum::ISBN.extractNumber('1-234-5-X').must_equal '12345X'\n end\n\n it \"should upcase any trailing X\" do\n StdNum::ISBN.extractNumber('1-234-56-x').must_equal '123456X'\n end\n\n it \"only allows a single trailing X\" do\n StdNum::ISBN.extractNumber('123456-X-X').must_equal '123456X'\n end\n\n it \"doesn't allow numbers that are too short\" do\n StdNum::ISBN.extractNumber('12345').must_equal nil\n end\n\n let(:identifiers_string) { '9780987115423 (print ed) 9780987115430 (web ed)' }\n it \"will extract multiple identifiers\" do\n StdNum::ISBN.extract_multiple_numbers(identifiers_string).must_be_kind_of Array\n StdNum::ISBN.extract_multiple_numbers(identifiers_string).count.must_equal 2\n StdNum::ISBN.extract_multiple_numbers(identifiers_string)[0].must_equal '9780987115423'\n StdNum::ISBN.extract_multiple_numbers(identifiers_string)[1].must_equal '9780987115430'\n end\n\n let(:string_with_no_identifiers) { 'This has no identifiers' }\n it \"will return an empty array when no identifiers are in the supplied string \" do\n StdNum::ISBN.extract_multiple_numbers(string_with_no_identifiers).must_be_kind_of Array\n StdNum::ISBN.extract_multiple_numbers(string_with_no_identifiers).count.must_equal 0\n\n StdNum::ISBN.extract_multiple_numbers('').must_be_kind_of Array\n StdNum::ISBN.extract_multiple_numbers('').count.must_equal 0\n end\n it \"skips over short prefixing numbers\" do\n StdNum::ISBN.extractNumber('ISBN13: 1234567890123').must_equal '1234567890123'\n end\n\nend\n\n\ndescribe \"ISBN\" do\n it \"computes 10-digit checksum\" do\n StdNum::ISBN.checkdigit('0-306-40615-X').must_equal '2'\n end\n\n it \"correctly uses X for checksum\" do\n StdNum::ISBN.checkdigit('061871460X').must_equal 'X'\n end\n\n it \"finds a zero checkdigit\" do\n StdNum::ISBN.checkdigit('0139381430').must_equal '0'\n end\n\n it \"computes 13-digit checksum\" do\n StdNum::ISBN.checkdigit('9780306406157').must_equal '7'\n end\n\n it \"computes a 13-digit checksum that is 0\" do\n StdNum::ISBN.checkdigit('9783837612950').must_equal '0'\n end\n\n it \"finds a good number valid\" do\n StdNum::ISBN.valid?('9780306406157').must_equal true\n end\n\n it \"says a good number is trying\" do\n StdNum::ISBN.at_least_trying?('9780306406157').must_equal true\n end\n\n it \"says bad data is not trying\" do\n StdNum::ISBN.at_least_trying?('978006406157').must_equal false\n StdNum::ISBN.at_least_trying?('406157').must_equal false\n StdNum::ISBN.at_least_trying?('$22').must_equal false\n StdNum::ISBN.at_least_trying?('hello').must_equal false\n end\n\n\n it \"finds a bad number invalid\" do\n StdNum::ISBN.valid?('9780306406154').must_equal false\n end\n\n it \"returns nil when computing checksum for bad ISBN\" do\n StdNum::ISBN.checkdigit('12345').must_equal nil\n end\n\n it \"converts 10 to 13\" do\n StdNum::ISBN.convert_to_13('0-306-40615-2').must_equal '9780306406157'\n end\n\n it \"passes through 13 digit number instead of converting to 13\" do\n StdNum::ISBN.convert_to_13('9780306406157').must_equal '9780306406157'\n end\n\n it \"converts 13 to 10\" do\n StdNum::ISBN.convert_to_10('978-0-306-40615-7').must_equal '0306406152'\n end\n\n it \"normalizes\" do\n StdNum::ISBN.normalize('0-306-40615-2').must_equal '9780306406157'\n StdNum::ISBN.normalize('0-306-40615-X').must_equal nil\n StdNum::ISBN.normalize('ISBN: 978-0-306-40615-7').must_equal '9780306406157'\n StdNum::ISBN.normalize('ISBN: 978-0-306-40615-3').must_equal nil\n end\n\n it \"gets both normalized values\" do\n a = StdNum::ISBN.allNormalizedValues('978-0-306-40615-7')\n a.sort.must_equal ['9780306406157', '0306406152' ].sort\n\n a = StdNum::ISBN.allNormalizedValues('0-306-40615-2')\n a.sort.must_equal ['9780306406157', '0306406152' ].sort\n end\n\n\n\nend\n\n\n\ndescribe 'ISSN' do\n it \"computes checksum\" do\n StdNum::ISSN.checkdigit('0378-5955').must_equal '5'\n end\n\n it \"normalizes\" do\n StdNum::ISSN.normalize('0378-5955').must_equal '03785955'\n end\nend\n\n\ndescribe 'LCCN basics' do\n\n # Tests take from http://www.loc.gov/marc/lccn-namespace.html#syntax\n test = {\n \"n78-890351\" => \"n78890351\",\n \"n78-89035\" => \"n78089035\",\n \"n 78890351 \" => \"n78890351\",\n \" 85000002 \" => \"85000002\",\n \"85-2 \" => \"85000002\",\n \"2001-000002\" => \"2001000002\",\n \"75-425165//r75\" => \"75425165\",\n \" 79139101 /AC/r932\" => \"79139101\",\n }\n\n test.each do |k, v|\n it \"normalizes #{k}\" do\n StdNum::LCCN.normalize(k.dup).must_equal v\n end\n end\n\n it \"validates correctly\" do\n StdNum::LCCN.valid?(\"n78-890351\").must_equal true\n StdNum::LCCN.valid?(\"n78-89035100444\").must_equal false, \"Too long\"\n StdNum::LCCN.valid?(\"n78\").must_equal false, \"Too short\"\n StdNum::LCCN.valid?(\"na078-890351\").must_equal false, \"naa78-890351 should start with three letters or digits\"\n StdNum::LCCN.valid?(\"n078-890351\").must_equal false, \"n078-890351 should start with two letters or two digits\"\n StdNum::LCCN.valid?(\"na078-890351\").must_equal false, \"na078-890351 should start with three letters or digits\"\n StdNum::LCCN.valid?(\"0an78-890351\").must_equal false, \"0an78-890351 should start with three letters or digits\"\n StdNum::LCCN.valid?(\"n78-89c0351\").must_equal false, \"n78-89c0351 has a letter after the dash\"\n end\n\n\nend\n\n\ndescribe \"LCCN tests from Business::LCCN perl module\" do\n tests = [\n { :orig => 'n78-890351',\n :canonical => 'n 78890351 ',\n :normalized => 'n78890351',\n :prefix => 'n',\n :year_cataloged => 1978,\n :serial => '890351',\n },\n { :orig => 'n 78890351 ',\n :canonical => 'n 78890351 ',\n :normalized => 'n78890351',\n :prefix => 'n',\n :year_cataloged => 1978,\n :serial => '890351',\n },\n { :orig => ' 85000002 ',\n :canonical => ' 85000002 ',\n :normalized => '85000002',\n :year_cataloged => 1985,\n :serial => '000002',\n },\n { :orig => '85-2 ',\n :canonical => ' 85000002 ',\n :normalized => '85000002',\n :year_cataloged => 1985,\n :serial => '000002',\n },\n { :orig => '2001-000002',\n :canonical => ' 2001000002',\n :normalized => '2001000002',\n :year_cataloged => 2001,\n :serial => '000002',\n },\n { :orig => '75-425165//r75',\n :canonical => ' 75425165 //r75',\n :normalized => '75425165',\n :prefix => '',\n :year_cataloged => nil,\n :serial => '425165',\n :revision_year => 1975,\n :revision_year_encoded => '75',\n :revision_number => nil,\n },\n { :orig => ' 79139101 /AC/r932',\n :canonical => ' 79139101 /AC/r932',\n :normalized => '79139101',\n :prefix => '',\n :year_cataloged => nil,\n :serial => '139101',\n :suffix_encoded => '/AC',\n :revision_year => 1993,\n :revision_year_encoded => '93',\n :revision_number => 2,\n },\n { :orig => '89-4',\n :canonical => ' 89000004 ',\n :normalized => '89000004',\n :year_cataloged => 1989,\n :serial => '000004',\n },\n { :orig => '89-45',\n :canonical => ' 89000045 ',\n :normalized => '89000045',\n :year_cataloged => 1989,\n :serial => '000045',\n },\n { :orig => '89-456',\n :canonical => ' 89000456 ',\n :normalized => '89000456',\n :year_cataloged => 1989,\n :serial => '000456',\n },\n { :orig => '89-1234',\n :canonical => ' 89001234 ',\n :normalized => '89001234',\n :year_cataloged => 1989,\n :serial => '001234',\n },\n { :orig => '89-001234',\n :canonical => ' 89001234 ',\n :normalized => '89001234',\n :year_cataloged => 1989,\n :serial => '001234',\n },\n { :orig => '89001234',\n :canonical => ' 89001234 ',\n :normalized => '89001234',\n :year_cataloged => 1989,\n :serial => '001234',\n },\n { :orig => '2002-1234',\n :canonical => ' 2002001234',\n :normalized => '2002001234',\n :year_cataloged => 2002,\n :serial => '001234',\n },\n { :orig => '2002-001234',\n :canonical => ' 2002001234',\n :normalized => '2002001234',\n :year_cataloged => 2002,\n :serial => '001234',\n },\n { :orig => '2002001234',\n :canonical => ' 2002001234',\n :normalized => '2002001234',\n :year_cataloged => 2002,\n :serial => '001234',\n },\n { :orig => ' 89001234 ',\n :canonical => ' 89001234 ',\n :normalized => '89001234',\n :year_cataloged => 1989,\n :serial => '001234',\n },\n { :orig => ' 2002001234',\n :canonical => ' 2002001234',\n :normalized => '2002001234',\n :year_cataloged => 2002,\n :serial => '001234',\n },\n { :orig => 'a89-1234',\n :canonical => 'a 89001234 ',\n :normalized => 'a89001234',\n :prefix => 'a',\n :year_cataloged => 1989,\n :serial => '001234',\n },\n { :orig => 'a89-001234',\n :canonical => 'a 89001234 ',\n :normalized => 'a89001234',\n :prefix => 'a',\n :year_cataloged => 1989,\n :serial => '001234',\n },\n { :orig => 'a89001234',\n :canonical => 'a 89001234 ',\n :normalized => 'a89001234',\n :prefix => 'a',\n :year_cataloged => 1989,\n :serial => '001234',\n },\n { :orig => 'a2002-1234',\n :canonical => 'a 2002001234',\n :normalized => 'a2002001234',\n :prefix => 'a',\n :year_cataloged => 2002,\n :serial => '001234',\n },\n { :orig => 'a2002-001234',\n :canonical => 'a 2002001234',\n :normalized => 'a2002001234',\n :prefix => 'a',\n :year_cataloged => 2002,\n :serial => '001234',\n },\n { :orig => 'a2002001234',\n :canonical => 'a 2002001234',\n :normalized => 'a2002001234',\n :prefix => 'a',\n :year_cataloged => 2002,\n :serial => '001234',\n },\n { :orig => 'a 89001234 ',\n :canonical => 'a 89001234 ',\n :normalized => 'a89001234',\n :prefix => 'a',\n :year_cataloged => 1989,\n :serial => '001234',\n },\n { :orig => 'a 89-001234 ',\n :canonical => 'a 89001234 ',\n :normalized => 'a89001234',\n :prefix => 'a',\n :year_cataloged => 1989,\n :serial => '001234',\n },\n { :orig => 'a 2002001234',\n :canonical => 'a 2002001234',\n :normalized => 'a2002001234',\n :prefix => 'a',\n :year_cataloged => 2002,\n :serial => '001234',\n },\n { :orig => 'ab89-1234',\n :canonical => 'ab 89001234 ',\n :normalized => 'ab89001234',\n :prefix => 'ab',\n :year_cataloged => 1989,\n :serial => '001234',\n },\n { :orig => 'ab89-001234',\n :canonical => 'ab 89001234 ',\n :normalized => 'ab89001234',\n :prefix => 'ab',\n :year_cataloged => 1989,\n :serial => '001234',\n },\n { :orig => 'ab89001234',\n :canonical => 'ab 89001234 ',\n :normalized => 'ab89001234',\n :prefix => 'ab',\n :year_cataloged => 1989,\n :serial => '001234',\n },\n { :orig => 'ab2002-1234',\n :canonical => 'ab2002001234',\n :normalized => 'ab2002001234',\n :prefix => 'ab',\n :year_cataloged => 2002,\n :serial => '001234',\n },\n { :orig => 'ab2002-001234',\n :canonical => 'ab2002001234',\n :normalized => 'ab2002001234',\n :prefix => 'ab',\n :year_cataloged => 2002,\n :serial => '001234',\n },\n { :orig => 'ab2002001234',\n :canonical => 'ab2002001234',\n :normalized => 'ab2002001234',\n :prefix => 'ab',\n :year_cataloged => 2002,\n :serial => '001234',\n },\n { :orig => 'ab 89001234 ',\n :canonical => 'ab 89001234 ',\n :normalized => 'ab89001234',\n :prefix => 'ab',\n :year_cataloged => 1989,\n :serial => '001234',\n },\n { :orig => 'ab 2002001234',\n :canonical => 'ab2002001234',\n :normalized => 'ab2002001234',\n :prefix => 'ab',\n :year_cataloged => 2002,\n :serial => '001234',\n },\n { :orig => 'ab 89-1234',\n :canonical => 'ab 89001234 ',\n :normalized => 'ab89001234',\n :prefix => 'ab',\n :year_cataloged => 1989,\n :serial => '001234',\n },\n { :orig => 'abc89-1234',\n :canonical => 'abc89001234 ',\n :normalized => 'abc89001234',\n :prefix => 'abc',\n :year_cataloged => 1989,\n :serial => '001234',\n },\n { :orig => 'abc89-001234',\n :canonical => 'abc89001234 ',\n :normalized => 'abc89001234',\n :prefix => 'abc',\n :year_cataloged => 1989,\n :serial => '001234',\n },\n { :orig => 'abc89001234',\n :canonical => 'abc89001234 ',\n :normalized => 'abc89001234',\n :prefix => 'abc',\n :year_cataloged => 1989,\n :serial => '001234',\n },\n { :orig => 'abc89001234 ',\n :canonical => 'abc89001234 ',\n :normalized => 'abc89001234',\n :prefix => 'abc',\n :year_cataloged => 1989,\n :serial => '001234',\n },\n { :orig => 'http://lccn.loc.gov/89001234',\n :canonical => ' 89001234 ',\n :normalized => '89001234',\n :year_cataloged => 1989,\n :serial => '001234',\n },\n { :orig => 'http://lccn.loc.gov/a89001234',\n :canonical => 'a 89001234 ',\n :normalized => 'a89001234',\n :serial => '001234',\n :prefix => 'a',\n :year_cataloged => 1989,\n },\n { :orig => 'http://lccn.loc.gov/ab89001234',\n :canonical => 'ab 89001234 ',\n :normalized => 'ab89001234',\n :prefix => 'ab',\n :year_cataloged => 1989,\n :serial => '001234',\n },\n { :orig => 'http://lccn.loc.gov/abc89001234',\n :canonical => 'abc89001234 ',\n :normalized => 'abc89001234',\n :prefix => 'abc',\n :year_cataloged => 1989,\n :serial => '001234',\n },\n { :orig => 'http://lccn.loc.gov/2002001234',\n :canonical => ' 2002001234',\n :normalized => '2002001234',\n :year_cataloged => 2002,\n :serial => '001234',\n },\n { :orig => 'http://lccn.loc.gov/a2002001234',\n :canonical => 'a 2002001234',\n :normalized => 'a2002001234',\n :prefix => 'a',\n :year_cataloged => 2002,\n :serial => '001234',\n },\n { :orig => 'http://lccn.loc.gov/ab2002001234',\n :canonical => 'ab2002001234',\n :normalized => 'ab2002001234',\n :prefix => 'ab',\n :year_cataloged => 2002,\n :serial => '001234',\n },\n { :orig => '00-21595',\n :canonical => ' 00021595 ',\n :normalized => '00021595',\n :year_cataloged => 2000,\n :serial => '021595',\n },\n { :orig => '2001001599',\n :canonical => ' 2001001599',\n :normalized => '2001001599',\n :year_cataloged => 2001,\n :serial => '001599',\n },\n { :orig => '99-18233',\n :canonical => ' 99018233 ',\n :normalized => '99018233',\n :year_cataloged => 1999,\n :serial => '018233',\n },\n { :orig => '98000595',\n :canonical => ' 98000595 ',\n :normalized => '98000595',\n :year_cataloged => 1898,\n :serial => '000595',\n },\n { :orig => '99005074',\n :canonical => ' 99005074 ',\n :normalized => '99005074',\n :year_cataloged => 1899,\n :serial => '005074',\n },\n { :orig => '00003373',\n :canonical => ' 00003373 ',\n :normalized => '00003373',\n :year_cataloged => 1900,\n :serial => '003373',\n },\n { :orig => '01001599',\n :canonical => ' 01001599 ',\n :normalized => '01001599',\n :year_cataloged => 1901,\n :serial => '001599',\n },\n { :orig => ' 95156543 ',\n :canonical => ' 95156543 ',\n :normalized => '95156543',\n :year_cataloged => 1995,\n :serial => '156543',\n },\n { :orig => ' 94014580 /AC/r95',\n :canonical => ' 94014580 /AC/r95',\n :normalized => '94014580',\n :year_cataloged => 1994,\n :serial => '014580',\n :suffix_encoded => '/AC',\n :revision_year_encoded => '95',\n :revision_year => 1995,\n },\n { :orig => ' 79310919 //r86',\n :canonical => ' 79310919 //r86',\n :normalized => '79310919',\n :year_cataloged => 1979,\n :serial => '310919',\n :revision_year_encoded => '86',\n :revision_year => 1986,\n },\n { :orig => 'gm 71005810 ',\n :canonical => 'gm 71005810 ',\n :normalized => 'gm71005810',\n :prefix => 'gm',\n :year_cataloged => 1971,\n :serial => '005810',\n },\n { :orig => 'sn2006058112 ',\n :canonical => 'sn2006058112',\n :normalized => 'sn2006058112',\n :prefix => 'sn',\n :year_cataloged => 2006,\n :serial => '058112',\n },\n { :orig => 'gm 71-2450',\n :canonical => 'gm 71002450 ',\n :normalized => 'gm71002450',\n :prefix => 'gm',\n :year_cataloged => 1971,\n :serial => '002450',\n },\n { :orig => '2001-1114',\n :canonical => ' 2001001114',\n :normalized => '2001001114',\n :year_cataloged => 2001,\n :serial => '001114',\n },\n ]\n tests.each do |h|\n it \"normalizes #{h[:orig]}\" do\n StdNum::LCCN.normalize(h[:orig]).must_equal h[:normalized], \"#{h[:orig]} doesn't normalize to #{h[:normalized]}\"\n end\n end\nend\n\n"}, "files_after": {"lib/library_stdnums.rb": "# Static Module functions to work with library \"standard numbers\" ISSN, ISBN, and LCCN\nmodule StdNum\n\n # Helper methods common to ISBN/ISSN\n module Helpers\n\n # The pattern we use to try and find an ISBN/ISSN. Ditch everthing before the first\n # digit, then take all the digits/hyphens, optionally followed by an 'X'\n # Since the shortest possible string is 7 digits followed by a checksum digit\n # for an ISSN, we'll make sure they're at least that long. Still imperfect\n # (would fine \"5------\", for example) but should work in most cases.\n STDNUMPAT = /^.*?(\\d[\\d\\-]{6,}[xX]?)/\n\n # Extract the most likely looking number from the string. This will be the first\n # string of digits-and-hyphens-and-maybe-a-trailing-X, with the hypens removed\n # @param [String] str The string from which to extract an ISBN/ISSN\n # @return [String] The extracted identifier\n def extractNumber str\n match = STDNUMPAT.match str\n return nil unless match\n return (match[1].gsub(/\\-/, '')).upcase\n end\n\n # Same as STDNUMPAT but allowing for all numbers in the provided string\n STDNUMPAT_MULTIPLE = /.*?(\\d[\\d\\-]{6,}[xX]?)/\n\n # Extract the most likely looking numbers from the string. This will be each\n # string with digits-and-hyphens-and-maybe-a-trailing-X, with the hypens removed\n # @param [String] str The string from which to extract the ISBN/ISSNs\n # @return [Array] An array of extracted identifiers\n def extract_multiple_numbers(str)\n return [] if str == '' || str.nil?\n str.scan(STDNUMPAT_MULTIPLE).flatten.map{ |i| i.gsub(/\\-/, '').upcase }\n end\n\n # Given any string, extract what looks like the most likely ISBN/ISSN\n # of the given size(s), or nil if nothing matches at the correct size.\n # @param [String] rawnum The raw string containing (hopefully) an ISSN/ISBN\n # @param [Integer, Array, nil] valid_sizes An integer or array of integers of valid sizes\n # for this type (e.g., 10 or 13 for ISBN, 8 for ISSN)\n # @return [String,nil] the reduced and verified number, or nil if there's no match at the right size\n def reduce_to_basics rawnum, valid_sizes = nil\n return nil if rawnum.nil?\n\n num = extractNumber rawnum\n\n # Does it even look like a number?\n return nil unless num\n\n # Return what we've got if we don't care about the size\n return num unless valid_sizes\n\n # Check for valid size(s)\n [valid_sizes].flatten.each do |s|\n return num if num.size == s\n end\n\n # Didn't check out size-wise. Return nil\n return nil\n end\n end\n\n # Validate, convert, and normalize ISBNs (10-digit or 13-digit)\n module ISBN\n extend Helpers\n\n # Does it even look like an ISBN?\n def self.at_least_trying? isbn\n reduce_to_basics(isbn, [10,13]) ? true : false\n end\n\n\n # Compute check digits for 10 or 13-digit ISBNs. See algorithm at\n # http://en.wikipedia.org/wiki/International_Standard_Book_Number\n # @param [String] isbn The ISBN (we'll try to clean it up if possible)\n # @param [Boolean] preprocessed Set to true if the ISBN has already been through reduce_to_basics\n # @return [String,nil] the one-character checkdigit, or nil if it's not an ISBN string\n def self.checkdigit isbn, preprocessed = false\n isbn = reduce_to_basics isbn, [10,13] unless preprocessed\n return nil unless isbn\n\n checkdigit = 0\n if isbn.size == 10\n digits = isbn[0..8].split(//).map {|i| i.to_i}\n (1..9).each do |i|\n checkdigit += digits[i-1] * i\n end\n checkdigit = checkdigit % 11\n return 'X' if checkdigit == 10\n return checkdigit.to_s\n else # size == 13\n checkdigit = 0\n digits = isbn[0..11].split(//).map {|i| i.to_i}\n 6.times do\n checkdigit += digits.shift\n checkdigit += digits.shift * 3\n end\n check = 10 - (checkdigit % 10)\n check = 0 if check == 10\n return check.to_s\n end\n end\n\n # Check to see if the checkdigit is correct\n # @param [String] isbn The ISBN (we'll try to clean it up if possible)\n # @param [Boolean] preprocessed Set to true if the ISBN has already been through reduce_to_basics\n # @return [Boolean] Whether or not the checkdigit is correct. Sneakily, return 'nil' for\n # values that don't even look like ISBNs, and 'false' for those that look possible but\n # don't normalize / have bad checkdigits\n def self.valid? isbn, preprocessed = false\n return nil if isbn.nil?\n isbn = reduce_to_basics(isbn, [10,13]) unless preprocessed\n return nil unless isbn\n return false unless isbn[-1..-1] == self.checkdigit(isbn, true)\n return false unless isbn.size == 10 || valid_isbn13_prefix?(isbn)\n return true\n end\n\n\n # For an ISBN, normalizing it is the same as converting to ISBN 13\n # and making sure it's valid\n #\n # @param [String] rawisbn The ISBN to normalize\n # @return [String, nil] the normalized (to 13 digit) ISBN, or nil on failure\n def self.normalize rawisbn\n isbn = convert_to_13 rawisbn\n if isbn\n return isbn\n else\n return nil\n end\n end\n\n # To convert to an ISBN13, throw a '978' on the front and\n # compute the checkdigit\n # We leave 13-digit numbers alone, figuring they're already ok. NO CHECKSUM CHECK IS DONE FOR 13-DIGIT ISBNS!\n # and return nil on anything that's not the right length\n # @param [String] isbn The ISBN (we'll try to clean it up if possible)\n # @return [String, nil] The converted 13-character ISBN, nil if something looks wrong, or whatever was passed in if it already looked like a 13-digit ISBN\n def self.convert_to_13 isbn\n isbn = reduce_to_basics isbn, [10,13]\n return nil unless isbn\n return nil unless valid?(isbn, true)\n return isbn if isbn.size == 13\n prefix = '978' + isbn[0..8]\n return prefix + self.checkdigit(prefix + '0', true)\n end\n\n\n # Convert to 10 if it's 13 digits and the first three digits are 978.\n # Pass through anything 10-digits, and return nil for everything else.\n # @param [String] isbn The ISBN (we'll try to clean it up if possible)\n # @return [String] The converted 10-character ISBN, nil if something looks wrong, or whatever was passed in if it already looked like a 10-digit ISBN\n def self.convert_to_10 isbn\n isbn = reduce_to_basics isbn, [10,13]\n\n # Already 10 digits? Just return\n return isbn if isbn.size == 10\n\n # Can't be converted to ISBN-10? Bail\n return nil unless isbn[0..2] == '978'\n\n prefix = isbn[3..11]\n return prefix + self.checkdigit(prefix + '0')\n end\n\n # Return an array of the ISBN13 and ISBN10 (in that order) for the passed in value. You'll\n # only get one value back if it's a 13-digit\n # ISBN that can't be converted to an ISBN10.\n # @param [String] isbn The original ISBN, in 10-character or 13-digit format\n # @return [Array, nil] Either the (one or two) normalized ISBNs, or nil if\n # it can't be recognized.\n #\n # @example Get the normalized values and index them (if valid) or original value (if not)\n # norms = StdNum::ISBN.allNormalizedValues(rawisbn)\n # doc['isbn'] = norms ? norms : [rawisbn]\n def self.allNormalizedValues isbn\n isbn = reduce_to_basics isbn, [10,13]\n return [] unless isbn\n case isbn.size\n when 10\n return [self.convert_to_13(isbn), isbn]\n when 13\n return [isbn, self.convert_to_10(isbn)].compact\n end\n end\n\n # Checks for a valid ISBN13 prefix\n # ISBN13 always starts with 978 or 979. For example: 1000000000012 has a valid check digit, but\n # is not a valid ISBN13.\n # @param [String] isbn13 The ISBN13 to be checked.\n # @return [Boolean] If true then the prefix is valid\n def self.valid_isbn13_prefix?(isbn13)\n return false unless isbn13.size == 13\n ['978', '979'].map { |prefix| isbn13.start_with?(prefix) }.any?\n end\n end\n\n # Validate and and normalize ISSNs\n module ISSN\n extend Helpers\n\n\n # Does it even look like an ISSN?\n def self.at_least_trying? issn\n return !(reduce_to_basics(issn, 8))\n end\n\n\n # Compute the checkdigit of an ISSN\n # @param [String] issn The ISSN (we'll try to clean it up if possible)\n # @param [Boolean] preprocessed Set to true if the number has already been through reduce_to_basic\n # @return [String] the one-character checkdigit\n\n def self.checkdigit issn, preprocessed = false\n issn = reduce_to_basics issn, 8 unless preprocessed\n return nil unless issn\n\n digits = issn[0..6].split(//).map {|i| i.to_i}\n checkdigit = 0\n (0..6).each do |i|\n checkdigit += digits[i] * (8 - i)\n end\n checkdigit = checkdigit % 11\n return '0' if checkdigit == 0\n checkdigit = 11 - checkdigit\n return 'X' if checkdigit == 10\n return checkdigit.to_s\n end\n\n # Check to see if the checkdigit is correct\n # @param [String] issn The ISSN (we'll try to clean it up if possible)\n # @param [Boolean] preprocessed Set to true if the number has already been through reduce_to_basic\n # @return [Boolean] Whether or not the checkdigit is correct. Sneakily, return 'nil' for\n # values that don't even look like ISBNs, and 'false' for those that look possible but\n # don't normalize / have bad checkdigits\n\n def self.valid? issn, preprocessed = false\n issn = reduce_to_basics issn, 8 unless preprocessed\n return nil unless issn\n return issn[-1..-1] == self.checkdigit(issn, true)\n end\n\n\n\n # Make sure it's valid, remove the dashes, uppercase the X, and return\n # @param [String] rawissn The ISSN to normalize\n # @return [String, nil] the normalized ISSN, or nil on failure\n def self.normalize rawissn\n issn = reduce_to_basics rawissn, 8\n if issn and valid?(issn, true)\n return issn\n else\n return nil\n end\n end\n\n\n\n end\n\n # Validate and and normalize LCCNs\n module LCCN\n\n\n # Get a string ready for processing as an LCCN\n # @param [String] str The possible lccn\n # @return [String] The munged string, ready for normalization\n\n def self.reduce_to_basic str\n rv = str.gsub(/\\s/, '') # ditch spaces\n rv.gsub!('http://lccn.loc.gov/', '') # remove URI prefix\n rv.gsub!(/\\/.*$/, '') # ditch everything after the first '/' (including the slash)\n return rv\n end\n\n # Normalize based on data at http://www.loc.gov/marc/lccn-namespace.html#syntax\n # @param [String] rawlccn The possible LCCN to normalize\n # @return [String, nil] the normalized LCCN, or nil if it looks malformed\n def self.normalize rawlccn\n lccn = reduce_to_basic(rawlccn)\n # If there's a dash in it, deal with that.\n if lccn =~ /^(.*?)\\-(.+)/\n pre = $1\n post = $2\n return nil unless post =~ /^\\d+$/ # must be all digits\n lccn = \"%s%06d\" % [pre, post.to_i]\n end\n\n if valid?(lccn, true)\n return lccn\n else\n return nil\n end\n end\n\n # The rules for validity according to http://www.loc.gov/marc/lccn-namespace.html#syntax:\n #\n # A normalized LCCN is a character string eight to twelve characters in length. (For purposes of this description characters are ordered from left to right -- \"first\" means \"leftmost\".)\n # The rightmost eight characters are always digits.\n # If the length is 9, then the first character must be alphabetic.\n # If the length is 10, then the first two characters must be either both digits or both alphabetic.\n # If the length is 11, then the first character must be alphabetic and the next two characters must be either both digits or both alphabetic.\n # If the length is 12, then the first two characters must be alphabetic and the remaining characters digits.\n #\n # @param [String] lccn The lccn to attempt to validate\n # @param [Boolean] preprocessed Set to true if the number has already been normalized\n # @return [Boolean] Whether or not the syntax seems ok\n\n def self.valid? lccn, preprocessed = false\n lccn = normalize(lccn) unless preprocessed\n return false unless lccn\n clean = lccn.gsub(/\\-/, '')\n suffix = clean[-8..-1] # \"the rightmost eight characters are always digits\"\n return false unless suffix and suffix =~ /^\\d+$/\n case clean.size # \"...is a character string eight to twelve digits in length\"\n when 8\n return true\n when 9\n return true if clean =~ /^[A-Za-z]/\n when 10\n return true if clean =~ /^\\d{2}/ or clean =~ /^[A-Za-z]{2}/\n when 11\n return true if clean =~ /^[A-Za-z](\\d{2}|[A-Za-z]{2})/\n when 12\n return true if clean =~ /^[A-Za-z]{2}\\d{2}/\n else\n return false\n end\n\n return false\n end\n\n end\n\nend\n\n", "spec/library_stdnums_spec.rb": "require 'spec_helper'\n\ndescribe \"Extract\" do\n it \"should leave a number alone\" do\n StdNum::ISBN.extractNumber('1234567').must_equal '1234567'\n end\n\n it \"should skip leading and trailing crap\" do\n StdNum::ISBN.extractNumber(' 1234567 (online)').must_equal '1234567'\n end\n\n it \"should allow hyphens\" do\n StdNum::ISBN.extractNumber(' 1-234-5').must_equal '12345'\n end\n\n it \"should return nil on a non-match\" do\n StdNum::ISBN.extractNumber('bill dueber').must_equal nil\n end\n\n it \"should allow a trailing X\" do\n StdNum::ISBN.extractNumber('1-234-5-X').must_equal '12345X'\n end\n\n it \"should upcase any trailing X\" do\n StdNum::ISBN.extractNumber('1-234-56-x').must_equal '123456X'\n end\n\n it \"only allows a single trailing X\" do\n StdNum::ISBN.extractNumber('123456-X-X').must_equal '123456X'\n end\n\n it \"doesn't allow numbers that are too short\" do\n StdNum::ISBN.extractNumber('12345').must_equal nil\n end\n\n let(:identifiers_string) { '9780987115423 (print ed) 9780987115430 (web ed)' }\n it \"will extract multiple identifiers\" do\n StdNum::ISBN.extract_multiple_numbers(identifiers_string).must_be_kind_of Array\n StdNum::ISBN.extract_multiple_numbers(identifiers_string).count.must_equal 2\n StdNum::ISBN.extract_multiple_numbers(identifiers_string)[0].must_equal '9780987115423'\n StdNum::ISBN.extract_multiple_numbers(identifiers_string)[1].must_equal '9780987115430'\n end\n\n let(:string_with_no_identifiers) { 'This has no identifiers' }\n it \"will return an empty array when no identifiers are in the supplied string \" do\n StdNum::ISBN.extract_multiple_numbers(string_with_no_identifiers).must_be_kind_of Array\n StdNum::ISBN.extract_multiple_numbers(string_with_no_identifiers).count.must_equal 0\n\n StdNum::ISBN.extract_multiple_numbers('').must_be_kind_of Array\n StdNum::ISBN.extract_multiple_numbers('').count.must_equal 0\n end\n it \"skips over short prefixing numbers\" do\n StdNum::ISBN.extractNumber('ISBN13: 1234567890123').must_equal '1234567890123'\n end\n\nend\n\n\ndescribe \"ISBN\" do\n it \"computes 10-digit checksum\" do\n StdNum::ISBN.checkdigit('0-306-40615-X').must_equal '2'\n end\n\n it \"correctly uses X for checksum\" do\n StdNum::ISBN.checkdigit('061871460X').must_equal 'X'\n end\n\n it \"finds a zero checkdigit\" do\n StdNum::ISBN.checkdigit('0139381430').must_equal '0'\n end\n\n it \"computes 13-digit checksum\" do\n StdNum::ISBN.checkdigit('9780306406157').must_equal '7'\n end\n\n it \"computes a 13-digit checksum that is 0\" do\n StdNum::ISBN.checkdigit('9783837612950').must_equal '0'\n end\n\n it \"finds a good number valid\" do\n StdNum::ISBN.valid?('9780306406157').must_equal true\n end\n\n it \"says a good number is trying\" do\n StdNum::ISBN.at_least_trying?('9780306406157').must_equal true\n end\n\n it \"says bad data is not trying\" do\n StdNum::ISBN.at_least_trying?('978006406157').must_equal false\n StdNum::ISBN.at_least_trying?('406157').must_equal false\n StdNum::ISBN.at_least_trying?('$22').must_equal false\n StdNum::ISBN.at_least_trying?('hello').must_equal false\n end\n\n\n it \"finds a bad number invalid\" do\n StdNum::ISBN.valid?('9780306406154').must_equal false\n end\n\n it \"returns nil when computing checksum for bad ISBN\" do\n StdNum::ISBN.checkdigit('12345').must_equal nil\n end\n\n it \"converts 10 to 13\" do\n StdNum::ISBN.convert_to_13('0-306-40615-2').must_equal '9780306406157'\n end\n\n it \"passes through 13 digit number instead of converting to 13\" do\n StdNum::ISBN.convert_to_13('9780306406157').must_equal '9780306406157'\n end\n\n it \"converts 13 to 10\" do\n StdNum::ISBN.convert_to_10('978-0-306-40615-7').must_equal '0306406152'\n end\n\n it \"normalizes\" do\n StdNum::ISBN.normalize('0-306-40615-2').must_equal '9780306406157'\n StdNum::ISBN.normalize('0-306-40615-X').must_equal nil\n StdNum::ISBN.normalize('ISBN: 978-0-306-40615-7').must_equal '9780306406157'\n StdNum::ISBN.normalize('ISBN: 978-0-306-40615-3').must_equal nil\n end\n\n it \"gets both normalized values\" do\n a = StdNum::ISBN.allNormalizedValues('978-0-306-40615-7')\n a.sort.must_equal ['9780306406157', '0306406152' ].sort\n\n a = StdNum::ISBN.allNormalizedValues('0-306-40615-2')\n a.sort.must_equal ['9780306406157', '0306406152' ].sort\n end\n\n it \"identifies an invalid ISBN13 due to the prefix\" do\n StdNum::ISBN.valid_isbn13_prefix?('9780000000002').must_equal true\n StdNum::ISBN.valid?('1000000000012').must_equal false\n end\n\nend\n\n\n\ndescribe 'ISSN' do\n it \"computes checksum\" do\n StdNum::ISSN.checkdigit('0378-5955').must_equal '5'\n end\n\n it \"normalizes\" do\n StdNum::ISSN.normalize('0378-5955').must_equal '03785955'\n end\nend\n\n\ndescribe 'LCCN basics' do\n\n # Tests take from http://www.loc.gov/marc/lccn-namespace.html#syntax\n test = {\n \"n78-890351\" => \"n78890351\",\n \"n78-89035\" => \"n78089035\",\n \"n 78890351 \" => \"n78890351\",\n \" 85000002 \" => \"85000002\",\n \"85-2 \" => \"85000002\",\n \"2001-000002\" => \"2001000002\",\n \"75-425165//r75\" => \"75425165\",\n \" 79139101 /AC/r932\" => \"79139101\",\n }\n\n test.each do |k, v|\n it \"normalizes #{k}\" do\n StdNum::LCCN.normalize(k.dup).must_equal v\n end\n end\n\n it \"validates correctly\" do\n StdNum::LCCN.valid?(\"n78-890351\").must_equal true\n StdNum::LCCN.valid?(\"n78-89035100444\").must_equal false, \"Too long\"\n StdNum::LCCN.valid?(\"n78\").must_equal false, \"Too short\"\n StdNum::LCCN.valid?(\"na078-890351\").must_equal false, \"naa78-890351 should start with three letters or digits\"\n StdNum::LCCN.valid?(\"n078-890351\").must_equal false, \"n078-890351 should start with two letters or two digits\"\n StdNum::LCCN.valid?(\"na078-890351\").must_equal false, \"na078-890351 should start with three letters or digits\"\n StdNum::LCCN.valid?(\"0an78-890351\").must_equal false, \"0an78-890351 should start with three letters or digits\"\n StdNum::LCCN.valid?(\"n78-89c0351\").must_equal false, \"n78-89c0351 has a letter after the dash\"\n end\n\n\nend\n\n\ndescribe \"LCCN tests from Business::LCCN perl module\" do\n tests = [\n { :orig => 'n78-890351',\n :canonical => 'n 78890351 ',\n :normalized => 'n78890351',\n :prefix => 'n',\n :year_cataloged => 1978,\n :serial => '890351',\n },\n { :orig => 'n 78890351 ',\n :canonical => 'n 78890351 ',\n :normalized => 'n78890351',\n :prefix => 'n',\n :year_cataloged => 1978,\n :serial => '890351',\n },\n { :orig => ' 85000002 ',\n :canonical => ' 85000002 ',\n :normalized => '85000002',\n :year_cataloged => 1985,\n :serial => '000002',\n },\n { :orig => '85-2 ',\n :canonical => ' 85000002 ',\n :normalized => '85000002',\n :year_cataloged => 1985,\n :serial => '000002',\n },\n { :orig => '2001-000002',\n :canonical => ' 2001000002',\n :normalized => '2001000002',\n :year_cataloged => 2001,\n :serial => '000002',\n },\n { :orig => '75-425165//r75',\n :canonical => ' 75425165 //r75',\n :normalized => '75425165',\n :prefix => '',\n :year_cataloged => nil,\n :serial => '425165',\n :revision_year => 1975,\n :revision_year_encoded => '75',\n :revision_number => nil,\n },\n { :orig => ' 79139101 /AC/r932',\n :canonical => ' 79139101 /AC/r932',\n :normalized => '79139101',\n :prefix => '',\n :year_cataloged => nil,\n :serial => '139101',\n :suffix_encoded => '/AC',\n :revision_year => 1993,\n :revision_year_encoded => '93',\n :revision_number => 2,\n },\n { :orig => '89-4',\n :canonical => ' 89000004 ',\n :normalized => '89000004',\n :year_cataloged => 1989,\n :serial => '000004',\n },\n { :orig => '89-45',\n :canonical => ' 89000045 ',\n :normalized => '89000045',\n :year_cataloged => 1989,\n :serial => '000045',\n },\n { :orig => '89-456',\n :canonical => ' 89000456 ',\n :normalized => '89000456',\n :year_cataloged => 1989,\n :serial => '000456',\n },\n { :orig => '89-1234',\n :canonical => ' 89001234 ',\n :normalized => '89001234',\n :year_cataloged => 1989,\n :serial => '001234',\n },\n { :orig => '89-001234',\n :canonical => ' 89001234 ',\n :normalized => '89001234',\n :year_cataloged => 1989,\n :serial => '001234',\n },\n { :orig => '89001234',\n :canonical => ' 89001234 ',\n :normalized => '89001234',\n :year_cataloged => 1989,\n :serial => '001234',\n },\n { :orig => '2002-1234',\n :canonical => ' 2002001234',\n :normalized => '2002001234',\n :year_cataloged => 2002,\n :serial => '001234',\n },\n { :orig => '2002-001234',\n :canonical => ' 2002001234',\n :normalized => '2002001234',\n :year_cataloged => 2002,\n :serial => '001234',\n },\n { :orig => '2002001234',\n :canonical => ' 2002001234',\n :normalized => '2002001234',\n :year_cataloged => 2002,\n :serial => '001234',\n },\n { :orig => ' 89001234 ',\n :canonical => ' 89001234 ',\n :normalized => '89001234',\n :year_cataloged => 1989,\n :serial => '001234',\n },\n { :orig => ' 2002001234',\n :canonical => ' 2002001234',\n :normalized => '2002001234',\n :year_cataloged => 2002,\n :serial => '001234',\n },\n { :orig => 'a89-1234',\n :canonical => 'a 89001234 ',\n :normalized => 'a89001234',\n :prefix => 'a',\n :year_cataloged => 1989,\n :serial => '001234',\n },\n { :orig => 'a89-001234',\n :canonical => 'a 89001234 ',\n :normalized => 'a89001234',\n :prefix => 'a',\n :year_cataloged => 1989,\n :serial => '001234',\n },\n { :orig => 'a89001234',\n :canonical => 'a 89001234 ',\n :normalized => 'a89001234',\n :prefix => 'a',\n :year_cataloged => 1989,\n :serial => '001234',\n },\n { :orig => 'a2002-1234',\n :canonical => 'a 2002001234',\n :normalized => 'a2002001234',\n :prefix => 'a',\n :year_cataloged => 2002,\n :serial => '001234',\n },\n { :orig => 'a2002-001234',\n :canonical => 'a 2002001234',\n :normalized => 'a2002001234',\n :prefix => 'a',\n :year_cataloged => 2002,\n :serial => '001234',\n },\n { :orig => 'a2002001234',\n :canonical => 'a 2002001234',\n :normalized => 'a2002001234',\n :prefix => 'a',\n :year_cataloged => 2002,\n :serial => '001234',\n },\n { :orig => 'a 89001234 ',\n :canonical => 'a 89001234 ',\n :normalized => 'a89001234',\n :prefix => 'a',\n :year_cataloged => 1989,\n :serial => '001234',\n },\n { :orig => 'a 89-001234 ',\n :canonical => 'a 89001234 ',\n :normalized => 'a89001234',\n :prefix => 'a',\n :year_cataloged => 1989,\n :serial => '001234',\n },\n { :orig => 'a 2002001234',\n :canonical => 'a 2002001234',\n :normalized => 'a2002001234',\n :prefix => 'a',\n :year_cataloged => 2002,\n :serial => '001234',\n },\n { :orig => 'ab89-1234',\n :canonical => 'ab 89001234 ',\n :normalized => 'ab89001234',\n :prefix => 'ab',\n :year_cataloged => 1989,\n :serial => '001234',\n },\n { :orig => 'ab89-001234',\n :canonical => 'ab 89001234 ',\n :normalized => 'ab89001234',\n :prefix => 'ab',\n :year_cataloged => 1989,\n :serial => '001234',\n },\n { :orig => 'ab89001234',\n :canonical => 'ab 89001234 ',\n :normalized => 'ab89001234',\n :prefix => 'ab',\n :year_cataloged => 1989,\n :serial => '001234',\n },\n { :orig => 'ab2002-1234',\n :canonical => 'ab2002001234',\n :normalized => 'ab2002001234',\n :prefix => 'ab',\n :year_cataloged => 2002,\n :serial => '001234',\n },\n { :orig => 'ab2002-001234',\n :canonical => 'ab2002001234',\n :normalized => 'ab2002001234',\n :prefix => 'ab',\n :year_cataloged => 2002,\n :serial => '001234',\n },\n { :orig => 'ab2002001234',\n :canonical => 'ab2002001234',\n :normalized => 'ab2002001234',\n :prefix => 'ab',\n :year_cataloged => 2002,\n :serial => '001234',\n },\n { :orig => 'ab 89001234 ',\n :canonical => 'ab 89001234 ',\n :normalized => 'ab89001234',\n :prefix => 'ab',\n :year_cataloged => 1989,\n :serial => '001234',\n },\n { :orig => 'ab 2002001234',\n :canonical => 'ab2002001234',\n :normalized => 'ab2002001234',\n :prefix => 'ab',\n :year_cataloged => 2002,\n :serial => '001234',\n },\n { :orig => 'ab 89-1234',\n :canonical => 'ab 89001234 ',\n :normalized => 'ab89001234',\n :prefix => 'ab',\n :year_cataloged => 1989,\n :serial => '001234',\n },\n { :orig => 'abc89-1234',\n :canonical => 'abc89001234 ',\n :normalized => 'abc89001234',\n :prefix => 'abc',\n :year_cataloged => 1989,\n :serial => '001234',\n },\n { :orig => 'abc89-001234',\n :canonical => 'abc89001234 ',\n :normalized => 'abc89001234',\n :prefix => 'abc',\n :year_cataloged => 1989,\n :serial => '001234',\n },\n { :orig => 'abc89001234',\n :canonical => 'abc89001234 ',\n :normalized => 'abc89001234',\n :prefix => 'abc',\n :year_cataloged => 1989,\n :serial => '001234',\n },\n { :orig => 'abc89001234 ',\n :canonical => 'abc89001234 ',\n :normalized => 'abc89001234',\n :prefix => 'abc',\n :year_cataloged => 1989,\n :serial => '001234',\n },\n { :orig => 'http://lccn.loc.gov/89001234',\n :canonical => ' 89001234 ',\n :normalized => '89001234',\n :year_cataloged => 1989,\n :serial => '001234',\n },\n { :orig => 'http://lccn.loc.gov/a89001234',\n :canonical => 'a 89001234 ',\n :normalized => 'a89001234',\n :serial => '001234',\n :prefix => 'a',\n :year_cataloged => 1989,\n },\n { :orig => 'http://lccn.loc.gov/ab89001234',\n :canonical => 'ab 89001234 ',\n :normalized => 'ab89001234',\n :prefix => 'ab',\n :year_cataloged => 1989,\n :serial => '001234',\n },\n { :orig => 'http://lccn.loc.gov/abc89001234',\n :canonical => 'abc89001234 ',\n :normalized => 'abc89001234',\n :prefix => 'abc',\n :year_cataloged => 1989,\n :serial => '001234',\n },\n { :orig => 'http://lccn.loc.gov/2002001234',\n :canonical => ' 2002001234',\n :normalized => '2002001234',\n :year_cataloged => 2002,\n :serial => '001234',\n },\n { :orig => 'http://lccn.loc.gov/a2002001234',\n :canonical => 'a 2002001234',\n :normalized => 'a2002001234',\n :prefix => 'a',\n :year_cataloged => 2002,\n :serial => '001234',\n },\n { :orig => 'http://lccn.loc.gov/ab2002001234',\n :canonical => 'ab2002001234',\n :normalized => 'ab2002001234',\n :prefix => 'ab',\n :year_cataloged => 2002,\n :serial => '001234',\n },\n { :orig => '00-21595',\n :canonical => ' 00021595 ',\n :normalized => '00021595',\n :year_cataloged => 2000,\n :serial => '021595',\n },\n { :orig => '2001001599',\n :canonical => ' 2001001599',\n :normalized => '2001001599',\n :year_cataloged => 2001,\n :serial => '001599',\n },\n { :orig => '99-18233',\n :canonical => ' 99018233 ',\n :normalized => '99018233',\n :year_cataloged => 1999,\n :serial => '018233',\n },\n { :orig => '98000595',\n :canonical => ' 98000595 ',\n :normalized => '98000595',\n :year_cataloged => 1898,\n :serial => '000595',\n },\n { :orig => '99005074',\n :canonical => ' 99005074 ',\n :normalized => '99005074',\n :year_cataloged => 1899,\n :serial => '005074',\n },\n { :orig => '00003373',\n :canonical => ' 00003373 ',\n :normalized => '00003373',\n :year_cataloged => 1900,\n :serial => '003373',\n },\n { :orig => '01001599',\n :canonical => ' 01001599 ',\n :normalized => '01001599',\n :year_cataloged => 1901,\n :serial => '001599',\n },\n { :orig => ' 95156543 ',\n :canonical => ' 95156543 ',\n :normalized => '95156543',\n :year_cataloged => 1995,\n :serial => '156543',\n },\n { :orig => ' 94014580 /AC/r95',\n :canonical => ' 94014580 /AC/r95',\n :normalized => '94014580',\n :year_cataloged => 1994,\n :serial => '014580',\n :suffix_encoded => '/AC',\n :revision_year_encoded => '95',\n :revision_year => 1995,\n },\n { :orig => ' 79310919 //r86',\n :canonical => ' 79310919 //r86',\n :normalized => '79310919',\n :year_cataloged => 1979,\n :serial => '310919',\n :revision_year_encoded => '86',\n :revision_year => 1986,\n },\n { :orig => 'gm 71005810 ',\n :canonical => 'gm 71005810 ',\n :normalized => 'gm71005810',\n :prefix => 'gm',\n :year_cataloged => 1971,\n :serial => '005810',\n },\n { :orig => 'sn2006058112 ',\n :canonical => 'sn2006058112',\n :normalized => 'sn2006058112',\n :prefix => 'sn',\n :year_cataloged => 2006,\n :serial => '058112',\n },\n { :orig => 'gm 71-2450',\n :canonical => 'gm 71002450 ',\n :normalized => 'gm71002450',\n :prefix => 'gm',\n :year_cataloged => 1971,\n :serial => '002450',\n },\n { :orig => '2001-1114',\n :canonical => ' 2001001114',\n :normalized => '2001001114',\n :year_cataloged => 2001,\n :serial => '001114',\n },\n ]\n tests.each do |h|\n it \"normalizes #{h[:orig]}\" do\n StdNum::LCCN.normalize(h[:orig]).must_equal h[:normalized], \"#{h[:orig]} doesn't normalize to #{h[:normalized]}\"\n end\n end\nend\n\n"}} -{"repo": "newism/nsm.tiny_mce.ee_addon", "pr_number": 16, "title": "Avoid developer log warning in EE 2.6 and up", "state": "closed", "merged_at": "2013-07-17T09:42:45Z", "additions": 1, "deletions": 1, "files_changed": ["ft.nsm_tiny_mce.php"], "files_before": {"ft.nsm_tiny_mce.php": " - Technical Director, Newism\n * @copyright \t\tCopyright (c) 2007-2010 Newism \n * @license \t\tCommercial - please see LICENSE file included with this distribution\n * @link\t\t\thttp://ee-garage.com/nsm-tiny-mce\n * @see\t\t\t\thttp://expressionengine.com/public_beta/docs/development/fieldtypes.html\n */\nclass Nsm_tiny_mce_ft extends EE_Fieldtype\n{\n\t/**\n\t * Field info - Required\n\t *\n\t * @access public\n\t * @var array\n\t */\n\tpublic $info = array(\n\t\t'name'\t\t=> 'NSM TinyMCE',\n\t\t'version'\t=> '1.1.1'\n\t);\n\n\t/**\n\t * The field settings array\n\t *\n\t * @access public\n\t * @var array\n\t */\n\tpublic $settings = array();\n\n\t/**\n\t * Path to the TinyMCE config files. Set in the constructor\n\t *\n\t * @access private\n\t * @var string\n\t */\n\tprivate $tiny_mce_config_path = \"\";\n\n\t/**\n\t * The field type - used for form field prefixes. Must be unique and match the class name. Set in the constructor\n\t *\n\t * @access private\n\t * @var string\n\t */\n\tprivate $field_type = '';\n\n\t/**\n\t * Constructor\n\t *\n\t * @access public\n\t *\n\t * Calls the parent constructor\n\t * Sets the tiny_mce_config_path using the PATH_THRID variable\n\t */\n\tpublic function __construct()\n\t{\n\t\tparent::EE_Fieldtype();\n\n\t\t$this->tiny_mce_config_path = PATH_THIRD_THEMES . \"nsm_tiny_mce/scripts/tiny_mce_config/\";\n\n\t\t$this->field_type = $this->addon_id = strtolower(substr(__CLASS__, 0, -3));\n\n\t\tif(!isset($this->EE->session->cache[__CLASS__]))\n\t\t{\n\t\t\t$this->EE->session->cache[__CLASS__]['loaded_configs'] = array();\n\t\t}\n\t}\n\n\t/**\n\t * Replaces the custom field tag\n\t *\n\t * @access public\n\t * @param $data string Contains the field data (or prepped data, if using pre_process)\n\t * @param $params array Contains field parameters (if any)\n\t * @param $tagdata mixed Contains data between tag (for tag pairs) FALSE for single tags\n\t * @return string The HTML replacing the tag\n\t *\n\t */\n\tpublic function replace_tag($data, $params = FALSE, $tagdata = FALSE)\n\t{\n\t\treturn $data;\n\t}\n\n\t/**\n\t * Display the field in the publish form\n\t *\n\t * @access public\n\t * @param $data String Contains the current field data. Blank for new entries.\n\t * @return String The custom field HTML\n\t *\n\t * Includes the TinyMCE base script and the field specific configuration.\n\t * Returns a standard textarea with a configuration specific class\n\t */\n\tpublic function display_field($data, $field_id = false)\n\t{\n\t\t$this->_addConfJs($this->settings[\"conf\"]);\n\n\t\tif(!$field_id)\n\t\t\t$field_id = $this->field_name;\n\n\t\t$this->EE->cp->add_to_foot('');\n\n\t\treturn form_textarea(array(\n\t\t\t'name'\t=> $this->field_name,\n\t\t\t'id'\t=> $field_id,\n\t\t\t'value'\t=> $data,\n\t\t\t'rows' => ' ',\n\t\t\t'style' => \"height: {$this->settings['height']}px\"\n\t\t));\n\t}\n\n\t/**\n\t * Displays the cell\n\t *\n\t * @access public\n\t * @param $data The cell data\n\t */\n\tpublic function display_cell($data)\n\t{\n\t\t$this->_addConfJs($this->settings[\"conf\"]);\n\n\t\tif(!isset($this->EE->session->cache[__CLASS__]['cell_js_loaded']))\n\t\t{\n\t\t\t$theme_url = $this->_getThemeUrl();\n\t\t\t$this->EE->cp->add_to_foot(\"\");\n\t\t\t$this->EE->session->cache[__CLASS__]['cell_js_loaded'] = TRUE;\n\t\t}\n\n\t\t$this->EE->cp->add_to_foot('');\n\n\t\treturn '';\n\t}\n\n\t/**\n\t * Displays the Low Variable field\n\t *\n\t * @access public\n\t * @param $var_data The variable data\n\t * @see http://loweblog.com/software/low-variables/docs/fieldtype-bridge/\n\t */\n\tpublic function display_var_field($var_data)\n\t{\n\t\treturn $this->display_field($var_data, \"nsm_tiny_mce_\" . substr($this->field_name, 4, 1));\n\t}\n\n\t/**\n\t * Publish form validation\n\t *\n\t * @param $data array Contains the submitted field data.\n\t * @return mixed TRUE or an error message\n\t */\n\tpublic function validate($data)\n\t{\n\t\treturn TRUE;\n\t}\n\n\t/**\n\t * Default field settings\n\t *\n\t * @access private\n\t * @return The default field settings\n\t */\n\tprivate function _defaultFieldSettings(){\n\t\treturn array(\n\t\t\t\"conf\" => FALSE,\n\t\t\t\"height\" => 300\n\t\t);\n\t}\n\n\t/**\n\t * Save the custom field settings\n\t *\n\t * @param $data array Not sure what this is yet, probably the submitted post data.\n\t * @return boolean Valid or not\n\t */\n\tpublic function save_settings($field_settings)\n\t{\n\t\t$field_settings = array_merge($this->_defaultFieldSettings(), $this->EE->input->post('nsm_tiny_mce'));\n\n\t\t// Force formatting\n\t\t$field_settings['field_fmt'] = 'none';\n\t\t$field_settings['field_show_fmt'] = 'n';\n\t\t$field_settings['field_type'] = 'nsm_tiny_mce';\n\n\t\t// Cleanup\n\t\tunset($_POST['nsm_tiny_mce']);\n\t\tforeach (array_keys($field_settings) as $setting)\n\t\t{\n\t\t\tif (isset($_POST[\"nsm_tiny_mce_{$setting}\"]))\n\t\t\t{\n\t\t\t\tunset($_POST[\"nsm_tiny_mce_{$setting}\"]);\n\t\t\t}\n\t\t}\n\n\t\treturn $field_settings;\n\t}\n\n\t/**\n\t * Process the cell settings before saving\n\t *\n\t * @access public\n\t * @param $col_settings array The settings for the column\n\t * @return array The new settings\n\t */\n\tpublic function save_cell_settings($col_settings)\n\t{\n\t\t$col_settings = $col_settings['nsm_tiny_mce'];\n\t\treturn $col_settings;\n\t}\n\n\t/**\n\t * Save the Low variable settings\n\t *\n\t * @access public\n\t * @param $var_settings The variable settings\n\t * @see http://loweblog.com/software/low-variables/docs/fieldtype-bridge/\n\t */\n\tpublic function save_var_settings($var_settings)\n\t{\n\t\treturn $this->EE->input->post('nsm_tiny_mce');\n\t}\n\n\n\n\n\t/**\n\t * Prepares settings array for fields and matrix cells\n\t *\n\t * @access public\n\t * @param $settings array The field / cell settings\n\t * @return array Labels and form inputs\n\t */\n\tprivate function _fieldSettings($settings)\n\t{\n\t\t$r = array();\n\n\t\t// TinyMCE height\n\t\t$r[] = array(\n\t\t\tlang('Height in px', 'nsm_tiny_mce_height'),\n\t\t\tform_input(\"nsm_tiny_mce[height]\", $settings['height'], \"id='nsm_tiny_mce_height' class='matrix-textarea'\")\n\t\t);\n\n\t\t// Configs\n\t\tif($configs = $this->_readTinyMCEConfigs())\n\t\t{\n\t\t\tforeach ($configs as $key => $value)\n\t\t\t{\n\t\t\t\t$options[$key] = ucfirst(str_replace(array(\"_\", \".js\"), array(\"\"), $key));\n\t\t\t}\n\t\t\t$confs = form_dropdown(\"nsm_tiny_mce[conf]\", $options, $settings['conf'], \"id='nsm_tiny_mce_conf'\");\n\t\t}\n\t\telse\n\t\t{\n\t\t\t$confs = \"

    \n\t\t\t\t\t\t\tNo configuration files could be found. Check that\n\t\t\t\t\t\t\t\".$this->tiny_mce_config_path.\"\n\t\t\t\t\t\t\tis readable and contains at least one configuration file.\n\t\t\t\t\t\t

    \";\n\t\t\t$confs .= form_hidden(\"nsm_tiny_mce[conf]\", '');\n\t\t}\n\n\t\t$r[] = array(\n\t\t\t\t\tlang('Configuration', 'nsm_tiny_mce_conf'),\n\t\t\t\t\t$confs\n\t\t\t\t);\n\n\t\treturn $r;\n\t}\n\n\t/**\n\t * Display the settings form for each custom field\n\t *\n\t * @access public\n\t * @param $data mixed Not sure what this data is yet :S\n\t * @return string Override the field custom settings with custom html\n\t *\n\t * In this case we add an extra row to the table. Not sure how the table is built\n\t */\n\tpublic function display_settings($field_settings)\n\t{\n\t\t$field_settings = array_merge($this->_defaultFieldSettings(), $field_settings);\n\t\t$rows = $this->_fieldSettings($field_settings);\n\n\t\t// add the rows\n\t\tforeach ($rows as $row)\n\t\t{\n\t\t\t$this->EE->table->add_row($row[0], $row[1]);\n\t\t}\n\t}\n\n\t/**\n\t * Display Cell Settings\n\t *\n\t * @access public\n\t * @param $cell_settings array The cell settings\n\t * @return array Label and form inputs\n\t */\n\tpublic function display_cell_settings($cell_settings)\n\t{\n\t\t$cell_settings = array_merge($this->_defaultFieldSettings(), $cell_settings);\n\t\treturn $this->_fieldSettings($cell_settings);\n\t}\n\n\t/**\n\t * Display Variable Settings\n\t *\n\t * @access public\n\t * @param $var_settings array The variable settings\n\t * @return array Label and form inputs\n\t */\n\tpublic function display_var_settings($var_settings)\n\t{\n\t\t$var_settings = array_merge($this->_defaultFieldSettings(), $var_settings);\n\t\treturn $this->_fieldSettings($var_settings);\n\t}\n\n\t/**\n\t * Adds the TinyMCE configuration to the CP\n\t */\n\tprivate function _addConfJs($conf, $cell = FALSE)\n\t{\n\n\t\t$theme_url = $this->_getThemeUrl();\n\n\t\tif(!isset($this->EE->session->cache[__CLASS__]['tiny_mce_loaded']))\n\t\t{\n\t\t\t$this->EE->cp->add_to_head(\"\");\n\n\t\t\t$this->EE->cp->add_to_foot(\"\");\n\t\t\t$this->EE->cp->add_to_foot('');\n\t\t\t$this->EE->session->cache[__CLASS__]['tiny_mce_loaded'] = TRUE;\n\t\t}\n\n\t\tif(!in_array($conf, $this->EE->session->cache[__CLASS__]['loaded_configs']))\n\t\t{\n\t\t\t$this->EE->session->cache[__CLASS__]['loaded_configs'][] = $conf;\n\t\t\t$this->EE->cp->add_to_foot(\"\");\n\n\t\t}\n\t}\n\n\t/**\n\t * Get the current themes URL from the theme folder + / + the addon id\n\t *\n\t * @access private\n\t * @return string The theme URL\n\t */\n\tprivate function _getThemeUrl()\n\t{\n\t\t$EE =& get_instance();\n\t\tif(!isset($EE->session->cache[$this->addon_id]['theme_url']))\n\t\t{\n\t\t\t$theme_url = URL_THIRD_THEMES;\n\t\t\tif (substr($theme_url, -1) != '/') $theme_url .= '/';\n\t\t\t$theme_url .= $this->addon_id;\n\t\t\t$EE->session->cache[$this->addon_id]['theme_url'] = $theme_url;\n\t\t}\n\t\treturn $EE->session->cache[$this->addon_id]['theme_url'];\n\t}\n\n\t/**\n\t * Reads the custom TinyMCE configs from the directory\n\t *\n\t * @access private\n\t * @return mixed FALSE if no configs are found or an array of filenames\n\t */\n\tprivate function _readTinyMCEConfigs()\n\t{\n\t\t// have the configs been processed?\n\t\tif(isset($this->EE->session->cache[__CLASS__]['tiny_mce_configs']) === FALSE)\n\t\t{\n\t\t\t// assume there are no configs\n\t\t\t$configs = FALSE;\n\t\t\t// if the provided string an actual directory\n\t\t\tif(is_dir($dir = $this->tiny_mce_config_path))\n\t\t\t{\n\t\t\t\t// open the directory and assign it to a handle\n\t\t\t\t$dir_handle = opendir($dir);\n\t\t\t\t// if there is a dir handle\n\t\t\t\tif($dir_handle)\n\t\t\t\t{\n\t\t\t\t\t/* This is the correct way to loop over the directory. */\n\t\t \t\t// loop over the files\n\t\t\t\t\twhile (false !== ($file = readdir($dir_handle)))\n\t\t\t\t\t{\n\t\t\t\t\t\t// if this is a real file\n\t\t\t\t\t\tif ($file != \".\" && $file != \"..\" && $file != \"Thumb.db\" && substr($file, 0, 1) != '-' && substr($file, -3) == \".js\")\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// add the config to the list\n\t\t\t\t\t\t\t$configs[$file] = file_get_contents($dir.$file);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t// assign the configs to a session var\n\t\t\t$this->EE->session->cache[__CLASS__]['tiny_mce_configs'] = $configs;\n\t\t}\n\n\t\t// return the session var\n\t\treturn $this->EE->session->cache[__CLASS__]['tiny_mce_configs'];\n\t}\n\n}\n//END CLASS"}, "files_after": {"ft.nsm_tiny_mce.php": " - Technical Director, Newism\n * @copyright \t\tCopyright (c) 2007-2010 Newism \n * @license \t\tCommercial - please see LICENSE file included with this distribution\n * @link\t\t\thttp://ee-garage.com/nsm-tiny-mce\n * @see\t\t\t\thttp://expressionengine.com/public_beta/docs/development/fieldtypes.html\n */\nclass Nsm_tiny_mce_ft extends EE_Fieldtype\n{\n\t/**\n\t * Field info - Required\n\t *\n\t * @access public\n\t * @var array\n\t */\n\tpublic $info = array(\n\t\t'name'\t\t=> 'NSM TinyMCE',\n\t\t'version'\t=> '1.1.1'\n\t);\n\n\t/**\n\t * The field settings array\n\t *\n\t * @access public\n\t * @var array\n\t */\n\tpublic $settings = array();\n\n\t/**\n\t * Path to the TinyMCE config files. Set in the constructor\n\t *\n\t * @access private\n\t * @var string\n\t */\n\tprivate $tiny_mce_config_path = \"\";\n\n\t/**\n\t * The field type - used for form field prefixes. Must be unique and match the class name. Set in the constructor\n\t *\n\t * @access private\n\t * @var string\n\t */\n\tprivate $field_type = '';\n\n\t/**\n\t * Constructor\n\t *\n\t * @access public\n\t *\n\t * Calls the parent constructor\n\t * Sets the tiny_mce_config_path using the PATH_THRID variable\n\t */\n\tpublic function __construct()\n\t{\n\t\tparent::__construct();\n\n\t\t$this->tiny_mce_config_path = PATH_THIRD_THEMES . \"nsm_tiny_mce/scripts/tiny_mce_config/\";\n\n\t\t$this->field_type = $this->addon_id = strtolower(substr(__CLASS__, 0, -3));\n\n\t\tif(!isset($this->EE->session->cache[__CLASS__]))\n\t\t{\n\t\t\t$this->EE->session->cache[__CLASS__]['loaded_configs'] = array();\n\t\t}\n\t}\n\n\t/**\n\t * Replaces the custom field tag\n\t *\n\t * @access public\n\t * @param $data string Contains the field data (or prepped data, if using pre_process)\n\t * @param $params array Contains field parameters (if any)\n\t * @param $tagdata mixed Contains data between tag (for tag pairs) FALSE for single tags\n\t * @return string The HTML replacing the tag\n\t *\n\t */\n\tpublic function replace_tag($data, $params = FALSE, $tagdata = FALSE)\n\t{\n\t\treturn $data;\n\t}\n\n\t/**\n\t * Display the field in the publish form\n\t *\n\t * @access public\n\t * @param $data String Contains the current field data. Blank for new entries.\n\t * @return String The custom field HTML\n\t *\n\t * Includes the TinyMCE base script and the field specific configuration.\n\t * Returns a standard textarea with a configuration specific class\n\t */\n\tpublic function display_field($data, $field_id = false)\n\t{\n\t\t$this->_addConfJs($this->settings[\"conf\"]);\n\n\t\tif(!$field_id)\n\t\t\t$field_id = $this->field_name;\n\n\t\t$this->EE->cp->add_to_foot('');\n\n\t\treturn form_textarea(array(\n\t\t\t'name'\t=> $this->field_name,\n\t\t\t'id'\t=> $field_id,\n\t\t\t'value'\t=> $data,\n\t\t\t'rows' => ' ',\n\t\t\t'style' => \"height: {$this->settings['height']}px\"\n\t\t));\n\t}\n\n\t/**\n\t * Displays the cell\n\t *\n\t * @access public\n\t * @param $data The cell data\n\t */\n\tpublic function display_cell($data)\n\t{\n\t\t$this->_addConfJs($this->settings[\"conf\"]);\n\n\t\tif(!isset($this->EE->session->cache[__CLASS__]['cell_js_loaded']))\n\t\t{\n\t\t\t$theme_url = $this->_getThemeUrl();\n\t\t\t$this->EE->cp->add_to_foot(\"\");\n\t\t\t$this->EE->session->cache[__CLASS__]['cell_js_loaded'] = TRUE;\n\t\t}\n\n\t\t$this->EE->cp->add_to_foot('');\n\n\t\treturn '';\n\t}\n\n\t/**\n\t * Displays the Low Variable field\n\t *\n\t * @access public\n\t * @param $var_data The variable data\n\t * @see http://loweblog.com/software/low-variables/docs/fieldtype-bridge/\n\t */\n\tpublic function display_var_field($var_data)\n\t{\n\t\treturn $this->display_field($var_data, \"nsm_tiny_mce_\" . substr($this->field_name, 4, 1));\n\t}\n\n\t/**\n\t * Publish form validation\n\t *\n\t * @param $data array Contains the submitted field data.\n\t * @return mixed TRUE or an error message\n\t */\n\tpublic function validate($data)\n\t{\n\t\treturn TRUE;\n\t}\n\n\t/**\n\t * Default field settings\n\t *\n\t * @access private\n\t * @return The default field settings\n\t */\n\tprivate function _defaultFieldSettings(){\n\t\treturn array(\n\t\t\t\"conf\" => FALSE,\n\t\t\t\"height\" => 300\n\t\t);\n\t}\n\n\t/**\n\t * Save the custom field settings\n\t *\n\t * @param $data array Not sure what this is yet, probably the submitted post data.\n\t * @return boolean Valid or not\n\t */\n\tpublic function save_settings($field_settings)\n\t{\n\t\t$field_settings = array_merge($this->_defaultFieldSettings(), $this->EE->input->post('nsm_tiny_mce'));\n\n\t\t// Force formatting\n\t\t$field_settings['field_fmt'] = 'none';\n\t\t$field_settings['field_show_fmt'] = 'n';\n\t\t$field_settings['field_type'] = 'nsm_tiny_mce';\n\n\t\t// Cleanup\n\t\tunset($_POST['nsm_tiny_mce']);\n\t\tforeach (array_keys($field_settings) as $setting)\n\t\t{\n\t\t\tif (isset($_POST[\"nsm_tiny_mce_{$setting}\"]))\n\t\t\t{\n\t\t\t\tunset($_POST[\"nsm_tiny_mce_{$setting}\"]);\n\t\t\t}\n\t\t}\n\n\t\treturn $field_settings;\n\t}\n\n\t/**\n\t * Process the cell settings before saving\n\t *\n\t * @access public\n\t * @param $col_settings array The settings for the column\n\t * @return array The new settings\n\t */\n\tpublic function save_cell_settings($col_settings)\n\t{\n\t\t$col_settings = $col_settings['nsm_tiny_mce'];\n\t\treturn $col_settings;\n\t}\n\n\t/**\n\t * Save the Low variable settings\n\t *\n\t * @access public\n\t * @param $var_settings The variable settings\n\t * @see http://loweblog.com/software/low-variables/docs/fieldtype-bridge/\n\t */\n\tpublic function save_var_settings($var_settings)\n\t{\n\t\treturn $this->EE->input->post('nsm_tiny_mce');\n\t}\n\n\n\n\n\t/**\n\t * Prepares settings array for fields and matrix cells\n\t *\n\t * @access public\n\t * @param $settings array The field / cell settings\n\t * @return array Labels and form inputs\n\t */\n\tprivate function _fieldSettings($settings)\n\t{\n\t\t$r = array();\n\n\t\t// TinyMCE height\n\t\t$r[] = array(\n\t\t\tlang('Height in px', 'nsm_tiny_mce_height'),\n\t\t\tform_input(\"nsm_tiny_mce[height]\", $settings['height'], \"id='nsm_tiny_mce_height' class='matrix-textarea'\")\n\t\t);\n\n\t\t// Configs\n\t\tif($configs = $this->_readTinyMCEConfigs())\n\t\t{\n\t\t\tforeach ($configs as $key => $value)\n\t\t\t{\n\t\t\t\t$options[$key] = ucfirst(str_replace(array(\"_\", \".js\"), array(\"\"), $key));\n\t\t\t}\n\t\t\t$confs = form_dropdown(\"nsm_tiny_mce[conf]\", $options, $settings['conf'], \"id='nsm_tiny_mce_conf'\");\n\t\t}\n\t\telse\n\t\t{\n\t\t\t$confs = \"

    \n\t\t\t\t\t\t\tNo configuration files could be found. Check that\n\t\t\t\t\t\t\t\".$this->tiny_mce_config_path.\"\n\t\t\t\t\t\t\tis readable and contains at least one configuration file.\n\t\t\t\t\t\t

    \";\n\t\t\t$confs .= form_hidden(\"nsm_tiny_mce[conf]\", '');\n\t\t}\n\n\t\t$r[] = array(\n\t\t\t\t\tlang('Configuration', 'nsm_tiny_mce_conf'),\n\t\t\t\t\t$confs\n\t\t\t\t);\n\n\t\treturn $r;\n\t}\n\n\t/**\n\t * Display the settings form for each custom field\n\t *\n\t * @access public\n\t * @param $data mixed Not sure what this data is yet :S\n\t * @return string Override the field custom settings with custom html\n\t *\n\t * In this case we add an extra row to the table. Not sure how the table is built\n\t */\n\tpublic function display_settings($field_settings)\n\t{\n\t\t$field_settings = array_merge($this->_defaultFieldSettings(), $field_settings);\n\t\t$rows = $this->_fieldSettings($field_settings);\n\n\t\t// add the rows\n\t\tforeach ($rows as $row)\n\t\t{\n\t\t\t$this->EE->table->add_row($row[0], $row[1]);\n\t\t}\n\t}\n\n\t/**\n\t * Display Cell Settings\n\t *\n\t * @access public\n\t * @param $cell_settings array The cell settings\n\t * @return array Label and form inputs\n\t */\n\tpublic function display_cell_settings($cell_settings)\n\t{\n\t\t$cell_settings = array_merge($this->_defaultFieldSettings(), $cell_settings);\n\t\treturn $this->_fieldSettings($cell_settings);\n\t}\n\n\t/**\n\t * Display Variable Settings\n\t *\n\t * @access public\n\t * @param $var_settings array The variable settings\n\t * @return array Label and form inputs\n\t */\n\tpublic function display_var_settings($var_settings)\n\t{\n\t\t$var_settings = array_merge($this->_defaultFieldSettings(), $var_settings);\n\t\treturn $this->_fieldSettings($var_settings);\n\t}\n\n\t/**\n\t * Adds the TinyMCE configuration to the CP\n\t */\n\tprivate function _addConfJs($conf, $cell = FALSE)\n\t{\n\n\t\t$theme_url = $this->_getThemeUrl();\n\n\t\tif(!isset($this->EE->session->cache[__CLASS__]['tiny_mce_loaded']))\n\t\t{\n\t\t\t$this->EE->cp->add_to_head(\"\");\n\n\t\t\t$this->EE->cp->add_to_foot(\"\");\n\t\t\t$this->EE->cp->add_to_foot('');\n\t\t\t$this->EE->session->cache[__CLASS__]['tiny_mce_loaded'] = TRUE;\n\t\t}\n\n\t\tif(!in_array($conf, $this->EE->session->cache[__CLASS__]['loaded_configs']))\n\t\t{\n\t\t\t$this->EE->session->cache[__CLASS__]['loaded_configs'][] = $conf;\n\t\t\t$this->EE->cp->add_to_foot(\"\");\n\n\t\t}\n\t}\n\n\t/**\n\t * Get the current themes URL from the theme folder + / + the addon id\n\t *\n\t * @access private\n\t * @return string The theme URL\n\t */\n\tprivate function _getThemeUrl()\n\t{\n\t\t$EE =& get_instance();\n\t\tif(!isset($EE->session->cache[$this->addon_id]['theme_url']))\n\t\t{\n\t\t\t$theme_url = URL_THIRD_THEMES;\n\t\t\tif (substr($theme_url, -1) != '/') $theme_url .= '/';\n\t\t\t$theme_url .= $this->addon_id;\n\t\t\t$EE->session->cache[$this->addon_id]['theme_url'] = $theme_url;\n\t\t}\n\t\treturn $EE->session->cache[$this->addon_id]['theme_url'];\n\t}\n\n\t/**\n\t * Reads the custom TinyMCE configs from the directory\n\t *\n\t * @access private\n\t * @return mixed FALSE if no configs are found or an array of filenames\n\t */\n\tprivate function _readTinyMCEConfigs()\n\t{\n\t\t// have the configs been processed?\n\t\tif(isset($this->EE->session->cache[__CLASS__]['tiny_mce_configs']) === FALSE)\n\t\t{\n\t\t\t// assume there are no configs\n\t\t\t$configs = FALSE;\n\t\t\t// if the provided string an actual directory\n\t\t\tif(is_dir($dir = $this->tiny_mce_config_path))\n\t\t\t{\n\t\t\t\t// open the directory and assign it to a handle\n\t\t\t\t$dir_handle = opendir($dir);\n\t\t\t\t// if there is a dir handle\n\t\t\t\tif($dir_handle)\n\t\t\t\t{\n\t\t\t\t\t/* This is the correct way to loop over the directory. */\n\t\t \t\t// loop over the files\n\t\t\t\t\twhile (false !== ($file = readdir($dir_handle)))\n\t\t\t\t\t{\n\t\t\t\t\t\t// if this is a real file\n\t\t\t\t\t\tif ($file != \".\" && $file != \"..\" && $file != \"Thumb.db\" && substr($file, 0, 1) != '-' && substr($file, -3) == \".js\")\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// add the config to the list\n\t\t\t\t\t\t\t$configs[$file] = file_get_contents($dir.$file);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t// assign the configs to a session var\n\t\t\t$this->EE->session->cache[__CLASS__]['tiny_mce_configs'] = $configs;\n\t\t}\n\n\t\t// return the session var\n\t\treturn $this->EE->session->cache[__CLASS__]['tiny_mce_configs'];\n\t}\n\n}\n//END CLASS"}} -{"repo": "fabriceb/sfFacebookConnectPlugin", "pr_number": 7, "title": "Doc + facebook object instanciation", "state": "closed", "merged_at": "2010-11-24T13:51:29Z", "additions": 47, "deletions": 7, "files_changed": ["lib/sfFacebook.class.php"], "files_before": {"lib/sfFacebook.class.php": ": new Facebook php-sdk\n */\n\n\n public static function getFacebookCookie()\n {\n $app_id = self::getApiKey();\n $application_secret = self::getApiSecret();\n $args = array();\n if (!isset($_COOKIE['fbs_' . $app_id]))\n {\n return null;\n }\n parse_str(trim($_COOKIE['fbs_' . $app_id], '\\\\\"'), $args);\n ksort($args);\n $payload = '';\n foreach ($args as $key => $value)\n {\n if ($key != 'sig')\n {\n $payload .= $key . '=' . $value;\n }\n }\n if (md5($payload . $application_secret) != $args['sig'])\n {\n return null;\n }\n return $args;\n }\n\n\n public static function getFacebookClient()\n {\n if (self::$client === null)\n {\n $params = array(\n 'appId' => self::getApiKey(),\n 'secret' => self::getApiSecret(),\n 'cookie' => self::getApiCookie(),\n 'domain' => self::getApiDomain()\n );\n\n self::$client = new Facebook($params);\n }\n\n if (!self::$client)\n {\n error_log('Could not create facebook client.');\n }\n\n return self::$client;\n }\n\n /**\n * get the facebook session\n *\n * @return Array\n * @author Benjamin Grandfond \n * @since 2010-05-13\n */\n public static function getSession()\n {\n\n return self::getFacebookClient()->getSession();\n }\n\n /**\n * get the facebook user\n *\n * @return Array\n * @author Benjamin Grandfond \n * @since 2010-05-13\n */\n public static function getUser()\n {\n\n return self::getFacebookClient()->getUser();\n }\n\n /**\n * get datas through the faceook graph api\n * @see http://developers.facebook.com/docs/api\n *\n * @return Array\n * @author Benjamin Grandfond \n * @since 2010-05-13\n */\n public static function getFacebookApi($param)\n {\n\n return self::getFacebookClient()->api($param);\n }\n\n /**\n * gets the facebook api key\n *\n * @return Facebook\n * @author fabriceb\n * @since 2009-05-17\n */\n public static function getApiKey()\n {\n\n return sfConfig::get('app_facebook_api_key');\n }\n\n /**\n * gets the facebook api secret\n *\n * @return Facebook\n * @author fabriceb\n * @since 2009-05-17\n */\n public static function getApiSecret()\n {\n\n return sfConfig::get('app_facebook_api_secret');\n }\n\n /**\n * get the facebook app cookie support\n *\n * @return Boolean\n * @author Benjamin Grandfond \n * @since 2010-05-12\n */\n public static function getApiCookie()\n {\n\n return sfConfig::get('app_facebook_api_cookie', true);\n }\n\n /**\n * get the facebook app domain\n *\n * @return Boolean\n * @author Benjamin Grandfond \n * @since 2010-05-12\n */\n public static function getApiDomain()\n {\n\n return sfConfig::get('app_facebook_api_domain', null);\n }\n\n /**\n * gets or create user with facebook uid inprofile\n *\n * @param Integer $facebook_uid\n * @param boolean $isActive\n * @return sfGuardUser $sfGuardUser\n */\n public static function getOrCreateUserByFacebookUid($facebook_uid, $isActive = true)\n {\n $sfGuardUser = self::getGuardAdapter()->getSfGuardUserByFacebookUid($facebook_uid, $isActive);\n\n if (!$sfGuardUser instanceof sfGuardUser)\n {\n if (sfConfig::get('sf_logging_enabled'))\n {\n sfContext::getInstance()->getLogger()->info('{sfFacebookConnect} No user exists with current email hash');\n }\n $sfGuardUser = self::getGuardAdapter()->createSfGuardUserWithFacebookUid($facebook_uid);\n }\n\n return $sfGuardUser;\n }\n\n /**\n * gets user with facebook uid inprofile\n *\n * @param Integer $facebook_uid\n * @param boolean $isActive\n * @return sfGuardUser $sfGuardUser\n */\n public static function getUserByFacebookUid($facebook_uid, $isActive = true)\n {\n $sfGuardUser = self::getGuardAdapter()->retrieveSfGuardUserByFacebookUid($facebook_uid, $isActive);\n\n if (!$sfGuardUser instanceof sfGuardUser)\n {\n if (sfConfig::get('sf_logging_enabled'))\n {\n sfContext::getInstance()->getLogger()->info('{sfFacebookConnect} No user exists with current email hash');\n }\n }\n\n return $sfGuardUser;\n }\n\n /**\n * Gets the currently logged sfGuardUser using Facebook Session\n *\n * @param boolean $create whether to automatically create a sfGuardUser\n * if none found corresponding to the Facebook session\n * @param boolean $isActive\n * @return sfGuardUser\n * @author fabriceb\n * @since 2009-05-17\n * @since 2009-08-25\n */\n public static function getSfGuardUserByFacebookSession($create = true, $isActive = true)\n {\n // We get the facebook uid from session\n $fb_uid = self::getAnyFacebookUid();\n if ($fb_uid)\n {\n\n if ($create)\n {\n\n return self::getOrCreateUserByFacebookUid($fb_uid, $isActive);\n }\n else\n {\n\n return self::getUserByFacebookUid($fb_uid, $isActive);\n }\n }\n\n if (sfConfig::get('sf_logging_enabled'))\n {\n sfContext::getInstance()->getLogger()->info('{sfFacebookConnect} No current Facebook session');\n }\n\n return null;\n }\n\n /**\n * checks the existence of the HTTP_X_FB_USER_REMOTE_ADDR porperty in the header\n * which is a sign of being included by the fbml interface\n *\n * @return boolean\n * @author fabriceb\n * @since Jun 8, 2009 fabriceb\n */\n public static function isInsideFacebook()\n {\n\n return isset($_SERVER['HTTP_X_FB_USER_REMOTE_ADDR']);\n }\n\n /**\n *\n * @return boolean\n * @author fabriceb\n * @since Jun 8, 2009 fabriceb\n */\n public static function inCanvas()\n {\n\n return self::getFacebookClient()->in_fb_canvas();\n }\n\n /**\n * redirects to the login page of the Facebook application if not logged yet\n *\n * @author fabriceb\n * @since Jun 8, 2009 fabriceb\n */\n public static function requireLogin()\n {\n self::getFacebookClient()->require_login();\n }\n\n /**\n * redirects depnding on in canvas or not\n *\n * @param $url\n * @param $statusCode\n * @return mixed sfView::NONE or sfStopException\n * @author fabriceb\n * @since Jun 8, 2009 fabriceb\n */\n public static function redirect($url, $statusCode = 302)\n {\n\n $context = sfContext::getInstance();\n $response = $context->getResponse();\n\n if (self::inCanvas())\n {\n $url = sfConfig::get('app_facebook_app_url').$context->getController()->genUrl($url, false);\n\n $text = '';\n $response->setContent(sfContext::getInstance()->getResponse()->getContent().$text);\n\n return sfView::NONE;\n }\n else\n {\n $fb_parameters = '?'.sfFacebook::getFacebookSigParameters(sfContext::getInstance()->getRequest());\n $url = $context->getController()->genUrl($url, true).$fb_parameters;\n\n $response->clearHttpHeaders();\n $response->setStatusCode($statusCode);\n $response->setHttpHeader('Location', $url);\n $response->setContent(sprintf('', 0, htmlspecialchars($url, ENT_QUOTES, sfConfig::get('sf_charset'))));\n $response->send();\n\n throw new sfStopException();\n }\n }\n\n /**\n *\n * @param integer $user_uid\n * @return integer[]\n * @author fabriceb\n * @since Jun 9, 2009 fabriceb\n */\n public static function getFacebookFriendsUids($user_uid = null)\n {\n\n try\n {\n $friends_uids = self::getFacebookApi()->friends_get(null, $user_uid);\n }\n catch(FacebookRestClientException $e)\n {\n $friends_uids = array();\n if (sfConfig::get('sf_logging_enabled'))\n {\n sfContext::getInstance()->getLogger()->info('{FacebookRestClientException} '.$e->getMessage());\n }\n }\n\n return $friends_uids;\n }\n\n /**\n *\n * @return sfFacebookGuardAdapter\n * @author fabriceb\n * @since Aug 10, 2009\n * @since 2009-10-08 Alban Creton : added configurability of the Guard Adapter.\n */\n public static function getGuardAdapter()\n {\n if (self::$guard_adapter === null)\n {\n if(sfConfig::get('app_facebook_guard_adapter') && class_exists(sfConfig::get('app_facebook_guard_adapter'), true))\n {\n $class = sfConfig::get('app_facebook_guard_adapter');\n }\n else if (class_exists('sfGuardUserPeer', true))\n {\n $class = 'sfFacebookPropelGuardAdapter';\n }\n else\n {\n $class = 'sfFacebookDoctrineGuardAdapter';\n }\n self::$guard_adapter = new $class();\n }\n if (!self::$guard_adapter)\n {\n error_log('Could not create guard adapter.');\n }\n\n return self::$guard_adapter;\n }\n\n\n /**\n *\n * @return boolean\n * @author fabriceb\n * @since Aug 27, 2009\n */\n public static function isJsLoaded()\n {\n\n return self::$is_js_loaded;\n }\n\n /**\n *\n * @return void\n * @author fabriceb\n * @since Aug 27, 2009\n */\n public static function setJsLoaded()\n {\n self::$is_js_loaded = true;\n }\n\n /**\n * Dirty way to convert fr into fr_FR\n * @param string $culture\n * @return string\n * @author fabriceb\n * @since Aug 28, 2009\n */\n public static function getLocale($culture = null)\n {\n if (is_null($culture))\n {\n $culture = sfContext::getInstance()->getUser()->getCulture();\n }\n\n $culture_to_locale = array(\n 'fr' => 'fr_FR',\n 'en' => 'en_US',\n 'de' => 'de_DE',\n 'it' => 'it_IT',\n );\n\n return array_key_exists($culture, $culture_to_locale) ? $culture_to_locale[$culture] : $culture;\n }\n\n /**\n * @return interger $facebook_uid\n * @author fabriceb\n * @since Oct 6, 2009\n */\n public static function getAnyFacebookUid()\n {\n\n $cookie = self::getFacebookCookie();\n $fb_uid = $cookie['uid'];\n sfContext::getInstance()->getLogger()->info('{sfFacebookConnect} Fb_uid from cookie : '.$fb_uid);\n\n return $fb_uid;\n }\n\n /**\n *\n * @param sfWebRequest $request\n * @return string\n * @author fabriceb\n * @since Oct 12, 2009\n */\n public static function getFacebookSigParameters(sfWebRequest $request)\n {\n $parameters = $request->getParameterHolder()->getAll();\n\n $parameter_string = '';\n foreach ($parameters as $key => $parameter)\n {\n if (substr($key,0,3)=='fb_')\n {\n $parameter_string .= '&'.$key.'='.$parameter;\n }\n }\n\n return $parameter_string;\n }\n\n}\n"}, "files_after": {"lib/sfFacebook.class.php": " $value)\n {\n if ($key != 'sig')\n {\n $payload .= $key . '=' . $value;\n }\n }\n if (md5($payload . $application_secret) != $args['sig'])\n {\n return null;\n }\n\n return $args;\n }\n\n /**\n * gets the facebook client instance\n *\n * @return Facebook\n * @author fabriceb\n * @since 2009-05-17\n * @since 2010-05-12 Benjamin Grandfond : new Facebook php-sdk\n * @since 2010-09-03 Benjamin Grandfond : correct the parameters sent to the facebook class constructor\n */\n\n\n public static function getFacebookCookie()\n {\n $app_id = self::getApiKey();\n $application_secret = self::getApiSecret();\n $args = array();\n if (!isset($_COOKIE['fbs_' . $app_id]))\n {\n return null;\n }\n parse_str(trim($_COOKIE['fbs_' . $app_id], '\\\\\"'), $args);\n ksort($args);\n $payload = '';\n foreach ($args as $key => $value)\n {\n if ($key != 'sig')\n {\n $payload .= $key . '=' . $value;\n }\n }\n if (md5($payload . $application_secret) != $args['sig'])\n {\n return null;\n }\n return $args;\n }\n\n\n public static function getFacebookClient()\n {\n if (self::$client === null)\n {\n $params = array(\n 'appId' => self::getApiId(),\n 'secret' => self::getApiSecret(),\n 'cookie' => self::getApiCookie(),\n 'domain' => self::getApiDomain()\n );\n\n self::$client = new Facebook($params);\n }\n\n if (!self::$client)\n {\n error_log('Could not create facebook client.');\n }\n\n return self::$client;\n }\n\n /**\n * get the facebook session\n *\n * @return Array\n * @author Benjamin Grandfond \n * @since 2010-05-13\n */\n public static function getSession()\n {\n\n return self::getFacebookClient()->getSession();\n }\n\n /**\n * get the facebook user\n *\n * @return Array\n * @author Benjamin Grandfond \n * @since 2010-05-13\n */\n public static function getUser()\n {\n\n return self::getFacebookClient()->getUser();\n }\n\n /**\n * get datas through the faceook graph api\n * @see http://developers.facebook.com/docs/api\n *\n * @return Array\n * @author Benjamin Grandfond \n * @since 2010-05-13\n */\n public static function getFacebookApi($param)\n {\n\n return self::getFacebookClient()->api($param);\n }\n\n /**\n * gets the facebook api key\n *\n * @return Facebook\n * @author fabriceb\n * @since 2009-05-17\n */\n public static function getApiKey()\n {\n\n return sfConfig::get('app_facebook_api_key');\n }\n\n /**\n * gets the facebook api secret\n *\n * @return Facebook\n * @author fabriceb\n * @since 2009-05-17\n */\n public static function getApiSecret()\n {\n\n return sfConfig::get('app_facebook_api_secret');\n }\n\n /**\n * get the facebook app id\n *\n * @return integer\n * @author Benjamin Grandfond \n * @since 2010-09-03\n */\n public static function getApiId()\n {\n\n return sfConfig::get('app_facebook_api_id');\n }\n\n /**\n * get the facebook app cookie support\n *\n * @return Boolean\n * @author Benjamin Grandfond \n * @since 2010-05-12\n */\n public static function getApiCookie()\n {\n\n return sfConfig::get('app_facebook_api_cookie', true);\n }\n\n /**\n * get the facebook app domain\n *\n * @return Boolean\n * @author Benjamin Grandfond \n * @since 2010-05-12\n */\n public static function getApiDomain()\n {\n\n return sfConfig::get('app_facebook_api_domain', null);\n }\n\n /**\n * gets or create user with facebook uid inprofile\n *\n * @param Integer $facebook_uid\n * @param boolean $isActive\n * @return sfGuardUser $sfGuardUser\n */\n public static function getOrCreateUserByFacebookUid($facebook_uid, $isActive = true)\n {\n $sfGuardUser = self::getGuardAdapter()->getSfGuardUserByFacebookUid($facebook_uid, $isActive);\n\n if (!$sfGuardUser instanceof sfGuardUser)\n {\n if (sfConfig::get('sf_logging_enabled'))\n {\n sfContext::getInstance()->getLogger()->info('{sfFacebookConnect} No user exists with current email hash');\n }\n $sfGuardUser = self::getGuardAdapter()->createSfGuardUserWithFacebookUid($facebook_uid);\n }\n\n return $sfGuardUser;\n }\n\n /**\n * gets user with facebook uid inprofile\n *\n * @param Integer $facebook_uid\n * @param boolean $isActive\n * @return sfGuardUser $sfGuardUser\n */\n public static function getUserByFacebookUid($facebook_uid, $isActive = true)\n {\n $sfGuardUser = self::getGuardAdapter()->retrieveSfGuardUserByFacebookUid($facebook_uid, $isActive);\n\n if (!$sfGuardUser instanceof sfGuardUser)\n {\n if (sfConfig::get('sf_logging_enabled'))\n {\n sfContext::getInstance()->getLogger()->info('{sfFacebookConnect} No user exists with current email hash');\n }\n }\n\n return $sfGuardUser;\n }\n\n /**\n * Gets the currently logged sfGuardUser using Facebook Session\n *\n * @param boolean $create whether to automatically create a sfGuardUser\n * if none found corresponding to the Facebook session\n * @param boolean $isActive\n * @return sfGuardUser\n * @author fabriceb\n * @since 2009-05-17\n * @since 2009-08-25\n */\n public static function getSfGuardUserByFacebookSession($create = true, $isActive = true)\n {\n // We get the facebook uid from session\n $fb_uid = self::getAnyFacebookUid();\n if ($fb_uid)\n {\n\n if ($create)\n {\n\n return self::getOrCreateUserByFacebookUid($fb_uid, $isActive);\n }\n else\n {\n\n return self::getUserByFacebookUid($fb_uid, $isActive);\n }\n }\n\n if (sfConfig::get('sf_logging_enabled'))\n {\n sfContext::getInstance()->getLogger()->info('{sfFacebookConnect} No current Facebook session');\n }\n\n return null;\n }\n\n /**\n * checks the existence of the HTTP_X_FB_USER_REMOTE_ADDR porperty in the header\n * which is a sign of being included by the fbml interface\n *\n * @return boolean\n * @author fabriceb\n * @since Jun 8, 2009 fabriceb\n */\n public static function isInsideFacebook()\n {\n\n return isset($_SERVER['HTTP_X_FB_USER_REMOTE_ADDR']);\n }\n\n /**\n *\n * @return boolean\n * @author fabriceb\n * @since Jun 8, 2009 fabriceb\n */\n public static function inCanvas()\n {\n\n return self::getFacebookClient()->in_fb_canvas();\n }\n\n /**\n * redirects to the login page of the Facebook application if not logged yet\n *\n * @author fabriceb\n * @since Jun 8, 2009 fabriceb\n */\n public static function requireLogin()\n {\n self::getFacebookClient()->require_login();\n }\n\n /**\n * redirects depnding on in canvas or not\n *\n * @param $url\n * @param $statusCode\n * @return mixed sfView::NONE or sfStopException\n * @author fabriceb\n * @since Jun 8, 2009 fabriceb\n */\n public static function redirect($url, $statusCode = 302)\n {\n\n $context = sfContext::getInstance();\n $response = $context->getResponse();\n\n if (self::inCanvas())\n {\n $url = sfConfig::get('app_facebook_app_url').$context->getController()->genUrl($url, false);\n\n $text = '';\n $response->setContent(sfContext::getInstance()->getResponse()->getContent().$text);\n\n return sfView::NONE;\n }\n else\n {\n $fb_parameters = '?'.sfFacebook::getFacebookSigParameters(sfContext::getInstance()->getRequest());\n $url = $context->getController()->genUrl($url, true).$fb_parameters;\n\n $response->clearHttpHeaders();\n $response->setStatusCode($statusCode);\n $response->setHttpHeader('Location', $url);\n $response->setContent(sprintf('', 0, htmlspecialchars($url, ENT_QUOTES, sfConfig::get('sf_charset'))));\n $response->send();\n\n throw new sfStopException();\n }\n }\n\n /**\n *\n * @param integer $user_uid\n * @return integer[]\n * @author fabriceb\n * @since Jun 9, 2009 fabriceb\n */\n public static function getFacebookFriendsUids($user_uid = null)\n {\n\n try\n {\n $friends_uids = self::getFacebookApi()->friends_get(null, $user_uid);\n }\n catch(FacebookRestClientException $e)\n {\n $friends_uids = array();\n if (sfConfig::get('sf_logging_enabled'))\n {\n sfContext::getInstance()->getLogger()->info('{FacebookRestClientException} '.$e->getMessage());\n }\n }\n\n return $friends_uids;\n }\n\n /**\n *\n * @return sfFacebookGuardAdapter\n * @author fabriceb\n * @since Aug 10, 2009\n * @since 2009-10-08 Alban Creton : added configurability of the Guard Adapter.\n */\n public static function getGuardAdapter()\n {\n if (self::$guard_adapter === null)\n {\n if(sfConfig::get('app_facebook_guard_adapter') && class_exists(sfConfig::get('app_facebook_guard_adapter'), true))\n {\n $class = sfConfig::get('app_facebook_guard_adapter');\n }\n else if (class_exists('sfGuardUserPeer', true))\n {\n $class = 'sfFacebookPropelGuardAdapter';\n }\n else\n {\n $class = 'sfFacebookDoctrineGuardAdapter';\n }\n self::$guard_adapter = new $class();\n }\n if (!self::$guard_adapter)\n {\n error_log('Could not create guard adapter.');\n }\n\n return self::$guard_adapter;\n }\n\n\n /**\n *\n * @return boolean\n * @author fabriceb\n * @since Aug 27, 2009\n */\n public static function isJsLoaded()\n {\n\n return self::$is_js_loaded;\n }\n\n /**\n *\n * @return void\n * @author fabriceb\n * @since Aug 27, 2009\n */\n public static function setJsLoaded()\n {\n self::$is_js_loaded = true;\n }\n\n /**\n * Dirty way to convert fr into fr_FR\n * @param string $culture\n * @return string\n * @author fabriceb\n * @since Aug 28, 2009\n */\n public static function getLocale($culture = null)\n {\n if (is_null($culture))\n {\n $culture = sfContext::getInstance()->getUser()->getCulture();\n }\n\n $culture_to_locale = array(\n 'fr' => 'fr_FR',\n 'en' => 'en_US',\n 'de' => 'de_DE',\n 'it' => 'it_IT',\n );\n\n return array_key_exists($culture, $culture_to_locale) ? $culture_to_locale[$culture] : $culture;\n }\n\n /**\n * @return interger $facebook_uid\n * @author fabriceb\n * @since Oct 6, 2009\n */\n public static function getAnyFacebookUid()\n {\n\n $cookie = self::getFacebookCookie();\n $fb_uid = $cookie['uid'];\n sfContext::getInstance()->getLogger()->info('{sfFacebookConnect} Fb_uid from cookie : '.$fb_uid);\n\n return $fb_uid;\n }\n\n /**\n *\n * @param sfWebRequest $request\n * @return string\n * @author fabriceb\n * @since Oct 12, 2009\n */\n public static function getFacebookSigParameters(sfWebRequest $request)\n {\n $parameters = $request->getParameterHolder()->getAll();\n\n $parameter_string = '';\n foreach ($parameters as $key => $parameter)\n {\n if (substr($key,0,3)=='fb_')\n {\n $parameter_string .= '&'.$key.'='.$parameter;\n }\n }\n\n return $parameter_string;\n }\n\n}\n"}} -{"repo": "MacSysadmin/pymacadmin", "pr_number": 13, "title": "Support for regexes, clearer logging, handle missing user_info", "state": "closed", "merged_at": "2016-01-16T03:38:04Z", "additions": 12, "deletions": 7, "files_changed": ["bin/crankd.py"], "files_before": {"bin/crankd.py": "#!/usr/bin/python2.7\n# encoding: utf-8\n\n\"\"\"\nUsage: %prog\n\nMonitor system event notifications\n\nConfiguration:\n\nThe configuration file is divided into sections for each class of\nevents. Each section is a dictionary using the event condition as the\nkey (\"NSWorkspaceDidWakeNotification\", \"State:/Network/Global/IPv4\",\netc). Each event must have one of the following properties:\n\ncommand: a shell command\nfunction: the name of a python function\nclass: the name of a python class which will be instantiated once\n and have methods called as events occur.\nmethod: (class, method) tuple\n\"\"\"\n\nfrom Cocoa import \\\n CFAbsoluteTimeGetCurrent, \\\n CFRunLoopAddSource, \\\n CFRunLoopAddTimer, \\\n CFRunLoopTimerCreate, \\\n NSObject, \\\n NSRunLoop, \\\n NSWorkspace, \\\n kCFRunLoopCommonModes\n\nfrom SystemConfiguration import \\\n SCDynamicStoreCopyKeyList, \\\n SCDynamicStoreCreate, \\\n SCDynamicStoreCreateRunLoopSource, \\\n SCDynamicStoreSetNotificationKeys\n\nfrom FSEvents import \\\n FSEventStreamCreate, \\\n FSEventStreamStart, \\\n FSEventStreamScheduleWithRunLoop, \\\n kFSEventStreamEventIdSinceNow, \\\n kCFRunLoopDefaultMode, \\\n kFSEventStreamEventFlagMustScanSubDirs, \\\n kFSEventStreamEventFlagUserDropped, \\\n kFSEventStreamEventFlagKernelDropped\n\nimport os\nimport os.path\nimport logging\nimport logging.handlers\nimport sys\nimport re\nfrom subprocess import call\nfrom optparse import OptionParser\nfrom plistlib import readPlist, writePlist\nfrom PyObjCTools import AppHelper\nfrom functools import partial\nimport signal\nfrom datetime import datetime\nfrom objc import super\n\n\nVERSION = '$Revision: #4 $'\n\nHANDLER_OBJECTS = dict() # Events which have a \"class\" handler use an instantiated object; we want to load only one copy\nSC_HANDLERS = dict() # Callbacks indexed by SystemConfiguration keys\nFS_WATCHED_FILES = dict() # Callbacks indexed by filesystem path\nWORKSPACE_HANDLERS = dict() # handlers for workspace events\n\n\nclass BaseHandler(object):\n # pylint: disable-msg=C0111,R0903\n pass\n\nclass NotificationHandler(NSObject):\n \"\"\"Simple base class for handling NSNotification events\"\"\"\n # Method names and class structure are dictated by Cocoa & PyObjC, which\n # is substantially different from PEP-8:\n # pylint: disable-msg=C0103,W0232,R0903\n\n def init(self):\n \"\"\"NSObject-compatible initializer\"\"\"\n self = super(NotificationHandler, self).init()\n if self is None: return None\n self.callable = self.not_implemented\n return self # NOTE: Unlike Python, NSObject's init() must return self!\n\n def not_implemented(self, *args, **kwargs):\n \"\"\"A dummy function which exists only to catch configuration errors\"\"\"\n # TODO: Is there a better way to report the caller's location?\n import inspect\n stack = inspect.stack()\n my_name = stack[0][3]\n caller = stack[1][3]\n raise NotImplementedError(\n \"%s should have been overridden. Called by %s as: %s(%s)\" % (\n my_name,\n caller,\n my_name,\n \", \".join(map(repr, args) + [ \"%s=%s\" % (k, repr(v)) for k,v in kwargs.items() ])\n )\n )\n\n def onNotification_(self, the_notification):\n \"\"\"Pass an NSNotifications to our handler\"\"\"\n if the_notification.userInfo:\n user_info = the_notification.userInfo()\n else:\n user_info = None\n self.callable(user_info=user_info) # pylint: disable-msg=E1101\n\n\ndef log_list(msg, items, level=logging.INFO):\n \"\"\"\n Record a a list of values with a message\n\n This would ordinarily be a simple logging call but we want to keep the\n length below the 1024-byte syslog() limitation and we'll format things\n nicely by repeating our message with as many of the values as will fit.\n\n Individual items longer than the maximum length will be truncated.\n \"\"\"\n\n max_len = 1024 - len(msg % \"\")\n cur_len = 0\n cur_items = list()\n\n while [ i[:max_len] for i in items]:\n i = items.pop()\n if cur_len + len(i) + 2 > max_len:\n logging.info(msg % \", \".join(cur_items))\n cur_len = 0\n cur_items = list()\n\n cur_items.append(i)\n cur_len += len(i) + 2\n\n logging.log(level, msg % \", \".join(cur_items))\n\ndef get_callable_for_event(name, event_config, context=None):\n \"\"\"\n Returns a callable object which can be used as a callback for any\n event. The returned function has context information, logging, etc.\n included so they do not need to be passed when the actual event\n occurs.\n\n NOTE: This function does not process \"class\" handlers - by design they\n are passed to the system libraries which expect a delegate object with\n various event handling methods\n \"\"\"\n\n kwargs = {\n 'context': context,\n 'key': name,\n 'config': event_config,\n }\n\n if \"command\" in event_config:\n f = partial(do_shell, event_config[\"command\"], **kwargs)\n elif \"function\" in event_config:\n f = partial(get_callable_from_string(event_config[\"function\"]), **kwargs)\n elif \"method\" in event_config:\n f = partial(getattr(get_handler_object(event_config['method'][0]), event_config['method'][1]), **kwargs)\n else:\n raise AttributeError(\"%s have a class, method, function or command\" % name)\n\n return f\n\n\ndef get_mod_func(callback):\n \"\"\"Convert a fully-qualified module.function name to (module, function) - stolen from Django\"\"\"\n try:\n dot = callback.rindex('.')\n except ValueError:\n return (callback, '')\n return (callback[:dot], callback[dot+1:])\n\n\ndef get_callable_from_string(f_name):\n \"\"\"Takes a string containing a function name (optionally module qualified) and returns a callable object\"\"\"\n try:\n mod_name, func_name = get_mod_func(f_name)\n if mod_name == \"\" and func_name == \"\":\n raise AttributeError(\"%s couldn't be converted to a module or function name\" % f_name)\n\n module = __import__(mod_name)\n\n if func_name == \"\":\n func_name = mod_name # The common case is an eponymous class\n\n return getattr(module, func_name)\n\n except (ImportError, AttributeError), exc:\n raise RuntimeError(\"Unable to create a callable object for '%s': %s\" % (f_name, exc))\n\n\ndef get_handler_object(class_name):\n \"\"\"Return a single instance of the given class name, instantiating it if necessary\"\"\"\n\n if class_name not in HANDLER_OBJECTS:\n h_obj = get_callable_from_string(class_name)()\n if isinstance(h_obj, BaseHandler):\n pass # TODO: Do we even need BaseHandler any more?\n HANDLER_OBJECTS[class_name] = h_obj\n\n return HANDLER_OBJECTS[class_name]\n\n\ndef handle_sc_event(store, changed_keys, info):\n \"\"\"Fire every event handler for one or more events\"\"\"\n\n for key in changed_keys:\n SC_HANDLERS[key](key=key, info=info)\n\n\ndef list_events(option, opt_str, value, parser):\n \"\"\"Displays the list of events which can be monitored on the current system\"\"\"\n\n print 'On this system SystemConfiguration supports these events:'\n for event in sorted(SCDynamicStoreCopyKeyList(get_sc_store(), '.*')):\n print \"\\t\", event\n\n print\n print \"Standard NSWorkspace Notification messages:\\n\\t\",\n print \"\\n\\t\".join('''\n NSWorkspaceDidLaunchApplicationNotification\n NSWorkspaceDidMountNotification\n NSWorkspaceDidPerformFileOperationNotification\n NSWorkspaceDidTerminateApplicationNotification\n NSWorkspaceDidUnmountNotification\n NSWorkspaceDidWakeNotification\n NSWorkspaceSessionDidBecomeActiveNotification\n NSWorkspaceSessionDidResignActiveNotification\n NSWorkspaceWillLaunchApplicationNotification\n NSWorkspaceWillPowerOffNotification\n NSWorkspaceWillSleepNotification\n NSWorkspaceWillUnmountNotification\n '''.split())\n\n sys.exit(0)\n\n\ndef process_commandline():\n \"\"\"\n Process command-line options\n Load our preference file\n Configure the module path to add Application Support directories\n \"\"\"\n parser = OptionParser(__doc__.strip())\n support_path = '/Library/' if os.getuid() == 0 else os.path.expanduser('~/Library/')\n preference_file = os.path.join(support_path, 'Preferences', 'com.googlecode.pymacadmin.crankd.plist')\n module_path = os.path.join(support_path, 'Application Support/crankd')\n\n if os.path.exists(module_path):\n sys.path.append(module_path)\n else:\n print >> sys.stderr, \"Module directory %s does not exist: Python handlers will need to use absolute pathnames\" % module_path\n\n parser.add_option(\"-f\", \"--config\", dest=\"config_file\", help='Use an alternate config file instead of %default', default=preference_file)\n parser.add_option(\"-l\", \"--list-events\", action=\"callback\", callback=list_events, help=\"List the events which can be monitored\")\n parser.add_option(\"-d\", \"--debug\", action=\"count\", default=False, help=\"Log detailed progress information\")\n (options, args) = parser.parse_args()\n\n if len(args):\n parser.error(\"Unknown command-line arguments: %s\" % args)\n\n options.support_path = support_path\n options.config_file = os.path.realpath(options.config_file)\n\n # This is somewhat messy but we want to alter the command-line to use full\n # file paths in case someone's code changes the current directory or the\n sys.argv = [ os.path.realpath(sys.argv[0]), ]\n\n if options.debug:\n logging.getLogger().setLevel(logging.DEBUG)\n sys.argv.append(\"--debug\")\n\n if options.config_file:\n sys.argv.append(\"--config\")\n sys.argv.append(options.config_file)\n\n return options\n\n\ndef load_config(options):\n \"\"\"Load our configuration from plist or create a default file if none exists\"\"\"\n if not os.path.exists(options.config_file):\n logging.info(\"%s does not exist - initializing with an example configuration\" % CRANKD_OPTIONS.config_file)\n print >>sys.stderr, 'Creating %s with default options for you to customize' % options.config_file\n print >>sys.stderr, '%s --list-events will list the events you can monitor on this system' % sys.argv[0]\n example_config = {\n 'SystemConfiguration': {\n 'State:/Network/Global/IPv4': {\n 'command': '/bin/echo \"Global IPv4 config changed\"'\n }\n },\n 'NSWorkspace': {\n 'NSWorkspaceDidMountNotification': {\n 'command': '/bin/echo \"A new volume was mounted!\"'\n },\n 'NSWorkspaceDidWakeNotification': {\n 'command': '/bin/echo \"The system woke from sleep!\"'\n },\n 'NSWorkspaceWillSleepNotification': {\n 'command': '/bin/echo \"The system is about to go to sleep!\"'\n }\n }\n }\n writePlist(example_config, options.config_file)\n sys.exit(1)\n\n logging.info(\"Loading configuration from %s\" % CRANKD_OPTIONS.config_file)\n\n plist = readPlist(options.config_file)\n\n if \"imports\" in plist:\n for module in plist['imports']:\n try:\n __import__(module)\n except ImportError, exc:\n print >> sys.stderr, \"Unable to import %s: %s\" % (module, exc)\n sys.exit(1)\n return plist\n\n\ndef configure_logging():\n \"\"\"Configures the logging module\"\"\"\n logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s')\n\n # Enable logging to syslog as well:\n # Normally this would not be necessary but logging assumes syslog listens on\n # localhost syslog/udp, which is disabled on 10.5 (rdar://5871746)\n syslog = logging.handlers.SysLogHandler('/var/run/syslog')\n syslog.setFormatter(logging.Formatter('%(name)s: %(message)s'))\n syslog.setLevel(logging.INFO)\n logging.getLogger().addHandler(syslog)\n\n\ndef get_sc_store():\n \"\"\"Returns an SCDynamicStore instance\"\"\"\n return SCDynamicStoreCreate(None, \"crankd\", handle_sc_event, None)\n\n\ndef add_workspace_notifications(nsw_config):\n # See http://developer.apple.com/documentation/Cocoa/Conceptual/Workspace/Workspace.html\n notification_center = NSWorkspace.sharedWorkspace().notificationCenter()\n\n for event in nsw_config:\n event_config = nsw_config[event]\n\n if \"class\" in event_config:\n obj = get_handler_object(event_config['class'])\n objc_method = \"on%s:\" % event\n py_method = objc_method.replace(\":\", \"_\")\n if not hasattr(obj, py_method) or not callable(getattr(obj, py_method)):\n print >> sys.stderr, \\\n \"NSWorkspace Notification %s: handler class %s must define a %s method\" % (event, event_config['class'], py_method)\n sys.exit(1)\n\n notification_center.addObserver_selector_name_object_(obj, objc_method, event, None)\n else:\n handler = NotificationHandler.new()\n handler.name = \"NSWorkspace Notification %s\" % event\n handler.callable = get_callable_for_event(event, event_config, context=handler.name)\n\n assert(callable(handler.onNotification_))\n\n notification_center.addObserver_selector_name_object_(handler, \"onNotification:\", event, None)\n WORKSPACE_HANDLERS[event] = handler\n\n log_list(\"Listening for these NSWorkspace notifications: %s\", nsw_config.keys())\n\n\ndef add_sc_notifications(sc_config):\n \"\"\"\n This uses the SystemConfiguration framework to get a SCDynamicStore session\n and register for certain events. See the Apple SystemConfiguration\n documentation for details:\n\n \n\n TN1145 may also be of interest:\n \n\n Inspired by the PyObjC SystemConfiguration callback demos:\n \n \"\"\"\n\n keys = sc_config.keys()\n\n try:\n for key in keys:\n SC_HANDLERS[key] = get_callable_for_event(key, sc_config[key], context=\"SystemConfiguration: %s\" % key)\n except AttributeError, exc:\n print >> sys.stderr, \"Error configuring SystemConfiguration events: %s\" % exc\n sys.exit(1)\n\n store = get_sc_store()\n\n SCDynamicStoreSetNotificationKeys(store, None, keys)\n\n # Get a CFRunLoopSource for our store session and add it to the application's runloop:\n CFRunLoopAddSource(\n NSRunLoop.currentRunLoop().getCFRunLoop(),\n SCDynamicStoreCreateRunLoopSource(None, store, 0),\n kCFRunLoopCommonModes\n )\n\n log_list(\"Listening for these SystemConfiguration events: %s\", keys)\n\n\ndef add_fs_notifications(fs_config):\n for path in fs_config:\n add_fs_notification(path, get_callable_for_event(path, fs_config[path], context=\"FSEvent: %s\" % path))\n\n\ndef add_fs_notification(f_path, callback):\n \"\"\"Adds an FSEvent notification for the specified path\"\"\"\n path = os.path.realpath(os.path.expanduser(f_path))\n if not os.path.exists(path):\n raise AttributeError(\"Cannot add an FSEvent notification: %s does not exist!\" % path)\n\n if not os.path.isdir(path):\n path = os.path.dirname(path)\n\n try:\n FS_WATCHED_FILES[path].append(callback)\n except KeyError:\n FS_WATCHED_FILES[path] = [callback]\n\n\ndef start_fs_events():\n stream_ref = FSEventStreamCreate(\n None, # Use the default CFAllocator\n fsevent_callback,\n None, # We don't need a FSEventStreamContext\n FS_WATCHED_FILES.keys(),\n kFSEventStreamEventIdSinceNow, # We only want events which happen in the future\n 1.0, # Process events within 1 second\n 0 # We don't need any special flags for our stream\n )\n\n if not stream_ref:\n raise RuntimeError(\"FSEventStreamCreate() failed!\")\n\n FSEventStreamScheduleWithRunLoop(stream_ref, NSRunLoop.currentRunLoop().getCFRunLoop(), kCFRunLoopDefaultMode)\n\n if not FSEventStreamStart(stream_ref):\n raise RuntimeError(\"Unable to start FSEvent stream!\")\n\n logging.debug(\"FSEventStream started for %d paths: %s\" % (len(FS_WATCHED_FILES), \", \".join(FS_WATCHED_FILES)))\n\n\ndef fsevent_callback(stream_ref, full_path, event_count, paths, masks, ids):\n \"\"\"Process an FSEvent (consult the Cocoa docs) and call each of our handlers which monitors that path or a parent\"\"\"\n for i in range(event_count):\n path = os.path.dirname(paths[i])\n\n if masks[i] & kFSEventStreamEventFlagMustScanSubDirs:\n recursive = True\n\n if masks[i] & kFSEventStreamEventFlagUserDropped:\n logging.error(\"We were too slow processing FSEvents and some events were dropped\")\n recursive = True\n\n if masks[i] & kFSEventStreamEventFlagKernelDropped:\n logging.error(\"The kernel was too slow processing FSEvents and some events were dropped!\")\n recursive = True\n else:\n recursive = False\n\n for i in [k for k in FS_WATCHED_FILES if path.startswith(k)]:\n logging.debug(\"FSEvent: %s: processing %d callback(s) for path %s\" % (i, len(FS_WATCHED_FILES[i]), path))\n for j in FS_WATCHED_FILES[i]:\n j(i, path=path, recursive=recursive)\n\n\ndef timer_callback(*args):\n \"\"\"Handles the timer events which we use simply to have the runloop run regularly. Currently this logs a timestamp for debugging purposes\"\"\"\n logging.debug(\"timer callback at %s\" % datetime.now())\n\n\ndef main():\n configure_logging()\n\n global CRANKD_OPTIONS, CRANKD_CONFIG\n CRANKD_OPTIONS = process_commandline()\n CRANKD_CONFIG = load_config(CRANKD_OPTIONS)\n\n if \"NSWorkspace\" in CRANKD_CONFIG:\n add_workspace_notifications(CRANKD_CONFIG['NSWorkspace'])\n\n if \"SystemConfiguration\" in CRANKD_CONFIG:\n add_sc_notifications(CRANKD_CONFIG['SystemConfiguration'])\n\n if \"FSEvents\" in CRANKD_CONFIG:\n add_fs_notifications(CRANKD_CONFIG['FSEvents'])\n\n # We reuse our FSEvents code to watch for changes to our files and\n # restart if any of our libraries have been updated:\n add_conditional_restart(CRANKD_OPTIONS.config_file, \"Configuration file %s changed\" % CRANKD_OPTIONS.config_file)\n for m in filter(lambda i: i and hasattr(i, '__file__'), sys.modules.values()):\n if m.__name__ == \"__main__\":\n msg = \"%s was updated\" % m.__file__\n else:\n msg = \"Module %s was updated\" % m.__name__\n\n add_conditional_restart(m.__file__, msg)\n\n signal.signal(signal.SIGHUP, partial(restart, \"SIGHUP received\"))\n\n start_fs_events()\n\n # NOTE: This timer is basically a kludge around the fact that we can't reliably get\n # signals or Control-C inside a runloop. This wakes us up often enough to\n # appear tolerably responsive:\n CFRunLoopAddTimer(\n NSRunLoop.currentRunLoop().getCFRunLoop(),\n CFRunLoopTimerCreate(None, CFAbsoluteTimeGetCurrent(), 2.0, 0, 0, timer_callback, None),\n kCFRunLoopCommonModes\n )\n\n try:\n AppHelper.runConsoleEventLoop(installInterrupt=True)\n except KeyboardInterrupt:\n logging.info(\"KeyboardInterrupt received, exiting\")\n\n sys.exit(0)\n\ndef create_env_name(name):\n \"\"\"\n Converts input names into more traditional shell environment name style\n\n >>> create_env_name(\"NSApplicationBundleIdentifier\")\n 'NSAPPLICATION_BUNDLE_IDENTIFIER'\n >>> create_env_name(\"NSApplicationBundleIdentifier-1234$foobar!\")\n 'NSAPPLICATION_BUNDLE_IDENTIFIER_1234_FOOBAR'\n \"\"\"\n new_name = re.sub(r'''(?<=[a-z])([A-Z])''', '_\\\\1', name)\n new_name = re.sub(r'\\W+', '_', new_name)\n new_name = re.sub(r'_{2,}', '_', new_name)\n return new_name.upper().strip(\"_\")\n\ndef do_shell(command, context=None, **kwargs):\n \"\"\"Executes a shell command with logging\"\"\"\n logging.info(\"%s: executing %s\" % (context, command))\n\n child_env = {'CRANKD_CONTEXT': context}\n\n # We'll pull a subset of the available information in for shell scripts.\n # Anyone who needs more will probably want to write a Python handler\n # instead so they can reuse things like our logger & config info and avoid\n # ordeals like associative arrays in Bash\n for k in [ 'info', 'key' ]:\n if k in kwargs and kwargs[k]:\n child_env['CRANKD_%s' % k.upper()] = str(kwargs[k])\n\n user_info = kwargs.get(\"user_info\")\n if user_info:\n for k, v in user_info.items():\n child_env[create_env_name(k)] = str(v)\n\n try:\n rc = call(command, shell=True, env=child_env)\n if rc == 0:\n logging.debug(\"`%s` returned %d\" % (command, rc))\n elif rc < 0:\n logging.error(\"`%s` was terminated by signal %d\" % (command, -rc))\n else:\n logging.error(\"`%s` returned %d\" % (command, rc))\n except OSError, exc:\n logging.error(\"Got an exception when executing %s:\" % (command, exc))\n\n\ndef add_conditional_restart(file_name, reason):\n \"\"\"FSEvents monitors directories, not files. This function uses stat to\n restart only if the file's mtime has changed\"\"\"\n file_name = os.path.realpath(file_name)\n while not os.path.exists(file_name):\n file_name = os.path.dirname(file_name)\n orig_stat = os.stat(file_name).st_mtime\n\n def cond_restart(*args, **kwargs):\n try:\n if os.stat(file_name).st_mtime != orig_stat:\n restart(reason)\n except (OSError, IOError, RuntimeError), exc:\n restart(\"Exception while checking %s: %s\" % (file_name, exc))\n\n add_fs_notification(file_name, cond_restart)\n\n\ndef restart(reason, *args, **kwargs):\n \"\"\"Perform a complete restart of the current process using exec()\"\"\"\n logging.info(\"Restarting: %s\" % reason)\n os.execv(sys.argv[0], sys.argv)\n\nif __name__ == '__main__':\n main()\n"}, "files_after": {"bin/crankd.py": "#!/usr/bin/python2.7\n# encoding: utf-8\n\n\"\"\"\nUsage: %prog\n\nMonitor system event notifications\n\nConfiguration:\n\nThe configuration file is divided into sections for each class of\nevents. Each section is a dictionary using the event condition as the\nkey (\"NSWorkspaceDidWakeNotification\", \"State:/Network/Global/IPv4\",\netc). Each event must have one of the following properties:\n\ncommand: a shell command\nfunction: the name of a python function\nclass: the name of a python class which will be instantiated once\n and have methods called as events occur.\nmethod: (class, method) tuple\n\"\"\"\n\nfrom Cocoa import \\\n CFAbsoluteTimeGetCurrent, \\\n CFRunLoopAddSource, \\\n CFRunLoopAddTimer, \\\n CFRunLoopTimerCreate, \\\n NSObject, \\\n NSRunLoop, \\\n NSWorkspace, \\\n kCFRunLoopCommonModes\n\nfrom SystemConfiguration import \\\n SCDynamicStoreCopyKeyList, \\\n SCDynamicStoreCreate, \\\n SCDynamicStoreCreateRunLoopSource, \\\n SCDynamicStoreSetNotificationKeys\n\nfrom FSEvents import \\\n FSEventStreamCreate, \\\n FSEventStreamStart, \\\n FSEventStreamScheduleWithRunLoop, \\\n kFSEventStreamEventIdSinceNow, \\\n kCFRunLoopDefaultMode, \\\n kFSEventStreamEventFlagMustScanSubDirs, \\\n kFSEventStreamEventFlagUserDropped, \\\n kFSEventStreamEventFlagKernelDropped\n\nimport os\nimport os.path\nimport logging\nimport logging.handlers\nimport sys\nimport re\nfrom subprocess import call\nfrom optparse import OptionParser\nfrom plistlib import readPlist, writePlist\nfrom PyObjCTools import AppHelper\nfrom functools import partial\nimport signal\nfrom datetime import datetime\nfrom objc import super\n\n\nVERSION = '$Revision: #4 $'\n\nHANDLER_OBJECTS = dict() # Events which have a \"class\" handler use an instantiated object; we want to load only one copy\nSC_HANDLERS = dict() # Callbacks indexed by SystemConfiguration keys\nFS_WATCHED_FILES = dict() # Callbacks indexed by filesystem path\nWORKSPACE_HANDLERS = dict() # handlers for workspace events\n\n\nclass BaseHandler(object):\n # pylint: disable-msg=C0111,R0903\n pass\n\nclass NotificationHandler(NSObject):\n \"\"\"Simple base class for handling NSNotification events\"\"\"\n # Method names and class structure are dictated by Cocoa & PyObjC, which\n # is substantially different from PEP-8:\n # pylint: disable-msg=C0103,W0232,R0903\n\n def init(self):\n \"\"\"NSObject-compatible initializer\"\"\"\n self = super(NotificationHandler, self).init()\n if self is None: return None\n self.callable = self.not_implemented\n return self # NOTE: Unlike Python, NSObject's init() must return self!\n\n def not_implemented(self, *args, **kwargs):\n \"\"\"A dummy function which exists only to catch configuration errors\"\"\"\n # TODO: Is there a better way to report the caller's location?\n import inspect\n stack = inspect.stack()\n my_name = stack[0][3]\n caller = stack[1][3]\n raise NotImplementedError(\n \"%s should have been overridden. Called by %s as: %s(%s)\" % (\n my_name,\n caller,\n my_name,\n \", \".join(map(repr, args) + [ \"%s=%s\" % (k, repr(v)) for k,v in kwargs.items() ])\n )\n )\n\n def onNotification_(self, the_notification):\n \"\"\"Pass an NSNotifications to our handler\"\"\"\n if the_notification.userInfo:\n user_info = the_notification.userInfo()\n else:\n user_info = None\n self.callable(user_info=user_info) # pylint: disable-msg=E1101\n\n\ndef log_list(msg, items, level=logging.INFO):\n \"\"\"\n Record a a list of values with a message\n\n This would ordinarily be a simple logging call but we want to keep the\n length below the 1024-byte syslog() limitation and we'll format things\n nicely by repeating our message with as many of the values as will fit.\n\n Individual items longer than the maximum length will be truncated.\n \"\"\"\n\n max_len = 1024 - len(msg % \"\")\n cur_len = 0\n cur_items = list()\n\n while [ i[:max_len] for i in items]:\n i = items.pop()\n if cur_len + len(i) + 2 > max_len:\n logging.info(msg % \", \".join(cur_items))\n cur_len = 0\n cur_items = list()\n\n cur_items.append(i)\n cur_len += len(i) + 2\n\n logging.log(level, msg % \", \".join(cur_items))\n\ndef get_callable_for_event(name, event_config, context=None):\n \"\"\"\n Returns a callable object which can be used as a callback for any\n event. The returned function has context information, logging, etc.\n included so they do not need to be passed when the actual event\n occurs.\n\n NOTE: This function does not process \"class\" handlers - by design they\n are passed to the system libraries which expect a delegate object with\n various event handling methods\n \"\"\"\n\n kwargs = {\n 'context': context,\n 'key': name,\n 'config': event_config,\n }\n\n if \"command\" in event_config:\n f = partial(do_shell, event_config[\"command\"], **kwargs)\n elif \"function\" in event_config:\n f = partial(get_callable_from_string(event_config[\"function\"]), **kwargs)\n elif \"method\" in event_config:\n f = partial(getattr(get_handler_object(event_config['method'][0]), event_config['method'][1]), **kwargs)\n else:\n raise AttributeError(\"%s have a class, method, function or command\" % name)\n\n return f\n\n\ndef get_mod_func(callback):\n \"\"\"Convert a fully-qualified module.function name to (module, function) - stolen from Django\"\"\"\n try:\n dot = callback.rindex('.')\n except ValueError:\n return (callback, '')\n return (callback[:dot], callback[dot+1:])\n\n\ndef get_callable_from_string(f_name):\n \"\"\"Takes a string containing a function name (optionally module qualified) and returns a callable object\"\"\"\n try:\n mod_name, func_name = get_mod_func(f_name)\n if mod_name == \"\" and func_name == \"\":\n raise AttributeError(\"%s couldn't be converted to a module or function name\" % f_name)\n\n module = __import__(mod_name)\n\n if func_name == \"\":\n func_name = mod_name # The common case is an eponymous class\n\n return getattr(module, func_name)\n\n except (ImportError, AttributeError), exc:\n raise RuntimeError(\"Unable to create a callable object for '%s': %s\" % (f_name, exc))\n\n\ndef get_handler_object(class_name):\n \"\"\"Return a single instance of the given class name, instantiating it if necessary\"\"\"\n\n if class_name not in HANDLER_OBJECTS:\n h_obj = get_callable_from_string(class_name)()\n if isinstance(h_obj, BaseHandler):\n pass # TODO: Do we even need BaseHandler any more?\n HANDLER_OBJECTS[class_name] = h_obj\n\n return HANDLER_OBJECTS[class_name]\n\n\ndef handle_sc_event(store, changed_keys, info):\n \"\"\"Fire every event handler for one or more events\"\"\"\n try:\n for key in changed_keys:\n SC_HANDLERS[key](key=key, info=info)\n except KeyError:\n # If there's no exact match, go through the list again assuming regex\n for key in changed_keys:\n for handler in SC_HANDLERS:\n if re.match(handler, key):\n SC_HANDLERS[handler](key=key, info=info)\n\n\n\ndef list_events(option, opt_str, value, parser):\n \"\"\"Displays the list of events which can be monitored on the current system\"\"\"\n\n print 'On this system SystemConfiguration supports these events:'\n for event in sorted(SCDynamicStoreCopyKeyList(get_sc_store(), '.*')):\n print \"\\t\", event\n\n print\n print \"Standard NSWorkspace Notification messages:\\n\\t\",\n print \"\\n\\t\".join('''\n NSWorkspaceDidLaunchApplicationNotification\n NSWorkspaceDidMountNotification\n NSWorkspaceDidPerformFileOperationNotification\n NSWorkspaceDidTerminateApplicationNotification\n NSWorkspaceDidUnmountNotification\n NSWorkspaceDidWakeNotification\n NSWorkspaceSessionDidBecomeActiveNotification\n NSWorkspaceSessionDidResignActiveNotification\n NSWorkspaceWillLaunchApplicationNotification\n NSWorkspaceWillPowerOffNotification\n NSWorkspaceWillSleepNotification\n NSWorkspaceWillUnmountNotification\n '''.split())\n\n sys.exit(0)\n\n\ndef process_commandline():\n \"\"\"\n Process command-line options\n Load our preference file\n Configure the module path to add Application Support directories\n \"\"\"\n parser = OptionParser(__doc__.strip())\n support_path = '/Library/' if os.getuid() == 0 else os.path.expanduser('~/Library/')\n preference_file = os.path.join(support_path, 'Preferences', 'com.googlecode.pymacadmin.crankd.plist')\n module_path = os.path.join(support_path, 'Application Support/crankd')\n\n if os.path.exists(module_path):\n sys.path.append(module_path)\n else:\n print >> sys.stderr, \"Module directory %s does not exist: Python handlers will need to use absolute pathnames\" % module_path\n\n parser.add_option(\"-f\", \"--config\", dest=\"config_file\", help='Use an alternate config file instead of %default', default=preference_file)\n parser.add_option(\"-l\", \"--list-events\", action=\"callback\", callback=list_events, help=\"List the events which can be monitored\")\n parser.add_option(\"-d\", \"--debug\", action=\"count\", default=False, help=\"Log detailed progress information\")\n (options, args) = parser.parse_args()\n\n if len(args):\n parser.error(\"Unknown command-line arguments: %s\" % args)\n\n options.support_path = support_path\n options.config_file = os.path.realpath(options.config_file)\n\n # This is somewhat messy but we want to alter the command-line to use full\n # file paths in case someone's code changes the current directory or the\n sys.argv = [ os.path.realpath(sys.argv[0]), ]\n\n if options.debug:\n logging.getLogger().setLevel(logging.DEBUG)\n sys.argv.append(\"--debug\")\n\n if options.config_file:\n sys.argv.append(\"--config\")\n sys.argv.append(options.config_file)\n\n return options\n\n\ndef load_config(options):\n \"\"\"Load our configuration from plist or create a default file if none exists\"\"\"\n if not os.path.exists(options.config_file):\n logging.info(\"%s does not exist - initializing with an example configuration\" % CRANKD_OPTIONS.config_file)\n print >>sys.stderr, 'Creating %s with default options for you to customize' % options.config_file\n print >>sys.stderr, '%s --list-events will list the events you can monitor on this system' % sys.argv[0]\n example_config = {\n 'SystemConfiguration': {\n 'State:/Network/Global/IPv4': {\n 'command': '/bin/echo \"Global IPv4 config changed\"'\n }\n },\n 'NSWorkspace': {\n 'NSWorkspaceDidMountNotification': {\n 'command': '/bin/echo \"A new volume was mounted!\"'\n },\n 'NSWorkspaceDidWakeNotification': {\n 'command': '/bin/echo \"The system woke from sleep!\"'\n },\n 'NSWorkspaceWillSleepNotification': {\n 'command': '/bin/echo \"The system is about to go to sleep!\"'\n }\n }\n }\n writePlist(example_config, options.config_file)\n sys.exit(1)\n\n logging.info(\"Loading configuration from %s\" % CRANKD_OPTIONS.config_file)\n\n plist = readPlist(options.config_file)\n\n if \"imports\" in plist:\n for module in plist['imports']:\n try:\n __import__(module)\n except ImportError, exc:\n print >> sys.stderr, \"Unable to import %s: %s\" % (module, exc)\n sys.exit(1)\n return plist\n\n\ndef configure_logging():\n \"\"\"Configures the logging module\"\"\"\n logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s')\n\n # Enable logging to syslog as well:\n # Normally this would not be necessary but logging assumes syslog listens on\n # localhost syslog/udp, which is disabled on 10.5 (rdar://5871746)\n syslog = logging.handlers.SysLogHandler('/var/run/syslog')\n syslog.setFormatter(logging.Formatter('%(pathname)s[%(process)d]:%(message)s'))\n syslog.setLevel(logging.INFO)\n logging.getLogger().addHandler(syslog)\n\n\ndef get_sc_store():\n \"\"\"Returns an SCDynamicStore instance\"\"\"\n return SCDynamicStoreCreate(None, \"crankd\", handle_sc_event, None)\n\n\ndef add_workspace_notifications(nsw_config):\n # See http://developer.apple.com/documentation/Cocoa/Conceptual/Workspace/Workspace.html\n notification_center = NSWorkspace.sharedWorkspace().notificationCenter()\n\n for event in nsw_config:\n event_config = nsw_config[event]\n\n if \"class\" in event_config:\n obj = get_handler_object(event_config['class'])\n objc_method = \"on%s:\" % event\n py_method = objc_method.replace(\":\", \"_\")\n if not hasattr(obj, py_method) or not callable(getattr(obj, py_method)):\n print >> sys.stderr, \\\n \"NSWorkspace Notification %s: handler class %s must define a %s method\" % (event, event_config['class'], py_method)\n sys.exit(1)\n\n notification_center.addObserver_selector_name_object_(obj, objc_method, event, None)\n else:\n handler = NotificationHandler.new()\n handler.name = \"NSWorkspace Notification %s\" % event\n handler.callable = get_callable_for_event(event, event_config, context=handler.name)\n\n assert(callable(handler.onNotification_))\n\n notification_center.addObserver_selector_name_object_(handler, \"onNotification:\", event, None)\n WORKSPACE_HANDLERS[event] = handler\n log_list(\"Listening for these NSWorkspace notifications: %s\", nsw_config.keys())\n\n\ndef add_sc_notifications(sc_config):\n \"\"\"\n This uses the SystemConfiguration framework to get a SCDynamicStore session\n and register for certain events. See the Apple SystemConfiguration\n documentation for details:\n\n \n\n TN1145 may also be of interest:\n \n\n Inspired by the PyObjC SystemConfiguration callback demos:\n \n \"\"\"\n\n keys = sc_config.keys()\n\n try:\n for key in keys:\n SC_HANDLERS[key] = get_callable_for_event(key, sc_config[key], context=\"SystemConfiguration: %s\" % key)\n except AttributeError, exc:\n print >> sys.stderr, \"Error configuring SystemConfiguration events: %s\" % exc\n sys.exit(1)\n\n store = get_sc_store()\n\n SCDynamicStoreSetNotificationKeys(store, None, keys)\n\n # Get a CFRunLoopSource for our store session and add it to the application's runloop:\n CFRunLoopAddSource(\n NSRunLoop.currentRunLoop().getCFRunLoop(),\n SCDynamicStoreCreateRunLoopSource(None, store, 0),\n kCFRunLoopCommonModes\n )\n\n log_list(\"Listening for these SystemConfiguration events: %s\", keys)\n\n\ndef add_fs_notifications(fs_config):\n for path in fs_config:\n add_fs_notification(path, get_callable_for_event(path, fs_config[path], context=\"FSEvent: %s\" % path))\n\n\ndef add_fs_notification(f_path, callback):\n \"\"\"Adds an FSEvent notification for the specified path\"\"\"\n path = os.path.realpath(os.path.expanduser(f_path))\n if not os.path.exists(path):\n raise AttributeError(\"Cannot add an FSEvent notification: %s does not exist!\" % path)\n\n if not os.path.isdir(path):\n path = os.path.dirname(path)\n\n try:\n FS_WATCHED_FILES[path].append(callback)\n except KeyError:\n FS_WATCHED_FILES[path] = [callback]\n\n\ndef start_fs_events():\n stream_ref = FSEventStreamCreate(\n None, # Use the default CFAllocator\n fsevent_callback,\n None, # We don't need a FSEventStreamContext\n FS_WATCHED_FILES.keys(),\n kFSEventStreamEventIdSinceNow, # We only want events which happen in the future\n 1.0, # Process events within 1 second\n 0 # We don't need any special flags for our stream\n )\n\n if not stream_ref:\n raise RuntimeError(\"FSEventStreamCreate() failed!\")\n\n FSEventStreamScheduleWithRunLoop(stream_ref, NSRunLoop.currentRunLoop().getCFRunLoop(), kCFRunLoopDefaultMode)\n\n if not FSEventStreamStart(stream_ref):\n raise RuntimeError(\"Unable to start FSEvent stream!\")\n\n logging.debug(\"FSEventStream started for %d paths: %s\" % (len(FS_WATCHED_FILES), \", \".join(FS_WATCHED_FILES)))\n\n\ndef fsevent_callback(stream_ref, full_path, event_count, paths, masks, ids):\n \"\"\"Process an FSEvent (consult the Cocoa docs) and call each of our handlers which monitors that path or a parent\"\"\"\n for i in range(event_count):\n path = os.path.dirname(paths[i])\n\n if masks[i] & kFSEventStreamEventFlagMustScanSubDirs:\n recursive = True\n\n if masks[i] & kFSEventStreamEventFlagUserDropped:\n logging.error(\"We were too slow processing FSEvents and some events were dropped\")\n recursive = True\n\n if masks[i] & kFSEventStreamEventFlagKernelDropped:\n logging.error(\"The kernel was too slow processing FSEvents and some events were dropped!\")\n recursive = True\n else:\n recursive = False\n\n for i in [k for k in FS_WATCHED_FILES if path.startswith(k)]:\n logging.debug(\"FSEvent: %s: processing %d callback(s) for path %s\" % (i, len(FS_WATCHED_FILES[i]), path))\n for j in FS_WATCHED_FILES[i]:\n j(i, path=path, recursive=recursive)\n\n\ndef timer_callback(*args):\n \"\"\"Handles the timer events which we use simply to have the runloop run regularly. Currently this logs a timestamp for debugging purposes\"\"\"\n logging.debug(\"timer callback at %s\" % datetime.now())\n\n\ndef main():\n configure_logging()\n\n global CRANKD_OPTIONS, CRANKD_CONFIG\n CRANKD_OPTIONS = process_commandline()\n CRANKD_CONFIG = load_config(CRANKD_OPTIONS)\n\n if \"NSWorkspace\" in CRANKD_CONFIG:\n add_workspace_notifications(CRANKD_CONFIG['NSWorkspace'])\n\n if \"SystemConfiguration\" in CRANKD_CONFIG:\n add_sc_notifications(CRANKD_CONFIG['SystemConfiguration'])\n\n if \"FSEvents\" in CRANKD_CONFIG:\n add_fs_notifications(CRANKD_CONFIG['FSEvents'])\n\n # We reuse our FSEvents code to watch for changes to our files and\n # restart if any of our libraries have been updated:\n add_conditional_restart(CRANKD_OPTIONS.config_file, \"Configuration file %s changed\" % CRANKD_OPTIONS.config_file)\n for m in filter(lambda i: i and hasattr(i, '__file__'), sys.modules.values()):\n if m.__name__ == \"__main__\":\n msg = \"%s was updated\" % m.__file__\n else:\n msg = \"Module %s was updated\" % m.__name__\n\n add_conditional_restart(m.__file__, msg)\n\n signal.signal(signal.SIGHUP, partial(restart, \"SIGHUP received\"))\n\n start_fs_events()\n\n # NOTE: This timer is basically a kludge around the fact that we can't reliably get\n # signals or Control-C inside a runloop. This wakes us up often enough to\n # appear tolerably responsive:\n CFRunLoopAddTimer(\n NSRunLoop.currentRunLoop().getCFRunLoop(),\n CFRunLoopTimerCreate(None, CFAbsoluteTimeGetCurrent(), 2.0, 0, 0, timer_callback, None),\n kCFRunLoopCommonModes\n )\n\n try:\n AppHelper.runConsoleEventLoop(installInterrupt=True)\n except KeyboardInterrupt:\n logging.info(\"KeyboardInterrupt received, exiting\")\n\n sys.exit(0)\n\ndef create_env_name(name):\n \"\"\"\n Converts input names into more traditional shell environment name style\n\n >>> create_env_name(\"NSApplicationBundleIdentifier\")\n 'NSAPPLICATION_BUNDLE_IDENTIFIER'\n >>> create_env_name(\"NSApplicationBundleIdentifier-1234$foobar!\")\n 'NSAPPLICATION_BUNDLE_IDENTIFIER_1234_FOOBAR'\n \"\"\"\n new_name = re.sub(r'''(?<=[a-z])([A-Z])''', '_\\\\1', name)\n new_name = re.sub(r'\\W+', '_', new_name)\n new_name = re.sub(r'_{2,}', '_', new_name)\n return new_name.upper().strip(\"_\")\n\ndef do_shell(command, context=None, **kwargs):\n \"\"\"Executes a shell command with logging\"\"\"\n logging.info(\"%s: executing %s\" % (context, command))\n\n child_env = {'CRANKD_CONTEXT': context}\n\n # We'll pull a subset of the available information in for shell scripts.\n # Anyone who needs more will probably want to write a Python handler\n # instead so they can reuse things like our logger & config info and avoid\n # ordeals like associative arrays in Bash\n for k in [ 'info', 'key' ]:\n if k in kwargs and kwargs[k]:\n child_env['CRANKD_%s' % k.upper()] = str(kwargs[k])\n\n if 'user_info' in kwargs:\n for k, v in kwargs['user_info'].items():\n child_env[create_env_name(k)] = str(v)\n\n try:\n rc = call(command, shell=True, env=child_env)\n if rc == 0:\n logging.debug(\"`%s` returned %d\" % (command, rc))\n elif rc < 0:\n logging.error(\"`%s` was terminated by signal %d\" % (command, -rc))\n else:\n logging.error(\"`%s` returned %d\" % (command, rc))\n except OSError, exc:\n logging.error(\"Got an exception when executing %s:\" % (command, exc))\n\n\ndef add_conditional_restart(file_name, reason):\n \"\"\"FSEvents monitors directories, not files. This function uses stat to\n restart only if the file's mtime has changed\"\"\"\n file_name = os.path.realpath(file_name)\n while not os.path.exists(file_name):\n file_name = os.path.dirname(file_name)\n orig_stat = os.stat(file_name).st_mtime\n\n def cond_restart(*args, **kwargs):\n try:\n if os.stat(file_name).st_mtime != orig_stat:\n restart(reason)\n except (OSError, IOError, RuntimeError), exc:\n restart(\"Exception while checking %s: %s\" % (file_name, exc))\n\n add_fs_notification(file_name, cond_restart)\n\n\ndef restart(reason, *args, **kwargs):\n \"\"\"Perform a complete restart of the current process using exec()\"\"\"\n logging.info(\"Restarting: %s\" % reason)\n os.execv(sys.argv[0], sys.argv)\n\nif __name__ == '__main__':\n main()\n"}} -{"repo": "creativedutchmen/Root-Page-Params", "pr_number": 1, "title": "lil spelling correction", "state": "closed", "merged_at": null, "additions": 1, "deletions": 1, "files_changed": ["extension.driver.php"], "files_before": {"extension.driver.php": " 'Root page params',\n\t\t\t\t\t\t 'version' => '1.2',\n\t\t\t\t\t\t 'release-date' => '2009-12-10',\n\t\t\t\t\t\t 'author' => array('name' => 'Huib Keemink',\n\t\t\t\t\t\t\t\t\t\t 'website' => 'http://www.creativedutchmen.com',\n\t\t\t\t\t\t\t\t\t\t 'email' => 'huib@creativedutchmen.com')\n\t\t\t\t \t\t);\n\t\t}\n\t\t\n\t\tpublic function getSubscribedDelegates(){\n\t\t\treturn array(\n\t\t\t\t\t\tarray(\n\t\t\t\t\t\t\t'page' => '/frontend/',\n\t\t\t\t\t\t\t'delegate' => 'FrontendPrePageResolve',\n\t\t\t\t\t\t\t'callback' => 'addPage'\n\t\t\t\t\t\t),\n\t\t\t\t\t\tarray(\n\t\t\t\t\t\t\t'page' => '/system/preferences/',\n\t\t\t\t\t\t\t'delegate' => 'AddCustomPreferenceFieldsets',\n\t\t\t\t\t\t\t'callback' => 'append_preferences'\n\t\t\t\t\t\t),\n\t\t\t\t\t\tarray(\n\t\t\t\t\t\t\t'page' => '/system/preferences/',\n\t\t\t\t\t\t\t'delegate' => 'Save',\n\t\t\t\t\t\t\t'callback' => 'save_settings'\n\t\t\t\t\t\t),\n\t\t\t);\n\t\t}\n\t\t\n\t\tpublic function addPage(&$context){\n\t\t\n\t\t\t//to prevent the callback loop\n\t\t\tif(!$this->alreadyRan){\n\t\t\t\t$this->alreadyRan = true;\n\t\t\t\t//the only way to access the current (active) pages.\n\t\t\t\t$front = FrontEnd::Page();\n\t\t\t\t\n\t\t\t\tif(!$front->resolvePage($context['page'])){\n\t\t\t\t\t//uses home page if no page is set in the config panel.\n\t\t\t\t\tif($this->_get_fallback() == ''){\n\t\t\t\t\t\t$indexPage = $this->__getIndexPage();\n\t\t\t\t\t\t$indexHandle = $indexPage['handle'];\n\t\t\t\t\t}\n\t\t\t\t\telse{\n\t\t\t\t\t\t$indexHandle = $this->_get_fallback();\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\t//adds the home page to the handle, if the current page is not found.\n\t\t\t\t\t//requires the home page to fallback to a 404 if the params do not match, otherwise no 404 error will ever be created.\n\t\t\t\t\t\n\t\t\t\t\t$params = $context['page'];\n\t\t\t\t\t\n\t\t\t\t\tif($this->_Parent->Configuration->get('map_sub_to_front', 'maptofront') == 'no'){\n\t\t\t\t\t\t$tmp = substr($indexHandle,0, strrpos($indexHandle, '/'));\n\t\t\t\t\t\tif(strlen($tmp) > 0){\n\t\t\t\t\t\t\t$params = substr($context['page'], strpos($context['page'], $tmp)+strlen($tmp));\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse{\n\t\t\t\t\t\t\t$params = '';\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t$context['page'] = $indexHandle.$params;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t}\n\t\t\n\t\t\n\t\tpublic function append_preferences(&$context)\n\t\t{\n\t\t\t# Add new fieldset\n\t\t\t$group = new XMLElement('fieldset');\n\t\t\t$group->setAttribute('class', 'settings');\n\t\t\t$group->appendChild(new XMLElement('legend', 'Root Page Params'));\n\n\t\t\t# Add Site Reference field\n\t\t\t//$label = Widget::Label('Fallback page');\n\t\t\t//$label->appendChild(Widget::Input('settings[maptofront][fallback]', General::Sanitize($this->_get_fallback())));\n\t\t\t\n\t\t\t//try to add a select box for the page (more user friendly)\n\t\t\t$label = Widget::Label(__('Page to append parameters to'));\n\t\t\t\n\t\t\t$pages = $this->_Parent->Database->fetch(\"\n\t\t\t\tSELECT\n\t\t\t\t\tp.*\n\t\t\t\tFROM\n\t\t\t\t\t`tbl_pages` AS p\n\t\t\t\tWHERE\n\t\t\t\t\tp.id != '{mysql_real_escape_string($page_id)}'\n\t\t\t\tORDER BY\n\t\t\t\t\tp.title ASC\n\t\t\t\");\n\t\t\t\n\t\t\t$options = array(\n\t\t\t\tarray('', false, '')\n\t\t\t);\n\t\t\t\n\t\t\tif (is_array($pages) && !empty($pages)) {\n\t\t\t\tif (!function_exists('__compare_pages')) {\n\t\t\t\t\tfunction __compare_pages($a, $b) {\n\t\t\t\t\t\treturn strnatcasecmp($a[2], $b[2]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tforeach ($pages as $page) {\n\t\t\t\t\t$options[] = array(\n\t\t\t\t\t\t$this->_Parent->resolvePagePath($page['id']), $this->_Parent->Configuration->get('fallback', 'maptofront') == $this->_Parent->resolvePagePath($page['id']),\n\t\t\t\t\t\t'/'.$this->_Parent->resolvePagePath($page['id'])\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tusort($options, '__compare_pages');\n\t\t\t}\n\t\t\t\n\t\t\t$label->appendChild(Widget::Select(\n\t\t\t\t'settings[maptofront][fallback]', $options\n\t\t\t));\n\t\t\t\n\t\t\t$group->appendChild($label);\n\t\t\t$group->appendChild(new XMLElement('p', 'The page to append the parameters to. Leave empty for home (default).', array('class' => 'help')));\n\t\t\t\n\t\t\t$label = Widget::Label();\n\t\t\t$input = Widget::Input('settings[maptofront][map_sub_to_front]', 'yes', 'checkbox');\n\t\t\tif($this->_Parent->Configuration->get('map_sub_to_front', 'maptofront') == 'yes') $input->setAttribute('checked', 'checked');\n\t\t\t$label->setValue($input->generate() . ' ' . __('Map supages to home page'));\n\t\t\t\n\t\t\t$group->appendChild($label);\n\t\t\t$group->appendChild(new XMLElement('p', 'Maps subpages to the root page when checked, maps subpages to their parents if unchecked.', array('class' => 'help')));\n\t\t\t\n\t\t\t$context['wrapper']->appendChild($group);\n\t\t}\n\t\t\n\t\t//any way to get this without using the database?\n\t\tfunction __getIndexPage(){\n\t\t\t$row = $this->_Parent->Database->fetchRow(0, \"SELECT `tbl_pages`.* FROM `tbl_pages`, `tbl_pages_types` \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t WHERE `tbl_pages_types`.page_id = `tbl_pages`.id \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t AND tbl_pages_types.`type` = 'index' \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t LIMIT 1\");\n\t\t\treturn $row;\n\t\t}\n\t\t\n\t\tfunction _get_fallback(){\n\t\t\t$default_fallback = '';\n\t\t\t$val = $this->_Parent->Configuration->get('fallback', 'maptofront');\n\t\t\t\n\t\t\treturn (isset($val)) ? $val : $default_fallback;\n\t\t}\n\t\t\n\t\tfunction save_settings($context){\n\t\t\tif(!isset($context['settings']['maptofront']['map_sub_to_front'])) $context['settings']['maptofront']['map_sub_to_front'] = 'no';\n\t\t\t\n\t\t\tif(!isset($context['settings']['maptofront'])){\n\t\t\t\t$context['settings']['maptofront'] = array('map_sub_to_front' => 'no');\n\t\t\t}\n\t\t}\n\t}\n"}, "files_after": {"extension.driver.php": " 'Root page params',\n\t\t\t\t\t\t 'version' => '1.2',\n\t\t\t\t\t\t 'release-date' => '2009-12-10',\n\t\t\t\t\t\t 'author' => array('name' => 'Huib Keemink',\n\t\t\t\t\t\t\t\t\t\t 'website' => 'http://www.creativedutchmen.com',\n\t\t\t\t\t\t\t\t\t\t 'email' => 'huib@creativedutchmen.com')\n\t\t\t\t \t\t);\n\t\t}\n\t\t\n\t\tpublic function getSubscribedDelegates(){\n\t\t\treturn array(\n\t\t\t\t\t\tarray(\n\t\t\t\t\t\t\t'page' => '/frontend/',\n\t\t\t\t\t\t\t'delegate' => 'FrontendPrePageResolve',\n\t\t\t\t\t\t\t'callback' => 'addPage'\n\t\t\t\t\t\t),\n\t\t\t\t\t\tarray(\n\t\t\t\t\t\t\t'page' => '/system/preferences/',\n\t\t\t\t\t\t\t'delegate' => 'AddCustomPreferenceFieldsets',\n\t\t\t\t\t\t\t'callback' => 'append_preferences'\n\t\t\t\t\t\t),\n\t\t\t\t\t\tarray(\n\t\t\t\t\t\t\t'page' => '/system/preferences/',\n\t\t\t\t\t\t\t'delegate' => 'Save',\n\t\t\t\t\t\t\t'callback' => 'save_settings'\n\t\t\t\t\t\t),\n\t\t\t);\n\t\t}\n\t\t\n\t\tpublic function addPage(&$context){\n\t\t\n\t\t\t//to prevent the callback loop\n\t\t\tif(!$this->alreadyRan){\n\t\t\t\t$this->alreadyRan = true;\n\t\t\t\t//the only way to access the current (active) pages.\n\t\t\t\t$front = FrontEnd::Page();\n\t\t\t\t\n\t\t\t\tif(!$front->resolvePage($context['page'])){\n\t\t\t\t\t//uses home page if no page is set in the config panel.\n\t\t\t\t\tif($this->_get_fallback() == ''){\n\t\t\t\t\t\t$indexPage = $this->__getIndexPage();\n\t\t\t\t\t\t$indexHandle = $indexPage['handle'];\n\t\t\t\t\t}\n\t\t\t\t\telse{\n\t\t\t\t\t\t$indexHandle = $this->_get_fallback();\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\t//adds the home page to the handle, if the current page is not found.\n\t\t\t\t\t//requires the home page to fallback to a 404 if the params do not match, otherwise no 404 error will ever be created.\n\t\t\t\t\t\n\t\t\t\t\t$params = $context['page'];\n\t\t\t\t\t\n\t\t\t\t\tif($this->_Parent->Configuration->get('map_sub_to_front', 'maptofront') == 'no'){\n\t\t\t\t\t\t$tmp = substr($indexHandle,0, strrpos($indexHandle, '/'));\n\t\t\t\t\t\tif(strlen($tmp) > 0){\n\t\t\t\t\t\t\t$params = substr($context['page'], strpos($context['page'], $tmp)+strlen($tmp));\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse{\n\t\t\t\t\t\t\t$params = '';\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t$context['page'] = $indexHandle.$params;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t}\n\t\t\n\t\t\n\t\tpublic function append_preferences(&$context)\n\t\t{\n\t\t\t# Add new fieldset\n\t\t\t$group = new XMLElement('fieldset');\n\t\t\t$group->setAttribute('class', 'settings');\n\t\t\t$group->appendChild(new XMLElement('legend', 'Root Page Params'));\n\n\t\t\t# Add Site Reference field\n\t\t\t//$label = Widget::Label('Fallback page');\n\t\t\t//$label->appendChild(Widget::Input('settings[maptofront][fallback]', General::Sanitize($this->_get_fallback())));\n\t\t\t\n\t\t\t//try to add a select box for the page (more user friendly)\n\t\t\t$label = Widget::Label(__('Page to append parameters to'));\n\t\t\t\n\t\t\t$pages = $this->_Parent->Database->fetch(\"\n\t\t\t\tSELECT\n\t\t\t\t\tp.*\n\t\t\t\tFROM\n\t\t\t\t\t`tbl_pages` AS p\n\t\t\t\tWHERE\n\t\t\t\t\tp.id != '{mysql_real_escape_string($page_id)}'\n\t\t\t\tORDER BY\n\t\t\t\t\tp.title ASC\n\t\t\t\");\n\t\t\t\n\t\t\t$options = array(\n\t\t\t\tarray('', false, '')\n\t\t\t);\n\t\t\t\n\t\t\tif (is_array($pages) && !empty($pages)) {\n\t\t\t\tif (!function_exists('__compare_pages')) {\n\t\t\t\t\tfunction __compare_pages($a, $b) {\n\t\t\t\t\t\treturn strnatcasecmp($a[2], $b[2]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tforeach ($pages as $page) {\n\t\t\t\t\t$options[] = array(\n\t\t\t\t\t\t$this->_Parent->resolvePagePath($page['id']), $this->_Parent->Configuration->get('fallback', 'maptofront') == $this->_Parent->resolvePagePath($page['id']),\n\t\t\t\t\t\t'/'.$this->_Parent->resolvePagePath($page['id'])\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tusort($options, '__compare_pages');\n\t\t\t}\n\t\t\t\n\t\t\t$label->appendChild(Widget::Select(\n\t\t\t\t'settings[maptofront][fallback]', $options\n\t\t\t));\n\t\t\t\n\t\t\t$group->appendChild($label);\n\t\t\t$group->appendChild(new XMLElement('p', 'The page to append the parameters to. Leave empty for home (default).', array('class' => 'help')));\n\t\t\t\n\t\t\t$label = Widget::Label();\n\t\t\t$input = Widget::Input('settings[maptofront][map_sub_to_front]', 'yes', 'checkbox');\n\t\t\tif($this->_Parent->Configuration->get('map_sub_to_front', 'maptofront') == 'yes') $input->setAttribute('checked', 'checked');\n\t\t\t$label->setValue($input->generate() . ' ' . __('Map subpages to home page'));\n\t\t\t\n\t\t\t$group->appendChild($label);\n\t\t\t$group->appendChild(new XMLElement('p', 'Maps subpages to the root page when checked, maps subpages to their parents if unchecked.', array('class' => 'help')));\n\t\t\t\n\t\t\t$context['wrapper']->appendChild($group);\n\t\t}\n\t\t\n\t\t//any way to get this without using the database?\n\t\tfunction __getIndexPage(){\n\t\t\t$row = $this->_Parent->Database->fetchRow(0, \"SELECT `tbl_pages`.* FROM `tbl_pages`, `tbl_pages_types` \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t WHERE `tbl_pages_types`.page_id = `tbl_pages`.id \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t AND tbl_pages_types.`type` = 'index' \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t LIMIT 1\");\n\t\t\treturn $row;\n\t\t}\n\t\t\n\t\tfunction _get_fallback(){\n\t\t\t$default_fallback = '';\n\t\t\t$val = $this->_Parent->Configuration->get('fallback', 'maptofront');\n\t\t\t\n\t\t\treturn (isset($val)) ? $val : $default_fallback;\n\t\t}\n\t\t\n\t\tfunction save_settings($context){\n\t\t\tif(!isset($context['settings']['maptofront']['map_sub_to_front'])) $context['settings']['maptofront']['map_sub_to_front'] = 'no';\n\t\t\t\n\t\t\tif(!isset($context['settings']['maptofront'])){\n\t\t\t\t$context['settings']['maptofront'] = array('map_sub_to_front' => 'no');\n\t\t\t}\n\t\t}\n\t}\n"}} -{"repo": "fgrehm/qmlunit", "pr_number": 1, "title": "Mergebranch", "state": "closed", "merged_at": null, "additions": 106, "deletions": 7, "files_changed": ["qmlunittestrunner.cpp", "scripts/QUnitTestXmlLogger.js"], "files_before": {"qmlunittestrunner.cpp": "#include \"qmlunittestrunner.h\"\n#include \"qmllogger.h\"\n#include \n#include \n#include \n\nQmlUnitTestRunner::QmlUnitTestRunner(QApplication *app) :\n QObject(app)\n{\n this->app = app;\n\n QStringList args = app->arguments();\n // Skips executable\n args.removeAt(0);\n\n if (args.count() == 0) {\n qDebug() << \"No arguments passed, failing back to qmlunit Test Suite (\" << (app->applicationDirPath() + \"/test\") << \")\\n\";\n args = QStringList(app->applicationDirPath() + \"/test\");\n }\n\n QStringListIterator i(args);\n while(i.hasNext())\n findTests(i.next());\n\n i = QStringListIterator(tests);\n qDebug() << \"Tests files found:\";\n while(i.hasNext()) {\n QString currentArg = i.next();\n qDebug() << \"\\t\" << currentArg;\n }\n}\n\nvoid QmlUnitTestRunner::setup(){\n QmlLogger *logger = new QmlLogger(app->applicationDirPath(), this);\n\n QDeclarativeEngine *engine = logger->engine();\n\n engine->setOfflineStoragePath(QDir::currentPath() + \"/storage\");\n engine->addImportPath(QDir::currentPath() + \"/QmlUnit\");\n engine->rootContext()->setContextProperty(\"testsInput\", tests);\n engine->rootContext()->setContextProperty(\"currentPath\", QDir::currentPath());\n\n logger->setup();\n}\n\nint QmlUnitTestRunner::exec() {\n setup();\n return app->exec();\n}\n\nvoid QmlUnitTestRunner::findTests(QString path) {\n if (isTest(path)) {\n tests << QDir(path).absolutePath();\n return;\n }\n\n QStringList filters; filters << \"*\";\n QDir dir = QDir(QDir(path).absolutePath());\n\n QListIterator files(dir.entryInfoList(filters, QDir::AllEntries | QDir::NoDotAndDotDot));\n while(files.hasNext()) {\n QFileInfo file = files.next();\n if (file.fileName() == \".\" || file.fileName() == \"..\") continue;\n\n if (isTest(file))\n tests << file.absoluteFilePath();\n else if (isDir(file))\n findTests(file.absoluteFilePath());\n }\n}\n\nbool QmlUnitTestRunner::isTest(QFileInfo file){\n return isTest(file.fileName());\n}\n\nbool QmlUnitTestRunner::isTest(QString filePath){\n return filePath.endsWith(\"Test.qml\");\n}\n\nbool QmlUnitTestRunner::isDir(QFileInfo file){\n return QDir(file.absoluteFilePath()).exists();\n}\n"}, "files_after": {"qmlunittestrunner.cpp": "#include \"qmlunittestrunner.h\"\n#include \"qmllogger.h\"\n#include \n#include \n#include \n\nQmlUnitTestRunner::QmlUnitTestRunner(QApplication *app) :\n QObject(app)\n{\n this->app = app;\n\n QStringList args = app->arguments();\n // Skips executable\n args.removeAt(0);\n \n // Parse possible xmlUnitOutput arg\n bool xmlOutput = false;\n \n if ((args.count() > 0) && args.contains(\"-xml\")) {\n xmlOutput = true;\n args.removeAt(args.indexOf(\"-xml\"));\n }\n \n if (args.count() == 0) {\n // Surpress all non-xml output if xml output was requested\n if (!xmlOutput) \n qDebug() << \"No arguments passed, failing back to qmlunit Test Suite (\" << (app->applicationDirPath() + \"/test\") << \")\\n\";\n args = QStringList(app->applicationDirPath() + \"/test\");\n }\n\n QStringListIterator i(args);\n while(i.hasNext())\n findTests(i.next());\n\n i = QStringListIterator(tests);\n \n // Surpress all non-xml output if xml output was requested\n if (!xmlOutput) {\n qDebug() << \"Tests files found:\";\n while(i.hasNext()) {\n QString currentArg = i.next();\n qDebug() << \"\\t\" << currentArg;\n }\n }\n}\n\nvoid QmlUnitTestRunner::setup(){\n QmlLogger *logger = new QmlLogger(app->applicationDirPath(), this);\n\n QDeclarativeEngine *engine = logger->engine();\n\n engine->setOfflineStoragePath(QDir::currentPath() + \"/storage\");\n engine->addImportPath(QDir::currentPath() + \"/QmlUnit\");\n engine->rootContext()->setContextProperty(\"testsInput\", tests);\n engine->rootContext()->setContextProperty(\"currentPath\", QDir::currentPath());\n\n logger->setup();\n}\n\nint QmlUnitTestRunner::exec() {\n setup();\n return app->exec();\n}\n\nvoid QmlUnitTestRunner::findTests(QString path) {\n if (isTest(path)) {\n tests << QDir(path).absolutePath();\n return;\n }\n\n QStringList filters; filters << \"*\";\n QDir dir = QDir(QDir(path).absolutePath());\n\n QListIterator files(dir.entryInfoList(filters, QDir::AllEntries | QDir::NoDotAndDotDot));\n while(files.hasNext()) {\n QFileInfo file = files.next();\n if (file.fileName() == \".\" || file.fileName() == \"..\") continue;\n\n if (isTest(file))\n tests << file.absoluteFilePath();\n else if (isDir(file))\n findTests(file.absoluteFilePath());\n }\n}\n\nbool QmlUnitTestRunner::isTest(QFileInfo file){\n return isTest(file.fileName());\n}\n\nbool QmlUnitTestRunner::isTest(QString filePath){\n return filePath.endsWith(\"Test.qml\");\n}\n\nbool QmlUnitTestRunner::isDir(QFileInfo file){\n return QDir(file.absoluteFilePath()).exists();\n}\n", "scripts/QUnitTestXmlLogger.js": "var currentTestSuite;\nvar testSuites = []; \n\nfunction addTestSuite(name) {\n\n currentTestSuite = {\n name: name,\n errors: 0,\n testsTotal: 0,\n time: 0.0, \n failures: 0,\n tests: []\n };\n testSuites.push(currentTestSuite)\n}\n\nfunction parseFailureMessage(assertions) {\n var message = \"\"\n for (var i=0; i\")\n logger.log(\"\")\n \n testSuites.forEach(function(testSuite) {\n logger.log(\" \")\n \n testSuite.tests.forEach(function(test) {\n if (test.failures == 0) { \n logger.log(\" \")\n } \n else {\n logger.log(\" \")\n logger.log(\" \")\n logger.log(\" \")\n } \n });\n \n logger.log(\" \")\n });\n \n logger.log(\"\")\n}\n\n\n"}} -{"repo": "SunboX/mootools-fx-text", "pr_number": 1, "title": "fx-text for the pack", "state": "closed", "merged_at": "2010-10-02T17:41:23Z", "additions": 82, "deletions": 55, "files_changed": ["Source/Element.retype.js", "Source/Fx.Text.js"], "files_before": {"Source/Element.retype.js": "/*\n---\n \nname: Element.retype\n \ndescription: Effect to animated replace the text of an element.\n\nauthors: Dipl.-Ing. (FH) Andr\u00e9 Fiedler \n\ncopyright: Copyright (c) 2010 Dipl.-Ing. (FH) Andr\u00e9 Fiedler \n \nlicense: MIT-style license.\n\nversion: 1.0\n \nrequires: Fx.Text\n \nprovides: Element.retype\n \n...\n*/\n\nElement.Properties.retype = {\r\n\r\n set: function(options){\r\n var retype = this.retrieve('retype');\r\n if (retype) \r\n retype.cancel();\r\n return this.eliminate('retype').store('retype:options', $extend({\r\n link: 'cancel'\r\n }, options));\r\n },\r\n \r\n get: function(options){\r\n if (options || !this.retrieve('retype')) {\r\n if (options || !this.retrieve('retype:options')) \r\n this.set('retype', options);\r\n this.store('retype', new Fx.Text(this, this.retrieve('retype:options')));\r\n }\r\n return this.retrieve('retype');\r\n } \r\n};\r\n\r\nElement.implement({\r\n\r\n retype: function(from, to){\r\n this.get('retype').start(from, to);\r\n return this;\r\n }\r\n});", "Source/Fx.Text.js": "/*\n---\n \nname: Fx.Text\n \ndescription: Effect to animated replace the text of an element.\n\nauthors: Dipl.-Ing. (FH) Andr\u00e9 Fiedler \n\ncopyright: Copyright (c) 2010 Dipl.-Ing. (FH) Andr\u00e9 Fiedler \n \nlicense: MIT-style license.\n\nversion: 1.2.1\n \nrequires: Core/1.2.4: Fx\n \nprovides: Fx.Text\n \n...\n*/\n\nFx.Text = new Class({\r\n\r\n Extends: Fx,\r\n \r\n initialize: function(element, options){\r\n this.element = this.subject = document.id(element);\r\n this.parent(options);\r\n },\r\n \r\n set: function(now){\r\n this.element.set('text', now);\r\n return this;\r\n },\r\n \r\n step: function(){\r\n if (!this.to) {\r\n this.to = this.from;\r\n this.from = this.element.get('text', '');\r\n }\r\n return this.parent();\r\n },\r\n \r\n compute: function(from, to, delta){\r\n var l = Math.round(to.length * delta);\r\n var r = Math.round((from.length - to.length) * delta);\r\n return to.substr(0, l) + from.substr(l, from.length - l - r);\r\n }\r\n});\n"}, "files_after": {"Source/Element.retype.js": "/*\n---\n \nname: Element.retype\n \ndescription: Effect to animated replace the text of an element.\n\nauthors: Dipl.-Ing. (FH) Andr\u00e9 Fiedler \n\ncopyright: Copyright (c) 2010 Dipl.-Ing. (FH) Andr\u00e9 Fiedler \n \nlicense: MIT-style license.\n\nversion: 1.0\n \nrequires:\n - Fx.Text\n \nprovides: Element.retype\n \n...\n*/\n\nElement.Properties.retype = {\r\n\r\n\tset: function(options){\r\n\t\tvar retype = this.retrieve('retype');\r\n\t\tif (retype)\r\n\t\t\tretype.cancel();\r\n\t\treturn this.eliminate('retype').store('retype:options', $extend({\r\n\t\t\tlink: 'cancel'\r\n\t\t}, options));\r\n\t},\r\n\t\r\n\tget: function(options){\r\n\t\tif (options || !this.retrieve('retype')){\r\n\t\t\tif (options || !this.retrieve('retype:options'))\r\n\t\t\t\tthis.set('retype', options);\r\n\t\t\tthis.store('retype', new Fx.Text(this, this.retrieve('retype:options')));\r\n\t\t}\r\n\t\treturn this.retrieve('retype');\r\n\t}\n\t\r\n};\r\n\r\nElement.implement({\r\n\r\n\tretype: function(from, to){\r\n\t\tthis.get('retype').start(from, to);\r\n\t\treturn this;\r\n\t}\n\t\r\n});\n", "Source/Fx.Text.js": "/*\n---\n \nname: Fx.Text\n \ndescription: Effect to animated replace the text of an element.\n\nauthors: Dipl.-Ing. (FH) Andr\u00e9 Fiedler \n\ncopyright: Copyright (c) 2010 Dipl.-Ing. (FH) Andr\u00e9 Fiedler \n \nlicense: MIT-style license.\n\nversion: 1.2.1\n \nrequires: \n - Core/Element\n - Core/Fx\n \nprovides: Fx.Text\n \n...\n*/\n\nFx.Text = new Class({\r\n\r\n\tExtends: Fx,\r\n\t\r\n\tinitialize: function(element, options){\r\n\t\tthis.element = this.subject = document.id(element);\r\n\t\tthis.parent(options);\r\n\t},\r\n\t\r\n\tset: function(now){\r\n\t\tthis.element.set('text', now);\r\n\t\treturn this;\r\n\t},\r\n\t\r\n\tstep: function(){\r\n\t\tif (!this.to){\r\n\t\t\tthis.to = this.from;\r\n\t\t\tthis.from = this.element.get('text', '');\r\n\t\t}\r\n\t\treturn this.parent();\r\n\t},\r\n\t\r\n\tcompute: function(from, to, delta){\r\n\t\tvar l = Math.round(to.length * delta),\n\t\t\tr = Math.round((from.length - to.length) * delta);\r\n\t\treturn to.substr(0, l) + from.substr(l, from.length - l - r);\r\n\t}\n\t\r\n});\n"}} -{"repo": "seam/servlet", "pr_number": 5, "title": "SEAMSERVLET-32", "state": "closed", "merged_at": "2011-03-25T05:19:21Z", "additions": 12, "deletions": 11, "files_changed": ["impl/src/main/java/org/jboss/seam/servlet/event/ImplicitServletObjectsHolder.java"], "files_before": {"impl/src/main/java/org/jboss/seam/servlet/event/ImplicitServletObjectsHolder.java": "/*\n * JBoss, Home of Professional Open Source\n * Copyright 2010, Red Hat Middleware LLC, and individual contributors\n * by the @authors tag. See the copyright.txt in the distribution for a\n * full listing of individual contributors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jboss.seam.servlet.event;\n\nimport javax.enterprise.context.ApplicationScoped;\nimport javax.enterprise.event.Observes;\nimport javax.enterprise.inject.spi.BeanManager;\nimport javax.inject.Inject;\nimport javax.servlet.ServletContext;\nimport javax.servlet.ServletRequest;\nimport javax.servlet.ServletResponse;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\nimport javax.servlet.http.HttpSession;\n\nimport org.jboss.seam.servlet.ServletRequestContext;\nimport org.jboss.seam.servlet.beanManager.ServletContextAttributeProvider;\nimport org.jboss.seam.servlet.http.HttpServletRequestContext;\nimport org.jboss.seam.servlet.support.ServletLogger;\nimport org.jboss.seam.solder.logging.Category;\n\n/**\n * A manager for tracking the contextual Servlet objects, specifically the {@link ServletContext}, {@link HttpServletRequest}\n * and {@link HttpServletResponse}.\n * \n * @author Dan Allen\n */\n@ApplicationScoped\npublic class ImplicitServletObjectsHolder {\n @Inject @Category(ServletLogger.CATEGORY)\n private ServletLogger log;\n\n private ServletContext servletCtx;\n\n private final ThreadLocal requestCtx = new InheritableThreadLocal() {\n @Override\n protected ServletRequestContext initialValue() {\n return null;\n }\n };\n\n protected void contextInitialized(@Observes @Initialized final InternalServletContextEvent e, BeanManager beanManager) {\n ServletContext ctx = e.getServletContext();\n log.servletContextInitialized(ctx);\n ctx.setAttribute(BeanManager.class.getName(), beanManager);\n ServletContextAttributeProvider.setServletContext(ctx);\n servletCtx = ctx;\n }\n\n protected void contextDestroyed(@Observes @Destroyed final InternalServletContextEvent e) {\n log.servletContextDestroyed(e.getServletContext());\n servletCtx = null;\n }\n\n protected void requestInitialized(@Observes @Initialized final InternalServletRequestEvent e) {\n ServletRequest req = e.getServletRequest();\n log.servletRequestInitialized(req);\n if (req instanceof HttpServletRequest) {\n requestCtx.set(new HttpServletRequestContext(req));\n } else {\n requestCtx.set(new ServletRequestContext(req));\n }\n }\n\n protected void requestDestroyed(@Observes @Destroyed final InternalServletRequestEvent e) {\n log.servletRequestDestroyed(e.getServletRequest());\n requestCtx.set(null);\n }\n\n protected void responseInitialized(@Observes @Initialized final InternalServletResponseEvent e) {\n ServletResponse res = e.getServletResponse();\n log.servletResponseInitialized(res);\n if (res instanceof HttpServletResponse) {\n requestCtx.set(new HttpServletRequestContext(requestCtx.get().getRequest(), res));\n } else {\n requestCtx.set(new ServletRequestContext(requestCtx.get().getRequest(), res));\n }\n }\n\n protected void responseDestroyed(@Observes @Destroyed final InternalServletResponseEvent e) {\n log.servletResponseDestroyed(e.getServletResponse());\n if (requestCtx.get() instanceof HttpServletRequestContext) {\n requestCtx.set(new HttpServletRequestContext(requestCtx.get().getRequest()));\n } else {\n requestCtx.set(new ServletRequestContext(requestCtx.get().getRequest()));\n }\n }\n\n public ServletContext getServletContext() {\n return servletCtx;\n }\n\n public ServletRequestContext getServletRequestContext() {\n return requestCtx.get();\n }\n\n public HttpServletRequestContext getHttpServletRequestContext() {\n if (requestCtx.get() instanceof HttpServletRequestContext) {\n return HttpServletRequestContext.class.cast(requestCtx.get());\n } else {\n return null;\n }\n }\n\n public ServletRequest getServletRequest() {\n if (requestCtx.get() != null) {\n return requestCtx.get().getRequest();\n } else {\n return null;\n }\n }\n\n public HttpServletRequest getHttpServletRequest() {\n if (requestCtx.get() instanceof HttpServletRequestContext) {\n return HttpServletRequestContext.class.cast(requestCtx.get()).getRequest();\n } else {\n return null;\n }\n }\n\n public ServletResponse getServletResponse() {\n if (requestCtx.get() != null) {\n return requestCtx.get().getResponse();\n } else {\n return null;\n }\n }\n\n public HttpServletResponse getHttpServletResponse() {\n if (requestCtx.get() instanceof HttpServletRequestContext) {\n return HttpServletRequestContext.class.cast(requestCtx.get()).getResponse();\n } else {\n return null;\n }\n }\n\n public HttpSession getHttpSession() {\n if (requestCtx.get() instanceof HttpServletRequestContext) {\n return HttpServletRequestContext.class.cast(requestCtx.get()).getRequest().getSession();\n } else {\n return null;\n }\n }\n\n static class InternalServletContextEvent {\n private ServletContext ctx;\n\n InternalServletContextEvent(ServletContext ctx) {\n this.ctx = ctx;\n }\n\n public ServletContext getServletContext() {\n return ctx;\n }\n }\n\n static class InternalServletRequestEvent {\n private ServletRequest request;\n\n InternalServletRequestEvent(ServletRequest request) {\n this.request = request;\n }\n\n public ServletRequest getServletRequest() {\n return request;\n }\n }\n\n static class InternalServletResponseEvent {\n private ServletResponse response;\n\n InternalServletResponseEvent(ServletResponse response) {\n this.response = response;\n }\n\n public ServletResponse getServletResponse() {\n return response;\n }\n }\n\n static class InternalHttpSessionEvent {\n private HttpSession session;\n\n InternalHttpSessionEvent(HttpSession session) {\n this.session = session;\n }\n\n public HttpSession getHttpSession() {\n return session;\n }\n }\n}\n"}, "files_after": {"impl/src/main/java/org/jboss/seam/servlet/event/ImplicitServletObjectsHolder.java": "/*\n * JBoss, Home of Professional Open Source\n * Copyright 2010, Red Hat Middleware LLC, and individual contributors\n * by the @authors tag. See the copyright.txt in the distribution for a\n * full listing of individual contributors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jboss.seam.servlet.event;\n\nimport javax.enterprise.context.ApplicationScoped;\nimport javax.enterprise.event.Observes;\nimport javax.enterprise.inject.spi.BeanManager;\nimport javax.inject.Inject;\nimport javax.servlet.ServletContext;\nimport javax.servlet.ServletRequest;\nimport javax.servlet.ServletResponse;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\nimport javax.servlet.http.HttpSession;\n\nimport org.jboss.seam.servlet.ServletRequestContext;\nimport org.jboss.seam.servlet.beanManager.ServletContextAttributeProvider;\nimport org.jboss.seam.servlet.http.HttpServletRequestContext;\nimport org.jboss.seam.servlet.support.ServletLogger;\nimport org.jboss.seam.solder.logging.Category;\n\n/**\n * A manager for tracking the contextual Servlet objects, specifically the {@link ServletContext}, {@link HttpServletRequest}\n * and {@link HttpServletResponse}.\n * \n * @author Dan Allen\n */\n@ApplicationScoped\npublic class ImplicitServletObjectsHolder {\n @Inject @Category(ServletLogger.CATEGORY)\n private ServletLogger log;\n\n private ServletContext servletCtx;\n\n private final ThreadLocal requestCtx = new ThreadLocal() {\n @Override\n protected ServletRequestContext initialValue() {\n return null;\n }\n };\n\n protected void contextInitialized(@Observes @Initialized final InternalServletContextEvent e, BeanManager beanManager) {\n ServletContext ctx = e.getServletContext();\n log.servletContextInitialized(ctx);\n ctx.setAttribute(BeanManager.class.getName(), beanManager);\n ServletContextAttributeProvider.setServletContext(ctx);\n servletCtx = ctx;\n }\n\n protected void contextDestroyed(@Observes @Destroyed final InternalServletContextEvent e) {\n log.servletContextDestroyed(e.getServletContext());\n servletCtx = null;\n }\n\n protected void requestInitialized(@Observes @Initialized final InternalServletRequestEvent e) {\n ServletRequest req = e.getServletRequest();\n log.servletRequestInitialized(req);\n if (req instanceof HttpServletRequest) {\n requestCtx.set(new HttpServletRequestContext(req));\n } else {\n requestCtx.set(new ServletRequestContext(req));\n }\n }\n\n protected void requestDestroyed(@Observes @Destroyed final InternalServletRequestEvent e) {\n log.servletRequestDestroyed(e.getServletRequest());\n requestCtx.set(null);\n }\n\n protected void responseInitialized(@Observes @Initialized final InternalServletResponseEvent e) {\n ServletResponse res = e.getServletResponse();\n log.servletResponseInitialized(res);\n if (res instanceof HttpServletResponse) {\n requestCtx.set(new HttpServletRequestContext(requestCtx.get().getRequest(), res));\n } else {\n requestCtx.set(new ServletRequestContext(requestCtx.get().getRequest(), res));\n }\n }\n\n protected void responseDestroyed(@Observes @Destroyed final InternalServletResponseEvent e) {\n log.servletResponseDestroyed(e.getServletResponse());\n if (requestCtx.get() instanceof HttpServletRequestContext) {\n requestCtx.set(new HttpServletRequestContext(requestCtx.get().getRequest()));\n } else {\n requestCtx.set(new ServletRequestContext(requestCtx.get().getRequest()));\n }\n }\n\n public ServletContext getServletContext() {\n return servletCtx;\n }\n\n public ServletRequestContext getServletRequestContext() {\n return requestCtx.get();\n }\n\n public HttpServletRequestContext getHttpServletRequestContext() {\n if (requestCtx.get() instanceof HttpServletRequestContext) {\n return HttpServletRequestContext.class.cast(requestCtx.get());\n } else {\n return null;\n }\n }\n\n public ServletRequest getServletRequest() {\n if (requestCtx.get() != null) {\n return requestCtx.get().getRequest();\n } else {\n return null;\n }\n }\n\n public HttpServletRequest getHttpServletRequest() {\n if (requestCtx.get() instanceof HttpServletRequestContext) {\n return HttpServletRequestContext.class.cast(requestCtx.get()).getRequest();\n } else {\n return null;\n }\n }\n\n public ServletResponse getServletResponse() {\n if (requestCtx.get() != null) {\n return requestCtx.get().getResponse();\n } else {\n return null;\n }\n }\n\n public HttpServletResponse getHttpServletResponse() {\n if (requestCtx.get() instanceof HttpServletRequestContext) {\n return HttpServletRequestContext.class.cast(requestCtx.get()).getResponse();\n } else {\n return null;\n }\n }\n\n public HttpSession getHttpSession() {\n if (requestCtx.get() instanceof HttpServletRequestContext) {\n return HttpServletRequestContext.class.cast(requestCtx.get()).getRequest().getSession();\n } else {\n return null;\n }\n }\n\n static class InternalServletContextEvent {\n private ServletContext ctx;\n\n InternalServletContextEvent(ServletContext ctx) {\n this.ctx = ctx;\n }\n\n public ServletContext getServletContext() {\n return ctx;\n }\n }\n\n static class InternalServletRequestEvent {\n private ServletRequest request;\n\n InternalServletRequestEvent(ServletRequest request) {\n this.request = request;\n }\n\n public ServletRequest getServletRequest() {\n return request;\n }\n }\n\n static class InternalServletResponseEvent {\n private ServletResponse response;\n\n InternalServletResponseEvent(ServletResponse response) {\n this.response = response;\n }\n\n public ServletResponse getServletResponse() {\n return response;\n }\n }\n\n static class InternalHttpSessionEvent {\n private HttpSession session;\n\n InternalHttpSessionEvent(HttpSession session) {\n this.session = session;\n }\n\n public HttpSession getHttpSession() {\n return session;\n }\n }\n}\n"}} -{"repo": "otrtool/otrtool", "pr_number": 12, "title": "Logfilemode must not be set if guimode is enabled.", "state": "closed", "merged_at": "2016-06-05T10:16:17Z", "additions": 1, "deletions": 1, "files_changed": ["src/main.c"], "files_before": {"src/main.c": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \n#include \"md5.h\"\n\n#include \n#include \n\n#define ERROR(...) \\\n ({fprintf(stderr, \"\\n\"); \\\n fprintf(stderr, __VA_ARGS__); \\\n fprintf(stderr, \"\\n\"); \\\n exit(EXIT_FAILURE); })\n\n#define PERROR(...) \\\n ({fprintf(stderr, \"\\n\"); \\\n fprintf(stderr, __VA_ARGS__); \\\n fprintf(stderr, \": \"); \\\n perror(NULL); \\\n exit(EXIT_FAILURE); })\n\n#define MIN(a,b) ((a)<(b)?(a):(b))\n\n#ifndef VERSION\n #define VERSION \"version unknown\"\n#endif\n\n#define LINE_LENGTH 80\n#define MAX_RESPONSE_LENGTH 1000\n#define CREAT_MODE S_IWUSR|S_IRUSR|S_IRGRP|S_IROTH\n\n#define VERB_INFO 1\n#define VERB_DEBUG 2\n\n#define ACTION_INFO 1\n#define ACTION_FETCHKEY 2\n#define ACTION_DECRYPT 3\n#define ACTION_VERIFY 4\n\n/* global options as supplied by the user via command-line etc. */\nstruct otrtool_options {\n int action;\n int verbosity;\n int guimode; // do not output \\r and stuff\n int unlinkmode;\n char *email;\n char *password;\n char *keyphrase;\n char *destdir;\n char *destfile;\n};\nstatic struct otrtool_options opts = {\n .action = ACTION_INFO,\n .verbosity = VERB_INFO,\n .guimode = 0,\n .unlinkmode = 0,\n .email = NULL,\n .password = NULL,\n .keyphrase = NULL,\n .destdir = NULL,\n .destfile = NULL,\n};\n\nstatic int interactive = 1; // ask questions instead of exiting\nstatic int logfilemode = 0; // do not output progress bar\n\nstatic char *email = NULL;\nstatic char *password = NULL;\nstatic char *keyphrase = NULL;\nstatic char *filename = NULL;\nstatic char *destfilename = NULL;\n\nstatic FILE *file = NULL;\nstatic FILE *keyfile = NULL;\nstatic FILE *ttyfile = NULL;\nstatic char *header = NULL;\nstatic char *info = NULL;\n\n// ######################## curl-stuff #######################\n\nstruct MemoryStruct {\n char *memory;\n size_t size;\n};\n\nstatic size_t WriteMemoryCallback(void *ptr, size_t size,\n size_t nmemb, void *data) {\n size_t realsize = size * nmemb;\n struct MemoryStruct *mem = (struct MemoryStruct *)data;\n char *newmem;\n \n // abort very long transfers\n if (mem->size + realsize > MAX_RESPONSE_LENGTH) {\n realsize = mem->size <= MAX_RESPONSE_LENGTH\n ? MAX_RESPONSE_LENGTH - mem->size\n : 0;\n }\n if (realsize < 1) return 0;\n \n // \"If realloc() fails the original block is left untouched\" (man 3 realloc)\n newmem = realloc(mem->memory, mem->size + realsize);\n if (newmem != NULL) {\n mem->memory = newmem;\n memcpy(&(mem->memory[mem->size]), ptr, realsize);\n mem->size += realsize;\n } else return 0;\n return realsize;\n}\n\n// ######################## generic functions ####################\n\nchar * bin2hex(void *data_, int len) {\n unsigned char *data = data_;\n unsigned char *result = malloc(sizeof(char) * len * 2 + 1);\n result[len * 2] = 0;\n int foo;\n for (len-- ; len >= 0 ; len--) {\n foo = data[len] % 16;\n result[len*2 + 1] = foo > 9 ? 0x37 + foo : 0x30 + foo;\n foo = data[len] >> 4;\n result[len*2] = foo > 9 ? 0x37 + foo : 0x30 + foo;\n }\n return (char*)result;\n}\n\nvoid * hex2bin(char *data_) {\n int len = strlen(data_) / 2;\n unsigned char *data = (unsigned char*)data_;\n // never tested with lowercase letters!\n unsigned char *result = malloc(sizeof(char) * len + 1);\n int foo, bar;\n result[len] = 0;\n for (len-- ; len >= 0 ; len--) {\n foo = data[len*2];\n if (foo < 0x41) {\n // is a digit\n bar = foo - 0x30;\n } else if (foo < 0x61) {\n // is a uppercase letter\n bar = foo - 0x37;\n } else {\n // is a lowercase letter\n bar = foo - 0x57;\n }\n result[len] = bar << 4;\n \n foo = data[len*2 + 1];\n if (foo < 0x41) {\n // is a digit\n bar = foo - 0x30;\n } else if (foo < 0x61) {\n // is a uppercase letter\n bar = foo - 0x37;\n } else {\n // is a lowercase letter\n bar = foo - 0x57;\n }\n result[len] += bar;\n }\n return (void*)result;\n}\n\n// C does not support binary constants, but gcc >= 4.3 does.\n// Because we can't really expect people to update their compilers in four\n// years (4.3 is from march 2008), the following defines will substitute\n// the three values used by base64Encode with their decimal equivalent.\n#define B_11 3\n#define B_1111 15\n#define B_111111 63\nchar * base64Encode(void *data_, int len) {\n unsigned char *data = data_;\n static const char *b64 = \"\\\nABCDEFGHIJKLMNOPQRSTUVWXYZ\\\nabcdefghijklmnopqrstuvwxyz\\\n0123456789+/\";\n int blocks = (len + 2) / 3;\n int newlen = blocks * 4 + 1;\n char *result = malloc(newlen);\n char *resptr = result;\n int i;\n \n for (i = len / 3 ; i > 0 ; i--) {\n resptr[0] = b64[ data[0] >> 2 ];\n resptr[1] = b64[ (data[0] & B_11) << 4\n | data[1] >> 4 ];\n resptr[2] = b64[ (data[1] & B_1111) << 2\n | data[2] >> 6 ];\n resptr[3] = b64[ data[2] & B_111111 ];\n resptr += 4;\n data += 3;\n }\n \n if (len < blocks * 3 - 1) {\n resptr[0] = b64[ data[0] >> 2 ];\n resptr[1] = b64[ (data[0] & B_11) << 4 ];\n resptr[2] = '=';\n resptr[3] = '=';\n resptr += 4;\n } else if (len < blocks * 3) {\n resptr[0] = b64[ data[0] >> 2 ];\n resptr[1] = b64[ (data[0] & B_11) << 4\n | data[1] >> 4 ];\n resptr[2] = b64[ (data[1] & B_1111) << 2 ];\n resptr[3] = '=';\n resptr += 4;\n }\n \n *resptr = 0;\n return result;\n}\n\nvoid * base64Decode(char *text, int *outlen) {\n static const unsigned char b64dec[] = {\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //00\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //10\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 62, 0, 0, 0, 63, //20\n 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 0, 0, 0, 0, 0, 0, //30\n 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, //40\n 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 0, 0, 0, 0, 0, //50\n 0, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, //60\n 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 0, 0, 0, 0, 0, //70\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //80\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //90\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //a0\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //b0\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //c0\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //d0\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //e0\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 //f0\n };\n // this functions treats invalid characters as 'A'. deal with it :-P\n int inlen = (strlen(text) >> 2) << 2;\n int blocks = inlen >> 2;\n *outlen = blocks * 3 - (text[inlen-2] == '='\n ? 2 : (text[inlen-1] == '=' ? 1 : 0));\n char *result = malloc(blocks * 3);\n char *resptr = result;\n u_int8_t *text_ = (u_int8_t*)text;\n int i;\n \n for (i = 0 ; i < blocks ; i++) {\n resptr[0] = b64dec[text_[0]] << 2 | b64dec[text_[1]] >> 4;\n resptr[1] = b64dec[text_[1]] << 4 | b64dec[text_[2]] >> 2;\n resptr[2] = b64dec[text_[2]] << 6 | b64dec[text_[3]];\n \n text_ += 4;\n resptr += 3;\n }\n \n return (void*)result;\n}\n\nint isBase64(char *text) {\n static const char *b64 = \"\\\nABCDEFGHIJKLMNOPQRSTUVWXYZ\\\nabcdefghijklmnopqrstuvwxyz\\\n0123456789+/=\";\n return strlen(text) == strspn(text, b64);\n}\n\nchar * queryGetParam(char *query, char *name) {\n char *begin = index(query, '&');\n char *end;\n int nameLen = strlen(name);\n \n while (begin != NULL) {\n begin++;\n if (strncmp(begin, name, nameLen) == 0 && begin[nameLen] == '=') {\n begin += nameLen + 1;\n end = index(begin, '&');\n if (end == NULL)\n end = begin + strlen(begin);\n char *result = malloc(end - begin + 1);\n strncpy(result, begin, end - begin);\n result[end - begin] = 0;\n return result;\n }\n begin = index(begin, '&');\n }\n return NULL;\n}\n\nvoid quote(char *message) {\n char line[LINE_LENGTH + 1];\n line[0] = '>';\n line[1] = ' ';\n int index = 2;\n \n while (*message != 0) {\n if (*message < 0x20 || *message > 0x7E) {\n line[index++] = ' ';\n } else {\n line[index++] = *message;\n }\n if (index == LINE_LENGTH) {\n line[index++] = '\\n';\n fwrite(line, index, 1, stderr);\n line[0] = '>';\n line[1] = ' ';\n index = 2;\n }\n message++;\n }\n line[index++] = '\\n';\n if (index != 3) fwrite(line, index, 1, stderr);\n}\n\nvoid dumpQuerystring(char *query) {\n int length = strlen(query);\n char line[LINE_LENGTH + 1];\n int index = 0;\n \n if (*query == '&') {\n line[0] = '&';\n index++;\n query++;\n }\n \n for (; length > 0 ; length --) {\n if (*query == '&') {\n line[index] = '\\n';\n fwrite(line, index + 1, 1, stderr);\n index = 0;\n }\n line[index] = *query;\n \n index++;\n if (index == LINE_LENGTH) {\n line[index] = '\\n';\n fwrite(line, index + 1, 1, stderr);\n line[0] = ' ';\n index = 1;\n }\n query++;\n }\n line[index] = '\\n';\n if (index != LINE_LENGTH) fwrite(line, index + 1, 1, stderr);\n}\n\nvoid dumpHex(void *data_, int len) {\n unsigned char *data = data_;\n unsigned char *line = malloc(sizeof(char) * LINE_LENGTH + 1);\n char *hexrep_orig = bin2hex(data, len);\n char *hexrep = hexrep_orig;\n int i, pos;\n \n for (pos = 0 ; pos < len ; pos += 16) {\n for (i = 0 ; i < 8 ; i++) {\n line[i*3] = pos+i < len ? hexrep[i*2] : ' ';\n line[i*3+1] = pos+i < len ? hexrep[i*2+1] : ' ';\n line[i*3+2] = ' ';\n }\n line[24] = ' ';\n for (i = 8 ; i < 16 ; i++) {\n line[i*3+1] = pos+i < len ? hexrep[i*2] : ' ';\n line[i*3+2] = pos+i < len ? hexrep[i*2+1] : ' ';\n line[i*3+3] = ' ';\n }\n line[49] = ' ';\n line[50] = '|';\n for (i = 0 ; i < 16 ; i++) {\n if (data[pos+i] >= 0x20 && data[pos+i] < 0x7f) {\n line[51+i] = pos+i < len ? data[pos+i] : ' ';\n } else {\n line[51+i] = pos+i < len ? '.' : ' ';\n }\n }\n line[67] = '|';\n \n line[68] = 0;\n fprintf(stderr, \"%08x %s\\n\", pos, line);\n hexrep += 32;\n }\n fprintf(stderr, \"%08x\\n\", len);\n free(line);\n free(hexrep_orig);\n}\n\n/* special case length=0 means 'finished' */\nvoid showProgress(long long position, long long length) {\n static long long oldpos = 0;\n static unsigned int blocknum = 0;\n const char progressbar[41] = \"========================================\";\n const char *rotatingFoo = \"|/-\\\\\";\n\n if (logfilemode)\n return;\n if (length > 0) {\n if (oldpos > position) {\n oldpos = 0;\n blocknum = 0;\n }\n if (position - oldpos >= 2097152 || position == 0) {\n if (opts.guimode == 0) {\n fprintf(stderr, \"[%-40.*s] %3i%% %c\\r\", (int)(position*40/length),\n progressbar, (int)(position*100/length),\n rotatingFoo[blocknum++ % 4]);\n } else {\n fprintf(stderr, \"gui> %3i\\n\", (int)(position*100/length));\n }\n fflush(stderr);\n oldpos = position;\n }\n } else {\n if (opts.guimode == 0) {\n fputs(\"[========================================] 100% \\n\", stderr);\n } else {\n fputs(\"gui> Finished\\n\", stderr);\n }\n oldpos = 0;\n blocknum = 0;\n }\n}\n\n// ###################### special functions ####################\n\nchar * getHeader() {\n unsigned char *header = malloc(sizeof(char) * 513);\n if (fread(header, 512, 1, file) < 1 && !feof(file))\n PERROR(\"Error reading file\");\n if (feof(file))\n ERROR(\"Error: unexpected end of file\");\n MCRYPT blowfish;\n blowfish = mcrypt_module_open(\"blowfish-compat\", NULL, \"ecb\", NULL);\n unsigned char hardKey[] = {\n 0xEF, 0x3A, 0xB2, 0x9C, 0xD1, 0x9F, 0x0C, 0xAC,\n 0x57, 0x59, 0xC7, 0xAB, 0xD1, 0x2C, 0xC9, 0x2B,\n 0xA3, 0xFE, 0x0A, 0xFE, 0xBF, 0x96, 0x0D, 0x63,\n 0xFE, 0xBD, 0x0F, 0x45};\n mcrypt_generic_init(blowfish, hardKey, 28, NULL);\n mdecrypt_generic(blowfish, header, 512);\n mcrypt_generic_deinit(blowfish);\n mcrypt_module_close(blowfish);\n header[512] = 0;\n \n char *padding = strstr((char*)header, \"&PD=\");\n if (padding == NULL)\n ERROR(\"Corrupted header: could not find padding\");\n *padding = 0;\n \n if (opts.verbosity >= VERB_DEBUG) {\n fputs(\"\\nDumping decrypted header:\\n\", stderr);\n dumpQuerystring((char*)header);\n fputs(\"\\n\", stderr);\n }\n return (char*)header;\n}\n\nvoid * generateBigkey(char *date) {\n char *mailhash = bin2hex(MD5(\n (unsigned char*)email, strlen(email), NULL), 16);\n char *passhash = bin2hex(MD5(\n (unsigned char*)password, strlen(password), NULL), 16);\n char *bigkey_hex = malloc(57 * sizeof(char));\n char *ptr = bigkey_hex;\n \n strncpy(ptr, mailhash, 13);\n ptr += 13;\n \n strncpy(ptr, date, 4);\n date += 4;\n ptr += 4;\n \n strncpy(ptr, passhash, 11);\n ptr += 11;\n \n strncpy(ptr, date, 2);\n date += 2;\n ptr += 2;\n \n strncpy(ptr, mailhash + 21, 11);\n ptr += 11;\n \n strncpy(ptr, date, 2);\n ptr += 2;\n \n strncpy(ptr, passhash + 19, 13);\n ptr += 13;\n \n *ptr = 0;\n \n if (opts.verbosity >= VERB_DEBUG) {\n fprintf(stderr, \"\\nGenerated BigKey: %s\\n\\n\", bigkey_hex);\n }\n \n void *res = hex2bin(bigkey_hex);\n \n free(bigkey_hex);\n free(mailhash);\n free(passhash);\n return res;\n}\n\nchar * generateRequest(void *bigkey, char *date) {\n char *headerFN = queryGetParam(header, \"FN\");\n char *thatohthing = queryGetParam(header, \"OH\");\n MCRYPT blowfish = mcrypt_module_open(\"blowfish-compat\", NULL, \"cbc\", NULL);\n char *iv = malloc(mcrypt_enc_get_iv_size(blowfish));\n char *code = malloc(513);\n char *dump = malloc(513);\n char *result = malloc(1024); // base64-encoded code is 680 bytes\n \n memset(iv, 0x42, mcrypt_enc_get_iv_size(blowfish));\n memset(dump, 'd', 512);\n dump[512] = 0;\n \n snprintf(code, 513, \"FOOOOBAR\\\n&OS=01677e4c0ae5468b9b8b823487f14524\\\n&M=01677e4c0ae5468b9b8b823487f14524\\\n&LN=DE\\\n&VN=1.4.1132\\\n&IR=TRUE\\\n&IK=aFzW1tL7nP9vXd8yUfB5kLoSyATQ\\\n&FN=%s\\\n&OH=%s\\\n&A=%s\\\n&P=%s\\\n&D=%s\", headerFN, thatohthing, email, password, dump);\n \n if (opts.verbosity >= VERB_DEBUG) {\n fputs(\"\\nGenerated request-'code':\\n\", stderr);\n dumpQuerystring(code);\n fputs(\"\\n\", stderr);\n }\n \n mcrypt_generic_init(blowfish, bigkey, 28, iv);\n mcrypt_generic(blowfish, code, 512);\n mcrypt_generic_deinit(blowfish);\n mcrypt_module_close(blowfish);\n \n if (opts.verbosity >= VERB_DEBUG) {\n fputs(\"\\nEncrypted request-'code':\\n\", stderr);\n dumpHex(code, 512);\n fputs(\"\\n\", stderr);\n }\n \n snprintf(result, 1024, \"http://87.236.198.182/quelle_neu1.php\\\n?code=%s\\\n&AA=%s\\\n&ZZ=%s\", base64Encode(code, 512), email, date);\n \n if (opts.verbosity >= VERB_DEBUG) {\n fprintf(stderr, \"\\nRequest:\\n%s\\n\\n\", result);\n }\n \n free(code);\n free(dump);\n free(iv);\n free(headerFN);\n free(thatohthing);\n return result;\n}\n\nstruct MemoryStruct * contactServer(char *request) {\n // http://curl.haxx.se/libcurl/c/getinmemory.html\n CURL *curl_handle;\n char errorstr[CURL_ERROR_SIZE];\n \n struct MemoryStruct *chunk = malloc(sizeof(struct MemoryStruct));\n chunk->memory=NULL; /* we expect realloc(NULL, size) to work */ \n chunk->size = 0; /* no data at this point */ \n \n curl_global_init(CURL_GLOBAL_ALL);\n \n /* init the curl session */ \n curl_handle = curl_easy_init();\n \n /* specify URL to get */ \n curl_easy_setopt(curl_handle, CURLOPT_URL, request);\n \n /* send all data to this function */ \n curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);\n \n /* we pass our 'chunk' struct to the callback function */ \n curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, (void *)chunk);\n \n /* imitate the original OTR client */ \n curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, \"Linux-OTR-Decoder/0.4.592\");\n curl_easy_setopt(curl_handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);\n \n /* set verbosity and error message buffer */\n if (opts.verbosity >= VERB_DEBUG)\n curl_easy_setopt(curl_handle, CURLOPT_VERBOSE, 1);\n curl_easy_setopt(curl_handle, CURLOPT_ERRORBUFFER, errorstr);\n \n /* get it! */ \n if (curl_easy_perform(curl_handle) != 0)\n ERROR(\"cURL error: %s\", errorstr);\n \n /* cleanup curl stuff */ \n curl_easy_cleanup(curl_handle);\n \n /*\n * Now, our chunk.memory points to a memory block that is chunk.size\n * bytes big and contains the remote file.\n *\n * Do something nice with it!\n *\n * You should be aware of the fact that at this point we might have an\n * allocated data block, and nothing has yet deallocated that data. So when\n * you're done with it, you should free() it as a nice application.\n */ \n \n /* we're done with libcurl, so clean it up */ \n curl_global_cleanup();\n \n // null-terminate response\n chunk->memory = realloc(chunk->memory, chunk->size + 1);\n if (chunk->memory == NULL) PERROR(\"realloc\");\n chunk->memory[chunk->size] = 0;\n return chunk;\n}\n\nchar * decryptResponse(char *response, int length, void *bigkey) {\n MCRYPT blowfish = mcrypt_module_open(\"blowfish-compat\", NULL, \"cbc\", NULL);\n \n if (length < mcrypt_enc_get_iv_size(blowfish) || length < 8)\n return NULL;\n length -= 8;\n \n char *result = malloc(length);\n memcpy(result, response+8, length);\n \n mcrypt_generic_init(blowfish, bigkey, 28, response);\n mdecrypt_generic(blowfish, result, length);\n mcrypt_generic_deinit(blowfish);\n mcrypt_module_close(blowfish);\n \n char *padding = strstr(result, \"&D=\");\n if (padding == NULL)\n ERROR(\"Corrupted response: could not find padding\");\n *padding = 0;\n \n if (opts.verbosity >= VERB_DEBUG) {\n fputs(\"\\nDecrypted response:\\n\", stderr);\n dumpQuerystring(result);\n fputs(\"\\n\", stderr);\n }\n \n return result;\n}\n\nvoid keycache_open() {\n char *home, *keyfilename;\n \n if ((home = getenv(\"HOME\")) == NULL) return;\n keyfilename = malloc(strlen(home) + 20);\n strcpy(keyfilename, home);\n strcat(keyfilename, \"/.otrkey_cache\");\n keyfile = fopen(keyfilename, \"a+\");\n free(keyfilename);\n}\n\nchar *keycache_get(const char *fh) {\n char *cachephrase, *cachefh;\n static char line[512];\n \n if (fh == NULL || keyfile == NULL) return NULL;\n rewind(keyfile);\n while (fgets(line, sizeof(line), keyfile) != NULL) {\n cachefh = strtok(line, \" \\t\\r\\n\");\n cachephrase = strtok(NULL, \" \\t\\r\\n\");\n if (cachephrase == NULL || cachefh == NULL) continue;\n if (strcmp(cachefh, fh) == 0) return cachephrase;\n }\n if (!feof(keyfile)) PERROR(\"fgets\");\n return NULL;\n}\n\nvoid keycache_put(const char *fh, const char *keyphrase) {\n char *cachephrase, *fn;\n \n if (fh == NULL || keyfile == NULL) return;\n if ((cachephrase = keycache_get(fh)) != NULL) {\n if (strcmp(keyphrase, cachephrase) != 0)\n fputs(\"warning: differing keyphrase was found in cache file!\\n\", stderr);\n else\n fputs(\"info: keyphrase was already in cache\\n\", stderr);\n return;\n }\n fn = queryGetParam(header, \"FN\");\n if (fprintf(keyfile, \"%s\\t%s\\t# %s\\n\", fh, keyphrase, fn) < 0)\n PERROR(\"fprintf\");\n fflush(keyfile);\n fputs(\"info: saved keyphrase to ~/.otrkey_cache\\n\", stderr);\n}\n\nvoid fetchKeyphrase() {\n struct termios ios0, ios1;\n time_t time_ = time(NULL);\n char *date = malloc(9);\n strftime(date, 9, \"%Y%m%d\", gmtime(&time_));\n \n if (info) {\n free(info);\n info = NULL;\n }\n \n if (opts.email == NULL) {\n if (!interactive) ERROR(\"Email address not specified\");\n opts.email = malloc(51);\n fputs(\"Enter your eMail-address: \", stderr);\n if (fscanf(ttyfile, \"%50s\", opts.email) < 1)\n ERROR(\"Email invalid\");\n while (fgetc(ttyfile) != '\\n');\n }\n email = strdup(opts.email);\n\n if (opts.password == NULL) {\n if (!interactive) ERROR(\"Password not specified\");\n opts.password = malloc(51);\n fputs(\"Enter your password: \", stderr);\n tcgetattr(fileno(ttyfile), &ios0);\n ios1 = ios0;\n ios1.c_lflag &= ~ECHO;\n tcsetattr(fileno(ttyfile), TCSAFLUSH, &ios1);\n if (fscanf(ttyfile, \"%50s\", opts.password) < 1) {\n tcsetattr(0, TCSAFLUSH, &ios0);\n ERROR(\"Password invalid\");\n }\n tcsetattr(fileno(ttyfile), TCSAFLUSH, &ios0);\n while (fgetc(ttyfile) != '\\n');\n fputc('\\n', stderr);\n }\n password = strdup(opts.password);\n \n char *bigkey = generateBigkey(date);\n char *request = generateRequest(bigkey, date);\n free(email);\n free(password);\n \n fputs(\"Trying to contact server...\\n\", stderr);\n struct MemoryStruct *response = contactServer(request);\n\n if (response->size == 0 || response->memory == NULL) {\n ERROR(\"Server sent an empty response, exiting\");\n }\n fputs(\"Server responded.\\n\", stderr);\n \n // skip initial whitespace\n char *message = response->memory;\n message += strspn(message, \" \\t\\n\");\n \n if (isBase64(message) == 0) {\n if (memcmp(message,\"MessageToBePrintedInDecoder\",27) ==0) {\n fputs(\"Server sent us this sweet message:\\n\", stderr);\n quote(message + 27);\n } else {\n fputs(\"Server sent us this ugly crap:\\n\", stderr);\n dumpHex(response->memory, response->size);\n }\n ERROR(\"Server response is unuseable, exiting\");\n }\n \n int info_len;\n char *info_crypted = base64Decode(message, &info_len);\n \n if (info_len % 8 != 0) {\n fputs(\"Length of response must be a multiple of 8.\", stderr);\n dumpHex(info_crypted, info_len);\n ERROR(\"Server response is unuseable, exiting\");\n }\n \n info = decryptResponse(info_crypted, info_len, bigkey);\n \n keyphrase = queryGetParam(info, \"HP\");\n if (keyphrase == NULL)\n ERROR(\"Response lacks keyphrase\");\n \n if (strlen(keyphrase) != 56)\n ERROR(\"Keyphrase has wrong length\");\n \n fprintf(stderr, \"Keyphrase: %s\\n\", keyphrase);\n keycache_put(queryGetParam(header, \"FH\"), keyphrase);\n \n free(date);\n free(bigkey);\n free(request);\n free(response->memory);\n free(response);\n free(info_crypted);\n}\n\nvoid openFile() {\n if (strcmp(\"-\", filename) == 0)\n file = stdin;\n else\n file = fopen(filename, \"rb\");\n \n if (file == NULL)\n PERROR(\"Error opening file\");\n \n char magic[11] = { 0 };\n if (fread(magic, 10, 1, file) < 1 && !feof(file))\n PERROR(\"Error reading file\");\n if (feof(file))\n ERROR(\"Error: unexpected end of file\");\n if (strcmp(magic, \"OTRKEYFILE\") != 0)\n ERROR(\"Wrong file format\");\n \n header = getHeader();\n}\n\ntypedef struct verifyFile_ctx {\n MD5_CTX ctx;\n char hash1[16];\n int input;\n} vfy_t;\n\nvoid verifyFile_init(vfy_t *vfy, int input) {\n char *hash_hex, *hash;\n int i;\n \n memset(vfy, 0, sizeof(*vfy));\n vfy->input = input;\n \n /* get MD5 sum from 'OH' or 'FH' header field */\n hash_hex = queryGetParam(header, vfy->input?\"OH\":\"FH\");\n if (hash_hex == NULL || strlen(hash_hex) != 48)\n ERROR(\"Missing hash in file header / unexpected format\");\n for (i=1; i<16; ++i) {\n hash_hex[2*i] = hash_hex[3*i];\n hash_hex[2*i+1] = hash_hex[3*i+1];\n }\n hash_hex[32] = 0;\n if (opts.verbosity >= VERB_DEBUG)\n fprintf(stderr, \"Checking %s against MD5 sum: %s\\n\",\n vfy->input?\"input\":\"output\", hash_hex);\n hash = hex2bin(hash_hex);\n memcpy(vfy->hash1, hash, 16);\n \n /* calculate MD5 sum of file (without header) */\n memset(&vfy->ctx, 0, sizeof(vfy->ctx));\n MD5_Init(&vfy->ctx);\n \n free(hash_hex);\n free(hash);\n}\n\nvoid verifyFile_data(vfy_t *vfy, char *buffer, size_t len) {\n MD5_Update(&vfy->ctx, buffer, len);\n}\n\nvoid verifyFile_final(vfy_t *vfy) {\n unsigned char md5[16];\n \n MD5_Final(md5, &vfy->ctx);\n if (memcmp(vfy->hash1, md5, 16) != 0) {\n if (vfy->input)\n ERROR(\"Input file had errors. Output may or may not be usable.\");\n else\n ERROR(\"Output verification failed. Wrong key?\");\n }\n}\n\nvoid verifyOnly() {\n vfy_t vfy;\n size_t n;\n static char buffer[65536];\n unsigned long long length;\n unsigned long long position;\n\n length = atoll(queryGetParam(header, \"SZ\")) - 522;\n fputs(\"Verifying otrkey...\\n\", stderr);\n verifyFile_init(&vfy, 1);\n for (position = 0; position < length; position += n) {\n showProgress(position, length);\n n = fread(buffer, 1, MIN(length - position, sizeof(buffer)), file);\n if (n == 0 || ferror(file)) break;\n verifyFile_data(&vfy, buffer, n);\n }\n if (position < length) {\n if (!feof(file)) PERROR(\"fread\");\n if (!logfilemode) fputc('\\n', stderr);\n fputs(\"file is too short\\n\", stderr);\n }\n else\n showProgress(1, 0);\n\n if (fread(buffer, 1, 1, file) > 0)\n fputs(\"file contains trailing garbage\\n\", stderr);\n else if (!feof(file))\n PERROR(\"fread\");\n verifyFile_final(&vfy);\n fputs(\"file is OK\\n\", stderr);\n}\n\nvoid decryptFile() {\n int fd;\n char *headerFN;\n struct stat st;\n FILE *destfile;\n\n if (opts.destfile == NULL) {\n headerFN = queryGetParam(header, \"FN\");\n if (opts.destdir != NULL) {\n destfilename = malloc(strlen(opts.destdir) + strlen(headerFN) + 2);\n strcpy(destfilename, opts.destdir);\n strcat(destfilename, \"/\");\n strcat(destfilename, headerFN);\n free(headerFN);\n }\n else {\n destfilename = headerFN;\n }\n }\n else {\n destfilename = strdup(opts.destfile);\n }\n \n if (strcmp(destfilename, \"-\") == 0) {\n if (isatty(1)) ERROR(\"error: cowardly refusing to output to a terminal\");\n fd = 1;\n }\n else\n fd = open(destfilename, O_WRONLY|O_CREAT|O_EXCL, CREAT_MODE);\n if (fd < 0 && errno == EEXIST) {\n if (stat(destfilename, &st) != 0 || S_ISREG(st.st_mode)) {\n if (!interactive) ERROR(\"Destination file exists: %s\", destfilename);\n fprintf(stderr, \"Destination file exists: %s\\nType y to overwrite: \",\n destfilename);\n if (fgetc(ttyfile) != 'y') exit(EXIT_FAILURE);\n while (fgetc(ttyfile) != '\\n');\n fd = open(destfilename, O_WRONLY|O_TRUNC, 0);\n }\n else\n fd = open(destfilename, O_WRONLY, 0);\n }\n if (fd < 0)\n PERROR(\"Error opening destination file: %s\", destfilename);\n if ((destfile = fdopen(fd, \"wb\")) == NULL)\n PERROR(\"fdopen\");\n \n fputs(\"Decrypting and verifying...\\n\", stderr); // -----------------------\n \n void *key = hex2bin(keyphrase);\n MCRYPT blowfish = mcrypt_module_open(\"blowfish-compat\", NULL, \"ecb\", NULL);\n mcrypt_generic_init(blowfish, key, 28, NULL);\n \n unsigned long long length = atoll(queryGetParam(header, \"SZ\")) - 522;\n unsigned long long position = 0;\n size_t readsize;\n size_t writesize;\n static char buffer[65536];\n vfy_t vfy_in, vfy_out;\n \n verifyFile_init(&vfy_in, 1);\n verifyFile_init(&vfy_out, 0);\n \n while (position < length) {\n showProgress(position, length);\n\n if (length - position >= sizeof(buffer)) {\n readsize = fread(buffer, 1, sizeof(buffer), file);\n } else {\n readsize = fread(buffer, 1, length - position, file);\n }\n if (readsize <= 0) {\n if (feof(file))\n ERROR(\"Input file is too short\");\n PERROR(\"Error reading input file\");\n }\n \n verifyFile_data(&vfy_in, buffer, readsize);\n /* If the payload length is not a multiple of eight,\n * the last few bytes are stored unencrypted */\n mdecrypt_generic(blowfish, buffer, readsize - readsize % 8);\n verifyFile_data(&vfy_out, buffer, readsize);\n \n writesize = fwrite(buffer, 1, readsize, destfile);\n if (writesize != readsize)\n PERROR(\"Error writing to destination file\");\n \n position += writesize;\n }\n showProgress(1, 0);\n\n verifyFile_final(&vfy_in);\n verifyFile_final(&vfy_out);\n fputs(\"OK checksums from header match\\n\", stderr);\n \n mcrypt_generic_deinit(blowfish);\n mcrypt_module_close(blowfish);\n \n if (fclose(destfile) != 0)\n PERROR(\"Error closing destination file.\");\n\n if (opts.unlinkmode) {\n if (strcmp(filename, \"-\") != 0 &&\n stat(filename, &st) == 0 && S_ISREG(st.st_mode) &&\n strcmp(destfilename, \"-\") != 0 &&\n stat(destfilename, &st) == 0 && S_ISREG(st.st_mode)) {\n if (unlink(filename) != 0)\n PERROR(\"Cannot delete input file\");\n else\n fputs(\"info: input file has been deleted\\n\", stderr);\n }\n else {\n fputs(\"Warning: Not deleting input file (input or \"\n \"output is not a regular file)\\n\", stderr);\n }\n }\n \n free(key);\n free(destfilename);\n}\n\nvoid processFile() {\n int storeKeyphrase;\n switch (opts.action) {\n case ACTION_INFO:\n // TODO: output something nicer than just the querystring\n dumpQuerystring(header);\n break;\n case ACTION_FETCHKEY:\n fetchKeyphrase();\n break;\n case ACTION_DECRYPT:\n storeKeyphrase = 1;\n if (opts.keyphrase == NULL) {\n storeKeyphrase = 0;\n keyphrase = keycache_get(queryGetParam(header, \"FH\"));\n if (keyphrase)\n fprintf(stderr, \"Keyphrase from cache: %s\\n\", keyphrase);\n else\n fetchKeyphrase();\n }\n else {\n keyphrase = strdup(opts.keyphrase);\n }\n decryptFile();\n if (storeKeyphrase)\n keycache_put(queryGetParam(header, \"FH\"), keyphrase);\n break;\n case ACTION_VERIFY:\n verifyOnly();\n break;\n }\n}\n\nvoid usageError() {\n fputs(\"\\n\"\n \"Usage: otrtool [-h] [-v] [-i|-f|-x|-y] [-u]\\n\"\n \" [-k ] [-e ] [-p ]\\n\"\n \" [-D ] [-O ]\\n\"\n \" [ ... []]\\n\"\n \"\\n\"\n \"MODES OF OPERATION\\n\"\n \" -i | Display information about file (default action)\\n\"\n \" -f | Fetch keyphrase for file\\n\"\n \" -x | Decrypt file\\n\"\n \" -y | Verify only\\n\"\n \"\\n\"\n \"FREQUENTLY USED OPTIONS\\n\"\n \" -k | Do not fetch keyphrase, use this one\\n\"\n \" -D | Output folder\\n\"\n \" -O | Output file (overrides -D)\\n\"\n \" -u | Delete otrkey-files after successful decryption\\n\"\n \"\\n\"\n \"See otrtool(1) for further information\\n\", stderr);\n}\n\nint main(int argc, char *argv[]) {\n fputs(\"OTR-Tool, \" VERSION \"\\n\", stderr);\n\n int i;\n int opt;\n while ( (opt = getopt(argc, argv, \"hvgifxyk:e:p:D:O:u\")) != -1) {\n switch (opt) {\n case 'h':\n usageError();\n exit(EXIT_SUCCESS);\n break;\n case 'v':\n opts.verbosity = VERB_DEBUG;\n break;\n case 'g':\n opts.guimode = 1;\n interactive = 0;\n break;\n case 'i':\n opts.action = ACTION_INFO;\n break;\n case 'f':\n opts.action = ACTION_FETCHKEY;\n break;\n case 'x':\n opts.action = ACTION_DECRYPT;\n break;\n case 'y':\n opts.action = ACTION_VERIFY;\n break;\n case 'k':\n opts.keyphrase = optarg;\n break;\n case 'e':\n opts.email = strdup(optarg);\n memset(optarg, 'x', strlen(optarg));\n break;\n case 'p':\n opts.password = strdup(optarg);\n memset(optarg, 'x', strlen(optarg));\n break;\n case 'D':\n opts.destdir = optarg;\n break;\n case 'O':\n opts.destfile = optarg;\n break;\n case 'u':\n opts.unlinkmode = 1;\n break;\n default:\n usageError();\n exit(EXIT_FAILURE);\n }\n }\n if (opts.verbosity >= VERB_DEBUG) {\n fputs(\"command line: \", stderr);\n for (i = 0; i < argc; ++i) {\n fputs(argv[i], stderr);\n fputc((i == argc - 1) ? '\\n' : ' ', stderr);\n }\n }\n \n if (optind >= argc) {\n fprintf(stderr, \"Missing argument: otrkey-file\\n\");\n usageError();\n exit(EXIT_FAILURE);\n }\n if (argc > optind + 1) {\n if (opts.destfile != NULL && strcmp(opts.destfile, \"-\") == 0) {\n i = 0;\n }\n else for (i = optind; i < argc; i++) {\n if (strcmp(argv[i], \"-\") == 0)\n break;\n }\n if (i < argc)\n ERROR(\"Usage error: piping is not possible with multiple input files\");\n }\n\n if (!isatty(2)) {\n logfilemode = 1;\n interactive = 0;\n }\n if (interactive) {\n if (!isatty(0)) {\n ttyfile = fopen(\"/dev/tty\", \"r\");\n if (ttyfile == NULL) {\n if (opts.verbosity >= VERB_DEBUG) perror(\"open /dev/tty\");\n interactive = 0;\n }\n }\n else ttyfile = stdin;\n }\n\n if (opts.action == ACTION_DECRYPT || opts.action == ACTION_VERIFY) {\n errno = 0;\n nice(10);\n if (errno == 0 && opts.verbosity >= VERB_DEBUG)\n fputs(\"NICE was set to 10\\n\", stderr);\n\n // I am not sure if this really catches all errors\n // If this causes problems, just delete the ionice-stuff\n #ifdef __NR_ioprio_set\n if (syscall(__NR_ioprio_set, 1, getpid(), 7 | 3 << 13) == 0\n && opts.verbosity >= VERB_DEBUG)\n fputs(\"IONICE class was set to Idle\\n\", stderr);\n #endif\n }\n if (opts.action == ACTION_FETCHKEY || opts.action == ACTION_DECRYPT) {\n keycache_open();\n }\n\n for (i = optind; i < argc; i++) {\n filename = argv[i];\n if (argc > optind + 1)\n fprintf(stderr, \"\\n==> %s <==\\n\", filename);\n openFile();\n processFile();\n if (fclose(file) != 0)\n PERROR(\"Error closing file\");\n free(header);\n }\n \n exit(EXIT_SUCCESS);\n}\n"}, "files_after": {"src/main.c": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \n#include \"md5.h\"\n\n#include \n#include \n\n#define ERROR(...) \\\n ({fprintf(stderr, \"\\n\"); \\\n fprintf(stderr, __VA_ARGS__); \\\n fprintf(stderr, \"\\n\"); \\\n exit(EXIT_FAILURE); })\n\n#define PERROR(...) \\\n ({fprintf(stderr, \"\\n\"); \\\n fprintf(stderr, __VA_ARGS__); \\\n fprintf(stderr, \": \"); \\\n perror(NULL); \\\n exit(EXIT_FAILURE); })\n\n#define MIN(a,b) ((a)<(b)?(a):(b))\n\n#ifndef VERSION\n #define VERSION \"version unknown\"\n#endif\n\n#define LINE_LENGTH 80\n#define MAX_RESPONSE_LENGTH 1000\n#define CREAT_MODE S_IWUSR|S_IRUSR|S_IRGRP|S_IROTH\n\n#define VERB_INFO 1\n#define VERB_DEBUG 2\n\n#define ACTION_INFO 1\n#define ACTION_FETCHKEY 2\n#define ACTION_DECRYPT 3\n#define ACTION_VERIFY 4\n\n/* global options as supplied by the user via command-line etc. */\nstruct otrtool_options {\n int action;\n int verbosity;\n int guimode; // do not output \\r and stuff\n int unlinkmode;\n char *email;\n char *password;\n char *keyphrase;\n char *destdir;\n char *destfile;\n};\nstatic struct otrtool_options opts = {\n .action = ACTION_INFO,\n .verbosity = VERB_INFO,\n .guimode = 0,\n .unlinkmode = 0,\n .email = NULL,\n .password = NULL,\n .keyphrase = NULL,\n .destdir = NULL,\n .destfile = NULL,\n};\n\nstatic int interactive = 1; // ask questions instead of exiting\nstatic int logfilemode = 0; // do not output progress bar\n\nstatic char *email = NULL;\nstatic char *password = NULL;\nstatic char *keyphrase = NULL;\nstatic char *filename = NULL;\nstatic char *destfilename = NULL;\n\nstatic FILE *file = NULL;\nstatic FILE *keyfile = NULL;\nstatic FILE *ttyfile = NULL;\nstatic char *header = NULL;\nstatic char *info = NULL;\n\n// ######################## curl-stuff #######################\n\nstruct MemoryStruct {\n char *memory;\n size_t size;\n};\n\nstatic size_t WriteMemoryCallback(void *ptr, size_t size,\n size_t nmemb, void *data) {\n size_t realsize = size * nmemb;\n struct MemoryStruct *mem = (struct MemoryStruct *)data;\n char *newmem;\n \n // abort very long transfers\n if (mem->size + realsize > MAX_RESPONSE_LENGTH) {\n realsize = mem->size <= MAX_RESPONSE_LENGTH\n ? MAX_RESPONSE_LENGTH - mem->size\n : 0;\n }\n if (realsize < 1) return 0;\n \n // \"If realloc() fails the original block is left untouched\" (man 3 realloc)\n newmem = realloc(mem->memory, mem->size + realsize);\n if (newmem != NULL) {\n mem->memory = newmem;\n memcpy(&(mem->memory[mem->size]), ptr, realsize);\n mem->size += realsize;\n } else return 0;\n return realsize;\n}\n\n// ######################## generic functions ####################\n\nchar * bin2hex(void *data_, int len) {\n unsigned char *data = data_;\n unsigned char *result = malloc(sizeof(char) * len * 2 + 1);\n result[len * 2] = 0;\n int foo;\n for (len-- ; len >= 0 ; len--) {\n foo = data[len] % 16;\n result[len*2 + 1] = foo > 9 ? 0x37 + foo : 0x30 + foo;\n foo = data[len] >> 4;\n result[len*2] = foo > 9 ? 0x37 + foo : 0x30 + foo;\n }\n return (char*)result;\n}\n\nvoid * hex2bin(char *data_) {\n int len = strlen(data_) / 2;\n unsigned char *data = (unsigned char*)data_;\n // never tested with lowercase letters!\n unsigned char *result = malloc(sizeof(char) * len + 1);\n int foo, bar;\n result[len] = 0;\n for (len-- ; len >= 0 ; len--) {\n foo = data[len*2];\n if (foo < 0x41) {\n // is a digit\n bar = foo - 0x30;\n } else if (foo < 0x61) {\n // is a uppercase letter\n bar = foo - 0x37;\n } else {\n // is a lowercase letter\n bar = foo - 0x57;\n }\n result[len] = bar << 4;\n \n foo = data[len*2 + 1];\n if (foo < 0x41) {\n // is a digit\n bar = foo - 0x30;\n } else if (foo < 0x61) {\n // is a uppercase letter\n bar = foo - 0x37;\n } else {\n // is a lowercase letter\n bar = foo - 0x57;\n }\n result[len] += bar;\n }\n return (void*)result;\n}\n\n// C does not support binary constants, but gcc >= 4.3 does.\n// Because we can't really expect people to update their compilers in four\n// years (4.3 is from march 2008), the following defines will substitute\n// the three values used by base64Encode with their decimal equivalent.\n#define B_11 3\n#define B_1111 15\n#define B_111111 63\nchar * base64Encode(void *data_, int len) {\n unsigned char *data = data_;\n static const char *b64 = \"\\\nABCDEFGHIJKLMNOPQRSTUVWXYZ\\\nabcdefghijklmnopqrstuvwxyz\\\n0123456789+/\";\n int blocks = (len + 2) / 3;\n int newlen = blocks * 4 + 1;\n char *result = malloc(newlen);\n char *resptr = result;\n int i;\n \n for (i = len / 3 ; i > 0 ; i--) {\n resptr[0] = b64[ data[0] >> 2 ];\n resptr[1] = b64[ (data[0] & B_11) << 4\n | data[1] >> 4 ];\n resptr[2] = b64[ (data[1] & B_1111) << 2\n | data[2] >> 6 ];\n resptr[3] = b64[ data[2] & B_111111 ];\n resptr += 4;\n data += 3;\n }\n \n if (len < blocks * 3 - 1) {\n resptr[0] = b64[ data[0] >> 2 ];\n resptr[1] = b64[ (data[0] & B_11) << 4 ];\n resptr[2] = '=';\n resptr[3] = '=';\n resptr += 4;\n } else if (len < blocks * 3) {\n resptr[0] = b64[ data[0] >> 2 ];\n resptr[1] = b64[ (data[0] & B_11) << 4\n | data[1] >> 4 ];\n resptr[2] = b64[ (data[1] & B_1111) << 2 ];\n resptr[3] = '=';\n resptr += 4;\n }\n \n *resptr = 0;\n return result;\n}\n\nvoid * base64Decode(char *text, int *outlen) {\n static const unsigned char b64dec[] = {\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //00\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //10\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 62, 0, 0, 0, 63, //20\n 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 0, 0, 0, 0, 0, 0, //30\n 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, //40\n 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 0, 0, 0, 0, 0, //50\n 0, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, //60\n 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 0, 0, 0, 0, 0, //70\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //80\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //90\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //a0\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //b0\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //c0\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //d0\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //e0\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 //f0\n };\n // this functions treats invalid characters as 'A'. deal with it :-P\n int inlen = (strlen(text) >> 2) << 2;\n int blocks = inlen >> 2;\n *outlen = blocks * 3 - (text[inlen-2] == '='\n ? 2 : (text[inlen-1] == '=' ? 1 : 0));\n char *result = malloc(blocks * 3);\n char *resptr = result;\n u_int8_t *text_ = (u_int8_t*)text;\n int i;\n \n for (i = 0 ; i < blocks ; i++) {\n resptr[0] = b64dec[text_[0]] << 2 | b64dec[text_[1]] >> 4;\n resptr[1] = b64dec[text_[1]] << 4 | b64dec[text_[2]] >> 2;\n resptr[2] = b64dec[text_[2]] << 6 | b64dec[text_[3]];\n \n text_ += 4;\n resptr += 3;\n }\n \n return (void*)result;\n}\n\nint isBase64(char *text) {\n static const char *b64 = \"\\\nABCDEFGHIJKLMNOPQRSTUVWXYZ\\\nabcdefghijklmnopqrstuvwxyz\\\n0123456789+/=\";\n return strlen(text) == strspn(text, b64);\n}\n\nchar * queryGetParam(char *query, char *name) {\n char *begin = index(query, '&');\n char *end;\n int nameLen = strlen(name);\n \n while (begin != NULL) {\n begin++;\n if (strncmp(begin, name, nameLen) == 0 && begin[nameLen] == '=') {\n begin += nameLen + 1;\n end = index(begin, '&');\n if (end == NULL)\n end = begin + strlen(begin);\n char *result = malloc(end - begin + 1);\n strncpy(result, begin, end - begin);\n result[end - begin] = 0;\n return result;\n }\n begin = index(begin, '&');\n }\n return NULL;\n}\n\nvoid quote(char *message) {\n char line[LINE_LENGTH + 1];\n line[0] = '>';\n line[1] = ' ';\n int index = 2;\n \n while (*message != 0) {\n if (*message < 0x20 || *message > 0x7E) {\n line[index++] = ' ';\n } else {\n line[index++] = *message;\n }\n if (index == LINE_LENGTH) {\n line[index++] = '\\n';\n fwrite(line, index, 1, stderr);\n line[0] = '>';\n line[1] = ' ';\n index = 2;\n }\n message++;\n }\n line[index++] = '\\n';\n if (index != 3) fwrite(line, index, 1, stderr);\n}\n\nvoid dumpQuerystring(char *query) {\n int length = strlen(query);\n char line[LINE_LENGTH + 1];\n int index = 0;\n \n if (*query == '&') {\n line[0] = '&';\n index++;\n query++;\n }\n \n for (; length > 0 ; length --) {\n if (*query == '&') {\n line[index] = '\\n';\n fwrite(line, index + 1, 1, stderr);\n index = 0;\n }\n line[index] = *query;\n \n index++;\n if (index == LINE_LENGTH) {\n line[index] = '\\n';\n fwrite(line, index + 1, 1, stderr);\n line[0] = ' ';\n index = 1;\n }\n query++;\n }\n line[index] = '\\n';\n if (index != LINE_LENGTH) fwrite(line, index + 1, 1, stderr);\n}\n\nvoid dumpHex(void *data_, int len) {\n unsigned char *data = data_;\n unsigned char *line = malloc(sizeof(char) * LINE_LENGTH + 1);\n char *hexrep_orig = bin2hex(data, len);\n char *hexrep = hexrep_orig;\n int i, pos;\n \n for (pos = 0 ; pos < len ; pos += 16) {\n for (i = 0 ; i < 8 ; i++) {\n line[i*3] = pos+i < len ? hexrep[i*2] : ' ';\n line[i*3+1] = pos+i < len ? hexrep[i*2+1] : ' ';\n line[i*3+2] = ' ';\n }\n line[24] = ' ';\n for (i = 8 ; i < 16 ; i++) {\n line[i*3+1] = pos+i < len ? hexrep[i*2] : ' ';\n line[i*3+2] = pos+i < len ? hexrep[i*2+1] : ' ';\n line[i*3+3] = ' ';\n }\n line[49] = ' ';\n line[50] = '|';\n for (i = 0 ; i < 16 ; i++) {\n if (data[pos+i] >= 0x20 && data[pos+i] < 0x7f) {\n line[51+i] = pos+i < len ? data[pos+i] : ' ';\n } else {\n line[51+i] = pos+i < len ? '.' : ' ';\n }\n }\n line[67] = '|';\n \n line[68] = 0;\n fprintf(stderr, \"%08x %s\\n\", pos, line);\n hexrep += 32;\n }\n fprintf(stderr, \"%08x\\n\", len);\n free(line);\n free(hexrep_orig);\n}\n\n/* special case length=0 means 'finished' */\nvoid showProgress(long long position, long long length) {\n static long long oldpos = 0;\n static unsigned int blocknum = 0;\n const char progressbar[41] = \"========================================\";\n const char *rotatingFoo = \"|/-\\\\\";\n\n if (logfilemode)\n return;\n if (length > 0) {\n if (oldpos > position) {\n oldpos = 0;\n blocknum = 0;\n }\n if (position - oldpos >= 2097152 || position == 0) {\n if (opts.guimode == 0) {\n fprintf(stderr, \"[%-40.*s] %3i%% %c\\r\", (int)(position*40/length),\n progressbar, (int)(position*100/length),\n rotatingFoo[blocknum++ % 4]);\n } else {\n fprintf(stderr, \"gui> %3i\\n\", (int)(position*100/length));\n }\n fflush(stderr);\n oldpos = position;\n }\n } else {\n if (opts.guimode == 0) {\n fputs(\"[========================================] 100% \\n\", stderr);\n } else {\n fputs(\"gui> Finished\\n\", stderr);\n }\n oldpos = 0;\n blocknum = 0;\n }\n}\n\n// ###################### special functions ####################\n\nchar * getHeader() {\n unsigned char *header = malloc(sizeof(char) * 513);\n if (fread(header, 512, 1, file) < 1 && !feof(file))\n PERROR(\"Error reading file\");\n if (feof(file))\n ERROR(\"Error: unexpected end of file\");\n MCRYPT blowfish;\n blowfish = mcrypt_module_open(\"blowfish-compat\", NULL, \"ecb\", NULL);\n unsigned char hardKey[] = {\n 0xEF, 0x3A, 0xB2, 0x9C, 0xD1, 0x9F, 0x0C, 0xAC,\n 0x57, 0x59, 0xC7, 0xAB, 0xD1, 0x2C, 0xC9, 0x2B,\n 0xA3, 0xFE, 0x0A, 0xFE, 0xBF, 0x96, 0x0D, 0x63,\n 0xFE, 0xBD, 0x0F, 0x45};\n mcrypt_generic_init(blowfish, hardKey, 28, NULL);\n mdecrypt_generic(blowfish, header, 512);\n mcrypt_generic_deinit(blowfish);\n mcrypt_module_close(blowfish);\n header[512] = 0;\n \n char *padding = strstr((char*)header, \"&PD=\");\n if (padding == NULL)\n ERROR(\"Corrupted header: could not find padding\");\n *padding = 0;\n \n if (opts.verbosity >= VERB_DEBUG) {\n fputs(\"\\nDumping decrypted header:\\n\", stderr);\n dumpQuerystring((char*)header);\n fputs(\"\\n\", stderr);\n }\n return (char*)header;\n}\n\nvoid * generateBigkey(char *date) {\n char *mailhash = bin2hex(MD5(\n (unsigned char*)email, strlen(email), NULL), 16);\n char *passhash = bin2hex(MD5(\n (unsigned char*)password, strlen(password), NULL), 16);\n char *bigkey_hex = malloc(57 * sizeof(char));\n char *ptr = bigkey_hex;\n \n strncpy(ptr, mailhash, 13);\n ptr += 13;\n \n strncpy(ptr, date, 4);\n date += 4;\n ptr += 4;\n \n strncpy(ptr, passhash, 11);\n ptr += 11;\n \n strncpy(ptr, date, 2);\n date += 2;\n ptr += 2;\n \n strncpy(ptr, mailhash + 21, 11);\n ptr += 11;\n \n strncpy(ptr, date, 2);\n ptr += 2;\n \n strncpy(ptr, passhash + 19, 13);\n ptr += 13;\n \n *ptr = 0;\n \n if (opts.verbosity >= VERB_DEBUG) {\n fprintf(stderr, \"\\nGenerated BigKey: %s\\n\\n\", bigkey_hex);\n }\n \n void *res = hex2bin(bigkey_hex);\n \n free(bigkey_hex);\n free(mailhash);\n free(passhash);\n return res;\n}\n\nchar * generateRequest(void *bigkey, char *date) {\n char *headerFN = queryGetParam(header, \"FN\");\n char *thatohthing = queryGetParam(header, \"OH\");\n MCRYPT blowfish = mcrypt_module_open(\"blowfish-compat\", NULL, \"cbc\", NULL);\n char *iv = malloc(mcrypt_enc_get_iv_size(blowfish));\n char *code = malloc(513);\n char *dump = malloc(513);\n char *result = malloc(1024); // base64-encoded code is 680 bytes\n \n memset(iv, 0x42, mcrypt_enc_get_iv_size(blowfish));\n memset(dump, 'd', 512);\n dump[512] = 0;\n \n snprintf(code, 513, \"FOOOOBAR\\\n&OS=01677e4c0ae5468b9b8b823487f14524\\\n&M=01677e4c0ae5468b9b8b823487f14524\\\n&LN=DE\\\n&VN=1.4.1132\\\n&IR=TRUE\\\n&IK=aFzW1tL7nP9vXd8yUfB5kLoSyATQ\\\n&FN=%s\\\n&OH=%s\\\n&A=%s\\\n&P=%s\\\n&D=%s\", headerFN, thatohthing, email, password, dump);\n \n if (opts.verbosity >= VERB_DEBUG) {\n fputs(\"\\nGenerated request-'code':\\n\", stderr);\n dumpQuerystring(code);\n fputs(\"\\n\", stderr);\n }\n \n mcrypt_generic_init(blowfish, bigkey, 28, iv);\n mcrypt_generic(blowfish, code, 512);\n mcrypt_generic_deinit(blowfish);\n mcrypt_module_close(blowfish);\n \n if (opts.verbosity >= VERB_DEBUG) {\n fputs(\"\\nEncrypted request-'code':\\n\", stderr);\n dumpHex(code, 512);\n fputs(\"\\n\", stderr);\n }\n \n snprintf(result, 1024, \"http://87.236.198.182/quelle_neu1.php\\\n?code=%s\\\n&AA=%s\\\n&ZZ=%s\", base64Encode(code, 512), email, date);\n \n if (opts.verbosity >= VERB_DEBUG) {\n fprintf(stderr, \"\\nRequest:\\n%s\\n\\n\", result);\n }\n \n free(code);\n free(dump);\n free(iv);\n free(headerFN);\n free(thatohthing);\n return result;\n}\n\nstruct MemoryStruct * contactServer(char *request) {\n // http://curl.haxx.se/libcurl/c/getinmemory.html\n CURL *curl_handle;\n char errorstr[CURL_ERROR_SIZE];\n \n struct MemoryStruct *chunk = malloc(sizeof(struct MemoryStruct));\n chunk->memory=NULL; /* we expect realloc(NULL, size) to work */ \n chunk->size = 0; /* no data at this point */ \n \n curl_global_init(CURL_GLOBAL_ALL);\n \n /* init the curl session */ \n curl_handle = curl_easy_init();\n \n /* specify URL to get */ \n curl_easy_setopt(curl_handle, CURLOPT_URL, request);\n \n /* send all data to this function */ \n curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);\n \n /* we pass our 'chunk' struct to the callback function */ \n curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, (void *)chunk);\n \n /* imitate the original OTR client */ \n curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, \"Linux-OTR-Decoder/0.4.592\");\n curl_easy_setopt(curl_handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);\n \n /* set verbosity and error message buffer */\n if (opts.verbosity >= VERB_DEBUG)\n curl_easy_setopt(curl_handle, CURLOPT_VERBOSE, 1);\n curl_easy_setopt(curl_handle, CURLOPT_ERRORBUFFER, errorstr);\n \n /* get it! */ \n if (curl_easy_perform(curl_handle) != 0)\n ERROR(\"cURL error: %s\", errorstr);\n \n /* cleanup curl stuff */ \n curl_easy_cleanup(curl_handle);\n \n /*\n * Now, our chunk.memory points to a memory block that is chunk.size\n * bytes big and contains the remote file.\n *\n * Do something nice with it!\n *\n * You should be aware of the fact that at this point we might have an\n * allocated data block, and nothing has yet deallocated that data. So when\n * you're done with it, you should free() it as a nice application.\n */ \n \n /* we're done with libcurl, so clean it up */ \n curl_global_cleanup();\n \n // null-terminate response\n chunk->memory = realloc(chunk->memory, chunk->size + 1);\n if (chunk->memory == NULL) PERROR(\"realloc\");\n chunk->memory[chunk->size] = 0;\n return chunk;\n}\n\nchar * decryptResponse(char *response, int length, void *bigkey) {\n MCRYPT blowfish = mcrypt_module_open(\"blowfish-compat\", NULL, \"cbc\", NULL);\n \n if (length < mcrypt_enc_get_iv_size(blowfish) || length < 8)\n return NULL;\n length -= 8;\n \n char *result = malloc(length);\n memcpy(result, response+8, length);\n \n mcrypt_generic_init(blowfish, bigkey, 28, response);\n mdecrypt_generic(blowfish, result, length);\n mcrypt_generic_deinit(blowfish);\n mcrypt_module_close(blowfish);\n \n char *padding = strstr(result, \"&D=\");\n if (padding == NULL)\n ERROR(\"Corrupted response: could not find padding\");\n *padding = 0;\n \n if (opts.verbosity >= VERB_DEBUG) {\n fputs(\"\\nDecrypted response:\\n\", stderr);\n dumpQuerystring(result);\n fputs(\"\\n\", stderr);\n }\n \n return result;\n}\n\nvoid keycache_open() {\n char *home, *keyfilename;\n \n if ((home = getenv(\"HOME\")) == NULL) return;\n keyfilename = malloc(strlen(home) + 20);\n strcpy(keyfilename, home);\n strcat(keyfilename, \"/.otrkey_cache\");\n keyfile = fopen(keyfilename, \"a+\");\n free(keyfilename);\n}\n\nchar *keycache_get(const char *fh) {\n char *cachephrase, *cachefh;\n static char line[512];\n \n if (fh == NULL || keyfile == NULL) return NULL;\n rewind(keyfile);\n while (fgets(line, sizeof(line), keyfile) != NULL) {\n cachefh = strtok(line, \" \\t\\r\\n\");\n cachephrase = strtok(NULL, \" \\t\\r\\n\");\n if (cachephrase == NULL || cachefh == NULL) continue;\n if (strcmp(cachefh, fh) == 0) return cachephrase;\n }\n if (!feof(keyfile)) PERROR(\"fgets\");\n return NULL;\n}\n\nvoid keycache_put(const char *fh, const char *keyphrase) {\n char *cachephrase, *fn;\n \n if (fh == NULL || keyfile == NULL) return;\n if ((cachephrase = keycache_get(fh)) != NULL) {\n if (strcmp(keyphrase, cachephrase) != 0)\n fputs(\"warning: differing keyphrase was found in cache file!\\n\", stderr);\n else\n fputs(\"info: keyphrase was already in cache\\n\", stderr);\n return;\n }\n fn = queryGetParam(header, \"FN\");\n if (fprintf(keyfile, \"%s\\t%s\\t# %s\\n\", fh, keyphrase, fn) < 0)\n PERROR(\"fprintf\");\n fflush(keyfile);\n fputs(\"info: saved keyphrase to ~/.otrkey_cache\\n\", stderr);\n}\n\nvoid fetchKeyphrase() {\n struct termios ios0, ios1;\n time_t time_ = time(NULL);\n char *date = malloc(9);\n strftime(date, 9, \"%Y%m%d\", gmtime(&time_));\n \n if (info) {\n free(info);\n info = NULL;\n }\n \n if (opts.email == NULL) {\n if (!interactive) ERROR(\"Email address not specified\");\n opts.email = malloc(51);\n fputs(\"Enter your eMail-address: \", stderr);\n if (fscanf(ttyfile, \"%50s\", opts.email) < 1)\n ERROR(\"Email invalid\");\n while (fgetc(ttyfile) != '\\n');\n }\n email = strdup(opts.email);\n\n if (opts.password == NULL) {\n if (!interactive) ERROR(\"Password not specified\");\n opts.password = malloc(51);\n fputs(\"Enter your password: \", stderr);\n tcgetattr(fileno(ttyfile), &ios0);\n ios1 = ios0;\n ios1.c_lflag &= ~ECHO;\n tcsetattr(fileno(ttyfile), TCSAFLUSH, &ios1);\n if (fscanf(ttyfile, \"%50s\", opts.password) < 1) {\n tcsetattr(0, TCSAFLUSH, &ios0);\n ERROR(\"Password invalid\");\n }\n tcsetattr(fileno(ttyfile), TCSAFLUSH, &ios0);\n while (fgetc(ttyfile) != '\\n');\n fputc('\\n', stderr);\n }\n password = strdup(opts.password);\n \n char *bigkey = generateBigkey(date);\n char *request = generateRequest(bigkey, date);\n free(email);\n free(password);\n \n fputs(\"Trying to contact server...\\n\", stderr);\n struct MemoryStruct *response = contactServer(request);\n\n if (response->size == 0 || response->memory == NULL) {\n ERROR(\"Server sent an empty response, exiting\");\n }\n fputs(\"Server responded.\\n\", stderr);\n \n // skip initial whitespace\n char *message = response->memory;\n message += strspn(message, \" \\t\\n\");\n \n if (isBase64(message) == 0) {\n if (memcmp(message,\"MessageToBePrintedInDecoder\",27) ==0) {\n fputs(\"Server sent us this sweet message:\\n\", stderr);\n quote(message + 27);\n } else {\n fputs(\"Server sent us this ugly crap:\\n\", stderr);\n dumpHex(response->memory, response->size);\n }\n ERROR(\"Server response is unuseable, exiting\");\n }\n \n int info_len;\n char *info_crypted = base64Decode(message, &info_len);\n \n if (info_len % 8 != 0) {\n fputs(\"Length of response must be a multiple of 8.\", stderr);\n dumpHex(info_crypted, info_len);\n ERROR(\"Server response is unuseable, exiting\");\n }\n \n info = decryptResponse(info_crypted, info_len, bigkey);\n \n keyphrase = queryGetParam(info, \"HP\");\n if (keyphrase == NULL)\n ERROR(\"Response lacks keyphrase\");\n \n if (strlen(keyphrase) != 56)\n ERROR(\"Keyphrase has wrong length\");\n \n fprintf(stderr, \"Keyphrase: %s\\n\", keyphrase);\n keycache_put(queryGetParam(header, \"FH\"), keyphrase);\n \n free(date);\n free(bigkey);\n free(request);\n free(response->memory);\n free(response);\n free(info_crypted);\n}\n\nvoid openFile() {\n if (strcmp(\"-\", filename) == 0)\n file = stdin;\n else\n file = fopen(filename, \"rb\");\n \n if (file == NULL)\n PERROR(\"Error opening file\");\n \n char magic[11] = { 0 };\n if (fread(magic, 10, 1, file) < 1 && !feof(file))\n PERROR(\"Error reading file\");\n if (feof(file))\n ERROR(\"Error: unexpected end of file\");\n if (strcmp(magic, \"OTRKEYFILE\") != 0)\n ERROR(\"Wrong file format\");\n \n header = getHeader();\n}\n\ntypedef struct verifyFile_ctx {\n MD5_CTX ctx;\n char hash1[16];\n int input;\n} vfy_t;\n\nvoid verifyFile_init(vfy_t *vfy, int input) {\n char *hash_hex, *hash;\n int i;\n \n memset(vfy, 0, sizeof(*vfy));\n vfy->input = input;\n \n /* get MD5 sum from 'OH' or 'FH' header field */\n hash_hex = queryGetParam(header, vfy->input?\"OH\":\"FH\");\n if (hash_hex == NULL || strlen(hash_hex) != 48)\n ERROR(\"Missing hash in file header / unexpected format\");\n for (i=1; i<16; ++i) {\n hash_hex[2*i] = hash_hex[3*i];\n hash_hex[2*i+1] = hash_hex[3*i+1];\n }\n hash_hex[32] = 0;\n if (opts.verbosity >= VERB_DEBUG)\n fprintf(stderr, \"Checking %s against MD5 sum: %s\\n\",\n vfy->input?\"input\":\"output\", hash_hex);\n hash = hex2bin(hash_hex);\n memcpy(vfy->hash1, hash, 16);\n \n /* calculate MD5 sum of file (without header) */\n memset(&vfy->ctx, 0, sizeof(vfy->ctx));\n MD5_Init(&vfy->ctx);\n \n free(hash_hex);\n free(hash);\n}\n\nvoid verifyFile_data(vfy_t *vfy, char *buffer, size_t len) {\n MD5_Update(&vfy->ctx, buffer, len);\n}\n\nvoid verifyFile_final(vfy_t *vfy) {\n unsigned char md5[16];\n \n MD5_Final(md5, &vfy->ctx);\n if (memcmp(vfy->hash1, md5, 16) != 0) {\n if (vfy->input)\n ERROR(\"Input file had errors. Output may or may not be usable.\");\n else\n ERROR(\"Output verification failed. Wrong key?\");\n }\n}\n\nvoid verifyOnly() {\n vfy_t vfy;\n size_t n;\n static char buffer[65536];\n unsigned long long length;\n unsigned long long position;\n\n length = atoll(queryGetParam(header, \"SZ\")) - 522;\n fputs(\"Verifying otrkey...\\n\", stderr);\n verifyFile_init(&vfy, 1);\n for (position = 0; position < length; position += n) {\n showProgress(position, length);\n n = fread(buffer, 1, MIN(length - position, sizeof(buffer)), file);\n if (n == 0 || ferror(file)) break;\n verifyFile_data(&vfy, buffer, n);\n }\n if (position < length) {\n if (!feof(file)) PERROR(\"fread\");\n if (!logfilemode) fputc('\\n', stderr);\n fputs(\"file is too short\\n\", stderr);\n }\n else\n showProgress(1, 0);\n\n if (fread(buffer, 1, 1, file) > 0)\n fputs(\"file contains trailing garbage\\n\", stderr);\n else if (!feof(file))\n PERROR(\"fread\");\n verifyFile_final(&vfy);\n fputs(\"file is OK\\n\", stderr);\n}\n\nvoid decryptFile() {\n int fd;\n char *headerFN;\n struct stat st;\n FILE *destfile;\n\n if (opts.destfile == NULL) {\n headerFN = queryGetParam(header, \"FN\");\n if (opts.destdir != NULL) {\n destfilename = malloc(strlen(opts.destdir) + strlen(headerFN) + 2);\n strcpy(destfilename, opts.destdir);\n strcat(destfilename, \"/\");\n strcat(destfilename, headerFN);\n free(headerFN);\n }\n else {\n destfilename = headerFN;\n }\n }\n else {\n destfilename = strdup(opts.destfile);\n }\n \n if (strcmp(destfilename, \"-\") == 0) {\n if (isatty(1)) ERROR(\"error: cowardly refusing to output to a terminal\");\n fd = 1;\n }\n else\n fd = open(destfilename, O_WRONLY|O_CREAT|O_EXCL, CREAT_MODE);\n if (fd < 0 && errno == EEXIST) {\n if (stat(destfilename, &st) != 0 || S_ISREG(st.st_mode)) {\n if (!interactive) ERROR(\"Destination file exists: %s\", destfilename);\n fprintf(stderr, \"Destination file exists: %s\\nType y to overwrite: \",\n destfilename);\n if (fgetc(ttyfile) != 'y') exit(EXIT_FAILURE);\n while (fgetc(ttyfile) != '\\n');\n fd = open(destfilename, O_WRONLY|O_TRUNC, 0);\n }\n else\n fd = open(destfilename, O_WRONLY, 0);\n }\n if (fd < 0)\n PERROR(\"Error opening destination file: %s\", destfilename);\n if ((destfile = fdopen(fd, \"wb\")) == NULL)\n PERROR(\"fdopen\");\n \n fputs(\"Decrypting and verifying...\\n\", stderr); // -----------------------\n \n void *key = hex2bin(keyphrase);\n MCRYPT blowfish = mcrypt_module_open(\"blowfish-compat\", NULL, \"ecb\", NULL);\n mcrypt_generic_init(blowfish, key, 28, NULL);\n \n unsigned long long length = atoll(queryGetParam(header, \"SZ\")) - 522;\n unsigned long long position = 0;\n size_t readsize;\n size_t writesize;\n static char buffer[65536];\n vfy_t vfy_in, vfy_out;\n \n verifyFile_init(&vfy_in, 1);\n verifyFile_init(&vfy_out, 0);\n \n while (position < length) {\n showProgress(position, length);\n\n if (length - position >= sizeof(buffer)) {\n readsize = fread(buffer, 1, sizeof(buffer), file);\n } else {\n readsize = fread(buffer, 1, length - position, file);\n }\n if (readsize <= 0) {\n if (feof(file))\n ERROR(\"Input file is too short\");\n PERROR(\"Error reading input file\");\n }\n \n verifyFile_data(&vfy_in, buffer, readsize);\n /* If the payload length is not a multiple of eight,\n * the last few bytes are stored unencrypted */\n mdecrypt_generic(blowfish, buffer, readsize - readsize % 8);\n verifyFile_data(&vfy_out, buffer, readsize);\n \n writesize = fwrite(buffer, 1, readsize, destfile);\n if (writesize != readsize)\n PERROR(\"Error writing to destination file\");\n \n position += writesize;\n }\n showProgress(1, 0);\n\n verifyFile_final(&vfy_in);\n verifyFile_final(&vfy_out);\n fputs(\"OK checksums from header match\\n\", stderr);\n \n mcrypt_generic_deinit(blowfish);\n mcrypt_module_close(blowfish);\n \n if (fclose(destfile) != 0)\n PERROR(\"Error closing destination file.\");\n\n if (opts.unlinkmode) {\n if (strcmp(filename, \"-\") != 0 &&\n stat(filename, &st) == 0 && S_ISREG(st.st_mode) &&\n strcmp(destfilename, \"-\") != 0 &&\n stat(destfilename, &st) == 0 && S_ISREG(st.st_mode)) {\n if (unlink(filename) != 0)\n PERROR(\"Cannot delete input file\");\n else\n fputs(\"info: input file has been deleted\\n\", stderr);\n }\n else {\n fputs(\"Warning: Not deleting input file (input or \"\n \"output is not a regular file)\\n\", stderr);\n }\n }\n \n free(key);\n free(destfilename);\n}\n\nvoid processFile() {\n int storeKeyphrase;\n switch (opts.action) {\n case ACTION_INFO:\n // TODO: output something nicer than just the querystring\n dumpQuerystring(header);\n break;\n case ACTION_FETCHKEY:\n fetchKeyphrase();\n break;\n case ACTION_DECRYPT:\n storeKeyphrase = 1;\n if (opts.keyphrase == NULL) {\n storeKeyphrase = 0;\n keyphrase = keycache_get(queryGetParam(header, \"FH\"));\n if (keyphrase)\n fprintf(stderr, \"Keyphrase from cache: %s\\n\", keyphrase);\n else\n fetchKeyphrase();\n }\n else {\n keyphrase = strdup(opts.keyphrase);\n }\n decryptFile();\n if (storeKeyphrase)\n keycache_put(queryGetParam(header, \"FH\"), keyphrase);\n break;\n case ACTION_VERIFY:\n verifyOnly();\n break;\n }\n}\n\nvoid usageError() {\n fputs(\"\\n\"\n \"Usage: otrtool [-h] [-v] [-i|-f|-x|-y] [-u]\\n\"\n \" [-k ] [-e ] [-p ]\\n\"\n \" [-D ] [-O ]\\n\"\n \" [ ... []]\\n\"\n \"\\n\"\n \"MODES OF OPERATION\\n\"\n \" -i | Display information about file (default action)\\n\"\n \" -f | Fetch keyphrase for file\\n\"\n \" -x | Decrypt file\\n\"\n \" -y | Verify only\\n\"\n \"\\n\"\n \"FREQUENTLY USED OPTIONS\\n\"\n \" -k | Do not fetch keyphrase, use this one\\n\"\n \" -D | Output folder\\n\"\n \" -O | Output file (overrides -D)\\n\"\n \" -u | Delete otrkey-files after successful decryption\\n\"\n \"\\n\"\n \"See otrtool(1) for further information\\n\", stderr);\n}\n\nint main(int argc, char *argv[]) {\n fputs(\"OTR-Tool, \" VERSION \"\\n\", stderr);\n\n int i;\n int opt;\n while ( (opt = getopt(argc, argv, \"hvgifxyk:e:p:D:O:u\")) != -1) {\n switch (opt) {\n case 'h':\n usageError();\n exit(EXIT_SUCCESS);\n break;\n case 'v':\n opts.verbosity = VERB_DEBUG;\n break;\n case 'g':\n opts.guimode = 1;\n interactive = 0;\n break;\n case 'i':\n opts.action = ACTION_INFO;\n break;\n case 'f':\n opts.action = ACTION_FETCHKEY;\n break;\n case 'x':\n opts.action = ACTION_DECRYPT;\n break;\n case 'y':\n opts.action = ACTION_VERIFY;\n break;\n case 'k':\n opts.keyphrase = optarg;\n break;\n case 'e':\n opts.email = strdup(optarg);\n memset(optarg, 'x', strlen(optarg));\n break;\n case 'p':\n opts.password = strdup(optarg);\n memset(optarg, 'x', strlen(optarg));\n break;\n case 'D':\n opts.destdir = optarg;\n break;\n case 'O':\n opts.destfile = optarg;\n break;\n case 'u':\n opts.unlinkmode = 1;\n break;\n default:\n usageError();\n exit(EXIT_FAILURE);\n }\n }\n if (opts.verbosity >= VERB_DEBUG) {\n fputs(\"command line: \", stderr);\n for (i = 0; i < argc; ++i) {\n fputs(argv[i], stderr);\n fputc((i == argc - 1) ? '\\n' : ' ', stderr);\n }\n }\n \n if (optind >= argc) {\n fprintf(stderr, \"Missing argument: otrkey-file\\n\");\n usageError();\n exit(EXIT_FAILURE);\n }\n if (argc > optind + 1) {\n if (opts.destfile != NULL && strcmp(opts.destfile, \"-\") == 0) {\n i = 0;\n }\n else for (i = optind; i < argc; i++) {\n if (strcmp(argv[i], \"-\") == 0)\n break;\n }\n if (i < argc)\n ERROR(\"Usage error: piping is not possible with multiple input files\");\n }\n\n if (!isatty(2) && opts.guimode == 0) {\n logfilemode = 1;\n interactive = 0;\n }\n if (interactive) {\n if (!isatty(0)) {\n ttyfile = fopen(\"/dev/tty\", \"r\");\n if (ttyfile == NULL) {\n if (opts.verbosity >= VERB_DEBUG) perror(\"open /dev/tty\");\n interactive = 0;\n }\n }\n else ttyfile = stdin;\n }\n\n if (opts.action == ACTION_DECRYPT || opts.action == ACTION_VERIFY) {\n errno = 0;\n nice(10);\n if (errno == 0 && opts.verbosity >= VERB_DEBUG)\n fputs(\"NICE was set to 10\\n\", stderr);\n\n // I am not sure if this really catches all errors\n // If this causes problems, just delete the ionice-stuff\n #ifdef __NR_ioprio_set\n if (syscall(__NR_ioprio_set, 1, getpid(), 7 | 3 << 13) == 0\n && opts.verbosity >= VERB_DEBUG)\n fputs(\"IONICE class was set to Idle\\n\", stderr);\n #endif\n }\n if (opts.action == ACTION_FETCHKEY || opts.action == ACTION_DECRYPT) {\n keycache_open();\n }\n\n for (i = optind; i < argc; i++) {\n filename = argv[i];\n if (argc > optind + 1)\n fprintf(stderr, \"\\n==> %s <==\\n\", filename);\n openFile();\n processFile();\n if (fclose(file) != 0)\n PERROR(\"Error closing file\");\n free(header);\n }\n \n exit(EXIT_SUCCESS);\n}\n"}} -{"repo": "rhr/ivy", "pr_number": 10, "title": "Cz staging", "state": "closed", "merged_at": "2017-08-15T17:39:52Z", "additions": 291, "deletions": 272, "files_changed": ["ivy/__init__.py", "ivy/ages.py", "ivy/align.py", "ivy/ascii.py", "ivy/autocollapse.py", "ivy/bipart.py", "ivy/chars/__init__.py", "ivy/chars/catpars.py", "ivy/chars/evolve.py", "ivy/chars/mk.py", "ivy/contrasts.py", "ivy/genbank.py", "ivy/interactive.py", "ivy/layout.py", "ivy/ltt.py", "ivy/newick.py", "ivy/nexus.py", "ivy/sequtil.py", "ivy/storage.py", "ivy/tree.py", "ivy/treebase.py", "ivy/vis/alignment.py", "ivy/vis/hardcopy.py", "ivy/vis/symbols.py", "ivy/vis/tree.py"], "files_before": {"ivy/__init__.py": "\"\"\"\nivy - a phylogenetics library and visual shell\nhttp://www.reelab.net/ivy\n\nCopyright 2010 Richard Ree \n\nRequired: ipython, matplotlib, scipy, numpy\nUseful: dendropy, biopython, etc.\n\"\"\"\n## This program is free software; you can redistribute it and/or\n## modify it under the terms of the GNU General Public License as\n## published by the Free Software Foundation; either version 3 of the\n## License, or (at your option) any later version.\n\n## This program is distributed in the hope that it will be useful, but\n## WITHOUT ANY WARRANTY; without even the implied warranty of\n## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n## General Public License for more details.\n\n## You should have received a copy of the GNU General Public License\n## along with this program. If not, see\n## .\n\nimport tree, layout, contrasts, ages\nimport bipart, genbank, nexus, newick, storage\n#import nodearray, data\nimport treebase\n#import db\n#import contrib\ntry:\n import ltt as _ltt\n ltt = _ltt.ltt\nexcept ImportError:\n pass\n\nimport chars, align, sequtil\n## try: import vis\n## except RuntimeError: pass\n", "ivy/ages.py": "\"\"\"\nCalculate node ages from branch lengths.\n\nThe function of interest is `ages2lengths`\n\"\"\"\n\ndef ages2lengths(node, node_ages, results={}):\n \"\"\"\n Convert node ages to branch lengths\n\n Args:\n node (Node): Node object\n node_ages (dict): Dict mapping nodes to ages\n Returns:\n dict: mapping of nodes to lengths\n\n \"\"\"\n for d in node.descendants():\n age = node_ages[d]\n if d.parent:\n parent_age = node_ages[d.parent]\n results[d] = parent_age - age\n return results\n\ndef min_ages(node, leaf_ages, results={}):\n \"\"\"\n Calculate minimum ages given fixed ages in leaf_ages\n\n Args:\n node (Node): A node object\n leaf_ages (dict): A dict mapping leaf nodes to ages\n Returns:\n dict: mapping of nodes to ages\n \"\"\"\n v = []\n for child in node.children:\n if child.label and (child.label in leaf_ages):\n age = leaf_ages[child.label]\n v.append(age)\n results[child] = age\n else:\n min_ages(child, leaf_ages, results)\n age = results[child]\n v.append(age)\n results[node] = max(v)\n return results\n\ndef smooth(node, node_ages, results={}):\n \"\"\"\n adjust ages of internal nodes by smoothing\n RR: I don't actually know what this function does -CZ\n \"\"\"\n if node.parent:\n parent_age = node_ages[node.parent]\n if node.children:\n max_child_age = max([ node_ages[child] for child in node.children ])\n # make the new age the average of parent and max child\n new_node_age = (parent_age + max_child_age)/2.0\n results[node] = new_node_age\n else:\n results[node] = node_ages[node]\n else:\n results[node] = node_ages[node]\n for child in node.children:\n smooth(child, node_ages, results)\n return results\n\nif __name__ == \"__main__\":\n import newick, ascii\n\n s = \"((((a,b),(c,d),(e,f)),g),h);\"\n root = newick.parse(s)\n\n leaf_ages = {\n \"a\": 3,\n \"b\": 2,\n \"c\": 4,\n \"d\": 1,\n \"e\": 3,\n \"f\": 0.5,\n \"g\": 10,\n \"h\": 5,\n }\n\n ma = min_ages(root, leaf_ages)\n d = ma\n for i in range(10):\n d = smooth(root, d)\n for node, val in ages2lengths(root, d).items():\n node.length = val\n print ascii.render(root, scaled=1)\n", "ivy/align.py": "import os\nfrom subprocess import Popen, PIPE\nfrom Bio import AlignIO\nfrom Bio.Alphabet import IUPAC\nfrom cStringIO import StringIO\nfrom tempfile import NamedTemporaryFile\n\nMUSCLE = \"/usr/bin/muscle\"\n\ndef muscle(seqs, cmd=None):\n if not cmd: cmd = MUSCLE\n assert os.path.exists(cmd)\n p = Popen([cmd], stdin=PIPE, stdout=PIPE)\n write = p.stdin.write\n for x in seqs:\n write(\">%s\\n%s\\n\" % (x.id, x.seq))\n out = p.communicate()[0]\n aln = AlignIO.read(StringIO(out), 'fasta', alphabet=IUPAC.ambiguous_dna)\n return aln\n\ndef musclep(seqs1, seqs2, cmd=\"/usr/bin/muscle\"):\n assert os.path.exists(cmd)\n f1 = NamedTemporaryFile(); f2 = NamedTemporaryFile()\n for s, f in ((seqs1, f1), (seqs2, f2)):\n write = f.file.write\n for x in s: write(\">%s\\n%s\\n\" % (x.id, x.seq))\n f1.file.flush(); f2.file.flush()\n cmd += \" -profile -in1 %s -in2 %s\" % (f1.name, f2.name)\n p = Popen(cmd.split(), stdout=PIPE)\n out = p.communicate()[0]\n aln = AlignIO.read(StringIO(out), 'fasta', alphabet=IUPAC.ambiguous_dna)\n f1.file.close(); f2.file.close()\n return aln\n \ndef read(data, format=None, name=None):\n from types import StringTypes\n \n def strip(s):\n fname = os.path.split(s)[-1]\n head, tail = os.path.splitext(fname)\n tail = tail.lower()\n if tail in (\".fasta\", \".nex\", \".nexus\"):\n return head\n else:\n return fname\n\n if (not format):\n if (type(data) in StringTypes) and os.path.isfile(data):\n s = data.lower()\n if s.endswith(\"fasta\"):\n format=\"fasta\"\n for tail in \".nex\", \".nexus\":\n if s.endswith(tail):\n format=\"nexus\"\n break\n\n if (not format):\n format = \"fasta\"\n\n if type(data) in StringTypes:\n if os.path.isfile(data):\n name = strip(data)\n with open(data) as f:\n return AlignIO.read(f, format, alphabet=IUPAC.ambiguous_dna)\n else:\n f = StringIO(data)\n return AlignIO.read(f, format, alphabet=IUPAC.ambiguous_dna)\n\n elif (hasattr(data, \"tell\") and hasattr(data, \"read\")):\n treename = strip(getattr(data, \"name\", None))\n return AlignIO.read(data, format, alphabet=IUPAC.ambiguous_dna)\n\n raise IOError, \"unable to read alignment from '%s'\" % data\n\ndef write(data, f, format='fasta'):\n AlignIO.write(data, f, format)\n \ndef find(aln, substr):\n \"\"\"\n generator that yields (seqnum, pos) tuples for every position of\n ``subseq`` in `aln`\n \"\"\"\n from sequtil import finditer\n N = len(substr)\n for i, rec in enumerate(aln):\n for j in finditer(rec.seq, substr):\n yield (i,j)\n \ndef find_id(aln, regexp):\n import re\n return [ (i,s) for i, s in enumerate(aln) if re.search(regexp, s.id) ]\n \ndef gapcols(aln, c='-'):\n from numpy import array\n a = array([ list(x.seq) for x in aln ])\n for i, col in enumerate(a.T):\n s = set(col==c)\n if len(s)==1 and True in s:\n yield i\n", "ivy/ascii.py": "from array import array\nfrom layout import depth_length_preorder_traversal\n\nclass AsciiBuffer:\n def __init__(self, width, height):\n self.width = width\n self.height = height\n self._b = [ array('c', ' '*width) for line in range(height) ]\n\n def putstr(self, r, c, s):\n assert r < self.height\n assert c+len(s) <= self.width, \"%s %s %s '%s'\" % (self.width, r, c, s)\n self._b[r][c:c+len(s)] = array('c', s)\n\n def __str__(self):\n return \"\\n\".join([ b.tostring() for b in self._b ])\n\ndef sum_to_root(node, internodes=True, length=False):\n \"\"\"\n Number of branches from node to root.\n\n Args:\n node (Node): A Node object\n RR: Do internodes and length do anything in this function? -CZ\n Returns:\n int: The number of branches from node to root.\n \"\"\"\n i = 0\n n = node\n while 1:\n if not n.parent:\n break\n else:\n n = n.parent\n i += 1\n return i\n\n## def depth_length_preorder_traversal(node):\n## if not node.parent:\n## node.depth = 0\n## node.length_to_root = 0.0\n## else:\n## p = node.parent\n## node.depth = p.depth + 1\n## node.length_to_root = p.length_to_root + (node.length or 0.0)\n## for ch in node.children:\n## depth_length_preorder_traversal(ch)\n\ndef smooth_cpos(node, n2c):\n for ch in node.children:\n smooth_cpos(ch, n2c)\n\n if node.parent and not node.isleaf:\n px = n2c[node.parent].c\n cx = min([ n2c[ch].c for ch in node.children ])\n dxp = n2c[node].c - px\n cxp = cx - n2c[node].c\n node.c = int(px + (cx - px)*0.5)\n\ndef scale_cpos(node, n2c, scalef, root_offset):\n if node.parent:\n n2c[node].c = n2c[node.parent].c + int(node.length * scalef)\n else:\n n2c[node].c = root_offset\n\n for ch in node.children:\n scale_cpos(ch, n2c, scalef, root_offset)\n\ndef set_rpos(node, n2c):\n for child in node.children:\n set_rpos(child, n2c)\n nc = n2c[node]\n if node.children:\n children = node.children\n c0 = n2c[children[0]]\n c1 = n2c[children[-1]]\n rmin = c0.r; rmax = c1.r\n nc.r = int(rmin + (rmax-rmin)/2.0)\n\ndef render(root, unitlen=3, minwidth=50, maxwidth=None, scaled=False,\n show_internal_labels=True):\n \"\"\"\n Create the ascii tree to be shown with print()\n \"\"\"\n n2c = depth_length_preorder_traversal(root)\n leaves = root.leaves(); nleaves = len(leaves)\n maxdepth = max([ n2c[lf].depth for lf in leaves ])\n max_labelwidth = max([ len(lf.label) for lf in leaves ]) + 1\n\n root_offset = 0\n if root.label and show_internal_labels:\n root_offset = len(root.label)\n\n width = maxdepth*unitlen + max_labelwidth + 2 + root_offset\n height = 2*nleaves - 1\n\n if width < minwidth:\n unitlen = (minwidth - max_labelwidth - 2 - root_offset)/maxdepth\n width = maxdepth*unitlen + max_labelwidth + 2 + root_offset\n\n buf = AsciiBuffer(width, height)\n\n for i, lf in enumerate(leaves):\n c = n2c[lf]\n c.c = width - max_labelwidth - 2\n c.r = i*2\n\n for node in root.postiter():\n nc = n2c[node]\n if node.children:\n children = node.children\n c0 = n2c[children[0]]\n c1 = n2c[children[-1]]\n rmin = c0.r; rmax = c1.r\n nc.r = int(rmin + (rmax-rmin)/2.0)\n nc.c = min([ n2c[ch].c for ch in children ]) - unitlen\n\n if not scaled:\n smooth_cpos(root, n2c)\n else:\n maxlen = max([ n2c[lf].length_to_root for lf in leaves ])\n scalef = (n2c[leaves[0]].c + 1 - root_offset)/maxlen\n scale_cpos(root, n2c, scalef, root_offset)\n\n for node in root.postiter():\n nc = n2c[node]\n if node.parent:\n pc = n2c[node.parent]\n for r in range(min([nc.r, pc.r]),\n max([nc.r, pc.r])):\n buf.putstr(r, pc.c, \":\")\n\n sym = getattr(nc, \"hchar\", \"-\")\n vbar = sym*(nc.c-pc.c)\n buf.putstr(nc.r, pc.c, vbar)\n\n if node.isleaf:\n buf.putstr(nc.r, nc.c+1, \" \"+node.label)\n else:\n if node.label and show_internal_labels:\n buf.putstr(nc.r, nc.c-len(node.label), node.label)\n\n buf.putstr(nc.r, nc.c, \"+\")\n\n return str(buf)\n\nif __name__ == \"__main__\":\n import random, tree\n rand = random.Random()\n\n t = tree.read(\n \"(foo,((bar,(dog,cat)dc)dcb,(shoe,(fly,(cow, bowwow)cowb)cbf)X)Y)Z;\"\n )\n\n #t = tree.read(\"(((foo:4.6):5.6, (bar:6.5, baz:2.3):3.0):3.0);\")\n #t = tree.read(\"(foo:4.6, (bar:6.5, baz:2.3)X:3.0)Y:3.0;\")\n\n i = 1\n print render(t, scaled=0, show_internal_labels=1)\n r = t.get(\"cat\").parent\n tree.reroot(t, r)\n tp = t.parent\n tp.remove_child(t)\n c = t.children[0]\n t.remove_child(c)\n tp.add_child(c)\n print render(r, scaled=0, show_internal_labels=1)\n", "ivy/autocollapse.py": "\"\"\"\nFor drawing big trees. Calculate which clades can be 'collapsed' and\ndisplayed with a placeholder.\n\nTODO: test and develop this module further\n\"\"\"\nfrom storage import Storage\n\ndef autocollapse_info(node, collapsed, visible=True, info={}):\n \"\"\"\n gather information to determine if a node should be collapsed\n\n *collapsed* is a set containing nodes that are already collapsed\n \"\"\"\n if node not in info:\n s = Storage()\n info[node] = s\n else:\n s = info[node]\n \n if visible and (node in collapsed):\n visible = False\n \n nnodes = 1 # total number of nodes, including node\n # number of visible leaves\n nvisible = int((visible and node.isleaf) or (node in collapsed))\n ntips = int(node.isleaf)\n ntips_visible = int(node.isleaf and visible)\n s.has_labeled_descendant = False\n s.depth = 1\n\n for child in node.children:\n autocollapse_info(child, collapsed, visible, info)\n cs = info[child]\n nnodes += cs.nnodes\n nvisible += cs.nvisible\n ntips += cs.ntips\n ntips_visible += cs.ntips_visible\n if (child.label and (not child.isleaf)) \\\n or (cs.has_labeled_descendant):\n s.has_labeled_descendant = True\n if cs.depth >= s.depth:\n s.depth = cs.depth+1\n s.nnodes = nnodes\n s.nvisible = nvisible\n s.ntips = ntips\n s.ntips_visible = ntips_visible\n return info\n\ndef autocollapse(root, collapsed=None, keep_visible=None, max_visible=1000):\n \"\"\"\n traverse a tree and find nodes that should be collapsed in order\n to satify *max_visible*\n\n *collapsed* is a set object for storing collapsed nodes\n\n *keep_visible* is a set object of nodes that should not be placed\n in *collapsed*\n \"\"\"\n collapsed = collapsed or set()\n keep_visible = keep_visible or set()\n ntries = 0\n while True:\n if ntries > 10:\n return\n info = autocollapse_info(root, collapsed)\n nvisible = info[root].nvisible\n if nvisible <= max_visible:\n return\n \n v = []\n for node in root.iternodes():\n s = info[node]\n if (node.label and (not node.isleaf) and node.parent and\n (node not in keep_visible)):\n w = s.nvisible/float(s.depth)\n if s.has_labeled_descendant:\n w *= 0.25\n v.append((w, node, s))\n v.sort(); v.reverse()\n for w, node, s in v:\n if node not in keep_visible and s.nvisible < (nvisible-1):\n print node\n collapsed.add(node)\n nvisible -= s.nvisible\n if nvisible <= max_visible:\n break\n ntries += 1\n return collapsed\n", "ivy/bipart.py": "import sys\nfrom pprint import pprint\nfrom glob import glob\nfrom storage import Storage\nfrom collections import defaultdict\n\n## class BipartSet(object):\n## \"A set of bipartitions\"\n## def __init__(self, elements):\n## self.elements = frozenset(elements)\n## self.ref = sorted(elements)[0]\n## self.node2bipart = Storage()\n\n## def add(self, subset, node):\n## # filter out elements of subset not in 'elements'\n## subset = (frozenset(subset) & self.elements)\n## if self.ref not in self.subset:\n## self.subset = self.elements - self.subset\n\nclass Bipart(object):\n \"\"\"\n A class representing a bipartition.\n \"\"\"\n def __init__(self, elements, subset, node=None, support=None):\n \"\"\"\n 'elements' and 'subset' are set objects\n \"\"\"\n self.subset = subset\n self.compute(elements)\n self.node = node\n self.support = support\n\n def __hash__(self):\n return self._hash\n\n def __eq__(self, other):\n assert self.elements == other.elements\n return ((self.subset == other.subset) or\n (self.subset == (self.elements - other.subset)))\n\n def __repr__(self):\n v = sorted(self.subset)\n return \"(%s)\" % \" \".join(map(str, v))\n\n def compute(self, elements):\n self.elements = frozenset(elements)\n self.ref = sorted(elements)[0]\n # filter out elements of subset not in 'elements'\n self.subset = (frozenset(self.subset) & self.elements)\n self._hash = hash(self.subset)\n if self.ref not in self.subset:\n self.subset = self.elements - self.subset\n self.complement = self.elements - self.subset\n\n def iscompatible(self, other):\n ## assert self.elements == other.elements\n if (self.subset.issubset(other.subset) or\n other.subset.issubset(self.subset)):\n return True\n if (((self.subset | other.subset) == self.elements) or\n (not (self.subset & other.subset))):\n return True\n return False\n\ndef conflict(bp1, bp2, support=None):\n if ((support and (bp1.support >= support) and (bp2.support >= support))\n or (not support)):\n if not bp1.iscompatible(bp2):\n return True\n return False\n\nclass TreeSet:\n def __init__(self, root, elements=None):\n self.root = root\n self.node2labels = root.leafsets(labels=True)\n self.elements = elements or self.node2labels.pop(root)\n self.biparts = [ Bipart(self.elements, v, node=k,\n support=int(k.label or 0))\n for k, v in self.node2labels.items() ]\n\ndef compare_trees(r1, r2, support=None):\n e = (set([ x.label for x in r1.leaves() ]) &\n set([ x.label for x in r2.leaves() ]))\n bp1 = [ Bipart(e, v, node=k, support=int(k.label or 0))\n for k, v in r1.leafsets(labels=True).items() ]\n bp2 = [ Bipart(e, v, node=k, support=int(k.label or 0))\n for k, v in r2.leafsets(labels=True).items() ]\n return compare(bp1, bp2, support)\n\ndef compare(set1, set2, support=None):\n hits1 = []; hits2 = []\n conflicts1 = defaultdict(set); conflicts2 = defaultdict(set)\n for bp1 in set1:\n for bp2 in set2:\n if bp1 == bp2:\n hits1.append(bp1.node); hits2.append(bp2.node)\n if conflict(bp1, bp2, support):\n conflicts1[bp1.node].add(bp2.node)\n conflicts2[bp2.node].add(bp1.node)\n return hits1, hits2, conflicts1, conflicts2\n \n## a = Bipart(\"abcdef\", \"abc\")\n## b = Bipart(\"abcdef\", \"def\")\n## c = Bipart(\"abcdef\", \"ab\")\n## d = Bipart(\"abcdef\", \"cd\")\n## print a == b\n## print a.iscompatible(b)\n## print a.iscompatible(c)\n## print a.iscompatible(d)\n## print c.iscompatible(d)\n## sys.exit() \n", "ivy/chars/__init__.py": "import mk, catpars, evolve\n", "ivy/chars/catpars.py": "import scipy, numpy\n\ndef default_costmatrix(numstates, dtype=numpy.int):\n \"a square array with zeroes along the diagonal, ones elsewhere\"\n return scipy.logical_not(scipy.identity(numstates)).astype(float)\n\ndef minstates(v):\n \"return the indices of v that equal the minimum\"\n return scipy.nonzero(scipy.equal(v, min(v)))\n\ndef downpass(node, states, stepmatrix, chardata, node2dpv=None):\n if node2dpv is None:\n node2dpv = {}\n \n if not node.isleaf:\n for child in node.children:\n downpass(child, states, stepmatrix, chardata, node2dpv)\n\n dpv = scipy.zeros([len(states)])\n node2dpv[node] = dpv\n for i in states:\n for child in node.children:\n child_dpv = node2dpv[child]\n mincost = min([ child_dpv[j] + stepmatrix[i,j] \\\n for j in states ])\n dpv[i] += mincost\n \n #print node.label, node.dpv\n\n else:\n #print node.label, chardata[node.label]\n node2dpv[node] = stepmatrix[:,chardata[node.label]]\n\n return node2dpv\n \n\ndef uppass(node, states, stepmatrix, node2dpv, node2upm={},\n node2ancstates=None):\n parent = node.parent\n if not node.isleaf:\n if parent is None: # root\n dpv = node2dpv[node]\n upm = None\n node.mincost = min(dpv)\n node2ancstates = {node: minstates(dpv)}\n \n else:\n M = scipy.zeros(stepmatrix.shape)\n for i in states:\n sibs = [ c for c in parent.children if c is not node ]\n for j in states:\n c = 0\n for sib in sibs:\n sibdpv = node2dpv[sib]\n c += min([ sibdpv[x] + stepmatrix[j,x]\n for x in states ])\n c += stepmatrix[j,i]\n\n p_upm = node2upm.get(parent)\n if p_upm is not None:\n c += min(p_upm[j])\n\n M[i,j] += c\n \n node2upm[node] = M\n\n v = node2dpv[node][:]\n for s in states:\n v[s] += min(M[s])\n node2ancstates[node] = minstates(v)\n\n for child in node.children:\n uppass(child, states, stepmatrix, node2dpv, node2upm,\n node2ancstates)\n\n return node2ancstates\n \ndef ancstates(tree, chardata, stepmatrix):\n states = range(len(stepmatrix))\n return uppass(tree, states, stepmatrix,\n downpass(tree, states, stepmatrix, chardata))\n\ndef _bindeltran(node, stepmatrix, node2dpv, node2deltr=None, ancstate=None):\n if node2deltr is None:\n node2deltr = {}\n\n dpv = node2dpv[node]\n if ancstate is not None:\n c, s = min([ (cost+stepmatrix[ancstate,i], i) \\\n for i, cost in enumerate(dpv) ])\n else:\n c, s = min([ (cost, i) for i, cost in enumerate(dpv) ])\n \n node2deltr[node] = s\n for child in node.children:\n _bindeltran(child, stepmatrix, node2dpv, node2deltr, s)\n\n return node2deltr\n \ndef binary_deltran(tree, chardata, stepmatrix):\n states = range(len(stepmatrix))\n node2dpv = downpass(tree, states, stepmatrix, chardata)\n node2deltr = _bindeltran(tree, stepmatrix, node2dpv)\n return node2deltr\n \n\nif __name__ == \"__main__\":\n from pprint import pprint\n from ivy import tree\n root = tree.read(\"(a,((b,c),(d,(e,f))));\")\n\n nstates = 4\n states = range(nstates)\n cm = default_costmatrix(nstates)\n chardata = dict(zip(\"abcdef\", map(int, \"000233\")))\n dp = downpass(root, states, cm, chardata)\n\n for i, node in enumerate(root):\n if not node.label:\n node.label = \"N%s\" % i\n else:\n node.label = \"%s (%s)\" % (node.label, chardata[node.label])\n\n print ascii.render(root)\n \n\n## nstates = 2\n## leaves = tree.leaves() \n## for leaf in leaves:\n## leaf.anc_cost_vector = chardata[leaf.label]\n\n pprint(\n #ancstates(root, chardata, cm)\n #uppass(root, states, cm, downpass(tree, states, cm, chardata))\n dp\n )\n\n\n", "ivy/chars/evolve.py": "#!/usr/bin/env python\n\"\"\"\nFunctions for evolving traits and trees.\n\"\"\"\ndef brownian(root, sigma=1.0, init=0.0, values={}):\n \"\"\"\n Recursively evolve a trait by Brownian motion up from the node\n *root*.\n\n * *sigma*: standard deviation of the normal random variate after\n one unit of branch length\n\n * *init*: initial value\n\n Returns: *values* - a dictionary mapping nodes to evolved values\n \"\"\"\n from scipy.stats import norm\n values[root] = init\n for child in root.children:\n time = child.length\n random_step = norm.rvs(init, scale=sigma*time)\n brownian(child, sigma, random_step, values)\n return values\n\ndef test_brownian():\n \"\"\"\n Evolve a trait up an example tree of primates:.\n\n ((((Homo:0.21,Pongo:0.21)N1:0.28,Macaca:0.49)N2:0.13,\n Ateles:0.62)N3:0.38,Galago:1.00)root;\n\n Returns: (*root*, *data*) - the root node and evolved data.\n \"\"\"\n import newick\n root = newick.parse(\n \"((((Homo:0.21,Pongo:0.21)N1:0.28,Macaca:0.49)N2:0.13,\"\\\n \"Ateles:0.62)N3:0.38,Galago:1.00)root;\"\n )\n print root.ascii(scaled=True) \n evolved = brownian(root)\n for node in root.iternodes():\n print node.label, evolved[node]\n return root, evolved\n\nif __name__ == \"__main__\":\n test_brownian()\n", "ivy/chars/mk.py": "\"\"\"\nCategorical Markov models with k states.\n\"\"\"\nimport numpy, scipy, random\nimport scipy.linalg\nimport scipy.optimize\nfrom scipy import array, zeros, ones\nfrom scipy.linalg import expm#, expm2, expm3\nfrom math import log, exp\nrand = random.Random()\nuniform = rand.uniform; expovariate = rand.expovariate\n\nLARGE = 10e10 # large -lnL value used to bound parameter optimization\n\nclass Q:\n def __init__(self, k=2, layout=None):\n \"\"\"\n Represents a square transition matrix with k states.\n \n 'layout' is a square (k,k) array of integers that index free\n rate parameters (values on the diagonal are ignored). Cells\n with value 0 will have the first rate parameter, 1 the\n second, etc.\n \"\"\"\n self.k = k\n self.range = range(k)\n self.offdiag = array(numpy.eye(k)==0, dtype=numpy.int)\n if layout is None:\n layout = zeros((k,k), numpy.int)\n self.layout = layout*self.offdiag\n\n def fill(self, rates):\n m = numpy.take(rates, self.layout)*self.offdiag\n v = m.sum(1) * -1\n for i in self.range:\n m[i,i] = v[i]\n return m\n\n def default_priors(self):\n p = 1.0/self.k\n return [p]*self.k\n\ndef sample_weighted(weights):\n u = uniform(0, sum(weights))\n x = 0.0\n for i, w in enumerate(weights):\n x += w\n if u < x:\n break\n return i\n\ndef conditionals(root, data, Q):\n nstates = Q.shape[0]\n states = range(nstates)\n nodes = [ x for x in root.postiter() ]\n nnodes = len(nodes)\n v = zeros((nnodes,nstates))\n n2i = {}\n \n for i, n in enumerate(nodes):\n n2i[n] = i\n if n.isleaf:\n state = data[n.label]\n try:\n state = int(state)\n v[i,state] = 1.0\n except ValueError:\n if state == '?' or state == '-':\n v[i,:] += 1/float(nstates)\n else:\n Pv = [ (expm(Q*child.length)*v[n2i[child]]).sum(1)\n for child in n.children ]\n v[i] = numpy.multiply(*Pv)\n # fossils\n state = None\n if n.label in data:\n state = int(data[n.label])\n elif n in data:\n state = int(data[n])\n if state != None:\n for s in states:\n if s != state: v[i,s] = 0.0\n \n return dict([ (n, v[i]) for n,i in n2i.items() ])\n\ndef contrasts(root, data, Q):\n cond = conditionals(root, data, Q)\n d = {}\n for n in root.postiter(lambda x:x.children):\n nc = cond[n]; nc /= sum(nc)\n diff = 0.0\n for child in n.children:\n cc = cond[child]; cc /= sum(cc)\n diff += numpy.sum(numpy.abs(nc-cc))\n d[n] = diff\n return d\n\ndef lnL(root, data, Q, priors):\n d = conditionals(root, data, Q)\n return numpy.log(sum(d[root]*priors))\n\ndef optimize(root, data, Q, priors=None):\n Qfill = Q.fill\n if priors is None: priors = Q.default_priors()\n def f(params):\n if (params<0).any(): return LARGE\n return -lnL(root, data, Qfill(params), priors)\n \n # initial parameter values\n p = [1.0]*len(set(Q.layout.flat))\n\n v = scipy.optimize.fmin_powell(\n f, p, full_output=True, disp=0, callback=None\n )\n params, neglnL = v[:2]\n if neglnL == LARGE:\n raise Exception(\"ConvergenceError\")\n return params, neglnL\n\ndef sim(root, n2p, s0, d=None):\n if d is None:\n d = {root:s0}\n for n in root.children:\n v = n2p[n][s0]\n i = sample_weighted(v)\n d[n] = i\n sim(n, n2p, i, d)\n return d\n\ndef stmap(root, states, ancstates, Q, condition_on_success):\n \"\"\"\n This and its dependent functions below need testing and\n optimization.\n \"\"\"\n results = []\n for n in root.descendants():\n si = ancstates[n.parent]\n sj = ancstates[n]\n v = simulate_on_branch(states, si, sj, Q, n.length,\n condition_on_success)\n print n, si, sj\n if v:\n results.append(v)\n else:\n return None\n return results\n\ndef simulate_on_branch(states, si, sj, Q, brlen, condition_on_success):\n point = 0.0\n history = [(si, point)]\n if si != sj: # condition on one change occurring\n lambd = -(Q[si,si])\n U = uniform(0.0, 1.0)\n # see appendix of Nielsen 2001, Genetics\n t = brlen - point\n newpoint = -(1.0/lambd) * log(1.0 - U*(1.0 - exp(-lambd * t)))\n newstate = draw_new_state(states, Q, si)\n history.append((newstate, newpoint))\n si = newstate; point = newpoint\n while 1:\n lambd = -(Q[si,si])\n rv = expovariate(lambd)\n newpoint = point + rv\n\n if newpoint <= brlen: # state change along branch\n newstate = draw_new_state(states, Q, si)\n history.append((newstate, newpoint))\n si = newstate; point = newpoint\n else:\n history.append((si, brlen))\n break\n \n if si == sj or (not condition_on_success): # success\n return history\n\n return None\n \ndef draw_new_state(states, Q, si):\n \"\"\"\n Given a rate matrix Q, a starting state si, and an ordered\n sequence of states, eg (0, 1), draw a new state sj with\n probability -(qij/qii)\n \"\"\"\n Qrow = Q[si]\n qii = Qrow[si]\n qij_probs = [ (x, -(Qrow[x]/qii)) for x in states if x != si ]\n uni = uniform(0.0, 1.0)\n val = 0.0\n for sj, prob in qij_probs:\n val += prob\n if uni < val:\n return sj\n \ndef sample_ancstates(node, states, conditionals, n2p, fixed={}):\n \"\"\"\n Sample ancestral states from their conditional likelihoods\n \"\"\"\n ancstates = {}\n for n in node.preiter():\n if n in fixed:\n state = fixed[n]\n else:\n cond = conditionals[n]\n\n if n.parent:\n P = n2p[n]\n ancst = ancstates[n.parent]\n newstate_Prow = P[ancst]\n cond *= newstate_Prow\n\n cond /= sum(cond)\n\n rv = uniform(0.0, 1.0)\n v = 0.0\n for state, c in zip(states, cond):\n v += c\n if rv < v:\n break\n ancstates[n] = state\n\n return ancstates\n", "ivy/contrasts.py": "\"\"\"\nCalculate independent contrasts\n\nTODO: include utilities for transforming data, etc.\n\"\"\"\ndef PIC(node, data, results={}):\n \"\"\"\n Phylogenetic independent contrasts.\n\n Recursively calculate independent contrasts of a bifurcating node\n given a dictionary of trait values.\n\n Args:\n node (Node): A node object\n data (dict): Mapping of leaf names to character values\n\n Returns:\n dict: Mapping of internal nodes to tuples containing ancestral\n state, its variance (error), the contrast, and the\n contrasts's variance.\n\n TODO: modify to accommodate polytomies.\n \"\"\"\n X = []; v = []\n for child in node.children:\n if child.children:\n PIC(child, data, results)\n child_results = results[child]\n X.append(child_results[0])\n v.append(child_results[1])\n else:\n X.append(data[child.label])\n v.append(child.length)\n\n Xi, Xj = X # Xi - Xj is the contrast value\n vi, vj = v\n\n # Xk is the reconstructed state at the node\n Xk = ((1.0/vi)*Xi + (1/vj)*Xj) / (1.0/vi + 1.0/vj)\n\n # vk is the variance\n vk = node.length + (vi*vj)/(vi+vj)\n\n results[node] = (Xk, vk, Xi-Xj, vi+vj)\n\n return results\n\nif __name__ == \"__main__\":\n import tree\n n = tree.read(\n \"((((Homo:0.21,Pongo:0.21)N1:0.28,Macaca:0.49)N2:0.13,\"\\\n \"Ateles:0.62)N3:0.38,Galago:1.00)N4:0.0;\"\n )\n char1 = {\n \"Homo\": 4.09434,\n \"Pongo\": 3.61092,\n \"Macaca\": 2.37024,\n \"Ateles\": 2.02815,\n \"Galago\": -1.46968\n }\n\n for k, v in PIC(n, char1).items():\n print k.label or k.id, v\n", "ivy/genbank.py": "import re, sys, logging\nfrom collections import defaultdict\nfrom itertools import izip_longest, ifilter\nfrom Bio import Entrez, SeqIO\nfrom Bio.Blast import NCBIWWW, NCBIXML\nfrom ivy.storage import Storage\n\nemail = \"\"\n\ndef batch(iterable, size):\n \"\"\"\n Take an iterable and return it in chunks (sub-iterables)\n\n Args:\n iterable: Any iterable\n size (int): Size of chunks\n Yields:\n Chunks of size `size`\n \"\"\"\n args = [ iter(iterable) ]*size\n for x in izip_longest(fillvalue=None, *args):\n yield ifilter(None, x)\n\ndef extract_gbac(s):\n \"\"\"\n Extract genbank accession\n\n Args:\n s (str): text string of genbank file\n Returns:\n list: Accession number(s)\n \"\"\"\n gbac_re = re.compile(r'[A-Z]{1,2}[0-9]{4,7}')\n return gbac_re.findall(s, re.M)\n # RR: This also returns various other strings that match the pattern (eg.\n # protein ids)\n\ndef extract_gene(seq, gene):\n \"\"\"\n RR: Not sure what format seq should be in -CZ\n \"\"\"\n for t in \"exon\", \"gene\":\n for x in seq.features:\n if x.type == t:\n v = x.qualifiers.get(\"gene\")\n if v == [gene]:\n if x.sub_features:\n s = [ seq[sf.location.start.position:\n sf.location.end.position]\n for sf in x.sub_features ]\n return reduce(lambda x,y:x+y, s)\n else:\n loc = x.location\n return seq[loc.start.position-10:loc.end.position+10]\n\ndef gi2webenv(gilist):\n h = Entrez.esearch(\n db=\"nucleotide\", term=\" OR \".join(gilist), usehistory=\"y\",\n retmax=len(gilist)\n )\n d = Entrez.read(h)\n return d[\"WebEnv\"], d[\"QueryKey\"]\n\ndef gi2tax(gi):\n global email\n assert email, \"set email!\"\n Entrez.email = email\n h = Entrez.elink(dbfrom='taxonomy', db='nucleotide', from_uid=gi,\n LinkName='nucleotide_taxonomy')\n r = Entrez.read(h)[0]\n h.close()\n i = r['LinkSetDb'][0]['Link'][0]['Id']\n h = Entrez.efetch(db='taxonomy', id=i, retmode='xml')\n r = Entrez.read(h)[0]\n h.close()\n return r\n\ndef ac2gi(ac):\n global email\n assert email, \"set email!\"\n Entrez.email = email\n h = Entrez.esearch(db=\"nucleotide\", term=ac, retmax=1)\n d = Entrez.read(h)['IdList'][0]\n h.close()\n return d\n\ndef acsum(aclist, batchsize=100):\n \"\"\"\n fetch esummary info for list of accession numbers -- useful for\n getting gi and taxids\n \"\"\"\n global email\n assert email, \"set email!\"\n Entrez.email = email\n results = {}\n for v in batch(aclist, batchsize):\n v = list(v)\n h = Entrez.esearch(\n db=\"nucleotide\", retmax=len(v),\n term=\" OR \".join([ \"%s[ACCN]\" % x for x in v ]),\n usehistory=\"y\"\n )\n d = Entrez.read(h)\n h.close()\n # gis, but not in order of aclist\n gis = d['IdList']\n d = Entrez.read(Entrez.esummary(db='nucleotide', id=','.join(gis)),\n validate=False)\n for x in d:\n ac = x['Caption']\n if ac in aclist:\n results[ac] = x\n return results\n\ndef fetch_aclist(aclist, batchsize=1000):\n global email\n assert email, \"set email!\"\n Entrez.email = email\n results = {}\n n = 0\n for v in batch(aclist, batchsize):\n v = list(v)\n h = Entrez.esearch(\n db=\"nucleotide\",\n term=\" OR \".join([ \"%s[ACCN]\" % x for x in v ]),\n usehistory=\"y\"\n )\n d = Entrez.read(h)\n h.close()\n h = Entrez.efetch(db=\"nucleotide\", rettype=\"gb\", retmax=len(v),\n webenv=d[\"WebEnv\"], query_key=d[\"QueryKey\"])\n seqs = SeqIO.parse(h, \"genbank\")\n for s in seqs:\n try:\n ac = s.annotations[\"accessions\"][0]\n if ac in aclist:\n results[ac] = s\n except:\n pass\n h.close()\n n += len(v)\n logging.info('fetched %s sequences', n)\n return results\n\ndef fetch_gilist(gilist, batchsize=1000):\n global email\n assert email, \"set email!\"\n Entrez.email = email\n results = {}\n for v in batch(gilist, batchsize):\n v = map(str, v)\n h = Entrez.epost(db=\"nucleotide\", id=\",\".join(v), usehistory=\"y\")\n d = Entrez.read(h)\n h.close()\n h = Entrez.efetch(db=\"nucleotide\", rettype=\"gb\", retmax=len(v),\n webenv=d[\"WebEnv\"], query_key=d[\"QueryKey\"])\n seqs = SeqIO.parse(h, \"genbank\")\n for s in seqs:\n try:\n gi = s.annotations[\"gi\"]\n if gi in v:\n s.id = organism_id(s)\n results[gi] = s\n except:\n pass\n h.close()\n return results\n\ndef organism_id(s):\n org = (s.annotations.get('organism') or '').replace('.', '')\n return '%s_%s' % (org.replace(' ','_'), s.id.split('.')[0])\n\ndef fetchseq(gi):\n global email\n assert email, \"set email!\"\n Entrez.email = email\n h = Entrez.efetch(db=\"nucleotide\", id=str(gi), rettype=\"gb\")\n s = SeqIO.read(h, 'genbank')\n s.id = organism_id(s)\n return s\n\ndef create_fastas(data, genes):\n fastas = dict([ (g, file(g+\".fasta\", \"w\")) for g in genes ])\n for label, seqs in data.items():\n for gene, s in zip(genes, seqs):\n if s and type(s) != str:\n tag = None\n try:\n tag = \"%s_%s\" % (label, s.annotations[\"accessions\"][0])\n except:\n tag = \"%s_%s\" % (label, s.name)\n if tag:\n fastas[gene].write(\">%s\\n%s\\n\" % (tag, s.seq))\n else:\n sys.stderr.write((\"error: not an accession number? \"\n \"%s (%s %s)\\n\" % (s, label, gene)))\n\n for f in fastas.values(): f.close()\n\ndef merge_fastas(fnames, name=\"merged\"):\n outfile = file(name+\".phy\", \"w\")\n gene2len = {}\n d = defaultdict(dict)\n for fn in fnames:\n gene = fn.split(\".\")[0]\n for rec in SeqIO.parse(file(fn), \"fasta\"):\n #sp = \"_\".join(rec.id.split(\"_\")[:2])\n if rec.id.startswith(\"Pedicularis\"):\n sp = rec.id.split(\"_\")[1]\n else:\n sp = rec.id.split(\"_\")[0]\n sp = \"_\".join(rec.id.split(\"_\")[:-1])\n seq = str(rec.seq)\n d[sp][gene] = seq\n if gene not in gene2len:\n gene2len[gene] = len(seq)\n\n ntax = len(d)\n nchar = sum(gene2len.values())\n outfile.write(\"%s %s\\n\" % (ntax, nchar))\n genes = list(sorted(gene2len.keys()))\n for sp, data in sorted(d.items()):\n s = \"\".join([ (data.get(gene) or \"\".join([\"?\"]*gene2len[gene]))\n for gene in genes ])\n outfile.write(\"%s %s\\n\" % (sp, s))\n outfile.close()\n parts = file(name+\".partitions\", \"w\")\n i = 1\n for g in genes:\n n = gene2len[g]\n parts.write(\"DNA, %s = %s-%s\\n\" % (g, i, i+n-1))\n i += n\n parts.close()\n\ndef blast_closest(fasta, e=10):\n f = NCBIWWW.qblast(\"blastn\", \"nr\", fasta, expect=e, hitlist_size=1)\n rec = NCBIXML.read(f)\n d = rec.descriptions[0]\n result = Storage()\n gi = re.findall(r'gi[|]([0-9]+)', d.title) or None\n if gi: result.gi = int(gi[0])\n ac = re.findall(r'gb[|]([^|]+)', d.title) or None\n if ac: result.ac = ac[0].split(\".\")[0]\n result.title = d.title.split(\"|\")[-1].strip()\n return result\n\ndef blast(query, e=10, n=100, entrez_query=\"\"):\n f = NCBIWWW.qblast(\"blastn\", \"nr\", query, expect=e, hitlist_size=n,\n entrez_query=entrez_query)\n recs = NCBIXML.parse(f)\n return recs\n ## v = []\n ## for d in rec.descriptions:\n ## result = Storage()\n ## gi = re.findall(r'gi[|]([0-9]+)', d.title) or None\n ## if gi: result.gi = int(gi[0])\n ## ac = re.findall(r'gb[|]([^|]+)', d.title) or None\n ## if ac: result.ac = ac[0].split(\".\")[0]\n ## result.title = d.title.split(\"|\")[-1].strip()\n ## v.append(result)\n ## return v\n\ndef start_codons(seq):\n i = seq.find('ATG')\n while i != -1:\n yield i\n i = seq.find('ATG', i+3)\n\ndef search_taxonomy(q):\n global email\n assert email, \"set email!\"\n Entrez.email = email\n h = Entrez.esearch(db=\"taxonomy\", term=q)\n return Entrez.read(h)['IdList']\n\ndef fetchtax(taxid):\n global email\n assert email, \"set email!\"\n Entrez.email = email\n n = 1\n if not isinstance(taxid, int):\n # string, possibly with multiple values?\n try:\n taxid = taxid.strip()\n n = taxid.count(',') + 1\n except AttributeError:\n # iterable of values?\n try:\n n = len(taxid)\n taxid = ','.join(map(str, taxid))\n except TypeError:\n pass\n else:\n taxid = str(taxid)\n h = Entrez.efetch(db='taxonomy', id=taxid, retmode='xml', retmax=n)\n if n == 1:\n r = Entrez.read(h)[0]\n else:\n # a list of taxonomy results in same order of taxids\n r = Entrez.read(h)\n return r\n\n__FIRST = re.compile('[^-]')\n__LAST = re.compile('[-]*$')\ndef trimpos(rec):\n 'return the positions of the first and last ungapped base'\n s = rec.seq.tostring()\n first = __FIRST.search(s).start()\n last = __LAST.search(s).start()-1\n return (first, last)\n\ndef fetch_DNA_seqs(terms, maxn=10000, batchsize=1000):\n \"\"\"\n terms: sequence of search terms, quoted appropriately, with Entrez\n specifiers, e.g. ['\"Mus musculus\"[organism]']\n maxn: maximum number of sequences to return\n returns list of SeqRecord objects\n \"\"\"\n global email\n assert email, \"set email!\"\n Entrez.email = email\n h = Entrez.esearch(db=\"nucleotide\", term=\" OR \".join(terms), usehistory=\"y\")\n d = Entrez.read(h)\n env = d['WebEnv']; key = d['QueryKey']\n N = int(d['Count'])\n if maxn: N = min(N, maxn)\n logging.info('fetching %s sequences', N)\n retstart = 0\n seqs = []\n n = 0\n while n < N:\n h = Entrez.efetch(\n db=\"nucleotide\", rettype='gb', webenv=env, query_key=key,\n retstart=retstart, retmax=batchsize\n )\n v = list(SeqIO.parse(h, \"genbank\"))\n n += len(v)\n logging.info('...fetched %s', n)\n seqs.extend(v)\n retstart += batchsize\n logging.info('...done')\n return seqs\n\ndef seqrec_taxid(seqrec):\n \"extract the NCBI taxon id from a sequence record\"\n for ft in seqrec.features:\n if ft.type == 'source':\n break\n try:\n for x in ft.qualifiers['db_xref']:\n if x.startswith('taxon:'):\n return int(x.split(':')[1])\n except:\n pass\n", "ivy/interactive.py": "#!/usr/bin/env ipython\n# -*- coding: utf-8 -*-\n\"\"\"\nAdds to the interactive IPython/pylab environment\n\"\"\"\nimport sys, os, re\nimport ivy\nimport ivy.vis\nfrom ivy.vis import symbols\n\ndef readtree(data, *args, **kwargs): return ivy.tree.read(data, *args, **kwargs)\n\ndef readaln(data, *args, **kwargs): return ivy.align.read(data, *args, **kwargs)\n\ndef treefig(*args, **kwargs):\n from ivy.vis import TreeFigure, MultiTreeFigure\n if len(args) == 1:\n fig = TreeFigure(args[0], **kwargs)\n else:\n fig = MultiTreeFigure(**kwargs)\n for arg in args:\n print arg\n fig.add(arg)\n fig.show()\n return fig\n\ndef alnfig(*args, **kwargs):\n from ivy.vis import AlignmentFigure\n return AlignmentFigure(*args, **kwargs)\n\ndef __maketree(self, s):\n import os#, IPython\n words = s.split()\n treename = \"root\"\n fname = None\n if words:\n treename = words.pop(0)\n if words and os.path.isfile(words[0]):\n fname = words.pop(0)\n\n if not fname:\n ## msg = \"\\n\".join([\n ## \"Name of tree file\",\n ## \"(Try dragging one into the terminal):\\n\"\n ## ])\n msg = \"Enter the name of a tree file or a newick string:\\n\"\n fname = raw_input(msg).strip()\n\n quotes = [\"'\", '\"']\n if fname and fname[0] in quotes:\n fname = fname[1:]\n if fname and fname[-1] in quotes:\n fname = fname[:-1]\n if fname:\n try:\n ## root = ivy.tree.read(fname)\n ## IPython.ipapi.get().to_user_ns({treename:root})\n cmd = \"%s = ivy.tree.read('%s')\" % (treename, fname)\n get_ipython().ex(cmd)\n print \"Tree parsed and assigned to variable '%s'\" % treename\n except:\n print \"Unable to parse tree file '%s'\" % fname\n else:\n print \"Cancelled\"\n\ndef __node_completer(self, event):\n symbol = event.symbol\n s = event.line\n if symbol:\n s = s[:-len(symbol)]\n quote = \"\"\n if s and s[-1] in [\"'\", '\"']:\n quote = s[-1]\n s = s[:-1]\n #base = (re.findall(r'(\\w+)\\[\\Z', s) or [None])[-1]\n base = \"\".join((re.findall(r'(\\w+\\.\\w*)?(\\.)?(\\w+)\\[\\Z', s) or [\"\"])[-1])\n ## print \"symbol:\", symbol\n ## print \"line:\", event.line\n ## print \"s:\", s\n ## print \"quote:\", quote\n ## print \"base:\", base\n ## print \"obj:\", self._ofind(base).get(\"obj\")\n\n obj = None\n if base:\n obj = self._ofind(base).get(\"obj\")\n ## print '\\n'\n ## print 'base', base\n ## print 'obj', obj\n if obj and isinstance(obj, ivy.tree.Node):\n completions = [\"'\"]\n if quote:\n completions = sorted([ x.label for x in obj.labeled() ])\n return completions\n\n raise IPython.core.error.TryNext()\n\ntry:\n ## import IPython\n IP = get_ipython() #IPython.ipapi.get()\n IP.magic('matplotlib')\n if IP:\n #IP.expose_magic(\"maketree\", __maketree)\n IP.define_magic(\"maketree\", __maketree)\n ## IP.set_hook(\n ## \"complete_command\", __node_completer, re_key=r'\\[*'\n ## )\n IP.set_hook(\n \"complete_command\", __node_completer,\n re_key='.+[[]([\\']|[\"])*\\w*$'\n )\n\nexcept:\n print sys.exc_info()[0]\n sys.stderr.write(\"Magic commands and completers requires IPython >= 0.11\\n\")\n\n## if __name__ == \"__main__\":\n## if len(sys.argv) > 1:\n## for fname in sys.argv[1:]:\n## if os.path.isfile(fname):\n## execfile(fname)\n", "ivy/layout.py": "\"\"\"\nlayout nodes in 2d space\n\nThe function of interest is `calc_node_positions` (aka nodepos)\n\"\"\"\nimport numpy\n\nclass Coordinates:\n \"\"\"\n Coordinates class for storing xy coordinates\n \"\"\"\n def __init__(self, x=0, y=0):\n self.x = x\n self.y = y\n\n def __repr__(self):\n return \"Coordinates(%g, %g)\" % (self.x, self.y)\n\n def point(self):\n return (self.x, self.y)\n\ndef smooth_xpos(node, n2coords):\n \"\"\"\n RR: What does smoothing do? -CZ\n \"\"\"\n if not node.isleaf:\n children = node.children\n for ch in children:\n smooth_xpos(ch, n2coords)\n\n if node.parent:\n px = n2coords[node.parent].x\n cx = min([ n2coords[ch].x for ch in children ])\n n2coords[node].x = (px + cx)/2.0\n\ndef depth_length_preorder_traversal(node, n2coords=None, isroot=False):\n \"\"\"\n Calculate node depth (root = depth 0) and length to root\n\n Args:\n node (Node): A node object\n\n Returns:\n dict: Mapping of nodes to coordinate objects. Coordinate\n objects have attributes \"depth\" and \"length_to_root\"\n \"\"\"\n if n2coords is None:\n n2coords = {}\n coords = n2coords.get(node) or Coordinates()\n coords.node = node\n if (not node.parent) or isroot:\n coords.depth = 0\n coords.length_to_root = 0.0\n else:\n try:\n p = n2coords[node.parent]\n coords.depth = p.depth + 1\n coords.length_to_root = p.length_to_root + (node.length or 0.0)\n except KeyError:\n print node.label, node.parent.label\n except AttributeError:\n coords.depth = 0\n coords.length_to_root = 0\n n2coords[node] = coords\n\n for ch in node.children:\n depth_length_preorder_traversal(ch, n2coords, False)\n\n return n2coords\n\ndef calc_node_positions(node, width, height,\n lpad=0, rpad=0, tpad=0, bpad=0,\n scaled=True, smooth=True, n2coords=None):\n \"\"\"\n Calculate where nodes should be positioned in 2d space for drawing a tree\n\n Args:\n node (Node): A (root) node\n width (float): The width of the canvas\n height (float): The height of the canvas\n lpad, rpad, tpad, bpad (float): Padding on the edges of the canvas.\n Optional, defaults to 0.\n scaled (bool): Whether or not the tree is scaled. Optional, defaults to\n True.\n smooth (bool): Whether or not to smooth the tree. Optional, defaults to\n True.\n Returns:\n dict: Mapping of nodes to Coordinates object\n Notes:\n Origin is at upper left\n \"\"\"\n width -= (lpad + rpad)\n height -= (tpad + bpad)\n\n if n2coords is None:\n n2coords = {}\n depth_length_preorder_traversal(node, n2coords=n2coords)\n leaves = node.leaves()\n nleaves = len(leaves)\n maxdepth = max([ n2coords[lf].depth for lf in leaves ])\n unitwidth = width/float(maxdepth)\n unitheight = height/(nleaves-1.0)\n\n xoff = (unitwidth * 0.5)\n yoff = (unitheight * 0.5)\n\n if scaled:\n maxlen = max([ n2coords[lf].length_to_root for lf in leaves ])\n scale = width/maxlen\n\n for i, lf in enumerate(leaves):\n c = n2coords[lf]\n c.y = i * unitheight\n if not scaled:\n c.x = width\n else:\n c.x = c.length_to_root * scale\n\n for n in node.postiter():\n c = n2coords[n]\n if (not n.isleaf) and n.children:\n children = n.children\n ymax = n2coords[children[0]].y\n ymin = n2coords[children[-1]].y\n c.y = (ymax + ymin)/2.0\n if not scaled:\n c.x = min([ n2coords[ch].x for ch in children ]) - unitwidth\n else:\n c.x = c.length_to_root * scale\n\n if (not scaled) and smooth:\n for i in range(10):\n smooth_xpos(node, n2coords)\n\n for coords in n2coords.values():\n coords.x += lpad\n coords.y += tpad\n\n for n, coords in n2coords.items():\n if n.parent:\n p = n2coords[n.parent]\n coords.px = p.x; coords.py = p.y\n else:\n coords.px = None; coords.py = None\n\n return n2coords\n\nnodepos = calc_node_positions\n\ndef cartesian(node, xscale=1.0, leafspace=None, scaled=True, n2coords=None,\n smooth=0, array=numpy.array, ones=numpy.ones, yunit=None):\n \"\"\"\n RR: What is the difference between this function and calc_node_positions?\n Is it being used anywhere? -CZ\n \"\"\"\n\n if n2coords is None:\n n2coords = {}\n\n depth_length_preorder_traversal(node, n2coords, True)\n leaves = node.leaves()\n nleaves = len(leaves)\n\n # leafspace is a vector that should sum to nleaves\n if leafspace is None:\n try: leafspace = [ float(x.leafspace) for x in leaves ]\n except: leafspace = numpy.zeros((nleaves,))\n assert len(leafspace) == nleaves\n #leafspace = array(leafspace)/(sum(leafspace)/float(nleaves))\n\n maxdepth = max([ n2coords[lf].depth for lf in leaves ])\n depth = maxdepth * xscale\n #if not yunit: yunit = 1.0/nleaves\n yunit = 1.0\n\n if scaled:\n maxlen = max([ n2coords[lf].length_to_root for lf in leaves ])\n depth = maxlen\n\n y = 0\n for i, lf in enumerate(leaves):\n c = n2coords[lf]\n yoff = 1 + (leafspace[i] * yunit)\n c.y = y + yoff*0.5\n y += yoff\n if not scaled:\n c.x = depth\n else:\n c.x = c.length_to_root\n\n for n in node.postiter():\n c = n2coords[n]\n if not n.isleaf:\n children = n.children\n v = [n2coords[children[0]].y, n2coords[children[-1]].y]\n v.sort()\n ymin, ymax = v\n c.y = (ymax + ymin)/2.0\n if not scaled:\n c.x = min([ n2coords[ch].x for ch in children ]) - 1.0\n else:\n c.x = c.length_to_root\n\n if not scaled:\n for i in range(smooth):\n smooth_xpos(node, n2coords)\n\n return n2coords\n\nif __name__ == \"__main__\":\n import tree\n node = tree.read(\"(a:3,(b:2,(c:4,d:5):1,(e:3,(f:1,g:1):2):2):2);\")\n for i, n in enumerate(node.iternodes()):\n if not n.isleaf:\n n.label = \"node%s\" % i\n node.label = \"root\"\n n2c = calc_node_positions(node, width=10, height=10, scaled=True)\n\n from pprint import pprint\n pprint(n2c)\n", "ivy/ltt.py": "\"\"\"\nCompute lineages through time\n\"\"\"\nimport numpy\n\n# RR: Should results be set to None and then defined in the function to avoid\n# problems with mutable defaults in functions? -CZ\ndef traverse(node, t=0, results=[]):\n \"\"\"\n Recursively traverse the tree and collect information about when\n nodes split and how many lineages are added by its splitting.\n \"\"\"\n if node.children:\n ## if not node.label:\n ## node.label = str(node.id)\n results.append((t, len(node.children)-1))\n for child in node.children:\n traverse(child, t+child.length, results)\n return results\n\ndef ltt(node):\n \"\"\"\n Calculate lineages through time. The tree is assumed to be an\n ultrametric chronogram (extant leaves, with branch lengths\n proportional to time).\n\n Args:\n node (Node): A node object. All nodes should have branch lengths.\n\n Returns:\n tuple: (times, diversity) - 1D-arrays containing the results.\n \"\"\"\n v = traverse(node) # v is a list of (time, diversity) values\n v.sort()\n # for plotting, it is easiest if x and y values are in separate\n # sequences, so we create a transposed array from v\n times, diversity = numpy.array(v).transpose()\n return times, diversity.cumsum()\n\ndef test():\n import newick, ascii\n n = newick.parse(\"(((a:1,b:2):3,(c:3,d:1):1,(e:0.5,f:3):2.5):1,g:4);\")\n v = ltt(n)\n print ascii.render(n, scaled=1)\n for t, n in v:\n print t, n\n\nif __name__ == \"__main__\":\n test()\n", "ivy/newick.py": "\"\"\"\nParse newick strings.\n\nThe function of interest is `parse`, which returns the root node of\nthe parsed tree.\n\"\"\"\nimport string, sys, re, shlex, types, itertools\nimport numpy\nimport nexus\nfrom cStringIO import StringIO\nfrom pprint import pprint\n\n## def read(s):\n## try:\n## s = file(s).read()\n## except:\n## try:\n## s = s.read()\n## except:\n## pass\n## return parse(s)\n\nLABELCHARS = '-.|/?#&'\nMETA = re.compile(r'([^,=\\s]+)\\s*=\\s*(\\{[^=}]*\\}|\"[^\"]*\"|[^,]+)?')\n\ndef add_label_chars(chars):\n global LABELCHARS\n LABELCHARS += chars\n\nclass Tokenizer(shlex.shlex):\n \"\"\"Provides tokens for parsing newick strings.\"\"\"\n def __init__(self, infile):\n global LABELCHARS\n shlex.shlex.__init__(self, infile, posix=False)\n self.commenters = ''\n self.wordchars = self.wordchars+LABELCHARS\n self.quotes = \"'\"\n\n def parse_embedded_comment(self):\n ws = self.whitespace\n self.whitespace = \"\"\n v = []\n while 1:\n token = self.get_token()\n if token == '':\n sys.stdout.write('EOF encountered mid-comment!\\n')\n break\n elif token == ']':\n break\n elif token == '[':\n self.parse_embedded_comment()\n else:\n v.append(token)\n self.whitespace = ws\n return \"\".join(v)\n ## print \"comment:\", v\n\ndef parse(data, ttable=None, treename=None):\n \"\"\"\n Parse a newick string.\n\n Args:\n data: Any file-like object that can be coerced into shlex, or\n a string (converted to StringIO)\n ttable (dict): Mapping of node labels in the newick string\n to other values.\n\n Returns:\n Node: The root node.\n \"\"\"\n from tree import Node\n\n if type(data) in types.StringTypes:\n data = StringIO(data)\n\n start_pos = data.tell()\n tokens = Tokenizer(data)\n\n node = None; root = None\n lp=0; rp=0; rooted=1\n\n previous = None\n\n ni = 0 # node id counter (preorder) - zero-based indexing\n li = 0 # leaf index counter\n ii = 0 # internal node index counter\n pi = 0 # postorder sequence\n while 1:\n token = tokens.get_token()\n #print token,\n if token == ';' or token == tokens.eof:\n assert lp == rp, \\\n \"unbalanced parentheses in tree description: (%s, %s)\" \\\n % (lp, rp)\n break\n\n # internal node\n elif token == '(':\n lp = lp+1\n newnode = Node()\n newnode.ni = ni; ni += 1\n newnode.isleaf = False\n newnode.ii = ii; ii += 1\n newnode.treename = treename\n if node:\n if node.children: newnode.left = node.children[-1].right+1\n else: newnode.left = node.left+1\n node.add_child(newnode)\n else:\n newnode.left = 1; newnode.right = 2\n newnode.right = newnode.left+1\n node = newnode\n\n elif token == ')':\n rp = rp+1\n node = node.parent\n node.pi = pi; pi += 1\n if node.children:\n node.right = node.children[-1].right + 1\n\n elif token == ',':\n node = node.parent\n if node.children:\n node.right = node.children[-1].right + 1\n\n # branch length\n elif token == ':':\n token = tokens.get_token()\n if token == '[':\n node.length_comment = tokens.parse_embedded_comment()\n token = tokens.get_token()\n\n if not (token == ''):\n try: brlen = float(token)\n except ValueError:\n raise ValueError, (\"invalid literal for branch length, \"\n \"'%s'\" % token)\n else:\n raise 'NewickError', \\\n 'unexpected end-of-file (expecting branch length)'\n\n node.length = brlen\n # comment\n elif token == '[':\n node.comment = tokens.parse_embedded_comment()\n if node.comment[0] == '&':\n # metadata\n meta = META.findall(node.comment[1:])\n if meta:\n for k, v in meta:\n v = eval(v.replace('{','(').replace('}',')'))\n node.meta[k] = v\n\n # leaf node or internal node label\n else:\n if previous != ')': # leaf node\n if ttable:\n try:\n ttoken = (ttable.get(int(token)) or\n ttable.get(token))\n except ValueError:\n ttoken = ttable.get(token)\n if ttoken:\n token = ttoken\n newnode = Node()\n newnode.ni = ni; ni += 1\n newnode.pi = pi; pi += 1\n newnode.label = \"_\".join(token.split()).replace(\"'\", \"\")\n newnode.isleaf = True\n newnode.li = li; li += 1\n if node.children: newnode.left = node.children[-1].right+1\n else: newnode.left = node.left+1\n newnode.right = newnode.left+1\n newnode.treename = treename\n node.add_child(newnode)\n node = newnode\n else: # label\n if ttable:\n node.label = ttable.get(token, token)\n else:\n node.label = token\n\n previous = token\n node.isroot = True\n return node\n\n## def string(node, length_fmt=\":%s\", end=True, newline=True):\n## \"Recursively create a newick string from node.\"\n## if not node.isleaf:\n## node_str = \"(%s)%s\" % \\\n## (\",\".join([ string(child, length_fmt, False, newline) \\\n## for child in node.children ]),\n## node.label or \"\"\n## )\n## else:\n## node_str = \"%s\" % node.label\n\n## if node.length is not None:\n## length_str = length_fmt % node.length\n## else:\n## length_str = \"\"\n\n## semicolon = \"\"\n## if end:\n## if not newline:\n## semicolon = \";\"\n## else:\n## semicolon = \";\\n\"\n## s = \"%s%s%s\" % (node_str, length_str, semicolon)\n## return s\n\n## def from_nexus(infile, bufsize=None):\n## bufsize = bufsize or 1024*5000\n## TTABLE = re.compile(r'\\btranslate\\s+([^;]+);', re.I | re.M)\n## TREE = re.compile(r'\\btree\\s+([_.\\w]+)\\s*=[^(]+(\\([^;]+;)', re.I | re.M)\n## s = infile.read(bufsize)\n## ttable = TTABLE.findall(s) or None\n## if ttable:\n## items = [ shlex.split(line) for line in ttable[0].split(\",\") ]\n## ttable = dict([ (k, v.replace(\" \", \"_\")) for k, v in items ])\n## trees = TREE.findall(s)\n## ## for i, t in enumerate(trees):\n## ## t = list(t)\n## ## if ttable:\n## ## t[1] = \"\".join(\n## ## [ ttable.get(x, \"_\".join(x.split()).replace(\"'\", \"\"))\n## ## for x in shlex.shlex(t[1]) ]\n## ## )\n## ## trees[i] = t\n## ## return trees\n## return ttable, trees\n\ndef parse_ampersand_comment(s):\n import pyparsing\n pyparsing.ParserElement.enablePackrat()\n from pyparsing import Word, Literal, QuotedString, CaselessKeyword, \\\n OneOrMore, Group, Optional, Suppress, Regex, Dict\n word = Word(string.letters+string.digits+\"%_\")\n key = word.setResultsName(\"key\") + Suppress(\"=\")\n single_value = (Word(string.letters+string.digits+\"-.\") |\n QuotedString(\"'\") |\n QuotedString('\"'))\n range_value = Group(Suppress(\"{\") +\n single_value.setResultsName(\"min\") +\n Suppress(\",\") +\n single_value.setResultsName(\"max\") +\n Suppress(\"}\"))\n pair = (key + (single_value | range_value).setResultsName(\"value\"))\n g = OneOrMore(pair)\n d = []\n for x in g.searchString(s):\n v = x.value\n if type(v) == str:\n try: v = float(v)\n except ValueError: pass\n else:\n try: v = map(float, v.asList())\n except ValueError: pass\n d.append((x.key, v))\n return d\n\ndef nexus_iter(infile):\n import pyparsing\n pyparsing.ParserElement.enablePackrat()\n from pyparsing import Word, Literal, QuotedString, CaselessKeyword, \\\n OneOrMore, Group, Optional, Suppress, Regex, Dict\n ## beginblock = Suppress(CaselessKeyword(\"begin\") +\n ## CaselessKeyword(\"trees\") + \";\")\n ## endblock = Suppress((CaselessKeyword(\"end\") |\n ## CaselessKeyword(\"endblock\")) + \";\")\n comment = Optional(Suppress(\"[&\") + Regex(r'[^]]+') + Suppress(\"]\"))\n ## translate = CaselessKeyword(\"translate\").suppress()\n name = Word(string.letters+string.digits+\"_.\") | QuotedString(\"'\")\n ## ttrec = Group(Word(string.digits).setResultsName(\"number\") +\n ## name.setResultsName(\"name\") +\n ## Optional(\",\").suppress())\n ## ttable = Group(translate + OneOrMore(ttrec) + Suppress(\";\"))\n newick = Regex(r'[^;]+;')\n tree = (CaselessKeyword(\"tree\").suppress() +\n Optional(\"*\").suppress() +\n name.setResultsName(\"tree_name\") +\n comment.setResultsName(\"tree_comment\") +\n Suppress(\"=\") +\n comment.setResultsName(\"root_comment\") +\n newick.setResultsName(\"newick\"))\n ## treesblock = Group(beginblock +\n ## Optional(ttable.setResultsName(\"ttable\")) +\n ## Group(OneOrMore(tree)) +\n ## endblock)\n\n def not_begin(s): return s.strip().lower() != \"begin trees;\"\n def not_end(s): return s.strip().lower() not in (\"end;\", \"endblock;\")\n def parse_ttable(f):\n ttable = {}\n while True:\n s = f.next().strip()\n if not s: continue\n if s.lower() == \";\": break\n if s[-1] == \",\": s = s[:-1]\n k, v = s.split()\n ttable[k] = v\n if s[-1] == \";\": break\n return ttable\n\n # read lines between \"begin trees;\" and \"end;\"\n f = itertools.takewhile(not_end, itertools.dropwhile(not_begin, infile))\n s = f.next().strip().lower()\n if s != \"begin trees;\":\n print sys.stderr, \"Expecting 'begin trees;', got %s\" % s\n raise StopIteration\n ttable = {}\n while True:\n try: s = f.next().strip()\n except StopIteration: break\n if not s: continue\n if s.lower() == \"translate\":\n ttable = parse_ttable(f)\n print \"ttable: %s\" % len(ttable)\n elif s.split()[0].lower()=='tree':\n match = tree.parseString(s)\n yield nexus.Newick(match, ttable)\n\n## def test():\n## with open(\"/home/rree/Dropbox/pedic-comm-amnat/phylo/beast-results/\"\n## \"simple_stigma.trees.log\") as f:\n## for rec in nexus_iter(f):\n## r = parse(rec.newick, ttable=rec.ttable)\n## for x in r: print x, x.comments\n\ndef test_parse_comment():\n v = ((\"height_median=1.1368683772161603E-13,height=9.188229043880098E-14,\"\n \"height_95%_HPD={5.6843418860808015E-14,1.7053025658242404E-13},\"\n \"height_range={0.0,2.8421709430404007E-13}\"),\n \"R\", \"lnP=-154.27154502342688,lnP=-24657.14341301901\",\n 'states=\"T-lateral\"')\n for s in v:\n print \"input:\", s\n print dict(parse_ampersand_comment(s))\n", "ivy/nexus.py": "import itertools\nfrom collections import defaultdict\nimport newick\n\nclass Newick(object):\n \"\"\"\n convenience class for storing the results of a newick tree\n record from a nexus file, as parsed by newick.nexus_iter\n \"\"\"\n def __init__(self, parse_results=None, ttable={}):\n self.name = \"\"\n self.comment = \"\"\n self.root_comment = \"\"\n self.newick = \"\"\n self.ttable = ttable\n if parse_results: self.populate(parse_results)\n\n def populate(self, parse_results, ttable={}):\n self.name = parse_results.tree_name\n self.comment = parse_results.tree_comment\n self.root_comment = parse_results.root_comment\n self.newick = parse_results.newick\n if ttable: self.ttable = ttable\n\n def parse(self, newick=newick):\n assert self.newick\n self.root = newick.parse(\n self.newick, ttable=self.ttable, treename=self.name\n )\n return self.root\n\ndef fetchaln(fname):\n \"\"\"Fetch alignment\"\"\"\n from Bio.Nexus import Nexus\n n = Nexus.Nexus(fname)\n return n\n\ndef split_blocks(infile):\n from cStringIO import StringIO\n dropwhile = itertools.dropwhile; takewhile = itertools.takewhile\n blocks = []\n not_begin = lambda s: not s.lower().startswith(\"begin\")\n not_end = lambda s: not s.strip().lower() in (\"end;\", \"endblock;\")\n while 1:\n f = takewhile(not_end, dropwhile(not_begin, infile))\n try:\n b = f.next().split()[-1][:-1]\n blocks.append((b, StringIO(\"\".join(list(f)))))\n except StopIteration:\n break\n return blocks\n\ndef parse_treesblock(infile):\n import string\n from pyparsing import Optional, Word, Regex, CaselessKeyword, Suppress\n from pyparsing import QuotedString\n comment = Optional(Suppress(\"[&\") + Regex(r'[^]]+') + Suppress(\"]\"))\n name = Word(string.letters+string.digits+\"_\") | QuotedString(\"'\")\n newick = Regex(r'[^;]+;')\n tree = (CaselessKeyword(\"tree\").suppress() +\n Optional(\"*\").suppress() +\n name.setResultsName(\"tree_name\") +\n comment.setResultsName(\"tree_comment\") +\n Suppress(\"=\") +\n comment.setResultsName(\"root_comment\") +\n newick.setResultsName(\"newick\"))\n ## treesblock = Group(beginblock +\n ## Optional(ttable.setResultsName(\"ttable\")) +\n ## Group(OneOrMore(tree)) +\n ## endblock)\n\n def parse_ttable(f):\n ttable = {}\n while True:\n s = f.next().strip()\n if s.lower() == \";\": break\n if s[-1] in \",;\": s = s[:-1]\n k, v = s.split()\n ttable[k] = v\n if s[-1] == \";\": break\n return ttable\n\n ttable = {}\n while True:\n try: s = infile.next().strip()\n except StopIteration: break\n if s.lower() == \"translate\":\n ttable = parse_ttable(infile)\n print \"ttable: %s\" % len(ttable)\n else:\n match = tree.parseString(s)\n yield Newick(match, ttable)\n", "ivy/sequtil.py": "from itertools import izip, imap\nimport numpy\n\ndef finditer(seq, substr, start=0):\n \"\"\"\n Find substrings within a sequence\n\n Args:\n seq (str): A sequence.\n substr (str): A subsequence to search for\n start (int): Starting index. Defaults to 0\n Yields:\n int: Starting indicies of where the substr was found in seq\n \"\"\"\n N = len(substr)\n i = seq.find(substr, start)\n while i >= 0:\n yield i\n i = seq.find(substr, i+N)\n\ndef gapidx(seq, gapchar='-'):\n \"\"\"\n For a sequence with gaps, calculate site positions without gaps\n\n Args:\n seq (list): Each element of the list is one character in a sequence.\n gapchar (str): The character gaps are coded as. Defaults to '-'\n Returns:\n array: An array where the first element corresponds to range(number of\n characters that are not gaps) and the second element is the indicies\n of all characters that are not gaps.\n \"\"\"\n a = numpy.array(seq)\n idx = numpy.arange(len(a))\n nongap = idx[a != gapchar]\n return numpy.array((numpy.arange(len(nongap)), nongap))\n\ndef find_stop_codons(seq, pos=0):\n \"\"\"\n Find stop codons within sequence (in reading frame)\n\n Args:\n seq (str): A sequence\n pos (int): Starting position. Defaults to 0.\n Yields:\n tuple: The index where the stop codon starts\n and which stop codon was found.\n \"\"\"\n s = seq[pos:]\n it = iter(s)\n g = imap(lambda x:\"\".join(x), izip(it, it, it))\n for i, x in enumerate(g):\n if x in (\"TAG\", \"TAA\", \"TGA\"):\n yield pos+(i*3), x\n", "ivy/storage.py": "from operator import itemgetter\nfrom heapq import nlargest\nfrom itertools import repeat, ifilter\n\nclass Storage(dict):\n \"\"\"\n A Storage object is like a dictionary except `obj.foo` can be used\n in addition to `obj['foo']`.\n\n From web2py/gluon/storage.py by Massimo Di Pierro (www.web2py.com)\n \"\"\"\n def __getattr__(self, key):\n try:\n return self[key]\n except KeyError:\n return None\n\n def __setattr__(self, key, value):\n self[key] = value\n\n def __delattr__(self, key):\n try:\n del self[key]\n except KeyError, k:\n raise AttributeError, k\n\n def __repr__(self):\n return ''\n\n def __getstate__(self):\n return dict(self)\n\n def __setstate__(self, value):\n for (k, v) in value.items():\n self[k] = v\n\nclass MaxDict(dict):\n def __setitem__(self, key, value):\n v = self.get(key)\n if value > v:\n dict.__setitem__(self, key, value)\n \n#from http://code.activestate.com/recipes/576611/\nclass Counter(dict):\n \"\"\"Dict subclass for counting hashable objects. Sometimes called a bag\n or multiset. Elements are stored as dictionary keys and their counts\n are stored as dictionary values.\n\n >>> Counter('zyzygy')\n Counter({'y': 3, 'z': 2, 'g': 1})\n\n \"\"\"\n\n def __init__(self, iterable=None, **kwds):\n \"\"\"Create a new, empty Counter object. And if given, count elements\n from an input iterable. Or, initialize the count from another mapping\n of elements to their counts.\n\n >>> c = Counter() # a new, empty counter\n >>> c = Counter('gallahad') # a new counter from an iterable\n >>> c = Counter({'a': 4, 'b': 2}) # a new counter from a mapping\n >>> c = Counter(a=4, b=2) # a new counter from keyword args\n\n \"\"\" \n self.update(iterable, **kwds)\n\n def __missing__(self, key):\n return 0\n\n def most_common(self, n=None):\n \"\"\"List the n most common elements and their counts from the most\n common to the least. If n is None, then list all element counts.\n\n >>> Counter('abracadabra').most_common(3)\n [('a', 5), ('r', 2), ('b', 2)]\n\n \"\"\" \n if n is None:\n return sorted(self.iteritems(), key=itemgetter(1), reverse=True)\n return nlargest(n, self.iteritems(), key=itemgetter(1))\n\n def elements(self):\n \"\"\"Iterator over elements repeating each as many times as its count.\n\n >>> c = Counter('ABCABC')\n >>> sorted(c.elements())\n ['A', 'A', 'B', 'B', 'C', 'C']\n\n If an element's count has been set to zero or is a negative number,\n elements() will ignore it.\n\n \"\"\"\n for elem, count in self.iteritems():\n for _ in repeat(None, count):\n yield elem\n\n # Override dict methods where the meaning changes for Counter objects.\n\n @classmethod\n def fromkeys(cls, iterable, v=None):\n raise NotImplementedError(\n 'Counter.fromkeys() is undefined. Use Counter(iterable) instead.')\n\n def update(self, iterable=None, **kwds):\n \"\"\"Like dict.update() but add counts instead of replacing them.\n\n Source can be an iterable, a dictionary, or another Counter instance.\n\n >>> c = Counter('which')\n >>> c.update('witch') # add elements from another iterable\n >>> d = Counter('watch')\n >>> c.update(d) # add elements from another counter\n >>> c['h'] # four 'h' in which, witch, and watch\n 4\n\n \"\"\" \n if iterable is not None:\n if hasattr(iterable, 'iteritems'):\n if self:\n self_get = self.get\n for elem, count in iterable.iteritems():\n self[elem] = self_get(elem, 0) + count\n else:\n dict.update(self, iterable) # fast path when counter is empty\n else:\n self_get = self.get\n for elem in iterable:\n self[elem] = self_get(elem, 0) + 1\n if kwds:\n self.update(kwds)\n\n def copy(self):\n 'Like dict.copy() but returns a Counter instance instead of a dict.'\n return Counter(self)\n\n def __delitem__(self, elem):\n 'Like dict.__delitem__() but does not raise KeyError for missing values.'\n if elem in self:\n dict.__delitem__(self, elem)\n\n def __repr__(self):\n if not self:\n return '%s()' % self.__class__.__name__\n items = ', '.join(map('%r: %r'.__mod__, self.most_common()))\n return '%s({%s})' % (self.__class__.__name__, items)\n\n # Multiset-style mathematical operations discussed in:\n # Knuth TAOCP Volume II section 4.6.3 exercise 19\n # and at http://en.wikipedia.org/wiki/Multiset\n #\n # Outputs guaranteed to only include positive counts.\n #\n # To strip negative and zero counts, add-in an empty counter:\n # c += Counter()\n\n def __add__(self, other):\n \"\"\"Add counts from two counters.\n\n >>> Counter('abbb') + Counter('bcc')\n Counter({'b': 4, 'c': 2, 'a': 1})\n\n\n \"\"\"\n if not isinstance(other, Counter):\n return NotImplemented\n result = Counter()\n for elem in set(self) | set(other):\n newcount = self[elem] + other[elem]\n if newcount > 0:\n result[elem] = newcount\n return result\n\n def __sub__(self, other):\n \"\"\" Subtract count, but keep only results with positive counts.\n\n >>> Counter('abbbc') - Counter('bccd')\n Counter({'b': 2, 'a': 1})\n\n \"\"\"\n if not isinstance(other, Counter):\n return NotImplemented\n result = Counter()\n for elem in set(self) | set(other):\n newcount = self[elem] - other[elem]\n if newcount > 0:\n result[elem] = newcount\n return result\n\n def __or__(self, other):\n \"\"\"Union is the maximum of value in either of the input counters.\n\n >>> Counter('abbb') | Counter('bcc')\n Counter({'b': 3, 'c': 2, 'a': 1})\n\n \"\"\"\n if not isinstance(other, Counter):\n return NotImplemented\n _max = max\n result = Counter()\n for elem in set(self) | set(other):\n newcount = _max(self[elem], other[elem])\n if newcount > 0:\n result[elem] = newcount\n return result\n\n def __and__(self, other):\n \"\"\" Intersection is the minimum of corresponding counts.\n\n >>> Counter('abbb') & Counter('bcc')\n Counter({'b': 1})\n\n \"\"\"\n if not isinstance(other, Counter):\n return NotImplemented\n _min = min\n result = Counter()\n if len(self) < len(other):\n self, other = other, self\n for elem in ifilter(self.__contains__, other):\n newcount = _min(self[elem], other[elem])\n if newcount > 0:\n result[elem] = newcount\n return result\n\ndef convert(d):\n \"convert a (potentially nested) dict to Storage\"\n from types import DictType\n t = type(d)\n if t == DictType:\n for k,v in d.items():\n d[k] = convert(v)\n return Storage(d)\n return d\n\nif __name__ == '__main__':\n import doctest\n print doctest.testmod()\n", "ivy/tree.py": "\"\"\"\nThe Node class and functions for creating trees from Newick strings,\netc.\n\nivy does not have a Tree class per se, as most functions operate\ndirectly on Node objects.\n\"\"\"\nimport os, types\nfrom storage import Storage\nfrom copy import copy as _copy\nfrom matrix import vcv\nimport newick\nfrom itertools import izip_longest\n\n## class Tree(object):\n## \"\"\"\n## A simple Tree class.\n## \"\"\"\n## def __init__(self, data=None, format=\"newick\", name=None, ttable=None):\n## self.root = None\n## if data:\n## self.root = read(data, format, name, ttable)\n## self.name = name\n## self.ttable = ttable\n\n## def __getattribute__(self, a):\n## r = object.__getattribute__(self, 'root')\n## try:\n## return object.__getattribute__(r, a)\n## except AttributeError:\n## return object.__getattribute__(self, a)\n\ndef traverse(node):\n \"recursive preorder iterator based solely on .children attribute\"\n yield node\n for child in node.children:\n for descendant in traverse(child):\n yield descendant\n\nclass Node(object):\n \"\"\"\n A basic Node class with attributes and references to child nodes\n ('children', a list) and 'parent'.\n\n Keyword Args:\n id: ID of the node. If not provided, is set using\n builtin id function\n ni (int): Node index.\n li (int): Leaf index.\n isroot (bool): Is the node a root.\n isleaf (bool): Is the node a leaf.\n label (str): Node label.\n length (float): Branch length from node to parent\n support: RR: Are these bootstrap support values? -CZ\n age (float): Age of the node in time units.\n parent (Node): Parent of the ndoe.\n children (list): List of node objects. Children of node\n nchildren (int): No. of children\n left: RR: Unsure what left and right mean -CZ\n treename: Name of tree\n comment: Comments for tree\n\n \"\"\"\n def __init__(self, **kwargs):\n self.id = None\n self.ni = None # node index\n self.li = None # leaf index\n self.isroot = False\n self.isleaf = False\n self.label = None\n self.length = None\n self.support = None\n self.age = None\n self.parent = None\n self.children = []\n self.nchildren = 0\n self.left = None\n self.right = None\n self.treename = \"\"\n self.comment = \"\"\n self.meta = {}\n ## self.length_comment = \"\"\n ## self.label_comment = \"\"\n if kwargs:\n for k, v in kwargs.items():\n setattr(self, k, v)\n if self.id is None: self.id = id(self)\n\n def __copy__(self):\n return self.copy()\n\n def __repr__(self):\n v = []\n if self.isroot:\n v.append(\"root\")\n elif self.isleaf:\n v.append(\"leaf\")\n\n if self.label:\n v.append(\"'%s'\" % self.label)\n\n s = \", \".join(v)\n\n nid = ((self.id if (self.id is not None) else self.ni) or\n '<%s>' % id(self))\n if s:\n s = \"Node(%s, %s)\" % (nid, s)\n else:\n s = \"Node(%s)\" % nid\n return s\n\n\n def __contains__(self, other):\n \"\"\"\n For use with `in` keyword\n\n Args:\n other: Another node or node label.\n Returns:\n bool: Whether or not the other node is a descendant of self\n \"\"\"\n otype = type(other)\n if other and otype in types.StringTypes:\n for x in self:\n if other == x.label:\n return True\n return False\n else:\n assert otype == type(self)\n for x in self.iternodes():\n if other == x:\n return True\n return False\n\n def __iter__(self):\n for node in self.iternodes():\n yield node\n\n def __len__(self):\n \"\"\"\n Number of nodes descended from self\n\n Returns:\n int: Number of nodes descended from self (including self)\n \"\"\"\n i = 0\n for n in self:\n i += 1\n return i\n\n def __nonzero__(self):\n return True\n\n def __getitem__(self, x):\n \"\"\"\n Args:\n x: A Node, Node.id (int) or a Node.label (string)\n\n Returns:\n Node: Found node(s)\n\n \"\"\"\n for n in self:\n if n==x or n.id==x or n.ni == x or (n.label and n.label==x):\n return n\n raise IndexError(str(x))\n\n def ascii(self, *args, **kwargs):\n \"\"\"\n Create ascii tree.\n\n Keyword Args:\n unitlen (float): How long each unit should be rendered as.\n Defaults to 3.\n minwidth (float): Minimum width of the plot. Defaults to 50\n maxwidth (float): Maximum width of the plot. Defaults to None\n scaled (bool): Whether or not the tree is scaled. Defaults to False\n show_internal_labels (bool): Whether or not to show labels\n on internal nodes. Defaults to True.\n Returns:\n str: Ascii tree to be shown with print().\n \"\"\"\n from ascii import render\n return render(self, *args, **kwargs)\n\n def collapse(self, add=False):\n \"\"\"\n Remove self and collapse children to polytomy\n\n Args:\n add (bool): Whether or not to add self's length to children's\n length.\n\n Returns:\n Node: Parent of self\n\n \"\"\"\n assert self.parent\n p = self.prune()\n for c in self.children:\n p.add_child(c)\n if add and (c.length is not None):\n c.length += self.length\n self.children = []\n return p\n\n def copy(self, recurse=False):\n \"\"\"\n Return a copy of the node, but not copies of children, parent,\n or any attribute that is a Node.\n\n If `recurse` is True, recursively copy child nodes.\n\n Args:\n recurse (bool): Whether or not to copy children as well as self.\n\n Returns:\n Node: A copy of self.\n\n TODO: test this function.\n\n RR: This function runs rather slowly -CZ\n \"\"\"\n newnode = Node()\n for attr, value in self.__dict__.items():\n if (attr not in (\"children\", \"parent\") and\n not isinstance(value, Node)):\n setattr(newnode, attr, _copy(value))\n if recurse:\n newnode.children = [\n child.copy(True) for child in self.children\n ]\n return newnode\n\n def leafsets(self, d=None, labels=False):\n \"\"\"return a mapping of nodes to leaf sets (nodes or labels)\"\"\"\n d = d or {}\n if not self.isleaf:\n s = set()\n for child in self.children:\n if child.isleaf:\n if labels:\n s.add(child.label)\n else:\n s.add(child)\n else:\n d = child.leafsets(d, labels)\n s = s | d[child]\n d[self] = frozenset(s)\n return d\n\n def mrca(self, *nodes):\n \"\"\"\n Find most recent common ancestor of *nodes*\n\n Args:\n *nodes (Node): Node objects\n Returns:\n Node: The MRCA of *nodes*\n \"\"\"\n if len(nodes) == 1:\n nodes = tuple(nodes[0])\n if len(nodes) == 1:\n return nodes[0]\n nodes = set([ self[n] for n in nodes ])\n anc = []\n def f(n):\n seen = set()\n for c in n.children: seen.update(f(c))\n if n in nodes: seen.add(n)\n if seen == nodes and (not anc): anc.append(n)\n return seen\n f(self)\n return anc[0]\n\n ## def mrca(self, *nodes):\n ## \"\"\"\n ## Find most recent common ancestor of *nodes*\n ## \"\"\"\n ## if len(nodes) == 1:\n ## nodes = tuple(nodes[0])\n ## if len(nodes) == 1:\n ## return nodes[0]\n ## ## assert len(nodes) > 1, (\n ## ## \"Need more than one node for mrca(), got %s\" % nodes\n ## ## )\n ## def f(x):\n ## if isinstance(x, Node):\n ## return x\n ## elif type(x) in types.StringTypes:\n ## return self.find(x)\n ## nodes = map(f, nodes)\n ## assert all(filter(lambda x: isinstance(x, Node), nodes))\n\n ## #v = [ list(n.rootpath()) for n in nodes if n in self ]\n ## v = [ list(x) for x in izip_longest(*[ reversed(list(n.rootpath()))\n ## for n in nodes if n in self ]) ]\n ## if len(v) == 1:\n ## return v[0][0]\n ## anc = None\n ## for x in v:\n ## s = set(x)\n ## if len(s) == 1: anc = list(s)[0]\n ## else: break\n ## return anc\n\n def ismono(self, *leaves):\n \"\"\"\n Test if leaf descendants are monophyletic\n\n Args:\n *leaves (Node): At least two leaf Node objects\n\n Returns:\n bool: Are the leaf descendants monophyletic?\n\n RR: Should this function have a check to make sure the input nodes are\n leaves? There is some strange behavior if you input internal nodes -CZ\n \"\"\"\n if len(leaves) == 1:\n leaves = list(leaves)[0]\n assert len(leaves) > 1, (\n \"Need more than one leaf for ismono(), got %s\" % leaves\n )\n anc = self.mrca(leaves)\n if anc:\n return bool(len(anc.leaves())==len(leaves))\n\n def order_subtrees_by_size(self, n2s=None, recurse=False, reverse=False):\n \"\"\"\n Order interal clades by size\n\n \"\"\"\n if n2s is None:\n n2s = clade_sizes(self)\n if not self.isleaf:\n v = [ (n2s[c], c.label, c) for c in self.children ]\n v.sort()\n if reverse:\n v.reverse()\n self.children = [ x[-1] for x in v ]\n if recurse:\n for c in self.children:\n c.order_subtrees_by_size(n2s, recurse=True, reverse=reverse)\n\n def ladderize(self, reverse=False):\n self.order_subtrees_by_size(recurse=True, reverse=reverse)\n return self\n\n def add_child(self, child):\n \"\"\"\n Add child as child of self\n\n Args:\n child (Node): A node object\n\n \"\"\"\n assert child not in self.children\n self.children.append(child)\n child.parent = self\n child.isroot = False\n self.nchildren += 1\n\n def bisect_branch(self):\n \"\"\"\n Add new node as parent to self in the middle of branch to parent.\n\n Returns:\n Node: A new node.\n\n \"\"\"\n assert self.parent\n parent = self.prune()\n n = Node()\n if self.length:\n n.length = self.length/2.0\n self.length /= 2.0\n parent.add_child(n)\n n.add_child(self)\n return n\n\n def remove_child(self, child):\n \"\"\"\n Remove child.\n\n Args:\n child (Node): A node object that is a child of self\n\n \"\"\"\n assert child in self.children\n self.children.remove(child)\n child.parent = None\n self.nchildren -= 1\n if not self.children:\n self.isleaf = True\n\n def labeled(self):\n \"\"\"\n Return a list of all descendant nodes that are labeled\n\n Returns:\n list: All descendants of self that are labeled (including self)\n \"\"\"\n return [ n for n in self if n.label ]\n\n def leaves(self, f=None):\n \"\"\"\n Return a list of leaves. Can be filtered with f.\n\n Args:\n f (function): A function that evaluates to True if called with desired\n node as the first input\n\n Returns:\n list: A list of leaves that are true for f (if f is given)\n\n \"\"\"\n if f: return [ n for n in self if (n.isleaf and f(n)) ]\n return [ n for n in self if n.isleaf ]\n\n def internals(self, f=None):\n \"\"\"\n Return a list nodes that have children (internal nodes)\n\n Args:\n f (function): A function that evaluates to true if called with desired\n node as the first input\n\n Returns:\n list: A list of internal nodes that are true for f (if f is given)\n\n \"\"\"\n if f: return [ n for n in self if (n.children and f(n)) ]\n return [ n for n in self if n.children ]\n\n def clades(self):\n \"\"\"\n Get internal nodes descended from self\n\n Returns:\n list: A list of internal nodes descended from (and not including) self.\n\n \"\"\"\n return [ n for n in self if (n is not self) and not n.isleaf ]\n\n def iternodes(self, f=None):\n \"\"\"\n Return a generator of nodes descendant from self - including self\n\n Args:\n f (function): A function that evaluates to true if called with\n desired node as the first input\n\n Yields:\n Node: Nodes descended from self (including self) in\n preorder sequence\n\n \"\"\"\n if (f and f(self)) or (not f):\n yield self\n for child in self.children:\n for n in child.iternodes(f):\n yield n\n\n def iterleaves(self):\n \"\"\"\n Yield leaves descendant from self\n \"\"\"\n return self.iternodes(lambda x:x.isleaf)\n\n def preiter(self, f=None):\n \"\"\"\n Yield nodes in preorder sequence\n \"\"\"\n for n in self.iternodes(f=f):\n yield n\n\n def postiter(self, f=None):\n \"\"\"\n Yield nodes in postorder sequence\n \"\"\"\n if not self.isleaf:\n for child in self.children:\n for n in child.postiter():\n if (f and f(n)) or (not f):\n yield n\n if (f and f(self)) or (not f):\n yield self\n\n def descendants(self, order=\"pre\", v=None, f=None):\n \"\"\"\n Return a list of nodes descendant from self - but _not_\n including self!\n\n Args:\n order (str): Indicates wether to return nodes in preorder or\n postorder sequence. Optional, defaults to \"pre\"\n f (function): filtering function that evaluates to True if desired\n node is called as the first parameter.\n\n Returns:\n list: A list of nodes descended from self not including self.\n\n \"\"\"\n v = v or []\n for child in self.children:\n if (f and f(child)) or (not f):\n if order == \"pre\":\n v.append(child)\n else:\n v.insert(0, child)\n if child.children:\n child.descendants(order, v, f)\n return v\n\n def get(self, f, *args, **kwargs):\n \"\"\"\n Return the first node found by node.find()\n\n Args:\n f (function): A function that evaluates to True if desired\n node is called as the first parameter.\n Returns:\n Node: The first node found by node.find()\n\n \"\"\"\n v = self.find(f, *args, **kwargs)\n try:\n return v.next()\n except StopIteration:\n return None\n\n def grep(self, s, ignorecase=True):\n \"\"\"\n Find nodes by regular-expression search of labels\n\n Args:\n s (str): String to search.\n ignorecase (bool): Indicates to ignore case. Defaults to true.\n\n Returns:\n lsit: A list of node objects whose labels were matched by s.\n\n \"\"\"\n import re\n if ignorecase:\n pattern = re.compile(s, re.IGNORECASE)\n else:\n pattern = re.compile(s)\n\n search = pattern.search\n return [ x for x in self if x.label and search(x.label) ]\n\n def lgrep(self, s, ignorecase=True):\n \"\"\"\n Find leaves by regular-expression search of labels\n\n Args:\n s (str): String to search.\n ignorecase (bool): Indicates to ignore case. Defaults to true.\n\n Returns:\n lsit: A list of node objects whose labels were matched by s.\n\n \"\"\"\n return [ x for x in self.grep(s, ignorecase=ignorecase) if x.isleaf ]\n\n def bgrep(self, s, ignorecase=True):\n \"\"\"\n Find branches (internal nodes) by regular-expression search of\n labels\n\n Args:\n s (str): String to search.\n ignorecase (bool): Indicates to ignore case. Defaults to true.\n\n Returns:\n lsit: A list of node objects whose labels were matched by s.\n\n \"\"\"\n return [ x for x in self.grep(s, ignorecase=ignorecase) if\n (not x.isleaf) ]\n\n def find(self, f, *args, **kwargs):\n \"\"\"\n Find descendant nodes.\n\n Args:\n f: Function or a string. If a string, it is converted to a\n function for finding *f* as a substring in node labels.\n Otherwise, *f* should evaluate to True if called with a desired\n node as the first parameter.\n\n Yields:\n Node: Found nodes in preorder sequence.\n\n \"\"\"\n if not f: return\n if type(f) in types.StringTypes:\n func = lambda x: (f or None) in (x.label or \"\")\n else:\n func = f\n for n in self.iternodes():\n if func(n, *args, **kwargs):\n yield n\n\n def findall(self, f, *args, **kwargs):\n \"\"\"Return a list of found nodes.\"\"\"\n return list(self.find(f, *args, **kwargs))\n\n def prune(self):\n \"\"\"\n Remove self if self is not root.\n\n Returns:\n Node: Parent of self. If parent had only two children,\n parent is now a 'knee' and can be removed with excise.\n\n \"\"\"\n p = self.parent\n if p:\n p.remove_child(self)\n return p\n\n def excise(self):\n \"\"\"\n For 'knees': remove self from between parent and single child\n \"\"\"\n assert self.parent\n assert len(self.children)==1\n p = self.parent\n c = self.children[0]\n if c.length is not None and self.length is not None:\n c.length += self.length\n c.prune()\n self.prune()\n p.add_child(c)\n return p\n\n def graft(self, node):\n \"\"\"\n Add node as sister to self.\n \"\"\"\n parent = self.parent\n parent.remove_child(self)\n n = Node()\n n.add_child(self)\n n.add_child(node)\n parent.add_child(n)\n\n ## def leaf_distances(self, store=None, measure=\"length\"):\n ## \"\"\"\n ## for each internal node, calculate the distance to each leaf,\n ## measured in branch length or internodes\n ## \"\"\"\n ## if store is None:\n ## store = {}\n ## leaf2len = {}\n ## if self.children:\n ## for child in self.children:\n ## if measure == \"length\":\n ## dist = child.length\n ## elif measure == \"nodes\":\n ## dist = 1\n ## child.leaf_distances(store, measure)\n ## if child.isleaf:\n ## leaf2len[child] = dist\n ## else:\n ## for k, v in store[child].items():\n ## leaf2len[k] = v + dist\n ## else:\n ## leaf2len[self] = {self: 0}\n ## store[self] = leaf2len\n ## return store\n\n def leaf_distances(self, measure=\"length\"):\n \"\"\"\n RR: I don't quite understand the structure of the output. Also,\n I can't figure out what \"measure\" does.-CZ\n \"\"\"\n from collections import defaultdict\n store = defaultdict(lambda:defaultdict(lambda:0))\n nodes = [ x for x in self if x.children ]\n for lf in self.leaves():\n x = lf.length\n for n in lf.rootpath(self):\n store[n][lf] = x\n x += (n.length or 0)\n return store\n\n def rootpath(self, end=None, stop=None):\n \"\"\"\n Iterate over parent nodes toward the root, or node *end* if\n encountered.\n\n Args:\n end (Node): A Node object to iterate to (instead of iterating\n towards root). Optional, defaults to None\n stop (function): A function that returns True if desired node is called\n as the first parameter. Optional, defaults to None\n\n Yields:\n Node: Nodes in path to root (or end).\n\n \"\"\"\n n = self.parent\n while 1:\n if n is None: raise StopIteration\n yield n\n if n.isroot or (end and n == end) or (stop and stop(n)):\n raise StopIteration\n n = n.parent\n\n def rootpath_length(self, end=None):\n \"\"\"\n Get length from self to root(if end is None) or length\n from self to an ancestor node (if end is an ancestor to self)\n\n Args:\n end (Node): A node object\n\n Returns:\n float: The length from self to root/end\n\n \"\"\"\n n = self\n x = 0.0\n while n.parent:\n x += n.length\n if n.parent == end:\n break\n n = n.parent\n return x\n ## f = lambda x:x.parent==end\n ## v = [self.length]+[ x.length for x in self.rootpath(stop=f)\n ## if x.parent ]\n ## assert None not in v\n ## return sum(v)\n\n def max_tippath(self, first=True):\n \"\"\"\n Get the maximum length from self to a leaf node\n \"\"\"\n v = 0\n if self.children:\n v = max([ c.max_tippath(False) for c in self.children ])\n if not first:\n if self.length is None: v += 1\n else: v += self.length\n return v\n\n def subtree_mapping(self, labels, clean=False):\n \"\"\"\n Find the set of nodes in 'labels', and create a new tree\n representing the subtree connecting them. Nodes are assumed\n to be non-nested.\n\n Returns:\n dict: a mapping of old nodes to new nodes and vice versa.\n\n TODO: test this, high bug probability\n \"\"\"\n d = {}\n oldtips = [ x for x in self.leaves() if x.label in labels ]\n for tip in oldtips:\n path = list(tip.rootpath())\n for node in path:\n if node not in d:\n newnode = Node()\n newnode.isleaf = node.isleaf\n newnode.length = node.length\n newnode.label = node.label\n d[node] = newnode\n d[newnode] = node\n else:\n newnode = d[node]\n\n for child in node.children:\n if child in d:\n newchild = d[child]\n if newchild not in newnode.children:\n newnode.add_child(newchild)\n d[\"oldroot\"] = self\n d[\"newroot\"] = d[self]\n if clean:\n n = d[\"newroot\"]\n while 1:\n if n.nchildren == 1:\n oldnode = d[n]\n del d[oldnode]; del d[n]\n child = n.children[0]\n child.parent = None\n child.isroot = True\n d[\"newroot\"] = child\n d[\"oldroot\"] = d[child]\n n = child\n else:\n break\n\n for tip in oldtips:\n newnode = d[tip]\n while 1:\n newnode = newnode.parent\n oldnode = d[newnode]\n if newnode.nchildren == 1:\n child = newnode.children[0]\n if newnode.length:\n child.length += newnode.length\n newnode.remove_child(child)\n if newnode.parent:\n parent = newnode.parent\n parent.remove_child(newnode)\n parent.add_child(child)\n del d[oldnode]; del d[newnode]\n if not newnode.parent:\n break\n\n return d\n\n def reroot_orig(self, newroot):\n assert newroot in self\n self.isroot = False\n newroot.isroot = True\n v = []\n n = newroot\n while 1:\n v.append(n)\n if not n.parent: break\n n = n.parent\n v.reverse()\n for i, cp in enumerate(v[:-1]):\n node = v[i+1]\n # node is current node; cp is current parent\n cp.remove_child(node)\n node.add_child(cp)\n cp.length = node.length\n return newroot\n\n def reroot(self, newroot):\n \"\"\"\n RR: I can't get this to work properly -CZ\n \"\"\"\n newroot = self[newroot]\n assert newroot in self\n self.isroot = False\n n = newroot\n v = list(n.rootpath())\n v.reverse()\n for node in (v+[n])[1:]:\n # node is current node; cp is current parent\n cp = node.parent\n cp.remove_child(node)\n node.add_child(cp)\n cp.length = node.length\n cp.label = node.label\n newroot.isroot = True\n return newroot\n\n def makeroot(self, shift_labels=False):\n \"\"\"\n shift_labels: flag to shift internal parent-child node labels\n when internode polarity changes; suitable e.g. if internal node\n labels indicate unrooted bipartition support\n \"\"\"\n v = list(self.rootpath())\n v[-1].isroot = False\n v.reverse()\n for node in v[1:] + [self]:\n # node is current node; cp is current parent\n cp = node.parent\n cp.remove_child(node)\n node.add_child(cp)\n cp.length = node.length\n if shift_labels:\n cp.label = node.label\n self.isroot = True\n return self\n\n def write(self, outfile=None, format=\"newick\", length_fmt=\":%g\", end=True,\n clobber=False):\n if format==\"newick\":\n s = write_newick(self, outfile, length_fmt, True, clobber)\n if not outfile:\n return s\n\n\nreroot = Node.reroot\n\ndef index(node, n=0, d=0):\n \"\"\"\n recursively attach 'next', 'back', (and 'left', 'right'), 'ni',\n 'ii', 'pi', and 'node_depth' attributes to nodes\n \"\"\"\n node.next = node.left = n\n if not node.parent:\n node.node_depth = d\n else:\n node.node_depth = node.parent.node_depth + 1\n n += 1\n for i, c in enumerate(node.children):\n if i > 0:\n n = node.children[i-1].back + 1\n index(c, n)\n\n if node.children:\n node.back = node.right = node.children[-1].back + 1\n else:\n node.back = node.right = n\n return node.back\n\ndef remove_singletons(root, add=True):\n \"Remove descendant nodes that are the sole child of their parent\"\n for leaf in root.leaves():\n for n in leaf.rootpath():\n if n.parent and len(n.parent.children)==1:\n n.collapse(add)\n\ndef cls(root):\n \"\"\"\n Get clade sizes of whole tree\n Args:\n * root: A root node\n\n Returns:\n * A dict mapping nodes to clade sizes\n\n \"\"\"\n results = {}\n for node in root.postiter():\n if node.isleaf:\n results[node] = 1\n else:\n results[node] = sum(results[child] for child in node.children)\n return results\n\ndef clade_sizes(node, results={}):\n \"\"\"Map node and descendants to number of descendant tips\"\"\"\n size = int(node.isleaf)\n if not node.isleaf:\n for child in node.children:\n clade_sizes(child, results)\n size += results[child]\n results[node] = size\n return results\n\ndef write(node, outfile=None, format=\"newick\", length_fmt=\":%g\",\n clobber=False):\n if format==\"newick\" or ((type(outfile) in types.StringTypes) and\n (outfile.endswith(\".newick\") or\n outfile.endswith(\".new\"))):\n s = write_newick(node, outfile, length_fmt, True, clobber)\n if not outfile:\n return s\n\ndef write_newick(node, outfile=None, length_fmt=\":%g\", end=False,\n clobber=False):\n if not node.isleaf:\n node_str = \"(%s)%s\" % \\\n (\",\".join([ write_newick(child, outfile, length_fmt,\n False, clobber)\n for child in node.children ]),\n (node.label or \"\")\n )\n else:\n node_str = \"%s\" % node.label\n\n if node.length is not None:\n length_str = length_fmt % node.length\n else:\n length_str = \"\"\n\n semicolon = \"\"\n if end:\n semicolon = \";\"\n s = \"%s%s%s\" % (node_str, length_str, semicolon)\n if end and outfile:\n flag = False\n if type(outfile) in types.StringTypes:\n if not clobber:\n assert not os.path.isfile(outfile), \"File '%s' exists! (Set clobber=True to overwrite)\" % outfile\n flag = True\n outfile = file(outfile, \"w\")\n outfile.write(s)\n if flag:\n outfile.close()\n return s\n\ndef read(data, format=None, treename=None, ttable=None):\n \"\"\"\n Read a single tree from *data*, which can be a Newick string, a\n file name, or a file-like object with `tell` and 'read`\n methods. *treename* is an optional string that will be attached to\n all created nodes.\n\n Args:\n data: A file or file-like object or newick string\n\n Returns:\n Node: The root node.\n \"\"\"\n import newick\n StringTypes = types.StringTypes\n\n def strip(s):\n fname = os.path.split(s)[-1]\n head, tail = os.path.splitext(fname)\n tail = tail.lower()\n if tail in (\".nwk\", \".tre\", \".tree\", \".newick\", \".nex\"):\n return head\n else:\n return fname\n\n if (not format):\n if (type(data) in StringTypes) and os.path.isfile(data):\n s = data.lower()\n for tail in \".nex\", \".nexus\", \".tre\":\n if s.endswith(tail):\n format=\"nexus\"\n break\n\n if (not format):\n format = \"newick\"\n\n if format == \"newick\":\n if type(data) in StringTypes:\n if os.path.isfile(data):\n treename = strip(data)\n return newick.parse(file(data), treename=treename,\n ttable=ttable)\n else:\n return newick.parse(data, ttable=ttable)\n\n elif (hasattr(data, \"tell\") and hasattr(data, \"read\")):\n treename = strip(getattr(data, \"name\", None))\n return newick.parse(data, treename=treename, ttable=ttable)\n elif format == \"nexus-dendropy\":\n import dendropy\n if type(data) in StringTypes:\n if os.path.isfile(data):\n treename = strip(data)\n return newick.parse(\n str(dendropy.Tree.get_from_path(data, \"nexus\")),\n treename=treename\n )\n else:\n return newick.parse(\n str(dendropy.Tree.get_from_string(data, \"nexus\"))\n )\n\n elif (hasattr(data, \"tell\") and hasattr(data, \"read\")):\n treename = strip(getattr(data, \"name\", None))\n return newick.parse(\n str(dendropy.Tree.get_from_stream(data, \"nexus\")),\n treename=treename\n )\n else:\n pass\n\n elif format == \"nexus\":\n if type(data) in StringTypes:\n if os.path.isfile(data):\n with open(data) as infile:\n rec = newick.nexus_iter(infile).next()\n if rec: return rec.parse()\n else:\n rec = newick.nexus_iter(StringIO(data)).next()\n if rec: return rec.parse()\n else:\n rec = newick.nexus_iter(data).next()\n if rec: return rec.parse()\n else:\n # implement other tree formats here (nexus, nexml etc.)\n raise IOError, \"format '%s' not implemented yet\" % format\n\n raise IOError, \"unable to read tree from '%s'\" % data\n\ndef readmany(data, format=\"newick\"):\n \"\"\"Iterate over trees from a source.\"\"\"\n if type(data) in types.StringTypes:\n if os.path.isfile(data):\n data = open(data)\n else:\n data = StringIO(data)\n\n if format == \"newick\":\n for line in data:\n yield newick.parse(line)\n elif format == \"nexus\":\n for rec in newick.nexus_iter(data):\n yield rec.parse()\n else:\n raise Exception, \"format '%s' not recognized\" % format\n data.close()\n\n## def randomly_resolve(n):\n## assert len(n.children)>2\n\n## def leaf_mrcas(root):\n## from itertools import product, izip, tee\n## from collections import OrderedDict\n## from numpy import empty\n## mrca = OrderedDict()\n## def pairwise(iterable, tee=tee, izip=izip):\n## a, b = tee(iterable)\n## next(b, None)\n## return izip(a, b)\n## def f(n):\n## if n.isleaf:\n## od = OrderedDict(); od[n] = n.length\n## return od\n## d = [ f(c) for c in n.children ]\n## for i, j in pairwise(xrange(len(d))):\n## di = d[i]; dj =d[j]\n## for ni, niv in di.iteritems():\n## for nj, njv in dj.iteritems():\n## mrca[(ni,nj)] = n\n## d[j].update(di)\n## return d[j]\n## f(root)\n## return mrca\n\ndef C(leaves, internals):\n from scipy.sparse import lil_matrix\n m = lil_matrix((len(internals), len(leaves)))\n for lf in leaves:\n v = lf.length if lf.length is not None else 1\n for n in lf.rootpath():\n m[n.ii,lf.li] = v\n v += n.length if n.length is not None else 1\n return m.tocsc()\n", "ivy/treebase.py": "\"\"\"\nFunctions to get trees and character data from treebase\n\"\"\"\n\nfrom urllib2 import urlopen\nfrom lxml import etree\nfrom collections import defaultdict\nfrom storage import Storage\nimport sys, re\n\n# \"http://purl.org/phylo/treebase/phylows/study/TB2:S11152\"\n\nTREEBASE_WEBSERVICE = \"http://purl.org/phylo/treebase/phylows\"\nNEXML_NAMESPACE = \"http://www.nexml.org/2009\"\nNEXML = \"{%s}\" % NEXML_NAMESPACE\nUNIPROT = \"http://purl.uniprot.org/taxonomy/\"\nNAMEBANK = (\"http://www.ubio.org/authority/metadata.php?\"\n \"lsid=urn:lsid:ubio.org:namebank:\")\n\nROW_SEGMENTS = (\"http://treebase.org/treebase-web/search/study/\"\n \"rowSegmentsTSV.html?matrixid=\")\n\nMETA_DATATYPE = {\n \"xsd:long\": int,\n \"xsd:integer\": int,\n \"xsd:string\": str\n }\n\nAMBIG_RE = re.compile(r'([{][a-zA-Z]+[}])')\n\ndef fetch_study(study_id, format=\"nexml\"):\n \"\"\"\n Get a study from treebase in one of various formats\n\n Args:\n study_id (str): The id of the study\n format (str): One of [\"rdf\", \"html\", \"nexml\", \"nexus\"]\n Returns:\n Str representing a nexus file (if format = \"nexus\")\n\n OR\n\n An lxml etree object\n \"\"\"\n try: study_id = \"S%s\" % int(study_id)\n except ValueError: pass\n\n # format is one of [\"rdf\", \"html\", \"nexml\", \"nexus\"]\n url = \"%s/study/TB2:%s?format=%s\" % (TREEBASE_WEBSERVICE, study_id, format)\n if format==\"nexus\":\n return urlopen(url).read()\n else:\n return etree.parse(url)\n\ndef parse_chars(e, otus):\n v = []\n for chars in e.findall(NEXML+\"characters\"):\n c = Storage(chars.attrib)\n c.states = parse_states(chars)\n c.meta = Storage()\n for meta in chars.findall(NEXML+\"meta\"):\n a = meta.attrib\n if a.get(\"content\"):\n value = META_DATATYPE[a[\"datatype\"]](a[\"content\"])\n c.meta[a[\"property\"]] = value\n c.matrices = []\n for matrix in chars.findall(NEXML+\"matrix\"):\n m = Storage()\n m.rows = []\n for row in matrix.findall(NEXML+\"row\"):\n r = Storage(row.attrib)\n r.otu = otus[r.otu]\n s = row.findall(NEXML+\"seq\")[0].text\n substrs = []\n for ss in AMBIG_RE.split(s):\n if ss.startswith(\"{\"):\n key = frozenset(ss[1:-1])\n val = c.states.states2symb.get(key)\n if key and not val:\n sys.stderr.write(\"missing ambig symbol for %s\\n\" %\n \"\".join(sorted(key)))\n ss = val or \"?\"\n substrs.append(ss)\n s = \"\".join(substrs)\n r.seq = s\n m.rows.append(r)\n c.matrices.append(m)\n v.append(c)\n return v\n\ndef parse_trees(e, otus):\n \"\"\"\n Get trees from an etree object\n\n Args:\n e: A nexml document parsed by etree\n otus: OTUs returned by parse_otus\n Returns:\n list: A list of ivy Storage objects each\n containing every node of a tree.\n \"\"\"\n from tree import Node\n v = []\n for tb in e.findall(NEXML+\"trees\"):\n for te in tb.findall(NEXML+\"tree\"):\n t = Storage()\n t.attrib = Storage(te.attrib)\n t.nodes = {}\n for n in te.findall(NEXML+\"node\"):\n node = Node()\n if n.attrib.get(\"otu\"):\n node.isleaf = True\n node.otu = otus[n.attrib[\"otu\"]]\n node.label = node.otu.label\n t.nodes[n.attrib[\"id\"]] = node\n for edge in te.findall(NEXML+\"edge\"):\n d = edge.attrib\n n = t.nodes[d[\"target\"]]\n p = t.nodes[d[\"source\"]]\n length = d.get(\"length\")\n if length:\n n.length = float(length)\n p.add_child(n)\n r = [ n for n in t.nodes.values() if not n.parent ]\n assert len(r)==1\n r = r[0]\n r.isroot = True\n for i, n in enumerate(r): n.id = i+1\n t.root = r\n v.append(t)\n return v\n\ndef parse_otus(e):\n \"\"\"\n Get OTUs from an etree object\n\n Args:\n e: A nexml document parsed by etree\n Returns:\n dict: A dict mapping keys to OTUs contained in ivy Storage objects\n \"\"\"\n v = {}\n for otus in e.findall(NEXML+\"otus\"):\n for x in otus.findall(NEXML+\"otu\"):\n otu = Storage()\n otu.id = x.attrib[\"id\"]\n otu.label = x.attrib[\"label\"]\n for meta in x.iterchildren():\n d = meta.attrib\n p = d.get(\"property\")\n if p and p == \"tb:identifier.taxon\":\n otu.tb_taxid = d[\"content\"]\n elif p and p == \"tb:identifier.taxonVariant\":\n otu.tb_taxid_variant = d[\"content\"]\n h = d.get(\"href\")\n if h and h.startswith(NAMEBANK):\n otu.namebank_id = int(h.replace(NAMEBANK, \"\"))\n elif h and h.startswith(UNIPROT):\n otu.ncbi_taxid = int(h.replace(UNIPROT, \"\"))\n v[otu.id] = otu\n return v\n\ndef parse_nexml(doc):\n \"\"\"\n Parse an etree ElementTree\n\n Args:\n doc: An etree ElementTree or a file that can be parsed into\n an etree ElementTree with etree.parse\n Returns:\n An ivy Storage object containing all the information from the\n nexml file: Characters, metadata, OTUs, and trees.\n \"\"\"\n if not isinstance(doc, (etree._ElementTree, etree._Element)):\n doc = etree.parse(doc)\n meta = {}\n for child in doc.findall(NEXML+\"meta\"):\n if \"content\" in child.attrib:\n d = child.attrib\n key = d[\"property\"]\n val = META_DATATYPE[d[\"datatype\"]](d[\"content\"])\n if (key in meta) and val:\n if isinstance(meta[key], list):\n meta[key].append(val)\n else:\n meta[key] = [meta[key], val]\n else:\n meta[key] = val\n\n otus = parse_otus(doc)\n\n return Storage(meta = meta,\n otus = otus,\n chars = parse_chars(doc, otus),\n trees = parse_trees(doc, otus))\n\ndef parse_states(e):\n \"\"\"e is a characters element\"\"\"\n f = e.findall(NEXML+\"format\")[0]\n sts = f.findall(NEXML+\"states\")[0]\n states2symb = {}\n symb2states = {}\n id2symb = {}\n for child in sts.iterchildren():\n t = child.tag\n if t == NEXML+\"state\":\n k = child.attrib[\"id\"]\n v = child.attrib[\"symbol\"]\n id2symb[k] = v\n states2symb[v] = v\n symb2states[v] = v\n elif t == NEXML+\"uncertain_state_set\":\n k = child.attrib[\"id\"]\n v = child.attrib[\"symbol\"]\n id2symb[k] = v\n memberstates = []\n for memb in child.findall(NEXML+\"member\"):\n sid = memb.attrib[\"state\"]\n symb = id2symb[sid]\n for x in symb2states[symb]: memberstates.append(x)\n memberstates = frozenset(memberstates)\n symb2states[v] = memberstates\n states2symb[memberstates] = v\n return Storage(states2symb=states2symb,\n symb2states=symb2states,\n id2symb=id2symb)\n\ndef parse_charsets(study_id):\n from cStringIO import StringIO\n nx = StringIO(fetch_study(study_id, 'nexus'))\n d = {}\n for line in nx.readlines():\n if line.strip().startswith(\"CHARSET \"):\n v = line.strip().split()\n label = v[1]\n first, last = map(int, line.split()[-1][:-1].split(\"-\"))\n d[label] = (first-1, last-1)\n return d\n\nif __name__ == \"__main__\":\n import sys\n from pprint import pprint\n e = fetch_study('S11152', 'nexus')\n #print e\n #e.write(sys.stdout, pretty_print=True)\n\n ## e = etree.parse('/tmp/tmp.xml')\n ## x = parse_nexml(e)\n ## pprint(x)\n", "ivy/vis/alignment.py": "\"\"\"\ninteractive viewers for trees, etc. using matplotlib\n\"\"\"\nfrom collections import defaultdict\nfrom ..storage import Storage\nfrom .. import align, sequtil\nimport matplotlib, numpy, types\nimport matplotlib.pyplot as pyplot\nfrom matplotlib.figure import SubplotParams, Figure\nfrom matplotlib.axes import Axes, subplot_class_factory\nfrom matplotlib.patches import Rectangle\nfrom matplotlib.collections import PatchCollection\nfrom matplotlib.widgets import RectangleSelector\nfrom matplotlib.transforms import Bbox, offset_copy, IdentityTransform\nfrom matplotlib import colors as mpl_colors\nfrom matplotlib.ticker import MaxNLocator, FuncFormatter, NullLocator\nfrom mpl_toolkits.axes_grid1.inset_locator import inset_axes\nfrom Bio.Align import MultipleSeqAlignment\n\nmatplotlib.rcParams['path.simplify'] = False\n\nclass UpdatingRect(Rectangle):\n def __call__(self, p):\n self.set_bounds(*p.viewLim.bounds)\n p.figure.canvas.draw_idle()\n\nclass AlignmentFigure:\n def __init__(self, aln, name=None, div=0.25, overview=True):\n if isinstance(aln, MultipleSeqAlignment):\n self.aln = aln\n else:\n self.aln = align.read(aln)\n self.name = name\n self.div_value = div\n pars = SubplotParams(\n left=0.2, right=1, bottom=0.05, top=1, wspace=0.01\n )\n fig = pyplot.figure(subplotpars=pars, facecolor=\"white\")\n self.figure = fig\n self.initialize_subplots(overview)\n self.show()\n self.connect_events()\n \n def initialize_subplots(self, overview=False):\n ## p = AlignmentPlot(self.figure, 212, aln=self.aln)\n p = AlignmentPlot(self.figure, 111, aln=self.aln, app=self)\n self.detail = self.figure.add_subplot(p)\n self.detail.plot_aln()\n if overview:\n self.overview = inset_axes(\n self.detail, width=\"30%\", height=\"20%\", loc=1\n )\n self.overview.xaxis.set_major_locator(NullLocator())\n self.overview.yaxis.set_major_locator(NullLocator())\n self.overview.imshow(\n self.detail.array, interpolation='nearest', aspect='auto',\n origin='lower'\n )\n rect = UpdatingRect(\n [0,0], 0, 0, facecolor='black', edgecolor='cyan', alpha=0.5\n )\n self.overview.zoomrect = rect\n rect.target = self.detail\n self.detail.callbacks.connect('xlim_changed', rect)\n self.detail.callbacks.connect('ylim_changed', rect)\n self.overview.add_patch(rect)\n rect(self.overview)\n\n else:\n self.overview = None\n \n def show(self):\n self.figure.show()\n\n def connect_events(self):\n mpl_connect = self.figure.canvas.mpl_connect\n mpl_connect(\"button_press_event\", self.onclick)\n mpl_connect(\"button_release_event\", self.onbuttonrelease)\n mpl_connect(\"scroll_event\", self.onscroll)\n mpl_connect(\"pick_event\", self.onpick)\n mpl_connect(\"motion_notify_event\", self.ondrag)\n mpl_connect(\"key_press_event\", self.onkeypress)\n mpl_connect(\"axes_enter_event\", self.axes_enter)\n mpl_connect(\"axes_leave_event\", self.axes_leave)\n\n @staticmethod\n def axes_enter(e):\n ax = e.inaxes\n ax._active = True\n\n @staticmethod\n def axes_leave(e):\n ax = e.inaxes\n ax._active = False\n\n @staticmethod\n def onselect(estart, estop):\n b = estart.button\n ## print b, estart.key\n\n @staticmethod\n def onkeypress(e):\n ax = e.inaxes\n k = e.key\n if ax and k:\n if k == 't':\n ax.home()\n elif k == \"down\":\n ax.scroll(0, -0.1)\n elif k == \"up\":\n ax.scroll(0, 0.1)\n elif k == \"left\":\n ax.scroll(-0.1, 0)\n elif k == \"right\":\n ax.scroll(0.1, 0)\n elif k in '=+':\n ax.zoom(0.1,0.1)\n elif k == '-':\n ax.zoom(-0.1,-0.1)\n ax.figure.canvas.draw_idle()\n\n @staticmethod\n def ondrag(e):\n ax = e.inaxes\n button = e.button\n if ax and button == 2:\n if not ax.pan_start:\n ax.pan_start = (e.xdata, e.ydata)\n return\n x, y = ax.pan_start\n xdelta = x - e.xdata\n ydelta = y - e.ydata\n x0, x1 = ax.get_xlim()\n xspan = x1-x0\n y0, y1 = ax.get_ylim()\n yspan = y1 - y0\n midx = (x1+x0)*0.5\n midy = (y1+y0)*0.5\n ax.set_xlim(midx+xdelta-xspan*0.5, midx+xdelta+xspan*0.5)\n ax.set_ylim(midy+ydelta-yspan*0.5, midy+ydelta+yspan*0.5)\n ax.figure.canvas.draw_idle()\n\n @staticmethod\n def onbuttonrelease(e):\n ax = e.inaxes\n button = e.button\n if button == 2:\n ## print \"pan end\"\n ax.pan_start = None\n ax.figure.canvas.draw_idle()\n\n @staticmethod\n def onpick(e):\n ax = e.mouseevent.inaxes\n if ax:\n ax.picked(e)\n ax.figure.canvas.draw_idle()\n\n @staticmethod\n def onscroll(e):\n ax = e.inaxes\n if ax:\n b = e.button\n ## print b\n k = e.key\n if k == None and b ==\"up\":\n ax.zoom(0.1,0.1)\n elif k == None and b ==\"down\":\n ax.zoom(-0.1,-0.1)\n elif k == \"shift\" and b == \"up\":\n ax.zoom_cxy(0.1, 0, e.xdata, e.ydata)\n elif k == \"shift\" and b == \"down\":\n ax.zoom_cxy(-0.1, 0, e.xdata, e.ydata)\n elif k == \"control\" and b == \"up\":\n ax.zoom_cxy(0, 0.1, e.xdata, e.ydata)\n elif k == \"control\" and b == \"down\":\n ax.zoom_cxy(0, -0.1, e.xdata, e.ydata)\n elif k == \"d\" and b == \"up\":\n ax.scroll(0, 0.1)\n elif (k == \"d\" and b == \"down\"):\n ax.scroll(0, -0.1)\n elif k == \"c\" and b == \"up\":\n ax.scroll(-0.1, 0)\n elif k == \"c\" and b == \"down\":\n ax.scroll(0.1, 0)\n ax.figure.canvas.draw_idle()\n\n @staticmethod\n def onclick(e):\n ax = e.inaxes\n if (ax and e.button==1 and hasattr(ax, \"zoomrect\") and ax.zoomrect):\n # overview clicked; reposition zoomrect\n r = ax.zoomrect\n x = e.xdata\n y = e.ydata\n arr = ax.transData.inverted().transform(r.get_extents())\n xoff = (arr[1][0]-arr[0][0])*0.5\n yoff = (arr[1][1]-arr[0][1])*0.5\n r.target.set_xlim(x-xoff,x+xoff)\n r.target.set_ylim(y-yoff,y+yoff)\n r(r.target)\n ax.figure.canvas.draw_idle()\n\n elif ax and e.button==2:\n ## print \"pan start\", (e.xdata, e.ydata)\n ax.pan_start = (e.xdata, e.ydata)\n ax.figure.canvas.draw_idle()\n\n elif ax and hasattr(ax, \"aln\") and ax.aln:\n x = int(e.xdata+0.5); y = int(e.ydata+0.5)\n aln = ax.aln\n if (0 <= x <= ax.nchar) and (0 <= y <= ax.ntax):\n seq = aln[y]; char = seq[x]\n if char not in '-?':\n v = sequtil.gapidx(seq)\n i = (v[1]==x).nonzero()[0][0]\n print (\"%s: row %s, site %s: '%s', seqpos %s\"\n % (seq.id, y, x, char, i))\n else:\n print \"%s: row %s, site %s: '%s'\" % (seq.id, y, x, char)\n\n def zoom(self, factor=0.1):\n \"Zoom both axes by *factor* (relative display size).\"\n self.detail.zoom(factor, factor)\n self.figure.canvas.draw_idle()\n\n def __get_selection(self):\n return self.detail.extract_selected()\n selected = property(__get_selection)\n \nclass Alignment(Axes):\n \"\"\"\n matplotlib.axes.Axes subclass for rendering sequence alignments.\n \"\"\"\n def __init__(self, fig, rect, *args, **kwargs):\n self.aln = kwargs.pop(\"aln\")\n nrows = len(self.aln)\n ncols = self.aln.get_alignment_length()\n self.alnidx = numpy.arange(ncols)\n self.app = kwargs.pop(\"app\", None)\n self.showy = kwargs.pop('showy', True)\n Axes.__init__(self, fig, rect, *args, **kwargs)\n rgb = mpl_colors.colorConverter.to_rgb\n gray = rgb('gray')\n d = defaultdict(lambda:gray)\n d[\"A\"] = rgb(\"red\")\n d[\"a\"] = rgb(\"red\")\n d[\"C\"] = rgb(\"blue\")\n d[\"c\"] = rgb(\"blue\")\n d[\"G\"] = rgb(\"green\")\n d[\"g\"] = rgb(\"green\")\n d[\"T\"] = rgb(\"yellow\")\n d[\"t\"] = rgb(\"yellow\")\n self.cmap = d\n self.selector = RectangleSelector(\n self, self.select_rectangle, useblit=True\n )\n def f(e):\n if e.button != 1: return True\n else: return RectangleSelector.ignore(self.selector, e)\n self.selector.ignore = f\n self.selected_rectangle = Rectangle(\n [0,0],0,0, facecolor='white', edgecolor='cyan', alpha=0.3\n )\n self.add_patch(self.selected_rectangle)\n self.highlight_find_collection = None\n\n def plot_aln(self):\n cmap = self.cmap\n self.ntax = len(self.aln); self.nchar = self.aln.get_alignment_length()\n a = numpy.array([ [ cmap[base] for base in x.seq ]\n for x in self.aln ])\n self.array = a\n self.imshow(a, interpolation='nearest', aspect='auto', origin='lower')\n y = [ i+0.5 for i in xrange(self.ntax) ]\n labels = [ x.id for x in self.aln ]\n ## locator.bin_boundaries(1,ntax)\n ## locator.view_limits(1,ntax)\n if self.showy:\n locator = MaxNLocator(nbins=50, integer=True)\n self.yaxis.set_major_locator(locator)\n def fmt(x, pos=None):\n if x<0: return \"\"\n try: return labels[int(round(x))]\n except: pass\n return \"\"\n self.yaxis.set_major_formatter(FuncFormatter(fmt))\n else:\n self.yaxis.set_major_locator(NullLocator())\n \n return self\n\n def select_rectangle(self, e0, e1):\n x0, x1 = map(int, sorted((e0.xdata+0.5, e1.xdata+0.5)))\n y0, y1 = map(int, sorted((e0.ydata+0.5, e1.ydata+0.5)))\n self.selected_chars = (x0, x1)\n self.selected_taxa = (y0, y1)\n self.selected_rectangle.set_bounds(x0-0.5,y0-0.5,x1-x0+1,y1-y0+1)\n self.app.figure.canvas.draw_idle()\n\n def highlight_find(self, substr):\n if not substr:\n if self.highlight_find_collection:\n self.highlight_find_collection.remove()\n self.highlight_find_collection = None\n return\n \n N = len(substr)\n v = []\n for y, x in align.find(self.aln, substr):\n r = Rectangle(\n [x-0.5,y-0.5], N, 1,\n facecolor='cyan', edgecolor='cyan', alpha=0.7\n )\n v.append(r)\n if self.highlight_find_collection:\n self.highlight_find_collection.remove()\n c = PatchCollection(v, True)\n self.highlight_find_collection = self.add_collection(c)\n self.app.figure.canvas.draw_idle()\n\n def extract_selected(self):\n r0, r1 = self.selected_taxa\n c0, c1 = self.selected_chars\n return self.aln[r0:r1+1,c0:c1+1]\n\n def zoom_cxy(self, x=0.1, y=0.1, cx=None, cy=None):\n \"\"\"\n Zoom the x and y axes in by the specified proportion of the\n current view, with a fixed data point (cx, cy)\n \"\"\"\n transform = self.transData.inverted().transform\n xlim = self.get_xlim(); xmid = sum(xlim)*0.5\n ylim = self.get_ylim(); ymid = sum(ylim)*0.5\n bb = self.get_window_extent()\n bbx = bb.expanded(1.0-x,1.0-y)\n points = transform(bbx.get_points())\n x0, x1 = points[:,0]; y0, y1 = points[:,1]\n deltax = xmid-x0; deltay = ymid-y0\n cx = cx or xmid; cy = cy or ymid\n xoff = (cx-xmid)*x\n self.set_xlim(xmid-deltax+xoff, xmid+deltax+xoff)\n yoff = (cy-ymid)*y\n self.set_ylim(ymid-deltay+yoff, ymid+deltay+yoff)\n\n def zoom(self, x=0.1, y=0.1, cx=None, cy=None):\n \"\"\"\n Zoom the x and y axes in by the specified proportion of the\n current view.\n \"\"\"\n # get the function to convert display coordinates to data\n # coordinates\n transform = self.transData.inverted().transform\n xlim = self.get_xlim()\n ylim = self.get_ylim()\n bb = self.get_window_extent()\n bbx = bb.expanded(1.0-x,1.0-y)\n points = transform(bbx.get_points())\n x0, x1 = points[:,0]; y0, y1 = points[:,1]\n deltax = x0 - xlim[0]; deltay = y0 - ylim[0]\n self.set_xlim(xlim[0]+deltax, xlim[1]-deltax)\n self.set_ylim(ylim[0]+deltay, ylim[1]-deltay)\n\n def center_y(self, y):\n ymin, ymax = self.get_ylim()\n yoff = (ymax - ymin) * 0.5\n self.set_ylim(y-yoff, y+yoff)\n\n def center_x(self, x, offset=0.3):\n xmin, xmax = self.get_xlim()\n xspan = xmax - xmin\n xoff = xspan*0.5 + xspan*offset\n self.set_xlim(x-xoff, x+xoff)\n\n def scroll(self, x, y):\n x0, x1 = self.get_xlim()\n y0, y1 = self.get_ylim()\n xd = (x1-x0)*x\n yd = (y1-y0)*y\n self.set_xlim(x0+xd, x1+xd)\n self.set_ylim(y0+yd, y1+yd)\n\n def home(self):\n self.set_xlim(0, self.nchar)\n self.set_ylim(self.ntax, 0)\n\nAlignmentPlot = subplot_class_factory(Alignment)\n\n", "ivy/vis/hardcopy.py": "import os, matplotlib\nfrom matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas\nfrom matplotlib.figure import Figure\nimport tree\nfrom axes_utils import adjust_limits\nimport tempfile\n\n## class TreeFigure:\n## def __init__(self):\n## pass\n\nmatplotlib.rcParams[\"xtick.direction\"] = \"out\"\n\nclass TreeFigure:\n def __init__(self, root, relwidth=0.5, leafpad=1.5, name=None,\n support=70.0, scaled=True, mark_named=True,\n leaf_fontsize=10, branch_fontsize=10,\n branch_width=1, branch_color=\"black\",\n highlight_support=True,\n branchlabels=True, leaflabels=True, decorators=[],\n xoff=0, yoff=0,\n xlim=None, ylim=None,\n height=None, width=None):\n self.root = root\n self.relwidth = relwidth\n self.leafpad = leafpad\n self.name = name\n self.support = support\n self.scaled = scaled\n self.mark_named = mark_named\n self.leaf_fontsize = leaf_fontsize\n self.branch_fontsize = branch_fontsize\n self.branch_width = branch_width\n self.branch_color = branch_color\n self.highlight_support = highlight_support\n self.branchlabels = branchlabels\n self.leaflabels = leaflabels\n self.decorators = decorators\n self.xoff = xoff\n self.yoff = yoff\n\n nleaves = len(root.leaves())\n self.dpi = 72.0\n h = height or (nleaves*self.leaf_fontsize*self.leafpad)/self.dpi\n self.height = h\n self.width = width or self.height*self.relwidth\n ## p = min(self.width, self.height)*0.1\n ## self.height += p\n ## self.width += p\n self.figure = Figure(figsize=(self.width, self.height), dpi=self.dpi)\n self.canvas = FigureCanvas(self.figure)\n self.axes = self.figure.add_axes(\n tree.TreePlot(self.figure, 1,1,1,\n support=self.support,\n scaled=self.scaled,\n mark_named=self.mark_named,\n leaf_fontsize=self.leaf_fontsize,\n branch_fontsize=self.branch_fontsize,\n branch_width=self.branch_width,\n branch_color=self.branch_color,\n highlight_support=self.highlight_support,\n branchlabels=self.branchlabels,\n leaflabels=self.leaflabels,\n interactive=False,\n decorators=self.decorators,\n xoff=self.xoff, yoff=self.yoff,\n name=self.name).plot_tree(self.root)\n )\n self.axes.spines[\"top\"].set_visible(False)\n self.axes.spines[\"left\"].set_visible(False)\n self.axes.spines[\"right\"].set_visible(False)\n self.axes.spines[\"bottom\"].set_smart_bounds(True)\n self.axes.xaxis.set_ticks_position(\"bottom\")\n\n for v in self.axes.node2label.values():\n v.set_visible(True)\n\n ## for k, v in self.decorators:\n ## func, args, kwargs = v\n ## func(self.axes, *args, **kwargs)\n\n self.canvas.draw()\n ## self.axes.home()\n ## adjust_limits(self.axes)\n self.axes.set_position([0.05,0.05,0.95,0.95])\n\n @property\n def detail(self):\n return self.axes\n \n def savefig(self, fname):\n root, ext = os.path.splitext(fname)\n buf = tempfile.TemporaryFile()\n for i in range(3):\n self.figure.savefig(buf, format=ext[1:].lower())\n self.home()\n buf.seek(0)\n buf.close()\n self.figure.savefig(fname)\n\n def set_relative_width(self, relwidth):\n w, h = self.figure.get_size_inches()\n self.figure.set_figwidth(h*relwidth)\n\n def autoheight(self):\n \"adjust figure height to show all leaf labels\"\n nleaves = len(self.root.leaves())\n h = (nleaves*self.leaf_fontsize*self.leafpad)/self.dpi\n self.height = h\n self.figure.set_size_inches(self.width, self.height)\n self.axes.set_ylim(-2, nleaves+2)\n\n def home(self):\n self.axes.home()\n", "ivy/vis/symbols.py": "\"\"\"\nConvenience functions for drawing shapes on TreePlots.\n\"\"\"\ntry:\n import Image\nexcept ImportError:\n from PIL import Image\nfrom numpy import pi\nfrom matplotlib.collections import RegularPolyCollection, CircleCollection\nfrom matplotlib.transforms import offset_copy\nfrom matplotlib.patches import Rectangle, Wedge, Circle, PathPatch\nfrom matplotlib.offsetbox import DrawingArea\nfrom itertools import izip_longest\nfrom matplotlib.axes import Axes\nfrom numpy import array\nfrom matplotlib.path import Path\n\n\ntry:\n from matplotlib.offsetbox import OffsetImage, AnnotationBbox\nexcept ImportError:\n pass\nfrom ..tree import Node\nimport colors as _colors\n\ndef _xy(plot, p):\n if isinstance(p, Node):\n c = plot.n2c[p]\n p = (c.x, c.y)\n elif isinstance(p, (list, tuple)):\n p = [ _xy(plot, x) for x in p ]\n else:\n pass\n return p\n\n\n\ndef image(plot, p, imgfile,\n maxdim=100, border=0,\n xoff=4, yoff=4,\n halign=0.0, valign=0.5,\n xycoords='data',\n boxcoords=('offset points')):\n \"\"\"\n Add images to plot\n\n Args:\n plot (Tree): A Tree plot instance\n p (Node): A node object\n imgfile (str): A path to an image\n maxdim (float): Maximum dimension of image. Optional,\n defaults to 100.\n border: RR: What does border do? -CZ\n xoff, yoff (float): X and Y offset. Optional, defaults to 4\n halign, valign (float): Horizontal and vertical alignment within\n box. Optional, defaults to 0.0 and 0.5, respectively.\n\n \"\"\"\n if xycoords == \"label\":\n xycoords = plot.node2label[p]\n x, y = (1, 0.5)\n else:\n x, y = _xy(plot, p)\n img = Image.open(imgfile)\n if max(img.size) > maxdim:\n img.thumbnail((maxdim, maxdim))\n imgbox = OffsetImage(img)\n abox = AnnotationBbox(imgbox, (x, y),\n xybox=(xoff, yoff),\n xycoords=xycoords,\n box_alignment=(halign,valign),\n pad=0.0,\n boxcoords=boxcoords)\n plot.add_artist(abox)\n plot.figure.canvas.draw_idle()\n\ndef images(plot, p, imgfiles,\n maxdim=100, border=0,\n xoff=4, yoff=4,\n halign=0.0, valign=0.5,\n xycoords='data', boxcoords=('offset points')):\n \"\"\"\n Add many images to plot at once\n\n Args:\n Plot (Tree): A Tree plot instance\n p (list): A list of node objects\n imgfile (list): A list of strs containing paths to image files.\n Must be the same length as p.\n maxdim (float): Maximum dimension of image. Optional,\n defaults to 100.\n border: RR: What does border do? -CZ\n xoff, yoff (float): X and Y offset. Optional, defaults to 4\n halign, valign (float): Horizontal and vertical alignment within\n box. Optional, defaults to 0.0 and 0.5, respectively.\n\n \"\"\"\n for x, f in zip(p, imgfiles):\n image(plot, x, f, maxdim, border, xoff, yoff, halign, valign,\n xycoords, boxcoords)\n\ndef pie(plot, p, values, colors=None, size=16, norm=True,\n xoff=0, yoff=0,\n halign=0.5, valign=0.5,\n xycoords='data', boxcoords=('offset points')):\n \"\"\"\n Draw a pie chart\n\n Args:\n plot (Tree): A Tree plot instance\n p (Node): A Node object\n values (list): A list of floats.\n colors (list): A list of strings to pull colors from. Optional.\n size (float): Diameter of the pie chart\n norm (bool): Whether or not to normalize the values so they\n add up to 360\n xoff, yoff (float): X and Y offset. Optional, defaults to 0\n halign, valign (float): Horizontal and vertical alignment within\n box. Optional, defaults to 0.5\n\n \"\"\"\n x, y = _xy(plot, p)\n da = DrawingArea(size, size); r = size*0.5; center = (r,r)\n x0 = 0\n S = 360.0\n if norm: S = 360.0/sum(values)\n if not colors:\n c = _colors.tango()\n colors = [ c.next() for v in values ]\n for i, v in enumerate(values):\n theta = v*S\n if v: da.add_artist(Wedge(center, r, x0, x0+theta,\n fc=colors[i], ec='none'))\n x0 += theta\n box = AnnotationBbox(da, (x,y), pad=0, frameon=False,\n xybox=(xoff, yoff),\n xycoords=xycoords,\n box_alignment=(halign,valign),\n boxcoords=boxcoords)\n plot.add_artist(box)\n plot.figure.canvas.draw_idle()\n return box\n\ndef hbar(plot, p, values, colors=None, height=16,\n xoff=0, yoff=0,\n halign=1, valign=0.5,\n xycoords='data', boxcoords=('offset points')):\n x, y = _xy(plot, p)\n h = height; w = sum(values) * height#; yoff=h*0.5\n da = DrawingArea(w, h)\n x0 = -sum(values)\n if not colors:\n c = _colors.tango()\n colors = [ c.next() for v in values ]\n for i, v in enumerate(values):\n if v: da.add_artist(Rectangle((x0,0), v*h, h, fc=colors[i], ec='none'))\n x0 += v*h\n box = AnnotationBbox(da, (x,y), pad=0, frameon=False,\n xybox=(xoff, yoff),\n xycoords=xycoords,\n box_alignment=(halign,valign),\n boxcoords=boxcoords)\n plot.add_artist(box)\n plot.figure.canvas.draw_idle()\n\ndef hbars(plot, p, values, colors=None, height=16,\n xoff=0, yoff=0,\n halign=1, valign=0.5,\n xycoords='data', boxcoords=('offset points')):\n for x, v in zip(p, values):\n hbar(plot, x, v, colors, height, xoff, yoff, halign, valign,\n xycoords, boxcoords)\n\ndef squares(plot, p, colors='r', size=15, xoff=0, yoff=0, alpha=1.0,\n zorder=1000):\n \"\"\"\n Draw a square at given node\n\n Args:\n plot (Tree): A Tree plot instance\n p: A node or list of nodes\n colors: Str or list of strs. Colors of squares to be drawn.\n Optional, defaults to 'r' (red)\n size (float): Size of the squares. Optional, defaults to 15\n xoff, yoff (float): Offset for x and y dimensions. Optional,\n defaults to 0.\n alpha (float): between 0 and 1. Alpha transparency of squares.\n Optional, defaults to 1 (fully opaque)\n zorder (int): The drawing order. Higher numbers appear on top\n of lower numbers. Optional, defaults to 1000.\n\n \"\"\"\n points = _xy(plot, p)\n trans = offset_copy(\n plot.transData, fig=plot.figure, x=xoff, y=yoff, units='points')\n\n col = RegularPolyCollection(\n numsides=4, rotation=pi*0.25, sizes=(size*size,),\n offsets=points, facecolors=colors, transOffset=trans,\n edgecolors='none', alpha=alpha, zorder=zorder\n )\n\n plot.add_collection(col)\n plot.figure.canvas.draw_idle()\n\ndef tipsquares(plot, p, colors='r', size=15, pad=2, edgepad=10):\n \"\"\"\n RR: Bug with this function. If you attempt to call it with a list as an\n argument for p, it will not only not work (expected) but it will also\n make it so that you can't interact with the tree figure (gives errors when\n you try to add symbols, select nodes, etc.) -CZ\n\n Add square after tip label, anchored to the side of the plot\n\n Args:\n plot (Tree): A Tree plot instance.\n p (Node): A Node object (Should be a leaf node).\n colors (str): olor of drawn square. Optional, defaults to 'r' (red)\n size (float): Size of square. Optional, defaults to 15\n pad: RR: I am unsure what this does. Does not seem to have visible\n effect when I change it. -CZ\n edgepad (float): Padding from square to edge of plot. Optional,\n defaults to 10.\n\n \"\"\"\n x, y = _xy(plot, p) # p is a single node or point in data coordinates\n n = len(colors)\n da = DrawingArea(size*n+pad*(n-1), size, 0, 0)\n sx = 0\n for c in colors:\n sq = Rectangle((sx,0), size, size, color=c)\n da.add_artist(sq)\n sx += size+pad\n box = AnnotationBbox(da, (x, y), xybox=(-edgepad,y),\n frameon=False,\n pad=0.0,\n xycoords='data',\n box_alignment=(1, 0.5),\n boxcoords=('axes points','data'))\n plot.add_artist(box)\n plot.figure.canvas.draw_idle()\n\n\ndef circles(plot, p, colors='g', size=15, xoff=0, yoff=0):\n \"\"\"\n Draw circles on plot\n\n Args:\n plot (Tree): A Tree plot instance\n p: A node object or list of Node objects\n colors: Str or list of strs. Colors of the circles. Optional,\n defaults to 'g' (green)\n size (float): Size of the circles. Optional, defaults to 15\n xoff, yoff (float): X and Y offset. Optional, defaults to 0.\n\n \"\"\"\n points = _xy(plot, p)\n trans = offset_copy(\n plot.transData, fig=plot.figure, x=xoff, y=yoff, units='points'\n )\n\n col = CircleCollection(\n sizes=(pi*size*size*0.25,),\n offsets=points, facecolors=colors, transOffset=trans,\n edgecolors='none'\n )\n\n plot.add_collection(col)\n plot.figure.canvas.draw_idle()\n return col\n\ndef legend(plot, colors, labels, shape='rectangle', loc='upper left', **kwargs):\n \"\"\"\n RR: the MPL legend function has changed since this function has been\n written. This function currently does not work. -CZ\n \"\"\"\n if shape == 'circle':\n shapes = [ Circle((0.5,0.5), radius=1, fc=c) for c in colors ]\n #shapes = [ CircleCollection([10],facecolors=[c]) for c in colors ]\n else:\n shapes = [ Rectangle((0,0),1,1,fc=c,ec='none') for c in colors ]\n\n return Axes.legend(plot, shapes, labels, loc=loc, **kwargs)\n\ndef leafspace_triangles(plot, color='black', rca=0.5):\n \"\"\"\n RR: Using this function on the primates tree (straight from the newick file)\n gives error: 'Node' object has no attribute 'leafspace'. How do you give\n nodes the leafspace attribute? -CZ\n rca = relative crown age\n \"\"\"\n leaves = plot.root.leaves()\n leafspace = [ float(x.leafspace) for x in leaves ]\n #leafspace = array(raw_leafspace)/(sum(raw_leafspace)/float(len(leaves)))\n pv = []\n for i, n in enumerate(leaves):\n if leafspace[i] > 0:\n p = plot.n2c[n]\n pp = plot.n2c[n.parent]\n spc = leafspace[i]\n yoff = spc/2.0\n x0 = pp.x + (p.x - pp.x)*rca\n verts = [(x0, p.y),\n (p.x, p.y-yoff),\n (p.x, p.y+yoff),\n (x0, p.y)]\n codes = [Path.MOVETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY]\n path = Path(verts, codes)\n patch = PathPatch(path, fc=color, lw=0)\n pv.append(plot.add_patch(patch))\n return pv\n\ndef text(plot, x, y, s, color='black', xoff=0, yoff=0, valign='center',\n halign='left', fontsize=10):\n \"\"\"\n Add text to the plot.\n\n Args:\n plot (Tree): A Tree plot instance\n x, y (float): x and y coordinates to place the text\n s (str): The text to write\n color (str): The color of the text. Optional, defaults to \"black\"\n xoff, yoff (float): x and y offset\n valign (str): Vertical alignment. Can be: 'center', 'top',\n 'bottom', or 'baseline'. Defaults to 'center'.\n halign (str): Horizontal alignment. Can be: 'center', 'right',\n or 'left'. Defaults to 'left'\n fontsize (float): Font size. Optional, defaults to 10\n\n \"\"\"\n txt = plot.annotate(\n s, xy=(x, y),\n xytext=(xoff, yoff),\n textcoords=\"offset points\",\n verticalalignment=valign,\n horizontalalignment=halign,\n fontsize=fontsize,\n clip_on=True,\n picker=True\n )\n txt.set_visible(True)\n return txt\n", "ivy/vis/tree.py": "\"\"\"\ninteractive viewers for trees, etc. using matplotlib\n\"\"\"\nimport sys, time, bisect, math, types, os, operator\nfrom collections import defaultdict\nfrom itertools import chain\nfrom pprint import pprint\nfrom .. import tree, bipart\nfrom ..layout import cartesian\nfrom ..storage import Storage\nfrom .. import pyperclip as clipboard\n#from ..nodecache import NodeCache\nimport matplotlib, numpy\nimport matplotlib.pyplot as pyplot\nfrom matplotlib.figure import SubplotParams, Figure\nfrom matplotlib.axes import Axes, subplot_class_factory\nfrom matplotlib.patches import PathPatch, Rectangle, Arc\nfrom matplotlib.path import Path\nfrom matplotlib.widgets import RectangleSelector\nfrom matplotlib.transforms import Bbox, offset_copy, IdentityTransform, \\\n Affine2D\nfrom matplotlib import cm as mpl_colormap\nfrom matplotlib import colors as mpl_colors\nfrom matplotlib.colorbar import Colorbar\nfrom matplotlib.collections import RegularPolyCollection, LineCollection, \\\n PatchCollection\nfrom matplotlib.lines import Line2D\ntry:\n from matplotlib.offsetbox import OffsetImage, AnnotationBbox\nexcept ImportError:\n pass\nfrom matplotlib._png import read_png\nfrom matplotlib.ticker import MaxNLocator, FuncFormatter, NullLocator\nfrom mpl_toolkits.axes_grid.anchored_artists import AnchoredText\nfrom mpl_toolkits.axes_grid1.inset_locator import inset_axes\nimport symbols, colors\nimport hardcopy as HC\ntry:\n import Image\nexcept ImportError:\n from PIL import Image\n\n#matplotlib.rcParams['path.simplify'] = False\n\n_tango = colors.tango()\nclass TreeFigure(object):\n \"\"\"\n Window for showing a single tree, optionally with split overview\n and detail panes.\n\n The navigation toolbar at the bottom is provided by matplotlib\n (http://matplotlib.sf.net/users/navigation_toolbar.html). Its\n pan/zoom button and zoom-rectangle button provide different modes\n of mouse interaction with the figure. When neither of these\n buttons are checked, the default mouse bindings are as follows:\n\n * button 1 drag: select nodes - retrieve by calling fig.selected\n * button 3 drag: pan view\n * scroll up/down: zoom in/out\n * scroll up/down with Control key: zoom y-axis\n * scroll up/down with Shift key: zoom x-axis\n * scroll up/down with 'd' key: pan view up/down\n * scroll up/down with 'e' key: pan view left/right\n * click on overview will center the detail pane on that region\n\n Default keybindings:\n\n * t: zoom out to full extent\n * +/-: zoom in/out\n\n Useful attributes and methods (assume an instance named *fig*):\n\n * fig.root - the root node (see [Node methods])\n * fig.highlight(s) - highlight and trace nodes with substring *s*\n * fig.zoom_clade(anc) - zoom to view node *anc* and all its descendants\n * fig.toggle_overview() - toggle visibility of the overview pane\n * fig.toggle_branchlabels() - ditto for branch labels\n * fig.toggle_leaflabels() - ditto for leaf labels\n * fig.decorate(func) - decorate the tree with a function (see\n :ref:`decorating TreeFigures `)\n \"\"\"\n def __init__(self, data, name=None, scaled=True, div=0.25,\n branchlabels=True, leaflabels=True, mark_named=True,\n highlight_support=True, xoff=0, yoff=0,\n overview=True, radial=False):\n self.overview = None\n self.overview_width = div\n self.dataplot = None\n self.dataplot_width = 0.25\n self.name = name\n self.scaled = scaled\n self.branchlabels = branchlabels\n self.leaflabels = leaflabels\n self.mark_named = mark_named\n self.xoff = xoff\n self.yoff = yoff\n self.radial = radial\n if radial:\n self.leaflabels = False\n self.highlighted = set()\n self.highlight_support = highlight_support\n if isinstance(data, tree.Node):\n root = data\n else:\n root = tree.read(data)\n self.root = root\n if not self.root:\n raise IOError, \"cannot coerce data into tree.Node\"\n self.name = self.name or root.treename\n pars = SubplotParams(\n left=0, right=1, bottom=0.05, top=1, wspace=0.01\n )\n fig = pyplot.figure(subplotpars=pars, facecolor=\"white\")\n connect_events(fig.canvas)\n self.figure = fig\n self.initialize_subplots(overview)\n self.home()\n\n def initialize_subplots(self, overview=True):\n if not self.radial:\n tp = TreePlot(self.figure, 1, 2, 2, app=self, name=self.name,\n scaled=self.scaled, branchlabels=self.branchlabels,\n highlight_support=self.highlight_support,\n leaflabels=self.leaflabels,\n mark_named=self.mark_named)\n detail = self.figure.add_subplot(tp)\n detail.set_root(self.root)\n detail.plot_tree()\n self.detail = detail\n tp = OverviewTreePlot(\n self.figure, 121, app=self, scaled=self.scaled,\n branchlabels=False, leaflabels=False,\n mark_named=self.mark_named,\n highlight_support=self.highlight_support,\n target=self.detail\n )\n ov = self.figure.add_subplot(tp)\n ov.set_root(self.root)\n ov.plot_tree()\n self.overview = ov\n if not overview:\n self.toggle_overview(False)\n self.set_positions()\n\n if self.detail.nleaves < 50:\n self.toggle_overview(False)\n else:\n tp = RadialTreePlot(\n self.figure, 111, app=self, name=self.name,\n scaled=self.scaled, branchlabels=self.branchlabels,\n highlight_support=self.highlight_support,\n leaflabels=self.leaflabels, mark_named=self.mark_named\n )\n ax2 = self.figure.add_subplot(tp)\n ax2.set_root(self.root)\n ax2.plot_tree()\n self.detail = ax2\n\n def __get_selected_nodes(self):\n return list(self.detail.selected_nodes)\n\n def __set_selected_nodes(self, nodes):\n self.detail.select_nodes(nodes)\n\n def __del_selected_nodes(self):\n self.detail.select_nodes(None)\n\n selected = property(__get_selected_nodes,\n __set_selected_nodes,\n __del_selected_nodes)\n\n ## def selected_nodes(self):\n ## return self.detail.selected_nodes\n\n @property\n def axes(self):\n return self.detail\n\n def add(self, data, name=None, support=70,\n branchlabels=False, leaflabels=True, mark_named=True):\n \"\"\"\n Add a new tree in a new window\n\n Args:\n data: A node object or tree file.\n name (str): Name of the plot. Defaults to None\n branchlabels (bool): Whether or not to draw branch labels.\n Defaults to False\n leaflabels (bool): Whether or not to draw leaf labels.\n Defaults to True\n \"\"\"\n newfig = MultiTreeFigure()\n ## newfig.add(self.root, name=self.name, support=self.support,\n ## branchlabels=self.branchlabels)\n newfig.add(data, name=name, support=support,\n branchlabels=branchlabels,\n leaflabels=leaflabels,\n mark_named=mark_named)\n return newfig\n\n def toggle_leaflabels(self):\n \"\"\"\n Toggle leaf labels and redraw tree\n \"\"\"\n self.leaflabels = not self.leaflabels\n self.detail.leaflabels = self.leaflabels\n self.redraw()\n\n def toggle_branchlabels(self):\n \"\"\"\n Toggle branch labels and redraw tree\n \"\"\"\n self.branchlabels = not self.branchlabels\n self.detail.branchlabels = self.branchlabels\n self.redraw()\n\n def toggle_overview(self, val=None):\n \"\"\"\n Toggle overview\n \"\"\"\n if val is None:\n if self.overview.get_visible():\n self.overview.set_visible(False)\n self.overview_width = 0.001\n else:\n self.overview.set_visible(True)\n self.overview_width = 0.25\n elif val:\n self.overview.set_visible(True)\n self.overview_width = val\n else:\n self.overview.set_visible(False)\n self.overview_width = 0.001\n self.set_positions()\n\n def set_scaled(self, scaled):\n \"\"\"\n RR: Using this method gives the error:\n redraw takes exactly 1 argument(2 given)-CZ\n Define whether or not the tree is scaled and redraw tree\n\n Args:\n scaled (bool): Whether or not the tree is scaled.\n \"\"\"\n for p in self.overview, self.detail:\n p.redraw(p.set_scaled(scaled))\n self.set_positions()\n\n def on_nodes_selected(self, treeplot):\n pass\n\n def picked(self, e):\n try:\n if e.mouseevent.button==1:\n s = e.artist.get_text()\n clipboard.copy(s)\n print s\n sys.stdout.flush()\n except:\n pass\n\n def ladderize(self, rev=False):\n \"\"\"\n Ladderize and redraw the tree\n \"\"\"\n self.root.ladderize(rev)\n self.redraw()\n\n def show(self):\n \"\"\"\n Plot the figure in a new window\n \"\"\"\n self.figure.show()\n\n def set_positions(self):\n ov = self.overview\n p = self.detail\n dp = self.dataplot\n height = 1.0-p.xoffset()\n if ov:\n box = [0, p.xoffset(), self.overview_width, height]\n ov.set_position(box)\n w = 1.0\n if ov:\n w -= self.overview_width\n if dp:\n w -= self.dataplot_width\n p.set_position([self.overview_width, p.xoffset(), w, height])\n if dp:\n box = [1.0-self.dataplot_width, p.xoffset(),\n self.dataplot_width, height]\n dp.set_position(box)\n self.figure.canvas.draw_idle()\n\n ## def div(self, v=0.3):\n ## assert 0 <= v < 1\n ## self.overview_width = v\n ## self.set_positions()\n ## self.figure.canvas.draw_idle()\n\n def add_dataplot(self):\n \"\"\"\n Add new plot to the side of existing plot\n \"\"\"\n np = 3 if self.overview else 2\n if self.dataplot:\n self.figure.delaxes(self.dataplot)\n self.dataplot = self.figure.add_subplot(1, np, np, sharey=self.detail)\n # left, bottom, width, height (proportions)\n dleft, dbottom, dwidth, dheight = self.detail.get_position().bounds\n # give the dataplot one-quarter the width of the detail axes\n w = dwidth * 0.25\n self.detail.set_position([dleft, dbottom, dwidth-w, dheight])\n self.dataplot.set_position([1-w, dbottom, w, dheight])\n self.dataplot.xaxis.set_visible(False)\n self.dataplot.yaxis.set_visible(False)\n for x in self.dataplot.spines.values():\n x.set_visible(False)\n self.figure.canvas.draw_idle()\n return self.dataplot\n\n def redraw(self):\n \"\"\"\n Replot the figure and overview\n \"\"\"\n self.detail.redraw()\n if self.overview: self.overview.redraw()\n self.highlight()\n self.set_positions()\n self.figure.canvas.draw_idle()\n\n def find(self, x):\n \"\"\"\n Find nodes\n\n Args:\n x (str): String to search\n Returns:\n list: A list of node objects found with the Node findall() method\n \"\"\"\n return self.root.findall(x)\n\n def hlines(self, nodes, width=5, color=\"red\", xoff=0, yoff=0):\n \"\"\"\n Highlight nodes\n\n Args:\n nodes (list): A list of node objects\n width (float): Width of highlighted lines. Defaults to 5\n color (str): Color of highlighted lines. Defaults to red\n xoff (float): Number of units to offset lines by. Defaults to 0\n yoff (float): Number of units to offset lines by. Defaults to 0\n \"\"\"\n self.overview.hlines(nodes, width=width, color=color,\n xoff=xoff, yoff=yoff)\n self.detail.hlines(nodes, width=width, color=color,\n xoff=xoff, yoff=yoff)\n\n def highlight(self, x=None, width=5, color=\"red\"):\n \"\"\"\n Highlight nodes\n\n Args:\n x: Str or list of Strs or Node or list of Nodes\n width (float): Width of highlighted lines. Defaults to 5\n color (str): Color of highlighted lines. Defaults to red\n \"\"\"\n if x:\n nodes = set()\n if type(x) in types.StringTypes:\n nodes = self.root.findall(x)\n elif isinstance(x, tree.Node):\n nodes = set(x)\n else:\n for n in x:\n if type(n) in types.StringTypes:\n found = self.root.findall(n)\n if found:\n nodes |= set(found)\n elif isinstance(n, tree.Node):\n nodes.add(n)\n\n self.highlighted = nodes\n else:\n self.highlighted = set()\n if self.overview:\n self.overview.highlight(self.highlighted, width=width, color=color)\n self.detail.highlight(self.highlighted, width=width, color=color)\n self.figure.canvas.draw_idle()\n\n def home(self):\n \"\"\"\n Return plot to initial size and location.\n \"\"\"\n if self.overview: self.overview.home()\n self.detail.home()\n\n def zoom_clade(self, x):\n \"\"\"\n Zoom to fit a node *x* and all its descendants in the view.\n\n Args:\n x: Node or str that matches the label of a node\n \"\"\"\n if not isinstance(x, tree.Node):\n x = self.root[x]\n self.detail.zoom_clade(x)\n\n def zoom(self, factor=0.1):\n \"\"\"Zoom both axes by *factor* (relative display size).\"\"\"\n self.detail.zoom(factor, factor)\n self.figure.canvas.draw_idle()\n\n def zx(self, factor=0.1):\n \"\"\"Zoom x axis by *factor*.\"\"\"\n self.detail.zoom(factor, 0)\n self.figure.canvas.draw_idle()\n\n def zy(self, factor=0.1):\n \"\"\"Zoom y axis by *factor*.\"\"\"\n self.detail.zoom(0, factor)\n self.figure.canvas.draw_idle()\n\n def decorate(self, func, *args, **kwargs):\n \"\"\"\n Decorate the tree.\n\n Args:\n func (function): A function that takes a TreePlot instance as the\n first parameter, and *args* and *kwargs* as additional\n parameters. It adds boxes, circles, etc to the TreePlot.\n\n Notes:\n If *kwargs* contains the key-value pair ('store', *name*),\n then the function is stored as *name* and re-called every time\n the TreePlot is redrawn, i.e., the decoration is persistent.\n Use ``rmdec(name)`` to remove the decorator from the treeplot.\n \"\"\"\n self.detail.decorate(func, *args, **kwargs)\n\n def rmdec(self, name):\n \"Remove the decoration 'name'.\"\n self.detail.rmdec(name)\n ## if name in self.detail.decorators:\n ## del self.detail.decorators[name]\n\n def cbar(self, node, width=6, color='blue', mrca = True):\n pass\n # self.axes.cbar(nodes = node, width = width, color = color, mrca = mrca)\n\n def unclutter(self, *args):\n self.detail.unclutter()\n\n def trace_branches(self, nodes, width=4, color=\"blue\"):\n \"\"\"\n RR: What is the difference between this and highlight? -CZ\n \"\"\"\n for p in self.overview, self.detail:\n p.trace_branches(nodes, width, color)\n\n def plot_continuous(self, *args, **kwargs):\n self.detail.plot_continuous(*args, **kwargs)\n\n def hardcopy(self, fname=None, relwidth=None, leafpad=1.5):\n if not relwidth:\n bbox = self.detail.get_tightbbox(self.figure.canvas.get_renderer())\n relwidth = bbox.width/bbox.height\n f = self.detail.hardcopy(\n relwidth=relwidth,\n leafpad=leafpad\n )\n f.axes.home()\n #f.axes.set_xlim(*self.detail.get_xlim())\n #f.axes.set_ylim(*self.detail.get_ylim())\n if fname:\n f.savefig(fname)\n return f\n\n def select_nodes(self, nodes=None):\n \"\"\"\n Select nodes on the plot\n\n Args:\n nodes: A node or list of ndoes\n Notes:\n If only one node is given, all of the node's ancestors are\n also selected. If a list of nodes is given (even if it has only\n one node), only the given node(s) are selected.\n \"\"\"\n self.detail.select_nodes(nodes)\n\n def decorate(self, func, *args, **kwargs): # RR: is this repeated from above? -CZ\n self.detail.decorate(func, *args, **kwargs)\n\n ## def dataplot(self):\n ## ax = self.figure.add_subplot(133, sharey=self.detail)\n ## ax.yaxis.set_visible(False)\n ## self.dataplot = ax\n ## return ax\n\n def attach_alignment(self, aln, overview=True):\n \"leaf labels expected to be sequence ids\"\n from Bio.Align import MultipleSeqAlignment\n from Bio.Seq import Seq\n from Bio.SeqRecord import SeqRecord\n from Bio.Alphabet import IUPAC\n from alignment import AlignmentFigure, AlignmentPlot\n if not isinstance(aln, MultipleSeqAlignment):\n from .. import align\n aln = align.read(aln)\n d = dict([ (x.id,x) for x in aln ])\n emptyseq = Seq('-'*aln.get_alignment_length(),\n alphabet=IUPAC.ambiguous_dna)\n aln = MultipleSeqAlignment(\n [ d.get(x.label) or SeqRecord(emptyseq, id=x.label)\n for x in self.root.leaves() ]\n )\n self.aln = aln\n p = AlignmentPlot(self.figure, 133, aln=aln, app=self,\n sharey=self.detail, showy=False)\n self.alnplot = Storage()\n self.alnplot.detail = self.figure.add_subplot(p)\n detail = self.alnplot.detail\n detail.plot_aln()\n if overview:\n self.alnplot.overview = inset_axes(\n detail, width=\"30%\", height=\"20%\", loc=1\n )\n overview = self.alnplot.overview\n overview.xaxis.set_major_locator(NullLocator())\n overview.yaxis.set_major_locator(NullLocator())\n overview.imshow(\n detail.array, interpolation='nearest', aspect='auto',\n origin='lower'\n )\n rect = UpdatingRect(\n [0,0], 0, 0, facecolor='black', edgecolor='cyan', alpha=0.5\n )\n overview.zoomrect = rect\n rect.target = detail\n detail.callbacks.connect('xlim_changed', rect)\n detail.callbacks.connect('ylim_changed', rect)\n overview.add_patch(rect)\n rect(overview)\n self.toggle_overview(False)\n xoff = self.detail.xoffset()\n self.detail.set_position([0, xoff, 0.3, 1.0-xoff])\n p.set_position([0.3, xoff, 0.7, 1.0-xoff])\n\n\nclass MultiTreeFigure(object):\n \"\"\"\n Window for showing multiple trees side-by-side.\n\n TODO: document this\n \"\"\"\n def __init__(self, trees=None, name=None, support=70,\n scaled=True, branchlabels=False, radial=False):\n \"\"\"\n *trees* are assumed to be objects suitable for passing to\n ivy.tree.read()\n \"\"\"\n self.root = []\n self.name = name\n self.name2plot = {}\n self.plot = []\n self.scaled = scaled\n self.branchlabels = branchlabels\n self.radial = radial\n self.highlighted = set()\n self.divs = []\n pars = SubplotParams(\n left=0, right=1, bottom=0.05, top=1, wspace=0.04\n )\n fig = pyplot.figure(subplotpars=pars)\n connect_events(fig.canvas)\n self.figure = fig\n\n for x in trees or []:\n self.add(x, support=support, scaled=scaled,\n branchlabels=branchlabels)\n\n def on_nodes_selected(self, treeplot):\n pass\n\n def clear(self):\n self.root = []\n self.name2plot = {}\n self.highlighted = set()\n self.divs = []\n self.figure.clf()\n\n def picked(self, e):\n try:\n if e.mouseevent.button==1:\n print e.artist.get_text()\n sys.stdout.flush()\n except:\n pass\n\n def getplot(self, x):\n p = None\n try:\n i = self.root.index(x)\n return self.plot[i]\n except ValueError:\n return self.name2plot.get(x)\n\n def add(self, data, name=None, support=70, scaled=True,\n branchlabels=False, leaflabels=True, mark_named=True):\n root = None\n if isinstance(data, tree.Node):\n root = data\n else:\n root = tree.read(data)\n if not root:\n raise IOError, \"cannot coerce data into tree.Node\"\n\n name = name or root.treename\n self.root.append(root)\n\n fig = self.figure\n N = len(self.plot)+1\n for i, p in enumerate(self.plot):\n p.change_geometry(1, N, i+1)\n plt = TreePlot(fig, 1, N, N, app=self, name=name, support=support,\n scaled=scaled, branchlabels=branchlabels,\n leaflabels=leaflabels, mark_named=mark_named)\n p = fig.add_subplot(plt)\n p.set_root(root)\n p.plot_tree()\n p.index = N-1\n self.plot.append(p)\n if name:\n assert name not in self.name2plot\n self.name2plot[name] = p\n\n ## global IP\n ## if IP:\n ## def f(shell, s):\n ## self.highlight(s)\n ## return sorted([ x.label for x in self.highlighted ])\n ## IP.expose_magic(\"highlight\", f)\n ## def f(shell, s):\n ## self.root.ladderize()\n ## self.redraw()\n ## IP.expose_magic(\"ladderize\", f)\n ## def f(shell, s):\n ## self.show()\n ## IP.expose_magic(\"show\", f)\n ## def f(shell, s):\n ## self.redraw()\n ## IP.expose_magic(\"redraw\", f)\n return p\n\n def show(self):\n self.figure.show()\n\n def redraw(self):\n for p in self.plot:\n p.redraw()\n self.figure.canvas.draw_idle()\n\n def ladderize(self, reverse=False):\n for n in self.root:\n n.ladderize(reverse)\n self.redraw()\n\n def highlight(self, s=None, add=False, width=5, color=\"red\"):\n \"\"\"\n Highlight nodes\n\n Args:\n s: Str or list of Strs or Node or list of Nodes\n add (bool): Whether to add to existing highlighted nodes or\n overwrite them.\n width (float): Width of highlighted lines. Defaults to 5\n color (str): Color of highlighted lines. Defaults to red\n \"\"\"\n if not s:\n self.highlighted = set()\n if not add:\n self.highlighted = set()\n\n nodesets = [ p.root.findall(s) for p in self.plot ]\n\n for nodes, p in zip(nodesets, self.plot):\n if nodes:\n p.highlight(nodes, width=width, color=color)\n else:\n p.highlight()\n\n self.highlighted = nodesets\n self.figure.canvas.draw_idle()\n\n ## for root in self.root:\n ## for node in root.iternodes():\n ## if node.label and (s in node.label):\n ## self.highlighted.add(node)\n ## self.highlight()\n\n def home(self):\n for p in self.plot: p.home()\n\n\ndef connect_events(canvas):\n mpl_connect = canvas.mpl_connect\n mpl_connect(\"button_press_event\", onclick)\n mpl_connect(\"button_release_event\", onbuttonrelease)\n mpl_connect(\"scroll_event\", onscroll)\n mpl_connect(\"pick_event\", onpick)\n mpl_connect(\"motion_notify_event\", ondrag)\n mpl_connect(\"key_press_event\", onkeypress)\n mpl_connect(\"axes_enter_event\", axes_enter)\n mpl_connect(\"axes_leave_event\", axes_leave)\n\nclass UpdatingRect(Rectangle):\n def __call__(self, p):\n self.set_bounds(*p.viewLim.bounds)\n p.figure.canvas.draw_idle()\n\nclass Tree(Axes):\n \"\"\"\n matplotlib.axes.Axes subclass for rendering trees.\n \"\"\"\n def __init__(self, fig, rect, *args, **kwargs):\n self.root = None\n self.app = kwargs.pop(\"app\", None)\n self.support = kwargs.pop(\"support\", 70.0)\n self.scaled = kwargs.pop(\"scaled\", True)\n self.leaflabels = kwargs.pop(\"leaflabels\", True)\n self.branchlabels = kwargs.pop(\"branchlabels\", True)\n self._mark_named = kwargs.pop(\"mark_named\", True)\n self.name = None\n self.leaf_fontsize = kwargs.pop(\"leaf_fontsize\", 10)\n self.branch_fontsize = kwargs.pop(\"branch_fontsize\", 10)\n self.branch_width = kwargs.pop(\"branch_width\", 1)\n self.branch_color = kwargs.pop(\"branch_color\", \"black\")\n self.interactive = kwargs.pop(\"interactive\", True)\n self.decorators = kwargs.pop(\"decorators\", [])\n ## if self.decorators:\n ## print >> sys.stderr, \"got %s decorators\" % len(self.decorators)\n self.xoff = kwargs.pop(\"xoff\", 0)\n self.yoff = kwargs.pop(\"yoff\", 0)\n self.highlight_support = kwargs.pop(\"highlight_support\", True)\n self.smooth_xpos = kwargs.pop(\"smooth_xpos\", 0)\n Axes.__init__(self, fig, rect, *args, **kwargs)\n self.nleaves = 0\n self.highlighted = None\n self.highlightpatch = None\n self.pan_start = None\n if not self.decorators:\n self.decorators = [\n (\"__selected_nodes__\", (Tree.highlight_selected_nodes, [], {}))\n ]\n self.name2dec = dict([ (x[0], i) for i, x in\n enumerate(self.decorators) ])\n self._active = False\n\n if self.interactive:\n self.callbacks.connect(\"ylim_changed\", self.draw_labels)\n self.selector = RectangleSelector(self, self.rectselect,\n useblit=True)\n def f(e):\n if e.button != 1: return True\n else: return RectangleSelector.ignore(self.selector, e)\n self.selector.ignore = f\n self.xoffset_value = 0.05\n self.selected_nodes = set()\n self.leaf_offset = 4\n self.leaf_valign = \"center\"\n self.leaf_halign = \"left\"\n self.branch_offset = -5\n self.branch_valign = \"center\"\n self.branch_halign = \"right\"\n\n self.spines[\"top\"].set_visible(False)\n self.spines[\"left\"].set_visible(False)\n self.spines[\"right\"].set_visible(False)\n self.xaxis.set_ticks_position(\"bottom\")\n\n def p2y(self):\n \"Convert a single display point to y-units\"\n transform = self.transData.inverted().transform\n return transform([0,1])[1] - transform([0,0])[1]\n\n def p2x(self):\n \"Convert a single display point to y-units\"\n transform = self.transData.inverted().transform\n return transform([0,0])[1] - transform([1,0])[1]\n\n def decorate(self, func, *args, **kwargs):\n \"\"\"\n Decorate the tree with function *func*. If *kwargs* contains\n the key-value pair ('store', *name*), the decorator function\n is stored in self.decorators and called upon every redraw.\n \"\"\"\n name = kwargs.pop(\"store\", None)\n if name:\n if name in self.name2dec:\n i = self.name2dec[name]\n self.decorators[i] = (name, (func, args, kwargs))\n else:\n self.decorators.append((name, (func, args, kwargs)))\n self.name2dec = dict([ (x[0], i) for i, x in\n enumerate(self.decorators) ])\n\n func(self, *args, **kwargs)\n\n def rmdec(self, name):\n if name in self.name2dec:\n i = self.name2dec[name]\n del self.decorators[i]\n self.name2dec = dict([ (x[0], i) for i, x in\n enumerate(self.decorators) ])\n\n\n def flip(self):\n \"\"\"\n Reverse the direction of the x-axis.\n \"\"\"\n self.leaf_offset *= -1\n self.branch_offset *= -1\n ha = self.leaf_halign\n self.leaf_halign = \"right\" if ha == \"left\" else \"left\"\n ha = self.branch_halign\n self.branch_halign = \"right\" if ha == \"left\" else \"left\"\n self.invert_xaxis()\n self.redraw()\n\n def xoffset(self):\n \"\"\"Space below x axis to show tick labels.\"\"\"\n if self.scaled:\n return self.xoffset_value\n else:\n return 0\n\n def save_newick(self, filename):\n \"\"\"\n Save tree as a newick file.\n\n Args:\n filename (str): Path to file.\n\n \"\"\"\n if os.path.exists(filename):\n s = raw_input(\"File %s exists, enter 'y' to overwrite \").strip()\n if (s and s.lower() != 'y') or (not s):\n return\n import newick\n f = file(filename, \"w\")\n f.write(newick.string(self.root))\n f.close()\n\n def set_scaled(self, scaled):\n flag = self.scaled != scaled\n self.scaled = scaled\n return flag\n\n def cbar(self, nodes, color=None, label=None, x=None, width=8, xoff=10,\n showlabel=True, mrca=True):\n \"\"\"\n Draw a 'clade' bar (i.e., along the y-axis) indicating a\n clade. *nodes* are assumed to be one or more nodes in the\n tree. If just one, it should be the internal node\n representing the clade of interest; otherwise, the clade of\n interest is the most recent common ancestor of the specified\n nodes. *label* is an optional string to be drawn next to the\n bar, *offset* by the specified number of display units. If\n *label* is ``None`` then the clade's label is used instead.\n\n Args:\n nodes: Node or list of nodes\n color (str): Color of the bar. Optional, defaults to None.\n label (str): Optional label for bar. If None, the clade's\n label is used instead. Defaults to None.\n width (float): Width of bar\n xoff (float): Offset from label to bar\n showlabel (bool): Whether or not to draw the label\n mrca: RR: Not quite sure what this does -CZ\n\n \"\"\"\n xlim = self.get_xlim(); ylim = self.get_ylim()\n if color is None: color = _tango.next()\n transform = self.transData.inverted().transform\n\n if mrca:\n if isinstance(nodes, tree.Node):\n spec = nodes\n elif type(nodes) in types.StringTypes:\n spec = self.root.get(nodes)\n else:\n spec = self.root.mrca(nodes)\n\n assert spec in self.root\n label = label or spec.label\n leaves = spec.leaves()\n\n else:\n leaves = nodes\n\n n2c = self.n2c\n\n y = sorted([ n2c[n].y for n in leaves ])\n ymin = y[0]; ymax = y[-1]; y = (ymax+ymin)*0.5\n\n if x is None:\n x = max([ n2c[n].x for n in leaves ])\n _x = 0\n for lf in leaves:\n txt = self.node2label.get(lf)\n if txt and txt.get_visible():\n _x = max(_x, transform(txt.get_window_extent())[1,0])\n if _x > x: x = _x\n\n v = sorted(list(transform(((0,0),(xoff,0)))[:,0]))\n xoff = v[1]-v[0]\n x += xoff\n\n Axes.plot(self, [x,x], [ymin, ymax], '-', linewidth=width, color=color)\n\n if showlabel and label:\n xo = self.leaf_offset\n if xo > 0:\n xo += width*0.5\n else:\n xo -= width*0.5\n txt = self.annotate(\n label,\n xy=(x, y),\n xytext=(xo, 0),\n textcoords=\"offset points\",\n verticalalignment=self.leaf_valign,\n horizontalalignment=self.leaf_halign,\n fontsize=self.leaf_fontsize,\n clip_on=True,\n picker=False\n )\n\n self.set_xlim(xlim); self.set_ylim(ylim)\n\n def anctrace(self, anc, descendants=None, width=4, color=\"blue\"):\n \"\"\"\n RR: This function gives me a 'list index out of range' error\n when I try to use it -CZ\n \"\"\"\n if not descendants:\n descendants = anc.leaves()\n else:\n for d in descendants:\n assert d in anc\n\n nodes = []\n for d in descendants:\n v = d.rootpath(anc)\n if v:\n nodes.extend(v)\n nodes = set(nodes)\n nodes.remove(anc)\n self.trace_branches(nodes, width, color)\n\n def trace_branches(self, nodes, width=4, color=\"blue\"):\n n2c = self.n2c\n M = Path.MOVETO; L = Path.LINETO\n verts = []\n codes = []\n for c, pc in [ (n2c[x], n2c[x.parent]) for x in nodes\n if (x in n2c) and x.parent ]:\n x = c.x; y = c.y\n px = pc.x; py = pc.y\n verts.append((x, y)); codes.append(M)\n verts.append((px, y)); codes.append(L)\n verts.append((px, py)); codes.append(L)\n px, py = verts[-1]\n verts.append((px, py)); codes.append(M)\n\n p = PathPatch(Path(verts, codes), fill=False,\n linewidth=width, edgecolor=color)\n self.add_patch(p)\n self.figure.canvas.draw_idle()\n return p\n\n def highlight_selected_nodes(self, color=\"green\"):\n xlim = self.get_xlim()\n ylim = self.get_ylim()\n get = self.n2c.get\n coords = filter(None, [ get(n) for n in self.selected_nodes ])\n x = [ c.x for c in coords ]\n y = [ c.y for c in coords ]\n if x and y:\n self.__selected_highlight_patch = self.scatter(x, y, s=60, c=color,\n zorder=100)\n self.set_xlim(xlim)\n self.set_ylim(ylim)\n self.figure.canvas.draw_idle()\n\n def select_nodes(self, nodes=None, add=False):\n try:\n self.__selected_highlight_patch.remove()\n self.figure.canvas.draw_idle()\n except:\n pass\n if add:\n if nodes:\n self.selected_nodes = self.selected_nodes | nodes\n if hasattr(self, \"app\") and self.app:\n self.app.on_nodes_selected(self)\n self.highlight_selected_nodes()\n else:\n if nodes:\n self.selected_nodes = nodes\n if hasattr(self, \"app\") and self.app:\n self.app.on_nodes_selected(self)\n self.highlight_selected_nodes()\n else:\n self.selected_nodes = set()\n\n def rectselect(self, e0, e1):\n xlim = self.get_xlim()\n ylim = self.get_ylim()\n s = set()\n x0, x1 = sorted((e0.xdata, e1.xdata))\n y0, y1 = sorted((e0.ydata, e1.ydata))\n add = e0.key == 'shift'\n for n, c in self.n2c.items():\n if (x0 < c.x < x1) and (y0 < c.y < y1):\n s.add(n)\n self.select_nodes(nodes = s, add = add)\n self.set_xlim(xlim)\n self.set_ylim(ylim)\n ## if s:\n ## print \"Selected:\"\n ## for n in s:\n ## print \" \", n\n\n def picked(self, e):\n if hasattr(self, \"app\") and self.app:\n self.app.picked(e)\n\n def window2data(self, expandx=1.0, expandy=1.0):\n \"\"\"\n return the data coordinates ((x0, y0),(x1, y1)) of the plot\n window, expanded by relative units of window size\n \"\"\"\n bb = self.get_window_extent()\n bbx = bb.expanded(expandx, expandy)\n return self.transData.inverted().transform(bbx.get_points())\n\n def get_visible_nodes(self, labeled_only=False):\n ## transform = self.transData.inverted().transform\n ## bb = self.get_window_extent()\n ## bbx = bb.expanded(1.1,1.1)\n ## ((x0, y0),(x1, y1)) = transform(bbx.get_points())\n ((x0, y0),(x1, y1)) = self.window2data(1.1, 1.1)\n #print \"visible_nodes points\", x0, x1, y0, y1\n\n if labeled_only:\n def f(v): return (y0 < v[0] < y1) and (v[2] in self.node2label)\n else:\n def f(v): return (y0 < v[0] < y1)\n for y, x, n in filter(f, self.coords):\n yield (n, x, y)\n\n def zoom_cxy(self, x=0.1, y=0.1, cx=None, cy=None):\n \"\"\"\n Zoom the x and y axes in by the specified proportion of the\n current view, with a fixed data point (cx, cy)\n \"\"\"\n transform = self.transData.inverted().transform\n xlim = self.get_xlim(); xmid = sum(xlim)*0.5\n ylim = self.get_ylim(); ymid = sum(ylim)*0.5\n bb = self.get_window_extent()\n bbx = bb.expanded(1.0-x,1.0-y)\n points = transform(bbx.get_points())\n x0, x1 = points[:,0]; y0, y1 = points[:,1]\n deltax = xmid-x0; deltay = ymid-y0\n cx = cx or xmid; cy = cy or ymid\n xoff = (cx-xmid)*x\n self.set_xlim(xmid-deltax+xoff, xmid+deltax+xoff)\n yoff = (cy-ymid)*y\n self.set_ylim(ymid-deltay+yoff, ymid+deltay+yoff)\n self.adjust_xspine()\n\n def zoom(self, x=0.1, y=0.1, cx=None, cy=None):\n \"\"\"\n Zoom the x and y axes in by the specified proportion of the\n current view.\n \"\"\"\n # get the function to convert display coordinates to data\n # coordinates\n transform = self.transData.inverted().transform\n xlim = self.get_xlim()\n ylim = self.get_ylim()\n bb = self.get_window_extent()\n bbx = bb.expanded(1.0-x,1.0-y)\n points = transform(bbx.get_points())\n x0, x1 = points[:,0]; y0, y1 = points[:,1]\n deltax = x0 - xlim[0]; deltay = y0 - ylim[0]\n self.set_xlim(xlim[0]+deltax, xlim[1]-deltax)\n self.set_ylim(ylim[0]+deltay, ylim[1]-deltay)\n self.adjust_xspine()\n\n def center_y(self, y):\n \"\"\"\n Center the y-axis of the canvas on the given y value\n \"\"\"\n ymin, ymax = self.get_ylim()\n yoff = (ymax - ymin) * 0.5\n self.set_ylim(y-yoff, y+yoff)\n self.adjust_xspine()\n\n def center_x(self, x, offset=0.3):\n \"\"\"\n Center the x-axis of the canvas on the given x value\n \"\"\"\n xmin, xmax = self.get_xlim()\n xspan = xmax - xmin\n xoff = xspan*0.5 + xspan*offset\n self.set_xlim(x-xoff, x+xoff)\n self.adjust_xspine()\n\n def center_node(self, node):\n \"\"\"\n Center the canvas on the given node\n \"\"\"\n c = self.n2c[node]\n y = c.y\n self.center_y(y)\n x = c.x\n self.center_x(x, 0.2)\n\n def do_highlight_support(self):\n \"\"\"\n TODO: reconfigure this, insert into self.decorators\n \"\"\"\n if self.support:\n lim = float(self.support)\n\n M = Path.MOVETO; L = Path.LINETO\n\n verts = []; codes = []\n segments = []\n def f(n):\n if n.isleaf or not n.parent: return False\n try: return float(n.label) >= lim\n except:\n try: return float(n.support) >= lim\n except: pass\n return False\n\n for node, coords in [ x for x in self.n2c.items() if f(x[0]) ]:\n x = coords.x; y = coords.y\n p = node.parent\n pcoords = self.n2c[p]\n px = pcoords.x; py = y\n if self.app and self.app.radial:\n pc = self.n2c[node.parent]; theta2 = pc.angle\n px = math.cos(math.radians(coords.angle))*pc.depth\n py = math.sin(math.radians(coords.angle))*pc.depth\n\n ## segments.append([(x, y),(px, y)])\n verts.append((x,y)); codes.append(M)\n verts.append((px,py)); codes.append(L)\n\n if verts:\n patch = PathPatch(Path(verts, codes), fill=False,\n linewidth=3, edgecolor='black')\n self.add_patch(patch)\n\n ## self.add_artist(Line2D(\n ## [x,px], [y,py], lw=3, solid_capstyle=\"butt\", color=\"black\"\n ## ))\n\n def hl(self, s):\n nodes = self.root.findall(s)\n if nodes:\n self.highlight(nodes)\n\n def hlines(self, nodes, width=5, color=\"red\", xoff=0, yoff=0):\n offset = IdentityTransform()\n segs = []; w = []; o = []\n for n in filter(lambda x:x.parent, nodes):\n c = self.n2c[n]; p = self.n2c[n.parent]\n segs.append(((p.x,c.y),(c.x,c.y)))\n w.append(width); o.append((xoff,yoff))\n lc = LineCollection(segs, linewidths=w, transOffset=offset, offsets=o)\n lc.set_color(color)\n Axes.add_collection(self, lc)\n ## self.drawstack.append((\"hlines\", [nodes], dict(width=width,\n ## color=color,\n ## xoff=xoff,\n ## yoff=yoff)))\n self.figure.canvas.draw_idle()\n return lc\n\n def hardcopy(self, relwidth=0.5, leafpad=1.5):\n p = HC.TreeFigure(self.root, relwidth=relwidth, leafpad=leafpad,\n name=self.name, support=self.support,\n leaf_fontsize=self.leaf_fontsize,\n branch_fontsize=self.branch_fontsize,\n branch_width=self.branch_width,\n branch_color=self.branch_color,\n highlight_support=self.highlight_support,\n branchlabels=self.branchlabels,\n decorators=self.decorators,\n leaflabels=self.leaflabels,\n mark_named=self._mark_named,\n xlim=self.get_xlim(),\n ylim=self.get_ylim())\n return p\n\n def highlight(self, nodes=None, width=5, color=\"red\"):\n if self.highlightpatch:\n try:\n self.highlightpatch.remove()\n except:\n pass\n if not nodes:\n return\n\n if len(nodes)>1:\n mrca = self.root.mrca(nodes)\n if not mrca:\n return\n else:\n mrca = list(nodes)[0]\n\n M = Path.MOVETO; L = Path.LINETO\n verts = []\n codes = []\n seen = set()\n for node, coords in [ x for x in self.n2c.items() if x[0] in nodes ]:\n x = coords.x; y = coords.y\n p = node.parent\n while p:\n pcoords = self.n2c[p]\n px = pcoords.x; py = pcoords.y\n if node not in seen:\n verts.append((x, y)); codes.append(M)\n verts.append((px, y)); codes.append(L)\n verts.append((px, py)); codes.append(L)\n seen.add(node)\n if p == mrca or node == mrca:\n break\n node = p\n coords = self.n2c[node]\n x = coords.x; y = coords.y\n p = node.parent\n px, py = verts[-1]\n verts.append((px, py)); codes.append(M)\n\n self.highlightpath = Path(verts, codes)\n self.highlightpatch = PathPatch(\n self.highlightpath, fill=False, linewidth=width, edgecolor=color,\n capstyle='round', joinstyle='round'\n )\n return self.add_patch(self.highlightpatch)\n\n def find(self, s):\n \"\"\"\n Find node(s) matching pattern s and zoom to node(s)\n \"\"\"\n nodes = list(self.root.find(s))\n if nodes:\n self.zoom_nodes(nodes)\n\n def zoom_nodes(self, nodes, border=1.2):\n y0, y1 = self.get_ylim(); x0, x1 = self.get_xlim()\n y0 = max(0, y0); y1 = min(1, y1)\n\n n2c = self.n2c\n v = [ n2c[n] for n in nodes ]\n ymin = min([ c.y for c in v ])\n ymax = max([ c.y for c in v ])\n xmin = min([ c.x for c in v ])\n xmax = max([ c.x for c in v ])\n bb = Bbox(((xmin,ymin), (xmax, ymax)))\n\n # convert data coordinates to display coordinates\n transform = self.transData.transform\n disp_bb = [Bbox(transform(bb))]\n for n in nodes:\n if n.isleaf:\n txt = self.node2label[n]\n if txt.get_visible():\n disp_bb.append(txt.get_window_extent())\n\n disp_bb = Bbox.union(disp_bb).expanded(border, border)\n\n # convert back to data coordinates\n points = self.transData.inverted().transform(disp_bb)\n x0, x1 = points[:,0]\n y0, y1 = points[:,1]\n self.set_xlim(x0, x1)\n self.set_ylim(y0, y1)\n\n def zoom_clade(self, anc, border=1.2):\n if anc.isleaf:\n self.center_node(anc)\n\n else:\n self.zoom_nodes(list(anc), border)\n\n def draw_leaf_labels(self, *args):\n leaves = list(filter(lambda x:x[0].isleaf,\n self.get_visible_nodes(labeled_only=True)))\n psep = self.leaf_pixelsep()\n fontsize = min(self.leaf_fontsize, max(psep, 8))\n n2l = self.node2label\n transform = self.transData.transform\n sub = operator.sub\n\n for n in leaves:\n n2l[n[0]].set_visible(False)\n\n # draw leaves\n leaves_drawn = []\n for n, x, y in leaves:\n txt = self.node2label[n]\n if not leaves_drawn:\n txt.set_visible(True)\n leaves_drawn.append(txt)\n self.figure.canvas.draw_idle()\n continue\n\n txt2 = leaves_drawn[-1]\n y0 = y; y1 = txt2.xy[1]\n sep = sub(*transform(([0,y0],[0,y1]))[:,1])\n if sep > fontsize:\n txt.set_visible(True)\n txt.set_size(fontsize)\n leaves_drawn.append(txt)\n self.figure.canvas.draw_idle()\n\n if leaves_drawn:\n leaves_drawn[0].set_size(fontsize)\n\n return fontsize\n\n def draw_labels(self, *args):\n fs = max(10, self.draw_leaf_labels())\n nodes = self.get_visible_nodes(labeled_only=True)\n ## print [ x[0].id for x in nodes ]\n branches = list(filter(lambda x:(not x[0].isleaf), nodes))\n n2l = self.node2label\n for n, x, y in branches:\n t = n2l[n]\n t.set_visible(True)\n t.set_size(fs)\n\n def unclutter(self, *args):\n nodes = self.get_visible_nodes(labeled_only=True)\n branches = list(filter(lambda x:(not x[0].isleaf), nodes))\n psep = self.leaf_pixelsep()\n n2l = self.node2label\n fontsize = min(self.leaf_fontsize*1.2, max(psep, self.leaf_fontsize))\n\n drawn = []\n for n, x, y in branches:\n txt = n2l[n]\n try:\n bb = txt.get_window_extent().expanded(2, 2)\n vis = True\n for n2 in reversed(drawn):\n txt2 = n2l[n2]\n if bb.overlaps(txt2.get_window_extent()):\n txt.set_visible(False)\n vis = False\n self.figure.canvas.draw_idle()\n break\n if vis:\n txt.set_visible(True)\n txt.set_size(fontsize)\n self.figure.canvas.draw_idle()\n drawn.append(n)\n except RuntimeError:\n pass\n ## txt.set_visible(True)\n ## txt.set_size(fontsize)\n ## drawn.append(n)\n ## self.figure.canvas.draw_idle()\n\n def leaf_pixelsep(self):\n y0, y1 = self.get_ylim()\n y0 = max(0, y0)\n y1 = min(self.nleaves, y1)\n display_points = self.transData.transform(((0, y0), (0, y1)))\n # height in pixels (visible y data extent)\n height = operator.sub(*reversed(display_points[:,1]))\n pixelsep = height/((y1-y0)/self.leaf_hsep)\n return pixelsep\n\n def ypp(self):\n y0, y1 = self.get_ylim()\n p0, p1 = self.transData.transform(((0, y0), (0, y1)))[:,1]\n return (y1-y0)/float(p1-p0)\n\n def draw_labels_old(self, *args):\n if self.nleaves:\n y0, y1 = self.get_ylim()\n y0 = max(0, y0); y1 = min(1, y1)\n\n display_points = self.transData.transform(((0, y0), (0, y1)))\n # height in pixels (visible y data extent)\n height = operator.sub(*reversed(display_points[:,1]))\n pixelsep = height/((y1-y0)/self.leaf_hsep)\n fontsize = min(max(pixelsep-2, 8), 12)\n\n if pixelsep >= 8:\n for node, txt in self.node2label.items():\n if node.isleaf:\n if self.leaflabels:\n c = self.n2c[node]\n x = c.x; y = c.y\n if (y0 < y < y1):\n txt.set_size(fontsize)\n txt.set_visible(True)\n else:\n if self.branchlabels:\n c = self.n2c[node]\n x = c.x; y = c.y\n if (y0 < y < y1):\n txt.set_size(fontsize)\n txt.set_visible(True)\n elif pixelsep >= 4:\n for node, txt in self.node2label.items():\n if node.isleaf:\n txt.set_visible(False)\n else:\n if self.branchlabels:\n c = self.n2c[node]\n x = c.x; y = c.y\n if (y0 < y < y1):\n txt.set_size(fontsize)\n txt.set_visible(True)\n else:\n for node, txt in self.node2label.items():\n txt.set_visible(False)\n self.figure.canvas.draw_idle()\n\n def redraw(self, home=False, layout=True):\n \"\"\"\n Replot the tree\n \"\"\"\n xlim = self.get_xlim()\n ylim = self.get_ylim()\n self.cla()\n if layout:\n self.layout()\n self.plot_tree()\n if self.interactive:\n self.callbacks.connect(\"ylim_changed\", self.draw_labels)\n\n if home:\n self.home()\n else:\n self.set_xlim(*xlim)\n self.set_ylim(*ylim)\n\n def set_name(self, name):\n self.name = name\n if name:\n at = AnchoredText(\n self.name, loc=2, frameon=True,\n prop=dict(size=12, weight=\"bold\")\n )\n at.patch.set_linewidth(0)\n at.patch.set_facecolor(\"white\")\n at.patch.set_alpha(0.6)\n self.add_artist(at)\n return at\n\n def _path_to_parent(self, node):\n \"\"\"\n For use in drawing branches\n \"\"\"\n c = self.n2c[node]; x = c.x; y = c.y\n pc = self.n2c[node.parent]; px = pc.x; py = pc.y\n M = Path.MOVETO; L = Path.LINETO\n verts = [(x, y), (px, y), (px, py)]\n codes = [M, L, L]\n return verts, codes\n ## return [PathPatch(Path(verts, codes), fill=False,\n ## linewidth=width or self.branch_width,\n ## edgecolor=color or self.branch_color)]\n\n\n def layout(self):\n self.n2c = cartesian(self.root, scaled=self.scaled, yunit=1.0,\n smooth=self.smooth_xpos)\n for c in self.n2c.values():\n c.x += self.xoff; c.y += self.yoff\n sv = sorted([\n [c.y, c.x, n] for n, c in self.n2c.items()\n ])\n self.coords = sv#numpy.array(sv)\n ## n2c = self.n2c\n ## self.node2linesegs = {}\n ## for node, coords in n2c.items():\n ## x = coords.x; y = coords.y\n ## v = [(x,y)]\n ## if node.parent:\n ## pcoords = n2c[node.parent]\n ## px = pcoords.x; py = pcoords.y\n ## v.append((px,y))\n ## v.append((px,py))\n ## self.node2linesegs[node] = v\n\n def set_root(self, root):\n self.root = root\n self.leaves = root.leaves()\n self.nleaves = len(self.leaves)\n self.leaf_hsep = 1.0#/float(self.nleaves)\n\n for n in root.descendants():\n if n.length is None:\n self.scaled=False; break\n self.layout()\n\n def plot_tree(self, root=None, **kwargs):\n \"\"\"\n Draw branches and labels\n \"\"\"\n if root and not self.root:\n self.set_root(root)\n\n if self.interactive: pyplot.ioff()\n\n if \"branchlabels\" in kwargs:\n self.branchlabels = kwargs[\"branchlabels\"]\n if \"leaflabels\" in kwargs:\n self.leaflabels = kwargs[\"leaflabels\"]\n self.yaxis.set_visible(False)\n self.create_branch_artists()\n self.create_label_artists()\n if self.highlight_support:\n self.do_highlight_support()\n self.mark_named()\n ## self.home()\n\n for k, v in self.decorators:\n func, args, kwargs = v\n func(self, *args, **kwargs)\n\n self.set_name(self.name)\n self.adjust_xspine()\n\n if self.interactive: pyplot.ion()\n\n labels = [ x.label for x in self.root.leaves() ]\n def fmt(x, pos=None):\n if x<0: return \"\"\n try: return labels[int(round(x))]\n except: pass\n return \"\"\n #self.yaxis.set_major_formatter(FuncFormatter(fmt))\n\n return self\n\n def clade_dimensions(self):\n n2c = self.n2c\n d = {}\n def recurse(n, n2c, d):\n v = []\n for c in n.children:\n recurse(c, n2c, d)\n if c.isleaf:\n x, y = n2c[c].point()\n x0 = x1 = x; y0 = y1 = y\n else:\n x0, x1, y0, y1 = d[c]\n v.append((x0, x1, y0, y1))\n if v:\n x0 = n2c[n].x\n x1 = max([ x[1] for x in v ])\n y0 = min([ x[2] for x in v ])\n y1 = max([ x[3] for x in v ])\n d[n] = (x0, x1, y0, y1)\n recurse(self.root, n2c, d)\n return d\n\n def clade_height_pixels(self):\n ypp = self.ypp()\n d = self.clade_dimensions()\n h = {}\n for n, (x0, x1, y0, y1) in d.items():\n h[n] = (y1-y0)/ypp\n return h\n\n def _decimate_nodes(self, n=500):\n leaves = self.leaves\n nleaves = len(leaves)\n if nleaves > n:\n indices = numpy.linspace(0, nleaves-1, n).astype(int)\n leaves = [ leaves[i] for i in indices ]\n return set(list(chain.from_iterable([ list(x.rootpath())\n for x in leaves ])))\n else:\n return self.root\n\n def create_branch_artists(self):\n \"\"\"\n Use MPL Paths to draw branches\n \"\"\"\n ## patches = []\n verts = []; codes = []\n for node in self.root.descendants():\n v, c = self._path_to_parent(node)\n verts.extend(v); codes.extend(c)\n self.branchpatch = PathPatch(\n Path(verts, codes), fill=False,\n linewidth=self.branch_width,\n edgecolor=self.branch_color\n )\n self.add_patch(self.branchpatch)\n ## for node in self._decimate_nodes():\n ## if node.parent:\n ## for p in self._path_to_parent(node):\n ## patches.append(p)\n ## self.branch_patches = PatchCollection(patches, match_original=True)\n ## self.add_collection(self.branch_patches)\n\n ## print \"enter: create_branch_artists\"\n ## self.node2branch = {}\n ## for node, segs in self.node2linesegs.items():\n ## line = Line2D(\n ## [x[0] for x in segs], [x[1] for x in segs],\n ## lw=self.branch_width, color=self.branch_color\n ## )\n ## line.set_visible(False)\n ## Axes.add_artist(self, line)\n ## self.node2branch[node] = line\n\n ## d = self.node2linesegs\n ## segs = [ d[n] for n in self.root if (n in d) ]\n\n ## dims = self.clade_dimensions(); ypp = self.ypp()\n ## def recurse(n, dims, clades, terminals):\n ## stop = False\n ## h = None\n ## v = dims.get(n)\n ## if v: h = (v[3]-v[2])/ypp\n ## if (h and (h < 20)) or (not h):\n ## stop = True\n ## terminals.append(n)\n ## if not stop:\n ## clades.append(n)\n ## for c in n.children:\n ## recurse(c, dims, clades, terminals)\n ## clades = []; terminals = []\n ## recurse(self.root, dims, clades, terminals)\n ## segs = [ d[n] for n in self.root if (n in d) and (n in clades) ]\n ## for t in terminals:\n ## if t.isleaf:\n ## segs.append(d[t])\n ## else:\n ## x0, x1, y0, y1 = dims[t]\n ## x, y = self.n2c[t].point()\n ## px, py = self.n2c[t.parent].point()\n ## segs.append(((px,py), (px,y), (x,y), (x1, y0), (x1,y1), (x,y)))\n\n ## lc = LineCollection(segs, linewidths=self.branch_width,\n ## colors = self.branch_color)\n ## self.branches_linecollection = Axes.add_collection(self, lc)\n ## print \"leave: create_branch_artists\"\n\n def create_label_artists(self):\n ## print \"enter: create_label_artists\"\n self.node2label = {}\n n2c = self.n2c\n for node, coords in n2c.items():\n x = coords.x; y = coords.y\n if node.isleaf and node.label and self.leaflabels:\n txt = self.annotate(\n node.label,\n xy=(x, y),\n xytext=(self.leaf_offset, 0),\n textcoords=\"offset points\",\n verticalalignment=self.leaf_valign,\n horizontalalignment=self.leaf_halign,\n fontsize=self.leaf_fontsize,\n clip_on=True,\n picker=True\n )\n txt.node = node\n txt.set_visible(False)\n self.node2label[node] = txt\n\n if (not node.isleaf) and node.label and self.branchlabels:\n txt = self.annotate(\n node.label,\n xy=(x, y),\n xytext=(self.branch_offset,0),\n textcoords=\"offset points\",\n verticalalignment=self.branch_valign,\n horizontalalignment=self.branch_halign,\n fontsize=self.branch_fontsize,\n bbox=dict(fc=\"lightyellow\", ec=\"none\", alpha=0.8),\n clip_on=True,\n picker=True\n )\n ## txt.set_visible(False)\n txt.node = node\n self.node2label[node] = txt\n ## print \"leave: create_label_artists\"\n\n def adjust_xspine(self):\n v = sorted([ c.x for c in self.n2c.values() ])\n try:\n self.spines[\"bottom\"].set_bounds(v[0],v[-1])\n except AttributeError:\n pass\n for t,n,s in self.xaxis.iter_ticks():\n if (n > v[-1]) or (n < v[0]):\n t.set_visible(False)\n\n def mark_named(self):\n if self._mark_named:\n n2c = self.n2c\n cv = [ c for n, c in n2c.items() if n.label and (not n.isleaf) ]\n x = [ c.x for c in cv ]\n y = [ c.y for c in cv ]\n if x and y:\n self.scatter(x, y, s=5, color='black')\n\n def home(self):\n td = self.transData\n trans = td.inverted().transform\n xmax = xmin = ymax = ymin = 0\n if self.node2label:\n try:\n v = [ x.get_window_extent() for x in self.node2label.values()\n if x.get_visible() ]\n if v:\n xmax = trans((max([ x.xmax for x in v ]),0))[0]\n xmin = trans((min([ x.xmin for x in v ]),0))[0]\n except RuntimeError:\n pass\n\n v = self.n2c.values()\n ymin = min([ c.y for c in v ])\n ymax = max([ c.y for c in v ])\n xmin = min(xmin, min([ c.x for c in v ]))\n xmax = max(xmax, max([ c.x for c in v ]))\n xspan = xmax - xmin; xpad = xspan*0.05\n yspan = ymax - ymin; ypad = yspan*0.05\n self.set_xlim(xmin-xpad, xmax+xpad*2)\n self.set_ylim(ymin-ypad, ymax+ypad)\n self.adjust_xspine()\n\n def scroll(self, x, y):\n x0, x1 = self.get_xlim()\n y0, y1 = self.get_ylim()\n xd = (x1-x0)*x\n yd = (y1-y0)*y\n self.set_xlim(x0+xd, x1+xd)\n self.set_ylim(y0+yd, y1+yd)\n self.adjust_xspine()\n\n def plot_labelcolor(self, nodemap, state2color=None):\n if state2color is None:\n c = colors.tango()\n states = sorted(set(nodemap.values()))\n state2color = dict(zip(states, c))\n\n for node, txt in self.node2label.items():\n s = nodemap.get(node)\n if s is not None:\n c = state2color[s]\n if c:\n txt.set_color(c)\n self.figure.canvas.draw_idle()\n\n def node_image(self, node, imgfile, maxdim=100, border=0):\n xoff = self.leaf_offset\n n = self.root[node]; c = self.n2c[n]; p = (c.x, c.y)\n img = Image.open(imgfile)\n if max(img.size) > maxdim:\n img.thumbnail((maxdim, maxdim))\n imgbox = OffsetImage(img)\n xycoords = self.node2label.get(node) or \"data\"\n if xycoords != \"data\": p = (1, 0.5)\n abox = AnnotationBbox(imgbox, p,\n xybox=(xoff, 0.0),\n xycoords=xycoords,\n box_alignment=(0.0,0.5),\n pad=0.0,\n boxcoords=(\"offset points\"))\n self.add_artist(abox)\n\n def plot_discrete(self, data, cmap=None, name=None,\n xoff=10, yoff=0, size=15, legend=1):\n root = self.root\n if cmap is None:\n import ivy\n c = colors.tango()\n states = sorted(set(data.values()))\n cmap = dict(zip(states, c))\n n2c = self.n2c\n points = []; c = []\n d = dict([ (n, data.get(n)) for n in root if data.get(n) is not None ])\n for n, v in d.items():\n coord = n2c[n]\n points.append((coord.x, coord.y)); c.append(cmap[v])\n\n boxes = symbols.squares(self, points, c, size, xoff=xoff, yoff=yoff)\n\n if legend:\n handles = []; labels = []\n for v, c in sorted(cmap.items()):\n handles.append(Rectangle((0,0),0.5,1,fc=c))\n labels.append(str(v))\n self.legend(handles, labels, loc=legend)\n\n self.figure.canvas.draw_idle()\n return boxes\n\n def plot_continuous(self, data, mid=None, name=None, cmap=None,\n size=15, colorbar=True):\n area = (size*0.5)*(size*0.5)*numpy.pi\n values = data.values()\n vmin = min(values); vmax = max(values)\n if mid is None:\n mid = (vmin+vmax)*0.5\n delta = vmax-vmin*0.5\n else:\n delta = max(abs(vmax-mid), abs(vmin-mid))\n norm = mpl_colors.Normalize(mid-delta, mid+delta)\n ## if cmap is None: cmap = mpl_colormap.binary\n if cmap is None: cmap = mpl_colormap.hot\n n2c = self.n2c\n X = numpy.array(\n [ (n2c[n].x, n2c[n].y, v) for n, v in data.items() if n in n2c ]\n )\n circles = self.scatter(\n X[:,0], X[:,1], s=area, c=X[:,2], cmap=cmap, norm=norm,\n zorder=1000\n )\n if colorbar:\n cbar = self.figure.colorbar(circles, ax=self, shrink=0.7)\n if name:\n cbar.ax.set_xlabel(name)\n\n self.figure.canvas.draw_idle()\n\nclass RadialTree(Tree):\n def layout(self):\n from ..layout_polar import calc_node_positions\n start = self.start if hasattr(self, 'start') else 0\n end = self.end if hasattr(self, 'end') else None\n self.n2c = calc_node_positions(self.root, scaled=self.scaled,\n start=start, end=end)\n sv = sorted([\n [c.y, c.x, n] for n, c in self.n2c.items()\n ])\n self.coords = sv\n\n ## def _path_to_parent(self, node, width=None, color=None):\n ## c = self.n2c[node]; theta1 = c.angle; r = c.depth\n ## M = Path.MOVETO; L = Path.LINETO\n ## pc = self.n2c[node.parent]; theta2 = pc.angle\n ## px1 = math.cos(math.radians(c.angle))*pc.depth\n ## py1 = math.sin(math.radians(c.angle))*pc.depth\n ## verts = [(c.x,c.y),(px1,py1)]; codes = [M,L]\n ## #verts.append((pc.x,pc.y)); codes.append(L)\n ## path = PathPatch(Path(verts, codes), fill=False,\n ## linewidth=width or self.branch_width,\n ## edgecolor=color or self.branch_color)\n ## diam = pc.depth*2\n ## t1, t2 = tuple(sorted((theta1,theta2)))\n ## arc = Arc((0,0), diam, diam, theta1=t1, theta2=t2,\n ## edgecolor=color or self.branch_color,\n ## linewidth=width or self.branch_width)\n ## return [path, arc]\n\n def _path_to_parent(self, node):\n c = self.n2c[node]; theta1 = c.angle; r = c.depth\n M = Path.MOVETO; L = Path.LINETO\n pc = self.n2c[node.parent]; theta2 = pc.angle\n px1 = math.cos(math.radians(c.angle))*pc.depth\n py1 = math.sin(math.radians(c.angle))*pc.depth\n verts = [(c.x,c.y),(px1,py1)]; codes = [M,L]\n t1, t2 = tuple(sorted((theta1,theta2)))\n diam = pc.depth*2\n arc = Arc((0,0), diam, diam, theta1=t1, theta2=t2)\n arcpath = arc.get_path()\n av = arcpath.vertices * pc.depth\n ac = arcpath.codes\n verts.extend(av.tolist())\n codes.extend(ac.tolist())\n return verts, codes\n\n def highlight(self, nodes=None, width=5, color=\"red\"):\n if self.highlightpatch:\n try:\n self.highlightpatch.remove()\n except:\n pass\n if not nodes:\n return\n\n if len(nodes)>1:\n mrca = self.root.mrca(nodes)\n if not mrca:\n return\n else:\n mrca = list(nodes)[0]\n\n M = Path.MOVETO; L = Path.LINETO\n verts = []\n codes = []\n seen = set()\n patches = []\n for node, coords in [ x for x in self.n2c.items() if x[0] in nodes ]:\n x = coords.x; y = coords.y\n p = node.parent\n while p:\n pcoords = self.n2c[p]\n px = pcoords.x; py = pcoords.y\n if node not in seen:\n v, c = self._path_to_parent(node)\n verts.extend(v)\n codes.extend(c)\n seen.add(node)\n if p == mrca or node == mrca:\n break\n node = p\n coords = self.n2c[node]\n x = coords.x; y = coords.y\n p = node.parent\n ## px, py = verts[-1]\n ## verts.append((px, py)); codes.append(M)\n self.highlightpath = Path(verts, codes)\n self.highlightpatch = PathPatch(\n self.highlightpath, fill=False, linewidth=width, edgecolor=color\n )\n self.add_patch(self.highlightpatch)\n ## self.highlight_patches = PatchCollection(patches, match_original=True)\n ## self.add_collection(self.highlight_patches)\n\n\nclass OverviewTree(Tree):\n def __init__(self, *args, **kwargs):\n kwargs[\"leaflabels\"] = False\n kwargs[\"branchlabels\"] = False\n Tree.__init__(self, *args, **kwargs)\n self.xaxis.set_visible(False)\n self.spines[\"bottom\"].set_visible(False)\n self.add_overview_rect()\n\n def set_target(self, target):\n self.target = target\n\n def add_overview_rect(self):\n rect = UpdatingRect([0, 0], 0, 0, facecolor='black', edgecolor='red')\n rect.set_alpha(0.2)\n rect.target = self.target\n rect.set_bounds(*self.target.viewLim.bounds)\n self.zoomrect = rect\n self.add_patch(rect)\n ## if pyplot.isinteractive():\n self.target.callbacks.connect('xlim_changed', rect)\n self.target.callbacks.connect('ylim_changed', rect)\n\n def redraw(self):\n Tree.redraw(self)\n self.add_overview_rect()\n self.figure.canvas.draw_idle()\n\ndef axes_enter(e):\n ax = e.inaxes\n ax._active = True\n\ndef axes_leave(e):\n ax = e.inaxes\n ax._active = False\n\ndef onselect(estart, estop):\n b = estart.button\n ## print b, estart.key\n\ndef onkeypress(e):\n ax = e.inaxes\n k = e.key\n if ax and k == 't':\n ax.home()\n if ax and k == \"down\":\n ax.scroll(0, -0.1)\n ax.figure.canvas.draw_idle()\n if ax and k == \"up\":\n ax.scroll(0, 0.1)\n ax.figure.canvas.draw_idle()\n if ax and k == \"left\":\n ax.scroll(-0.1, 0)\n ax.figure.canvas.draw_idle()\n if ax and k == \"right\":\n ax.scroll(0.1, 0)\n ax.figure.canvas.draw_idle()\n if ax and k and k in '=+':\n ax.zoom(0.1,0.1)\n if ax and k == '-':\n ax.zoom(-0.1,-0.1)\n\ndef ondrag(e):\n ax = e.inaxes\n button = e.button\n if ax and button == 2:\n if not ax.pan_start:\n ax.pan_start = (e.xdata, e.ydata)\n return\n x, y = ax.pan_start\n xdelta = x - e.xdata\n ydelta = y - e.ydata\n x0, x1 = ax.get_xlim()\n xspan = x1-x0\n y0, y1 = ax.get_ylim()\n yspan = y1 - y0\n midx = (x1+x0)*0.5\n midy = (y1+y0)*0.5\n ax.set_xlim(midx+xdelta-xspan*0.5, midx+xdelta+xspan*0.5)\n ax.set_ylim(midy+ydelta-yspan*0.5, midy+ydelta+yspan*0.5)\n ax.adjust_xspine()\n\ndef onbuttonrelease(e):\n ax = e.inaxes\n button = e.button\n if button == 2:\n ## print \"pan end\"\n ax.pan_start = None\n\ndef onpick(e):\n ax = e.mouseevent.inaxes\n if ax:\n ax.picked(e)\n\ndef onscroll(e):\n ax = e.inaxes\n if ax:\n b = e.button\n ## print b\n k = e.key\n if k == None and b ==\"up\":\n ax.zoom(0.1,0.1)\n if k == None and b ==\"down\":\n ax.zoom(-0.1,-0.1)\n if k == \"shift\" and b == \"up\":\n ax.zoom_cxy(0.1, 0, e.xdata, e.ydata)\n if k == \"shift\" and b == \"down\":\n ax.zoom_cxy(-0.1, 0, e.xdata, e.ydata)\n if k == \"control\" and b == \"up\":\n ax.zoom_cxy(0, 0.1, e.xdata, e.ydata)\n if k == \"control\" and b == \"down\":\n ax.zoom_cxy(0, -0.1, e.xdata, e.ydata)\n if k == \"d\" and b == \"up\":\n ax.scroll(0, 0.1)\n if (k == \"d\" and b == \"down\"):\n ax.scroll(0, -0.1)\n if k == \"c\" and b == \"up\":\n ax.scroll(-0.1, 0)\n if k == \"c\" and b == \"down\":\n ax.scroll(0.1, 0)\n try: ax.adjust_xspine()\n except: pass\n ax.figure.canvas.draw_idle()\n\ndef onclick(e):\n ax = e.inaxes\n if ax and e.button==1 and hasattr(ax, \"zoomrect\") and ax.zoomrect:\n # overview clicked; reposition zoomrect\n r = ax.zoomrect\n x = e.xdata\n y = e.ydata\n arr = ax.transData.inverted().transform(r.get_extents())\n xoff = (arr[1][0]-arr[0][0])*0.5\n yoff = (arr[1][1]-arr[0][1])*0.5\n r.target.set_xlim(x-xoff,x+xoff)\n r.target.set_ylim(y-yoff,y+yoff)\n r(r.target)\n ax.figure.canvas.draw_idle()\n\n if ax and e.button==2:\n ## print \"pan start\", (e.xdata, e.ydata)\n ax.pan_start = (e.xdata, e.ydata)\n\n\ndef test_decorate(treeplot):\n import evolve\n data = evolve.brownian(treeplot.root)\n values = data.values()\n vmin = min(values); vmax = max(values)\n norm = mpl_colors.Normalize(vmin, vmax)\n cmap = mpl_colormap.binary\n n2c = treeplot.n2c\n X = numpy.array(\n [ (n2c[n].x, n2c[n].y, v)\n for n, v in data.items() if n in n2c ]\n )\n circles = treeplot.scatter(\n X[:,0], X[:,1], s=200, c=X[:,2], cmap=cmap, norm=norm,\n zorder=100\n )\n\nclass Decorator(object):\n def __init__(self, treeplot):\n self.plot = treeplot\n\nclass VisToggle(object):\n def __init__(self, name, treeplot=None, value=False):\n self.name = name\n self.plot = treeplot\n self.value = value\n\n def __nonzero__(self):\n return self.value\n\n def __repr__(self):\n return \"%s: %s\" % (self.name, self.value)\n\n def redraw(self):\n if self.plot:\n self.plot.redraw()\n\n def toggle(self):\n self.value = not self.value\n self.redraw()\n\n def show(self):\n if self.value == False:\n self.value = True\n self.redraw()\n\n def hide(self):\n if self.value == True:\n self.value = False\n self.redraw()\n\n\nTreePlot = subplot_class_factory(Tree)\nRadialTreePlot = subplot_class_factory(RadialTree)\nOverviewTreePlot = subplot_class_factory(OverviewTree)\n\nif __name__ == \"__main__\":\n import evolve\n root, data = evolve.test_brownian()\n plot_continuous(root, data, name=\"Brownian\", mid=0.0)\n"}, "files_after": {"ivy/__init__.py": "\"\"\"\nivy - a phylogenetics library and visual shell\nhttp://www.reelab.net/ivy\n\nCopyright 2010 Richard Ree \n\nRequired: ipython, matplotlib, scipy, numpy\nUseful: dendropy, biopython, etc.\n\"\"\"\n## This program is free software; you can redistribute it and/or\n## modify it under the terms of the GNU General Public License as\n## published by the Free Software Foundation; either version 3 of the\n## License, or (at your option) any later version.\n\n## This program is distributed in the hope that it will be useful, but\n## WITHOUT ANY WARRANTY; without even the implied warranty of\n## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n## General Public License for more details.\n\n## You should have received a copy of the GNU General Public License\n## along with this program. If not, see\n## .\n\nfrom . import tree, layout, contrasts, ages\nfrom . import genbank, nexus, newick, storage\n# from . import bipart\n# import nodearray, data\n# from . import treebase\n# import db\n# import contrib\ntry:\n import ltt as _ltt\n ltt = _ltt.ltt\nexcept ImportError:\n pass\n\nfrom . import align, sequtil\n# from . import chars, align, sequtil\n## try: import vis\n## except RuntimeError: pass\n", "ivy/ages.py": "\"\"\"\nCalculate node ages from branch lengths.\n\nThe function of interest is `ages2lengths`\n\"\"\"\nfrom __future__ import print_function\n\ndef ages2lengths(node, node_ages, results={}):\n \"\"\"\n Convert node ages to branch lengths\n\n Args:\n node (Node): Node object\n node_ages (dict): Dict mapping nodes to ages\n Returns:\n dict: mapping of nodes to lengths\n\n \"\"\"\n for d in node.descendants():\n age = node_ages[d]\n if d.parent:\n parent_age = node_ages[d.parent]\n results[d] = parent_age - age\n return results\n\ndef min_ages(node, leaf_ages, results={}):\n \"\"\"\n Calculate minimum ages given fixed ages in leaf_ages\n\n Args:\n node (Node): A node object\n leaf_ages (dict): A dict mapping leaf nodes to ages\n Returns:\n dict: mapping of nodes to ages\n \"\"\"\n v = []\n for child in node.children:\n if child.label and (child.label in leaf_ages):\n age = leaf_ages[child.label]\n v.append(age)\n results[child] = age\n else:\n min_ages(child, leaf_ages, results)\n age = results[child]\n v.append(age)\n results[node] = max(v)\n return results\n\ndef smooth(node, node_ages, results={}):\n \"\"\"\n adjust ages of internal nodes by smoothing\n RR: I don't actually know what this function does -CZ\n \"\"\"\n if node.parent:\n parent_age = node_ages[node.parent]\n if node.children:\n max_child_age = max([ node_ages[child] for child in node.children ])\n # make the new age the average of parent and max child\n new_node_age = (parent_age + max_child_age)/2.0\n results[node] = new_node_age\n else:\n results[node] = node_ages[node]\n else:\n results[node] = node_ages[node]\n for child in node.children:\n smooth(child, node_ages, results)\n return results\n\nif __name__ == \"__main__\":\n import newick, ascii\n\n s = \"((((a,b),(c,d),(e,f)),g),h);\"\n root = newick.parse(s)\n\n leaf_ages = {\n \"a\": 3,\n \"b\": 2,\n \"c\": 4,\n \"d\": 1,\n \"e\": 3,\n \"f\": 0.5,\n \"g\": 10,\n \"h\": 5,\n }\n\n ma = min_ages(root, leaf_ages)\n d = ma\n for i in range(10):\n d = smooth(root, d)\n for node, val in ages2lengths(root, d).items():\n node.length = val\n print(ascii.render(root, scaled=1))\n", "ivy/align.py": "import os\nfrom subprocess import Popen, PIPE\nfrom Bio import AlignIO\nfrom Bio.Alphabet import IUPAC\ntry:\n from cStringIO import StringIO\nexcept ImportError:\n from io import StringIO\nfrom tempfile import NamedTemporaryFile\n\nMUSCLE = \"/usr/bin/muscle\"\n\ndef muscle(seqs, cmd=None):\n if not cmd: cmd = MUSCLE\n assert os.path.exists(cmd)\n p = Popen([cmd], stdin=PIPE, stdout=PIPE)\n write = p.stdin.write\n for x in seqs:\n write(\">%s\\n%s\\n\" % (x.id, x.seq))\n out = p.communicate()[0]\n aln = AlignIO.read(StringIO(out), 'fasta', alphabet=IUPAC.ambiguous_dna)\n return aln\n\ndef musclep(seqs1, seqs2, cmd=\"/usr/bin/muscle\"):\n assert os.path.exists(cmd)\n f1 = NamedTemporaryFile(); f2 = NamedTemporaryFile()\n for s, f in ((seqs1, f1), (seqs2, f2)):\n write = f.file.write\n for x in s: write(\">%s\\n%s\\n\" % (x.id, x.seq))\n f1.file.flush(); f2.file.flush()\n cmd += \" -profile -in1 %s -in2 %s\" % (f1.name, f2.name)\n p = Popen(cmd.split(), stdout=PIPE)\n out = p.communicate()[0]\n aln = AlignIO.read(StringIO(out), 'fasta', alphabet=IUPAC.ambiguous_dna)\n f1.file.close(); f2.file.close()\n return aln\n \ndef read(data, format=None, name=None):\n from types import StringTypes\n \n def strip(s):\n fname = os.path.split(s)[-1]\n head, tail = os.path.splitext(fname)\n tail = tail.lower()\n if tail in (\".fasta\", \".nex\", \".nexus\"):\n return head\n else:\n return fname\n\n if (not format):\n if (type(data) in StringTypes) and os.path.isfile(data):\n s = data.lower()\n if s.endswith(\"fasta\"):\n format=\"fasta\"\n for tail in \".nex\", \".nexus\":\n if s.endswith(tail):\n format=\"nexus\"\n break\n\n if (not format):\n format = \"fasta\"\n\n if type(data) in StringTypes:\n if os.path.isfile(data):\n name = strip(data)\n with open(data) as f:\n return AlignIO.read(f, format, alphabet=IUPAC.ambiguous_dna)\n else:\n f = StringIO(data)\n return AlignIO.read(f, format, alphabet=IUPAC.ambiguous_dna)\n\n elif (hasattr(data, \"tell\") and hasattr(data, \"read\")):\n treename = strip(getattr(data, \"name\", None))\n return AlignIO.read(data, format, alphabet=IUPAC.ambiguous_dna)\n\n raise IOError(\"unable to read alignment from '%s'\" % data)\n\ndef write(data, f, format='fasta'):\n AlignIO.write(data, f, format)\n \ndef find(aln, substr):\n \"\"\"\n generator that yields (seqnum, pos) tuples for every position of\n ``subseq`` in `aln`\n \"\"\"\n from sequtil import finditer\n N = len(substr)\n for i, rec in enumerate(aln):\n for j in finditer(rec.seq, substr):\n yield (i,j)\n \ndef find_id(aln, regexp):\n import re\n return [ (i,s) for i, s in enumerate(aln) if re.search(regexp, s.id) ]\n \ndef gapcols(aln, c='-'):\n from numpy import array\n a = array([ list(x.seq) for x in aln ])\n for i, col in enumerate(a.T):\n s = set(col==c)\n if len(s)==1 and True in s:\n yield i\n", "ivy/ascii.py": "from __future__ import print_function\nimport math\nfrom array import array\nfrom .layout import depth_length_preorder_traversal\n\nclass AsciiBuffer:\n def __init__(self, width, height):\n self.width = int(width)\n self.height = int(height)\n self._b = [ array('u', ' '*self.width) for line in range(self.height) ]\n\n def putstr(self, r, c, s):\n assert r < self.height\n assert c+len(s) <= self.width, \"%s %s %s '%s'\" % (self.width, r, c, s)\n c = int(c)\n self._b[r][c:c+len(s)+1] = array('u', s)\n\n def __str__(self):\n return \"\\n\".join([ ''.join(b) for b in self._b ])\n\ndef sum_to_root(node, internodes=True, length=False):\n \"\"\"\n Number of branches from node to root.\n\n Args:\n node (Node): A Node object\n RR: Do internodes and length do anything in this function? -CZ\n Returns:\n int: The number of branches from node to root.\n \"\"\"\n i = 0\n n = node\n while 1:\n if not n.parent:\n break\n else:\n n = n.parent\n i += 1\n return i\n\n## def depth_length_preorder_traversal(node):\n## if not node.parent:\n## node.depth = 0\n## node.length_to_root = 0.0\n## else:\n## p = node.parent\n## node.depth = p.depth + 1\n## node.length_to_root = p.length_to_root + (node.length or 0.0)\n## for ch in node.children:\n## depth_length_preorder_traversal(ch)\n\ndef smooth_cpos(node, n2c):\n for ch in node.children:\n smooth_cpos(ch, n2c)\n\n if node.parent and not node.isleaf:\n px = n2c[node.parent].c\n cx = min([ n2c[ch].c for ch in node.children ])\n dxp = n2c[node].c - px\n cxp = cx - n2c[node].c\n n2c[node].c = px + (cx - px)*0.5\n\ndef scale_cpos(node, n2c, scalef, root_offset):\n if node.parent:\n n2c[node].c = n2c[node.parent].c + (node.length * scalef)\n else:\n n2c[node].c = root_offset\n\n for ch in node.children:\n scale_cpos(ch, n2c, scalef, root_offset)\n\ndef set_rpos(node, n2c):\n for child in node.children:\n set_rpos(child, n2c)\n nc = n2c[node]\n if node.children:\n children = node.children\n c0 = n2c[children[0]]\n c1 = n2c[children[-1]]\n rmin = c0.r; rmax = c1.r\n nc.r = math.ceil(rmin + (rmax-rmin)/2.0)\n\ndef render(root, unitlen=3, minwidth=50, maxwidth=None, scaled=False,\n show_internal_labels=True):\n \"\"\"\n Create the ascii tree to be shown with print()\n \"\"\"\n n2c = depth_length_preorder_traversal(root)\n leaves = root.leaves(); nleaves = len(leaves)\n maxdepth = max([ n2c[lf].depth for lf in leaves ])\n max_labelwidth = max([ len(lf.label) for lf in leaves ]) + 1\n\n root_offset = 0\n if root.label and show_internal_labels:\n root_offset = len(root.label)\n\n width = maxdepth*unitlen + max_labelwidth + 2 + root_offset\n height = 2*nleaves - 1\n\n if width < minwidth:\n unitlen = math.ceil((minwidth - max_labelwidth - 2 - root_offset)/maxdepth)\n width = maxdepth*unitlen + max_labelwidth + 2 + root_offset\n\n print(width, height)\n buf = AsciiBuffer(width, height)\n\n for i, lf in enumerate(leaves):\n c = n2c[lf]\n c.c = width - max_labelwidth - 2\n c.r = i*2\n\n for node in root.postiter():\n nc = n2c[node]\n if node.children:\n children = node.children\n c0 = n2c[children[0]]\n c1 = n2c[children[-1]]\n rmin = c0.r; rmax = c1.r\n nc.r = math.ceil(rmin + (rmax-rmin)/2.0)\n nc.c = min([ n2c[ch].c for ch in children ]) - unitlen\n\n\n if not scaled:\n smooth_cpos(root, n2c)\n else:\n maxlen = max([ n2c[lf].length_to_root for lf in leaves ])\n scalef = (n2c[leaves[0]].c + 1 - root_offset)/maxlen\n scale_cpos(root, n2c, scalef, root_offset)\n\n for node in root.postiter():\n nc = n2c[node]\n if node.parent:\n pc = n2c[node.parent]\n for r in range(min([nc.r, pc.r]),\n max([nc.r, pc.r])):\n buf.putstr(r, pc.c, \":\")\n\n sym = getattr(nc, \"hchar\", \"-\")\n vbar = sym*math.floor(nc.c-pc.c)\n buf.putstr(nc.r, math.ceil(pc.c), vbar)\n\n if node.isleaf:\n buf.putstr(nc.r, nc.c+1, \" \"+node.label)\n else:\n if node.label and show_internal_labels:\n buf.putstr(nc.r, nc.c-len(node.label), node.label)\n\n buf.putstr(nc.r, nc.c, \"+\")\n\n return str(buf)\n\nif __name__ == \"__main__\":\n from . import tree\n t = tree.read(\n \"(foo,((bar,(dog,cat)dc)dcb,(shoe,(fly,(cow, bowwow)cowb)cbf)X)Y)Z;\"\n )\n\n #t = tree.read(\"(((foo:4.6):5.6, (bar:6.5, baz:2.3):3.0):3.0);\")\n #t = tree.read(\"(foo:4.6, (bar:6.5, baz:2.3)X:3.0)Y:3.0;\")\n\n i = 1\n print(render(t, scaled=0, show_internal_labels=1))\n r = t.get(\"cat\").parent\n tree.reroot(t, r)\n tp = t.parent\n tp.remove_child(t)\n c = t.children[0]\n t.remove_child(c)\n tp.add_child(c)\n print(render(r, scaled=0, show_internal_labels=1))\n", "ivy/autocollapse.py": "\"\"\"\nFor drawing big trees. Calculate which clades can be 'collapsed' and\ndisplayed with a placeholder.\n\nTODO: test and develop this module further\n\"\"\"\nfrom storage import Storage\n\ndef autocollapse_info(node, collapsed, visible=True, info={}):\n \"\"\"\n gather information to determine if a node should be collapsed\n\n *collapsed* is a set containing nodes that are already collapsed\n \"\"\"\n if node not in info:\n s = Storage()\n info[node] = s\n else:\n s = info[node]\n \n if visible and (node in collapsed):\n visible = False\n \n nnodes = 1 # total number of nodes, including node\n # number of visible leaves\n nvisible = int((visible and node.isleaf) or (node in collapsed))\n ntips = int(node.isleaf)\n ntips_visible = int(node.isleaf and visible)\n s.has_labeled_descendant = False\n s.depth = 1\n\n for child in node.children:\n autocollapse_info(child, collapsed, visible, info)\n cs = info[child]\n nnodes += cs.nnodes\n nvisible += cs.nvisible\n ntips += cs.ntips\n ntips_visible += cs.ntips_visible\n if (child.label and (not child.isleaf)) \\\n or (cs.has_labeled_descendant):\n s.has_labeled_descendant = True\n if cs.depth >= s.depth:\n s.depth = cs.depth+1\n s.nnodes = nnodes\n s.nvisible = nvisible\n s.ntips = ntips\n s.ntips_visible = ntips_visible\n return info\n\ndef autocollapse(root, collapsed=None, keep_visible=None, max_visible=1000):\n \"\"\"\n traverse a tree and find nodes that should be collapsed in order\n to satify *max_visible*\n\n *collapsed* is a set object for storing collapsed nodes\n\n *keep_visible* is a set object of nodes that should not be placed\n in *collapsed*\n \"\"\"\n collapsed = collapsed or set()\n keep_visible = keep_visible or set()\n ntries = 0\n while True:\n if ntries > 10:\n return\n info = autocollapse_info(root, collapsed)\n nvisible = info[root].nvisible\n if nvisible <= max_visible:\n return\n \n v = []\n for node in root.iternodes():\n s = info[node]\n if (node.label and (not node.isleaf) and node.parent and\n (node not in keep_visible)):\n w = s.nvisible/float(s.depth)\n if s.has_labeled_descendant:\n w *= 0.25\n v.append((w, node, s))\n v.sort(); v.reverse()\n for w, node, s in v:\n if node not in keep_visible and s.nvisible < (nvisible-1):\n print(node)\n collapsed.add(node)\n nvisible -= s.nvisible\n if nvisible <= max_visible:\n break\n ntries += 1\n return collapsed\n", "ivy/bipart.py": "from collections import defaultdict\n\n## class BipartSet(object):\n## \"A set of bipartitions\"\n## def __init__(self, elements):\n## self.elements = frozenset(elements)\n## self.ref = sorted(elements)[0]\n## self.node2bipart = Storage()\n\n## def add(self, subset, node):\n## # filter out elements of subset not in 'elements'\n## subset = (frozenset(subset) & self.elements)\n## if self.ref not in self.subset:\n## self.subset = self.elements - self.subset\n\nclass Bipart(object):\n \"\"\"\n A class representing a bipartition.\n \"\"\"\n def __init__(self, elements, subset, node=None, support=None):\n \"\"\"\n 'elements' and 'subset' are set objects\n \"\"\"\n self.subset = subset\n self.compute(elements)\n self.node = node\n self.support = support\n\n def __hash__(self):\n return self._hash\n\n def __eq__(self, other):\n assert self.elements == other.elements\n return ((self.subset == other.subset) or\n (self.subset == (self.elements - other.subset)))\n\n def __repr__(self):\n v = sorted(self.subset)\n return \"(%s)\" % \" \".join(map(str, v))\n\n def compute(self, elements):\n self.elements = frozenset(elements)\n self.ref = sorted(elements)[0]\n # filter out elements of subset not in 'elements'\n self.subset = (frozenset(self.subset) & self.elements)\n self._hash = hash(self.subset)\n if self.ref not in self.subset:\n self.subset = self.elements - self.subset\n self.complement = self.elements - self.subset\n\n def iscompatible(self, other):\n ## assert self.elements == other.elements\n if (self.subset.issubset(other.subset) or\n other.subset.issubset(self.subset)):\n return True\n if (((self.subset | other.subset) == self.elements) or\n (not (self.subset & other.subset))):\n return True\n return False\n\ndef conflict(bp1, bp2, support=None):\n if ((support and (bp1.support >= support) and (bp2.support >= support))\n or (not support)):\n if not bp1.iscompatible(bp2):\n return True\n return False\n\nclass TreeSet:\n def __init__(self, root, elements=None):\n self.root = root\n self.node2labels = root.leafsets(labels=True)\n self.elements = elements or self.node2labels.pop(root)\n self.biparts = [ Bipart(self.elements, v, node=k,\n support=int(k.label or 0))\n for k, v in self.node2labels.items() ]\n\ndef compare_trees(r1, r2, support=None):\n e = (set([ x.label for x in r1.leaves() ]) &\n set([ x.label for x in r2.leaves() ]))\n bp1 = [ Bipart(e, v, node=k, support=int(k.label or 0))\n for k, v in r1.leafsets(labels=True).items() ]\n bp2 = [ Bipart(e, v, node=k, support=int(k.label or 0))\n for k, v in r2.leafsets(labels=True).items() ]\n return compare(bp1, bp2, support)\n\ndef compare(set1, set2, support=None):\n hits1 = []; hits2 = []\n conflicts1 = defaultdict(set); conflicts2 = defaultdict(set)\n for bp1 in set1:\n for bp2 in set2:\n if bp1 == bp2:\n hits1.append(bp1.node); hits2.append(bp2.node)\n if conflict(bp1, bp2, support):\n conflicts1[bp1.node].add(bp2.node)\n conflicts2[bp2.node].add(bp1.node)\n return hits1, hits2, conflicts1, conflicts2\n \n## a = Bipart(\"abcdef\", \"abc\")\n## b = Bipart(\"abcdef\", \"def\")\n## c = Bipart(\"abcdef\", \"ab\")\n## d = Bipart(\"abcdef\", \"cd\")\n## print a == b\n## print a.iscompatible(b)\n## print a.iscompatible(c)\n## print a.iscompatible(d)\n## print c.iscompatible(d)\n## sys.exit() \n", "ivy/chars/__init__.py": "from . import mk, catpars, evolve\n", "ivy/chars/catpars.py": "from __future__ import print_function\nimport numpy as np\n\ndef default_costmatrix(numstates, dtype=np.int):\n \"a square array with zeroes along the diagonal, ones elsewhere\"\n return np.logical_not(np.identity(numstates)).astype(float)\n\ndef minstates(v):\n \"return the indices of v that equal the minimum\"\n return np.nonzero(np.equal(v, min(v)))\n\ndef downpass(node, states, stepmatrix, chardata, node2dpv=None):\n if node2dpv is None:\n node2dpv = {}\n \n if not node.isleaf:\n for child in node.children:\n downpass(child, states, stepmatrix, chardata, node2dpv)\n\n dpv = np.zeros([len(states)])\n node2dpv[node] = dpv\n for i in states:\n for child in node.children:\n child_dpv = node2dpv[child]\n mincost = min([ child_dpv[j] + stepmatrix[i,j] \\\n for j in states ])\n dpv[i] += mincost\n \n #print node.label, node.dpv\n\n else:\n #print node.label, chardata[node.label]\n node2dpv[node] = stepmatrix[:,chardata[node.label]]\n\n return node2dpv\n \n\ndef uppass(node, states, stepmatrix, node2dpv, node2upm={},\n node2ancstates=None):\n parent = node.parent\n if not node.isleaf:\n if parent is None: # root\n dpv = node2dpv[node]\n upm = None\n node.mincost = min(dpv)\n node2ancstates = {node: minstates(dpv)}\n \n else:\n M = np.zeros(stepmatrix.shape)\n for i in states:\n sibs = [ c for c in parent.children if c is not node ]\n for j in states:\n c = 0\n for sib in sibs:\n sibdpv = node2dpv[sib]\n c += min([ sibdpv[x] + stepmatrix[j,x]\n for x in states ])\n c += stepmatrix[j,i]\n\n p_upm = node2upm.get(parent)\n if p_upm is not None:\n c += min(p_upm[j])\n\n M[i,j] += c\n \n node2upm[node] = M\n\n v = node2dpv[node][:]\n for s in states:\n v[s] += min(M[s])\n node2ancstates[node] = minstates(v)\n\n for child in node.children:\n uppass(child, states, stepmatrix, node2dpv, node2upm,\n node2ancstates)\n\n return node2ancstates\n \ndef ancstates(tree, chardata, stepmatrix):\n states = range(len(stepmatrix))\n return uppass(tree, states, stepmatrix,\n downpass(tree, states, stepmatrix, chardata))\n\ndef _bindeltran(node, stepmatrix, node2dpv, node2deltr=None, ancstate=None):\n if node2deltr is None:\n node2deltr = {}\n\n dpv = node2dpv[node]\n if ancstate is not None:\n c, s = min([ (cost+stepmatrix[ancstate,i], i) \\\n for i, cost in enumerate(dpv) ])\n else:\n c, s = min([ (cost, i) for i, cost in enumerate(dpv) ])\n \n node2deltr[node] = s\n for child in node.children:\n _bindeltran(child, stepmatrix, node2dpv, node2deltr, s)\n\n return node2deltr\n \ndef binary_deltran(tree, chardata, stepmatrix):\n states = range(len(stepmatrix))\n node2dpv = downpass(tree, states, stepmatrix, chardata)\n node2deltr = _bindeltran(tree, stepmatrix, node2dpv)\n return node2deltr\n \n\nif __name__ == \"__main__\":\n from pprint import pprint\n from ivy import tree\n root = tree.read(\"(a,((b,c),(d,(e,f))));\")\n\n nstates = 4\n states = range(nstates)\n cm = default_costmatrix(nstates)\n chardata = dict(zip(\"abcdef\", map(int, \"000233\")))\n dp = downpass(root, states, cm, chardata)\n\n for i, node in enumerate(root):\n if not node.label:\n node.label = \"N%s\" % i\n else:\n node.label = \"%s (%s)\" % (node.label, chardata[node.label])\n\n print(ascii.render(root))\n \n\n## nstates = 2\n## leaves = tree.leaves() \n## for leaf in leaves:\n## leaf.anc_cost_vector = chardata[leaf.label]\n\n pprint(\n #ancstates(root, chardata, cm)\n #uppass(root, states, cm, downpass(tree, states, cm, chardata))\n dp\n )\n\n\n", "ivy/chars/evolve.py": "#!/usr/bin/env python\n\"\"\"\nFunctions for evolving traits and trees.\n\"\"\"\nfrom __future__ import print_function\n\ndef brownian(root, sigma=1.0, init=0.0, values={}):\n \"\"\"\n Recursively evolve a trait by Brownian motion up from the node\n *root*.\n\n * *sigma*: standard deviation of the normal random variate after\n one unit of branch length\n\n * *init*: initial value\n\n Returns: *values* - a dictionary mapping nodes to evolved values\n \"\"\"\n from scipy.stats import norm\n values[root] = init\n for child in root.children:\n time = child.length\n random_step = norm.rvs(init, scale=sigma*time)\n brownian(child, sigma, random_step, values)\n return values\n\ndef test_brownian():\n \"\"\"\n Evolve a trait up an example tree of primates:.\n\n ((((Homo:0.21,Pongo:0.21)N1:0.28,Macaca:0.49)N2:0.13,\n Ateles:0.62)N3:0.38,Galago:1.00)root;\n\n Returns: (*root*, *data*) - the root node and evolved data.\n \"\"\"\n import newick\n root = newick.parse(\n \"((((Homo:0.21,Pongo:0.21)N1:0.28,Macaca:0.49)N2:0.13,\"\\\n \"Ateles:0.62)N3:0.38,Galago:1.00)root;\"\n )\n print(root.ascii(scaled=True))\n evolved = brownian(root)\n for node in root.iternodes():\n print(node.label, evolved[node])\n return root, evolved\n\nif __name__ == \"__main__\":\n test_brownian()\n", "ivy/chars/mk.py": "\"\"\"\nCategorical Markov models with k states.\n\"\"\"\nfrom __future__ import print_function\nimport numpy, scipy, random\nimport scipy.linalg\nimport scipy.optimize\nfrom math import log, exp\nrand = random.Random()\nuniform = rand.uniform; expovariate = rand.expovariate\n\nLARGE = 10e10 # large -lnL value used to bound parameter optimization\n\nclass Q:\n def __init__(self, k=2, layout=None):\n \"\"\"\n Represents a square transition matrix with k states.\n \n 'layout' is a square (k,k) array of integers that index free\n rate parameters (values on the diagonal are ignored). Cells\n with value 0 will have the first rate parameter, 1 the\n second, etc.\n \"\"\"\n self.k = k\n self.range = range(k)\n self.offdiag = array(numpy.eye(k)==0, dtype=numpy.int)\n if layout is None:\n layout = zeros((k,k), numpy.int)\n self.layout = layout*self.offdiag\n\n def fill(self, rates):\n m = numpy.take(rates, self.layout)*self.offdiag\n v = m.sum(1) * -1\n for i in self.range:\n m[i,i] = v[i]\n return m\n\n def default_priors(self):\n p = 1.0/self.k\n return [p]*self.k\n\ndef sample_weighted(weights):\n u = uniform(0, sum(weights))\n x = 0.0\n for i, w in enumerate(weights):\n x += w\n if u < x:\n break\n return i\n\ndef conditionals(root, data, Q):\n nstates = Q.shape[0]\n states = range(nstates)\n nodes = [ x for x in root.postiter() ]\n nnodes = len(nodes)\n v = zeros((nnodes,nstates))\n n2i = {}\n \n for i, n in enumerate(nodes):\n n2i[n] = i\n if n.isleaf:\n state = data[n.label]\n try:\n state = int(state)\n v[i,state] = 1.0\n except ValueError:\n if state == '?' or state == '-':\n v[i,:] += 1/float(nstates)\n else:\n Pv = [ (expm(Q*child.length)*v[n2i[child]]).sum(1)\n for child in n.children ]\n v[i] = numpy.multiply(*Pv)\n # fossils\n state = None\n if n.label in data:\n state = int(data[n.label])\n elif n in data:\n state = int(data[n])\n if state != None:\n for s in states:\n if s != state: v[i,s] = 0.0\n \n return dict([ (n, v[i]) for n,i in n2i.items() ])\n\ndef contrasts(root, data, Q):\n cond = conditionals(root, data, Q)\n d = {}\n for n in root.postiter(lambda x:x.children):\n nc = cond[n]; nc /= sum(nc)\n diff = 0.0\n for child in n.children:\n cc = cond[child]; cc /= sum(cc)\n diff += numpy.sum(numpy.abs(nc-cc))\n d[n] = diff\n return d\n\ndef lnL(root, data, Q, priors):\n d = conditionals(root, data, Q)\n return numpy.log(sum(d[root]*priors))\n\ndef optimize(root, data, Q, priors=None):\n Qfill = Q.fill\n if priors is None: priors = Q.default_priors()\n def f(params):\n if (params<0).any(): return LARGE\n return -lnL(root, data, Qfill(params), priors)\n \n # initial parameter values\n p = [1.0]*len(set(Q.layout.flat))\n\n v = scipy.optimize.fmin_powell(\n f, p, full_output=True, disp=0, callback=None\n )\n params, neglnL = v[:2]\n if neglnL == LARGE:\n raise Exception(\"ConvergenceError\")\n return params, neglnL\n\ndef sim(root, n2p, s0, d=None):\n if d is None:\n d = {root:s0}\n for n in root.children:\n v = n2p[n][s0]\n i = sample_weighted(v)\n d[n] = i\n sim(n, n2p, i, d)\n return d\n\ndef stmap(root, states, ancstates, Q, condition_on_success):\n \"\"\"\n This and its dependent functions below need testing and\n optimization.\n \"\"\"\n results = []\n for n in root.descendants():\n si = ancstates[n.parent]\n sj = ancstates[n]\n v = simulate_on_branch(states, si, sj, Q, n.length,\n condition_on_success)\n print(n, si, sj)\n if v:\n results.append(v)\n else:\n return None\n return results\n\ndef simulate_on_branch(states, si, sj, Q, brlen, condition_on_success):\n point = 0.0\n history = [(si, point)]\n if si != sj: # condition on one change occurring\n lambd = -(Q[si,si])\n U = uniform(0.0, 1.0)\n # see appendix of Nielsen 2001, Genetics\n t = brlen - point\n newpoint = -(1.0/lambd) * log(1.0 - U*(1.0 - exp(-lambd * t)))\n newstate = draw_new_state(states, Q, si)\n history.append((newstate, newpoint))\n si = newstate; point = newpoint\n while 1:\n lambd = -(Q[si,si])\n rv = expovariate(lambd)\n newpoint = point + rv\n\n if newpoint <= brlen: # state change along branch\n newstate = draw_new_state(states, Q, si)\n history.append((newstate, newpoint))\n si = newstate; point = newpoint\n else:\n history.append((si, brlen))\n break\n \n if si == sj or (not condition_on_success): # success\n return history\n\n return None\n \ndef draw_new_state(states, Q, si):\n \"\"\"\n Given a rate matrix Q, a starting state si, and an ordered\n sequence of states, eg (0, 1), draw a new state sj with\n probability -(qij/qii)\n \"\"\"\n Qrow = Q[si]\n qii = Qrow[si]\n qij_probs = [ (x, -(Qrow[x]/qii)) for x in states if x != si ]\n uni = uniform(0.0, 1.0)\n val = 0.0\n for sj, prob in qij_probs:\n val += prob\n if uni < val:\n return sj\n \ndef sample_ancstates(node, states, conditionals, n2p, fixed={}):\n \"\"\"\n Sample ancestral states from their conditional likelihoods\n \"\"\"\n ancstates = {}\n for n in node.preiter():\n if n in fixed:\n state = fixed[n]\n else:\n cond = conditionals[n]\n\n if n.parent:\n P = n2p[n]\n ancst = ancstates[n.parent]\n newstate_Prow = P[ancst]\n cond *= newstate_Prow\n\n cond /= sum(cond)\n\n rv = uniform(0.0, 1.0)\n v = 0.0\n for state, c in zip(states, cond):\n v += c\n if rv < v:\n break\n ancstates[n] = state\n\n return ancstates\n", "ivy/contrasts.py": "\"\"\"\nCalculate independent contrasts\n\nTODO: include utilities for transforming data, etc.\n\"\"\"\nfrom __future__ import print_function\n\ndef PIC(node, data, results={}):\n \"\"\"\n Phylogenetic independent contrasts.\n\n Recursively calculate independent contrasts of a bifurcating node\n given a dictionary of trait values.\n\n Args:\n node (Node): A node object\n data (dict): Mapping of leaf names to character values\n\n Returns:\n dict: Mapping of internal nodes to tuples containing ancestral\n state, its variance (error), the contrast, and the\n contrasts's variance.\n\n TODO: modify to accommodate polytomies.\n \"\"\"\n X = []; v = []\n for child in node.children:\n if child.children:\n PIC(child, data, results)\n child_results = results[child]\n X.append(child_results[0])\n v.append(child_results[1])\n else:\n X.append(data[child.label])\n v.append(child.length)\n\n Xi, Xj = X # Xi - Xj is the contrast value\n vi, vj = v\n\n # Xk is the reconstructed state at the node\n Xk = ((1.0/vi)*Xi + (1/vj)*Xj) / (1.0/vi + 1.0/vj)\n\n # vk is the variance\n vk = node.length + (vi*vj)/(vi+vj)\n\n results[node] = (Xk, vk, Xi-Xj, vi+vj)\n\n return results\n\nif __name__ == \"__main__\":\n import tree\n n = tree.read(\n \"((((Homo:0.21,Pongo:0.21)N1:0.28,Macaca:0.49)N2:0.13,\"\\\n \"Ateles:0.62)N3:0.38,Galago:1.00)N4:0.0;\"\n )\n char1 = {\n \"Homo\": 4.09434,\n \"Pongo\": 3.61092,\n \"Macaca\": 2.37024,\n \"Ateles\": 2.02815,\n \"Galago\": -1.46968\n }\n\n for k, v in PIC(n, char1).items():\n print(k.label or k.id, v)\n", "ivy/genbank.py": "import re, sys, logging\nfrom collections import defaultdict\ntry:\n from itertools import izip_longest, ifilter\nexcept:\n from itertools import zip_longest as izip_longest\nfrom Bio import Entrez, SeqIO\nfrom Bio.Blast import NCBIWWW, NCBIXML\nfrom . import storage\n\nemail = \"\"\n\ndef batch(iterable, size):\n \"\"\"\n Take an iterable and return it in chunks (sub-iterables)\n\n Args:\n iterable: Any iterable\n size (int): Size of chunks\n Yields:\n Chunks of size `size`\n \"\"\"\n args = [ iter(iterable) ]*size\n for x in izip_longest(fillvalue=None, *args):\n yield ifilter(None, x)\n\ndef extract_gbac(s):\n \"\"\"\n Extract genbank accession\n\n Args:\n s (str): text string of genbank file\n Returns:\n list: Accession number(s)\n \"\"\"\n gbac_re = re.compile(r'[A-Z]{1,2}[0-9]{4,7}')\n return gbac_re.findall(s, re.M)\n # RR: This also returns various other strings that match the pattern (eg.\n # protein ids)\n\ndef extract_gene(seq, gene):\n \"\"\"\n RR: Not sure what format seq should be in -CZ\n \"\"\"\n for t in \"exon\", \"gene\":\n for x in seq.features:\n if x.type == t:\n v = x.qualifiers.get(\"gene\")\n if v == [gene]:\n if x.sub_features:\n s = [ seq[sf.location.start.position:\n sf.location.end.position]\n for sf in x.sub_features ]\n return reduce(lambda x,y:x+y, s)\n else:\n loc = x.location\n return seq[loc.start.position-10:loc.end.position+10]\n\ndef gi2webenv(gilist):\n h = Entrez.esearch(\n db=\"nucleotide\", term=\" OR \".join(gilist), usehistory=\"y\",\n retmax=len(gilist)\n )\n d = Entrez.read(h)\n return d[\"WebEnv\"], d[\"QueryKey\"]\n\ndef gi2tax(gi):\n global email\n assert email, \"set email!\"\n Entrez.email = email\n h = Entrez.elink(dbfrom='taxonomy', db='nucleotide', from_uid=gi,\n LinkName='nucleotide_taxonomy')\n r = Entrez.read(h)[0]\n h.close()\n i = r['LinkSetDb'][0]['Link'][0]['Id']\n h = Entrez.efetch(db='taxonomy', id=i, retmode='xml')\n r = Entrez.read(h)[0]\n h.close()\n return r\n\ndef ac2gi(ac):\n global email\n assert email, \"set email!\"\n Entrez.email = email\n h = Entrez.esearch(db=\"nucleotide\", term=ac, retmax=1)\n d = Entrez.read(h)['IdList'][0]\n h.close()\n return d\n\ndef acsum(aclist, batchsize=100):\n \"\"\"\n fetch esummary info for list of accession numbers -- useful for\n getting gi and taxids\n \"\"\"\n global email\n assert email, \"set email!\"\n Entrez.email = email\n results = {}\n for v in batch(aclist, batchsize):\n v = list(v)\n h = Entrez.esearch(\n db=\"nucleotide\", retmax=len(v),\n term=\" OR \".join([ \"%s[ACCN]\" % x for x in v ]),\n usehistory=\"y\"\n )\n d = Entrez.read(h)\n h.close()\n # gis, but not in order of aclist\n gis = d['IdList']\n d = Entrez.read(Entrez.esummary(db='nucleotide', id=','.join(gis)),\n validate=False)\n for x in d:\n ac = x['Caption']\n if ac in aclist:\n results[ac] = x\n return results\n\ndef fetch_aclist(aclist, batchsize=1000):\n global email\n assert email, \"set email!\"\n Entrez.email = email\n results = {}\n n = 0\n for v in batch(aclist, batchsize):\n v = list(v)\n h = Entrez.esearch(\n db=\"nucleotide\",\n term=\" OR \".join([ \"%s[ACCN]\" % x for x in v ]),\n usehistory=\"y\"\n )\n d = Entrez.read(h)\n h.close()\n h = Entrez.efetch(db=\"nucleotide\", rettype=\"gb\", retmax=len(v),\n webenv=d[\"WebEnv\"], query_key=d[\"QueryKey\"])\n seqs = SeqIO.parse(h, \"genbank\")\n for s in seqs:\n try:\n ac = s.annotations[\"accessions\"][0]\n if ac in aclist:\n results[ac] = s\n except:\n pass\n h.close()\n n += len(v)\n logging.info('fetched %s sequences', n)\n return results\n\ndef fetch_gilist(gilist, batchsize=1000):\n global email\n assert email, \"set email!\"\n Entrez.email = email\n results = {}\n for v in batch(gilist, batchsize):\n v = map(str, v)\n h = Entrez.epost(db=\"nucleotide\", id=\",\".join(v), usehistory=\"y\")\n d = Entrez.read(h)\n h.close()\n h = Entrez.efetch(db=\"nucleotide\", rettype=\"gb\", retmax=len(v),\n webenv=d[\"WebEnv\"], query_key=d[\"QueryKey\"])\n seqs = SeqIO.parse(h, \"genbank\")\n for s in seqs:\n try:\n gi = s.annotations[\"gi\"]\n if gi in v:\n s.id = organism_id(s)\n results[gi] = s\n except:\n pass\n h.close()\n return results\n\ndef organism_id(s):\n org = (s.annotations.get('organism') or '').replace('.', '')\n return '%s_%s' % (org.replace(' ','_'), s.id.split('.')[0])\n\ndef fetchseq(gi):\n global email\n assert email, \"set email!\"\n Entrez.email = email\n h = Entrez.efetch(db=\"nucleotide\", id=str(gi), rettype=\"gb\")\n s = SeqIO.read(h, 'genbank')\n s.id = organism_id(s)\n return s\n\ndef create_fastas(data, genes):\n fastas = dict([ (g, file(g+\".fasta\", \"w\")) for g in genes ])\n for label, seqs in data.items():\n for gene, s in zip(genes, seqs):\n if s and type(s) != str:\n tag = None\n try:\n tag = \"%s_%s\" % (label, s.annotations[\"accessions\"][0])\n except:\n tag = \"%s_%s\" % (label, s.name)\n if tag:\n fastas[gene].write(\">%s\\n%s\\n\" % (tag, s.seq))\n else:\n sys.stderr.write((\"error: not an accession number? \"\n \"%s (%s %s)\\n\" % (s, label, gene)))\n\n for f in fastas.values(): f.close()\n\ndef merge_fastas(fnames, name=\"merged\"):\n outfile = file(name+\".phy\", \"w\")\n gene2len = {}\n d = defaultdict(dict)\n for fn in fnames:\n gene = fn.split(\".\")[0]\n for rec in SeqIO.parse(file(fn), \"fasta\"):\n #sp = \"_\".join(rec.id.split(\"_\")[:2])\n if rec.id.startswith(\"Pedicularis\"):\n sp = rec.id.split(\"_\")[1]\n else:\n sp = rec.id.split(\"_\")[0]\n sp = \"_\".join(rec.id.split(\"_\")[:-1])\n seq = str(rec.seq)\n d[sp][gene] = seq\n if gene not in gene2len:\n gene2len[gene] = len(seq)\n\n ntax = len(d)\n nchar = sum(gene2len.values())\n outfile.write(\"%s %s\\n\" % (ntax, nchar))\n genes = list(sorted(gene2len.keys()))\n for sp, data in sorted(d.items()):\n s = \"\".join([ (data.get(gene) or \"\".join([\"?\"]*gene2len[gene]))\n for gene in genes ])\n outfile.write(\"%s %s\\n\" % (sp, s))\n outfile.close()\n parts = file(name+\".partitions\", \"w\")\n i = 1\n for g in genes:\n n = gene2len[g]\n parts.write(\"DNA, %s = %s-%s\\n\" % (g, i, i+n-1))\n i += n\n parts.close()\n\ndef blast_closest(fasta, e=10):\n f = NCBIWWW.qblast(\"blastn\", \"nr\", fasta, expect=e, hitlist_size=1)\n rec = NCBIXML.read(f)\n d = rec.descriptions[0]\n result = storage.Storage()\n gi = re.findall(r'gi[|]([0-9]+)', d.title) or None\n if gi: result.gi = int(gi[0])\n ac = re.findall(r'gb[|]([^|]+)', d.title) or None\n if ac: result.ac = ac[0].split(\".\")[0]\n result.title = d.title.split(\"|\")[-1].strip()\n return result\n\ndef blast(query, e=10, n=100, entrez_query=\"\"):\n f = NCBIWWW.qblast(\"blastn\", \"nr\", query, expect=e, hitlist_size=n,\n entrez_query=entrez_query)\n recs = NCBIXML.parse(f)\n return recs\n ## v = []\n ## for d in rec.descriptions:\n ## result = Storage()\n ## gi = re.findall(r'gi[|]([0-9]+)', d.title) or None\n ## if gi: result.gi = int(gi[0])\n ## ac = re.findall(r'gb[|]([^|]+)', d.title) or None\n ## if ac: result.ac = ac[0].split(\".\")[0]\n ## result.title = d.title.split(\"|\")[-1].strip()\n ## v.append(result)\n ## return v\n\ndef start_codons(seq):\n i = seq.find('ATG')\n while i != -1:\n yield i\n i = seq.find('ATG', i+3)\n\ndef search_taxonomy(q):\n global email\n assert email, \"set email!\"\n Entrez.email = email\n h = Entrez.esearch(db=\"taxonomy\", term=q)\n return Entrez.read(h)['IdList']\n\ndef fetchtax(taxid):\n global email\n assert email, \"set email!\"\n Entrez.email = email\n n = 1\n if not isinstance(taxid, int):\n # string, possibly with multiple values?\n try:\n taxid = taxid.strip()\n n = taxid.count(',') + 1\n except AttributeError:\n # iterable of values?\n try:\n n = len(taxid)\n taxid = ','.join(map(str, taxid))\n except TypeError:\n pass\n else:\n taxid = str(taxid)\n h = Entrez.efetch(db='taxonomy', id=taxid, retmode='xml', retmax=n)\n if n == 1:\n r = Entrez.read(h)[0]\n else:\n # a list of taxonomy results in same order of taxids\n r = Entrez.read(h)\n return r\n\n__FIRST = re.compile('[^-]')\n__LAST = re.compile('[-]*$')\ndef trimpos(rec):\n 'return the positions of the first and last ungapped base'\n s = rec.seq.tostring()\n first = __FIRST.search(s).start()\n last = __LAST.search(s).start()-1\n return (first, last)\n\ndef fetch_DNA_seqs(terms, maxn=10000, batchsize=1000):\n \"\"\"\n terms: sequence of search terms, quoted appropriately, with Entrez\n specifiers, e.g. ['\"Mus musculus\"[organism]']\n maxn: maximum number of sequences to return\n returns list of SeqRecord objects\n \"\"\"\n global email\n assert email, \"set email!\"\n Entrez.email = email\n h = Entrez.esearch(db=\"nucleotide\", term=\" OR \".join(terms), usehistory=\"y\")\n d = Entrez.read(h)\n env = d['WebEnv']; key = d['QueryKey']\n N = int(d['Count'])\n if maxn: N = min(N, maxn)\n logging.info('fetching %s sequences', N)\n retstart = 0\n seqs = []\n n = 0\n while n < N:\n h = Entrez.efetch(\n db=\"nucleotide\", rettype='gb', webenv=env, query_key=key,\n retstart=retstart, retmax=batchsize\n )\n v = list(SeqIO.parse(h, \"genbank\"))\n n += len(v)\n logging.info('...fetched %s', n)\n seqs.extend(v)\n retstart += batchsize\n logging.info('...done')\n return seqs\n\ndef seqrec_taxid(seqrec):\n \"extract the NCBI taxon id from a sequence record\"\n for ft in seqrec.features:\n if ft.type == 'source':\n break\n try:\n for x in ft.qualifiers['db_xref']:\n if x.startswith('taxon:'):\n return int(x.split(':')[1])\n except:\n pass\n", "ivy/interactive.py": "#!/usr/bin/env ipython\n# -*- coding: utf-8 -*-\n\"\"\"\nAdds to the interactive IPython/pylab environment\n\"\"\"\nimport sys, os, re\nfrom . import tree, align\nfrom . import vis\n\ndef readtree(data, *args, **kwargs):\n return tree.read(data, *args, **kwargs)\n\ndef readaln(data, *args, **kwargs):\n return align.read(data, *args, **kwargs)\n\ndef treefig(*args, **kwargs):\n if len(args) == 1:\n fig = vis.TreeFigure(args[0], **kwargs)\n else:\n fig = vis.MultiTreeFigure(**kwargs)\n for arg in args:\n # print arg\n fig.add(arg)\n fig.show()\n return fig\n\ndef alnfig(*args, **kwargs):\n return vis.AlignmentFigure(*args, **kwargs)\n\ndef __maketree(self, s):\n words = s.split()\n treename = \"root\"\n fname = None\n if words:\n treename = words.pop(0)\n if words and os.path.isfile(words[0]):\n fname = words.pop(0)\n\n if not fname:\n ## msg = \"\\n\".join([\n ## \"Name of tree file\",\n ## \"(Try dragging one into the terminal):\\n\"\n ## ])\n msg = \"Enter the name of a tree file or a newick string:\\n\"\n fname = raw_input(msg).strip()\n\n quotes = [\"'\", '\"']\n if fname and fname[0] in quotes:\n fname = fname[1:]\n if fname and fname[-1] in quotes:\n fname = fname[:-1]\n if fname:\n try:\n ## root = ivy.tree.read(fname)\n ## IPython.ipapi.get().to_user_ns({treename:root})\n cmd = \"%s = ivy.tree.read('%s')\" % (treename, fname)\n get_ipython().ex(cmd)\n print(\"Tree parsed and assigned to variable '%s'\" % treename)\n except:\n print(\"Unable to parse tree file '%s'\" % fname)\n else:\n print(\"Cancelled\")\n\ndef __node_completer(self, event):\n symbol = event.symbol\n s = event.line\n if symbol:\n s = s[:-len(symbol)]\n quote = \"\"\n if s and s[-1] in [\"'\", '\"']:\n quote = s[-1]\n s = s[:-1]\n #base = (re.findall(r'(\\w+)\\[\\Z', s) or [None])[-1]\n base = \"\".join((re.findall(r'(\\w+\\.\\w*)?(\\.)?(\\w+)\\[\\Z', s) or [\"\"])[-1])\n ## print \"symbol:\", symbol\n ## print \"line:\", event.line\n ## print \"s:\", s\n ## print \"quote:\", quote\n ## print \"base:\", base\n ## print \"obj:\", self._ofind(base).get(\"obj\")\n\n obj = None\n if base:\n obj = self._ofind(base).get(\"obj\")\n ## print '\\n'\n ## print 'base', base\n ## print 'obj', obj\n if obj and isinstance(obj, tree.Node):\n completions = [\"'\"]\n if quote:\n completions = sorted([ x.label for x in obj.labeled() ])\n return completions\n\n raise IPython.core.error.TryNext()\n\ntry:\n ## import IPython\n IP = get_ipython() #IPython.ipapi.get()\n IP.magic('matplotlib')\n if IP:\n #IP.expose_magic(\"maketree\", __maketree)\n # IP.define_magic(\"maketree\", __maketree)\n ## IP.set_hook(\n ## \"complete_command\", __node_completer, re_key=r'\\[*'\n ## )\n IP.set_hook(\n \"complete_command\", __node_completer,\n re_key='.+[[]([\\']|[\"])*\\w*$'\n )\n\nexcept:\n print(sys.exc_info()[0])\n sys.stderr.write(\"Magic commands and completers requires IPython >= 0.11\\n\")\n\n## if __name__ == \"__main__\":\n## if len(sys.argv) > 1:\n## for fname in sys.argv[1:]:\n## if os.path.isfile(fname):\n## execfile(fname)\n", "ivy/layout.py": "\"\"\"\nlayout nodes in 2d space\n\nThe function of interest is `calc_node_positions` (aka nodepos)\n\"\"\"\nfrom __future__ import print_function\nimport numpy\n\nclass Coordinates:\n \"\"\"\n Coordinates class for storing xy coordinates\n \"\"\"\n def __init__(self, x=0, y=0):\n self.x = x\n self.y = y\n\n def __repr__(self):\n return \"Coordinates(%g, %g)\" % (self.x, self.y)\n\n def point(self):\n return (self.x, self.y)\n\ndef smooth_xpos(node, n2coords):\n \"\"\"\n RR: What does smoothing do? -CZ\n \"\"\"\n if not node.isleaf:\n children = node.children\n for ch in children:\n smooth_xpos(ch, n2coords)\n\n if node.parent:\n px = n2coords[node.parent].x\n cx = min([ n2coords[ch].x for ch in children ])\n n2coords[node].x = (px + cx)/2.0\n\ndef depth_length_preorder_traversal(node, n2coords=None, isroot=False):\n \"\"\"\n Calculate node depth (root = depth 0) and length to root\n\n Args:\n node (Node): A node object\n\n Returns:\n dict: Mapping of nodes to coordinate objects. Coordinate\n objects have attributes \"depth\" and \"length_to_root\"\n \"\"\"\n if n2coords is None:\n n2coords = {}\n coords = n2coords.get(node) or Coordinates()\n coords.node = node\n if (not node.parent) or isroot:\n coords.depth = 0\n coords.length_to_root = 0.0\n else:\n try:\n p = n2coords[node.parent]\n coords.depth = p.depth + 1\n coords.length_to_root = p.length_to_root + (node.length or 0.0)\n except KeyError:\n print(node.label, node.parent.label)\n except AttributeError:\n coords.depth = 0\n coords.length_to_root = 0\n n2coords[node] = coords\n\n for ch in node.children:\n depth_length_preorder_traversal(ch, n2coords, False)\n\n return n2coords\n\ndef calc_node_positions(node, width, height,\n lpad=0, rpad=0, tpad=0, bpad=0,\n scaled=True, smooth=True, n2coords=None):\n \"\"\"\n Calculate where nodes should be positioned in 2d space for drawing a tree\n\n Args:\n node (Node): A (root) node\n width (float): The width of the canvas\n height (float): The height of the canvas\n lpad, rpad, tpad, bpad (float): Padding on the edges of the canvas.\n Optional, defaults to 0.\n scaled (bool): Whether or not the tree is scaled. Optional, defaults to\n True.\n smooth (bool): Whether or not to smooth the tree. Optional, defaults to\n True.\n Returns:\n dict: Mapping of nodes to Coordinates object\n Notes:\n Origin is at upper left\n \"\"\"\n width -= (lpad + rpad)\n height -= (tpad + bpad)\n\n if n2coords is None:\n n2coords = {}\n depth_length_preorder_traversal(node, n2coords=n2coords)\n leaves = node.leaves()\n nleaves = len(leaves)\n maxdepth = max([ n2coords[lf].depth for lf in leaves ])\n unitwidth = width/float(maxdepth)\n unitheight = height/(nleaves-1.0)\n\n xoff = (unitwidth * 0.5)\n yoff = (unitheight * 0.5)\n\n if scaled:\n maxlen = max([ n2coords[lf].length_to_root for lf in leaves ])\n scale = width/maxlen\n\n for i, lf in enumerate(leaves):\n c = n2coords[lf]\n c.y = i * unitheight\n if not scaled:\n c.x = width\n else:\n c.x = c.length_to_root * scale\n\n for n in node.postiter():\n c = n2coords[n]\n if (not n.isleaf) and n.children:\n children = n.children\n ymax = n2coords[children[0]].y\n ymin = n2coords[children[-1]].y\n c.y = (ymax + ymin)/2.0\n if not scaled:\n c.x = min([ n2coords[ch].x for ch in children ]) - unitwidth\n else:\n c.x = c.length_to_root * scale\n\n if (not scaled) and smooth:\n for i in range(10):\n smooth_xpos(node, n2coords)\n\n for coords in n2coords.values():\n coords.x += lpad\n coords.y += tpad\n\n for n, coords in n2coords.items():\n if n.parent:\n p = n2coords[n.parent]\n coords.px = p.x; coords.py = p.y\n else:\n coords.px = None; coords.py = None\n\n return n2coords\n\nnodepos = calc_node_positions\n\ndef cartesian(node, xscale=1.0, leafspace=None, scaled=True, n2coords=None,\n smooth=0, array=numpy.array, ones=numpy.ones, yunit=None):\n \"\"\"\n RR: What is the difference between this function and calc_node_positions?\n Is it being used anywhere? -CZ\n \"\"\"\n\n if n2coords is None:\n n2coords = {}\n\n depth_length_preorder_traversal(node, n2coords, True)\n leaves = node.leaves()\n nleaves = len(leaves)\n\n # leafspace is a vector that should sum to nleaves\n if leafspace is None:\n try: leafspace = [ float(x.leafspace) for x in leaves ]\n except: leafspace = numpy.zeros((nleaves,))\n assert len(leafspace) == nleaves\n #leafspace = array(leafspace)/(sum(leafspace)/float(nleaves))\n\n maxdepth = max([ n2coords[lf].depth for lf in leaves ])\n depth = maxdepth * xscale\n #if not yunit: yunit = 1.0/nleaves\n yunit = 1.0\n\n if scaled:\n maxlen = max([ n2coords[lf].length_to_root for lf in leaves ])\n depth = maxlen\n\n y = 0\n for i, lf in enumerate(leaves):\n c = n2coords[lf]\n yoff = 1 + (leafspace[i] * yunit)\n c.y = y + yoff*0.5\n y += yoff\n if not scaled:\n c.x = depth\n else:\n c.x = c.length_to_root\n\n for n in node.postiter():\n c = n2coords[n]\n if not n.isleaf:\n children = n.children\n v = [n2coords[children[0]].y, n2coords[children[-1]].y]\n v.sort()\n ymin, ymax = v\n c.y = (ymax + ymin)/2.0\n if not scaled:\n c.x = min([ n2coords[ch].x for ch in children ]) - 1.0\n else:\n c.x = c.length_to_root\n\n if not scaled:\n for i in range(smooth):\n smooth_xpos(node, n2coords)\n\n return n2coords\n\nif __name__ == \"__main__\":\n import tree\n node = tree.read(\"(a:3,(b:2,(c:4,d:5):1,(e:3,(f:1,g:1):2):2):2);\")\n for i, n in enumerate(node.iternodes()):\n if not n.isleaf:\n n.label = \"node%s\" % i\n node.label = \"root\"\n n2c = calc_node_positions(node, width=10, height=10, scaled=True)\n\n from pprint import pprint\n pprint(n2c)\n", "ivy/ltt.py": "\"\"\"\nCompute lineages through time\n\"\"\"\nimport numpy\n\n# RR: Should results be set to None and then defined in the function to avoid\n# problems with mutable defaults in functions? -CZ\ndef traverse(node, t=0, results=[]):\n \"\"\"\n Recursively traverse the tree and collect information about when\n nodes split and how many lineages are added by its splitting.\n \"\"\"\n if node.children:\n ## if not node.label:\n ## node.label = str(node.id)\n results.append((t, len(node.children)-1))\n for child in node.children:\n traverse(child, t+child.length, results)\n return results\n\ndef ltt(node):\n \"\"\"\n Calculate lineages through time. The tree is assumed to be an\n ultrametric chronogram (extant leaves, with branch lengths\n proportional to time).\n\n Args:\n node (Node): A node object. All nodes should have branch lengths.\n\n Returns:\n tuple: (times, diversity) - 1D-arrays containing the results.\n \"\"\"\n v = traverse(node) # v is a list of (time, diversity) values\n v.sort()\n # for plotting, it is easiest if x and y values are in separate\n # sequences, so we create a transposed array from v\n times, diversity = numpy.array(v).transpose()\n return times, diversity.cumsum()\n\ndef test():\n import newick, ascii\n n = newick.parse(\"(((a:1,b:2):3,(c:3,d:1):1,(e:0.5,f:3):2.5):1,g:4);\")\n v = ltt(n)\n print(ascii.render(n, scaled=1))\n for t, n in v:\n print(t, n)\n\nif __name__ == \"__main__\":\n test()\n", "ivy/newick.py": "\"\"\"\nParse newick strings.\n\nThe function of interest is `parse`, which returns the root node of\nthe parsed tree.\n\"\"\"\nfrom __future__ import print_function, absolute_import, division, unicode_literals\nimport string, sys, re, shlex, itertools\ntry:\n from cStringIO import StringIO\nexcept:\n from io import StringIO\n\n## def read(s):\n## try:\n## s = file(s).read()\n## except:\n## try:\n## s = s.read()\n## except:\n## pass\n## return parse(s)\n\nLABELCHARS = '-.|/?#&'\nMETA = re.compile(r'([^,=\\s]+)\\s*=\\s*(\\{[^=}]*\\}|\"[^\"]*\"|[^,]+)?')\n\ndef add_label_chars(chars):\n global LABELCHARS\n LABELCHARS += chars\n\nclass Error(Exception):\n pass\n\nclass Tokenizer(shlex.shlex):\n \"\"\"Provides tokens for parsing newick strings.\"\"\"\n def __init__(self, infile):\n global LABELCHARS\n shlex.shlex.__init__(self, infile, posix=False)\n self.commenters = ''\n self.wordchars = self.wordchars+LABELCHARS\n self.quotes = \"'\"\n\n def parse_embedded_comment(self):\n ws = self.whitespace\n self.whitespace = \"\"\n v = []\n while 1:\n token = self.get_token()\n if token == '':\n sys.stdout.write('EOF encountered mid-comment!\\n')\n break\n elif token == ']':\n break\n elif token == '[':\n self.parse_embedded_comment()\n else:\n v.append(token)\n self.whitespace = ws\n return \"\".join(v)\n ## print \"comment:\", v\n\ndef parse(data, ttable=None, treename=None):\n \"\"\"\n Parse a newick string.\n\n Args:\n data: Any file-like object that can be coerced into shlex, or\n a string (converted to StringIO)\n ttable (dict): Mapping of node labels in the newick string\n to other values.\n\n Returns:\n Node: The root node.\n \"\"\"\n from .tree import Node\n\n if isinstance(data, str):\n data = StringIO(data)\n\n start_pos = data.tell()\n tokens = Tokenizer(data)\n\n node = None; root = None\n lp=0; rp=0; rooted=1\n\n previous = None\n\n ni = 0 # node id counter (preorder) - zero-based indexing\n li = 0 # leaf index counter\n ii = 0 # internal node index counter\n pi = 0 # postorder sequence\n while 1:\n token = tokens.get_token()\n #print token,\n if token == ';' or token == tokens.eof:\n assert lp == rp, \\\n \"unbalanced parentheses in tree description: (%s, %s)\" \\\n % (lp, rp)\n break\n\n # internal node\n elif token == '(':\n lp = lp+1\n newnode = Node()\n newnode.ni = ni; ni += 1\n newnode.isleaf = False\n newnode.ii = ii; ii += 1\n newnode.treename = treename\n if node:\n if node.children: newnode.left = node.children[-1].right+1\n else: newnode.left = node.left+1\n node.add_child(newnode)\n else:\n newnode.left = 1; newnode.right = 2\n newnode.right = newnode.left+1\n node = newnode\n\n elif token == ')':\n rp = rp+1\n node = node.parent\n node.pi = pi; pi += 1\n if node.children:\n node.right = node.children[-1].right + 1\n\n elif token == ',':\n node = node.parent\n if node.children:\n node.right = node.children[-1].right + 1\n\n # branch length\n elif token == ':':\n token = tokens.get_token()\n if token == '[':\n node.length_comment = tokens.parse_embedded_comment()\n token = tokens.get_token()\n\n if not (token == ''):\n try: brlen = float(token)\n except ValueError as exc:\n raise ValueError(\n \"invalid literal for branch length, '{}'\".format(token))\n else:\n raise Error('unexpected end-of-file (expecting branch length)')\n\n node.length = brlen\n # comment\n elif token == '[':\n node.comment = tokens.parse_embedded_comment()\n if node.comment[0] == '&':\n # metadata\n meta = META.findall(node.comment[1:])\n if meta:\n for k, v in meta:\n v = eval(v.replace('{','(').replace('}',')'))\n node.meta[k] = v\n\n # leaf node or internal node label\n else:\n if previous != ')': # leaf node\n if ttable:\n try:\n ttoken = (ttable.get(int(token)) or\n ttable.get(token))\n except ValueError:\n ttoken = ttable.get(token)\n if ttoken:\n token = ttoken\n newnode = Node()\n newnode.ni = ni; ni += 1\n newnode.pi = pi; pi += 1\n newnode.label = \"_\".join(token.split()).replace(\"'\", \"\")\n newnode.isleaf = True\n newnode.li = li; li += 1\n if node.children: newnode.left = node.children[-1].right+1\n else: newnode.left = node.left+1\n newnode.right = newnode.left+1\n newnode.treename = treename\n node.add_child(newnode)\n node = newnode\n else: # label\n if ttable:\n node.label = ttable.get(token, token)\n else:\n node.label = token\n\n previous = token\n node.isroot = True\n return node\n\n## def string(node, length_fmt=\":%s\", end=True, newline=True):\n## \"Recursively create a newick string from node.\"\n## if not node.isleaf:\n## node_str = \"(%s)%s\" % \\\n## (\",\".join([ string(child, length_fmt, False, newline) \\\n## for child in node.children ]),\n## node.label or \"\"\n## )\n## else:\n## node_str = \"%s\" % node.label\n\n## if node.length is not None:\n## length_str = length_fmt % node.length\n## else:\n## length_str = \"\"\n\n## semicolon = \"\"\n## if end:\n## if not newline:\n## semicolon = \";\"\n## else:\n## semicolon = \";\\n\"\n## s = \"%s%s%s\" % (node_str, length_str, semicolon)\n## return s\n\n## def from_nexus(infile, bufsize=None):\n## bufsize = bufsize or 1024*5000\n## TTABLE = re.compile(r'\\btranslate\\s+([^;]+);', re.I | re.M)\n## TREE = re.compile(r'\\btree\\s+([_.\\w]+)\\s*=[^(]+(\\([^;]+;)', re.I | re.M)\n## s = infile.read(bufsize)\n## ttable = TTABLE.findall(s) or None\n## if ttable:\n## items = [ shlex.split(line) for line in ttable[0].split(\",\") ]\n## ttable = dict([ (k, v.replace(\" \", \"_\")) for k, v in items ])\n## trees = TREE.findall(s)\n## ## for i, t in enumerate(trees):\n## ## t = list(t)\n## ## if ttable:\n## ## t[1] = \"\".join(\n## ## [ ttable.get(x, \"_\".join(x.split()).replace(\"'\", \"\"))\n## ## for x in shlex.shlex(t[1]) ]\n## ## )\n## ## trees[i] = t\n## ## return trees\n## return ttable, trees\n\ndef parse_ampersand_comment(s):\n import pyparsing\n pyparsing.ParserElement.enablePackrat()\n from pyparsing import Word, Literal, QuotedString, CaselessKeyword, \\\n OneOrMore, Group, Optional, Suppress, Regex, Dict\n word = Word(string.ascii_letters+string.digits+\"%_\")\n key = word.setResultsName(\"key\") + Suppress(\"=\")\n single_value = (Word(string.ascii_letters+string.digits+\"-.\") |\n QuotedString(\"'\") |\n QuotedString('\"'))\n range_value = Group(Suppress(\"{\") +\n single_value.setResultsName(\"min\") +\n Suppress(\",\") +\n single_value.setResultsName(\"max\") +\n Suppress(\"}\"))\n pair = (key + (single_value | range_value).setResultsName(\"value\"))\n g = OneOrMore(pair)\n d = []\n for x in g.searchString(s):\n v = x.value\n if isinstance(v, str):\n try: v = float(v)\n except ValueError: pass\n else:\n try: v = map(float, v.asList())\n except ValueError: pass\n d.append((x.key, v))\n return d\n\n# def test_parse_comment():\n# v = ((\"height_median=1.1368683772161603E-13,height=9.188229043880098E-14,\"\n# \"height_95%_HPD={5.6843418860808015E-14,1.7053025658242404E-13},\"\n# \"height_range={0.0,2.8421709430404007E-13}\"),\n# \"R\", \"lnP=-154.27154502342688,lnP=-24657.14341301901\",\n# 'states=\"T-lateral\"')\n# for s in v:\n# print \"input:\", s\n# print dict(parse_ampersand_comment(s))\n", "ivy/nexus.py": "from __future__ import print_function\nimport itertools\nfrom . import newick\n\nclass Newick(object):\n \"\"\"\n convenience class for storing the results of a newick tree\n record from a nexus file, as parsed by newick.nexus_iter\n \"\"\"\n def __init__(self, parse_results=None, ttable={}):\n self.name = \"\"\n self.comment = \"\"\n self.root_comment = \"\"\n self.newick = \"\"\n self.ttable = ttable\n if parse_results: self.populate(parse_results)\n\n def populate(self, parse_results, ttable={}):\n self.name = parse_results.tree_name\n self.comment = parse_results.tree_comment\n self.root_comment = parse_results.root_comment\n self.newick = parse_results.newick\n if ttable: self.ttable = ttable\n\n def parse(self, newick=newick):\n assert self.newick\n self.root = newick.parse(\n self.newick, ttable=self.ttable, treename=self.name\n )\n return self.root\n\ndef fetchaln(fname):\n \"\"\"Fetch alignment\"\"\"\n from Bio.Nexus import Nexus\n n = Nexus.Nexus(fname)\n return n\n\ndef split_blocks(infile):\n try:\n from cStringIO import StringIO\n except:\n from io import StringIO\n dropwhile = itertools.dropwhile; takewhile = itertools.takewhile\n blocks = []\n not_begin = lambda s: not s.lower().startswith(\"begin\")\n not_end = lambda s: not s.strip().lower() in (\"end;\", \"endblock;\")\n while 1:\n f = takewhile(not_end, dropwhile(not_begin, infile))\n try:\n b = f.next().split()[-1][:-1]\n blocks.append((b, StringIO(\"\".join(list(f)))))\n except StopIteration:\n break\n return blocks\n\ndef parse_treesblock(infile):\n import string\n from pyparsing import Optional, Word, Regex, CaselessKeyword, Suppress\n from pyparsing import QuotedString\n comment = Optional(Suppress(\"[&\") + Regex(r'[^]]+') + Suppress(\"]\"))\n name = Word(alphanums+\"_\") | QuotedString(\"'\")\n newick = Regex(r'[^;]+;')\n tree = (CaselessKeyword(\"tree\").suppress() +\n Optional(\"*\").suppress() +\n name.setResultsName(\"tree_name\") +\n comment.setResultsName(\"tree_comment\") +\n Suppress(\"=\") +\n comment.setResultsName(\"root_comment\") +\n newick.setResultsName(\"newick\"))\n ## treesblock = Group(beginblock +\n ## Optional(ttable.setResultsName(\"ttable\")) +\n ## Group(OneOrMore(tree)) +\n ## endblock)\n\n def parse_ttable(f):\n ttable = {}\n while True:\n s = f.next().strip()\n if s.lower() == \";\":\n break\n if s[-1] in \",;\":\n s = s[:-1]\n k, v = s.split()\n ttable[k] = v\n if s[-1] == \";\":\n break\n return ttable\n\n ttable = {}\n while True:\n try:\n s = infile.next().strip()\n except StopIteration:\n break\n if s.lower() == \"translate\":\n ttable = parse_ttable(infile)\n # print(\"ttable: %s\" % len(ttable))\n else:\n match = tree.parseString(s)\n yield Newick(match, ttable)\n\ndef iter_trees(infile):\n import pyparsing\n pyparsing.ParserElement.enablePackrat()\n from pyparsing import (\n Word, Literal, QuotedString, CaselessKeyword, CharsNotIn,\n OneOrMore, Group, Optional, Suppress, Regex, Dict, ZeroOrMore,\n alphanums, nums)\n comment = Optional(Suppress(\"[&\") + Regex(r'[^]]+') + Suppress(\"]\"))\n name = Word(alphanums+\"_.\") | QuotedString(\"'\")\n newick = Regex(r'[^;]+;')\n tree = (CaselessKeyword(\"tree\").suppress() +\n Optional(\"*\").suppress() +\n name.setResultsName(\"tree_name\") +\n comment.setResultsName(\"tree_comment\") +\n Suppress(\"=\") +\n comment.setResultsName(\"root_comment\") +\n newick.setResultsName(\"newick\"))\n\n def not_begin(s):\n # print('not_begin', s)\n return s.strip().lower() != \"begin trees;\"\n def not_end(s):\n # print('not_end', s)\n return s.strip().lower() not in (\"end;\", \"endblock;\")\n def parse_ttable(f):\n ttable = {}\n # com = Suppress('[') + ZeroOrMore(CharsNotIn(']')) + Suppress(']')\n com = Suppress('[' + ZeroOrMore(CharsNotIn(']') + ']'))\n while True:\n s = next(f).strip()\n if not s:\n continue\n s = com.transformString(s).strip()\n if s.lower() == \";\":\n break\n b = False\n if s[-1] in \",;\":\n if s[-1] == ';':\n b = True\n s = s[:-1]\n # print(s)\n k, v = s.split()\n ttable[k] = v\n if b:\n break\n return ttable\n\n # read lines between \"begin trees;\" and \"end;\"\n f = itertools.takewhile(not_end, itertools.dropwhile(not_begin, infile))\n s = next(f).strip().lower()\n if s != \"begin trees;\":\n print(\"Expecting 'begin trees;', got %s\" % s, file=sys.stderr)\n raise StopIteration\n ttable = {}\n while True:\n try:\n s = next(f).strip()\n except StopIteration:\n break\n if not s:\n continue\n if s.lower() == \"translate\":\n ttable = parse_ttable(f)\n # print \"ttable: %s\" % len(ttable)\n elif s.split()[0].lower()=='tree':\n match = tree.parseString(s)\n yield Newick(match, ttable)\n", "ivy/sequtil.py": "try:\n from itertools import izip, imap\nexcept ImportError:\n izip = zip\n imap = map\nimport numpy\n\ndef finditer(seq, substr, start=0):\n \"\"\"\n Find substrings within a sequence\n\n Args:\n seq (str): A sequence.\n substr (str): A subsequence to search for\n start (int): Starting index. Defaults to 0\n Yields:\n int: Starting indicies of where the substr was found in seq\n \"\"\"\n N = len(substr)\n i = seq.find(substr, start)\n while i >= 0:\n yield i\n i = seq.find(substr, i+N)\n\ndef gapidx(seq, gapchar='-'):\n \"\"\"\n For a sequence with gaps, calculate site positions without gaps\n\n Args:\n seq (list): Each element of the list is one character in a sequence.\n gapchar (str): The character gaps are coded as. Defaults to '-'\n Returns:\n array: An array where the first element corresponds to range(number of\n characters that are not gaps) and the second element is the indicies\n of all characters that are not gaps.\n \"\"\"\n a = numpy.array(seq)\n idx = numpy.arange(len(a))\n nongap = idx[a != gapchar]\n return numpy.array((numpy.arange(len(nongap)), nongap))\n\ndef find_stop_codons(seq, pos=0):\n \"\"\"\n Find stop codons within sequence (in reading frame)\n\n Args:\n seq (str): A sequence\n pos (int): Starting position. Defaults to 0.\n Yields:\n tuple: The index where the stop codon starts\n and which stop codon was found.\n \"\"\"\n s = seq[pos:]\n it = iter(s)\n g = imap(lambda x:\"\".join(x), izip(it, it, it))\n for i, x in enumerate(g):\n if x in (\"TAG\", \"TAA\", \"TGA\"):\n yield pos+(i*3), x\n", "ivy/storage.py": "from __future__ import print_function\nfrom operator import itemgetter\nfrom heapq import nlargest\nfrom itertools import repeat\ntry:\n from itertools import ifilter\nexcept:\n ifilter = filter\n\nclass Storage(dict):\n \"\"\"\n A Storage object is like a dictionary except `obj.foo` can be used\n in addition to `obj['foo']`.\n\n From web2py/gluon/storage.py by Massimo Di Pierro (www.web2py.com)\n \"\"\"\n def __getattr__(self, key):\n try:\n return self[key]\n except KeyError:\n return None\n\n def __setattr__(self, key, value):\n self[key] = value\n\n def __delattr__(self, key):\n del self[key]\n\n def __repr__(self):\n return ''\n\n def __getstate__(self):\n return dict(self)\n\n def __setstate__(self, value):\n for (k, v) in value.items():\n self[k] = v\n\nclass MaxDict(dict):\n def __setitem__(self, key, value):\n v = self.get(key)\n if value > v:\n dict.__setitem__(self, key, value)\n \n#from http://code.activestate.com/recipes/576611/\nclass Counter(dict):\n \"\"\"Dict subclass for counting hashable objects. Sometimes called a bag\n or multiset. Elements are stored as dictionary keys and their counts\n are stored as dictionary values.\n\n >>> Counter('zyzygy')\n Counter({'y': 3, 'z': 2, 'g': 1})\n\n \"\"\"\n\n def __init__(self, iterable=None, **kwds):\n \"\"\"Create a new, empty Counter object. And if given, count elements\n from an input iterable. Or, initialize the count from another mapping\n of elements to their counts.\n\n >>> c = Counter() # a new, empty counter\n >>> c = Counter('gallahad') # a new counter from an iterable\n >>> c = Counter({'a': 4, 'b': 2}) # a new counter from a mapping\n >>> c = Counter(a=4, b=2) # a new counter from keyword args\n\n \"\"\" \n self.update(iterable, **kwds)\n\n def __missing__(self, key):\n return 0\n\n def most_common(self, n=None):\n \"\"\"List the n most common elements and their counts from the most\n common to the least. If n is None, then list all element counts.\n\n >>> Counter('abracadabra').most_common(3)\n [('a', 5), ('r', 2), ('b', 2)]\n\n \"\"\" \n if n is None:\n return sorted(self.iteritems(), key=itemgetter(1), reverse=True)\n return nlargest(n, self.iteritems(), key=itemgetter(1))\n\n def elements(self):\n \"\"\"Iterator over elements repeating each as many times as its count.\n\n >>> c = Counter('ABCABC')\n >>> sorted(c.elements())\n ['A', 'A', 'B', 'B', 'C', 'C']\n\n If an element's count has been set to zero or is a negative number,\n elements() will ignore it.\n\n \"\"\"\n for elem, count in self.iteritems():\n for _ in repeat(None, count):\n yield elem\n\n # Override dict methods where the meaning changes for Counter objects.\n\n @classmethod\n def fromkeys(cls, iterable, v=None):\n raise NotImplementedError(\n 'Counter.fromkeys() is undefined. Use Counter(iterable) instead.')\n\n def update(self, iterable=None, **kwds):\n \"\"\"Like dict.update() but add counts instead of replacing them.\n\n Source can be an iterable, a dictionary, or another Counter instance.\n\n >>> c = Counter('which')\n >>> c.update('witch') # add elements from another iterable\n >>> d = Counter('watch')\n >>> c.update(d) # add elements from another counter\n >>> c['h'] # four 'h' in which, witch, and watch\n 4\n\n \"\"\" \n if iterable is not None:\n if hasattr(iterable, 'iteritems'):\n if self:\n self_get = self.get\n for elem, count in iterable.iteritems():\n self[elem] = self_get(elem, 0) + count\n else:\n dict.update(self, iterable) # fast path when counter is empty\n else:\n self_get = self.get\n for elem in iterable:\n self[elem] = self_get(elem, 0) + 1\n if kwds:\n self.update(kwds)\n\n def copy(self):\n 'Like dict.copy() but returns a Counter instance instead of a dict.'\n return Counter(self)\n\n def __delitem__(self, elem):\n 'Like dict.__delitem__() but does not raise KeyError for missing values.'\n if elem in self:\n dict.__delitem__(self, elem)\n\n def __repr__(self):\n if not self:\n return '%s()' % self.__class__.__name__\n items = ', '.join(map('%r: %r'.__mod__, self.most_common()))\n return '%s({%s})' % (self.__class__.__name__, items)\n\n # Multiset-style mathematical operations discussed in:\n # Knuth TAOCP Volume II section 4.6.3 exercise 19\n # and at http://en.wikipedia.org/wiki/Multiset\n #\n # Outputs guaranteed to only include positive counts.\n #\n # To strip negative and zero counts, add-in an empty counter:\n # c += Counter()\n\n def __add__(self, other):\n \"\"\"Add counts from two counters.\n\n >>> Counter('abbb') + Counter('bcc')\n Counter({'b': 4, 'c': 2, 'a': 1})\n\n\n \"\"\"\n if not isinstance(other, Counter):\n return NotImplemented\n result = Counter()\n for elem in set(self) | set(other):\n newcount = self[elem] + other[elem]\n if newcount > 0:\n result[elem] = newcount\n return result\n\n def __sub__(self, other):\n \"\"\" Subtract count, but keep only results with positive counts.\n\n >>> Counter('abbbc') - Counter('bccd')\n Counter({'b': 2, 'a': 1})\n\n \"\"\"\n if not isinstance(other, Counter):\n return NotImplemented\n result = Counter()\n for elem in set(self) | set(other):\n newcount = self[elem] - other[elem]\n if newcount > 0:\n result[elem] = newcount\n return result\n\n def __or__(self, other):\n \"\"\"Union is the maximum of value in either of the input counters.\n\n >>> Counter('abbb') | Counter('bcc')\n Counter({'b': 3, 'c': 2, 'a': 1})\n\n \"\"\"\n if not isinstance(other, Counter):\n return NotImplemented\n _max = max\n result = Counter()\n for elem in set(self) | set(other):\n newcount = _max(self[elem], other[elem])\n if newcount > 0:\n result[elem] = newcount\n return result\n\n def __and__(self, other):\n \"\"\" Intersection is the minimum of corresponding counts.\n\n >>> Counter('abbb') & Counter('bcc')\n Counter({'b': 1})\n\n \"\"\"\n if not isinstance(other, Counter):\n return NotImplemented\n _min = min\n result = Counter()\n if len(self) < len(other):\n self, other = other, self\n for elem in ifilter(self.__contains__, other):\n newcount = _min(self[elem], other[elem])\n if newcount > 0:\n result[elem] = newcount\n return result\n\ndef convert(d):\n \"convert a (potentially nested) dict to Storage\"\n from types import DictType\n t = type(d)\n if t == DictType:\n for k,v in d.items():\n d[k] = convert(v)\n return Storage(d)\n return d\n\nif __name__ == '__main__':\n import doctest\n print(doctest.testmod())\n", "ivy/tree.py": "\"\"\"\nThe Node class and functions for creating trees from Newick strings,\netc.\n\nivy does not have a Tree class per se, as most functions operate\ndirectly on Node objects.\n\"\"\"\nimport os\n# from storage import Storage\nfrom copy import copy as _copy\n# from matrix import vcv\nfrom . import newick, nexus\n# from itertools import izip_longest\n\n## class Tree(object):\n## \"\"\"\n## A simple Tree class.\n## \"\"\"\n## def __init__(self, data=None, format=\"newick\", name=None, ttable=None):\n## self.root = None\n## if data:\n## self.root = read(data, format, name, ttable)\n## self.name = name\n## self.ttable = ttable\n\n## def __getattribute__(self, a):\n## r = object.__getattribute__(self, 'root')\n## try:\n## return object.__getattribute__(r, a)\n## except AttributeError:\n## return object.__getattribute__(self, a)\n\ndef traverse(node):\n \"recursive preorder iterator based solely on .children attribute\"\n yield node\n for child in node.children:\n for descendant in traverse(child):\n yield descendant\n\nclass Node(object):\n \"\"\"\n A basic Node class with attributes and references to child nodes\n ('children', a list) and 'parent'.\n\n Keyword Args:\n id: ID of the node. If not provided, is set using\n builtin id function\n ni (int): Node index.\n li (int): Leaf index.\n isroot (bool): Is the node a root.\n isleaf (bool): Is the node a leaf.\n label (str): Node label.\n length (float): Branch length from node to parent\n support: RR: Are these bootstrap support values? -CZ\n age (float): Age of the node in time units.\n parent (Node): Parent of the ndoe.\n children (list): List of node objects. Children of node\n nchildren (int): No. of children\n left: RR: Unsure what left and right mean -CZ\n treename: Name of tree\n comment: Comments for tree\n\n \"\"\"\n def __init__(self, **kwargs):\n self.id = None\n self.ni = None # node index\n self.li = None # leaf index\n self.isroot = False\n self.isleaf = False\n self.label = None\n self.length = None\n self.support = None\n self.age = None\n self.parent = None\n self.children = []\n self.nchildren = 0\n self.left = None\n self.right = None\n self.treename = \"\"\n self.comment = \"\"\n self.meta = {}\n ## self.length_comment = \"\"\n ## self.label_comment = \"\"\n if kwargs:\n for k, v in kwargs.items():\n setattr(self, k, v)\n if self.id is None:\n self.id = id(self)\n\n def __copy__(self):\n return self.copy()\n\n def __repr__(self):\n v = []\n if self.isroot:\n v.append(\"root\")\n elif self.isleaf:\n v.append(\"leaf\")\n\n if self.label:\n v.append(\"'%s'\" % self.label)\n\n s = \", \".join(v)\n\n nid = self.ni if (self.ni is not None) else self.id\n\n if s:\n s = \"Node(%s, %s)\" % (nid, s)\n else:\n s = \"Node(%s)\" % nid\n return s\n\n\n def __contains__(self, other):\n \"\"\"\n For use with `in` keyword\n\n Args:\n other: Another node or node label.\n Returns:\n bool: Whether or not the other node is a descendant of self\n \"\"\"\n if other and isinstance(other, str):\n for x in self:\n if other == x.label:\n return True\n return False\n else:\n assert isinstance(self, Node)\n for x in self.iternodes():\n if other == x:\n return True\n return False\n\n def __iter__(self):\n for node in self.iternodes():\n yield node\n\n def __len__(self):\n \"\"\"\n Number of nodes descended from self\n\n Returns:\n int: Number of nodes descended from self (including self)\n \"\"\"\n i = 0\n for n in self:\n i += 1\n return i\n\n def __nonzero__(self):\n return True\n\n def __getitem__(self, x):\n \"\"\"\n Args:\n x: A Node, Node.id (int) or a Node.label (string)\n\n Returns:\n Node: Found node(s)\n\n \"\"\"\n for n in self:\n if n==x or n.id==x or n.ni == x or (n.label and n.label==x):\n return n\n raise IndexError(str(x))\n\n def ascii(self, *args, **kwargs):\n \"\"\"\n Create ascii tree.\n\n Keyword Args:\n unitlen (float): How long each unit should be rendered as.\n Defaults to 3.\n minwidth (float): Minimum width of the plot. Defaults to 50\n maxwidth (float): Maximum width of the plot. Defaults to None\n scaled (bool): Whether or not the tree is scaled. Defaults to False\n show_internal_labels (bool): Whether or not to show labels\n on internal nodes. Defaults to True.\n Returns:\n str: Ascii tree to be shown with print().\n \"\"\"\n from . import ascii as _ascii\n return _ascii.render(self, *args, **kwargs)\n\n def collapse(self, add=False):\n \"\"\"\n Remove self and collapse children to polytomy\n\n Args:\n add (bool): Whether or not to add self's length to children's\n length.\n\n Returns:\n Node: Parent of self\n\n \"\"\"\n assert self.parent\n p = self.prune()\n for c in self.children:\n p.add_child(c)\n if add and (c.length is not None):\n c.length += self.length\n self.children = []\n return p\n\n def copy(self, recurse=False):\n \"\"\"\n Return a copy of the node, but not copies of children, parent,\n or any attribute that is a Node.\n\n If `recurse` is True, recursively copy child nodes.\n\n Args:\n recurse (bool): Whether or not to copy children as well as self.\n\n Returns:\n Node: A copy of self.\n\n TODO: test this function.\n\n RR: This function runs rather slowly -CZ\n \"\"\"\n newnode = Node()\n for attr, value in self.__dict__.items():\n if (attr not in (\"children\", \"parent\") and\n not isinstance(value, Node)):\n setattr(newnode, attr, _copy(value))\n if recurse:\n newnode.children = [\n child.copy(True) for child in self.children\n ]\n return newnode\n\n def leafsets(self, d=None, labels=False):\n \"\"\"return a mapping of nodes to leaf sets (nodes or labels)\"\"\"\n d = d or {}\n if not self.isleaf:\n s = set()\n for child in self.children:\n if child.isleaf:\n if labels:\n s.add(child.label)\n else:\n s.add(child)\n else:\n d = child.leafsets(d, labels)\n s = s | d[child]\n d[self] = frozenset(s)\n return d\n\n def mrca(self, *nodes):\n \"\"\"\n Find most recent common ancestor of *nodes*\n\n Args:\n *nodes (Node): Node objects\n Returns:\n Node: The MRCA of *nodes*\n \"\"\"\n if len(nodes) == 1:\n nodes = tuple(nodes[0])\n if len(nodes) == 1:\n return nodes[0]\n nodes = set([ self[n] for n in nodes ])\n anc = []\n def f(n):\n seen = set()\n for c in n.children: seen.update(f(c))\n if n in nodes: seen.add(n)\n if seen == nodes and (not anc): anc.append(n)\n return seen\n f(self)\n return anc[0]\n\n ## def mrca(self, *nodes):\n ## \"\"\"\n ## Find most recent common ancestor of *nodes*\n ## \"\"\"\n ## if len(nodes) == 1:\n ## nodes = tuple(nodes[0])\n ## if len(nodes) == 1:\n ## return nodes[0]\n ## ## assert len(nodes) > 1, (\n ## ## \"Need more than one node for mrca(), got %s\" % nodes\n ## ## )\n ## def f(x):\n ## if isinstance(x, Node):\n ## return x\n ## elif type(x) in types.StringTypes:\n ## return self.find(x)\n ## nodes = map(f, nodes)\n ## assert all(filter(lambda x: isinstance(x, Node), nodes))\n\n ## #v = [ list(n.rootpath()) for n in nodes if n in self ]\n ## v = [ list(x) for x in izip_longest(*[ reversed(list(n.rootpath()))\n ## for n in nodes if n in self ]) ]\n ## if len(v) == 1:\n ## return v[0][0]\n ## anc = None\n ## for x in v:\n ## s = set(x)\n ## if len(s) == 1: anc = list(s)[0]\n ## else: break\n ## return anc\n\n def ismono(self, *leaves):\n \"\"\"\n Test if leaf descendants are monophyletic\n\n Args:\n *leaves (Node): At least two leaf Node objects\n\n Returns:\n bool: Are the leaf descendants monophyletic?\n\n RR: Should this function have a check to make sure the input nodes are\n leaves? There is some strange behavior if you input internal nodes -CZ\n \"\"\"\n if len(leaves) == 1:\n leaves = list(leaves)[0]\n assert len(leaves) > 1, (\n \"Need more than one leaf for ismono(), got %s\" % leaves\n )\n anc = self.mrca(leaves)\n if anc:\n return bool(len(anc.leaves())==len(leaves))\n\n def order_subtrees_by_size(self, n2s=None, recurse=False, reverse=False):\n \"\"\"\n Order interal clades by size\n\n \"\"\"\n if n2s is None:\n n2s = clade_sizes(self)\n if not self.isleaf:\n v = [ (n2s[c], c.label or '', c.id, c) for c in self.children ]\n v.sort()\n if reverse:\n v.reverse()\n self.children = [ x[-1] for x in v ]\n if recurse:\n for c in self.children:\n c.order_subtrees_by_size(n2s, recurse=True, reverse=reverse)\n\n def ladderize(self, reverse=False):\n self.order_subtrees_by_size(recurse=True, reverse=reverse)\n return self\n\n def add_child(self, child):\n \"\"\"\n Add child as child of self\n\n Args:\n child (Node): A node object\n\n \"\"\"\n assert child not in self.children\n self.children.append(child)\n child.parent = self\n child.isroot = False\n self.nchildren += 1\n\n def bisect_branch(self):\n \"\"\"\n Add new node as parent to self in the middle of branch to parent.\n\n Returns:\n Node: A new node.\n\n \"\"\"\n assert self.parent\n parent = self.prune()\n n = Node()\n if self.length:\n n.length = self.length/2.0\n self.length /= 2.0\n parent.add_child(n)\n n.add_child(self)\n return n\n\n def remove_child(self, child):\n \"\"\"\n Remove child.\n\n Args:\n child (Node): A node object that is a child of self\n\n \"\"\"\n assert child in self.children\n self.children.remove(child)\n child.parent = None\n self.nchildren -= 1\n if not self.children:\n self.isleaf = True\n\n def labeled(self):\n \"\"\"\n Return a list of all descendant nodes that are labeled\n\n Returns:\n list: All descendants of self that are labeled (including self)\n \"\"\"\n return [ n for n in self if n.label ]\n\n def leaves(self, f=None):\n \"\"\"\n Return a list of leaves. Can be filtered with f.\n\n Args:\n f (function): A function that evaluates to True if called with desired\n node as the first input\n\n Returns:\n list: A list of leaves that are true for f (if f is given)\n\n \"\"\"\n if f: return [ n for n in self if (n.isleaf and f(n)) ]\n return [ n for n in self if n.isleaf ]\n\n def internals(self, f=None):\n \"\"\"\n Return a list nodes that have children (internal nodes)\n\n Args:\n f (function): A function that evaluates to true if called with desired\n node as the first input\n\n Returns:\n list: A list of internal nodes that are true for f (if f is given)\n\n \"\"\"\n if f: return [ n for n in self if (n.children and f(n)) ]\n return [ n for n in self if n.children ]\n\n def clades(self):\n \"\"\"\n Get internal nodes descended from self\n\n Returns:\n list: A list of internal nodes descended from (and not including) self.\n\n \"\"\"\n return [ n for n in self if (n is not self) and not n.isleaf ]\n\n def iternodes(self, f=None):\n \"\"\"\n Return a generator of nodes descendant from self - including self\n\n Args:\n f (function): A function that evaluates to true if called with\n desired node as the first input\n\n Yields:\n Node: Nodes descended from self (including self) in\n preorder sequence\n\n \"\"\"\n if (f and f(self)) or (not f):\n yield self\n for child in self.children:\n for n in child.iternodes(f):\n yield n\n\n def iterleaves(self):\n \"\"\"\n Yield leaves descendant from self\n \"\"\"\n return self.iternodes(lambda x:x.isleaf)\n\n def preiter(self, f=None):\n \"\"\"\n Yield nodes in preorder sequence\n \"\"\"\n for n in self.iternodes(f=f):\n yield n\n\n def postiter(self, f=None):\n \"\"\"\n Yield nodes in postorder sequence\n \"\"\"\n if not self.isleaf:\n for child in self.children:\n for n in child.postiter():\n if (f and f(n)) or (not f):\n yield n\n if (f and f(self)) or (not f):\n yield self\n\n def descendants(self, order=\"pre\", v=None, f=None):\n \"\"\"\n Return a list of nodes descendant from self - but _not_\n including self!\n\n Args:\n order (str): Indicates wether to return nodes in preorder or\n postorder sequence. Optional, defaults to \"pre\"\n f (function): filtering function that evaluates to True if desired\n node is called as the first parameter.\n\n Returns:\n list: A list of nodes descended from self not including self.\n\n \"\"\"\n v = v or []\n for child in self.children:\n if (f and f(child)) or (not f):\n if order == \"pre\":\n v.append(child)\n else:\n v.insert(0, child)\n if child.children:\n child.descendants(order, v, f)\n return v\n\n def get(self, f, *args, **kwargs):\n \"\"\"\n Return the first node found by node.find()\n\n Args:\n f (function): A function that evaluates to True if desired\n node is called as the first parameter.\n Returns:\n Node: The first node found by node.find()\n\n \"\"\"\n v = self.find(f, *args, **kwargs)\n try:\n return v.next()\n except StopIteration:\n return None\n\n def grep(self, s, ignorecase=True):\n \"\"\"\n Find nodes by regular-expression search of labels\n\n Args:\n s (str): String to search.\n ignorecase (bool): Indicates to ignore case. Defaults to true.\n\n Returns:\n lsit: A list of node objects whose labels were matched by s.\n\n \"\"\"\n import re\n if ignorecase:\n pattern = re.compile(s, re.IGNORECASE)\n else:\n pattern = re.compile(s)\n\n search = pattern.search\n return [ x for x in self if x.label and search(x.label) ]\n\n def lgrep(self, s, ignorecase=True):\n \"\"\"\n Find leaves by regular-expression search of labels\n\n Args:\n s (str): String to search.\n ignorecase (bool): Indicates to ignore case. Defaults to true.\n\n Returns:\n lsit: A list of node objects whose labels were matched by s.\n\n \"\"\"\n return [ x for x in self.grep(s, ignorecase=ignorecase) if x.isleaf ]\n\n def bgrep(self, s, ignorecase=True):\n \"\"\"\n Find branches (internal nodes) by regular-expression search of\n labels\n\n Args:\n s (str): String to search.\n ignorecase (bool): Indicates to ignore case. Defaults to true.\n\n Returns:\n lsit: A list of node objects whose labels were matched by s.\n\n \"\"\"\n return [ x for x in self.grep(s, ignorecase=ignorecase) if\n (not x.isleaf) ]\n\n def find(self, f, *args, **kwargs):\n \"\"\"\n Find descendant nodes.\n\n Args:\n f: Function or a string. If a string, it is converted to a\n function for finding *f* as a substring in node labels.\n Otherwise, *f* should evaluate to True if called with a desired\n node as the first parameter.\n\n Yields:\n Node: Found nodes in preorder sequence.\n\n \"\"\"\n if not f:\n return\n if isinstance(f, str):\n func = lambda x: (f or None) in (x.label or \"\")\n else:\n func = f\n for n in self.iternodes():\n if func(n, *args, **kwargs):\n yield n\n\n def findall(self, f, *args, **kwargs):\n \"\"\"Return a list of found nodes.\"\"\"\n return list(self.find(f, *args, **kwargs))\n\n def prune(self):\n \"\"\"\n Remove self if self is not root.\n\n Returns:\n Node: Parent of self. If parent had only two children,\n parent is now a 'knee' and can be removed with excise.\n\n \"\"\"\n p = self.parent\n if p:\n p.remove_child(self)\n return p\n\n def excise(self):\n \"\"\"\n For 'knees': remove self from between parent and single child\n \"\"\"\n assert self.parent\n assert len(self.children)==1\n p = self.parent\n c = self.children[0]\n if c.length is not None and self.length is not None:\n c.length += self.length\n c.prune()\n self.prune()\n p.add_child(c)\n return p\n\n def graft(self, node):\n \"\"\"\n Add node as sister to self.\n \"\"\"\n parent = self.parent\n parent.remove_child(self)\n n = Node()\n n.add_child(self)\n n.add_child(node)\n parent.add_child(n)\n\n ## def leaf_distances(self, store=None, measure=\"length\"):\n ## \"\"\"\n ## for each internal node, calculate the distance to each leaf,\n ## measured in branch length or internodes\n ## \"\"\"\n ## if store is None:\n ## store = {}\n ## leaf2len = {}\n ## if self.children:\n ## for child in self.children:\n ## if measure == \"length\":\n ## dist = child.length\n ## elif measure == \"nodes\":\n ## dist = 1\n ## child.leaf_distances(store, measure)\n ## if child.isleaf:\n ## leaf2len[child] = dist\n ## else:\n ## for k, v in store[child].items():\n ## leaf2len[k] = v + dist\n ## else:\n ## leaf2len[self] = {self: 0}\n ## store[self] = leaf2len\n ## return store\n\n def leaf_distances(self, measure=\"length\"):\n \"\"\"\n RR: I don't quite understand the structure of the output. Also,\n I can't figure out what \"measure\" does.-CZ\n \"\"\"\n from collections import defaultdict\n store = defaultdict(lambda:defaultdict(lambda:0))\n nodes = [ x for x in self if x.children ]\n for lf in self.leaves():\n x = lf.length\n for n in lf.rootpath(self):\n store[n][lf] = x\n x += (n.length or 0)\n return store\n\n def rootpath(self, end=None, stop=None):\n \"\"\"\n Iterate over parent nodes toward the root, or node *end* if\n encountered.\n\n Args:\n end (Node): A Node object to iterate to (instead of iterating\n towards root). Optional, defaults to None\n stop (function): A function that returns True if desired node is called\n as the first parameter. Optional, defaults to None\n\n Yields:\n Node: Nodes in path to root (or end).\n\n \"\"\"\n n = self.parent\n while 1:\n if n is None: raise StopIteration\n yield n\n if n.isroot or (end and n == end) or (stop and stop(n)):\n raise StopIteration\n n = n.parent\n\n def rootpath_length(self, end=None):\n \"\"\"\n Get length from self to root(if end is None) or length\n from self to an ancestor node (if end is an ancestor to self)\n\n Args:\n end (Node): A node object\n\n Returns:\n float: The length from self to root/end\n\n \"\"\"\n n = self\n x = 0.0\n while n.parent:\n x += n.length\n if n.parent == end:\n break\n n = n.parent\n return x\n ## f = lambda x:x.parent==end\n ## v = [self.length]+[ x.length for x in self.rootpath(stop=f)\n ## if x.parent ]\n ## assert None not in v\n ## return sum(v)\n\n def max_tippath(self, first=True):\n \"\"\"\n Get the maximum length from self to a leaf node\n \"\"\"\n v = 0\n if self.children:\n v = max([ c.max_tippath(False) for c in self.children ])\n if not first:\n if self.length is None: v += 1\n else: v += self.length\n return v\n\n def subtree_mapping(self, labels, clean=False):\n \"\"\"\n Find the set of nodes in 'labels', and create a new tree\n representing the subtree connecting them. Nodes are assumed\n to be non-nested.\n\n Returns:\n dict: a mapping of old nodes to new nodes and vice versa.\n\n TODO: test this, high bug probability\n \"\"\"\n d = {}\n oldtips = [ x for x in self.leaves() if x.label in labels ]\n for tip in oldtips:\n path = list(tip.rootpath())\n for node in path:\n if node not in d:\n newnode = Node()\n newnode.isleaf = node.isleaf\n newnode.length = node.length\n newnode.label = node.label\n d[node] = newnode\n d[newnode] = node\n else:\n newnode = d[node]\n\n for child in node.children:\n if child in d:\n newchild = d[child]\n if newchild not in newnode.children:\n newnode.add_child(newchild)\n d[\"oldroot\"] = self\n d[\"newroot\"] = d[self]\n if clean:\n n = d[\"newroot\"]\n while 1:\n if n.nchildren == 1:\n oldnode = d[n]\n del d[oldnode]; del d[n]\n child = n.children[0]\n child.parent = None\n child.isroot = True\n d[\"newroot\"] = child\n d[\"oldroot\"] = d[child]\n n = child\n else:\n break\n\n for tip in oldtips:\n newnode = d[tip]\n while 1:\n newnode = newnode.parent\n oldnode = d[newnode]\n if newnode.nchildren == 1:\n child = newnode.children[0]\n if newnode.length:\n child.length += newnode.length\n newnode.remove_child(child)\n if newnode.parent:\n parent = newnode.parent\n parent.remove_child(newnode)\n parent.add_child(child)\n del d[oldnode]; del d[newnode]\n if not newnode.parent:\n break\n\n return d\n\n def reroot_orig(self, newroot):\n assert newroot in self\n self.isroot = False\n newroot.isroot = True\n v = []\n n = newroot\n while 1:\n v.append(n)\n if not n.parent: break\n n = n.parent\n v.reverse()\n for i, cp in enumerate(v[:-1]):\n node = v[i+1]\n # node is current node; cp is current parent\n cp.remove_child(node)\n node.add_child(cp)\n cp.length = node.length\n return newroot\n\n def reroot(self, newroot):\n \"\"\"\n RR: I can't get this to work properly -CZ\n \"\"\"\n newroot = self[newroot]\n assert newroot in self\n self.isroot = False\n n = newroot\n v = list(n.rootpath())\n v.reverse()\n for node in (v+[n])[1:]:\n # node is current node; cp is current parent\n cp = node.parent\n cp.remove_child(node)\n node.add_child(cp)\n cp.length = node.length\n cp.label = node.label\n newroot.isroot = True\n return newroot\n\n def makeroot(self, shift_labels=False):\n \"\"\"\n shift_labels: flag to shift internal parent-child node labels\n when internode polarity changes; suitable e.g. if internal node\n labels indicate unrooted bipartition support\n \"\"\"\n v = list(self.rootpath())\n v[-1].isroot = False\n v.reverse()\n for node in v[1:] + [self]:\n # node is current node; cp is current parent\n cp = node.parent\n cp.remove_child(node)\n node.add_child(cp)\n cp.length = node.length\n if shift_labels:\n cp.label = node.label\n self.isroot = True\n return self\n\n def write(self, outfile=None, format=\"newick\", length_fmt=\":%g\", end=True,\n clobber=False):\n if format==\"newick\":\n s = write_newick(self, outfile, length_fmt, True, clobber)\n if not outfile:\n return s\n\n\nreroot = Node.reroot\n\ndef index(node, n=0, d=0):\n \"\"\"\n recursively attach 'next', 'back', (and 'left', 'right'), 'ni',\n 'ii', 'pi', and 'node_depth' attributes to nodes\n \"\"\"\n node.next = node.left = n\n if not node.parent:\n node.node_depth = d\n else:\n node.node_depth = node.parent.node_depth + 1\n n += 1\n for i, c in enumerate(node.children):\n if i > 0:\n n = node.children[i-1].back + 1\n index(c, n)\n\n if node.children:\n node.back = node.right = node.children[-1].back + 1\n else:\n node.back = node.right = n\n return node.back\n\ndef remove_singletons(root, add=True):\n \"Remove descendant nodes that are the sole child of their parent\"\n for leaf in root.leaves():\n for n in leaf.rootpath():\n if n.parent and len(n.parent.children)==1:\n n.collapse(add)\n\ndef cls(root):\n \"\"\"\n Get clade sizes of whole tree\n Args:\n * root: A root node\n\n Returns:\n * A dict mapping nodes to clade sizes\n\n \"\"\"\n results = {}\n for node in root.postiter():\n if node.isleaf:\n results[node] = 1\n else:\n results[node] = sum(results[child] for child in node.children)\n return results\n\ndef clade_sizes(node, results={}):\n \"\"\"Map node and descendants to number of descendant tips\"\"\"\n size = int(node.isleaf)\n if not node.isleaf:\n for child in node.children:\n clade_sizes(child, results)\n size += results[child]\n results[node] = size\n return results\n\ndef write(node, outfile=None, format=\"newick\", length_fmt=\":%g\",\n clobber=False):\n if format==\"newick\" or (isinstance(outfile, str) and\n outfile.endswith(\".newick\") or\n outfile.endswith(\".new\")):\n s = write_newick(node, outfile, length_fmt, True, clobber)\n if not outfile:\n return s\n\ndef write_newick(node, outfile=None, length_fmt=\":%g\", end=False,\n clobber=False):\n if not node.isleaf:\n node_str = \"(%s)%s\" % \\\n (\",\".join([ write_newick(child, outfile, length_fmt,\n False, clobber)\n for child in node.children ]),\n (node.label or \"\")\n )\n else:\n node_str = \"%s\" % node.label\n\n if node.length is not None:\n length_str = length_fmt % node.length\n else:\n length_str = \"\"\n\n semicolon = \"\"\n if end:\n semicolon = \";\"\n s = \"%s%s%s\" % (node_str, length_str, semicolon)\n if end and outfile:\n flag = False\n if isinstance(outfile, str):\n if not clobber:\n assert not os.path.isfile(outfile), \"File '%s' exists! (Set clobber=True to overwrite)\" % outfile\n flag = True\n outfile = open(outfile, \"w\")\n outfile.write(s)\n if flag:\n outfile.close()\n return s\n\ndef read(data, format=None, treename=None, ttable=None):\n \"\"\"\n Read a single tree from *data*, which can be a Newick string, a\n file name, or a file-like object with `tell` and 'read`\n methods. *treename* is an optional string that will be attached to\n all created nodes.\n\n Args:\n data: A file or file-like object or newick string\n\n Returns:\n Node: The root node.\n \"\"\"\n\n def strip(s):\n fname = os.path.split(s)[-1]\n head, tail = os.path.splitext(fname)\n tail = tail.lower()\n if tail in (\".nwk\", \".tre\", \".tree\", \".newick\", \".nex\"):\n return head\n else:\n return fname\n\n if (not format):\n if isinstance(data, str) and os.path.isfile(data):\n s = data.lower()\n for tail in \".nex\", \".nexus\", \".tre\":\n if s.endswith(tail):\n format=\"nexus\"\n break\n\n if (not format):\n format = \"newick\"\n\n if format == \"newick\":\n if isinstance(data, str):\n if os.path.isfile(data):\n treename = strip(data)\n return newick.parse(open(data), treename=treename,\n ttable=ttable)\n else:\n return newick.parse(data, ttable=ttable)\n\n elif (hasattr(data, \"tell\") and hasattr(data, \"read\")):\n treename = strip(getattr(data, \"name\", None))\n return newick.parse(data, treename=treename, ttable=ttable)\n elif format == \"nexus-dendropy\":\n import dendropy\n if isinstance(data, str):\n if os.path.isfile(data):\n treename = strip(data)\n return newick.parse(\n str(dendropy.Tree.get_from_path(data, \"nexus\")),\n treename=treename\n )\n else:\n return newick.parse(\n str(dendropy.Tree.get_from_string(data, \"nexus\"))\n )\n\n elif (hasattr(data, \"tell\") and hasattr(data, \"read\")):\n treename = strip(getattr(data, \"name\", None))\n return newick.parse(\n str(dendropy.Tree.get_from_stream(data, \"nexus\")),\n treename=treename\n )\n else:\n pass\n\n elif format == \"nexus\":\n if isinstance(data, str):\n if os.path.isfile(data):\n with open(data) as infile:\n nexiter = nexus.iter_trees(infile)\n rec = next(nexiter)\n if rec:\n return rec.parse()\n else:\n nexiter = nexus.iter_trees(StringIO(data))\n else:\n nexiter = nexus.iter_trees(data)\n rec = next(nexiter)\n if rec:\n return rec.parse()\n else:\n # implement other tree formats here (nexus, nexml etc.)\n raise IOError(\"format '%s' not implemented yet\" % format)\n\n raise IOError(\"unable to read tree from '%s'\" % data)\n\ndef readmany(data, format=\"newick\"):\n \"\"\"Iterate over trees from a source.\"\"\"\n if isinstance(data, str):\n if os.path.isfile(data):\n data = open(data)\n else:\n data = StringIO(data)\n\n if format == \"newick\":\n for line in data:\n yield newick.parse(line)\n elif format == \"nexus\":\n for rec in newick.nexus_iter(data):\n yield rec.parse()\n else:\n raise Exception(\"format '%s' not recognized\" % format)\n data.close()\n\n## def randomly_resolve(n):\n## assert len(n.children)>2\n\n## def leaf_mrcas(root):\n## from itertools import product, izip, tee\n## from collections import OrderedDict\n## from numpy import empty\n## mrca = OrderedDict()\n## def pairwise(iterable, tee=tee, izip=izip):\n## a, b = tee(iterable)\n## next(b, None)\n## return izip(a, b)\n## def f(n):\n## if n.isleaf:\n## od = OrderedDict(); od[n] = n.length\n## return od\n## d = [ f(c) for c in n.children ]\n## for i, j in pairwise(xrange(len(d))):\n## di = d[i]; dj =d[j]\n## for ni, niv in di.iteritems():\n## for nj, njv in dj.iteritems():\n## mrca[(ni,nj)] = n\n## d[j].update(di)\n## return d[j]\n## f(root)\n## return mrca\n\ndef C(leaves, internals):\n from scipy.sparse import lil_matrix\n m = lil_matrix((len(internals), len(leaves)))\n for lf in leaves:\n v = lf.length if lf.length is not None else 1\n for n in lf.rootpath():\n m[n.ii,lf.li] = v\n v += n.length if n.length is not None else 1\n return m.tocsc()\n", "ivy/treebase.py": "\"\"\"\nFunctions to get trees and character data from treebase\n\"\"\"\n\ntry:\n from urllib2 import urlopen\nexcept ImportError:\n from urllib.request import urlopen\nfrom lxml import etree\nfrom . import storage\nimport sys, re\n\n# \"http://purl.org/phylo/treebase/phylows/study/TB2:S11152\"\n\nTREEBASE_WEBSERVICE = \"http://purl.org/phylo/treebase/phylows\"\nNEXML_NAMESPACE = \"http://www.nexml.org/2009\"\nNEXML = \"{%s}\" % NEXML_NAMESPACE\nUNIPROT = \"http://purl.uniprot.org/taxonomy/\"\nNAMEBANK = (\"http://www.ubio.org/authority/metadata.php?\"\n \"lsid=urn:lsid:ubio.org:namebank:\")\n\nROW_SEGMENTS = (\"http://treebase.org/treebase-web/search/study/\"\n \"rowSegmentsTSV.html?matrixid=\")\n\nMETA_DATATYPE = {\n \"xsd:long\": int,\n \"xsd:integer\": int,\n \"xsd:string\": str\n }\n\nAMBIG_RE = re.compile(r'([{][a-zA-Z]+[}])')\n\ndef fetch_study(study_id, format=\"nexml\"):\n \"\"\"\n Get a study from treebase in one of various formats\n\n Args:\n study_id (str): The id of the study\n format (str): One of [\"rdf\", \"html\", \"nexml\", \"nexus\"]\n Returns:\n Str representing a nexus file (if format = \"nexus\")\n\n OR\n\n An lxml etree object\n \"\"\"\n try: study_id = \"S%s\" % int(study_id)\n except ValueError: pass\n\n # format is one of [\"rdf\", \"html\", \"nexml\", \"nexus\"]\n url = \"%s/study/TB2:%s?format=%s\" % (TREEBASE_WEBSERVICE, study_id, format)\n if format==\"nexus\":\n return urlopen(url).read()\n else:\n return etree.parse(url)\n\ndef parse_chars(e, otus):\n v = []\n for chars in e.findall(NEXML+\"characters\"):\n c = storage.Storage(chars.attrib)\n c.states = parse_states(chars)\n c.meta = storage.Storage()\n for meta in chars.findall(NEXML+\"meta\"):\n a = meta.attrib\n if a.get(\"content\"):\n value = META_DATATYPE[a[\"datatype\"]](a[\"content\"])\n c.meta[a[\"property\"]] = value\n c.matrices = []\n for matrix in chars.findall(NEXML+\"matrix\"):\n m = storage.Storage()\n m.rows = []\n for row in matrix.findall(NEXML+\"row\"):\n r = storage.Storage(row.attrib)\n r.otu = otus[r.otu]\n s = row.findall(NEXML+\"seq\")[0].text\n substrs = []\n for ss in AMBIG_RE.split(s):\n if ss.startswith(\"{\"):\n key = frozenset(ss[1:-1])\n val = c.states.states2symb.get(key)\n if key and not val:\n sys.stderr.write(\"missing ambig symbol for %s\\n\" %\n \"\".join(sorted(key)))\n ss = val or \"?\"\n substrs.append(ss)\n s = \"\".join(substrs)\n r.seq = s\n m.rows.append(r)\n c.matrices.append(m)\n v.append(c)\n return v\n\ndef parse_trees(e, otus):\n \"\"\"\n Get trees from an etree object\n\n Args:\n e: A nexml document parsed by etree\n otus: OTUs returned by parse_otus\n Returns:\n list: A list of ivy Storage objects each\n containing every node of a tree.\n \"\"\"\n from tree import Node\n v = []\n for tb in e.findall(NEXML+\"trees\"):\n for te in tb.findall(NEXML+\"tree\"):\n t = storage.Storage()\n t.attrib = storage.Storage(te.attrib)\n t.nodes = {}\n for n in te.findall(NEXML+\"node\"):\n node = Node()\n if n.attrib.get(\"otu\"):\n node.isleaf = True\n node.otu = otus[n.attrib[\"otu\"]]\n node.label = node.otu.label\n t.nodes[n.attrib[\"id\"]] = node\n for edge in te.findall(NEXML+\"edge\"):\n d = edge.attrib\n n = t.nodes[d[\"target\"]]\n p = t.nodes[d[\"source\"]]\n length = d.get(\"length\")\n if length:\n n.length = float(length)\n p.add_child(n)\n r = [ n for n in t.nodes.values() if not n.parent ]\n assert len(r)==1\n r = r[0]\n r.isroot = True\n for i, n in enumerate(r): n.id = i+1\n t.root = r\n v.append(t)\n return v\n\ndef parse_otus(e):\n \"\"\"\n Get OTUs from an etree object\n\n Args:\n e: A nexml document parsed by etree\n Returns:\n dict: A dict mapping keys to OTUs contained in ivy Storage objects\n \"\"\"\n v = {}\n for otus in e.findall(NEXML+\"otus\"):\n for x in otus.findall(NEXML+\"otu\"):\n otu = storage.Storage()\n otu.id = x.attrib[\"id\"]\n otu.label = x.attrib[\"label\"]\n for meta in x.iterchildren():\n d = meta.attrib\n p = d.get(\"property\")\n if p and p == \"tb:identifier.taxon\":\n otu.tb_taxid = d[\"content\"]\n elif p and p == \"tb:identifier.taxonVariant\":\n otu.tb_taxid_variant = d[\"content\"]\n h = d.get(\"href\")\n if h and h.startswith(NAMEBANK):\n otu.namebank_id = int(h.replace(NAMEBANK, \"\"))\n elif h and h.startswith(UNIPROT):\n otu.ncbi_taxid = int(h.replace(UNIPROT, \"\"))\n v[otu.id] = otu\n return v\n\ndef parse_nexml(doc):\n \"\"\"\n Parse an etree ElementTree\n\n Args:\n doc: An etree ElementTree or a file that can be parsed into\n an etree ElementTree with etree.parse\n Returns:\n An ivy Storage object containing all the information from the\n nexml file: Characters, metadata, OTUs, and trees.\n \"\"\"\n if not isinstance(doc, (etree._ElementTree, etree._Element)):\n doc = etree.parse(doc)\n meta = {}\n for child in doc.findall(NEXML+\"meta\"):\n if \"content\" in child.attrib:\n d = child.attrib\n key = d[\"property\"]\n val = META_DATATYPE[d[\"datatype\"]](d[\"content\"])\n if (key in meta) and val:\n if isinstance(meta[key], list):\n meta[key].append(val)\n else:\n meta[key] = [meta[key], val]\n else:\n meta[key] = val\n\n otus = parse_otus(doc)\n\n return Storage(meta = meta,\n otus = otus,\n chars = parse_chars(doc, otus),\n trees = parse_trees(doc, otus))\n\ndef parse_states(e):\n \"\"\"e is a characters element\"\"\"\n f = e.findall(NEXML+\"format\")[0]\n sts = f.findall(NEXML+\"states\")[0]\n states2symb = {}\n symb2states = {}\n id2symb = {}\n for child in sts.iterchildren():\n t = child.tag\n if t == NEXML+\"state\":\n k = child.attrib[\"id\"]\n v = child.attrib[\"symbol\"]\n id2symb[k] = v\n states2symb[v] = v\n symb2states[v] = v\n elif t == NEXML+\"uncertain_state_set\":\n k = child.attrib[\"id\"]\n v = child.attrib[\"symbol\"]\n id2symb[k] = v\n memberstates = []\n for memb in child.findall(NEXML+\"member\"):\n sid = memb.attrib[\"state\"]\n symb = id2symb[sid]\n for x in symb2states[symb]: memberstates.append(x)\n memberstates = frozenset(memberstates)\n symb2states[v] = memberstates\n states2symb[memberstates] = v\n return Storage(states2symb=states2symb,\n symb2states=symb2states,\n id2symb=id2symb)\n\ndef parse_charsets(study_id):\n from cStringIO import StringIO\n nx = StringIO(fetch_study(study_id, 'nexus'))\n d = {}\n for line in nx.readlines():\n if line.strip().startswith(\"CHARSET \"):\n v = line.strip().split()\n label = v[1]\n first, last = map(int, line.split()[-1][:-1].split(\"-\"))\n d[label] = (first-1, last-1)\n return d\n\nif __name__ == \"__main__\":\n import sys\n from pprint import pprint\n e = fetch_study('S11152', 'nexus')\n #print e\n #e.write(sys.stdout, pretty_print=True)\n\n ## e = etree.parse('/tmp/tmp.xml')\n ## x = parse_nexml(e)\n ## pprint(x)\n", "ivy/vis/alignment.py": "\"\"\"\ninteractive viewers for trees, etc. using matplotlib\n\"\"\"\nfrom collections import defaultdict\nfrom .. import align, sequtil\nimport matplotlib, numpy\nimport matplotlib.pyplot as pyplot\nfrom matplotlib.figure import SubplotParams\nfrom matplotlib.axes import Axes, subplot_class_factory\nfrom matplotlib.patches import Rectangle\nfrom matplotlib.collections import PatchCollection\nfrom matplotlib.widgets import RectangleSelector\nfrom matplotlib import colors as mpl_colors\nfrom matplotlib.ticker import MaxNLocator, FuncFormatter, NullLocator\nfrom mpl_toolkits.axes_grid1.inset_locator import inset_axes\nfrom Bio.Align import MultipleSeqAlignment\n\nmatplotlib.rcParams['path.simplify'] = False\n\nclass UpdatingRect(Rectangle):\n def __call__(self, p):\n self.set_bounds(*p.viewLim.bounds)\n p.figure.canvas.draw_idle()\n\nclass AlignmentFigure:\n def __init__(self, aln, name=None, div=0.25, overview=True):\n if isinstance(aln, MultipleSeqAlignment):\n self.aln = aln\n else:\n self.aln = align.read(aln)\n self.name = name\n self.div_value = div\n pars = SubplotParams(\n left=0.2, right=1, bottom=0.05, top=1, wspace=0.01\n )\n fig = pyplot.figure(subplotpars=pars, facecolor=\"white\")\n self.figure = fig\n self.initialize_subplots(overview)\n self.show()\n self.connect_events()\n \n def initialize_subplots(self, overview=False):\n ## p = AlignmentPlot(self.figure, 212, aln=self.aln)\n p = AlignmentPlot(self.figure, 111, aln=self.aln, app=self)\n self.detail = self.figure.add_subplot(p)\n self.detail.plot_aln()\n if overview:\n self.overview = inset_axes(\n self.detail, width=\"30%\", height=\"20%\", loc=1\n )\n self.overview.xaxis.set_major_locator(NullLocator())\n self.overview.yaxis.set_major_locator(NullLocator())\n self.overview.imshow(\n self.detail.array, interpolation='nearest', aspect='auto',\n origin='lower'\n )\n rect = UpdatingRect(\n [0,0], 0, 0, facecolor='black', edgecolor='cyan', alpha=0.5\n )\n self.overview.zoomrect = rect\n rect.target = self.detail\n self.detail.callbacks.connect('xlim_changed', rect)\n self.detail.callbacks.connect('ylim_changed', rect)\n self.overview.add_patch(rect)\n rect(self.overview)\n\n else:\n self.overview = None\n \n def show(self):\n self.figure.show()\n\n def connect_events(self):\n mpl_connect = self.figure.canvas.mpl_connect\n mpl_connect(\"button_press_event\", self.onclick)\n mpl_connect(\"button_release_event\", self.onbuttonrelease)\n mpl_connect(\"scroll_event\", self.onscroll)\n mpl_connect(\"pick_event\", self.onpick)\n mpl_connect(\"motion_notify_event\", self.ondrag)\n mpl_connect(\"key_press_event\", self.onkeypress)\n mpl_connect(\"axes_enter_event\", self.axes_enter)\n mpl_connect(\"axes_leave_event\", self.axes_leave)\n\n @staticmethod\n def axes_enter(e):\n ax = e.inaxes\n ax._active = True\n\n @staticmethod\n def axes_leave(e):\n ax = e.inaxes\n ax._active = False\n\n @staticmethod\n def onselect(estart, estop):\n b = estart.button\n ## print b, estart.key\n\n @staticmethod\n def onkeypress(e):\n ax = e.inaxes\n k = e.key\n if ax and k:\n if k == 't':\n ax.home()\n elif k == \"down\":\n ax.scroll(0, -0.1)\n elif k == \"up\":\n ax.scroll(0, 0.1)\n elif k == \"left\":\n ax.scroll(-0.1, 0)\n elif k == \"right\":\n ax.scroll(0.1, 0)\n elif k in '=+':\n ax.zoom(0.1,0.1)\n elif k == '-':\n ax.zoom(-0.1,-0.1)\n ax.figure.canvas.draw_idle()\n\n @staticmethod\n def ondrag(e):\n ax = e.inaxes\n button = e.button\n if ax and button == 2:\n if not ax.pan_start:\n ax.pan_start = (e.xdata, e.ydata)\n return\n x, y = ax.pan_start\n xdelta = x - e.xdata\n ydelta = y - e.ydata\n x0, x1 = ax.get_xlim()\n xspan = x1-x0\n y0, y1 = ax.get_ylim()\n yspan = y1 - y0\n midx = (x1+x0)*0.5\n midy = (y1+y0)*0.5\n ax.set_xlim(midx+xdelta-xspan*0.5, midx+xdelta+xspan*0.5)\n ax.set_ylim(midy+ydelta-yspan*0.5, midy+ydelta+yspan*0.5)\n ax.figure.canvas.draw_idle()\n\n @staticmethod\n def onbuttonrelease(e):\n ax = e.inaxes\n button = e.button\n if button == 2:\n ## print \"pan end\"\n ax.pan_start = None\n ax.figure.canvas.draw_idle()\n\n @staticmethod\n def onpick(e):\n ax = e.mouseevent.inaxes\n if ax:\n ax.picked(e)\n ax.figure.canvas.draw_idle()\n\n @staticmethod\n def onscroll(e):\n ax = e.inaxes\n if ax:\n b = e.button\n ## print b\n k = e.key\n if k == None and b ==\"up\":\n ax.zoom(0.1,0.1)\n elif k == None and b ==\"down\":\n ax.zoom(-0.1,-0.1)\n elif k == \"shift\" and b == \"up\":\n ax.zoom_cxy(0.1, 0, e.xdata, e.ydata)\n elif k == \"shift\" and b == \"down\":\n ax.zoom_cxy(-0.1, 0, e.xdata, e.ydata)\n elif k == \"control\" and b == \"up\":\n ax.zoom_cxy(0, 0.1, e.xdata, e.ydata)\n elif k == \"control\" and b == \"down\":\n ax.zoom_cxy(0, -0.1, e.xdata, e.ydata)\n elif k == \"d\" and b == \"up\":\n ax.scroll(0, 0.1)\n elif (k == \"d\" and b == \"down\"):\n ax.scroll(0, -0.1)\n elif k == \"c\" and b == \"up\":\n ax.scroll(-0.1, 0)\n elif k == \"c\" and b == \"down\":\n ax.scroll(0.1, 0)\n ax.figure.canvas.draw_idle()\n\n @staticmethod\n def onclick(e):\n ax = e.inaxes\n if (ax and e.button==1 and hasattr(ax, \"zoomrect\") and ax.zoomrect):\n # overview clicked; reposition zoomrect\n r = ax.zoomrect\n x = e.xdata\n y = e.ydata\n arr = ax.transData.inverted().transform(r.get_extents())\n xoff = (arr[1][0]-arr[0][0])*0.5\n yoff = (arr[1][1]-arr[0][1])*0.5\n r.target.set_xlim(x-xoff,x+xoff)\n r.target.set_ylim(y-yoff,y+yoff)\n r(r.target)\n ax.figure.canvas.draw_idle()\n\n elif ax and e.button==2:\n ## print \"pan start\", (e.xdata, e.ydata)\n ax.pan_start = (e.xdata, e.ydata)\n ax.figure.canvas.draw_idle()\n\n elif ax and hasattr(ax, \"aln\") and ax.aln:\n x = int(e.xdata+0.5); y = int(e.ydata+0.5)\n aln = ax.aln\n if (0 <= x <= ax.nchar) and (0 <= y <= ax.ntax):\n seq = aln[y]; char = seq[x]\n if char not in '-?':\n v = sequtil.gapidx(seq)\n i = (v[1]==x).nonzero()[0][0]\n print(\"%s: row %s, site %s: '%s', seqpos %s\"\n % (seq.id, y, x, char, i))\n else:\n print(\"%s: row %s, site %s: '%s'\" % (seq.id, y, x, char))\n\n def zoom(self, factor=0.1):\n \"Zoom both axes by *factor* (relative display size).\"\n self.detail.zoom(factor, factor)\n self.figure.canvas.draw_idle()\n\n def __get_selection(self):\n return self.detail.extract_selected()\n selected = property(__get_selection)\n \nclass Alignment(Axes):\n \"\"\"\n matplotlib.axes.Axes subclass for rendering sequence alignments.\n \"\"\"\n def __init__(self, fig, rect, *args, **kwargs):\n self.aln = kwargs.pop(\"aln\")\n nrows = len(self.aln)\n ncols = self.aln.get_alignment_length()\n self.alnidx = numpy.arange(ncols)\n self.app = kwargs.pop(\"app\", None)\n self.showy = kwargs.pop('showy', True)\n Axes.__init__(self, fig, rect, *args, **kwargs)\n rgb = mpl_colors.colorConverter.to_rgb\n gray = rgb('gray')\n d = defaultdict(lambda:gray)\n d[\"A\"] = rgb(\"red\")\n d[\"a\"] = rgb(\"red\")\n d[\"C\"] = rgb(\"blue\")\n d[\"c\"] = rgb(\"blue\")\n d[\"G\"] = rgb(\"green\")\n d[\"g\"] = rgb(\"green\")\n d[\"T\"] = rgb(\"yellow\")\n d[\"t\"] = rgb(\"yellow\")\n self.cmap = d\n self.selector = RectangleSelector(\n self, self.select_rectangle, useblit=True\n )\n def f(e):\n if e.button != 1: return True\n else: return RectangleSelector.ignore(self.selector, e)\n self.selector.ignore = f\n self.selected_rectangle = Rectangle(\n [0,0],0,0, facecolor='white', edgecolor='cyan', alpha=0.3\n )\n self.add_patch(self.selected_rectangle)\n self.highlight_find_collection = None\n\n def plot_aln(self):\n cmap = self.cmap\n self.ntax = len(self.aln); self.nchar = self.aln.get_alignment_length()\n a = numpy.array([ [ cmap[base] for base in x.seq ]\n for x in self.aln ])\n self.array = a\n self.imshow(a, interpolation='nearest', aspect='auto', origin='lower')\n y = [ i+0.5 for i in xrange(self.ntax) ]\n labels = [ x.id for x in self.aln ]\n ## locator.bin_boundaries(1,ntax)\n ## locator.view_limits(1,ntax)\n if self.showy:\n locator = MaxNLocator(nbins=50, integer=True)\n self.yaxis.set_major_locator(locator)\n def fmt(x, pos=None):\n if x<0: return \"\"\n try: return labels[int(round(x))]\n except: pass\n return \"\"\n self.yaxis.set_major_formatter(FuncFormatter(fmt))\n else:\n self.yaxis.set_major_locator(NullLocator())\n \n return self\n\n def select_rectangle(self, e0, e1):\n x0, x1 = map(int, sorted((e0.xdata+0.5, e1.xdata+0.5)))\n y0, y1 = map(int, sorted((e0.ydata+0.5, e1.ydata+0.5)))\n self.selected_chars = (x0, x1)\n self.selected_taxa = (y0, y1)\n self.selected_rectangle.set_bounds(x0-0.5,y0-0.5,x1-x0+1,y1-y0+1)\n self.app.figure.canvas.draw_idle()\n\n def highlight_find(self, substr):\n if not substr:\n if self.highlight_find_collection:\n self.highlight_find_collection.remove()\n self.highlight_find_collection = None\n return\n \n N = len(substr)\n v = []\n for y, x in align.find(self.aln, substr):\n r = Rectangle(\n [x-0.5,y-0.5], N, 1,\n facecolor='cyan', edgecolor='cyan', alpha=0.7\n )\n v.append(r)\n if self.highlight_find_collection:\n self.highlight_find_collection.remove()\n c = PatchCollection(v, True)\n self.highlight_find_collection = self.add_collection(c)\n self.app.figure.canvas.draw_idle()\n\n def extract_selected(self):\n r0, r1 = self.selected_taxa\n c0, c1 = self.selected_chars\n return self.aln[r0:r1+1,c0:c1+1]\n\n def zoom_cxy(self, x=0.1, y=0.1, cx=None, cy=None):\n \"\"\"\n Zoom the x and y axes in by the specified proportion of the\n current view, with a fixed data point (cx, cy)\n \"\"\"\n transform = self.transData.inverted().transform\n xlim = self.get_xlim(); xmid = sum(xlim)*0.5\n ylim = self.get_ylim(); ymid = sum(ylim)*0.5\n bb = self.get_window_extent()\n bbx = bb.expanded(1.0-x,1.0-y)\n points = transform(bbx.get_points())\n x0, x1 = points[:,0]; y0, y1 = points[:,1]\n deltax = xmid-x0; deltay = ymid-y0\n cx = cx or xmid; cy = cy or ymid\n xoff = (cx-xmid)*x\n self.set_xlim(xmid-deltax+xoff, xmid+deltax+xoff)\n yoff = (cy-ymid)*y\n self.set_ylim(ymid-deltay+yoff, ymid+deltay+yoff)\n\n def zoom(self, x=0.1, y=0.1, cx=None, cy=None):\n \"\"\"\n Zoom the x and y axes in by the specified proportion of the\n current view.\n \"\"\"\n # get the function to convert display coordinates to data\n # coordinates\n transform = self.transData.inverted().transform\n xlim = self.get_xlim()\n ylim = self.get_ylim()\n bb = self.get_window_extent()\n bbx = bb.expanded(1.0-x,1.0-y)\n points = transform(bbx.get_points())\n x0, x1 = points[:,0]; y0, y1 = points[:,1]\n deltax = x0 - xlim[0]; deltay = y0 - ylim[0]\n self.set_xlim(xlim[0]+deltax, xlim[1]-deltax)\n self.set_ylim(ylim[0]+deltay, ylim[1]-deltay)\n\n def center_y(self, y):\n ymin, ymax = self.get_ylim()\n yoff = (ymax - ymin) * 0.5\n self.set_ylim(y-yoff, y+yoff)\n\n def center_x(self, x, offset=0.3):\n xmin, xmax = self.get_xlim()\n xspan = xmax - xmin\n xoff = xspan*0.5 + xspan*offset\n self.set_xlim(x-xoff, x+xoff)\n\n def scroll(self, x, y):\n x0, x1 = self.get_xlim()\n y0, y1 = self.get_ylim()\n xd = (x1-x0)*x\n yd = (y1-y0)*y\n self.set_xlim(x0+xd, x1+xd)\n self.set_ylim(y0+yd, y1+yd)\n\n def home(self):\n self.set_xlim(0, self.nchar)\n self.set_ylim(self.ntax, 0)\n\nAlignmentPlot = subplot_class_factory(Alignment)\n\n", "ivy/vis/hardcopy.py": "import os, matplotlib\nfrom matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas\nfrom matplotlib.figure import Figure\nfrom . import tree\nimport tempfile\n\n## class TreeFigure:\n## def __init__(self):\n## pass\n\nmatplotlib.rcParams[\"xtick.direction\"] = \"out\"\n\nclass TreeFigure:\n def __init__(self, root, relwidth=0.5, leafpad=1.5, name=None,\n support=70.0, scaled=True, mark_named=True,\n leaf_fontsize=10, branch_fontsize=10,\n branch_width=1, branch_color=\"black\",\n highlight_support=True,\n branchlabels=True, leaflabels=True, decorators=[],\n xoff=0, yoff=0,\n xlim=None, ylim=None,\n height=None, width=None):\n self.root = root\n self.relwidth = relwidth\n self.leafpad = leafpad\n self.name = name\n self.support = support\n self.scaled = scaled\n self.mark_named = mark_named\n self.leaf_fontsize = leaf_fontsize\n self.branch_fontsize = branch_fontsize\n self.branch_width = branch_width\n self.branch_color = branch_color\n self.highlight_support = highlight_support\n self.branchlabels = branchlabels\n self.leaflabels = leaflabels\n self.decorators = decorators\n self.xoff = xoff\n self.yoff = yoff\n\n nleaves = len(root.leaves())\n self.dpi = 72.0\n h = height or (nleaves*self.leaf_fontsize*self.leafpad)/self.dpi\n self.height = h\n self.width = width or self.height*self.relwidth\n ## p = min(self.width, self.height)*0.1\n ## self.height += p\n ## self.width += p\n self.figure = Figure(figsize=(self.width, self.height), dpi=self.dpi)\n self.canvas = FigureCanvas(self.figure)\n self.axes = self.figure.add_axes(\n tree.TreePlot(self.figure, 1,1,1,\n support=self.support,\n scaled=self.scaled,\n mark_named=self.mark_named,\n leaf_fontsize=self.leaf_fontsize,\n branch_fontsize=self.branch_fontsize,\n branch_width=self.branch_width,\n branch_color=self.branch_color,\n highlight_support=self.highlight_support,\n branchlabels=self.branchlabels,\n leaflabels=self.leaflabels,\n interactive=False,\n decorators=self.decorators,\n xoff=self.xoff, yoff=self.yoff,\n name=self.name).plot_tree(self.root)\n )\n self.axes.spines[\"top\"].set_visible(False)\n self.axes.spines[\"left\"].set_visible(False)\n self.axes.spines[\"right\"].set_visible(False)\n self.axes.spines[\"bottom\"].set_smart_bounds(True)\n self.axes.xaxis.set_ticks_position(\"bottom\")\n\n for v in self.axes.node2label.values():\n v.set_visible(True)\n\n ## for k, v in self.decorators:\n ## func, args, kwargs = v\n ## func(self.axes, *args, **kwargs)\n\n self.canvas.draw()\n ## self.axes.home()\n ## adjust_limits(self.axes)\n self.axes.set_position([0.05,0.05,0.95,0.95])\n\n @property\n def detail(self):\n return self.axes\n \n def savefig(self, fname):\n root, ext = os.path.splitext(fname)\n buf = tempfile.TemporaryFile()\n for i in range(3):\n self.figure.savefig(buf, format=ext[1:].lower())\n self.home()\n buf.seek(0)\n buf.close()\n self.figure.savefig(fname)\n\n def set_relative_width(self, relwidth):\n w, h = self.figure.get_size_inches()\n self.figure.set_figwidth(h*relwidth)\n\n def autoheight(self):\n \"adjust figure height to show all leaf labels\"\n nleaves = len(self.root.leaves())\n h = (nleaves*self.leaf_fontsize*self.leafpad)/self.dpi\n self.height = h\n self.figure.set_size_inches(self.width, self.height)\n self.axes.set_ylim(-2, nleaves+2)\n\n def home(self):\n self.axes.home()\n", "ivy/vis/symbols.py": "\"\"\"\nConvenience functions for drawing shapes on TreePlots.\n\"\"\"\ntry:\n import Image\nexcept ImportError:\n from PIL import Image\nfrom numpy import pi\nfrom matplotlib.collections import RegularPolyCollection, CircleCollection\nfrom matplotlib.transforms import offset_copy\nfrom matplotlib.patches import Rectangle, Wedge, Circle, PathPatch\nfrom matplotlib.offsetbox import DrawingArea\nfrom matplotlib.axes import Axes\nfrom matplotlib.path import Path\n\ntry:\n from matplotlib.offsetbox import OffsetImage, AnnotationBbox\nexcept ImportError:\n pass\nfrom ..tree import Node\nfrom . import colors as _colors\n\ndef _xy(plot, p):\n if isinstance(p, Node):\n c = plot.n2c[p]\n p = (c.x, c.y)\n elif isinstance(p, (list, tuple)):\n p = [ _xy(plot, x) for x in p ]\n else:\n pass\n return p\n\n\n\ndef image(plot, p, imgfile,\n maxdim=100, border=0,\n xoff=4, yoff=4,\n halign=0.0, valign=0.5,\n xycoords='data',\n boxcoords=('offset points')):\n \"\"\"\n Add images to plot\n\n Args:\n plot (Tree): A Tree plot instance\n p (Node): A node object\n imgfile (str): A path to an image\n maxdim (float): Maximum dimension of image. Optional,\n defaults to 100.\n border: RR: What does border do? -CZ\n xoff, yoff (float): X and Y offset. Optional, defaults to 4\n halign, valign (float): Horizontal and vertical alignment within\n box. Optional, defaults to 0.0 and 0.5, respectively.\n\n \"\"\"\n if xycoords == \"label\":\n xycoords = plot.node2label[p]\n x, y = (1, 0.5)\n else:\n x, y = _xy(plot, p)\n img = Image.open(imgfile)\n if max(img.size) > maxdim:\n img.thumbnail((maxdim, maxdim))\n imgbox = OffsetImage(img)\n abox = AnnotationBbox(imgbox, (x, y),\n xybox=(xoff, yoff),\n xycoords=xycoords,\n box_alignment=(halign,valign),\n pad=0.0,\n boxcoords=boxcoords)\n plot.add_artist(abox)\n plot.figure.canvas.draw_idle()\n\ndef images(plot, p, imgfiles,\n maxdim=100, border=0,\n xoff=4, yoff=4,\n halign=0.0, valign=0.5,\n xycoords='data', boxcoords=('offset points')):\n \"\"\"\n Add many images to plot at once\n\n Args:\n Plot (Tree): A Tree plot instance\n p (list): A list of node objects\n imgfile (list): A list of strs containing paths to image files.\n Must be the same length as p.\n maxdim (float): Maximum dimension of image. Optional,\n defaults to 100.\n border: RR: What does border do? -CZ\n xoff, yoff (float): X and Y offset. Optional, defaults to 4\n halign, valign (float): Horizontal and vertical alignment within\n box. Optional, defaults to 0.0 and 0.5, respectively.\n\n \"\"\"\n for x, f in zip(p, imgfiles):\n image(plot, x, f, maxdim, border, xoff, yoff, halign, valign,\n xycoords, boxcoords)\n\ndef pie(plot, p, values, colors=None, size=16, norm=True,\n xoff=0, yoff=0,\n halign=0.5, valign=0.5,\n xycoords='data', boxcoords=('offset points')):\n \"\"\"\n Draw a pie chart\n\n Args:\n plot (Tree): A Tree plot instance\n p (Node): A Node object\n values (list): A list of floats.\n colors (list): A list of strings to pull colors from. Optional.\n size (float): Diameter of the pie chart\n norm (bool): Whether or not to normalize the values so they\n add up to 360\n xoff, yoff (float): X and Y offset. Optional, defaults to 0\n halign, valign (float): Horizontal and vertical alignment within\n box. Optional, defaults to 0.5\n\n \"\"\"\n x, y = _xy(plot, p)\n da = DrawingArea(size, size); r = size*0.5; center = (r,r)\n x0 = 0\n S = 360.0\n if norm: S = 360.0/sum(values)\n if not colors:\n c = _colors.tango()\n colors = [ c.next() for v in values ]\n for i, v in enumerate(values):\n theta = v*S\n if v: da.add_artist(Wedge(center, r, x0, x0+theta,\n fc=colors[i], ec='none'))\n x0 += theta\n box = AnnotationBbox(da, (x,y), pad=0, frameon=False,\n xybox=(xoff, yoff),\n xycoords=xycoords,\n box_alignment=(halign,valign),\n boxcoords=boxcoords)\n plot.add_artist(box)\n plot.figure.canvas.draw_idle()\n return box\n\ndef hbar(plot, p, values, colors=None, height=16,\n xoff=0, yoff=0,\n halign=1, valign=0.5,\n xycoords='data', boxcoords=('offset points')):\n x, y = _xy(plot, p)\n h = height; w = sum(values) * height#; yoff=h*0.5\n da = DrawingArea(w, h)\n x0 = -sum(values)\n if not colors:\n c = _colors.tango()\n colors = [ c.next() for v in values ]\n for i, v in enumerate(values):\n if v: da.add_artist(Rectangle((x0,0), v*h, h, fc=colors[i], ec='none'))\n x0 += v*h\n box = AnnotationBbox(da, (x,y), pad=0, frameon=False,\n xybox=(xoff, yoff),\n xycoords=xycoords,\n box_alignment=(halign,valign),\n boxcoords=boxcoords)\n plot.add_artist(box)\n plot.figure.canvas.draw_idle()\n\ndef hbars(plot, p, values, colors=None, height=16,\n xoff=0, yoff=0,\n halign=1, valign=0.5,\n xycoords='data', boxcoords=('offset points')):\n for x, v in zip(p, values):\n hbar(plot, x, v, colors, height, xoff, yoff, halign, valign,\n xycoords, boxcoords)\n\ndef squares(plot, p, colors='r', size=15, xoff=0, yoff=0, alpha=1.0,\n zorder=1000):\n \"\"\"\n Draw a square at given node\n\n Args:\n plot (Tree): A Tree plot instance\n p: A node or list of nodes\n colors: Str or list of strs. Colors of squares to be drawn.\n Optional, defaults to 'r' (red)\n size (float): Size of the squares. Optional, defaults to 15\n xoff, yoff (float): Offset for x and y dimensions. Optional,\n defaults to 0.\n alpha (float): between 0 and 1. Alpha transparency of squares.\n Optional, defaults to 1 (fully opaque)\n zorder (int): The drawing order. Higher numbers appear on top\n of lower numbers. Optional, defaults to 1000.\n\n \"\"\"\n points = _xy(plot, p)\n trans = offset_copy(\n plot.transData, fig=plot.figure, x=xoff, y=yoff, units='points')\n\n col = RegularPolyCollection(\n numsides=4, rotation=pi*0.25, sizes=(size*size,),\n offsets=points, facecolors=colors, transOffset=trans,\n edgecolors='none', alpha=alpha, zorder=zorder\n )\n\n plot.add_collection(col)\n plot.figure.canvas.draw_idle()\n\ndef tipsquares(plot, p, colors='r', size=15, pad=2, edgepad=10):\n \"\"\"\n RR: Bug with this function. If you attempt to call it with a list as an\n argument for p, it will not only not work (expected) but it will also\n make it so that you can't interact with the tree figure (gives errors when\n you try to add symbols, select nodes, etc.) -CZ\n\n Add square after tip label, anchored to the side of the plot\n\n Args:\n plot (Tree): A Tree plot instance.\n p (Node): A Node object (Should be a leaf node).\n colors (str): olor of drawn square. Optional, defaults to 'r' (red)\n size (float): Size of square. Optional, defaults to 15\n pad: RR: I am unsure what this does. Does not seem to have visible\n effect when I change it. -CZ\n edgepad (float): Padding from square to edge of plot. Optional,\n defaults to 10.\n\n \"\"\"\n x, y = _xy(plot, p) # p is a single node or point in data coordinates\n n = len(colors)\n da = DrawingArea(size*n+pad*(n-1), size, 0, 0)\n sx = 0\n for c in colors:\n sq = Rectangle((sx,0), size, size, color=c)\n da.add_artist(sq)\n sx += size+pad\n box = AnnotationBbox(da, (x, y), xybox=(-edgepad,y),\n frameon=False,\n pad=0.0,\n xycoords='data',\n box_alignment=(1, 0.5),\n boxcoords=('axes points','data'))\n plot.add_artist(box)\n plot.figure.canvas.draw_idle()\n\n\ndef circles(plot, p, colors='g', size=15, xoff=0, yoff=0):\n \"\"\"\n Draw circles on plot\n\n Args:\n plot (Tree): A Tree plot instance\n p: A node object or list of Node objects\n colors: Str or list of strs. Colors of the circles. Optional,\n defaults to 'g' (green)\n size (float): Size of the circles. Optional, defaults to 15\n xoff, yoff (float): X and Y offset. Optional, defaults to 0.\n\n \"\"\"\n points = _xy(plot, p)\n trans = offset_copy(\n plot.transData, fig=plot.figure, x=xoff, y=yoff, units='points'\n )\n\n col = CircleCollection(\n sizes=(pi*size*size*0.25,),\n offsets=points, facecolors=colors, transOffset=trans,\n edgecolors='none'\n )\n\n plot.add_collection(col)\n plot.figure.canvas.draw_idle()\n return col\n\ndef legend(plot, colors, labels, shape='rectangle', loc='upper left', **kwargs):\n \"\"\"\n RR: the MPL legend function has changed since this function has been\n written. This function currently does not work. -CZ\n \"\"\"\n if shape == 'circle':\n shapes = [ Circle((0.5,0.5), radius=1, fc=c) for c in colors ]\n #shapes = [ CircleCollection([10],facecolors=[c]) for c in colors ]\n else:\n shapes = [ Rectangle((0,0),1,1,fc=c,ec='none') for c in colors ]\n\n return Axes.legend(plot, shapes, labels, loc=loc, **kwargs)\n\ndef leafspace_triangles(plot, color='black', rca=0.5):\n \"\"\"\n RR: Using this function on the primates tree (straight from the newick file)\n gives error: 'Node' object has no attribute 'leafspace'. How do you give\n nodes the leafspace attribute? -CZ\n rca = relative crown age\n \"\"\"\n leaves = plot.root.leaves()\n leafspace = [ float(x.leafspace) for x in leaves ]\n #leafspace = array(raw_leafspace)/(sum(raw_leafspace)/float(len(leaves)))\n pv = []\n for i, n in enumerate(leaves):\n if leafspace[i] > 0:\n p = plot.n2c[n]\n pp = plot.n2c[n.parent]\n spc = leafspace[i]\n yoff = spc/2.0\n x0 = pp.x + (p.x - pp.x)*rca\n verts = [(x0, p.y),\n (p.x, p.y-yoff),\n (p.x, p.y+yoff),\n (x0, p.y)]\n codes = [Path.MOVETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY]\n path = Path(verts, codes)\n patch = PathPatch(path, fc=color, lw=0)\n pv.append(plot.add_patch(patch))\n return pv\n\ndef text(plot, x, y, s, color='black', xoff=0, yoff=0, valign='center',\n halign='left', fontsize=10):\n \"\"\"\n Add text to the plot.\n\n Args:\n plot (Tree): A Tree plot instance\n x, y (float): x and y coordinates to place the text\n s (str): The text to write\n color (str): The color of the text. Optional, defaults to \"black\"\n xoff, yoff (float): x and y offset\n valign (str): Vertical alignment. Can be: 'center', 'top',\n 'bottom', or 'baseline'. Defaults to 'center'.\n halign (str): Horizontal alignment. Can be: 'center', 'right',\n or 'left'. Defaults to 'left'\n fontsize (float): Font size. Optional, defaults to 10\n\n \"\"\"\n txt = plot.annotate(\n s, xy=(x, y),\n xytext=(xoff, yoff),\n textcoords=\"offset points\",\n verticalalignment=valign,\n horizontalalignment=halign,\n fontsize=fontsize,\n clip_on=True,\n picker=True\n )\n txt.set_visible(True)\n return txt\n", "ivy/vis/tree.py": "\"\"\"\ninteractive viewers for trees, etc. using matplotlib\n\"\"\"\nimport sys, math, types, os, operator\nfrom itertools import chain\nfrom .. import tree\nfrom ..layout import cartesian\nfrom ..storage import Storage\nfrom .. import pyperclip as clipboard\n# from ..nodecache import NodeCache\nimport matplotlib.pyplot as pyplot\nfrom matplotlib.axes import Axes, subplot_class_factory\nfrom matplotlib.figure import SubplotParams\nfrom matplotlib.patches import PathPatch, Rectangle, Arc\nfrom matplotlib.path import Path\nfrom matplotlib.widgets import RectangleSelector\nfrom matplotlib import cm as mpl_colormap\nfrom matplotlib import colors as mpl_colors\nfrom matplotlib.collections import LineCollection\ntry:\n from matplotlib.offsetbox import OffsetImage, AnnotationBbox\nexcept ImportError:\n pass\nfrom matplotlib.ticker import NullLocator\nfrom mpl_toolkits.axes_grid.anchored_artists import AnchoredText\nfrom mpl_toolkits.axes_grid1.inset_locator import inset_axes\nfrom . import symbols, colors\nfrom . import hardcopy as HC\ntry:\n import Image\nexcept ImportError:\n from PIL import Image\n\n# matplotlib.rcParams['path.simplify'] = False\n\n_tango = colors.tango()\nclass TreeFigure(object):\n \"\"\"\n Window for showing a single tree, optionally with split overview\n and detail panes.\n\n The navigation toolbar at the bottom is provided by matplotlib\n (http://matplotlib.sf.net/users/navigation_toolbar.html). Its\n pan/zoom button and zoom-rectangle button provide different modes\n of mouse interaction with the figure. When neither of these\n buttons are checked, the default mouse bindings are as follows:\n\n * button 1 drag: select nodes - retrieve by calling fig.selected_nodes\n * button 3 drag: pan view\n * scroll up/down: zoom in/out\n * scroll up/down with Control key: zoom y-axis\n * scroll up/down with Shift key: zoom x-axis\n * scroll up/down with 'd' key: pan view up/down\n * scroll up/down with 'e' key: pan view left/right\n * click on overview will center the detail pane on that region\n\n Default keybindings:\n\n * t: zoom out to full extent\n * +/-: zoom in/out\n\n Useful attributes and methods (assume an instance named *fig*):\n\n * fig.root - the root node (see [Node methods])\n * fig.highlight(s) - highlight and trace nodes with substring *s*\n * fig.zoom_clade(anc) - zoom to view node *anc* and all its descendants\n * fig.toggle_overview() - toggle visibility of the overview pane\n * fig.toggle_branchlabels() - ditto for branch labels\n * fig.toggle_leaflabels() - ditto for leaf labels\n * fig.decorate(func) - decorate the tree with a function (see\n :ref:`decorating TreeFigures `)\n \"\"\"\n def __init__(self, data, name=None, scaled=True, div=0.25,\n branchlabels=True, leaflabels=True, mark_named=True,\n highlight_support=True, xoff=0, yoff=0,\n overview=True, radial=False):\n self.overview = None\n self.overview_width = div\n self.dataplot = None\n self.dataplot_width = 0.25\n self.name = name\n self.scaled = scaled\n self.branchlabels = branchlabels\n self.leaflabels = leaflabels\n self.mark_named = mark_named\n self.xoff = xoff\n self.yoff = yoff\n self.radial = radial\n if radial:\n self.leaflabels = False\n self.highlighted = set()\n self.highlight_support = highlight_support\n if isinstance(data, tree.Node):\n root = data\n else:\n root = tree.read(data)\n self.root = root\n if not self.root:\n raise IOError(\"cannot coerce data into tree.Node\")\n self.name = self.name or root.treename\n pars = SubplotParams(\n left=0, right=1, bottom=0.05, top=1, wspace=0.01\n )\n fig = pyplot.figure(subplotpars=pars, facecolor=\"white\")\n connect_events(fig.canvas)\n self.figure = fig\n self.initialize_subplots(overview)\n self.home()\n\n def initialize_subplots(self, overview=True):\n if not self.radial:\n tp = TreePlot(self.figure, 1, 2, 2, app=self, name=self.name,\n scaled=self.scaled, branchlabels=self.branchlabels,\n highlight_support=self.highlight_support,\n leaflabels=self.leaflabels,\n mark_named=self.mark_named)\n detail = self.figure.add_subplot(tp)\n detail.set_root(self.root)\n detail.plot_tree()\n self.detail = detail\n tp = OverviewTreePlot(\n self.figure, 121, app=self, scaled=self.scaled,\n branchlabels=False, leaflabels=False,\n mark_named=self.mark_named,\n highlight_support=self.highlight_support,\n target=self.detail\n )\n ov = self.figure.add_subplot(tp)\n ov.set_root(self.root)\n ov.plot_tree()\n self.overview = ov\n if not overview:\n self.toggle_overview(False)\n self.set_positions()\n\n if self.detail.nleaves < 50:\n self.toggle_overview(False)\n else:\n tp = RadialTreePlot(\n self.figure, 111, app=self, name=self.name,\n scaled=self.scaled, branchlabels=self.branchlabels,\n highlight_support=self.highlight_support,\n leaflabels=self.leaflabels, mark_named=self.mark_named\n )\n ax2 = self.figure.add_subplot(tp)\n ax2.set_root(self.root)\n ax2.plot_tree()\n self.detail = ax2\n\n def __get_selected_nodes(self):\n return list(self.detail.selected_nodes)\n\n def __set_selected_nodes(self, nodes):\n self.detail.select_nodes(nodes)\n\n def __del_selected_nodes(self):\n self.detail.select_nodes(None)\n\n selected = property(__get_selected_nodes,\n __set_selected_nodes,\n __del_selected_nodes)\n\n ## def selected_nodes(self):\n ## return self.detail.selected_nodes\n\n @property\n def axes(self):\n return self.detail\n\n def add(self, data, name=None, support=70,\n branchlabels=False, leaflabels=True, mark_named=True):\n \"\"\"\n Add a new tree in a new window\n\n Args:\n data: A node object or tree file.\n name (str): Name of the plot. Defaults to None\n branchlabels (bool): Whether or not to draw branch labels.\n Defaults to False\n leaflabels (bool): Whether or not to draw leaf labels.\n Defaults to True\n \"\"\"\n newfig = MultiTreeFigure()\n ## newfig.add(self.root, name=self.name, support=self.support,\n ## branchlabels=self.branchlabels)\n newfig.add(data, name=name, support=support,\n branchlabels=branchlabels,\n leaflabels=leaflabels,\n mark_named=mark_named)\n return newfig\n\n def toggle_leaflabels(self):\n \"\"\"\n Toggle leaf labels and redraw tree\n \"\"\"\n self.leaflabels = not self.leaflabels\n self.detail.leaflabels = self.leaflabels\n self.redraw()\n\n def toggle_branchlabels(self):\n \"\"\"\n Toggle branch labels and redraw tree\n \"\"\"\n self.branchlabels = not self.branchlabels\n self.detail.branchlabels = self.branchlabels\n self.redraw()\n\n def toggle_overview(self, val=None):\n \"\"\"\n Toggle overview\n \"\"\"\n if val is None:\n if self.overview.get_visible():\n self.overview.set_visible(False)\n self.overview_width = 0.001\n else:\n self.overview.set_visible(True)\n self.overview_width = 0.25\n elif val:\n self.overview.set_visible(True)\n self.overview_width = val\n else:\n self.overview.set_visible(False)\n self.overview_width = 0.001\n self.set_positions()\n\n def set_scaled(self, scaled):\n \"\"\"\n RR: Using this method gives the error:\n redraw takes exactly 1 argument(2 given)-CZ\n Define whether or not the tree is scaled and redraw tree\n\n Args:\n scaled (bool): Whether or not the tree is scaled.\n \"\"\"\n for p in self.overview, self.detail:\n p.redraw(p.set_scaled(scaled))\n self.set_positions()\n\n def on_nodes_selected(self, treeplot):\n pass\n\n def picked(self, e):\n try:\n if e.mouseevent.button==1:\n s = e.artist.get_text()\n clipboard.copy(s)\n print(s)\n sys.stdout.flush()\n except:\n pass\n\n def ladderize(self, rev=False):\n \"\"\"\n Ladderize and redraw the tree\n \"\"\"\n self.root.ladderize(rev)\n self.redraw()\n\n def show(self):\n \"\"\"\n Plot the figure in a new window\n \"\"\"\n self.figure.show()\n\n def set_positions(self):\n ov = self.overview\n p = self.detail\n dp = self.dataplot\n height = 1.0-p.xoffset()\n if ov:\n box = [0, p.xoffset(), self.overview_width, height]\n ov.set_position(box)\n w = 1.0\n if ov:\n w -= self.overview_width\n if dp:\n w -= self.dataplot_width\n p.set_position([self.overview_width, p.xoffset(), w, height])\n if dp:\n box = [1.0-self.dataplot_width, p.xoffset(),\n self.dataplot_width, height]\n dp.set_position(box)\n self.figure.canvas.draw_idle()\n\n ## def div(self, v=0.3):\n ## assert 0 <= v < 1\n ## self.overview_width = v\n ## self.set_positions()\n ## self.figure.canvas.draw_idle()\n\n def add_dataplot(self):\n \"\"\"\n Add new plot to the side of existing plot\n \"\"\"\n np = 3 if self.overview else 2\n if self.dataplot:\n self.figure.delaxes(self.dataplot)\n self.dataplot = self.figure.add_subplot(1, np, np, sharey=self.detail)\n # left, bottom, width, height (proportions)\n dleft, dbottom, dwidth, dheight = self.detail.get_position().bounds\n # give the dataplot one-quarter the width of the detail axes\n w = dwidth * 0.25\n self.detail.set_position([dleft, dbottom, dwidth-w, dheight])\n self.dataplot.set_position([1-w, dbottom, w, dheight])\n self.dataplot.xaxis.set_visible(False)\n self.dataplot.yaxis.set_visible(False)\n for x in self.dataplot.spines.values():\n x.set_visible(False)\n self.figure.canvas.draw_idle()\n return self.dataplot\n\n def redraw(self):\n \"\"\"\n Replot the figure and overview\n \"\"\"\n self.detail.redraw()\n if self.overview: self.overview.redraw()\n self.highlight()\n self.set_positions()\n self.figure.canvas.draw_idle()\n\n def find(self, x):\n \"\"\"\n Find nodes\n\n Args:\n x (str): String to search\n Returns:\n list: A list of node objects found with the Node findall() method\n \"\"\"\n return self.root.findall(x)\n\n def hlines(self, nodes, width=5, color=\"red\", xoff=0, yoff=0):\n \"\"\"\n Highlight nodes\n\n Args:\n nodes (list): A list of node objects\n width (float): Width of highlighted lines. Defaults to 5\n color (str): Color of highlighted lines. Defaults to red\n xoff (float): Number of units to offset lines by. Defaults to 0\n yoff (float): Number of units to offset lines by. Defaults to 0\n \"\"\"\n self.overview.hlines(nodes, width=width, color=color,\n xoff=xoff, yoff=yoff)\n self.detail.hlines(nodes, width=width, color=color,\n xoff=xoff, yoff=yoff)\n\n def highlight(self, x=None, width=5, color=\"red\"):\n \"\"\"\n Highlight nodes\n\n Args:\n x: Str or list of Strs or Node or list of Nodes\n width (float): Width of highlighted lines. Defaults to 5\n color (str): Color of highlighted lines. Defaults to red\n \"\"\"\n if x:\n nodes = set()\n if type(x) in types.StringTypes:\n nodes = self.root.findall(x)\n elif isinstance(x, tree.Node):\n nodes = set(x)\n else:\n for n in x:\n if type(n) in types.StringTypes:\n found = self.root.findall(n)\n if found:\n nodes |= set(found)\n elif isinstance(n, tree.Node):\n nodes.add(n)\n\n self.highlighted = nodes\n else:\n self.highlighted = set()\n if self.overview:\n self.overview.highlight(self.highlighted, width=width, color=color)\n self.detail.highlight(self.highlighted, width=width, color=color)\n self.figure.canvas.draw_idle()\n\n def home(self):\n \"\"\"\n Return plot to initial size and location.\n \"\"\"\n if self.overview: self.overview.home()\n self.detail.home()\n\n def zoom_clade(self, x):\n \"\"\"\n Zoom to fit a node *x* and all its descendants in the view.\n\n Args:\n x: Node or str that matches the label of a node\n \"\"\"\n if not isinstance(x, tree.Node):\n x = self.root[x]\n self.detail.zoom_clade(x)\n\n def zoom(self, factor=0.1):\n \"\"\"Zoom both axes by *factor* (relative display size).\"\"\"\n self.detail.zoom(factor, factor)\n self.figure.canvas.draw_idle()\n\n def zx(self, factor=0.1):\n \"\"\"Zoom x axis by *factor*.\"\"\"\n self.detail.zoom(factor, 0)\n self.figure.canvas.draw_idle()\n\n def zy(self, factor=0.1):\n \"\"\"Zoom y axis by *factor*.\"\"\"\n self.detail.zoom(0, factor)\n self.figure.canvas.draw_idle()\n\n def decorate(self, func, *args, **kwargs):\n \"\"\"\n Decorate the tree.\n\n Args:\n func (function): A function that takes a TreePlot instance as the\n first parameter, and *args* and *kwargs* as additional\n parameters. It adds boxes, circles, etc to the TreePlot.\n\n Notes:\n If *kwargs* contains the key-value pair ('store', *name*),\n then the function is stored as *name* and re-called every time\n the TreePlot is redrawn, i.e., the decoration is persistent.\n Use ``rmdec(name)`` to remove the decorator from the treeplot.\n \"\"\"\n self.detail.decorate(func, *args, **kwargs)\n\n def rmdec(self, name):\n \"Remove the decoration 'name'.\"\n self.detail.rmdec(name)\n ## if name in self.detail.decorators:\n ## del self.detail.decorators[name]\n\n def cbar(self, node, width=6, color='blue', mrca = True):\n pass\n # self.axes.cbar(nodes = node, width = width, color = color, mrca = mrca)\n\n def unclutter(self, *args):\n self.detail.unclutter()\n\n def trace_branches(self, nodes, width=4, color=\"blue\"):\n \"\"\"\n RR: What is the difference between this and highlight? -CZ\n \"\"\"\n for p in self.overview, self.detail:\n p.trace_branches(nodes, width, color)\n\n def plot_continuous(self, *args, **kwargs):\n self.detail.plot_continuous(*args, **kwargs)\n\n def hardcopy(self, fname=None, relwidth=None, leafpad=1.5):\n if not relwidth:\n bbox = self.detail.get_tightbbox(self.figure.canvas.get_renderer())\n relwidth = bbox.width/bbox.height\n f = self.detail.hardcopy(\n relwidth=relwidth,\n leafpad=leafpad\n )\n f.axes.home()\n #f.axes.set_xlim(*self.detail.get_xlim())\n #f.axes.set_ylim(*self.detail.get_ylim())\n if fname:\n f.savefig(fname)\n return f\n\n def select_nodes(self, nodes=None):\n \"\"\"\n Select nodes on the plot\n\n Args:\n nodes: A node or list of ndoes\n Notes:\n If only one node is given, all of the node's ancestors are\n also selected. If a list of nodes is given (even if it has only\n one node), only the given node(s) are selected.\n \"\"\"\n self.detail.select_nodes(nodes)\n\n def decorate(self, func, *args, **kwargs): # RR: is this repeated from above? -CZ\n self.detail.decorate(func, *args, **kwargs)\n\n ## def dataplot(self):\n ## ax = self.figure.add_subplot(133, sharey=self.detail)\n ## ax.yaxis.set_visible(False)\n ## self.dataplot = ax\n ## return ax\n\n def attach_alignment(self, aln, overview=True):\n \"leaf labels expected to be sequence ids\"\n from Bio.Align import MultipleSeqAlignment\n from Bio.Seq import Seq\n from Bio.SeqRecord import SeqRecord\n from Bio.Alphabet import IUPAC\n from alignment import AlignmentFigure, AlignmentPlot\n if not isinstance(aln, MultipleSeqAlignment):\n from .. import align\n aln = align.read(aln)\n d = dict([ (x.id,x) for x in aln ])\n emptyseq = Seq('-'*aln.get_alignment_length(),\n alphabet=IUPAC.ambiguous_dna)\n aln = MultipleSeqAlignment(\n [ d.get(x.label) or SeqRecord(emptyseq, id=x.label)\n for x in self.root.leaves() ]\n )\n self.aln = aln\n p = AlignmentPlot(self.figure, 133, aln=aln, app=self,\n sharey=self.detail, showy=False)\n self.alnplot = Storage()\n self.alnplot.detail = self.figure.add_subplot(p)\n detail = self.alnplot.detail\n detail.plot_aln()\n if overview:\n self.alnplot.overview = inset_axes(\n detail, width=\"30%\", height=\"20%\", loc=1\n )\n overview = self.alnplot.overview\n overview.xaxis.set_major_locator(NullLocator())\n overview.yaxis.set_major_locator(NullLocator())\n overview.imshow(\n detail.array, interpolation='nearest', aspect='auto',\n origin='lower'\n )\n rect = UpdatingRect(\n [0,0], 0, 0, facecolor='black', edgecolor='cyan', alpha=0.5\n )\n overview.zoomrect = rect\n rect.target = detail\n detail.callbacks.connect('xlim_changed', rect)\n detail.callbacks.connect('ylim_changed', rect)\n overview.add_patch(rect)\n rect(overview)\n self.toggle_overview(False)\n xoff = self.detail.xoffset()\n self.detail.set_position([0, xoff, 0.3, 1.0-xoff])\n p.set_position([0.3, xoff, 0.7, 1.0-xoff])\n\n\nclass MultiTreeFigure(object):\n \"\"\"\n Window for showing multiple trees side-by-side.\n\n TODO: document this\n \"\"\"\n def __init__(self, trees=None, name=None, support=70,\n scaled=True, branchlabels=False, radial=False):\n \"\"\"\n *trees* are assumed to be objects suitable for passing to\n ivy.tree.read()\n \"\"\"\n self.root = []\n self.name = name\n self.name2plot = {}\n self.plot = []\n self.scaled = scaled\n self.branchlabels = branchlabels\n self.radial = radial\n self.highlighted = set()\n self.divs = []\n pars = SubplotParams(\n left=0, right=1, bottom=0.05, top=1, wspace=0.04\n )\n fig = pyplot.figure(subplotpars=pars)\n connect_events(fig.canvas)\n self.figure = fig\n\n for x in trees or []:\n self.add(x, support=support, scaled=scaled,\n branchlabels=branchlabels)\n\n def on_nodes_selected(self, treeplot):\n pass\n\n def clear(self):\n self.root = []\n self.name2plot = {}\n self.highlighted = set()\n self.divs = []\n self.figure.clf()\n\n def picked(self, e):\n try:\n if e.mouseevent.button==1:\n print(e.artist.get_text())\n sys.stdout.flush()\n except:\n pass\n\n def getplot(self, x):\n p = None\n try:\n i = self.root.index(x)\n return self.plot[i]\n except ValueError:\n return self.name2plot.get(x)\n\n def add(self, data, name=None, support=70, scaled=True,\n branchlabels=False, leaflabels=True, mark_named=True):\n root = None\n if isinstance(data, tree.Node):\n root = data\n else:\n root = tree.read(data)\n if not root:\n raise IOError(\"cannot coerce data into tree.Node\")\n\n name = name or root.treename\n self.root.append(root)\n\n fig = self.figure\n N = len(self.plot)+1\n for i, p in enumerate(self.plot):\n p.change_geometry(1, N, i+1)\n plt = TreePlot(fig, 1, N, N, app=self, name=name, support=support,\n scaled=scaled, branchlabels=branchlabels,\n leaflabels=leaflabels, mark_named=mark_named)\n p = fig.add_subplot(plt)\n p.set_root(root)\n p.plot_tree()\n p.index = N-1\n self.plot.append(p)\n if name:\n assert name not in self.name2plot\n self.name2plot[name] = p\n\n ## global IP\n ## if IP:\n ## def f(shell, s):\n ## self.highlight(s)\n ## return sorted([ x.label for x in self.highlighted ])\n ## IP.expose_magic(\"highlight\", f)\n ## def f(shell, s):\n ## self.root.ladderize()\n ## self.redraw()\n ## IP.expose_magic(\"ladderize\", f)\n ## def f(shell, s):\n ## self.show()\n ## IP.expose_magic(\"show\", f)\n ## def f(shell, s):\n ## self.redraw()\n ## IP.expose_magic(\"redraw\", f)\n return p\n\n def show(self):\n self.figure.show()\n\n def redraw(self):\n for p in self.plot:\n p.redraw()\n self.figure.canvas.draw_idle()\n\n def ladderize(self, reverse=False):\n for n in self.root:\n n.ladderize(reverse)\n self.redraw()\n\n def highlight(self, s=None, add=False, width=5, color=\"red\"):\n \"\"\"\n Highlight nodes\n\n Args:\n s: Str or list of Strs or Node or list of Nodes\n add (bool): Whether to add to existing highlighted nodes or\n overwrite them.\n width (float): Width of highlighted lines. Defaults to 5\n color (str): Color of highlighted lines. Defaults to red\n \"\"\"\n if not s:\n self.highlighted = set()\n if not add:\n self.highlighted = set()\n\n nodesets = [ p.root.findall(s) for p in self.plot ]\n\n for nodes, p in zip(nodesets, self.plot):\n if nodes:\n p.highlight(nodes, width=width, color=color)\n else:\n p.highlight()\n\n self.highlighted = nodesets\n self.figure.canvas.draw_idle()\n\n ## for root in self.root:\n ## for node in root.iternodes():\n ## if node.label and (s in node.label):\n ## self.highlighted.add(node)\n ## self.highlight()\n\n def home(self):\n for p in self.plot: p.home()\n\n\ndef connect_events(canvas):\n mpl_connect = canvas.mpl_connect\n mpl_connect(\"button_press_event\", onclick)\n mpl_connect(\"button_release_event\", onbuttonrelease)\n mpl_connect(\"scroll_event\", onscroll)\n mpl_connect(\"pick_event\", onpick)\n mpl_connect(\"motion_notify_event\", ondrag)\n mpl_connect(\"key_press_event\", onkeypress)\n mpl_connect(\"axes_enter_event\", axes_enter)\n mpl_connect(\"axes_leave_event\", axes_leave)\n\nclass UpdatingRect(Rectangle):\n def __call__(self, p):\n self.set_bounds(*p.viewLim.bounds)\n p.figure.canvas.draw_idle()\n\nclass Tree(Axes):\n \"\"\"\n matplotlib.axes.Axes subclass for rendering trees.\n \"\"\"\n def __init__(self, fig, rect, *args, **kwargs):\n self.root = None\n self.app = kwargs.pop(\"app\", None)\n self.support = kwargs.pop(\"support\", 70.0)\n self.scaled = kwargs.pop(\"scaled\", True)\n self.leaflabels = kwargs.pop(\"leaflabels\", True)\n self.branchlabels = kwargs.pop(\"branchlabels\", True)\n self._mark_named = kwargs.pop(\"mark_named\", True)\n self.name = None\n self.leaf_fontsize = kwargs.pop(\"leaf_fontsize\", 10)\n self.branch_fontsize = kwargs.pop(\"branch_fontsize\", 10)\n self.branch_width = kwargs.pop(\"branch_width\", 1)\n self.branch_color = kwargs.pop(\"branch_color\", \"black\")\n self.interactive = kwargs.pop(\"interactive\", True)\n self.decorators = kwargs.pop(\"decorators\", [])\n ## if self.decorators:\n ## print >> sys.stderr, \"got %s decorators\" % len(self.decorators)\n self.xoff = kwargs.pop(\"xoff\", 0)\n self.yoff = kwargs.pop(\"yoff\", 0)\n self.highlight_support = kwargs.pop(\"highlight_support\", True)\n self.smooth_xpos = kwargs.pop(\"smooth_xpos\", 0)\n Axes.__init__(self, fig, rect, *args, **kwargs)\n self.nleaves = 0\n self.highlighted = None\n self.highlightpatch = None\n self.pan_start = None\n if not self.decorators:\n self.decorators = [\n (\"__selected_nodes__\", (Tree.highlight_selected_nodes, [], {}))\n ]\n self.name2dec = dict([ (x[0], i) for i, x in\n enumerate(self.decorators) ])\n self._active = False\n\n if self.interactive:\n self.callbacks.connect(\"ylim_changed\", self.draw_labels)\n self.selector = RectangleSelector(self, self.rectselect,\n useblit=True)\n def f(e):\n if e.button != 1: return True\n else: return RectangleSelector.ignore(self.selector, e)\n self.selector.ignore = f\n self.xoffset_value = 0.05\n self.selected_nodes = set()\n self.leaf_offset = 4\n self.leaf_valign = \"center\"\n self.leaf_halign = \"left\"\n self.branch_offset = -5\n self.branch_valign = \"center\"\n self.branch_halign = \"right\"\n\n self.spines[\"top\"].set_visible(False)\n self.spines[\"left\"].set_visible(False)\n self.spines[\"right\"].set_visible(False)\n self.xaxis.set_ticks_position(\"bottom\")\n\n def p2y(self):\n \"Convert a single display point to y-units\"\n transform = self.transData.inverted().transform\n return transform([0,1])[1] - transform([0,0])[1]\n\n def p2x(self):\n \"Convert a single display point to y-units\"\n transform = self.transData.inverted().transform\n return transform([0,0])[1] - transform([1,0])[1]\n\n def decorate(self, func, *args, **kwargs):\n \"\"\"\n Decorate the tree with function *func*. If *kwargs* contains\n the key-value pair ('store', *name*), the decorator function\n is stored in self.decorators and called upon every redraw.\n \"\"\"\n name = kwargs.pop(\"store\", None)\n if name:\n if name in self.name2dec:\n i = self.name2dec[name]\n self.decorators[i] = (name, (func, args, kwargs))\n else:\n self.decorators.append((name, (func, args, kwargs)))\n self.name2dec = dict([ (x[0], i) for i, x in\n enumerate(self.decorators) ])\n\n func(self, *args, **kwargs)\n\n def rmdec(self, name):\n if name in self.name2dec:\n i = self.name2dec[name]\n del self.decorators[i]\n self.name2dec = dict([ (x[0], i) for i, x in\n enumerate(self.decorators) ])\n\n\n def flip(self):\n \"\"\"\n Reverse the direction of the x-axis.\n \"\"\"\n self.leaf_offset *= -1\n self.branch_offset *= -1\n ha = self.leaf_halign\n self.leaf_halign = \"right\" if ha == \"left\" else \"left\"\n ha = self.branch_halign\n self.branch_halign = \"right\" if ha == \"left\" else \"left\"\n self.invert_xaxis()\n self.redraw()\n\n def xoffset(self):\n \"\"\"Space below x axis to show tick labels.\"\"\"\n if self.scaled:\n return self.xoffset_value\n else:\n return 0\n\n def save_newick(self, filename):\n \"\"\"\n Save tree as a newick file.\n\n Args:\n filename (str): Path to file.\n\n \"\"\"\n if os.path.exists(filename):\n s = raw_input(\"File %s exists, enter 'y' to overwrite \").strip()\n if (s and s.lower() != 'y') or (not s):\n return\n import newick\n f = file(filename, \"w\")\n f.write(newick.string(self.root))\n f.close()\n\n def set_scaled(self, scaled):\n flag = self.scaled != scaled\n self.scaled = scaled\n return flag\n\n def cbar(self, nodes, color=None, label=None, x=None, width=8, xoff=10,\n showlabel=True, mrca=True):\n \"\"\"\n Draw a 'clade' bar (i.e., along the y-axis) indicating a\n clade. *nodes* are assumed to be one or more nodes in the\n tree. If just one, it should be the internal node\n representing the clade of interest; otherwise, the clade of\n interest is the most recent common ancestor of the specified\n nodes. *label* is an optional string to be drawn next to the\n bar, *offset* by the specified number of display units. If\n *label* is ``None`` then the clade's label is used instead.\n\n Args:\n nodes: Node or list of nodes\n color (str): Color of the bar. Optional, defaults to None.\n label (str): Optional label for bar. If None, the clade's\n label is used instead. Defaults to None.\n width (float): Width of bar\n xoff (float): Offset from label to bar\n showlabel (bool): Whether or not to draw the label\n mrca: RR: Not quite sure what this does -CZ\n\n \"\"\"\n xlim = self.get_xlim(); ylim = self.get_ylim()\n if color is None: color = _tango.next()\n transform = self.transData.inverted().transform\n\n if mrca:\n if isinstance(nodes, tree.Node):\n spec = nodes\n elif type(nodes) in types.StringTypes:\n spec = self.root.get(nodes)\n else:\n spec = self.root.mrca(nodes)\n\n assert spec in self.root\n label = label or spec.label\n leaves = spec.leaves()\n\n else:\n leaves = nodes\n\n n2c = self.n2c\n\n y = sorted([ n2c[n].y for n in leaves ])\n ymin = y[0]; ymax = y[-1]; y = (ymax+ymin)*0.5\n\n if x is None:\n x = max([ n2c[n].x for n in leaves ])\n _x = 0\n for lf in leaves:\n txt = self.node2label.get(lf)\n if txt and txt.get_visible():\n _x = max(_x, transform(txt.get_window_extent())[1,0])\n if _x > x: x = _x\n\n v = sorted(list(transform(((0,0),(xoff,0)))[:,0]))\n xoff = v[1]-v[0]\n x += xoff\n\n Axes.plot(self, [x,x], [ymin, ymax], '-', linewidth=width, color=color)\n\n if showlabel and label:\n xo = self.leaf_offset\n if xo > 0:\n xo += width*0.5\n else:\n xo -= width*0.5\n txt = self.annotate(\n label,\n xy=(x, y),\n xytext=(xo, 0),\n textcoords=\"offset points\",\n verticalalignment=self.leaf_valign,\n horizontalalignment=self.leaf_halign,\n fontsize=self.leaf_fontsize,\n clip_on=True,\n picker=False\n )\n\n self.set_xlim(xlim); self.set_ylim(ylim)\n\n def anctrace(self, anc, descendants=None, width=4, color=\"blue\"):\n \"\"\"\n RR: This function gives me a 'list index out of range' error\n when I try to use it -CZ\n \"\"\"\n if not descendants:\n descendants = anc.leaves()\n else:\n for d in descendants:\n assert d in anc\n\n nodes = []\n for d in descendants:\n v = d.rootpath(anc)\n if v:\n nodes.extend(v)\n nodes = set(nodes)\n nodes.remove(anc)\n self.trace_branches(nodes, width, color)\n\n def trace_branches(self, nodes, width=4, color=\"blue\"):\n n2c = self.n2c\n M = Path.MOVETO; L = Path.LINETO\n verts = []\n codes = []\n for c, pc in [ (n2c[x], n2c[x.parent]) for x in nodes\n if (x in n2c) and x.parent ]:\n x = c.x; y = c.y\n px = pc.x; py = pc.y\n verts.append((x, y)); codes.append(M)\n verts.append((px, y)); codes.append(L)\n verts.append((px, py)); codes.append(L)\n px, py = verts[-1]\n verts.append((px, py)); codes.append(M)\n\n p = PathPatch(Path(verts, codes), fill=False,\n linewidth=width, edgecolor=color)\n self.add_patch(p)\n self.figure.canvas.draw_idle()\n return p\n\n def highlight_selected_nodes(self, color=\"green\"):\n xlim = self.get_xlim()\n ylim = self.get_ylim()\n get = self.n2c.get\n coords = list(filter(None, [ get(n) for n in self.selected_nodes ]))\n x = [ c.x for c in coords ]\n y = [ c.y for c in coords ]\n if x and y:\n self.__selected_highlight_patch = self.scatter(x, y, s=60, c=color,\n zorder=100)\n self.set_xlim(xlim)\n self.set_ylim(ylim)\n self.figure.canvas.draw_idle()\n\n def select_nodes(self, nodes=None, add=False):\n try:\n self.__selected_highlight_patch.remove()\n self.figure.canvas.draw_idle()\n except:\n pass\n if add:\n if nodes:\n self.selected_nodes = self.selected_nodes | nodes\n if hasattr(self, \"app\") and self.app:\n self.app.on_nodes_selected(self)\n self.highlight_selected_nodes()\n else:\n if nodes:\n self.selected_nodes = nodes\n if hasattr(self, \"app\") and self.app:\n self.app.on_nodes_selected(self)\n self.highlight_selected_nodes()\n else:\n self.selected_nodes = set()\n\n def rectselect(self, e0, e1):\n xlim = self.get_xlim()\n ylim = self.get_ylim()\n s = set()\n x0, x1 = sorted((e0.xdata, e1.xdata))\n y0, y1 = sorted((e0.ydata, e1.ydata))\n add = e0.key == 'shift'\n for n, c in self.n2c.items():\n if (x0 < c.x < x1) and (y0 < c.y < y1):\n s.add(n)\n self.select_nodes(nodes = s, add = add)\n self.set_xlim(xlim)\n self.set_ylim(ylim)\n ## if s:\n ## print \"Selected:\"\n ## for n in s:\n ## print \" \", n\n\n def picked(self, e):\n if hasattr(self, \"app\") and self.app:\n self.app.picked(e)\n\n def window2data(self, expandx=1.0, expandy=1.0):\n \"\"\"\n return the data coordinates ((x0, y0),(x1, y1)) of the plot\n window, expanded by relative units of window size\n \"\"\"\n bb = self.get_window_extent()\n bbx = bb.expanded(expandx, expandy)\n return self.transData.inverted().transform(bbx.get_points())\n\n def get_visible_nodes(self, labeled_only=False):\n ## transform = self.transData.inverted().transform\n ## bb = self.get_window_extent()\n ## bbx = bb.expanded(1.1,1.1)\n ## ((x0, y0),(x1, y1)) = transform(bbx.get_points())\n ((x0, y0),(x1, y1)) = self.window2data(1.1, 1.1)\n #print \"visible_nodes points\", x0, x1, y0, y1\n\n if labeled_only:\n def f(v): return (y0 < v[0] < y1) and (v[2] in self.node2label)\n else:\n def f(v): return (y0 < v[0] < y1)\n for y, x, n in filter(f, self.coords):\n yield (n, x, y)\n\n def zoom_cxy(self, x=0.1, y=0.1, cx=None, cy=None):\n \"\"\"\n Zoom the x and y axes in by the specified proportion of the\n current view, with a fixed data point (cx, cy)\n \"\"\"\n transform = self.transData.inverted().transform\n xlim = self.get_xlim(); xmid = sum(xlim)*0.5\n ylim = self.get_ylim(); ymid = sum(ylim)*0.5\n bb = self.get_window_extent()\n bbx = bb.expanded(1.0-x,1.0-y)\n points = transform(bbx.get_points())\n x0, x1 = points[:,0]; y0, y1 = points[:,1]\n deltax = xmid-x0; deltay = ymid-y0\n cx = cx or xmid; cy = cy or ymid\n xoff = (cx-xmid)*x\n self.set_xlim(xmid-deltax+xoff, xmid+deltax+xoff)\n yoff = (cy-ymid)*y\n self.set_ylim(ymid-deltay+yoff, ymid+deltay+yoff)\n self.adjust_xspine()\n\n def zoom(self, x=0.1, y=0.1, cx=None, cy=None):\n \"\"\"\n Zoom the x and y axes in by the specified proportion of the\n current view.\n \"\"\"\n # get the function to convert display coordinates to data\n # coordinates\n transform = self.transData.inverted().transform\n xlim = self.get_xlim()\n ylim = self.get_ylim()\n bb = self.get_window_extent()\n bbx = bb.expanded(1.0-x,1.0-y)\n points = transform(bbx.get_points())\n x0, x1 = points[:,0]; y0, y1 = points[:,1]\n deltax = x0 - xlim[0]; deltay = y0 - ylim[0]\n self.set_xlim(xlim[0]+deltax, xlim[1]-deltax)\n self.set_ylim(ylim[0]+deltay, ylim[1]-deltay)\n self.adjust_xspine()\n\n def center_y(self, y):\n \"\"\"\n Center the y-axis of the canvas on the given y value\n \"\"\"\n ymin, ymax = self.get_ylim()\n yoff = (ymax - ymin) * 0.5\n self.set_ylim(y-yoff, y+yoff)\n self.adjust_xspine()\n\n def center_x(self, x, offset=0.3):\n \"\"\"\n Center the x-axis of the canvas on the given x value\n \"\"\"\n xmin, xmax = self.get_xlim()\n xspan = xmax - xmin\n xoff = xspan*0.5 + xspan*offset\n self.set_xlim(x-xoff, x+xoff)\n self.adjust_xspine()\n\n def center_node(self, node):\n \"\"\"\n Center the canvas on the given node\n \"\"\"\n c = self.n2c[node]\n y = c.y\n self.center_y(y)\n x = c.x\n self.center_x(x, 0.2)\n\n def do_highlight_support(self):\n \"\"\"\n TODO: reconfigure this, insert into self.decorators\n \"\"\"\n if self.support:\n lim = float(self.support)\n\n M = Path.MOVETO; L = Path.LINETO\n\n verts = []; codes = []\n segments = []\n def f(n):\n if n.isleaf or not n.parent: return False\n try: return float(n.label) >= lim\n except:\n try: return float(n.support) >= lim\n except: pass\n return False\n\n for node, coords in [ x for x in self.n2c.items() if f(x[0]) ]:\n x = coords.x; y = coords.y\n p = node.parent\n pcoords = self.n2c[p]\n px = pcoords.x; py = y\n if self.app and self.app.radial:\n pc = self.n2c[node.parent]; theta2 = pc.angle\n px = math.cos(math.radians(coords.angle))*pc.depth\n py = math.sin(math.radians(coords.angle))*pc.depth\n\n ## segments.append([(x, y),(px, y)])\n verts.append((x,y)); codes.append(M)\n verts.append((px,py)); codes.append(L)\n\n if verts:\n patch = PathPatch(Path(verts, codes), fill=False,\n linewidth=3, edgecolor='black')\n self.add_patch(patch)\n\n ## self.add_artist(Line2D(\n ## [x,px], [y,py], lw=3, solid_capstyle=\"butt\", color=\"black\"\n ## ))\n\n def hl(self, s):\n nodes = self.root.findall(s)\n if nodes:\n self.highlight(nodes)\n\n def hlines(self, nodes, width=5, color=\"red\", xoff=0, yoff=0):\n offset = IdentityTransform()\n segs = []; w = []; o = []\n for n in filter(lambda x:x.parent, nodes):\n c = self.n2c[n]; p = self.n2c[n.parent]\n segs.append(((p.x,c.y),(c.x,c.y)))\n w.append(width); o.append((xoff,yoff))\n lc = LineCollection(segs, linewidths=w, transOffset=offset, offsets=o)\n lc.set_color(color)\n Axes.add_collection(self, lc)\n ## self.drawstack.append((\"hlines\", [nodes], dict(width=width,\n ## color=color,\n ## xoff=xoff,\n ## yoff=yoff)))\n self.figure.canvas.draw_idle()\n return lc\n\n def hardcopy(self, relwidth=0.5, leafpad=1.5):\n p = HC.TreeFigure(self.root, relwidth=relwidth, leafpad=leafpad,\n name=self.name, support=self.support,\n leaf_fontsize=self.leaf_fontsize,\n branch_fontsize=self.branch_fontsize,\n branch_width=self.branch_width,\n branch_color=self.branch_color,\n highlight_support=self.highlight_support,\n branchlabels=self.branchlabels,\n decorators=self.decorators,\n leaflabels=self.leaflabels,\n mark_named=self._mark_named,\n xlim=self.get_xlim(),\n ylim=self.get_ylim())\n return p\n\n def highlight(self, nodes=None, width=5, color=\"red\"):\n if self.highlightpatch:\n try:\n self.highlightpatch.remove()\n except:\n pass\n if not nodes:\n return\n\n if len(nodes)>1:\n mrca = self.root.mrca(nodes)\n if not mrca:\n return\n else:\n mrca = list(nodes)[0]\n\n M = Path.MOVETO; L = Path.LINETO\n verts = []\n codes = []\n seen = set()\n for node, coords in [ x for x in self.n2c.items() if x[0] in nodes ]:\n x = coords.x; y = coords.y\n p = node.parent\n while p:\n pcoords = self.n2c[p]\n px = pcoords.x; py = pcoords.y\n if node not in seen:\n verts.append((x, y)); codes.append(M)\n verts.append((px, y)); codes.append(L)\n verts.append((px, py)); codes.append(L)\n seen.add(node)\n if p == mrca or node == mrca:\n break\n node = p\n coords = self.n2c[node]\n x = coords.x; y = coords.y\n p = node.parent\n px, py = verts[-1]\n verts.append((px, py)); codes.append(M)\n\n self.highlightpath = Path(verts, codes)\n self.highlightpatch = PathPatch(\n self.highlightpath, fill=False, linewidth=width, edgecolor=color,\n capstyle='round', joinstyle='round'\n )\n return self.add_patch(self.highlightpatch)\n\n def find(self, s):\n \"\"\"\n Find node(s) matching pattern s and zoom to node(s)\n \"\"\"\n nodes = list(self.root.find(s))\n if nodes:\n self.zoom_nodes(nodes)\n\n def zoom_nodes(self, nodes, border=1.2):\n y0, y1 = self.get_ylim(); x0, x1 = self.get_xlim()\n y0 = max(0, y0); y1 = min(1, y1)\n\n n2c = self.n2c\n v = [ n2c[n] for n in nodes ]\n ymin = min([ c.y for c in v ])\n ymax = max([ c.y for c in v ])\n xmin = min([ c.x for c in v ])\n xmax = max([ c.x for c in v ])\n bb = Bbox(((xmin,ymin), (xmax, ymax)))\n\n # convert data coordinates to display coordinates\n transform = self.transData.transform\n disp_bb = [Bbox(transform(bb))]\n for n in nodes:\n if n.isleaf:\n txt = self.node2label[n]\n if txt.get_visible():\n disp_bb.append(txt.get_window_extent())\n\n disp_bb = Bbox.union(disp_bb).expanded(border, border)\n\n # convert back to data coordinates\n points = self.transData.inverted().transform(disp_bb)\n x0, x1 = points[:,0]\n y0, y1 = points[:,1]\n self.set_xlim(x0, x1)\n self.set_ylim(y0, y1)\n\n def zoom_clade(self, anc, border=1.2):\n if anc.isleaf:\n self.center_node(anc)\n\n else:\n self.zoom_nodes(list(anc), border)\n\n def draw_leaf_labels(self, *args):\n leaves = list(filter(lambda x:x[0].isleaf,\n self.get_visible_nodes(labeled_only=True)))\n psep = self.leaf_pixelsep()\n fontsize = min(self.leaf_fontsize, max(psep, 8))\n n2l = self.node2label\n transform = self.transData.transform\n sub = operator.sub\n\n for n in leaves:\n n2l[n[0]].set_visible(False)\n\n # draw leaves\n leaves_drawn = []\n for n, x, y in leaves:\n txt = self.node2label[n]\n if not leaves_drawn:\n txt.set_visible(True)\n leaves_drawn.append(txt)\n self.figure.canvas.draw_idle()\n continue\n\n txt2 = leaves_drawn[-1]\n y0 = y; y1 = txt2.xy[1]\n sep = sub(*transform(([0,y0],[0,y1]))[:,1])\n if sep > fontsize:\n txt.set_visible(True)\n txt.set_size(fontsize)\n leaves_drawn.append(txt)\n self.figure.canvas.draw_idle()\n\n if leaves_drawn:\n leaves_drawn[0].set_size(fontsize)\n\n return fontsize\n\n def draw_labels(self, *args):\n fs = max(10, self.draw_leaf_labels())\n nodes = self.get_visible_nodes(labeled_only=True)\n ## print [ x[0].id for x in nodes ]\n branches = list(filter(lambda x:(not x[0].isleaf), nodes))\n n2l = self.node2label\n for n, x, y in branches:\n t = n2l[n]\n t.set_visible(True)\n t.set_size(fs)\n\n def unclutter(self, *args):\n nodes = self.get_visible_nodes(labeled_only=True)\n branches = list(filter(lambda x:(not x[0].isleaf), nodes))\n psep = self.leaf_pixelsep()\n n2l = self.node2label\n fontsize = min(self.leaf_fontsize*1.2, max(psep, self.leaf_fontsize))\n\n drawn = []\n for n, x, y in branches:\n txt = n2l[n]\n try:\n bb = txt.get_window_extent().expanded(2, 2)\n vis = True\n for n2 in reversed(drawn):\n txt2 = n2l[n2]\n if bb.overlaps(txt2.get_window_extent()):\n txt.set_visible(False)\n vis = False\n self.figure.canvas.draw_idle()\n break\n if vis:\n txt.set_visible(True)\n txt.set_size(fontsize)\n self.figure.canvas.draw_idle()\n drawn.append(n)\n except RuntimeError:\n pass\n ## txt.set_visible(True)\n ## txt.set_size(fontsize)\n ## drawn.append(n)\n ## self.figure.canvas.draw_idle()\n\n def leaf_pixelsep(self):\n y0, y1 = self.get_ylim()\n y0 = max(0, y0)\n y1 = min(self.nleaves, y1)\n display_points = self.transData.transform(((0, y0), (0, y1)))\n # height in pixels (visible y data extent)\n height = operator.sub(*reversed(display_points[:,1]))\n pixelsep = height/((y1-y0)/self.leaf_hsep)\n return pixelsep\n\n def ypp(self):\n y0, y1 = self.get_ylim()\n p0, p1 = self.transData.transform(((0, y0), (0, y1)))[:,1]\n return (y1-y0)/float(p1-p0)\n\n def draw_labels_old(self, *args):\n if self.nleaves:\n y0, y1 = self.get_ylim()\n y0 = max(0, y0); y1 = min(1, y1)\n\n display_points = self.transData.transform(((0, y0), (0, y1)))\n # height in pixels (visible y data extent)\n height = operator.sub(*reversed(display_points[:,1]))\n pixelsep = height/((y1-y0)/self.leaf_hsep)\n fontsize = min(max(pixelsep-2, 8), 12)\n\n if pixelsep >= 8:\n for node, txt in self.node2label.items():\n if node.isleaf:\n if self.leaflabels:\n c = self.n2c[node]\n x = c.x; y = c.y\n if (y0 < y < y1):\n txt.set_size(fontsize)\n txt.set_visible(True)\n else:\n if self.branchlabels:\n c = self.n2c[node]\n x = c.x; y = c.y\n if (y0 < y < y1):\n txt.set_size(fontsize)\n txt.set_visible(True)\n elif pixelsep >= 4:\n for node, txt in self.node2label.items():\n if node.isleaf:\n txt.set_visible(False)\n else:\n if self.branchlabels:\n c = self.n2c[node]\n x = c.x; y = c.y\n if (y0 < y < y1):\n txt.set_size(fontsize)\n txt.set_visible(True)\n else:\n for node, txt in self.node2label.items():\n txt.set_visible(False)\n self.figure.canvas.draw_idle()\n\n def redraw(self, home=False, layout=True):\n \"\"\"\n Replot the tree\n \"\"\"\n xlim = self.get_xlim()\n ylim = self.get_ylim()\n self.cla()\n if layout:\n self.layout()\n self.plot_tree()\n if self.interactive:\n self.callbacks.connect(\"ylim_changed\", self.draw_labels)\n\n if home:\n self.home()\n else:\n self.set_xlim(*xlim)\n self.set_ylim(*ylim)\n\n def set_name(self, name):\n self.name = name\n if name:\n at = AnchoredText(\n self.name, loc=2, frameon=True,\n prop=dict(size=12, weight=\"bold\")\n )\n at.patch.set_linewidth(0)\n at.patch.set_facecolor(\"white\")\n at.patch.set_alpha(0.6)\n self.add_artist(at)\n return at\n\n def _path_to_parent(self, node):\n \"\"\"\n For use in drawing branches\n \"\"\"\n c = self.n2c[node]; x = c.x; y = c.y\n pc = self.n2c[node.parent]; px = pc.x; py = pc.y\n M = Path.MOVETO; L = Path.LINETO\n verts = [(x, y), (px, y), (px, py)]\n codes = [M, L, L]\n return verts, codes\n ## return [PathPatch(Path(verts, codes), fill=False,\n ## linewidth=width or self.branch_width,\n ## edgecolor=color or self.branch_color)]\n\n\n def layout(self):\n self.n2c = cartesian(self.root, scaled=self.scaled, yunit=1.0,\n smooth=self.smooth_xpos)\n for c in self.n2c.values():\n c.x += self.xoff; c.y += self.yoff\n sv = sorted([\n [c.y, c.x, n] for n, c in self.n2c.items()\n ])\n self.coords = sv#numpy.array(sv)\n ## n2c = self.n2c\n ## self.node2linesegs = {}\n ## for node, coords in n2c.items():\n ## x = coords.x; y = coords.y\n ## v = [(x,y)]\n ## if node.parent:\n ## pcoords = n2c[node.parent]\n ## px = pcoords.x; py = pcoords.y\n ## v.append((px,y))\n ## v.append((px,py))\n ## self.node2linesegs[node] = v\n\n def set_root(self, root):\n self.root = root\n self.leaves = root.leaves()\n self.nleaves = len(self.leaves)\n self.leaf_hsep = 1.0#/float(self.nleaves)\n\n for n in root.descendants():\n if n.length is None:\n self.scaled=False; break\n self.layout()\n\n def plot_tree(self, root=None, **kwargs):\n \"\"\"\n Draw branches and labels\n \"\"\"\n if root and not self.root:\n self.set_root(root)\n\n if self.interactive: pyplot.ioff()\n\n if \"branchlabels\" in kwargs:\n self.branchlabels = kwargs[\"branchlabels\"]\n if \"leaflabels\" in kwargs:\n self.leaflabels = kwargs[\"leaflabels\"]\n self.yaxis.set_visible(False)\n self.create_branch_artists()\n self.create_label_artists()\n if self.highlight_support:\n self.do_highlight_support()\n self.mark_named()\n ## self.home()\n\n for k, v in self.decorators:\n func, args, kwargs = v\n func(self, *args, **kwargs)\n\n self.set_name(self.name)\n self.adjust_xspine()\n\n if self.interactive: pyplot.ion()\n\n labels = [ x.label for x in self.root.leaves() ]\n def fmt(x, pos=None):\n if x<0: return \"\"\n try: return labels[int(round(x))]\n except: pass\n return \"\"\n #self.yaxis.set_major_formatter(FuncFormatter(fmt))\n\n return self\n\n def clade_dimensions(self):\n n2c = self.n2c\n d = {}\n def recurse(n, n2c, d):\n v = []\n for c in n.children:\n recurse(c, n2c, d)\n if c.isleaf:\n x, y = n2c[c].point()\n x0 = x1 = x; y0 = y1 = y\n else:\n x0, x1, y0, y1 = d[c]\n v.append((x0, x1, y0, y1))\n if v:\n x0 = n2c[n].x\n x1 = max([ x[1] for x in v ])\n y0 = min([ x[2] for x in v ])\n y1 = max([ x[3] for x in v ])\n d[n] = (x0, x1, y0, y1)\n recurse(self.root, n2c, d)\n return d\n\n def clade_height_pixels(self):\n ypp = self.ypp()\n d = self.clade_dimensions()\n h = {}\n for n, (x0, x1, y0, y1) in d.items():\n h[n] = (y1-y0)/ypp\n return h\n\n def _decimate_nodes(self, n=500):\n leaves = self.leaves\n nleaves = len(leaves)\n if nleaves > n:\n indices = numpy.linspace(0, nleaves-1, n).astype(int)\n leaves = [ leaves[i] for i in indices ]\n return set(list(chain.from_iterable([ list(x.rootpath())\n for x in leaves ])))\n else:\n return self.root\n\n def create_branch_artists(self):\n \"\"\"\n Use MPL Paths to draw branches\n \"\"\"\n ## patches = []\n verts = []; codes = []\n for node in self.root.descendants():\n v, c = self._path_to_parent(node)\n verts.extend(v); codes.extend(c)\n self.branchpatch = PathPatch(\n Path(verts, codes), fill=False,\n linewidth=self.branch_width,\n edgecolor=self.branch_color\n )\n self.add_patch(self.branchpatch)\n ## for node in self._decimate_nodes():\n ## if node.parent:\n ## for p in self._path_to_parent(node):\n ## patches.append(p)\n ## self.branch_patches = PatchCollection(patches, match_original=True)\n ## self.add_collection(self.branch_patches)\n\n ## print \"enter: create_branch_artists\"\n ## self.node2branch = {}\n ## for node, segs in self.node2linesegs.items():\n ## line = Line2D(\n ## [x[0] for x in segs], [x[1] for x in segs],\n ## lw=self.branch_width, color=self.branch_color\n ## )\n ## line.set_visible(False)\n ## Axes.add_artist(self, line)\n ## self.node2branch[node] = line\n\n ## d = self.node2linesegs\n ## segs = [ d[n] for n in self.root if (n in d) ]\n\n ## dims = self.clade_dimensions(); ypp = self.ypp()\n ## def recurse(n, dims, clades, terminals):\n ## stop = False\n ## h = None\n ## v = dims.get(n)\n ## if v: h = (v[3]-v[2])/ypp\n ## if (h and (h < 20)) or (not h):\n ## stop = True\n ## terminals.append(n)\n ## if not stop:\n ## clades.append(n)\n ## for c in n.children:\n ## recurse(c, dims, clades, terminals)\n ## clades = []; terminals = []\n ## recurse(self.root, dims, clades, terminals)\n ## segs = [ d[n] for n in self.root if (n in d) and (n in clades) ]\n ## for t in terminals:\n ## if t.isleaf:\n ## segs.append(d[t])\n ## else:\n ## x0, x1, y0, y1 = dims[t]\n ## x, y = self.n2c[t].point()\n ## px, py = self.n2c[t.parent].point()\n ## segs.append(((px,py), (px,y), (x,y), (x1, y0), (x1,y1), (x,y)))\n\n ## lc = LineCollection(segs, linewidths=self.branch_width,\n ## colors = self.branch_color)\n ## self.branches_linecollection = Axes.add_collection(self, lc)\n ## print \"leave: create_branch_artists\"\n\n def create_label_artists(self):\n ## print \"enter: create_label_artists\"\n self.node2label = {}\n n2c = self.n2c\n for node, coords in n2c.items():\n x = coords.x; y = coords.y\n if node.isleaf and node.label and self.leaflabels:\n txt = self.annotate(\n node.label,\n xy=(x, y),\n xytext=(self.leaf_offset, 0),\n textcoords=\"offset points\",\n verticalalignment=self.leaf_valign,\n horizontalalignment=self.leaf_halign,\n fontsize=self.leaf_fontsize,\n clip_on=True,\n picker=True\n )\n txt.node = node\n txt.set_visible(False)\n self.node2label[node] = txt\n\n if (not node.isleaf) and node.label and self.branchlabels:\n txt = self.annotate(\n node.label,\n xy=(x, y),\n xytext=(self.branch_offset,0),\n textcoords=\"offset points\",\n verticalalignment=self.branch_valign,\n horizontalalignment=self.branch_halign,\n fontsize=self.branch_fontsize,\n bbox=dict(fc=\"lightyellow\", ec=\"none\", alpha=0.8),\n clip_on=True,\n picker=True\n )\n ## txt.set_visible(False)\n txt.node = node\n self.node2label[node] = txt\n ## print \"leave: create_label_artists\"\n\n def adjust_xspine(self):\n v = sorted([ c.x for c in self.n2c.values() ])\n try:\n self.spines[\"bottom\"].set_bounds(v[0],v[-1])\n except AttributeError:\n pass\n for t,n,s in self.xaxis.iter_ticks():\n if (n > v[-1]) or (n < v[0]):\n t.set_visible(False)\n\n def mark_named(self):\n if self._mark_named:\n n2c = self.n2c\n cv = [ c for n, c in n2c.items() if n.label and (not n.isleaf) ]\n x = [ c.x for c in cv ]\n y = [ c.y for c in cv ]\n if x and y:\n self.scatter(x, y, s=5, color='black')\n\n def home(self):\n td = self.transData\n trans = td.inverted().transform\n xmax = xmin = ymax = ymin = 0\n if self.node2label:\n try:\n v = [ x.get_window_extent() for x in self.node2label.values()\n if x.get_visible() ]\n if v:\n xmax = trans((max([ x.xmax for x in v ]),0))[0]\n xmin = trans((min([ x.xmin for x in v ]),0))[0]\n except RuntimeError:\n pass\n\n v = self.n2c.values()\n ymin = min([ c.y for c in v ])\n ymax = max([ c.y for c in v ])\n xmin = min(xmin, min([ c.x for c in v ]))\n xmax = max(xmax, max([ c.x for c in v ]))\n xspan = xmax - xmin; xpad = xspan*0.05\n yspan = ymax - ymin; ypad = yspan*0.05\n self.set_xlim(xmin-xpad, xmax+xpad*2)\n self.set_ylim(ymin-ypad, ymax+ypad)\n self.adjust_xspine()\n\n def scroll(self, x, y):\n x0, x1 = self.get_xlim()\n y0, y1 = self.get_ylim()\n xd = (x1-x0)*x\n yd = (y1-y0)*y\n self.set_xlim(x0+xd, x1+xd)\n self.set_ylim(y0+yd, y1+yd)\n self.adjust_xspine()\n\n def plot_labelcolor(self, nodemap, state2color=None):\n if state2color is None:\n c = colors.tango()\n states = sorted(set(nodemap.values()))\n state2color = dict(zip(states, c))\n\n for node, txt in self.node2label.items():\n s = nodemap.get(node)\n if s is not None:\n c = state2color[s]\n if c:\n txt.set_color(c)\n self.figure.canvas.draw_idle()\n\n def node_image(self, node, imgfile, maxdim=100, border=0):\n xoff = self.leaf_offset\n n = self.root[node]; c = self.n2c[n]; p = (c.x, c.y)\n img = Image.open(imgfile)\n if max(img.size) > maxdim:\n img.thumbnail((maxdim, maxdim))\n imgbox = OffsetImage(img)\n xycoords = self.node2label.get(node) or \"data\"\n if xycoords != \"data\": p = (1, 0.5)\n abox = AnnotationBbox(imgbox, p,\n xybox=(xoff, 0.0),\n xycoords=xycoords,\n box_alignment=(0.0,0.5),\n pad=0.0,\n boxcoords=(\"offset points\"))\n self.add_artist(abox)\n\n def plot_discrete(self, data, cmap=None, name=None,\n xoff=10, yoff=0, size=15, legend=1):\n root = self.root\n if cmap is None:\n import ivy\n c = colors.tango()\n states = sorted(set(data.values()))\n cmap = dict(zip(states, c))\n n2c = self.n2c\n points = []; c = []\n d = dict([ (n, data.get(n)) for n in root if data.get(n) is not None ])\n for n, v in d.items():\n coord = n2c[n]\n points.append((coord.x, coord.y)); c.append(cmap[v])\n\n boxes = symbols.squares(self, points, c, size, xoff=xoff, yoff=yoff)\n\n if legend:\n handles = []; labels = []\n for v, c in sorted(cmap.items()):\n handles.append(Rectangle((0,0),0.5,1,fc=c))\n labels.append(str(v))\n self.legend(handles, labels, loc=legend)\n\n self.figure.canvas.draw_idle()\n return boxes\n\n def plot_continuous(self, data, mid=None, name=None, cmap=None,\n size=15, colorbar=True):\n area = (size*0.5)*(size*0.5)*numpy.pi\n values = data.values()\n vmin = min(values); vmax = max(values)\n if mid is None:\n mid = (vmin+vmax)*0.5\n delta = vmax-vmin*0.5\n else:\n delta = max(abs(vmax-mid), abs(vmin-mid))\n norm = mpl_colors.Normalize(mid-delta, mid+delta)\n ## if cmap is None: cmap = mpl_colormap.binary\n if cmap is None: cmap = mpl_colormap.hot\n n2c = self.n2c\n X = numpy.array(\n [ (n2c[n].x, n2c[n].y, v) for n, v in data.items() if n in n2c ]\n )\n circles = self.scatter(\n X[:,0], X[:,1], s=area, c=X[:,2], cmap=cmap, norm=norm,\n zorder=1000\n )\n if colorbar:\n cbar = self.figure.colorbar(circles, ax=self, shrink=0.7)\n if name:\n cbar.ax.set_xlabel(name)\n\n self.figure.canvas.draw_idle()\n\nclass RadialTree(Tree):\n def layout(self):\n from ..layout_polar import calc_node_positions\n start = self.start if hasattr(self, 'start') else 0\n end = self.end if hasattr(self, 'end') else None\n self.n2c = calc_node_positions(self.root, scaled=self.scaled,\n start=start, end=end)\n sv = sorted([\n [c.y, c.x, n] for n, c in self.n2c.items()\n ])\n self.coords = sv\n\n ## def _path_to_parent(self, node, width=None, color=None):\n ## c = self.n2c[node]; theta1 = c.angle; r = c.depth\n ## M = Path.MOVETO; L = Path.LINETO\n ## pc = self.n2c[node.parent]; theta2 = pc.angle\n ## px1 = math.cos(math.radians(c.angle))*pc.depth\n ## py1 = math.sin(math.radians(c.angle))*pc.depth\n ## verts = [(c.x,c.y),(px1,py1)]; codes = [M,L]\n ## #verts.append((pc.x,pc.y)); codes.append(L)\n ## path = PathPatch(Path(verts, codes), fill=False,\n ## linewidth=width or self.branch_width,\n ## edgecolor=color or self.branch_color)\n ## diam = pc.depth*2\n ## t1, t2 = tuple(sorted((theta1,theta2)))\n ## arc = Arc((0,0), diam, diam, theta1=t1, theta2=t2,\n ## edgecolor=color or self.branch_color,\n ## linewidth=width or self.branch_width)\n ## return [path, arc]\n\n def _path_to_parent(self, node):\n c = self.n2c[node]; theta1 = c.angle; r = c.depth\n M = Path.MOVETO; L = Path.LINETO\n pc = self.n2c[node.parent]; theta2 = pc.angle\n px1 = math.cos(math.radians(c.angle))*pc.depth\n py1 = math.sin(math.radians(c.angle))*pc.depth\n verts = [(c.x,c.y),(px1,py1)]; codes = [M,L]\n t1, t2 = tuple(sorted((theta1,theta2)))\n diam = pc.depth*2\n arc = Arc((0,0), diam, diam, theta1=t1, theta2=t2)\n arcpath = arc.get_path()\n av = arcpath.vertices * pc.depth\n ac = arcpath.codes\n verts.extend(av.tolist())\n codes.extend(ac.tolist())\n return verts, codes\n\n def highlight(self, nodes=None, width=5, color=\"red\"):\n if self.highlightpatch:\n try:\n self.highlightpatch.remove()\n except:\n pass\n if not nodes:\n return\n\n if len(nodes)>1:\n mrca = self.root.mrca(nodes)\n if not mrca:\n return\n else:\n mrca = list(nodes)[0]\n\n M = Path.MOVETO; L = Path.LINETO\n verts = []\n codes = []\n seen = set()\n patches = []\n for node, coords in [ x for x in self.n2c.items() if x[0] in nodes ]:\n x = coords.x; y = coords.y\n p = node.parent\n while p:\n pcoords = self.n2c[p]\n px = pcoords.x; py = pcoords.y\n if node not in seen:\n v, c = self._path_to_parent(node)\n verts.extend(v)\n codes.extend(c)\n seen.add(node)\n if p == mrca or node == mrca:\n break\n node = p\n coords = self.n2c[node]\n x = coords.x; y = coords.y\n p = node.parent\n ## px, py = verts[-1]\n ## verts.append((px, py)); codes.append(M)\n self.highlightpath = Path(verts, codes)\n self.highlightpatch = PathPatch(\n self.highlightpath, fill=False, linewidth=width, edgecolor=color\n )\n self.add_patch(self.highlightpatch)\n ## self.highlight_patches = PatchCollection(patches, match_original=True)\n ## self.add_collection(self.highlight_patches)\n\n\nclass OverviewTree(Tree):\n def __init__(self, *args, **kwargs):\n kwargs[\"leaflabels\"] = False\n kwargs[\"branchlabels\"] = False\n Tree.__init__(self, *args, **kwargs)\n self.xaxis.set_visible(False)\n self.spines[\"bottom\"].set_visible(False)\n self.add_overview_rect()\n\n def set_target(self, target):\n self.target = target\n\n def add_overview_rect(self):\n rect = UpdatingRect([0, 0], 0, 0, facecolor='black', edgecolor='red')\n rect.set_alpha(0.2)\n rect.target = self.target\n rect.set_bounds(*self.target.viewLim.bounds)\n self.zoomrect = rect\n self.add_patch(rect)\n ## if pyplot.isinteractive():\n self.target.callbacks.connect('xlim_changed', rect)\n self.target.callbacks.connect('ylim_changed', rect)\n\n def redraw(self):\n Tree.redraw(self)\n self.add_overview_rect()\n self.figure.canvas.draw_idle()\n\ndef axes_enter(e):\n ax = e.inaxes\n ax._active = True\n\ndef axes_leave(e):\n ax = e.inaxes\n ax._active = False\n\ndef onselect(estart, estop):\n b = estart.button\n ## print b, estart.key\n\ndef onkeypress(e):\n ax = e.inaxes\n k = e.key\n if ax and k == 't':\n ax.home()\n if ax and k == \"down\":\n ax.scroll(0, -0.1)\n ax.figure.canvas.draw_idle()\n if ax and k == \"up\":\n ax.scroll(0, 0.1)\n ax.figure.canvas.draw_idle()\n if ax and k == \"left\":\n ax.scroll(-0.1, 0)\n ax.figure.canvas.draw_idle()\n if ax and k == \"right\":\n ax.scroll(0.1, 0)\n ax.figure.canvas.draw_idle()\n if ax and k and k in '=+':\n ax.zoom(0.1,0.1)\n if ax and k == '-':\n ax.zoom(-0.1,-0.1)\n\ndef ondrag(e):\n ax = e.inaxes\n button = e.button\n if ax and button == 2:\n if not ax.pan_start:\n ax.pan_start = (e.xdata, e.ydata)\n return\n x, y = ax.pan_start\n xdelta = x - e.xdata\n ydelta = y - e.ydata\n x0, x1 = ax.get_xlim()\n xspan = x1-x0\n y0, y1 = ax.get_ylim()\n yspan = y1 - y0\n midx = (x1+x0)*0.5\n midy = (y1+y0)*0.5\n ax.set_xlim(midx+xdelta-xspan*0.5, midx+xdelta+xspan*0.5)\n ax.set_ylim(midy+ydelta-yspan*0.5, midy+ydelta+yspan*0.5)\n ax.adjust_xspine()\n\ndef onbuttonrelease(e):\n ax = e.inaxes\n button = e.button\n if button == 2:\n ## print \"pan end\"\n ax.pan_start = None\n\ndef onpick(e):\n ax = e.mouseevent.inaxes\n if ax:\n ax.picked(e)\n\ndef onscroll(e):\n ax = e.inaxes\n if ax:\n b = e.button\n ## print b\n k = e.key\n if k == None and b ==\"up\":\n ax.zoom(0.1,0.1)\n if k == None and b ==\"down\":\n ax.zoom(-0.1,-0.1)\n if k == \"shift\" and b == \"up\":\n ax.zoom_cxy(0.1, 0, e.xdata, e.ydata)\n if k == \"shift\" and b == \"down\":\n ax.zoom_cxy(-0.1, 0, e.xdata, e.ydata)\n if k == \"control\" and b == \"up\":\n ax.zoom_cxy(0, 0.1, e.xdata, e.ydata)\n if k == \"control\" and b == \"down\":\n ax.zoom_cxy(0, -0.1, e.xdata, e.ydata)\n if k == \"d\" and b == \"up\":\n ax.scroll(0, 0.1)\n if (k == \"d\" and b == \"down\"):\n ax.scroll(0, -0.1)\n if k == \"c\" and b == \"up\":\n ax.scroll(-0.1, 0)\n if k == \"c\" and b == \"down\":\n ax.scroll(0.1, 0)\n try: ax.adjust_xspine()\n except: pass\n ax.figure.canvas.draw_idle()\n\ndef onclick(e):\n ax = e.inaxes\n if ax and e.button==1 and hasattr(ax, \"zoomrect\") and ax.zoomrect:\n # overview clicked; reposition zoomrect\n r = ax.zoomrect\n x = e.xdata\n y = e.ydata\n arr = ax.transData.inverted().transform(r.get_extents())\n xoff = (arr[1][0]-arr[0][0])*0.5\n yoff = (arr[1][1]-arr[0][1])*0.5\n r.target.set_xlim(x-xoff,x+xoff)\n r.target.set_ylim(y-yoff,y+yoff)\n r(r.target)\n ax.figure.canvas.draw_idle()\n\n if ax and e.button==2:\n ## print \"pan start\", (e.xdata, e.ydata)\n ax.pan_start = (e.xdata, e.ydata)\n\n\ndef test_decorate(treeplot):\n import evolve\n data = evolve.brownian(treeplot.root)\n values = data.values()\n vmin = min(values); vmax = max(values)\n norm = mpl_colors.Normalize(vmin, vmax)\n cmap = mpl_colormap.binary\n n2c = treeplot.n2c\n X = numpy.array(\n [ (n2c[n].x, n2c[n].y, v)\n for n, v in data.items() if n in n2c ]\n )\n circles = treeplot.scatter(\n X[:,0], X[:,1], s=200, c=X[:,2], cmap=cmap, norm=norm,\n zorder=100\n )\n\nclass Decorator(object):\n def __init__(self, treeplot):\n self.plot = treeplot\n\nclass VisToggle(object):\n def __init__(self, name, treeplot=None, value=False):\n self.name = name\n self.plot = treeplot\n self.value = value\n\n def __nonzero__(self):\n return self.value\n\n def __repr__(self):\n return \"%s: %s\" % (self.name, self.value)\n\n def redraw(self):\n if self.plot:\n self.plot.redraw()\n\n def toggle(self):\n self.value = not self.value\n self.redraw()\n\n def show(self):\n if self.value == False:\n self.value = True\n self.redraw()\n\n def hide(self):\n if self.value == True:\n self.value = False\n self.redraw()\n\n\nTreePlot = subplot_class_factory(Tree)\nRadialTreePlot = subplot_class_factory(RadialTree)\nOverviewTreePlot = subplot_class_factory(OverviewTree)\n\nif __name__ == \"__main__\":\n import evolve\n root, data = evolve.test_brownian()\n plot_continuous(root, data, name=\"Brownian\", mid=0.0)\n"}} -{"repo": "ewhauser/zookeeper", "pr_number": 37, "title": "Updated .Net library to .netstandard2.0", "state": "closed", "merged_at": null, "additions": 97, "deletions": 31594, "files_changed": ["src/dotnet/ZooKeeperNet.Recipes.Tests/Properties/AssemblyInfo.cs", "src/dotnet/ZooKeeperNet.Recipes/Properties/AssemblyInfo.cs", "src/dotnet/ZooKeeperNet.Tests/AbstractZooKeeperTests.cs", "src/dotnet/ZooKeeperNet.Tests/Properties/AssemblyInfo.cs", "src/dotnet/ZooKeeperNet.Tests/RecoveryTest.cs", "src/dotnet/ZooKeeperNet/Properties/AssemblyInfo.cs"], "files_before": {"src/dotnet/ZooKeeperNet.Recipes.Tests/Properties/AssemblyInfo.cs": "\ufeffusing System.Reflection;\r\nusing System.Runtime.CompilerServices;\r\nusing System.Runtime.InteropServices;\r\n\r\n// General Information about an assembly is controlled through the following \r\n// set of attributes. Change these attribute values to modify the information\r\n// associated with an assembly.\r\n[assembly: AssemblyTitle(\"SharpKeeperRecipes.Tests\")]\r\n[assembly: AssemblyDescription(\"\")]\r\n[assembly: AssemblyConfiguration(\"\")]\r\n[assembly: AssemblyCompany(\"Microsoft\")]\r\n[assembly: AssemblyProduct(\"SharpKeeperRecipes.Tests\")]\r\n[assembly: AssemblyCopyright(\"Copyright \u00a9 Microsoft 2010\")]\r\n[assembly: AssemblyTrademark(\"\")]\r\n[assembly: AssemblyCulture(\"\")]\r\n\r\n// Setting ComVisible to false makes the types in this assembly not visible \r\n// to COM components. If you need to access a type in this assembly from \r\n// COM, set the ComVisible attribute to true on that type.\r\n[assembly: ComVisible(false)]\r\n\r\n// The following GUID is for the ID of the typelib if this project is exposed to COM\r\n[assembly: Guid(\"a1b5ade2-64f4-46ee-b8eb-067c351afb45\")]\r\n\r\n// Version information for an assembly consists of the following four values:\r\n//\r\n// Major Version\r\n// Minor Version \r\n// Build Number\r\n// Revision\r\n//\r\n// You can specify all the values or you can default the Build and Revision Numbers \r\n// by using the '*' as shown below:\r\n// [assembly: AssemblyVersion(\"1.0.*\")]\r\n[assembly: AssemblyVersion(\"1.0.0.0\")]\r\n[assembly: AssemblyFileVersion(\"1.0.0.0\")]\r\n", "src/dotnet/ZooKeeperNet.Recipes/Properties/AssemblyInfo.cs": "\ufeffusing System.Reflection;\r\nusing System.Runtime.CompilerServices;\r\nusing System.Runtime.InteropServices;\r\n\r\n// General Information about an assembly is controlled through the following \r\n// set of attributes. Change these attribute values to modify the information\r\n// associated with an assembly.\r\n[assembly: AssemblyTitle(\"ZooKeeperNet.Recipes\")]\r\n[assembly: AssemblyConfiguration(\"\")]\r\n[assembly: AssemblyCulture(\"\")]\r\n// The following GUID is for the ID of the typelib if this project is exposed to COM\r\n[assembly: Guid(\"2fa24a05-e792-49c5-908a-9ae26ecb6401\")]", "src/dotnet/ZooKeeperNet.Tests/AbstractZooKeeperTests.cs": "/*\r\n * Licensed to the Apache Software Foundation (ASF) under one or more\r\n * contributor license agreements. See the NOTICE file distributed with\r\n * this work for additional information regarding copyright ownership.\r\n * The ASF licenses this file to You under the Apache License, Version 2.0\r\n * (the \"License\"); you may not use this file except in compliance with\r\n * the License. You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n *\r\n */\r\nnamespace ZooKeeperNet.Tests\r\n{\r\n using System;\r\n using System.Runtime.CompilerServices;\r\n using System.Threading;\r\n using log4net.Config;\r\n\r\n public abstract class AbstractZooKeeperTests\r\n {\r\n static AbstractZooKeeperTests()\r\n {\r\n XmlConfigurator.Configure(); \r\n }\r\n\r\n protected static readonly TimeSpan CONNECTION_TIMEOUT = new TimeSpan(0, 0, 0, 0, 10000);\r\n\r\n protected virtual ZooKeeper CreateClient()\r\n {\r\n CountdownWatcher watcher = new CountdownWatcher();\r\n return new ZooKeeper(\"127.0.0.1:2181\", new TimeSpan(0, 0, 0, 10000), watcher);\r\n }\r\n\r\n protected virtual ZooKeeper CreateClient(string node)\r\n {\r\n CountdownWatcher watcher = new CountdownWatcher();\r\n return new ZooKeeper(\"127.0.0.1:2181\" + node, new TimeSpan(0, 0, 0, 10000), watcher);\r\n }\r\n\r\n protected ZooKeeper CreateClient(IWatcher watcher)\r\n {\r\n return new ZooKeeper(\"127.0.0.1:2181\", new TimeSpan(0, 0, 0, 10000), watcher);\r\n }\r\n\r\n protected ZooKeeper CreateClientWithAddress(string address)\r\n {\r\n CountdownWatcher watcher = new CountdownWatcher();\r\n return new ZooKeeper(address, new TimeSpan(0, 0, 0, 10000), watcher);\r\n }\r\n\r\n public class CountdownWatcher : IWatcher\r\n {\r\n readonly ManualResetEvent resetEvent = new ManualResetEvent(false);\r\n private static readonly object sync = new object();\r\n\r\n volatile bool connected;\r\n\r\n public CountdownWatcher()\r\n {\r\n Reset();\r\n }\r\n\r\n [MethodImpl(MethodImplOptions.Synchronized)]\r\n public void Reset()\r\n {\r\n resetEvent.Set();\r\n connected = false;\r\n }\r\n\r\n [MethodImpl(MethodImplOptions.Synchronized)]\r\n public virtual void Process(WatchedEvent @event)\r\n {\r\n if (@event.State == KeeperState.SyncConnected)\r\n {\r\n connected = true;\r\n lock (sync)\r\n {\r\n Monitor.PulseAll(sync);\r\n }\r\n resetEvent.Set();\r\n }\r\n else\r\n {\r\n connected = false;\r\n lock (sync)\r\n {\r\n Monitor.PulseAll(sync);\r\n }\r\n }\r\n }\r\n\r\n [MethodImpl(MethodImplOptions.Synchronized)]\r\n bool IsConnected()\r\n {\r\n return connected;\r\n }\r\n\r\n [MethodImpl(MethodImplOptions.Synchronized)]\r\n void waitForConnected(TimeSpan timeout)\r\n {\r\n DateTime expire = DateTime.UtcNow + timeout;\r\n TimeSpan left = timeout;\r\n while (!connected && left.TotalMilliseconds > 0)\r\n {\r\n lock (sync)\r\n {\r\n Monitor.TryEnter(sync, left);\r\n }\r\n left = expire - DateTime.UtcNow;\r\n }\r\n if (!connected)\r\n {\r\n throw new TimeoutException(\"Did not connect\");\r\n\r\n }\r\n }\r\n\r\n void waitForDisconnected(TimeSpan timeout)\r\n {\r\n DateTime expire = DateTime.UtcNow + timeout;\r\n TimeSpan left = timeout;\r\n while (connected && left.TotalMilliseconds > 0)\r\n {\r\n lock (sync)\r\n {\r\n Monitor.TryEnter(sync, left);\r\n }\r\n left = expire - DateTime.UtcNow;\r\n }\r\n if (connected)\r\n {\r\n throw new TimeoutException(\"Did not disconnect\");\r\n }\r\n }\r\n }\r\n\r\n }\r\n}\r\n", "src/dotnet/ZooKeeperNet.Tests/Properties/AssemblyInfo.cs": "/*\r\n * Licensed to the Apache Software Foundation (ASF) under one or more\r\n * contributor license agreements. See the NOTICE file distributed with\r\n * this work for additional information regarding copyright ownership.\r\n * The ASF licenses this file to You under the Apache License, Version 2.0\r\n * (the \"License\"); you may not use this file except in compliance with\r\n * the License. You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n *\r\n */\r\n\ufeffusing System.Reflection;\r\nusing System.Runtime.CompilerServices;\r\nusing System.Runtime.InteropServices;\r\n\r\n// General Information about an assembly is controlled through the following \r\n// set of attributes. Change these attribute values to modify the information\r\n// associated with an assembly.\r\n[assembly: AssemblyTitle(\"SharpKeeper.Tests\")]\r\n[assembly: AssemblyDescription(\"\")]\r\n[assembly: AssemblyConfiguration(\"\")]\r\n[assembly: AssemblyCompany(\"Microsoft\")]\r\n[assembly: AssemblyProduct(\"SharpKeeper.Tests\")]\r\n[assembly: AssemblyCopyright(\"Copyright \u00a9 Microsoft 2010\")]\r\n[assembly: AssemblyTrademark(\"\")]\r\n[assembly: AssemblyCulture(\"\")]\r\n\r\n// Setting ComVisible to false makes the types in this assembly not visible \r\n// to COM components. If you need to access a type in this assembly from \r\n// COM, set the ComVisible attribute to true on that type.\r\n[assembly: ComVisible(false)]\r\n\r\n// The following GUID is for the ID of the typelib if this project is exposed to COM\r\n[assembly: Guid(\"0755fc77-447a-4817-b43f-82ba61d1c2a6\")]\r\n\r\n// Version information for an assembly consists of the following four values:\r\n//\r\n// Major Version\r\n// Minor Version \r\n// Build Number\r\n// Revision\r\n//\r\n// You can specify all the values or you can default the Build and Revision Numbers \r\n// by using the '*' as shown below:\r\n// [assembly: AssemblyVersion(\"1.0.*\")]\r\n[assembly: AssemblyVersion(\"1.0.0.0\")]\r\n[assembly: AssemblyFileVersion(\"1.0.0.0\")]\r\n", "src/dotnet/ZooKeeperNet.Tests/RecoveryTest.cs": "/**\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\r\nusing System;\r\nusing System.Threading;\r\nusing log4net;\r\nusing NUnit.Framework;\r\nusing Org.Apache.Zookeeper.Data;\r\n\r\nnamespace ZooKeeperNet.Tests\r\n{\r\n public class RecoveryTest : AbstractZooKeeperTests, IWatcher\r\n {\r\n private readonly ILog LOG = LogManager.GetLogger(typeof(RecoveryTest));\r\n private int setDataCount;\r\n private int processCount;\r\n private readonly string testPath = \"/unittests/recoverytests/\" + Guid.NewGuid();\r\n\r\n [Test, Explicit]\r\n public void ReconnectsWhenDisconnected()\r\n {\r\n using (CancellationTokenSource token = new CancellationTokenSource())\r\n {\r\n Thread thread = new Thread(Run)\r\n {\r\n IsBackground = true,\r\n Name = \"RecoveryTest.Run\"\r\n };\r\n thread.Start(token.Token);\r\n Thread.Sleep(15*1000);\r\n LOG.Error(\"STOP ZK!!!! Count: \" + processCount);\r\n Thread.Sleep(20*1000);\r\n LOG.Error(\"START ZK!!! Count: \" + processCount);\r\n Thread.Sleep(30*1000);\r\n LOG.Error(\"Stopping ZK client.\");\r\n token.Cancel();\r\n LOG.Error(\"Waiting for thread to stop...\" + processCount);\r\n thread.Join();\r\n if (thread.IsAlive)\r\n Assert.Fail(\"Thread still alive\");\r\n Assert.AreEqual(setDataCount, processCount, \"setDataCount == processCount\");\r\n LOG.Error(\"Finished:\" + setDataCount + \":\" + processCount);\r\n }\r\n }\r\n\r\n private void Run(object sender)\r\n {\r\n try\r\n {\r\n CancellationToken token = (CancellationToken)sender;\r\n using (ZooKeeper zooKeeper = CreateClient(this))\r\n {\r\n Stat stat = new Stat();\r\n if (zooKeeper.Exists(\"/unittests/recoverytests\", false) == null)\r\n {\r\n zooKeeper.Create(\"/unittests\", new byte[] {0}, Ids.OPEN_ACL_UNSAFE, CreateMode.Persistent);\r\n zooKeeper.Create(\"/unittests/recoverytests\", new byte[] {0}, Ids.OPEN_ACL_UNSAFE, CreateMode.Persistent);\r\n }\r\n if (zooKeeper.Exists(testPath, false) == null)\r\n { \r\n zooKeeper.Create(testPath, new byte[] {0}, Ids.OPEN_ACL_UNSAFE, CreateMode.Persistent);\r\n }\r\n while (zooKeeper.State.IsAlive() && !token.IsCancellationRequested)\r\n {\r\n try\r\n {\r\n zooKeeper.GetData(testPath, true, stat);\r\n zooKeeper.SetData(testPath, Guid.NewGuid().ToByteArray(), -1);\r\n setDataCount++;\r\n }\r\n catch(KeeperException ke)\r\n {\r\n LOG.Error(ke);\r\n }\r\n }\r\n LOG.Error(\"Waiting for dispose.\");\r\n }\r\n }\r\n catch(Exception ex)\r\n {\r\n LOG.Error(ex);\r\n }\r\n }\r\n\r\n public void Process(WatchedEvent @event)\r\n {\r\n LOG.Debug(@event);\r\n if (@event.Type == EventType.NodeCreated || @event.Type == EventType.NodeDataChanged)\r\n {\r\n Interlocked.Increment(ref processCount);\r\n }\r\n }\r\n }\r\n}", "src/dotnet/ZooKeeperNet/Properties/AssemblyInfo.cs": "/*\r\n * Licensed to the Apache Software Foundation (ASF) under one or more\r\n * contributor license agreements. See the NOTICE file distributed with\r\n * this work for additional information regarding copyright ownership.\r\n * The ASF licenses this file to You under the Apache License, Version 2.0\r\n * (the \"License\"); you may not use this file except in compliance with\r\n * the License. You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n *\r\n */\r\nusing System.Reflection;\r\nusing System.Runtime.InteropServices;\r\n\r\n// General Information about an assembly is controlled through the following \r\n// set of attributes. Change these attribute values to modify the information\r\n// associated with an assembly.\r\n[assembly: AssemblyTitle(\"ZooKeeperNet\")]\r\n[assembly: AssemblyConfiguration(\"\")]\r\n[assembly: AssemblyCulture(\"\")]\r\n\r\n// The following GUID is for the ID of the typelib if this project is exposed to COM\r\n[assembly: Guid(\"0ee34fd6-195e-4912-906a-44062ecaffad\")]"}, "files_after": {"src/dotnet/ZooKeeperNet.Tests/AbstractZooKeeperTests.cs": "/*\r\n * Licensed to the Apache Software Foundation (ASF) under one or more\r\n * contributor license agreements. See the NOTICE file distributed with\r\n * this work for additional information regarding copyright ownership.\r\n * The ASF licenses this file to You under the Apache License, Version 2.0\r\n * (the \"License\"); you may not use this file except in compliance with\r\n * the License. You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n *\r\n */\r\n\r\nusing System.IO;\r\nusing System.Xml;\r\n\r\nnamespace ZooKeeperNet.Tests\r\n{\r\n using System;\r\n using System.Runtime.CompilerServices;\r\n using System.Threading;\r\n\r\n public abstract class AbstractZooKeeperTests\r\n {\r\n static AbstractZooKeeperTests()\r\n {\r\n XmlDocument log4netConfig = new XmlDocument();\r\n log4netConfig.Load(File.OpenRead(\"log4net.xml\"));\r\n var repository = log4net.LogManager.CreateRepository(\"tests\");\r\n log4net.Config.XmlConfigurator.Configure(repository, log4netConfig[\"log4net\"]);\r\n }\r\n\r\n protected static readonly TimeSpan CONNECTION_TIMEOUT = new TimeSpan(0, 0, 0, 0, 10000);\r\n\r\n protected virtual ZooKeeper CreateClient()\r\n {\r\n CountdownWatcher watcher = new CountdownWatcher();\r\n return new ZooKeeper(\"127.0.0.1:2181\", new TimeSpan(0, 0, 0, 10000), watcher);\r\n }\r\n\r\n protected virtual ZooKeeper CreateClient(string node)\r\n {\r\n CountdownWatcher watcher = new CountdownWatcher();\r\n return new ZooKeeper(\"127.0.0.1:2181\" + node, new TimeSpan(0, 0, 0, 10000), watcher);\r\n }\r\n\r\n protected ZooKeeper CreateClient(IWatcher watcher)\r\n {\r\n return new ZooKeeper(\"127.0.0.1:2181\", new TimeSpan(0, 0, 0, 10000), watcher);\r\n }\r\n\r\n protected ZooKeeper CreateClientWithAddress(string address)\r\n {\r\n CountdownWatcher watcher = new CountdownWatcher();\r\n return new ZooKeeper(address, new TimeSpan(0, 0, 0, 10000), watcher);\r\n }\r\n\r\n public class CountdownWatcher : IWatcher\r\n {\r\n readonly ManualResetEvent resetEvent = new ManualResetEvent(false);\r\n private static readonly object sync = new object();\r\n\r\n volatile bool connected;\r\n\r\n public CountdownWatcher()\r\n {\r\n Reset();\r\n }\r\n\r\n [MethodImpl(MethodImplOptions.Synchronized)]\r\n public void Reset()\r\n {\r\n resetEvent.Set();\r\n connected = false;\r\n }\r\n\r\n [MethodImpl(MethodImplOptions.Synchronized)]\r\n public virtual void Process(WatchedEvent @event)\r\n {\r\n if (@event.State == KeeperState.SyncConnected)\r\n {\r\n connected = true;\r\n lock (sync)\r\n {\r\n Monitor.PulseAll(sync);\r\n }\r\n resetEvent.Set();\r\n }\r\n else\r\n {\r\n connected = false;\r\n lock (sync)\r\n {\r\n Monitor.PulseAll(sync);\r\n }\r\n }\r\n }\r\n\r\n [MethodImpl(MethodImplOptions.Synchronized)]\r\n bool IsConnected()\r\n {\r\n return connected;\r\n }\r\n\r\n [MethodImpl(MethodImplOptions.Synchronized)]\r\n void waitForConnected(TimeSpan timeout)\r\n {\r\n DateTime expire = DateTime.UtcNow + timeout;\r\n TimeSpan left = timeout;\r\n while (!connected && left.TotalMilliseconds > 0)\r\n {\r\n lock (sync)\r\n {\r\n Monitor.TryEnter(sync, left);\r\n }\r\n left = expire - DateTime.UtcNow;\r\n }\r\n if (!connected)\r\n {\r\n throw new TimeoutException(\"Did not connect\");\r\n\r\n }\r\n }\r\n\r\n void waitForDisconnected(TimeSpan timeout)\r\n {\r\n DateTime expire = DateTime.UtcNow + timeout;\r\n TimeSpan left = timeout;\r\n while (connected && left.TotalMilliseconds > 0)\r\n {\r\n lock (sync)\r\n {\r\n Monitor.TryEnter(sync, left);\r\n }\r\n left = expire - DateTime.UtcNow;\r\n }\r\n if (connected)\r\n {\r\n throw new TimeoutException(\"Did not disconnect\");\r\n }\r\n }\r\n }\r\n\r\n }\r\n}\r\n", "src/dotnet/ZooKeeperNet.Tests/RecoveryTest.cs": "/**\r\n * Licensed to the Apache Software Foundation (ASF) under one\r\n * or more contributor license agreements. See the NOTICE file\r\n * distributed with this work for additional information\r\n * regarding copyright ownership. The ASF licenses this file\r\n * to you under the Apache License, Version 2.0 (the\r\n * \"License\"); you may not use this file except in compliance\r\n * with the License. You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nusing System;\r\nusing System.Threading;\r\nusing log4net;\r\nusing NUnit.Framework;\r\nusing Org.Apache.Zookeeper.Data;\r\n\r\nnamespace ZooKeeperNet.Tests\r\n{\r\n public class RecoveryTest : AbstractZooKeeperTests, IWatcher\r\n {\r\n private readonly ILog LOG = LogManager.GetLogger(typeof(RecoveryTest));\r\n private int setDataCount;\r\n private int processCount;\r\n private readonly string testPath = \"/unittests/recoverytests/\" + Guid.NewGuid();\r\n\r\n [Test, Explicit]\r\n public void ReconnectsWhenDisconnected()\r\n {\r\n using (\r\n CancellationTokenSource token = new CancellationTokenSource())\r\n {\r\n Thread thread = new Thread(Run)\r\n {\r\n IsBackground = true,\r\n Name = \"RecoveryTest.Run\"\r\n };\r\n thread.Start(token.Token);\r\n Thread.Sleep(15*1000);\r\n LOG.Error(\"STOP ZK!!!! Count: \" + processCount);\r\n Thread.Sleep(20*1000);\r\n LOG.Error(\"START ZK!!! Count: \" + processCount);\r\n Thread.Sleep(30*1000);\r\n LOG.Error(\"Stopping ZK client.\");\r\n token.Cancel();\r\n LOG.Error(\"Waiting for thread to stop...\" + processCount);\r\n thread.Join();\r\n if (thread.IsAlive)\r\n Assert.Fail(\"Thread still alive\");\r\n Assert.AreEqual(setDataCount, processCount, \"setDataCount == processCount\");\r\n LOG.Error(\"Finished:\" + setDataCount + \":\" + processCount);\r\n }\r\n }\r\n\r\n private void Run(object sender)\r\n {\r\n try\r\n {\r\n CancellationToken token = (CancellationToken)sender;\r\n using (ZooKeeper zooKeeper = CreateClient(this))\r\n {\r\n Stat stat = new Stat();\r\n if (zooKeeper.Exists(\"/unittests/recoverytests\", false) == null)\r\n {\r\n zooKeeper.Create(\"/unittests\", new byte[] {0}, Ids.OPEN_ACL_UNSAFE, CreateMode.Persistent);\r\n zooKeeper.Create(\"/unittests/recoverytests\", new byte[] {0}, Ids.OPEN_ACL_UNSAFE, CreateMode.Persistent);\r\n }\r\n if (zooKeeper.Exists(testPath, false) == null)\r\n { \r\n zooKeeper.Create(testPath, new byte[] {0}, Ids.OPEN_ACL_UNSAFE, CreateMode.Persistent);\r\n }\r\n while (zooKeeper.State.IsAlive() && !token.IsCancellationRequested)\r\n {\r\n try\r\n {\r\n zooKeeper.GetData(testPath, true, stat);\r\n zooKeeper.SetData(testPath, Guid.NewGuid().ToByteArray(), -1);\r\n setDataCount++;\r\n }\r\n catch(KeeperException ke)\r\n {\r\n LOG.Error(ke);\r\n }\r\n }\r\n LOG.Error(\"Waiting for dispose.\");\r\n }\r\n }\r\n catch(Exception ex)\r\n {\r\n LOG.Error(ex);\r\n }\r\n }\r\n\r\n public void Process(WatchedEvent @event)\r\n {\r\n LOG.Debug(@event);\r\n if (@event.Type == EventType.NodeCreated || @event.Type == EventType.NodeDataChanged)\r\n {\r\n Interlocked.Increment(ref processCount);\r\n }\r\n }\r\n }\r\n}"}} -{"repo": "jedie/django-tools", "pr_number": 99, "title": "Dev", "state": "closed", "merged_at": "2024-08-25T12:57:27Z", "additions": 1243, "deletions": 561, "files_changed": ["django_tools/__init__.py", "django_tools_project/tests/__init__.py", "manage.py"], "files_before": {"django_tools/__init__.py": "\"\"\"\n \"django-tools\n miscellaneous tools for Django based projects\n\"\"\"\n\n__version__ = '0.56.0'\n__author__ = 'Jens Diemer '\n", "django_tools_project/tests/__init__.py": "import os\nimport unittest.util\nfrom pathlib import Path\n\nfrom bx_py_utils.test_utils.deny_requests import deny_any_real_request\n\n\ndef pre_configure_tests() -> None:\n print(f'Configure unittests via \"load_tests Protocol\" from {Path(__file__).relative_to(Path.cwd())}')\n\n # Hacky way to display more \"assert\"-Context in failing tests:\n _MIN_MAX_DIFF = unittest.util._MAX_LENGTH - unittest.util._MIN_DIFF_LEN\n unittest.util._MAX_LENGTH = int(os.environ.get('UNITTEST_MAX_LENGTH', 300))\n unittest.util._MIN_DIFF_LEN = unittest.util._MAX_LENGTH - _MIN_MAX_DIFF\n\n # Deny any request via docket/urllib3 because tests they should mock all requests:\n deny_any_real_request()\n\n\ndef load_tests(loader, tests, pattern):\n \"\"\"\n Use unittest \"load_tests Protocol\" as a hook to setup test environment before running tests.\n https://docs.python.org/3/library/unittest.html#load-tests-protocol\n \"\"\"\n pre_configure_tests()\n return loader.discover(start_dir=Path(__file__).parent, pattern=pattern)\n", "manage.py": "#!/usr/bin/env python3\n\n\"\"\"\n bootstrap CLI\n ~~~~~~~~~~~~~\n\n Just call this file, and the magic happens ;)\n\"\"\"\n\nimport hashlib\nimport shlex\nimport signal\nimport subprocess\nimport sys\nimport venv\nfrom pathlib import Path\n\n\ndef print_no_pip_error():\n print('Error: Pip not available!')\n print('Hint: \"apt-get install python3-venv\"\\n')\n\n\ntry:\n from ensurepip import version\nexcept ModuleNotFoundError as err:\n print(err)\n print('-' * 100)\n print_no_pip_error()\n raise\nelse:\n if not version():\n print_no_pip_error()\n sys.exit(-1)\n\n\nassert sys.version_info >= (3, 10), f'Python version {sys.version_info} is too old!'\n\n\nif sys.platform == 'win32': # wtf\n # Files under Windows, e.g.: .../.venv/Scripts/python.exe\n BIN_NAME = 'Scripts'\n FILE_EXT = '.exe'\nelse:\n # Files under Linux/Mac and all other than Windows, e.g.: .../.venv/bin/python\n BIN_NAME = 'bin'\n FILE_EXT = ''\n\nBASE_PATH = Path(__file__).parent\nVENV_PATH = BASE_PATH / '.venv'\nBIN_PATH = VENV_PATH / BIN_NAME\nPYTHON_PATH = BIN_PATH / f'python{FILE_EXT}'\nPIP_PATH = BIN_PATH / f'pip{FILE_EXT}'\nPIP_SYNC_PATH = BIN_PATH / f'pip-sync{FILE_EXT}'\n\nDEP_LOCK_PATH = BASE_PATH / 'requirements.dev.txt'\nDEP_HASH_PATH = VENV_PATH / '.dep_hash'\n\n# script file defined in pyproject.toml as [console_scripts]\n# (Under Windows: \".exe\" not added!)\nPROJECT_SHELL_SCRIPT = BIN_PATH / 'django_tools_project'\n\n\ndef get_dep_hash():\n \"\"\"Get SHA512 hash from lock file content.\"\"\"\n return hashlib.sha512(DEP_LOCK_PATH.read_bytes()).hexdigest()\n\n\ndef store_dep_hash():\n \"\"\"Generate .venv/.dep_hash\"\"\"\n DEP_HASH_PATH.write_text(get_dep_hash())\n\n\ndef venv_up2date():\n \"\"\"Is existing .venv is up-to-date?\"\"\"\n if DEP_HASH_PATH.is_file():\n return DEP_HASH_PATH.read_text() == get_dep_hash()\n return False\n\n\ndef verbose_check_call(*popen_args):\n print(f'\\n+ {shlex.join(str(arg) for arg in popen_args)}\\n')\n return subprocess.check_call(popen_args)\n\n\ndef noop_sigint_handler(signal_num, frame):\n \"\"\"\n Don't exist cmd2 shell on \"Interrupt from keyboard\"\n e.g.: User stops the dev. server by CONTROL-C\n \"\"\"\n\n\ndef main(argv):\n assert DEP_LOCK_PATH.is_file(), f'File not found: \"{DEP_LOCK_PATH}\" !'\n\n # Create virtual env in \".venv/\":\n if not PYTHON_PATH.is_file():\n print(f'Create virtual env here: {VENV_PATH.absolute()}')\n builder = venv.EnvBuilder(symlinks=True, upgrade=True, with_pip=True)\n builder.create(env_dir=VENV_PATH)\n\n if not PROJECT_SHELL_SCRIPT.is_file() or not venv_up2date():\n # Update pip\n verbose_check_call(PYTHON_PATH, '-m', 'pip', 'install', '-U', 'pip')\n\n # Install pip-tools\n verbose_check_call(PYTHON_PATH, '-m', 'pip', 'install', '-U', 'pip-tools')\n\n # install requirements via \"pip-sync\"\n verbose_check_call(PIP_SYNC_PATH, str(DEP_LOCK_PATH))\n\n # install project\n verbose_check_call(PIP_PATH, 'install', '--no-deps', '-e', '.')\n store_dep_hash()\n\n signal.signal(signal.SIGINT, noop_sigint_handler) # ignore \"Interrupt from keyboard\" signals\n\n # Call our entry point CLI:\n try:\n verbose_check_call(PROJECT_SHELL_SCRIPT, *argv[1:])\n except subprocess.CalledProcessError as err:\n sys.exit(err.returncode)\n\n\nif __name__ == '__main__':\n main(sys.argv)\n"}, "files_after": {"django_tools/__init__.py": "\"\"\"\n \"django-tools\n miscellaneous tools for Django based projects\n\"\"\"\n\n__version__ = '0.56.1'\n__author__ = 'Jens Diemer '\n", "django_tools_project/tests/__init__.py": "import os\nimport unittest.util\nfrom pathlib import Path\n\nfrom bx_py_utils.test_utils.deny_requests import deny_any_real_request\nfrom typeguard import install_import_hook\n\n\n# Check type annotations via typeguard in all tests:\ninstall_import_hook(packages=('django_tools', 'django_tools_project'))\n\n\ndef pre_configure_tests() -> None:\n print(f'Configure unittests via \"load_tests Protocol\" from {Path(__file__).relative_to(Path.cwd())}')\n\n # Hacky way to display more \"assert\"-Context in failing tests:\n _MIN_MAX_DIFF = unittest.util._MAX_LENGTH - unittest.util._MIN_DIFF_LEN\n unittest.util._MAX_LENGTH = int(os.environ.get('UNITTEST_MAX_LENGTH', 600))\n unittest.util._MIN_DIFF_LEN = unittest.util._MAX_LENGTH - _MIN_MAX_DIFF\n\n # Deny any request via docket/urllib3 because tests they should mock all requests:\n deny_any_real_request()\n\n\ndef load_tests(loader, tests, pattern):\n \"\"\"\n Use unittest \"load_tests Protocol\" as a hook to setup test environment before running tests.\n https://docs.python.org/3/library/unittest.html#load-tests-protocol\n \"\"\"\n pre_configure_tests()\n return loader.discover(start_dir=Path(__file__).parent, pattern=pattern)\n", "manage.py": "#!/usr/bin/env python3\n\n\"\"\"\n bootstrap CLI\n ~~~~~~~~~~~~~\n\n Just call this file, and the magic happens ;)\n\"\"\"\n\nimport hashlib\nimport shlex\nimport signal\nimport subprocess\nimport sys\nimport venv\nfrom pathlib import Path\n\n\ndef print_no_pip_error():\n print('Error: Pip not available!')\n print('Hint: \"apt-get install python3-venv\"\\n')\n\n\ntry:\n from ensurepip import version\nexcept ModuleNotFoundError as err:\n print(err)\n print('-' * 100)\n print_no_pip_error()\n raise\nelse:\n if not version():\n print_no_pip_error()\n sys.exit(-1)\n\n\nassert sys.version_info >= (3, 10), f'Python version {sys.version_info} is too old!'\n\n\nif sys.platform == 'win32': # wtf\n # Files under Windows, e.g.: .../.venv/Scripts/python.exe\n BIN_NAME = 'Scripts'\n FILE_EXT = '.exe'\nelse:\n # Files under Linux/Mac and all other than Windows, e.g.: .../.venv/bin/python\n BIN_NAME = 'bin'\n FILE_EXT = ''\n\nBASE_PATH = Path(__file__).parent\nVENV_PATH = BASE_PATH / '.venv'\nBIN_PATH = VENV_PATH / BIN_NAME\nPYTHON_PATH = BIN_PATH / f'python3{FILE_EXT}'\nPIP_PATH = BIN_PATH / f'pip{FILE_EXT}'\nPIP_SYNC_PATH = BIN_PATH / f'pip-sync{FILE_EXT}'\n\nDEP_LOCK_PATH = BASE_PATH / 'requirements.dev.txt'\nDEP_HASH_PATH = VENV_PATH / '.dep_hash'\n\n# script file defined in pyproject.toml as [console_scripts]\n# (Under Windows: \".exe\" not added!)\nPROJECT_SHELL_SCRIPT = BIN_PATH / 'django_tools_project'\n\n\ndef get_dep_hash():\n \"\"\"Get SHA512 hash from lock file content.\"\"\"\n return hashlib.sha512(DEP_LOCK_PATH.read_bytes()).hexdigest()\n\n\ndef store_dep_hash():\n \"\"\"Generate .venv/.dep_hash\"\"\"\n DEP_HASH_PATH.write_text(get_dep_hash())\n\n\ndef venv_up2date():\n \"\"\"Is existing .venv is up-to-date?\"\"\"\n if DEP_HASH_PATH.is_file():\n return DEP_HASH_PATH.read_text() == get_dep_hash()\n return False\n\n\ndef verbose_check_call(*popen_args):\n print(f'\\n+ {shlex.join(str(arg) for arg in popen_args)}\\n')\n return subprocess.check_call(popen_args)\n\n\ndef noop_sigint_handler(signal_num, frame):\n \"\"\"\n Don't exist cmd2 shell on \"Interrupt from keyboard\"\n e.g.: User stops the dev. server by CONTROL-C\n \"\"\"\n\n\ndef main(argv):\n assert DEP_LOCK_PATH.is_file(), f'File not found: \"{DEP_LOCK_PATH}\" !'\n\n # Create virtual env in \".venv/\":\n if not PYTHON_PATH.is_file():\n print(f'Create virtual env here: {VENV_PATH.absolute()}')\n builder = venv.EnvBuilder(symlinks=True, upgrade=True, with_pip=True)\n builder.create(env_dir=VENV_PATH)\n\n if not PROJECT_SHELL_SCRIPT.is_file() or not venv_up2date():\n # Update pip\n verbose_check_call(PYTHON_PATH, '-m', 'pip', 'install', '-U', 'pip')\n\n # Install pip-tools\n verbose_check_call(PYTHON_PATH, '-m', 'pip', 'install', '-U', 'pip-tools')\n\n # install requirements via \"pip-sync\"\n verbose_check_call(PIP_SYNC_PATH, str(DEP_LOCK_PATH))\n\n # install project\n verbose_check_call(PIP_PATH, 'install', '--no-deps', '-e', '.')\n store_dep_hash()\n\n # Activate git pre-commit hooks:\n verbose_check_call(PYTHON_PATH, '-m', 'pre_commit', 'install')\n verbose_check_call(PYTHON_PATH, '-m', 'pre_commit', 'autoupdate')\n\n signal.signal(signal.SIGINT, noop_sigint_handler) # ignore \"Interrupt from keyboard\" signals\n\n # Call our entry point CLI:\n try:\n verbose_check_call(PROJECT_SHELL_SCRIPT, *argv[1:])\n except subprocess.CalledProcessError as err:\n sys.exit(err.returncode)\n\n\nif __name__ == '__main__':\n main(sys.argv)\n"}} -{"repo": "jmax/bookr", "pr_number": 2, "title": "Modificadiones solicitadas", "state": "closed", "merged_at": null, "additions": 7, "deletions": 1, "files_changed": ["public/stylesheets/customstyles.css"], "files_before": {}, "files_after": {"public/stylesheets/customstyles.css": "//add here your custom styles"}} -{"repo": "hmason/hackMatch", "pr_number": 1, "title": "hmason", "state": "open", "merged_at": null, "additions": 111, "deletions": 89, "files_changed": ["download_stopwords.py", "hackmatch.py"], "files_before": {"hackmatch.py": "#!/usr/bin/env python\n# encoding: utf-8\n# recognize.\n\"\"\"\nhackmatch.py\n\nCreated by Hilary Mason, Chris Wiggins, and Evan Korth.\nCopyright (c) 2010 hackNY. All rights reserved.\n\"\"\"\n\nimport sys, os\nimport csv\nimport string\nfrom collections import defaultdict\nfrom optparse import OptionParser\nfrom nltk.tokenize import *\nfrom nltk.corpus import stopwords\nfrom hcluster import jaccard\n\n# startups: Name,E-mail,Company,In NYC,Funding,Site,Blog,Twitter,Num Employees,Environment,Project,Skills,Misc\n# students: Student Name,e-mail,University,Major,Degree,Graduation Date,Site,Blog,Twitter,Facebook,Project,Skills,Misc\n\nclass HackMatch(object):\n DEBUG = False\n BOW_FIELDS = ['Environment', 'Project', 'Skills', 'Misc']\n COMPLETENESS_THRESHOLD = 4 # num of words necessary to match\n \n def __init__(self, student_file, startup_file, num_matches=3, distance=jaccard):\n self.stopwords = self.get_stopwords()\n self.distance = distance\n \n student_data = self.parseCSV(student_file)\n startup_data = self.parseCSV(startup_file)\n \n doc_words = self.defineFeatures([student_data, startup_data], self.BOW_FIELDS)\n\n # matches = self.doRanking(student_data, startup_data, doc_words, self.BOW_FIELDS, base_name_field='Student Name', match_name_field='Company')\n matches = self.doRanking(startup_data, student_data, doc_words, self.BOW_FIELDS)\n\n self.printMatches(matches, num_matches)\n \n def printMatches(self, matches, num_matches):\n for n, m in matches.items():\n print n\n for item, score in sorted(m.items(), key=lambda(i,c):(-c, i))[:num_matches]:\n print \"\\t%s :: %s\" % (item, score)\n # print \"'%s' '%s' %s\" % (n.translate(string.maketrans(\"\",\"\"), string.punctuation), item.translate(string.maketrans(\"\",\"\"), string.punctuation), score)\n print '\\n'\n \n \n def doRanking(self, base_data, match_data, doc_words, fields=[], base_name_field='Company', match_name_field='Student Name'):\n \"\"\"\n do ranking\n \"\"\"\n base = {}\n for item in base_data:\n base[item[base_name_field]] = self.extractFeatures(item, doc_words, fields)\n \n matches = defaultdict(dict)\n for match_item in match_data:\n match_features = self.extractFeatures(match_item, doc_words, fields)\n\n for base_item, base_item_features in base.items(): # actually do the comparison\n if not base_item_features or not match_features:\n matches[match_item[match_name_field]][base_item] = 0.0\n else:\n matches[match_item[match_name_field]][base_item] = self.distance(base_item_features, match_features)\n if self.DEBUG:\n print \"%s :: %s = %s \" % (match_item[match_name_field], base_item, self.distance(base_item_features, match_features))\n\n return matches\n\n def extractFeatures(self, item, doc_words, fields=[]):\n s_tokens = []\n for f in fields:\n tokens = None\n try:\n tokens = word_tokenize(item[f])\n except (KeyError, TypeError):\n pass\n \n if tokens:\n s_tokens.extend(tokens)\n \n s_features = [] \n for token in doc_words:\n if token in s_tokens:\n s_features.append(1)\n else:\n s_features.append(0)\n \n if sum(s_features) <= self.COMPLETENESS_THRESHOLD:\n return None\n \n return s_features\n\n def defineFeatures(self, data, fields=[]):\n \"\"\"\n define the global bag of words features\n \"\"\"\n ngram_freq = {}\n \n for d in data:\n for r in d:\n for f in fields:\n tokens = None\n try:\n tokens = word_tokenize(r[f])\n except (KeyError, TypeError):\n pass\n \n if tokens:\n for t in [t.lower() for t in tokens if t.lower() not in self.stopwords]:\n t = t.strip('.')\n ngram_freq[t] = ngram_freq.get(t, 0) + 1\n \n ngram_freq = dict([(w,c) for w,c in ngram_freq.items() if c > 1])\n if self.DEBUG:\n print \"Global vocabulary: %s\" % len(ngram_freq) \n return ngram_freq\n \n def get_stopwords(self):\n sw = stopwords.words('english')\n sw.extend([',', '\\xe2', '.', ')', '(', ':', \"'s\", \"'nt\", '\\x99', '\\x86', '\\xae', '\\x92'])\n return sw\n \n def parseCSV(self, filename):\n \"\"\"\n parseCSV: parses the CSV file to a dict\n \"\"\"\n csv_reader = csv.DictReader(open(filename))\n return [r for r in csv_reader]\n \n \nif __name__ == '__main__':\n parser = OptionParser()\n parser.add_option(\"-n\",\"--number\", action=\"store\", type=\"int\", dest=\"num_matches\",default=10,help=\"number of results to return\")\n parser.add_option(\"-s\",\"--student\", action=\"store\", type=\"string\", dest=\"student_file\",default=\"unmatched_students.csv\",help=\"csv of student data\")\n parser.add_option(\"-t\",\"--startup\", action=\"store\", type=\"string\", dest=\"startup_file\",default=\"unmatched_top_startups.csv\",help=\"csv of startup data\")\n (options, args) = parser.parse_args()\n \n h = HackMatch(num_matches=options.num_matches, student_file=options.student_file, startup_file=options.startup_file)"}, "files_after": {"download_stopwords.py": "from nltk import download\ndownload('stopwords')\n", "hackmatch.py": "#!/usr/bin/env python\n# encoding: utf-8\n# recognize.\n\"\"\"\nhackmatch.py\n\nCreated by Hilary Mason, Chris Wiggins, and Evan Korth.\nCopyright (c) 2010 hackNY. All rights reserved.\n\"\"\"\n# pylint: disable=W0614\n# pylint: disable=C0301\n\nfrom collections import defaultdict\nfrom optparse import OptionParser\nfrom nltk.corpus import stopwords\nfrom nltk.tokenize import word_tokenize\nfrom hcluster import jaccard\nfrom operator import itemgetter\nfrom csv import DictReader\n\n# startups: Name,E-mail,Company,In NYC,Funding,Site,Blog,Twitter,Num Employees,Environment,Project,Skills,Misc\n# students: Student Name,e-mail,University,Major,Degree,Graduation Date,Site,Blog,Twitter,Facebook,Project,Skills,Misc\n\n# Hack\n# I'd like to write this:\n# return reduce(list.extend, list_of_lists)\n# but it generates an error I don't get\ndef list_reducer(list_iter):\n result = []\n for l in list_iter:\n result.extend(l)\n return result\n\ndef get_stopwords():\n \"\"\"\n get_stopwords: generate a list of stop words\n \"\"\"\n return stopwords.words('english') + [',', '\\xe2', '.', ')', '(', ':', \"'s\", \"'nt\", '\\x99', '\\x86', '\\xae', '\\x92']\n\ndef parse_csv(filename):\n \"\"\"\n parse_csv: parses the CSV file to a dict\n \"\"\"\n csv_reader = DictReader(open(filename))\n return [r for r in csv_reader]\n\ndef print_matches(matches, num_matches):\n \"\"\"\n print_matches: print the top 'num_matches' matches\n \"\"\"\n for key, value_dict in matches.items():\n print key\n all_matches = sorted(value_dict.items(), key=itemgetter(1))\n top_matches = all_matches[-num_matches:]\n for item, score in top_matches:\n print \"\\t%(item)s :: %(score)s\" % locals()\n # print \"'%s' '%s' %s\" % (n.translate(string.maketrans(\"\",\"\"), string.punctuation), item.translate(string.maketrans(\"\",\"\"), string.punctuation), score)\n print '\\n'\n\nclass HackMatch(object):\n \"\"\"\n HackMatch: class to encapsulate matching companies versus startups on selected fields\n \"\"\"\n DEBUG = False\n BOW_FIELDS = ['Environment', 'Project', 'Skills', 'Misc']\n COMPLETENESS_THRESHOLD = 4 # num of words necessary to match\n \n def __init__(self, student_file, startup_file, num_matches=3, distance=jaccard):\n self.stopwords = set(get_stopwords())\n self.distance = distance\n \n student_data = parse_csv(student_file)\n startup_data = parse_csv(startup_file)\n \n doc_words = self.define_features([student_data, startup_data], self.BOW_FIELDS)\n\n # matches = self.do_ranking(student_data, startup_data, doc_words, self.BOW_FIELDS, base_name_field='Student Name', match_name_field='Company')\n matches = self.do_ranking(startup_data, student_data, doc_words, self.BOW_FIELDS)\n\n print_matches(matches, num_matches)\n \n def do_ranking(self, base_data, match_data, doc_words, fields=None, base_name_field='Company', match_name_field='Student Name'):\n \"\"\"\n do ranking\n \"\"\"\n fields = fields or []\n base = dict((item[base_name_field], self.extract_features(item, doc_words, fields)) for item in base_data)\n\n matches = defaultdict(dict)\n for match_item in match_data:\n match_features = self.extract_features(match_item, doc_words, fields)\n temp_dict = matches[match_item[match_name_field]]\n for base_item, base_item_features in base.items(): # actually do the comparison\n if not base_item_features or not match_features:\n temp_dict[base_item] = 0.0\n else:\n temp_dict[base_item] = self.distance(base_item_features, match_features)\n if self.DEBUG:\n print \"%s :: %s = %s \" % (match_item[match_name_field], base_item, self.distance(base_item_features, match_features))\n return matches\n\n def extract_features(self, item_dict, doc_words, fields=None):\n \"\"\"\n extract_features: Determine whether features pass test\n \"\"\"\n fields = fields or []\n tokeniter = (item_dict[f] for f in fields if f in item_dict)\n s_tokens = list_reducer(tokeniter)\n s_features = [token in s_tokens for token in doc_words]\n return s_features if sum(s_features) > self.COMPLETENESS_THRESHOLD else None\n\n def define_features(self, data, fields=None):\n \"\"\"\n define the global bag of words features\n \"\"\"\n fields = fields or []\n ngram_freq = defaultdict(int)\n \n featureiter = (\n r[f]\n for d in data\n for r in d\n for f in fields\n if f in r\n )\n for field in featureiter:\n tokeniter = (word.lower() for word in word_tokenize(field))\n legaliter = (word.strip('.') for word in tokeniter if word not in self.stopwords)\n for legal_word in legaliter:\n ngram_freq[legal_word] += 1\n ngram_freq = dict((word, word_count) for word, word_count in ngram_freq.items() if word_count > 1)\n if self.DEBUG:\n print \"Global vocabulary: %s\" % len(ngram_freq) \n return ngram_freq\n\nif __name__ == '__main__':\n parser = OptionParser()\n parser.add_option(\"-n\", \"--number\", action=\"store\", type=\"int\", dest=\"num_matches\", default=10, help=\"number of results to return\")\n parser.add_option(\"-s\", \"--student\", action=\"store\", type=\"string\", dest=\"student_file\", default=\"unmatched_students.csv\", help=\"csv of student data\")\n parser.add_option(\"-t\", \"--startup\", action=\"store\", type=\"string\", dest=\"startup_file\", default=\"unmatched_top_startups.csv\", help=\"csv of startup data\")\n (options, args) = parser.parse_args()\n \n hackmatch = HackMatch(num_matches=options.num_matches, student_file=options.student_file, startup_file=options.startup_file)\n"}} -{"repo": "babs/pyrowl", "pr_number": 7, "title": "pep8 style", "state": "closed", "merged_at": null, "additions": 30, "deletions": 26, "files_changed": ["pynma/__init__.py", "pynma/pynma.py", "setup.py", "test.py"], "files_before": {"pynma/__init__.py": "#!/usr/bin/python\n\nfrom .pynma import PyNMA \n\n", "pynma/pynma.py": "#!/usr/bin/python\n\nfrom xml.dom.minidom import parseString\n\ntry:\n from http.client import HTTPSConnection\nexcept ImportError:\n from httplib import HTTPSConnection\n\ntry:\n from urllib.parse import urlencode\nexcept ImportError:\n from urllib import urlencode\n\n__version__ = \"0.1\"\n\nAPI_SERVER = 'www.notifymyandroid.com'\nADD_PATH = '/publicapi/notify'\n\nUSER_AGENT=\"PyNMA/v%s\"%__version__\n\ndef uniq_preserve(seq): # Dave Kirby\n # Order preserving\n seen = set()\n return [x for x in seq if x not in seen and not seen.add(x)]\n\ndef uniq(seq):\n # Not order preserving\n return list({}.fromkeys(seq).keys())\n\nclass PyNMA(object):\n \"\"\"PyNMA(apikey=[], developerkey=None)\ntakes 2 optional arguments:\n - (opt) apykey: might me a string containing 1 key or an array of keys\n - (opt) developerkey: where you can store your developer key\n\"\"\"\n\n def __init__(self, apikey=[], developerkey=None):\n self._developerkey = None\n self.developerkey(developerkey)\n if apikey:\n if type(apikey) == str:\n apikey = [apikey]\n self._apikey = uniq(apikey)\n\n def addkey(self, key):\n \"Add a key (register ?)\"\n if type(key) == str:\n if not key in self._apikey:\n self._apikey.append(key)\n elif type(key) == list:\n for k in key:\n if not k in self._apikey:\n self._apikey.append(k)\n\n def delkey(self, key):\n \"Removes a key (unregister ?)\"\n if type(key) == str:\n if key in self._apikey:\n self._apikey.remove(key)\n elif type(key) == list:\n for k in key:\n if key in self._apikey:\n self._apikey.remove(k)\n\n def developerkey(self, developerkey):\n \"Sets the developer key (and check it has the good length)\"\n if type(developerkey) == str and len(developerkey) == 48:\n self._developerkey = developerkey\n\n def push(self, application=\"\", event=\"\", description=\"\", url=\"\", contenttype=None, priority=0, batch_mode=False, html=False):\n \"\"\"Pushes a message on the registered API keys.\ntakes 5 arguments:\n - (req) application: application name [256]\n - (req) event: event name [1000]\n - (req) description: description [10000]\n - (opt) url: url [512]\n - (opt) contenttype: Content Type (act: None (plain text) or text/html)\n - (opt) priority: from -2 (lowest) to 2 (highest) (def:0)\n - (opt) batch_mode: push to all keys at once (def:False)\n\n - (opt) html: shortcut for contenttype=text/html\n\n - (opt) html: shortcut for contenttype=text/html\n\nWarning: using batch_mode will return error only if all API keys are bad\n cf: https://www.notifymyandroid.com/api.jsp\n\"\"\"\n datas = {\n 'application': application[:256].encode('utf8'),\n 'event': event[:1024].encode('utf8'),\n 'description': description[:10000].encode('utf8'),\n 'priority': priority\n }\n\n if url:\n datas['url'] = url[:512]\n\n if contenttype == \"text/html\" or html == True: # Currently only accepted content type\n datas['content-type'] = \"text/html\"\n\n if self._developerkey:\n datas['developerkey'] = self._developerkey\n\n results = {}\n\n if not batch_mode:\n for key in self._apikey:\n datas['apikey'] = key\n res = self.callapi('POST', ADD_PATH, datas)\n results[key] = res\n else:\n datas['apikey'] = \",\".join(self._apikey)\n res = self.callapi('POST', ADD_PATH, datas)\n results[datas['apikey']] = res\n return results\n \n def callapi(self, method, path, args):\n headers = { 'User-Agent': USER_AGENT }\n if method == \"POST\":\n headers['Content-type'] = \"application/x-www-form-urlencoded\"\n http_handler = HTTPSConnection(API_SERVER)\n http_handler.request(method, path, urlencode(args), headers)\n resp = http_handler.getresponse()\n\n try:\n res = self._parse_reponse(resp.read())\n except Exception as e:\n res = {'type': \"pynmaerror\",\n 'code': 600,\n 'message': str(e)\n }\n pass\n \n return res\n\n def _parse_reponse(self, response):\n root = parseString(response).firstChild\n for elem in root.childNodes:\n if elem.nodeType == elem.TEXT_NODE: continue\n if elem.tagName == 'success':\n res = dict(list(elem.attributes.items()))\n res['message'] = \"\"\n res['type'] = elem.tagName\n return res\n if elem.tagName == 'error':\n res = dict(list(elem.attributes.items()))\n res['message'] = elem.firstChild.nodeValue\n res['type'] = elem.tagName\n return res\n \n \n", "setup.py": "#!/usr/bin/env python\nfrom setuptools import setup, find_packages\n\nsetup(\n name='pyrowl',\n version='0.1',\n packages=find_packages()\n)\n\n", "test.py": "#!/usr/bin/python\n\nfrom pynma import PyNMA\nfrom pprint import pprint\nimport os\n\np = None\n\ndef main(keys):\n global p\n pkey = None\n \n p = PyNMA()\n if os.path.isfile(\"mydeveloperkey\"):\n dkey = open(\"mydeveloperkey\",'r').readline().strip()\n p.developerkey(dkey)\n\n p.addkey(keys)\n res = p.push(\"test app\", 'test event', 'test msg google', 'http://example.com', batch_mode=False, html=True)\n pprint(res)\n \nif __name__ == \"__main__\":\n if os.path.isfile('myapikey'):\n keys = [_f for _f in open(\"myapikey\",'r').read().split(\"\\n\") if _f]\n \n main(keys)\n else:\n print(\"need a file named myapikey containing one apikey per line\")\n"}, "files_after": {"pynma/__init__.py": "#!/usr/bin/python\n\nfrom .pynma import PyNMA\n", "pynma/pynma.py": "#!/usr/bin/python\n\nfrom xml.dom.minidom import parseString\n\ntry:\n from http.client import HTTPSConnection\nexcept ImportError:\n from httplib import HTTPSConnection\n\ntry:\n from urllib.parse import urlencode\nexcept ImportError:\n from urllib import urlencode\n\n__version__ = \"0.1\"\n\nAPI_SERVER = 'www.notifymyandroid.com'\nADD_PATH = '/publicapi/notify'\n\nUSER_AGENT = \"PyNMA/v%s\" % __version__\n\n\ndef uniq_preserve(seq): # Dave Kirby\n # Order preserving\n seen = set()\n return [x for x in seq if x not in seen and not seen.add(x)]\n\n\ndef uniq(seq):\n # Not order preserving\n return list({}.fromkeys(seq).keys())\n\n\nclass PyNMA(object):\n \"\"\"PyNMA(apikey=[], developerkey=None)\ntakes 2 optional arguments:\n - (opt) apykey: might me a string containing 1 key or an array of keys\n - (opt) developerkey: where you can store your developer key\n\"\"\"\n\n def __init__(self, apikey=[], developerkey=None):\n self._developerkey = None\n self.developerkey(developerkey)\n if apikey:\n if type(apikey) == str:\n apikey = [apikey]\n self._apikey = uniq(apikey)\n\n def addkey(self, key):\n \"Add a key (register ?)\"\n if type(key) == str:\n if key not in self._apikey:\n self._apikey.append(key)\n elif type(key) == list:\n for k in key:\n if k not in self._apikey:\n self._apikey.append(k)\n\n def delkey(self, key):\n \"Removes a key (unregister ?)\"\n if type(key) == str:\n if key in self._apikey:\n self._apikey.remove(key)\n elif type(key) == list:\n for k in key:\n if key in self._apikey:\n self._apikey.remove(k)\n\n def developerkey(self, developerkey):\n \"Sets the developer key (and check it has the good length)\"\n if type(developerkey) == str and len(developerkey) == 48:\n self._developerkey = developerkey\n\n def push(self, application=\"\", event=\"\", description=\"\", url=\"\",\n contenttype=None, priority=0, batch_mode=False, html=False):\n \"\"\"Pushes a message on the registered API keys.\ntakes 5 arguments:\n - (req) application: application name [256]\n - (req) event: event name [1000]\n - (req) description: description [10000]\n - (opt) url: url [512]\n - (opt) contenttype: Content Type (act: None (plain text) or text/html)\n - (opt) priority: from -2 (lowest) to 2 (highest) (def:0)\n - (opt) batch_mode: push to all keys at once (def:False)\n\n - (opt) html: shortcut for contenttype=text/html\n\n - (opt) html: shortcut for contenttype=text/html\n\nWarning: using batch_mode will return error only if all API keys are bad\n cf: https://www.notifymyandroid.com/api.jsp\n\"\"\"\n datas = {\n 'application': application[:256].encode('utf8'),\n 'event': event[:1024].encode('utf8'),\n 'description': description[:10000].encode('utf8'),\n 'priority': priority\n }\n\n if url:\n datas['url'] = url[:512]\n\n # Currently only accepted content type\n if contenttype == \"text/html\" or html is True:\n datas['content-type'] = \"text/html\"\n\n if self._developerkey:\n datas['developerkey'] = self._developerkey\n\n results = {}\n\n if not batch_mode:\n for key in self._apikey:\n datas['apikey'] = key\n res = self.callapi('POST', ADD_PATH, datas)\n results[key] = res\n else:\n datas['apikey'] = \",\".join(self._apikey)\n res = self.callapi('POST', ADD_PATH, datas)\n results[datas['apikey']] = res\n return results\n\n def callapi(self, method, path, args):\n headers = {'User-Agent': USER_AGENT}\n if method == \"POST\":\n headers['Content-type'] = \"application/x-www-form-urlencoded\"\n http_handler = HTTPSConnection(API_SERVER)\n http_handler.request(method, path, urlencode(args), headers)\n resp = http_handler.getresponse()\n\n try:\n res = self._parse_reponse(resp.read())\n except Exception as e:\n res = {'type': \"pynmaerror\",\n 'code': 600,\n 'message': str(e)\n }\n pass\n\n return res\n\n def _parse_reponse(self, response):\n root = parseString(response).firstChild\n for elem in root.childNodes:\n if elem.nodeType == elem.TEXT_NODE:\n continue\n if elem.tagName == 'success':\n res = dict(list(elem.attributes.items()))\n res['message'] = \"\"\n res['type'] = elem.tagName\n return res\n if elem.tagName == 'error':\n res = dict(list(elem.attributes.items()))\n res['message'] = elem.firstChild.nodeValue\n res['type'] = elem.tagName\n return res\n", "setup.py": "#!/usr/bin/env python\nfrom setuptools import setup, find_packages\n\nsetup(\n name='pyrowl',\n version='0.1',\n packages=find_packages()\n)\n", "test.py": "#!/usr/bin/python\n\nfrom pynma import PyNMA\nfrom pprint import pprint\nimport os\n\np = None\n\n\ndef main(keys):\n global p\n\n p = PyNMA()\n if os.path.isfile(\"mydeveloperkey\"):\n dkey = open(\"mydeveloperkey\", 'r').readline().strip()\n p.developerkey(dkey)\n\n p.addkey(keys)\n res = p.push(\"test app\", 'test event',\n 'test msg google',\n 'http://example.com', batch_mode=False, html=True)\n pprint(res)\n\nif __name__ == \"__main__\":\n if os.path.isfile('myapikey'):\n keys = [_f for _f in open(\"myapikey\", 'r').read().split(\"\\n\") if _f]\n\n main(keys)\n else:\n print(\"need a file named myapikey containing one apikey per line\")\n"}} -{"repo": "marcuswestin/fin", "pr_number": 1, "title": "Hi! I fixed some code for you!", "state": "closed", "merged_at": "2012-07-09T02:14:48Z", "additions": 1, "deletions": 1, "files_changed": ["engines/development/storage.js"], "files_before": {"engines/development/storage.js": "var fs = require('fs'),\n\tpath = require('path')\n\nvar data = {},\n\tdataDumpFile = './_development-engine-dump.json'\n\nif (path.existsSync(dataDumpFile)) {\n\tconsole.log('node engine found ' + dataDumpFile + ' - loading data...')\n\tdata = JSON.parse(fs.readFileSync(dataDumpFile))\n\tconsole.log('done loading data')\n}\n\nprocess.on('exit', function() {\n\tconsole.log('node storage engine detected shutdown')\n\tdumpData()\n})\n\nfunction dumpData() {\n\tconsole.log('dumping data...')\n\tfs.writeFileSync(dataDumpFile, JSON.stringify(data))\n\tconsole.log('done dumping data.')\n}\n\nsetInterval(dumpData, 60000)\n\nfunction typeError(operation, type, key) {\n\treturn '\"'+operation+'\" expected a '+type+' at key \"'+key+'\" but found a '+typeof data[key]\n}\n\nvar storeAPI = module.exports = {\n\t/* Getters\n\t *********/\n\tgetBytes: function(key, callback) {\n\t\tif (typeof data[key] == 'undefined') {\n\t\t\tcallback && callback(null, null)\n\t\t} else if (typeof data[key] == 'string' || typeof data[key] == 'number' || typeof data[key] == 'boolean') {\n\t\t\tcallback && callback(null, data[key])\n\t\t} else {\n\t\t\tcallback && callback(typeError('getBytes', 'string or number', key))\n\t\t}\n\t},\n\t\n\tgetListItems: function(key, from, to, callback) {\n\t\tif (typeof data[key] == 'undefined') {\n\t\t\tcallback && callback(null, [])\n\t\t} else if (!(data[key] instanceof Array)) {\n\t\t\tcallback && callback(typeError('getListItems', 'list', key))\n\t\t} else {\n\t\t\tif (to < 0) { to = data[key].length + to + 1 }\n\t\t\tfrom = Math.max(from, 0)\n\t\t\tto = Math.min(to, data[key].length)\n\t\t\tcallback && callback(null, data[key].slice(from, to - from))\n\t\t}\n\t},\n\t\n\tgetMembers: function(key, callback) {\n\t\tif (typeof data[key] == 'undefined') {\n\t\t\tcallback && callback(null, [])\n\t\t} else if (typeof data[key] != 'object') {\n\t\t\tcallback && callback(typeError('getMembers', 'set', key))\n\t\t} else {\n\t\t\tvar response = []\n\t\t\tfor (var value in data[key]) { response.push(JSON.parse(value)) }\n\t\t\tcallback && callback(null, response)\n\t\t}\n\t},\n\t\n\t/* Mutation handlers\n\t *******************/\n\thandleMutation: function(operation, key, args, callback) {\n\t\tvar operationArgs = [key].concat(args)\n\t\tif (callback) { operationArgs.push(callback) }\n\t\tstoreAPI[operation].apply(this, operationArgs)\n\t},\n\t\n\ttransact: function(transactionFn) {\n\t\t// the development engine acts atomically. We assume node won't halt during an operation\n\t\ttransactionFn()\n\t},\n\t\n\tset: function(key, value, callback) {\n\t\tif (typeof data[key] == 'undefined' || typeof data[key] == 'string' || typeof data[key] == 'number' || typeof data[key] == 'boolean') {\n\t\t\tdata[key] = value\n\t\t\tcallback && callback(null, data[key])\n\t\t} else {\n\t\t\tcallback && callback(typeError('set', 'string or number', key), null)\n\t\t}\n\t},\n\t\n\tpush: function(key, values, callback) {\n\t\tif (typeof data[key] == 'undefined') {\n\t\t\tdata[key] = [].concat(values)\n\t\t\tcallback && callback(null, null)\n\t\t} else if (data[key] instanceof Array) {\n\t\t\tdata[key] = data[key].concat(values)\n\t\t\tcallback && callback(null, null)\n\t\t} else {\n\t\t\tcallback && callback(typeError('push', 'list', key), null)\n\t\t}\n\t},\n\t\n\tunshift: function(key, values, callback) {\n\t\tvar values = Array.prototype.slice.call(arguments, 1)\n\t\tif (typeof data[key] == 'undefined') {\n\t\t\tdata[key] = [].concat(values)\n\t\t\tcallback && callback(null, null)\n\t\t} else if (data[key] instanceof Array) {\n\t\t\tdata[key] = values.concat(data[key])\n\t\t\tcallback && callback(null, null)\n\t\t} else {\n\t\t\tcallback && callback(typeError('push', 'list', key), null)\n\t\t}\n\t},\n\t\n\tincrement: function(key, callback) {\n\t\tif (typeof data[key] == 'undefined') {\n\t\t\tdata[key] = 1\n\t\t\tcallback && callback(null, data[key])\n\t\t} else if (typeof data[key] == 'number') {\n\t\t\tdata[key] += 1\n\t\t\tcallback && callback(null, data[key])\n\t\t} else {\n\t\t\tcallback && callback(typeError('increment', 'number', key), null)\n\t\t}\n\t},\n\t\n\tdecrement: function(key, callback) {\n\t\tif (typeof data[key] == 'undefined') {\n\t\t\tdata[key] = -1\n\t\t\tcallback && callback(null, data[key])\n\t\t} else if (typeof data[key] == 'number') {\n\t\t\tdata[key] -= 1\n\t\t\tcallback && callback(null, data[key])\n\t\t} else {\n\t\t\tcallback && callback(typeError('decrement', 'number', key), null)\n\t\t}\n\t},\n\t\n\tadd: function(key, value, callback) {\n\t\tif (typeof data[key] == 'undefined') {\n\t\t\tdata[key] = value\n\t\t\tcallback && callback(null, data[key])\n\t\t} else if (typeof data[key] == 'number') {\n\t\t\tdata[key] += value\n\t\t\tcallback && callback(null, data[key])\n\t\t} else {\n\t\t\tcallback && callback(typeError('add', 'number', key), null)\n\t\t}\n\t},\n\t\n\tsubtract: function(key, value, callback) {\n\t\tif (typeof data[key] == 'undefined') {\n\t\t\tdata[key] = -value\n\t\t\tcallback && callback(null, data[key])\n\t\t} else if (typeof data[key] == 'number') {\n\t\t\tdata[key] -= value\n\t\t\tcallback && callback(null, data[key])\n\t\t} else {\n\t\t\tcallback && callback(typeError('subtract', 'number', key), null)\n\t\t}\n\t},\n\t\n\tsadd: function(key, value, callback) {\n\t\tvalue = JSON.stringify(value)\n\t\tif (typeof data[key] == 'undefined') {\n\t\t\tdata[key] = {}\n\t\t\tdata[key][value] = true\n\t\t\tcallback && callback(null, 1)\n\t\t} else if (typeof data[key] == 'object') {\n\t\t\tvar response = data[key][value] ? 0 : 1\n\t\t\tdata[key][value] = true\n\t\t\tcallback && callback(null, response)\n\t\t} else {\n\t\t\tcallback && callback(typeError('sadd', 'set', key), null)\n\t\t}\n\t},\n\t\n\tsrem: function(key, value, callback) {\n\t\tvalue = JSON.stringify(value)\n\t\tif (typeof data[key] == 'undefined') {\n\t\t\tcallback && callback(null, 0)\n\t\t} else if (typeof data[key] == 'object') {\n\t\t\tvar response = data[key][value] ? 1 : 0\n\t\t\tdelete data[key][value]\n\t\t\tcallback && callback(null, response)\n\t\t} else {\n\t\t\tcallback && callback(typeError('srem', 'set', key), null)\n\t\t}\n\t}\n}\n"}, "files_after": {"engines/development/storage.js": "var fs = require('fs'),\n\tpath = require('path')\n\nvar data = {},\n\tdataDumpFile = './_development-engine-dump.json'\n\nif (fs.existsSync(dataDumpFile)) {\n\tconsole.log('node engine found ' + dataDumpFile + ' - loading data...')\n\tdata = JSON.parse(fs.readFileSync(dataDumpFile))\n\tconsole.log('done loading data')\n}\n\nprocess.on('exit', function() {\n\tconsole.log('node storage engine detected shutdown')\n\tdumpData()\n})\n\nfunction dumpData() {\n\tconsole.log('dumping data...')\n\tfs.writeFileSync(dataDumpFile, JSON.stringify(data))\n\tconsole.log('done dumping data.')\n}\n\nsetInterval(dumpData, 60000)\n\nfunction typeError(operation, type, key) {\n\treturn '\"'+operation+'\" expected a '+type+' at key \"'+key+'\" but found a '+typeof data[key]\n}\n\nvar storeAPI = module.exports = {\n\t/* Getters\n\t *********/\n\tgetBytes: function(key, callback) {\n\t\tif (typeof data[key] == 'undefined') {\n\t\t\tcallback && callback(null, null)\n\t\t} else if (typeof data[key] == 'string' || typeof data[key] == 'number' || typeof data[key] == 'boolean') {\n\t\t\tcallback && callback(null, data[key])\n\t\t} else {\n\t\t\tcallback && callback(typeError('getBytes', 'string or number', key))\n\t\t}\n\t},\n\t\n\tgetListItems: function(key, from, to, callback) {\n\t\tif (typeof data[key] == 'undefined') {\n\t\t\tcallback && callback(null, [])\n\t\t} else if (!(data[key] instanceof Array)) {\n\t\t\tcallback && callback(typeError('getListItems', 'list', key))\n\t\t} else {\n\t\t\tif (to < 0) { to = data[key].length + to + 1 }\n\t\t\tfrom = Math.max(from, 0)\n\t\t\tto = Math.min(to, data[key].length)\n\t\t\tcallback && callback(null, data[key].slice(from, to - from))\n\t\t}\n\t},\n\t\n\tgetMembers: function(key, callback) {\n\t\tif (typeof data[key] == 'undefined') {\n\t\t\tcallback && callback(null, [])\n\t\t} else if (typeof data[key] != 'object') {\n\t\t\tcallback && callback(typeError('getMembers', 'set', key))\n\t\t} else {\n\t\t\tvar response = []\n\t\t\tfor (var value in data[key]) { response.push(JSON.parse(value)) }\n\t\t\tcallback && callback(null, response)\n\t\t}\n\t},\n\t\n\t/* Mutation handlers\n\t *******************/\n\thandleMutation: function(operation, key, args, callback) {\n\t\tvar operationArgs = [key].concat(args)\n\t\tif (callback) { operationArgs.push(callback) }\n\t\tstoreAPI[operation].apply(this, operationArgs)\n\t},\n\t\n\ttransact: function(transactionFn) {\n\t\t// the development engine acts atomically. We assume node won't halt during an operation\n\t\ttransactionFn()\n\t},\n\t\n\tset: function(key, value, callback) {\n\t\tif (typeof data[key] == 'undefined' || typeof data[key] == 'string' || typeof data[key] == 'number' || typeof data[key] == 'boolean') {\n\t\t\tdata[key] = value\n\t\t\tcallback && callback(null, data[key])\n\t\t} else {\n\t\t\tcallback && callback(typeError('set', 'string or number', key), null)\n\t\t}\n\t},\n\t\n\tpush: function(key, values, callback) {\n\t\tif (typeof data[key] == 'undefined') {\n\t\t\tdata[key] = [].concat(values)\n\t\t\tcallback && callback(null, null)\n\t\t} else if (data[key] instanceof Array) {\n\t\t\tdata[key] = data[key].concat(values)\n\t\t\tcallback && callback(null, null)\n\t\t} else {\n\t\t\tcallback && callback(typeError('push', 'list', key), null)\n\t\t}\n\t},\n\t\n\tunshift: function(key, values, callback) {\n\t\tvar values = Array.prototype.slice.call(arguments, 1)\n\t\tif (typeof data[key] == 'undefined') {\n\t\t\tdata[key] = [].concat(values)\n\t\t\tcallback && callback(null, null)\n\t\t} else if (data[key] instanceof Array) {\n\t\t\tdata[key] = values.concat(data[key])\n\t\t\tcallback && callback(null, null)\n\t\t} else {\n\t\t\tcallback && callback(typeError('push', 'list', key), null)\n\t\t}\n\t},\n\t\n\tincrement: function(key, callback) {\n\t\tif (typeof data[key] == 'undefined') {\n\t\t\tdata[key] = 1\n\t\t\tcallback && callback(null, data[key])\n\t\t} else if (typeof data[key] == 'number') {\n\t\t\tdata[key] += 1\n\t\t\tcallback && callback(null, data[key])\n\t\t} else {\n\t\t\tcallback && callback(typeError('increment', 'number', key), null)\n\t\t}\n\t},\n\t\n\tdecrement: function(key, callback) {\n\t\tif (typeof data[key] == 'undefined') {\n\t\t\tdata[key] = -1\n\t\t\tcallback && callback(null, data[key])\n\t\t} else if (typeof data[key] == 'number') {\n\t\t\tdata[key] -= 1\n\t\t\tcallback && callback(null, data[key])\n\t\t} else {\n\t\t\tcallback && callback(typeError('decrement', 'number', key), null)\n\t\t}\n\t},\n\t\n\tadd: function(key, value, callback) {\n\t\tif (typeof data[key] == 'undefined') {\n\t\t\tdata[key] = value\n\t\t\tcallback && callback(null, data[key])\n\t\t} else if (typeof data[key] == 'number') {\n\t\t\tdata[key] += value\n\t\t\tcallback && callback(null, data[key])\n\t\t} else {\n\t\t\tcallback && callback(typeError('add', 'number', key), null)\n\t\t}\n\t},\n\t\n\tsubtract: function(key, value, callback) {\n\t\tif (typeof data[key] == 'undefined') {\n\t\t\tdata[key] = -value\n\t\t\tcallback && callback(null, data[key])\n\t\t} else if (typeof data[key] == 'number') {\n\t\t\tdata[key] -= value\n\t\t\tcallback && callback(null, data[key])\n\t\t} else {\n\t\t\tcallback && callback(typeError('subtract', 'number', key), null)\n\t\t}\n\t},\n\t\n\tsadd: function(key, value, callback) {\n\t\tvalue = JSON.stringify(value)\n\t\tif (typeof data[key] == 'undefined') {\n\t\t\tdata[key] = {}\n\t\t\tdata[key][value] = true\n\t\t\tcallback && callback(null, 1)\n\t\t} else if (typeof data[key] == 'object') {\n\t\t\tvar response = data[key][value] ? 0 : 1\n\t\t\tdata[key][value] = true\n\t\t\tcallback && callback(null, response)\n\t\t} else {\n\t\t\tcallback && callback(typeError('sadd', 'set', key), null)\n\t\t}\n\t},\n\t\n\tsrem: function(key, value, callback) {\n\t\tvalue = JSON.stringify(value)\n\t\tif (typeof data[key] == 'undefined') {\n\t\t\tcallback && callback(null, 0)\n\t\t} else if (typeof data[key] == 'object') {\n\t\t\tvar response = data[key][value] ? 1 : 0\n\t\t\tdelete data[key][value]\n\t\t\tcallback && callback(null, response)\n\t\t} else {\n\t\t\tcallback && callback(typeError('srem', 'set', key), null)\n\t\t}\n\t}\n}\n"}} -{"repo": "tauren/jquery-ui", "pr_number": 1, "title": "Fix sequential type ahead should through the list if not match is found for two same consecutive letters", "state": "closed", "merged_at": null, "additions": 743, "deletions": 140, "files_changed": ["demos/selectmenu/overlay.html", "demos/selectmenu/refresh.html", "demos/selectmenu/typeahead.html", "tests/unit/selectmenu/normalselect.html", "tests/unit/selectmenu/selectmenu.html", "tests/unit/selectmenu/selectmenu_typeahead_sequential.js", "ui/jquery.ui.selectmenu.js"], "files_before": {"ui/jquery.ui.selectmenu.js": " /*\n * jQuery UI selectmenu dev version\n *\n * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)\n * Dual licensed under the MIT (MIT-LICENSE.txt)\n * and GPL (GPL-LICENSE.txt) licenses.\n *\n * http://docs.jquery.com/UI\n * https://github.com/fnagel/jquery-ui/wiki/Selectmenu\n */\n\n(function($) {\n\n$.widget(\"ui.selectmenu\", {\n\tgetter: \"value\",\n\tversion: \"1.8\",\n\teventPrefix: \"selectmenu\",\n\toptions: {\n\t\ttransferClasses: true,\n\t\ttypeAhead: \"sequential\",\n\t\tstyle: 'dropdown',\n\t\tpositionOptions: {\n\t\t\tmy: \"left top\",\n\t\t\tat: \"left bottom\",\n\t\t\toffset: null\n\t\t},\n\t\twidth: null,\n\t\tmenuWidth: null,\n\t\thandleWidth: 26,\n\t\tmaxHeight: null,\n\t\ticons: null,\n\t\tformat: null,\n\t\tbgImage: function() {},\n\t\twrapperElement: \"\"\n\t},\n\n\t_create: function() {\n\t\tvar self = this, o = this.options;\n\n\t\t// set a default id value, generate a new random one if not set by developer\n\t\tvar selectmenuId = this.element.attr('id') || 'ui-selectmenu-' + Math.random().toString(16).slice(2, 10);\n\n\t\t// quick array of button and menu id's\n\t\tthis.ids = [ selectmenuId + '-button', selectmenuId + '-menu' ];\n\n\t\t// define safe mouseup for future toggling\n\t\tthis._safemouseup = true;\n\n\t\t// create menu button wrapper\n\t\tthis.newelement = $('')\n\t\t\t.insertAfter(this.element);\n\t\tthis.newelement.wrap(o.wrapperElement);\n\n\t\t// transfer tabindex\n\t\tvar tabindex = this.element.attr('tabindex');\n\t\tif (tabindex) {\n\t\t\tthis.newelement.attr('tabindex', tabindex);\n\t\t}\n\n\t\t// save reference to select in data for ease in calling methods\n\t\tthis.newelement.data('selectelement', this.element);\n\n\t\t// menu icon\n\t\tthis.selectmenuIcon = $('')\n\t\t\t.prependTo(this.newelement);\n\n\t\t// append status span to button\n\t\tthis.newelement.prepend('');\n\n\t\t// make associated form label trigger focus\n\t\t$( 'label[for=\"' + selectmenuId + '\"]' )\n\t\t\t.attr( 'for', this.ids[0] )\n\t\t\t.bind( 'click.selectmenu', function() {\n\t\t\t\tself.newelement[0].focus();\n\t\t\t\treturn false;\n\t\t\t});\n\n\t\t// click toggle for menu visibility\n\t\tthis.newelement\n\t\t\t.bind('mousedown.selectmenu', function(event) {\n\t\t\t\tself._toggle(event, true);\n\t\t\t\t// make sure a click won't open/close instantly\n\t\t\t\tif (o.style == \"popup\") {\n\t\t\t\t\tself._safemouseup = false;\n\t\t\t\t\tsetTimeout(function() { self._safemouseup = true; }, 300);\n\t\t\t\t}\n\t\t\t\treturn false;\n\t\t\t})\n\t\t\t.bind('click.selectmenu', function() {\n\t\t\t\treturn false;\n\t\t\t})\n\t\t\t.bind(\"keydown.selectmenu\", function(event) {\n\t\t\t\tvar ret = false;\n\t\t\t\tswitch (event.keyCode) {\n\t\t\t\t\tcase $.ui.keyCode.ENTER:\n\t\t\t\t\t\tret = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase $.ui.keyCode.SPACE:\n\t\t\t\t\t\tself._toggle(event);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase $.ui.keyCode.UP:\n\t\t\t\t\t\tif (event.altKey) {\n\t\t\t\t\t\t\tself.open(event);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tself._moveSelection(-1);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase $.ui.keyCode.DOWN:\n\t\t\t\t\t\tif (event.altKey) {\n\t\t\t\t\t\t\tself.open(event);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tself._moveSelection(1);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase $.ui.keyCode.LEFT:\n\t\t\t\t\t\tself._moveSelection(-1);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase $.ui.keyCode.RIGHT:\n\t\t\t\t\t\tself._moveSelection(1);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase $.ui.keyCode.TAB:\n\t\t\t\t\t\tret = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tret = true;\n\t\t\t\t}\n\t\t\t\treturn ret;\n\t\t\t})\n\t\t\t.bind('keypress.selectmenu', function(event) {\n\t\t\t\tself._typeAhead(event.which, 'mouseup');\n\t\t\t\treturn true;\n\t\t\t})\n\t\t\t.bind('mouseover.selectmenu focus.selectmenu', function() {\n\t\t\t\tif (!o.disabled) {\n\t\t\t\t\t$(this).addClass(self.widgetBaseClass + '-focus ui-state-hover');\n\t\t\t\t}\n\t\t\t})\n\t\t\t.bind('mouseout.selectmenu blur.selectmenu', function() {\n\t\t\t\tif (!o.disabled) {\n\t\t\t\t\t$(this).removeClass(self.widgetBaseClass + '-focus ui-state-hover');\n\t\t\t\t}\n\t\t\t});\n\n\t\t// document click closes menu\n\t\t$(document).bind(\"mousedown.selectmenu\", function(event) {\n\t\t\tself.close(event);\n\t\t});\n\n\t\t// change event on original selectmenu\n\t\tthis.element\n\t\t\t.bind(\"click.selectmenu\", function() {\n\t\t\t\tself._refreshValue();\n\t\t\t})\n\t\t\t// FIXME: newelement can be null under unclear circumstances in IE8\n\t\t\t// TODO not sure if this is still a problem (fnagel 20.03.11)\n\t\t\t.bind(\"focus.selectmenu\", function() {\n\t\t\t\tif (self.newelement) {\n\t\t\t\t\tself.newelement[0].focus();\n\t\t\t\t}\n\t\t\t});\n\n\t\t// set width when not set via options\n\t\tif (!o.width) {\n\t\t\to.width = this.element.outerWidth();\n\t\t}\n\t\t// set menu button width\n\t\tthis.newelement.width(o.width);\n\n\t\t// hide original selectmenu element\n\t\tthis.element.hide();\n\n\t\t// create menu portion, append to body\n\t\tthis.list = $('
      ').appendTo('body');\n\t\tthis.list.wrap(o.wrapperElement);\n\n\t\t// transfer menu click to menu button\n\t\tthis.list\n\t\t\t.bind(\"keydown.selectmenu\", function(event) {\n\t\t\t\tvar ret = false;\n\t\t\t\tswitch (event.keyCode) {\n\t\t\t\t\tcase $.ui.keyCode.UP:\n\t\t\t\t\t\tif (event.altKey) {\n\t\t\t\t\t\t\tself.close(event, true);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tself._moveFocus(-1);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase $.ui.keyCode.DOWN:\n\t\t\t\t\t\tif (event.altKey) {\n\t\t\t\t\t\t\tself.close(event, true);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tself._moveFocus(1);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase $.ui.keyCode.LEFT:\n\t\t\t\t\t\tself._moveFocus(-1);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase $.ui.keyCode.RIGHT:\n\t\t\t\t\t\tself._moveFocus(1);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase $.ui.keyCode.HOME:\n\t\t\t\t\t\tself._moveFocus(':first');\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase $.ui.keyCode.PAGE_UP:\n\t\t\t\t\t\tself._scrollPage('up');\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase $.ui.keyCode.PAGE_DOWN:\n\t\t\t\t\t\tself._scrollPage('down');\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase $.ui.keyCode.END:\n\t\t\t\t\t\tself._moveFocus(':last');\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase $.ui.keyCode.ENTER:\n\t\t\t\t\tcase $.ui.keyCode.SPACE:\n\t\t\t\t\t\tself.close(event, true);\n\t\t\t\t\t\t$(event.target).parents('li:eq(0)').trigger('mouseup');\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase $.ui.keyCode.TAB:\n\t\t\t\t\t\tret = true;\n\t\t\t\t\t\tself.close(event, true);\n\t\t\t\t\t\t$(event.target).parents('li:eq(0)').trigger('mouseup');\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase $.ui.keyCode.ESCAPE:\n\t\t\t\t\t\tself.close(event, true);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tret = true;\n\t\t\t\t}\n\t\t\t\treturn ret;\n\t\t\t})\n\t\t\t.bind('keypress.selectmenu', function(event) {\n\t\t\t\tself._typeAhead(event.which, 'focus');\n\t\t\t\treturn true;\n\t\t\t})\n\t\t\t// this allows for using the scrollbar in an overflowed list\n\t\t\t.bind( 'mousedown.selectmenu mouseup.selectmenu', function() { return false; });\n\n\n\t\t// needed when window is resized\n\t\t$(window).bind( \"resize.selectmenu\", $.proxy( self._refreshPosition, this ) );\n\t},\n\n\t_init: function() {\n\t\tvar self = this, o = this.options;\n\n\t\t// serialize selectmenu element options\n\t\tvar selectOptionData = [];\n\t\tthis.element\n\t\t\t.find('option')\n\t\t\t.each(function() {\n\t\t\t\tselectOptionData.push({\n\t\t\t\t\tvalue: $(this).attr('value'),\n\t\t\t\t\ttext: self._formatText($(this).text()),\n\t\t\t\t\tselected: $(this).attr('selected'),\n\t\t\t\t\tdisabled: $(this).attr('disabled'),\n\t\t\t\t\tclasses: $(this).attr('class'),\n\t\t\t\t\ttypeahead: $(this).attr('typeahead'),\n\t\t\t\t\tparentOptGroup: $(this).parent('optgroup'),\n\t\t\t\t\tbgImage: o.bgImage.call($(this))\n\t\t\t\t});\n\t\t\t});\n\n\t\t// active state class is only used in popup style\n\t\tvar activeClass = (self.options.style == \"popup\") ? \" ui-state-active\" : \"\";\n\n\t\t// empty list so we can refresh the selectmenu via selectmenu()\n\t\tthis.list.html(\"\");\n\n\t\t// write li's\n\t\tfor (var i = 0; i < selectOptionData.length; i++) {\n\t\t\t\tvar thisLi = $('
    • '+ selectOptionData[i].text +'
    • ')\n\t\t\t\t.data('index', i)\n\t\t\t\t.addClass(selectOptionData[i].classes)\n\t\t\t\t.data('optionClasses', selectOptionData[i].classes || '')\n\t\t\t\t.bind(\"mouseup.selectmenu\", function(event) {\n\t\t\t\t\tif (self._safemouseup && !self._disabled(event.currentTarget) && !self._disabled($( event.currentTarget ).parents( \"ul>li.\" + self.widgetBaseClass + \"-group \" )) ) {\n\t\t\t\t\t\tvar changed = $(this).data('index') != self._selectedIndex();\n\t\t\t\t\t\tself.index($(this).data('index'));\n\t\t\t\t\t\tself.select(event);\n\t\t\t\t\t\tif (changed) {\n\t\t\t\t\t\t\tself.change(event);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tself.close(event, true);\n\t\t\t\t\t}\n\t\t\t\t\treturn false;\n\t\t\t\t})\n\t\t\t\t.bind(\"click.selectmenu\", function() {\n\t\t\t\t\treturn false;\n\t\t\t\t})\n\t\t\t\t.bind('mouseover.selectmenu focus.selectmenu', function(e) {\n\t\t\t\t\t// no hover if diabled\n\t\t\t\t\tif (!$(e.currentTarget).hasClass(self.namespace + '-state-disabled')) {\n\t\t\t\t\t\tself._selectedOptionLi().addClass(activeClass);\n\t\t\t\t\t\tself._focusedOptionLi().removeClass(self.widgetBaseClass + '-item-focus ui-state-hover');\n\t\t\t\t\t\t$(this).removeClass('ui-state-active').addClass(self.widgetBaseClass + '-item-focus ui-state-hover');\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t\t.bind('mouseout.selectmenu blur.selectmenu', function() {\n\t\t\t\t\tif ($(this).is(self._selectedOptionLi().selector)) {\n\t\t\t\t\t\t$(this).addClass(activeClass);\n\t\t\t\t\t}\n\t\t\t\t\t$(this).removeClass(self.widgetBaseClass + '-item-focus ui-state-hover');\n\t\t\t\t});\n\n\t\t\t// optgroup or not...\n\t\t\tif ( selectOptionData[i].parentOptGroup.length ) {\n\t\t\t\tvar optGroupName = self.widgetBaseClass + '-group-' + this.element.find( 'optgroup' ).index( selectOptionData[i].parentOptGroup );\n\t\t\t\tif (this.list.find( 'li.' + optGroupName ).length ) {\n\t\t\t\t\tthis.list.find( 'li.' + optGroupName + ':last ul' ).append( thisLi );\n\t\t\t\t} else {\n\t\t\t\t\t$('
    • ' + selectOptionData[i].parentOptGroup.attr('label') + '
      • ')\n\t\t\t\t\t\t.appendTo( this.list )\n\t\t\t\t\t\t.find( 'ul' )\n\t\t\t\t\t\t.append( thisLi );\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tthisLi.appendTo(this.list);\n\t\t\t}\n\n\t\t\t// append icon if option is specified\n\t\t\tif (o.icons) {\n\t\t\t\tfor (var j in o.icons) {\n\t\t\t\t\tif (thisLi.is(o.icons[j].find)) {\n\t\t\t\t\t\tthisLi\n\t\t\t\t\t\t\t.data('optionClasses', selectOptionData[i].classes + ' ' + self.widgetBaseClass + '-hasIcon')\n\t\t\t\t\t\t\t.addClass(self.widgetBaseClass + '-hasIcon');\n\t\t\t\t\t\tvar iconClass = o.icons[j].icon || \"\";\n\t\t\t\t\t\tthisLi\n\t\t\t\t\t\t\t.find('a:eq(0)')\n\t\t\t\t\t\t\t.prepend('');\n\t\t\t\t\t\tif (selectOptionData[i].bgImage) {\n\t\t\t\t\t\t\tthisLi.find('span').css('background-image', selectOptionData[i].bgImage);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// we need to set and unset the CSS classes for dropdown and popup style\n\t\tvar isDropDown = (o.style == 'dropdown');\n\t\tthis.newelement\n\t\t\t.toggleClass(self.widgetBaseClass + \"-dropdown\", isDropDown)\n\t\t\t.toggleClass(self.widgetBaseClass + \"-popup\", !isDropDown);\n\t\tthis.list\n\t\t\t.toggleClass(self.widgetBaseClass + \"-menu-dropdown ui-corner-bottom\", isDropDown)\n\t\t\t.toggleClass(self.widgetBaseClass + \"-menu-popup ui-corner-all\", !isDropDown)\n\t\t\t// add corners to top and bottom menu items\n\t\t\t.find('li:first')\n\t\t\t.toggleClass(\"ui-corner-top\", !isDropDown)\n\t\t\t.end().find('li:last')\n\t\t\t.addClass(\"ui-corner-bottom\");\n\t\tthis.selectmenuIcon\n\t\t\t.toggleClass('ui-icon-triangle-1-s', isDropDown)\n\t\t\t.toggleClass('ui-icon-triangle-2-n-s', !isDropDown);\n\n\t\t// transfer classes to selectmenu and list\n\t\tif (o.transferClasses) {\n\t\t\tvar transferClasses = this.element.attr('class') || '';\n\t\t\tthis.newelement.add(this.list).addClass(transferClasses);\n\t\t}\n\n\t\t// set menu width to either menuWidth option value, width option value, or select width\n\t\tif (o.style == 'dropdown') {\n\t\t\tthis.list.width(o.menuWidth ? o.menuWidth : o.width);\n\t\t} else {\n\t\t\tthis.list.width(o.menuWidth ? o.menuWidth : o.width - o.handleWidth);\n\t\t}\n\t\to.minMenuWidth && this.list.width() < o.minMenuWidth && this.list.width(o.minMenuWidth);\n\n\t\t// calculate default max height\n\t\tif (o.maxHeight) {\n\t\t\t// set max height from option\n\t\t\tif (o.maxHeight < this.list.height()) {\n\t\t\t\tthis.list.height(o.maxHeight);\n\t\t\t}\n\t\t} else {\n\t\t\tif (!o.format && ($(window).height() / 3) < this.list.height()) {\n\t\t\t\to.maxHeight = $(window).height() / 3;\n\t\t\t\tthis.list.height(o.maxHeight);\n\t\t\t}\n\t\t}\n\n\t\t// save reference to actionable li's (not group label li's)\n\t\tthis._optionLis = this.list.find('li:not(.' + self.widgetBaseClass + '-group)');\n\n\t\t// transfer disabled state\n\t\tif ( this.element.attr( 'disabled' ) === true ) {\n\t\t\tthis.disable();\n\t\t} else {\n\t\t\tthis.enable()\n\t\t}\n\t\t\n\t\t// update value\n\t\tthis.index(this._selectedIndex());\n\n\t\t// needed when selectmenu is placed at the very bottom / top of the page\n\t\twindow.setTimeout(function() {\n\t\t\tself._refreshPosition();\n\t\t}, 200);\n\t},\n\n\tdestroy: function() {\n\t\tthis.element.removeData( this.widgetName )\n\t\t\t.removeClass( this.widgetBaseClass + '-disabled' + ' ' + this.namespace + '-state-disabled' )\n\t\t\t.removeAttr( 'aria-disabled' )\n\t\t\t.unbind( \".selectmenu\" );\n\n\t\t$( window ).unbind( \".selectmenu\" );\n\t\t$( document ).unbind( \".selectmenu\" );\n\n\t\t// unbind click on label, reset its for attr\n\t\t$( 'label[for=' + this.newelement.attr('id') + ']' )\n\t\t\t.attr( 'for', this.element.attr( 'id' ) )\n\t\t\t.unbind( '.selectmenu' );\n\n\t\tif ( this.options.wrapperElement ) {\n\t\t\tthis.newelement.find( this.options.wrapperElement ).remove();\n\t\t\tthis.list.find( this.options.wrapperElement ).remove();\n\t\t} else {\n\t\t\tthis.newelement.remove();\n\t\t\tthis.list.remove();\n\t\t}\n\t\tthis.element.show();\n\n\t\t// call widget destroy function\n\t\t$.Widget.prototype.destroy.apply(this, arguments);\n\t},\n\n\t_typeAhead: function(code, eventType){\n\t\tvar self = this, focusFound = false, C = String.fromCharCode(code).toUpperCase();\n\t\tc = C.toLowerCase();\n\n\t\tif (self.options.typeAhead == 'sequential') {\n\t\t\t// clear the timeout so we can use _prevChar\n\t\t\twindow.clearTimeout('ui.selectmenu-' + self.selectmenuId);\n\n\t\t\t// define our find var\n\t\t\tvar find = typeof(self._prevChar) == 'undefined' ? '' : self._prevChar.join('');\n\n\t\t\tfunction focusOptSeq(elem, ind, c){\n\t\t\t\tfocusFound = true;\n\t\t\t\t$(elem).trigger(eventType);\n\t\t\t\ttypeof(self._prevChar) == 'undefined' ? self._prevChar = [c] : self._prevChar[self._prevChar.length] = c;\n\t\t\t}\n\t\t\tthis.list.find('li a').each(function(i) {\n\t\t\t\tif (!focusFound) {\n\t\t\t\t\t// allow the typeahead attribute on the option tag for a more specific lookup\n\t\t\t\t\tvar thisText = $(this).attr('typeahead') || $(this).text();\n\t\t\t\t\tif (thisText.indexOf(find+C) == 0) {\n\t\t\t\t\t\tfocusOptSeq(this,i,C)\n\t\t\t\t\t} else if (thisText.indexOf(find+c) == 0) {\n\t\t\t\t\t\tfocusOptSeq(this,i,c)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t\t// set a 1 second timeout for sequenctial typeahead\n\t\t\t// \tkeep this set even if we have no matches so it doesnt typeahead somewhere else\n\t\t\twindow.setTimeout(function(el) {\n\t\t\t\tself._prevChar = undefined;\n\t\t\t}, 1000, self);\n\n\t\t} else {\n\t\t\t//define self._prevChar if needed\n\t\t\tif (!self._prevChar){ self._prevChar = ['',0]; }\n\n\t\t\tvar focusFound = false;\n\t\t\tfunction focusOpt(elem, ind){\n\t\t\t\tfocusFound = true;\n\t\t\t\t$(elem).trigger(eventType);\n\t\t\t\tself._prevChar[1] = ind;\n\t\t\t}\n\t\t\tthis.list.find('li a').each(function(i){\n\t\t\t\tif(!focusFound){\n\t\t\t\t\tvar thisText = $(this).text();\n\t\t\t\t\tif( thisText.indexOf(C) == 0 || thisText.indexOf(c) == 0){\n\t\t\t\t\t\t\tif(self._prevChar[0] == C){\n\t\t\t\t\t\t\t\tif(self._prevChar[1] < i){ focusOpt(this,i); }\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse{ focusOpt(this,i); }\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t\tthis._prevChar[0] = C;\n\t\t}\n\t},\n\n\t// returns some usefull information, called by callbacks only\n\t_uiHash: function() {\n\t\tvar index = this.index();\n\t\treturn {\n\t\t\tindex: index,\n\t\t\toption: $(\"option\", this.element).get(index),\n\t\t\tvalue: this.element[0].value\n\t\t};\n\t},\n\n\topen: function(event) {\n\t\tvar self = this;\n\t\tif ( this.newelement.attr(\"aria-disabled\") != 'true' ) {\n\t\t\tthis._closeOthers(event);\n\t\t\tthis.newelement\n\t\t\t\t.addClass('ui-state-active');\n\t\t\tif (self.options.wrapperElement) {\n\t\t\t\tthis.list.parent().appendTo('body');\n\t\t\t} else {\n\t\t\t\tthis.list.appendTo('body');\n\t\t\t}\n\n\t\t\tthis.list.addClass(self.widgetBaseClass + '-open')\n\t\t\t\t.attr('aria-hidden', false)\n\t\t\t\t.find('li:not(.' + self.widgetBaseClass + '-group):eq(' + this._selectedIndex() + ') a')[0].focus();\n\t\t\tif ( this.options.style == \"dropdown\" ) {\n\t\t\t\tthis.newelement.removeClass('ui-corner-all').addClass('ui-corner-top');\n\t\t\t}\n\t\t\tthis._refreshPosition();\n\t\t\tthis._trigger(\"open\", event, this._uiHash());\n\t\t}\n\t},\n\n\tclose: function(event, retainFocus) {\n\t\tif ( this.newelement.is('.ui-state-active') ) {\n\t\t\tthis.newelement\n\t\t\t\t.removeClass('ui-state-active');\n\t\t\tthis.list\n\t\t\t\t.attr('aria-hidden', true)\n\t\t\t\t.removeClass(this.widgetBaseClass + '-open');\n\t\t\tif ( this.options.style == \"dropdown\" ) {\n\t\t\t\tthis.newelement.removeClass('ui-corner-top').addClass('ui-corner-all');\n\t\t\t}\n\t\t\tif ( retainFocus ) {\n\t\t\t\tthis.newelement.focus();\n\t\t\t}\n\t\t\tthis._trigger(\"close\", event, this._uiHash());\n\t\t}\n\t},\n\n\tchange: function(event) {\n\t\tthis.element.trigger(\"change\");\n\t\tthis._trigger(\"change\", event, this._uiHash());\n\t},\n\n\tselect: function(event) {\n\t\tif (this._disabled(event.currentTarget)) { return false; }\n\t\tthis._trigger(\"select\", event, this._uiHash());\n\t},\n\n\t_closeOthers: function(event) {\n\t\t$('.' + this.widgetBaseClass + '.ui-state-active').not(this.newelement).each(function() {\n\t\t\t$(this).data('selectelement').selectmenu('close', event);\n\t\t});\n\t\t$('.' + this.widgetBaseClass + '.ui-state-hover').trigger('mouseout');\n\t},\n\n\t_toggle: function(event, retainFocus) {\n\t\tif ( this.list.is('.' + this.widgetBaseClass + '-open') ) {\n\t\t\tthis.close(event, retainFocus);\n\t\t} else {\n\t\t\tthis.open(event);\n\t\t}\n\t},\n\n\t_formatText: function(text) {\n\t\treturn (this.options.format ? this.options.format(text) : text);\n\t},\n\n\t_selectedIndex: function() {\n\t\treturn this.element[0].selectedIndex;\n\t},\n\n\t_selectedOptionLi: function() {\n\t\treturn this._optionLis.eq(this._selectedIndex());\n\t},\n\n\t_focusedOptionLi: function() {\n\t\treturn this.list.find('.' + this.widgetBaseClass + '-item-focus');\n\t},\n\n\t_moveSelection: function(amt, recIndex) {\n\t\tvar currIndex = parseInt(this._selectedOptionLi().data('index') || 0, 10);\n\t\tvar newIndex = currIndex + amt;\n\t\t// do not loop when using up key\n\n\t\tif (newIndex < 0) {\n\t\t\tnewIndex = 0;\n\t\t}\n\t\tif (newIndex > this._optionLis.size() - 1) {\n\t\t\tnewIndex = this._optionLis.size() - 1;\n\t\t}\n\t\t//Occurs when a full loop has been made\n\t\tif (newIndex === recIndex) { return false; }\n\n\t\tif (this._optionLis.eq(newIndex).hasClass( this.namespace + '-state-disabled' )) {\n\t\t\t// if option at newIndex is disabled, call _moveFocus, incrementing amt by one\n\t\t\t(amt > 0) ? ++amt : --amt;\n\t\t\tthis._moveSelection(amt, newIndex);\n\t\t} else {\n\t\t\treturn this._optionLis.eq(newIndex).trigger('mouseup');\n\t\t}\n\t},\n\n\t_moveFocus: function(amt, recIndex) {\n\t\tif (!isNaN(amt)) {\n\t\t\tvar currIndex = parseInt(this._focusedOptionLi().data('index') || 0, 10);\n\t\t\tvar newIndex = currIndex + amt;\n\t\t}\n\t\telse {\n\t\t\tvar newIndex = parseInt(this._optionLis.filter(amt).data('index'), 10);\n\t\t}\n\n\t\tif (newIndex < 0) {\n\t\t\tnewIndex = 0;\n\t\t}\n\t\tif (newIndex > this._optionLis.size() - 1) {\n\t\t\tnewIndex = this._optionLis.size() - 1;\n\t\t}\n\n\t\t//Occurs when a full loop has been made\n\t\tif (newIndex === recIndex) { return false; }\n\n\t\tvar activeID = this.widgetBaseClass + '-item-' + Math.round(Math.random() * 1000);\n\n\t\tthis._focusedOptionLi().find('a:eq(0)').attr('id', '');\n\n\t\tif (this._optionLis.eq(newIndex).hasClass( this.namespace + '-state-disabled' )) {\n\t\t\t// if option at newIndex is disabled, call _moveFocus, incrementing amt by one\n\t\t\t(amt > 0) ? ++amt : --amt;\n\t\t\tthis._moveFocus(amt, newIndex);\n\t\t} else {\n\t\t\tthis._optionLis.eq(newIndex).find('a:eq(0)').attr('id',activeID).focus();\n\t\t}\n\n\t\tthis.list.attr('aria-activedescendant', activeID);\n\t},\n\n\t_scrollPage: function(direction) {\n\t\tvar numPerPage = Math.floor(this.list.outerHeight() / this.list.find('li:first').outerHeight());\n\t\tnumPerPage = (direction == 'up' ? -numPerPage : numPerPage);\n\t\tthis._moveFocus(numPerPage);\n\t},\n\n\t_setOption: function(key, value) {\n\t\tthis.options[key] = value;\n\t\t// set\n\t\tif (key == 'disabled') {\n\t\t\tthis.close();\n\t\t\tthis.element\n\t\t\t\t.add(this.newelement)\n\t\t\t\t.add(this.list)[value ? 'addClass' : 'removeClass'](\n\t\t\t\t\tthis.widgetBaseClass + '-disabled' + ' ' +\n\t\t\t\t\tthis.namespace + '-state-disabled')\n\t\t\t\t.attr(\"aria-disabled\", value);\n\t\t}\n\t},\n\n\tdisable: function(index, type){\n\t\t\t// if options is not provided, call the parents disable function\n\t\t\tif ( typeof( index ) == 'undefined' ) {\n\t\t\t\tthis._setOption( 'disabled', true );\n\t\t\t} else {\n\t\t\t\tif ( type == \"optgroup\" ) {\n\t\t\t\t\tthis._disableOptgroup(index);\n\t\t\t\t} else {\n\t\t\t\t\tthis._disableOption(index);\n\t\t\t\t}\n\t\t\t}\n\t},\n\n\tenable: function(index, type) {\n\t\t\t// if options is not provided, call the parents enable function\n\t\t\tif ( typeof( index ) == 'undefined' ) {\n\t\t\t\tthis._setOption('disabled', false);\n\t\t\t} else {\n\t\t\t\tif ( type == \"optgroup\" ) {\n\t\t\t\t\tthis._enableOptgroup(index);\n\t\t\t\t} else {\n\t\t\t\t\tthis._enableOption(index);\n\t\t\t\t}\n\t\t\t}\n\t},\n\n\t_disabled: function(elem) {\n\t\t\treturn $(elem).hasClass( this.namespace + '-state-disabled' );\n\t},\n\n\n\t_disableOption: function(index) {\n\t\t\tvar optionElem = this._optionLis.eq(index);\n\t\t\tif (optionElem) {\n\t\t\t\toptionElem.addClass(this.namespace + '-state-disabled')\n\t\t\t\t\t.find(\"a\").attr(\"aria-disabled\", true);\n\t\t\t\tthis.element.find(\"option\").eq(index).attr(\"disabled\", \"disabled\");\n\t\t\t}\n\t},\n\n\t_enableOption: function(index) {\n\t\t\tvar optionElem = this._optionLis.eq(index);\n\t\t\tif (optionElem) {\n\t\t\t\toptionElem.removeClass( this.namespace + '-state-disabled' )\n\t\t\t\t\t.find(\"a\").attr(\"aria-disabled\", false);\n\t\t\t\tthis.element.find(\"option\").eq(index).removeAttr(\"disabled\");\n\t\t\t}\n\t},\n\n\t_disableOptgroup: function(index) {\n\t\t\tvar optGroupElem = this.list.find( 'li.' + this.widgetBaseClass + '-group-' + index );\n\t\t\tif (optGroupElem) {\n\t\t\t\toptGroupElem.addClass(this.namespace + '-state-disabled')\n\t\t\t\t\t.attr(\"aria-disabled\", true);\n\t\t\t\tthis.element.find(\"optgroup\").eq(index).attr(\"disabled\", \"disabled\");\n\t\t\t}\n\t},\n\n\t_enableOptgroup: function(index) {\n\t\t\tvar optGroupElem = this.list.find( 'li.' + this.widgetBaseClass + '-group-' + index );\n\t\t\tif (optGroupElem) {\n\t\t\t\toptGroupElem.removeClass(this.namespace + '-state-disabled')\n\t\t\t\t\t.attr(\"aria-disabled\", false);\n\t\t\t\tthis.element.find(\"optgroup\").eq(index).removeAttr(\"disabled\");\n\t\t\t}\n\t},\n\n\tindex: function(newValue) {\n\t\tif (arguments.length) {\n\t\t\tif (!this._disabled($(this._optionLis[newValue]))) {\n\t\t\t\tthis.element[0].selectedIndex = newValue;\n\t\t\t\tthis._refreshValue();\n\t\t\t} else {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t} else {\n\t\t\treturn this._selectedIndex();\n\t\t}\n\t},\n\n\tvalue: function(newValue) {\n\t\tif (arguments.length) {\n\t\t\tthis.element[0].value = newValue;\n\t\t\tthis._refreshValue();\n\t\t} else {\n\t\t\treturn this.element[0].value;\n\t\t}\n\t},\n\n\t_refreshValue: function() {\n\t\tvar activeClass = (this.options.style == \"popup\") ? \" ui-state-active\" : \"\";\n\t\tvar activeID = this.widgetBaseClass + '-item-' + Math.round(Math.random() * 1000);\n\t\t// deselect previous\n\t\tthis.list\n\t\t\t.find('.' + this.widgetBaseClass + '-item-selected')\n\t\t\t.removeClass(this.widgetBaseClass + \"-item-selected\" + activeClass)\n\t\t\t.find('a')\n\t\t\t.attr('aria-selected', 'false')\n\t\t\t.attr('id', '');\n\t\t// select new\n\t\tthis._selectedOptionLi()\n\t\t\t.addClass(this.widgetBaseClass + \"-item-selected\" + activeClass)\n\t\t\t.find('a')\n\t\t\t.attr('aria-selected', 'true')\n\t\t\t.attr('id', activeID);\n\n\t\t// toggle any class brought in from option\n\t\tvar currentOptionClasses = (this.newelement.data('optionClasses') ? this.newelement.data('optionClasses') : \"\");\n\t\tvar newOptionClasses = (this._selectedOptionLi().data('optionClasses') ? this._selectedOptionLi().data('optionClasses') : \"\");\n\t\tthis.newelement\n\t\t\t.removeClass(currentOptionClasses)\n\t\t\t.data('optionClasses', newOptionClasses)\n\t\t\t.addClass( newOptionClasses )\n\t\t\t.find('.' + this.widgetBaseClass + '-status')\n\t\t\t.html(\n\t\t\t\tthis._selectedOptionLi()\n\t\t\t\t\t.find('a:eq(0)')\n\t\t\t\t\t.html()\n\t\t\t);\n\n\t\tthis.list.attr('aria-activedescendant', activeID);\n\t},\n\n\t_refreshPosition: function() {\n\t\tvar o = this.options;\n\t\t// if its a native pop-up we need to calculate the position of the selected li\n\t\tif (o.style == \"popup\" && !o.positionOptions.offset) {\n\t\t\tvar selected = this._selectedOptionLi();\n\t\t\tvar _offset = \"0 -\" + (selected.outerHeight() + selected.offset().top - this.list.offset().top);\n\t\t}\n\t\t// update zIndex if jQuery UI is able to process\n\t\tvar zIndexElement = this.element.zIndex();\n\t\tif (zIndexElement) {\n\t\t\tthis.list.css({\n\t\t\t\tzIndex: zIndexElement\n\t\t\t});\n\t\t}\n\t\tthis.list.position({\n\t\t\t\t// set options for position plugin\n\t\t\t\tof: o.positionOptions.of || this.newelement,\n\t\t\t\tmy: o.positionOptions.my,\n\t\t\t\tat: o.positionOptions.at,\n\t\t\t\toffset: o.positionOptions.offset || _offset,\n\t\t\t\tcollision: o.positionOptions.collision || 'flip'\n\t\t\t});\n\t}\n});\n\n})(jQuery);\n"}, "files_after": {"demos/selectmenu/overlay.html": "\ufeff\r\n \r\n \r\n \r\n OpenLayers Google Layer Example\r\n \r\n \r\n \r\n \r\n\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\r\n\r\n \r\n \r\n \r\n \r\n \r\n

        Google Layer Example

        \r\n\r\n
        \r\n Google\r\n
        \r\n\r\n

        \r\n Demonstrate use of the various types of Google layers.\r\n

        \r\n \r\n
        \r\n\r\n \r\n", "demos/selectmenu/refresh.html": "\n\n\t\n\t\n\tDemo Page for jQuery UI selectmenu\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\n\t\n\t\n\n
        \n


        \n
        \n \n \n
        \n


        \n\t\n\t
        \n \n
        \n\n", "demos/selectmenu/typeahead.html": "\n\n\t\n\t\n\tDemo Page for jQuery UI selectmenu\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\n\t\n\t\n\n\n\t
        \n\t
        \n\t
        \n\t\t
        \n\t\t\t\n\t\t\t\t\n\t\t
        \n\t
        \n\n", "tests/unit/selectmenu/normalselect.html": "\n\n\n\n\n\t

        Normal select menu

        \n\t\n", "tests/unit/selectmenu/selectmenu.html": "\n\n\n\t\n\tjQuery UI SelectMenu Test Suite\n\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\n\t\t\n\n\n\n\n

        jQuery UI SelectMenu Test Suite

        \n

        \n

        \n
          \n
        \n\n\n", "tests/unit/selectmenu/selectmenu_typeahead_sequential.js": "/*\n * selectmenu_typeahead_sequential.js\n */\n(function($) {\n\n\tvar currentTestId = 0;\n\tvar currentSelectMenu;\n\tvar currentSelectMenuButton;\n\t\n\tvar createKeypressEvent = function(charCode) {\n\t\tvar e = jQuery.Event(\"keypress\");\n\t\te.which = charCode;\n\t\treturn e;\n\t};\n\t\n\tvar s = createKeypressEvent(83);\t\n\tvar j = createKeypressEvent(74);\t\n\tvar o = createKeypressEvent(79);\n\tvar enter = createKeypressEvent(13);\n\tvar down = createKeypressEvent(40);\n\t\n\tvar jOptions = [\n\t\t'James',\n\t\t'John',\n\t\t'Jzer'\t\t\n\t];\n\t\n\tvar sOptions = [\n\t\t'Sam',\n\t\t'Shirly'\n\t];\n\t\n\tvar setupSelectMenu = function(id) {\n\t\tvar fieldset = $('
        ');\n\t\t$('')\n\t\t\t.appendTo(fieldset);\n\t\t$('')\n\t\t\t.appendTo(fieldset);\n\t\t\t\n\t\tfieldset.appendTo('body');\n\t\t$('select#cycling' + id).selectmenu();\n\t\t\n\t\treturn $('select#cycling' + id);\n\t};\n\t\n\tvar setupSelectMenuWithSOptionSelected = function(id) {\n\t\tvar fieldset = $('
        ');\n\t\t$('')\n\t\t\t.appendTo(fieldset);\n\t\t$('')\n\t\t\t.appendTo(fieldset);\n\t\t\t\n\t\tfieldset.appendTo('body');\n\t\t$('select#cycling' + id).selectmenu();\n\t\t\n\t\treturn $('select#cycling' + id);\n\t};\n\t\n\tvar teardownSelectMenu = function(id) {\n\t\t$('select#cycling' + id + '').selectmenu(\"destroy\").remove();\n\t\t$('label[for=\"cycling' + id + '\"]').remove();\n\t\t$('fieldset#field' + id).remove();\n\t};\n\n\tmodule(\"selectmenu: sequential typeahead - given three items starts with 'j' and two items start with s\", {\n\t\tsetup: function() {\n\t\t\tcurrentSelectMenu = setupSelectMenu(currentTestId);\n\t\t\tcurrentSelectMenuButton = $('#cycling' + currentTestId + '-button');\t\t\t\n\t\t\tcurrentSelectMenuButton.trigger('mousedown.selectmenu');\n\t\t},\n\t\tteardown: function() {\n\t\t\t//teardownSelectMenu(currentTestId);\n\t\t\tcurrentTestId++;\n\t\t}\n\t});\n\n\ttest(\"one 'j' should select first item that starts with j\", function() {\n\t\tcurrentSelectMenuButton.trigger(j);\n\t\tcurrentSelectMenuButton.trigger(enter);\n\t\t\n\t\tequals(currentSelectMenu.val(), jOptions[0]);\n\t});\n\t\n\ttest(\"two 'j' should select second item that starts with j\", function() {\n\t\tcurrentSelectMenuButton.trigger(j);\n\t\tcurrentSelectMenuButton.trigger(j);\n\t\t\n\t\tequals(currentSelectMenu.val(), jOptions[1]);\n\t});\n\t\n\ttest(\"three 'j' should select third item that starts with j\", function() {\n\t\tcurrentSelectMenuButton.trigger(j);\n\t\tcurrentSelectMenuButton.trigger(j);\n\t\tcurrentSelectMenuButton.trigger(j);\n\t\t\n\t\tequals(currentSelectMenu.val(), jOptions[2])\n\t});\n\t\n\ttest(\"four 'j' should select first item that starts with j\", function() {\n\t\tcurrentSelectMenuButton.trigger(j);\n\t\tcurrentSelectMenuButton.trigger(j);\n\t\tcurrentSelectMenuButton.trigger(j);\n\t\tcurrentSelectMenuButton.trigger(j);\n\t\t\n\t\tequals(currentSelectMenu.val(), jOptions[0])\n\t});\n\t\n\ttest(\"typing 'jo' should select first item that starts with 'jo'\", function() {\n\t\tcurrentSelectMenuButton.trigger(j);\n\t\tcurrentSelectMenuButton.trigger(o);\n\t\t\n\t\tvar firstOptionThatStartsWithJO = jOptions[1];\n\t\t\n\t\tequals(currentSelectMenu.val(), firstOptionThatStartsWithJO)\n\t});\n\t\n\ttest(\"one 's' should select first item that starts with s\", function() {\t\t\n\t\tcurrentSelectMenuButton.trigger(s);\n\t\t\n\t\tequals(currentSelectMenu.val(), sOptions[0]);\n\t});\n\t\n\ttest(\"one 's' followed by two 'j' should select second item that starts with j\", function() {\t\t\n\t\tcurrentSelectMenuButton.trigger(s);\n\t\tcurrentSelectMenuButton.trigger(enter);\n\t\t\n\t\tcurrentSelectMenuButton.trigger(j);\n\t\tcurrentSelectMenuButton.trigger(j);\n\t\tcurrentSelectMenuButton.trigger(enter);\n\t\t\n\t\tequals( currentSelectMenu.val(), jOptions[1]);\n\t});\n\t\n\ttest(\"'sjs' should select first item that starts with s\", function() {\t\t\n\t\tcurrentSelectMenuButton.trigger(s);\t\t\n\t\tcurrentSelectMenuButton.trigger(j);\n\t\tcurrentSelectMenuButton.trigger(s);\n\t\t\n\t\tequals( currentSelectMenu.val(), sOptions[0]);\n\t});\n\t\n})(jQuery);", "ui/jquery.ui.selectmenu.js": " /*\n * jQuery UI selectmenu dev version\n *\n * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)\n * Dual licensed under the MIT (MIT-LICENSE.txt)\n * and GPL (GPL-LICENSE.txt) licenses.\n *\n * http://docs.jquery.com/UI\n * https://github.com/fnagel/jquery-ui/wiki/Selectmenu\n */\n\n(function($) {\n\n$.widget(\"ui.selectmenu\", {\n\tgetter: \"value\",\n\tversion: \"1.8\",\n\teventPrefix: \"selectmenu\",\n\toptions: {\n\t\ttransferClasses: true,\n\t\ttypeAhead: \"sequential\",\n\t\tstyle: 'dropdown',\n\t\tpositionOptions: {\n\t\t\tmy: \"left top\",\n\t\t\tat: \"left bottom\",\n\t\t\toffset: null\n\t\t},\n\t\twidth: null,\n\t\tmenuWidth: null,\n\t\thandleWidth: 26,\n\t\tmaxHeight: null,\n\t\ticons: null,\n\t\tformat: null,\n\t\tbgImage: function() {},\n\t\twrapperElement: \"\"\n\t},\n\n\t_create: function() {\n\t\tvar self = this, o = this.options;\n\n\t\t// set a default id value, generate a new random one if not set by developer\n\t\tvar selectmenuId = this.element.attr('id') || 'ui-selectmenu-' + Math.random().toString(16).slice(2, 10);\n\n\t\t// quick array of button and menu id's\n\t\tthis.ids = [ selectmenuId + '-button', selectmenuId + '-menu' ];\n\n\t\t// define safe mouseup for future toggling\n\t\tthis._safemouseup = true;\n\n\t\t// create menu button wrapper\n\t\tthis.newelement = $('')\n\t\t\t.insertAfter(this.element);\n\t\tthis.newelement.wrap(o.wrapperElement);\n\n\t\t// transfer tabindex\n\t\tvar tabindex = this.element.attr('tabindex');\n\t\tif (tabindex) {\n\t\t\tthis.newelement.attr('tabindex', tabindex);\n\t\t}\n\n\t\t// save reference to select in data for ease in calling methods\n\t\tthis.newelement.data('selectelement', this.element);\n\n\t\t// menu icon\n\t\tthis.selectmenuIcon = $('')\n\t\t\t.prependTo(this.newelement);\n\n\t\t// append status span to button\n\t\tthis.newelement.prepend('');\n\n\t\t// make associated form label trigger focus\n\t\t$( 'label[for=\"' + selectmenuId + '\"]' )\n\t\t\t.attr( 'for', this.ids[0] )\n\t\t\t.bind( 'click.selectmenu', function() {\n\t\t\t\tself.newelement[0].focus();\n\t\t\t\treturn false;\n\t\t\t});\n\n\t\t// click toggle for menu visibility\n\t\tthis.newelement\n\t\t\t.bind('mousedown.selectmenu', function(event) {\n\t\t\t\tself._toggle(event, true);\n\t\t\t\t// make sure a click won't open/close instantly\n\t\t\t\tif (o.style == \"popup\") {\n\t\t\t\t\tself._safemouseup = false;\n\t\t\t\t\tsetTimeout(function() { self._safemouseup = true; }, 300);\n\t\t\t\t}\n\t\t\t\treturn false;\n\t\t\t})\n\t\t\t.bind('click.selectmenu', function() {\n\t\t\t\treturn false;\n\t\t\t})\n\t\t\t.bind(\"keydown.selectmenu\", function(event) {\n\t\t\t\tvar ret = false;\n\t\t\t\tswitch (event.keyCode) {\n\t\t\t\t\tcase $.ui.keyCode.ENTER:\n\t\t\t\t\t\tret = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase $.ui.keyCode.SPACE:\n\t\t\t\t\t\tself._toggle(event);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase $.ui.keyCode.UP:\n\t\t\t\t\t\tif (event.altKey) {\n\t\t\t\t\t\t\tself.open(event);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tself._moveSelection(-1);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase $.ui.keyCode.DOWN:\n\t\t\t\t\t\tif (event.altKey) {\n\t\t\t\t\t\t\tself.open(event);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tself._moveSelection(1);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase $.ui.keyCode.LEFT:\n\t\t\t\t\t\tself._moveSelection(-1);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase $.ui.keyCode.RIGHT:\n\t\t\t\t\t\tself._moveSelection(1);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase $.ui.keyCode.TAB:\n\t\t\t\t\t\tret = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tret = true;\n\t\t\t\t}\n\t\t\t\treturn ret;\n\t\t\t})\n\t\t\t.bind('keypress.selectmenu', function(event) {\n\t\t\t\tself._typeAhead(event.which, 'mouseup');\n\t\t\t\treturn true;\n\t\t\t})\n\t\t\t.bind('mouseover.selectmenu focus.selectmenu', function() {\n\t\t\t\tif (!o.disabled) {\n\t\t\t\t\t$(this).addClass(self.widgetBaseClass + '-focus ui-state-hover');\n\t\t\t\t}\n\t\t\t})\n\t\t\t.bind('mouseout.selectmenu blur.selectmenu', function() {\n\t\t\t\tif (!o.disabled) {\n\t\t\t\t\t$(this).removeClass(self.widgetBaseClass + '-focus ui-state-hover');\n\t\t\t\t}\n\t\t\t});\n\n\t\t// document click closes menu\n\t\t$(document).bind(\"mousedown.selectmenu\", function(event) {\n\t\t\tself.close(event);\n\t\t});\n\n\t\t// change event on original selectmenu\n\t\tthis.element\n\t\t\t.bind(\"click.selectmenu\", function() {\n\t\t\t\tself._refreshValue();\n\t\t\t})\n\t\t\t// FIXME: newelement can be null under unclear circumstances in IE8\n\t\t\t// TODO not sure if this is still a problem (fnagel 20.03.11)\n\t\t\t.bind(\"focus.selectmenu\", function() {\n\t\t\t\tif (self.newelement) {\n\t\t\t\t\tself.newelement[0].focus();\n\t\t\t\t}\n\t\t\t});\n\n\t\t// set width when not set via options\n\t\tif (!o.width) {\n\t\t\to.width = this.element.outerWidth();\n\t\t}\n\t\t// set menu button width\n\t\tthis.newelement.width(o.width);\n\n\t\t// hide original selectmenu element\n\t\tthis.element.hide();\n\n\t\t// create menu portion, append to body\n\t\tthis.list = $('
          ').appendTo('body');\n\t\tthis.list.wrap(o.wrapperElement);\n\n\t\t// transfer menu click to menu button\n\t\tthis.list\n\t\t\t.bind(\"keydown.selectmenu\", function(event) {\n\t\t\t\tvar ret = false;\n\t\t\t\tswitch (event.keyCode) {\n\t\t\t\t\tcase $.ui.keyCode.UP:\n\t\t\t\t\t\tif (event.altKey) {\n\t\t\t\t\t\t\tself.close(event, true);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tself._moveFocus(-1);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase $.ui.keyCode.DOWN:\n\t\t\t\t\t\tif (event.altKey) {\n\t\t\t\t\t\t\tself.close(event, true);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tself._moveFocus(1);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase $.ui.keyCode.LEFT:\n\t\t\t\t\t\tself._moveFocus(-1);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase $.ui.keyCode.RIGHT:\n\t\t\t\t\t\tself._moveFocus(1);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase $.ui.keyCode.HOME:\n\t\t\t\t\t\tself._moveFocus(':first');\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase $.ui.keyCode.PAGE_UP:\n\t\t\t\t\t\tself._scrollPage('up');\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase $.ui.keyCode.PAGE_DOWN:\n\t\t\t\t\t\tself._scrollPage('down');\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase $.ui.keyCode.END:\n\t\t\t\t\t\tself._moveFocus(':last');\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase $.ui.keyCode.ENTER:\n\t\t\t\t\tcase $.ui.keyCode.SPACE:\n\t\t\t\t\t\tself.close(event, true);\n\t\t\t\t\t\t$(event.target).parents('li:eq(0)').trigger('mouseup');\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase $.ui.keyCode.TAB:\n\t\t\t\t\t\tret = true;\n\t\t\t\t\t\tself.close(event, true);\n\t\t\t\t\t\t$(event.target).parents('li:eq(0)').trigger('mouseup');\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase $.ui.keyCode.ESCAPE:\n\t\t\t\t\t\tself.close(event, true);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tret = true;\n\t\t\t\t}\n\t\t\t\treturn ret;\n\t\t\t})\n\t\t\t.bind('keypress.selectmenu', function(event) {\n\t\t\t\tself._typeAhead(event.which, 'focus');\n\t\t\t\treturn true;\n\t\t\t})\n\t\t\t// this allows for using the scrollbar in an overflowed list\n\t\t\t.bind( 'mousedown.selectmenu mouseup.selectmenu', function() { return false; });\n\n\n\t\t// needed when window is resized\n\t\t$(window).bind( \"resize.selectmenu\", $.proxy( self._refreshPosition, this ) );\n\t},\n\n\t_init: function() {\n\t\tvar self = this, o = this.options;\n\n\t\t// serialize selectmenu element options\n\t\tvar selectOptionData = [];\n\t\tthis.element\n\t\t\t.find('option')\n\t\t\t.each(function() {\n\t\t\t\tvar opt = $(this);\n\t\t\t\tselectOptionData.push({\n\t\t\t\t\tvalue: opt.attr('value'),\n\t\t\t\t\ttext: self._formatText($(this).text()),\n\t\t\t\t\tselected: opt.attr('selected'),\n\t\t\t\t\tdisabled: opt.attr('disabled'),\n\t\t\t\t\tclasses: opt.attr('class'),\n\t\t\t\t\ttypeahead: opt.attr('typeahead'),\n\t\t\t\t\tparentOptGroup: opt.parent('optgroup'),\n\t\t\t\t\tbgImage: o.bgImage.call(opt)\n\t\t\t\t});\n\t\t\t});\n\n\t\t// active state class is only used in popup style\n\t\tvar activeClass = (self.options.style == \"popup\") ? \" ui-state-active\" : \"\";\n\n\t\t// empty list so we can refresh the selectmenu via selectmenu()\n\t\tthis.list.html(\"\");\n\n\t\t// write li's\n\t\tif (selectOptionData.length) {\n\t\t\tfor (var i = 0; i < selectOptionData.length; i++) {\n\t\t\t\tvar thisLi = $('
        • '+ selectOptionData[i].text +'
        • ')\n\t\t\t\t\t.data('index', i)\n\t\t\t\t\t.addClass(selectOptionData[i].classes)\n\t\t\t\t\t.data('optionClasses', selectOptionData[i].classes || '')\n\t\t\t\t\t.bind(\"mouseup.selectmenu\", function(event) {\n\t\t\t\t\t\tif (self._safemouseup && !self._disabled(event.currentTarget) && !self._disabled($( event.currentTarget ).parents( \"ul>li.\" + self.widgetBaseClass + \"-group \" )) ) {\n\t\t\t\t\t\t\tvar changed = $(this).data('index') != self._selectedIndex();\n\t\t\t\t\t\t\tself.index($(this).data('index'));\n\t\t\t\t\t\t\tself.select(event);\n\t\t\t\t\t\t\tif (changed) {\n\t\t\t\t\t\t\t\tself.change(event);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tself.close(event, true);\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t})\n\t\t\t\t\t.bind(\"click.selectmenu\", function() {\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t})\n\t\t\t\t\t.bind('mouseover.selectmenu focus.selectmenu', function(e) {\n\t\t\t\t\t\t// no hover if diabled\n\t\t\t\t\t\tif (!$(e.currentTarget).hasClass(self.namespace + '-state-disabled') && !$(e.currentTarget).parent(\"ul\").parent(\"li\").hasClass(self.namespace + '-state-disabled')) {\n\t\t\t\t\t\t\tself._selectedOptionLi().addClass(activeClass);\n\t\t\t\t\t\t\tself._focusedOptionLi().removeClass(self.widgetBaseClass + '-item-focus ui-state-hover');\n\t\t\t\t\t\t\t$(this).removeClass('ui-state-active').addClass(self.widgetBaseClass + '-item-focus ui-state-hover');\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t\t.bind('mouseout.selectmenu blur.selectmenu', function() {\n\t\t\t\t\t\tif ($(this).is(self._selectedOptionLi().selector)) {\n\t\t\t\t\t\t\t$(this).addClass(activeClass);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t$(this).removeClass(self.widgetBaseClass + '-item-focus ui-state-hover');\n\t\t\t\t\t});\n\n\t\t\t\t// optgroup or not...\n\t\t\t\tif ( selectOptionData[i].parentOptGroup.length ) {\n\t\t\t\t\tvar optGroupName = self.widgetBaseClass + '-group-' + this.element.find( 'optgroup' ).index( selectOptionData[i].parentOptGroup );\n\t\t\t\t\tif (this.list.find( 'li.' + optGroupName ).length ) {\n\t\t\t\t\t\tthis.list.find( 'li.' + optGroupName + ':last ul' ).append( thisLi );\n\t\t\t\t\t} else {\n\t\t\t\t\t\t$('
        • ' + selectOptionData[i].parentOptGroup.attr('label') + '
          • ')\n\t\t\t\t\t\t\t.appendTo( this.list )\n\t\t\t\t\t\t\t.find( 'ul' )\n\t\t\t\t\t\t\t.append( thisLi );\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tthisLi.appendTo(this.list);\n\t\t\t\t}\n\n\t\t\t\t// append icon if option is specified\n\t\t\t\tif (o.icons) {\n\t\t\t\t\tfor (var j in o.icons) {\n\t\t\t\t\t\tif (thisLi.is(o.icons[j].find)) {\n\t\t\t\t\t\t\tthisLi\n\t\t\t\t\t\t\t\t.data('optionClasses', selectOptionData[i].classes + ' ' + self.widgetBaseClass + '-hasIcon')\n\t\t\t\t\t\t\t\t.addClass(self.widgetBaseClass + '-hasIcon');\n\t\t\t\t\t\t\tvar iconClass = o.icons[j].icon || \"\";\n\t\t\t\t\t\t\tthisLi\n\t\t\t\t\t\t\t\t.find('a:eq(0)')\n\t\t\t\t\t\t\t\t.prepend('');\n\t\t\t\t\t\t\tif (selectOptionData[i].bgImage) {\n\t\t\t\t\t\t\t\tthisLi.find('span').css('background-image', selectOptionData[i].bgImage);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\t$('
          • ').appendTo(this.list);\n\t\t}\n\t\t// we need to set and unset the CSS classes for dropdown and popup style\n\t\tvar isDropDown = ( o.style == 'dropdown' );\n\t\tthis.newelement\n\t\t\t.toggleClass( self.widgetBaseClass + '-dropdown', isDropDown )\n\t\t\t.toggleClass( self.widgetBaseClass + '-popup', !isDropDown );\n\t\tthis.list\n\t\t\t.toggleClass( self.widgetBaseClass + '-menu-dropdown ui-corner-bottom', isDropDown )\n\t\t\t.toggleClass( self.widgetBaseClass + '-menu-popup ui-corner-all', !isDropDown )\n\t\t\t// add corners to top and bottom menu items\n\t\t\t.find( 'li:first' )\n\t\t\t.toggleClass( 'ui-corner-top', !isDropDown )\n\t\t\t.end().find( 'li:last' )\n\t\t\t.addClass( 'ui-corner-bottom' );\n\t\tthis.selectmenuIcon\n\t\t\t.toggleClass( 'ui-icon-triangle-1-s', isDropDown )\n\t\t\t.toggleClass( 'ui-icon-triangle-2-n-s', !isDropDown );\n\n\t\t// transfer classes to selectmenu and list\n\t\tif ( o.transferClasses ) {\n\t\t\tvar transferClasses = this.element.attr( 'class' ) || '';\n\t\t\tthis.newelement.add( this.list ).addClass( transferClasses );\n\t\t}\n\n\t\t// set menu width to either menuWidth option value, width option value, or select width\n\t\tif ( o.style == 'dropdown' ) {\n\t\t\tthis.list.width( o.menuWidth ? o.menuWidth : o.width );\n\t\t} else {\n\t\t\tthis.list.width( o.menuWidth ? o.menuWidth : o.width - o.handleWidth );\n\t\t}\n\t\to.minMenuWidth && this.list.width() < o.minMenuWidth && this.list.width(o.minMenuWidth);\n\n\t\t// reset height to auto\n\t\tthis.list.css(\"height\", \"auto\");\n\t\tvar listH = this.list.height();\n\t\t// calculate default max height\n\t\tif ( o.maxHeight && o.maxHeight < listH) {\n\t\t\tthis.list.height( o.maxHeight );\n\t\t} else {\n\t\t\tvar winH = $( window ).height() / 3;\n\t\t\tif ( winH < listH ) this.list.height( winH );\t\n\t\t}\n\t\t\n\t\t// save reference to actionable li's (not group label li's)\n\t\tthis._optionLis = this.list.find( 'li:not(.' + self.widgetBaseClass + '-group)' );\n\n\t\t// transfer disabled state\n\t\tif ( this.element.attr( 'disabled' ) === true ) {\n\t\t\tthis.disable();\n\t\t} else {\n\t\t\tthis.enable()\n\t\t}\n\t\t\n\t\t// update value\n\t\tthis.index( this._selectedIndex() );\n\n\t\t// needed when selectmenu is placed at the very bottom / top of the page\n\t\twindow.setTimeout( function() {\n\t\t\tself._refreshPosition();\n\t\t}, 200 );\n\t},\n\n\tdestroy: function() {\n\t\tthis.element.removeData( this.widgetName )\n\t\t\t.removeClass( this.widgetBaseClass + '-disabled' + ' ' + this.namespace + '-state-disabled' )\n\t\t\t.removeAttr( 'aria-disabled' )\n\t\t\t.unbind( \".selectmenu\" );\n\n\t\t$( window ).unbind( \".selectmenu\" );\n\t\t$( document ).unbind( \".selectmenu\" );\n\n\t\t// unbind click on label, reset its for attr\n\t\t$( 'label[for=' + this.newelement.attr('id') + ']' )\n\t\t\t.attr( 'for', this.element.attr( 'id' ) )\n\t\t\t.unbind( '.selectmenu' );\n\n\t\tif ( this.options.wrapperElement ) {\n\t\t\tthis.newelement.find( this.options.wrapperElement ).remove();\n\t\t\tthis.list.find( this.options.wrapperElement ).remove();\n\t\t} else {\n\t\t\tthis.newelement.remove();\n\t\t\tthis.list.remove();\n\t\t}\n\t\tthis.element.show();\n\n\t\t// call widget destroy function\n\t\t$.Widget.prototype.destroy.apply(this, arguments);\n\t},\n\n\t_typeAhead: function(code, eventType){\n\t\tvar self = this, focusFound = false, C = String.fromCharCode(code).toUpperCase(), c = C.toLowerCase();\n\n\t\tif (self.options.typeAhead == 'sequential') {\n\t\t\tvar currentFocusedPosition = {\n\t\t\t\tget: function() {\n\t\t\t\t\tif (typeof(self._currentFocusedPosition) === 'undefined') {\n\t\t\t\t\t\tself._currentFocusedPosition = {};\n\t\t\t\t\t}\n\t\t\t\t\treturn self._currentFocusedPosition;\n\t\t\t\t},\n\t\t\t\treset:function() {\n\t\t\t\t\tself._currentFocusedPosition = {};\n\t\t\t\t}\n\t\t\t};\n\t\t\t\n\t\t\tvar prevChars = {\n\t\t\t\tisEmpty: function() {\n\t\t\t\t\treturn typeof(self._prevChar) === 'undefined';\n\t\t\t\t},\n\t\t\t\tlastCharIsNotEqualTo: function(character) {\n\t\t\t\t\treturn (self._prevChar[self._prevChar.length - 1] !== character.toLowerCase() && \n\t\t\t\t\t\tself._prevChar[self._prevChar.length - 1] !== character.toUpperCase());\n\t\t\t\t},\n\t\t\t\ttoString: function() {\n\t\t\t\t\treturn typeof(self._prevChar) === 'undefined' ? \n\t\t\t\t\t\t'' : \n\t\t\t\t\t\tself._prevChar.join('');\n\t\t\t\t},\n\t\t\t\treset: function() {\n\t\t\t\t\tself._prevChar = undefined;\n\t\t\t\t},\n\t\t\t\tadd: function(c) {\n\t\t\t\t\ttypeof(self._prevChar) === 'undefined' ? \n\t\t\t\t\t\tself._prevChar = [c] : \n\t\t\t\t\t\tself._prevChar[self._prevChar.length] = c;\n\t\t\t\t}\t\t\t\n\t\t\t};\t\t\n\n\t\t\tvar clearPrevCharTimeout = {\n\t\t\t\tget: function() {\n\t\t\t\t\treturn self._clearPrevChar;\n\t\t\t\t},\n\t\t\t\tset: function(value) {\n\t\t\t\t\tself._clearPrevChar = value;\n\t\t\t\t}, \n\t\t\t\texists: function() {\n\t\t\t\t\treturn typeof(self._clearPrevChar) !== 'undefined';\n\t\t\t\t},\n\t\t\t\treset: function() {\n\t\t\t\t\tself._clearPrevChar = undefined;\n\t\t\t\t}\n\t\t\t};\t\t\t\n\n\t\t\t\n\t\t\tfunction startWithSpecification(text, pattern) {\n\t\t\t\treturn (text.toLowerCase().indexOf( pattern.toLowerCase() ) === 0);\n\t\t\t}\n\t\t\t\n\t\t\tfunction lessThanCurrentFocusedPositionSpecification(index, character) {\n\t\t\t\treturn index <= currentFocusedPosition.get()[c];\n\t\t\t}\n\t\t\t\n\t\t\tfunction focusOptSeq(elem){\n\t\t\t\t$(elem).trigger(eventType);\n\t\t\t}\n\t\t\t\n\t\t\tfunction matchIsFound(character, indexOfMatch) {\n\t\t\t\tprevChars.add(character);\t\t\t\t\t\t\t\t\n\t\t\t\tcurrentFocusedPosition.get()[character.toLowerCase()] = indexOfMatch;\n\t\t\t}\n\t\t\t\n\t\t\t\t\t\t\n\t\t\tfunction matchFirstCharFromTheBeginningOfList(listToSearch) {\n\t\t\t\tmatchFirstLetter.call(this, listToSearch);\n\t\t\t}\n\n\t\t\tfunction matchFirstLetter(listToSearch) {\t\t\t\t\n\t\t\t\treturn searchListForCharSuffixedby.apply(this, [listToSearch, '']);\n\t\t\t}\n\t\t\t\n\t\t\tfunction matchByString(listToSearch, pattern) {\t\t\t\t\n\t\t\t\treturn searchListForCharSuffixedby.apply(this, [listToSearch, pattern]);\n\t\t\t}\t\t\n\t\t\t\n\t\t\tfunction matchByFirstCharFromCurrentFocusedPosition(listToSearch) {\n\t\t\t\treturn searchListForCharSuffixedby.apply(this, \n\t\t\t\t\t[listToSearch, '', lessThanCurrentFocusedPositionSpecification]);\n\t\t\t}\n\t\t\t\n\t\t\tfunction searchListForCharSuffixedby(listToSearch, pattern, preCondition) {\t\t\t\n\t\t\t\tvar found = false;\t\n\t\t\t\t\n\t\t\t\tlistToSearch.each(function(i) {\n\t\t\t\t\tif (!found) {\n\t\t\t\t\t\tif (preCondition && preCondition(i, c)) {\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\t\t// allow the typeahead attribute on the option tag for a more specific lookup\n\t\t\t\t\t\tvar thisText = $(this).attr('typeahead') || $(this).text();\n\t\t\t\t\t\t\n\t\t\t\t\t\t// allow the typeahead attribute on the option tag for a more specific lookup\n\t\t\t\t\t\tif ( !startWithSpecification(thisText, (pattern || '') + c) ) {\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tmatchIsFound(c, i);\n\t\t\t\t\t\tfocusOptSeq(this);\n\t\t\t\t\t\tfound = true;\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\t\n\t\t\t\treturn found;\n\t\t\t}\t\n\t\t\t\n\t\t\tfunction doSearch() {\n\t\t\t\tvar listToSearch = this.list.find('li a');\n\t\t\t\t\n\t\t\t\t// for the 1st letter, should select the first item which has the same first letter\n\t\t\t\tif ( prevChars.isEmpty() ) {\n\t\t\t\t\tmatchFirstLetter.call(this, listToSearch);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t// try to match by string first\n\t\t\t\tif ( matchByString.call(this, listToSearch, prevChars.toString()) ) {\n\t\t\t\t\treturn;\n\t\t\t\t}\t\t\t\t\t\n\t\t\t\t\n\t\t\t\t// if previous char is different from current char, flush the currentFocusedPosition\n\t\t\t\tif ( prevChars.lastCharIsNotEqualTo(c) ) {\n\t\t\t\t\tcurrentFocusedPosition.reset();\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t// try to match by the first letter starting from current position\n\t\t\t\tif ( matchByFirstCharFromCurrentFocusedPosition.call(this, listToSearch) ) {\t\t\t\t\n\t\t\t\t\treturn;\n\t\t\t\t}\t\t\t\t\n\t\t\t\t\n\t\t\t\t// lastly, try to rematch from the beginning again\n\t\t\t\tmatchFirstCharFromTheBeginningOfList.call(this, listToSearch);\n\t\t\t}\n\t\t\t\n\t\t\tfunction clearPreviousTimeouts() {\n\t\t\t\t// TODO: it's not very clear what this is needed for?\n\t\t\t\t// clear the timeout so we can use _prevChar\n\t\t\t\twindow.clearTimeout('ui.selectmenu-' + self.selectmenuId);\n\t\t\t\t\n\t\t\t\tif ( clearPrevCharTimeout.exists() ) {\n\t\t\t\t\twindow.clearTimeout( clearPrevCharTimeout.get() );\n\t\t\t\t\tclearPrevCharTimeout.reset();\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tfunction setTimeoutToClear() {\n\t\t\t\t// set a 1 second timeout for sequential typeahead\n\t\t\t\t// keep this set even if we have no matches so it doesnt typeahead somewhere else\t\n\t\t\t\tclearPrevCharTimeout.set(\n\t\t\t\t\twindow.setTimeout(function(el) {\n\t\t\t\t\t\tprevChars.reset();\n\t\t\t\t\t\tcurrentFocusedPosition.reset();\n\t\t\t\t\t}, 1000, self));\n\t\t\t}\n\t\t\t\n\t\t\tclearPreviousTimeouts();\n\t\t\tdoSearch.call(this);\n\t\t\tsetTimeoutToClear();\n\t\t\t\n\t\t} else {\n\t\t\t//define self._prevChar if needed\n\t\t\tif (!self._prevChar){ self._prevChar = ['',0]; }\n\n\t\t\tvar focusFound = false;\n\t\t\tfunction focusOpt(elem, ind){\n\t\t\t\tfocusFound = true;\n\t\t\t\t$(elem).trigger(eventType);\n\t\t\t\tself._prevChar[1] = ind;\n\t\t\t}\n\t\t\tthis.list.find('li a').each(function(i){\n\t\t\t\tif(!focusFound){\n\t\t\t\t\tvar thisText = $(this).text();\n\t\t\t\t\tif( thisText.indexOf(C) == 0 || thisText.indexOf(c) == 0){\n\t\t\t\t\t\t\tif(self._prevChar[0] == C){\n\t\t\t\t\t\t\t\tif(self._prevChar[1] < i){ focusOpt(this,i); }\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse{ focusOpt(this,i); }\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t\tthis._prevChar[0] = C;\n\t\t}\n\t},\n\n\t// returns some usefull information, called by callbacks only\n\t_uiHash: function() {\n\t\tvar index = this.index();\n\t\treturn {\n\t\t\tindex: index,\n\t\t\toption: $(\"option\", this.element).get(index),\n\t\t\tvalue: this.element[0].value\n\t\t};\n\t},\n\n\topen: function(event) {\n\t\tvar self = this;\n\t\tif ( this.newelement.attr(\"aria-disabled\") != 'true' ) {\n\t\t\tthis._closeOthers(event);\n\t\t\tthis.newelement\n\t\t\t\t.addClass('ui-state-active');\n\t\t\tif (self.options.wrapperElement) {\n\t\t\t\tthis.list.parent().appendTo('body');\n\t\t\t} else {\n\t\t\t\tthis.list.appendTo('body');\n\t\t\t}\n\n\t\t\tthis.list.addClass(self.widgetBaseClass + '-open')\n\t\t\t\t.attr('aria-hidden', false);\n\t\t\t\n\t\t\tselected = this.list.find('li:not(.' + self.widgetBaseClass + '-group):eq(' + this._selectedIndex() + ') a');\n\t\t\tif (selected.length) selected[0].focus();\n\t\t\t\n\t\t\tif ( this.options.style == \"dropdown\" ) {\n\t\t\t\tthis.newelement.removeClass('ui-corner-all').addClass('ui-corner-top');\n\t\t\t}\n\t\t\t\n\t\t\tthis._refreshPosition();\n\t\t\tthis._trigger(\"open\", event, this._uiHash());\n\t\t}\n\t},\n\n\tclose: function(event, retainFocus) {\n\t\tif ( this.newelement.is('.ui-state-active') ) {\n\t\t\tthis.newelement\n\t\t\t\t.removeClass('ui-state-active');\n\t\t\tthis.list\n\t\t\t\t.attr('aria-hidden', true)\n\t\t\t\t.removeClass(this.widgetBaseClass + '-open');\n\t\t\tif ( this.options.style == \"dropdown\" ) {\n\t\t\t\tthis.newelement.removeClass('ui-corner-top').addClass('ui-corner-all');\n\t\t\t}\n\t\t\tif ( retainFocus ) {\n\t\t\t\tthis.newelement.focus();\n\t\t\t}\n\t\t\tthis._trigger(\"close\", event, this._uiHash());\n\t\t}\n\t},\n\n\tchange: function(event) {\n\t\tthis.element.trigger(\"change\");\n\t\tthis._trigger(\"change\", event, this._uiHash());\n\t},\n\n\tselect: function(event) {\n\t\tif (this._disabled(event.currentTarget)) { return false; }\n\t\tthis._trigger(\"select\", event, this._uiHash());\n\t},\n\n\t_closeOthers: function(event) {\n\t\t$('.' + this.widgetBaseClass + '.ui-state-active').not(this.newelement).each(function() {\n\t\t\t$(this).data('selectelement').selectmenu('close', event);\n\t\t});\n\t\t$('.' + this.widgetBaseClass + '.ui-state-hover').trigger('mouseout');\n\t},\n\n\t_toggle: function(event, retainFocus) {\n\t\tif ( this.list.is('.' + this.widgetBaseClass + '-open') ) {\n\t\t\tthis.close(event, retainFocus);\n\t\t} else {\n\t\t\tthis.open(event);\n\t\t}\n\t},\n\n\t_formatText: function(text) {\n\t\treturn (this.options.format ? this.options.format(text) : text);\n\t},\n\n\t_selectedIndex: function() {\n\t\treturn this.element[0].selectedIndex;\n\t},\n\n\t_selectedOptionLi: function() {\n\t\treturn this._optionLis.eq(this._selectedIndex());\n\t},\n\n\t_focusedOptionLi: function() {\n\t\treturn this.list.find('.' + this.widgetBaseClass + '-item-focus');\n\t},\n\n\t_moveSelection: function(amt, recIndex) {\n\t\t// do nothing if disabled\n\t\tif (!this.options.disabled) {\n\t\t\tvar currIndex = parseInt(this._selectedOptionLi().data('index') || 0, 10);\n\t\t\tvar newIndex = currIndex + amt;\n\t\t\t// do not loop when using up key\n\n\t\t\tif (newIndex < 0) {\n\t\t\t\tnewIndex = 0;\n\t\t\t}\n\t\t\tif (newIndex > this._optionLis.size() - 1) {\n\t\t\t\tnewIndex = this._optionLis.size() - 1;\n\t\t\t}\n\t\t\t// Occurs when a full loop has been made\n\t\t\tif (newIndex === recIndex) { return false; }\n\n\t\t\tif (this._optionLis.eq(newIndex).hasClass( this.namespace + '-state-disabled' )) {\n\t\t\t\t// if option at newIndex is disabled, call _moveFocus, incrementing amt by one\n\t\t\t\t(amt > 0) ? ++amt : --amt;\n\t\t\t\tthis._moveSelection(amt, newIndex);\n\t\t\t} else {\n\t\t\t\treturn this._optionLis.eq(newIndex).trigger('mouseup');\n\t\t\t}\n\t\t}\n\t},\n\n\t_moveFocus: function(amt, recIndex) {\n\t\tif (!isNaN(amt)) {\n\t\t\tvar currIndex = parseInt(this._focusedOptionLi().data('index') || 0, 10);\n\t\t\tvar newIndex = currIndex + amt;\n\t\t}\n\t\telse {\n\t\t\tvar newIndex = parseInt(this._optionLis.filter(amt).data('index'), 10);\n\t\t}\n\n\t\tif (newIndex < 0) {\n\t\t\tnewIndex = 0;\n\t\t}\n\t\tif (newIndex > this._optionLis.size() - 1) {\n\t\t\tnewIndex = this._optionLis.size() - 1;\n\t\t}\n\n\t\t//Occurs when a full loop has been made\n\t\tif (newIndex === recIndex) { return false; }\n\n\t\tvar activeID = this.widgetBaseClass + '-item-' + Math.round(Math.random() * 1000);\n\n\t\tthis._focusedOptionLi().find('a:eq(0)').attr('id', '');\n\n\t\tif (this._optionLis.eq(newIndex).hasClass( this.namespace + '-state-disabled' )) {\n\t\t\t// if option at newIndex is disabled, call _moveFocus, incrementing amt by one\n\t\t\t(amt > 0) ? ++amt : --amt;\n\t\t\tthis._moveFocus(amt, newIndex);\n\t\t} else {\n\t\t\tthis._optionLis.eq(newIndex).find('a:eq(0)').attr('id',activeID).focus();\n\t\t}\n\n\t\tthis.list.attr('aria-activedescendant', activeID);\n\t},\n\n\t_scrollPage: function(direction) {\n\t\tvar numPerPage = Math.floor(this.list.outerHeight() / this.list.find('li:first').outerHeight());\n\t\tnumPerPage = (direction == 'up' ? -numPerPage : numPerPage);\n\t\tthis._moveFocus(numPerPage);\n\t},\n\n\t_setOption: function(key, value) {\n\t\tthis.options[key] = value;\n\t\t// set\n\t\tif (key == 'disabled') {\n\t\t\tthis.close();\n\t\t\tthis.element\n\t\t\t\t.add(this.newelement)\n\t\t\t\t.add(this.list)[value ? 'addClass' : 'removeClass'](\n\t\t\t\t\tthis.widgetBaseClass + '-disabled' + ' ' +\n\t\t\t\t\tthis.namespace + '-state-disabled')\n\t\t\t\t.attr(\"aria-disabled\", value);\n\t\t}\n\t},\n\n\tdisable: function(index, type){\n\t\t\t// if options is not provided, call the parents disable function\n\t\t\tif ( typeof( index ) == 'undefined' ) {\n\t\t\t\tthis._setOption( 'disabled', true );\n\t\t\t} else {\n\t\t\t\tif ( type == \"optgroup\" ) {\n\t\t\t\t\tthis._disableOptgroup(index);\n\t\t\t\t} else {\n\t\t\t\t\tthis._disableOption(index);\n\t\t\t\t}\n\t\t\t}\n\t},\n\n\tenable: function(index, type) {\n\t\t\t// if options is not provided, call the parents enable function\n\t\t\tif ( typeof( index ) == 'undefined' ) {\n\t\t\t\tthis._setOption('disabled', false);\n\t\t\t} else {\n\t\t\t\tif ( type == \"optgroup\" ) {\n\t\t\t\t\tthis._enableOptgroup(index);\n\t\t\t\t} else {\n\t\t\t\t\tthis._enableOption(index);\n\t\t\t\t}\n\t\t\t}\n\t},\n\n\t_disabled: function(elem) {\n\t\t\treturn $(elem).hasClass( this.namespace + '-state-disabled' );\n\t},\n\n\n\t_disableOption: function(index) {\n\t\t\tvar optionElem = this._optionLis.eq(index);\n\t\t\tif (optionElem) {\n\t\t\t\toptionElem.addClass(this.namespace + '-state-disabled')\n\t\t\t\t\t.find(\"a\").attr(\"aria-disabled\", true);\n\t\t\t\tthis.element.find(\"option\").eq(index).attr(\"disabled\", \"disabled\");\n\t\t\t}\n\t},\n\n\t_enableOption: function(index) {\n\t\t\tvar optionElem = this._optionLis.eq(index);\n\t\t\tif (optionElem) {\n\t\t\t\toptionElem.removeClass( this.namespace + '-state-disabled' )\n\t\t\t\t\t.find(\"a\").attr(\"aria-disabled\", false);\n\t\t\t\tthis.element.find(\"option\").eq(index).removeAttr(\"disabled\");\n\t\t\t}\n\t},\n\n\t_disableOptgroup: function(index) {\n\t\t\tvar optGroupElem = this.list.find( 'li.' + this.widgetBaseClass + '-group-' + index );\n\t\t\tif (optGroupElem) {\n\t\t\t\toptGroupElem.addClass(this.namespace + '-state-disabled')\n\t\t\t\t\t.attr(\"aria-disabled\", true);\n\t\t\t\tthis.element.find(\"optgroup\").eq(index).attr(\"disabled\", \"disabled\");\n\t\t\t}\n\t},\n\n\t_enableOptgroup: function(index) {\n\t\t\tvar optGroupElem = this.list.find( 'li.' + this.widgetBaseClass + '-group-' + index );\n\t\t\tif (optGroupElem) {\n\t\t\t\toptGroupElem.removeClass(this.namespace + '-state-disabled')\n\t\t\t\t\t.attr(\"aria-disabled\", false);\n\t\t\t\tthis.element.find(\"optgroup\").eq(index).removeAttr(\"disabled\");\n\t\t\t}\n\t},\n\n\tindex: function(newValue) {\n\t\tif (arguments.length) {\n\t\t\tif (!this._disabled($(this._optionLis[newValue]))) {\n\t\t\t\tthis.element[0].selectedIndex = newValue;\n\t\t\t\tthis._refreshValue();\n\t\t\t} else {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t} else {\n\t\t\treturn this._selectedIndex();\n\t\t}\n\t},\n\n\tvalue: function(newValue) {\n\t\tif (arguments.length) {\n\t\t\tthis.element[0].value = newValue;\n\t\t\tthis._refreshValue();\n\t\t} else {\n\t\t\treturn this.element[0].value;\n\t\t}\n\t},\n\n\t_refreshValue: function() {\n\t\tvar activeClass = (this.options.style == \"popup\") ? \" ui-state-active\" : \"\";\n\t\tvar activeID = this.widgetBaseClass + '-item-' + Math.round(Math.random() * 1000);\n\t\t// deselect previous\n\t\tthis.list\n\t\t\t.find('.' + this.widgetBaseClass + '-item-selected')\n\t\t\t.removeClass(this.widgetBaseClass + \"-item-selected\" + activeClass)\n\t\t\t.find('a')\n\t\t\t.attr('aria-selected', 'false')\n\t\t\t.attr('id', '');\n\t\t// select new\n\t\tthis._selectedOptionLi()\n\t\t\t.addClass(this.widgetBaseClass + \"-item-selected\" + activeClass)\n\t\t\t.find('a')\n\t\t\t.attr('aria-selected', 'true')\n\t\t\t.attr('id', activeID);\n\n\t\t// toggle any class brought in from option\n\t\tvar currentOptionClasses = (this.newelement.data('optionClasses') ? this.newelement.data('optionClasses') : \"\");\n\t\tvar newOptionClasses = (this._selectedOptionLi().data('optionClasses') ? this._selectedOptionLi().data('optionClasses') : \"\");\n\t\tthis.newelement\n\t\t\t.removeClass(currentOptionClasses)\n\t\t\t.data('optionClasses', newOptionClasses)\n\t\t\t.addClass( newOptionClasses )\n\t\t\t.find('.' + this.widgetBaseClass + '-status')\n\t\t\t.html(\n\t\t\t\tthis._selectedOptionLi()\n\t\t\t\t\t.find('a:eq(0)')\n\t\t\t\t\t.html()\n\t\t\t);\n\n\t\tthis.list.attr('aria-activedescendant', activeID);\n\t},\n\n\t_refreshPosition: function() {\n\t\tvar o = this.options;\n\t\t// if its a native pop-up we need to calculate the position of the selected li\n\t\tif (o.style == \"popup\" && !o.positionOptions.offset) {\n\t\t\tvar selected = this._selectedOptionLi();\n\t\t\tvar _offset = \"0 -\" + (selected.outerHeight() + selected.offset().top - this.list.offset().top);\n\t\t}\n\t\t// update zIndex if jQuery UI is able to process\n\t\tvar zIndexElement = this.element.zIndex();\n\t\tif (zIndexElement) {\n\t\t\tthis.list.css({\n\t\t\t\tzIndex: zIndexElement\n\t\t\t});\n\t\t}\n\t\tthis.list.position({\n\t\t\t\t// set options for position plugin\n\t\t\t\tof: o.positionOptions.of || this.newelement,\n\t\t\t\tmy: o.positionOptions.my,\n\t\t\t\tat: o.positionOptions.at,\n\t\t\t\toffset: o.positionOptions.offset || _offset,\n\t\t\t\tcollision: o.positionOptions.collision || 'flip'\n\t\t\t});\n\t}\n});\n\n})(jQuery);\n"}} -{"repo": "Trepan-Debuggers/remake", "pr_number": 149, "title": "Enable --debugger-stop with -X", "state": "closed", "merged_at": "2023-08-28T03:36:30Z", "additions": 38, "deletions": 39, "files_changed": ["src/main.c"], "files_before": {"src/main.c": "/* Argument parsing and main program of GNU Make.\nCopyright (C) 1988-2020 Free Software Foundation, Inc.\nCopyright (C) 2015, 2017 Rocky Bernstein\nThis file is part of GNU Make.\n\nGNU Make is free software; you can redistribute it and/or modify it under the\nterms of the GNU General Public License as published by the Free Software\nFoundation; either version 3 of the License, or (at your option) any later\nversion.\n\nGNU Make is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE. See the GNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License along with\nthis program. If not, see . */\n\n#include \"makeint.h\"\n#include \"globals.h\"\n#include \"profile.h\"\n#include \"os.h\"\n#include \"filedef.h\"\n#include \"dep.h\"\n#include \"variable.h\"\n#include \"job.h\"\n#include \"commands.h\"\n#include \"rule.h\"\n#include \"debug.h\"\n#include \"getopt.h\"\n// debugger include(s)\n#include \"cmd.h\"\n\n#include \n#ifdef WINDOWS32\n# include \n# include \n#ifdef HAVE_STRINGS_H\n# include \t/* for strcasecmp */\n#endif\n# include \"pathstuff.h\"\n# include \"sub_proc.h\"\n# include \"w32err.h\"\n#endif\n#ifdef HAVE_FCNTL_H\n# include \n#endif\n\nstruct goaldep *read_makefiles;\n\nextern void initialize_stopchar_map ();\n\n#if defined HAVE_WAITPID || defined HAVE_WAIT3\n# define HAVE_WAIT_NOHANG\n#endif\n\n#ifndef HAVE_UNISTD_H\nint chdir ();\n#endif\n#ifndef STDC_HEADERS\n# ifndef sun /* Sun has an incorrect decl in a header. */\nvoid exit (int) NORETURN;\n# endif\ndouble atof ();\n#endif\n\nstatic void clean_jobserver (int status);\nstatic void print_data_base (void);\nvoid print_rule_data_base (bool b_verbose);\nstatic void print_version (void);\nstatic void decode_switches (int argc, const char **argv, int env);\nstatic void decode_env_switches (const char *envar, size_t len);\nstatic struct variable *define_makeflags (int all, int makefile);\nstatic char *quote_for_env (char *out, const char *in);\nstatic void initialize_global_hash_tables (void);\n\n\f\n/* The structure that describes an accepted command switch. */\n\nstruct command_switch\n {\n int c; /* The switch character. */\n\n enum /* Type of the value. */\n {\n flag, /* Turn int flag on. */\n flag_off, /* Turn int flag off. */\n string, /* One string per invocation. */\n strlist, /* One string per switch. */\n filename, /* A string containing a file name. */\n positive_int, /* A positive integer. */\n floating, /* A floating-point number (double). */\n ignore /* Ignored. */\n } type;\n\n void *value_ptr; /* Pointer to the value-holding variable. */\n\n unsigned int env:1; /* Can come from MAKEFLAGS. */\n unsigned int toenv:1; /* Should be put in MAKEFLAGS. */\n unsigned int no_makefile:1; /* Don't propagate when remaking makefiles. */\n\n const void *noarg_value; /* Pointer to value used if no arg given. */\n const void *default_value; /* Pointer to default value. */\n\n const char *long_name; /* Long option name. */\n };\n\n/* True if C is a switch value that corresponds to a short option. */\n\n#define short_option(c) ((c) <= CHAR_MAX)\n\n/* The structure used to hold the list of strings given\n in command switches of a type that takes strlist arguments. */\n\n/* The recognized command switches. */\n\nstatic const int default_silent_flag = 0;\n\n/* Nonzero means either -s was given, or .SILENT-with-no-deps was seen. */\n\nint run_silent = 0;\n\n/*! If non-null, contains the type of tracing we are to do.\n This is coordinated with tracing_flag. */\nstringlist_t *tracing_opts = NULL;\n\n/*! If true, show version information on entry. */\nbool b_show_version = false;\n\n/*! If true, go into debugger on error.\nSets --debugger --debugger-stop=error. */\nint post_mortem_flag = 0;\n\n/*! Nonzero means use GNU readline in the debugger. */\nint use_readline_flag =\n#ifdef HAVE_LIBREADLINE\n 1\n#else\n 0\n#endif\n ;\n\n/*! If nonzero, the basename of filenames is in giving locations. Normally,\n giving a file directory location helps a debugger frontend\n when we change directories. For regression tests it is helpful to\n list just the basename part as that doesn't change from installation\n to installation. Users may have their preferences too.\n*/\nint basename_filenames = 0;\n\n/* Synchronize output (--output-sync). */\n\nchar *output_sync_option = 0;\n\n/* Specify profile output formatting (--profile) */\n\nchar *profile_option = 0;\n\n/* Specify the output directory for profiling information */\n\nstatic struct stringlist *profile_dir_opt = 0;\n\n/* Output level (--verbosity). */\n\nstatic struct stringlist *verbosity_opts;\n\n/* Environment variables override makefile definitions. */\n\n/* Nonzero means keep going even if remaking some file fails (-k). */\n\nint keep_going_flag;\nstatic const int default_keep_going_flag = 0;\n\n/*! Nonzero gives a list of explicit target names that have commands\n AND comments associated with them and exits. Set by option --task-comments\n */\n\nint show_task_comments_flag = 0;\n\n/* Nonzero means ignore print_directory and never print the directory.\n This is necessary because print_directory is set implicitly. */\n\nint inhibit_print_directory = 0;\n\n/* List of makefiles given with -f switches. */\n\nstatic struct stringlist *makefiles = 0;\n\n/* Size of the stack when we started. */\n\n#ifdef SET_STACK_SIZE\nstruct rlimit stack_limit;\n#endif\n\n\n/* Number of job slots for parallelism. */\n\nunsigned int job_slots;\n\n#define INVALID_JOB_SLOTS (-1)\nstatic unsigned int master_job_slots = 0;\nstatic int arg_job_slots = INVALID_JOB_SLOTS;\n\nstatic const int default_job_slots = INVALID_JOB_SLOTS;\n\n/* Value of job_slots that means no limit. */\n\nstatic const int inf_jobs = 0;\n\n/* Authorization for the jobserver. */\n\nstatic char *jobserver_auth = NULL;\n\n/* Handle for the mutex used on Windows to synchronize output of our\n children under -O. */\n\nchar *sync_mutex = NULL;\n\n/* Maximum load average at which multiple jobs will be run.\n Negative values mean unlimited, while zero means limit to\n zero load (which could be useful to start infinite jobs remotely\n but one at a time locally). */\ndouble max_load_average = -1.0;\ndouble default_load_average = -1.0;\n\n/* List of directories given with -C switches. */\n\nstatic struct stringlist *directories = 0;\n\n/* List of include directories given with -I switches. */\n\nstatic struct stringlist *include_directories = 0;\n\n/* List of files given with -o switches. */\n\nstatic struct stringlist *old_files = 0;\n\n/* List of files given with -W switches. */\n\nstatic struct stringlist *new_files = 0;\n\n/* List of strings to be eval'd. */\nstatic struct stringlist *eval_strings = 0;\n\n/* If nonzero, we should just print usage and exit. */\n\nstatic int print_usage_flag = 0;\n\n/*! Do we want to go into a debugger or not?\n Values are \"error\" - enter on errors or fatal errors\n \"fatal\" - enter on fatal errors\n \"goal\" - set to enter debugger before updating goal\n \"preread\" - set to enter debugger before reading makefile(s)\n \"preaction\" - set to enter debugger before performing any\n actions(s)\n \"full\" - \"enter\" + \"error\" + \"fatal\"\n*/\nstatic stringlist_t* debugger_opts = NULL;\n\n/* If nonzero, always build all targets, regardless of whether\n they appear out of date or not. */\nstatic int always_make_set = 0;\nint always_make_flag = 0;\n\n/* If nonzero, we're in the \"try to rebuild makefiles\" phase. */\n\nint rebuilding_makefiles = 0;\n\n\f\n/* The usage output. We write it this way to make life easier for the\n translators, especially those trying to translate to right-to-left\n languages like Hebrew. */\n\nstatic const char *const usage[] =\n {\n N_(\"Options:\\n\"),\n N_(\"\\\n -b, -m Ignored for compatibility.\\n\"),\n N_(\"\\\n -B, --always-make Unconditionally make all targets.\\n\"),\n N_(\"\\\n -c, --search-parent Search parent directories for Makefile.\\n\"),\n N_(\"\\\n -C DIRECTORY, --directory=DIRECTORY\\n\\\n Change to DIRECTORY before doing anything.\\n\"),\n N_(\"\\\n -d Print lots of debugging information.\\n\"),\n N_(\"\\\n --debug[=FLAGS] Print various types of debugging information.\\n\"),\n N_(\"\\\n -e, --environment-overrides\\n\\\n Environment variables override makefiles.\\n\"),\n N_(\"\\\n -E STRING, --eval=STRING Evaluate STRING as a makefile statement.\\n\"),\n N_(\"\\\n -f FILE, --file=FILE, --makefile=FILE\\n\\\n Read FILE as a makefile.\\n\"),\n N_(\"\\\n -h, --help Print this message and exit.\\n\"),\n N_(\"\\\n -i, --ignore-errors Ignore errors from recipes.\\n\"),\n N_(\"\\\n -I DIRECTORY, --include-dir=DIRECTORY\\n\\\n Search DIRECTORY for included makefiles.\\n\"),\n N_(\"\\\n -j [N], --jobs[=N] Allow N jobs at once; infinite jobs with no arg.\\n\"),\n N_(\"\\\n -k, --keep-going Keep going when some targets can't be made.\\n\"),\n N_(\"\\\n -l [N], --load-average[=N], --max-load[=N]\\n\\\n Don't start multiple jobs unless load is below N.\\n\"),\n N_(\"\\\n -L, --check-symlink-times Use the latest mtime between symlinks and target.\\n\"),\n N_(\"\\\n --no-extended-errors Do not give additional error reporting.\\n\"),\n N_(\"\\\n -n, --just-print, --dry-run, --recon\\n\\\n Don't actually run any recipe; just print them.\\n\"),\n N_(\"\\\n -o FILE, --old-file=FILE, --assume-old=FILE\\n\\\n Consider FILE to be very old and don't remake it.\\n\"),\n N_(\"\\\n -O[TYPE], --output-sync[=TYPE]\\n\\\n Synchronize output of parallel jobs by TYPE.\\n\"),\n N_(\"\\\n -p, --print-data-base Print make's internal database.\\n\"),\n N_(\"\\\n -P, --profile[=FORMAT] Print profiling information for each target using FORMAT.\\n\\\n If FORMAT isn't specified, default to \\\"callgrind\\\"\\n\"),\n N_(\"\\\n --profile-directory=DIR Output profiling data to the DIR directory.\\n\"),\n N_(\"\\\n -q, --question Run no recipe; exit status says if up to date.\\n\"),\n N_(\"\\\n -r, --no-builtin-rules Disable the built-in implicit rules.\\n\"),\n N_(\"\\\n -R, --no-builtin-variables Disable the built-in variable settings.\\n\"),\n N_(\"\\\n -s, --silent, --quiet Don't echo recipes.\\n\"),\n N_(\"\\\n --no-silent Echo recipes (disable --silent mode).\\n\"),\n N_(\"\\\n -S, --no-keep-going, --stop\\n\\\n Turns off -k.\\n\"),\n N_(\"\\\n --targets Give list of explicitly-named targets.\\n\"),\n N_(\"\\\n --tasks Give list of targets which have descriptions\\n\\\n associated with them.\\n\"),\n N_(\"\\\n -t, --touch Touch targets instead of remaking them.\\n\"),\n N_(\"\\\n -v, --version Print the version number of make and exit.\\n\"),\n N_(\"\\\n --verbosity=LEVEL Set verbosity level. LEVEL may be \\\"terse\\\" \\\"no-header\\\" or\\n\\\n \\\"full\\\". The default is \\\"full\\\".\\n\"),\n N_(\"\\\n -w, --print-directory Print the current directory.\\n\"),\n N_(\"\\\n --no-print-directory Turn off -w, even if it was turned on implicitly.\\n\"),\n N_(\"\\\n -W FILE, --what-if=FILE, --new-file=FILE, --assume-new=FILE\\n\\\n Consider FILE to be infinitely new.\\n\"),\n N_(\"\\\n --warn-undefined-variables Warn when an undefined variable is referenced.\\n\"),\n N_(\"\\\n -x, --trace[=TYPE] Trace command execution TYPE may be\\n\\\n \\\"command\\\", \\\"read\\\", \\\"normal\\\".\\\"\\n\\\n \\\"noshell\\\", or \\\"full\\\". Default is \\\"normal\\\"\\n\"),\n N_(\"\\\n --debugger-stop[=TYPE] Which point to enter debugger. TYPE may be\\n\\\n \\\"goal\\\", \\\"preread\\\", \\\"preaction\\\",\\n\\\n \\\"full\\\", \\\"error\\\", or \\\"fatal\\\".\\n\\\n Only makes sense with -X set.\\n\"),\n N_(\"\\\n -v, --version Print the version number of make and exit.\\n\"),\n N_(\"\\\n -X, --debugger Enter debugger.\\n\"),\n N_(\"\\\n -!, --post-mortem Go into debugger on error.\\n\\\n Same as --debugger --debugger-stop=error\\n\"),\n N_(\"\\\n --no-readline Do not use GNU ReadLine in debugger.\\n\"),\n NULL\n };\n\n/* The table of command switches.\n Order matters here: this is the order MAKEFLAGS will be constructed.\n So be sure all simple flags (single char, no argument) come first. */\n\nstatic const struct command_switch switches[] =\n {\n { 'b', ignore, 0, 0, 0, 0, 0, 0, 0 },\n { 'B', flag, &always_make_set, 1, 1, 0, 0, 0, \"always-make\" },\n { 'c', flag, &search_parent_flag, 1, 1, 0, 0, 0, \"search-parent\" },\n { 'd', flag, &debug_flag, 1, 1, 0, 0, 0, 0 },\n { 'e', flag, &env_overrides, 1, 1, 0, 0, 0, \"environment-overrides\", },\n { 'h', flag, &print_usage_flag, 0, 0, 0, 0, 0, \"help\" },\n { 'i', flag, &ignore_errors_flag, 1, 1, 0, 0, 0, \"ignore-errors\" },\n { 'k', flag, &keep_going_flag, 1, 1, 0, 0, &default_keep_going_flag,\n \"keep-going\" },\n { 'L', flag, &check_symlink_flag, 1, 1, 0, 0, 0, \"check-symlink-times\" },\n { 'm', ignore, 0, 0, 0, 0, 0, 0, 0 },\n { 'n', flag, &just_print_flag, 1, 1, 1, 0, 0, \"just-print\" },\n { 'p', flag, &print_data_base_flag, 1, 1, 0, 0, 0, \"print-data-base\" },\n { 'P', string, &profile_option, 1, 1, 0, \"callgrind\", 0, \"profile\" },\n { 'q', flag, &question_flag, 1, 1, 1, 0, 0, \"question\" },\n { 'r', flag, &no_builtin_rules_flag, 1, 1, 0, 0, 0, \"no-builtin-rules\" },\n { 'R', flag, &no_builtin_variables_flag, 1, 1, 0, 0, 0,\n \"no-builtin-variables\" },\n { 's', flag, &silent_flag, 1, 1, 0, 0, &default_silent_flag, \"silent\" },\n { 'S', flag_off, &keep_going_flag, 1, 1, 0, 0, &default_keep_going_flag,\n \"no-keep-going\" },\n { 't', flag, &touch_flag, 1, 1, 1, 0, 0, \"touch\" },\n { 'v', flag, &print_version_flag, 1, 1, 0, 0, 0, \"version\" },\n { 'w', flag, &print_directory, 1, 1, 0, 0, 0, \"print-directory\" },\n { 'X', flag, &debugger_flag, 1, 1, 0, 0, 0, \"debugger\" },\n { '!', flag, &post_mortem_flag, 1, 1, 0, 0, 0, \"post-mortem\" },\n\n /* These options take arguments. */\n { 'C', filename, &directories, 0, 0, 0, 0, 0, \"directory\" },\n { 'E', strlist, &eval_strings, 1, 0, 0, 0, 0, \"eval\" },\n { 'f', filename, &makefiles, 0, 0, 0, 0, 0, \"file\" },\n { 'I', filename, &include_directories, 1, 1, 0, 0, 0,\n \"include-dir\" },\n { 'j', positive_int, &arg_job_slots, 1, 1, 0, &inf_jobs, &default_job_slots,\n \"jobs\" },\n { 'l', floating, &max_load_average, 1, 1, 0, &default_load_average,\n &default_load_average, \"load-average\" },\n { 'o', filename, &old_files, 0, 0, 0, 0, 0, \"old-file\" },\n { 'O', string, &output_sync_option, 1, 1, 0, \"target\", 0, \"output-sync\" },\n { 'W', filename, &new_files, 0, 0, 0, 0, 0, \"what-if\" },\n { 'x', strlist, &tracing_opts, 1, 1, 0, \"normal\", 0, \"trace\" },\n\n /* These are long-style options. */\n { CHAR_MAX+1, strlist, &db_flags, 1, 1, 0, \"basic\", 0, \"debug\" },\n { CHAR_MAX+2, string, &jobserver_auth, 1, 1, 0, 0, 0, \"jobserver-auth\" },\n { CHAR_MAX+3, flag, &show_tasks_flag, 0, 0, 0, 0, 0, \"tasks\" },\n { CHAR_MAX+4, flag, &inhibit_print_directory, 1, 1, 0, 0, 0,\n \"no-print-directory\" },\n { CHAR_MAX+5, flag, &warn_undefined_variables_flag, 1, 1, 0, 0, 0,\n \"warn-undefined-variables\" },\n { CHAR_MAX+7, string, &sync_mutex, 1, 1, 0, 0, 0, \"sync-mutex\" },\n { CHAR_MAX+8, flag_off, &silent_flag, 1, 1, 0, 0, &default_silent_flag, \"no-silent\" },\n { CHAR_MAX+9, string, &jobserver_auth, 1, 0, 0, 0, 0, \"jobserver-fds\" },\n { CHAR_MAX+10, strlist, &verbosity_opts, 1, 1, 0, 0, 0,\n \"verbosity\" },\n { CHAR_MAX+11, flag, (char *) &no_extended_errors, 1, 1, 0, 0, 0,\n \"no-extended-errors\", },\n { CHAR_MAX+12, flag_off, (char *) &use_readline_flag, 1, 0, 0, 0, 0,\n \"no-readline\", },\n { CHAR_MAX+13, flag, &show_targets_flag, 0, 0, 0, 0, 0,\n \"targets\" },\n { CHAR_MAX+14, strlist, &debugger_opts, 1, 1, 0, \"preaction\", 0,\n \"debugger-stop\" },\n { CHAR_MAX+15, filename, &profile_dir_opt, 1, 1, 0, 0, 0, \"profile-directory\" },\n { 0, 0, 0, 0, 0, 0, 0, 0, 0 }\n };\n\n/* Secondary long names for options. */\n\nstatic struct option long_option_aliases[] =\n {\n { \"quiet\", no_argument, 0, 's' },\n { \"stop\", no_argument, 0, 'S' },\n { \"new-file\", required_argument, 0, 'W' },\n { \"assume-new\", required_argument, 0, 'W' },\n { \"assume-old\", required_argument, 0, 'o' },\n { \"max-load\", optional_argument, 0, 'l' },\n { \"dry-run\", no_argument, 0, 'n' },\n { \"recon\", no_argument, 0, 'n' },\n { \"makefile\", required_argument, 0, 'f' },\n };\n\n/* List of goal targets. */\n\nstatic struct goaldep *goals, *lastgoal;\n\n/* List of variables which were defined on the command line\n (or, equivalently, in MAKEFLAGS). */\n\nstruct command_variable\n {\n struct command_variable *next;\n struct variable *variable;\n };\nstatic struct command_variable *command_variables;\n\n/*! Value of argv[0] which seems to get modified. Can we merge this with\n program below? */\nchar *argv0 = NULL;\n\n/*! The name we were invoked with. */\n\n/*! Our initial arguments -- used for debugger restart execvp. */\nconst char * const*global_argv;\n\n/*! Our current directory before processing any -C options. */\nchar *directory_before_chdir = NULL;\n\n/*! Pointer to the value of the .DEFAULT_GOAL special variable.\n The value will be the name of the goal to remake if the command line\n does not override it. It can be set by the makefile, or else it's\n the first target defined in the makefile whose name does not start\n with '.'. */\nstruct variable * default_goal_var;\n\n/*! Pointer to structure for the file .DEFAULT\n whose commands are used for any file that has none of its own.\n This is zero if the makefiles do not define .DEFAULT. */\nstruct file *default_file;\n\n/* Nonzero if we have seen the '.SECONDEXPANSION' target.\n This turns on secondary expansion of prerequisites. */\n\nint second_expansion;\n\n/* Nonzero if we have seen the '.ONESHELL' target.\n This causes the entire recipe to be handed to SHELL\n as a single string, potentially containing newlines. */\n\nint one_shell;\n\n/* Nonzero if we have seen the '.NOTPARALLEL' target.\n This turns off parallel builds for this invocation of make. */\n\nint not_parallel;\n\n/* Nonzero if some rule detected clock skew; we keep track so (a) we only\n print one warning about it during the run, and (b) we can print a final\n warning at the end of the run. */\n\nint clock_skew_detected;\n\n/* If output-sync is enabled we'll collect all the output generated due to\n options, while reading makefiles, etc. */\n\nstruct output make_sync;\n\n\f\n/* Mask of signals that are being caught with fatal_error_signal. */\n\n#if defined(POSIX)\nsigset_t fatal_signal_set;\n#elif defined(HAVE_SIGSETMASK)\nint fatal_signal_mask;\n#endif\n\n#if !HAVE_DECL_BSD_SIGNAL && !defined bsd_signal\n# if !defined HAVE_SIGACTION\n# define bsd_signal signal\n# else\ntypedef RETSIGTYPE (*bsd_signal_ret_t) (int);\n\nstatic bsd_signal_ret_t\nbsd_signal (int sig, bsd_signal_ret_t func)\n{\n struct sigaction act, oact;\n act.sa_handler = func;\n act.sa_flags = SA_RESTART;\n sigemptyset (&act.sa_mask);\n sigaddset (&act.sa_mask, sig);\n if (sigaction (sig, &act, &oact) != 0)\n return SIG_ERR;\n return oact.sa_handler;\n}\n# endif\n#endif\n\nvoid\ndecode_trace_flags (stringlist_t *ppsz_tracing_opts)\n{\n if (ppsz_tracing_opts) {\n const char **p;\n db_level |= (DB_TRACE | DB_SHELL);\n if (!ppsz_tracing_opts->list)\n db_level |= (DB_BASIC);\n else\n for (p = ppsz_tracing_opts->list; *p != 0; ++p) {\n if (0 == strcmp(*p, \"command\"))\n ;\n else if (0 == strcmp(*p, \"full\"))\n db_level |= (DB_VERBOSE|DB_READ_MAKEFILES);\n else if (0 == strcmp(*p, \"normal\"))\n db_level |= DB_BASIC;\n else if (0 == strcmp(*p, \"noshell\"))\n db_level = DB_BASIC | DB_TRACE;\n else if (0 == strcmp(*p, \"read\"))\n db_level |= DB_READ_MAKEFILES;\n else\n OS ( fatal, NILF, _(\"unknown trace command execution type `%s'\"), *p);\n }\n }\n}\n\nvoid\ndecode_verbosity_flags (stringlist_t *ppsz_verbosity_opts)\n{\n if (ppsz_verbosity_opts) {\n const char **p;\n if (ppsz_verbosity_opts->list)\n for (p = ppsz_verbosity_opts->list; *p != 0; ++p) {\n if (0 == strcmp(*p, \"no-header\"))\n b_show_version = false;\n else if (0 == strcmp(*p, \"full\")) {\n db_level |= (DB_VERBOSE);\n\t b_show_version = true;\n\t} else if (0 == strcmp(*p, \"terse\")) {\n\t db_level &= (~DB_VERBOSE);\n\t b_show_version = false;\n\t}\n }\n }\n}\n\nstatic void\ninitialize_global_hash_tables (void)\n{\n init_hash_global_variable_set ();\n strcache_init ();\n init_hash_files ();\n hash_init_directories ();\n hash_init_function_table ();\n}\n\n/* This character map locate stop chars when parsing GNU makefiles.\n Each element is true if we should stop parsing on that character. */\n\nstatic const char *\nexpand_command_line_file (const char *name)\n{\n const char *cp;\n char *expanded = 0;\n\n if (name[0] == '\\0')\n O (fatal, NILF, _(\"empty string invalid as file name\"));\n\n if (name[0] == '~')\n {\n expanded = remake_tilde_expand (name);\n if (expanded && expanded[0] != '\\0')\n name = expanded;\n }\n\n /* This is also done in parse_file_seq, so this is redundant\n for names read from makefiles. It is here for names passed\n on the command line. */\n while (name[0] == '.' && name[1] == '/')\n {\n name += 2;\n while (name[0] == '/')\n /* Skip following slashes: \".//foo\" is \"foo\", not \"/foo\". */\n ++name;\n }\n\n if (name[0] == '\\0')\n {\n /* Nothing else but one or more \"./\", maybe plus slashes! */\n name = \"./\";\n }\n\n cp = strcache_add (name);\n\n free (expanded);\n\n return cp;\n}\n\n/* Toggle -d on receipt of SIGUSR1. */\n\n#ifdef SIGUSR1\nstatic RETSIGTYPE\ndebug_signal_handler (int sig UNUSED)\n{\n db_level = db_level ? DB_NONE : DB_BASIC;\n}\n#endif\n\nstatic void\ndecode_debug_flags (void)\n{\n const char **pp;\n\n if (debug_flag)\n db_level = DB_ALL;\n\n if (db_flags)\n for (pp=db_flags->list; *pp; ++pp)\n {\n const char *p = *pp;\n\n while (1)\n {\n switch (tolower (p[0]))\n {\n case 'a':\n db_level |= DB_ALL;\n break;\n case 'b':\n db_level |= DB_BASIC;\n break;\n case 'i':\n db_level |= DB_BASIC | DB_IMPLICIT;\n break;\n case 'j':\n db_level |= DB_JOBS;\n break;\n case 'm':\n db_level |= DB_BASIC | DB_MAKEFILES;\n break;\n case 'n':\n db_level = 0;\n break;\n case 'v':\n db_level |= DB_BASIC | DB_VERBOSE;\n break;\n default:\n OS (fatal, NILF,\n _(\"unknown debug level specification '%s'\"), p);\n }\n\n while (*(++p) != '\\0')\n if (*p == ',' || *p == ' ')\n {\n ++p;\n break;\n }\n\n if (*p == '\\0')\n break;\n }\n }\n\n if (db_level)\n verify_flag = 1;\n\n if (! db_level)\n debug_flag = 0;\n}\n\nstatic void\ndecode_output_sync_flags (void)\n{\n#ifdef NO_OUTPUT_SYNC\n output_sync = OUTPUT_SYNC_NONE;\n#else\n if (output_sync_option)\n {\n if (streq (output_sync_option, \"none\"))\n output_sync = OUTPUT_SYNC_NONE;\n else if (streq (output_sync_option, \"line\"))\n output_sync = OUTPUT_SYNC_LINE;\n else if (streq (output_sync_option, \"target\"))\n output_sync = OUTPUT_SYNC_TARGET;\n else if (streq (output_sync_option, \"recurse\"))\n output_sync = OUTPUT_SYNC_RECURSE;\n else\n OS (fatal, NILF,\n _(\"unknown output-sync type '%s'\"), output_sync_option);\n }\n\n if (sync_mutex)\n RECORD_SYNC_MUTEX (sync_mutex);\n#endif\n}\n\nvoid\ndecode_profile_options(void)\n{\n if (profile_option)\n {\n if (streq (profile_option, \"callgrind\"))\n profile_flag = PROFILE_CALLGRIND;\n else if (streq (profile_option, \"json\"))\n profile_flag = PROFILE_JSON;\n else\n profile_flag = PROFILE_DISABLED;\n }\n else\n {\n profile_flag = PROFILE_DISABLED;\n }\n\n if (profile_dir_opt == NULL)\n {\n profile_directory = starting_directory;\n }\n else\n {\n const char *dir = profile_dir_opt->list[profile_dir_opt->idx - 1];\n if (dir[0] != '/') {\n char directory[GET_PATH_MAX];\n sprintf(directory, \"%s/%s\", starting_directory, dir);\n profile_dir_opt->list[profile_dir_opt->idx - 1] = strcache_add(directory);\n }\n profile_directory = profile_dir_opt->list[profile_dir_opt->idx - 1];\n }\n}\n\n#ifdef WINDOWS32\n\n#ifndef NO_OUTPUT_SYNC\n\n/* This is called from start_job_command when it detects that\n output_sync option is in effect. The handle to the synchronization\n mutex is passed, as a string, to sub-makes via the --sync-mutex\n command-line argument. */\nvoid\nprepare_mutex_handle_string (sync_handle_t handle)\n{\n if (!sync_mutex)\n {\n /* Prepare the mutex handle string for our children. */\n /* 2 hex digits per byte + 2 characters for \"0x\" + null. */\n sync_mutex = xmalloc ((2 * sizeof (sync_handle_t)) + 2 + 1);\n sprintf (sync_mutex, \"0x%Ix\", handle);\n define_makeflags (1, 0);\n }\n}\n\n#endif /* NO_OUTPUT_SYNC */\n\n/*\n * HANDLE runtime exceptions by avoiding a requestor on the GUI. Capture\n * exception and print it to stderr instead.\n *\n * If ! DB_VERBOSE, just print a simple message and exit.\n * If DB_VERBOSE, print a more verbose message.\n * If compiled for DEBUG, let exception pass through to GUI so that\n * debuggers can attach.\n */\nLONG WINAPI\nhandle_runtime_exceptions (struct _EXCEPTION_POINTERS *exinfo)\n{\n PEXCEPTION_RECORD exrec = exinfo->ExceptionRecord;\n LPSTR cmdline = GetCommandLine ();\n LPSTR prg = strtok (cmdline, \" \");\n CHAR errmsg[1024];\n#ifdef USE_EVENT_LOG\n HANDLE hEventSource;\n LPTSTR lpszStrings[1];\n#endif\n\n if (! ISDB (DB_VERBOSE))\n {\n sprintf (errmsg,\n _(\"%s: Interrupt/Exception caught (code = 0x%lx, addr = 0x%p)\\n\"),\n prg, exrec->ExceptionCode, exrec->ExceptionAddress);\n fprintf (stderr, errmsg);\n exit (255);\n }\n\n sprintf (errmsg,\n _(\"\\nUnhandled exception filter called from program %s\\nExceptionCode = %lx\\nExceptionFlags = %lx\\nExceptionAddress = 0x%p\\n\"),\n prg, exrec->ExceptionCode, exrec->ExceptionFlags,\n exrec->ExceptionAddress);\n\n if (exrec->ExceptionCode == EXCEPTION_ACCESS_VIOLATION\n && exrec->NumberParameters >= 2)\n sprintf (&errmsg[strlen(errmsg)],\n (exrec->ExceptionInformation[0]\n ? _(\"Access violation: write operation at address 0x%p\\n\")\n : _(\"Access violation: read operation at address 0x%p\\n\")),\n (PVOID)exrec->ExceptionInformation[1]);\n\n /* turn this on if we want to put stuff in the event log too */\n#ifdef USE_EVENT_LOG\n hEventSource = RegisterEventSource (NULL, \"GNU Make\");\n lpszStrings[0] = errmsg;\n\n if (hEventSource != NULL)\n {\n ReportEvent (hEventSource, /* handle of event source */\n EVENTLOG_ERROR_TYPE, /* event type */\n 0, /* event category */\n 0, /* event ID */\n NULL, /* current user's SID */\n 1, /* strings in lpszStrings */\n 0, /* no bytes of raw data */\n lpszStrings, /* array of error strings */\n NULL); /* no raw data */\n\n (VOID) DeregisterEventSource (hEventSource);\n }\n#endif\n\n /* Write the error to stderr too */\n fprintf (stderr, errmsg);\n\n#ifdef DEBUG\n return EXCEPTION_CONTINUE_SEARCH;\n#else\n exit (255);\n return (255); /* not reached */\n#endif\n}\n\n/*\n * On WIN32 systems we don't have the luxury of a /bin directory that\n * is mapped globally to every drive mounted to the system. Since make could\n * be invoked from any drive, and we don't want to propagate /bin/sh\n * to every single drive. Allow ourselves a chance to search for\n * a value for default shell here (if the default path does not exist).\n */\n\nint\nfind_and_set_default_shell (const char *token)\n{\n int sh_found = 0;\n char *atoken = 0;\n const char *search_token;\n const char *tokend;\n PATH_VAR(sh_path);\n extern const char *default_shell;\n\n if (!token)\n search_token = default_shell;\n else\n search_token = atoken = xstrdup (token);\n\n /* If the user explicitly requests the DOS cmd shell, obey that request.\n However, make sure that's what they really want by requiring the value\n of SHELL either equal, or have a final path element of, \"cmd\" or\n \"cmd.exe\" case-insensitive. */\n tokend = search_token + strlen (search_token) - 3;\n if (((tokend == search_token\n || (tokend > search_token\n && (tokend[-1] == '/' || tokend[-1] == '\\\\')))\n && !strcasecmp (tokend, \"cmd\"))\n || ((tokend - 4 == search_token\n || (tokend - 4 > search_token\n && (tokend[-5] == '/' || tokend[-5] == '\\\\')))\n && !strcasecmp (tokend - 4, \"cmd.exe\")))\n {\n batch_mode_shell = 1;\n unixy_shell = 0;\n sprintf (sh_path, \"%s\", search_token);\n default_shell = xstrdup (w32ify (sh_path, 0));\n DB (DB_VERBOSE, (_(\"find_and_set_shell() setting default_shell = %s\\n\"),\n default_shell));\n sh_found = 1;\n }\n else if (!no_default_sh_exe\n && (token == NULL || !strcmp (search_token, default_shell)))\n {\n /* no new information, path already set or known */\n sh_found = 1;\n }\n else if (_access (search_token, 0) == 0)\n {\n /* search token path was found */\n sprintf (sh_path, \"%s\", search_token);\n default_shell = xstrdup (w32ify (sh_path, 0));\n DB (DB_VERBOSE, (_(\"find_and_set_shell() setting default_shell = %s\\n\"),\n default_shell));\n sh_found = 1;\n }\n else\n {\n char *p;\n struct variable *v = lookup_variable (STRING_SIZE_TUPLE (\"PATH\"));\n\n /* Search Path for shell */\n if (v && v->value)\n {\n char *ep;\n\n p = v->value;\n ep = strchr (p, PATH_SEPARATOR_CHAR);\n\n while (ep && *ep)\n {\n *ep = '\\0';\n\n sprintf (sh_path, \"%s/%s\", p, search_token);\n if (_access (sh_path, 0) == 0)\n {\n default_shell = xstrdup (w32ify (sh_path, 0));\n sh_found = 1;\n *ep = PATH_SEPARATOR_CHAR;\n\n /* terminate loop */\n p += strlen (p);\n }\n else\n {\n *ep = PATH_SEPARATOR_CHAR;\n p = ++ep;\n }\n\n ep = strchr (p, PATH_SEPARATOR_CHAR);\n }\n\n /* be sure to check last element of Path */\n if (p && *p)\n {\n sprintf (sh_path, \"%s/%s\", p, search_token);\n if (_access (sh_path, 0) == 0)\n {\n default_shell = xstrdup (w32ify (sh_path, 0));\n sh_found = 1;\n }\n }\n\n if (sh_found)\n DB (DB_VERBOSE,\n (_(\"find_and_set_shell() path search set default_shell = %s\\n\"),\n default_shell));\n }\n }\n\n /* naive test */\n if (!unixy_shell && sh_found\n && (strstr (default_shell, \"sh\") || strstr (default_shell, \"SH\")))\n {\n unixy_shell = 1;\n batch_mode_shell = 0;\n }\n\n#ifdef BATCH_MODE_ONLY_SHELL\n batch_mode_shell = 1;\n#endif\n\n free (atoken);\n\n return (sh_found);\n}\n#endif /* WINDOWS32 */\n\n#ifdef __MSDOS__\nstatic void\nmsdos_return_to_initial_directory (void)\n{\n if (directory_before_chdir)\n chdir (directory_before_chdir);\n}\n#endif /* __MSDOS__ */\n\nstatic void\nreset_jobserver (void)\n{\n jobserver_clear ();\n free (jobserver_auth);\n jobserver_auth = NULL;\n}\n\nint\nmain (int argc, const char **argv, char **envp)\n{\n static char *stdin_nm = 0;\n int makefile_status = MAKE_SUCCESS;\n PATH_VAR (current_directory);\n unsigned int restarts = 0;\n unsigned int syncing = 0;\n int argv_slots;\n#ifdef WINDOWS32\n const char *unix_path = NULL;\n const char *windows32_path = NULL;\n\n SetUnhandledExceptionFilter (handle_runtime_exceptions);\n\n /* start off assuming we have no shell */\n unixy_shell = 0;\n no_default_sh_exe = 1;\n#endif\n\n /* Useful for attaching debuggers, etc. */\n#ifdef SPIN\n SPIN (\"main-entry\");\n#endif\n\n argv0 = strdup(argv[0]);\n output_init (&make_sync);\n\n initialize_stopchar_map();\n\n#ifdef SET_STACK_SIZE\n /* Get rid of any avoidable limit on stack size. */\n {\n struct rlimit rlim;\n\n /* Set the stack limit huge so that alloca does not fail. */\n if (getrlimit (RLIMIT_STACK, &rlim) == 0\n && rlim.rlim_cur > 0 && rlim.rlim_cur < rlim.rlim_max)\n {\n stack_limit = rlim;\n rlim.rlim_cur = rlim.rlim_max;\n setrlimit (RLIMIT_STACK, &rlim);\n }\n else\n stack_limit.rlim_cur = 0;\n }\n#endif\n\n global_argv = argv;\n /* Needed for OS/2 */\n initialize_main (&argc, &argv);\n\n#ifdef MAKE_MAINTAINER_MODE\n /* In maintainer mode we always enable verification. */\n verify_flag = 1;\n#endif\n\n#if defined (__MSDOS__) && !defined (_POSIX_SOURCE)\n /* Request the most powerful version of 'system', to\n make up for the dumb default shell. */\n __system_flags = (__system_redirect\n | __system_use_shell\n | __system_allow_multiple_cmds\n | __system_allow_long_cmds\n | __system_handle_null_commands\n | __system_emulate_chdir);\n\n#endif\n\n /* Set up gettext/internationalization support. */\n setlocale (LC_ALL, \"\");\n /* The cast to void shuts up compiler warnings on systems that\n disable NLS. */\n (void)bindtextdomain (PACKAGE, LOCALEDIR);\n (void)textdomain (PACKAGE);\n\n#ifdef POSIX\n sigemptyset (&fatal_signal_set);\n#define ADD_SIG(sig) sigaddset (&fatal_signal_set, sig)\n#else\n#ifdef HAVE_SIGSETMASK\n fatal_signal_mask = 0;\n#define ADD_SIG(sig) fatal_signal_mask |= sigmask (sig)\n#else\n#define ADD_SIG(sig) (void)sig\n#endif\n#endif\n\n#define FATAL_SIG(sig) \\\n if (bsd_signal (sig, fatal_error_signal) == SIG_IGN) \\\n bsd_signal (sig, SIG_IGN); \\\n else \\\n ADD_SIG (sig);\n\n#ifdef SIGHUP\n FATAL_SIG (SIGHUP);\n#endif\n#ifdef SIGQUIT\n FATAL_SIG (SIGQUIT);\n#endif\n FATAL_SIG (SIGINT);\n FATAL_SIG (SIGTERM);\n\n#ifdef __MSDOS__\n /* Windows 9X delivers FP exceptions in child programs to their\n parent! We don't want Make to die when a child divides by zero,\n so we work around that lossage by catching SIGFPE. */\n FATAL_SIG (SIGFPE);\n#endif\n\n#ifdef SIGDANGER\n FATAL_SIG (SIGDANGER);\n#endif\n#ifdef SIGXCPU\n FATAL_SIG (SIGXCPU);\n#endif\n#ifdef SIGXFSZ\n FATAL_SIG (SIGXFSZ);\n#endif\n\n#undef FATAL_SIG\n\n /* Do not ignore the child-death signal. This must be done before\n any children could possibly be created; otherwise, the wait\n functions won't work on systems with the SVR4 ECHILD brain\n damage, if our invoker is ignoring this signal. */\n\n#ifdef HAVE_WAIT_NOHANG\n# if defined SIGCHLD\n (void) bsd_signal (SIGCHLD, SIG_DFL);\n# endif\n# if defined SIGCLD && SIGCLD != SIGCHLD\n (void) bsd_signal (SIGCLD, SIG_DFL);\n# endif\n#endif\n\n output_init (NULL);\n\n /* Figure out where this program lives. */\n\n if (argv[0] == 0)\n argv[0] = (char *)\"\";\n if (argv[0][0] == '\\0')\n program = \"make\";\n else\n {\n#if defined(HAVE_DOS_PATHS)\n const char* start = argv[0];\n\n /* Skip an initial drive specifier if present. */\n if (isalpha ((unsigned char)start[0]) && start[1] == ':')\n start += 2;\n\n if (start[0] == '\\0')\n program = \"make\";\n else\n {\n program = start + strlen (start);\n while (program > start && ! STOP_SET (program[-1], MAP_DIRSEP))\n --program;\n\n /* Remove the .exe extension if present. */\n {\n size_t len = strlen (program);\n if (len > 4 && streq (&program[len - 4], \".exe\"))\n program = xstrndup (program, len - 4);\n }\n }\n#else\n program = strrchr (argv[0], '/');\n if (program == 0)\n program = argv[0];\n else\n ++program;\n#endif\n }\n\n /* Set up to access user data (files). */\n user_access ();\n\n initialize_global_hash_tables ();\n\n /* Figure out where we are. */\n\n#ifdef WINDOWS32\n if (getcwd_fs (current_directory, GET_PATH_MAX) == 0)\n#else\n if (getcwd (current_directory, GET_PATH_MAX) == 0)\n#endif\n {\n#ifdef HAVE_GETCWD\n perror_with_name (\"getcwd\", \"\");\n#else\n OS (error, NILF, \"getwd: %s\", current_directory);\n#endif\n current_directory[0] = '\\0';\n directory_before_chdir = 0;\n }\n else\n directory_before_chdir = xstrdup (current_directory);\n\n#ifdef __MSDOS__\n /* Make sure we will return to the initial directory, come what may. */\n atexit (msdos_return_to_initial_directory);\n#endif\n\n /* Initialize the special variables. */\n define_variable_cname (\".VARIABLES\", \"\", o_default, 0)->special = 1;\n /* define_variable_cname (\".TARGETS\", \"\", o_default, 0)->special = 1; */\n define_variable_cname (\".RECIPEPREFIX\", \"\", o_default, 0)->special = 1;\n define_variable_cname (\".SHELLFLAGS\", \"-c\", o_default, 0);\n define_variable_cname (\".LOADED\", \"\", o_default, 0);\n\n /* Set up .FEATURES\n Use a separate variable because define_variable_cname() is a macro and\n some compilers (MSVC) don't like conditionals in macros. */\n {\n const char *features = \"target-specific order-only second-expansion\"\n \" else-if shortest-stem undefine oneshell nocomment\"\n \" grouped-target extra-prereqs\"\n#ifndef NO_ARCHIVES\n \" archives\"\n#endif\n#ifdef MAKE_JOBSERVER\n \" jobserver\"\n#endif\n#ifndef NO_OUTPUT_SYNC\n \" output-sync\"\n#endif\n#ifdef MAKE_SYMLINKS\n \" check-symlink\"\n#endif\n#ifdef HAVE_GUILE\n \" guile\"\n#endif\n#ifdef MAKE_LOAD\n \" load\"\n#endif\n#ifdef MAKE_MAINTAINER_MODE\n \" maintainer\"\n#endif\n ;\n\n define_variable_cname (\".FEATURES\", features, o_default, 0);\n }\n\n /* Configure GNU Guile support */\n guile_gmake_setup (NILF);\n\n /* Read in variables from the environment. It is important that this be\n done before $(MAKE) is figured out so its definitions will not be\n from the environment. */\n\n {\n unsigned int i;\n\n for (i = 0; envp[i] != 0; ++i)\n {\n struct variable *v;\n const char *ep = envp[i];\n /* By default, export all variables culled from the environment. */\n enum variable_export export = v_export;\n size_t len;\n\n while (! STOP_SET (*ep, MAP_EQUALS))\n ++ep;\n\n /* If there's no equals sign it's a malformed environment. Ignore. */\n if (*ep == '\\0')\n continue;\n\n /* Length of the variable name, and skip the '='. */\n len = ep++ - envp[i];\n\n /* If this is MAKE_RESTARTS, check to see if the \"already printed\n the enter statement\" flag is set. */\n if (len == 13 && strneq (envp[i], \"MAKE_RESTARTS\", 13))\n {\n if (*ep == '-')\n {\n OUTPUT_TRACED ();\n ++ep;\n }\n restarts = (unsigned int) atoi (ep);\n export = v_noexport;\n }\n\n v = define_variable (envp[i], len, ep, o_env, 1);\n\n /* POSIX says the value of SHELL set in the makefile won't change the\n value of SHELL given to subprocesses. */\n if (streq (v->name, \"SHELL\"))\n {\n export = v_noexport;\n shell_var.name = xstrdup (\"SHELL\");\n shell_var.length = 5;\n shell_var.value = xstrdup (ep);\n }\n\n v->export = export;\n }\n }\n\n /* Decode the switches. */\n decode_env_switches (STRING_SIZE_TUPLE (\"GNUMAKEFLAGS\"));\n\n /* Clear GNUMAKEFLAGS to avoid duplication. */\n define_variable_cname (\"GNUMAKEFLAGS\", \"\", o_env, 0);\n\n decode_env_switches (STRING_SIZE_TUPLE (\"MAKEFLAGS\"));\n\n#if 0\n /* People write things like:\n MFLAGS=\"CC=gcc -pipe\" \"CFLAGS=-g\"\n and we set the -p, -i and -e switches. Doesn't seem quite right. */\n decode_env_switches (STRING_SIZE_TUPLE (\"MFLAGS\"));\n#endif\n\n /* In output sync mode we need to sync any output generated by reading the\n makefiles, such as in $(info ...) or stderr from $(shell ...) etc. */\n\n syncing = make_sync.syncout = (output_sync == OUTPUT_SYNC_LINE\n || output_sync == OUTPUT_SYNC_TARGET);\n OUTPUT_SET (&make_sync);\n\n /* Parse the command line options. Remember the job slots set this way. */\n {\n int env_slots = arg_job_slots;\n arg_job_slots = INVALID_JOB_SLOTS;\n\n decode_switches (argc, (const char **)argv, 0);\n argv_slots = arg_job_slots;\n\n if (arg_job_slots == INVALID_JOB_SLOTS)\n arg_job_slots = env_slots;\n }\n\n /* Set a variable specifying whether stdout/stdin is hooked to a TTY. */\n#ifdef HAVE_ISATTY\n if (isatty (fileno (stdout)))\n if (! lookup_variable (STRING_SIZE_TUPLE (\"MAKE_TERMOUT\")))\n {\n const char *tty = TTYNAME (fileno (stdout));\n define_variable_cname (\"MAKE_TERMOUT\", tty ? tty : DEFAULT_TTYNAME,\n o_default, 0)->export = v_export;\n }\n if (isatty (fileno (stderr)))\n if (! lookup_variable (STRING_SIZE_TUPLE (\"MAKE_TERMERR\")))\n {\n const char *tty = TTYNAME (fileno (stderr));\n define_variable_cname (\"MAKE_TERMERR\", tty ? tty : DEFAULT_TTYNAME,\n o_default, 0)->export = v_export;\n }\n#endif\n\n /* Reset in case the switches changed our minds. */\n syncing = (output_sync == OUTPUT_SYNC_LINE\n || output_sync == OUTPUT_SYNC_TARGET);\n\n if (make_sync.syncout && ! syncing)\n output_close (&make_sync);\n\n make_sync.syncout = syncing;\n OUTPUT_SET (&make_sync);\n\n /* Figure out the level of recursion. */\n {\n struct variable *v = lookup_variable (STRING_SIZE_TUPLE (MAKELEVEL_NAME));\n if (v && v->value[0] != '\\0' && v->value[0] != '-')\n makelevel = (unsigned int) atoi (v->value);\n else\n makelevel = 0;\n\n v = lookup_variable (STRING_SIZE_TUPLE (MAKEPARENT_PID_NAME));\n if (v && v->value[0] != '\\0' && v->value[0] != '-')\n makeparent_pid = (pid_t) atoi (v->value);\n else\n makeparent_pid = (pid_t)0;\n\n v = lookup_variable (STRING_SIZE_TUPLE (MAKEPARENT_TARGET_NAME));\n if (v && v->value[0] != '\\0' && v->value[0] != '-') {\n makeparent_target = v->value;\n } else {\n makeparent_target = NULL;\n }\n }\n\n decode_trace_flags (tracing_opts);\n decode_verbosity_flags (verbosity_opts);\n\n /* FIXME: put into a subroutine like decode_trace_flags */\n if (post_mortem_flag) {\n debugger_on_error |= (DEBUGGER_ON_ERROR|DEBUGGER_ON_FATAL);\n debugger_enabled = 1;\n } else if (debugger_flag) {\n b_debugger_preread = false;\n job_slots = 1;\n i_debugger_stepping = 1;\n i_debugger_nexting = 0;\n debugger_enabled = 1;\n /* For now we'll do basic debugging. Later, \"stepping'\n will stop here while next won't - either way no printing.\n */\n db_level |= DB_BASIC | DB_CALL | DB_SHELL | DB_UPDATE_GOAL\n | DB_MAKEFILES;\n } else {\n /* debugging sets some things */\n if (debugger_opts) {\n const char **p;\n b_show_version = true;\n for (p = debugger_opts->list; *p != 0; ++p)\n {\n if (0 == strcmp(*p, \"preread\")) {\n b_debugger_preread = true;\n db_level |= DB_READ_MAKEFILES;\n }\n\n if (0 == strcmp(*p, \"goal\")) {\n b_debugger_goal = true;\n db_level |= DB_UPDATE_GOAL;\n }\n\n if ( 0 == strcmp(*p, \"full\") || b_debugger_preread || b_debugger_goal\n || 0 == strcmp(*p, \"preaction\") ) {\n job_slots = 1;\n i_debugger_stepping = 1;\n i_debugger_nexting = 0;\n debugger_enabled = 1;\n /* For now we'll do basic debugging. Later, \"stepping'\n will stop here while next won't - either way no printing.\n */\n db_level |= DB_BASIC | DB_CALL | DB_UPDATE_GOAL\n | b_debugger_goal ? 0 : DB_SHELL\n | DB_MAKEFILES;\n }\n if ( 0 == strcmp(*p, \"full\") || b_debugger_goal\n || 0 == strcmp(*p, \"error\") ) {\n debugger_on_error |= (DEBUGGER_ON_ERROR|DEBUGGER_ON_FATAL);\n } else if ( 0 == strcmp(*p, \"fatal\") ) {\n debugger_on_error |= DEBUGGER_ON_FATAL;\n }\n }\n#ifndef HAVE_LIBREADLINE\n O (error, NILF,\n \"warning: you specified a debugger option, but you don't have readline support\");\n O (error, NILF,\n \"debugger support compiled in. Debugger options will be ignored.\");\n#endif\n }\n }\n\n /* Set always_make_flag if -B was given and we've not restarted already. */\n always_make_flag = always_make_set && (restarts == 0);\n\n /* Print version information, and exit. */\n if (print_version_flag)\n {\n print_version ();\n die (MAKE_SUCCESS);\n }\n\n if (ISDB (DB_BASIC) && makelevel == 0 && b_show_version)\n print_version ();\n\n /* Set the \"MAKE_COMMAND\" variable to the name we were invoked with.\n (If it is a relative pathname with a slash, prepend our directory name\n so the result will run the same program regardless of the current dir.\n If it is a name with no slash, we can only hope that PATH did not\n find it in the current directory.) */\n if (current_directory[0] != '\\0'\n && argv[0] != 0 && argv[0][0] != '/' && strchr (argv[0], '/') != 0\n )\n argv[0] = xstrdup (concat (3, current_directory, \"/\", argv[0]));\n\n /* We may move, but until we do, here we are. */\n starting_directory = current_directory;\n\n /* Update profile global options from cli options */\n decode_profile_options();\n if (profile_flag) profile_init(PACKAGE_TARNAME \" \" PACKAGE_VERSION, argv, arg_job_slots);\n\n /* Validate the arg_job_slots configuration before we define MAKEFLAGS so\n users get an accurate value in their makefiles.\n At this point arg_job_slots is the argv setting, if there is one, else\n the MAKEFLAGS env setting, if there is one. */\n\n if (jobserver_auth)\n {\n /* We're a child in an existing jobserver group. */\n if (argv_slots == INVALID_JOB_SLOTS)\n {\n /* There's no -j option on the command line: check authorization. */\n if (jobserver_parse_auth (jobserver_auth))\n {\n /* Success! Use the jobserver. */\n goto job_setup_complete;\n }\n\n /* Oops: we have jobserver-auth but it's invalid :(. */\n O (error, NILF, _(\"warning: jobserver unavailable: using -j1. Add '+' to parent make rule.\"));\n arg_job_slots = 1;\n }\n\n /* The user provided a -j setting on the command line so use it: we're\n the master make of a new jobserver group. */\n else if (!restarts)\n ON (error, NILF,\n _(\"warning: -j%d forced in submake: resetting jobserver mode.\"),\n argv_slots);\n\n /* We can't use our parent's jobserver, so reset. */\n reset_jobserver ();\n }\n\n job_setup_complete:\n\n /* The extra indirection through $(MAKE_COMMAND) is done\n for hysterical raisins. */\n\n define_variable_cname (\"MAKE_COMMAND\", argv[0], o_default, 0);\n define_variable_cname (\"MAKE\", \"$(MAKE_COMMAND)\", o_default, 1);\n\n if (command_variables != 0)\n {\n struct command_variable *cv;\n struct variable *v;\n size_t len = 0;\n char *value, *p;\n\n /* Figure out how much space will be taken up by the command-line\n variable definitions. */\n for (cv = command_variables; cv != 0; cv = cv->next)\n {\n v = cv->variable;\n len += 2 * strlen (v->name);\n if (! v->recursive)\n ++len;\n ++len;\n len += 2 * strlen (v->value);\n ++len;\n }\n\n /* Now allocate a buffer big enough and fill it. */\n p = value = alloca (len);\n for (cv = command_variables; cv != 0; cv = cv->next)\n {\n v = cv->variable;\n p = quote_for_env (p, v->name);\n if (! v->recursive)\n *p++ = ':';\n *p++ = '=';\n p = quote_for_env (p, v->value);\n *p++ = ' ';\n }\n p[-1] = '\\0'; /* Kill the final space and terminate. */\n\n /* Define an unchangeable variable with a name that no POSIX.2\n makefile could validly use for its own variable. */\n define_variable_cname (\"-*-command-variables-*-\", value, o_automatic, 0);\n\n /* Define the variable; this will not override any user definition.\n Normally a reference to this variable is written into the value of\n MAKEFLAGS, allowing the user to override this value to affect the\n exported value of MAKEFLAGS. In POSIX-pedantic mode, we cannot\n allow the user's setting of MAKEOVERRIDES to affect MAKEFLAGS, so\n a reference to this hidden variable is written instead. */\n define_variable_cname (\"MAKEOVERRIDES\", \"${-*-command-variables-*-}\",\n o_env, 1);\n }\n\n /* If there were -C flags, move ourselves about. */\n if (directories != 0)\n {\n unsigned int i;\n for (i = 0; directories->list[i] != 0; ++i)\n {\n const char *dir = directories->list[i];\n if (chdir (dir) < 0)\n pfatal_with_name (dir);\n }\n }\n\n /* Except under -s, always do -w in sub-makes and under -C. */\n if (!silent_flag && (directories != 0 || makelevel > 0))\n print_directory = 1;\n\n /* Let the user disable that with --no-print-directory. */\n if (inhibit_print_directory)\n print_directory = 0;\n\n /* If -R was given, set -r too (doesn't make sense otherwise!) */\n if (no_builtin_variables_flag)\n no_builtin_rules_flag = 1;\n\n /* Construct the list of include directories to search. */\n\n construct_include_path (include_directories == 0\n ? 0 : include_directories->list);\n\n /* If we chdir'ed, figure out where we are now. */\n if (directories)\n {\n#ifdef WINDOWS32\n if (getcwd_fs (current_directory, GET_PATH_MAX) == 0)\n#else\n if (getcwd (current_directory, GET_PATH_MAX) == 0)\n#endif\n {\n#ifdef HAVE_GETCWD\n perror_with_name (\"getcwd\", \"\");\n#else\n OS (error, NILF, \"getwd: %s\", current_directory);\n#endif\n starting_directory = 0;\n }\n else\n starting_directory = current_directory;\n }\n\n define_variable_cname (\"CURDIR\", current_directory, o_file, 0);\n\n /* Read any stdin makefiles into temporary files. */\n\n if (makefiles != 0)\n {\n unsigned int i;\n for (i = 0; i < makefiles->idx; ++i)\n if (makefiles->list[i][0] == '-' && makefiles->list[i][1] == '\\0')\n {\n /* This makefile is standard input. Since we may re-exec\n and thus re-read the makefiles, we read standard input\n into a temporary file and read from that. */\n FILE *outfile;\n char *template;\n const char *tmpdir;\n\n if (stdin_nm)\n O (fatal, NILF,\n _(\"Makefile from standard input specified twice.\"));\n\n#ifdef P_tmpdir\n# define DEFAULT_TMPDIR P_tmpdir\n#else\n# define DEFAULT_TMPDIR \"/tmp\"\n#endif\n#define DEFAULT_TMPFILE \"GmXXXXXX\"\n\n if (((tmpdir = getenv (\"TMPDIR\")) == NULL || *tmpdir == '\\0')\n )\n tmpdir = DEFAULT_TMPDIR;\n\n template = alloca (strlen (tmpdir) + CSTRLEN (DEFAULT_TMPFILE) + 2);\n strcpy (template, tmpdir);\n\n#ifdef HAVE_DOS_PATHS\n if (strchr (\"/\\\\\", template[strlen (template) - 1]) == NULL)\n strcat (template, \"/\");\n#else\n# ifndef VMS\n if (template[strlen (template) - 1] != '/')\n strcat (template, \"/\");\n# endif /* !VMS */\n#endif /* !HAVE_DOS_PATHS */\n\n strcat (template, DEFAULT_TMPFILE);\n outfile = get_tmpfile (&stdin_nm, template);\n if (outfile == 0)\n pfatal_with_name (_(\"fopen (temporary file)\"));\n while (!feof (stdin) && ! ferror (stdin))\n {\n char buf[2048];\n size_t n = fread (buf, 1, sizeof (buf), stdin);\n if (n > 0 && fwrite (buf, 1, n, outfile) != n)\n pfatal_with_name (_(\"fwrite (temporary file)\"));\n }\n fclose (outfile);\n\n /* Replace the name that read_all_makefiles will\n see with the name of the temporary file. */\n makefiles->list[i] = strcache_add (stdin_nm);\n\n /* Make sure the temporary file will not be remade. */\n {\n struct file *f = enter_file (strcache_add (stdin_nm));\n f->updated = 1;\n f->update_status = us_success;\n f->command_state = cs_finished;\n /* Can't be intermediate, or it'll be removed too early for\n make re-exec. */\n f->intermediate = 0;\n f->dontcare = 0;\n }\n }\n }\n\n#ifndef __EMX__ /* Don't use a SIGCHLD handler for OS/2 */\n#if !defined(HAVE_WAIT_NOHANG) || defined(MAKE_JOBSERVER)\n /* Set up to handle children dying. This must be done before\n reading in the makefiles so that 'shell' function calls will work.\n\n If we don't have a hanging wait we have to fall back to old, broken\n functionality here and rely on the signal handler and counting\n children.\n\n If we're using the jobs pipe we need a signal handler so that SIGCHLD is\n not ignored; we need it to interrupt the read(2) of the jobserver pipe if\n we're waiting for a token.\n\n If none of these are true, we don't need a signal handler at all. */\n {\n# if defined SIGCHLD\n bsd_signal (SIGCHLD, child_handler);\n# endif\n# if defined SIGCLD && SIGCLD != SIGCHLD\n bsd_signal (SIGCLD, child_handler);\n# endif\n }\n\n#ifdef HAVE_PSELECT\n /* If we have pselect() then we need to block SIGCHLD so it's deferred. */\n {\n sigset_t block;\n sigemptyset (&block);\n sigaddset (&block, SIGCHLD);\n if (sigprocmask (SIG_SETMASK, &block, NULL) < 0)\n pfatal_with_name (\"sigprocmask(SIG_SETMASK, SIGCHLD)\");\n }\n#endif\n\n#endif\n#endif\n\n /* Let the user send us SIGUSR1 to toggle the -d flag during the run. */\n#ifdef SIGUSR1\n bsd_signal (SIGUSR1, debug_signal_handler);\n#endif\n\n /* Define the initial list of suffixes for old-style rules. */\n set_default_suffixes ();\n\n /* Define the file rules for the built-in suffix rules. These will later\n be converted into pattern rules. We used to do this in\n install_default_implicit_rules, but since that happens after reading\n makefiles, it results in the built-in pattern rules taking precedence\n over makefile-specified suffix rules, which is wrong. */\n install_default_suffix_rules ();\n\n /* Define some internal and special variables. */\n define_automatic_variables ();\n\n /* Set up the MAKEFLAGS and MFLAGS variables for makefiles to see.\n Initialize it to be exported but allow the makefile to reset it. */\n define_makeflags (0, 0)->export = v_export;\n\n /* Define the default variables. */\n define_default_variables ();\n\n default_file = enter_file (strcache_add (\".DEFAULT\"));\n\n default_goal_var = define_variable_cname (\".DEFAULT_GOAL\", \"\", o_file, 0);\n\n /* Evaluate all strings provided with --eval.\n Also set up the $(-*-eval-flags-*-) variable. */\n\n if (eval_strings)\n {\n char *p, *value;\n unsigned int i;\n size_t len = (CSTRLEN (\"--eval=\") + 1) * eval_strings->idx;\n\n for (i = 0; i < eval_strings->idx; ++i)\n {\n p = xstrdup (eval_strings->list[i]);\n len += 2 * strlen (p);\n eval_buffer (p, NULL);\n free (p);\n }\n\n p = value = alloca (len);\n for (i = 0; i < eval_strings->idx; ++i)\n {\n strcpy (p, \"--eval=\");\n p += CSTRLEN (\"--eval=\");\n p = quote_for_env (p, eval_strings->list[i]);\n *(p++) = ' ';\n }\n p[-1] = '\\0';\n\n define_variable_cname (\"-*-eval-flags-*-\", value, o_automatic, 0);\n }\n\n /* Read all the makefiles. */\n\n read_makefiles = read_all_makefiles (makefiles == 0 ? 0 : makefiles->list);\n\n#ifdef WINDOWS32\n /* look one last time after reading all Makefiles */\n if (no_default_sh_exe)\n no_default_sh_exe = !find_and_set_default_shell (NULL);\n#endif /* WINDOWS32 */\n\n#if defined (__MSDOS__) || defined (__EMX__) || defined (VMS)\n /* We need to know what kind of shell we will be using. */\n {\n extern int _is_unixy_shell (const char *_path);\n struct variable *shv = lookup_variable (STRING_SIZE_TUPLE (\"SHELL\"));\n extern int unixy_shell;\n extern const char *default_shell;\n\n if (shv && *shv->value)\n {\n char *shell_path = recursively_expand (shv);\n\n if (shell_path && _is_unixy_shell (shell_path))\n unixy_shell = 1;\n else\n unixy_shell = 0;\n if (shell_path)\n default_shell = shell_path;\n }\n }\n#endif /* __MSDOS__ || __EMX__ */\n\n {\n int old_builtin_rules_flag = no_builtin_rules_flag;\n int old_builtin_variables_flag = no_builtin_variables_flag;\n int old_arg_job_slots = arg_job_slots;\n\n arg_job_slots = INVALID_JOB_SLOTS;\n\n /* Decode switches again, for variables set by the makefile. */\n decode_env_switches (STRING_SIZE_TUPLE (\"GNUMAKEFLAGS\"));\n\n /* Clear GNUMAKEFLAGS to avoid duplication. */\n define_variable_cname (\"GNUMAKEFLAGS\", \"\", o_override, 0);\n\n decode_env_switches (STRING_SIZE_TUPLE (\"MAKEFLAGS\"));\n#if 0\n decode_env_switches (STRING_SIZE_TUPLE (\"MFLAGS\"));\n#endif\n\n /* If -j is not set in the makefile, or it was set on the command line,\n reset to use the previous value. */\n if (arg_job_slots == INVALID_JOB_SLOTS || argv_slots != INVALID_JOB_SLOTS)\n arg_job_slots = old_arg_job_slots;\n\n else if (jobserver_auth)\n {\n /* Makefile MAKEFLAGS set -j, but we already have a jobserver.\n Make us the master of a new jobserver group. */\n if (!restarts)\n ON (error, NILF,\n _(\"warning: -j%d forced in makefile: resetting jobserver mode.\"),\n arg_job_slots);\n\n /* We can't use our parent's jobserver, so reset. */\n reset_jobserver ();\n }\n\n /* Reset in case the switches changed our mind. */\n syncing = (output_sync == OUTPUT_SYNC_LINE\n || output_sync == OUTPUT_SYNC_TARGET);\n\n if (make_sync.syncout && ! syncing)\n output_close (&make_sync);\n\n make_sync.syncout = syncing;\n OUTPUT_SET (&make_sync);\n\n /* If we've disabled builtin rules, get rid of them. */\n if (no_builtin_rules_flag && ! old_builtin_rules_flag)\n {\n if (suffix_file->builtin)\n {\n free_dep_chain (suffix_file->deps);\n suffix_file->deps = 0;\n }\n define_variable_cname (\"SUFFIXES\", \"\", o_default, 0);\n }\n\n /* If we've disabled builtin variables, get rid of them. */\n if (no_builtin_variables_flag && ! old_builtin_variables_flag)\n undefine_default_variables ();\n }\n\n /* Final jobserver configuration.\n\n If we have jobserver_auth then we are a client in an existing jobserver\n group, that's already been verified OK above. If we don't have\n jobserver_auth and jobserver is enabled, then start a new jobserver.\n\n arg_job_slots = INVALID_JOB_SLOTS if we don't want -j in MAKEFLAGS\n\n arg_job_slots = # of jobs of parallelism\n\n job_slots = 0 for no limits on jobs, or when limiting via jobserver.\n\n job_slots = 1 for standard non-parallel mode.\n\n job_slots >1 for old-style parallelism without jobservers. */\n\n if (jobserver_auth)\n job_slots = 0;\n else if (arg_job_slots == INVALID_JOB_SLOTS)\n job_slots = 1;\n else\n job_slots = arg_job_slots;\n\n /* If we have >1 slot at this point, then we're a top-level make.\n Set up the jobserver.\n\n Every make assumes that it always has one job it can run. For the\n submakes it's the token they were given by their parent. For the top\n make, we just subtract one from the number the user wants. */\n\n if (job_slots > 1 && jobserver_setup (job_slots - 1))\n {\n /* Fill in the jobserver_auth for our children. */\n jobserver_auth = jobserver_get_auth ();\n\n if (jobserver_auth)\n {\n /* We're using the jobserver so set job_slots to 0. */\n master_job_slots = job_slots;\n job_slots = 0;\n }\n }\n\n /* If we're not using parallel jobs, then we don't need output sync.\n This is so people can enable output sync in GNUMAKEFLAGS or similar, but\n not have it take effect unless parallel builds are enabled. */\n if (syncing && job_slots == 1)\n {\n OUTPUT_UNSET ();\n output_close (&make_sync);\n syncing = 0;\n output_sync = OUTPUT_SYNC_NONE;\n }\n\n#ifndef MAKE_SYMLINKS\n if (check_symlink_flag)\n {\n O (error, NILF, _(\"Symbolic links not supported: disabling -L.\"));\n check_symlink_flag = 0;\n }\n#endif\n\n /* Set up MAKEFLAGS and MFLAGS again, so they will be right. */\n\n define_makeflags (1, 0);\n\n /* Make each 'struct goaldep' point at the 'struct file' for the file\n depended on. Also do magic for special targets. */\n\n snap_deps ();\n\n /* Convert old-style suffix rules to pattern rules. It is important to\n do this before installing the built-in pattern rules below, so that\n makefile-specified suffix rules take precedence over built-in pattern\n rules. */\n\n convert_to_pattern ();\n\n /* Install the default implicit pattern rules.\n This used to be done before reading the makefiles.\n But in that case, built-in pattern rules were in the chain\n before user-defined ones, so they matched first. */\n\n install_default_implicit_rules ();\n\n /* Compute implicit rule limits and do magic for pattern rules. */\n\n snap_implicit_rules ();\n\n /* Construct the listings of directories in VPATH lists. */\n\n build_vpath_lists ();\n\n /* Mark files given with -o flags as very old and as having been updated\n already, and files given with -W flags as brand new (time-stamp as far\n as possible into the future). If restarts is set we'll do -W later. */\n\n if (old_files != 0)\n {\n const char **p;\n for (p = old_files->list; *p != 0; ++p)\n {\n struct file *f = enter_file (*p);\n f->last_mtime = f->mtime_before_update = OLD_MTIME;\n f->updated = 1;\n f->update_status = us_success;\n f->command_state = cs_finished;\n }\n }\n\n if (!restarts && new_files != 0)\n {\n const char **p;\n for (p = new_files->list; *p != 0; ++p)\n {\n struct file *f = enter_file (*p);\n f->last_mtime = f->mtime_before_update = NEW_MTIME;\n }\n }\n\n /* Initialize the remote job module. */\n remote_setup ();\n\n /* Dump any output we've collected. */\n\n OUTPUT_UNSET ();\n output_close (&make_sync);\n\n if (read_makefiles)\n {\n /* Update any makefiles if necessary. */\n\n FILE_TIMESTAMP *makefile_mtimes;\n char **aargv = NULL;\n const char **nargv;\n int nargc;\n enum update_status status;\n\n DB (DB_BASIC, (_(\"Updating makefiles...\\n\")));\n\n {\n struct goaldep *d;\n unsigned int num_mkfiles = 0;\n for (d = read_makefiles; d != NULL; d = d->next)\n ++num_mkfiles;\n\n makefile_mtimes = alloca (num_mkfiles * sizeof (FILE_TIMESTAMP));\n }\n\n /* Remove any makefiles we don't want to try to update. Record the\n current modtimes of the others so we can compare them later. */\n {\n struct goaldep *d = read_makefiles;\n struct goaldep *last = NULL;\n unsigned int mm_idx = 0;\n\n while (d != 0)\n {\n struct file *f;\n\n for (f = d->file->double_colon; f != NULL; f = f->prev)\n if (f->deps == 0 && f->cmds != 0)\n break;\n\n if (f)\n {\n /* This makefile is a :: target with commands, but no\n dependencies. So, it will always be remade. This might\n well cause an infinite loop, so don't try to remake it.\n (This will only happen if your makefiles are written\n exceptionally stupidly; but if you work for Athena, that's\n how you write your makefiles.) */\n\n DB (DB_VERBOSE,\n (_(\"Makefile '%s' might loop; not remaking it.\\n\"),\n f->name));\n\n if (last)\n last->next = d->next;\n else\n read_makefiles = d->next;\n\n /* Free the storage. */\n free_goaldep (d);\n\n d = last ? last->next : read_makefiles;\n }\n else\n {\n makefile_mtimes[mm_idx++] = file_mtime_no_search (d->file);\n last = d;\n d = d->next;\n }\n }\n }\n\n /* Set up 'MAKEFLAGS' specially while remaking makefiles. */\n define_makeflags (1, 1);\n\n {\n int orig_db_level = db_level;\n\n if (! ISDB (DB_MAKEFILES))\n db_level = DB_NONE;\n\n rebuilding_makefiles = 1;\n\tstatus = update_goal_chain (read_makefiles);\n rebuilding_makefiles = 0;\n\n db_level = orig_db_level;\n }\n\n switch (status)\n {\n case us_question:\n /* The only way this can happen is if the user specified -q and asked\n for one of the makefiles to be remade as a target on the command\n line. Since we're not actually updating anything with -q we can\n treat this as \"did nothing\". */\n\n case us_none:\n /* Did nothing. */\n break;\n\n case us_failed:\n /* Failed to update. Figure out if we care. */\n {\n /* Nonzero if any makefile was successfully remade. */\n int any_remade = 0;\n /* Nonzero if any makefile we care about failed\n in updating or could not be found at all. */\n int any_failed = 0;\n unsigned int i;\n struct goaldep *d;\n\n for (i = 0, d = read_makefiles; d != 0; ++i, d = d->next)\n {\n if (d->file->updated)\n {\n /* This makefile was updated. */\n if (d->file->update_status == us_success)\n {\n /* It was successfully updated. */\n any_remade |= (file_mtime_no_search (d->file)\n != makefile_mtimes[i]);\n }\n else if (! (d->flags & RM_DONTCARE))\n {\n FILE_TIMESTAMP mtime;\n /* The update failed and this makefile was not\n from the MAKEFILES variable, so we care. */\n OS (error, NILF, _(\"Failed to remake makefile '%s'.\"),\n d->file->name);\n mtime = file_mtime_no_search (d->file);\n any_remade |= (mtime != NONEXISTENT_MTIME\n && mtime != makefile_mtimes[i]);\n makefile_status = MAKE_FAILURE;\n }\n }\n else\n /* This makefile was not found at all. */\n if (! (d->flags & RM_DONTCARE))\n {\n const char *dnm = dep_name (d);\n size_t l = strlen (dnm);\n\n /* This is a makefile we care about. See how much. */\n if (d->flags & RM_INCLUDED)\n /* An included makefile. We don't need to die, but we\n do want to complain. */\n error (NILF, l,\n _(\"Included makefile '%s' was not found.\"), dnm);\n else\n {\n /* A normal makefile. We must die later. */\n error (NILF, l,\n _(\"Makefile '%s' was not found\"), dnm);\n any_failed = 1;\n }\n }\n }\n\n if (any_remade)\n goto re_exec;\n if (any_failed)\n die (MAKE_FAILURE);\n break;\n }\n\n case us_success:\n re_exec:\n /* Updated successfully. Re-exec ourselves. */\n\n remove_intermediates (0);\n\n if (print_data_base_flag)\n print_data_base ();\n\n clean_jobserver (0);\n\n if (makefiles != 0)\n {\n /* These names might have changed. */\n int i, j = 0;\n for (i = 1; i < argc; ++i)\n if (strneq (argv[i], \"-f\", 2)) /* XXX */\n {\n if (argv[i][2] == '\\0')\n /* This cast is OK since we never modify argv. */\n argv[++i] = (char *) makefiles->list[j];\n else\n argv[i] = xstrdup (concat (2, \"-f\", makefiles->list[j]));\n ++j;\n }\n }\n\n /* Add -o option for the stdin temporary file, if necessary. */\n nargc = argc;\n if (stdin_nm)\n {\n void *m = xmalloc ((nargc + 2) * sizeof (char *));\n aargv = m;\n memcpy (aargv, argv, argc * sizeof (char *));\n aargv[nargc++] = xstrdup (concat (2, \"-o\", stdin_nm));\n aargv[nargc] = 0;\n nargv = m;\n }\n else\n nargv = (const char**)argv;\n\n if (directories != 0 && directories->idx > 0)\n {\n int bad = 1;\n if (directory_before_chdir != 0)\n {\n if (chdir (directory_before_chdir) < 0)\n perror_with_name (\"chdir\", \"\");\n else\n bad = 0;\n }\n if (bad)\n O (fatal, NILF,\n _(\"Couldn't change back to original directory.\"));\n }\n\n ++restarts;\n\n if (ISDB (DB_BASIC))\n {\n const char **p;\n printf (_(\"Re-executing[%u]:\"), restarts);\n for (p = nargv; *p != 0; ++p)\n printf (\" %s\", *p);\n putchar ('\\n');\n fflush (stdout);\n }\n\n {\n char **p;\n for (p = environ; *p != 0; ++p)\n {\n if (strneq (*p, MAKELEVEL_NAME \"=\", MAKELEVEL_LENGTH+1))\n {\n *p = alloca (40);\n sprintf (*p, \"%s=%u\", MAKELEVEL_NAME, makelevel);\n }\n else if (strneq (*p, \"MAKE_RESTARTS=\", CSTRLEN (\"MAKE_RESTARTS=\")))\n {\n *p = alloca (40);\n sprintf (*p, \"MAKE_RESTARTS=%s%u\",\n OUTPUT_IS_TRACED () ? \"-\" : \"\", restarts);\n restarts = 0;\n }\n }\n }\n\n /* If we didn't set the restarts variable yet, add it. */\n if (restarts)\n {\n char *b = alloca (40);\n sprintf (b, \"MAKE_RESTARTS=%s%u\",\n OUTPUT_IS_TRACED () ? \"-\" : \"\", restarts);\n putenv (b);\n }\n\n fflush (stdout);\n fflush (stderr);\n\n /* The exec'd \"child\" will be another make, of course. */\n jobserver_pre_child(1);\n\n#ifdef SET_STACK_SIZE\n /* Reset limits, if necessary. */\n if (stack_limit.rlim_cur)\n setrlimit (RLIMIT_STACK, &stack_limit);\n#endif\n exec_command ((char **)nargv, environ);\n\n /* We shouldn't get here but just in case. */\n jobserver_post_child(1);\n free (aargv);\n break;\n }\n }\n\n /* Set up 'MAKEFLAGS' again for the normal targets. */\n define_makeflags (1, 0);\n\n /* Set always_make_flag if -B was given. */\n always_make_flag = always_make_set;\n\n /* If restarts is set we haven't set up -W files yet, so do that now. */\n if (restarts && new_files != 0)\n {\n const char **p;\n for (p = new_files->list; *p != 0; ++p)\n {\n struct file *f = enter_file (*p);\n f->last_mtime = f->mtime_before_update = NEW_MTIME;\n }\n }\n\n /* If there is a temp file from reading a makefile from stdin, get rid of\n it now. */\n if (stdin_nm && unlink (stdin_nm) < 0 && errno != ENOENT)\n perror_with_name (_(\"unlink (temporary file): \"), stdin_nm);\n\n /* If there were no command-line goals, use the default. */\n if (goals == 0)\n {\n char *p;\n\n if (default_goal_var->recursive)\n p = variable_expand (default_goal_var->value);\n else\n {\n p = variable_buffer_output (variable_buffer, default_goal_var->value,\n strlen (default_goal_var->value));\n *p = '\\0';\n p = variable_buffer;\n }\n\n if (*p != '\\0')\n {\n struct file *f = lookup_file (p);\n\n /* If .DEFAULT_GOAL is a non-existent target, enter it into the\n table and let the standard logic sort it out. */\n if (f == 0)\n {\n struct nameseq *ns;\n\n ns = PARSE_SIMPLE_SEQ (&p, struct nameseq);\n if (ns)\n {\n /* .DEFAULT_GOAL should contain one target. */\n if (ns->next != 0)\n O (fatal, NILF,\n _(\".DEFAULT_GOAL contains more than one target\"));\n\n f = enter_file (strcache_add (ns->name));\n\n ns->name = 0; /* It was reused by enter_file(). */\n free_ns_chain (ns);\n }\n }\n\n if (f)\n {\n goals = alloc_goaldep ();\n goals->file = f;\n }\n }\n }\n else\n lastgoal->next = 0;\n\n\n if (!goals)\n {\n struct variable *v = lookup_variable (STRING_SIZE_TUPLE (\"MAKEFILE_LIST\"));\n if (v && v->value && v->value[0] != '\\0')\n O (fatal, NILF, _(\"No targets\"));\n\n O (fatal, NILF, _(\"No targets specified and no makefile found\"));\n }\n if (show_task_comments_flag) {\n dbg_cmd_info_targets(show_task_comments_flag\n\t\t\t ? INFO_TARGET_TASKS_WITH_COMMENTS\n\t\t\t : INFO_TARGET_TASKS);\n die(0);\n }\n if (show_tasks_flag) {\n dbg_cmd_info_tasks();\n die(0);\n } else if (show_targets_flag) {\n dbg_cmd_info_targets(INFO_TARGET_NAME);\n die(0);\n }\n\n /* Update the goals. */\n\n DB (DB_BASIC, (_(\"Updating goal targets...\\n\")));\n\n {\n switch (update_goal_chain (goals))\n {\n case us_none:\n /* Nothing happened. */\n /* FALLTHROUGH */\n case us_success:\n /* Keep the previous result. */\n break;\n case us_question:\n /* We are under -q and would run some commands. */\n makefile_status = MAKE_TROUBLE;\n break;\n case us_failed:\n /* Updating failed. POSIX.2 specifies exit status >1 for this; */\n makefile_status = MAKE_FAILURE;\n break;\n }\n\n /* If we detected some clock skew, generate one last warning */\n if (clock_skew_detected)\n O (error, NILF,\n _(\"warning: Clock skew detected. Your build may be incomplete.\"));\n\n /* Exit. */\n die (makefile_status);\n }\n\n /* NOTREACHED */\n exit (MAKE_SUCCESS);\n}\n\f\n/* Parsing of arguments, decoding of switches. */\n\nstatic char options[1 + sizeof (switches) / sizeof (switches[0]) * 3];\nstatic struct option long_options[(sizeof (switches) / sizeof (switches[0])) +\n (sizeof (long_option_aliases) /\n sizeof (long_option_aliases[0]))];\n\n/* Fill in the string and vector for getopt. */\nstatic void\ninit_switches (void)\n{\n char *p;\n unsigned int c;\n unsigned int i;\n\n if (options[0] != '\\0')\n /* Already done. */\n return;\n\n p = options;\n\n /* Return switch and non-switch args in order, regardless of\n POSIXLY_CORRECT. Non-switch args are returned as option 1. */\n *p++ = '-';\n\n for (i = 0; switches[i].c != '\\0'; ++i)\n {\n long_options[i].name = (char *) (switches[i].long_name == 0 ? \"\" :\n switches[i].long_name);\n long_options[i].flag = 0;\n long_options[i].val = switches[i].c;\n if (short_option (switches[i].c))\n *p++ = (char) switches[i].c;\n switch (switches[i].type)\n {\n case flag:\n case flag_off:\n case ignore:\n long_options[i].has_arg = no_argument;\n break;\n\n case string:\n case strlist:\n case filename:\n case positive_int:\n case floating:\n if (short_option (switches[i].c))\n *p++ = ':';\n if (switches[i].noarg_value != 0)\n {\n if (short_option (switches[i].c))\n *p++ = ':';\n long_options[i].has_arg = optional_argument;\n }\n else\n long_options[i].has_arg = required_argument;\n break;\n }\n }\n *p = '\\0';\n for (c = 0; c < (sizeof (long_option_aliases) /\n sizeof (long_option_aliases[0]));\n ++c)\n long_options[i++] = long_option_aliases[c];\n long_options[i].name = 0;\n}\n\n\n/* Non-option argument. It might be a variable definition. */\nstatic void\nhandle_non_switch_argument (const char *arg, int env)\n{\n struct variable *v;\n\n if (arg[0] == '-' && arg[1] == '\\0')\n /* Ignore plain '-' for compatibility. */\n return;\n\n v = try_variable_definition (0, arg, o_command, 0);\n if (v != 0)\n {\n /* It is indeed a variable definition. If we don't already have this\n one, record a pointer to the variable for later use in\n define_makeflags. */\n struct command_variable *cv;\n\n for (cv = command_variables; cv != 0; cv = cv->next)\n if (cv->variable == v)\n break;\n\n if (! cv)\n {\n cv = xmalloc (sizeof (*cv));\n cv->variable = v;\n cv->next = command_variables;\n command_variables = cv;\n }\n }\n else if (! env)\n {\n /* Not an option or variable definition; it must be a goal\n target! Enter it as a file and add it to the dep chain of\n goals. */\n struct file *f = enter_file (strcache_add (expand_command_line_file (arg)));\n f->cmd_target = 1;\n\n if (goals == 0)\n {\n goals = alloc_goaldep ();\n lastgoal = goals;\n }\n else\n {\n lastgoal->next = alloc_goaldep ();\n lastgoal = lastgoal->next;\n }\n\n lastgoal->file = f;\n\n {\n /* Add this target name to the MAKECMDGOALS variable. */\n struct variable *gv;\n const char *value;\n\n gv = lookup_variable (STRING_SIZE_TUPLE (\"MAKECMDGOALS\"));\n if (gv == 0)\n value = f->name;\n else\n {\n /* Paste the old and new values together */\n size_t oldlen, newlen;\n char *vp;\n\n oldlen = strlen (gv->value);\n newlen = strlen (f->name);\n vp = alloca (oldlen + 1 + newlen + 1);\n memcpy (vp, gv->value, oldlen);\n vp[oldlen] = ' ';\n memcpy (&vp[oldlen + 1], f->name, newlen + 1);\n value = vp;\n }\n define_variable_cname (\"MAKECMDGOALS\", value, o_default, 0);\n }\n }\n}\n\n/* Print a nice usage method. */\n\nstatic void\nprint_usage (int bad)\n{\n const char *const *cpp;\n FILE *usageto;\n\n if (print_version_flag)\n print_version ();\n\n usageto = bad ? stderr : stdout;\n\n fprintf (usageto, _(\"Usage: %s [options] [target] ...\\n\"), program);\n\n for (cpp = usage; *cpp; ++cpp)\n fputs (_(*cpp), usageto);\n\n if (!remote_description || *remote_description == '\\0')\n fprintf (usageto, _(\"\\nThis program built for %s\\n\"), make_host);\n else\n fprintf (usageto, _(\"\\nThis program built for %s (%s)\\n\"),\n make_host, remote_description);\n\n fprintf (usageto, _(\"Report bugs to https://github.com/rocky/remake/issues\\n\"));\n}\n\n/* Decode switches from ARGC and ARGV.\n They came from the environment if ENV is nonzero. */\n\nstatic void\ndecode_switches (int argc, const char **argv, int env)\n{\n int bad = 0;\n const struct command_switch *cs;\n struct stringlist *sl;\n int c;\n\n /* getopt does most of the parsing for us.\n First, get its vectors set up. */\n\n init_switches ();\n\n /* Let getopt produce error messages for the command line,\n but not for options from the environment. */\n opterr = !env;\n /* Reset getopt's state. */\n optind = 0;\n\n while (optind < argc)\n {\n const char *coptarg;\n\n /* Parse the next argument. */\n c = getopt_long (argc, (char*const*)argv, options, long_options, NULL);\n coptarg = optarg;\n if (c == EOF)\n /* End of arguments, or \"--\" marker seen. */\n break;\n else if (c == 1)\n /* An argument not starting with a dash. */\n handle_non_switch_argument (coptarg, env);\n else if (c == '?')\n /* Bad option. We will print a usage message and die later.\n But continue to parse the other options so the user can\n see all he did wrong. */\n bad = 1;\n else\n for (cs = switches; cs->c != '\\0'; ++cs)\n if (cs->c == c)\n {\n /* Whether or not we will actually do anything with\n this switch. We test this individually inside the\n switch below rather than just once outside it, so that\n options which are to be ignored still consume args. */\n int doit = !env || cs->env;\n\n switch (cs->type)\n {\n default:\n abort ();\n\n case ignore:\n break;\n\n case flag:\n case flag_off:\n if (doit)\n *(int *) cs->value_ptr = cs->type == flag;\n break;\n\n case string:\n case strlist:\n case filename:\n if (!doit)\n break;\n\n if (! coptarg)\n coptarg = xstrdup (cs->noarg_value);\n else if (*coptarg == '\\0')\n {\n char opt[2] = \"c\";\n const char *op = opt;\n\n if (short_option (cs->c))\n opt[0] = (char) cs->c;\n else\n op = cs->long_name;\n\n error (NILF, strlen (op),\n _(\"the '%s%s' option requires a non-empty string argument\"),\n short_option (cs->c) ? \"-\" : \"--\", op);\n bad = 1;\n break;\n }\n\n if (cs->type == string)\n {\n char **val = (char **)cs->value_ptr;\n free (*val);\n *val = xstrdup (coptarg);\n break;\n }\n\n sl = *(struct stringlist **) cs->value_ptr;\n if (sl == 0)\n {\n sl = xmalloc (sizeof (struct stringlist));\n sl->max = 5;\n sl->idx = 0;\n sl->list = xmalloc (5 * sizeof (char *));\n *(struct stringlist **) cs->value_ptr = sl;\n }\n else if (sl->idx == sl->max - 1)\n {\n sl->max += 5;\n /* MSVC erroneously warns without a cast here. */\n sl->list = xrealloc ((void *)sl->list,\n sl->max * sizeof (char *));\n }\n if (cs->type == filename)\n sl->list[sl->idx++] = expand_command_line_file (coptarg);\n else\n sl->list[sl->idx++] = xstrdup (coptarg);\n sl->list[sl->idx] = 0;\n break;\n\n case positive_int:\n /* See if we have an option argument; if we do require that\n it's all digits, not something like \"10foo\". */\n if (coptarg == 0 && argc > optind)\n {\n const char *cp;\n for (cp=argv[optind]; ISDIGIT (cp[0]); ++cp)\n ;\n if (cp[0] == '\\0')\n coptarg = argv[optind++];\n }\n\n if (!doit)\n break;\n\n if (coptarg)\n {\n int i = atoi (coptarg);\n const char *cp;\n\n /* Yes, I realize we're repeating this in some cases. */\n for (cp = coptarg; ISDIGIT (cp[0]); ++cp)\n ;\n\n if (i < 1 || cp[0] != '\\0')\n {\n error (NILF, 0,\n _(\"the '-%c' option requires a positive integer argument\"),\n cs->c);\n bad = 1;\n }\n else\n *(unsigned int *) cs->value_ptr = i;\n }\n else\n *(unsigned int *) cs->value_ptr\n = *(unsigned int *) cs->noarg_value;\n break;\n\n case floating:\n if (coptarg == 0 && optind < argc\n && (ISDIGIT (argv[optind][0]) || argv[optind][0] == '.'))\n coptarg = argv[optind++];\n\n if (doit)\n *(double *) cs->value_ptr\n = (coptarg != 0 ? atof (coptarg)\n : *(double *) cs->noarg_value);\n\n break;\n }\n\n /* We've found the switch. Stop looking. */\n break;\n }\n }\n\n /* There are no more options according to getting getopt, but there may\n be some arguments left. Since we have asked for non-option arguments\n to be returned in order, this only happens when there is a \"--\"\n argument to prevent later arguments from being options. */\n while (optind < argc)\n handle_non_switch_argument (argv[optind++], env);\n\n if (!env && (bad || print_usage_flag))\n {\n print_usage (bad);\n die (bad ? MAKE_FAILURE : MAKE_SUCCESS);\n }\n\n /* If there are any options that need to be decoded do it now. */\n decode_debug_flags ();\n decode_output_sync_flags ();\n\n /* Perform any special switch handling. */\n run_silent = silent_flag;\n\n}\n\n/* Decode switches from environment variable ENVAR (which is LEN chars long).\n We do this by chopping the value into a vector of words, prepending a\n dash to the first word if it lacks one, and passing the vector to\n decode_switches. */\n\nstatic void\ndecode_env_switches (const char *envar, size_t len)\n{\n char *varref = alloca (2 + len + 2);\n char *value, *p, *buf;\n int argc;\n const char **argv;\n\n /* Get the variable's value. */\n varref[0] = '$';\n varref[1] = '(';\n memcpy (&varref[2], envar, len);\n varref[2 + len] = ')';\n varref[2 + len + 1] = '\\0';\n value = variable_expand (varref);\n\n /* Skip whitespace, and check for an empty value. */\n NEXT_TOKEN (value);\n len = strlen (value);\n if (len == 0)\n return;\n\n /* Allocate a vector that is definitely big enough. */\n argv = alloca ((1 + len + 1) * sizeof (char *));\n\n /* getopt will look at the arguments starting at ARGV[1].\n Prepend a spacer word. */\n argv[0] = 0;\n argc = 1;\n\n /* We need a buffer to copy the value into while we split it into words\n and unquote it. Set up in case we need to prepend a dash later. */\n buf = alloca (1 + len + 1);\n buf[0] = '-';\n p = buf+1;\n argv[argc] = p;\n while (*value != '\\0')\n {\n if (*value == '\\\\' && value[1] != '\\0')\n ++value; /* Skip the backslash. */\n else if (ISBLANK (*value))\n {\n /* End of the word. */\n *p++ = '\\0';\n argv[++argc] = p;\n do\n ++value;\n while (ISBLANK (*value));\n continue;\n }\n *p++ = *value++;\n }\n *p = '\\0';\n argv[++argc] = 0;\n assert (p < buf + len + 2);\n\n if (argv[1][0] != '-' && strchr (argv[1], '=') == 0)\n /* The first word doesn't start with a dash and isn't a variable\n definition, so add a dash. */\n argv[1] = buf;\n\n /* Parse those words. */\n decode_switches (argc, argv, 1);\n}\n\f\n/* Quote the string IN so that it will be interpreted as a single word with\n no magic by decode_env_switches; also double dollar signs to avoid\n variable expansion in make itself. Write the result into OUT, returning\n the address of the next character to be written.\n Allocating space for OUT twice the length of IN is always sufficient. */\n\nstatic char *\nquote_for_env (char *out, const char *in)\n{\n while (*in != '\\0')\n {\n if (*in == '$')\n *out++ = '$';\n else if (ISBLANK (*in) || *in == '\\\\')\n *out++ = '\\\\';\n *out++ = *in++;\n }\n\n return out;\n}\n\n/* Define the MAKEFLAGS and MFLAGS variables to reflect the settings of the\n command switches. Include options with args if ALL is nonzero.\n Don't include options with the 'no_makefile' flag set if MAKEFILE. */\n\nstatic struct variable *\ndefine_makeflags (int all, int makefile)\n{\n const char ref[] = \"MAKEOVERRIDES\";\n const char posixref[] = \"-*-command-variables-*-\";\n const char evalref[] = \"$(-*-eval-flags-*-)\";\n const struct command_switch *cs;\n char *flagstring;\n char *p;\n\n /* We will construct a linked list of 'struct flag's describing\n all the flags which need to go in MAKEFLAGS. Then, once we\n know how many there are and their lengths, we can put them all\n together in a string. */\n\n struct flag\n {\n struct flag *next;\n const struct command_switch *cs;\n const char *arg;\n };\n struct flag *flags = 0;\n struct flag *last = 0;\n size_t flagslen = 0;\n#define ADD_FLAG(ARG, LEN) \\\n do { \\\n struct flag *new = alloca (sizeof (struct flag)); \\\n new->cs = cs; \\\n new->arg = (ARG); \\\n new->next = 0; \\\n if (! flags) \\\n flags = new; \\\n else \\\n last->next = new; \\\n last = new; \\\n if (new->arg == 0) \\\n /* Just a single flag letter: \" -x\" */ \\\n flagslen += 3; \\\n else \\\n /* \" -xfoo\", plus space to escape \"foo\". */ \\\n flagslen += 1 + 1 + 1 + (3 * (LEN)); \\\n if (!short_option (cs->c)) \\\n /* This switch has no single-letter version, so we use the long. */ \\\n flagslen += 2 + strlen (cs->long_name); \\\n } while (0)\n\n for (cs = switches; cs->c != '\\0'; ++cs)\n if (cs->toenv && (!makefile || !cs->no_makefile))\n switch (cs->type)\n {\n case ignore:\n break;\n\n case flag:\n case flag_off:\n if ((!*(int *) cs->value_ptr) == (cs->type == flag_off)\n && (cs->default_value == 0\n || *(int *) cs->value_ptr != *(int *) cs->default_value))\n\t if (cs->c != 'X') ADD_FLAG (0, 0);\n break;\n\n case positive_int:\n if (all)\n {\n if ((cs->default_value != 0\n && (*(unsigned int *) cs->value_ptr\n == *(unsigned int *) cs->default_value)))\n break;\n else if (cs->noarg_value != 0\n && (*(unsigned int *) cs->value_ptr ==\n *(unsigned int *) cs->noarg_value))\n ADD_FLAG (\"\", 0); /* Optional value omitted; see below. */\n else\n {\n char *buf = alloca (30);\n sprintf (buf, \"%u\", *(unsigned int *) cs->value_ptr);\n ADD_FLAG (buf, strlen (buf));\n }\n }\n break;\n\n case floating:\n if (all)\n {\n if (cs->default_value != 0\n && (*(double *) cs->value_ptr\n == *(double *) cs->default_value))\n break;\n else if (cs->noarg_value != 0\n && (*(double *) cs->value_ptr\n == *(double *) cs->noarg_value))\n ADD_FLAG (\"\", 0); /* Optional value omitted; see below. */\n else\n {\n char *buf = alloca (100);\n sprintf (buf, \"%g\", *(double *) cs->value_ptr);\n ADD_FLAG (buf, strlen (buf));\n }\n }\n break;\n\n case string:\n if (all)\n {\n p = *((char **)cs->value_ptr);\n if (p)\n ADD_FLAG (p, strlen (p));\n }\n break;\n\n case filename:\n case strlist:\n if (all)\n {\n struct stringlist *sl = *(struct stringlist **) cs->value_ptr;\n if (sl != 0)\n {\n unsigned int i;\n for (i = 0; i < sl->idx; ++i)\n ADD_FLAG (sl->list[i], strlen (sl->list[i]));\n }\n }\n break;\n\n default:\n abort ();\n }\n\n#undef ADD_FLAG\n\n /* Four more for the possible \" -- \", plus variable references. */\n flagslen += 4 + CSTRLEN (posixref) + 4 + CSTRLEN (evalref) + 4;\n\n /* Construct the value in FLAGSTRING.\n We allocate enough space for a preceding dash and trailing null. */\n flagstring = alloca (1 + flagslen + 1);\n memset (flagstring, '\\0', 1 + flagslen + 1);\n p = flagstring;\n\n /* Start with a dash, for MFLAGS. */\n *p++ = '-';\n\n /* Add simple options as a group. */\n while (flags != 0 && !flags->arg && short_option (flags->cs->c))\n {\n if (flags->cs->c != 'X') {\n *p++ = (char) flags->cs->c;\n flags = flags->next;\n }\n }\n\n /* Now add more complex flags: ones with options and/or long names. */\n while (flags)\n {\n *p++ = ' ';\n *p++ = '-';\n\n /* Add the flag letter or name to the string. */\n if (short_option (flags->cs->c)) {\n if (flags->cs->c != 'X') *p++ = (char) flags->cs->c;\n } else\n {\n /* Long options require a double-dash. */\n *p++ = '-';\n strcpy (p, flags->cs->long_name);\n p += strlen (p);\n }\n /* An omitted optional argument has an ARG of \"\". */\n if (flags->arg && flags->arg[0] != '\\0')\n {\n if (!short_option (flags->cs->c))\n /* Long options require '='. */\n *p++ = '=';\n p = quote_for_env (p, flags->arg);\n }\n flags = flags->next;\n }\n\n /* If no flags at all, get rid of the initial dash. */\n if (p == &flagstring[1])\n {\n flagstring[0] = '\\0';\n p = flagstring;\n }\n\n /* Define MFLAGS before appending variable definitions. Omit an initial\n empty dash. Since MFLAGS is not parsed for flags, there is no reason to\n override any makefile redefinition. */\n define_variable_cname (\"MFLAGS\",\n flagstring + (flagstring[0] == '-' && flagstring[1] == ' ' ? 2 : 0),\n o_env, 1);\n\n /* Write a reference to -*-eval-flags-*-, which contains all the --eval\n flag options. */\n if (eval_strings)\n {\n *p++ = ' ';\n memcpy (p, evalref, CSTRLEN (evalref));\n p += CSTRLEN (evalref);\n }\n\n if (all)\n {\n /* If there are any overrides to add, write a reference to\n $(MAKEOVERRIDES), which contains command-line variable definitions.\n Separate the variables from the switches with a \"--\" arg. */\n\n const char *r = posix_pedantic ? posixref : ref;\n size_t l = strlen (r);\n struct variable *v = lookup_variable (r, l);\n\n if (v && v->value && v->value[0] != '\\0')\n {\n strcpy (p, \" -- \");\n p += 4;\n\n *(p++) = '$';\n *(p++) = '(';\n memcpy (p, r, l);\n p += l;\n *(p++) = ')';\n }\n }\n\n /* If there is a leading dash, omit it. */\n if (flagstring[0] == '-')\n ++flagstring;\n\n /* This used to use o_env, but that lost when a makefile defined MAKEFLAGS.\n Makefiles set MAKEFLAGS to add switches, but we still want to redefine\n its value with the full set of switches. Then we used o_file, but that\n lost when users added -e, causing a previous MAKEFLAGS env. var. to take\n precedence over the new one. Of course, an override or command\n definition will still take precedence. */\n return define_variable_cname (\"MAKEFLAGS\", flagstring,\n env_overrides ? o_env_override : o_file, 1);\n}\n\f\n/* Print version information. */\n\nstatic void\nprint_version (void)\n{\n static int printed_version = 0;\n\n const char *precede = print_data_base_flag ? \"# \" : \"\";\n\n if (printed_version)\n /* Do it only once. */\n return;\n\n printf (\"%sGNU Make %s\\n\", precede, version_string);\n\n if (!remote_description || *remote_description == '\\0')\n printf (_(\"%sBuilt for %s\\n\"), precede, make_host);\n else\n printf (_(\"%sBuilt for %s (%s)\\n\"),\n precede, make_host, remote_description);\n\n /* Print this untranslated. The coding standards recommend translating the\n (C) to the copyright symbol, but this string is going to change every\n year, and none of the rest of it should be translated (including the\n word \"Copyright\"), so it hardly seems worth it. */\n\n printf (\"%sCopyright (C) 1988-2020 Free Software Foundation, Inc.\\n\"\n\t \"Copyright (C) 2015, 2017 Rocky Bernstein.\\n\",\n precede);\n\n printf (_(\"%sLicense GPLv3+: GNU GPL version 3 or later \\n\\\n%sThis is free software: you are free to change and redistribute it.\\n\\\n%sThere is NO WARRANTY, to the extent permitted by law.\\n\"),\n precede, precede, precede);\n\n printed_version = 1;\n\n /* Flush stdout so the user doesn't have to wait to see the\n version information while make thinks about things. */\n fflush (stdout);\n}\n\n/* Print a bunch of information about this and that. */\n\nstatic void\nprint_data_base (void)\n{\n time_t when = time ((time_t *) 0);\n\n print_version ();\n\n printf (_(\"\\n# Make data base, printed on %s\"), ctime (&when));\n\n print_variable_data_base ();\n print_dir_data_base ();\n print_rule_data_base (true);\n print_file_data_base ();\n print_vpath_data_base ();\n strcache_print_stats (\"#\");\n\n when = time ((time_t *) 0);\n printf (_(\"\\n# Finished Make data base on %s\\n\"), ctime (&when));\n}\n\nstatic void\nclean_jobserver (int status)\n{\n /* Sanity: have we written all our jobserver tokens back? If our\n exit status is 2 that means some kind of syntax error; we might not\n have written all our tokens so do that now. If tokens are left\n after any other error code, that's bad. */\n\n if (jobserver_enabled() && jobserver_tokens)\n {\n if (status != 2)\n ON (error, NILF,\n \"INTERNAL: Exiting with %u jobserver tokens (should be 0)!\",\n jobserver_tokens);\n else\n /* Don't write back the \"free\" token */\n while (--jobserver_tokens)\n jobserver_release (0);\n }\n\n\n /* Sanity: If we're the master, were all the tokens written back? */\n\n if (master_job_slots)\n {\n /* We didn't write one for ourself, so start at 1. */\n unsigned int tokens = 1 + jobserver_acquire_all ();\n\n if (tokens != master_job_slots)\n ONN (error, NILF,\n \"INTERNAL: Exiting with %u jobserver tokens available; should be %u!\",\n tokens, master_job_slots);\n\n reset_jobserver ();\n }\n}\n\f\n/* Exit with STATUS, cleaning up as necessary. */\n\nvoid\ndie (int status)\n{\n static char dying = 0;\n\n if (!dying)\n {\n int err;\n\n dying = 1;\n\n if (print_version_flag)\n print_version ();\n\n /* Wait for children to die. */\n err = (status != 0);\n while (job_slots_used > 0)\n reap_children (1, err, NULL);\n\n /* Let the remote job module clean up its state. */\n remote_cleanup ();\n\n /* Remove the intermediate files. */\n remove_intermediates (0);\n\n if (print_data_base_flag)\n print_data_base ();\n\n if (verify_flag)\n verify_file_data_base ();\n\n clean_jobserver (status);\n\n if (output_context)\n {\n /* die() might be called in a recipe output context due to an\n $(error ...) function. */\n output_close (output_context);\n\n if (output_context != &make_sync)\n output_close (&make_sync);\n\n OUTPUT_UNSET ();\n }\n\n output_close (NULL);\n\n /* Try to move back to the original directory. This is essential on\n MS-DOS (where there is really only one process), and on Unix it\n puts core files in the original directory instead of the -C\n directory. Must wait until after remove_intermediates(), or unlinks\n of relative pathnames fail. */\n if (directory_before_chdir != 0)\n {\n /* If it fails we don't care: shut up GCC. */\n int _x UNUSED;\n _x = chdir (directory_before_chdir);\n }\n }\n\n if (profile_flag) {\n const char *status_str;\n switch (status) {\n case MAKE_SUCCESS:\n\tstatus_str = \"Normal program termination\";\n\tbreak;\n case MAKE_TROUBLE:\n\tstatus_str = \"Platform failure termination\";\n\tbreak;\n case MAKE_FAILURE:\n\tstatus_str = \"Failure program termination\";\n\tbreak;\n case DEBUGGER_QUIT_RC:\n\tstatus_str = \"Debugger termination\";\n\tbreak;\n default:\n\tstatus_str = \"\";\n }\n\n profile_close(status_str, goals, (jobserver_auth != NULL));\n }\n exit (status);\n}\n"}, "files_after": {"src/main.c": "/* Argument parsing and main program of GNU Make.\nCopyright (C) 1988-2020 Free Software Foundation, Inc.\nCopyright (C) 2015, 2017 Rocky Bernstein\nThis file is part of GNU Make.\n\nGNU Make is free software; you can redistribute it and/or modify it under the\nterms of the GNU General Public License as published by the Free Software\nFoundation; either version 3 of the License, or (at your option) any later\nversion.\n\nGNU Make is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE. See the GNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License along with\nthis program. If not, see . */\n\n#include \"makeint.h\"\n#include \"globals.h\"\n#include \"profile.h\"\n#include \"os.h\"\n#include \"filedef.h\"\n#include \"dep.h\"\n#include \"variable.h\"\n#include \"job.h\"\n#include \"commands.h\"\n#include \"rule.h\"\n#include \"debug.h\"\n#include \"getopt.h\"\n// debugger include(s)\n#include \"cmd.h\"\n\n#include \n#ifdef WINDOWS32\n# include \n# include \n#ifdef HAVE_STRINGS_H\n# include \t/* for strcasecmp */\n#endif\n# include \"pathstuff.h\"\n# include \"sub_proc.h\"\n# include \"w32err.h\"\n#endif\n#ifdef HAVE_FCNTL_H\n# include \n#endif\n\nstruct goaldep *read_makefiles;\n\nextern void initialize_stopchar_map ();\n\n#if defined HAVE_WAITPID || defined HAVE_WAIT3\n# define HAVE_WAIT_NOHANG\n#endif\n\n#ifndef HAVE_UNISTD_H\nint chdir ();\n#endif\n#ifndef STDC_HEADERS\n# ifndef sun /* Sun has an incorrect decl in a header. */\nvoid exit (int) NORETURN;\n# endif\ndouble atof ();\n#endif\n\nstatic void clean_jobserver (int status);\nstatic void print_data_base (void);\nvoid print_rule_data_base (bool b_verbose);\nstatic void print_version (void);\nstatic void decode_switches (int argc, const char **argv, int env);\nstatic void decode_env_switches (const char *envar, size_t len);\nstatic struct variable *define_makeflags (int all, int makefile);\nstatic char *quote_for_env (char *out, const char *in);\nstatic void initialize_global_hash_tables (void);\n\n\f\n/* The structure that describes an accepted command switch. */\n\nstruct command_switch\n {\n int c; /* The switch character. */\n\n enum /* Type of the value. */\n {\n flag, /* Turn int flag on. */\n flag_off, /* Turn int flag off. */\n string, /* One string per invocation. */\n strlist, /* One string per switch. */\n filename, /* A string containing a file name. */\n positive_int, /* A positive integer. */\n floating, /* A floating-point number (double). */\n ignore /* Ignored. */\n } type;\n\n void *value_ptr; /* Pointer to the value-holding variable. */\n\n unsigned int env:1; /* Can come from MAKEFLAGS. */\n unsigned int toenv:1; /* Should be put in MAKEFLAGS. */\n unsigned int no_makefile:1; /* Don't propagate when remaking makefiles. */\n\n const void *noarg_value; /* Pointer to value used if no arg given. */\n const void *default_value; /* Pointer to default value. */\n\n const char *long_name; /* Long option name. */\n };\n\n/* True if C is a switch value that corresponds to a short option. */\n\n#define short_option(c) ((c) <= CHAR_MAX)\n\n/* The structure used to hold the list of strings given\n in command switches of a type that takes strlist arguments. */\n\n/* The recognized command switches. */\n\nstatic const int default_silent_flag = 0;\n\n/* Nonzero means either -s was given, or .SILENT-with-no-deps was seen. */\n\nint run_silent = 0;\n\n/*! If non-null, contains the type of tracing we are to do.\n This is coordinated with tracing_flag. */\nstringlist_t *tracing_opts = NULL;\n\n/*! If true, show version information on entry. */\nbool b_show_version = false;\n\n/*! If true, go into debugger on error.\nSets --debugger --debugger-stop=error. */\nint post_mortem_flag = 0;\n\n/*! Nonzero means use GNU readline in the debugger. */\nint use_readline_flag =\n#ifdef HAVE_LIBREADLINE\n 1\n#else\n 0\n#endif\n ;\n\n/*! If nonzero, the basename of filenames is in giving locations. Normally,\n giving a file directory location helps a debugger frontend\n when we change directories. For regression tests it is helpful to\n list just the basename part as that doesn't change from installation\n to installation. Users may have their preferences too.\n*/\nint basename_filenames = 0;\n\n/* Synchronize output (--output-sync). */\n\nchar *output_sync_option = 0;\n\n/* Specify profile output formatting (--profile) */\n\nchar *profile_option = 0;\n\n/* Specify the output directory for profiling information */\n\nstatic struct stringlist *profile_dir_opt = 0;\n\n/* Output level (--verbosity). */\n\nstatic struct stringlist *verbosity_opts;\n\n/* Environment variables override makefile definitions. */\n\n/* Nonzero means keep going even if remaking some file fails (-k). */\n\nint keep_going_flag;\nstatic const int default_keep_going_flag = 0;\n\n/*! Nonzero gives a list of explicit target names that have commands\n AND comments associated with them and exits. Set by option --task-comments\n */\n\nint show_task_comments_flag = 0;\n\n/* Nonzero means ignore print_directory and never print the directory.\n This is necessary because print_directory is set implicitly. */\n\nint inhibit_print_directory = 0;\n\n/* List of makefiles given with -f switches. */\n\nstatic struct stringlist *makefiles = 0;\n\n/* Size of the stack when we started. */\n\n#ifdef SET_STACK_SIZE\nstruct rlimit stack_limit;\n#endif\n\n\n/* Number of job slots for parallelism. */\n\nunsigned int job_slots;\n\n#define INVALID_JOB_SLOTS (-1)\nstatic unsigned int master_job_slots = 0;\nstatic int arg_job_slots = INVALID_JOB_SLOTS;\n\nstatic const int default_job_slots = INVALID_JOB_SLOTS;\n\n/* Value of job_slots that means no limit. */\n\nstatic const int inf_jobs = 0;\n\n/* Authorization for the jobserver. */\n\nstatic char *jobserver_auth = NULL;\n\n/* Handle for the mutex used on Windows to synchronize output of our\n children under -O. */\n\nchar *sync_mutex = NULL;\n\n/* Maximum load average at which multiple jobs will be run.\n Negative values mean unlimited, while zero means limit to\n zero load (which could be useful to start infinite jobs remotely\n but one at a time locally). */\ndouble max_load_average = -1.0;\ndouble default_load_average = -1.0;\n\n/* List of directories given with -C switches. */\n\nstatic struct stringlist *directories = 0;\n\n/* List of include directories given with -I switches. */\n\nstatic struct stringlist *include_directories = 0;\n\n/* List of files given with -o switches. */\n\nstatic struct stringlist *old_files = 0;\n\n/* List of files given with -W switches. */\n\nstatic struct stringlist *new_files = 0;\n\n/* List of strings to be eval'd. */\nstatic struct stringlist *eval_strings = 0;\n\n/* If nonzero, we should just print usage and exit. */\n\nstatic int print_usage_flag = 0;\n\n/*! Do we want to go into a debugger or not?\n Values are \"error\" - enter on errors or fatal errors\n \"fatal\" - enter on fatal errors\n \"goal\" - set to enter debugger before updating goal\n \"preread\" - set to enter debugger before reading makefile(s)\n \"preaction\" - set to enter debugger before performing any\n actions(s)\n \"full\" - \"enter\" + \"error\" + \"fatal\"\n*/\nstatic stringlist_t* debugger_opts = NULL;\n\n/* If nonzero, always build all targets, regardless of whether\n they appear out of date or not. */\nstatic int always_make_set = 0;\nint always_make_flag = 0;\n\n/* If nonzero, we're in the \"try to rebuild makefiles\" phase. */\n\nint rebuilding_makefiles = 0;\n\n\f\n/* The usage output. We write it this way to make life easier for the\n translators, especially those trying to translate to right-to-left\n languages like Hebrew. */\n\nstatic const char *const usage[] =\n {\n N_(\"Options:\\n\"),\n N_(\"\\\n -b, -m Ignored for compatibility.\\n\"),\n N_(\"\\\n -B, --always-make Unconditionally make all targets.\\n\"),\n N_(\"\\\n -c, --search-parent Search parent directories for Makefile.\\n\"),\n N_(\"\\\n -C DIRECTORY, --directory=DIRECTORY\\n\\\n Change to DIRECTORY before doing anything.\\n\"),\n N_(\"\\\n -d Print lots of debugging information.\\n\"),\n N_(\"\\\n --debug[=FLAGS] Print various types of debugging information.\\n\"),\n N_(\"\\\n -e, --environment-overrides\\n\\\n Environment variables override makefiles.\\n\"),\n N_(\"\\\n -E STRING, --eval=STRING Evaluate STRING as a makefile statement.\\n\"),\n N_(\"\\\n -f FILE, --file=FILE, --makefile=FILE\\n\\\n Read FILE as a makefile.\\n\"),\n N_(\"\\\n -h, --help Print this message and exit.\\n\"),\n N_(\"\\\n -i, --ignore-errors Ignore errors from recipes.\\n\"),\n N_(\"\\\n -I DIRECTORY, --include-dir=DIRECTORY\\n\\\n Search DIRECTORY for included makefiles.\\n\"),\n N_(\"\\\n -j [N], --jobs[=N] Allow N jobs at once; infinite jobs with no arg.\\n\"),\n N_(\"\\\n -k, --keep-going Keep going when some targets can't be made.\\n\"),\n N_(\"\\\n -l [N], --load-average[=N], --max-load[=N]\\n\\\n Don't start multiple jobs unless load is below N.\\n\"),\n N_(\"\\\n -L, --check-symlink-times Use the latest mtime between symlinks and target.\\n\"),\n N_(\"\\\n --no-extended-errors Do not give additional error reporting.\\n\"),\n N_(\"\\\n -n, --just-print, --dry-run, --recon\\n\\\n Don't actually run any recipe; just print them.\\n\"),\n N_(\"\\\n -o FILE, --old-file=FILE, --assume-old=FILE\\n\\\n Consider FILE to be very old and don't remake it.\\n\"),\n N_(\"\\\n -O[TYPE], --output-sync[=TYPE]\\n\\\n Synchronize output of parallel jobs by TYPE.\\n\"),\n N_(\"\\\n -p, --print-data-base Print make's internal database.\\n\"),\n N_(\"\\\n -P, --profile[=FORMAT] Print profiling information for each target using FORMAT.\\n\\\n If FORMAT isn't specified, default to \\\"callgrind\\\"\\n\"),\n N_(\"\\\n --profile-directory=DIR Output profiling data to the DIR directory.\\n\"),\n N_(\"\\\n -q, --question Run no recipe; exit status says if up to date.\\n\"),\n N_(\"\\\n -r, --no-builtin-rules Disable the built-in implicit rules.\\n\"),\n N_(\"\\\n -R, --no-builtin-variables Disable the built-in variable settings.\\n\"),\n N_(\"\\\n -s, --silent, --quiet Don't echo recipes.\\n\"),\n N_(\"\\\n --no-silent Echo recipes (disable --silent mode).\\n\"),\n N_(\"\\\n -S, --no-keep-going, --stop\\n\\\n Turns off -k.\\n\"),\n N_(\"\\\n --targets Give list of explicitly-named targets.\\n\"),\n N_(\"\\\n --tasks Give list of targets which have descriptions\\n\\\n associated with them.\\n\"),\n N_(\"\\\n -t, --touch Touch targets instead of remaking them.\\n\"),\n N_(\"\\\n -v, --version Print the version number of make and exit.\\n\"),\n N_(\"\\\n --verbosity=LEVEL Set verbosity level. LEVEL may be \\\"terse\\\" \\\"no-header\\\" or\\n\\\n \\\"full\\\". The default is \\\"full\\\".\\n\"),\n N_(\"\\\n -w, --print-directory Print the current directory.\\n\"),\n N_(\"\\\n --no-print-directory Turn off -w, even if it was turned on implicitly.\\n\"),\n N_(\"\\\n -W FILE, --what-if=FILE, --new-file=FILE, --assume-new=FILE\\n\\\n Consider FILE to be infinitely new.\\n\"),\n N_(\"\\\n --warn-undefined-variables Warn when an undefined variable is referenced.\\n\"),\n N_(\"\\\n -x, --trace[=TYPE] Trace command execution TYPE may be\\n\\\n \\\"command\\\", \\\"read\\\", \\\"normal\\\".\\\"\\n\\\n \\\"noshell\\\", or \\\"full\\\". Default is \\\"normal\\\"\\n\"),\n N_(\"\\\n --debugger-stop[=TYPE] Which point to enter debugger. TYPE may be\\n\\\n \\\"goal\\\", \\\"preread\\\", \\\"preaction\\\",\\n\\\n \\\"full\\\", \\\"error\\\", or \\\"fatal\\\".\\n\\\n Only makes sense with -X set.\\n\"),\n N_(\"\\\n -v, --version Print the version number of make and exit.\\n\"),\n N_(\"\\\n -X, --debugger Enter debugger.\\n\"),\n N_(\"\\\n -!, --post-mortem Go into debugger on error.\\n\\\n Same as --debugger --debugger-stop=error\\n\"),\n N_(\"\\\n --no-readline Do not use GNU ReadLine in debugger.\\n\"),\n NULL\n };\n\n/* The table of command switches.\n Order matters here: this is the order MAKEFLAGS will be constructed.\n So be sure all simple flags (single char, no argument) come first. */\n\nstatic const struct command_switch switches[] =\n {\n { 'b', ignore, 0, 0, 0, 0, 0, 0, 0 },\n { 'B', flag, &always_make_set, 1, 1, 0, 0, 0, \"always-make\" },\n { 'c', flag, &search_parent_flag, 1, 1, 0, 0, 0, \"search-parent\" },\n { 'd', flag, &debug_flag, 1, 1, 0, 0, 0, 0 },\n { 'e', flag, &env_overrides, 1, 1, 0, 0, 0, \"environment-overrides\", },\n { 'h', flag, &print_usage_flag, 0, 0, 0, 0, 0, \"help\" },\n { 'i', flag, &ignore_errors_flag, 1, 1, 0, 0, 0, \"ignore-errors\" },\n { 'k', flag, &keep_going_flag, 1, 1, 0, 0, &default_keep_going_flag,\n \"keep-going\" },\n { 'L', flag, &check_symlink_flag, 1, 1, 0, 0, 0, \"check-symlink-times\" },\n { 'm', ignore, 0, 0, 0, 0, 0, 0, 0 },\n { 'n', flag, &just_print_flag, 1, 1, 1, 0, 0, \"just-print\" },\n { 'p', flag, &print_data_base_flag, 1, 1, 0, 0, 0, \"print-data-base\" },\n { 'P', string, &profile_option, 1, 1, 0, \"callgrind\", 0, \"profile\" },\n { 'q', flag, &question_flag, 1, 1, 1, 0, 0, \"question\" },\n { 'r', flag, &no_builtin_rules_flag, 1, 1, 0, 0, 0, \"no-builtin-rules\" },\n { 'R', flag, &no_builtin_variables_flag, 1, 1, 0, 0, 0,\n \"no-builtin-variables\" },\n { 's', flag, &silent_flag, 1, 1, 0, 0, &default_silent_flag, \"silent\" },\n { 'S', flag_off, &keep_going_flag, 1, 1, 0, 0, &default_keep_going_flag,\n \"no-keep-going\" },\n { 't', flag, &touch_flag, 1, 1, 1, 0, 0, \"touch\" },\n { 'v', flag, &print_version_flag, 1, 1, 0, 0, 0, \"version\" },\n { 'w', flag, &print_directory, 1, 1, 0, 0, 0, \"print-directory\" },\n { 'X', flag, &debugger_flag, 1, 1, 0, 0, 0, \"debugger\" },\n { '!', flag, &post_mortem_flag, 1, 1, 0, 0, 0, \"post-mortem\" },\n\n /* These options take arguments. */\n { 'C', filename, &directories, 0, 0, 0, 0, 0, \"directory\" },\n { 'E', strlist, &eval_strings, 1, 0, 0, 0, 0, \"eval\" },\n { 'f', filename, &makefiles, 0, 0, 0, 0, 0, \"file\" },\n { 'I', filename, &include_directories, 1, 1, 0, 0, 0,\n \"include-dir\" },\n { 'j', positive_int, &arg_job_slots, 1, 1, 0, &inf_jobs, &default_job_slots,\n \"jobs\" },\n { 'l', floating, &max_load_average, 1, 1, 0, &default_load_average,\n &default_load_average, \"load-average\" },\n { 'o', filename, &old_files, 0, 0, 0, 0, 0, \"old-file\" },\n { 'O', string, &output_sync_option, 1, 1, 0, \"target\", 0, \"output-sync\" },\n { 'W', filename, &new_files, 0, 0, 0, 0, 0, \"what-if\" },\n { 'x', strlist, &tracing_opts, 1, 1, 0, \"normal\", 0, \"trace\" },\n\n /* These are long-style options. */\n { CHAR_MAX+1, strlist, &db_flags, 1, 1, 0, \"basic\", 0, \"debug\" },\n { CHAR_MAX+2, string, &jobserver_auth, 1, 1, 0, 0, 0, \"jobserver-auth\" },\n { CHAR_MAX+3, flag, &show_tasks_flag, 0, 0, 0, 0, 0, \"tasks\" },\n { CHAR_MAX+4, flag, &inhibit_print_directory, 1, 1, 0, 0, 0,\n \"no-print-directory\" },\n { CHAR_MAX+5, flag, &warn_undefined_variables_flag, 1, 1, 0, 0, 0,\n \"warn-undefined-variables\" },\n { CHAR_MAX+7, string, &sync_mutex, 1, 1, 0, 0, 0, \"sync-mutex\" },\n { CHAR_MAX+8, flag_off, &silent_flag, 1, 1, 0, 0, &default_silent_flag, \"no-silent\" },\n { CHAR_MAX+9, string, &jobserver_auth, 1, 0, 0, 0, 0, \"jobserver-fds\" },\n { CHAR_MAX+10, strlist, &verbosity_opts, 1, 1, 0, 0, 0,\n \"verbosity\" },\n { CHAR_MAX+11, flag, (char *) &no_extended_errors, 1, 1, 0, 0, 0,\n \"no-extended-errors\", },\n { CHAR_MAX+12, flag_off, (char *) &use_readline_flag, 1, 0, 0, 0, 0,\n \"no-readline\", },\n { CHAR_MAX+13, flag, &show_targets_flag, 0, 0, 0, 0, 0,\n \"targets\" },\n { CHAR_MAX+14, strlist, &debugger_opts, 1, 1, 0, \"preaction\", 0,\n \"debugger-stop\" },\n { CHAR_MAX+15, filename, &profile_dir_opt, 1, 1, 0, 0, 0, \"profile-directory\" },\n { 0, 0, 0, 0, 0, 0, 0, 0, 0 }\n };\n\n/* Secondary long names for options. */\n\nstatic struct option long_option_aliases[] =\n {\n { \"quiet\", no_argument, 0, 's' },\n { \"stop\", no_argument, 0, 'S' },\n { \"new-file\", required_argument, 0, 'W' },\n { \"assume-new\", required_argument, 0, 'W' },\n { \"assume-old\", required_argument, 0, 'o' },\n { \"max-load\", optional_argument, 0, 'l' },\n { \"dry-run\", no_argument, 0, 'n' },\n { \"recon\", no_argument, 0, 'n' },\n { \"makefile\", required_argument, 0, 'f' },\n };\n\n/* List of goal targets. */\n\nstatic struct goaldep *goals, *lastgoal;\n\n/* List of variables which were defined on the command line\n (or, equivalently, in MAKEFLAGS). */\n\nstruct command_variable\n {\n struct command_variable *next;\n struct variable *variable;\n };\nstatic struct command_variable *command_variables;\n\n/*! Value of argv[0] which seems to get modified. Can we merge this with\n program below? */\nchar *argv0 = NULL;\n\n/*! The name we were invoked with. */\n\n/*! Our initial arguments -- used for debugger restart execvp. */\nconst char * const*global_argv;\n\n/*! Our current directory before processing any -C options. */\nchar *directory_before_chdir = NULL;\n\n/*! Pointer to the value of the .DEFAULT_GOAL special variable.\n The value will be the name of the goal to remake if the command line\n does not override it. It can be set by the makefile, or else it's\n the first target defined in the makefile whose name does not start\n with '.'. */\nstruct variable * default_goal_var;\n\n/*! Pointer to structure for the file .DEFAULT\n whose commands are used for any file that has none of its own.\n This is zero if the makefiles do not define .DEFAULT. */\nstruct file *default_file;\n\n/* Nonzero if we have seen the '.SECONDEXPANSION' target.\n This turns on secondary expansion of prerequisites. */\n\nint second_expansion;\n\n/* Nonzero if we have seen the '.ONESHELL' target.\n This causes the entire recipe to be handed to SHELL\n as a single string, potentially containing newlines. */\n\nint one_shell;\n\n/* Nonzero if we have seen the '.NOTPARALLEL' target.\n This turns off parallel builds for this invocation of make. */\n\nint not_parallel;\n\n/* Nonzero if some rule detected clock skew; we keep track so (a) we only\n print one warning about it during the run, and (b) we can print a final\n warning at the end of the run. */\n\nint clock_skew_detected;\n\n/* If output-sync is enabled we'll collect all the output generated due to\n options, while reading makefiles, etc. */\n\nstruct output make_sync;\n\n\f\n/* Mask of signals that are being caught with fatal_error_signal. */\n\n#if defined(POSIX)\nsigset_t fatal_signal_set;\n#elif defined(HAVE_SIGSETMASK)\nint fatal_signal_mask;\n#endif\n\n#if !HAVE_DECL_BSD_SIGNAL && !defined bsd_signal\n# if !defined HAVE_SIGACTION\n# define bsd_signal signal\n# else\ntypedef RETSIGTYPE (*bsd_signal_ret_t) (int);\n\nstatic bsd_signal_ret_t\nbsd_signal (int sig, bsd_signal_ret_t func)\n{\n struct sigaction act, oact;\n act.sa_handler = func;\n act.sa_flags = SA_RESTART;\n sigemptyset (&act.sa_mask);\n sigaddset (&act.sa_mask, sig);\n if (sigaction (sig, &act, &oact) != 0)\n return SIG_ERR;\n return oact.sa_handler;\n}\n# endif\n#endif\n\nvoid\ndecode_trace_flags (stringlist_t *ppsz_tracing_opts)\n{\n if (ppsz_tracing_opts) {\n const char **p;\n db_level |= (DB_TRACE | DB_SHELL);\n if (!ppsz_tracing_opts->list)\n db_level |= (DB_BASIC);\n else\n for (p = ppsz_tracing_opts->list; *p != 0; ++p) {\n if (0 == strcmp(*p, \"command\"))\n ;\n else if (0 == strcmp(*p, \"full\"))\n db_level |= (DB_VERBOSE|DB_READ_MAKEFILES);\n else if (0 == strcmp(*p, \"normal\"))\n db_level |= DB_BASIC;\n else if (0 == strcmp(*p, \"noshell\"))\n db_level = DB_BASIC | DB_TRACE;\n else if (0 == strcmp(*p, \"read\"))\n db_level |= DB_READ_MAKEFILES;\n else\n OS ( fatal, NILF, _(\"unknown trace command execution type `%s'\"), *p);\n }\n }\n}\n\nvoid\ndecode_verbosity_flags (stringlist_t *ppsz_verbosity_opts)\n{\n if (ppsz_verbosity_opts) {\n const char **p;\n if (ppsz_verbosity_opts->list)\n for (p = ppsz_verbosity_opts->list; *p != 0; ++p) {\n if (0 == strcmp(*p, \"no-header\"))\n b_show_version = false;\n else if (0 == strcmp(*p, \"full\")) {\n db_level |= (DB_VERBOSE);\n\t b_show_version = true;\n\t} else if (0 == strcmp(*p, \"terse\")) {\n\t db_level &= (~DB_VERBOSE);\n\t b_show_version = false;\n\t}\n }\n }\n}\n\nstatic void\ninitialize_global_hash_tables (void)\n{\n init_hash_global_variable_set ();\n strcache_init ();\n init_hash_files ();\n hash_init_directories ();\n hash_init_function_table ();\n}\n\n/* This character map locate stop chars when parsing GNU makefiles.\n Each element is true if we should stop parsing on that character. */\n\nstatic const char *\nexpand_command_line_file (const char *name)\n{\n const char *cp;\n char *expanded = 0;\n\n if (name[0] == '\\0')\n O (fatal, NILF, _(\"empty string invalid as file name\"));\n\n if (name[0] == '~')\n {\n expanded = remake_tilde_expand (name);\n if (expanded && expanded[0] != '\\0')\n name = expanded;\n }\n\n /* This is also done in parse_file_seq, so this is redundant\n for names read from makefiles. It is here for names passed\n on the command line. */\n while (name[0] == '.' && name[1] == '/')\n {\n name += 2;\n while (name[0] == '/')\n /* Skip following slashes: \".//foo\" is \"foo\", not \"/foo\". */\n ++name;\n }\n\n if (name[0] == '\\0')\n {\n /* Nothing else but one or more \"./\", maybe plus slashes! */\n name = \"./\";\n }\n\n cp = strcache_add (name);\n\n free (expanded);\n\n return cp;\n}\n\n/* Toggle -d on receipt of SIGUSR1. */\n\n#ifdef SIGUSR1\nstatic RETSIGTYPE\ndebug_signal_handler (int sig UNUSED)\n{\n db_level = db_level ? DB_NONE : DB_BASIC;\n}\n#endif\n\nstatic void\ndecode_debug_flags (void)\n{\n const char **pp;\n\n if (debug_flag)\n db_level = DB_ALL;\n\n if (db_flags)\n for (pp=db_flags->list; *pp; ++pp)\n {\n const char *p = *pp;\n\n while (1)\n {\n switch (tolower (p[0]))\n {\n case 'a':\n db_level |= DB_ALL;\n break;\n case 'b':\n db_level |= DB_BASIC;\n break;\n case 'i':\n db_level |= DB_BASIC | DB_IMPLICIT;\n break;\n case 'j':\n db_level |= DB_JOBS;\n break;\n case 'm':\n db_level |= DB_BASIC | DB_MAKEFILES;\n break;\n case 'n':\n db_level = 0;\n break;\n case 'v':\n db_level |= DB_BASIC | DB_VERBOSE;\n break;\n default:\n OS (fatal, NILF,\n _(\"unknown debug level specification '%s'\"), p);\n }\n\n while (*(++p) != '\\0')\n if (*p == ',' || *p == ' ')\n {\n ++p;\n break;\n }\n\n if (*p == '\\0')\n break;\n }\n }\n\n if (db_level)\n verify_flag = 1;\n\n if (! db_level)\n debug_flag = 0;\n}\n\nstatic void\ndecode_output_sync_flags (void)\n{\n#ifdef NO_OUTPUT_SYNC\n output_sync = OUTPUT_SYNC_NONE;\n#else\n if (output_sync_option)\n {\n if (streq (output_sync_option, \"none\"))\n output_sync = OUTPUT_SYNC_NONE;\n else if (streq (output_sync_option, \"line\"))\n output_sync = OUTPUT_SYNC_LINE;\n else if (streq (output_sync_option, \"target\"))\n output_sync = OUTPUT_SYNC_TARGET;\n else if (streq (output_sync_option, \"recurse\"))\n output_sync = OUTPUT_SYNC_RECURSE;\n else\n OS (fatal, NILF,\n _(\"unknown output-sync type '%s'\"), output_sync_option);\n }\n\n if (sync_mutex)\n RECORD_SYNC_MUTEX (sync_mutex);\n#endif\n}\n\nvoid\ndecode_profile_options(void)\n{\n if (profile_option)\n {\n if (streq (profile_option, \"callgrind\"))\n profile_flag = PROFILE_CALLGRIND;\n else if (streq (profile_option, \"json\"))\n profile_flag = PROFILE_JSON;\n else\n profile_flag = PROFILE_DISABLED;\n }\n else\n {\n profile_flag = PROFILE_DISABLED;\n }\n\n if (profile_dir_opt == NULL)\n {\n profile_directory = starting_directory;\n }\n else\n {\n const char *dir = profile_dir_opt->list[profile_dir_opt->idx - 1];\n if (dir[0] != '/') {\n char directory[GET_PATH_MAX];\n sprintf(directory, \"%s/%s\", starting_directory, dir);\n profile_dir_opt->list[profile_dir_opt->idx - 1] = strcache_add(directory);\n }\n profile_directory = profile_dir_opt->list[profile_dir_opt->idx - 1];\n }\n}\n\n#ifdef WINDOWS32\n\n#ifndef NO_OUTPUT_SYNC\n\n/* This is called from start_job_command when it detects that\n output_sync option is in effect. The handle to the synchronization\n mutex is passed, as a string, to sub-makes via the --sync-mutex\n command-line argument. */\nvoid\nprepare_mutex_handle_string (sync_handle_t handle)\n{\n if (!sync_mutex)\n {\n /* Prepare the mutex handle string for our children. */\n /* 2 hex digits per byte + 2 characters for \"0x\" + null. */\n sync_mutex = xmalloc ((2 * sizeof (sync_handle_t)) + 2 + 1);\n sprintf (sync_mutex, \"0x%Ix\", handle);\n define_makeflags (1, 0);\n }\n}\n\n#endif /* NO_OUTPUT_SYNC */\n\n/*\n * HANDLE runtime exceptions by avoiding a requestor on the GUI. Capture\n * exception and print it to stderr instead.\n *\n * If ! DB_VERBOSE, just print a simple message and exit.\n * If DB_VERBOSE, print a more verbose message.\n * If compiled for DEBUG, let exception pass through to GUI so that\n * debuggers can attach.\n */\nLONG WINAPI\nhandle_runtime_exceptions (struct _EXCEPTION_POINTERS *exinfo)\n{\n PEXCEPTION_RECORD exrec = exinfo->ExceptionRecord;\n LPSTR cmdline = GetCommandLine ();\n LPSTR prg = strtok (cmdline, \" \");\n CHAR errmsg[1024];\n#ifdef USE_EVENT_LOG\n HANDLE hEventSource;\n LPTSTR lpszStrings[1];\n#endif\n\n if (! ISDB (DB_VERBOSE))\n {\n sprintf (errmsg,\n _(\"%s: Interrupt/Exception caught (code = 0x%lx, addr = 0x%p)\\n\"),\n prg, exrec->ExceptionCode, exrec->ExceptionAddress);\n fprintf (stderr, errmsg);\n exit (255);\n }\n\n sprintf (errmsg,\n _(\"\\nUnhandled exception filter called from program %s\\nExceptionCode = %lx\\nExceptionFlags = %lx\\nExceptionAddress = 0x%p\\n\"),\n prg, exrec->ExceptionCode, exrec->ExceptionFlags,\n exrec->ExceptionAddress);\n\n if (exrec->ExceptionCode == EXCEPTION_ACCESS_VIOLATION\n && exrec->NumberParameters >= 2)\n sprintf (&errmsg[strlen(errmsg)],\n (exrec->ExceptionInformation[0]\n ? _(\"Access violation: write operation at address 0x%p\\n\")\n : _(\"Access violation: read operation at address 0x%p\\n\")),\n (PVOID)exrec->ExceptionInformation[1]);\n\n /* turn this on if we want to put stuff in the event log too */\n#ifdef USE_EVENT_LOG\n hEventSource = RegisterEventSource (NULL, \"GNU Make\");\n lpszStrings[0] = errmsg;\n\n if (hEventSource != NULL)\n {\n ReportEvent (hEventSource, /* handle of event source */\n EVENTLOG_ERROR_TYPE, /* event type */\n 0, /* event category */\n 0, /* event ID */\n NULL, /* current user's SID */\n 1, /* strings in lpszStrings */\n 0, /* no bytes of raw data */\n lpszStrings, /* array of error strings */\n NULL); /* no raw data */\n\n (VOID) DeregisterEventSource (hEventSource);\n }\n#endif\n\n /* Write the error to stderr too */\n fprintf (stderr, errmsg);\n\n#ifdef DEBUG\n return EXCEPTION_CONTINUE_SEARCH;\n#else\n exit (255);\n return (255); /* not reached */\n#endif\n}\n\n/*\n * On WIN32 systems we don't have the luxury of a /bin directory that\n * is mapped globally to every drive mounted to the system. Since make could\n * be invoked from any drive, and we don't want to propagate /bin/sh\n * to every single drive. Allow ourselves a chance to search for\n * a value for default shell here (if the default path does not exist).\n */\n\nint\nfind_and_set_default_shell (const char *token)\n{\n int sh_found = 0;\n char *atoken = 0;\n const char *search_token;\n const char *tokend;\n PATH_VAR(sh_path);\n extern const char *default_shell;\n\n if (!token)\n search_token = default_shell;\n else\n search_token = atoken = xstrdup (token);\n\n /* If the user explicitly requests the DOS cmd shell, obey that request.\n However, make sure that's what they really want by requiring the value\n of SHELL either equal, or have a final path element of, \"cmd\" or\n \"cmd.exe\" case-insensitive. */\n tokend = search_token + strlen (search_token) - 3;\n if (((tokend == search_token\n || (tokend > search_token\n && (tokend[-1] == '/' || tokend[-1] == '\\\\')))\n && !strcasecmp (tokend, \"cmd\"))\n || ((tokend - 4 == search_token\n || (tokend - 4 > search_token\n && (tokend[-5] == '/' || tokend[-5] == '\\\\')))\n && !strcasecmp (tokend - 4, \"cmd.exe\")))\n {\n batch_mode_shell = 1;\n unixy_shell = 0;\n sprintf (sh_path, \"%s\", search_token);\n default_shell = xstrdup (w32ify (sh_path, 0));\n DB (DB_VERBOSE, (_(\"find_and_set_shell() setting default_shell = %s\\n\"),\n default_shell));\n sh_found = 1;\n }\n else if (!no_default_sh_exe\n && (token == NULL || !strcmp (search_token, default_shell)))\n {\n /* no new information, path already set or known */\n sh_found = 1;\n }\n else if (_access (search_token, 0) == 0)\n {\n /* search token path was found */\n sprintf (sh_path, \"%s\", search_token);\n default_shell = xstrdup (w32ify (sh_path, 0));\n DB (DB_VERBOSE, (_(\"find_and_set_shell() setting default_shell = %s\\n\"),\n default_shell));\n sh_found = 1;\n }\n else\n {\n char *p;\n struct variable *v = lookup_variable (STRING_SIZE_TUPLE (\"PATH\"));\n\n /* Search Path for shell */\n if (v && v->value)\n {\n char *ep;\n\n p = v->value;\n ep = strchr (p, PATH_SEPARATOR_CHAR);\n\n while (ep && *ep)\n {\n *ep = '\\0';\n\n sprintf (sh_path, \"%s/%s\", p, search_token);\n if (_access (sh_path, 0) == 0)\n {\n default_shell = xstrdup (w32ify (sh_path, 0));\n sh_found = 1;\n *ep = PATH_SEPARATOR_CHAR;\n\n /* terminate loop */\n p += strlen (p);\n }\n else\n {\n *ep = PATH_SEPARATOR_CHAR;\n p = ++ep;\n }\n\n ep = strchr (p, PATH_SEPARATOR_CHAR);\n }\n\n /* be sure to check last element of Path */\n if (p && *p)\n {\n sprintf (sh_path, \"%s/%s\", p, search_token);\n if (_access (sh_path, 0) == 0)\n {\n default_shell = xstrdup (w32ify (sh_path, 0));\n sh_found = 1;\n }\n }\n\n if (sh_found)\n DB (DB_VERBOSE,\n (_(\"find_and_set_shell() path search set default_shell = %s\\n\"),\n default_shell));\n }\n }\n\n /* naive test */\n if (!unixy_shell && sh_found\n && (strstr (default_shell, \"sh\") || strstr (default_shell, \"SH\")))\n {\n unixy_shell = 1;\n batch_mode_shell = 0;\n }\n\n#ifdef BATCH_MODE_ONLY_SHELL\n batch_mode_shell = 1;\n#endif\n\n free (atoken);\n\n return (sh_found);\n}\n#endif /* WINDOWS32 */\n\n#ifdef __MSDOS__\nstatic void\nmsdos_return_to_initial_directory (void)\n{\n if (directory_before_chdir)\n chdir (directory_before_chdir);\n}\n#endif /* __MSDOS__ */\n\nstatic void\nreset_jobserver (void)\n{\n jobserver_clear ();\n free (jobserver_auth);\n jobserver_auth = NULL;\n}\n\nint\nmain (int argc, const char **argv, char **envp)\n{\n static char *stdin_nm = 0;\n int makefile_status = MAKE_SUCCESS;\n PATH_VAR (current_directory);\n unsigned int restarts = 0;\n unsigned int syncing = 0;\n int argv_slots;\n#ifdef WINDOWS32\n const char *unix_path = NULL;\n const char *windows32_path = NULL;\n\n SetUnhandledExceptionFilter (handle_runtime_exceptions);\n\n /* start off assuming we have no shell */\n unixy_shell = 0;\n no_default_sh_exe = 1;\n#endif\n\n /* Useful for attaching debuggers, etc. */\n#ifdef SPIN\n SPIN (\"main-entry\");\n#endif\n\n argv0 = strdup(argv[0]);\n output_init (&make_sync);\n\n initialize_stopchar_map();\n\n#ifdef SET_STACK_SIZE\n /* Get rid of any avoidable limit on stack size. */\n {\n struct rlimit rlim;\n\n /* Set the stack limit huge so that alloca does not fail. */\n if (getrlimit (RLIMIT_STACK, &rlim) == 0\n && rlim.rlim_cur > 0 && rlim.rlim_cur < rlim.rlim_max)\n {\n stack_limit = rlim;\n rlim.rlim_cur = rlim.rlim_max;\n setrlimit (RLIMIT_STACK, &rlim);\n }\n else\n stack_limit.rlim_cur = 0;\n }\n#endif\n\n global_argv = argv;\n /* Needed for OS/2 */\n initialize_main (&argc, &argv);\n\n#ifdef MAKE_MAINTAINER_MODE\n /* In maintainer mode we always enable verification. */\n verify_flag = 1;\n#endif\n\n#if defined (__MSDOS__) && !defined (_POSIX_SOURCE)\n /* Request the most powerful version of 'system', to\n make up for the dumb default shell. */\n __system_flags = (__system_redirect\n | __system_use_shell\n | __system_allow_multiple_cmds\n | __system_allow_long_cmds\n | __system_handle_null_commands\n | __system_emulate_chdir);\n\n#endif\n\n /* Set up gettext/internationalization support. */\n setlocale (LC_ALL, \"\");\n /* The cast to void shuts up compiler warnings on systems that\n disable NLS. */\n (void)bindtextdomain (PACKAGE, LOCALEDIR);\n (void)textdomain (PACKAGE);\n\n#ifdef POSIX\n sigemptyset (&fatal_signal_set);\n#define ADD_SIG(sig) sigaddset (&fatal_signal_set, sig)\n#else\n#ifdef HAVE_SIGSETMASK\n fatal_signal_mask = 0;\n#define ADD_SIG(sig) fatal_signal_mask |= sigmask (sig)\n#else\n#define ADD_SIG(sig) (void)sig\n#endif\n#endif\n\n#define FATAL_SIG(sig) \\\n if (bsd_signal (sig, fatal_error_signal) == SIG_IGN) \\\n bsd_signal (sig, SIG_IGN); \\\n else \\\n ADD_SIG (sig);\n\n#ifdef SIGHUP\n FATAL_SIG (SIGHUP);\n#endif\n#ifdef SIGQUIT\n FATAL_SIG (SIGQUIT);\n#endif\n FATAL_SIG (SIGINT);\n FATAL_SIG (SIGTERM);\n\n#ifdef __MSDOS__\n /* Windows 9X delivers FP exceptions in child programs to their\n parent! We don't want Make to die when a child divides by zero,\n so we work around that lossage by catching SIGFPE. */\n FATAL_SIG (SIGFPE);\n#endif\n\n#ifdef SIGDANGER\n FATAL_SIG (SIGDANGER);\n#endif\n#ifdef SIGXCPU\n FATAL_SIG (SIGXCPU);\n#endif\n#ifdef SIGXFSZ\n FATAL_SIG (SIGXFSZ);\n#endif\n\n#undef FATAL_SIG\n\n /* Do not ignore the child-death signal. This must be done before\n any children could possibly be created; otherwise, the wait\n functions won't work on systems with the SVR4 ECHILD brain\n damage, if our invoker is ignoring this signal. */\n\n#ifdef HAVE_WAIT_NOHANG\n# if defined SIGCHLD\n (void) bsd_signal (SIGCHLD, SIG_DFL);\n# endif\n# if defined SIGCLD && SIGCLD != SIGCHLD\n (void) bsd_signal (SIGCLD, SIG_DFL);\n# endif\n#endif\n\n output_init (NULL);\n\n /* Figure out where this program lives. */\n\n if (argv[0] == 0)\n argv[0] = (char *)\"\";\n if (argv[0][0] == '\\0')\n program = \"make\";\n else\n {\n#if defined(HAVE_DOS_PATHS)\n const char* start = argv[0];\n\n /* Skip an initial drive specifier if present. */\n if (isalpha ((unsigned char)start[0]) && start[1] == ':')\n start += 2;\n\n if (start[0] == '\\0')\n program = \"make\";\n else\n {\n program = start + strlen (start);\n while (program > start && ! STOP_SET (program[-1], MAP_DIRSEP))\n --program;\n\n /* Remove the .exe extension if present. */\n {\n size_t len = strlen (program);\n if (len > 4 && streq (&program[len - 4], \".exe\"))\n program = xstrndup (program, len - 4);\n }\n }\n#else\n program = strrchr (argv[0], '/');\n if (program == 0)\n program = argv[0];\n else\n ++program;\n#endif\n }\n\n /* Set up to access user data (files). */\n user_access ();\n\n initialize_global_hash_tables ();\n\n /* Figure out where we are. */\n\n#ifdef WINDOWS32\n if (getcwd_fs (current_directory, GET_PATH_MAX) == 0)\n#else\n if (getcwd (current_directory, GET_PATH_MAX) == 0)\n#endif\n {\n#ifdef HAVE_GETCWD\n perror_with_name (\"getcwd\", \"\");\n#else\n OS (error, NILF, \"getwd: %s\", current_directory);\n#endif\n current_directory[0] = '\\0';\n directory_before_chdir = 0;\n }\n else\n directory_before_chdir = xstrdup (current_directory);\n\n#ifdef __MSDOS__\n /* Make sure we will return to the initial directory, come what may. */\n atexit (msdos_return_to_initial_directory);\n#endif\n\n /* Initialize the special variables. */\n define_variable_cname (\".VARIABLES\", \"\", o_default, 0)->special = 1;\n /* define_variable_cname (\".TARGETS\", \"\", o_default, 0)->special = 1; */\n define_variable_cname (\".RECIPEPREFIX\", \"\", o_default, 0)->special = 1;\n define_variable_cname (\".SHELLFLAGS\", \"-c\", o_default, 0);\n define_variable_cname (\".LOADED\", \"\", o_default, 0);\n\n /* Set up .FEATURES\n Use a separate variable because define_variable_cname() is a macro and\n some compilers (MSVC) don't like conditionals in macros. */\n {\n const char *features = \"target-specific order-only second-expansion\"\n \" else-if shortest-stem undefine oneshell nocomment\"\n \" grouped-target extra-prereqs\"\n#ifndef NO_ARCHIVES\n \" archives\"\n#endif\n#ifdef MAKE_JOBSERVER\n \" jobserver\"\n#endif\n#ifndef NO_OUTPUT_SYNC\n \" output-sync\"\n#endif\n#ifdef MAKE_SYMLINKS\n \" check-symlink\"\n#endif\n#ifdef HAVE_GUILE\n \" guile\"\n#endif\n#ifdef MAKE_LOAD\n \" load\"\n#endif\n#ifdef MAKE_MAINTAINER_MODE\n \" maintainer\"\n#endif\n ;\n\n define_variable_cname (\".FEATURES\", features, o_default, 0);\n }\n\n /* Configure GNU Guile support */\n guile_gmake_setup (NILF);\n\n /* Read in variables from the environment. It is important that this be\n done before $(MAKE) is figured out so its definitions will not be\n from the environment. */\n\n {\n unsigned int i;\n\n for (i = 0; envp[i] != 0; ++i)\n {\n struct variable *v;\n const char *ep = envp[i];\n /* By default, export all variables culled from the environment. */\n enum variable_export export = v_export;\n size_t len;\n\n while (! STOP_SET (*ep, MAP_EQUALS))\n ++ep;\n\n /* If there's no equals sign it's a malformed environment. Ignore. */\n if (*ep == '\\0')\n continue;\n\n /* Length of the variable name, and skip the '='. */\n len = ep++ - envp[i];\n\n /* If this is MAKE_RESTARTS, check to see if the \"already printed\n the enter statement\" flag is set. */\n if (len == 13 && strneq (envp[i], \"MAKE_RESTARTS\", 13))\n {\n if (*ep == '-')\n {\n OUTPUT_TRACED ();\n ++ep;\n }\n restarts = (unsigned int) atoi (ep);\n export = v_noexport;\n }\n\n v = define_variable (envp[i], len, ep, o_env, 1);\n\n /* POSIX says the value of SHELL set in the makefile won't change the\n value of SHELL given to subprocesses. */\n if (streq (v->name, \"SHELL\"))\n {\n export = v_noexport;\n shell_var.name = xstrdup (\"SHELL\");\n shell_var.length = 5;\n shell_var.value = xstrdup (ep);\n }\n\n v->export = export;\n }\n }\n\n /* Decode the switches. */\n decode_env_switches (STRING_SIZE_TUPLE (\"GNUMAKEFLAGS\"));\n\n /* Clear GNUMAKEFLAGS to avoid duplication. */\n define_variable_cname (\"GNUMAKEFLAGS\", \"\", o_env, 0);\n\n decode_env_switches (STRING_SIZE_TUPLE (\"MAKEFLAGS\"));\n\n#if 0\n /* People write things like:\n MFLAGS=\"CC=gcc -pipe\" \"CFLAGS=-g\"\n and we set the -p, -i and -e switches. Doesn't seem quite right. */\n decode_env_switches (STRING_SIZE_TUPLE (\"MFLAGS\"));\n#endif\n\n /* In output sync mode we need to sync any output generated by reading the\n makefiles, such as in $(info ...) or stderr from $(shell ...) etc. */\n\n syncing = make_sync.syncout = (output_sync == OUTPUT_SYNC_LINE\n || output_sync == OUTPUT_SYNC_TARGET);\n OUTPUT_SET (&make_sync);\n\n /* Parse the command line options. Remember the job slots set this way. */\n {\n int env_slots = arg_job_slots;\n arg_job_slots = INVALID_JOB_SLOTS;\n\n decode_switches (argc, (const char **)argv, 0);\n argv_slots = arg_job_slots;\n\n if (arg_job_slots == INVALID_JOB_SLOTS)\n arg_job_slots = env_slots;\n }\n\n /* Set a variable specifying whether stdout/stdin is hooked to a TTY. */\n#ifdef HAVE_ISATTY\n if (isatty (fileno (stdout)))\n if (! lookup_variable (STRING_SIZE_TUPLE (\"MAKE_TERMOUT\")))\n {\n const char *tty = TTYNAME (fileno (stdout));\n define_variable_cname (\"MAKE_TERMOUT\", tty ? tty : DEFAULT_TTYNAME,\n o_default, 0)->export = v_export;\n }\n if (isatty (fileno (stderr)))\n if (! lookup_variable (STRING_SIZE_TUPLE (\"MAKE_TERMERR\")))\n {\n const char *tty = TTYNAME (fileno (stderr));\n define_variable_cname (\"MAKE_TERMERR\", tty ? tty : DEFAULT_TTYNAME,\n o_default, 0)->export = v_export;\n }\n#endif\n\n /* Reset in case the switches changed our minds. */\n syncing = (output_sync == OUTPUT_SYNC_LINE\n || output_sync == OUTPUT_SYNC_TARGET);\n\n if (make_sync.syncout && ! syncing)\n output_close (&make_sync);\n\n make_sync.syncout = syncing;\n OUTPUT_SET (&make_sync);\n\n /* Figure out the level of recursion. */\n {\n struct variable *v = lookup_variable (STRING_SIZE_TUPLE (MAKELEVEL_NAME));\n if (v && v->value[0] != '\\0' && v->value[0] != '-')\n makelevel = (unsigned int) atoi (v->value);\n else\n makelevel = 0;\n\n v = lookup_variable (STRING_SIZE_TUPLE (MAKEPARENT_PID_NAME));\n if (v && v->value[0] != '\\0' && v->value[0] != '-')\n makeparent_pid = (pid_t) atoi (v->value);\n else\n makeparent_pid = (pid_t)0;\n\n v = lookup_variable (STRING_SIZE_TUPLE (MAKEPARENT_TARGET_NAME));\n if (v && v->value[0] != '\\0' && v->value[0] != '-') {\n makeparent_target = v->value;\n } else {\n makeparent_target = NULL;\n }\n }\n\n decode_trace_flags (tracing_opts);\n decode_verbosity_flags (verbosity_opts);\n\n /* FIXME: put into a subroutine like decode_trace_flags */\n if (post_mortem_flag) {\n debugger_on_error |= (DEBUGGER_ON_ERROR|DEBUGGER_ON_FATAL);\n debugger_enabled = 1;\n } else if (debugger_flag) {\n b_debugger_preread = false;\n job_slots = 1;\n i_debugger_stepping = 1;\n i_debugger_nexting = 0;\n debugger_enabled = 1;\n /* For now we'll do basic debugging. Later, \"stepping'\n will stop here while next won't - either way no printing.\n */\n db_level |= DB_BASIC | DB_CALL | DB_SHELL | DB_UPDATE_GOAL\n | DB_MAKEFILES;\n }\n /* debugging sets some things */\n if (debugger_opts) {\n const char **p;\n b_show_version = true;\n for (p = debugger_opts->list; *p != 0; ++p)\n {\n if (0 == strcmp(*p, \"preread\")) {\n b_debugger_preread = true;\n db_level |= DB_READ_MAKEFILES;\n }\n\n if (0 == strcmp(*p, \"goal\")) {\n b_debugger_goal = true;\n db_level |= DB_UPDATE_GOAL;\n }\n\n if ( 0 == strcmp(*p, \"full\") || b_debugger_preread || b_debugger_goal\n || 0 == strcmp(*p, \"preaction\") ) {\n job_slots = 1;\n i_debugger_stepping = 1;\n i_debugger_nexting = 0;\n debugger_enabled = 1;\n /* For now we'll do basic debugging. Later, \"stepping'\n will stop here while next won't - either way no printing.\n */\n db_level |= DB_BASIC | DB_CALL | DB_UPDATE_GOAL\n | b_debugger_goal ? 0 : DB_SHELL\n | DB_MAKEFILES;\n }\n if ( 0 == strcmp(*p, \"full\") || b_debugger_goal\n || 0 == strcmp(*p, \"error\") ) {\n debugger_on_error |= (DEBUGGER_ON_ERROR|DEBUGGER_ON_FATAL);\n } else if ( 0 == strcmp(*p, \"fatal\") ) {\n debugger_on_error |= DEBUGGER_ON_FATAL;\n }\n }\n#ifndef HAVE_LIBREADLINE\n O (error, NILF,\n \"warning: you specified a debugger option, but you don't have readline support\");\n O (error, NILF,\n \"debugger support compiled in. Debugger options will be ignored.\");\n#endif\n }\n\n /* Set always_make_flag if -B was given and we've not restarted already. */\n always_make_flag = always_make_set && (restarts == 0);\n\n /* Print version information, and exit. */\n if (print_version_flag)\n {\n print_version ();\n die (MAKE_SUCCESS);\n }\n\n if (ISDB (DB_BASIC) && makelevel == 0 && b_show_version)\n print_version ();\n\n /* Set the \"MAKE_COMMAND\" variable to the name we were invoked with.\n (If it is a relative pathname with a slash, prepend our directory name\n so the result will run the same program regardless of the current dir.\n If it is a name with no slash, we can only hope that PATH did not\n find it in the current directory.) */\n if (current_directory[0] != '\\0'\n && argv[0] != 0 && argv[0][0] != '/' && strchr (argv[0], '/') != 0\n )\n argv[0] = xstrdup (concat (3, current_directory, \"/\", argv[0]));\n\n /* We may move, but until we do, here we are. */\n starting_directory = current_directory;\n\n /* Update profile global options from cli options */\n decode_profile_options();\n if (profile_flag) profile_init(PACKAGE_TARNAME \" \" PACKAGE_VERSION, argv, arg_job_slots);\n\n /* Validate the arg_job_slots configuration before we define MAKEFLAGS so\n users get an accurate value in their makefiles.\n At this point arg_job_slots is the argv setting, if there is one, else\n the MAKEFLAGS env setting, if there is one. */\n\n if (jobserver_auth)\n {\n /* We're a child in an existing jobserver group. */\n if (argv_slots == INVALID_JOB_SLOTS)\n {\n /* There's no -j option on the command line: check authorization. */\n if (jobserver_parse_auth (jobserver_auth))\n {\n /* Success! Use the jobserver. */\n goto job_setup_complete;\n }\n\n /* Oops: we have jobserver-auth but it's invalid :(. */\n O (error, NILF, _(\"warning: jobserver unavailable: using -j1. Add '+' to parent make rule.\"));\n arg_job_slots = 1;\n }\n\n /* The user provided a -j setting on the command line so use it: we're\n the master make of a new jobserver group. */\n else if (!restarts)\n ON (error, NILF,\n _(\"warning: -j%d forced in submake: resetting jobserver mode.\"),\n argv_slots);\n\n /* We can't use our parent's jobserver, so reset. */\n reset_jobserver ();\n }\n\n job_setup_complete:\n\n /* The extra indirection through $(MAKE_COMMAND) is done\n for hysterical raisins. */\n\n define_variable_cname (\"MAKE_COMMAND\", argv[0], o_default, 0);\n define_variable_cname (\"MAKE\", \"$(MAKE_COMMAND)\", o_default, 1);\n\n if (command_variables != 0)\n {\n struct command_variable *cv;\n struct variable *v;\n size_t len = 0;\n char *value, *p;\n\n /* Figure out how much space will be taken up by the command-line\n variable definitions. */\n for (cv = command_variables; cv != 0; cv = cv->next)\n {\n v = cv->variable;\n len += 2 * strlen (v->name);\n if (! v->recursive)\n ++len;\n ++len;\n len += 2 * strlen (v->value);\n ++len;\n }\n\n /* Now allocate a buffer big enough and fill it. */\n p = value = alloca (len);\n for (cv = command_variables; cv != 0; cv = cv->next)\n {\n v = cv->variable;\n p = quote_for_env (p, v->name);\n if (! v->recursive)\n *p++ = ':';\n *p++ = '=';\n p = quote_for_env (p, v->value);\n *p++ = ' ';\n }\n p[-1] = '\\0'; /* Kill the final space and terminate. */\n\n /* Define an unchangeable variable with a name that no POSIX.2\n makefile could validly use for its own variable. */\n define_variable_cname (\"-*-command-variables-*-\", value, o_automatic, 0);\n\n /* Define the variable; this will not override any user definition.\n Normally a reference to this variable is written into the value of\n MAKEFLAGS, allowing the user to override this value to affect the\n exported value of MAKEFLAGS. In POSIX-pedantic mode, we cannot\n allow the user's setting of MAKEOVERRIDES to affect MAKEFLAGS, so\n a reference to this hidden variable is written instead. */\n define_variable_cname (\"MAKEOVERRIDES\", \"${-*-command-variables-*-}\",\n o_env, 1);\n }\n\n /* If there were -C flags, move ourselves about. */\n if (directories != 0)\n {\n unsigned int i;\n for (i = 0; directories->list[i] != 0; ++i)\n {\n const char *dir = directories->list[i];\n if (chdir (dir) < 0)\n pfatal_with_name (dir);\n }\n }\n\n /* Except under -s, always do -w in sub-makes and under -C. */\n if (!silent_flag && (directories != 0 || makelevel > 0))\n print_directory = 1;\n\n /* Let the user disable that with --no-print-directory. */\n if (inhibit_print_directory)\n print_directory = 0;\n\n /* If -R was given, set -r too (doesn't make sense otherwise!) */\n if (no_builtin_variables_flag)\n no_builtin_rules_flag = 1;\n\n /* Construct the list of include directories to search. */\n\n construct_include_path (include_directories == 0\n ? 0 : include_directories->list);\n\n /* If we chdir'ed, figure out where we are now. */\n if (directories)\n {\n#ifdef WINDOWS32\n if (getcwd_fs (current_directory, GET_PATH_MAX) == 0)\n#else\n if (getcwd (current_directory, GET_PATH_MAX) == 0)\n#endif\n {\n#ifdef HAVE_GETCWD\n perror_with_name (\"getcwd\", \"\");\n#else\n OS (error, NILF, \"getwd: %s\", current_directory);\n#endif\n starting_directory = 0;\n }\n else\n starting_directory = current_directory;\n }\n\n define_variable_cname (\"CURDIR\", current_directory, o_file, 0);\n\n /* Read any stdin makefiles into temporary files. */\n\n if (makefiles != 0)\n {\n unsigned int i;\n for (i = 0; i < makefiles->idx; ++i)\n if (makefiles->list[i][0] == '-' && makefiles->list[i][1] == '\\0')\n {\n /* This makefile is standard input. Since we may re-exec\n and thus re-read the makefiles, we read standard input\n into a temporary file and read from that. */\n FILE *outfile;\n char *template;\n const char *tmpdir;\n\n if (stdin_nm)\n O (fatal, NILF,\n _(\"Makefile from standard input specified twice.\"));\n\n#ifdef P_tmpdir\n# define DEFAULT_TMPDIR P_tmpdir\n#else\n# define DEFAULT_TMPDIR \"/tmp\"\n#endif\n#define DEFAULT_TMPFILE \"GmXXXXXX\"\n\n if (((tmpdir = getenv (\"TMPDIR\")) == NULL || *tmpdir == '\\0')\n )\n tmpdir = DEFAULT_TMPDIR;\n\n template = alloca (strlen (tmpdir) + CSTRLEN (DEFAULT_TMPFILE) + 2);\n strcpy (template, tmpdir);\n\n#ifdef HAVE_DOS_PATHS\n if (strchr (\"/\\\\\", template[strlen (template) - 1]) == NULL)\n strcat (template, \"/\");\n#else\n# ifndef VMS\n if (template[strlen (template) - 1] != '/')\n strcat (template, \"/\");\n# endif /* !VMS */\n#endif /* !HAVE_DOS_PATHS */\n\n strcat (template, DEFAULT_TMPFILE);\n outfile = get_tmpfile (&stdin_nm, template);\n if (outfile == 0)\n pfatal_with_name (_(\"fopen (temporary file)\"));\n while (!feof (stdin) && ! ferror (stdin))\n {\n char buf[2048];\n size_t n = fread (buf, 1, sizeof (buf), stdin);\n if (n > 0 && fwrite (buf, 1, n, outfile) != n)\n pfatal_with_name (_(\"fwrite (temporary file)\"));\n }\n fclose (outfile);\n\n /* Replace the name that read_all_makefiles will\n see with the name of the temporary file. */\n makefiles->list[i] = strcache_add (stdin_nm);\n\n /* Make sure the temporary file will not be remade. */\n {\n struct file *f = enter_file (strcache_add (stdin_nm));\n f->updated = 1;\n f->update_status = us_success;\n f->command_state = cs_finished;\n /* Can't be intermediate, or it'll be removed too early for\n make re-exec. */\n f->intermediate = 0;\n f->dontcare = 0;\n }\n }\n }\n\n#ifndef __EMX__ /* Don't use a SIGCHLD handler for OS/2 */\n#if !defined(HAVE_WAIT_NOHANG) || defined(MAKE_JOBSERVER)\n /* Set up to handle children dying. This must be done before\n reading in the makefiles so that 'shell' function calls will work.\n\n If we don't have a hanging wait we have to fall back to old, broken\n functionality here and rely on the signal handler and counting\n children.\n\n If we're using the jobs pipe we need a signal handler so that SIGCHLD is\n not ignored; we need it to interrupt the read(2) of the jobserver pipe if\n we're waiting for a token.\n\n If none of these are true, we don't need a signal handler at all. */\n {\n# if defined SIGCHLD\n bsd_signal (SIGCHLD, child_handler);\n# endif\n# if defined SIGCLD && SIGCLD != SIGCHLD\n bsd_signal (SIGCLD, child_handler);\n# endif\n }\n\n#ifdef HAVE_PSELECT\n /* If we have pselect() then we need to block SIGCHLD so it's deferred. */\n {\n sigset_t block;\n sigemptyset (&block);\n sigaddset (&block, SIGCHLD);\n if (sigprocmask (SIG_SETMASK, &block, NULL) < 0)\n pfatal_with_name (\"sigprocmask(SIG_SETMASK, SIGCHLD)\");\n }\n#endif\n\n#endif\n#endif\n\n /* Let the user send us SIGUSR1 to toggle the -d flag during the run. */\n#ifdef SIGUSR1\n bsd_signal (SIGUSR1, debug_signal_handler);\n#endif\n\n /* Define the initial list of suffixes for old-style rules. */\n set_default_suffixes ();\n\n /* Define the file rules for the built-in suffix rules. These will later\n be converted into pattern rules. We used to do this in\n install_default_implicit_rules, but since that happens after reading\n makefiles, it results in the built-in pattern rules taking precedence\n over makefile-specified suffix rules, which is wrong. */\n install_default_suffix_rules ();\n\n /* Define some internal and special variables. */\n define_automatic_variables ();\n\n /* Set up the MAKEFLAGS and MFLAGS variables for makefiles to see.\n Initialize it to be exported but allow the makefile to reset it. */\n define_makeflags (0, 0)->export = v_export;\n\n /* Define the default variables. */\n define_default_variables ();\n\n default_file = enter_file (strcache_add (\".DEFAULT\"));\n\n default_goal_var = define_variable_cname (\".DEFAULT_GOAL\", \"\", o_file, 0);\n\n /* Evaluate all strings provided with --eval.\n Also set up the $(-*-eval-flags-*-) variable. */\n\n if (eval_strings)\n {\n char *p, *value;\n unsigned int i;\n size_t len = (CSTRLEN (\"--eval=\") + 1) * eval_strings->idx;\n\n for (i = 0; i < eval_strings->idx; ++i)\n {\n p = xstrdup (eval_strings->list[i]);\n len += 2 * strlen (p);\n eval_buffer (p, NULL);\n free (p);\n }\n\n p = value = alloca (len);\n for (i = 0; i < eval_strings->idx; ++i)\n {\n strcpy (p, \"--eval=\");\n p += CSTRLEN (\"--eval=\");\n p = quote_for_env (p, eval_strings->list[i]);\n *(p++) = ' ';\n }\n p[-1] = '\\0';\n\n define_variable_cname (\"-*-eval-flags-*-\", value, o_automatic, 0);\n }\n\n /* Read all the makefiles. */\n\n read_makefiles = read_all_makefiles (makefiles == 0 ? 0 : makefiles->list);\n\n#ifdef WINDOWS32\n /* look one last time after reading all Makefiles */\n if (no_default_sh_exe)\n no_default_sh_exe = !find_and_set_default_shell (NULL);\n#endif /* WINDOWS32 */\n\n#if defined (__MSDOS__) || defined (__EMX__) || defined (VMS)\n /* We need to know what kind of shell we will be using. */\n {\n extern int _is_unixy_shell (const char *_path);\n struct variable *shv = lookup_variable (STRING_SIZE_TUPLE (\"SHELL\"));\n extern int unixy_shell;\n extern const char *default_shell;\n\n if (shv && *shv->value)\n {\n char *shell_path = recursively_expand (shv);\n\n if (shell_path && _is_unixy_shell (shell_path))\n unixy_shell = 1;\n else\n unixy_shell = 0;\n if (shell_path)\n default_shell = shell_path;\n }\n }\n#endif /* __MSDOS__ || __EMX__ */\n\n {\n int old_builtin_rules_flag = no_builtin_rules_flag;\n int old_builtin_variables_flag = no_builtin_variables_flag;\n int old_arg_job_slots = arg_job_slots;\n\n arg_job_slots = INVALID_JOB_SLOTS;\n\n /* Decode switches again, for variables set by the makefile. */\n decode_env_switches (STRING_SIZE_TUPLE (\"GNUMAKEFLAGS\"));\n\n /* Clear GNUMAKEFLAGS to avoid duplication. */\n define_variable_cname (\"GNUMAKEFLAGS\", \"\", o_override, 0);\n\n decode_env_switches (STRING_SIZE_TUPLE (\"MAKEFLAGS\"));\n#if 0\n decode_env_switches (STRING_SIZE_TUPLE (\"MFLAGS\"));\n#endif\n\n /* If -j is not set in the makefile, or it was set on the command line,\n reset to use the previous value. */\n if (arg_job_slots == INVALID_JOB_SLOTS || argv_slots != INVALID_JOB_SLOTS)\n arg_job_slots = old_arg_job_slots;\n\n else if (jobserver_auth)\n {\n /* Makefile MAKEFLAGS set -j, but we already have a jobserver.\n Make us the master of a new jobserver group. */\n if (!restarts)\n ON (error, NILF,\n _(\"warning: -j%d forced in makefile: resetting jobserver mode.\"),\n arg_job_slots);\n\n /* We can't use our parent's jobserver, so reset. */\n reset_jobserver ();\n }\n\n /* Reset in case the switches changed our mind. */\n syncing = (output_sync == OUTPUT_SYNC_LINE\n || output_sync == OUTPUT_SYNC_TARGET);\n\n if (make_sync.syncout && ! syncing)\n output_close (&make_sync);\n\n make_sync.syncout = syncing;\n OUTPUT_SET (&make_sync);\n\n /* If we've disabled builtin rules, get rid of them. */\n if (no_builtin_rules_flag && ! old_builtin_rules_flag)\n {\n if (suffix_file->builtin)\n {\n free_dep_chain (suffix_file->deps);\n suffix_file->deps = 0;\n }\n define_variable_cname (\"SUFFIXES\", \"\", o_default, 0);\n }\n\n /* If we've disabled builtin variables, get rid of them. */\n if (no_builtin_variables_flag && ! old_builtin_variables_flag)\n undefine_default_variables ();\n }\n\n /* Final jobserver configuration.\n\n If we have jobserver_auth then we are a client in an existing jobserver\n group, that's already been verified OK above. If we don't have\n jobserver_auth and jobserver is enabled, then start a new jobserver.\n\n arg_job_slots = INVALID_JOB_SLOTS if we don't want -j in MAKEFLAGS\n\n arg_job_slots = # of jobs of parallelism\n\n job_slots = 0 for no limits on jobs, or when limiting via jobserver.\n\n job_slots = 1 for standard non-parallel mode.\n\n job_slots >1 for old-style parallelism without jobservers. */\n\n if (jobserver_auth)\n job_slots = 0;\n else if (arg_job_slots == INVALID_JOB_SLOTS)\n job_slots = 1;\n else\n job_slots = arg_job_slots;\n\n /* If we have >1 slot at this point, then we're a top-level make.\n Set up the jobserver.\n\n Every make assumes that it always has one job it can run. For the\n submakes it's the token they were given by their parent. For the top\n make, we just subtract one from the number the user wants. */\n\n if (job_slots > 1 && jobserver_setup (job_slots - 1))\n {\n /* Fill in the jobserver_auth for our children. */\n jobserver_auth = jobserver_get_auth ();\n\n if (jobserver_auth)\n {\n /* We're using the jobserver so set job_slots to 0. */\n master_job_slots = job_slots;\n job_slots = 0;\n }\n }\n\n /* If we're not using parallel jobs, then we don't need output sync.\n This is so people can enable output sync in GNUMAKEFLAGS or similar, but\n not have it take effect unless parallel builds are enabled. */\n if (syncing && job_slots == 1)\n {\n OUTPUT_UNSET ();\n output_close (&make_sync);\n syncing = 0;\n output_sync = OUTPUT_SYNC_NONE;\n }\n\n#ifndef MAKE_SYMLINKS\n if (check_symlink_flag)\n {\n O (error, NILF, _(\"Symbolic links not supported: disabling -L.\"));\n check_symlink_flag = 0;\n }\n#endif\n\n /* Set up MAKEFLAGS and MFLAGS again, so they will be right. */\n\n define_makeflags (1, 0);\n\n /* Make each 'struct goaldep' point at the 'struct file' for the file\n depended on. Also do magic for special targets. */\n\n snap_deps ();\n\n /* Convert old-style suffix rules to pattern rules. It is important to\n do this before installing the built-in pattern rules below, so that\n makefile-specified suffix rules take precedence over built-in pattern\n rules. */\n\n convert_to_pattern ();\n\n /* Install the default implicit pattern rules.\n This used to be done before reading the makefiles.\n But in that case, built-in pattern rules were in the chain\n before user-defined ones, so they matched first. */\n\n install_default_implicit_rules ();\n\n /* Compute implicit rule limits and do magic for pattern rules. */\n\n snap_implicit_rules ();\n\n /* Construct the listings of directories in VPATH lists. */\n\n build_vpath_lists ();\n\n /* Mark files given with -o flags as very old and as having been updated\n already, and files given with -W flags as brand new (time-stamp as far\n as possible into the future). If restarts is set we'll do -W later. */\n\n if (old_files != 0)\n {\n const char **p;\n for (p = old_files->list; *p != 0; ++p)\n {\n struct file *f = enter_file (*p);\n f->last_mtime = f->mtime_before_update = OLD_MTIME;\n f->updated = 1;\n f->update_status = us_success;\n f->command_state = cs_finished;\n }\n }\n\n if (!restarts && new_files != 0)\n {\n const char **p;\n for (p = new_files->list; *p != 0; ++p)\n {\n struct file *f = enter_file (*p);\n f->last_mtime = f->mtime_before_update = NEW_MTIME;\n }\n }\n\n /* Initialize the remote job module. */\n remote_setup ();\n\n /* Dump any output we've collected. */\n\n OUTPUT_UNSET ();\n output_close (&make_sync);\n\n if (read_makefiles)\n {\n /* Update any makefiles if necessary. */\n\n FILE_TIMESTAMP *makefile_mtimes;\n char **aargv = NULL;\n const char **nargv;\n int nargc;\n enum update_status status;\n\n DB (DB_BASIC, (_(\"Updating makefiles...\\n\")));\n\n {\n struct goaldep *d;\n unsigned int num_mkfiles = 0;\n for (d = read_makefiles; d != NULL; d = d->next)\n ++num_mkfiles;\n\n makefile_mtimes = alloca (num_mkfiles * sizeof (FILE_TIMESTAMP));\n }\n\n /* Remove any makefiles we don't want to try to update. Record the\n current modtimes of the others so we can compare them later. */\n {\n struct goaldep *d = read_makefiles;\n struct goaldep *last = NULL;\n unsigned int mm_idx = 0;\n\n while (d != 0)\n {\n struct file *f;\n\n for (f = d->file->double_colon; f != NULL; f = f->prev)\n if (f->deps == 0 && f->cmds != 0)\n break;\n\n if (f)\n {\n /* This makefile is a :: target with commands, but no\n dependencies. So, it will always be remade. This might\n well cause an infinite loop, so don't try to remake it.\n (This will only happen if your makefiles are written\n exceptionally stupidly; but if you work for Athena, that's\n how you write your makefiles.) */\n\n DB (DB_VERBOSE,\n (_(\"Makefile '%s' might loop; not remaking it.\\n\"),\n f->name));\n\n if (last)\n last->next = d->next;\n else\n read_makefiles = d->next;\n\n /* Free the storage. */\n free_goaldep (d);\n\n d = last ? last->next : read_makefiles;\n }\n else\n {\n makefile_mtimes[mm_idx++] = file_mtime_no_search (d->file);\n last = d;\n d = d->next;\n }\n }\n }\n\n /* Set up 'MAKEFLAGS' specially while remaking makefiles. */\n define_makeflags (1, 1);\n\n {\n int orig_db_level = db_level;\n\n if (! ISDB (DB_MAKEFILES))\n db_level = DB_NONE;\n\n rebuilding_makefiles = 1;\n\tstatus = update_goal_chain (read_makefiles);\n rebuilding_makefiles = 0;\n\n db_level = orig_db_level;\n }\n\n switch (status)\n {\n case us_question:\n /* The only way this can happen is if the user specified -q and asked\n for one of the makefiles to be remade as a target on the command\n line. Since we're not actually updating anything with -q we can\n treat this as \"did nothing\". */\n\n case us_none:\n /* Did nothing. */\n break;\n\n case us_failed:\n /* Failed to update. Figure out if we care. */\n {\n /* Nonzero if any makefile was successfully remade. */\n int any_remade = 0;\n /* Nonzero if any makefile we care about failed\n in updating or could not be found at all. */\n int any_failed = 0;\n unsigned int i;\n struct goaldep *d;\n\n for (i = 0, d = read_makefiles; d != 0; ++i, d = d->next)\n {\n if (d->file->updated)\n {\n /* This makefile was updated. */\n if (d->file->update_status == us_success)\n {\n /* It was successfully updated. */\n any_remade |= (file_mtime_no_search (d->file)\n != makefile_mtimes[i]);\n }\n else if (! (d->flags & RM_DONTCARE))\n {\n FILE_TIMESTAMP mtime;\n /* The update failed and this makefile was not\n from the MAKEFILES variable, so we care. */\n OS (error, NILF, _(\"Failed to remake makefile '%s'.\"),\n d->file->name);\n mtime = file_mtime_no_search (d->file);\n any_remade |= (mtime != NONEXISTENT_MTIME\n && mtime != makefile_mtimes[i]);\n makefile_status = MAKE_FAILURE;\n }\n }\n else\n /* This makefile was not found at all. */\n if (! (d->flags & RM_DONTCARE))\n {\n const char *dnm = dep_name (d);\n size_t l = strlen (dnm);\n\n /* This is a makefile we care about. See how much. */\n if (d->flags & RM_INCLUDED)\n /* An included makefile. We don't need to die, but we\n do want to complain. */\n error (NILF, l,\n _(\"Included makefile '%s' was not found.\"), dnm);\n else\n {\n /* A normal makefile. We must die later. */\n error (NILF, l,\n _(\"Makefile '%s' was not found\"), dnm);\n any_failed = 1;\n }\n }\n }\n\n if (any_remade)\n goto re_exec;\n if (any_failed)\n die (MAKE_FAILURE);\n break;\n }\n\n case us_success:\n re_exec:\n /* Updated successfully. Re-exec ourselves. */\n\n remove_intermediates (0);\n\n if (print_data_base_flag)\n print_data_base ();\n\n clean_jobserver (0);\n\n if (makefiles != 0)\n {\n /* These names might have changed. */\n int i, j = 0;\n for (i = 1; i < argc; ++i)\n if (strneq (argv[i], \"-f\", 2)) /* XXX */\n {\n if (argv[i][2] == '\\0')\n /* This cast is OK since we never modify argv. */\n argv[++i] = (char *) makefiles->list[j];\n else\n argv[i] = xstrdup (concat (2, \"-f\", makefiles->list[j]));\n ++j;\n }\n }\n\n /* Add -o option for the stdin temporary file, if necessary. */\n nargc = argc;\n if (stdin_nm)\n {\n void *m = xmalloc ((nargc + 2) * sizeof (char *));\n aargv = m;\n memcpy (aargv, argv, argc * sizeof (char *));\n aargv[nargc++] = xstrdup (concat (2, \"-o\", stdin_nm));\n aargv[nargc] = 0;\n nargv = m;\n }\n else\n nargv = (const char**)argv;\n\n if (directories != 0 && directories->idx > 0)\n {\n int bad = 1;\n if (directory_before_chdir != 0)\n {\n if (chdir (directory_before_chdir) < 0)\n perror_with_name (\"chdir\", \"\");\n else\n bad = 0;\n }\n if (bad)\n O (fatal, NILF,\n _(\"Couldn't change back to original directory.\"));\n }\n\n ++restarts;\n\n if (ISDB (DB_BASIC))\n {\n const char **p;\n printf (_(\"Re-executing[%u]:\"), restarts);\n for (p = nargv; *p != 0; ++p)\n printf (\" %s\", *p);\n putchar ('\\n');\n fflush (stdout);\n }\n\n {\n char **p;\n for (p = environ; *p != 0; ++p)\n {\n if (strneq (*p, MAKELEVEL_NAME \"=\", MAKELEVEL_LENGTH+1))\n {\n *p = alloca (40);\n sprintf (*p, \"%s=%u\", MAKELEVEL_NAME, makelevel);\n }\n else if (strneq (*p, \"MAKE_RESTARTS=\", CSTRLEN (\"MAKE_RESTARTS=\")))\n {\n *p = alloca (40);\n sprintf (*p, \"MAKE_RESTARTS=%s%u\",\n OUTPUT_IS_TRACED () ? \"-\" : \"\", restarts);\n restarts = 0;\n }\n }\n }\n\n /* If we didn't set the restarts variable yet, add it. */\n if (restarts)\n {\n char *b = alloca (40);\n sprintf (b, \"MAKE_RESTARTS=%s%u\",\n OUTPUT_IS_TRACED () ? \"-\" : \"\", restarts);\n putenv (b);\n }\n\n fflush (stdout);\n fflush (stderr);\n\n /* The exec'd \"child\" will be another make, of course. */\n jobserver_pre_child(1);\n\n#ifdef SET_STACK_SIZE\n /* Reset limits, if necessary. */\n if (stack_limit.rlim_cur)\n setrlimit (RLIMIT_STACK, &stack_limit);\n#endif\n exec_command ((char **)nargv, environ);\n\n /* We shouldn't get here but just in case. */\n jobserver_post_child(1);\n free (aargv);\n break;\n }\n }\n\n /* Set up 'MAKEFLAGS' again for the normal targets. */\n define_makeflags (1, 0);\n\n /* Set always_make_flag if -B was given. */\n always_make_flag = always_make_set;\n\n /* If restarts is set we haven't set up -W files yet, so do that now. */\n if (restarts && new_files != 0)\n {\n const char **p;\n for (p = new_files->list; *p != 0; ++p)\n {\n struct file *f = enter_file (*p);\n f->last_mtime = f->mtime_before_update = NEW_MTIME;\n }\n }\n\n /* If there is a temp file from reading a makefile from stdin, get rid of\n it now. */\n if (stdin_nm && unlink (stdin_nm) < 0 && errno != ENOENT)\n perror_with_name (_(\"unlink (temporary file): \"), stdin_nm);\n\n /* If there were no command-line goals, use the default. */\n if (goals == 0)\n {\n char *p;\n\n if (default_goal_var->recursive)\n p = variable_expand (default_goal_var->value);\n else\n {\n p = variable_buffer_output (variable_buffer, default_goal_var->value,\n strlen (default_goal_var->value));\n *p = '\\0';\n p = variable_buffer;\n }\n\n if (*p != '\\0')\n {\n struct file *f = lookup_file (p);\n\n /* If .DEFAULT_GOAL is a non-existent target, enter it into the\n table and let the standard logic sort it out. */\n if (f == 0)\n {\n struct nameseq *ns;\n\n ns = PARSE_SIMPLE_SEQ (&p, struct nameseq);\n if (ns)\n {\n /* .DEFAULT_GOAL should contain one target. */\n if (ns->next != 0)\n O (fatal, NILF,\n _(\".DEFAULT_GOAL contains more than one target\"));\n\n f = enter_file (strcache_add (ns->name));\n\n ns->name = 0; /* It was reused by enter_file(). */\n free_ns_chain (ns);\n }\n }\n\n if (f)\n {\n goals = alloc_goaldep ();\n goals->file = f;\n }\n }\n }\n else\n lastgoal->next = 0;\n\n\n if (!goals)\n {\n struct variable *v = lookup_variable (STRING_SIZE_TUPLE (\"MAKEFILE_LIST\"));\n if (v && v->value && v->value[0] != '\\0')\n O (fatal, NILF, _(\"No targets\"));\n\n O (fatal, NILF, _(\"No targets specified and no makefile found\"));\n }\n if (show_task_comments_flag) {\n dbg_cmd_info_targets(show_task_comments_flag\n\t\t\t ? INFO_TARGET_TASKS_WITH_COMMENTS\n\t\t\t : INFO_TARGET_TASKS);\n die(0);\n }\n if (show_tasks_flag) {\n dbg_cmd_info_tasks();\n die(0);\n } else if (show_targets_flag) {\n dbg_cmd_info_targets(INFO_TARGET_NAME);\n die(0);\n }\n\n /* Update the goals. */\n\n DB (DB_BASIC, (_(\"Updating goal targets...\\n\")));\n\n {\n switch (update_goal_chain (goals))\n {\n case us_none:\n /* Nothing happened. */\n /* FALLTHROUGH */\n case us_success:\n /* Keep the previous result. */\n break;\n case us_question:\n /* We are under -q and would run some commands. */\n makefile_status = MAKE_TROUBLE;\n break;\n case us_failed:\n /* Updating failed. POSIX.2 specifies exit status >1 for this; */\n makefile_status = MAKE_FAILURE;\n break;\n }\n\n /* If we detected some clock skew, generate one last warning */\n if (clock_skew_detected)\n O (error, NILF,\n _(\"warning: Clock skew detected. Your build may be incomplete.\"));\n\n /* Exit. */\n die (makefile_status);\n }\n\n /* NOTREACHED */\n exit (MAKE_SUCCESS);\n}\n\f\n/* Parsing of arguments, decoding of switches. */\n\nstatic char options[1 + sizeof (switches) / sizeof (switches[0]) * 3];\nstatic struct option long_options[(sizeof (switches) / sizeof (switches[0])) +\n (sizeof (long_option_aliases) /\n sizeof (long_option_aliases[0]))];\n\n/* Fill in the string and vector for getopt. */\nstatic void\ninit_switches (void)\n{\n char *p;\n unsigned int c;\n unsigned int i;\n\n if (options[0] != '\\0')\n /* Already done. */\n return;\n\n p = options;\n\n /* Return switch and non-switch args in order, regardless of\n POSIXLY_CORRECT. Non-switch args are returned as option 1. */\n *p++ = '-';\n\n for (i = 0; switches[i].c != '\\0'; ++i)\n {\n long_options[i].name = (char *) (switches[i].long_name == 0 ? \"\" :\n switches[i].long_name);\n long_options[i].flag = 0;\n long_options[i].val = switches[i].c;\n if (short_option (switches[i].c))\n *p++ = (char) switches[i].c;\n switch (switches[i].type)\n {\n case flag:\n case flag_off:\n case ignore:\n long_options[i].has_arg = no_argument;\n break;\n\n case string:\n case strlist:\n case filename:\n case positive_int:\n case floating:\n if (short_option (switches[i].c))\n *p++ = ':';\n if (switches[i].noarg_value != 0)\n {\n if (short_option (switches[i].c))\n *p++ = ':';\n long_options[i].has_arg = optional_argument;\n }\n else\n long_options[i].has_arg = required_argument;\n break;\n }\n }\n *p = '\\0';\n for (c = 0; c < (sizeof (long_option_aliases) /\n sizeof (long_option_aliases[0]));\n ++c)\n long_options[i++] = long_option_aliases[c];\n long_options[i].name = 0;\n}\n\n\n/* Non-option argument. It might be a variable definition. */\nstatic void\nhandle_non_switch_argument (const char *arg, int env)\n{\n struct variable *v;\n\n if (arg[0] == '-' && arg[1] == '\\0')\n /* Ignore plain '-' for compatibility. */\n return;\n\n v = try_variable_definition (0, arg, o_command, 0);\n if (v != 0)\n {\n /* It is indeed a variable definition. If we don't already have this\n one, record a pointer to the variable for later use in\n define_makeflags. */\n struct command_variable *cv;\n\n for (cv = command_variables; cv != 0; cv = cv->next)\n if (cv->variable == v)\n break;\n\n if (! cv)\n {\n cv = xmalloc (sizeof (*cv));\n cv->variable = v;\n cv->next = command_variables;\n command_variables = cv;\n }\n }\n else if (! env)\n {\n /* Not an option or variable definition; it must be a goal\n target! Enter it as a file and add it to the dep chain of\n goals. */\n struct file *f = enter_file (strcache_add (expand_command_line_file (arg)));\n f->cmd_target = 1;\n\n if (goals == 0)\n {\n goals = alloc_goaldep ();\n lastgoal = goals;\n }\n else\n {\n lastgoal->next = alloc_goaldep ();\n lastgoal = lastgoal->next;\n }\n\n lastgoal->file = f;\n\n {\n /* Add this target name to the MAKECMDGOALS variable. */\n struct variable *gv;\n const char *value;\n\n gv = lookup_variable (STRING_SIZE_TUPLE (\"MAKECMDGOALS\"));\n if (gv == 0)\n value = f->name;\n else\n {\n /* Paste the old and new values together */\n size_t oldlen, newlen;\n char *vp;\n\n oldlen = strlen (gv->value);\n newlen = strlen (f->name);\n vp = alloca (oldlen + 1 + newlen + 1);\n memcpy (vp, gv->value, oldlen);\n vp[oldlen] = ' ';\n memcpy (&vp[oldlen + 1], f->name, newlen + 1);\n value = vp;\n }\n define_variable_cname (\"MAKECMDGOALS\", value, o_default, 0);\n }\n }\n}\n\n/* Print a nice usage method. */\n\nstatic void\nprint_usage (int bad)\n{\n const char *const *cpp;\n FILE *usageto;\n\n if (print_version_flag)\n print_version ();\n\n usageto = bad ? stderr : stdout;\n\n fprintf (usageto, _(\"Usage: %s [options] [target] ...\\n\"), program);\n\n for (cpp = usage; *cpp; ++cpp)\n fputs (_(*cpp), usageto);\n\n if (!remote_description || *remote_description == '\\0')\n fprintf (usageto, _(\"\\nThis program built for %s\\n\"), make_host);\n else\n fprintf (usageto, _(\"\\nThis program built for %s (%s)\\n\"),\n make_host, remote_description);\n\n fprintf (usageto, _(\"Report bugs to https://github.com/rocky/remake/issues\\n\"));\n}\n\n/* Decode switches from ARGC and ARGV.\n They came from the environment if ENV is nonzero. */\n\nstatic void\ndecode_switches (int argc, const char **argv, int env)\n{\n int bad = 0;\n const struct command_switch *cs;\n struct stringlist *sl;\n int c;\n\n /* getopt does most of the parsing for us.\n First, get its vectors set up. */\n\n init_switches ();\n\n /* Let getopt produce error messages for the command line,\n but not for options from the environment. */\n opterr = !env;\n /* Reset getopt's state. */\n optind = 0;\n\n while (optind < argc)\n {\n const char *coptarg;\n\n /* Parse the next argument. */\n c = getopt_long (argc, (char*const*)argv, options, long_options, NULL);\n coptarg = optarg;\n if (c == EOF)\n /* End of arguments, or \"--\" marker seen. */\n break;\n else if (c == 1)\n /* An argument not starting with a dash. */\n handle_non_switch_argument (coptarg, env);\n else if (c == '?')\n /* Bad option. We will print a usage message and die later.\n But continue to parse the other options so the user can\n see all he did wrong. */\n bad = 1;\n else\n for (cs = switches; cs->c != '\\0'; ++cs)\n if (cs->c == c)\n {\n /* Whether or not we will actually do anything with\n this switch. We test this individually inside the\n switch below rather than just once outside it, so that\n options which are to be ignored still consume args. */\n int doit = !env || cs->env;\n\n switch (cs->type)\n {\n default:\n abort ();\n\n case ignore:\n break;\n\n case flag:\n case flag_off:\n if (doit)\n *(int *) cs->value_ptr = cs->type == flag;\n break;\n\n case string:\n case strlist:\n case filename:\n if (!doit)\n break;\n\n if (! coptarg)\n coptarg = xstrdup (cs->noarg_value);\n else if (*coptarg == '\\0')\n {\n char opt[2] = \"c\";\n const char *op = opt;\n\n if (short_option (cs->c))\n opt[0] = (char) cs->c;\n else\n op = cs->long_name;\n\n error (NILF, strlen (op),\n _(\"the '%s%s' option requires a non-empty string argument\"),\n short_option (cs->c) ? \"-\" : \"--\", op);\n bad = 1;\n break;\n }\n\n if (cs->type == string)\n {\n char **val = (char **)cs->value_ptr;\n free (*val);\n *val = xstrdup (coptarg);\n break;\n }\n\n sl = *(struct stringlist **) cs->value_ptr;\n if (sl == 0)\n {\n sl = xmalloc (sizeof (struct stringlist));\n sl->max = 5;\n sl->idx = 0;\n sl->list = xmalloc (5 * sizeof (char *));\n *(struct stringlist **) cs->value_ptr = sl;\n }\n else if (sl->idx == sl->max - 1)\n {\n sl->max += 5;\n /* MSVC erroneously warns without a cast here. */\n sl->list = xrealloc ((void *)sl->list,\n sl->max * sizeof (char *));\n }\n if (cs->type == filename)\n sl->list[sl->idx++] = expand_command_line_file (coptarg);\n else\n sl->list[sl->idx++] = xstrdup (coptarg);\n sl->list[sl->idx] = 0;\n break;\n\n case positive_int:\n /* See if we have an option argument; if we do require that\n it's all digits, not something like \"10foo\". */\n if (coptarg == 0 && argc > optind)\n {\n const char *cp;\n for (cp=argv[optind]; ISDIGIT (cp[0]); ++cp)\n ;\n if (cp[0] == '\\0')\n coptarg = argv[optind++];\n }\n\n if (!doit)\n break;\n\n if (coptarg)\n {\n int i = atoi (coptarg);\n const char *cp;\n\n /* Yes, I realize we're repeating this in some cases. */\n for (cp = coptarg; ISDIGIT (cp[0]); ++cp)\n ;\n\n if (i < 1 || cp[0] != '\\0')\n {\n error (NILF, 0,\n _(\"the '-%c' option requires a positive integer argument\"),\n cs->c);\n bad = 1;\n }\n else\n *(unsigned int *) cs->value_ptr = i;\n }\n else\n *(unsigned int *) cs->value_ptr\n = *(unsigned int *) cs->noarg_value;\n break;\n\n case floating:\n if (coptarg == 0 && optind < argc\n && (ISDIGIT (argv[optind][0]) || argv[optind][0] == '.'))\n coptarg = argv[optind++];\n\n if (doit)\n *(double *) cs->value_ptr\n = (coptarg != 0 ? atof (coptarg)\n : *(double *) cs->noarg_value);\n\n break;\n }\n\n /* We've found the switch. Stop looking. */\n break;\n }\n }\n\n /* There are no more options according to getting getopt, but there may\n be some arguments left. Since we have asked for non-option arguments\n to be returned in order, this only happens when there is a \"--\"\n argument to prevent later arguments from being options. */\n while (optind < argc)\n handle_non_switch_argument (argv[optind++], env);\n\n if (!env && (bad || print_usage_flag))\n {\n print_usage (bad);\n die (bad ? MAKE_FAILURE : MAKE_SUCCESS);\n }\n\n /* If there are any options that need to be decoded do it now. */\n decode_debug_flags ();\n decode_output_sync_flags ();\n\n /* Perform any special switch handling. */\n run_silent = silent_flag;\n\n}\n\n/* Decode switches from environment variable ENVAR (which is LEN chars long).\n We do this by chopping the value into a vector of words, prepending a\n dash to the first word if it lacks one, and passing the vector to\n decode_switches. */\n\nstatic void\ndecode_env_switches (const char *envar, size_t len)\n{\n char *varref = alloca (2 + len + 2);\n char *value, *p, *buf;\n int argc;\n const char **argv;\n\n /* Get the variable's value. */\n varref[0] = '$';\n varref[1] = '(';\n memcpy (&varref[2], envar, len);\n varref[2 + len] = ')';\n varref[2 + len + 1] = '\\0';\n value = variable_expand (varref);\n\n /* Skip whitespace, and check for an empty value. */\n NEXT_TOKEN (value);\n len = strlen (value);\n if (len == 0)\n return;\n\n /* Allocate a vector that is definitely big enough. */\n argv = alloca ((1 + len + 1) * sizeof (char *));\n\n /* getopt will look at the arguments starting at ARGV[1].\n Prepend a spacer word. */\n argv[0] = 0;\n argc = 1;\n\n /* We need a buffer to copy the value into while we split it into words\n and unquote it. Set up in case we need to prepend a dash later. */\n buf = alloca (1 + len + 1);\n buf[0] = '-';\n p = buf+1;\n argv[argc] = p;\n while (*value != '\\0')\n {\n if (*value == '\\\\' && value[1] != '\\0')\n ++value; /* Skip the backslash. */\n else if (ISBLANK (*value))\n {\n /* End of the word. */\n *p++ = '\\0';\n argv[++argc] = p;\n do\n ++value;\n while (ISBLANK (*value));\n continue;\n }\n *p++ = *value++;\n }\n *p = '\\0';\n argv[++argc] = 0;\n assert (p < buf + len + 2);\n\n if (argv[1][0] != '-' && strchr (argv[1], '=') == 0)\n /* The first word doesn't start with a dash and isn't a variable\n definition, so add a dash. */\n argv[1] = buf;\n\n /* Parse those words. */\n decode_switches (argc, argv, 1);\n}\n\f\n/* Quote the string IN so that it will be interpreted as a single word with\n no magic by decode_env_switches; also double dollar signs to avoid\n variable expansion in make itself. Write the result into OUT, returning\n the address of the next character to be written.\n Allocating space for OUT twice the length of IN is always sufficient. */\n\nstatic char *\nquote_for_env (char *out, const char *in)\n{\n while (*in != '\\0')\n {\n if (*in == '$')\n *out++ = '$';\n else if (ISBLANK (*in) || *in == '\\\\')\n *out++ = '\\\\';\n *out++ = *in++;\n }\n\n return out;\n}\n\n/* Define the MAKEFLAGS and MFLAGS variables to reflect the settings of the\n command switches. Include options with args if ALL is nonzero.\n Don't include options with the 'no_makefile' flag set if MAKEFILE. */\n\nstatic struct variable *\ndefine_makeflags (int all, int makefile)\n{\n const char ref[] = \"MAKEOVERRIDES\";\n const char posixref[] = \"-*-command-variables-*-\";\n const char evalref[] = \"$(-*-eval-flags-*-)\";\n const struct command_switch *cs;\n char *flagstring;\n char *p;\n\n /* We will construct a linked list of 'struct flag's describing\n all the flags which need to go in MAKEFLAGS. Then, once we\n know how many there are and their lengths, we can put them all\n together in a string. */\n\n struct flag\n {\n struct flag *next;\n const struct command_switch *cs;\n const char *arg;\n };\n struct flag *flags = 0;\n struct flag *last = 0;\n size_t flagslen = 0;\n#define ADD_FLAG(ARG, LEN) \\\n do { \\\n struct flag *new = alloca (sizeof (struct flag)); \\\n new->cs = cs; \\\n new->arg = (ARG); \\\n new->next = 0; \\\n if (! flags) \\\n flags = new; \\\n else \\\n last->next = new; \\\n last = new; \\\n if (new->arg == 0) \\\n /* Just a single flag letter: \" -x\" */ \\\n flagslen += 3; \\\n else \\\n /* \" -xfoo\", plus space to escape \"foo\". */ \\\n flagslen += 1 + 1 + 1 + (3 * (LEN)); \\\n if (!short_option (cs->c)) \\\n /* This switch has no single-letter version, so we use the long. */ \\\n flagslen += 2 + strlen (cs->long_name); \\\n } while (0)\n\n for (cs = switches; cs->c != '\\0'; ++cs)\n if (cs->toenv && (!makefile || !cs->no_makefile))\n switch (cs->type)\n {\n case ignore:\n break;\n\n case flag:\n case flag_off:\n if ((!*(int *) cs->value_ptr) == (cs->type == flag_off)\n && (cs->default_value == 0\n || *(int *) cs->value_ptr != *(int *) cs->default_value))\n\t if (cs->c != 'X') ADD_FLAG (0, 0);\n break;\n\n case positive_int:\n if (all)\n {\n if ((cs->default_value != 0\n && (*(unsigned int *) cs->value_ptr\n == *(unsigned int *) cs->default_value)))\n break;\n else if (cs->noarg_value != 0\n && (*(unsigned int *) cs->value_ptr ==\n *(unsigned int *) cs->noarg_value))\n ADD_FLAG (\"\", 0); /* Optional value omitted; see below. */\n else\n {\n char *buf = alloca (30);\n sprintf (buf, \"%u\", *(unsigned int *) cs->value_ptr);\n ADD_FLAG (buf, strlen (buf));\n }\n }\n break;\n\n case floating:\n if (all)\n {\n if (cs->default_value != 0\n && (*(double *) cs->value_ptr\n == *(double *) cs->default_value))\n break;\n else if (cs->noarg_value != 0\n && (*(double *) cs->value_ptr\n == *(double *) cs->noarg_value))\n ADD_FLAG (\"\", 0); /* Optional value omitted; see below. */\n else\n {\n char *buf = alloca (100);\n sprintf (buf, \"%g\", *(double *) cs->value_ptr);\n ADD_FLAG (buf, strlen (buf));\n }\n }\n break;\n\n case string:\n if (all)\n {\n p = *((char **)cs->value_ptr);\n if (p)\n ADD_FLAG (p, strlen (p));\n }\n break;\n\n case filename:\n case strlist:\n if (all)\n {\n struct stringlist *sl = *(struct stringlist **) cs->value_ptr;\n if (sl != 0)\n {\n unsigned int i;\n for (i = 0; i < sl->idx; ++i)\n ADD_FLAG (sl->list[i], strlen (sl->list[i]));\n }\n }\n break;\n\n default:\n abort ();\n }\n\n#undef ADD_FLAG\n\n /* Four more for the possible \" -- \", plus variable references. */\n flagslen += 4 + CSTRLEN (posixref) + 4 + CSTRLEN (evalref) + 4;\n\n /* Construct the value in FLAGSTRING.\n We allocate enough space for a preceding dash and trailing null. */\n flagstring = alloca (1 + flagslen + 1);\n memset (flagstring, '\\0', 1 + flagslen + 1);\n p = flagstring;\n\n /* Start with a dash, for MFLAGS. */\n *p++ = '-';\n\n /* Add simple options as a group. */\n while (flags != 0 && !flags->arg && short_option (flags->cs->c))\n {\n if (flags->cs->c != 'X') {\n *p++ = (char) flags->cs->c;\n flags = flags->next;\n }\n }\n\n /* Now add more complex flags: ones with options and/or long names. */\n while (flags)\n {\n *p++ = ' ';\n *p++ = '-';\n\n /* Add the flag letter or name to the string. */\n if (short_option (flags->cs->c)) {\n if (flags->cs->c != 'X') *p++ = (char) flags->cs->c;\n } else\n {\n /* Long options require a double-dash. */\n *p++ = '-';\n strcpy (p, flags->cs->long_name);\n p += strlen (p);\n }\n /* An omitted optional argument has an ARG of \"\". */\n if (flags->arg && flags->arg[0] != '\\0')\n {\n if (!short_option (flags->cs->c))\n /* Long options require '='. */\n *p++ = '=';\n p = quote_for_env (p, flags->arg);\n }\n flags = flags->next;\n }\n\n /* If no flags at all, get rid of the initial dash. */\n if (p == &flagstring[1])\n {\n flagstring[0] = '\\0';\n p = flagstring;\n }\n\n /* Define MFLAGS before appending variable definitions. Omit an initial\n empty dash. Since MFLAGS is not parsed for flags, there is no reason to\n override any makefile redefinition. */\n define_variable_cname (\"MFLAGS\",\n flagstring + (flagstring[0] == '-' && flagstring[1] == ' ' ? 2 : 0),\n o_env, 1);\n\n /* Write a reference to -*-eval-flags-*-, which contains all the --eval\n flag options. */\n if (eval_strings)\n {\n *p++ = ' ';\n memcpy (p, evalref, CSTRLEN (evalref));\n p += CSTRLEN (evalref);\n }\n\n if (all)\n {\n /* If there are any overrides to add, write a reference to\n $(MAKEOVERRIDES), which contains command-line variable definitions.\n Separate the variables from the switches with a \"--\" arg. */\n\n const char *r = posix_pedantic ? posixref : ref;\n size_t l = strlen (r);\n struct variable *v = lookup_variable (r, l);\n\n if (v && v->value && v->value[0] != '\\0')\n {\n strcpy (p, \" -- \");\n p += 4;\n\n *(p++) = '$';\n *(p++) = '(';\n memcpy (p, r, l);\n p += l;\n *(p++) = ')';\n }\n }\n\n /* If there is a leading dash, omit it. */\n if (flagstring[0] == '-')\n ++flagstring;\n\n /* This used to use o_env, but that lost when a makefile defined MAKEFLAGS.\n Makefiles set MAKEFLAGS to add switches, but we still want to redefine\n its value with the full set of switches. Then we used o_file, but that\n lost when users added -e, causing a previous MAKEFLAGS env. var. to take\n precedence over the new one. Of course, an override or command\n definition will still take precedence. */\n return define_variable_cname (\"MAKEFLAGS\", flagstring,\n env_overrides ? o_env_override : o_file, 1);\n}\n\f\n/* Print version information. */\n\nstatic void\nprint_version (void)\n{\n static int printed_version = 0;\n\n const char *precede = print_data_base_flag ? \"# \" : \"\";\n\n if (printed_version)\n /* Do it only once. */\n return;\n\n printf (\"%sGNU Make %s\\n\", precede, version_string);\n\n if (!remote_description || *remote_description == '\\0')\n printf (_(\"%sBuilt for %s\\n\"), precede, make_host);\n else\n printf (_(\"%sBuilt for %s (%s)\\n\"),\n precede, make_host, remote_description);\n\n /* Print this untranslated. The coding standards recommend translating the\n (C) to the copyright symbol, but this string is going to change every\n year, and none of the rest of it should be translated (including the\n word \"Copyright\"), so it hardly seems worth it. */\n\n printf (\"%sCopyright (C) 1988-2020 Free Software Foundation, Inc.\\n\"\n\t \"Copyright (C) 2015, 2017 Rocky Bernstein.\\n\",\n precede);\n\n printf (_(\"%sLicense GPLv3+: GNU GPL version 3 or later \\n\\\n%sThis is free software: you are free to change and redistribute it.\\n\\\n%sThere is NO WARRANTY, to the extent permitted by law.\\n\"),\n precede, precede, precede);\n\n printed_version = 1;\n\n /* Flush stdout so the user doesn't have to wait to see the\n version information while make thinks about things. */\n fflush (stdout);\n}\n\n/* Print a bunch of information about this and that. */\n\nstatic void\nprint_data_base (void)\n{\n time_t when = time ((time_t *) 0);\n\n print_version ();\n\n printf (_(\"\\n# Make data base, printed on %s\"), ctime (&when));\n\n print_variable_data_base ();\n print_dir_data_base ();\n print_rule_data_base (true);\n print_file_data_base ();\n print_vpath_data_base ();\n strcache_print_stats (\"#\");\n\n when = time ((time_t *) 0);\n printf (_(\"\\n# Finished Make data base on %s\\n\"), ctime (&when));\n}\n\nstatic void\nclean_jobserver (int status)\n{\n /* Sanity: have we written all our jobserver tokens back? If our\n exit status is 2 that means some kind of syntax error; we might not\n have written all our tokens so do that now. If tokens are left\n after any other error code, that's bad. */\n\n if (jobserver_enabled() && jobserver_tokens)\n {\n if (status != 2)\n ON (error, NILF,\n \"INTERNAL: Exiting with %u jobserver tokens (should be 0)!\",\n jobserver_tokens);\n else\n /* Don't write back the \"free\" token */\n while (--jobserver_tokens)\n jobserver_release (0);\n }\n\n\n /* Sanity: If we're the master, were all the tokens written back? */\n\n if (master_job_slots)\n {\n /* We didn't write one for ourself, so start at 1. */\n unsigned int tokens = 1 + jobserver_acquire_all ();\n\n if (tokens != master_job_slots)\n ONN (error, NILF,\n \"INTERNAL: Exiting with %u jobserver tokens available; should be %u!\",\n tokens, master_job_slots);\n\n reset_jobserver ();\n }\n}\n\f\n/* Exit with STATUS, cleaning up as necessary. */\n\nvoid\ndie (int status)\n{\n static char dying = 0;\n\n if (!dying)\n {\n int err;\n\n dying = 1;\n\n if (print_version_flag)\n print_version ();\n\n /* Wait for children to die. */\n err = (status != 0);\n while (job_slots_used > 0)\n reap_children (1, err, NULL);\n\n /* Let the remote job module clean up its state. */\n remote_cleanup ();\n\n /* Remove the intermediate files. */\n remove_intermediates (0);\n\n if (print_data_base_flag)\n print_data_base ();\n\n if (verify_flag)\n verify_file_data_base ();\n\n clean_jobserver (status);\n\n if (output_context)\n {\n /* die() might be called in a recipe output context due to an\n $(error ...) function. */\n output_close (output_context);\n\n if (output_context != &make_sync)\n output_close (&make_sync);\n\n OUTPUT_UNSET ();\n }\n\n output_close (NULL);\n\n /* Try to move back to the original directory. This is essential on\n MS-DOS (where there is really only one process), and on Unix it\n puts core files in the original directory instead of the -C\n directory. Must wait until after remove_intermediates(), or unlinks\n of relative pathnames fail. */\n if (directory_before_chdir != 0)\n {\n /* If it fails we don't care: shut up GCC. */\n int _x UNUSED;\n _x = chdir (directory_before_chdir);\n }\n }\n\n if (profile_flag) {\n const char *status_str;\n switch (status) {\n case MAKE_SUCCESS:\n\tstatus_str = \"Normal program termination\";\n\tbreak;\n case MAKE_TROUBLE:\n\tstatus_str = \"Platform failure termination\";\n\tbreak;\n case MAKE_FAILURE:\n\tstatus_str = \"Failure program termination\";\n\tbreak;\n case DEBUGGER_QUIT_RC:\n\tstatus_str = \"Debugger termination\";\n\tbreak;\n default:\n\tstatus_str = \"\";\n }\n\n profile_close(status_str, goals, (jobserver_auth != NULL));\n }\n exit (status);\n}\n"}} -{"repo": "RobotiumTech/robotium", "pr_number": 851, "title": "Added a loop that retries getLocationOnScreen until it gets a value", "state": "closed", "merged_at": "2016-09-27T18:23:56Z", "additions": 7, "deletions": 1, "files_changed": ["robotium-solo/src/main/java/com/robotium/solo/Clicker.java"], "files_before": {"robotium-solo/src/main/java/com/robotium/solo/Clicker.java": "package com.robotium.solo;\n\nimport java.lang.reflect.Constructor;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.List;\n\nimport junit.framework.Assert;\nimport android.app.Activity;\nimport android.app.Instrumentation;\nimport android.content.Context;\nimport android.os.SystemClock;\nimport android.util.Log;\nimport android.view.KeyEvent;\nimport android.view.MenuItem;\nimport android.view.MotionEvent;\nimport android.view.View;\nimport android.view.ViewConfiguration;\nimport android.view.ViewGroup;\nimport android.view.Window;\nimport android.widget.AbsListView;\nimport android.widget.TextView;\n\n/**\n * Contains various click methods. Examples are: clickOn(),\n * clickOnText(), clickOnScreen().\n *\n * @author Renas Reda, renas.reda@robotium.com\n *\n */\n\nclass Clicker {\n\n\tprivate final String LOG_TAG = \"Robotium\";\n\tprivate final ActivityUtils activityUtils;\n\tprivate final ViewFetcher viewFetcher;\n\tprivate final Instrumentation inst;\n\tprivate final Sender sender;\n\tprivate final Sleeper sleeper;\n\tprivate final Waiter waiter;\n\tprivate final WebUtils webUtils;\n\tprivate final DialogUtils dialogUtils;\n\tprivate final int MINI_WAIT = 300;\n\tprivate final int WAIT_TIME = 1500;\n\n\n\t/**\n\t * Constructs this object.\n\t *\n\t * @param activityUtils the {@code ActivityUtils} instance\n\t * @param viewFetcher the {@code ViewFetcher} instance\n\t * @param sender the {@code Sender} instance\n\t * @param inst the {@code android.app.Instrumentation} instance\n\t * @param sleeper the {@code Sleeper} instance\n\t * @param waiter the {@code Waiter} instance\n\t * @param webUtils the {@code WebUtils} instance\n\t * @param dialogUtils the {@code DialogUtils} instance\n\t */\n\n\tpublic Clicker(ActivityUtils activityUtils, ViewFetcher viewFetcher, Sender sender, Instrumentation inst, Sleeper sleeper, Waiter waiter, WebUtils webUtils, DialogUtils dialogUtils) {\n\n\t\tthis.activityUtils = activityUtils;\n\t\tthis.viewFetcher = viewFetcher;\n\t\tthis.sender = sender;\n\t\tthis.inst = inst;\n\t\tthis.sleeper = sleeper;\n\t\tthis.waiter = waiter;\n\t\tthis.webUtils = webUtils;\n\t\tthis.dialogUtils = dialogUtils;\n\t}\n\n\t/**\n\t * Clicks on a given coordinate on the screen.\n\t *\n\t * @param x the x coordinate\n\t * @param y the y coordinate\n\t */\n\n\tpublic void clickOnScreen(float x, float y, View view) {\n\t\tboolean successfull = false;\n\t\tint retry = 0;\n\t\tSecurityException ex = null;\n\n\t\twhile(!successfull && retry < 20) {\n\t\t\tlong downTime = SystemClock.uptimeMillis();\n\t\t\tlong eventTime = SystemClock.uptimeMillis();\n\t\t\tMotionEvent event = MotionEvent.obtain(downTime, eventTime,\n\t\t\t\t\tMotionEvent.ACTION_DOWN, x, y, 0);\n\t\t\tMotionEvent event2 = MotionEvent.obtain(downTime, eventTime,\n\t\t\t\t\tMotionEvent.ACTION_UP, x, y, 0);\n\t\t\ttry{\n\t\t\t\tinst.sendPointerSync(event);\n\t\t\t\tinst.sendPointerSync(event2);\n\t\t\t\tsuccessfull = true;\n\t\t\t}catch(SecurityException e){\n\t\t\t\tex = e;\n\t\t\t\tdialogUtils.hideSoftKeyboard(null, false, true);\n\t\t\t\tsleeper.sleep(MINI_WAIT);\n\t\t\t\tretry++;\n\t\t\t\tView identicalView = viewFetcher.getIdenticalView(view);\n\t\t\t\tif(identicalView != null){\n\t\t\t\t\tfloat[] xyToClick = getClickCoordinates(identicalView);\n\t\t\t\t\tx = xyToClick[0]; \n\t\t\t\t\ty = xyToClick[1];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif(!successfull) {\n\t\t\tAssert.fail(\"Click at (\"+x+\", \"+y+\") can not be completed! (\"+(ex != null ? ex.getClass().getName()+\": \"+ex.getMessage() : \"null\")+\")\");\n\t\t}\n\t}\n\n\t/**\n\t * Long clicks a given coordinate on the screen.\n\t *\n\t * @param x the x coordinate\n\t * @param y the y coordinate\n\t * @param time the amount of time to long click\n\t */\n\n\tpublic void clickLongOnScreen(float x, float y, int time, View view) {\n\t\tboolean successfull = false;\n\t\tint retry = 0;\n\t\tSecurityException ex = null;\n\t\tlong downTime = SystemClock.uptimeMillis();\n\t\tlong eventTime = SystemClock.uptimeMillis();\n\t\tMotionEvent event = MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_DOWN, x, y, 0);\n\n\t\twhile(!successfull && retry < 20) {\n\t\t\ttry{\n\t\t\t\tinst.sendPointerSync(event);\n\t\t\t\tsuccessfull = true;\n\t\t\t\tsleeper.sleep(MINI_WAIT);\n\t\t\t}catch(SecurityException e){\n\t\t\t\tex = e;\n\t\t\t\tdialogUtils.hideSoftKeyboard(null, false, true);\n\t\t\t\tsleeper.sleep(MINI_WAIT);\n\t\t\t\tretry++;\n\t\t\t\tView identicalView = viewFetcher.getIdenticalView(view);\n\t\t\t\tif(identicalView != null){\n\t\t\t\t\tfloat[] xyToClick = getClickCoordinates(identicalView);\n\t\t\t\t\tx = xyToClick[0];\n\t\t\t\t\ty = xyToClick[1];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif(!successfull) {\n\t\t\tAssert.fail(\"Long click at (\"+x+\", \"+y+\") can not be completed! (\"+(ex != null ? ex.getClass().getName()+\": \"+ex.getMessage() : \"null\")+\")\");\n\t\t}\n\n\t\teventTime = SystemClock.uptimeMillis();\n\t\tevent = MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_MOVE, x + 1.0f, y + 1.0f, 0);\n\t\tinst.sendPointerSync(event);\n\t\tif(time > 0)\n\t\t\tsleeper.sleep(time);\n\t\telse\n\t\t\tsleeper.sleep((int)(ViewConfiguration.getLongPressTimeout() * 2.5f));\n\n\t\teventTime = SystemClock.uptimeMillis();\n\t\tevent = MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_UP, x, y, 0);\n\t\tinst.sendPointerSync(event);\n\t\tsleeper.sleep();\n\t}\n\n\n\t/**\n\t * Clicks on a given {@link View}.\n\t *\n\t * @param view the view that should be clicked\n\t */\n\n\tpublic void clickOnScreen(View view) {\n\t\tclickOnScreen(view, false, 0);\n\t}\n\n\t/**\n\t * Private method used to click on a given view.\n\t *\n\t * @param view the view that should be clicked\n\t * @param longClick true if the click should be a long click\n\t * @param time the amount of time to long click\n\t */\n\n\tpublic void clickOnScreen(View view, boolean longClick, int time) {\n\t\tif(view == null)\n\t\t\tAssert.fail(\"View is null and can therefore not be clicked!\");\n\n\t\tfloat[] xyToClick = getClickCoordinates(view);\n\t\tfloat x = xyToClick[0];\n\t\tfloat y = xyToClick[1];\n\n\t\tif(x == 0 || y == 0){\n\t\t\tsleeper.sleepMini();\n\t\t\ttry {\n\t\t\t\tview = viewFetcher.getIdenticalView(view);\n\t\t\t} catch (Exception ignored){}\n\n\t\t\tif(view != null){\n\t\t\t\txyToClick = getClickCoordinates(view);\n\t\t\t\tx = xyToClick[0];\n\t\t\t\ty = xyToClick[1];\n\t\t\t}\n\t\t}\n\n\t\tif (longClick)\n\t\t\tclickLongOnScreen(x, y, time, view);\n\t\telse\n\t\t\tclickOnScreen(x, y, view);\n\t}\t\n\n\t/**\n\t * Returns click coordinates for the specified view.\n\t * \n\t * @param view the view to get click coordinates from\n\t * @return click coordinates for a specified view\n\t */\n\n\tprivate float[] getClickCoordinates(View view){\n\t\tsleeper.sleep(200);\n\t\tint[] xyLocation = new int[2];\n\t\tfloat[] xyToClick = new float[2];\n\n\t\tview.getLocationOnScreen(xyLocation);\n\n\t\tfinal int viewWidth = view.getWidth();\n\t\tfinal int viewHeight = view.getHeight();\n\t\tfinal float x = xyLocation[0] + (viewWidth / 2.0f);\n\t\tfloat y = xyLocation[1] + (viewHeight / 2.0f);\n\n\t\txyToClick[0] = x;\n\t\txyToClick[1] = y;\n\n\t\treturn xyToClick;\n\t}\n\t\n\t\n\n\n\t/**\n\t * Long clicks on a specific {@link TextView} and then selects\n\t * an item from the context menu that appears. Will automatically scroll when needed.\n\t *\n\t * @param text the text that should be clicked on. The parameter will be interpreted as a regular expression.\n\t * @param index the index of the menu item that should be pressed\n\t */\n\n\tpublic void clickLongOnTextAndPress(String text, int index)\n\t{\n\t\tclickOnText(text, true, 0, true, 0);\n\t\tdialogUtils.waitForDialogToOpen(Timeout.getSmallTimeout(), true);\n\t\ttry{\n\t\t\tinst.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_DOWN);\n\t\t}catch(SecurityException e){\n\t\t\tAssert.fail(\"Can not press the context menu!\");\n\t\t}\n\t\tfor(int i = 0; i < index; i++)\n\t\t{\n\t\t\tsleeper.sleepMini();\n\t\t\tinst.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_DOWN);\n\t\t}\n\t\tinst.sendKeyDownUpSync(KeyEvent.KEYCODE_ENTER);\n\t}\n\n\t/**\n\t * Opens the menu and waits for it to open.\n\t */\n\n\tprivate void openMenu(){\n\t\tsleeper.sleepMini();\n\n\t\tif(!dialogUtils.waitForDialogToOpen(MINI_WAIT, false)) {\n\t\t\ttry{\n\t\t\t\tsender.sendKeyCode(KeyEvent.KEYCODE_MENU);\n\t\t\t\tdialogUtils.waitForDialogToOpen(WAIT_TIME, true);\n\t\t\t}catch(SecurityException e){\n\t\t\t\tAssert.fail(\"Can not open the menu!\");\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Clicks on a menu item with a given text.\n\t *\n\t * @param text the menu text that should be clicked on. The parameter will be interpreted as a regular expression.\n\t */\n\n\tpublic void clickOnMenuItem(String text)\n\t{\n\t\topenMenu();\n\t\tclickOnText(text, false, 1, true, 0);\n\t}\n\n\t/**\n\t * Clicks on a menu item with a given text.\n\t *\n\t * @param text the menu text that should be clicked on. The parameter will be interpreted as a regular expression.\n\t * @param subMenu true if the menu item could be located in a sub menu\n\t */\n\n\tpublic void clickOnMenuItem(String text, boolean subMenu)\n\t{\n\t\tsleeper.sleepMini();\n\n\t\tTextView textMore = null;\n\t\tint [] xy = new int[2];\n\t\tint x = 0;\n\t\tint y = 0;\n\n\t\tif(!dialogUtils.waitForDialogToOpen(MINI_WAIT, false)) {\n\t\t\ttry{\n\t\t\t\tsender.sendKeyCode(KeyEvent.KEYCODE_MENU);\n\t\t\t\tdialogUtils.waitForDialogToOpen(WAIT_TIME, true);\n\t\t\t}catch(SecurityException e){\n\t\t\t\tAssert.fail(\"Can not open the menu!\");\n\t\t\t}\n\t\t}\n\t\tboolean textShown = waiter.waitForText(text, 1, WAIT_TIME, true) != null;\n\n\t\tif(subMenu && (viewFetcher.getCurrentViews(TextView.class, true).size() > 5) && !textShown){\n\t\t\tfor(TextView textView : viewFetcher.getCurrentViews(TextView.class, true)){\n\t\t\t\tx = xy[0];\n\t\t\t\ty = xy[1];\n\t\t\t\ttextView.getLocationOnScreen(xy);\n\n\t\t\t\tif(xy[0] > x || xy[1] > y)\n\t\t\t\t\ttextMore = textView;\n\t\t\t}\n\t\t}\n\t\tif(textMore != null)\n\t\t\tclickOnScreen(textMore);\n\n\t\tclickOnText(text, false, 1, true, 0);\n\t}\n\n\t/**\n\t * Clicks on an ActionBar item with a given resource id\n\t *\n\t * @param resourceId the R.id of the ActionBar item\n\t */\n\n\tpublic void clickOnActionBarItem(int resourceId){\n\t\tsleeper.sleep();\n\t\tActivity activity = activityUtils.getCurrentActivity();\n\t\tif(activity != null){\n\t\t\tinst.invokeMenuActionSync(activity, resourceId, 0);\n\t\t}\n\t}\n\n\t/**\n\t * Clicks on an ActionBar Home/Up button.\n\t */\n\n\tpublic void clickOnActionBarHomeButton() {\n\t\tActivity activity = activityUtils.getCurrentActivity();\n\t\tMenuItem homeMenuItem = null;\n\n\t\ttry {\n\t\t\tClass cls = Class.forName(\"com.android.internal.view.menu.ActionMenuItem\");\n\t\t\tClass partypes[] = new Class[6];\n\t\t\tpartypes[0] = Context.class;\n\t\t\tpartypes[1] = Integer.TYPE;\n\t\t\tpartypes[2] = Integer.TYPE;\n\t\t\tpartypes[3] = Integer.TYPE;\n\t\t\tpartypes[4] = Integer.TYPE;\n\t\t\tpartypes[5] = CharSequence.class;\n\t\t\tConstructor ct = cls.getConstructor(partypes);\n\t\t\tObject argList[] = new Object[6];\n\t\t\targList[0] = activity;\n\t\t\targList[1] = 0;\n\t\t\targList[2] = android.R.id.home;\n\t\t\targList[3] = 0;\n\t\t\targList[4] = 0;\n\t\t\targList[5] = \"\";\n\t\t\thomeMenuItem = (MenuItem) ct.newInstance(argList);\n\t\t} catch (Exception ex) {\n\t\t\tLog.d(LOG_TAG, \"Can not find methods to invoke Home button!\");\n\t\t}\n\n\t\tif (homeMenuItem != null) {\n\t\t\ttry{\n\t\t\t\tactivity.getWindow().getCallback().onMenuItemSelected(Window.FEATURE_OPTIONS_PANEL, homeMenuItem);\n\t\t\t}catch(Exception ignored) {}\n\t\t}\n\t}\n\n\t/**\n\t * Clicks on a web element using the given By method.\n\t *\n\t * @param by the By object e.g. By.id(\"id\");\n\t * @param match if multiple objects match, this determines which one will be clicked\n\t * @param scroll true if scrolling should be performed\n\t * @param useJavaScriptToClick true if click should be perfomed through JavaScript\n\t */\n\n\tpublic void clickOnWebElement(By by, int match, boolean scroll, boolean useJavaScriptToClick){\n\t\tWebElement webElement = null;\n\t\t\n\t\tif(useJavaScriptToClick){\n\t\t\twebElement = waiter.waitForWebElement(by, match, Timeout.getSmallTimeout(), false);\n\t\t\tif(webElement == null){\n\t\t\t\tAssert.fail(\"WebElement with \" + webUtils.splitNameByUpperCase(by.getClass().getSimpleName()) + \": '\" + by.getValue() + \"' is not found!\");\n\t\t\t}\n\t\t\twebUtils.executeJavaScript(by, true);\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tWebElement webElementToClick = waiter.waitForWebElement(by, match, Timeout.getSmallTimeout(), scroll);\n\t\t\n\t\tif(webElementToClick == null){\n\t\t\tif(match > 1) {\n\t\t\t\tAssert.fail(match + \" WebElements with \" + webUtils.splitNameByUpperCase(by.getClass().getSimpleName()) + \": '\" + by.getValue() + \"' are not found!\");\n\t\t\t}\n\t\t\telse {\n\t\t\t\tAssert.fail(\"WebElement with \" + webUtils.splitNameByUpperCase(by.getClass().getSimpleName()) + \": '\" + by.getValue() + \"' is not found!\");\n\t\t\t}\n\t\t}\n\t\t\n\t\tclickOnScreen(webElementToClick.getLocationX(), webElementToClick.getLocationY(), null);\n\t}\n\n\n\t/**\n\t * Clicks on a specific {@link TextView} displaying a given text.\n\t *\n\t * @param regex the text that should be clicked on. The parameter will be interpreted as a regular expression.\n\t * @param longClick {@code true} if the click should be a long click\n\t * @param match the regex match that should be clicked on\n\t * @param scroll true if scrolling should be performed\n\t * @param time the amount of time to long click\n\t */\n\n\tpublic void clickOnText(String regex, boolean longClick, int match, boolean scroll, int time) {\n\t\tTextView textToClick = waiter.waitForText(regex, match, Timeout.getSmallTimeout(), scroll, true, false);\n\n\t\tif (textToClick != null) {\n\t\t\tclickOnScreen(textToClick, longClick, time);\n\t\t}\n\n\t\telse {\n\n\t\t\tif(match > 1){\n\t\t\t\tAssert.fail(match + \" matches of text string: '\" + regex + \"' are not found!\");\n\t\t\t}\n\n\t\t\telse{\n\t\t\t\tArrayList allTextViews = RobotiumUtils.removeInvisibleViews(viewFetcher.getCurrentViews(TextView.class, true));\n\t\t\t\tallTextViews.addAll((Collection) webUtils.getTextViewsFromWebView());\n\n\t\t\t\tfor (TextView textView : allTextViews) {\n\t\t\t\t\tLog.d(LOG_TAG, \"'\" + regex + \"' not found. Have found: '\" + textView.getText() + \"'\");\n\t\t\t\t}\n\t\t\t\tallTextViews = null;\n\t\t\t\tAssert.fail(\"Text string: '\" + regex + \"' is not found!\");\n\t\t\t}\n\t\t}\n\t}\n\n\n\t/**\n\t * Clicks on a {@code View} of a specific class, with a given text.\n\t *\n\t * @param viewClass what kind of {@code View} to click, e.g. {@code Button.class} or {@code TextView.class}\n\t * @param nameRegex the name of the view presented to the user. The parameter will be interpreted as a regular expression.\n\t */\n\n\tpublic void clickOn(Class viewClass, String nameRegex) {\n\t\tT viewToClick = (T) waiter.waitForText(viewClass, nameRegex, 0, Timeout.getSmallTimeout(), true, true, false);\n\n\t\tif (viewToClick != null) {\n\t\t\tclickOnScreen(viewToClick);\n\t\t} else {\n\t\t\tArrayList allTextViews = RobotiumUtils.removeInvisibleViews(viewFetcher.getCurrentViews(viewClass, true));\n\n\t\t\tfor (T view : allTextViews) {\n\t\t\t\tLog.d(LOG_TAG, \"'\" + nameRegex + \"' not found. Have found: '\" + view.getText() + \"'\");\n\t\t\t}\n\t\t\tAssert.fail(viewClass.getSimpleName() + \" with text: '\" + nameRegex + \"' is not found!\");\n\t\t}\n\t}\n\n\t/**\n\t * Clicks on a {@code View} of a specific class, with a certain index.\n\t *\n\t * @param viewClass what kind of {@code View} to click, e.g. {@code Button.class} or {@code ImageView.class}\n\t * @param index the index of the {@code View} to be clicked, within {@code View}s of the specified class\n\t */\n\n\tpublic void clickOn(Class viewClass, int index) {\n\t\tclickOnScreen(waiter.waitForAndGetView(index, viewClass));\n\t}\n\n\n\t/**\n\t * Clicks on a certain list line and returns the {@link TextView}s that\n\t * the list line is showing. Will use the first list it finds.\n\t *\n\t * @param line the line that should be clicked\n\t * @return a {@code List} of the {@code TextView}s located in the list line\n\t */\n\n\tpublic ArrayList clickInList(int line) {\n\t\treturn clickInList(line, 0, 0, false, 0);\n\t}\n\t\n\t/**\n\t * Clicks on a View with a specified resource id located in a specified list line\n\t *\n\t * @param line the line where the View is located\n\t * @param id the resource id of the View\n\t */\n\n\tpublic void clickInList(int line, int id) {\n\t\tclickInList(line, 0, id, false, 0);\n\t}\n\n\t/**\n\t * Clicks on a certain list line on a specified List and\n\t * returns the {@link TextView}s that the list line is showing.\n\t *\n\t * @param line the line that should be clicked\n\t * @param index the index of the list. E.g. Index 1 if two lists are available\n\t * @param id the resource id of the View to click\n\t * @return an {@code ArrayList} of the {@code TextView}s located in the list line\n\t */\n\n\tpublic ArrayList clickInList(int line, int index, int id, boolean longClick, int time) {\n\t\tfinal long endTime = SystemClock.uptimeMillis() + Timeout.getSmallTimeout();\n\n\t\tint lineIndex = line - 1;\n\t\tif(lineIndex < 0)\n\t\t\tlineIndex = 0;\n\n\t\tArrayList views = new ArrayList();\n\t\tfinal AbsListView absListView = waiter.waitForAndGetView(index, AbsListView.class);\n\n\t\tif(absListView == null)\n\t\t\tAssert.fail(\"AbsListView is null!\");\n\n\t\tfailIfIndexHigherThenChildCount(absListView, lineIndex, endTime);\n\n\t\tView viewOnLine = getViewOnAbsListLine(absListView, index, lineIndex);\n\n\t\tif(viewOnLine != null){\n\t\t\tviews = viewFetcher.getViews(viewOnLine, true);\n\t\t\tviews = RobotiumUtils.removeInvisibleViews(views);\n\n\t\t\tif(id == 0){\n\t\t\t\tclickOnScreen(viewOnLine, longClick, time);\n\t\t\t}\n\t\t\telse{\n\t\t\t\tclickOnScreen(getView(id, views));\n\t\t\t}\n\t\t}\n\t\treturn RobotiumUtils.filterViews(TextView.class, views);\n\t}\n\t\n\t/**\n\t * Clicks on a certain list line and returns the {@link TextView}s that\n\t * the list line is showing. Will use the first list it finds.\n\t *\n\t * @param line the line that should be clicked\n\t * @return a {@code List} of the {@code TextView}s located in the list line\n\t */\n\n\tpublic ArrayList clickInRecyclerView(int line) {\n\t\treturn clickInRecyclerView(line, 0, 0, false, 0);\n\t}\n\t\n\t/**\n\t * Clicks on a View with a specified resource id located in a specified RecyclerView itemIndex\n\t *\n\t * @param itemIndex the index where the View is located\n\t * @param id the resource id of the View\n\t */\n\n\tpublic void clickInRecyclerView(int itemIndex, int id) {\n\t\tclickInRecyclerView(itemIndex, 0, id, false, 0);\n\t}\n\n\t\n\t/**\n\t * Clicks on a certain list line on a specified List and\n\t * returns the {@link TextView}s that the list line is showing.\n\t *\n\t * @param itemIndex the item index that should be clicked\n\t * @param recyclerViewIndex the index of the RecyclerView. E.g. Index 1 if two RecyclerViews are available\n\t * @param id the resource id of the View to click\n\t * @return an {@code ArrayList} of the {@code TextView}s located in the list line\n\t */\n\n\tpublic ArrayList clickInRecyclerView(int itemIndex, int recyclerViewIndex, int id, boolean longClick, int time) {\n\t\tView viewOnLine = null;\n\t\tfinal long endTime = SystemClock.uptimeMillis() + Timeout.getSmallTimeout();\n\n\t\tif(itemIndex < 0)\n\t\t\titemIndex = 0;\n\n\t\tArrayList views = new ArrayList();\n\t\tViewGroup recyclerView = viewFetcher.getRecyclerView(recyclerViewIndex, Timeout.getSmallTimeout());\n\t\t\n\t\tif(recyclerView == null){\n\t\t\tAssert.fail(\"RecyclerView is not found!\");\n\t\t}\n\t\telse{\n\t\t\tfailIfIndexHigherThenChildCount(recyclerView, itemIndex, endTime);\n\t\t\tviewOnLine = getViewOnRecyclerItemIndex((ViewGroup) recyclerView, recyclerViewIndex, itemIndex);\n\t\t}\n\t\t\n\t\tif(viewOnLine != null){\n\t\t\tviews = viewFetcher.getViews(viewOnLine, true);\n\t\t\tviews = RobotiumUtils.removeInvisibleViews(views);\n\t\t\t\n\t\t\tif(id == 0){\n\t\t\t\tclickOnScreen(viewOnLine, longClick, time);\n\t\t\t}\n\t\t\telse{\n\t\t\t\tclickOnScreen(getView(id, views));\n\t\t\t}\n\t\t}\n\t\treturn RobotiumUtils.filterViews(TextView.class, views);\n\t}\n\t\n\tprivate View getView(int id, List views){\n\t\tfor(View view : views){\n\t\t\tif(id == view.getId()){\n\t\t\t\treturn view;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\t\n\tprivate void failIfIndexHigherThenChildCount(ViewGroup viewGroup, int index, long endTime){\n\t\twhile(index > viewGroup.getChildCount()){\n\t\t\tfinal boolean timedOut = SystemClock.uptimeMillis() > endTime;\n\t\t\tif (timedOut){\n\t\t\t\tint numberOfIndexes = viewGroup.getChildCount();\n\t\t\t\tAssert.fail(\"Can not click on index \" + index + \" as there are only \" + numberOfIndexes + \" indexes available\");\n\t\t\t}\n\t\t\tsleeper.sleep();\n\t\t}\n\t}\n\t\n\n\t/**\n\t * Returns the view in the specified list line\n\t * \n\t * @param absListView the ListView to use\n\t * @param index the index of the list. E.g. Index 1 if two lists are available\n\t * @param lineIndex the line index of the View\n\t * @return the View located at a specified list line\n\t */\n\n\tprivate View getViewOnAbsListLine(AbsListView absListView, int index, int lineIndex){\n\t\tfinal long endTime = SystemClock.uptimeMillis() + Timeout.getSmallTimeout();\n\t\tView view = absListView.getChildAt(lineIndex);\n\n\t\twhile(view == null){\n\t\t\tfinal boolean timedOut = SystemClock.uptimeMillis() > endTime;\n\t\t\tif (timedOut){\n\t\t\t\tAssert.fail(\"View is null and can therefore not be clicked!\");\n\t\t\t}\n\t\t\t\n\t\t\tsleeper.sleep();\n\t\t\tabsListView = (AbsListView) viewFetcher.getIdenticalView(absListView);\n\n\t\t\tif(absListView == null){\n\t\t\t\tabsListView = waiter.waitForAndGetView(index, AbsListView.class);\n\t\t\t}\n\t\t\t\n\t\t\tview = absListView.getChildAt(lineIndex);\n\t\t}\n\t\treturn view;\n\t}\n\t\n\t/**\n\t * Returns the view in the specified item index\n\t * \n\t * @param recyclerView the RecyclerView to use\n\t * @param itemIndex the item index of the View\n\t * @return the View located at a specified item index\n\t */\n\n\tprivate View getViewOnRecyclerItemIndex(ViewGroup recyclerView, int recyclerViewIndex, int itemIndex){\n\t\tfinal long endTime = SystemClock.uptimeMillis() + Timeout.getSmallTimeout();\n\t\tView view = recyclerView.getChildAt(itemIndex);\n\n\t\twhile(view == null){\n\t\t\tfinal boolean timedOut = SystemClock.uptimeMillis() > endTime;\n\t\t\tif (timedOut){\n\t\t\t\tAssert.fail(\"View is null and can therefore not be clicked!\");\n\t\t\t}\n\n\t\t\tsleeper.sleep();\n\t\t\trecyclerView = (ViewGroup) viewFetcher.getIdenticalView(recyclerView);\n\n\t\t\tif(recyclerView == null){\n\t\t\t\trecyclerView = (ViewGroup) viewFetcher.getRecyclerView(false, recyclerViewIndex);\n\t\t\t}\n\n\t\t\tif(recyclerView != null){\n\t\t\t\tview = recyclerView.getChildAt(itemIndex);\n\t\t\t}\n\t\t}\n\t\treturn view;\n\t}\n\t\n\t\n}\n"}, "files_after": {"robotium-solo/src/main/java/com/robotium/solo/Clicker.java": "package com.robotium.solo;\n\nimport java.lang.reflect.Constructor;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.List;\n\nimport junit.framework.Assert;\nimport android.app.Activity;\nimport android.app.Instrumentation;\nimport android.content.Context;\nimport android.os.SystemClock;\nimport android.util.Log;\nimport android.view.KeyEvent;\nimport android.view.MenuItem;\nimport android.view.MotionEvent;\nimport android.view.View;\nimport android.view.ViewConfiguration;\nimport android.view.ViewGroup;\nimport android.view.Window;\nimport android.widget.AbsListView;\nimport android.widget.TextView;\n\n/**\n * Contains various click methods. Examples are: clickOn(),\n * clickOnText(), clickOnScreen().\n *\n * @author Renas Reda, renas.reda@robotium.com\n *\n */\n\nclass Clicker {\n\n\tprivate final String LOG_TAG = \"Robotium\";\n\tprivate final ActivityUtils activityUtils;\n\tprivate final ViewFetcher viewFetcher;\n\tprivate final Instrumentation inst;\n\tprivate final Sender sender;\n\tprivate final Sleeper sleeper;\n\tprivate final Waiter waiter;\n\tprivate final WebUtils webUtils;\n\tprivate final DialogUtils dialogUtils;\n\tprivate final int MINI_WAIT = 300;\n\tprivate final int WAIT_TIME = 1500;\n\n\n\t/**\n\t * Constructs this object.\n\t *\n\t * @param activityUtils the {@code ActivityUtils} instance\n\t * @param viewFetcher the {@code ViewFetcher} instance\n\t * @param sender the {@code Sender} instance\n\t * @param inst the {@code android.app.Instrumentation} instance\n\t * @param sleeper the {@code Sleeper} instance\n\t * @param waiter the {@code Waiter} instance\n\t * @param webUtils the {@code WebUtils} instance\n\t * @param dialogUtils the {@code DialogUtils} instance\n\t */\n\n\tpublic Clicker(ActivityUtils activityUtils, ViewFetcher viewFetcher, Sender sender, Instrumentation inst, Sleeper sleeper, Waiter waiter, WebUtils webUtils, DialogUtils dialogUtils) {\n\n\t\tthis.activityUtils = activityUtils;\n\t\tthis.viewFetcher = viewFetcher;\n\t\tthis.sender = sender;\n\t\tthis.inst = inst;\n\t\tthis.sleeper = sleeper;\n\t\tthis.waiter = waiter;\n\t\tthis.webUtils = webUtils;\n\t\tthis.dialogUtils = dialogUtils;\n\t}\n\n\t/**\n\t * Clicks on a given coordinate on the screen.\n\t *\n\t * @param x the x coordinate\n\t * @param y the y coordinate\n\t */\n\n\tpublic void clickOnScreen(float x, float y, View view) {\n\t\tboolean successfull = false;\n\t\tint retry = 0;\n\t\tSecurityException ex = null;\n\n\t\twhile(!successfull && retry < 20) {\n\t\t\tlong downTime = SystemClock.uptimeMillis();\n\t\t\tlong eventTime = SystemClock.uptimeMillis();\n\t\t\tMotionEvent event = MotionEvent.obtain(downTime, eventTime,\n\t\t\t\t\tMotionEvent.ACTION_DOWN, x, y, 0);\n\t\t\tMotionEvent event2 = MotionEvent.obtain(downTime, eventTime,\n\t\t\t\t\tMotionEvent.ACTION_UP, x, y, 0);\n\t\t\ttry{\n\t\t\t\tinst.sendPointerSync(event);\n\t\t\t\tinst.sendPointerSync(event2);\n\t\t\t\tsuccessfull = true;\n\t\t\t}catch(SecurityException e){\n\t\t\t\tex = e;\n\t\t\t\tdialogUtils.hideSoftKeyboard(null, false, true);\n\t\t\t\tsleeper.sleep(MINI_WAIT);\n\t\t\t\tretry++;\n\t\t\t\tView identicalView = viewFetcher.getIdenticalView(view);\n\t\t\t\tif(identicalView != null){\n\t\t\t\t\tfloat[] xyToClick = getClickCoordinates(identicalView);\n\t\t\t\t\tx = xyToClick[0]; \n\t\t\t\t\ty = xyToClick[1];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif(!successfull) {\n\t\t\tAssert.fail(\"Click at (\"+x+\", \"+y+\") can not be completed! (\"+(ex != null ? ex.getClass().getName()+\": \"+ex.getMessage() : \"null\")+\")\");\n\t\t}\n\t}\n\n\t/**\n\t * Long clicks a given coordinate on the screen.\n\t *\n\t * @param x the x coordinate\n\t * @param y the y coordinate\n\t * @param time the amount of time to long click\n\t */\n\n\tpublic void clickLongOnScreen(float x, float y, int time, View view) {\n\t\tboolean successfull = false;\n\t\tint retry = 0;\n\t\tSecurityException ex = null;\n\t\tlong downTime = SystemClock.uptimeMillis();\n\t\tlong eventTime = SystemClock.uptimeMillis();\n\t\tMotionEvent event = MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_DOWN, x, y, 0);\n\n\t\twhile(!successfull && retry < 20) {\n\t\t\ttry{\n\t\t\t\tinst.sendPointerSync(event);\n\t\t\t\tsuccessfull = true;\n\t\t\t\tsleeper.sleep(MINI_WAIT);\n\t\t\t}catch(SecurityException e){\n\t\t\t\tex = e;\n\t\t\t\tdialogUtils.hideSoftKeyboard(null, false, true);\n\t\t\t\tsleeper.sleep(MINI_WAIT);\n\t\t\t\tretry++;\n\t\t\t\tView identicalView = viewFetcher.getIdenticalView(view);\n\t\t\t\tif(identicalView != null){\n\t\t\t\t\tfloat[] xyToClick = getClickCoordinates(identicalView);\n\t\t\t\t\tx = xyToClick[0];\n\t\t\t\t\ty = xyToClick[1];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif(!successfull) {\n\t\t\tAssert.fail(\"Long click at (\"+x+\", \"+y+\") can not be completed! (\"+(ex != null ? ex.getClass().getName()+\": \"+ex.getMessage() : \"null\")+\")\");\n\t\t}\n\n\t\teventTime = SystemClock.uptimeMillis();\n\t\tevent = MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_MOVE, x + 1.0f, y + 1.0f, 0);\n\t\tinst.sendPointerSync(event);\n\t\tif(time > 0)\n\t\t\tsleeper.sleep(time);\n\t\telse\n\t\t\tsleeper.sleep((int)(ViewConfiguration.getLongPressTimeout() * 2.5f));\n\n\t\teventTime = SystemClock.uptimeMillis();\n\t\tevent = MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_UP, x, y, 0);\n\t\tinst.sendPointerSync(event);\n\t\tsleeper.sleep();\n\t}\n\n\n\t/**\n\t * Clicks on a given {@link View}.\n\t *\n\t * @param view the view that should be clicked\n\t */\n\n\tpublic void clickOnScreen(View view) {\n\t\tclickOnScreen(view, false, 0);\n\t}\n\n\t/**\n\t * Private method used to click on a given view.\n\t *\n\t * @param view the view that should be clicked\n\t * @param longClick true if the click should be a long click\n\t * @param time the amount of time to long click\n\t */\n\n\tpublic void clickOnScreen(View view, boolean longClick, int time) {\n\t\tif(view == null)\n\t\t\tAssert.fail(\"View is null and can therefore not be clicked!\");\n\n\t\tfloat[] xyToClick = getClickCoordinates(view);\n\t\tfloat x = xyToClick[0];\n\t\tfloat y = xyToClick[1];\n\n\t\tif(x == 0 || y == 0){\n\t\t\tsleeper.sleepMini();\n\t\t\ttry {\n\t\t\t\tview = viewFetcher.getIdenticalView(view);\n\t\t\t} catch (Exception ignored){}\n\n\t\t\tif(view != null){\n\t\t\t\txyToClick = getClickCoordinates(view);\n\t\t\t\tx = xyToClick[0];\n\t\t\t\ty = xyToClick[1];\n\t\t\t}\n\t\t}\n\n\t\tsleeper.sleep(300);\n\t\tif (longClick)\n\t\t\tclickLongOnScreen(x, y, time, view);\n\t\telse\n\t\t\tclickOnScreen(x, y, view);\n\t}\t\n\n\t/**\n\t * Returns click coordinates for the specified view.\n\t * \n\t * @param view the view to get click coordinates from\n\t * @return click coordinates for a specified view\n\t */\n\n\tprivate float[] getClickCoordinates(View view){\n\t\tint[] xyLocation = new int[2];\n\t\tfloat[] xyToClick = new float[2];\n\t\tint trialCount = 0;\n\n\t\tview.getLocationOnScreen(xyLocation);\n\t\twhile(xyLocation[0] == 0 && xyLocation[1] == 0 && trialCount < 10) {\n\t\t\tsleeper.sleep(300);\n\t\t\tview.getLocationOnScreen(xyLocation);\n\t\t\ttrialCount++;\n\t\t}\n\n\t\tfinal int viewWidth = view.getWidth();\n\t\tfinal int viewHeight = view.getHeight();\n\t\tfinal float x = xyLocation[0] + (viewWidth / 2.0f);\n\t\tfloat y = xyLocation[1] + (viewHeight / 2.0f);\n\n\t\txyToClick[0] = x;\n\t\txyToClick[1] = y;\n\n\t\treturn xyToClick;\n\t}\n\t\n\t\n\n\n\t/**\n\t * Long clicks on a specific {@link TextView} and then selects\n\t * an item from the context menu that appears. Will automatically scroll when needed.\n\t *\n\t * @param text the text that should be clicked on. The parameter will be interpreted as a regular expression.\n\t * @param index the index of the menu item that should be pressed\n\t */\n\n\tpublic void clickLongOnTextAndPress(String text, int index)\n\t{\n\t\tclickOnText(text, true, 0, true, 0);\n\t\tdialogUtils.waitForDialogToOpen(Timeout.getSmallTimeout(), true);\n\t\ttry{\n\t\t\tinst.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_DOWN);\n\t\t}catch(SecurityException e){\n\t\t\tAssert.fail(\"Can not press the context menu!\");\n\t\t}\n\t\tfor(int i = 0; i < index; i++)\n\t\t{\n\t\t\tsleeper.sleepMini();\n\t\t\tinst.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_DOWN);\n\t\t}\n\t\tinst.sendKeyDownUpSync(KeyEvent.KEYCODE_ENTER);\n\t}\n\n\t/**\n\t * Opens the menu and waits for it to open.\n\t */\n\n\tprivate void openMenu(){\n\t\tsleeper.sleepMini();\n\n\t\tif(!dialogUtils.waitForDialogToOpen(MINI_WAIT, false)) {\n\t\t\ttry{\n\t\t\t\tsender.sendKeyCode(KeyEvent.KEYCODE_MENU);\n\t\t\t\tdialogUtils.waitForDialogToOpen(WAIT_TIME, true);\n\t\t\t}catch(SecurityException e){\n\t\t\t\tAssert.fail(\"Can not open the menu!\");\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Clicks on a menu item with a given text.\n\t *\n\t * @param text the menu text that should be clicked on. The parameter will be interpreted as a regular expression.\n\t */\n\n\tpublic void clickOnMenuItem(String text)\n\t{\n\t\topenMenu();\n\t\tclickOnText(text, false, 1, true, 0);\n\t}\n\n\t/**\n\t * Clicks on a menu item with a given text.\n\t *\n\t * @param text the menu text that should be clicked on. The parameter will be interpreted as a regular expression.\n\t * @param subMenu true if the menu item could be located in a sub menu\n\t */\n\n\tpublic void clickOnMenuItem(String text, boolean subMenu)\n\t{\n\t\tsleeper.sleepMini();\n\n\t\tTextView textMore = null;\n\t\tint [] xy = new int[2];\n\t\tint x = 0;\n\t\tint y = 0;\n\n\t\tif(!dialogUtils.waitForDialogToOpen(MINI_WAIT, false)) {\n\t\t\ttry{\n\t\t\t\tsender.sendKeyCode(KeyEvent.KEYCODE_MENU);\n\t\t\t\tdialogUtils.waitForDialogToOpen(WAIT_TIME, true);\n\t\t\t}catch(SecurityException e){\n\t\t\t\tAssert.fail(\"Can not open the menu!\");\n\t\t\t}\n\t\t}\n\t\tboolean textShown = waiter.waitForText(text, 1, WAIT_TIME, true) != null;\n\n\t\tif(subMenu && (viewFetcher.getCurrentViews(TextView.class, true).size() > 5) && !textShown){\n\t\t\tfor(TextView textView : viewFetcher.getCurrentViews(TextView.class, true)){\n\t\t\t\tx = xy[0];\n\t\t\t\ty = xy[1];\n\t\t\t\ttextView.getLocationOnScreen(xy);\n\n\t\t\t\tif(xy[0] > x || xy[1] > y)\n\t\t\t\t\ttextMore = textView;\n\t\t\t}\n\t\t}\n\t\tif(textMore != null)\n\t\t\tclickOnScreen(textMore);\n\n\t\tclickOnText(text, false, 1, true, 0);\n\t}\n\n\t/**\n\t * Clicks on an ActionBar item with a given resource id\n\t *\n\t * @param resourceId the R.id of the ActionBar item\n\t */\n\n\tpublic void clickOnActionBarItem(int resourceId){\n\t\tsleeper.sleep();\n\t\tActivity activity = activityUtils.getCurrentActivity();\n\t\tif(activity != null){\n\t\t\tinst.invokeMenuActionSync(activity, resourceId, 0);\n\t\t}\n\t}\n\n\t/**\n\t * Clicks on an ActionBar Home/Up button.\n\t */\n\n\tpublic void clickOnActionBarHomeButton() {\n\t\tActivity activity = activityUtils.getCurrentActivity();\n\t\tMenuItem homeMenuItem = null;\n\n\t\ttry {\n\t\t\tClass cls = Class.forName(\"com.android.internal.view.menu.ActionMenuItem\");\n\t\t\tClass partypes[] = new Class[6];\n\t\t\tpartypes[0] = Context.class;\n\t\t\tpartypes[1] = Integer.TYPE;\n\t\t\tpartypes[2] = Integer.TYPE;\n\t\t\tpartypes[3] = Integer.TYPE;\n\t\t\tpartypes[4] = Integer.TYPE;\n\t\t\tpartypes[5] = CharSequence.class;\n\t\t\tConstructor ct = cls.getConstructor(partypes);\n\t\t\tObject argList[] = new Object[6];\n\t\t\targList[0] = activity;\n\t\t\targList[1] = 0;\n\t\t\targList[2] = android.R.id.home;\n\t\t\targList[3] = 0;\n\t\t\targList[4] = 0;\n\t\t\targList[5] = \"\";\n\t\t\thomeMenuItem = (MenuItem) ct.newInstance(argList);\n\t\t} catch (Exception ex) {\n\t\t\tLog.d(LOG_TAG, \"Can not find methods to invoke Home button!\");\n\t\t}\n\n\t\tif (homeMenuItem != null) {\n\t\t\ttry{\n\t\t\t\tactivity.getWindow().getCallback().onMenuItemSelected(Window.FEATURE_OPTIONS_PANEL, homeMenuItem);\n\t\t\t}catch(Exception ignored) {}\n\t\t}\n\t}\n\n\t/**\n\t * Clicks on a web element using the given By method.\n\t *\n\t * @param by the By object e.g. By.id(\"id\");\n\t * @param match if multiple objects match, this determines which one will be clicked\n\t * @param scroll true if scrolling should be performed\n\t * @param useJavaScriptToClick true if click should be perfomed through JavaScript\n\t */\n\n\tpublic void clickOnWebElement(By by, int match, boolean scroll, boolean useJavaScriptToClick){\n\t\tWebElement webElement = null;\n\t\t\n\t\tif(useJavaScriptToClick){\n\t\t\twebElement = waiter.waitForWebElement(by, match, Timeout.getSmallTimeout(), false);\n\t\t\tif(webElement == null){\n\t\t\t\tAssert.fail(\"WebElement with \" + webUtils.splitNameByUpperCase(by.getClass().getSimpleName()) + \": '\" + by.getValue() + \"' is not found!\");\n\t\t\t}\n\t\t\twebUtils.executeJavaScript(by, true);\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tWebElement webElementToClick = waiter.waitForWebElement(by, match, Timeout.getSmallTimeout(), scroll);\n\t\t\n\t\tif(webElementToClick == null){\n\t\t\tif(match > 1) {\n\t\t\t\tAssert.fail(match + \" WebElements with \" + webUtils.splitNameByUpperCase(by.getClass().getSimpleName()) + \": '\" + by.getValue() + \"' are not found!\");\n\t\t\t}\n\t\t\telse {\n\t\t\t\tAssert.fail(\"WebElement with \" + webUtils.splitNameByUpperCase(by.getClass().getSimpleName()) + \": '\" + by.getValue() + \"' is not found!\");\n\t\t\t}\n\t\t}\n\t\t\n\t\tclickOnScreen(webElementToClick.getLocationX(), webElementToClick.getLocationY(), null);\n\t}\n\n\n\t/**\n\t * Clicks on a specific {@link TextView} displaying a given text.\n\t *\n\t * @param regex the text that should be clicked on. The parameter will be interpreted as a regular expression.\n\t * @param longClick {@code true} if the click should be a long click\n\t * @param match the regex match that should be clicked on\n\t * @param scroll true if scrolling should be performed\n\t * @param time the amount of time to long click\n\t */\n\n\tpublic void clickOnText(String regex, boolean longClick, int match, boolean scroll, int time) {\n\t\tTextView textToClick = waiter.waitForText(regex, match, Timeout.getSmallTimeout(), scroll, true, false);\n\n\t\tif (textToClick != null) {\n\t\t\tclickOnScreen(textToClick, longClick, time);\n\t\t}\n\n\t\telse {\n\n\t\t\tif(match > 1){\n\t\t\t\tAssert.fail(match + \" matches of text string: '\" + regex + \"' are not found!\");\n\t\t\t}\n\n\t\t\telse{\n\t\t\t\tArrayList allTextViews = RobotiumUtils.removeInvisibleViews(viewFetcher.getCurrentViews(TextView.class, true));\n\t\t\t\tallTextViews.addAll((Collection) webUtils.getTextViewsFromWebView());\n\n\t\t\t\tfor (TextView textView : allTextViews) {\n\t\t\t\t\tLog.d(LOG_TAG, \"'\" + regex + \"' not found. Have found: '\" + textView.getText() + \"'\");\n\t\t\t\t}\n\t\t\t\tallTextViews = null;\n\t\t\t\tAssert.fail(\"Text string: '\" + regex + \"' is not found!\");\n\t\t\t}\n\t\t}\n\t}\n\n\n\t/**\n\t * Clicks on a {@code View} of a specific class, with a given text.\n\t *\n\t * @param viewClass what kind of {@code View} to click, e.g. {@code Button.class} or {@code TextView.class}\n\t * @param nameRegex the name of the view presented to the user. The parameter will be interpreted as a regular expression.\n\t */\n\n\tpublic void clickOn(Class viewClass, String nameRegex) {\n\t\tT viewToClick = (T) waiter.waitForText(viewClass, nameRegex, 0, Timeout.getSmallTimeout(), true, true, false);\n\n\t\tif (viewToClick != null) {\n\t\t\tclickOnScreen(viewToClick);\n\t\t} else {\n\t\t\tArrayList allTextViews = RobotiumUtils.removeInvisibleViews(viewFetcher.getCurrentViews(viewClass, true));\n\n\t\t\tfor (T view : allTextViews) {\n\t\t\t\tLog.d(LOG_TAG, \"'\" + nameRegex + \"' not found. Have found: '\" + view.getText() + \"'\");\n\t\t\t}\n\t\t\tAssert.fail(viewClass.getSimpleName() + \" with text: '\" + nameRegex + \"' is not found!\");\n\t\t}\n\t}\n\n\t/**\n\t * Clicks on a {@code View} of a specific class, with a certain index.\n\t *\n\t * @param viewClass what kind of {@code View} to click, e.g. {@code Button.class} or {@code ImageView.class}\n\t * @param index the index of the {@code View} to be clicked, within {@code View}s of the specified class\n\t */\n\n\tpublic void clickOn(Class viewClass, int index) {\n\t\tclickOnScreen(waiter.waitForAndGetView(index, viewClass));\n\t}\n\n\n\t/**\n\t * Clicks on a certain list line and returns the {@link TextView}s that\n\t * the list line is showing. Will use the first list it finds.\n\t *\n\t * @param line the line that should be clicked\n\t * @return a {@code List} of the {@code TextView}s located in the list line\n\t */\n\n\tpublic ArrayList clickInList(int line) {\n\t\treturn clickInList(line, 0, 0, false, 0);\n\t}\n\t\n\t/**\n\t * Clicks on a View with a specified resource id located in a specified list line\n\t *\n\t * @param line the line where the View is located\n\t * @param id the resource id of the View\n\t */\n\n\tpublic void clickInList(int line, int id) {\n\t\tclickInList(line, 0, id, false, 0);\n\t}\n\n\t/**\n\t * Clicks on a certain list line on a specified List and\n\t * returns the {@link TextView}s that the list line is showing.\n\t *\n\t * @param line the line that should be clicked\n\t * @param index the index of the list. E.g. Index 1 if two lists are available\n\t * @param id the resource id of the View to click\n\t * @return an {@code ArrayList} of the {@code TextView}s located in the list line\n\t */\n\n\tpublic ArrayList clickInList(int line, int index, int id, boolean longClick, int time) {\n\t\tfinal long endTime = SystemClock.uptimeMillis() + Timeout.getSmallTimeout();\n\n\t\tint lineIndex = line - 1;\n\t\tif(lineIndex < 0)\n\t\t\tlineIndex = 0;\n\n\t\tArrayList views = new ArrayList();\n\t\tfinal AbsListView absListView = waiter.waitForAndGetView(index, AbsListView.class);\n\n\t\tif(absListView == null)\n\t\t\tAssert.fail(\"AbsListView is null!\");\n\n\t\tfailIfIndexHigherThenChildCount(absListView, lineIndex, endTime);\n\n\t\tView viewOnLine = getViewOnAbsListLine(absListView, index, lineIndex);\n\n\t\tif(viewOnLine != null){\n\t\t\tviews = viewFetcher.getViews(viewOnLine, true);\n\t\t\tviews = RobotiumUtils.removeInvisibleViews(views);\n\n\t\t\tif(id == 0){\n\t\t\t\tclickOnScreen(viewOnLine, longClick, time);\n\t\t\t}\n\t\t\telse{\n\t\t\t\tclickOnScreen(getView(id, views));\n\t\t\t}\n\t\t}\n\t\treturn RobotiumUtils.filterViews(TextView.class, views);\n\t}\n\t\n\t/**\n\t * Clicks on a certain list line and returns the {@link TextView}s that\n\t * the list line is showing. Will use the first list it finds.\n\t *\n\t * @param line the line that should be clicked\n\t * @return a {@code List} of the {@code TextView}s located in the list line\n\t */\n\n\tpublic ArrayList clickInRecyclerView(int line) {\n\t\treturn clickInRecyclerView(line, 0, 0, false, 0);\n\t}\n\t\n\t/**\n\t * Clicks on a View with a specified resource id located in a specified RecyclerView itemIndex\n\t *\n\t * @param itemIndex the index where the View is located\n\t * @param id the resource id of the View\n\t */\n\n\tpublic void clickInRecyclerView(int itemIndex, int id) {\n\t\tclickInRecyclerView(itemIndex, 0, id, false, 0);\n\t}\n\n\t\n\t/**\n\t * Clicks on a certain list line on a specified List and\n\t * returns the {@link TextView}s that the list line is showing.\n\t *\n\t * @param itemIndex the item index that should be clicked\n\t * @param recyclerViewIndex the index of the RecyclerView. E.g. Index 1 if two RecyclerViews are available\n\t * @param id the resource id of the View to click\n\t * @return an {@code ArrayList} of the {@code TextView}s located in the list line\n\t */\n\n\tpublic ArrayList clickInRecyclerView(int itemIndex, int recyclerViewIndex, int id, boolean longClick, int time) {\n\t\tView viewOnLine = null;\n\t\tfinal long endTime = SystemClock.uptimeMillis() + Timeout.getSmallTimeout();\n\n\t\tif(itemIndex < 0)\n\t\t\titemIndex = 0;\n\n\t\tArrayList views = new ArrayList();\n\t\tViewGroup recyclerView = viewFetcher.getRecyclerView(recyclerViewIndex, Timeout.getSmallTimeout());\n\t\t\n\t\tif(recyclerView == null){\n\t\t\tAssert.fail(\"RecyclerView is not found!\");\n\t\t}\n\t\telse{\n\t\t\tfailIfIndexHigherThenChildCount(recyclerView, itemIndex, endTime);\n\t\t\tviewOnLine = getViewOnRecyclerItemIndex((ViewGroup) recyclerView, recyclerViewIndex, itemIndex);\n\t\t}\n\t\t\n\t\tif(viewOnLine != null){\n\t\t\tviews = viewFetcher.getViews(viewOnLine, true);\n\t\t\tviews = RobotiumUtils.removeInvisibleViews(views);\n\t\t\t\n\t\t\tif(id == 0){\n\t\t\t\tclickOnScreen(viewOnLine, longClick, time);\n\t\t\t}\n\t\t\telse{\n\t\t\t\tclickOnScreen(getView(id, views));\n\t\t\t}\n\t\t}\n\t\treturn RobotiumUtils.filterViews(TextView.class, views);\n\t}\n\t\n\tprivate View getView(int id, List views){\n\t\tfor(View view : views){\n\t\t\tif(id == view.getId()){\n\t\t\t\treturn view;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\t\n\tprivate void failIfIndexHigherThenChildCount(ViewGroup viewGroup, int index, long endTime){\n\t\twhile(index > viewGroup.getChildCount()){\n\t\t\tfinal boolean timedOut = SystemClock.uptimeMillis() > endTime;\n\t\t\tif (timedOut){\n\t\t\t\tint numberOfIndexes = viewGroup.getChildCount();\n\t\t\t\tAssert.fail(\"Can not click on index \" + index + \" as there are only \" + numberOfIndexes + \" indexes available\");\n\t\t\t}\n\t\t\tsleeper.sleep();\n\t\t}\n\t}\n\t\n\n\t/**\n\t * Returns the view in the specified list line\n\t * \n\t * @param absListView the ListView to use\n\t * @param index the index of the list. E.g. Index 1 if two lists are available\n\t * @param lineIndex the line index of the View\n\t * @return the View located at a specified list line\n\t */\n\n\tprivate View getViewOnAbsListLine(AbsListView absListView, int index, int lineIndex){\n\t\tfinal long endTime = SystemClock.uptimeMillis() + Timeout.getSmallTimeout();\n\t\tView view = absListView.getChildAt(lineIndex);\n\n\t\twhile(view == null){\n\t\t\tfinal boolean timedOut = SystemClock.uptimeMillis() > endTime;\n\t\t\tif (timedOut){\n\t\t\t\tAssert.fail(\"View is null and can therefore not be clicked!\");\n\t\t\t}\n\t\t\t\n\t\t\tsleeper.sleep();\n\t\t\tabsListView = (AbsListView) viewFetcher.getIdenticalView(absListView);\n\n\t\t\tif(absListView == null){\n\t\t\t\tabsListView = waiter.waitForAndGetView(index, AbsListView.class);\n\t\t\t}\n\t\t\t\n\t\t\tview = absListView.getChildAt(lineIndex);\n\t\t}\n\t\treturn view;\n\t}\n\t\n\t/**\n\t * Returns the view in the specified item index\n\t * \n\t * @param recyclerView the RecyclerView to use\n\t * @param itemIndex the item index of the View\n\t * @return the View located at a specified item index\n\t */\n\n\tprivate View getViewOnRecyclerItemIndex(ViewGroup recyclerView, int recyclerViewIndex, int itemIndex){\n\t\tfinal long endTime = SystemClock.uptimeMillis() + Timeout.getSmallTimeout();\n\t\tView view = recyclerView.getChildAt(itemIndex);\n\n\t\twhile(view == null){\n\t\t\tfinal boolean timedOut = SystemClock.uptimeMillis() > endTime;\n\t\t\tif (timedOut){\n\t\t\t\tAssert.fail(\"View is null and can therefore not be clicked!\");\n\t\t\t}\n\n\t\t\tsleeper.sleep();\n\t\t\trecyclerView = (ViewGroup) viewFetcher.getIdenticalView(recyclerView);\n\n\t\t\tif(recyclerView == null){\n\t\t\t\trecyclerView = (ViewGroup) viewFetcher.getRecyclerView(false, recyclerViewIndex);\n\t\t\t}\n\n\t\t\tif(recyclerView != null){\n\t\t\t\tview = recyclerView.getChildAt(itemIndex);\n\t\t\t}\n\t\t}\n\t\treturn view;\n\t}\n\t\n\t\n}\n"}} -{"repo": "ivanacostarubio/bartender", "pr_number": 2, "title": "1140 Grid added", "state": "closed", "merged_at": "2012-09-13T23:37:06Z", "additions": 1373, "deletions": 47, "files_changed": ["app.rb", "public/js/css3-mediaqueries.js", "public/stylesheets/1140.css", "public/stylesheets/grid-styles.css", "public/stylesheets/ie.css", "public/stylesheets/styles.css"], "files_before": {"app.rb": "require 'rubygems'\nrequire 'sinatra/base'\nrequire 'slim'\nrequire 'sass'\nrequire 'mongoid'\n\nMongoid.load!(\"config/mongoid.yml\")\n\nSlim::Engine.set_default_options :sections => false\n\nclass App < Sinatra::Base\n\n set :public, File.join(File.dirname(__FILE__), 'public')\n set :views, File.join(File.dirname(__FILE__), 'views')\n\n helpers do\n def partial(page, options={})\n haml page, options.merge!(:layout => false)\n end\n end\n\n\n get('/') do \n slim :index\n end\n\n get('/styles') do \n slim :styles\n end\n\nend\n", "public/stylesheets/styles.css": "/*\nSyntax error: Invalid CSS after \"...nge: background\": expected selector or at-rule, was \": $orange; /* f...\"\n on line 11 of public/stylesheets/styles.scss\n\n6: $vine: #ac3900;\n7: $white: #ffffff;\n8: $black: #000000;\n9: $lightgrey: #e6e5e5;\n10: $textgrey: #959494;\n11: $gradientorange: background: $orange; /* for non-css3 browsers */\n12: filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='$orange', endColorstr='$orangered'); /* for IE */\n13: background: -webkit-gradient(linear, left top, left bottom, from($orange), to($orangered)); /* for webkit browsers */\n14: background: -moz-linear-gradient(top, $orange, $orangered); /* for firefox 3.6+ */ \n15: ;\n16: \n\nBacktrace:\npublic/stylesheets/styles.scss:11\n/Users/bellatrix/.rvm/gems/ruby-1.9.3-p0@bartender/gems/sass-3.2.1/lib/sass/scss/parser.rb:1130:in `expected'\n/Users/bellatrix/.rvm/gems/ruby-1.9.3-p0@bartender/gems/sass-3.2.1/lib/sass/scss/parser.rb:1066:in `expected'\n/Users/bellatrix/.rvm/gems/ruby-1.9.3-p0@bartender/gems/sass-3.2.1/lib/sass/scss/parser.rb:28:in `parse'\n/Users/bellatrix/.rvm/gems/ruby-1.9.3-p0@bartender/gems/sass-3.2.1/lib/sass/engine.rb:342:in `_to_tree'\n/Users/bellatrix/.rvm/gems/ruby-1.9.3-p0@bartender/gems/sass-3.2.1/lib/sass/engine.rb:315:in `_render'\n/Users/bellatrix/.rvm/gems/ruby-1.9.3-p0@bartender/gems/sass-3.2.1/lib/sass/engine.rb:262:in `render'\n/Users/bellatrix/.rvm/gems/ruby-1.9.3-p0@bartender/gems/sass-3.2.1/lib/sass/plugin/compiler.rb:340:in `update_stylesheet'\n/Users/bellatrix/.rvm/gems/ruby-1.9.3-p0@bartender/gems/sass-3.2.1/lib/sass/plugin/compiler.rb:202:in `block in update_stylesheets'\n/Users/bellatrix/.rvm/gems/ruby-1.9.3-p0@bartender/gems/sass-3.2.1/lib/sass/plugin/compiler.rb:200:in `each'\n/Users/bellatrix/.rvm/gems/ruby-1.9.3-p0@bartender/gems/sass-3.2.1/lib/sass/plugin/compiler.rb:200:in `update_stylesheets'\n/Users/bellatrix/.rvm/gems/ruby-1.9.3-p0@bartender/gems/sass-3.2.1/lib/sass/plugin/compiler.rb:298:in `block in watch'\n/Users/bellatrix/.rvm/gems/ruby-1.9.3-p0@bartender/gems/sass-3.2.1/vendor/listen/lib/listen/multi_listener.rb:86:in `call'\n/Users/bellatrix/.rvm/gems/ruby-1.9.3-p0@bartender/gems/sass-3.2.1/vendor/listen/lib/listen/multi_listener.rb:86:in `on_change'\n/Users/bellatrix/.rvm/gems/ruby-1.9.3-p0@bartender/gems/sass-3.2.1/vendor/listen/lib/listen/multi_listener.rb:95:in `block in initialize_adapter'\n/Users/bellatrix/.rvm/gems/ruby-1.9.3-p0@bartender/gems/sass-3.2.1/vendor/listen/lib/listen/adapters/polling.rb:55:in `call'\n/Users/bellatrix/.rvm/gems/ruby-1.9.3-p0@bartender/gems/sass-3.2.1/vendor/listen/lib/listen/adapters/polling.rb:55:in `poll'\n/Users/bellatrix/.rvm/gems/ruby-1.9.3-p0@bartender/gems/sass-3.2.1/vendor/listen/lib/listen/adapters/polling.rb:31:in `block in start'\n*/\nbody:before {\n white-space: pre;\n font-family: monospace;\n content: \"Syntax error: Invalid CSS after \\\"...nge: background\\\": expected selector or at-rule, was \\\": $orange; /* f...\\\"\\A on line 11 of public/stylesheets/styles.scss\\A \\A 6: $vine: #ac3900;\\A 7: $white: #ffffff;\\A 8: $black: #000000;\\A 9: $lightgrey: #e6e5e5;\\A 10: $textgrey: #959494;\\A 11: $gradientorange: background: $orange; /* for non-css3 browsers */\\A 12: filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='$orange', endColorstr='$orangered'); /* for IE */\\A 13: background: -webkit-gradient(linear, left top, left bottom, from($orange), to($orangered)); /* for webkit browsers */\\A 14: background: -moz-linear-gradient(top, $orange, $orangered); /* for firefox 3.6+ */ \\A 15: ;\\A 16: \"; }\n"}, "files_after": {"app.rb": "require 'rubygems'\nrequire 'sinatra/base'\nrequire 'slim'\nrequire 'sass'\nrequire 'mongoid'\n\nMongoid.load!(\"config/mongoid.yml\")\n\nSlim::Engine.set_default_options :sections => false\n\nclass App < Sinatra::Base\n\n set :public, File.join(File.dirname(__FILE__), 'public')\n set :views, File.join(File.dirname(__FILE__), 'views')\n\n helpers do\n def partial(page, options={})\n haml page, options.merge!(:layout => false)\n end\n end\n\n\n get('/') do \n slim :index\n end\n\n get('/styles') do \n slim :styles\n end\n \n get('/grid') do \n slim :grid\n end\n \n\nend\n", "public/js/css3-mediaqueries.js": "if(typeof Object.create!==\"function\"){\nObject.create=function(o){\nfunction F(){\n};\nF.prototype=o;\nreturn new F();\n};\n}\nvar ua={toString:function(){\nreturn navigator.userAgent;\n},test:function(s){\nreturn this.toString().toLowerCase().indexOf(s.toLowerCase())>-1;\n}};\nua.version=(ua.toString().toLowerCase().match(/[\\s\\S]+(?:rv|it|ra|ie)[\\/: ]([\\d.]+)/)||[])[1];\nua.webkit=ua.test(\"webkit\");\nua.gecko=ua.test(\"gecko\")&&!ua.webkit;\nua.opera=ua.test(\"opera\");\nua.ie=ua.test(\"msie\")&&!ua.opera;\nua.ie6=ua.ie&&document.compatMode&&typeof document.documentElement.style.maxHeight===\"undefined\";\nua.ie7=ua.ie&&document.documentElement&&typeof document.documentElement.style.maxHeight!==\"undefined\"&&typeof XDomainRequest===\"undefined\";\nua.ie8=ua.ie&&typeof XDomainRequest!==\"undefined\";\nvar domReady=function(){\nvar _1=[];\nvar _2=function(){\nif(!arguments.callee.done){\narguments.callee.done=true;\nfor(var i=0;i<_1.length;i++){\n_1[i]();\n}\n}\n};\nif(document.addEventListener){\ndocument.addEventListener(\"DOMContentLoaded\",_2,false);\n}\nif(ua.ie){\n(function(){\ntry{\ndocument.documentElement.doScroll(\"left\");\n}\ncatch(e){\nsetTimeout(arguments.callee,50);\nreturn;\n}\n_2();\n})();\ndocument.onreadystatechange=function(){\nif(document.readyState===\"complete\"){\ndocument.onreadystatechange=null;\n_2();\n}\n};\n}\nif(ua.webkit&&document.readyState){\n(function(){\nif(document.readyState!==\"loading\"){\n_2();\n}else{\nsetTimeout(arguments.callee,10);\n}\n})();\n}\nwindow.onload=_2;\nreturn function(fn){\nif(typeof fn===\"function\"){\n_1[_1.length]=fn;\n}\nreturn fn;\n};\n}();\nvar cssHelper=function(){\nvar _3={BLOCKS:/[^\\s{][^{]*\\{(?:[^{}]*\\{[^{}]*\\}[^{}]*|[^{}]*)*\\}/g,BLOCKS_INSIDE:/[^\\s{][^{]*\\{[^{}]*\\}/g,DECLARATIONS:/[a-zA-Z\\-]+[^;]*:[^;]+;/g,RELATIVE_URLS:/url\\(['\"]?([^\\/\\)'\"][^:\\)'\"]+)['\"]?\\)/g,REDUNDANT_COMPONENTS:/(?:\\/\\*([^*\\\\\\\\]|\\*(?!\\/))+\\*\\/|@import[^;]+;)/g,REDUNDANT_WHITESPACE:/\\s*(,|:|;|\\{|\\})\\s*/g,MORE_WHITESPACE:/\\s{2,}/g,FINAL_SEMICOLONS:/;\\}/g,NOT_WHITESPACE:/\\S+/g};\nvar _4,_5=false;\nvar _6=[];\nvar _7=function(fn){\nif(typeof fn===\"function\"){\n_6[_6.length]=fn;\n}\n};\nvar _8=function(){\nfor(var i=0;i<_6.length;i++){\n_6[i](_4);\n}\n};\nvar _9={};\nvar _a=function(n,v){\nif(_9[n]){\nvar _b=_9[n].listeners;\nif(_b){\nfor(var i=0;i<_b.length;i++){\n_b[i](v);\n}\n}\n}\n};\nvar _c=function(_d,_e,_f){\nif(ua.ie&&!window.XMLHttpRequest){\nwindow.XMLHttpRequest=function(){\nreturn new ActiveXObject(\"Microsoft.XMLHTTP\");\n};\n}\nif(!XMLHttpRequest){\nreturn \"\";\n}\nvar r=new XMLHttpRequest();\ntry{\nr.open(\"get\",_d,true);\nr.setRequestHeader(\"X_REQUESTED_WITH\",\"XMLHttpRequest\");\n}\ncatch(e){\n_f();\nreturn;\n}\nvar _10=false;\nsetTimeout(function(){\n_10=true;\n},5000);\ndocument.documentElement.style.cursor=\"progress\";\nr.onreadystatechange=function(){\nif(r.readyState===4&&!_10){\nif(!r.status&&location.protocol===\"file:\"||(r.status>=200&&r.status<300)||r.status===304||navigator.userAgent.indexOf(\"Safari\")>-1&&typeof r.status===\"undefined\"){\n_e(r.responseText);\n}else{\n_f();\n}\ndocument.documentElement.style.cursor=\"\";\nr=null;\n}\n};\nr.send(\"\");\n};\nvar _11=function(_12){\n_12=_12.replace(_3.REDUNDANT_COMPONENTS,\"\");\n_12=_12.replace(_3.REDUNDANT_WHITESPACE,\"$1\");\n_12=_12.replace(_3.MORE_WHITESPACE,\" \");\n_12=_12.replace(_3.FINAL_SEMICOLONS,\"}\");\nreturn _12;\n};\nvar _13={mediaQueryList:function(s){\nvar o={};\nvar idx=s.indexOf(\"{\");\nvar lt=s.substring(0,idx);\ns=s.substring(idx+1,s.length-1);\nvar mqs=[],rs=[];\nvar qts=lt.toLowerCase().substring(7).split(\",\");\nfor(var i=0;i-1&&_23.href&&_23.href.length!==0&&!_23.disabled){\n_1f[_1f.length]=_23;\n}\n}\nif(_1f.length>0){\nvar c=0;\nvar _24=function(){\nc++;\nif(c===_1f.length){\n_20();\n}\n};\nvar _25=function(_26){\nvar _27=_26.href;\n_c(_27,function(_28){\n_28=_11(_28).replace(_3.RELATIVE_URLS,\"url(\"+_27.substring(0,_27.lastIndexOf(\"/\"))+\"/$1)\");\n_26.cssHelperText=_28;\n_24();\n},_24);\n};\nfor(i=0;i<_1f.length;i++){\n_25(_1f[i]);\n}\n}else{\n_20();\n}\n};\nvar _29={mediaQueryLists:\"array\",rules:\"array\",selectors:\"object\",declarations:\"array\",properties:\"object\"};\nvar _2a={mediaQueryLists:null,rules:null,selectors:null,declarations:null,properties:null};\nvar _2b=function(_2c,v){\nif(_2a[_2c]!==null){\nif(_29[_2c]===\"array\"){\nreturn (_2a[_2c]=_2a[_2c].concat(v));\n}else{\nvar c=_2a[_2c];\nfor(var n in v){\nif(v.hasOwnProperty(n)){\nif(!c[n]){\nc[n]=v[n];\n}else{\nc[n]=c[n].concat(v[n]);\n}\n}\n}\nreturn c;\n}\n}\n};\nvar _2d=function(_2e){\n_2a[_2e]=(_29[_2e]===\"array\")?[]:{};\nfor(var i=0;i<_4.length;i++){\n_2b(_2e,_4[i].cssHelperParsed[_2e]);\n}\nreturn _2a[_2e];\n};\ndomReady(function(){\nvar els=document.body.getElementsByTagName(\"*\");\nfor(var i=0;i=_44)||(max&&_46<_44)||(!min&&!max&&_46===_44));\n}else{\nreturn false;\n}\n}else{\nreturn _46>0;\n}\n}else{\nif(\"device-height\"===_41.substring(l-13,l)){\n_47=screen.height;\nif(_42!==null){\nif(_43===\"length\"){\nreturn ((min&&_47>=_44)||(max&&_47<_44)||(!min&&!max&&_47===_44));\n}else{\nreturn false;\n}\n}else{\nreturn _47>0;\n}\n}else{\nif(\"width\"===_41.substring(l-5,l)){\n_46=document.documentElement.clientWidth||document.body.clientWidth;\nif(_42!==null){\nif(_43===\"length\"){\nreturn ((min&&_46>=_44)||(max&&_46<_44)||(!min&&!max&&_46===_44));\n}else{\nreturn false;\n}\n}else{\nreturn _46>0;\n}\n}else{\nif(\"height\"===_41.substring(l-6,l)){\n_47=document.documentElement.clientHeight||document.body.clientHeight;\nif(_42!==null){\nif(_43===\"length\"){\nreturn ((min&&_47>=_44)||(max&&_47<_44)||(!min&&!max&&_47===_44));\n}else{\nreturn false;\n}\n}else{\nreturn _47>0;\n}\n}else{\nif(\"device-aspect-ratio\"===_41.substring(l-19,l)){\nreturn _43===\"aspect-ratio\"&&screen.width*_44[1]===screen.height*_44[0];\n}else{\nif(\"color-index\"===_41.substring(l-11,l)){\nvar _48=Math.pow(2,screen.colorDepth);\nif(_42!==null){\nif(_43===\"absolute\"){\nreturn ((min&&_48>=_44)||(max&&_48<_44)||(!min&&!max&&_48===_44));\n}else{\nreturn false;\n}\n}else{\nreturn _48>0;\n}\n}else{\nif(\"color\"===_41.substring(l-5,l)){\nvar _49=screen.colorDepth;\nif(_42!==null){\nif(_43===\"absolute\"){\nreturn ((min&&_49>=_44)||(max&&_49<_44)||(!min&&!max&&_49===_44));\n}else{\nreturn false;\n}\n}else{\nreturn _49>0;\n}\n}else{\nif(\"resolution\"===_41.substring(l-10,l)){\nvar res;\nif(_45===\"dpcm\"){\nres=_3d(\"1cm\");\n}else{\nres=_3d(\"1in\");\n}\nif(_42!==null){\nif(_43===\"resolution\"){\nreturn ((min&&res>=_44)||(max&&res<_44)||(!min&&!max&&res===_44));\n}else{\nreturn false;\n}\n}else{\nreturn res>0;\n}\n}else{\nreturn false;\n}\n}\n}\n}\n}\n}\n}\n}\n};\nvar _4a=function(mq){\nvar _4b=mq.getValid();\nvar _4c=mq.getExpressions();\nvar l=_4c.length;\nif(l>0){\nfor(var i=0;i0){\ns[c++]=\",\";\n}\ns[c++]=n;\n}\n}\nif(s.length>0){\n_39[_39.length]=cssHelper.addStyle(\"@media \"+s.join(\"\")+\"{\"+mql.getCssText()+\"}\",false);\n}\n};\nvar _4e=function(_4f){\nfor(var i=0;i<_4f.length;i++){\n_4d(_4f[i]);\n}\nif(ua.ie){\ndocument.documentElement.style.display=\"block\";\nsetTimeout(function(){\ndocument.documentElement.style.display=\"\";\n},0);\nsetTimeout(function(){\ncssHelper.broadcast(\"cssMediaQueriesTested\");\n},100);\n}else{\ncssHelper.broadcast(\"cssMediaQueriesTested\");\n}\n};\nvar _50=function(){\nfor(var i=0;i<_39.length;i++){\ncssHelper.removeStyle(_39[i]);\n}\n_39=[];\ncssHelper.mediaQueryLists(_4e);\n};\nvar _51=0;\nvar _52=function(){\nvar _53=cssHelper.getViewportWidth();\nvar _54=cssHelper.getViewportHeight();\nif(ua.ie){\nvar el=document.createElement(\"div\");\nel.style.position=\"absolute\";\nel.style.top=\"-9999em\";\nel.style.overflow=\"scroll\";\ndocument.body.appendChild(el);\n_51=el.offsetWidth-el.clientWidth;\ndocument.body.removeChild(el);\n}\nvar _55;\nvar _56=function(){\nvar vpw=cssHelper.getViewportWidth();\nvar vph=cssHelper.getViewportHeight();\nif(Math.abs(vpw-_53)>_51||Math.abs(vph-_54)>_51){\n_53=vpw;\n_54=vph;\nclearTimeout(_55);\n_55=setTimeout(function(){\nif(!_3a()){\n_50();\n}else{\ncssHelper.broadcast(\"cssMediaQueriesTested\");\n}\n},500);\n}\n};\nwindow.onresize=function(){\nvar x=window.onresize||function(){\n};\nreturn function(){\nx();\n_56();\n};\n}();\n};\nvar _57=document.documentElement;\n_57.style.marginLeft=\"-32767px\";\nsetTimeout(function(){\n_57.style.marginTop=\"\";\n},20000);\nreturn function(){\nif(!_3a()){\ncssHelper.addListener(\"newStyleParsed\",function(el){\n_4e(el.cssHelperParsed.mediaQueryLists);\n});\ncssHelper.addListener(\"cssMediaQueriesTested\",function(){\nif(ua.ie){\n_57.style.width=\"1px\";\n}\nsetTimeout(function(){\n_57.style.width=\"\";\n_57.style.marginLeft=\"\";\n},0);\ncssHelper.removeListener(\"cssMediaQueriesTested\",arguments.callee);\n});\n_3c();\n_50();\n}else{\n_57.style.marginLeft=\"\";\n}\n_52();\n};\n}());\ntry{\ndocument.execCommand(\"BackgroundImageCache\",false,true);\n}\ncatch(e){\n}\n\r\n", "public/stylesheets/1140.css": "/* CSS Resets */\n\nhtml,body,div,span,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,address,cite,code,del,dfn,em,img,ins,q,small,strong,sub,sup,dl,dt,dd,ol,ul,li,fieldset,form,label,legend,table,caption,tbody,tfoot,thead,tr,th,td{border:0;margin:0;padding:0}article,aside,figure,figure img,figcaption,hgroup,footer,header,nav,section,video,object{display:block}a img{border:0}figure{position:relative}figure img{width:100%}\n\n\n/* ==================================================================================================================== */\n/* ! The 1140px Grid V2 by Andy Taylor \\ http://cssgrid.net \\ http://www.twitter.com/andytlr \\ http://www.andytlr.com */\n/* ==================================================================================================================== */\n\n.container {\npadding-left: 20px;\npadding-right: 20px;\n}\n\n.row {\nwidth: 100%;\nmax-width: 1140px;\nmin-width: 755px;\nmargin: 0 auto;\noverflow: hidden;\n}\n\n.onecol, .twocol, .threecol, .fourcol, .fivecol, .sixcol, .sevencol, .eightcol, .ninecol, .tencol, .elevencol {\nmargin-right: 3.8%;\nfloat: left;\nmin-height: 1px;\n}\n\n.row .onecol {\nwidth: 4.85%;\n}\n\n.row .twocol {\nwidth: 13.45%;\n}\n\n.row .threecol {\nwidth: 22.05%;\n}\n\n.row .fourcol {\nwidth: 30.75%;\n}\n\n.row .fivecol {\nwidth: 39.45%;\n}\n\n.row .sixcol {\nwidth: 48%;\n}\n\n.row .sevencol {\nwidth: 56.75%;\n}\n\n.row .eightcol {\nwidth: 65.4%;\n}\n\n.row .ninecol {\nwidth: 74.05%;\n}\n\n.row .tencol {\nwidth: 82.7%;\n}\n\n.row .elevencol {\nwidth: 91.35%;\n}\n\n.row .twelvecol {\nwidth: 100%;\nfloat: left;\n}\n\n.last {\nmargin-right: 0px;\n}\n\nimg, object, embed {\nmax-width: 100%;\n}\n\nimg {\n\theight: auto;\n}\n\n\n/* Smaller screens */\n\n@media only screen and (max-width: 1023px) {\n\n\tbody {\n\tfont-size: 0.8em;\n\tline-height: 1.5em;\n\t}\n\t\n\t}\n\n\n/* Mobile */\n\n@media handheld, only screen and (max-width: 767px) {\n\n\tbody {\n\tfont-size: 16px;\n\t-webkit-text-size-adjust: none;\n\t}\n\t\n\t.row, body, .container {\n\twidth: 100%;\n\tmin-width: 0;\n\tmargin-left: 0px;\n\tmargin-right: 0px;\n\tpadding-left: 0px;\n\tpadding-right: 0px;\n\t}\n\t\n\t.row .onecol, .row .twocol, .row .threecol, .row .fourcol, .row .fivecol, .row .sixcol, .row .sevencol, .row .eightcol, .row .ninecol, .row .tencol, .row .elevencol, .row .twelvecol {\n\twidth: auto;\n\tfloat: none;\n\tmargin-left: 0px;\n\tmargin-right: 0px;\n\tpadding-left: 20px;\n\tpadding-right: 20px;\n\t}\n\n}", "public/stylesheets/grid-styles.css": "/* ============================== */\n/* ! Layout for desktop version */\n/* ============================== */\n\n\tbody {\n\t\t\n\t}\n\t\n\n/* ============================= */\n/* ! Layout for mobile version */\n/* ============================= */\n\n@media handheld, only screen and (max-width: 767px) {\n\n\tbody {\n\t\t\n\t}\n\n}\n\n\n/* ========================================== */\n/* ! Provide higher res assets for iPhone 4 */\n/* ========================================== */\n\n@media only screen and (-webkit-min-device-pixel-ratio: 2) { \n\n/*\t.logo {\n\t\tbackground: url(logo2x.jpg) no-repeat;\n\t\tbackground-size: 212px 303px;\n\t}*/\n\n}", "public/stylesheets/ie.css": ".onecol {\nwidth: 4.7%;\n}\n\n.twocol {\nwidth: 13.2%;\n}\n\n.threecol {\nwidth: 22.05%;\n}\n\n.fourcol {\nwidth: 30.6%;\n}\n\n.fivecol {\nwidth: 39%;\n}\n\n.sixcol {\nwidth: 48%;\n}\n\n.sevencol {\nwidth: 56.75%;\n}\n\n.eightcol {\nwidth: 61.6%;\n}\n\n.ninecol {\nwidth: 74.05%;\n}\n\n.tencol {\nwidth: 82%;\n}\n\n.elevencol {\nwidth: 91.35%;\n}", "public/stylesheets/styles.css": ".clear {\n clear: both; }\n\n#wrapper {\n width: 1024px;\n margin: 50px auto; }\n\nhr {\n border-bottom: #e6e5e5;\n opacity: 0.3; }\n\nh1, h2, h3, h4, p, a, li {\n font-family: \"HelveticaNeue-Light\", \"Helvetica Neue Light\", \"Helvetica Neue\", Helvetica, Arial, \"Lucida Grande\", sans-serif;\n font-weight: 100;\n color: #282827; }\n\nh1 {\n font-size: 6em;\n letter-spacing: -6px;\n line-height: 0.95em;\n margin: 10px 0;\n color: black; }\n\nh2 {\n font-size: 4em;\n letter-spacing: -4px;\n line-height: 0.85em; }\n\nh3 {\n font-size: 3em;\n letter-spacing: -3px;\n line-height: 0.85em;\n margin: 10px 0 20px 0; }\n\nh4 {\n font-size: 2em;\n letter-spacing: -0.5px;\n line-height: 0.85em;\n margin: 10px 0 20px 0; }\n\np, a, li {\n font-size: 1.2em; }\n\na {\n color: #fc5401; }\n a:hover {\n color: #282827; }\n\nli {\n line-height: 30px; }\n\n.button.orange {\n border: 1px solid #fc5401;\n -webkit-border-radius: 4px;\n border-radius: 4px;\n float: left;\n color: white;\n padding: 10px 20px;\n box-shadow: 0 3px 2px -2px gray;\n margin: 20px 0;\n background: #e37600;\n /* for non-css3 browsers */\n filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#e37600', endColorstr='#fc5401');\n /* for IE */\n background: -webkit-gradient(linear, left top, left bottom, from(#e37600), to(#fc5401));\n /* for webkit browsers */\n background: -moz-linear-gradient(top, #e37600, #fc5401);\n /* for firefox 3.6+ */\n border: 1px solid #fc5401; }\n .button.orange a {\n text-decoration: none; }\n .button.orange p {\n margin: 0;\n font-size: 1em;\n color: white; }\n .button.orange:hover {\n background: #fc5401;\n /* for non-css3 browsers */\n filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fc5401', endColorstr='#e37600');\n /* for IE */\n background: -webkit-gradient(linear, left top, left bottom, from(#fc5401), to(#e37600));\n /* for webkit browsers */\n background: -moz-linear-gradient(top, #fc5401, #e37600);\n /* for firefox 3.6+ */\n border: 1px solid #fc5401; }\n\n.title {\n width: 100%;\n border-bottom: 3px solid black;\n margin: 0 0 40px 0; }\n\n.twocolumn {\n width: 50%;\n float: left;\n margin: 0 0 50px 0; }\n\nform {\n width: 100%;\n padding: 10px;\n background: white;\n /* for non-css3 browsers */\n filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='$white', endColorstr='$lightgrey');\n /* for IE */\n background: -webkit-gradient(linear, left top, left bottom, from(white), to(#e6e5e5));\n /* for webkit browsers */\n background: -moz-linear-gradient(top, white, #e6e5e5);\n /* for firefox 3.6+ */\n border: 1px solid #e6e5e5;\n position: relative;\n margin: 20px 0 50px 0; }\n\nform:before, form:after {\n content: \"\";\n position: absolute;\n z-index: -1;\n bottom: 8px;\n left: 10px;\n width: 60%;\n height: 20%;\n max-width: 300px;\n -webkit-box-shadow: 0 10px 10px rgba(0, 0, 0, 0.5);\n -moz-box-shadow: 0 10px 10px rgba(0, 0, 0, 0.5);\n box-shadow: 0 10px 10px rgba(0, 0, 0, 0.5);\n -webkit-transform: rotate(-3deg);\n -moz-transform: rotate(-3deg);\n -o-transform: rotate(-3deg);\n transform: rotate(-3deg); }\n\nform:after {\n right: 10px;\n left: auto;\n -webkit-transform: rotate(3deg);\n -moz-transform: rotate(3deg);\n -o-transform: rotate(3deg);\n transform: rotate(3deg); }\n\ninput, textarea, select {\n width: 95%;\n border: 1px solid #e6e5e5;\n height: 35px;\n padding: 5px 10px;\n margin: 0 0 10px 0;\n font-family: \"HelveticaNeue-Light\", \"Helvetica Neue Light\", \"Helvetica Neue\", Helvetica, Arial, \"Lucida Grande\", sans-serif;\n font-size: 18px;\n color: #959494; }\n\nselect {\n width: 99%;\n height: 40px;\n font-size: 1.2em; }\n\ntextarea {\n height: 100px; }\n\nlabel.label_input {\n width: 95%;\n position: absolute;\n top: 1px;\n right: 1px;\n bottom: 1px;\n left: 2px;\n z-index: 1;\n padding: 13px 3px 13px 10px;\n line-height: 20px;\n white-space: nowrap;\n cursor: text;\n display: block;\n font-size: 1.1em;\n font-family: \"HelveticaNeue-Light\", \"Helvetica Neue Light\", \"Helvetica Neue\", Helvetica, Arial, \"Lucida Grande\", sans-serif;\n color: #959494; }\n\nlabel {\n font-size: 1.2em;\n font-family: \"HelveticaNeue-Light\", \"Helvetica Neue Light\", \"Helvetica Neue\", Helvetica, Arial, \"Lucida Grande\", sans-serif;\n color: #959494;\n float: left; }\n\n.input-placeholder {\n position: relative; }\n\n.button.orange.send {\n width: 30%;\n margin: 10px 0 10px 150px;\n line-height: 0;\n letter-spacing: 0; }\n\n.boxui.header, .boxui.box {\n width: 100%;\n -webkit-border-radius: 4px 4px 0 0;\n border-radius: 4px 4px 0 0;\n background: white;\n border: 1px solid #e6e5e5;\n margin: 40px 0 0 0;\n background: white;\n /* for non-css3 browsers */\n filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='$white', endColorstr='$lightgrey');\n /* for IE */\n background: -webkit-gradient(linear, left top, left bottom, from(white), to(#e6e5e5));\n /* for webkit browsers */\n background: -moz-linear-gradient(top, white, #e6e5e5);\n /* for firefox 3.6+ */\n padding: 10px; }\n .boxui.header p, .boxui.box p {\n margin: 0; }\n\n.boxui.box {\n -webkit-border-radius: 0 0 4px 4px;\n border-radius: 0 0 4px 4px;\n margin: 0;\n background: white; }\n\nlabel, select {\n font-size: 1.1em; }\n\n.radio {\n width: 5%;\n float: left;\n height: 22px; }\n\n.container p {\n color: #fff;\n line-height: 100px;\n background: #000;\n text-align: center;\n margin: 20px 0 0 0; }\n"}} -{"repo": "hifi/cnc-ddraw", "pr_number": 5, "title": "Merged improvements by others", "state": "open", "merged_at": null, "additions": 6498, "deletions": 54, "files_changed": ["main.c", "render.c", "render_soft.c"], "files_before": {"main.c": "/*\n * Copyright (c) 2010 Toni Spets \n *\n * Permission to use, copy, modify, and distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n */\n\n#include \n#include \n#include \n#include \n#include \"ddraw.h\"\n\n#include \"main.h\"\n#include \"palette.h\"\n#include \"surface.h\"\n#include \"clipper.h\"\n\n/* from mouse.c */\nBOOL WINAPI fake_GetCursorPos(LPPOINT lpPoint);\nvoid mouse_init(HWND);\nvoid mouse_lock();\nvoid mouse_unlock();\n\n/* from screenshot.c */\n#ifdef HAVE_LIBPNG\nBOOL screenshot(struct IDirectDrawSurfaceImpl *);\n#endif\n\nIDirectDrawImpl *ddraw = NULL;\n\nDWORD WINAPI render_main(void);\nDWORD WINAPI render_soft_main(void);\nDWORD WINAPI render_dummy_main(void);\n\nHRESULT __stdcall ddraw_Compact(IDirectDrawImpl *This)\n{\n printf(\"DirectDraw::Compact(This=%p)\\n\", This);\n\n return DD_OK;\n}\n\nHRESULT __stdcall ddraw_DuplicateSurface(IDirectDrawImpl *This, LPDIRECTDRAWSURFACE src, LPDIRECTDRAWSURFACE *dest)\n{\n printf(\"DirectDraw::DuplicateSurface(This=%p, ...)\\n\", This);\n return DD_OK;\n}\n\nHRESULT __stdcall ddraw_EnumDisplayModes(IDirectDrawImpl *This, DWORD a, LPDDSURFACEDESC b, LPVOID c, LPDDENUMMODESCALLBACK d)\n{\n printf(\"DirectDraw::EnumDisplayModes(This=%p, ...)\\n\", This);\n return DD_OK;\n}\n\nHRESULT __stdcall ddraw_EnumSurfaces(IDirectDrawImpl *This, DWORD a, LPDDSURFACEDESC b, LPVOID c, LPDDENUMSURFACESCALLBACK d)\n{\n printf(\"DirectDraw::EnumSurfaces(This=%p, ...)\\n\", This);\n return DD_OK;\n}\n\nHRESULT __stdcall ddraw_FlipToGDISurface(IDirectDrawImpl *This)\n{\n printf(\"DirectDraw::FlipToGDISurface(This=%p)\\n\", This);\n\n return DD_OK;\n}\n\nHRESULT __stdcall ddraw_GetCaps(IDirectDrawImpl *This, LPDDCAPS lpDDDriverCaps, LPDDCAPS lpDDEmulCaps)\n{\n printf(\"DirectDraw::GetCaps(This=%p, lpDDDriverCaps=%p, lpDDEmulCaps=%p)\\n\", This, lpDDDriverCaps, lpDDEmulCaps);\n\n if(lpDDDriverCaps)\n {\n lpDDDriverCaps->dwSize = sizeof(DDCAPS);\n lpDDDriverCaps->dwCaps = DDCAPS_BLT|DDCAPS_PALETTE;\n lpDDDriverCaps->dwCKeyCaps = 0;\n lpDDDriverCaps->dwPalCaps = DDPCAPS_8BIT|DDPCAPS_PRIMARYSURFACE;\n lpDDDriverCaps->dwVidMemTotal = 16777216;\n lpDDDriverCaps->dwVidMemFree = 16777216;\n lpDDDriverCaps->dwMaxVisibleOverlays = 0;\n lpDDDriverCaps->dwCurrVisibleOverlays = 0;\n lpDDDriverCaps->dwNumFourCCCodes = 0;\n lpDDDriverCaps->dwAlignBoundarySrc = 0;\n lpDDDriverCaps->dwAlignSizeSrc = 0;\n lpDDDriverCaps->dwAlignBoundaryDest = 0;\n lpDDDriverCaps->dwAlignSizeDest = 0;\n }\n\n if(lpDDEmulCaps)\n {\n lpDDEmulCaps->dwSize = 0;\n }\n\n return DD_OK;\n}\n\nHRESULT __stdcall ddraw_GetDisplayMode(IDirectDrawImpl *This, LPDDSURFACEDESC a)\n{\n printf(\"DirectDraw::GetDisplayMode(This=%p, ...)\\n\", This);\n return DD_OK;\n}\n\nHRESULT __stdcall ddraw_GetFourCCCodes(IDirectDrawImpl *This, LPDWORD a, LPDWORD b)\n{\n printf(\"DirectDraw::GetFourCCCodes(This=%p, ...)\\n\", This);\n return DD_OK;\n}\n\nHRESULT __stdcall ddraw_GetGDISurface(IDirectDrawImpl *This, LPDIRECTDRAWSURFACE *a)\n{\n printf(\"DirectDraw::GetGDISurface(This=%p, ...)\\n\", This);\n return DD_OK;\n}\n\nHRESULT __stdcall ddraw_GetMonitorFrequency(IDirectDrawImpl *This, LPDWORD a)\n{\n printf(\"DirectDraw::GetMonitorFrequency(This=%p, ...)\\n\", This);\n return DD_OK;\n}\n\nHRESULT __stdcall ddraw_GetScanLine(IDirectDrawImpl *This, LPDWORD a)\n{\n printf(\"DirectDraw::GetScanLine(This=%p, ...)\\n\", This);\n return DD_OK;\n}\n\nHRESULT __stdcall ddraw_GetVerticalBlankStatus(IDirectDrawImpl *This, LPBOOL a)\n{\n printf(\"DirectDraw::GetVerticalBlankStatus(This=%p, ...)\\n\", This);\n return DD_OK;\n}\n\nHRESULT __stdcall ddraw_Initialize(IDirectDrawImpl *This, GUID *a)\n{\n printf(\"DirectDraw::Initialize(This=%p, ...)\\n\", This);\n return DD_OK;\n}\n\nHRESULT __stdcall ddraw_RestoreDisplayMode(IDirectDrawImpl *This)\n{\n printf(\"DirectDraw::RestoreDisplayMode(This=%p)\\n\", This);\n\n if(!This->render.run)\n {\n return DD_OK;\n }\n\n /* only stop drawing in GL mode when minimized */\n if (This->renderer == render_main)\n {\n EnterCriticalSection(&This->cs);\n This->render.run = FALSE;\n ReleaseSemaphore(ddraw->render.sem, 1, NULL);\n LeaveCriticalSection(&This->cs);\n\n WaitForSingleObject(This->render.thread, INFINITE);\n This->render.thread = NULL;\n }\n\n if(!ddraw->windowed)\n {\n ChangeDisplaySettings(&This->mode, 0);\n }\n\n return DD_OK;\n}\n\nHRESULT __stdcall ddraw_SetDisplayMode(IDirectDrawImpl *This, DWORD width, DWORD height, DWORD bpp)\n{\n printf(\"DirectDraw::SetDisplayMode(This=%p, width=%d, height=%d, bpp=%d)\\n\", This, (unsigned int)width, (unsigned int)height, (unsigned int)bpp);\n\n This->mode.dmSize = sizeof(DEVMODE);\n This->mode.dmDriverExtra = 0;\n\n if(EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &This->mode) == FALSE)\n {\n /* not expected */\n return DDERR_UNSUPPORTED;\n }\n\n This->width = width;\n This->height = height;\n This->bpp = bpp;\n This->cursorclip.width = width;\n This->cursorclip.height = height;\n\n ddraw->cursor.x = ddraw->cursorclip.width / 2;\n ddraw->cursor.y = ddraw->cursorclip.height / 2;\n\n if(This->render.width < This->width)\n {\n This->render.width = This->width;\n }\n if(This->render.height < This->height)\n {\n This->render.height = This->height;\n }\n\n This->render.run = TRUE;\n\n if (This->renderer == render_dummy_main)\n {\n if(This->render.thread == NULL)\n {\n This->render.thread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)This->renderer, NULL, 0, NULL);\n }\n return DD_OK;\n }\n\n mouse_unlock();\n\n if(This->windowed)\n {\n if(!This->windowed_init)\n {\n if (!This->border)\n {\n SetWindowLong(This->hWnd, GWL_STYLE, GetWindowLong(This->hWnd, GWL_STYLE) & ~(WS_CAPTION | WS_THICKFRAME | WS_MINIMIZE | WS_MAXIMIZE | WS_SYSMENU));\n }\n else\n {\n SetWindowLong(This->hWnd, GWL_STYLE, GetWindowLong(This->hWnd, GWL_STYLE) | WS_CAPTION | WS_BORDER | WS_SYSMENU | WS_MINIMIZEBOX);\n }\n\n /* center the window with correct dimensions */\n int x = (This->mode.dmPelsWidth / 2) - (This->render.width / 2);\n int y = (This->mode.dmPelsHeight / 2) - (This->render.height / 2);\n RECT dst = { x, y, This->render.width+x, This->render.height+y };\n AdjustWindowRect(&dst, GetWindowLong(This->hWnd, GWL_STYLE), FALSE);\n SetWindowPos(This->hWnd, HWND_NOTOPMOST, dst.left, dst.top, (dst.right - dst.left), (dst.bottom - dst.top), SWP_SHOWWINDOW);\n\n This->windowed_init = TRUE;\n }\n }\n else\n {\n SetWindowPos(This->hWnd, HWND_TOPMOST, 0, 0, This->render.width, This->render.height, SWP_SHOWWINDOW);\n\n mouse_lock();\n\n memset(&This->render.mode, 0, sizeof(DEVMODE));\n This->render.mode.dmSize = sizeof(DEVMODE);\n This->render.mode.dmFields = DM_PELSWIDTH|DM_PELSHEIGHT;\n This->render.mode.dmPelsWidth = This->render.width;\n This->render.mode.dmPelsHeight = This->render.height;\n if(This->render.bpp)\n {\n This->render.mode.dmFields |= DM_BITSPERPEL;\n This->render.mode.dmBitsPerPel = This->render.bpp;\n }\n\n if(!This->devmode && ChangeDisplaySettings(&This->render.mode, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL)\n {\n This->render.run = FALSE;\n return DDERR_INVALIDMODE;\n }\n }\n\n if(This->render.thread == NULL)\n {\n This->render.thread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)This->renderer, NULL, 0, NULL);\n }\n\n return DD_OK;\n}\n\n/* minimal window proc for dummy renderer as everything is emulated */\nLRESULT CALLBACK dummy_WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)\n{\n switch(uMsg)\n {\n /* if the plugin window changes */\n case WM_USER:\n ddraw->hWnd = (HWND)lParam;\n ddraw->render.hDC = GetDC(ddraw->hWnd);\n case WM_ACTIVATEAPP:\n if (wParam == TRUE)\n {\n break;\n }\n case WM_SIZE:\n case WM_NCACTIVATE:\n return DefWindowProc(hWnd, uMsg, wParam, lParam);\n case WM_MOUSEMOVE:\n case WM_NCMOUSEMOVE:\n ddraw->cursor.x = GET_X_LPARAM(lParam);\n ddraw->cursor.y = GET_Y_LPARAM(lParam);\n break;\n }\n\n if (ddraw->WndProc)\n {\n return ddraw->WndProc(hWnd, uMsg, wParam, lParam);\n }\n\n return DefWindowProc(hWnd, uMsg, wParam, lParam);\n}\n\nLRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)\n{\n RECT rc = { 0, 0, ddraw->render.width, ddraw->render.height };\n\n switch(uMsg)\n {\n /* Carmageddon stops the main loop when it sees these, DefWindowProc is also bad */\n case WM_WINDOWPOSCHANGING:\n case WM_WINDOWPOSCHANGED:\n return 0;\n\n /* C&C and RA really don't want to close down */\n case WM_SYSCOMMAND:\n if (wParam == SC_CLOSE)\n {\n exit(0);\n }\n return DefWindowProc(hWnd, uMsg, wParam, lParam);\n\n case WM_ACTIVATE:\n if (wParam == WA_ACTIVE || wParam == WA_CLICKACTIVE)\n {\n if (wParam == WA_ACTIVE)\n {\n mouse_lock();\n }\n if (!ddraw->windowed)\n {\n ChangeDisplaySettings(&ddraw->render.mode, CDS_FULLSCREEN);\n }\n }\n else if (wParam == WA_INACTIVE)\n {\n mouse_unlock();\n\n /* minimize our window on defocus when in fullscreen */\n if (!ddraw->windowed)\n {\n ChangeDisplaySettings(&ddraw->mode, 0);\n ShowWindow(ddraw->hWnd, SW_MINIMIZE);\n }\n }\n return 0;\n\n case WM_MOUSELEAVE:\n mouse_unlock();\n return 0;\n\n case WM_ACTIVATEAPP:\n /* C&C and RA stop drawing when they receive this with FALSE wParam, disable in windowed mode */\n if (ddraw->windowed)\n {\n return 0;\n }\n break;\n\n case WM_KEYDOWN:\n if(wParam == VK_CONTROL || wParam == VK_TAB)\n {\n if(GetAsyncKeyState(VK_CONTROL) & 0x8000 && GetAsyncKeyState(VK_TAB) & 0x8000)\n {\n mouse_unlock();\n return 0;\n }\n }\n#ifdef HAVE_LIBPNG\n if(wParam == VK_CONTROL || wParam == 0x53 /* S */)\n {\n if(GetAsyncKeyState(VK_CONTROL) & 0x8000 && GetAsyncKeyState(0x53) & 0x8000)\n {\n screenshot(ddraw->primary);\n return 0;\n }\n }\n#endif\n break;\n\n /* button up messages reactivate cursor lock */\n case WM_LBUTTONUP:\n case WM_RBUTTONUP:\n case WM_MBUTTONUP:\n if (ddraw->mhack && !ddraw->locked)\n {\n ddraw->cursor.x = LOWORD(lParam) * ((float)ddraw->width / ddraw->render.width);\n ddraw->cursor.y = HIWORD(lParam) * ((float)ddraw->height / ddraw->render.height);\n mouse_lock();\n return 0;\n }\n /* fall through for lParam */\n\n /* down messages are ignored if we have no cursor lock */\n case WM_LBUTTONDOWN:\n case WM_RBUTTONDOWN:\n case WM_MBUTTONDOWN:\n case WM_MOUSEMOVE:\n if (ddraw->mhack)\n {\n if (!ddraw->locked)\n {\n return 0;\n }\n\n fake_GetCursorPos(NULL); /* update our own cursor */\n lParam = MAKELPARAM(ddraw->cursor.x, ddraw->cursor.y);\n }\n\n if (ddraw->devmode)\n {\n mouse_lock();\n ddraw->cursor.x = GET_X_LPARAM(lParam);\n ddraw->cursor.y = GET_Y_LPARAM(lParam);\n }\n break;\n\n /* make sure we redraw when WM_PAINT is requested */\n case WM_PAINT:\n EnterCriticalSection(&ddraw->cs);\n ReleaseSemaphore(ddraw->render.sem, 1, NULL);\n LeaveCriticalSection(&ddraw->cs);\n break;\n\n case WM_ERASEBKGND:\n EnterCriticalSection(&ddraw->cs);\n FillRect(ddraw->render.hDC, &rc, (HBRUSH) GetStockObject(BLACK_BRUSH));\n ReleaseSemaphore(ddraw->render.sem, 1, NULL);\n LeaveCriticalSection(&ddraw->cs);\n break;\n }\n\n return ddraw->WndProc(hWnd, uMsg, wParam, lParam);\n}\n\nHRESULT __stdcall ddraw_SetCooperativeLevel(IDirectDrawImpl *This, HWND hWnd, DWORD dwFlags)\n{\n PIXELFORMATDESCRIPTOR pfd;\n\n printf(\"DirectDraw::SetCooperativeLevel(This=%p, hWnd=0x%08X, dwFlags=0x%08X)\\n\", This, (unsigned int)hWnd, (unsigned int)dwFlags);\n\n /* Red Alert for some weird reason does this on Windows XP */\n if(hWnd == NULL)\n {\n return DDERR_INVALIDPARAMS;\n }\n\n if (This->hWnd == NULL)\n {\n This->hWnd = hWnd;\n }\n\n mouse_init(hWnd);\n\n This->WndProc = (LRESULT CALLBACK (*)(HWND, UINT, WPARAM, LPARAM))GetWindowLong(hWnd, GWL_WNDPROC);\n\n if (This->renderer == render_dummy_main)\n {\n This->render.hDC = GetDC(This->hWnd);\n SetWindowLong(hWnd, GWL_WNDPROC, (LONG)dummy_WndProc);\n ShowWindow(hWnd, SW_HIDE);\n PostMessage(hWnd, WM_ACTIVATEAPP, TRUE, TRUE);\n PostMessage(This->hWnd, WM_USER, 0, (LPARAM)hWnd);\n return DD_OK;\n }\n\n SetWindowLong(This->hWnd, GWL_WNDPROC, (LONG)WndProc);\n\n if(!This->render.hDC)\n {\n This->render.hDC = GetDC(This->hWnd);\n\n memset(&pfd, 0, sizeof(PIXELFORMATDESCRIPTOR));\n pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR);\n pfd.nVersion = 1;\n pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER | (This->renderer == render_main ? PFD_SUPPORT_OPENGL : 0);\n pfd.iPixelType = PFD_TYPE_RGBA;\n pfd.cColorBits = ddraw->render.bpp ? ddraw->render.bpp : ddraw->mode.dmBitsPerPel;\n pfd.iLayerType = PFD_MAIN_PLANE;\n SetPixelFormat( This->render.hDC, ChoosePixelFormat( This->render.hDC, &pfd ), &pfd );\n }\n\n SetCursor(LoadCursor(NULL, IDC_ARROW));\n\n GetWindowText(This->hWnd, (LPTSTR)&This->title, sizeof(This->title));\n\n if(This->vhack == 1)\n {\n if (strcmp(This->title, \"Command & Conquer\"))\n {\n This->vhack = 0;\n }\n }\n\n return DD_OK;\n}\n\nHRESULT __stdcall ddraw_WaitForVerticalBlank(IDirectDrawImpl *This, DWORD a, HANDLE b)\n{\n#if _DEBUG\n printf(\"DirectDraw::WaitForVerticalBlank(This=%p, ...)\\n\", This);\n#endif\n return DD_OK;\n}\n\nHRESULT __stdcall ddraw_QueryInterface(IDirectDrawImpl *This, REFIID riid, void **obj)\n{\n printf(\"DirectDraw::QueryInterface(This=%p, riid=%08X, obj=%p)\\n\", This, (unsigned int)riid, obj);\n\n *obj = This;\n\n return S_OK;\n}\n\nULONG __stdcall ddraw_AddRef(IDirectDrawImpl *This)\n{\n printf(\"DirectDraw::AddRef(This=%p)\\n\", This);\n\n This->Ref++;\n\n return This->Ref;\n}\n\nULONG __stdcall ddraw_Release(IDirectDrawImpl *This)\n{\n printf(\"DirectDraw::Release(This=%p)\\n\", This);\n\n This->Ref--;\n\n if(This->Ref == 0)\n {\n if (This->hWnd && This->renderer == render_dummy_main)\n {\n PostMessage(This->hWnd, WM_USER, 0, 0);\n }\n\n if(This->render.run)\n {\n EnterCriticalSection(&This->cs);\n This->render.run = FALSE;\n ReleaseSemaphore(ddraw->render.sem, 1, NULL);\n LeaveCriticalSection(&This->cs);\n\n WaitForSingleObject(This->render.thread, INFINITE);\n This->render.thread = NULL;\n }\n\n if(This->render.hDC)\n {\n ReleaseDC(This->hWnd, This->render.hDC);\n This->render.hDC = NULL;\n }\n\n if(This->render.ev)\n {\n CloseHandle(This->render.ev);\n ddraw->render.ev = NULL;\n }\n\n if(This->real_dll)\n {\n FreeLibrary(This->real_dll);\n }\n\n DeleteCriticalSection(&This->cs);\n\n /* restore old wndproc, subsequent ddraw creation will otherwise fail */\n SetWindowLong(This->hWnd, GWL_WNDPROC, (LONG)This->WndProc);\n HeapFree(GetProcessHeap(), 0, This);\n ddraw = NULL;\n return 0;\n }\n\n return This->Ref;\n}\n\nstruct IDirectDrawImplVtbl iface =\n{\n /* IUnknown */\n ddraw_QueryInterface,\n ddraw_AddRef,\n ddraw_Release,\n /* IDirectDrawImpl */\n ddraw_Compact,\n ddraw_CreateClipper,\n ddraw_CreatePalette,\n ddraw_CreateSurface,\n ddraw_DuplicateSurface,\n ddraw_EnumDisplayModes,\n ddraw_EnumSurfaces,\n ddraw_FlipToGDISurface,\n ddraw_GetCaps,\n ddraw_GetDisplayMode,\n ddraw_GetFourCCCodes,\n ddraw_GetGDISurface,\n ddraw_GetMonitorFrequency,\n ddraw_GetScanLine,\n ddraw_GetVerticalBlankStatus,\n ddraw_Initialize,\n ddraw_RestoreDisplayMode,\n ddraw_SetCooperativeLevel,\n ddraw_SetDisplayMode,\n ddraw_WaitForVerticalBlank\n};\n\nint stdout_open = 0;\nHRESULT WINAPI DirectDrawCreate(GUID FAR* lpGUID, LPDIRECTDRAW FAR* lplpDD, IUnknown FAR* pUnkOuter) \n{\n#if _DEBUG\n if(!stdout_open)\n {\n freopen(\"stdout.txt\", \"w\", stdout);\n setvbuf(stdout, NULL, _IONBF, 0);\n stdout_open = 1;\n }\n#endif\n\n printf(\"DirectDrawCreate(lpGUID=%p, lplpDD=%p, pUnkOuter=%p)\\n\", lpGUID, lplpDD, pUnkOuter);\n\n if(ddraw)\n {\n /* FIXME: check the calling module before passing the call! */\n return ddraw->DirectDrawCreate(lpGUID, lplpDD, pUnkOuter);\n\n /*\n printf(\" returning DDERR_DIRECTDRAWALREADYCREATED\\n\");\n return DDERR_DIRECTDRAWALREADYCREATED;\n */\n } \n\n IDirectDrawImpl *This = (IDirectDrawImpl *)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(IDirectDrawImpl));\n This->lpVtbl = &iface;\n printf(\" This = %p\\n\", This);\n *lplpDD = (LPDIRECTDRAW)This;\n This->Ref = 0;\n ddraw_AddRef(This);\n\n ddraw = This;\n\n This->real_dll = LoadLibrary(\"system32\\\\ddraw.dll\");\n if(!This->real_dll)\n {\n ddraw_Release(This);\n return DDERR_GENERIC;\n }\n\n This->DirectDrawCreate = (HRESULT WINAPI (*)(GUID FAR*, LPDIRECTDRAW FAR*, IUnknown FAR*))GetProcAddress(This->real_dll, \"DirectDrawCreate\");\n\n if(!This->DirectDrawCreate)\n {\n ddraw_Release(This);\n return DDERR_GENERIC;\n }\n\n InitializeCriticalSection(&This->cs);\n This->render.ev = CreateEvent(NULL, TRUE, FALSE, NULL);\n This->render.sem = CreateSemaphore(NULL, 0, 1, NULL);\n\n /* load configuration options from ddraw.ini */\n char cwd[MAX_PATH];\n char ini_path[MAX_PATH];\n char tmp[256];\n GetCurrentDirectoryA(sizeof(cwd), cwd);\n snprintf(ini_path, sizeof(ini_path), \"%s\\\\ddraw.ini\", cwd);\n\n if(GetFileAttributes(ini_path) == 0xFFFFFFFF)\n {\n FILE *fh = fopen(ini_path, \"w\");\n fputs(\n \"[ddraw]\\n\"\n \"; width and height of the window, defaults to the size game requests\\r\\n\"\n \"width=0\\n\"\n \"height=0\\n\"\n \"; bits per pixel, possible values: 16, 24 and 32, 0 = auto\\n\"\n \"bpp=0\\n\"\n \"windowed=true\\n\"\n \"; show window borders in windowed mode\\n\"\n \"border=true\\n\"\n \"; use letter- or windowboxing to make a best fit (GDI only!)\\n\"\n \"boxing=false\\n\"\n \"; real rendering rate, -1 = screen rate, 0 = unlimited, n = cap\\n\"\n \"maxfps=0\\n\"\n \"; vertical synchronization, enable if you get tearing (OpenGL only)\\n\"\n \"vsync=false\\n\"\n \"; scaling filter, nearest = sharp, linear = smooth (OpenGL only)\\n\"\n \"filter=nearest\\n\"\n \"; automatic mouse sensitivity scaling\\n\"\n \"adjmouse=false\\n\"\n \"; manual sensitivity scaling, 0 = disabled, 0.5 = half, 1.0 = normal\\n\"\n \"sensitivity=0.0\\n\"\n \"; enable C&C/RA mouse hack\\n\"\n \"mhack=true\\n\"\n \"; enable C&C video resize hack, auto = auto-detect game, true = forced, false = disabled (OpenGL only)\\n\"\n \"vhack=false\\n\"\n \"; switch between OpenGL (opengl) and software (gdi) renderers, latter supports less features but might be faster depending on the GPU\\n\"\n \"renderer=gdi\\n\"\n \"; force CPU0 affinity, avoids crashes with RA, *might* have a performance impact\\n\"\n \"singlecpu=true\\n\"\n , fh);\n fclose(fh);\n }\n\n GetPrivateProfileStringA(\"ddraw\", \"windowed\", \"TRUE\", tmp, sizeof(tmp), ini_path);\n if (tolower(tmp[0]) == 'n' || tolower(tmp[0]) == 'f' || tolower(tmp[0]) == 'd' || tmp[0] == '0')\n {\n This->windowed = FALSE;\n }\n else\n {\n This->windowed = TRUE;\n }\n\n GetPrivateProfileStringA(\"ddraw\", \"border\", \"TRUE\", tmp, sizeof(tmp), ini_path);\n if (tolower(tmp[0]) == 'n' || tolower(tmp[0]) == 'f' || tolower(tmp[0]) == 'd' || tmp[0] == '0')\n {\n This->border = FALSE;\n }\n else\n {\n This->border = TRUE;\n }\n\n GetPrivateProfileStringA(\"ddraw\", \"boxing\", \"FALSE\", tmp, sizeof(tmp), ini_path);\n if (tolower(tmp[0]) == 'n' || tolower(tmp[0]) == 'f' || tolower(tmp[0]) == 'd' || tmp[0] == '0')\n {\n This->boxing = FALSE;\n }\n else\n {\n This->boxing = TRUE;\n }\n\n This->render.maxfps = GetPrivateProfileIntA(\"ddraw\", \"maxfps\", 0, ini_path);\n This->render.width = GetPrivateProfileIntA(\"ddraw\", \"width\", 0, ini_path);\n This->render.height = GetPrivateProfileIntA(\"ddraw\", \"height\", 0, ini_path);\n\n This->render.bpp = GetPrivateProfileIntA(\"ddraw\", \"bpp\", 32, ini_path);\n if (This->render.bpp != 16 && This->render.bpp != 24 && This->render.bpp != 32)\n {\n This->render.bpp = 0;\n }\n\n GetPrivateProfileStringA(\"ddraw\", \"filter\", tmp, tmp, sizeof(tmp), ini_path);\n if (tolower(tmp[0]) == 'l' || tolower(tmp[3]) == 'l')\n {\n This->render.filter = 1;\n }\n else\n {\n This->render.filter = 0;\n }\n\n GetPrivateProfileStringA(\"ddraw\", \"adjmouse\", \"FALSE\", tmp, sizeof(tmp), ini_path);\n if (tolower(tmp[0]) == 'y' || tolower(tmp[0]) == 't' || tolower(tmp[0]) == 'e' || tmp[0] == '1')\n {\n This->adjmouse = TRUE;\n }\n else\n {\n This->adjmouse = FALSE;\n }\n\n GetPrivateProfileStringA(\"ddraw\", \"mhack\", \"TRUE\", tmp, sizeof(tmp), ini_path);\n if (tolower(tmp[0]) == 'y' || tolower(tmp[0]) == 't' || tolower(tmp[0]) == 'e' || tmp[0] == '1')\n {\n This->mhack = TRUE;\n }\n else\n {\n This->mhack = FALSE;\n }\n\n GetPrivateProfileStringA(\"ddraw\", \"devmode\", \"FALSE\", tmp, sizeof(tmp), ini_path);\n if (tolower(tmp[0]) == 'y' || tolower(tmp[0]) == 't' || tolower(tmp[0]) == 'e' || tmp[0] == '1')\n {\n This->devmode = TRUE;\n This->mhack = FALSE;\n }\n else\n {\n This->devmode = FALSE;\n }\n\n GetPrivateProfileStringA(\"ddraw\", \"vsync\", \"FALSE\", tmp, sizeof(tmp), ini_path);\n if (tolower(tmp[0]) == 'y' || tolower(tmp[0]) == 't' || tolower(tmp[0]) == 'e' || tmp[0] == '1')\n {\n This->vsync = TRUE;\n }\n else\n {\n This->vsync = FALSE;\n }\n\n GetPrivateProfileStringA(\"ddraw\", \"sensitivity\", \"0\", tmp, sizeof(tmp), ini_path);\n This->sensitivity = strtof(tmp, NULL);\n\n GetPrivateProfileStringA(\"ddraw\", \"vhack\", \"false\", tmp, sizeof(tmp), ini_path);\n if (tolower(tmp[0]) == 'y' || tolower(tmp[0]) == 't' || tolower(tmp[0]) == 'e' || tmp[0] == '1')\n {\n This->vhack = 2;\n }\n else if(tolower(tmp[0]) == 'a')\n {\n This->vhack = 1;\n }\n else\n {\n This->vhack = 0;\n }\n\n GetPrivateProfileStringA(\"ddraw\", \"renderer\", \"gdi\", tmp, sizeof(tmp), ini_path);\n if(tolower(tmp[0]) == 'd' || tolower(tmp[0]) == 'd')\n {\n printf(\"DirectDrawCreate: Using dummy renderer\\n\");\n This->renderer = render_dummy_main;\n }\n else if(tolower(tmp[0]) == 's' || tolower(tmp[0]) == 'g')\n {\n printf(\"DirectDrawCreate: Using software renderer\\n\");\n This->renderer = render_soft_main;\n }\n else\n {\n printf(\"DirectDrawCreate: Using OpenGL renderer\\n\");\n This->renderer = render_main;\n }\n\n GetPrivateProfileStringA(\"ddraw\", \"singlecpu\", \"true\", tmp, sizeof(tmp), ini_path);\n if (tolower(tmp[0]) == 'y' || tolower(tmp[0]) == 't' || tolower(tmp[0]) == 'e' || tmp[0] == '1')\n {\n printf(\"DirectDrawCreate: Setting CPU0 affinity\\n\");\n SetProcessAffinityMask(GetCurrentProcess(), 1);\n }\n\n /* last minute check for cnc-plugin */\n if (GetEnvironmentVariable(\"DDRAW_WINDOW\", tmp, sizeof(tmp)) > 0)\n {\n This->hWnd = (HWND)atoi(tmp);\n This->renderer = render_dummy_main;\n This->windowed = TRUE;\n\n if (GetEnvironmentVariable(\"DDRAW_WIDTH\", tmp, sizeof(tmp)) > 0)\n {\n This->render.width = atoi(tmp);\n }\n\n if (GetEnvironmentVariable(\"DDRAW_HEIGHT\", tmp, sizeof(tmp)) > 0)\n {\n This->render.height = atoi(tmp);\n }\n\n printf(\"DirectDrawCreate: Detected cnc-plugin at window %08X in %dx%d\\n\", (unsigned int)This->hWnd, This->render.width, This->render.height);\n }\n\n return DD_OK;\n}\n", "render.c": "/*\n * Copyright (c) 2010 Toni Spets \n *\n * Permission to use, copy, modify, and distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n */\n\n#include \n#include \n\n#include \"main.h\"\n#include \"surface.h\"\n\n#define CUTSCENE_WIDTH 640\n#define CUTSCENE_HEIGHT 400\n\nBOOL detect_cutscene();\n\nDWORD WINAPI render_main(void)\n{\n int i,j;\n HGLRC hRC;\n\n int tex_width = ddraw->width > 1024 ? ddraw->width : 1024;\n int tex_height = ddraw->height > 1024 ? ddraw->height : 1024;\n float scale_w = 1.0f;\n float scale_h = 1.0f;\n int *tex = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, tex_width * tex_height * sizeof(int));\n\n hRC = wglCreateContext( ddraw->render.hDC );\n wglMakeCurrent( ddraw->render.hDC, hRC );\n\n char *glext = (char *)glGetString(GL_EXTENSIONS);\n\n if(glext && strstr(glext, \"WGL_EXT_swap_control\"))\n {\n BOOL (APIENTRY *wglSwapIntervalEXT)(int) = (BOOL (APIENTRY *)(int))wglGetProcAddress(\"wglSwapIntervalEXT\");\n if(wglSwapIntervalEXT)\n {\n if(ddraw->vsync)\n {\n wglSwapIntervalEXT(1);\n }\n else\n {\n wglSwapIntervalEXT(0);\n }\n }\n }\n\n DWORD tick_start = 0;\n DWORD tick_end = 0;\n DWORD frame_len = 0;\n\n if(ddraw->render.maxfps < 0)\n {\n ddraw->render.maxfps = ddraw->mode.dmDisplayFrequency;\n }\n\n if(ddraw->render.maxfps > 0)\n {\n frame_len = 1000.0f / ddraw->render.maxfps;\n }\n\n glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, tex_width, tex_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, tex);\n glViewport(0, 0, ddraw->render.width, ddraw->render.height);\n\n if(ddraw->render.filter)\n {\n glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);\n glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);\n }\n else\n {\n glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST);\n glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST);\n }\n\n glEnable(GL_TEXTURE_2D);\n\n while(ddraw->render.run && WaitForSingleObject(ddraw->render.sem, INFINITE) != WAIT_FAILED)\n {\n scale_w = (float)ddraw->width/tex_width;\n scale_h = (float)ddraw->height/tex_height;\n\n if(ddraw->render.maxfps > 0)\n {\n tick_start = GetTickCount();\n }\n\n /* convert ddraw surface to opengl texture */\n EnterCriticalSection(&ddraw->cs);\n\n if(ddraw->primary && ddraw->primary->palette)\n {\n if(ddraw->vhack && detect_cutscene())\n {\n scale_w *= (float)CUTSCENE_WIDTH / ddraw->width;\n scale_h *= (float)CUTSCENE_HEIGHT / ddraw->height;\n\n if (ddraw->cursorclip.width != CUTSCENE_WIDTH || ddraw->cursorclip.height != CUTSCENE_HEIGHT)\n {\n ddraw->cursorclip.width = CUTSCENE_WIDTH;\n ddraw->cursorclip.height = CUTSCENE_HEIGHT;\n ddraw->cursor.x = CUTSCENE_WIDTH / 2;\n ddraw->cursor.y = CUTSCENE_HEIGHT / 2;\n }\n }\n else\n {\n if (ddraw->cursorclip.width != ddraw->width || ddraw->cursorclip.height != ddraw->height)\n {\n ddraw->cursorclip.width = ddraw->width;\n ddraw->cursorclip.height = ddraw->height;\n ddraw->cursor.x = ddraw->width / 2;\n ddraw->cursor.y = ddraw->height / 2;\n }\n }\n\n for(i=0; iheight; i++)\n {\n for(j=0; jwidth; j++)\n {\n tex[i*ddraw->width+j] = ddraw->primary->palette->data_bgr[((unsigned char *)ddraw->primary->surface)[i*ddraw->primary->lPitch + j*ddraw->primary->lXPitch]];\n }\n }\n }\n LeaveCriticalSection(&ddraw->cs);\n\n glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, ddraw->width, ddraw->height, GL_RGBA, GL_UNSIGNED_BYTE, tex);\n\n glBegin(GL_TRIANGLE_FAN);\n glTexCoord2f(0,0); glVertex2f(-1, 1);\n glTexCoord2f(scale_w,0); glVertex2f( 1, 1);\n glTexCoord2f(scale_w,scale_h); glVertex2f( 1, -1);\t\n glTexCoord2f(0,scale_h); glVertex2f(-1, -1);\n glEnd();\n\n SwapBuffers(ddraw->render.hDC);\n\n if(ddraw->render.maxfps > 0)\n {\n tick_end = GetTickCount();\n\n if(tick_end - tick_start < frame_len)\n {\n Sleep( frame_len - (tick_end - tick_start) );\n }\n }\n\n SetEvent(ddraw->render.ev);\n }\n\n HeapFree(GetProcessHeap(), 0, tex);\n\n wglMakeCurrent(NULL, NULL);\n wglDeleteContext(hRC);\n\n return 0;\n}\n\nstatic unsigned char getPixel(int x, int y)\n{\n return ((unsigned char *)ddraw->primary->surface)[y*ddraw->primary->lPitch + x*ddraw->primary->lXPitch];\n}\n\nBOOL detect_cutscene()\n{\n if(ddraw->width <= CUTSCENE_WIDTH || ddraw->height <= CUTSCENE_HEIGHT)\n return FALSE;\n\n return getPixel(CUTSCENE_WIDTH + 1, 0) == 0 || getPixel(CUTSCENE_WIDTH + 5, 1) == 0 ? TRUE : FALSE;\n}\n", "render_soft.c": "/*\n * Copyright (c) 2011 Toni Spets \n *\n * Permission to use, copy, modify, and distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n */\n\n#include \n#include \n\n#include \"main.h\"\n#include \"surface.h\"\n\nDWORD WINAPI render_soft_main(void)\n{\n PBITMAPINFO bmi = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(BITMAPINFOHEADER) + sizeof(RGBQUAD) * 256);\n\n bmi->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);\n bmi->bmiHeader.biWidth = ddraw->width;\n bmi->bmiHeader.biHeight = -ddraw->height;\n bmi->bmiHeader.biPlanes = 1;\n bmi->bmiHeader.biBitCount = ddraw->bpp;\n bmi->bmiHeader.biCompression = BI_RGB;\n\n DWORD dst_top = 0;\n DWORD dst_left = 0;\n DWORD dst_width = ddraw->render.width;\n DWORD dst_height = ddraw->render.height;\n\n DWORD tick_start = 0;\n DWORD tick_end = 0;\n DWORD frame_len = 0;\n\n if (ddraw->boxing)\n {\n dst_width = ddraw->width;\n dst_height = ddraw->height;\n\n /* test if we can double scale the window */\n if (ddraw->width * 2 <= ddraw->render.width && ddraw->height * 2 <= ddraw->render.height)\n {\n dst_width *= 2;\n dst_height *= 2;\n }\n\n dst_top = ddraw->render.height / 2 - dst_height / 2;\n dst_left = ddraw->render.width / 2 - dst_width / 2;\n }\n\n if(ddraw->render.maxfps < 0)\n {\n ddraw->render.maxfps = ddraw->mode.dmDisplayFrequency;\n }\n\n if(ddraw->render.maxfps > 0)\n {\n frame_len = 1000.0f / ddraw->render.maxfps;\n }\n\n while (ddraw->render.run && WaitForSingleObject(ddraw->render.sem, INFINITE) != WAIT_FAILED)\n {\n if(ddraw->render.maxfps > 0)\n {\n tick_start = GetTickCount();\n }\n\n EnterCriticalSection(&ddraw->cs);\n\n if (ddraw->primary && (ddraw->primary->palette || ddraw->bpp == 16))\n {\n if (ddraw->primary->palette && ddraw->primary->palette->data_rgb == NULL)\n {\n ddraw->primary->palette->data_rgb = &bmi->bmiColors[0];\n }\n\n if (ddraw->render.width != ddraw->width || ddraw->render.height != ddraw->height)\n {\n StretchDIBits(ddraw->render.hDC, dst_left, dst_top, dst_width, dst_height, 0, 0, ddraw->width, ddraw->height, ddraw->primary->surface, bmi, DIB_RGB_COLORS, SRCCOPY);\n }\n else\n {\n SetDIBitsToDevice(ddraw->render.hDC, 0, 0, ddraw->width, ddraw->height, 0, 0, 0, ddraw->height, ddraw->primary->surface, bmi, DIB_RGB_COLORS);\n }\n }\n LeaveCriticalSection(&ddraw->cs);\n\n if(ddraw->render.maxfps > 0)\n {\n tick_end = GetTickCount();\n\n if(tick_end - tick_start < frame_len)\n {\n Sleep( frame_len - (tick_end - tick_start) );\n }\n }\n\n SetEvent(ddraw->render.ev);\n }\n\n HeapFree(GetProcessHeap(), 0, bmi);\n\n return TRUE;\n}\n"}, "files_after": {"main.c": "/*\n * Copyright (c) 2010 Toni Spets \n *\n * Permission to use, copy, modify, and distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n */\n\n#include \n#include \n#include \n#include \n#include \"ddraw.h\"\n\n#include \"main.h\"\n#include \"palette.h\"\n#include \"surface.h\"\n#include \"clipper.h\"\n\n#define IDR_MYMENU 93\n\n/* from mouse.c */\nBOOL WINAPI fake_GetCursorPos(LPPOINT lpPoint);\nvoid mouse_init(HWND);\nvoid mouse_lock();\nvoid mouse_unlock();\n\n/* from screenshot.c */\n#ifdef HAVE_LIBPNG\nBOOL screenshot(struct IDirectDrawSurfaceImpl *);\n#endif\n\nIDirectDrawImpl *ddraw = NULL;\n\nDWORD WINAPI render_main(void);\nDWORD WINAPI render_soft_main(void);\nDWORD WINAPI render_dummy_main(void);\n\nHRESULT __stdcall ddraw_Compact(IDirectDrawImpl *This)\n{\n printf(\"DirectDraw::Compact(This=%p)\\n\", This);\n\n return DD_OK;\n}\n\nHRESULT __stdcall ddraw_DuplicateSurface(IDirectDrawImpl *This, LPDIRECTDRAWSURFACE src, LPDIRECTDRAWSURFACE *dest)\n{\n printf(\"DirectDraw::DuplicateSurface(This=%p, ...)\\n\", This);\n return DD_OK;\n}\n\nHRESULT __stdcall ddraw_EnumDisplayModes(IDirectDrawImpl *This, DWORD a, LPDDSURFACEDESC b, LPVOID c, LPDDENUMMODESCALLBACK d)\n{\n printf(\"DirectDraw::EnumDisplayModes(This=%p, ...)\\n\", This);\n return DD_OK;\n}\n\nHRESULT __stdcall ddraw_EnumSurfaces(IDirectDrawImpl *This, DWORD a, LPDDSURFACEDESC b, LPVOID c, LPDDENUMSURFACESCALLBACK d)\n{\n printf(\"DirectDraw::EnumSurfaces(This=%p, ...)\\n\", This);\n return DD_OK;\n}\n\nHRESULT __stdcall ddraw_FlipToGDISurface(IDirectDrawImpl *This)\n{\n printf(\"DirectDraw::FlipToGDISurface(This=%p)\\n\", This);\n\n return DD_OK;\n}\n\nHRESULT __stdcall ddraw_GetCaps(IDirectDrawImpl *This, LPDDCAPS lpDDDriverCaps, LPDDCAPS lpDDEmulCaps)\n{\n printf(\"DirectDraw::GetCaps(This=%p, lpDDDriverCaps=%p, lpDDEmulCaps=%p)\\n\", This, lpDDDriverCaps, lpDDEmulCaps);\n\n if(lpDDDriverCaps)\n {\n lpDDDriverCaps->dwSize = sizeof(DDCAPS);\n lpDDDriverCaps->dwCaps = DDCAPS_BLT|DDCAPS_PALETTE;\n lpDDDriverCaps->dwCKeyCaps = 0;\n lpDDDriverCaps->dwPalCaps = DDPCAPS_8BIT|DDPCAPS_PRIMARYSURFACE;\n lpDDDriverCaps->dwVidMemTotal = 16777216;\n lpDDDriverCaps->dwVidMemFree = 16777216;\n lpDDDriverCaps->dwMaxVisibleOverlays = 0;\n lpDDDriverCaps->dwCurrVisibleOverlays = 0;\n lpDDDriverCaps->dwNumFourCCCodes = 0;\n lpDDDriverCaps->dwAlignBoundarySrc = 0;\n lpDDDriverCaps->dwAlignSizeSrc = 0;\n lpDDDriverCaps->dwAlignBoundaryDest = 0;\n lpDDDriverCaps->dwAlignSizeDest = 0;\n }\n\n if(lpDDEmulCaps)\n {\n lpDDEmulCaps->dwSize = 0;\n }\n\n return DD_OK;\n}\n\nHRESULT __stdcall ddraw_GetDisplayMode(IDirectDrawImpl *This, LPDDSURFACEDESC a)\n{\n printf(\"DirectDraw::GetDisplayMode(This=%p, ...)\\n\", This);\n return DD_OK;\n}\n\nHRESULT __stdcall ddraw_GetFourCCCodes(IDirectDrawImpl *This, LPDWORD a, LPDWORD b)\n{\n printf(\"DirectDraw::GetFourCCCodes(This=%p, ...)\\n\", This);\n return DD_OK;\n}\n\nHRESULT __stdcall ddraw_GetGDISurface(IDirectDrawImpl *This, LPDIRECTDRAWSURFACE *a)\n{\n printf(\"DirectDraw::GetGDISurface(This=%p, ...)\\n\", This);\n return DD_OK;\n}\n\nHRESULT __stdcall ddraw_GetMonitorFrequency(IDirectDrawImpl *This, LPDWORD a)\n{\n printf(\"DirectDraw::GetMonitorFrequency(This=%p, ...)\\n\", This);\n return DD_OK;\n}\n\nHRESULT __stdcall ddraw_GetScanLine(IDirectDrawImpl *This, LPDWORD a)\n{\n printf(\"DirectDraw::GetScanLine(This=%p, ...)\\n\", This);\n return DD_OK;\n}\n\nHRESULT __stdcall ddraw_GetVerticalBlankStatus(IDirectDrawImpl *This, LPBOOL a)\n{\n printf(\"DirectDraw::GetVerticalBlankStatus(This=%p, ...)\\n\", This);\n return DD_OK;\n}\n\nHRESULT __stdcall ddraw_Initialize(IDirectDrawImpl *This, GUID *a)\n{\n printf(\"DirectDraw::Initialize(This=%p, ...)\\n\", This);\n return DD_OK;\n}\n\nHRESULT __stdcall ddraw_RestoreDisplayMode(IDirectDrawImpl *This)\n{\n printf(\"DirectDraw::RestoreDisplayMode(This=%p)\\n\", This);\n\n if(!This->render.run)\n {\n return DD_OK;\n }\n\n /* only stop drawing in GL mode when minimized */\n if (This->renderer == render_main)\n {\n EnterCriticalSection(&This->cs);\n This->render.run = FALSE;\n ReleaseSemaphore(ddraw->render.sem, 1, NULL);\n LeaveCriticalSection(&This->cs);\n\n WaitForSingleObject(This->render.thread, INFINITE);\n This->render.thread = NULL;\n }\n\n if(!ddraw->windowed)\n {\n ChangeDisplaySettings(&This->mode, 0);\n }\n\n return DD_OK;\n}\n\nHRESULT __stdcall ddraw_SetDisplayMode(IDirectDrawImpl *This, DWORD width, DWORD height, DWORD bpp)\n{\n printf(\"DirectDraw::SetDisplayMode(This=%p, width=%d, height=%d, bpp=%d)\\n\", This, (unsigned int)width, (unsigned int)height, (unsigned int)bpp);\n\n This->mode.dmSize = sizeof(DEVMODE);\n This->mode.dmDriverExtra = 0;\n\n if(EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &This->mode) == FALSE)\n {\n /* not expected */\n return DDERR_UNSUPPORTED;\n }\n\n This->width = width;\n This->height = height;\n This->bpp = bpp;\n This->cursorclip.width = width;\n This->cursorclip.height = height;\n\n ddraw->cursor.x = ddraw->cursorclip.width / 2;\n ddraw->cursor.y = ddraw->cursorclip.height / 2;\n\n if(This->render.width < This->width)\n {\n This->render.width = This->width;\n }\n if(This->render.height < This->height)\n {\n This->render.height = This->height;\n }\n\n This->render.run = TRUE;\n\n if (This->renderer == render_dummy_main)\n {\n if(This->render.thread == NULL)\n {\n This->render.thread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)This->renderer, NULL, 0, NULL);\n }\n return DD_OK;\n }\n\n mouse_unlock();\n\t\n\tconst HANDLE hbicon = LoadImage(GetModuleHandle(0), MAKEINTRESOURCE(IDR_MYMENU), IMAGE_ICON, GetSystemMetrics(SM_CXICON), GetSystemMetrics(SM_CYICON), 0);\n\tif (hbicon)\n\t\tSendMessage(This->hWnd, WM_SETICON, ICON_BIG, (LPARAM)hbicon);\n\n\tconst HANDLE hsicon = LoadImage(GetModuleHandle(0), MAKEINTRESOURCE(IDR_MYMENU), IMAGE_ICON, GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), 0);\n\tif (hsicon)\n\t\tSendMessage(This->hWnd, WM_SETICON, ICON_SMALL, (LPARAM)hsicon);\n\n if(This->windowed)\n {\n if(!This->windowed_init)\n {\n if (!This->border)\n {\n SetWindowLong(This->hWnd, GWL_STYLE, GetWindowLong(This->hWnd, GWL_STYLE) & ~(WS_CAPTION | WS_THICKFRAME | WS_MINIMIZE | WS_MAXIMIZE | WS_SYSMENU));\n }\n else\n {\n SetWindowLong(This->hWnd, GWL_STYLE, GetWindowLong(This->hWnd, GWL_STYLE) | WS_CAPTION | WS_BORDER | WS_SYSMENU | WS_MINIMIZEBOX);\n }\n\n /* center the window with correct dimensions */\n int x = (This->mode.dmPelsWidth / 2) - (This->render.width / 2);\n int y = (This->mode.dmPelsHeight / 2) - (This->render.height / 2);\n RECT dst = { x, y, This->render.width+x, This->render.height+y };\n AdjustWindowRect(&dst, GetWindowLong(This->hWnd, GWL_STYLE), FALSE);\n SetWindowPos(This->hWnd, HWND_NOTOPMOST, dst.left, dst.top, (dst.right - dst.left), (dst.bottom - dst.top), SWP_SHOWWINDOW);\n\n This->windowed_init = TRUE;\n }\n }\n else\n {\n SetWindowPos(This->hWnd, HWND_TOPMOST, 0, 0, This->render.width, This->render.height, SWP_SHOWWINDOW);\n\n mouse_lock();\n\n memset(&This->render.mode, 0, sizeof(DEVMODE));\n This->render.mode.dmSize = sizeof(DEVMODE);\n This->render.mode.dmFields = DM_PELSWIDTH|DM_PELSHEIGHT;\n This->render.mode.dmPelsWidth = This->render.width;\n This->render.mode.dmPelsHeight = This->render.height;\n if(This->render.bpp)\n {\n This->render.mode.dmFields |= DM_BITSPERPEL;\n This->render.mode.dmBitsPerPel = This->render.bpp;\n }\n\n if(!This->devmode && ChangeDisplaySettings(&This->render.mode, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL)\n {\n This->render.run = FALSE;\n return DDERR_INVALIDMODE;\n }\n }\n\n if(This->render.thread == NULL)\n {\n This->render.thread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)This->renderer, NULL, 0, NULL);\n }\n\n return DD_OK;\n}\n\n/* minimal window proc for dummy renderer as everything is emulated */\nLRESULT CALLBACK dummy_WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)\n{\n switch(uMsg)\n {\n /* if the plugin window changes */\n case WM_USER:\n ddraw->hWnd = (HWND)lParam;\n ddraw->render.hDC = GetDC(ddraw->hWnd);\n case WM_ACTIVATEAPP:\n if (wParam == TRUE)\n {\n break;\n }\n case WM_SIZE:\n case WM_NCACTIVATE:\n return DefWindowProc(hWnd, uMsg, wParam, lParam);\n case WM_MOUSEMOVE:\n case WM_NCMOUSEMOVE:\n ddraw->cursor.x = GET_X_LPARAM(lParam);\n ddraw->cursor.y = GET_Y_LPARAM(lParam);\n break;\n }\n\n if (ddraw->WndProc)\n {\n return ddraw->WndProc(hWnd, uMsg, wParam, lParam);\n }\n\n return DefWindowProc(hWnd, uMsg, wParam, lParam);\n}\n\nLRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)\n{\n RECT rc = { 0, 0, ddraw->render.width, ddraw->render.height };\n\n switch(uMsg)\n {\n /* Carmageddon stops the main loop when it sees these, DefWindowProc is also bad */\n case WM_WINDOWPOSCHANGING:\n case WM_WINDOWPOSCHANGED:\n return 0;\n\n /* C&C and RA really don't want to close down */\n case WM_SYSCOMMAND:\n if (wParam == SC_CLOSE)\n {\n exit(0);\n }\n return DefWindowProc(hWnd, uMsg, wParam, lParam);\n\n case WM_ACTIVATE:\n if (wParam == WA_ACTIVE || wParam == WA_CLICKACTIVE)\n {\n if (wParam == WA_ACTIVE)\n {\n mouse_lock();\n }\n if (!ddraw->windowed)\n {\n ChangeDisplaySettings(&ddraw->render.mode, CDS_FULLSCREEN);\n }\n }\n else if (wParam == WA_INACTIVE)\n {\n mouse_unlock();\n\n /* minimize our window on defocus when in fullscreen */\n if (!ddraw->windowed)\n {\n ChangeDisplaySettings(&ddraw->mode, 0);\n ShowWindow(ddraw->hWnd, SW_MINIMIZE);\n }\n }\n return 0;\n\n case WM_MOUSELEAVE:\n mouse_unlock();\n return 0;\n\n case WM_ACTIVATEAPP:\n /* C&C and RA stop drawing when they receive this with FALSE wParam, disable in windowed mode */\n if (ddraw->windowed)\n {\n return 0;\n }\n break;\n\n case WM_KEYDOWN:\n if(wParam == VK_CONTROL || wParam == VK_TAB)\n {\n if(GetAsyncKeyState(VK_CONTROL) & 0x8000 && GetAsyncKeyState(VK_TAB) & 0x8000)\n {\n mouse_unlock();\n return 0;\n }\n }\n#ifdef HAVE_LIBPNG\n if(wParam == VK_CONTROL || wParam == 0x53 /* S */)\n {\n if(GetAsyncKeyState(VK_CONTROL) & 0x8000 && GetAsyncKeyState(0x53) & 0x8000)\n {\n screenshot(ddraw->primary);\n return 0;\n }\n }\n#endif\n break;\n\n /* button up messages reactivate cursor lock */\n case WM_LBUTTONUP:\n case WM_RBUTTONUP:\n case WM_MBUTTONUP:\n if (ddraw->mhack && !ddraw->locked)\n {\n ddraw->cursor.x = LOWORD(lParam) * ((float)ddraw->width / ddraw->render.width);\n ddraw->cursor.y = HIWORD(lParam) * ((float)ddraw->height / ddraw->render.height);\n mouse_lock();\n return 0;\n }\n /* fall through for lParam */\n\n /* down messages are ignored if we have no cursor lock */\n case WM_LBUTTONDOWN:\n case WM_RBUTTONDOWN:\n case WM_MBUTTONDOWN:\n case WM_MOUSEMOVE:\n if (ddraw->mhack)\n {\n if (!ddraw->locked)\n {\n return 0;\n }\n\n fake_GetCursorPos(NULL); /* update our own cursor */\n lParam = MAKELPARAM(ddraw->cursor.x, ddraw->cursor.y);\n }\n\n if (ddraw->devmode)\n {\n mouse_lock();\n ddraw->cursor.x = GET_X_LPARAM(lParam);\n ddraw->cursor.y = GET_Y_LPARAM(lParam);\n }\n break;\n\n /* make sure we redraw when WM_PAINT is requested */\n case WM_PAINT:\n EnterCriticalSection(&ddraw->cs);\n ReleaseSemaphore(ddraw->render.sem, 1, NULL);\n LeaveCriticalSection(&ddraw->cs);\n break;\n\n case WM_ERASEBKGND:\n EnterCriticalSection(&ddraw->cs);\n FillRect(ddraw->render.hDC, &rc, (HBRUSH) GetStockObject(BLACK_BRUSH));\n ReleaseSemaphore(ddraw->render.sem, 1, NULL);\n LeaveCriticalSection(&ddraw->cs);\n break;\n }\n\n return ddraw->WndProc(hWnd, uMsg, wParam, lParam);\n}\n\nHRESULT __stdcall ddraw_SetCooperativeLevel(IDirectDrawImpl *This, HWND hWnd, DWORD dwFlags)\n{\n PIXELFORMATDESCRIPTOR pfd;\n\n printf(\"DirectDraw::SetCooperativeLevel(This=%p, hWnd=0x%08X, dwFlags=0x%08X)\\n\", This, (unsigned int)hWnd, (unsigned int)dwFlags);\n\n /* Red Alert for some weird reason does this on Windows XP */\n if(hWnd == NULL)\n {\n return DDERR_INVALIDPARAMS;\n }\n\n if (This->hWnd == NULL)\n {\n This->hWnd = hWnd;\n }\n\n mouse_init(hWnd);\n\n This->WndProc = (LRESULT CALLBACK (*)(HWND, UINT, WPARAM, LPARAM))GetWindowLong(hWnd, GWL_WNDPROC);\n\n if (This->renderer == render_dummy_main)\n {\n This->render.hDC = GetDC(This->hWnd);\n SetWindowLong(hWnd, GWL_WNDPROC, (LONG)dummy_WndProc);\n ShowWindow(hWnd, SW_HIDE);\n PostMessage(hWnd, WM_ACTIVATEAPP, TRUE, TRUE);\n PostMessage(This->hWnd, WM_USER, 0, (LPARAM)hWnd);\n return DD_OK;\n }\n\n SetWindowLong(This->hWnd, GWL_WNDPROC, (LONG)WndProc);\n\n if(!This->render.hDC)\n {\n This->render.hDC = GetDC(This->hWnd);\n\n memset(&pfd, 0, sizeof(PIXELFORMATDESCRIPTOR));\n pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR);\n pfd.nVersion = 1;\n pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER | (This->renderer == render_main ? PFD_SUPPORT_OPENGL : 0);\n pfd.iPixelType = PFD_TYPE_RGBA;\n pfd.cColorBits = ddraw->render.bpp ? ddraw->render.bpp : ddraw->mode.dmBitsPerPel;\n pfd.iLayerType = PFD_MAIN_PLANE;\n SetPixelFormat( This->render.hDC, ChoosePixelFormat( This->render.hDC, &pfd ), &pfd );\n }\n\n SetCursor(LoadCursor(NULL, IDC_ARROW));\n\n GetWindowText(This->hWnd, (LPTSTR)&This->title, sizeof(This->title));\n\n\tif (!strcmp(This->title, \"Red Alert\"))\n\t{\n\t\tddraw->isredalert = 1;\n\t}\n\n return DD_OK;\n}\n\nHRESULT __stdcall ddraw_WaitForVerticalBlank(IDirectDrawImpl *This, DWORD a, HANDLE b)\n{\n#if _DEBUG\n printf(\"DirectDraw::WaitForVerticalBlank(This=%p, ...)\\n\", This);\n#endif\n return DD_OK;\n}\n\nHRESULT __stdcall ddraw_QueryInterface(IDirectDrawImpl *This, REFIID riid, void **obj)\n{\n printf(\"DirectDraw::QueryInterface(This=%p, riid=%08X, obj=%p)\\n\", This, (unsigned int)riid, obj);\n\n *obj = This;\n\n return S_OK;\n}\n\nULONG __stdcall ddraw_AddRef(IDirectDrawImpl *This)\n{\n printf(\"DirectDraw::AddRef(This=%p)\\n\", This);\n\n This->Ref++;\n\n return This->Ref;\n}\n\nULONG __stdcall ddraw_Release(IDirectDrawImpl *This)\n{\n printf(\"DirectDraw::Release(This=%p)\\n\", This);\n\n This->Ref--;\n\n if(This->Ref == 0)\n {\n if (This->hWnd && This->renderer == render_dummy_main)\n {\n PostMessage(This->hWnd, WM_USER, 0, 0);\n }\n\n if(This->render.run)\n {\n EnterCriticalSection(&This->cs);\n This->render.run = FALSE;\n ReleaseSemaphore(ddraw->render.sem, 1, NULL);\n LeaveCriticalSection(&This->cs);\n\n WaitForSingleObject(This->render.thread, INFINITE);\n This->render.thread = NULL;\n }\n\n if(This->render.hDC)\n {\n ReleaseDC(This->hWnd, This->render.hDC);\n This->render.hDC = NULL;\n }\n\n if(This->render.ev)\n {\n CloseHandle(This->render.ev);\n ddraw->render.ev = NULL;\n }\n\n if(This->real_dll)\n {\n FreeLibrary(This->real_dll);\n }\n\n DeleteCriticalSection(&This->cs);\n\n /* restore old wndproc, subsequent ddraw creation will otherwise fail */\n SetWindowLong(This->hWnd, GWL_WNDPROC, (LONG)This->WndProc);\n HeapFree(GetProcessHeap(), 0, This);\n ddraw = NULL;\n return 0;\n }\n\n return This->Ref;\n}\n\nstruct IDirectDrawImplVtbl iface =\n{\n /* IUnknown */\n ddraw_QueryInterface,\n ddraw_AddRef,\n ddraw_Release,\n /* IDirectDrawImpl */\n ddraw_Compact,\n ddraw_CreateClipper,\n ddraw_CreatePalette,\n ddraw_CreateSurface,\n ddraw_DuplicateSurface,\n ddraw_EnumDisplayModes,\n ddraw_EnumSurfaces,\n ddraw_FlipToGDISurface,\n ddraw_GetCaps,\n ddraw_GetDisplayMode,\n ddraw_GetFourCCCodes,\n ddraw_GetGDISurface,\n ddraw_GetMonitorFrequency,\n ddraw_GetScanLine,\n ddraw_GetVerticalBlankStatus,\n ddraw_Initialize,\n ddraw_RestoreDisplayMode,\n ddraw_SetCooperativeLevel,\n ddraw_SetDisplayMode,\n ddraw_WaitForVerticalBlank\n};\n\nint stdout_open = 0;\nHRESULT WINAPI DirectDrawCreate(GUID FAR* lpGUID, LPDIRECTDRAW FAR* lplpDD, IUnknown FAR* pUnkOuter) \n{\n#if _DEBUG\n if(!stdout_open)\n {\n freopen(\"stdout.txt\", \"w\", stdout);\n setvbuf(stdout, NULL, _IONBF, 0);\n stdout_open = 1;\n }\n#endif\n\n printf(\"DirectDrawCreate(lpGUID=%p, lplpDD=%p, pUnkOuter=%p)\\n\", lpGUID, lplpDD, pUnkOuter);\n\n if(ddraw)\n {\n /* FIXME: check the calling module before passing the call! */\n return ddraw->DirectDrawCreate(lpGUID, lplpDD, pUnkOuter);\n\n /*\n printf(\" returning DDERR_DIRECTDRAWALREADYCREATED\\n\");\n return DDERR_DIRECTDRAWALREADYCREATED;\n */\n } \n\n IDirectDrawImpl *This = (IDirectDrawImpl *)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(IDirectDrawImpl));\n This->lpVtbl = &iface;\n printf(\" This = %p\\n\", This);\n *lplpDD = (LPDIRECTDRAW)This;\n This->Ref = 0;\n ddraw_AddRef(This);\n\n ddraw = This;\n\n This->real_dll = LoadLibrary(\"system32\\\\ddraw.dll\");\n if(!This->real_dll)\n {\n ddraw_Release(This);\n return DDERR_GENERIC;\n }\n\n This->DirectDrawCreate = (HRESULT WINAPI (*)(GUID FAR*, LPDIRECTDRAW FAR*, IUnknown FAR*))GetProcAddress(This->real_dll, \"DirectDrawCreate\");\n\n if(!This->DirectDrawCreate)\n {\n ddraw_Release(This);\n return DDERR_GENERIC;\n }\n\n InitializeCriticalSection(&This->cs);\n This->render.ev = CreateEvent(NULL, TRUE, FALSE, NULL);\n This->render.sem = CreateSemaphore(NULL, 0, 1, NULL);\n\n /* load configuration options from ddraw.ini */\n char cwd[MAX_PATH];\n char ini_path[MAX_PATH];\n char tmp[256];\n GetCurrentDirectoryA(sizeof(cwd), cwd);\n snprintf(ini_path, sizeof(ini_path), \"%s\\\\ddraw.ini\", cwd);\n\n if(GetFileAttributes(ini_path) == 0xFFFFFFFF)\n {\n FILE *fh = fopen(ini_path, \"w\");\n fputs(\n \"[ddraw]\\n\"\n \"; width and height of the window, defaults to the size game requests\\r\\n\"\n \"width=0\\n\"\n \"height=0\\n\"\n \"; bits per pixel, possible values: 16, 24 and 32, 0 = auto\\n\"\n \"bpp=0\\n\"\n \"windowed=true\\n\"\n \"; show window borders in windowed mode\\n\"\n \"border=true\\n\"\n \"; use letter- or windowboxing to make a best fit (GDI only!)\\n\"\n \"boxing=false\\n\"\n \"; real rendering rate, -1 = screen rate, 0 = unlimited, n = cap\\n\"\n \"maxfps=0\\n\"\n \"; vertical synchronization, enable if you get tearing (OpenGL only)\\n\"\n \"vsync=false\\n\"\n \"; scaling filter, nearest = sharp, linear = smooth (OpenGL only)\\n\"\n \"filter=nearest\\n\"\n \"; automatic mouse sensitivity scaling\\n\"\n \"adjmouse=false\\n\"\n \"; manual sensitivity scaling, 0 = disabled, 0.5 = half, 1.0 = normal\\n\"\n \"sensitivity=0.0\\n\"\n \"; enable C&C/RA mouse hack\\n\"\n \"mhack=true\\n\"\n \"; enable C&C video resize hack, auto = auto-detect game, true = forced, false = disabled (OpenGL only)\\n\"\n \"vhack=false\\n\"\n \"; switch between OpenGL (opengl) and software (gdi) renderers, latter supports less features but might be faster depending on the GPU\\n\"\n \"renderer=gdi\\n\"\n \"; force CPU0 affinity, avoids crashes with RA, *might* have a performance impact\\n\"\n \"singlecpu=true\\n\"\n , fh);\n fclose(fh);\n }\n\n GetPrivateProfileStringA(\"ddraw\", \"windowed\", \"TRUE\", tmp, sizeof(tmp), ini_path);\n if (tolower(tmp[0]) == 'n' || tolower(tmp[0]) == 'f' || tolower(tmp[0]) == 'd' || tmp[0] == '0')\n {\n This->windowed = FALSE;\n }\n else\n {\n This->windowed = TRUE;\n }\n\n GetPrivateProfileStringA(\"ddraw\", \"border\", \"TRUE\", tmp, sizeof(tmp), ini_path);\n if (tolower(tmp[0]) == 'n' || tolower(tmp[0]) == 'f' || tolower(tmp[0]) == 'd' || tmp[0] == '0')\n {\n This->border = FALSE;\n }\n else\n {\n This->border = TRUE;\n }\n\n GetPrivateProfileStringA(\"ddraw\", \"boxing\", \"FALSE\", tmp, sizeof(tmp), ini_path);\n if (tolower(tmp[0]) == 'n' || tolower(tmp[0]) == 'f' || tolower(tmp[0]) == 'd' || tmp[0] == '0')\n {\n This->boxing = FALSE;\n }\n else\n {\n This->boxing = TRUE;\n }\n\n This->render.maxfps = GetPrivateProfileIntA(\"ddraw\", \"maxfps\", 0, ini_path);\n This->render.width = GetPrivateProfileIntA(\"ddraw\", \"width\", 0, ini_path);\n This->render.height = GetPrivateProfileIntA(\"ddraw\", \"height\", 0, ini_path);\n\n This->render.bpp = GetPrivateProfileIntA(\"ddraw\", \"bpp\", 32, ini_path);\n if (This->render.bpp != 16 && This->render.bpp != 24 && This->render.bpp != 32)\n {\n This->render.bpp = 0;\n }\n\n GetPrivateProfileStringA(\"ddraw\", \"filter\", tmp, tmp, sizeof(tmp), ini_path);\n if (tolower(tmp[0]) == 'l' || tolower(tmp[3]) == 'l')\n {\n This->render.filter = 1;\n }\n else\n {\n This->render.filter = 0;\n }\n\n GetPrivateProfileStringA(\"ddraw\", \"adjmouse\", \"FALSE\", tmp, sizeof(tmp), ini_path);\n if (tolower(tmp[0]) == 'y' || tolower(tmp[0]) == 't' || tolower(tmp[0]) == 'e' || tmp[0] == '1')\n {\n This->adjmouse = TRUE;\n }\n else\n {\n This->adjmouse = FALSE;\n }\n\n GetPrivateProfileStringA(\"ddraw\", \"mhack\", \"TRUE\", tmp, sizeof(tmp), ini_path);\n if (tolower(tmp[0]) == 'y' || tolower(tmp[0]) == 't' || tolower(tmp[0]) == 'e' || tmp[0] == '1')\n {\n This->mhack = TRUE;\n }\n else\n {\n This->mhack = FALSE;\n }\n\n GetPrivateProfileStringA(\"ddraw\", \"devmode\", \"FALSE\", tmp, sizeof(tmp), ini_path);\n if (tolower(tmp[0]) == 'y' || tolower(tmp[0]) == 't' || tolower(tmp[0]) == 'e' || tmp[0] == '1')\n {\n This->devmode = TRUE;\n This->mhack = FALSE;\n }\n else\n {\n This->devmode = FALSE;\n }\n\n GetPrivateProfileStringA(\"ddraw\", \"vsync\", \"FALSE\", tmp, sizeof(tmp), ini_path);\n if (tolower(tmp[0]) == 'y' || tolower(tmp[0]) == 't' || tolower(tmp[0]) == 'e' || tmp[0] == '1')\n {\n This->vsync = TRUE;\n }\n else\n {\n This->vsync = FALSE;\n }\n\n GetPrivateProfileStringA(\"ddraw\", \"sensitivity\", \"0\", tmp, sizeof(tmp), ini_path);\n This->sensitivity = strtof(tmp, NULL);\n\n GetPrivateProfileStringA(\"ddraw\", \"vhack\", \"false\", tmp, sizeof(tmp), ini_path);\n if (tolower(tmp[0]) == 'y' || tolower(tmp[0]) == 't' || tolower(tmp[0]) == 'e' || tmp[0] == '1')\n {\n This->vhack = 2;\n }\n else if(tolower(tmp[0]) == 'a')\n {\n This->vhack = 1;\n }\n else\n {\n This->vhack = 0;\n }\n\n GetPrivateProfileStringA(\"ddraw\", \"renderer\", \"gdi\", tmp, sizeof(tmp), ini_path);\n if(tolower(tmp[0]) == 'd' || tolower(tmp[0]) == 'd')\n {\n printf(\"DirectDrawCreate: Using dummy renderer\\n\");\n This->renderer = render_dummy_main;\n }\n else if(tolower(tmp[0]) == 's' || tolower(tmp[0]) == 'g')\n {\n printf(\"DirectDrawCreate: Using software renderer\\n\");\n This->renderer = render_soft_main;\n }\n else\n {\n printf(\"DirectDrawCreate: Using OpenGL renderer\\n\");\n This->renderer = render_main;\n }\n\n GetPrivateProfileStringA(\"ddraw\", \"singlecpu\", \"true\", tmp, sizeof(tmp), ini_path);\n if (tolower(tmp[0]) == 'y' || tolower(tmp[0]) == 't' || tolower(tmp[0]) == 'e' || tmp[0] == '1')\n {\n printf(\"DirectDrawCreate: Setting CPU0 affinity\\n\");\n SetProcessAffinityMask(GetCurrentProcess(), 1);\n }\n\n /* last minute check for cnc-plugin */\n if (GetEnvironmentVariable(\"DDRAW_WINDOW\", tmp, sizeof(tmp)) > 0)\n {\n This->hWnd = (HWND)atoi(tmp);\n This->renderer = render_dummy_main;\n This->windowed = TRUE;\n\n if (GetEnvironmentVariable(\"DDRAW_WIDTH\", tmp, sizeof(tmp)) > 0)\n {\n This->render.width = atoi(tmp);\n }\n\n if (GetEnvironmentVariable(\"DDRAW_HEIGHT\", tmp, sizeof(tmp)) > 0)\n {\n This->render.height = atoi(tmp);\n }\n\n printf(\"DirectDrawCreate: Detected cnc-plugin at window %08X in %dx%d\\n\", (unsigned int)This->hWnd, This->render.width, This->render.height);\n }\n\n\n return DD_OK;\n}\n", "render.c": "/*\n * Copyright (c) 2010 Toni Spets \n *\n * Permission to use, copy, modify, and distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n */\n\n/*\nEdits by Ben Lankamp\n\nAdded pillar box rendering for OpenGL\n*/\n#include \n#include \n\n#include \"main.h\"\n#include \"surface.h\"\n\n#define CUTSCENE_WIDTH 640\n#define CUTSCENE_HEIGHT 400\n\n#define ASPECT_RATIO 4/3\n\nBOOL detect_cutscene();\n\nDWORD WINAPI render_main(void)\n{\n int i,j,prevRow,nextRow;\n HGLRC hRC;\n\n // fixed: texture not square but ASPECT RATIO scaled\n int tex_width = ddraw->width > 1024 ? ddraw->width : 1024;\n int tex_height = ddraw->height > 768 ? ddraw->height : 768;\n float scale_w = 1.0f;\n float scale_h = 1.0f;\n int *tex = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, tex_width * tex_height * sizeof(int));\n\n hRC = wglCreateContext( ddraw->render.hDC );\n wglMakeCurrent( ddraw->render.hDC, hRC );\n\n char *glext = (char *)glGetString(GL_EXTENSIONS);\n\n if(glext && strstr(glext, \"WGL_EXT_swap_control\"))\n {\n BOOL (APIENTRY *wglSwapIntervalEXT)(int) = (BOOL (APIENTRY *)(int))wglGetProcAddress(\"wglSwapIntervalEXT\");\n if(wglSwapIntervalEXT)\n {\n if(ddraw->vsync)\n {\n wglSwapIntervalEXT(1);\n }\n else\n {\n wglSwapIntervalEXT(0);\n }\n }\n }\n\n DWORD tick_start = 0;\n DWORD tick_end = 0;\n DWORD frame_len = 0;\n\n if(ddraw->render.maxfps < 0)\n {\n ddraw->render.maxfps = ddraw->mode.dmDisplayFrequency;\n }\n\n if(ddraw->render.maxfps > 0)\n {\n frame_len = 1000.0f / ddraw->render.maxfps;\n }\n\n glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, tex_width, tex_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, tex);\n\n // define screen width and height\n // define projected width and height (aspect ratio preserved)\n int screenWidth = ddraw->render.width;\n int screenHeight = ddraw->render.height;\n\n // define projection width and height depending on the aspect ratio\n // this effectively sets a pillar box view\n int projectedHeight = screenHeight;\n int projectedWidth = projectedHeight * ASPECT_RATIO;\n int projectedLeft, projectedTop;\n\n if(ddraw->boxing)\n {\n projectedLeft = (screenWidth - projectedWidth) / 2;\n projectedTop = (screenHeight - projectedHeight) / 2;\n\n glViewport(projectedLeft, projectedTop, projectedWidth, projectedHeight);\n }\n else\n {\n projectedWidth = screenWidth;\n projectedHeight = screenHeight;\n glViewport(0, 0, screenWidth, screenHeight);\n }\n\n if(ddraw->render.filter)\n {\n glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);\n glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);\n }\n else\n {\n glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST);\n glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST);\n }\n\n glEnable(GL_TEXTURE_2D);\n\t\n\ttimeBeginPeriod(1);\n\t\n\n\n while(ddraw->render.run && WaitForSingleObject(ddraw->render.sem, INFINITE) != WAIT_FAILED)\n {\n\t\tscale_w = (float)ddraw->width/tex_width;\n\t\tscale_h = (float)ddraw->height/tex_height;\n\t\n if(ddraw->render.maxfps > 0)\n {\n tick_start = GetTickCount();\n }\n\n /* convert ddraw surface to opengl texture */\n EnterCriticalSection(&ddraw->cs);\n\n if(ddraw->primary && ddraw->primary->palette)\n {\n if(ddraw->vhack && detect_cutscene())\n {\n scale_w *= (float)CUTSCENE_WIDTH / ddraw->width;\n scale_h *= (float)CUTSCENE_HEIGHT / ddraw->height;\n\n if (ddraw->cursorclip.width != CUTSCENE_WIDTH || ddraw->cursorclip.height != CUTSCENE_HEIGHT)\n {\n ddraw->cursorclip.width = CUTSCENE_WIDTH;\n ddraw->cursorclip.height = CUTSCENE_HEIGHT;\n ddraw->cursor.x = CUTSCENE_WIDTH / 2;\n ddraw->cursor.y = CUTSCENE_HEIGHT / 2;\n }\n }\n else\n {\n if (ddraw->cursorclip.width != ddraw->width || ddraw->cursorclip.height != ddraw->height)\n {\n ddraw->cursorclip.width = ddraw->width;\n ddraw->cursorclip.height = ddraw->height;\n ddraw->cursor.x = ddraw->width / 2;\n ddraw->cursor.y = ddraw->height / 2;\n }\n }\n\n // regular paint\n for(i=0; iheight; i++)\n {\n for(j=0; jwidth; j++)\n {\n tex[i*ddraw->width+j] = ddraw->primary->palette->data_bgr[((unsigned char *)ddraw->primary->surface)[i*ddraw->primary->lPitch + j*ddraw->primary->lXPitch]];\n }\n }\n\n // poor man's deinterlace\n if(ddraw->vhack && detect_cutscene())\n {\n for(i = 1; i < (ddraw->height - 1); i += 2)\n {\n for(j=0; jwidth; j++)\n {\n if(tex[i*ddraw->width+j] == 0)\n {\n prevRow = tex[(i-1)*ddraw->width+j];\n nextRow = tex[(i+1)*ddraw->width+j];\n\n tex[i*ddraw->width+j] = (prevRow+nextRow)/2;\n }\n }\n }\n }\n }\n LeaveCriticalSection(&ddraw->cs);\n\n glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, ddraw->width, ddraw->height, GL_RGBA, GL_UNSIGNED_BYTE, tex);\n\n glBegin(GL_TRIANGLE_FAN);\n glTexCoord2f(0,0); glVertex2f(-1, 1);\n glTexCoord2f(scale_w,0); glVertex2f( 1, 1);\n glTexCoord2f(scale_w,scale_h); glVertex2f( 1, -1);\n glTexCoord2f(0,scale_h); glVertex2f(-1, -1);\n glEnd();\n\t\t\n\t\tSwapBuffers(ddraw->render.hDC); \n\n if((ddraw->render.maxfps > 0))\n { \n\t\t\ttick_end = GetTickCount();\n\t\t\t\n if(tick_end - tick_start < frame_len)\n {\n\t\t\t\tSleep( frame_len - (tick_end - tick_start));\n }\n }\n\n SetEvent(ddraw->render.ev);\n }\n\ttimeEndPeriod(1);\n\t\t\n HeapFree(GetProcessHeap(), 0, tex);\n\n wglMakeCurrent(NULL, NULL);\n wglDeleteContext(hRC);\n\n return 0;\n}\n", "render_soft.c": "/*\n * Copyright (c) 2011 Toni Spets \n *\n * Permission to use, copy, modify, and distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n */\n\n#include \n#include \n\n#include \"main.h\"\n#include \"surface.h\"\n\n#define CUTSCENE_WIDTH 640\n#define CUTSCENE_HEIGHT 400\n\nstatic unsigned char getPixel(int x, int y)\n{\n\treturn ((unsigned char *)ddraw->primary->surface)[y*ddraw->primary->lPitch + x*ddraw->primary->lXPitch];\n}\n\nint* InMovie = (int*)0x00665F58;\nint* IsVQA640 = (int*)0x0065D7BC; \nBYTE* ShouldStretch = (BYTE*)0x00607D78;\n\nBOOL detect_cutscene()\n{\n\tif(ddraw->width <= CUTSCENE_WIDTH || ddraw->height <= CUTSCENE_HEIGHT)\n\t\treturn FALSE;\n\t\t\n\tif (ddraw->isredalert == TRUE)\n\t{\n\t\tif ((*InMovie && !*IsVQA640) || *ShouldStretch)\n\t\t{\n\t\t\treturn TRUE;\n\t\t}\n\t\treturn FALSE;\n\t}\n\n\treturn getPixel(CUTSCENE_WIDTH + 1, 0) == 0 || getPixel(CUTSCENE_WIDTH + 5, 1) == 0 ? TRUE : FALSE;\t\n}\n\nDWORD WINAPI render_soft_main(void)\n{\n PBITMAPINFO bmi = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(BITMAPINFOHEADER) + sizeof(RGBQUAD) * 256);\n\n bmi->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);\n bmi->bmiHeader.biWidth = ddraw->width;\n bmi->bmiHeader.biHeight = -ddraw->height;\n bmi->bmiHeader.biPlanes = 1;\n bmi->bmiHeader.biBitCount = ddraw->bpp;\n bmi->bmiHeader.biCompression = BI_RGB;\n\n DWORD dst_top = 0;\n DWORD dst_left = 0;\n DWORD dst_width = ddraw->render.width;\n DWORD dst_height = ddraw->render.height;\n\n DWORD tick_start = 0;\n DWORD tick_end = 0;\n DWORD frame_len = 0;\n\t\n\ttimeBeginPeriod(1);\n\n if (ddraw->boxing)\n {\n dst_width = ddraw->width;\n dst_height = ddraw->height;\n\n /* test if we can double scale the window */\n if (ddraw->width * 2 <= ddraw->render.width && ddraw->height * 2 <= ddraw->render.height)\n {\n dst_width *= 2;\n dst_height *= 2;\n }\n\n dst_top = ddraw->render.height / 2 - dst_height / 2;\n dst_left = ddraw->render.width / 2 - dst_width / 2;\n }\n\n if(ddraw->render.maxfps < 0)\n {\n ddraw->render.maxfps = ddraw->mode.dmDisplayFrequency;\n }\n\n if(ddraw->render.maxfps > 0)\n {\n frame_len = 1000.0f / ddraw->render.maxfps;\n }\n\n while (ddraw->render.run && WaitForSingleObject(ddraw->render.sem, INFINITE) != WAIT_FAILED)\n {\n if(ddraw->render.maxfps > 0)\n {\n tick_start = GetTickCount();\n }\n\t\t\n\t\t EnterCriticalSection(&ddraw->cs);\n\n if (ddraw->primary && (ddraw->primary->palette || ddraw->bpp == 16))\n {\n if (ddraw->primary->palette && ddraw->primary->palette->data_rgb == NULL)\n {\n ddraw->primary->palette->data_rgb = &bmi->bmiColors[0];\n }\n\n if ((ddraw->render.width != ddraw->width || ddraw->render.height != ddraw->height) && !(ddraw->vhack && detect_cutscene()) )\n {\n StretchDIBits(ddraw->render.hDC, dst_left, dst_top, dst_width, dst_height, 0, 0, ddraw->width, ddraw->height, ddraw->primary->surface, bmi, DIB_RGB_COLORS, SRCCOPY);\n }\n\t\t\telse if (!(ddraw->vhack && detect_cutscene()))\n\t\t\t{\n\t\t\t\tSetDIBitsToDevice(ddraw->render.hDC, 0, 0, ddraw->width, ddraw->height, 0, 0, 0, ddraw->height, ddraw->primary->surface, bmi, DIB_RGB_COLORS);\n\t\t\t}\n\n }\n\t\tif (ddraw->vhack && ddraw->primary && detect_cutscene()) // for vhack\n\t\t{\n\t\t\tif (ddraw->primary->palette && ddraw->primary->palette->data_rgb == NULL)\n {\n ddraw->primary->palette->data_rgb = &bmi->bmiColors[0];\n }\n\t\t\t// for 800 x 600:\n\t\t\t//StretchDIBits(ddraw->render.hDC, 0, 0, ddraw->render.width, ddraw->render.height, 0, 200, CUTSCENE_WIDTH, CUTSCENE_HEIGHT, ddraw->primary->surface, bmi, DIB_RGB_COLORS, SRCCOPY);\n\t\t\t\n\t\t\t\t\t\tStretchDIBits(ddraw->render.hDC, 0, 0, ddraw->render.width, ddraw->render.height, 0, ddraw->height-400, CUTSCENE_WIDTH, CUTSCENE_HEIGHT, ddraw->primary->surface, bmi, DIB_RGB_COLORS, SRCCOPY);\n\n\t\t\t\n\t\t\tif (ddraw->primary->palette && (ddraw->cursorclip.width != CUTSCENE_WIDTH || ddraw->cursorclip.height != CUTSCENE_HEIGHT))\n\t\t\t{\n\t\t\t\tddraw->cursorclip.width = CUTSCENE_WIDTH;\n\t\t\t\tddraw->cursorclip.height = CUTSCENE_HEIGHT;\n\t\t\t\tddraw->cursor.x = CUTSCENE_WIDTH / 2;\n\t\t\t\tddraw->cursor.y = CUTSCENE_HEIGHT / 2;\n\t\t\t}\n\t\t}\n\t\telse if(ddraw->primary && ddraw->primary->palette && (ddraw->cursorclip.width != ddraw->width || ddraw->cursorclip.height != ddraw->height))\n\t\t{\n\t\t\tddraw->cursorclip.width = ddraw->width;\n\t\t\tddraw->cursorclip.height = ddraw->height;\n\t\t\tddraw->cursor.x = ddraw->width / 2;\n\t\t\tddraw->cursor.y = ddraw->height / 2;\n\t\t}\n\n LeaveCriticalSection(&ddraw->cs);\n\n if((ddraw->render.maxfps > 0) && !detect_cutscene())\n {\n tick_end = GetTickCount();\n\n if(tick_end - tick_start < frame_len)\n {\n Sleep( frame_len - (tick_end - tick_start) + 1);\n }\n }\n SetEvent(ddraw->render.ev);\n }\n\ttimeEndPeriod(1);\n\n HeapFree(GetProcessHeap(), 0, bmi);\n\n return TRUE;\n}\n"}} -{"repo": "krisleech/jQuery-Character-Counter", "pr_number": 1, "title": "add a class if character limit exceed's ", "state": "closed", "merged_at": "2013-03-04T18:36:56Z", "additions": 37, "deletions": 21, "files_changed": ["counter.jquery.js", "index.html"], "files_before": {"counter.jquery.js": "(function($){\n $.fn.counter = function() {\n return this.each(function() {\n max_length = parseInt($(this).attr('data-max-length'));\n\n var length = $(this).val().length; \n $(this).parent().find('.counter_label').html(max_length-length + ' characters left');\n // bind on key up event\n $(this).keyup(function(){\n // calc length and truncate if needed\n var new_length = $(this).val().length;\n if (new_length > max_length-1) {\n $(this).val($(this).val().substring(0, options.max_length));\n }\n // update visual counter\n $(this).parent().find('.counter_label').html(max_length-new_length + ' characters left');\n });\n });\n };\n})(jQuery);\n\n\n", "index.html": "\n\n\n\n\t\n\tindex\n\t\n\t\n\t\n\t\n\t\n\n\n\t\n\t\n\t\n\t
            \n\t\t
            \n\t\t\t
            \n\t\t\t\n\t\t
            \n\t\t\n\t\t
            \n\t\t\t
            \n\t\t\t\n\t\t
            \t\t\n\t
            \n\n\n"}, "files_after": {"counter.jquery.js": "(function ($) {\n $.fn.counter = function (options) {\n var defaults={\n limitExceedClass:''\n };\n var options=$.extend({},defaults,options);\n return this.each(function () {\n max_length = parseInt($(this).attr('data-max-length'));\n\n var length = $(this).val().length;\n $(this).parent().find('.counter_label').html(max_length - length + ' characters left');\n // bind on key up event\n $(this).keyup(function () {\n // calc length and truncate if needed\n var new_length = $(this).val().length;\n if (new_length > max_length - 1) {\n $(this).parent().find('.counter_label').addClass(options.limitExceedClass);\n }\n else {\n $(this).parent().find('.counter_label').removeClass(options.limitExceedClass);\n }\n // update visual counter\n $(this).parent().find('.counter_label').html(max_length - new_length + ' characters left');\n });\n });\n };\n})(jQuery);\n$(document).ready(function () {\n $('textarea').counter();\n\n})\n\n\n", "index.html": "\n\n\n\n\t\n\tindex\n\t\n\t\n\t\n\t\n\t\n\t\n\n\n\t\n\t\n\t\n\t
            \n\t\t
            \n\t\t\t
            \n\t\t\t\n\t\t
            \n\t\t\n\t\t
            \n\t\t\t
            \n\t\t\t\n\t\t
            \t\t\n\t
            \n\n\n"}} -{"repo": "mgalgs/termship", "pr_number": 1, "title": "Use no-more-secrets", "state": "closed", "merged_at": "2016-09-19T09:33:24Z", "additions": 25, "deletions": 17, "files_changed": ["screen.c"], "files_before": {"screen.c": "/* -*- c-basic-offset: 2 -*- */\n/**\n * This file contains all the ui routines.\n */\n\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"gamepieces.h\"\n#include \"connection.h\"\n#include \"screen.h\"\n#include \"log.h\"\n#include \"common.h\"\n\n#define MAX_NAME 100\n\nextern Ship Shipset[];\nextern Ship PeerShipset[];\nchar global_user_name[MAX_NAME];\nchar peer_user_name[MAX_NAME];\nint user_mode;\ntypedef enum SHOT_SPOT {\n UNTOUCHED=0,\n MISS,\n HIT\n} SHOT_SPOT;\nSHOT_SPOT player_shots[BOARD_SIZE][BOARD_SIZE]; /* 1=hit, 2=miss */\nSHOT_SPOT peer_shots[BOARD_SIZE][BOARD_SIZE]; /* 1=hit, 2=miss */\n\n\nWINDOW *player_win;\nWINDOW *opponent_win;\nWINDOW *status_win;\n\nvoid place_hit_or_mis(WINDOW * win,int mesg, int x, int y, bool was_peer_shot)\n{\n //-2game -1 hit sink 1hit 0miss\n //deal with hits first\n\n if ((mesg == -2) || (mesg == -1) || (mesg == 1)) {\n wattron(win,COLOR_PAIR(4));\n mvwprintw(win, y+2, x*2+3,\"#\");\n wattroff(win,COLOR_PAIR(4));\n wrefresh(win);\n if (was_peer_shot)\n peer_shots[x][y] = HIT;\n else\n player_shots[x][y] = HIT;\n } else { // miss\n wattron(win,COLOR_PAIR(3));\n mvwprintw(win, y+2, x*2+3,\"@\");\n wattroff(win,COLOR_PAIR(3));\n wrefresh(win);\n if (was_peer_shot)\n peer_shots[x][y] = MISS;\n else\n player_shots[x][y] = MISS;\n }\n}\n\n/**\n * Display battlefields after exchanging boards.\n */\nvoid show_battlefields()\n{\n /* dump battlefields: */\n if (user_mode == SERVER_MODE) {\n write_to_log(\"player_shots:\\n\");\n for (int i=0; i 3+startx+20) {\n playerx -=2;\n player_pos.x--;\n move(playery, playerx);\n break;\n }\n break;\n case KEY_RIGHT:\n if (playerx < -3+startx+20+width) {\n playerx +=2;\n player_pos.x++;\n move(playery, playerx);\n break; \n }\n break;\n case KEY_UP:\n if (playery > 2+starty) {\n --playery;\n --player_pos.y;\n move(playery, playerx);\n break;\n }\n break;\n case KEY_DOWN:\n if (playery < starty+height-2) {\n ++playery;\n ++player_pos.y;\n move(playery, playerx);\n break; \n }\n case 10:\n case KEY_ENTER:\n if (player_shots[player_pos.x][player_pos.y] == UNTOUCHED) {\n *x = player_pos.x;\n *y = player_pos.y;\n return;\n } else {\n move(playery, playerx);\n }\n break;\n \n }\n } \n}\n\nvoid display_boards(void)\n{\n int startx, starty, width, height; \n int stat_width, stat_height;\n\n char players_grid[BOARD_SIZE][BOARD_SIZE];\n\n int f, h = 0;\n char t;\n int i;\n stat_height= 5;\n stat_width=50;\n\n keypad(stdscr, TRUE); \n height = 3+BOARD_SIZE; \n width = 14+BOARD_SIZE; \n starty = (LINES - height) / 2; \n startx = (COLS - width) / 2; \n clear();\n refresh(); \n\n player_win = newwin(height, width, starty, startx+20); \n box(player_win, 0, 0);\n wrefresh(player_win);\n\n opponent_win = newwin(height, width, starty, startx-20);\n box(opponent_win, 0, 0);\n wrefresh(opponent_win);\n\n status_win = newwin(stat_height, stat_width, starty+13, startx-20);\n\n create_grid(players_grid, Shipset);\n\n clear();\n refresh();\n\n mvprintw(starty-1, startx-15, global_user_name);\n mvwprintw(opponent_win, 1,1,\" A B C D E F G H I J\");\n wattron(opponent_win,COLOR_PAIR(2));\n mvwprintw(opponent_win, 1, 1, \" \");\n wattroff(opponent_win,COLOR_PAIR(2));\n\n for (h = 0; h -1);\n\n sprintf(msg, \"Game over! You %s!\\nPress any key to view battlefields.\", win_status ? \"won\" : \"lost\");\n show_message_box(msg);\n getch();\n exchange_shipsets(sock);\n show_battlefields();\n}\n\n\nvoid title_screen()\n{\n char *picture[] = {\n \" # # ( )\",\n \" ___#_#___|__\",\n \" _ |____________| _\",\n \" _=====| | | | | |==== _\",\n \" =====| |.---------------------------. | |====\",\n \" <--------------------' . . . . . . . . '--------------/\",\n \" \\\\ /\",\n \" \\\\_______________________________________________WWS_________/\",\n \" wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww\",\n \"wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww\",\n \" wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww\",\n NULL\n };\n\n print_picture(stdscr, picture);\n\n /* int numsquiggles = 8; */\n /* int numreps = 2; */\n /* int framespeed = 60000; */\n /* do a little \"animation\" */\n /* for (int i=0; i0; --j) { */\n /* char msg[100]; */\n /* int s=0; */\n /* for (int k=0; k largest_line_length\n ? i-prev_newline_index\n : largest_line_length;\n prev_newline_index = i;\n if (string[i] == '\\n')\n height++;\n /* sprintf(msg, \"found newline or null at %d. now height is %d largest line is %d\\n\", i, height, largest_line_length); */\n /* write_to_log(msg); */\n }\n }\n largest_line_length = largest_line_length == 0\n ? strlen(string)\n : largest_line_length;\n /* sprintf(msg, \"At the end, now height is %d largest line is %d\\n\", height, largest_line_length); */\n /* write_to_log(msg); */\n\n width = largest_line_length + 6;\n\n\n /* if there's an existing message box up and this string is a\n different length than the last one, we need to recompute the\n width, so we just hide the message box. */\n if (*last_box_width != width || *last_box_height != height) {\n sprintf(msg, \"implicit hide of the message box because %d != %d || %d != %d\\n\",\n *last_box_width, width, *last_box_height, height);\n write_to_log(msg);\n hide_message_box_win(win, pan);\n }\n\n if (*win == NULL) {\n *win = newwin(height, width,\n (LINES-height)/2,\n (COLS-width)/2);\n sprintf(msg, \"created new win at *win %p\\n\", *win);\n write_to_log(msg);\n }\n if (*pan == NULL) {\n *pan = new_panel(*win);\n sprintf(msg, \"created new *pan at %p\\n\", *pan);\n write_to_log(msg);\n }\n wattron(*win, BLUE_ON_BLACK);\n box(*win, 0, 0);\n wattroff(*win, BLUE_ON_BLACK);\n /* border(186, 186, 205, 205, */\n /* 201, 187, 200, 188); */\n /* border(ls, rs, chtype ts, chtype bs, */\n /* chtype tl, chtype tr, chtype bl, chtype br); */\n\n int current_y = 1;\n wattron(*win, WHITE_ON_RED);\n for (int i=0; i maxlen ? len : maxlen;\n }\n return maxlen;\n}\n\nvoid print_picture(WINDOW *win, char *picture[])\n{\n /* get width of picture */\n int picwidth = get_picture_width(picture);\n int leftoffset = (COLS - picwidth)/2;\n int topoffset = 2;\n for (int i=0; picture[i] != NULL; ++i) {\n mvwprintw(win, topoffset+i, leftoffset, picture[i]);\n }\n}\n\n/**\n * dest should have enough space (at least len) to hold the string.\n */\nvoid get_text_string_from_centered_panel(char const *const prompt, char *dest, int len)\n{\n WINDOW *panel_win;\n PANEL *the_panel;\n int panel_height=6,panel_width;\n /* char *dest = malloc(100); */\n\n int promptlen = strlen(prompt);\n panel_width = MAX(30, promptlen+5);\n\n /* Create the window to hold the panel */\n panel_win = newwin(panel_height,\n panel_width,\n (LINES-panel_height)/2,\n (COLS-panel_width)/2);\n box(panel_win, 0, 0);\n print_in_middle(panel_win, 1,\n 0, panel_width,\n prompt, COLOR_PAIR(6));\n wattron(panel_win, COLOR_PAIR(5));\n mvwhline(panel_win, 3, 2, ' ', panel_width-4);\n curs_set(1); // make cursor visible\n echo();\n mvwgetnstr(panel_win, 3, 2, dest, len);\n noecho();\n curs_set(0); // make cursor invisible\n wattroff(panel_win, COLOR_PAIR(5));\n \n /* create the panel from our window */\n the_panel = new_panel(panel_win);\n top_panel(the_panel);\n update_panels();\n doupdate();\n\n del_panel(the_panel);\n update_panels();\n delwin(panel_win);\n doupdate();\n}\n\n\n/**\n * Constructs and returns a new Animation object. This doesn't load\n * the animation. That will be done at play time or you can call\n * load_animation to do it manually. The animation should be free'd by\n * the user.\n */\nAnimation *create_animation(char *loadFile)\n{\n Animation *anim = (Animation *)malloc(sizeof(Animation));\n KINDLY_DIE_IF_NULL(anim);\n anim->isLoaded = false;\n anim->loadFile = (char *) malloc(sizeof(char) * MAX_FILE_LEAF_NAME);\n KINDLY_DIE_IF_NULL(anim->loadFile);\n strcpy(anim->loadFile, loadFile);\n return anim;\n}\n\nvoid destroy_animation(Animation *anim)\n{\n for(int i=0; i < anim->numFrames; ++i) {\n free(anim->frames[i]);\n }\n free(anim->frames);\n free(anim->loadFile);\n free(anim);\n}\n\n\n/**\n * Loads up the animation. Make sure you set the `loadFile` attribute\n * of the Animation before calling this function.\n */\nvoid load_animation(Animation *anim)\n{\n FILE *fp;\n char msg[500], loadFileFullPath[MAX_FILE_FULL_PATH];\n char *line, *thisFrame;\n size_t len=0;\n ssize_t read;\n\n sprintf(loadFileFullPath, \"%s/animations/%s\", xstr(TERMSHIP_PATH), anim->loadFile);\n sprintf(msg, \"Loading animation file from %s...\\n\", loadFileFullPath);\n write_to_log(msg);\n\n fp = fopen(loadFileFullPath, \"r\");\n if (fp == NULL) {\n cleanup_ncurses();\n printf(\"couldn't open %s for reading...\\n\", loadFileFullPath);\n exit(EXIT_FAILURE);\n }\n\n /*** read the header lines: ***/\n /* First is the size (in lines) of each of the frames we're about to\n read */\n line = NULL;\n read = getline(&line, &len, fp);\n sscanf(line, \"%d\\n\", &(anim->height));\n free(line);\n sprintf(msg, \"%s has height %d\\n\", loadFileFullPath,\n anim->height);\n write_to_log(msg);\n /* Next is the total number of frames */\n line = NULL;\n read = getline(&line, &len, fp);\n sscanf(line, \"%d\\n\", &(anim->numFrames));\n free(line);\n sprintf(msg, \"%s has %d total frames\\n\", loadFileFullPath, anim->numFrames);\n write_to_log(msg);\n /* Next is the desired frame rate: */\n line = NULL;\n read = getline(&line, &len, fp);\n sscanf(line, \"%d\\n\", &(anim->fps));\n free(line);\n sprintf(msg, \"%s will run at %d fps\\n\", loadFileFullPath, anim->fps);\n write_to_log(msg);\n\n (void)read; /*compiler warnings*/\n\n /* Allocate space for the animation (the frames, not the actual lines quite yet): */\n anim->frames = (char **) malloc(sizeof(char *) * anim->numFrames);\n KINDLY_DIE_IF_NULL(anim->frames);\n thisFrame = (char *) malloc(sizeof(char) * anim->height * MAX_FRAME_WIDTH);\n KINDLY_DIE_IF_NULL(thisFrame);\n\n int max_width = 0;\n for (int i=0; i < anim->numFrames; ++i) {\n bool last_char_was_newline = false;\n int chars_read;\n for (chars_read=0; ; ++chars_read) {\n int ch = fgetc(fp);\n /* sprintf(msg, \"[%d] => %c\\n\", chars_read, (char)ch); */\n /* write_to_log(msg); */\n thisFrame[chars_read] = ch;\n if (ch == '\\n') {\n /* two newlines in a row. next frame. */\n if (last_char_was_newline)\n break;\n last_char_was_newline = true;\n } else {\n last_char_was_newline = false;\n }\n }\n thisFrame[chars_read-1] = '\\0'; /* overwriting the final newline */\n anim->frames[i] = (char *) malloc((sizeof(char) * chars_read)); /* don't need +1 because we truncated the last newline */\n KINDLY_DIE_IF_NULL(anim->frames[i]);\n strcpy(anim->frames[i], thisFrame);\n\n max_width = MAX(chars_read, max_width);\n\n } /*eo for each line*/\n\n free(thisFrame);\n\n anim->width = max_width;\n\n anim->isLoaded = true;\n}\n\n/**\n * Plays the specified animation. Loads it if necessary.\n */\nvoid play_animation\n(Animation *anim, char *subtitle, bool press_key_to_continue, bool hold_at_end)\n{\n static WINDOW *animation_window = NULL;\n static PANEL *animation_panel = NULL;\n static int anim_width;\n static int anim_height;\n char msg[500];\n (void)msg;\n char *hold_message = \"\\n(Press any key to continue)\";\n\n if (!anim->isLoaded) load_animation(anim);\n\n anim_width = anim->width;\n anim_height = anim->height;\n\n if (subtitle != NULL)\n anim_height++;\n\n\n\n for (int i=0; i < anim->numFrames; ++i) {\n char *theframe = anim->frames[i];\n if (subtitle != NULL) {\n theframe = (char *) malloc(strlen(anim->frames[i]) + strlen(subtitle) + 2); /* +2 for extra null and newline */\n KINDLY_DIE_IF_NULL(theframe);\n strcpy(theframe, anim->frames[i]);\n strcat(theframe, \"\\n\");\n strcat(theframe, subtitle);\n }\n\n show_message_box_win(&animation_window, &animation_panel,\n\t\t\t theframe, &anim_width, &anim_height);\n\n if (subtitle != NULL)\n free(theframe);\n\n if (press_key_to_continue) {\n /* no delay if press_key_to_continue is set: */\n nodelay(animation_window, true);\n if (ERR != wgetch(animation_window)) {\n\tnodelay(animation_window, false);\n\treturn;\n }\n nodelay(animation_window, false);\n }\n\n /* we assume the show_message_box_win takes 0 time */\n usleep( (1/(float)anim->fps) * 1000000 );\n }\n\n if (hold_at_end) {\n char *hold_frame = (char *) malloc(strlen(anim->frames[anim->numFrames-1]) + strlen(hold_message) + 1);\n KINDLY_DIE_IF_NULL(hold_frame);\n strcpy(hold_frame, anim->frames[anim->numFrames-1]);\n strcat(hold_frame, hold_message);\n show_message_box_win(&animation_window, &animation_panel,\n hold_frame, &anim_width, &anim_height);\n getch();\n free(hold_frame);\n }\n\n hide_message_box_win(&animation_window, &animation_panel);\n}\n\n\nvoid cleanup_ncurses()\n{\n endwin(); /* end curses mode */\n}\n\nvoid kindly_die(char *msg)\n{\n cleanup_ncurses();\n printf(msg);\n exit(-1);\n}\n"}, "files_after": {"screen.c": "/* -*- c-basic-offset: 2 -*- */\n/**\n * This file contains all the ui routines.\n */\n\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"gamepieces.h\"\n#include \"connection.h\"\n#include \"screen.h\"\n#include \"log.h\"\n#include \"common.h\"\n#include \"no-more-secrets/src/nms.h\"\n\n#define MAX_NAME 100\n\nextern Ship Shipset[];\nextern Ship PeerShipset[];\nchar global_user_name[MAX_NAME];\nchar peer_user_name[MAX_NAME];\nint user_mode;\ntypedef enum SHOT_SPOT {\n UNTOUCHED=0,\n MISS,\n HIT\n} SHOT_SPOT;\nSHOT_SPOT player_shots[BOARD_SIZE][BOARD_SIZE]; /* 1=hit, 2=miss */\nSHOT_SPOT peer_shots[BOARD_SIZE][BOARD_SIZE]; /* 1=hit, 2=miss */\n\n\nWINDOW *player_win;\nWINDOW *opponent_win;\nWINDOW *status_win;\n\nvoid place_hit_or_mis(WINDOW * win,int mesg, int x, int y, bool was_peer_shot)\n{\n //-2game -1 hit sink 1hit 0miss\n //deal with hits first\n\n if ((mesg == -2) || (mesg == -1) || (mesg == 1)) {\n wattron(win,COLOR_PAIR(4));\n mvwprintw(win, y+2, x*2+3,\"#\");\n wattroff(win,COLOR_PAIR(4));\n wrefresh(win);\n if (was_peer_shot)\n peer_shots[x][y] = HIT;\n else\n player_shots[x][y] = HIT;\n } else { // miss\n wattron(win,COLOR_PAIR(3));\n mvwprintw(win, y+2, x*2+3,\"@\");\n wattroff(win,COLOR_PAIR(3));\n wrefresh(win);\n if (was_peer_shot)\n peer_shots[x][y] = MISS;\n else\n player_shots[x][y] = MISS;\n }\n}\n\n/**\n * Display battlefields after exchanging boards.\n */\nvoid show_battlefields()\n{\n /* dump battlefields: */\n if (user_mode == SERVER_MODE) {\n write_to_log(\"player_shots:\\n\");\n for (int i=0; i 3+startx+20) {\n playerx -=2;\n player_pos.x--;\n move(playery, playerx);\n break;\n }\n break;\n case KEY_RIGHT:\n if (playerx < -3+startx+20+width) {\n playerx +=2;\n player_pos.x++;\n move(playery, playerx);\n break; \n }\n break;\n case KEY_UP:\n if (playery > 2+starty) {\n --playery;\n --player_pos.y;\n move(playery, playerx);\n break;\n }\n break;\n case KEY_DOWN:\n if (playery < starty+height-2) {\n ++playery;\n ++player_pos.y;\n move(playery, playerx);\n break; \n }\n case 10:\n case KEY_ENTER:\n if (player_shots[player_pos.x][player_pos.y] == UNTOUCHED) {\n *x = player_pos.x;\n *y = player_pos.y;\n return;\n } else {\n move(playery, playerx);\n }\n break;\n \n }\n } \n}\n\nvoid display_boards(void)\n{\n int startx, starty, width, height; \n int stat_width, stat_height;\n\n char players_grid[BOARD_SIZE][BOARD_SIZE];\n\n int f, h = 0;\n char t;\n int i;\n stat_height= 5;\n stat_width=50;\n\n keypad(stdscr, TRUE); \n height = 3+BOARD_SIZE; \n width = 14+BOARD_SIZE; \n starty = (LINES - height) / 2; \n startx = (COLS - width) / 2; \n clear();\n refresh(); \n\n player_win = newwin(height, width, starty, startx+20); \n box(player_win, 0, 0);\n wrefresh(player_win);\n\n opponent_win = newwin(height, width, starty, startx-20);\n box(opponent_win, 0, 0);\n wrefresh(opponent_win);\n\n status_win = newwin(stat_height, stat_width, starty+13, startx-20);\n\n create_grid(players_grid, Shipset);\n\n clear();\n refresh();\n\n mvprintw(starty-1, startx-15, global_user_name);\n mvwprintw(opponent_win, 1,1,\" A B C D E F G H I J\");\n wattron(opponent_win,COLOR_PAIR(2));\n mvwprintw(opponent_win, 1, 1, \" \");\n wattroff(opponent_win,COLOR_PAIR(2));\n\n for (h = 0; h -1);\n\n sprintf(msg, \"Game over! You %s!\\nPress any key to view battlefields.\", win_status ? \"won\" : \"lost\");\n show_message_box(msg);\n getch();\n exchange_shipsets(sock);\n show_battlefields();\n}\n\n\nvoid title_screen()\n{\n char *picture = \n \" # # ( )\\n\"\n \" ___#_#___|__\\n\"\n \" _ |____________| _\\n\"\n \" _=====| | | | | |==== _\\n\"\n \" =====| |.---------------------------. | |====\\n\"\n \" <--------------------' . . . . . . . . '--------------/\\n\"\n \" \\\\ /\\n\"\n \" \\\\_______________________________________________WWS_________/\\n\"\n \" wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww\\n\"\n \"wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww\\n\"\n \" wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww\\n\";\n\n NmsArgs args = INIT_NMSARGS;\n args.src = picture;\n nms_exec(&args);\n clear();\n //print_picture(stdscr, picture);\n\n /* int numsquiggles = 8; */\n /* int numreps = 2; */\n /* int framespeed = 60000; */\n /* do a little \"animation\" */\n /* for (int i=0; i0; --j) { */\n /* char msg[100]; */\n /* int s=0; */\n /* for (int k=0; k largest_line_length\n ? i-prev_newline_index\n : largest_line_length;\n prev_newline_index = i;\n if (string[i] == '\\n')\n height++;\n /* sprintf(msg, \"found newline or null at %d. now height is %d largest line is %d\\n\", i, height, largest_line_length); */\n /* write_to_log(msg); */\n }\n }\n largest_line_length = largest_line_length == 0\n ? strlen(string)\n : largest_line_length;\n /* sprintf(msg, \"At the end, now height is %d largest line is %d\\n\", height, largest_line_length); */\n /* write_to_log(msg); */\n\n width = largest_line_length + 6;\n\n\n /* if there's an existing message box up and this string is a\n different length than the last one, we need to recompute the\n width, so we just hide the message box. */\n if (*last_box_width != width || *last_box_height != height) {\n sprintf(msg, \"implicit hide of the message box because %d != %d || %d != %d\\n\",\n *last_box_width, width, *last_box_height, height);\n write_to_log(msg);\n hide_message_box_win(win, pan);\n }\n\n if (*win == NULL) {\n *win = newwin(height, width,\n (LINES-height)/2,\n (COLS-width)/2);\n sprintf(msg, \"created new win at *win %p\\n\", *win);\n write_to_log(msg);\n }\n if (*pan == NULL) {\n *pan = new_panel(*win);\n sprintf(msg, \"created new *pan at %p\\n\", *pan);\n write_to_log(msg);\n }\n wattron(*win, BLUE_ON_BLACK);\n box(*win, 0, 0);\n wattroff(*win, BLUE_ON_BLACK);\n /* border(186, 186, 205, 205, */\n /* 201, 187, 200, 188); */\n /* border(ls, rs, chtype ts, chtype bs, */\n /* chtype tl, chtype tr, chtype bl, chtype br); */\n\n int current_y = 1;\n wattron(*win, WHITE_ON_RED);\n for (int i=0; i maxlen ? len : maxlen;\n }\n return maxlen;\n}\n\nvoid print_picture(WINDOW *win, char *picture[])\n{\n /* get width of picture */\n int picwidth = get_picture_width(picture);\n int leftoffset = (COLS - picwidth)/2;\n int topoffset = 2;\n for (int i=0; picture[i] != NULL; ++i) {\n mvwprintw(win, topoffset+i, leftoffset, picture[i]);\n }\n}\n\n/**\n * dest should have enough space (at least len) to hold the string.\n */\nvoid get_text_string_from_centered_panel(char const *const prompt, char *dest, int len)\n{\n WINDOW *panel_win;\n PANEL *the_panel;\n int panel_height=6,panel_width;\n /* char *dest = malloc(100); */\n\n int promptlen = strlen(prompt);\n panel_width = MAX(30, promptlen+5);\n\n /* Create the window to hold the panel */\n panel_win = newwin(panel_height,\n panel_width,\n (LINES-panel_height)/2,\n (COLS-panel_width)/2);\n box(panel_win, 0, 0);\n print_in_middle(panel_win, 1,\n 0, panel_width,\n prompt, COLOR_PAIR(6));\n wattron(panel_win, COLOR_PAIR(5));\n mvwhline(panel_win, 3, 2, ' ', panel_width-4);\n curs_set(1); // make cursor visible\n echo();\n mvwgetnstr(panel_win, 3, 2, dest, len);\n noecho();\n curs_set(0); // make cursor invisible\n wattroff(panel_win, COLOR_PAIR(5));\n \n /* create the panel from our window */\n the_panel = new_panel(panel_win);\n top_panel(the_panel);\n update_panels();\n doupdate();\n\n del_panel(the_panel);\n update_panels();\n delwin(panel_win);\n doupdate();\n}\n\n\n/**\n * Constructs and returns a new Animation object. This doesn't load\n * the animation. That will be done at play time or you can call\n * load_animation to do it manually. The animation should be free'd by\n * the user.\n */\nAnimation *create_animation(char *loadFile)\n{\n Animation *anim = (Animation *)malloc(sizeof(Animation));\n KINDLY_DIE_IF_NULL(anim);\n anim->isLoaded = false;\n anim->loadFile = (char *) malloc(sizeof(char) * MAX_FILE_LEAF_NAME);\n KINDLY_DIE_IF_NULL(anim->loadFile);\n strcpy(anim->loadFile, loadFile);\n return anim;\n}\n\nvoid destroy_animation(Animation *anim)\n{\n for(int i=0; i < anim->numFrames; ++i) {\n free(anim->frames[i]);\n }\n free(anim->frames);\n free(anim->loadFile);\n free(anim);\n}\n\n\n/**\n * Loads up the animation. Make sure you set the `loadFile` attribute\n * of the Animation before calling this function.\n */\nvoid load_animation(Animation *anim)\n{\n FILE *fp;\n char msg[500], loadFileFullPath[MAX_FILE_FULL_PATH];\n char *line, *thisFrame;\n size_t len=0;\n ssize_t read;\n\n sprintf(loadFileFullPath, \"%s/animations/%s\", xstr(TERMSHIP_PATH), anim->loadFile);\n sprintf(msg, \"Loading animation file from %s...\\n\", loadFileFullPath);\n write_to_log(msg);\n\n fp = fopen(loadFileFullPath, \"r\");\n if (fp == NULL) {\n cleanup_ncurses();\n printf(\"couldn't open %s for reading...\\n\", loadFileFullPath);\n exit(EXIT_FAILURE);\n }\n\n /*** read the header lines: ***/\n /* First is the size (in lines) of each of the frames we're about to\n read */\n line = NULL;\n read = getline(&line, &len, fp);\n sscanf(line, \"%d\\n\", &(anim->height));\n free(line);\n sprintf(msg, \"%s has height %d\\n\", loadFileFullPath,\n anim->height);\n write_to_log(msg);\n /* Next is the total number of frames */\n line = NULL;\n read = getline(&line, &len, fp);\n sscanf(line, \"%d\\n\", &(anim->numFrames));\n free(line);\n sprintf(msg, \"%s has %d total frames\\n\", loadFileFullPath, anim->numFrames);\n write_to_log(msg);\n /* Next is the desired frame rate: */\n line = NULL;\n read = getline(&line, &len, fp);\n sscanf(line, \"%d\\n\", &(anim->fps));\n free(line);\n sprintf(msg, \"%s will run at %d fps\\n\", loadFileFullPath, anim->fps);\n write_to_log(msg);\n\n (void)read; /*compiler warnings*/\n\n /* Allocate space for the animation (the frames, not the actual lines quite yet): */\n anim->frames = (char **) malloc(sizeof(char *) * anim->numFrames);\n KINDLY_DIE_IF_NULL(anim->frames);\n thisFrame = (char *) malloc(sizeof(char) * anim->height * MAX_FRAME_WIDTH);\n KINDLY_DIE_IF_NULL(thisFrame);\n\n int max_width = 0;\n for (int i=0; i < anim->numFrames; ++i) {\n bool last_char_was_newline = false;\n int chars_read;\n for (chars_read=0; ; ++chars_read) {\n int ch = fgetc(fp);\n /* sprintf(msg, \"[%d] => %c\\n\", chars_read, (char)ch); */\n /* write_to_log(msg); */\n thisFrame[chars_read] = ch;\n if (ch == '\\n') {\n /* two newlines in a row. next frame. */\n if (last_char_was_newline)\n break;\n last_char_was_newline = true;\n } else {\n last_char_was_newline = false;\n }\n }\n thisFrame[chars_read-1] = '\\0'; /* overwriting the final newline */\n anim->frames[i] = (char *) malloc((sizeof(char) * chars_read)); /* don't need +1 because we truncated the last newline */\n KINDLY_DIE_IF_NULL(anim->frames[i]);\n strcpy(anim->frames[i], thisFrame);\n\n max_width = MAX(chars_read, max_width);\n\n } /*eo for each line*/\n\n free(thisFrame);\n\n anim->width = max_width;\n\n anim->isLoaded = true;\n}\n\n/**\n * Plays the specified animation. Loads it if necessary.\n */\nvoid play_animation\n(Animation *anim, char *subtitle, bool press_key_to_continue, bool hold_at_end)\n{\n static WINDOW *animation_window = NULL;\n static PANEL *animation_panel = NULL;\n static int anim_width;\n static int anim_height;\n char msg[500];\n (void)msg;\n char *hold_message = \"\\n(Press any key to continue)\";\n\n if (!anim->isLoaded) load_animation(anim);\n\n anim_width = anim->width;\n anim_height = anim->height;\n\n if (subtitle != NULL)\n anim_height++;\n\n\n\n for (int i=0; i < anim->numFrames; ++i) {\n char *theframe = anim->frames[i];\n if (subtitle != NULL) {\n theframe = (char *) malloc(strlen(anim->frames[i]) + strlen(subtitle) + 2); /* +2 for extra null and newline */\n KINDLY_DIE_IF_NULL(theframe);\n strcpy(theframe, anim->frames[i]);\n strcat(theframe, \"\\n\");\n strcat(theframe, subtitle);\n }\n\n show_message_box_win(&animation_window, &animation_panel,\n\t\t\t theframe, &anim_width, &anim_height);\n\n if (subtitle != NULL)\n free(theframe);\n\n if (press_key_to_continue) {\n /* no delay if press_key_to_continue is set: */\n nodelay(animation_window, true);\n if (ERR != wgetch(animation_window)) {\n\tnodelay(animation_window, false);\n\treturn;\n }\n nodelay(animation_window, false);\n }\n\n /* we assume the show_message_box_win takes 0 time */\n usleep( (1/(float)anim->fps) * 1000000 );\n }\n\n if (hold_at_end) {\n char *hold_frame = (char *) malloc(strlen(anim->frames[anim->numFrames-1]) + strlen(hold_message) + 1);\n KINDLY_DIE_IF_NULL(hold_frame);\n strcpy(hold_frame, anim->frames[anim->numFrames-1]);\n strcat(hold_frame, hold_message);\n show_message_box_win(&animation_window, &animation_panel,\n hold_frame, &anim_width, &anim_height);\n getch();\n free(hold_frame);\n }\n\n hide_message_box_win(&animation_window, &animation_panel);\n}\n\n\nvoid cleanup_ncurses()\n{\n endwin(); /* end curses mode */\n}\n\nvoid kindly_die(char *msg)\n{\n cleanup_ncurses();\n printf(msg);\n exit(-1);\n}\n"}} -{"repo": "digitalbazaar/forge", "pr_number": 1077, "title": "In CTR mode, support to encrypt/decrypt from the middle of a message", "state": "open", "merged_at": null, "additions": 5, "deletions": 2, "files_changed": ["lib/cipherModes.js"], "files_before": {"lib/cipherModes.js": "/**\n * Supported cipher modes.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./util');\n\nforge.cipher = forge.cipher || {};\n\n// supported cipher modes\nvar modes = module.exports = forge.cipher.modes = forge.cipher.modes || {};\n\n/** Electronic codebook (ECB) (Don't use this; it's not secure) **/\n\nmodes.ecb = function(options) {\n options = options || {};\n this.name = 'ECB';\n this.cipher = options.cipher;\n this.blockSize = options.blockSize || 16;\n this._ints = this.blockSize / 4;\n this._inBlock = new Array(this._ints);\n this._outBlock = new Array(this._ints);\n};\n\nmodes.ecb.prototype.start = function(options) {};\n\nmodes.ecb.prototype.encrypt = function(input, output, finish) {\n // not enough input to encrypt\n if(input.length() < this.blockSize && !(finish && input.length() > 0)) {\n return true;\n }\n\n // get next block\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = input.getInt32();\n }\n\n // encrypt block\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // write output\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(this._outBlock[i]);\n }\n};\n\nmodes.ecb.prototype.decrypt = function(input, output, finish) {\n // not enough input to decrypt\n if(input.length() < this.blockSize && !(finish && input.length() > 0)) {\n return true;\n }\n\n // get next block\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = input.getInt32();\n }\n\n // decrypt block\n this.cipher.decrypt(this._inBlock, this._outBlock);\n\n // write output\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(this._outBlock[i]);\n }\n};\n\nmodes.ecb.prototype.pad = function(input, options) {\n // add PKCS#7 padding to block (each pad byte is the\n // value of the number of pad bytes)\n var padding = (input.length() === this.blockSize ?\n this.blockSize : (this.blockSize - input.length()));\n input.fillWithByte(padding, padding);\n return true;\n};\n\nmodes.ecb.prototype.unpad = function(output, options) {\n // check for error: input data not a multiple of blockSize\n if(options.overflow > 0) {\n return false;\n }\n\n // ensure padding byte count is valid\n var len = output.length();\n var count = output.at(len - 1);\n if(count > (this.blockSize << 2)) {\n return false;\n }\n\n // trim off padding bytes\n output.truncate(count);\n return true;\n};\n\n/** Cipher-block Chaining (CBC) **/\n\nmodes.cbc = function(options) {\n options = options || {};\n this.name = 'CBC';\n this.cipher = options.cipher;\n this.blockSize = options.blockSize || 16;\n this._ints = this.blockSize / 4;\n this._inBlock = new Array(this._ints);\n this._outBlock = new Array(this._ints);\n};\n\nmodes.cbc.prototype.start = function(options) {\n // Note: legacy support for using IV residue (has security flaws)\n // if IV is null, reuse block from previous processing\n if(options.iv === null) {\n // must have a previous block\n if(!this._prev) {\n throw new Error('Invalid IV parameter.');\n }\n this._iv = this._prev.slice(0);\n } else if(!('iv' in options)) {\n throw new Error('Invalid IV parameter.');\n } else {\n // save IV as \"previous\" block\n this._iv = transformIV(options.iv, this.blockSize);\n this._prev = this._iv.slice(0);\n }\n};\n\nmodes.cbc.prototype.encrypt = function(input, output, finish) {\n // not enough input to encrypt\n if(input.length() < this.blockSize && !(finish && input.length() > 0)) {\n return true;\n }\n\n // get next block\n // CBC XOR's IV (or previous block) with plaintext\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = this._prev[i] ^ input.getInt32();\n }\n\n // encrypt block\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // write output, save previous block\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(this._outBlock[i]);\n }\n this._prev = this._outBlock;\n};\n\nmodes.cbc.prototype.decrypt = function(input, output, finish) {\n // not enough input to decrypt\n if(input.length() < this.blockSize && !(finish && input.length() > 0)) {\n return true;\n }\n\n // get next block\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = input.getInt32();\n }\n\n // decrypt block\n this.cipher.decrypt(this._inBlock, this._outBlock);\n\n // write output, save previous ciphered block\n // CBC XOR's IV (or previous block) with ciphertext\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(this._prev[i] ^ this._outBlock[i]);\n }\n this._prev = this._inBlock.slice(0);\n};\n\nmodes.cbc.prototype.pad = function(input, options) {\n // add PKCS#7 padding to block (each pad byte is the\n // value of the number of pad bytes)\n var padding = (input.length() === this.blockSize ?\n this.blockSize : (this.blockSize - input.length()));\n input.fillWithByte(padding, padding);\n return true;\n};\n\nmodes.cbc.prototype.unpad = function(output, options) {\n // check for error: input data not a multiple of blockSize\n if(options.overflow > 0) {\n return false;\n }\n\n // ensure padding byte count is valid\n var len = output.length();\n var count = output.at(len - 1);\n if(count > (this.blockSize << 2)) {\n return false;\n }\n\n // trim off padding bytes\n output.truncate(count);\n return true;\n};\n\n/** Cipher feedback (CFB) **/\n\nmodes.cfb = function(options) {\n options = options || {};\n this.name = 'CFB';\n this.cipher = options.cipher;\n this.blockSize = options.blockSize || 16;\n this._ints = this.blockSize / 4;\n this._inBlock = null;\n this._outBlock = new Array(this._ints);\n this._partialBlock = new Array(this._ints);\n this._partialOutput = forge.util.createBuffer();\n this._partialBytes = 0;\n};\n\nmodes.cfb.prototype.start = function(options) {\n if(!('iv' in options)) {\n throw new Error('Invalid IV parameter.');\n }\n // use IV as first input\n this._iv = transformIV(options.iv, this.blockSize);\n this._inBlock = this._iv.slice(0);\n this._partialBytes = 0;\n};\n\nmodes.cfb.prototype.encrypt = function(input, output, finish) {\n // not enough input to encrypt\n var inputLength = input.length();\n if(inputLength === 0) {\n return true;\n }\n\n // encrypt block\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // handle full block\n if(this._partialBytes === 0 && inputLength >= this.blockSize) {\n // XOR input with output, write input as output\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = input.getInt32() ^ this._outBlock[i];\n output.putInt32(this._inBlock[i]);\n }\n return;\n }\n\n // handle partial block\n var partialBytes = (this.blockSize - inputLength) % this.blockSize;\n if(partialBytes > 0) {\n partialBytes = this.blockSize - partialBytes;\n }\n\n // XOR input with output, write input as partial output\n this._partialOutput.clear();\n for(var i = 0; i < this._ints; ++i) {\n this._partialBlock[i] = input.getInt32() ^ this._outBlock[i];\n this._partialOutput.putInt32(this._partialBlock[i]);\n }\n\n if(partialBytes > 0) {\n // block still incomplete, restore input buffer\n input.read -= this.blockSize;\n } else {\n // block complete, update input block\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = this._partialBlock[i];\n }\n }\n\n // skip any previous partial bytes\n if(this._partialBytes > 0) {\n this._partialOutput.getBytes(this._partialBytes);\n }\n\n if(partialBytes > 0 && !finish) {\n output.putBytes(this._partialOutput.getBytes(\n partialBytes - this._partialBytes));\n this._partialBytes = partialBytes;\n return true;\n }\n\n output.putBytes(this._partialOutput.getBytes(\n inputLength - this._partialBytes));\n this._partialBytes = 0;\n};\n\nmodes.cfb.prototype.decrypt = function(input, output, finish) {\n // not enough input to decrypt\n var inputLength = input.length();\n if(inputLength === 0) {\n return true;\n }\n\n // encrypt block (CFB always uses encryption mode)\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // handle full block\n if(this._partialBytes === 0 && inputLength >= this.blockSize) {\n // XOR input with output, write input as output\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = input.getInt32();\n output.putInt32(this._inBlock[i] ^ this._outBlock[i]);\n }\n return;\n }\n\n // handle partial block\n var partialBytes = (this.blockSize - inputLength) % this.blockSize;\n if(partialBytes > 0) {\n partialBytes = this.blockSize - partialBytes;\n }\n\n // XOR input with output, write input as partial output\n this._partialOutput.clear();\n for(var i = 0; i < this._ints; ++i) {\n this._partialBlock[i] = input.getInt32();\n this._partialOutput.putInt32(this._partialBlock[i] ^ this._outBlock[i]);\n }\n\n if(partialBytes > 0) {\n // block still incomplete, restore input buffer\n input.read -= this.blockSize;\n } else {\n // block complete, update input block\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = this._partialBlock[i];\n }\n }\n\n // skip any previous partial bytes\n if(this._partialBytes > 0) {\n this._partialOutput.getBytes(this._partialBytes);\n }\n\n if(partialBytes > 0 && !finish) {\n output.putBytes(this._partialOutput.getBytes(\n partialBytes - this._partialBytes));\n this._partialBytes = partialBytes;\n return true;\n }\n\n output.putBytes(this._partialOutput.getBytes(\n inputLength - this._partialBytes));\n this._partialBytes = 0;\n};\n\n/** Output feedback (OFB) **/\n\nmodes.ofb = function(options) {\n options = options || {};\n this.name = 'OFB';\n this.cipher = options.cipher;\n this.blockSize = options.blockSize || 16;\n this._ints = this.blockSize / 4;\n this._inBlock = null;\n this._outBlock = new Array(this._ints);\n this._partialOutput = forge.util.createBuffer();\n this._partialBytes = 0;\n};\n\nmodes.ofb.prototype.start = function(options) {\n if(!('iv' in options)) {\n throw new Error('Invalid IV parameter.');\n }\n // use IV as first input\n this._iv = transformIV(options.iv, this.blockSize);\n this._inBlock = this._iv.slice(0);\n this._partialBytes = 0;\n};\n\nmodes.ofb.prototype.encrypt = function(input, output, finish) {\n // not enough input to encrypt\n var inputLength = input.length();\n if(input.length() === 0) {\n return true;\n }\n\n // encrypt block (OFB always uses encryption mode)\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // handle full block\n if(this._partialBytes === 0 && inputLength >= this.blockSize) {\n // XOR input with output and update next input\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(input.getInt32() ^ this._outBlock[i]);\n this._inBlock[i] = this._outBlock[i];\n }\n return;\n }\n\n // handle partial block\n var partialBytes = (this.blockSize - inputLength) % this.blockSize;\n if(partialBytes > 0) {\n partialBytes = this.blockSize - partialBytes;\n }\n\n // XOR input with output\n this._partialOutput.clear();\n for(var i = 0; i < this._ints; ++i) {\n this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]);\n }\n\n if(partialBytes > 0) {\n // block still incomplete, restore input buffer\n input.read -= this.blockSize;\n } else {\n // block complete, update input block\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = this._outBlock[i];\n }\n }\n\n // skip any previous partial bytes\n if(this._partialBytes > 0) {\n this._partialOutput.getBytes(this._partialBytes);\n }\n\n if(partialBytes > 0 && !finish) {\n output.putBytes(this._partialOutput.getBytes(\n partialBytes - this._partialBytes));\n this._partialBytes = partialBytes;\n return true;\n }\n\n output.putBytes(this._partialOutput.getBytes(\n inputLength - this._partialBytes));\n this._partialBytes = 0;\n};\n\nmodes.ofb.prototype.decrypt = modes.ofb.prototype.encrypt;\n\n/** Counter (CTR) **/\n\nmodes.ctr = function(options) {\n options = options || {};\n this.name = 'CTR';\n this.cipher = options.cipher;\n this.blockSize = options.blockSize || 16;\n this._ints = this.blockSize / 4;\n this._inBlock = null;\n this._outBlock = new Array(this._ints);\n this._partialOutput = forge.util.createBuffer();\n this._partialBytes = 0;\n};\n\nmodes.ctr.prototype.start = function(options) {\n if(!('iv' in options)) {\n throw new Error('Invalid IV parameter.');\n }\n // use IV as first input\n this._iv = transformIV(options.iv, this.blockSize);\n this._inBlock = this._iv.slice(0);\n this._partialBytes = 0;\n};\n\nmodes.ctr.prototype.encrypt = function(input, output, finish) {\n // not enough input to encrypt\n var inputLength = input.length();\n if(inputLength === 0) {\n return true;\n }\n\n // encrypt block (CTR always uses encryption mode)\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // handle full block\n if(this._partialBytes === 0 && inputLength >= this.blockSize) {\n // XOR input with output\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(input.getInt32() ^ this._outBlock[i]);\n }\n } else {\n // handle partial block\n var partialBytes = (this.blockSize - inputLength) % this.blockSize;\n if(partialBytes > 0) {\n partialBytes = this.blockSize - partialBytes;\n }\n\n // XOR input with output\n this._partialOutput.clear();\n for(var i = 0; i < this._ints; ++i) {\n this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]);\n }\n\n if(partialBytes > 0) {\n // block still incomplete, restore input buffer\n input.read -= this.blockSize;\n }\n\n // skip any previous partial bytes\n if(this._partialBytes > 0) {\n this._partialOutput.getBytes(this._partialBytes);\n }\n\n if(partialBytes > 0 && !finish) {\n output.putBytes(this._partialOutput.getBytes(\n partialBytes - this._partialBytes));\n this._partialBytes = partialBytes;\n return true;\n }\n\n output.putBytes(this._partialOutput.getBytes(\n inputLength - this._partialBytes));\n this._partialBytes = 0;\n }\n\n // block complete, increment counter (input block)\n inc32(this._inBlock);\n};\n\nmodes.ctr.prototype.decrypt = modes.ctr.prototype.encrypt;\n\n/** Galois/Counter Mode (GCM) **/\n\nmodes.gcm = function(options) {\n options = options || {};\n this.name = 'GCM';\n this.cipher = options.cipher;\n this.blockSize = options.blockSize || 16;\n this._ints = this.blockSize / 4;\n this._inBlock = new Array(this._ints);\n this._outBlock = new Array(this._ints);\n this._partialOutput = forge.util.createBuffer();\n this._partialBytes = 0;\n\n // R is actually this value concatenated with 120 more zero bits, but\n // we only XOR against R so the other zeros have no effect -- we just\n // apply this value to the first integer in a block\n this._R = 0xE1000000;\n};\n\nmodes.gcm.prototype.start = function(options) {\n if(!('iv' in options)) {\n throw new Error('Invalid IV parameter.');\n }\n // ensure IV is a byte buffer\n var iv = forge.util.createBuffer(options.iv);\n\n // no ciphered data processed yet\n this._cipherLength = 0;\n\n // default additional data is none\n var additionalData;\n if('additionalData' in options) {\n additionalData = forge.util.createBuffer(options.additionalData);\n } else {\n additionalData = forge.util.createBuffer();\n }\n\n // default tag length is 128 bits\n if('tagLength' in options) {\n this._tagLength = options.tagLength;\n } else {\n this._tagLength = 128;\n }\n\n // if tag is given, ensure tag matches tag length\n this._tag = null;\n if(options.decrypt) {\n // save tag to check later\n this._tag = forge.util.createBuffer(options.tag).getBytes();\n if(this._tag.length !== (this._tagLength / 8)) {\n throw new Error('Authentication tag does not match tag length.');\n }\n }\n\n // create tmp storage for hash calculation\n this._hashBlock = new Array(this._ints);\n\n // no tag generated yet\n this.tag = null;\n\n // generate hash subkey\n // (apply block cipher to \"zero\" block)\n this._hashSubkey = new Array(this._ints);\n this.cipher.encrypt([0, 0, 0, 0], this._hashSubkey);\n\n // generate table M\n // use 4-bit tables (32 component decomposition of a 16 byte value)\n // 8-bit tables take more space and are known to have security\n // vulnerabilities (in native implementations)\n this.componentBits = 4;\n this._m = this.generateHashTable(this._hashSubkey, this.componentBits);\n\n // Note: support IV length different from 96 bits? (only supporting\n // 96 bits is recommended by NIST SP-800-38D)\n // generate J_0\n var ivLength = iv.length();\n if(ivLength === 12) {\n // 96-bit IV\n this._j0 = [iv.getInt32(), iv.getInt32(), iv.getInt32(), 1];\n } else {\n // IV is NOT 96-bits\n this._j0 = [0, 0, 0, 0];\n while(iv.length() > 0) {\n this._j0 = this.ghash(\n this._hashSubkey, this._j0,\n [iv.getInt32(), iv.getInt32(), iv.getInt32(), iv.getInt32()]);\n }\n this._j0 = this.ghash(\n this._hashSubkey, this._j0, [0, 0].concat(from64To32(ivLength * 8)));\n }\n\n // generate ICB (initial counter block)\n this._inBlock = this._j0.slice(0);\n inc32(this._inBlock);\n this._partialBytes = 0;\n\n // consume authentication data\n additionalData = forge.util.createBuffer(additionalData);\n // save additional data length as a BE 64-bit number\n this._aDataLength = from64To32(additionalData.length() * 8);\n // pad additional data to 128 bit (16 byte) block size\n var overflow = additionalData.length() % this.blockSize;\n if(overflow) {\n additionalData.fillWithByte(0, this.blockSize - overflow);\n }\n this._s = [0, 0, 0, 0];\n while(additionalData.length() > 0) {\n this._s = this.ghash(this._hashSubkey, this._s, [\n additionalData.getInt32(),\n additionalData.getInt32(),\n additionalData.getInt32(),\n additionalData.getInt32()\n ]);\n }\n};\n\nmodes.gcm.prototype.encrypt = function(input, output, finish) {\n // not enough input to encrypt\n var inputLength = input.length();\n if(inputLength === 0) {\n return true;\n }\n\n // encrypt block\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // handle full block\n if(this._partialBytes === 0 && inputLength >= this.blockSize) {\n // XOR input with output\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(this._outBlock[i] ^= input.getInt32());\n }\n this._cipherLength += this.blockSize;\n } else {\n // handle partial block\n var partialBytes = (this.blockSize - inputLength) % this.blockSize;\n if(partialBytes > 0) {\n partialBytes = this.blockSize - partialBytes;\n }\n\n // XOR input with output\n this._partialOutput.clear();\n for(var i = 0; i < this._ints; ++i) {\n this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]);\n }\n\n if(partialBytes <= 0 || finish) {\n // handle overflow prior to hashing\n if(finish) {\n // get block overflow\n var overflow = inputLength % this.blockSize;\n this._cipherLength += overflow;\n // truncate for hash function\n this._partialOutput.truncate(this.blockSize - overflow);\n } else {\n this._cipherLength += this.blockSize;\n }\n\n // get output block for hashing\n for(var i = 0; i < this._ints; ++i) {\n this._outBlock[i] = this._partialOutput.getInt32();\n }\n this._partialOutput.read -= this.blockSize;\n }\n\n // skip any previous partial bytes\n if(this._partialBytes > 0) {\n this._partialOutput.getBytes(this._partialBytes);\n }\n\n if(partialBytes > 0 && !finish) {\n // block still incomplete, restore input buffer, get partial output,\n // and return early\n input.read -= this.blockSize;\n output.putBytes(this._partialOutput.getBytes(\n partialBytes - this._partialBytes));\n this._partialBytes = partialBytes;\n return true;\n }\n\n output.putBytes(this._partialOutput.getBytes(\n inputLength - this._partialBytes));\n this._partialBytes = 0;\n }\n\n // update hash block S\n this._s = this.ghash(this._hashSubkey, this._s, this._outBlock);\n\n // increment counter (input block)\n inc32(this._inBlock);\n};\n\nmodes.gcm.prototype.decrypt = function(input, output, finish) {\n // not enough input to decrypt\n var inputLength = input.length();\n if(inputLength < this.blockSize && !(finish && inputLength > 0)) {\n return true;\n }\n\n // encrypt block (GCM always uses encryption mode)\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // increment counter (input block)\n inc32(this._inBlock);\n\n // update hash block S\n this._hashBlock[0] = input.getInt32();\n this._hashBlock[1] = input.getInt32();\n this._hashBlock[2] = input.getInt32();\n this._hashBlock[3] = input.getInt32();\n this._s = this.ghash(this._hashSubkey, this._s, this._hashBlock);\n\n // XOR hash input with output\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(this._outBlock[i] ^ this._hashBlock[i]);\n }\n\n // increment cipher data length\n if(inputLength < this.blockSize) {\n this._cipherLength += inputLength % this.blockSize;\n } else {\n this._cipherLength += this.blockSize;\n }\n};\n\nmodes.gcm.prototype.afterFinish = function(output, options) {\n var rval = true;\n\n // handle overflow\n if(options.decrypt && options.overflow) {\n output.truncate(this.blockSize - options.overflow);\n }\n\n // handle authentication tag\n this.tag = forge.util.createBuffer();\n\n // concatenate additional data length with cipher length\n var lengths = this._aDataLength.concat(from64To32(this._cipherLength * 8));\n\n // include lengths in hash\n this._s = this.ghash(this._hashSubkey, this._s, lengths);\n\n // do GCTR(J_0, S)\n var tag = [];\n this.cipher.encrypt(this._j0, tag);\n for(var i = 0; i < this._ints; ++i) {\n this.tag.putInt32(this._s[i] ^ tag[i]);\n }\n\n // trim tag to length\n this.tag.truncate(this.tag.length() % (this._tagLength / 8));\n\n // check authentication tag\n if(options.decrypt && this.tag.bytes() !== this._tag) {\n rval = false;\n }\n\n return rval;\n};\n\n/**\n * See NIST SP-800-38D 6.3 (Algorithm 1). This function performs Galois\n * field multiplication. The field, GF(2^128), is defined by the polynomial:\n *\n * x^128 + x^7 + x^2 + x + 1\n *\n * Which is represented in little-endian binary form as: 11100001 (0xe1). When\n * the value of a coefficient is 1, a bit is set. The value R, is the\n * concatenation of this value and 120 zero bits, yielding a 128-bit value\n * which matches the block size.\n *\n * This function will multiply two elements (vectors of bytes), X and Y, in\n * the field GF(2^128). The result is initialized to zero. For each bit of\n * X (out of 128), x_i, if x_i is set, then the result is multiplied (XOR'd)\n * by the current value of Y. For each bit, the value of Y will be raised by\n * a power of x (multiplied by the polynomial x). This can be achieved by\n * shifting Y once to the right. If the current value of Y, prior to being\n * multiplied by x, has 0 as its LSB, then it is a 127th degree polynomial.\n * Otherwise, we must divide by R after shifting to find the remainder.\n *\n * @param x the first block to multiply by the second.\n * @param y the second block to multiply by the first.\n *\n * @return the block result of the multiplication.\n */\nmodes.gcm.prototype.multiply = function(x, y) {\n var z_i = [0, 0, 0, 0];\n var v_i = y.slice(0);\n\n // calculate Z_128 (block has 128 bits)\n for(var i = 0; i < 128; ++i) {\n // if x_i is 0, Z_{i+1} = Z_i (unchanged)\n // else Z_{i+1} = Z_i ^ V_i\n // get x_i by finding 32-bit int position, then left shift 1 by remainder\n var x_i = x[(i / 32) | 0] & (1 << (31 - i % 32));\n if(x_i) {\n z_i[0] ^= v_i[0];\n z_i[1] ^= v_i[1];\n z_i[2] ^= v_i[2];\n z_i[3] ^= v_i[3];\n }\n\n // if LSB(V_i) is 1, V_i = V_i >> 1\n // else V_i = (V_i >> 1) ^ R\n this.pow(v_i, v_i);\n }\n\n return z_i;\n};\n\nmodes.gcm.prototype.pow = function(x, out) {\n // if LSB(x) is 1, x = x >>> 1\n // else x = (x >>> 1) ^ R\n var lsb = x[3] & 1;\n\n // always do x >>> 1:\n // starting with the rightmost integer, shift each integer to the right\n // one bit, pulling in the bit from the integer to the left as its top\n // most bit (do this for the last 3 integers)\n for(var i = 3; i > 0; --i) {\n out[i] = (x[i] >>> 1) | ((x[i - 1] & 1) << 31);\n }\n // shift the first integer normally\n out[0] = x[0] >>> 1;\n\n // if lsb was not set, then polynomial had a degree of 127 and doesn't\n // need to divided; otherwise, XOR with R to find the remainder; we only\n // need to XOR the first integer since R technically ends w/120 zero bits\n if(lsb) {\n out[0] ^= this._R;\n }\n};\n\nmodes.gcm.prototype.tableMultiply = function(x) {\n // assumes 4-bit tables are used\n var z = [0, 0, 0, 0];\n for(var i = 0; i < 32; ++i) {\n var idx = (i / 8) | 0;\n var x_i = (x[idx] >>> ((7 - (i % 8)) * 4)) & 0xF;\n var ah = this._m[i][x_i];\n z[0] ^= ah[0];\n z[1] ^= ah[1];\n z[2] ^= ah[2];\n z[3] ^= ah[3];\n }\n return z;\n};\n\n/**\n * A continuing version of the GHASH algorithm that operates on a single\n * block. The hash block, last hash value (Ym) and the new block to hash\n * are given.\n *\n * @param h the hash block.\n * @param y the previous value for Ym, use [0, 0, 0, 0] for a new hash.\n * @param x the block to hash.\n *\n * @return the hashed value (Ym).\n */\nmodes.gcm.prototype.ghash = function(h, y, x) {\n y[0] ^= x[0];\n y[1] ^= x[1];\n y[2] ^= x[2];\n y[3] ^= x[3];\n return this.tableMultiply(y);\n //return this.multiply(y, h);\n};\n\n/**\n * Precomputes a table for multiplying against the hash subkey. This\n * mechanism provides a substantial speed increase over multiplication\n * performed without a table. The table-based multiplication this table is\n * for solves X * H by multiplying each component of X by H and then\n * composing the results together using XOR.\n *\n * This function can be used to generate tables with different bit sizes\n * for the components, however, this implementation assumes there are\n * 32 components of X (which is a 16 byte vector), therefore each component\n * takes 4-bits (so the table is constructed with bits=4).\n *\n * @param h the hash subkey.\n * @param bits the bit size for a component.\n */\nmodes.gcm.prototype.generateHashTable = function(h, bits) {\n // TODO: There are further optimizations that would use only the\n // first table M_0 (or some variant) along with a remainder table;\n // this can be explored in the future\n var multiplier = 8 / bits;\n var perInt = 4 * multiplier;\n var size = 16 * multiplier;\n var m = new Array(size);\n for(var i = 0; i < size; ++i) {\n var tmp = [0, 0, 0, 0];\n var idx = (i / perInt) | 0;\n var shft = ((perInt - 1 - (i % perInt)) * bits);\n tmp[idx] = (1 << (bits - 1)) << shft;\n m[i] = this.generateSubHashTable(this.multiply(tmp, h), bits);\n }\n return m;\n};\n\n/**\n * Generates a table for multiplying against the hash subkey for one\n * particular component (out of all possible component values).\n *\n * @param mid the pre-multiplied value for the middle key of the table.\n * @param bits the bit size for a component.\n */\nmodes.gcm.prototype.generateSubHashTable = function(mid, bits) {\n // compute the table quickly by minimizing the number of\n // POW operations -- they only need to be performed for powers of 2,\n // all other entries can be composed from those powers using XOR\n var size = 1 << bits;\n var half = size >>> 1;\n var m = new Array(size);\n m[half] = mid.slice(0);\n var i = half >>> 1;\n while(i > 0) {\n // raise m0[2 * i] and store in m0[i]\n this.pow(m[2 * i], m[i] = []);\n i >>= 1;\n }\n i = 2;\n while(i < half) {\n for(var j = 1; j < i; ++j) {\n var m_i = m[i];\n var m_j = m[j];\n m[i + j] = [\n m_i[0] ^ m_j[0],\n m_i[1] ^ m_j[1],\n m_i[2] ^ m_j[2],\n m_i[3] ^ m_j[3]\n ];\n }\n i *= 2;\n }\n m[0] = [0, 0, 0, 0];\n /* Note: We could avoid storing these by doing composition during multiply\n calculate top half using composition by speed is preferred. */\n for(i = half + 1; i < size; ++i) {\n var c = m[i ^ half];\n m[i] = [mid[0] ^ c[0], mid[1] ^ c[1], mid[2] ^ c[2], mid[3] ^ c[3]];\n }\n return m;\n};\n\n/** Utility functions */\n\nfunction transformIV(iv, blockSize) {\n if(typeof iv === 'string') {\n // convert iv string into byte buffer\n iv = forge.util.createBuffer(iv);\n }\n\n if(forge.util.isArray(iv) && iv.length > 4) {\n // convert iv byte array into byte buffer\n var tmp = iv;\n iv = forge.util.createBuffer();\n for(var i = 0; i < tmp.length; ++i) {\n iv.putByte(tmp[i]);\n }\n }\n\n if(iv.length() < blockSize) {\n throw new Error(\n 'Invalid IV length; got ' + iv.length() +\n ' bytes and expected ' + blockSize + ' bytes.');\n }\n\n if(!forge.util.isArray(iv)) {\n // convert iv byte buffer into 32-bit integer array\n var ints = [];\n var blocks = blockSize / 4;\n for(var i = 0; i < blocks; ++i) {\n ints.push(iv.getInt32());\n }\n iv = ints;\n }\n\n return iv;\n}\n\nfunction inc32(block) {\n // increment last 32 bits of block only\n block[block.length - 1] = (block[block.length - 1] + 1) & 0xFFFFFFFF;\n}\n\nfunction from64To32(num) {\n // convert 64-bit number to two BE Int32s\n return [(num / 0x100000000) | 0, num & 0xFFFFFFFF];\n}\n"}, "files_after": {"lib/cipherModes.js": "/**\n * Supported cipher modes.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./util');\n\nforge.cipher = forge.cipher || {};\n\n// supported cipher modes\nvar modes = module.exports = forge.cipher.modes = forge.cipher.modes || {};\n\n/** Electronic codebook (ECB) (Don't use this; it's not secure) **/\n\nmodes.ecb = function(options) {\n options = options || {};\n this.name = 'ECB';\n this.cipher = options.cipher;\n this.blockSize = options.blockSize || 16;\n this._ints = this.blockSize / 4;\n this._inBlock = new Array(this._ints);\n this._outBlock = new Array(this._ints);\n};\n\nmodes.ecb.prototype.start = function(options) {};\n\nmodes.ecb.prototype.encrypt = function(input, output, finish) {\n // not enough input to encrypt\n if(input.length() < this.blockSize && !(finish && input.length() > 0)) {\n return true;\n }\n\n // get next block\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = input.getInt32();\n }\n\n // encrypt block\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // write output\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(this._outBlock[i]);\n }\n};\n\nmodes.ecb.prototype.decrypt = function(input, output, finish) {\n // not enough input to decrypt\n if(input.length() < this.blockSize && !(finish && input.length() > 0)) {\n return true;\n }\n\n // get next block\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = input.getInt32();\n }\n\n // decrypt block\n this.cipher.decrypt(this._inBlock, this._outBlock);\n\n // write output\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(this._outBlock[i]);\n }\n};\n\nmodes.ecb.prototype.pad = function(input, options) {\n // add PKCS#7 padding to block (each pad byte is the\n // value of the number of pad bytes)\n var padding = (input.length() === this.blockSize ?\n this.blockSize : (this.blockSize - input.length()));\n input.fillWithByte(padding, padding);\n return true;\n};\n\nmodes.ecb.prototype.unpad = function(output, options) {\n // check for error: input data not a multiple of blockSize\n if(options.overflow > 0) {\n return false;\n }\n\n // ensure padding byte count is valid\n var len = output.length();\n var count = output.at(len - 1);\n if(count > (this.blockSize << 2)) {\n return false;\n }\n\n // trim off padding bytes\n output.truncate(count);\n return true;\n};\n\n/** Cipher-block Chaining (CBC) **/\n\nmodes.cbc = function(options) {\n options = options || {};\n this.name = 'CBC';\n this.cipher = options.cipher;\n this.blockSize = options.blockSize || 16;\n this._ints = this.blockSize / 4;\n this._inBlock = new Array(this._ints);\n this._outBlock = new Array(this._ints);\n};\n\nmodes.cbc.prototype.start = function(options) {\n // Note: legacy support for using IV residue (has security flaws)\n // if IV is null, reuse block from previous processing\n if(options.iv === null) {\n // must have a previous block\n if(!this._prev) {\n throw new Error('Invalid IV parameter.');\n }\n this._iv = this._prev.slice(0);\n } else if(!('iv' in options)) {\n throw new Error('Invalid IV parameter.');\n } else {\n // save IV as \"previous\" block\n this._iv = transformIV(options.iv, this.blockSize);\n this._prev = this._iv.slice(0);\n }\n};\n\nmodes.cbc.prototype.encrypt = function(input, output, finish) {\n // not enough input to encrypt\n if(input.length() < this.blockSize && !(finish && input.length() > 0)) {\n return true;\n }\n\n // get next block\n // CBC XOR's IV (or previous block) with plaintext\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = this._prev[i] ^ input.getInt32();\n }\n\n // encrypt block\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // write output, save previous block\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(this._outBlock[i]);\n }\n this._prev = this._outBlock;\n};\n\nmodes.cbc.prototype.decrypt = function(input, output, finish) {\n // not enough input to decrypt\n if(input.length() < this.blockSize && !(finish && input.length() > 0)) {\n return true;\n }\n\n // get next block\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = input.getInt32();\n }\n\n // decrypt block\n this.cipher.decrypt(this._inBlock, this._outBlock);\n\n // write output, save previous ciphered block\n // CBC XOR's IV (or previous block) with ciphertext\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(this._prev[i] ^ this._outBlock[i]);\n }\n this._prev = this._inBlock.slice(0);\n};\n\nmodes.cbc.prototype.pad = function(input, options) {\n // add PKCS#7 padding to block (each pad byte is the\n // value of the number of pad bytes)\n var padding = (input.length() === this.blockSize ?\n this.blockSize : (this.blockSize - input.length()));\n input.fillWithByte(padding, padding);\n return true;\n};\n\nmodes.cbc.prototype.unpad = function(output, options) {\n // check for error: input data not a multiple of blockSize\n if(options.overflow > 0) {\n return false;\n }\n\n // ensure padding byte count is valid\n var len = output.length();\n var count = output.at(len - 1);\n if(count > (this.blockSize << 2)) {\n return false;\n }\n\n // trim off padding bytes\n output.truncate(count);\n return true;\n};\n\n/** Cipher feedback (CFB) **/\n\nmodes.cfb = function(options) {\n options = options || {};\n this.name = 'CFB';\n this.cipher = options.cipher;\n this.blockSize = options.blockSize || 16;\n this._ints = this.blockSize / 4;\n this._inBlock = null;\n this._outBlock = new Array(this._ints);\n this._partialBlock = new Array(this._ints);\n this._partialOutput = forge.util.createBuffer();\n this._partialBytes = 0;\n};\n\nmodes.cfb.prototype.start = function(options) {\n if(!('iv' in options)) {\n throw new Error('Invalid IV parameter.');\n }\n // use IV as first input\n this._iv = transformIV(options.iv, this.blockSize);\n this._inBlock = this._iv.slice(0);\n this._partialBytes = 0;\n};\n\nmodes.cfb.prototype.encrypt = function(input, output, finish) {\n // not enough input to encrypt\n var inputLength = input.length();\n if(inputLength === 0) {\n return true;\n }\n\n // encrypt block\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // handle full block\n if(this._partialBytes === 0 && inputLength >= this.blockSize) {\n // XOR input with output, write input as output\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = input.getInt32() ^ this._outBlock[i];\n output.putInt32(this._inBlock[i]);\n }\n return;\n }\n\n // handle partial block\n var partialBytes = (this.blockSize - inputLength) % this.blockSize;\n if(partialBytes > 0) {\n partialBytes = this.blockSize - partialBytes;\n }\n\n // XOR input with output, write input as partial output\n this._partialOutput.clear();\n for(var i = 0; i < this._ints; ++i) {\n this._partialBlock[i] = input.getInt32() ^ this._outBlock[i];\n this._partialOutput.putInt32(this._partialBlock[i]);\n }\n\n if(partialBytes > 0) {\n // block still incomplete, restore input buffer\n input.read -= this.blockSize;\n } else {\n // block complete, update input block\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = this._partialBlock[i];\n }\n }\n\n // skip any previous partial bytes\n if(this._partialBytes > 0) {\n this._partialOutput.getBytes(this._partialBytes);\n }\n\n if(partialBytes > 0 && !finish) {\n output.putBytes(this._partialOutput.getBytes(\n partialBytes - this._partialBytes));\n this._partialBytes = partialBytes;\n return true;\n }\n\n output.putBytes(this._partialOutput.getBytes(\n inputLength - this._partialBytes));\n this._partialBytes = 0;\n};\n\nmodes.cfb.prototype.decrypt = function(input, output, finish) {\n // not enough input to decrypt\n var inputLength = input.length();\n if(inputLength === 0) {\n return true;\n }\n\n // encrypt block (CFB always uses encryption mode)\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // handle full block\n if(this._partialBytes === 0 && inputLength >= this.blockSize) {\n // XOR input with output, write input as output\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = input.getInt32();\n output.putInt32(this._inBlock[i] ^ this._outBlock[i]);\n }\n return;\n }\n\n // handle partial block\n var partialBytes = (this.blockSize - inputLength) % this.blockSize;\n if(partialBytes > 0) {\n partialBytes = this.blockSize - partialBytes;\n }\n\n // XOR input with output, write input as partial output\n this._partialOutput.clear();\n for(var i = 0; i < this._ints; ++i) {\n this._partialBlock[i] = input.getInt32();\n this._partialOutput.putInt32(this._partialBlock[i] ^ this._outBlock[i]);\n }\n\n if(partialBytes > 0) {\n // block still incomplete, restore input buffer\n input.read -= this.blockSize;\n } else {\n // block complete, update input block\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = this._partialBlock[i];\n }\n }\n\n // skip any previous partial bytes\n if(this._partialBytes > 0) {\n this._partialOutput.getBytes(this._partialBytes);\n }\n\n if(partialBytes > 0 && !finish) {\n output.putBytes(this._partialOutput.getBytes(\n partialBytes - this._partialBytes));\n this._partialBytes = partialBytes;\n return true;\n }\n\n output.putBytes(this._partialOutput.getBytes(\n inputLength - this._partialBytes));\n this._partialBytes = 0;\n};\n\n/** Output feedback (OFB) **/\n\nmodes.ofb = function(options) {\n options = options || {};\n this.name = 'OFB';\n this.cipher = options.cipher;\n this.blockSize = options.blockSize || 16;\n this._ints = this.blockSize / 4;\n this._inBlock = null;\n this._outBlock = new Array(this._ints);\n this._partialOutput = forge.util.createBuffer();\n this._partialBytes = 0;\n};\n\nmodes.ofb.prototype.start = function(options) {\n if(!('iv' in options)) {\n throw new Error('Invalid IV parameter.');\n }\n // use IV as first input\n this._iv = transformIV(options.iv, this.blockSize);\n this._inBlock = this._iv.slice(0);\n this._partialBytes = 0;\n};\n\nmodes.ofb.prototype.encrypt = function(input, output, finish) {\n // not enough input to encrypt\n var inputLength = input.length();\n if(input.length() === 0) {\n return true;\n }\n\n // encrypt block (OFB always uses encryption mode)\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // handle full block\n if(this._partialBytes === 0 && inputLength >= this.blockSize) {\n // XOR input with output and update next input\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(input.getInt32() ^ this._outBlock[i]);\n this._inBlock[i] = this._outBlock[i];\n }\n return;\n }\n\n // handle partial block\n var partialBytes = (this.blockSize - inputLength) % this.blockSize;\n if(partialBytes > 0) {\n partialBytes = this.blockSize - partialBytes;\n }\n\n // XOR input with output\n this._partialOutput.clear();\n for(var i = 0; i < this._ints; ++i) {\n this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]);\n }\n\n if(partialBytes > 0) {\n // block still incomplete, restore input buffer\n input.read -= this.blockSize;\n } else {\n // block complete, update input block\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = this._outBlock[i];\n }\n }\n\n // skip any previous partial bytes\n if(this._partialBytes > 0) {\n this._partialOutput.getBytes(this._partialBytes);\n }\n\n if(partialBytes > 0 && !finish) {\n output.putBytes(this._partialOutput.getBytes(\n partialBytes - this._partialBytes));\n this._partialBytes = partialBytes;\n return true;\n }\n\n output.putBytes(this._partialOutput.getBytes(\n inputLength - this._partialBytes));\n this._partialBytes = 0;\n};\n\nmodes.ofb.prototype.decrypt = modes.ofb.prototype.encrypt;\n\n/** Counter (CTR) **/\n\nmodes.ctr = function(options) {\n options = options || {};\n this.name = 'CTR';\n this.cipher = options.cipher;\n this.blockSize = options.blockSize || 16;\n this._ints = this.blockSize / 4;\n this._inBlock = null;\n this._outBlock = new Array(this._ints);\n this._partialOutput = forge.util.createBuffer();\n this._partialBytes = 0;\n};\n\nmodes.ctr.prototype.start = function(options) {\n if(!('iv' in options)) {\n throw new Error('Invalid IV parameter.');\n }\n // use IV as first input\n this._iv = transformIV(options.iv, this.blockSize);\n this._inBlock = this._iv.slice(0);\n if(options.counter) {\n inc32(this._inBlock, options.counter);\n }\n this._partialBytes = 0;\n};\n\nmodes.ctr.prototype.encrypt = function(input, output, finish) {\n // not enough input to encrypt\n var inputLength = input.length();\n if(inputLength === 0) {\n return true;\n }\n\n // encrypt block (CTR always uses encryption mode)\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // handle full block\n if(this._partialBytes === 0 && inputLength >= this.blockSize) {\n // XOR input with output\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(input.getInt32() ^ this._outBlock[i]);\n }\n } else {\n // handle partial block\n var partialBytes = (this.blockSize - inputLength) % this.blockSize;\n if(partialBytes > 0) {\n partialBytes = this.blockSize - partialBytes;\n }\n\n // XOR input with output\n this._partialOutput.clear();\n for(var i = 0; i < this._ints; ++i) {\n this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]);\n }\n\n if(partialBytes > 0) {\n // block still incomplete, restore input buffer\n input.read -= this.blockSize;\n }\n\n // skip any previous partial bytes\n if(this._partialBytes > 0) {\n this._partialOutput.getBytes(this._partialBytes);\n }\n\n if(partialBytes > 0 && !finish) {\n output.putBytes(this._partialOutput.getBytes(\n partialBytes - this._partialBytes));\n this._partialBytes = partialBytes;\n return true;\n }\n\n output.putBytes(this._partialOutput.getBytes(\n inputLength - this._partialBytes));\n this._partialBytes = 0;\n }\n\n // block complete, increment counter (input block)\n inc32(this._inBlock);\n};\n\nmodes.ctr.prototype.decrypt = modes.ctr.prototype.encrypt;\n\n/** Galois/Counter Mode (GCM) **/\n\nmodes.gcm = function(options) {\n options = options || {};\n this.name = 'GCM';\n this.cipher = options.cipher;\n this.blockSize = options.blockSize || 16;\n this._ints = this.blockSize / 4;\n this._inBlock = new Array(this._ints);\n this._outBlock = new Array(this._ints);\n this._partialOutput = forge.util.createBuffer();\n this._partialBytes = 0;\n\n // R is actually this value concatenated with 120 more zero bits, but\n // we only XOR against R so the other zeros have no effect -- we just\n // apply this value to the first integer in a block\n this._R = 0xE1000000;\n};\n\nmodes.gcm.prototype.start = function(options) {\n if(!('iv' in options)) {\n throw new Error('Invalid IV parameter.');\n }\n // ensure IV is a byte buffer\n var iv = forge.util.createBuffer(options.iv);\n\n // no ciphered data processed yet\n this._cipherLength = 0;\n\n // default additional data is none\n var additionalData;\n if('additionalData' in options) {\n additionalData = forge.util.createBuffer(options.additionalData);\n } else {\n additionalData = forge.util.createBuffer();\n }\n\n // default tag length is 128 bits\n if('tagLength' in options) {\n this._tagLength = options.tagLength;\n } else {\n this._tagLength = 128;\n }\n\n // if tag is given, ensure tag matches tag length\n this._tag = null;\n if(options.decrypt) {\n // save tag to check later\n this._tag = forge.util.createBuffer(options.tag).getBytes();\n if(this._tag.length !== (this._tagLength / 8)) {\n throw new Error('Authentication tag does not match tag length.');\n }\n }\n\n // create tmp storage for hash calculation\n this._hashBlock = new Array(this._ints);\n\n // no tag generated yet\n this.tag = null;\n\n // generate hash subkey\n // (apply block cipher to \"zero\" block)\n this._hashSubkey = new Array(this._ints);\n this.cipher.encrypt([0, 0, 0, 0], this._hashSubkey);\n\n // generate table M\n // use 4-bit tables (32 component decomposition of a 16 byte value)\n // 8-bit tables take more space and are known to have security\n // vulnerabilities (in native implementations)\n this.componentBits = 4;\n this._m = this.generateHashTable(this._hashSubkey, this.componentBits);\n\n // Note: support IV length different from 96 bits? (only supporting\n // 96 bits is recommended by NIST SP-800-38D)\n // generate J_0\n var ivLength = iv.length();\n if(ivLength === 12) {\n // 96-bit IV\n this._j0 = [iv.getInt32(), iv.getInt32(), iv.getInt32(), 1];\n } else {\n // IV is NOT 96-bits\n this._j0 = [0, 0, 0, 0];\n while(iv.length() > 0) {\n this._j0 = this.ghash(\n this._hashSubkey, this._j0,\n [iv.getInt32(), iv.getInt32(), iv.getInt32(), iv.getInt32()]);\n }\n this._j0 = this.ghash(\n this._hashSubkey, this._j0, [0, 0].concat(from64To32(ivLength * 8)));\n }\n\n // generate ICB (initial counter block)\n this._inBlock = this._j0.slice(0);\n inc32(this._inBlock);\n this._partialBytes = 0;\n\n // consume authentication data\n additionalData = forge.util.createBuffer(additionalData);\n // save additional data length as a BE 64-bit number\n this._aDataLength = from64To32(additionalData.length() * 8);\n // pad additional data to 128 bit (16 byte) block size\n var overflow = additionalData.length() % this.blockSize;\n if(overflow) {\n additionalData.fillWithByte(0, this.blockSize - overflow);\n }\n this._s = [0, 0, 0, 0];\n while(additionalData.length() > 0) {\n this._s = this.ghash(this._hashSubkey, this._s, [\n additionalData.getInt32(),\n additionalData.getInt32(),\n additionalData.getInt32(),\n additionalData.getInt32()\n ]);\n }\n};\n\nmodes.gcm.prototype.encrypt = function(input, output, finish) {\n // not enough input to encrypt\n var inputLength = input.length();\n if(inputLength === 0) {\n return true;\n }\n\n // encrypt block\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // handle full block\n if(this._partialBytes === 0 && inputLength >= this.blockSize) {\n // XOR input with output\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(this._outBlock[i] ^= input.getInt32());\n }\n this._cipherLength += this.blockSize;\n } else {\n // handle partial block\n var partialBytes = (this.blockSize - inputLength) % this.blockSize;\n if(partialBytes > 0) {\n partialBytes = this.blockSize - partialBytes;\n }\n\n // XOR input with output\n this._partialOutput.clear();\n for(var i = 0; i < this._ints; ++i) {\n this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]);\n }\n\n if(partialBytes <= 0 || finish) {\n // handle overflow prior to hashing\n if(finish) {\n // get block overflow\n var overflow = inputLength % this.blockSize;\n this._cipherLength += overflow;\n // truncate for hash function\n this._partialOutput.truncate(this.blockSize - overflow);\n } else {\n this._cipherLength += this.blockSize;\n }\n\n // get output block for hashing\n for(var i = 0; i < this._ints; ++i) {\n this._outBlock[i] = this._partialOutput.getInt32();\n }\n this._partialOutput.read -= this.blockSize;\n }\n\n // skip any previous partial bytes\n if(this._partialBytes > 0) {\n this._partialOutput.getBytes(this._partialBytes);\n }\n\n if(partialBytes > 0 && !finish) {\n // block still incomplete, restore input buffer, get partial output,\n // and return early\n input.read -= this.blockSize;\n output.putBytes(this._partialOutput.getBytes(\n partialBytes - this._partialBytes));\n this._partialBytes = partialBytes;\n return true;\n }\n\n output.putBytes(this._partialOutput.getBytes(\n inputLength - this._partialBytes));\n this._partialBytes = 0;\n }\n\n // update hash block S\n this._s = this.ghash(this._hashSubkey, this._s, this._outBlock);\n\n // increment counter (input block)\n inc32(this._inBlock);\n};\n\nmodes.gcm.prototype.decrypt = function(input, output, finish) {\n // not enough input to decrypt\n var inputLength = input.length();\n if(inputLength < this.blockSize && !(finish && inputLength > 0)) {\n return true;\n }\n\n // encrypt block (GCM always uses encryption mode)\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // increment counter (input block)\n inc32(this._inBlock);\n\n // update hash block S\n this._hashBlock[0] = input.getInt32();\n this._hashBlock[1] = input.getInt32();\n this._hashBlock[2] = input.getInt32();\n this._hashBlock[3] = input.getInt32();\n this._s = this.ghash(this._hashSubkey, this._s, this._hashBlock);\n\n // XOR hash input with output\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(this._outBlock[i] ^ this._hashBlock[i]);\n }\n\n // increment cipher data length\n if(inputLength < this.blockSize) {\n this._cipherLength += inputLength % this.blockSize;\n } else {\n this._cipherLength += this.blockSize;\n }\n};\n\nmodes.gcm.prototype.afterFinish = function(output, options) {\n var rval = true;\n\n // handle overflow\n if(options.decrypt && options.overflow) {\n output.truncate(this.blockSize - options.overflow);\n }\n\n // handle authentication tag\n this.tag = forge.util.createBuffer();\n\n // concatenate additional data length with cipher length\n var lengths = this._aDataLength.concat(from64To32(this._cipherLength * 8));\n\n // include lengths in hash\n this._s = this.ghash(this._hashSubkey, this._s, lengths);\n\n // do GCTR(J_0, S)\n var tag = [];\n this.cipher.encrypt(this._j0, tag);\n for(var i = 0; i < this._ints; ++i) {\n this.tag.putInt32(this._s[i] ^ tag[i]);\n }\n\n // trim tag to length\n this.tag.truncate(this.tag.length() % (this._tagLength / 8));\n\n // check authentication tag\n if(options.decrypt && this.tag.bytes() !== this._tag) {\n rval = false;\n }\n\n return rval;\n};\n\n/**\n * See NIST SP-800-38D 6.3 (Algorithm 1). This function performs Galois\n * field multiplication. The field, GF(2^128), is defined by the polynomial:\n *\n * x^128 + x^7 + x^2 + x + 1\n *\n * Which is represented in little-endian binary form as: 11100001 (0xe1). When\n * the value of a coefficient is 1, a bit is set. The value R, is the\n * concatenation of this value and 120 zero bits, yielding a 128-bit value\n * which matches the block size.\n *\n * This function will multiply two elements (vectors of bytes), X and Y, in\n * the field GF(2^128). The result is initialized to zero. For each bit of\n * X (out of 128), x_i, if x_i is set, then the result is multiplied (XOR'd)\n * by the current value of Y. For each bit, the value of Y will be raised by\n * a power of x (multiplied by the polynomial x). This can be achieved by\n * shifting Y once to the right. If the current value of Y, prior to being\n * multiplied by x, has 0 as its LSB, then it is a 127th degree polynomial.\n * Otherwise, we must divide by R after shifting to find the remainder.\n *\n * @param x the first block to multiply by the second.\n * @param y the second block to multiply by the first.\n *\n * @return the block result of the multiplication.\n */\nmodes.gcm.prototype.multiply = function(x, y) {\n var z_i = [0, 0, 0, 0];\n var v_i = y.slice(0);\n\n // calculate Z_128 (block has 128 bits)\n for(var i = 0; i < 128; ++i) {\n // if x_i is 0, Z_{i+1} = Z_i (unchanged)\n // else Z_{i+1} = Z_i ^ V_i\n // get x_i by finding 32-bit int position, then left shift 1 by remainder\n var x_i = x[(i / 32) | 0] & (1 << (31 - i % 32));\n if(x_i) {\n z_i[0] ^= v_i[0];\n z_i[1] ^= v_i[1];\n z_i[2] ^= v_i[2];\n z_i[3] ^= v_i[3];\n }\n\n // if LSB(V_i) is 1, V_i = V_i >> 1\n // else V_i = (V_i >> 1) ^ R\n this.pow(v_i, v_i);\n }\n\n return z_i;\n};\n\nmodes.gcm.prototype.pow = function(x, out) {\n // if LSB(x) is 1, x = x >>> 1\n // else x = (x >>> 1) ^ R\n var lsb = x[3] & 1;\n\n // always do x >>> 1:\n // starting with the rightmost integer, shift each integer to the right\n // one bit, pulling in the bit from the integer to the left as its top\n // most bit (do this for the last 3 integers)\n for(var i = 3; i > 0; --i) {\n out[i] = (x[i] >>> 1) | ((x[i - 1] & 1) << 31);\n }\n // shift the first integer normally\n out[0] = x[0] >>> 1;\n\n // if lsb was not set, then polynomial had a degree of 127 and doesn't\n // need to divided; otherwise, XOR with R to find the remainder; we only\n // need to XOR the first integer since R technically ends w/120 zero bits\n if(lsb) {\n out[0] ^= this._R;\n }\n};\n\nmodes.gcm.prototype.tableMultiply = function(x) {\n // assumes 4-bit tables are used\n var z = [0, 0, 0, 0];\n for(var i = 0; i < 32; ++i) {\n var idx = (i / 8) | 0;\n var x_i = (x[idx] >>> ((7 - (i % 8)) * 4)) & 0xF;\n var ah = this._m[i][x_i];\n z[0] ^= ah[0];\n z[1] ^= ah[1];\n z[2] ^= ah[2];\n z[3] ^= ah[3];\n }\n return z;\n};\n\n/**\n * A continuing version of the GHASH algorithm that operates on a single\n * block. The hash block, last hash value (Ym) and the new block to hash\n * are given.\n *\n * @param h the hash block.\n * @param y the previous value for Ym, use [0, 0, 0, 0] for a new hash.\n * @param x the block to hash.\n *\n * @return the hashed value (Ym).\n */\nmodes.gcm.prototype.ghash = function(h, y, x) {\n y[0] ^= x[0];\n y[1] ^= x[1];\n y[2] ^= x[2];\n y[3] ^= x[3];\n return this.tableMultiply(y);\n //return this.multiply(y, h);\n};\n\n/**\n * Precomputes a table for multiplying against the hash subkey. This\n * mechanism provides a substantial speed increase over multiplication\n * performed without a table. The table-based multiplication this table is\n * for solves X * H by multiplying each component of X by H and then\n * composing the results together using XOR.\n *\n * This function can be used to generate tables with different bit sizes\n * for the components, however, this implementation assumes there are\n * 32 components of X (which is a 16 byte vector), therefore each component\n * takes 4-bits (so the table is constructed with bits=4).\n *\n * @param h the hash subkey.\n * @param bits the bit size for a component.\n */\nmodes.gcm.prototype.generateHashTable = function(h, bits) {\n // TODO: There are further optimizations that would use only the\n // first table M_0 (or some variant) along with a remainder table;\n // this can be explored in the future\n var multiplier = 8 / bits;\n var perInt = 4 * multiplier;\n var size = 16 * multiplier;\n var m = new Array(size);\n for(var i = 0; i < size; ++i) {\n var tmp = [0, 0, 0, 0];\n var idx = (i / perInt) | 0;\n var shft = ((perInt - 1 - (i % perInt)) * bits);\n tmp[idx] = (1 << (bits - 1)) << shft;\n m[i] = this.generateSubHashTable(this.multiply(tmp, h), bits);\n }\n return m;\n};\n\n/**\n * Generates a table for multiplying against the hash subkey for one\n * particular component (out of all possible component values).\n *\n * @param mid the pre-multiplied value for the middle key of the table.\n * @param bits the bit size for a component.\n */\nmodes.gcm.prototype.generateSubHashTable = function(mid, bits) {\n // compute the table quickly by minimizing the number of\n // POW operations -- they only need to be performed for powers of 2,\n // all other entries can be composed from those powers using XOR\n var size = 1 << bits;\n var half = size >>> 1;\n var m = new Array(size);\n m[half] = mid.slice(0);\n var i = half >>> 1;\n while(i > 0) {\n // raise m0[2 * i] and store in m0[i]\n this.pow(m[2 * i], m[i] = []);\n i >>= 1;\n }\n i = 2;\n while(i < half) {\n for(var j = 1; j < i; ++j) {\n var m_i = m[i];\n var m_j = m[j];\n m[i + j] = [\n m_i[0] ^ m_j[0],\n m_i[1] ^ m_j[1],\n m_i[2] ^ m_j[2],\n m_i[3] ^ m_j[3]\n ];\n }\n i *= 2;\n }\n m[0] = [0, 0, 0, 0];\n /* Note: We could avoid storing these by doing composition during multiply\n calculate top half using composition by speed is preferred. */\n for(i = half + 1; i < size; ++i) {\n var c = m[i ^ half];\n m[i] = [mid[0] ^ c[0], mid[1] ^ c[1], mid[2] ^ c[2], mid[3] ^ c[3]];\n }\n return m;\n};\n\n/** Utility functions */\n\nfunction transformIV(iv, blockSize) {\n if(typeof iv === 'string') {\n // convert iv string into byte buffer\n iv = forge.util.createBuffer(iv);\n }\n\n if(forge.util.isArray(iv) && iv.length > 4) {\n // convert iv byte array into byte buffer\n var tmp = iv;\n iv = forge.util.createBuffer();\n for(var i = 0; i < tmp.length; ++i) {\n iv.putByte(tmp[i]);\n }\n }\n\n if(iv.length() < blockSize) {\n throw new Error(\n 'Invalid IV length; got ' + iv.length() +\n ' bytes and expected ' + blockSize + ' bytes.');\n }\n\n if(!forge.util.isArray(iv)) {\n // convert iv byte buffer into 32-bit integer array\n var ints = [];\n var blocks = blockSize / 4;\n for(var i = 0; i < blocks; ++i) {\n ints.push(iv.getInt32());\n }\n iv = ints;\n }\n\n return iv;\n}\n\nfunction inc32(block, count) {\n // increment last 32 bits of block only\n block[block.length - 1] = (block[block.length - 1] + (count || 1)) & 0xFFFFFFFF;\n}\n\nfunction from64To32(num) {\n // convert 64-bit number to two BE Int32s\n return [(num / 0x100000000) | 0, num & 0xFFFFFFFF];\n}\n"}} -{"repo": "FrozenCanuck/Ki", "pr_number": 25, "title": "Event handlers in states with concurrent substates get triggered multiple times", "state": "closed", "merged_at": null, "additions": 25, "deletions": 4, "files_changed": ["frameworks/foundation/system/statechart.js", "frameworks/foundation/tests/event_handling/basic/with_concurrent_states.js"], "files_before": {"frameworks/foundation/system/statechart.js": "// ==========================================================================\n// Project: Ki - A Statechart Framework for SproutCore\n// License: Licensed under MIT license (see license.js)\n// ==========================================================================\n\n/*globals Ki */\n\nsc_require('system/state');\n\n/**\n The startchart manager mixin allows an object to be a statechart. By becoming a statechart, the\n object can then be manage a set of its own states.\n \n This implemention of the statechart manager closely follows the concepts stated in D. Harel's \n original paper \"Statecharts: A Visual Formalism For Complex Systems\" \n (www.wisdom.weizmann.ac.il/~harel/papers/Statecharts.pdf). \n \n The statechart allows for complex state heircharies by nesting states within states, and \n allows for state orthogonality based on the use of concurrent states.\n \n At minimum, a statechart must have one state: The root state. All other states in the statechart\n are a decendents (substates) of the root state.\n \n The following example shows how states are nested within a statechart:\n \n {{{\n \n MyApp.Statechart = SC.Object.extend(Ki.StatechartManager, {\n \n rootState: Ki.State.design({\n \n initialSubstate: 'stateA',\n \n stateA: Ki.State.design({\n // ... can continue to nest further states\n }),\n \n stateB: Ki.State.design({\n // ... can continue to nest further states\n })\n })\n \n })\n \n }}}\n \n Note how in the example above, the root state as an explicit initial substate to enter into. If no\n initial substate is provided, then the statechart will default to the the state's first substate.\n \n You can also defined states without explicitly defining the root state. To do so, simply create properties\n on your object that represents states. Upon initialization, a root state will be constructed automatically\n by the mixin and make the states on the object substates of the root state. As an example:\n \n {{{\n \n MyApp.Statechart = SC.Object.extend(Ki.StatechartManager, {\n \n initialState: 'stateA',\n \n stateA: Ki.State.design({\n // ... can continue to nest further states\n }),\n \n stateB: Ki.State.design({\n // ... can continue to nest further states\n })\n \n })\n \n }}} \n \n If you liked to specify a class that should be used as the root state but using the above method to defined\n states, you can set the rootStateExample property with a class that extends from Ki.State. If the \n rootStateExaple property is not explicitly assigned the then default class used will be Ki.State.\n \n To provide your statechart with orthogonality, you use concurrent states. If you use concurrent states,\n then your statechart will have multiple current states. That is because each concurrent state represents an\n independent state structure from other concurrent states. The following example shows how to provide your\n statechart with concurrent states:\n \n {{{\n \n MyApp.Statechart = SC.Object.extend(Ki.StatechartManager, {\n \n rootState: Ki.State.design({\n \n substatesAreConcurrent: YES,\n \n stateA: Ki.State.design({\n // ... can continue to nest further states\n }),\n \n stateB: Ki.State.design({\n // ... can continue to nest further states\n })\n })\n \n })\n \n }}}\n \n Above, to indicate that a state's substates are concurrent, you just have to set the substatesAreConcurrent to \n YES. Once done, then stateA and stateB will be independent of each other and each will manage their\n own current substates. The root state will then have more then one current substate.\n \n To define concurrent states directly on the object without explicitly defining a root, you can do the \n following:\n \n {{{\n\n MyApp.Statechart = SC.Object.extend(Ki.StatechartManager, {\n \n statesAreConcurrent: YES,\n \n stateA: Ki.State.design({\n // ... can continue to nest further states\n }),\n \n stateB: Ki.State.design({\n // ... can continue to nest further states\n })\n \n })\n\n }}}\n \n Remember that a startchart can have a mixture of nested and concurrent states in order for you to \n create as complex of statecharts that suite your needs. Here is an example of a mixed state structure:\n \n {{{\n \n MyApp.Statechart = SC.Object.extend(Ki.StatechartManager, {\n \n rootState: Ki.State.design({\n \n initialSubstate: 'stateA',\n \n stateA: Ki.State.design({\n \n substatesAreConcurrent: YES,\n \n stateM: Ki.State.design({ ... })\n stateN: Ki.State.design({ ... })\n stateO: Ki.State.design({ ... })\n \n }),\n \n stateB: Ki.State.design({\n \n initialSubstate: 'stateX',\n \n stateX: Ki.State.design({ ... })\n stateY: Ki.State.desgin({ ... })\n \n })\n })\n \n })\n \n }}}\n \n Depending on your needs, a statechart can have lots of states, which can become hard to manage all within\n one file. To modularize your states and make them easier to manage and maintain, you can plug-in states\n into other states. Let's say we are using the statechart in the last example above, and all the code is \n within one file. We could update the code and split the logic across two or more files like so:\n \n {{{\n ---- state_a.js\n \n MyApp.StateA = Ki.State.extend({\n \n substatesAreConcurrent: YES,\n \n stateM: Ki.State.design({ ... })\n stateN: Ki.State.design({ ... })\n stateO: Ki.State.design({ ... })\n \n });\n \n ---- state_b.js\n \n MyApp.StateB = Ki.State.extend({\n \n substatesAreConcurrent: YES,\n \n stateM: Ki.State.design({ ... })\n stateN: Ki.State.design({ ... })\n stateO: Ki.State.design({ ... })\n \n });\n \n ---- statechart.js\n \n MyApp.Statechart = SC.Object.extend(Ki.StatechartManager, {\n \n rootState: Ki.State.design({\n \n initialSubstate: 'stateA',\n \n stateA: Ki.State.plugin('MyApp.StateA'),\n \n stateB: Ki.State.plugin('MyApp.StateB')\n \n })\n \n })\n \n }}}\n \n Using state plug-in functionality is optional. If you use the plug-in feature you can break up your statechart\n into as many files as you see fit.\n\n*/\n\nKi.StatechartManager = {\n \n // Walk like a duck\n isResponderContext: YES,\n \n // Walk like a duck\n isStatechart: YES,\n \n /**\n Indicates if this statechart has been initialized\n\n @property {Boolean}\n */\n statechartIsInitialized: NO,\n \n /**\n The root state of this statechart. All statecharts must have a root state.\n \n If this property is left unassigned then when the statechart is initialized\n it will used the rootStateExample, initialState, and statesAreConcurrent\n properties to construct a root state.\n \n @see #rootStateExample\n @see #initialState\n @see #statesAreConcurrent\n \n @property {Ki.State}\n */\n rootState: null,\n \n /** \n Represents the class used to construct a class that will be the root state for\n this statechart. The class assigned must derive from Ki.State. \n \n This property will only be used if the rootState property is not assigned.\n \n @see #rootState\n \n @property {Ki.State}\n */\n rootStateExample: Ki.State,\n \n /** \n Indicates what state should be the intiail state of this statechart. The value\n assigned must be the name of a property on this object that represents a state.\n As well, the statesAreConcurrent must be set to NO.\n \n This property will only be used if the rootState property is not assigned.\n \n @see #rootState\n \n @property {String} \n */\n initialState: null,\n \n /** \n Indicates if properties on this object representing states are concurrent to each other.\n If YES then they are concurrent, otherwise they are not. If the YES, then the\n initialState property must not be assigned.\n \n This property will only be used if the rootState property is not assigned.\n \n @see #rootState\n \n @property {Boolean}\n */\n statesAreConcurrent: NO,\n \n /** \n Indicates whether to use a monitor to monitor that statechart's activities. If true then\n the monitor will be active, otherwise the monitor will not be used. Useful for debugging\n purposes.\n \n @property {Boolean}\n */\n monitorIsActive: NO,\n \n /**\n A statechart monitor that can be used to monitor this statechart. Useful for debugging purposes.\n A monitor will only be used if monitorIsActive is true.\n \n @property {Ki.StatechartMonitor}\n */\n monitor: null,\n \n /**\n Used to specify what property (key) on the statechart should be used as the trace property. By\n default the property is 'trace'.\n\n @property {String}\n */\n statechartTraceKey: 'trace',\n\n /**\n Indicates whether to trace the statecharts activities. If true then the statechart will output\n its activites to the browser's JS console. Useful for debugging purposes.\n\n @see #statechartTraceKey\n\n @property {Boolean}\n */\n trace: NO,\n \n /**\n Used to specify what property (key) on the statechart should be used as the owner property. By\n default the property is 'owner'.\n\n @property {String}\n */\n statechartOwnerKey: 'owner',\n\n /**\n Sets who the owner is of this statechart. If null then the owner is this object otherwise\n the owner is the assigned object. \n\n @see #statechartOwnerKey\n\n @property {SC.Object}\n */\n owner: null,\n\n /** \n Indicates if the statechart should be automatically initialized by this\n object after it has been created. If YES then initStatechart will be\n called automatically, otherwise it will not.\n \n @property {Boolean}\n */\n autoInitStatechart: YES,\n \n /**\n If yes, any warning messages produced by the statechart or any of its states will\n not be logged, otherwise all warning messages will be logged. \n \n While designing and debugging your statechart, it's best to keep this value false.\n In production you can then suppress the warning messages.\n \n @property {Boolean}\n */\n suppressStatechartWarnings: NO,\n \n initMixin: function() {\n if (this.get('autoInitStatechart')) {\n this.initStatechart();\n }\n },\n \n destroyMixin: function() {\n var root = this.get('rootState'),\n traceKey = this.get('statechartTraceKey');\n\n this.removeObserver(traceKey, this, '_statechartTraceDidChange');\n\n root.destroy();\n this.set('rootState', null);\n },\n\n /**\n Initializes the statechart. By initializing the statechart, it will create all the states and register\n them with the statechart. Once complete, the statechart can be used to go to states and send events to.\n */\n initStatechart: function() {\n if (this.get('statechartIsInitialized')) return;\n \n this._gotoStateLocked = NO;\n this._sendEventLocked = NO;\n this._pendingStateTransitions = [];\n this._pendingSentEvents = [];\n \n this.sendAction = this.sendEvent;\n \n if (this.get('monitorIsActive')) {\n this.set('monitor', Ki.StatechartMonitor.create());\n }\n\n var traceKey = this.get('statechartTraceKey');\n\n this.addObserver(traceKey, this, '_statechartTraceDidChange');\n this._statechartTraceDidChange();\n\n var trace = this.get('allowTracing'),\n rootState = this.get('rootState'),\n msg;\n \n if (trace) this.statechartLogTrace(\"BEGIN initialize statechart\");\n \n // If no root state was explicitly defined then try to construct\n // a root state class\n if (!rootState) {\n rootState = this._constructRootStateClass();\n }\n else if (SC.typeOf(rootState) === SC.T_FUNCTION && rootState.statePlugin) {\n rootState = rootState.apply(this);\n }\n \n if (!(SC.kindOf(rootState, Ki.State) && rootState.isClass)) {\n msg = \"Unable to initialize statechart. Root state must be a state class\";\n this.statechartLogError(msg);\n throw msg;\n }\n \n rootState = this.createRootState(rootState, { \n statechart: this, \n name: Ki.ROOT_STATE_NAME \n });\n \n this.set('rootState', rootState);\n rootState.initState();\n \n if (SC.kindOf(rootState.get('initialSubstate'), Ki.EmptyState)) {\n msg = \"Unable to initialize statechart. Root state must have an initial substate explicilty defined\";\n this.statechartLogError(msg);\n throw msg;\n }\n \n if (!SC.empty(this.get('initialState'))) {\n var key = 'initialState';\n this.set(key, rootState.get(this.get(key)));\n } \n \n this.set('statechartIsInitialized', YES);\n this.gotoState(rootState);\n \n if (trace) this.statechartLogTrace(\"END initialize statechart\");\n },\n \n /**\n Will create a root state for the statechart\n */\n createRootState: function(state, attrs) {\n if (!attrs) attrs = {};\n state = state.create(attrs);\n return state;\n },\n \n /**\n Returns an array of all the current states for this statechart\n \n @returns {Array} the current states\n */\n currentStates: function() {\n return this.getPath('rootState.currentSubstates');\n }.property().cacheable(),\n \n /**\n Returns the first current state for this statechart. \n \n @return {Ki.State}\n */\n firstCurrentState: function() {\n var cs = this.get('currentStates');\n return cs ? cs.objectAt(0) : null;\n }.property('currentStates').cacheable(),\n \n /**\n Returns the count of the current states for this statechart\n \n @returns {Number} the count \n */\n currentStateCount: function() {\n return this.getPath('currentStates.length');\n }.property('currentStates').cacheable(),\n \n /**\n Checks if a given state is a current state of this statechart. \n \n @param state {State} the state to check\n @returns {Boolean} true if the state is a current state, otherwise fals is returned\n */\n stateIsCurrentState: function(state) {\n return this.get('rootState').stateIsCurrentSubstate(state);\n },\n \n /**\n Checks if the given value represents a state is this statechart\n \n @param value {State|String} either a state object or the name of a state\n @returns {Boolean} true if the state does belong ot the statechart, otherwise false is returned\n */\n doesContainState: function(value) {\n return !SC.none(this.getState(value));\n },\n \n /**\n Gets a state from the statechart that matches the given value\n \n @param value {State|String} either a state object of the name of a state\n @returns {State} if a match then the matching state is returned, otherwise null is returned \n */\n getState: function(value) {\n return this.get('rootState').getSubstate(value);\n },\n \n /**\n When called, the statechart will proceed with making state transitions in the statechart starting from \n a current state that meet the statechart conditions. When complete, some or all of the statechart's \n current states will be changed, and all states that were part of the transition process will either \n be exited or entered in a specific order.\n \n The state that is given to go to will not necessarily be a current state when the state transition process\n is complete. The final state or states are dependent on factors such an initial substates, concurrent \n states, and history states.\n \n Because the statechart can have one or more current states, it may be necessary to indicate what current state\n to start from. If no current state to start from is provided, then the statechart will default to using\n the first current state that it has; depending of the make up of the statechart (no concurrent state vs.\n with concurrent states), the outcome may be unexpected. For a statechart with concurrent states, it is best\n to provide a current state in which to start from.\n \n When using history states, the statechart will first make transitions to the given state and then use that\n state's history state and recursively follow each history state's history state until there are no \n more history states to follow. If the given state does not have a history state, then the statechart\n will continue following state transition procedures.\n \n Method can be called in the following ways:\n \n {{{\n \n // With one argument. \n gotoState()\n \n // With two argument.\n gotoState(, )\n \n // With three argument.\n gotoState(, , )\n gotoState(, , )\n \n // With four argument.\n gotoState(, , , )\n \n }}}\n \n where is either a Ki.State object or a string and is a regular JS hash object.\n \n @param state {Ki.State|String} the state to go to (may not be the final state in the transition process)\n @param fromCurrentState {Ki.State|String} Optional. The current state to start the transition process from.\n @param useHistory {Boolean} Optional. Indicates whether to include using history states in the transition process\n @param context {Hash} Optional. A context object that will be passed to all exited and entered states\n */\n gotoState: function(state, fromCurrentState, useHistory, context) {\n \n if (!this.get('statechartIsInitialized')) {\n this.statechartLogError(\"can not go to state %@. statechart has not yet been initialized\".fmt(state));\n return;\n }\n \n if (this.get('isDestroyed')) {\n this.statechartLogError(\"can not go to state %@. statechart is destroyed\".fmt(this));\n return;\n }\n \n var args = this._processGotoStateArgs(arguments);\n\n state = args.state;\n fromCurrentState = args.fromCurrentState;\n useHistory = args.useHistory;\n context = args.context;\n \n var pivotState = null,\n exitStates = [],\n enterStates = [],\n trace = this.get('allowTracing'),\n rootState = this.get('rootState'),\n paramState = state,\n paramFromCurrentState = fromCurrentState;\n \n state = rootState.getSubstate(state);\n \n if (SC.none(state)) {\n this.statechartLogError(\"Can not to goto state %@. Not a recognized state in statechart\".fmt(paramState));\n return;\n }\n \n if (this._gotoStateLocked) {\n // There is a state transition currently happening. Add this requested state\n // transition to the queue of pending state transitions. The request will\n // be invoked after the current state transition is finished.\n this._pendingStateTransitions.push({\n state: state,\n fromCurrentState: fromCurrentState,\n useHistory: useHistory,\n context: context\n });\n \n return;\n }\n \n // Lock the current state transition so that no other requested state transition \n // interferes. \n this._gotoStateLocked = YES;\n \n if (!SC.none(fromCurrentState)) {\n // Check to make sure the current state given is actually a current state of this statechart\n fromCurrentState = rootState.getSubstate(fromCurrentState);\n if (SC.none(fromCurrentState) || !fromCurrentState.get('isCurrentState')) {\n var msg = \"Can not to goto state %@. %@ is not a recognized current state in statechart\";\n this.statechartLogError(msg.fmt(paramState, paramFromCurrentState));\n this._gotoStateLocked = NO;\n return;\n }\n } \n else if (this.getPath('currentStates.length') > 0) {\n // No explicit current state to start from; therefore, just use the first current state as \n // a default, if there is a current state.\n fromCurrentState = this.get('currentStates')[0];\n }\n \n if (trace) {\n this.statechartLogTrace(\"BEGIN gotoState: %@\".fmt(state));\n this.statechartLogTrace(\"starting from current state: %@\".fmt(fromCurrentState));\n this.statechartLogTrace(\"current states before: %@\".fmt(this.get('currentStates')));\n }\n\n // If there is a current state to start the transition process from, then determine what\n // states are to be exited\n if (!SC.none(fromCurrentState)) {\n exitStates = this._createStateChain(fromCurrentState);\n }\n \n // Now determine the initial states to be entered\n enterStates = this._createStateChain(state);\n \n // Get the pivot state to indicate when to go from exiting states to entering states\n pivotState = this._findPivotState(exitStates, enterStates);\n\n if (pivotState) {\n if (trace) this.statechartLogTrace(\"pivot state = %@\".fmt(pivotState));\n if (pivotState.get('substatesAreConcurrent')) {\n this.statechartLogError(\"Can not go to state %@ from %@. Pivot state %@ has concurrent substates.\".fmt(state, fromCurrentState, pivotState));\n this._gotoStateLocked = NO;\n return;\n }\n }\n \n // Collect what actions to perform for the state transition process\n var gotoStateActions = [];\n \n // Go ahead and find states that are to be exited\n this._traverseStatesToExit(exitStates.shift(), exitStates, pivotState, gotoStateActions);\n \n // Now go find states that are to entered\n if (pivotState !== state) {\n this._traverseStatesToEnter(enterStates.pop(), enterStates, pivotState, useHistory, gotoStateActions);\n } else {\n this._traverseStatesToExit(pivotState, [], null, gotoStateActions);\n this._traverseStatesToEnter(pivotState, null, null, useHistory, gotoStateActions);\n }\n \n // Collected all the state transition actions to be performed. Now execute them.\n this._executeGotoStateActions(state, gotoStateActions, null, context);\n },\n \n /**\n Indicates if the statechart is in an active goto state process\n */\n gotoStateActive: function() {\n return this._gotoStateLocked;\n }.property(),\n \n /**\n Indicates if the statechart is in an active goto state process\n that has been suspended\n */\n gotoStateSuspended: function() {\n return this._gotoStateLocked && !!this._gotoStateSuspendedPoint;\n }.property(),\n \n /**\n Resumes an active goto state transition process that has been suspended.\n */\n resumeGotoState: function() {\n if (!this.get('gotoStateSuspended')) {\n this.statechartLogError(\"Can not resume goto state since it has not been suspended\");\n return;\n }\n \n var point = this._gotoStateSuspendedPoint;\n this._executeGotoStateActions(point.gotoState, point.actions, point.marker, point.context);\n },\n \n /** @private */\n _executeGotoStateActions: function(gotoState, actions, marker, context) {\n var action = null,\n len = actions.length,\n actionResult = null;\n \n marker = SC.none(marker) ? 0 : marker;\n \n for (; marker < len; marker += 1) {\n action = actions[marker];\n switch (action.action) {\n case Ki.EXIT_STATE:\n actionResult = this._exitState(action.state, context);\n break;\n \n case Ki.ENTER_STATE:\n actionResult = this._enterState(action.state, action.currentState, context);\n break;\n }\n \n //\n // Check if the state wants to perform an asynchronous action during\n // the state transition process. If so, then we need to first\n // suspend the state transition process and then invoke the \n // asynchronous action. Once called, it is then up to the state or something \n // else to resume this statechart's state transition process by calling the\n // statechart's resumeGotoState method.\n //\n if (SC.kindOf(actionResult, Ki.Async)) {\n this._gotoStateSuspendedPoint = {\n gotoState: gotoState,\n actions: actions,\n marker: marker + 1,\n context: context\n }; \n \n actionResult.tryToPerform(action.state);\n return;\n }\n }\n \n this.notifyPropertyChange('currentStates');\n \n if (this.get('allowTracing')) {\n this.statechartLogTrace(\"current states after: %@\".fmt(this.get('currentStates')));\n this.statechartLogTrace(\"END gotoState: %@\".fmt(gotoState));\n }\n \n // Okay. We're done with the current state transition. Make sure to unlock the\n // gotoState and let other pending state transitions execute.\n this._gotoStateSuspendedPoint = null;\n this._gotoStateLocked = NO;\n this._flushPendingStateTransition();\n },\n \n /** @private */\n _exitState: function(state, context) {\n if (state.get('currentSubstates').indexOf(state) >= 0) { \n var parentState = state.get('parentState');\n while (parentState) {\n parentState.get('currentSubstates').removeObject(state);\n parentState = parentState.get('parentState');\n }\n }\n \n if (this.get('allowTracing')) this.statechartLogTrace(\"exiting state: %@\".fmt(state));\n \n state.set('currentSubstates', []);\n state.notifyPropertyChange('isCurrentState');\n var result = this.exitState(state, context);\n \n if (this.get('monitorIsActive')) this.get('monitor').pushExitedState(state);\n \n state._traverseStatesToExit_skipState = NO;\n \n return result;\n },\n \n /**\n What will actually invoke a state's exitState method.\n \n Called during the state transition process whenever the gotoState method is\n invoked.\n \n @param state {Ki.State} the state whose enterState method is to be invoked\n @param context {Hash} a context hash object to provide the enterState method\n */\n exitState: function(state, context) {\n return state.exitState(context);\n },\n \n /** @private */\n _enterState: function(state, current, context) {\n var parentState = state.get('parentState');\n if (parentState && !state.get('isConcurrentState')) parentState.set('historyState', state);\n \n if (current) {\n parentState = state;\n while (parentState) {\n parentState.get('currentSubstates').push(state);\n parentState = parentState.get('parentState');\n }\n }\n \n if (this.get('allowTracing')) this.statechartLogTrace(\"entering state: %@\".fmt(state));\n \n state.notifyPropertyChange('isCurrentState');\n var result = this.enterState(state, context);\n \n if (this.get('monitorIsActive')) this.get('monitor').pushEnteredState(state);\n \n return result;\n },\n \n /**\n What will actually invoke a state's enterState method.\n \n Called during the state transition process whenever the gotoState method is\n invoked.\n \n @param state {Ki.State} the state whose enterState method is to be invoked\n @param context {Hash} a context hash object to provide the enterState method\n */\n enterState: function(state, context) {\n return state.enterState(context);\n },\n \n /**\n When called, the statechart will proceed to make transitions to the given state then follow that\n state's history state. \n \n You can either go to a given state's history recursively or non-recursively. To go to a state's history\n recursively means to following each history state's history state until no more history states can be\n followed. Non-recursively means to just to the given state's history state but do not recusively follow\n history states. If the given state does not have a history state, then the statechart will just follow\n normal procedures when making state transitions.\n \n Because a statechart can have one or more current states, depending on if the statechart has any concurrent\n states, it is optional to provided current state in which to start the state transition process from. If no\n current state is provided, then the statechart will default to the first current state that it has; which, \n depending on the make up of that statechart, can lead to unexpected outcomes. For a statechart with concurrent\n states, it is best to explicitly supply a current state.\n \n Method can be called in the following ways:\n \n {{{\n \n // With one arguments. \n gotoHistorytate()\n \n // With two arguments. \n gotoHistorytate(, )\n \n // With three arguments.\n gotoHistorytate(, , )\n gotoHistorytate(, , )\n \n // With four argumetns\n gotoHistorytate(, , , )\n \n }}}\n \n where is either a Ki.State object or a string and is a regular JS hash object.\n \n @param state {Ki.State|String} the state to go to and follow it's history state\n @param fromCurrentState {Ki.State|String} Optional. the current state to start the state transition process from\n @param recursive {Boolean} Optional. whether to follow history states recursively.\n */\n gotoHistoryState: function(state, fromCurrentState, recursive, context) {\n if (!this.get('statechartIsInitialized')) {\n this.statechartLogError(\"can not go to state %@'s history state. Statechart has not yet been initialized\".fmt(state));\n return;\n }\n \n var args = this._processGotoStateArgs(arguments);\n \n state = args.state;\n fromCurrentState = args.fromCurrentState;\n recursive = args.useHistory;\n context = args.context;\n \n state = this.getState(state);\n \n if (!state) {\n this.statechartLogError(\"Can not to goto state %@'s history state. Not a recognized state in statechart\".fmt(state));\n return;\n }\n \n var historyState = state.get('historyState');\n \n if (!recursive) { \n if (historyState) {\n this.gotoState(historyState, fromCurrentState, context);\n } else {\n this.gotoState(state, fromCurrentState, context);\n }\n } else {\n this.gotoState(state, fromCurrentState, YES, context);\n }\n },\n \n /**\n Sends a given event to all the statechart's current states.\n \n If a current state does can not respond to the sent event, then the current state's parent state\n will be tried. This process is recursively done until no more parent state can be tried.\n \n @param event {String} name of the event\n @param arg1 {Object} optional argument\n @param arg2 {Object} optional argument\n @returns {SC.Responder} the responder that handled it or null\n */\n sendEvent: function(event, arg1, arg2) {\n \n if (this.get('isDestroyed')) {\n this.statechartLogError(\"can send event %@. statechart is destroyed\".fmt(event));\n return;\n }\n \n var statechartHandledEvent = NO,\n eventHandled = NO,\n currentStates = this.get('currentStates').slice(),\n len = 0,\n i = 0,\n state = null,\n trace = this.get('allowTracing');\n \n if (this._sendEventLocked || this._goStateLocked) {\n // Want to prevent any actions from being processed by the states until \n // they have had a chance to handle the most immediate action or completed \n // a state transition\n this._pendingSentEvents.push({\n event: event,\n arg1: arg1,\n arg2: arg2\n });\n\n return;\n }\n \n this._sendEventLocked = YES;\n \n if (trace) {\n this.statechartLogTrace(\"BEGIN sendEvent: event<%@>\".fmt(event));\n }\n \n len = currentStates.get('length');\n for (; i < len; i += 1) {\n eventHandled = NO;\n state = currentStates[i];\n if (!state.get('isCurrentState')) continue;\n while (!eventHandled && state) {\n eventHandled = state.tryToHandleEvent(event, arg1, arg2);\n if (!eventHandled) state = state.get('parentState');\n else statechartHandledEvent = YES;\n }\n }\n \n // Now that all the states have had a chance to process the \n // first event, we can go ahead and flush any pending sent events.\n this._sendEventLocked = NO;\n \n if (trace) {\n if (!statechartHandledEvent) this.statechartLogTrace(\"No state was able handle event %@\".fmt(event));\n this.statechartLogTrace(\"END sendEvent: event<%@>\".fmt(event));\n }\n \n var result = this._flushPendingSentEvents();\n \n return statechartHandledEvent ? this : (result ? this : null);\n },\n\n /** @private\n \n Creates a chain of states from the given state to the greatest ancestor state (the root state). Used\n when perform state transitions.\n */\n _createStateChain: function(state) {\n var chain = [];\n \n while (state) {\n chain.push(state);\n state = state.get('parentState');\n }\n \n return chain;\n },\n \n /** @private\n \n Finds a pivot state from two given state chains. The pivot state is the state indicating when states\n go from being exited to states being entered during the state transition process. The value \n returned is the fist matching state between the two given state chains. \n */\n _findPivotState: function(stateChain1, stateChain2) {\n if (stateChain1.length === 0 || stateChain2.length === 0) return null;\n \n var pivot = stateChain1.find(function(state, index) {\n if (stateChain2.indexOf(state) >= 0) return YES;\n });\n \n return pivot;\n },\n \n /** @private\n \n Recursively follow states that are to be exited during a state transition process. The exit\n process is to start from the given state and work its way up to when either all exit\n states have been reached based on a given exit path or when a stop state has been reached.\n \n @param state {State} the state to be exited\n @param exitStatePath {Array} an array representing a path of states that are to be exited\n @param stopState {State} an explicit state in which to stop the exiting process\n */\n _traverseStatesToExit: function(state, exitStatePath, stopState, gotoStateActions) { \n if (!state || state === stopState) return;\n \n var trace = this.get('allowTracing');\n \n // This state has concurrent substates. Therefore we have to make sure we\n // exit them up to this state before we can go any further up the exit chain.\n if (state.get('substatesAreConcurrent')) {\n var i = 0,\n currentSubstates = state.get('currentSubstates'),\n len = currentSubstates.length,\n currentState = null;\n \n for (; i < len; i += 1) {\n currentState = currentSubstates[i];\n if (currentState._traverseStatesToExit_skipState === YES) continue;\n var chain = this._createStateChain(currentState);\n this._traverseStatesToExit(chain.shift(), chain, state, gotoStateActions);\n }\n }\n \n gotoStateActions.push({ action: Ki.EXIT_STATE, state: state });\n if (state.get('isCurrentState')) state._traverseStatesToExit_skipState = YES;\n this._traverseStatesToExit(exitStatePath.shift(), exitStatePath, stopState, gotoStateActions);\n },\n \n /** @private\n \n Recursively follow states that are to be entred during the state transition process. The\n enter process is to start from the given state and work its way down a given enter path. When\n the end of enter path has been reached, then continue entering states based on whether \n an initial substate is defined, there are concurrent substates or history states are to be\n followed; when none of those condition are met then the enter process is done.\n \n @param state {State} the sate to be entered\n @param enterStatePath {Array} an array representing an initial path of states that are to be entered\n @param pivotState {State} The state pivoting when to go from exiting states to entering states\n @param useHistory {Boolean} indicates whether to recursively follow history states \n */\n _traverseStatesToEnter: function(state, enterStatePath, pivotState, useHistory, gotoStateActions) {\n if (!state) return;\n \n var trace = this.get('allowTracing');\n \n // We do not want to enter states in the enter path until the pivot state has been reached. After\n // the pivot state has been reached, then we can go ahead and actually enter states.\n if (pivotState) {\n if (state !== pivotState) {\n this._traverseStatesToEnter(enterStatePath.pop(), enterStatePath, pivotState, useHistory, gotoStateActions);\n } else {\n this._traverseStatesToEnter(enterStatePath.pop(), enterStatePath, null, useHistory, gotoStateActions);\n }\n }\n \n // If no more explicit enter path instructions, then default to enter states based on \n // other criteria\n else if (!enterStatePath || enterStatePath.length === 0) {\n var gotoStateAction = { action: Ki.ENTER_STATE, state: state, currentState: NO };\n gotoStateActions.push(gotoStateAction);\n \n var initialSubstate = state.get('initialSubstate'),\n historyState = state.get('historyState');\n \n // State has concurrent substates. Need to enter all of the substates\n if (state.get('substatesAreConcurrent')) {\n this._traverseConcurrentStatesToEnter(state.get('substates'), null, useHistory, gotoStateActions);\n }\n \n // State has substates and we are instructed to recursively follow the state's\n // history state if it has one.\n else if (state.get('hasSubstates') && historyState && useHistory) {\n this._traverseStatesToEnter(historyState, null, null, useHistory, gotoStateActions);\n }\n \n // State has an initial substate to enter\n else if (initialSubstate) {\n if (SC.kindOf(initialSubstate, Ki.HistoryState)) {\n if (!useHistory) useHistory = initialSubstate.get('isRecursive');\n initialSubstate = initialSubstate.get('state');\n }\n this._traverseStatesToEnter(initialSubstate, null, null, useHistory, gotoStateActions); \n } \n \n // Looks like we hit the end of the road. Therefore the state has now become\n // a current state of the statechart.\n else {\n gotoStateAction.currentState = YES;\n }\n }\n \n // Still have an explicit enter path to follow, so keep moving through the path.\n else if (enterStatePath.length > 0) {\n gotoStateActions.push({ action: Ki.ENTER_STATE, state: state });\n var nextState = enterStatePath.pop();\n this._traverseStatesToEnter(nextState, enterStatePath, null, useHistory, gotoStateActions); \n \n // We hit a state that has concurrent substates. Must go through each of the substates\n // and enter them\n if (state.get('substatesAreConcurrent')) {\n this._traverseConcurrentStatesToEnter(state.get('substates'), nextState, useHistory, gotoStateActions);\n }\n }\n },\n \n /** @override\n \n Returns YES if the named value translates into an executable function on\n any of the statechart's current states or the statechart itself.\n \n @param event {String} the property name to check\n @returns {Boolean}\n */\n respondsTo: function(event) {\n var currentStates = this.get('currentStates'),\n len = currentStates.get('length'), \n i = 0, state = null;\n \n for (; i < len; i += 1) {\n state = currentStates.objectAt(i);\n while (state) {\n if (state.respondsToEvent(event)) return true;\n state = state.get('parentState');\n }\n }\n \n // None of the current states can respond. Now check the statechart itself\n return SC.typeOf(this[event]) === SC.T_FUNCTION; \n },\n \n /** @override\n \n Attemps to handle a given event against any of the statechart's current states and the\n statechart itself. If any current state can handle the event or the statechart itself can\n handle the event then YES is returned, otherwise NO is returned.\n \n @param event {String} what to perform\n @param arg1 {Object} Optional\n @param arg2 {Object} Optional\n @returns {Boolean} YES if handled, NO if not handled\n */\n tryToPerform: function(event, arg1, arg2) {\n if (this.respondsTo(event)) {\n if (SC.typeOf(this[event]) === SC.T_FUNCTION) return (this[event](arg1, arg2) !== NO);\n else return !!this.sendEvent(event, arg1, arg2);\n } return NO;\n },\n \n /**\n Used to invoke a method on current states. If the method can not be executed\n on a current state, then the state's parent states will be tried in order\n of closest ancestry.\n \n A few notes: \n \n 1) Calling this is not the same as calling sendEvent or sendAction.\n Rather, this should be seen as calling normal methods on a state that \n will *not* call gotoState or gotoHistoryState. \n \n 2) A state will only ever be invoked once per call. So if there are two \n or more current states that have the same parent state, then that parent \n state will only be invoked once if none of the current states are able\n to invoke the given method.\n \n When calling this method, you are able to supply zero ore more arguments\n that can be pass onto the method called on the states. As an example\n \n {{{\n \n invokeStateMethod('render', context, firstTime);\n \n }}}\n \n The above call will invoke the render method on the current states\n and supply the context and firstTime arguments to the method. \n \n Because a statechart can have more than one current state and the method \n invoked may return a value, the addition of a callback function may be provided \n in order to handle the returned value for each state. As an example, let's say\n we want to call a calculate method on the current states where the method\n will return a value when invoked. We can handle the returned values like so:\n \n {{{\n \n invokeStateMethod('calculate', value, function(state, result) {\n // .. handle the result returned from calculate that was invoked\n // on the given state\n })\n \n }}}\n \n If the method invoked does not return a value and a callback function is\n supplied, then result value will simply be undefined. In all cases, if\n a callback function is given, it must be the last value supplied to this\n method.\n \n invokeStateMethod will return a value if only one state was able to have \n the given method invoked on it, otherwise no value is returned. \n \n @param methodName {String} methodName a method name\n @param args {Object...} Optional. any additional arguments\n @param func {Function} Optional. a callback function. Must be the last\n value supplied if provided.\n \n @returns a value if the number of current states is one, otherwise undefined\n is returned. The value is the result of the method that got invoked\n on a state.\n */\n invokeStateMethod: function(methodName, args, func) {\n if (methodName === 'unknownEvent') {\n this.statechartLogError(\"can not invoke method unkownEvent\");\n return;\n }\n \n args = SC.A(arguments); args.shift();\n \n var len = args.length, \n arg = len > 0 ? args[len - 1] : null,\n callback = SC.typeOf(arg) === SC.T_FUNCTION ? args.pop() : null,\n currentStates = this.get('currentStates'), \n i = 0, state = null, checkedStates = {},\n method, result = undefined, calledStates = 0;\n \n len = currentStates.get('length');\n \n for (; i < len; i += 1) {\n state = currentStates.objectAt(i);\n while (state) {\n if (checkedStates[state.get('fullPath')]) break;\n checkedStates[state.get('fullPath')] = YES;\n method = state[methodName];\n if (SC.typeOf(method) === SC.T_FUNCTION && !method.isEventHandler) {\n result = method.apply(state, args);\n if (callback) callback.call(this, state, result);\n calledStates += 1; \n break;\n }\n state = state.get('parentState');\n }\n }\n \n return calledStates === 1 ? result : undefined;\n },\n \n /** @private\n \n Iterate over all the given concurrent states and enter them\n */\n _traverseConcurrentStatesToEnter: function(states, exclude, useHistory, gotoStateActions) {\n var i = 0,\n len = states.length,\n state = null;\n \n for (; i < len; i += 1) {\n state = states[i];\n if (state !== exclude) this._traverseStatesToEnter(state, null, null, useHistory, gotoStateActions);\n }\n },\n \n /** @private\n \n Called by gotoState to flush a pending state transition at the front of the \n pending queue.\n */\n _flushPendingStateTransition: function() {\n if (!this._pendingStateTransitions) {\n this.statechartLogError(\"Unable to flush pending state transition. _pendingStateTransitions is invalid\");\n return;\n }\n var pending = this._pendingStateTransitions.shift();\n if (!pending) return;\n this.gotoState(pending.state, pending.fromCurrentState, pending.useHistory, pending.context);\n },\n \n /** @private\n\n Called by sendEvent to flush a pending actions at the front of the pending\n queue\n */\n _flushPendingSentEvents: function() {\n var pending = this._pendingSentEvents.shift();\n if (!pending) return null;\n return this.sendEvent(pending.event, pending.arg1, pending.arg2);\n },\n \n /** @private */\n _monitorIsActiveDidChange: function() {\n if (this.get('monitorIsActive') && SC.none(this.get('monitor'))) {\n this.set('monitor', Ki.StatechartMonitor.create());\n }\n }.observes('monitorIsActive'),\n \n /** @private \n Will process the arguments supplied to the gotoState method.\n \n TODO: Come back to this and refactor the code. It works, but it\n could certainly be improved\n */\n _processGotoStateArgs: function(args) {\n var processedArgs = { \n state: null, \n fromCurrentState: null, \n useHistory: false, \n context: null \n },\n len = null,\n value = null;\n \n args = SC.$A(args);\n args = args.filter(function(item) {\n return !(item === undefined); \n });\n len = args.length;\n \n if (len < 1) return processedArgs;\n \n processedArgs.state = args[0];\n \n if (len === 2) {\n value = args[1];\n switch (SC.typeOf(value)) {\n case SC.T_BOOL: \n processedArgs.useHistory = value;\n break;\n case SC.T_HASH:\n processedArgs.context = value;\n break;\n default:\n processedArgs.fromCurrentState = value;\n }\n }\n else if (len === 3) {\n value = args[1];\n if (SC.typeOf(value) === SC.T_BOOL) {\n processedArgs.useHistory = value;\n processedArgs.context = args[2];\n } else {\n processedArgs.fromCurrentState = value;\n value = args[2];\n if (SC.typeOf(value) === SC.T_BOOL) {\n processedArgs.useHistory = value;\n } else {\n processedArgs.context = value;\n }\n }\n }\n else {\n processedArgs.fromCurrentState = args[1];\n processedArgs.useHistory = args[2];\n processedArgs.context = args[3];\n }\n \n return processedArgs;\n },\n \n /** @private \n \n Will return a newly constructed root state class. The root state will have substates added to\n it based on properties found on this state that derive from a Ki.State class. For the\n root state to be successfully built, the following much be met:\n \n - The rootStateExample property must be defined with a class that derives from Ki.State\n - Either the initialState or statesAreConcurrent property must be set, but not both\n - There must be one or more states that can be added to the root state\n \n */\n _constructRootStateClass: function() {\n var rsExampleKey = 'rootStateExample',\n rsExample = this.get(rsExampleKey),\n initialState = this.get('initialState'),\n statesAreConcurrent = this.get('statesAreConcurrent'),\n stateCount = 0,\n key, value, valueIsFunc, attrs = {};\n \n if (SC.typeOf(rsExample) === SC.T_FUNCTION && rsExample.statePlugin) {\n rsExample = rsExample.apply(this);\n }\n\n if (!(SC.kindOf(rsExample, Ki.State) && rsExample.isClass)) {\n this._logStatechartCreationError(\"Invalid root state example\");\n return null;\n }\n \n if (statesAreConcurrent && !SC.empty(initialState)) {\n this._logStatechartCreationError(\"Can not assign an initial state when states are concurrent\");\n } else if (statesAreConcurrent) {\n attrs.substatesAreConcurrent = YES;\n } else if (SC.typeOf(initialState) === SC.T_STRING) {\n attrs.initialSubstate = initialState;\n } else {\n this._logStatechartCreationError(\"Must either define initial state or assign states as concurrent\");\n return null;\n }\n \n for (key in this) {\n if (key === rsExampleKey) continue;\n \n value = this[key];\n valueIsFunc = SC.typeOf(value) === SC.T_FUNCTION;\n \n if (valueIsFunc && value.statePlugin) {\n value = value.apply(this);\n }\n \n if (SC.kindOf(value, Ki.State) && value.isClass && this[key] !== this.constructor) {\n attrs[key] = value;\n stateCount += 1;\n }\n }\n \n if (stateCount === 0) {\n this._logStatechartCreationError(\"Must define one or more states\");\n return null;\n }\n \n return rsExample.extend(attrs);\n },\n \n /** @private */\n _logStatechartCreationError: function(msg) {\n SC.Logger.error(\"Unable to create statechart for %@: %@.\".fmt(this, msg));\n },\n \n /** \n Used to log a statechart trace message\n */\n statechartLogTrace: function(msg) {\n SC.Logger.info(\"%@: %@\".fmt(this.get('statechartLogPrefix'), msg));\n },\n \n /**\n Used to log a statechart error message\n */\n statechartLogError: function(msg) {\n SC.Logger.error(\"ERROR %@: %@\".fmt(this.get('statechartLogPrefix'), msg));\n },\n \n /** \n Used to log a statechart warning message\n */\n statechartLogWarning: function(msg) {\n if (this.get('suppressStatechartWarnings')) return;\n SC.Logger.warn(\"WARN %@: %@\".fmt(this.get('statechartLogPrefix'), msg));\n },\n \n /** @property */\n statechartLogPrefix: function() {\n var className = SC._object_className(this.constructor),\n name = this.get('name'), prefix;\n \n if (SC.empty(name)) prefix = \"%@<%@>\".fmt(className, SC.guidFor(this));\n else prefix = \"%@<%@, %@>\".fmt(className, name, SC.guidFor(this));\n \n return prefix;\n }.property().cacheable(),\n\n /** @private @property */\n allowTracing: function() {\n var key = this.get('statechartTraceKey');\n return this.get(key);\n }.property().cacheable(),\n\n /** @private */\n _statechartTraceDidChange: function() {\n this.notifyPropertyChange('allowTracing');\n }\n \n};\n\n/** \n The default name given to a statechart's root state\n*/\nKi.ROOT_STATE_NAME = \"__ROOT_STATE__\";\n\n/**\n Constants used during the state transition process\n*/\nKi.EXIT_STATE = 0;\nKi.ENTER_STATE = 1;\n\n/**\n A Startchart class. \n*/\nKi.Statechart = SC.Object.extend(Ki.StatechartManager, {\n autoInitStatechart: NO\n});\n\nKi.Statechart.design = Ki.Statechart.extend;\n\n/**\n Represents a call that is intended to be asynchronous. This is\n used during a state transition process when either entering or\n exiting a state.\n*/\nKi.Async = SC.Object.extend({\n \n func: null,\n \n arg1: null,\n \n arg2: null,\n \n /** @private\n Called by the statechart\n */\n tryToPerform: function(state) {\n var func = this.get('func'),\n arg1 = this.get('arg1'),\n arg2 = this.get('arg2'),\n funcType = SC.typeOf(func);\n \n if (funcType === SC.T_STRING) {\n state.tryToPerform(func, arg1, arg2);\n } \n else if (funcType === SC.T_FUNCTION) {\n func.apply(state, [arg1, arg2]);\n }\n }\n \n});\n\n/**\n Singleton\n*/\nKi.Async.mixin({\n \n /**\n Call in either a state's enterState or exitState method when you\n want a state to perform an asynchronous action, such as an animation.\n \n Examples:\n \n {{\n \n Ki.State.extend({\n \n enterState: function() {\n return Ki.Async.perform('foo');\n },\n \n exitState: function() {\n return Ki.Async.perform('bar', 100);\n }\n \n foo: function() { ... },\n \n bar: function(arg) { ... }\n \n });\n \n }}\n \n @param func {String|Function} the functio to be invoked on a state\n @param arg1 Optional. An argument to pass to the given function\n @param arg2 Optional. An argument to pass to the given function\n @return {Ki.Async} a new instance of a Ki.Async\n */\n perform: function(func, arg1, arg2) {\n return Ki.Async.create({ func: func, arg1: arg1, arg2: arg2 });\n }\n \n});", "frameworks/foundation/tests/event_handling/basic/with_concurrent_states.js": "// ==========================================================================\n// Ki.Statechart Unit Test\n// ==========================================================================\n/*globals Ki */\n\nvar statechart = null;\n\n// ..........................................................\n// CONTENT CHANGING\n// \n\nmodule(\"Ki.Statechart: With Concurrent States - Send Event Tests\", {\n setup: function() {\n\n statechart = Ki.Statechart.create({\n \n monitorIsActive: YES,\n \n rootState: Ki.State.design({\n \n initialSubstate: 'x',\n \n x: Ki.State.design({\n \n substatesAreConcurrent: YES,\n \n a: Ki.State.design({\n\n initialSubstate: 'c',\n\n eventAInvoked: NO,\n\n eventA: function() { this.set('eventAInvoked', YES); },\n\n c: Ki.State.design({\n eventB: function() { this.gotoState('d'); },\n eventD: function() { this.gotoState('y'); }\n }),\n\n d: Ki.State.design({\n eventC: function() { this.gotoState('c'); }\n })\n\n }),\n\n b: Ki.State.design({\n\n initialSubstate: 'e',\n\n eventAInvoked: NO,\n\n eventA: function() { this.set('eventAInvoked', YES); },\n\n e: Ki.State.design({\n eventB: function() { this.gotoState('f'); },\n eventD: function() { this.gotoState('y'); }\n }),\n\n f: Ki.State.design({\n eventC: function() { this.gotoState('e'); }\n })\n\n })\n \n }),\n \n y: Ki.State.design()\n \n })\n \n });\n \n statechart.initStatechart();\n },\n \n teardown: function() {\n statechart.destroy();\n statechart = null;\n }\n});\n\ntest(\"send event eventA\", function() {\n var monitor = statechart.get('monitor'),\n stateA = statechart.getState('a'),\n stateB = statechart.getState('b');\n \n monitor.reset();\n\n equals(stateA.get('eventAInvoked'), false);\n equals(stateB.get('eventAInvoked'), false);\n\n statechart.sendEvent('eventA');\n \n equals(monitor.get('length'), 0, 'state sequence should be of length 0');\n equals(statechart.stateIsCurrentState('c'), true, 'current state should be c');\n equals(statechart.stateIsCurrentState('e'), true, 'current state should be e');\n equals(stateA.get('eventAInvoked'), true);\n equals(stateB.get('eventAInvoked'), true);\n});\n\ntest(\"send event eventB\", function() {\n var monitor = statechart.get('monitor');\n \n monitor.reset();\n \n equals(statechart.stateIsCurrentState('c'), true, 'current state should be c');\n equals(statechart.stateIsCurrentState('e'), true, 'current state should be e');\n \n statechart.sendEvent('eventB');\n \n equals(statechart.get('currentStateCount'), 2, 'current state count should be 2');\n equals(statechart.stateIsCurrentState('d'), true, 'current state should be d');\n equals(statechart.stateIsCurrentState('f'), true, 'current state should be f');\n \n equals(monitor.get('length'), 4, 'state sequence should be of length 4');\n equals(monitor.matchSequence()\n .begin()\n .exited('c').entered('d')\n .exited('e').entered('f')\n .end(), \n true, 'sequence should be exited[c], entered[d], exited[e], entered[f]');\n});\n\ntest(\"send event eventB then eventC\", function() {\n var monitor = statechart.get('monitor');\n\n statechart.sendEvent('eventB');\n \n equals(statechart.stateIsCurrentState('d'), true, 'current state should be d');\n equals(statechart.stateIsCurrentState('f'), true, 'current state should be f');\n\n monitor.reset();\n \n statechart.sendEvent('eventC');\n\n equals(statechart.stateIsCurrentState('c'), true, 'current state should be c');\n equals(statechart.stateIsCurrentState('e'), true, 'current state should be e');\n\n equals(monitor.get('length'), 4, 'state sequence should be of length 4');\n equals(monitor.matchSequence()\n .begin()\n .exited('d').entered('c')\n .exited('f').entered('e')\n .end(), \n true, 'sequence should be exited[d], entered[c], exited[f], entered[e]');\n});\n\ntest(\"send event eventD\", function() {\n var monitor = statechart.get('monitor');\n \n monitor.reset();\n \n equals(statechart.stateIsCurrentState('c'), true, 'current state should be c');\n equals(statechart.stateIsCurrentState('e'), true, 'current state should be e');\n \n statechart.sendEvent('eventD');\n \n equals(monitor.get('length'), 6, 'state sequence should be of length 6');\n equals(monitor.matchSequence()\n .begin()\n .exited('c', 'a', 'e', 'b', 'x').entered('y')\n .end(), \n true, 'sequence should be exited[c, a, e, b, x], entered[y]');\n \n equals(statechart.currentStateCount(), 1, 'statechart should only have 1 current state');\n equals(statechart.stateIsCurrentState('c'), false, 'current state not should be c');\n equals(statechart.stateIsCurrentState('e'), false, 'current state not should be e');\n equals(statechart.stateIsCurrentState('y'), true, 'current state should be y');\n});\n\ntest(\"send event eventZ\", function() {\n var monitor = statechart.get('monitor');\n \n monitor.reset();\n \n equals(statechart.stateIsCurrentState('c'), true, 'current state should be c');\n equals(statechart.stateIsCurrentState('e'), true, 'current state should be e');\n \n equals(monitor.get('length'), 0, 'state sequence should be of length 0');\n \n equals(statechart.stateIsCurrentState('c'), true, 'current state should be c');\n equals(statechart.stateIsCurrentState('e'), true, 'current state should be e');\n});\n"}, "files_after": {"frameworks/foundation/system/statechart.js": "// ==========================================================================\n// Project: Ki - A Statechart Framework for SproutCore\n// License: Licensed under MIT license (see license.js)\n// ==========================================================================\n\n/*globals Ki */\n\nsc_require('system/state');\n\n/**\n The startchart manager mixin allows an object to be a statechart. By becoming a statechart, the\n object can then be manage a set of its own states.\n \n This implemention of the statechart manager closely follows the concepts stated in D. Harel's \n original paper \"Statecharts: A Visual Formalism For Complex Systems\" \n (www.wisdom.weizmann.ac.il/~harel/papers/Statecharts.pdf). \n \n The statechart allows for complex state heircharies by nesting states within states, and \n allows for state orthogonality based on the use of concurrent states.\n \n At minimum, a statechart must have one state: The root state. All other states in the statechart\n are a decendents (substates) of the root state.\n \n The following example shows how states are nested within a statechart:\n \n {{{\n \n MyApp.Statechart = SC.Object.extend(Ki.StatechartManager, {\n \n rootState: Ki.State.design({\n \n initialSubstate: 'stateA',\n \n stateA: Ki.State.design({\n // ... can continue to nest further states\n }),\n \n stateB: Ki.State.design({\n // ... can continue to nest further states\n })\n })\n \n })\n \n }}}\n \n Note how in the example above, the root state as an explicit initial substate to enter into. If no\n initial substate is provided, then the statechart will default to the the state's first substate.\n \n You can also defined states without explicitly defining the root state. To do so, simply create properties\n on your object that represents states. Upon initialization, a root state will be constructed automatically\n by the mixin and make the states on the object substates of the root state. As an example:\n \n {{{\n \n MyApp.Statechart = SC.Object.extend(Ki.StatechartManager, {\n \n initialState: 'stateA',\n \n stateA: Ki.State.design({\n // ... can continue to nest further states\n }),\n \n stateB: Ki.State.design({\n // ... can continue to nest further states\n })\n \n })\n \n }}} \n \n If you liked to specify a class that should be used as the root state but using the above method to defined\n states, you can set the rootStateExample property with a class that extends from Ki.State. If the \n rootStateExaple property is not explicitly assigned the then default class used will be Ki.State.\n \n To provide your statechart with orthogonality, you use concurrent states. If you use concurrent states,\n then your statechart will have multiple current states. That is because each concurrent state represents an\n independent state structure from other concurrent states. The following example shows how to provide your\n statechart with concurrent states:\n \n {{{\n \n MyApp.Statechart = SC.Object.extend(Ki.StatechartManager, {\n \n rootState: Ki.State.design({\n \n substatesAreConcurrent: YES,\n \n stateA: Ki.State.design({\n // ... can continue to nest further states\n }),\n \n stateB: Ki.State.design({\n // ... can continue to nest further states\n })\n })\n \n })\n \n }}}\n \n Above, to indicate that a state's substates are concurrent, you just have to set the substatesAreConcurrent to \n YES. Once done, then stateA and stateB will be independent of each other and each will manage their\n own current substates. The root state will then have more then one current substate.\n \n To define concurrent states directly on the object without explicitly defining a root, you can do the \n following:\n \n {{{\n\n MyApp.Statechart = SC.Object.extend(Ki.StatechartManager, {\n \n statesAreConcurrent: YES,\n \n stateA: Ki.State.design({\n // ... can continue to nest further states\n }),\n \n stateB: Ki.State.design({\n // ... can continue to nest further states\n })\n \n })\n\n }}}\n \n Remember that a startchart can have a mixture of nested and concurrent states in order for you to \n create as complex of statecharts that suite your needs. Here is an example of a mixed state structure:\n \n {{{\n \n MyApp.Statechart = SC.Object.extend(Ki.StatechartManager, {\n \n rootState: Ki.State.design({\n \n initialSubstate: 'stateA',\n \n stateA: Ki.State.design({\n \n substatesAreConcurrent: YES,\n \n stateM: Ki.State.design({ ... })\n stateN: Ki.State.design({ ... })\n stateO: Ki.State.design({ ... })\n \n }),\n \n stateB: Ki.State.design({\n \n initialSubstate: 'stateX',\n \n stateX: Ki.State.design({ ... })\n stateY: Ki.State.desgin({ ... })\n \n })\n })\n \n })\n \n }}}\n \n Depending on your needs, a statechart can have lots of states, which can become hard to manage all within\n one file. To modularize your states and make them easier to manage and maintain, you can plug-in states\n into other states. Let's say we are using the statechart in the last example above, and all the code is \n within one file. We could update the code and split the logic across two or more files like so:\n \n {{{\n ---- state_a.js\n \n MyApp.StateA = Ki.State.extend({\n \n substatesAreConcurrent: YES,\n \n stateM: Ki.State.design({ ... })\n stateN: Ki.State.design({ ... })\n stateO: Ki.State.design({ ... })\n \n });\n \n ---- state_b.js\n \n MyApp.StateB = Ki.State.extend({\n \n substatesAreConcurrent: YES,\n \n stateM: Ki.State.design({ ... })\n stateN: Ki.State.design({ ... })\n stateO: Ki.State.design({ ... })\n \n });\n \n ---- statechart.js\n \n MyApp.Statechart = SC.Object.extend(Ki.StatechartManager, {\n \n rootState: Ki.State.design({\n \n initialSubstate: 'stateA',\n \n stateA: Ki.State.plugin('MyApp.StateA'),\n \n stateB: Ki.State.plugin('MyApp.StateB')\n \n })\n \n })\n \n }}}\n \n Using state plug-in functionality is optional. If you use the plug-in feature you can break up your statechart\n into as many files as you see fit.\n\n*/\n\nKi.StatechartManager = {\n \n // Walk like a duck\n isResponderContext: YES,\n \n // Walk like a duck\n isStatechart: YES,\n \n /**\n Indicates if this statechart has been initialized\n\n @property {Boolean}\n */\n statechartIsInitialized: NO,\n \n /**\n The root state of this statechart. All statecharts must have a root state.\n \n If this property is left unassigned then when the statechart is initialized\n it will used the rootStateExample, initialState, and statesAreConcurrent\n properties to construct a root state.\n \n @see #rootStateExample\n @see #initialState\n @see #statesAreConcurrent\n \n @property {Ki.State}\n */\n rootState: null,\n \n /** \n Represents the class used to construct a class that will be the root state for\n this statechart. The class assigned must derive from Ki.State. \n \n This property will only be used if the rootState property is not assigned.\n \n @see #rootState\n \n @property {Ki.State}\n */\n rootStateExample: Ki.State,\n \n /** \n Indicates what state should be the intiail state of this statechart. The value\n assigned must be the name of a property on this object that represents a state.\n As well, the statesAreConcurrent must be set to NO.\n \n This property will only be used if the rootState property is not assigned.\n \n @see #rootState\n \n @property {String} \n */\n initialState: null,\n \n /** \n Indicates if properties on this object representing states are concurrent to each other.\n If YES then they are concurrent, otherwise they are not. If the YES, then the\n initialState property must not be assigned.\n \n This property will only be used if the rootState property is not assigned.\n \n @see #rootState\n \n @property {Boolean}\n */\n statesAreConcurrent: NO,\n \n /** \n Indicates whether to use a monitor to monitor that statechart's activities. If true then\n the monitor will be active, otherwise the monitor will not be used. Useful for debugging\n purposes.\n \n @property {Boolean}\n */\n monitorIsActive: NO,\n \n /**\n A statechart monitor that can be used to monitor this statechart. Useful for debugging purposes.\n A monitor will only be used if monitorIsActive is true.\n \n @property {Ki.StatechartMonitor}\n */\n monitor: null,\n \n /**\n Used to specify what property (key) on the statechart should be used as the trace property. By\n default the property is 'trace'.\n\n @property {String}\n */\n statechartTraceKey: 'trace',\n\n /**\n Indicates whether to trace the statecharts activities. If true then the statechart will output\n its activites to the browser's JS console. Useful for debugging purposes.\n\n @see #statechartTraceKey\n\n @property {Boolean}\n */\n trace: NO,\n \n /**\n Used to specify what property (key) on the statechart should be used as the owner property. By\n default the property is 'owner'.\n\n @property {String}\n */\n statechartOwnerKey: 'owner',\n\n /**\n Sets who the owner is of this statechart. If null then the owner is this object otherwise\n the owner is the assigned object. \n\n @see #statechartOwnerKey\n\n @property {SC.Object}\n */\n owner: null,\n\n /** \n Indicates if the statechart should be automatically initialized by this\n object after it has been created. If YES then initStatechart will be\n called automatically, otherwise it will not.\n \n @property {Boolean}\n */\n autoInitStatechart: YES,\n \n /**\n If yes, any warning messages produced by the statechart or any of its states will\n not be logged, otherwise all warning messages will be logged. \n \n While designing and debugging your statechart, it's best to keep this value false.\n In production you can then suppress the warning messages.\n \n @property {Boolean}\n */\n suppressStatechartWarnings: NO,\n \n initMixin: function() {\n if (this.get('autoInitStatechart')) {\n this.initStatechart();\n }\n },\n \n destroyMixin: function() {\n var root = this.get('rootState'),\n traceKey = this.get('statechartTraceKey');\n\n this.removeObserver(traceKey, this, '_statechartTraceDidChange');\n\n root.destroy();\n this.set('rootState', null);\n },\n\n /**\n Initializes the statechart. By initializing the statechart, it will create all the states and register\n them with the statechart. Once complete, the statechart can be used to go to states and send events to.\n */\n initStatechart: function() {\n if (this.get('statechartIsInitialized')) return;\n \n this._gotoStateLocked = NO;\n this._sendEventLocked = NO;\n this._pendingStateTransitions = [];\n this._pendingSentEvents = [];\n \n this.sendAction = this.sendEvent;\n \n if (this.get('monitorIsActive')) {\n this.set('monitor', Ki.StatechartMonitor.create());\n }\n\n var traceKey = this.get('statechartTraceKey');\n\n this.addObserver(traceKey, this, '_statechartTraceDidChange');\n this._statechartTraceDidChange();\n\n var trace = this.get('allowTracing'),\n rootState = this.get('rootState'),\n msg;\n \n if (trace) this.statechartLogTrace(\"BEGIN initialize statechart\");\n \n // If no root state was explicitly defined then try to construct\n // a root state class\n if (!rootState) {\n rootState = this._constructRootStateClass();\n }\n else if (SC.typeOf(rootState) === SC.T_FUNCTION && rootState.statePlugin) {\n rootState = rootState.apply(this);\n }\n \n if (!(SC.kindOf(rootState, Ki.State) && rootState.isClass)) {\n msg = \"Unable to initialize statechart. Root state must be a state class\";\n this.statechartLogError(msg);\n throw msg;\n }\n \n rootState = this.createRootState(rootState, { \n statechart: this, \n name: Ki.ROOT_STATE_NAME \n });\n \n this.set('rootState', rootState);\n rootState.initState();\n \n if (SC.kindOf(rootState.get('initialSubstate'), Ki.EmptyState)) {\n msg = \"Unable to initialize statechart. Root state must have an initial substate explicilty defined\";\n this.statechartLogError(msg);\n throw msg;\n }\n \n if (!SC.empty(this.get('initialState'))) {\n var key = 'initialState';\n this.set(key, rootState.get(this.get(key)));\n } \n \n this.set('statechartIsInitialized', YES);\n this.gotoState(rootState);\n \n if (trace) this.statechartLogTrace(\"END initialize statechart\");\n },\n \n /**\n Will create a root state for the statechart\n */\n createRootState: function(state, attrs) {\n if (!attrs) attrs = {};\n state = state.create(attrs);\n return state;\n },\n \n /**\n Returns an array of all the current states for this statechart\n \n @returns {Array} the current states\n */\n currentStates: function() {\n return this.getPath('rootState.currentSubstates');\n }.property().cacheable(),\n \n /**\n Returns the first current state for this statechart. \n \n @return {Ki.State}\n */\n firstCurrentState: function() {\n var cs = this.get('currentStates');\n return cs ? cs.objectAt(0) : null;\n }.property('currentStates').cacheable(),\n \n /**\n Returns the count of the current states for this statechart\n \n @returns {Number} the count \n */\n currentStateCount: function() {\n return this.getPath('currentStates.length');\n }.property('currentStates').cacheable(),\n \n /**\n Checks if a given state is a current state of this statechart. \n \n @param state {State} the state to check\n @returns {Boolean} true if the state is a current state, otherwise fals is returned\n */\n stateIsCurrentState: function(state) {\n return this.get('rootState').stateIsCurrentSubstate(state);\n },\n \n /**\n Checks if the given value represents a state is this statechart\n \n @param value {State|String} either a state object or the name of a state\n @returns {Boolean} true if the state does belong ot the statechart, otherwise false is returned\n */\n doesContainState: function(value) {\n return !SC.none(this.getState(value));\n },\n \n /**\n Gets a state from the statechart that matches the given value\n \n @param value {State|String} either a state object of the name of a state\n @returns {State} if a match then the matching state is returned, otherwise null is returned \n */\n getState: function(value) {\n return this.get('rootState').getSubstate(value);\n },\n \n /**\n When called, the statechart will proceed with making state transitions in the statechart starting from \n a current state that meet the statechart conditions. When complete, some or all of the statechart's \n current states will be changed, and all states that were part of the transition process will either \n be exited or entered in a specific order.\n \n The state that is given to go to will not necessarily be a current state when the state transition process\n is complete. The final state or states are dependent on factors such an initial substates, concurrent \n states, and history states.\n \n Because the statechart can have one or more current states, it may be necessary to indicate what current state\n to start from. If no current state to start from is provided, then the statechart will default to using\n the first current state that it has; depending of the make up of the statechart (no concurrent state vs.\n with concurrent states), the outcome may be unexpected. For a statechart with concurrent states, it is best\n to provide a current state in which to start from.\n \n When using history states, the statechart will first make transitions to the given state and then use that\n state's history state and recursively follow each history state's history state until there are no \n more history states to follow. If the given state does not have a history state, then the statechart\n will continue following state transition procedures.\n \n Method can be called in the following ways:\n \n {{{\n \n // With one argument. \n gotoState()\n \n // With two argument.\n gotoState(, )\n \n // With three argument.\n gotoState(, , )\n gotoState(, , )\n \n // With four argument.\n gotoState(, , , )\n \n }}}\n \n where is either a Ki.State object or a string and is a regular JS hash object.\n \n @param state {Ki.State|String} the state to go to (may not be the final state in the transition process)\n @param fromCurrentState {Ki.State|String} Optional. The current state to start the transition process from.\n @param useHistory {Boolean} Optional. Indicates whether to include using history states in the transition process\n @param context {Hash} Optional. A context object that will be passed to all exited and entered states\n */\n gotoState: function(state, fromCurrentState, useHistory, context) {\n \n if (!this.get('statechartIsInitialized')) {\n this.statechartLogError(\"can not go to state %@. statechart has not yet been initialized\".fmt(state));\n return;\n }\n \n if (this.get('isDestroyed')) {\n this.statechartLogError(\"can not go to state %@. statechart is destroyed\".fmt(this));\n return;\n }\n \n var args = this._processGotoStateArgs(arguments);\n\n state = args.state;\n fromCurrentState = args.fromCurrentState;\n useHistory = args.useHistory;\n context = args.context;\n \n var pivotState = null,\n exitStates = [],\n enterStates = [],\n trace = this.get('allowTracing'),\n rootState = this.get('rootState'),\n paramState = state,\n paramFromCurrentState = fromCurrentState;\n \n state = rootState.getSubstate(state);\n \n if (SC.none(state)) {\n this.statechartLogError(\"Can not to goto state %@. Not a recognized state in statechart\".fmt(paramState));\n return;\n }\n \n if (this._gotoStateLocked) {\n // There is a state transition currently happening. Add this requested state\n // transition to the queue of pending state transitions. The request will\n // be invoked after the current state transition is finished.\n this._pendingStateTransitions.push({\n state: state,\n fromCurrentState: fromCurrentState,\n useHistory: useHistory,\n context: context\n });\n \n return;\n }\n \n // Lock the current state transition so that no other requested state transition \n // interferes. \n this._gotoStateLocked = YES;\n \n if (!SC.none(fromCurrentState)) {\n // Check to make sure the current state given is actually a current state of this statechart\n fromCurrentState = rootState.getSubstate(fromCurrentState);\n if (SC.none(fromCurrentState) || !fromCurrentState.get('isCurrentState')) {\n var msg = \"Can not to goto state %@. %@ is not a recognized current state in statechart\";\n this.statechartLogError(msg.fmt(paramState, paramFromCurrentState));\n this._gotoStateLocked = NO;\n return;\n }\n } \n else if (this.getPath('currentStates.length') > 0) {\n // No explicit current state to start from; therefore, just use the first current state as \n // a default, if there is a current state.\n fromCurrentState = this.get('currentStates')[0];\n }\n \n if (trace) {\n this.statechartLogTrace(\"BEGIN gotoState: %@\".fmt(state));\n this.statechartLogTrace(\"starting from current state: %@\".fmt(fromCurrentState));\n this.statechartLogTrace(\"current states before: %@\".fmt(this.get('currentStates')));\n }\n\n // If there is a current state to start the transition process from, then determine what\n // states are to be exited\n if (!SC.none(fromCurrentState)) {\n exitStates = this._createStateChain(fromCurrentState);\n }\n \n // Now determine the initial states to be entered\n enterStates = this._createStateChain(state);\n \n // Get the pivot state to indicate when to go from exiting states to entering states\n pivotState = this._findPivotState(exitStates, enterStates);\n\n if (pivotState) {\n if (trace) this.statechartLogTrace(\"pivot state = %@\".fmt(pivotState));\n if (pivotState.get('substatesAreConcurrent')) {\n this.statechartLogError(\"Can not go to state %@ from %@. Pivot state %@ has concurrent substates.\".fmt(state, fromCurrentState, pivotState));\n this._gotoStateLocked = NO;\n return;\n }\n }\n \n // Collect what actions to perform for the state transition process\n var gotoStateActions = [];\n \n // Go ahead and find states that are to be exited\n this._traverseStatesToExit(exitStates.shift(), exitStates, pivotState, gotoStateActions);\n \n // Now go find states that are to entered\n if (pivotState !== state) {\n this._traverseStatesToEnter(enterStates.pop(), enterStates, pivotState, useHistory, gotoStateActions);\n } else {\n this._traverseStatesToExit(pivotState, [], null, gotoStateActions);\n this._traverseStatesToEnter(pivotState, null, null, useHistory, gotoStateActions);\n }\n \n // Collected all the state transition actions to be performed. Now execute them.\n this._executeGotoStateActions(state, gotoStateActions, null, context);\n },\n \n /**\n Indicates if the statechart is in an active goto state process\n */\n gotoStateActive: function() {\n return this._gotoStateLocked;\n }.property(),\n \n /**\n Indicates if the statechart is in an active goto state process\n that has been suspended\n */\n gotoStateSuspended: function() {\n return this._gotoStateLocked && !!this._gotoStateSuspendedPoint;\n }.property(),\n \n /**\n Resumes an active goto state transition process that has been suspended.\n */\n resumeGotoState: function() {\n if (!this.get('gotoStateSuspended')) {\n this.statechartLogError(\"Can not resume goto state since it has not been suspended\");\n return;\n }\n \n var point = this._gotoStateSuspendedPoint;\n this._executeGotoStateActions(point.gotoState, point.actions, point.marker, point.context);\n },\n \n /** @private */\n _executeGotoStateActions: function(gotoState, actions, marker, context) {\n var action = null,\n len = actions.length,\n actionResult = null;\n \n marker = SC.none(marker) ? 0 : marker;\n \n for (; marker < len; marker += 1) {\n action = actions[marker];\n switch (action.action) {\n case Ki.EXIT_STATE:\n actionResult = this._exitState(action.state, context);\n break;\n \n case Ki.ENTER_STATE:\n actionResult = this._enterState(action.state, action.currentState, context);\n break;\n }\n \n //\n // Check if the state wants to perform an asynchronous action during\n // the state transition process. If so, then we need to first\n // suspend the state transition process and then invoke the \n // asynchronous action. Once called, it is then up to the state or something \n // else to resume this statechart's state transition process by calling the\n // statechart's resumeGotoState method.\n //\n if (SC.kindOf(actionResult, Ki.Async)) {\n this._gotoStateSuspendedPoint = {\n gotoState: gotoState,\n actions: actions,\n marker: marker + 1,\n context: context\n }; \n \n actionResult.tryToPerform(action.state);\n return;\n }\n }\n \n this.notifyPropertyChange('currentStates');\n \n if (this.get('allowTracing')) {\n this.statechartLogTrace(\"current states after: %@\".fmt(this.get('currentStates')));\n this.statechartLogTrace(\"END gotoState: %@\".fmt(gotoState));\n }\n \n // Okay. We're done with the current state transition. Make sure to unlock the\n // gotoState and let other pending state transitions execute.\n this._gotoStateSuspendedPoint = null;\n this._gotoStateLocked = NO;\n this._flushPendingStateTransition();\n },\n \n /** @private */\n _exitState: function(state, context) {\n if (state.get('currentSubstates').indexOf(state) >= 0) { \n var parentState = state.get('parentState');\n while (parentState) {\n parentState.get('currentSubstates').removeObject(state);\n parentState = parentState.get('parentState');\n }\n }\n \n if (this.get('allowTracing')) this.statechartLogTrace(\"exiting state: %@\".fmt(state));\n \n state.set('currentSubstates', []);\n state.notifyPropertyChange('isCurrentState');\n var result = this.exitState(state, context);\n \n if (this.get('monitorIsActive')) this.get('monitor').pushExitedState(state);\n \n state._traverseStatesToExit_skipState = NO;\n \n return result;\n },\n \n /**\n What will actually invoke a state's exitState method.\n \n Called during the state transition process whenever the gotoState method is\n invoked.\n \n @param state {Ki.State} the state whose enterState method is to be invoked\n @param context {Hash} a context hash object to provide the enterState method\n */\n exitState: function(state, context) {\n return state.exitState(context);\n },\n \n /** @private */\n _enterState: function(state, current, context) {\n var parentState = state.get('parentState');\n if (parentState && !state.get('isConcurrentState')) parentState.set('historyState', state);\n \n if (current) {\n parentState = state;\n while (parentState) {\n parentState.get('currentSubstates').push(state);\n parentState = parentState.get('parentState');\n }\n }\n \n if (this.get('allowTracing')) this.statechartLogTrace(\"entering state: %@\".fmt(state));\n \n state.notifyPropertyChange('isCurrentState');\n var result = this.enterState(state, context);\n \n if (this.get('monitorIsActive')) this.get('monitor').pushEnteredState(state);\n \n return result;\n },\n \n /**\n What will actually invoke a state's enterState method.\n \n Called during the state transition process whenever the gotoState method is\n invoked.\n \n @param state {Ki.State} the state whose enterState method is to be invoked\n @param context {Hash} a context hash object to provide the enterState method\n */\n enterState: function(state, context) {\n return state.enterState(context);\n },\n \n /**\n When called, the statechart will proceed to make transitions to the given state then follow that\n state's history state. \n \n You can either go to a given state's history recursively or non-recursively. To go to a state's history\n recursively means to following each history state's history state until no more history states can be\n followed. Non-recursively means to just to the given state's history state but do not recusively follow\n history states. If the given state does not have a history state, then the statechart will just follow\n normal procedures when making state transitions.\n \n Because a statechart can have one or more current states, depending on if the statechart has any concurrent\n states, it is optional to provided current state in which to start the state transition process from. If no\n current state is provided, then the statechart will default to the first current state that it has; which, \n depending on the make up of that statechart, can lead to unexpected outcomes. For a statechart with concurrent\n states, it is best to explicitly supply a current state.\n \n Method can be called in the following ways:\n \n {{{\n \n // With one arguments. \n gotoHistorytate()\n \n // With two arguments. \n gotoHistorytate(, )\n \n // With three arguments.\n gotoHistorytate(, , )\n gotoHistorytate(, , )\n \n // With four argumetns\n gotoHistorytate(, , , )\n \n }}}\n \n where is either a Ki.State object or a string and is a regular JS hash object.\n \n @param state {Ki.State|String} the state to go to and follow it's history state\n @param fromCurrentState {Ki.State|String} Optional. the current state to start the state transition process from\n @param recursive {Boolean} Optional. whether to follow history states recursively.\n */\n gotoHistoryState: function(state, fromCurrentState, recursive, context) {\n if (!this.get('statechartIsInitialized')) {\n this.statechartLogError(\"can not go to state %@'s history state. Statechart has not yet been initialized\".fmt(state));\n return;\n }\n \n var args = this._processGotoStateArgs(arguments);\n \n state = args.state;\n fromCurrentState = args.fromCurrentState;\n recursive = args.useHistory;\n context = args.context;\n \n state = this.getState(state);\n \n if (!state) {\n this.statechartLogError(\"Can not to goto state %@'s history state. Not a recognized state in statechart\".fmt(state));\n return;\n }\n \n var historyState = state.get('historyState');\n \n if (!recursive) { \n if (historyState) {\n this.gotoState(historyState, fromCurrentState, context);\n } else {\n this.gotoState(state, fromCurrentState, context);\n }\n } else {\n this.gotoState(state, fromCurrentState, YES, context);\n }\n },\n \n /**\n Sends a given event to all the statechart's current states.\n \n If a current state does can not respond to the sent event, then the current state's parent state\n will be tried. This process is recursively done until no more parent state can be tried.\n \n @param event {String} name of the event\n @param arg1 {Object} optional argument\n @param arg2 {Object} optional argument\n @returns {SC.Responder} the responder that handled it or null\n */\n sendEvent: function(event, arg1, arg2) {\n \n if (this.get('isDestroyed')) {\n this.statechartLogError(\"can send event %@. statechart is destroyed\".fmt(event));\n return;\n }\n \n var statechartHandledEvent = NO,\n eventHandled = NO,\n currentStates = this.get('currentStates').slice(),\n len = 0,\n i = 0,\n state = null,\n trace = this.get('allowTracing'),\n attemptedStates = [];\n \n if (this._sendEventLocked || this._goStateLocked) {\n // Want to prevent any actions from being processed by the states until \n // they have had a chance to handle the most immediate action or completed \n // a state transition\n this._pendingSentEvents.push({\n event: event,\n arg1: arg1,\n arg2: arg2\n });\n\n return;\n }\n \n this._sendEventLocked = YES;\n \n if (trace) {\n this.statechartLogTrace(\"BEGIN sendEvent: event<%@>\".fmt(event));\n }\n \n len = currentStates.get('length');\n for (; i < len; i += 1) {\n eventHandled = NO;\n state = currentStates[i];\n if (!state.get('isCurrentState')) continue;\n while (!eventHandled && state) {\n if (attemptedStates.indexOf(state) !== -1) break;\n attemptedStates.push(state);\n eventHandled = state.tryToHandleEvent(event, arg1, arg2);\n if (!eventHandled) state = state.get('parentState');\n else statechartHandledEvent = YES;\n }\n }\n \n // Now that all the states have had a chance to process the \n // first event, we can go ahead and flush any pending sent events.\n this._sendEventLocked = NO;\n \n if (trace) {\n if (!statechartHandledEvent) this.statechartLogTrace(\"No state was able handle event %@\".fmt(event));\n this.statechartLogTrace(\"END sendEvent: event<%@>\".fmt(event));\n }\n \n var result = this._flushPendingSentEvents();\n \n return statechartHandledEvent ? this : (result ? this : null);\n },\n\n /** @private\n \n Creates a chain of states from the given state to the greatest ancestor state (the root state). Used\n when perform state transitions.\n */\n _createStateChain: function(state) {\n var chain = [];\n \n while (state) {\n chain.push(state);\n state = state.get('parentState');\n }\n \n return chain;\n },\n \n /** @private\n \n Finds a pivot state from two given state chains. The pivot state is the state indicating when states\n go from being exited to states being entered during the state transition process. The value \n returned is the fist matching state between the two given state chains. \n */\n _findPivotState: function(stateChain1, stateChain2) {\n if (stateChain1.length === 0 || stateChain2.length === 0) return null;\n \n var pivot = stateChain1.find(function(state, index) {\n if (stateChain2.indexOf(state) >= 0) return YES;\n });\n \n return pivot;\n },\n \n /** @private\n \n Recursively follow states that are to be exited during a state transition process. The exit\n process is to start from the given state and work its way up to when either all exit\n states have been reached based on a given exit path or when a stop state has been reached.\n \n @param state {State} the state to be exited\n @param exitStatePath {Array} an array representing a path of states that are to be exited\n @param stopState {State} an explicit state in which to stop the exiting process\n */\n _traverseStatesToExit: function(state, exitStatePath, stopState, gotoStateActions) { \n if (!state || state === stopState) return;\n \n var trace = this.get('allowTracing');\n \n // This state has concurrent substates. Therefore we have to make sure we\n // exit them up to this state before we can go any further up the exit chain.\n if (state.get('substatesAreConcurrent')) {\n var i = 0,\n currentSubstates = state.get('currentSubstates'),\n len = currentSubstates.length,\n currentState = null;\n \n for (; i < len; i += 1) {\n currentState = currentSubstates[i];\n if (currentState._traverseStatesToExit_skipState === YES) continue;\n var chain = this._createStateChain(currentState);\n this._traverseStatesToExit(chain.shift(), chain, state, gotoStateActions);\n }\n }\n \n gotoStateActions.push({ action: Ki.EXIT_STATE, state: state });\n if (state.get('isCurrentState')) state._traverseStatesToExit_skipState = YES;\n this._traverseStatesToExit(exitStatePath.shift(), exitStatePath, stopState, gotoStateActions);\n },\n \n /** @private\n \n Recursively follow states that are to be entred during the state transition process. The\n enter process is to start from the given state and work its way down a given enter path. When\n the end of enter path has been reached, then continue entering states based on whether \n an initial substate is defined, there are concurrent substates or history states are to be\n followed; when none of those condition are met then the enter process is done.\n \n @param state {State} the sate to be entered\n @param enterStatePath {Array} an array representing an initial path of states that are to be entered\n @param pivotState {State} The state pivoting when to go from exiting states to entering states\n @param useHistory {Boolean} indicates whether to recursively follow history states \n */\n _traverseStatesToEnter: function(state, enterStatePath, pivotState, useHistory, gotoStateActions) {\n if (!state) return;\n \n var trace = this.get('allowTracing');\n \n // We do not want to enter states in the enter path until the pivot state has been reached. After\n // the pivot state has been reached, then we can go ahead and actually enter states.\n if (pivotState) {\n if (state !== pivotState) {\n this._traverseStatesToEnter(enterStatePath.pop(), enterStatePath, pivotState, useHistory, gotoStateActions);\n } else {\n this._traverseStatesToEnter(enterStatePath.pop(), enterStatePath, null, useHistory, gotoStateActions);\n }\n }\n \n // If no more explicit enter path instructions, then default to enter states based on \n // other criteria\n else if (!enterStatePath || enterStatePath.length === 0) {\n var gotoStateAction = { action: Ki.ENTER_STATE, state: state, currentState: NO };\n gotoStateActions.push(gotoStateAction);\n \n var initialSubstate = state.get('initialSubstate'),\n historyState = state.get('historyState');\n \n // State has concurrent substates. Need to enter all of the substates\n if (state.get('substatesAreConcurrent')) {\n this._traverseConcurrentStatesToEnter(state.get('substates'), null, useHistory, gotoStateActions);\n }\n \n // State has substates and we are instructed to recursively follow the state's\n // history state if it has one.\n else if (state.get('hasSubstates') && historyState && useHistory) {\n this._traverseStatesToEnter(historyState, null, null, useHistory, gotoStateActions);\n }\n \n // State has an initial substate to enter\n else if (initialSubstate) {\n if (SC.kindOf(initialSubstate, Ki.HistoryState)) {\n if (!useHistory) useHistory = initialSubstate.get('isRecursive');\n initialSubstate = initialSubstate.get('state');\n }\n this._traverseStatesToEnter(initialSubstate, null, null, useHistory, gotoStateActions); \n } \n \n // Looks like we hit the end of the road. Therefore the state has now become\n // a current state of the statechart.\n else {\n gotoStateAction.currentState = YES;\n }\n }\n \n // Still have an explicit enter path to follow, so keep moving through the path.\n else if (enterStatePath.length > 0) {\n gotoStateActions.push({ action: Ki.ENTER_STATE, state: state });\n var nextState = enterStatePath.pop();\n this._traverseStatesToEnter(nextState, enterStatePath, null, useHistory, gotoStateActions); \n \n // We hit a state that has concurrent substates. Must go through each of the substates\n // and enter them\n if (state.get('substatesAreConcurrent')) {\n this._traverseConcurrentStatesToEnter(state.get('substates'), nextState, useHistory, gotoStateActions);\n }\n }\n },\n \n /** @override\n \n Returns YES if the named value translates into an executable function on\n any of the statechart's current states or the statechart itself.\n \n @param event {String} the property name to check\n @returns {Boolean}\n */\n respondsTo: function(event) {\n var currentStates = this.get('currentStates'),\n len = currentStates.get('length'), \n i = 0, state = null;\n \n for (; i < len; i += 1) {\n state = currentStates.objectAt(i);\n while (state) {\n if (state.respondsToEvent(event)) return true;\n state = state.get('parentState');\n }\n }\n \n // None of the current states can respond. Now check the statechart itself\n return SC.typeOf(this[event]) === SC.T_FUNCTION; \n },\n \n /** @override\n \n Attemps to handle a given event against any of the statechart's current states and the\n statechart itself. If any current state can handle the event or the statechart itself can\n handle the event then YES is returned, otherwise NO is returned.\n \n @param event {String} what to perform\n @param arg1 {Object} Optional\n @param arg2 {Object} Optional\n @returns {Boolean} YES if handled, NO if not handled\n */\n tryToPerform: function(event, arg1, arg2) {\n if (this.respondsTo(event)) {\n if (SC.typeOf(this[event]) === SC.T_FUNCTION) return (this[event](arg1, arg2) !== NO);\n else return !!this.sendEvent(event, arg1, arg2);\n } return NO;\n },\n \n /**\n Used to invoke a method on current states. If the method can not be executed\n on a current state, then the state's parent states will be tried in order\n of closest ancestry.\n \n A few notes: \n \n 1) Calling this is not the same as calling sendEvent or sendAction.\n Rather, this should be seen as calling normal methods on a state that \n will *not* call gotoState or gotoHistoryState. \n \n 2) A state will only ever be invoked once per call. So if there are two \n or more current states that have the same parent state, then that parent \n state will only be invoked once if none of the current states are able\n to invoke the given method.\n \n When calling this method, you are able to supply zero ore more arguments\n that can be pass onto the method called on the states. As an example\n \n {{{\n \n invokeStateMethod('render', context, firstTime);\n \n }}}\n \n The above call will invoke the render method on the current states\n and supply the context and firstTime arguments to the method. \n \n Because a statechart can have more than one current state and the method \n invoked may return a value, the addition of a callback function may be provided \n in order to handle the returned value for each state. As an example, let's say\n we want to call a calculate method on the current states where the method\n will return a value when invoked. We can handle the returned values like so:\n \n {{{\n \n invokeStateMethod('calculate', value, function(state, result) {\n // .. handle the result returned from calculate that was invoked\n // on the given state\n })\n \n }}}\n \n If the method invoked does not return a value and a callback function is\n supplied, then result value will simply be undefined. In all cases, if\n a callback function is given, it must be the last value supplied to this\n method.\n \n invokeStateMethod will return a value if only one state was able to have \n the given method invoked on it, otherwise no value is returned. \n \n @param methodName {String} methodName a method name\n @param args {Object...} Optional. any additional arguments\n @param func {Function} Optional. a callback function. Must be the last\n value supplied if provided.\n \n @returns a value if the number of current states is one, otherwise undefined\n is returned. The value is the result of the method that got invoked\n on a state.\n */\n invokeStateMethod: function(methodName, args, func) {\n if (methodName === 'unknownEvent') {\n this.statechartLogError(\"can not invoke method unkownEvent\");\n return;\n }\n \n args = SC.A(arguments); args.shift();\n \n var len = args.length, \n arg = len > 0 ? args[len - 1] : null,\n callback = SC.typeOf(arg) === SC.T_FUNCTION ? args.pop() : null,\n currentStates = this.get('currentStates'), \n i = 0, state = null, checkedStates = {},\n method, result = undefined, calledStates = 0;\n \n len = currentStates.get('length');\n \n for (; i < len; i += 1) {\n state = currentStates.objectAt(i);\n while (state) {\n if (checkedStates[state.get('fullPath')]) break;\n checkedStates[state.get('fullPath')] = YES;\n method = state[methodName];\n if (SC.typeOf(method) === SC.T_FUNCTION && !method.isEventHandler) {\n result = method.apply(state, args);\n if (callback) callback.call(this, state, result);\n calledStates += 1; \n break;\n }\n state = state.get('parentState');\n }\n }\n \n return calledStates === 1 ? result : undefined;\n },\n \n /** @private\n \n Iterate over all the given concurrent states and enter them\n */\n _traverseConcurrentStatesToEnter: function(states, exclude, useHistory, gotoStateActions) {\n var i = 0,\n len = states.length,\n state = null;\n \n for (; i < len; i += 1) {\n state = states[i];\n if (state !== exclude) this._traverseStatesToEnter(state, null, null, useHistory, gotoStateActions);\n }\n },\n \n /** @private\n \n Called by gotoState to flush a pending state transition at the front of the \n pending queue.\n */\n _flushPendingStateTransition: function() {\n if (!this._pendingStateTransitions) {\n this.statechartLogError(\"Unable to flush pending state transition. _pendingStateTransitions is invalid\");\n return;\n }\n var pending = this._pendingStateTransitions.shift();\n if (!pending) return;\n this.gotoState(pending.state, pending.fromCurrentState, pending.useHistory, pending.context);\n },\n \n /** @private\n\n Called by sendEvent to flush a pending actions at the front of the pending\n queue\n */\n _flushPendingSentEvents: function() {\n var pending = this._pendingSentEvents.shift();\n if (!pending) return null;\n return this.sendEvent(pending.event, pending.arg1, pending.arg2);\n },\n \n /** @private */\n _monitorIsActiveDidChange: function() {\n if (this.get('monitorIsActive') && SC.none(this.get('monitor'))) {\n this.set('monitor', Ki.StatechartMonitor.create());\n }\n }.observes('monitorIsActive'),\n \n /** @private \n Will process the arguments supplied to the gotoState method.\n \n TODO: Come back to this and refactor the code. It works, but it\n could certainly be improved\n */\n _processGotoStateArgs: function(args) {\n var processedArgs = { \n state: null, \n fromCurrentState: null, \n useHistory: false, \n context: null \n },\n len = null,\n value = null;\n \n args = SC.$A(args);\n args = args.filter(function(item) {\n return !(item === undefined); \n });\n len = args.length;\n \n if (len < 1) return processedArgs;\n \n processedArgs.state = args[0];\n \n if (len === 2) {\n value = args[1];\n switch (SC.typeOf(value)) {\n case SC.T_BOOL: \n processedArgs.useHistory = value;\n break;\n case SC.T_HASH:\n processedArgs.context = value;\n break;\n default:\n processedArgs.fromCurrentState = value;\n }\n }\n else if (len === 3) {\n value = args[1];\n if (SC.typeOf(value) === SC.T_BOOL) {\n processedArgs.useHistory = value;\n processedArgs.context = args[2];\n } else {\n processedArgs.fromCurrentState = value;\n value = args[2];\n if (SC.typeOf(value) === SC.T_BOOL) {\n processedArgs.useHistory = value;\n } else {\n processedArgs.context = value;\n }\n }\n }\n else {\n processedArgs.fromCurrentState = args[1];\n processedArgs.useHistory = args[2];\n processedArgs.context = args[3];\n }\n \n return processedArgs;\n },\n \n /** @private \n \n Will return a newly constructed root state class. The root state will have substates added to\n it based on properties found on this state that derive from a Ki.State class. For the\n root state to be successfully built, the following much be met:\n \n - The rootStateExample property must be defined with a class that derives from Ki.State\n - Either the initialState or statesAreConcurrent property must be set, but not both\n - There must be one or more states that can be added to the root state\n \n */\n _constructRootStateClass: function() {\n var rsExampleKey = 'rootStateExample',\n rsExample = this.get(rsExampleKey),\n initialState = this.get('initialState'),\n statesAreConcurrent = this.get('statesAreConcurrent'),\n stateCount = 0,\n key, value, valueIsFunc, attrs = {};\n \n if (SC.typeOf(rsExample) === SC.T_FUNCTION && rsExample.statePlugin) {\n rsExample = rsExample.apply(this);\n }\n\n if (!(SC.kindOf(rsExample, Ki.State) && rsExample.isClass)) {\n this._logStatechartCreationError(\"Invalid root state example\");\n return null;\n }\n \n if (statesAreConcurrent && !SC.empty(initialState)) {\n this._logStatechartCreationError(\"Can not assign an initial state when states are concurrent\");\n } else if (statesAreConcurrent) {\n attrs.substatesAreConcurrent = YES;\n } else if (SC.typeOf(initialState) === SC.T_STRING) {\n attrs.initialSubstate = initialState;\n } else {\n this._logStatechartCreationError(\"Must either define initial state or assign states as concurrent\");\n return null;\n }\n \n for (key in this) {\n if (key === rsExampleKey) continue;\n \n value = this[key];\n valueIsFunc = SC.typeOf(value) === SC.T_FUNCTION;\n \n if (valueIsFunc && value.statePlugin) {\n value = value.apply(this);\n }\n \n if (SC.kindOf(value, Ki.State) && value.isClass && this[key] !== this.constructor) {\n attrs[key] = value;\n stateCount += 1;\n }\n }\n \n if (stateCount === 0) {\n this._logStatechartCreationError(\"Must define one or more states\");\n return null;\n }\n \n return rsExample.extend(attrs);\n },\n \n /** @private */\n _logStatechartCreationError: function(msg) {\n SC.Logger.error(\"Unable to create statechart for %@: %@.\".fmt(this, msg));\n },\n \n /** \n Used to log a statechart trace message\n */\n statechartLogTrace: function(msg) {\n SC.Logger.info(\"%@: %@\".fmt(this.get('statechartLogPrefix'), msg));\n },\n \n /**\n Used to log a statechart error message\n */\n statechartLogError: function(msg) {\n SC.Logger.error(\"ERROR %@: %@\".fmt(this.get('statechartLogPrefix'), msg));\n },\n \n /** \n Used to log a statechart warning message\n */\n statechartLogWarning: function(msg) {\n if (this.get('suppressStatechartWarnings')) return;\n SC.Logger.warn(\"WARN %@: %@\".fmt(this.get('statechartLogPrefix'), msg));\n },\n \n /** @property */\n statechartLogPrefix: function() {\n var className = SC._object_className(this.constructor),\n name = this.get('name'), prefix;\n \n if (SC.empty(name)) prefix = \"%@<%@>\".fmt(className, SC.guidFor(this));\n else prefix = \"%@<%@, %@>\".fmt(className, name, SC.guidFor(this));\n \n return prefix;\n }.property().cacheable(),\n\n /** @private @property */\n allowTracing: function() {\n var key = this.get('statechartTraceKey');\n return this.get(key);\n }.property().cacheable(),\n\n /** @private */\n _statechartTraceDidChange: function() {\n this.notifyPropertyChange('allowTracing');\n }\n \n};\n\n/** \n The default name given to a statechart's root state\n*/\nKi.ROOT_STATE_NAME = \"__ROOT_STATE__\";\n\n/**\n Constants used during the state transition process\n*/\nKi.EXIT_STATE = 0;\nKi.ENTER_STATE = 1;\n\n/**\n A Startchart class. \n*/\nKi.Statechart = SC.Object.extend(Ki.StatechartManager, {\n autoInitStatechart: NO\n});\n\nKi.Statechart.design = Ki.Statechart.extend;\n\n/**\n Represents a call that is intended to be asynchronous. This is\n used during a state transition process when either entering or\n exiting a state.\n*/\nKi.Async = SC.Object.extend({\n \n func: null,\n \n arg1: null,\n \n arg2: null,\n \n /** @private\n Called by the statechart\n */\n tryToPerform: function(state) {\n var func = this.get('func'),\n arg1 = this.get('arg1'),\n arg2 = this.get('arg2'),\n funcType = SC.typeOf(func);\n \n if (funcType === SC.T_STRING) {\n state.tryToPerform(func, arg1, arg2);\n } \n else if (funcType === SC.T_FUNCTION) {\n func.apply(state, [arg1, arg2]);\n }\n }\n \n});\n\n/**\n Singleton\n*/\nKi.Async.mixin({\n \n /**\n Call in either a state's enterState or exitState method when you\n want a state to perform an asynchronous action, such as an animation.\n \n Examples:\n \n {{\n \n Ki.State.extend({\n \n enterState: function() {\n return Ki.Async.perform('foo');\n },\n \n exitState: function() {\n return Ki.Async.perform('bar', 100);\n }\n \n foo: function() { ... },\n \n bar: function(arg) { ... }\n \n });\n \n }}\n \n @param func {String|Function} the functio to be invoked on a state\n @param arg1 Optional. An argument to pass to the given function\n @param arg2 Optional. An argument to pass to the given function\n @return {Ki.Async} a new instance of a Ki.Async\n */\n perform: function(func, arg1, arg2) {\n return Ki.Async.create({ func: func, arg1: arg1, arg2: arg2 });\n }\n \n});\n", "frameworks/foundation/tests/event_handling/basic/with_concurrent_states.js": "// ==========================================================================\n// Ki.Statechart Unit Test\n// ==========================================================================\n/*globals Ki */\n\nvar statechart = null;\n\n// ..........................................................\n// CONTENT CHANGING\n// \n\nmodule(\"Ki.Statechart: With Concurrent States - Send Event Tests\", {\n setup: function() {\n\n statechart = Ki.Statechart.create({\n \n monitorIsActive: YES,\n \n rootState: Ki.State.design({\n \n initialSubstate: 'x',\n \n x: Ki.State.design({\n \n substatesAreConcurrent: YES,\n \n a: Ki.State.design({\n\n initialSubstate: 'c',\n\n eventAInvoked: NO,\n\n eventA: function() { this.set('eventAInvoked', YES); },\n\n c: Ki.State.design({\n eventB: function() { this.gotoState('d'); },\n eventD: function() { this.gotoState('y'); }\n }),\n\n d: Ki.State.design({\n eventC: function() { this.gotoState('c'); }\n })\n\n }),\n\n b: Ki.State.design({\n\n initialSubstate: 'e',\n\n eventAInvoked: NO,\n\n eventA: function() { this.set('eventAInvoked', YES); },\n\n e: Ki.State.design({\n eventB: function() { this.gotoState('f'); },\n eventD: function() { this.gotoState('y'); }\n }),\n\n f: Ki.State.design({\n eventC: function() { this.gotoState('e'); }\n })\n\n })\n \n }),\n \n y: Ki.State.design(),\n\n numEventEInvocations: 0,\n\n eventE: function() {\n var num = this.get('numEventEInvocations');\n this.set('numEventEInvocations', num + 1);\n }\n })\n \n });\n \n statechart.initStatechart();\n },\n \n teardown: function() {\n statechart.destroy();\n statechart = null;\n }\n});\n\ntest(\"send event eventA\", function() {\n var monitor = statechart.get('monitor'),\n stateA = statechart.getState('a'),\n stateB = statechart.getState('b');\n \n monitor.reset();\n\n equals(stateA.get('eventAInvoked'), false);\n equals(stateB.get('eventAInvoked'), false);\n\n statechart.sendEvent('eventA');\n \n equals(monitor.get('length'), 0, 'state sequence should be of length 0');\n equals(statechart.stateIsCurrentState('c'), true, 'current state should be c');\n equals(statechart.stateIsCurrentState('e'), true, 'current state should be e');\n equals(stateA.get('eventAInvoked'), true);\n equals(stateB.get('eventAInvoked'), true);\n});\n\ntest(\"send event eventB\", function() {\n var monitor = statechart.get('monitor');\n \n monitor.reset();\n \n equals(statechart.stateIsCurrentState('c'), true, 'current state should be c');\n equals(statechart.stateIsCurrentState('e'), true, 'current state should be e');\n \n statechart.sendEvent('eventB');\n \n equals(statechart.get('currentStateCount'), 2, 'current state count should be 2');\n equals(statechart.stateIsCurrentState('d'), true, 'current state should be d');\n equals(statechart.stateIsCurrentState('f'), true, 'current state should be f');\n \n equals(monitor.get('length'), 4, 'state sequence should be of length 4');\n equals(monitor.matchSequence()\n .begin()\n .exited('c').entered('d')\n .exited('e').entered('f')\n .end(), \n true, 'sequence should be exited[c], entered[d], exited[e], entered[f]');\n});\n\ntest(\"send event eventB then eventC\", function() {\n var monitor = statechart.get('monitor');\n\n statechart.sendEvent('eventB');\n \n equals(statechart.stateIsCurrentState('d'), true, 'current state should be d');\n equals(statechart.stateIsCurrentState('f'), true, 'current state should be f');\n\n monitor.reset();\n \n statechart.sendEvent('eventC');\n\n equals(statechart.stateIsCurrentState('c'), true, 'current state should be c');\n equals(statechart.stateIsCurrentState('e'), true, 'current state should be e');\n\n equals(monitor.get('length'), 4, 'state sequence should be of length 4');\n equals(monitor.matchSequence()\n .begin()\n .exited('d').entered('c')\n .exited('f').entered('e')\n .end(), \n true, 'sequence should be exited[d], entered[c], exited[f], entered[e]');\n});\n\ntest(\"send event eventD\", function() {\n var monitor = statechart.get('monitor');\n \n monitor.reset();\n \n equals(statechart.stateIsCurrentState('c'), true, 'current state should be c');\n equals(statechart.stateIsCurrentState('e'), true, 'current state should be e');\n \n statechart.sendEvent('eventD');\n \n equals(monitor.get('length'), 6, 'state sequence should be of length 6');\n equals(monitor.matchSequence()\n .begin()\n .exited('c', 'a', 'e', 'b', 'x').entered('y')\n .end(), \n true, 'sequence should be exited[c, a, e, b, x], entered[y]');\n \n equals(statechart.currentStateCount(), 1, 'statechart should only have 1 current state');\n equals(statechart.stateIsCurrentState('c'), false, 'current state not should be c');\n equals(statechart.stateIsCurrentState('e'), false, 'current state not should be e');\n equals(statechart.stateIsCurrentState('y'), true, 'current state should be y');\n});\n\ntest(\"send event eventE\", function() {\n equals(statechart.stateIsCurrentState('c'), true, 'current state should be c');\n equals(statechart.stateIsCurrentState('e'), true, 'current state should be e');\n\n statechart.sendEvent('eventE');\n\n equals(statechart.stateIsCurrentState('c'), true, 'current state should be c');\n equals(statechart.stateIsCurrentState('e'), true, 'current state should be e');\n\n equals(statechart.getPath('rootState.numEventEInvocations'), 1, 'eventE should be invoked only once')\n});\n\ntest(\"send event eventZ\", function() {\n var monitor = statechart.get('monitor');\n \n monitor.reset();\n \n equals(statechart.stateIsCurrentState('c'), true, 'current state should be c');\n equals(statechart.stateIsCurrentState('e'), true, 'current state should be e');\n \n equals(monitor.get('length'), 0, 'state sequence should be of length 0');\n \n equals(statechart.stateIsCurrentState('c'), true, 'current state should be c');\n equals(statechart.stateIsCurrentState('e'), true, 'current state should be e');\n});\n"}} -{"repo": "nicolaasmatthijs/3akai-ux", "pr_number": 21, "title": "SAKIII-4928, SAKIII-4936, SAKIII-4942, SAKIII-4958, SAKIII-4961, SAKIII-4967, SAKIII-4968, SAKIII-4971, SAKIII-4878, SAKIII-4980, SAKIII-4997, SAKIII-5002, SAKIII-5028, SAKIII-5029, SAKIII-5032", "state": "closed", "merged_at": "2012-02-22T13:54:17Z", "additions": 109191, "deletions": 3438, "files_changed": ["dev/403.html", "dev/404.html", "dev/500.html", "dev/acknowledgements.html", "dev/allcategories.html", "dev/category.html", "dev/configuration/config.js", "dev/content_profile.html", "dev/create_new_account.html", "dev/createnew.html", "dev/css/FSS/fss-base.css", "dev/css/sakai/sakai.base.css", "dev/css/sakai/sakai.corev1.css", "dev/group.html", "dev/index.html", "dev/javascript/acknowledgements.js", "dev/javascript/category.js", "dev/javascript/content_profile.js", "dev/javascript/createnew.js", "dev/javascript/search.js", "dev/javascript/user.js", "dev/layout1.html", "dev/layout2.html", "dev/lib/__tinymce/classes/AddOnManager.js", "dev/lib/__tinymce/classes/ControlManager.js"], "files_before": {"dev/403.html": "\n\n\n \n\n \n \n \n \n\n \n \n \n\n \n \n\n \n\n \n\n \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n \n

            __MSG__NO_ACCOUNT__ __MSG__SIGN_UP__

            \n
            \n
            \n
            __MSG__ARE_YOU_LOOKING_FOR__
            \n
            \n
            \n \n
            \n
            \n
            \n \n
            \n
            \n \n
            \n
            \n\n
            \n
            __MSG__BROWSE_CATEGORIES__
            \n
            \n
            \n
            \n

            __MSG__YOU_CAN_BROWSE_THIS_INSTITUTION__ __MSG__CATEGORIES_LC__ __MSG__WHERE_YOU_CAN_CONNECT_WITH_PEOPLE_VIEW_COURSE_DETAILS_SEARCH_FOR_CONTENT_AND_JOIN_GROUPS__

            \n
            \n
            \n \n
            \n
            \n
            \n
            \n \"__MSG__YOU_ARE_NOT_ALLOWED_TO_SEE_THIS_PAGE__\"\n
            \n

            __MSG__YOU_ARE_NOT_ALLOWED_TO_SEE_THIS_PAGE__

            \n

            __MSG__YOU_TRIED_TO_ACCESS_PAGE_WITHOUT_PERMISSIONS__

            \n\n

            __MSG__WHAT_TO_DO_NOW_HERE_ARE_SOME_SUGGESTIONS__

            \n
            \n \n \n
            \n\n \n \n
            \n
            \n
            \n
            \n \n
            \n\n \n \n\n \n \n \n\n", "dev/404.html": "\n\n\n \n\n \n \n \n \n\n \n \n \n\n \n \n\n \n\n \n\n \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n \n

            __MSG__NO_ACCOUNT__ __MSG__SIGN_UP__

            \n
            \n
            \n
            __MSG__ARE_YOU_LOOKING_FOR__
            \n
            \n
            \n \n
            \n
            \n
            \n \n
            \n
            \n \n
            \n
            \n\n
            \n
            __MSG__BROWSE_CATEGORIES__
            \n
            \n
            \n
            \n

            __MSG__YOU_CAN_BROWSE_THIS_INSTITUTION__ 0 __MSG__CATEGORIES_LC__ __MSG__WHERE_YOU_CAN_CONNECT_WITH_PEOPLE_VIEW_COURSE_DETAILS_SEARCH_FOR_CONTENT_AND_JOIN_GROUPS__

            \n
            \n
            \n \n
            \n
            \n
            \n
            \n \"__MSG__THE_PAGE_YOU_REQUESTED_WAS_NOT_FOUND__\"\n
            \n

            __MSG__THE_PAGE_YOU_REQUESTED_WAS_NOT_FOUND__

            \n

            __MSG__POSSIBLE_REASONS_FOR_THE_PAGE_NOT_BEING_FOUND__

            \n
            \n
            \n
            \n

            __MSG__WHAT_TO_DO_NOW_HERE_ARE_SOME_SUGGESTIONS__

            \n
            \n \n \n
            \n\n \n \n
            \n
            \n
            \n
            \n \n
            \n\n \n \n\n \n \n \n\n", "dev/500.html": "\n\n\n \n\n \n \n \n \n\n \n \n \n\n \n \n\n \n\n \n\n \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n \n

            __MSG__NO_ACCOUNT__ __MSG__SIGN_UP__

            \n
            \n
            \n
            __MSG__ARE_YOU_LOOKING_FOR__
            \n
            \n
            \n \n
            \n
            \n
            \n \n
            \n
            \n \n
            \n
            \n\n
            \n
            __MSG__BROWSE_CATEGORIES__
            \n
            \n
            \n
            \n

            __MSG__YOU_CAN_BROWSE_THIS_INSTITUTION__ __MSG__CATEGORIES_LC__ __MSG__WHERE_YOU_CAN_CONNECT_WITH_PEOPLE_VIEW_COURSE_DETAILS_SEARCH_FOR_CONTENT_AND_JOIN_GROUPS__

            \n
            \n
            \n \n
            \n
            \n
            \n
            \n \"__MSG__OOPS_AN_ERROR_HAS_OCCURRED__\"\n
            \n

            __MSG__OOPS_AN_ERROR_HAS_OCCURRED__

            \n

            \n\n

            __MSG__WHAT_TO_DO_NOW_HERE_ARE_SOME_SUGGESTIONS__

            \n
            \n \n \n
            \n\n \n \n
            \n
            \n
            \n
            \n \n
            \n\n \n \n\n \n \n \n\n", "dev/acknowledgements.html": "\n\n\n \n\n \n \n \n\n \n \n\n \n \n \n \n \n\n \n \n \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n \n \n \n \n
            \n \n
            \n\n \n
            \n
            \n
            \n
            \n \"__MSG__JQUERY__\"\n \"__MSG__JQUERY__\"\n
            \n
            \n

            __MSG__JQUERY_AND_JQUERY_UI__

            \n www.jquery.com

            \n __MSG__JQUERY_IS_A_FAST_AND_CONCISE__\n
            \n
            \n
            \n
            \n\n \n
            \n
            \n
            \n
            \n \"__MSG__APACHE_SLING__\"\n
            \n
            \n

            __MSG__APACHE_SLING__

            \n sling.apache.org

            \n __MSG__APACHE_SLING_IS_A_WEB_FRAMWORK__\n
            \n
            \n
            \n
            \n\n \n
            \n
            \n
            \n
            \n \"__MSG__FLUID_INFUSION__\"\n
            \n
            \n

            __MSG__FLUID_INFUSION__

            \n http://www.fluidproject.org/products/infusion

            \n __MSG__WE_THINK_GOOD_INTERFACES__\n
            \n
            \n
            \n
            \n\n
            \n
            \n
            \n\n \n
            \n __MSG__THE_PRODUCT_INCLUDES_SOFTWARE_FROM__\n\n
            \n

            __MSG__TRIMPATH__

            \n http://code.google.com/p/trimpath/wiki/JavaScriptTemplates\n
            \n __MSG__JAVASCRIPT_TEMPLATES__\n
            \n
            \n

            __MSG__MOXIECODE_SYSTEMS_AB__

            \n tinymce.moxiecode.com\n
            \n __MSG__TINYMCE_JAVASCRIPT_WYSIWYG_EDITOR__\n
            \n
            \n

            __MSG__GOOGLE_INC__

            \n http://code.google.com/p/google-caja/wiki/JsHtmlSanitizer\n
            \n __MSG__JSHTMLSANITIZER_LIBRARY_FROM_THE_CAJA_PROJECT__\n
            \n
            \n

            __MSG__JORDAN_BOESH__

            \n www.boedesign.com\n
            \n __MSG__GRITTER_JQUERY_PLUGIN__\n
            \n
            \n

            __MSG__BRICE_BURGESS__

            \n http://dev.iceburg.net/jquery/jqModal\n
            \n __MSG__JQMODAL_JQUERY_PLUGIN__\n
            \n
            \n

            __MSG__DREW_WILSON__

            \n http://code.drewwilson.com/entry/autosuggest-jquery-plugin\n
            \n __MSG__AUTOSUGGEST_JQUERY_PLUGIN__\n
            \n
            \n

            __MSG__COWBOY_BEN_ALMAN__

            \n http://benalman.com/about/license\n
            \n __MSG__JQUERY_BBQ__\n
            \n
            \n

            __MSG__KLAUS_HARTL__

            \n stilbuero.de\n
            \n __MSG__COOKIE_JQUERY_PLUGIN__\n
            \n
            \n

            __MSG__MIKE_ALSUP__

            \n http://malsup.com/jquery/form\n
            \n __MSG__JQUERY_FORM_PLUGIN__\n
            \n
            \n

            __MSG__MICHAL_WOJCIECHOWSKI__

            \n http://odyniec.net/projects/imgareaselect\n
            \n __MSG__IMGAREASELECT_JQUERY_PLUGIN__\n
            \n
            \n

            __MSG__MIKA_TUUPOLA_DYLAN_VERHEUL__

            \n http://www.appelsiini.net/projects/jeditable\n
            \n __MSG__JEDITABLE_JQUERY_PLUGIN__\n
            \n
            \n

            __MSG__BRANTLEY_HARRIS__

            \n http://code.google.com/p/jquery-json\n
            \n __MSG__JQUERY_JSON_PLUGIN__\n
            \n
            \n

            __MSG__IVAN_BOSZHANOV__

            \n jstree.com\n
            \n __MSG__JSTREE_JQUERY_PLUGIN__\n
            \n
            \n

            __MSG__FYNETWORKS_COM__

            \n http://www.fyneworks.com/jquery/multiple-file-upload\n
            \n __MSG__JQUERY_MULTIPLE_FILE_UPLOAD_PLUGIN__\n
            \n
            \n

            __MSG__JON_PAUL_DAVIES__

            \n http://jonpauldavies.github.com/JQuery/Pager\n
            \n __MSG__JQUERY_PAGER_PLUGIN__\n
            \n
            \n

            __MSG__AUTHOR_JEREMY_HORN__

            \n http://tpgblog.com/ThreeDots\n
            \n __MSG__THREEDOTS_JQUERY_PLUGIN__\n
            \n
            \n

            __MSG__RYAN_MCGEARY__

            \n timeago.yarp.com\n
            \n __MSG__TIMEAGO_JQUERY_PLUGIN__\n
            \n
            \n

            __MSG__JORN_ZAEFFERER__

            \n http://bassistance.de/jquery-plugins/jquery-plugin-validation\n
            \n __MSG__JQUERY_VALIDATION_PLUGIN__\n
            \n
            \n

            __MSG__ADAM_VANDENBERG__

            \n http://adamv.com/dev/javascript/querystring\n
            \n __MSG__QUERYSTRING__\n
            \n
            \n

            __MSG__DOMINIC_MITCHELL__

            \n http://search.cpan.org/~hdm/JavaScript-JSLint-0.06\n
            \n __MSG__JAVASCRIPT_JSLINT__\n
            \n
            \n

            __MSG__MICHAEL_MATHEWS__

            \n http://code.google.com/p/jsdoc-toolkit\n
            \n __MSG__JSDOC_TOOLKIT__\n
            \n
            \n

            __MSG__YAHOO_INC__

            \n http://developer.yahoo.com/yui/compressor\n
            \n __MSG__YUI_COMPRESSOR__\n
            \n
            \n

            __MSG__YUSUKE_KAMIYAMANE__

            \n p.yusukekamiyamane.com\n
            \n __MSG__FUGUE_ICONS__\n
            \n
            \n

            __MSG__MARK_JAMES__

            \n http://www.famfamfam.com/lab/icons/silk\n
            \n __MSG__SILK_ICONS__\n
            \n
            \n

            __MSG__APACHE_SOFTWARE_FOUNDATION__

            \n www.apache.org\n
            \n
            \n
            \n

            __MSG__ANT_CONTRIB__

            \n http://sourceforge.net/projects/ant-contrib\n
            \n
            \n\n
            \n
            \n
            \n\n \n
            \n\n \n
            \n

            __MSG__NAKAMURA_THE_SERVER_PART_OF_SAKAI_3__

            \n
              \n
            • __MSG__APACHE_ARIES_JMX_API__
            • \n
            • __MSG__APACHE_ARIES_JMS_CORE__
            • \n
            • __MSG__APACHE_COMMONS_IO_BUNDLE__
            • \n
            • __MSG__APACHE_DERBY__
            • \n
            • __MSG__APACHE_FELIX_BUNDLE_REPOSITORY__
            • \n
            • __MSG__APACHE_FELIX_CONFIGURATION_ADMIN_SERVICE__
            • \n
            • __MSG__APACHE_FELIX_DECLARATIVE_SERVICES__
            • \n
            • __MSG__APACHE_FELIX_EVENTADMIN__
            • \n
            • __MSG__APACHE_FELIX_FILE_INSTALL__
            • \n
            • __MSG__APACHE_FELIX_HTTP_WHITEBOARD__
            • \n
            • __MSG__APACHE_FELIX_METATYPE_SERVICE__
            • \n
            • __MSG__APACHE_FELIX_WEB_CONSOLE_EVENT_PLUGIN__
            • \n
            • __MSG__APACHE_FELIX_WEB_CONSOLE_MEMORY_USAGE_PLUGIN__
            • \n
            • __MSG__APACHE_FELIX_WEB_MANAGEMENT_CONSOLE__
            • \n
            • __MSG__APACHE_JACKRABBIT_API__
            • \n
            • __MSG__APACHE_SLING_ADAPTER_MANAGER_IMPLEMENTATION__
            • \n
            • __MSG__APACHE_SLING_API__
            • \n
            • __MSG__APACHE_SLING_AUTHENTICATION_SERVICE__
            • \n
            • __MSG__APACHE_SLING_BUNDLE_RESOURCE_PROVIDER__
            • \n
            • __MSG__APACHE_SLING_COMMONS_OSGI_SUPPORT__
            • \n
            • __MSG__APACHE_SLING_DEFAULT_GET_SERVLETS__
            • \n
            • __MSG__APACHE_SLING_DEFAULT_POST_SERVLETS__
            • \n
            • __MSG__APACHE_SLING_DYNAMIC_CLASS_LOADER_SUPPORT__
            • \n
            • __MSG__APACHE_SLING_ENGINE_IMPLEMENTATION__
            • \n
            • __MSG__APACHE_SLING_FILESYSTEM_RESOURCE_PROVIDER__
            • \n
            • __MSG__APACHE_SLING_GROOVY_EXTENSION__
            • \n
            • __MSG__APACHE_SLING_INITIAL_CONTENT_LOADER__
            • \n
            • __MSG__APACHE_SLING_JACKRABBIT_EMBEDDED_REPOSITORY__
            • \n
            • __MSG__APACHE_SLING_JACKRABBIT_JSR_ACCESS_CONTROL_MANAGER_SUPPORT__
            • \n
            • __MSG__APACHE_SLING_JCR_BASE_BUNDLE__
            • \n
            • __MSG__APACHE_SLING_JCR_CLASSLOADER__
            • \n
            • __MSG__APACHE_SLING_JCR_RESOURCE_RESOLVER__
            • \n
            • __MSG__APACHE_SLING_JCR_WEBCONSOLE_BUNDLE__
            • \n
            • __MSG__APACHE_SLING_JSON_LIBRARY__
            • \n
            • __MSG__APACHE_SLING_JSP_TAG_LIBRARY__
            • \n
            • __MSG__APACHE_SLING_LAUNCHPAD_CONTENT__
            • \n
            • __MSG__APACHE_SLING_MIME_TYPE_MAPPING_SUPPORT__
            • \n
            • __MSG__APACHE_SLING_OBJECT_CONTENT_MAPPING__
            • \n
            • __MSG__APACHE_SLING_OPENID_AUTHENTICATION__
            • \n
            • __MSG__APACHE_SLING_OSGI_LOGSERVICE_IMPLEMENTATION__
            • \n
            • __MSG__APACHE_SLING_REPOSITORY_API_BUNDLE__
            • \n
            • __MSG__APACHE_SLING_SCHEDULER_SUPPORT__
            • \n
            • __MSG__APACHE_SLING_SCRIPTING_CORE_IMPLEMENTATION__
            • \n
            • __MSG__APACHE_SLING_SCRIPTING_IMPLEMENTATION_API__
            • \n
            • __MSG__APACHE_SLING_SCRIPTING_JAVASCRIPT_SUPPORT__
            • \n
            • __MSG__APACHE_SLING_SCRIPTING_JSP_SUPPORT__
            • \n
            • __MSG__APACHE_SLING_SERVLET_RESOLVER__
            • \n
            • __MSG__APACHE_SLING_SETTINGS__
            • \n
            • __MSG__APACHE_SLING_THREAD_DUMPER__
            • \n
            • __MSG__APACHE_SLING_THREAD_SUPPORT__
            • \n
            • __MSG__APACHE_SLING_WEB_CONSOLE_BRANDING__
            • \n
            • __MSG__APACHE_SLING_WEB_CONSOLE_SECURITY_PROVIDER__
            • \n
            • __MSG__COMMONS_CODE__
            • \n
            • __MSG__COMMONS_COLLECTIONS__
            • \n
            • __MSG__COMMONS_EMAIL__
            • \n
            • __MSG__COMMONS_FILEUPLOAD__
            • \n
            • __MSG__COMMONS_LANG__
            • \n
            • __MSG__COMMONS_POOL__
            • \n
            • __MSG__CONTENT_REPOSITORY_FOR_JAVATM_TECHNOLOGY_API__
            • \n
            • __MSG__GERONIMO_EJB__
            • \n
            • __MSG__GERONIMO_J2EE_CONNECTOR__
            • \n
            • __MSG__GERONIMO_J2EE_MANAGEMENT__
            • \n
            • __MSG__GERONIMO_JMS__
            • \n
            • __MSG__GERONIMO_JTA__
            • \n
            • __MSG__GROOVY_RUNTIME__
            • \n
            • __MSG__JACKRABBIT_JCR_COMMONS__
            • \n
            • __MSG__JACKRABBIT_JCR_RMI__
            • \n
            • __MSG__JACKRABBIT_SPI__
            • \n
            • __MSG__JACKRABBIT_SPI_COMMONS__
            • \n
            • __MSG__JAXB_API__
            • \n
            • __MSG__NAKAMURA_HTTP_JETTY__
            • \n
            • __MSG__OPS4J_PAX_WEB_SERVICE__
            • \n
            • __MSG__SAKAI_3_UX_LOADER__
            • \n
            • __MSG__SAKAI_NAKAMURA_ACTIVE_MQ_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_ACTIVITY_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_APACHE_COMMONS_HTTPCLIENT_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_AUTHORIZATION_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_BASIC_LTI_CONSUMER_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_BATCH_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_CALENDAR_BASED_EVENTS_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_CAPTCHA_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_CHAT_SERVICES_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_CONFIGURATION_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_CONNECTIONS_MANAGEMENT_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_DATABASE_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_DISCUSSION_MANAGEMENT_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_DOCUMENT_PROXY__
            • \n
            • __MSG__SAKAI_NAKAMURA_DOCUMENTATION_SUPPORT_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_FILES_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_FORM_AUTH_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_GOOGLE_COLLECTIONS__
            • \n
            • __MSG__SAKAI_NAKAMURA_HTTP_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_IMAGE_SERVICE__
            • \n
            • __MSG__SAKAI_NAKAMURA_JAVAX_ACTIVATION_AND_MAIL_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_JAXP_API_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_JCR_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_JSON_LIB_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_LOCKING_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_ME_SERVICE_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_MEMORY_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_MESSAGING_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_MODEL_DIRECTORY__
            • \n
            • __MSG__SAKAI_NAKAMURA_OSGI_TO_JMS_EVENTS_BRIDGE_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_OUTGOING_EMAIL_SENDER__
            • \n
            • __MSG__SAKAI_NAKAMURA_PAGES_STRUCTURED_CONTENT__
            • \n
            • __MSG__SAKAI_NAKAMURA_PERSONAL_SPACE_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_PRESENCE_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_PROFILE_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_PROXY_SERVICE__
            • \n
            • __MSG__SAKAI_NAKAMURA_SAKAI_CLUSTER_TRACKING__
            • \n
            • __MSG__SAKAI_NAKAMURA_SEARCH_SUPPORT_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_SECURITY_LOADER_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_SITE_SERVICE_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_SLING_RESOURCE_EXTENSION BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_SMTP_SERVER__
            • \n
            • __MSG__SAKAI_NAKAMURA_SOLR_BASED_SEARCH_SERVICE__
            • \n
            • __MSG__SAKAI_NAKAMURA_SPARSE_MAP_CONTENT_STORAGE_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_TEMPLATES_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_TIKA_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_TRUSTED_AUTHENTICATION_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_USER_EXTENSIONS_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_UTILITIES__
            • \n
            • __MSG__SAKAI_NAKAMURA_VERSION_EXTENSION_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_WOODSTOX_STAX__
            • \n
            • __MSG__SAKAI_NAKAMURA_WORLD_SUPPORT__
            • \n
            \n
            \n\n __MSG__COPYRIGHT_THE_SAKAI_FOUNDATION__\n
            \n
            \n\n \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n\n \n
            \n\n\n \n \n\n \n \n \n\n", "dev/allcategories.html": "\n\n \n \n \n \n \n \n \n \n \n \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            __MSG__ALL_CATEGORIES__
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n \n
            \n\n \n \n \n \n", "dev/category.html": "\n\n \n \n \n \n \n \n \n \n \n \n
            __MSG__IE_PLACEHOLDER__
            \n \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n \n
            \n\n \n \n \n \n", "dev/configuration/config.js": "/*\n * Licensed to the Sakai Foundation (SF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The SF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations under the License.\n */\ndefine(function(){\n var config = {\n URL: {\n // Static URLs\n GATEWAY_URL: \"/\",\n GROUP_DEFAULT_ICON_URL: \"/dev/images/group_avatar_icon_64x64_nob.png\",\n GROUP_DEFAULT_ICON_URL_LARGE: \"/dev/images/group_avatar_icon_100x100_nob.png\",\n I10N_BUNDLE_URL: \"/dev/lib/misc/l10n/cultures/globalize.culture.__CODE__.js\",\n I18N_BUNDLE_ROOT: \"/dev/bundle/\",\n INBOX_URL: \"/me#l=messages/inbox\",\n INVITATIONS_URL: \"/me#l=messages/invitations\",\n LOGOUT_URL: \"/logout\",\n MY_DASHBOARD_URL: \"/me#l=dashboard\",\n PROFILE_EDIT_URL: \"/me#l=profile/basic\",\n SEARCH_ACTIVITY_ALL_URL: \"/var/search/activity/all.json\",\n SEARCH_URL: \"/search\",\n TINY_MCE_CONTENT_CSS: \"/dev/css/FSS/fss-base.css,/dev/css/sakai/main.css,/dev/css/sakai/sakai.corev1.css,/dev/css/sakai/sakai.base.css,/dev/css/sakai/sakai.editor.css,/dev/css/sakai/sakai.content_profile.css\",\n USER_DEFAULT_ICON_URL: \"/dev/images/default_User_icon_50x50.png\",\n USER_DEFAULT_ICON_URL_LARGE: \"/dev/images/default_User_icon_100x100.png\",\n INFINITE_LOADING_ICON: \"/dev/images/Infinite_Scrolling_Loader_v01.gif\",\n\n // Services\n BATCH: \"/system/batch\",\n CAPTCHA_SERVICE: \"/system/captcha\",\n CONTACTS_FIND: \"/var/contacts/find.json\",\n CONTACTS_FIND_STATE: \"/var/contacts/findstate.json\",\n CONTACTS_FIND_ALL: \"/var/contacts/find-all.json\",\n CREATE_USER_SERVICE: \"/system/userManager/user.create.html\",\n DISCUSSION_GETPOSTS_THREADED: \"/var/search/discussions/threaded.json?path=__PATH__&marker=__MARKER__\",\n GOOGLE_CHARTS_API: \"http://chart.apis.google.com/chart\",\n GROUP_CREATE_SERVICE: \"/system/userManager/group.create.json\",\n GROUPS_MANAGER: \"/system/me/managedgroups.json\",\n GROUPS_MEMBER: \"/system/me/groups.json\",\n IMAGE_SERVICE: \"/var/image/cropit\",\n LOGIN_SERVICE: \"/system/sling/formlogin\",\n LOGOUT_SERVICE: \"/system/sling/logout?resource=/index\",\n ME_SERVICE: \"/system/me\",\n MESSAGE_BOX_SERVICE: \"/var/message/box.json\",\n MESSAGE_BOXCATEGORY_SERVICE: \"/var/message/boxcategory.json\",\n MESSAGE_BOXCATEGORY_ALL_SERVICE: \"/var/message/boxcategory-all.json\",\n POOLED_CONTENT_MANAGER: \"/var/search/pool/me/manager.json\",\n POOLED_CONTENT_MANAGER_ALL: \"/var/search/pool/me/manager-all.json\",\n POOLED_CONTENT_VIEWER: \"/var/search/pool/me/viewer.json\",\n POOLED_CONTENT_VIEWER_ALL: \"/var/search/pool/me/viewer-all.json\",\n POOLED_CONTENT_SPECIFIC_USER: \"/var/search/pool/manager-viewer.json\",\n POOLED_CONTENT_ACTIVITY_FEED: \"/var/search/pool/activityfeed.json\",\n PRESENCE_SERVICE: \"/var/presence.json\",\n SAKAI2_TOOLS_SERVICE: \"/var/proxy/s23/site.json?siteid=__SITEID__\",\n WORLD_CREATION_SERVICE: \"/system/world/create\",\n WORLD_INFO_URL: \"/var/templates/worlds.2.json\",\n\n // Replace these in widgets with proper widgetsave functions from magic\n SEARCH_ALL_ENTITIES: \"/var/search/general.json\",\n SEARCH_ALL_ENTITIES_ALL: \"/var/search/general-all.json\",\n SEARCH_ALL_FILES: \"/var/search/pool/all.json\",\n SEARCH_ALL_FILES_ALL: \"/var/search/pool/all-all.json\",\n SEARCH_MY_BOOKMARKS: \"/var/search/files/mybookmarks.json\",\n SEARCH_MY_BOOKMARKS_ALL: \"/var/search/files/mybookmarks-all.json\",\n SEARCH_MY_CONTACTS: \"/var/search/files/mycontacts.json\",\n SEARCH_MY_FILES: \"/var/search/files/myfiles.json\",\n SEARCH_MY_FILES_ALL: \"/var/search/files/myfiles-all.json\",\n SEARCH_GROUP_MEMBERS: \"/var/search/groupmembers.json\",\n SEARCH_GROUP_MEMBERS_ALL: \"/var/search/groupmembers-all.json\",\n SEARCH_GROUPS: \"/var/search/groups.infinity.json\",\n SEARCH_GROUPS_ALL: \"/var/search/groups-all.json\",\n SEARCH_USERS_ACCEPTED: \"/var/contacts/findstate.infinity.json\",\n SEARCH_USERS: \"/var/search/users.infinity.json\",\n SEARCH_USERS_ALL: \"/var/search/users-all.json\",\n SEARCH_USERS_GROUPS: \"/var/search/usersgroups.json\",\n SEARCH_USERS_GROUPS_ALL: \"/var/search/usersgroups-all.json\",\n USER_CHANGEPASS_SERVICE: \"/system/userManager/user/__USERID__.changePassword.html\",\n USER_EXISTENCE_SERVICE: \"/system/userManager/user.exists.html?userid=__USERID__\"\n },\n\n PageTitles: {\n \"prefix\": \"TITLE_PREFIX\",\n \"pages\": {\n /** 403.html **/\n /** 404.html **/\n /** 500.html **/\n /** account_preferences.html **/\n \"/dev/account_preferences.html\": \"ACCOUNT_PREFERENCES\",\n \"/preferences\": \"ACCOUNT_PREFERENCES\",\n /** acknowledgements.html **/\n \"/dev/acknowledgements.html\": \"ACKNOWLEDGEMENTS\",\n \"/acknowledgements\": \"ACKNOWLEDGEMENTS\",\n /** allcategories.html **/\n \"/categories\": \"BROWSE_ALL_CATEGORIES\",\n \"/dev/allcategories.html\": \"BROWSE_ALL_CATEGORIES\",\n /** category.html **/\n /** content_profile.html **/\n \"/dev/content_profile.html\": \"CONTENT_PROFILE\",\n \"/content\": \"CONTENT_PROFILE\",\n /** create_new_account.html **/\n \"/dev/create_new_account.html\": \"CREATE_A_NEW_ACCOUNT\",\n \"/register\": \"CREATE_A_NEW_ACCOUNT\",\n /** explore.html **/\n \"/\": \"EXPLORE\",\n \"/dev\": \"EXPLORE\",\n \"/dev/\": \"EXPLORE\",\n \"/index.html\": \"EXPLORE\",\n \"/dev/explore.html\": \"EXPLORE\",\n \"/index\": \"EXPLORE\",\n /** logout.html **/\n \"/dev/logout.html\": \"LOGGING_OUT\",\n \"/logout\": \"LOGGING_OUT\",\n /** search.html **/\n \"/dev/search.html\": \"SEARCH\",\n \"/search\": \"SEARCH\",\n /** createnew.html **/\n \"/create\": \"CREATE\"\n }\n },\n\n ErrorPage: {\n /*\n * These links are displayed in the 403 and 404 error pages.\n */\n Links: {\n whatToDo: [{\n \"title\": \"EXPLORE_THE_INSTITUTION\",\n \"url\": \"/index\"\n }, {\n \"title\": \"BROWSE_INSTITUTION_CATEGORIES\",\n \"url\": \"/categories\"\n }, {\n \"title\": \"VIEW_THE_INSTITUTION_WEBSITE\",\n \"url\": \"http://sakaiproject.org/\"\n }, {\n \"title\": \"VISIT_THE_SUPPORT_FORUM\",\n \"url\": \"http://sakaiproject.org/\"\n }],\n getInTouch: [{\n \"title\": \"SEND_US_YOUR_FEEDBACK\",\n \"url\": \"http://sakaiproject.org/\"\n }, {\n \"title\": \"CONTACT_SUPPORT\",\n \"url\": \"http://sakaiproject.org/\"\n }]\n }\n },\n\n Domain: {\n /*\n * These domain labels can be used anywhere on the site (i.e in the video\n * widget) to convert common domains into shorter, more readable labels\n * for display purposes.\n */\n Labels: {\n \"youtube.com\": \"YouTube\",\n \"www.youtube.com\": \"YouTube\",\n \"youtube.co.uk\": \"YouTube\",\n \"www.youtube.co.uk\": \"YouTube\",\n \"vimeo.com\": \"Vimeo\",\n \"www.vimeo.com\": \"Vimeo\",\n \"vimeo.co.uk\": \"Vimeo\",\n \"www.vimeo.co.uk\": \"Vimeo\",\n \"video.google.com\": \"Google Video\"\n }\n },\n\n SakaiDomain: window.location.protocol + \"//\" + window.location.host,\n\n Permissions: {\n /*\n * A collection of permission keys and range of values to be referenced\n * for making permissions decisions. The values of properties are only\n * for reference, may not match designs and are not to be placed in the\n * UI (message bundles should be used to match up-to-date designs).\n */\n Groups: {\n joinable: {\n \"manager_add\": \"no\", // Managers add people\n \"user_direct\": \"yes\", // People can automatically join\n \"user_request\": \"withauth\" // People request to join\n },\n visible: {\n \"members\": \"members-only\", // Group members only (includes managers)\n \"allusers\": \"logged-in-only\", // All logged in users\n \"public\": \"public\" // Anyone on the Internet\n },\n \"defaultaccess\": \"public\", // public, logged-in-only or members-only (see above for role description)\n \"defaultjoin\": \"yes\", // no, yes, or withauth (see above for descriptions)\n \"addcontentmanagers\": true // true, false. If set to yes, group managers will be added as manager for a file \n // added to a group library in context of that group\n },\n Content: {\n /*\n * public - anyone\n * everyone - logged in users\n * private - private\n */\n \"defaultaccess\": \"public\" // public, everyone or private (see above for role description)\n },\n Documents: {\n /*\n * public - anyone\n * everyone - logged in users\n * private - private\n */\n \"defaultaccess\": \"public\" // public, everyone or private (see above for role description)\n },\n Links: {\n \"defaultaccess\": \"public\" // public, everyone or private (see above for role description)\n },\n Copyright: {\n types: {\n \"creativecommons\": {\n \"title\": \"CREATIVE_COMMONS_LICENSE\"\n },\n \"copyrighted\": {\n \"title\": \"COPYRIGHTED\"\n },\n \"nocopyright\": {\n \"title\": \"NO_COPYRIGHT\"\n },\n \"licensed\": {\n \"title\": \"LICENSED\"\n },\n \"waivecopyright\": {\n \"title\": \"WAIVE_COPYRIGHT\"\n }\n },\n defaults: {\n \"content\": \"creativecommons\",\n \"sakaidocs\": \"creativecommons\",\n \"links\": \"creativecommons\",\n \"collections\": \"creativecommons\"\n }\n }\n },\n\n allowPasswordChange: true,\n\n Profile: {\n /*\n * This is a collection of profile configuration functions and settings\n * The structure of the config object is identical to the storage object\n * When system/me returns profile data for the logged in user the profile_config and profile_data objects could be merged\n * \"label\": the internationalizable message for the entry label in HTML\n * \"required\": {Boolean} Whether the entry is compulsory or not\n * \"display\": {Boolean} Show the entry in the profile or not\n * \"editable\": {Boolean} Whether or not the entry is editable\n * For a date entry field use \"date\" as the type for MM/dd/yyyy and \"dateITA\" as the type for dd/MM/yyyy\n *\n */\n configuration: {\n\n defaultConfig: {\n\n \"basic\": {\n \"label\": \"__MSG__PROFILE_BASIC_LABEL__\",\n \"required\": true,\n \"display\": true,\n \"access\": \"everybody\",\n \"modifyacl\": false,\n \"permission\": \"anonymous\",\n \"order\": 0,\n \"elements\": {\n \"firstName\": {\n \"label\": \"__MSG__PROFILE_BASIC_FIRSTNAME_LABEL__\",\n \"errorMessage\": \"__MSG__PROFILE_BASIC_FIRSTNAME_ERROR__\",\n \"required\": true,\n \"display\": true,\n \"limitDisplayWidth\": 300\n },\n \"lastName\": {\n \"label\": \"__MSG__PROFILE_BASIC_LASTNAME_LABEL__\",\n \"errorMessage\": \"__MSG__PROFILE_BASIC_LASTNAME_ERROR__\",\n \"required\": true,\n \"display\": true,\n \"limitDisplayWidth\": 300\n },\n \"picture\": {\n \"label\": \"__MSG__PROFILE_BASIC_PICTURE_LABEL__\",\n \"required\": false,\n \"display\": false\n },\n \"preferredName\": {\n \"label\": \"__MSG__PROFILE_BASIC_PREFERREDNAME_LABEL__\",\n \"required\": false,\n \"display\": true\n },\n \"email\": {\n \"label\": \"__MSG__PROFILE_BASIC_EMAIL_LABEL__\",\n \"errorMessage\": \"__MSG__PROFILE_BASIC_EMAIL_ERROR__\",\n \"required\": true,\n \"display\": true,\n \"validation\": \"email\"\n },\n \"status\": {\n \"label\": \"__MSG__PROFILE_BASIC_STATUS_LABEL__\",\n \"required\": false,\n \"display\": false\n },\n \"role\": {\n \"label\": \"__MSG__PROFILE_BASIC_ROLE_LABEL__\",\n \"required\": false,\n \"display\": true,\n \"type\": \"select\",\n \"select_elements\": {\n \"academic_related_staff\": \"__MSG__PROFILE_BASIC_ROLE_ACADEMIC_RELATED_STAFF_LABEL__\",\n \"academic_staff\": \"__MSG__PROFILE_BASIC_ROLE_ACADEMIC_STAFF_LABEL__\",\n \"assistent_staff\": \"__MSG__PROFILE_BASIC_ROLE_ASSISTENT_STAFF_LABEL__\",\n \"graduate_student\": \"__MSG__PROFILE_BASIC_ROLE_GRADUATE_STUDENT_LABEL__\",\n \"undergraduate_student\": \"__MSG__PROFILE_BASIC_ROLE_UNDERGRADUATE_STUDENT_LABEL__\",\n \"non_academic_staff\": \"__MSG__PROFILE_BASIC_ROLE_NON_ACADEMIC_STAFF_LABEL__\",\n \"postgraduate_student\": \"__MSG__PROFILE_BASIC_ROLE_POSTGRADUATE_STUDENT_LABEL__\",\n \"research_staff\": \"__MSG__PROFILE_BASIC_ROLE_RESEARCH_STAFF_LABEL__\",\n \"other\": \"__MSG__PROFILE_BASIC_ROLE_OTHER_LABEL__\"\n }\n },\n \"department\": {\n \"label\": \"__MSG__PROFILE_BASIC_DEPARTMENT_LABEL__\",\n \"required\": false,\n \"display\": true\n },\n \"college\": {\n \"label\": \"__MSG__PROFILE_BASIC_COLLEGE_LABEL__\",\n \"required\": false,\n \"display\": true\n },\n \"tags\": {\n \"label\": \"__MSG__TAGS_AND_CATEGORIES__\",\n \"required\": false,\n \"display\": true,\n \"type\": \"tags\",\n \"tagField\": true\n }\n }\n },\n \"aboutme\": {\n \"label\": \"__MSG__PROFILE_ABOUTME_LABEL__\",\n \"required\": true,\n \"display\": true,\n \"access\": \"everybody\",\n \"modifyacl\": true,\n \"permission\": \"anonymous\",\n \"order\": 1,\n \"elements\": {\n \"aboutme\": {\n \"label\": \"__MSG__PROFILE_ABOUTME_LABEL__\",\n \"required\": false,\n \"display\": true,\n \"type\": \"textarea\"\n },\n \"academicinterests\": {\n \"label\": \"__MSG__PROFILE_ABOUTME_ACADEMICINTERESTS_LABEL__\",\n \"required\": false,\n \"display\": true,\n \"type\": \"textarea\"\n },\n \"personalinterests\": {\n \"label\": \"__MSG__PROFILE_ABOUTME_PERSONALINTERESTS_LABEL__\",\n \"required\": false,\n \"display\": true,\n \"type\": \"textarea\"\n },\n \"hobbies\": {\n \"label\": \"__MSG__PROFILE_ABOUTME_HOBBIES_LABEL__\",\n \"required\": false,\n \"display\": true\n }\n }\n },\n \"publications\": {\n \"label\": \"__MSG__PROFILE_PUBLICATIONS_LABEL__\",\n \"required\": false,\n \"display\": true,\n \"access\": \"everybody\",\n \"modifyacl\": true,\n \"permission\": \"anonymous\",\n \"multiple\": true,\n \"multipleLabel\": \"__MSG__PROFILE_PUBLICATION_LABEL__\",\n \"order\": 2,\n //\"template\": \"profile_section_publications_template\",\n \"elements\": {\n \"maintitle\": {\n \"label\": \"__MSG__PROFILE_PUBLICATIONS_MAIN_TITLE__\",\n \"required\": true,\n \"display\": true,\n \"example\": \"__MSG__PROFILE_PUBLICATIONS_MAIN_TITLE_EXAMPLE__\"\n },\n \"mainauthor\": {\n \"label\": \"__MSG__PROFILE_PUBLICATIONS_MAIN_AUTHOR__\",\n \"required\": true,\n \"display\": true\n },\n \"coauthor\": {\n \"label\": \"__MSG__PROFILE_PUBLICATIONS_CO_AUTHOR__\",\n \"required\": false,\n \"display\": true,\n \"example\": \"__MSG__PROFILE_PUBLICATIONS_CO_AUTHOR_EXAMPLE__\"\n },\n \"publisher\": {\n \"label\": \"__MSG__PROFILE_PUBLICATIONS_PUBLISHER__\",\n \"required\": true,\n \"display\": true\n },\n \"placeofpublication\": {\n \"label\": \"__MSG__PROFILE_PUBLICATIONS_PLACE_OF_PUBLICATION__\",\n \"required\": true,\n \"display\": true\n },\n \"volumetitle\": {\n \"label\": \"__MSG__PROFILE_PUBLICATIONS_VOLUME_TITLE__\",\n \"required\": false,\n \"display\": true\n },\n \"volumeinformation\": {\n \"label\": \"__MSG__PROFILE_PUBLICATIONS_VOLUME_INFORMATION__\",\n \"required\": false,\n \"display\": true,\n \"example\": \"__MSG__PROFILE_PUBLICATIONS_VOLUME_INFORMATION_EXAMPLE__\"\n },\n \"year\": {\n \"label\": \"__MSG__PROFILE_PUBLICATIONS_YEAR__\",\n \"required\": true,\n \"display\": true\n },\n \"number\": {\n \"label\": \"__MSG__PROFILE_PUBLICATIONS_NUMBER__\",\n \"required\": false,\n \"display\": true\n },\n \"series title\": {\n \"label\": \"__MSG__PROFILE_PUBLICATIONS_SERIES_TITLE__\",\n \"required\": false,\n \"display\": true\n },\n \"url\": {\n \"label\": \"__MSG__PROFILE_PUBLICATIONS_URL__\",\n \"required\": false,\n \"display\": true,\n \"validation\": \"appendhttp url\"\n }\n }\n }\n }\n },\n /*\n * set what name to display where only the first name is used\n */\n userFirstNameDisplay: \"firstName\",\n\n /*\n * set how the user's name is displayed across the entire system\n * - values can be compound, like \"firstName lastName\" or singular like \"displayName\"\n */\n userNameDisplay: \"firstName lastName\",\n\n /*\n * the default, if the user doesn't have the userNameDisplay property set in their\n * profile, use this one.\n * Note: the value for userNameDisplay and this value can be the same.\n * If neither exists, nothing will show\n */\n userNameDefaultDisplay: \"firstName lastName\",\n\n /*\n * Set the default user settings in account preferences for automatic tagging\n * and auto-tagged notifications\n */\n defaultAutoTagging: true,\n defaultSendTagMsg: true\n },\n\n Groups: {\n /*\n * Email message that will be sent to group managers when a user requests\n * to join their group.\n * ${user} will be replaced by the name of the requesting user and ${group}\n * will be replaced with the group name.\n */\n JoinRequest: {\n title: \"${user} has requested to join your group: ${group}\",\n body: \"${user} has requested to join your group: ${group}. Use the links below to respond to this request.\"\n }\n },\n\n Relationships: {\n /*\n * Relationships used by the add contacts widget to define what relationship the contacts can have\n */\n \"contacts\": [{\n \"name\": \"__MSG__CLASSMATE__\",\n \"definition\": \"__MSG__IS_MY_CLASSMATE__\",\n \"selected\": true\n }, {\n \"name\": \"__MSG__SUPERVISOR__\",\n \"inverse\": \"__MSG__SUPERVISED__\",\n \"definition\": \"__MSG__IS_MY_SUPERVISOR__\",\n \"selected\": false\n }, {\n \"name\": \"__MSG__SUPERVISED__\",\n \"inverse\": \"__MSG__SUPERVISOR__\",\n \"definition\": \"__MSG__IS_SUPERVISED_BY_ME__\",\n \"selected\": false\n }, {\n \"name\": \"__MSG__LECTURER__\",\n \"inverse\": \"__MSG__STUDENT__\",\n \"definition\": \"__MSG__IS_MY_LECTURER__\",\n \"selected\": false\n }, {\n \"name\": \"__MSG__STUDENT__\",\n \"inverse\": \"__MSG__LECTURER__\",\n \"definition\": \"__MSG__IS_MY_STUDENT__\",\n \"selected\": false\n }, {\n \"name\": \"__MSG__COLLEAGUE__\",\n \"definition\": \"__MSG__IS_MY_COLLEAGUE__\",\n \"selected\": false\n }, {\n \"name\": \"__MSG__COLLEGE_MATE__\",\n \"definition\": \"__MSG__IS_MY_COLLEGE_MATE__\",\n \"selected\": false\n }, {\n \"name\": \"__MSG__SHARES_INTERESTS__\",\n \"definition\": \"__MSG__SHARES_INTEREST_WITH_ME__\",\n \"selected\": false\n }]\n },\n\n SystemTour: {\n \"enableReminders\": true,\n \"reminderIntervalHours\": \"168\"\n },\n\n enableBranding: true,\n\n // Set this to true if you have an authentication system such as CAS\n // that needs to redirect the user's browser on logout\n followLogoutRedirects: false,\n\n // Set this to the hostname of your CLE instance if you're using CAS\n // proxy tickets\n hybridCasHost: false,\n\n Messages: {\n Types: {\n inbox: \"inbox\",\n sent: \"sent\",\n trash: \"trash\"\n },\n Categories: {\n message: \"Message\",\n announcement: \"Announcement\",\n chat: \"Chat\",\n invitation: \"Invitation\"\n },\n Subject: \"subject\",\n Type: \"type\",\n Body: \"body\",\n To: \"to\",\n read: \"read\"\n },\n Extensions:{\n \"docx\":\"application/doc\",\n \"doc\":\"application/doc\",\n \"odt\":\"application/doc\",\n \"ods\":\"application/vnd.ms-excel\",\n \"xls\":\"application/vnd.ms-excel\",\n \"xlsx\":\"application/vnd.ms-excel\",\n \"odp\":\"application/vnd.ms-powerpoint\",\n \"ppt\":\"application/vnd.ms-powerpoint\",\n \"pptx\":\"application/vnd.ms-powerpoint\",\n \"odg\":\"image/jpeg\",\n \"png\":\"image/png\",\n \"jp2\":\"images/jp2\",\n \"jpg\":\"image/jpeg\",\n \"jpeg\":\"image/jpeg\",\n \"bmp\":\"image/bmp\",\n \"gif\":\"image/gif\",\n \"tif\":\"image/tiff\",\n \"tiff\":\"images/tiff\",\n \"pdf\":\"application/x-pdf\",\n \"swf\":\"application/x-shockwave-flash\",\n \"flv\":\"video/x-msvideo\",\n \"mpg\":\"video/x-msvideo\",\n \"mpeg\":\"video/x-msvideo\",\n \"mp4\":\"video/x-msvideo\",\n \"avi\":\"video/x-msvideo\",\n \"mov\":\"video/x-msvideo\",\n \"txt\":\"text/rtf\",\n \"rtf\":\"text/rtf\",\n \"htm\":\"text/html\",\n \"html\":\"text/html\",\n \"wav\": \"audio/x-wav\",\n \"mp3\": \"audio/mpeg\",\n \"tar\": \"application/zip\",\n \"zip\": \"application/zip\",\n \"other\":\"other\"\n },\n MimeTypes: {\n \"application/doc\": {\n cssClass: \"icon-doc-sprite\",\n URL: \"/dev/images/mimetypes/doc.png\",\n description: \"WORD_DOCUMENT\"\n },\n \"application/msword\": {\n cssClass: \"icon-doc-sprite\",\n URL: \"/dev/images/mimetypes/doc.png\",\n description: \"WORD_DOCUMENT\"\n },\n \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\": {\n cssClass: \"icon-doc-sprite\",\n URL: \"/dev/images/mimetypes/doc.png\",\n description: \"WORD_DOCUMENT\"\n },\n \"application/pdf\": {\n cssClass: \"icon-pdf-sprite\",\n URL: \"/dev/images/mimetypes/pdf.png\",\n description: \"PDF_DOCUMENT\"\n },\n \"application/x-download\": {\n cssClass: \"icon-pdf-sprite\",\n URL: \"/dev/images/mimetypes/pdf.png\",\n description: \"PDF_DOCUMENT\"\n },\n \"application/x-pdf\": {\n cssClass: \"icon-pdf-sprite\",\n URL: \"/dev/images/mimetypes/pdf.png\",\n description: \"PDF_DOCUMENT\"\n },\n \"application/vnd.ms-powerpoint\": {\n cssClass: \"icon-pps-sprite\",\n URL: \"/dev/images/mimetypes/pps.png\",\n description: \"POWERPOINT_DOCUMENT\"\n },\n \"application/vnd.openxmlformats-officedocument.presentationml.presentation\": {\n cssClass: \"icon-pps-sprite\",\n URL: \"/dev/images/mimetypes/pps.png\",\n description: \"POWERPOINT_DOCUMENT\"\n },\n \"application/vnd.oasis.opendocument.text\": {\n cssClass: \"icon-doc-sprite\",\n URL: \"/dev/images/mimetypes/doc.png\",\n description: \"OPEN_OFFICE_DOCUMENT\"\n },\n \"application/vnd.oasis.opendocument.presentation\": {\n cssClass: \"icon-pps-sprite\",\n URL: \"/dev/images/mimetypes/pps.png\",\n description: \"OPEN_OFFICE_PRESENTATION\"\n },\n \"application/vnd.oasis.opendocument.spreadsheet\": {\n cssClass: \"icon-pps-sprite\",\n URL: \"/dev/images/mimetypes/spreadsheet.png\",\n description: \"OPEN_OFFICE_SPREADSHEET\"\n },\n\n \"application/x-shockwave-flash\": {\n cssClass: \"icon-swf-sprite\",\n URL: \"/dev/images/mimetypes/swf.png\",\n description: \"FLASH_PLAYER_FILE\"\n },\n \"application/zip\": {\n cssClass: \"icon-zip-sprite\",\n URL: \"/dev/images/mimetypes/zip.png\",\n description: \"ARCHIVE_FILE\"\n },\n \"application/x-zip-compressed\": {\n cssClass: \"icon-zip-sprite\",\n URL: \"/dev/images/mimetypes/zip.png\",\n description: \"ARCHIVE_FILE\"\n },\n \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\": {\n cssClass: \"icon-spreadsheet-sprite\",\n URL: \"/dev/images/mimetypes/spreadsheet.png\",\n description: \"SPREADSHEET_DOCUMENT\"\n },\n \"application/vnd.ms-excel\": {\n cssClass: \"icon-spreadsheet-sprite\",\n URL: \"/dev/images/mimetypes/spreadsheet.png\",\n description: \"SPREADSHEET_DOCUMENT\"\n },\n \"audio/x-wav\": {\n cssClass: \"icon-audio-sprite\",\n URL: \"/dev/images/mimetypes/sound.png\",\n description: \"SOUND_FILE\"\n },\n \"audio/mpeg\": {\n cssClass: \"icon-audio-sprite\",\n URL: \"/dev/images/mimetypes/sound.png\",\n description: \"SOUND_FILE\"\n },\n \"text/plain\": {\n cssClass: \"icon-txt-sprite\",\n URL: \"/dev/images/mimetypes/txt.png\",\n description: \"TEXT_DOCUMENT\"\n },\n \"text/rtf\": {\n cssClass: \"icon-txt-sprite\",\n URL: \"/dev/images/mimetypes/txt.png\",\n description: \"TEXT_DOCUMENT\"\n },\n \"image/png\": {\n cssClass: \"icon-image-sprite\",\n URL: \"/dev/images/mimetypes/images.png\",\n description: \"PNG_IMAGE\"\n },\n \"image/bmp\": {\n cssClass: \"icon-image-sprite\",\n URL: \"/dev/images/mimetypes/images.png\",\n description: \"BMP_IMAGE\"\n },\n \"image/gif\": {\n cssClass: \"icon-image-sprite\",\n URL: \"/dev/images/mimetypes/images.png\",\n description: \"GIF_IMAGE\"\n },\n \"image/jp2\": {\n cssClass: \"icon-image-sprite\",\n URL: \"/dev/images/mimetypes/images.png\",\n description: \"JPG2000_IMAGE\"\n },\n \"image/jpeg\": {\n cssClass: \"icon-image-sprite\",\n URL: \"/dev/images/mimetypes/images.png\",\n description: \"JPG_IMAGE\"\n },\n \"image/pjpeg\": {\n cssClass: \"icon-image-sprite\",\n URL: \"/dev/images/mimetypes/images.png\",\n description: \"JPG_IMAGE\"\n },\n \"image/tiff\": {\n cssClass: \"icon-image-sprite\",\n URL: \"/dev/images/mimetypes/images.png\",\n description: \"TIFF_IMAGE\"\n },\n \"text/html\": {\n cssClass: \"icon-html-sprite\",\n URL: \"/dev/images/mimetypes/html.png\",\n description: \"HTML_DOCUMENT\"\n },\n \"video/x-msvideo\": {\n cssClass: \"icon-video-sprite\",\n URL: \"/dev/images/mimetypes/video.png\",\n description: \"VIDEO_FILE\"\n },\n \"video/mp4\": {\n cssClass: \"icon-video-sprite\",\n URL: \"/dev/images/mimetypes/video.png\",\n description: \"VIDEO_FILE\"\n },\n \"video/quicktime\": {\n cssClass: \"icon-video-sprite\",\n URL: \"/dev/images/mimetypes/video.png\",\n description: \"VIDEO_FILE\"\n },\n \"video/x-ms-wmv\": {\n cssClass: \"icon-video-sprite\",\n URL: \"/dev/images/mimetypes/video.png\",\n description: \"VIDEO_FILE\"\n },\n \"folder\": {\n cssClass: \"icon-kmultiple-sprite\",\n URL: \"/dev/images/mimetypes/kmultiple.png\",\n description: \"FOLDER\"\n },\n \"x-sakai/link\": {\n cssClass: \"icon-url-sprite\",\n URL: \"/dev/images/mimetypes/html.png\",\n description: \"URL_LINK\"\n },\n \"x-sakai/document\": {\n cssClass: \"icon-sakaidoc-sprite\",\n URL: \"/dev/images/mimetypes/sakaidoc.png\",\n description: \"DOCUMENT\"\n },\n \"x-sakai/collection\": {\n cssClass: \"icon-collection-sprite\",\n URL: \"/dev/images/mimetypes/collection.png\",\n description: \"COLLECTION\"\n },\n \"kaltura/video\": {\n cssClass: \"icon-video-sprite\",\n URL: \"/dev/images/mimetypes/video.png\",\n description: \"VIDEO_FILE\"\n },\n \"kaltura/audio\": {\n cssClass: \"icon-sound-sprite\",\n URL: \"/dev/images/mimetypes/sound.png\",\n description: \"SOUND_FILE\"\n },\n \"other\": {\n cssClass: \"icon-unknown-sprite\",\n URL: \"/dev/images/mimetypes/unknown.png\",\n description: \"OTHER_DOCUMENT\"\n }\n },\n\n Authentication: {\n \"allowInternalAccountCreation\": true,\n \"internal\": true,\n \"external\": [{\n label: \"External Login System 1\",\n url: \"http://external.login1.com/\"\n }, {\n label: \"External Login System 2\",\n url: \"http://external.login2.com/\"\n }],\n \"hideLoginOn\": [\"/dev\", \"/dev/index.html\", \"/dev/create_new_account.html\"]\n },\n\n notification: {\n type: {\n ERROR: {\n image: \"/dev/images/notifications_exclamation_icon.png\",\n time: 10000\n },\n INFORMATION: {\n image: \"/dev/images/notifications_info_icon.png\",\n time: 5000\n }\n }\n },\n\n Navigation: [{\n \"url\": \"/me#l=dashboard\",\n \"id\": \"navigation_you_link\",\n \"anonymous\": false,\n \"label\": \"YOU\",\n \"append\": \"messages\",\n \"subnav\": [{\n \"url\": \"/me#l=dashboard\",\n \"id\": \"subnavigation_home_link\",\n \"label\": \"MY_HOME\"\n }, {\n \"url\": \"/me#l=messages/inbox\",\n \"id\": \"subnavigation_messages_link\",\n \"label\": \"MY_MESSAGES\"\n }, {\n \"id\": \"subnavigation_hr\"\n }, {\n \"url\": \"/me#l=profile/basic\",\n \"id\": \"subnavigation_profile_link\",\n \"label\": \"MY_PROFILE\"\n }, {\n \"url\": \"/me#l=library\",\n \"id\": \"subnavigation_content_link\",\n \"label\": \"MY_LIBRARY\"\n }, {\n \"url\": \"/me#l=memberships\",\n \"id\": \"subnavigation_memberships_link\",\n \"label\": \"MY_MEMBERSHIPS\"\n }, {\n \"url\": \"/me#l=contacts\",\n \"id\": \"subnavigation_contacts_link\",\n \"label\": \"MY_CONTACTS_CAP\"\n }]\n }, {\n \"url\": \"#\",\n \"id\": \"navigation_create_and_add_link\",\n \"anonymous\": false,\n \"label\": \"CREATE_AND_COLLECT\",\n \"append\": \"collections\",\n \"subnav\": [{\n \"id\": \"subnavigation_add_content_link\",\n \"label\": \"ADD_CONTENT\",\n \"url\": \"#\"\n }, {\n \"id\": \"subnavigation_add_collection_link\",\n \"label\": \"ADD_COLLECTION\",\n \"url\": \"#\"\n }, {\n \"id\": \"subnavigation_hr\"\n }]\n }, {\n \"url\": \"/index\",\n \"id\": \"navigation_explore_link\",\n \"anonymous\": false,\n \"label\": \"EXPLORE\",\n \"subnav\": [{\n \"id\": \"subnavigation_explore_categories_link\",\n \"label\": \"BROWSE_ALL_CATEGORIES\",\n \"url\": \"/categories\"\n },{\n \"id\": \"subnavigation_hr\"\n },{\n \"id\": \"subnavigation_explore_content_link\",\n \"label\": \"CONTENT\",\n \"url\": \"/search#l=content\"\n }, {\n \"id\": \"subnavigation_explore_people_link\",\n \"label\": \"PEOPLE\",\n \"url\": \"/search#l=people\"\n }]\n }, {\n \"url\": \"/index\",\n \"id\": \"navigation_anon_explore_link\",\n \"anonymous\": true,\n \"label\": \"EXPLORE\",\n \"subnav\": [{\n \"id\": \"subnavigation_explore_categories_link\",\n \"label\": \"BROWSE_ALL_CATEGORIES\",\n \"url\": \"/categories\"\n },{\n \"id\": \"subnavigation_hr\"\n },{\n \"id\": \"subnavigation_explore_content_link\",\n \"label\": \"CONTENT\",\n \"url\": \"/search#l=content\"\n }, {\n \"id\": \"subnavigation_explore_people_link\",\n \"label\": \"PEOPLE\",\n \"url\": \"/search#l=people\"\n }]\n }, {\n \"url\": \"/register\",\n \"id\": \"navigation_anon_signup_link\",\n \"anonymous\": true,\n \"label\": \"SIGN_UP\"\n }],\n\n Footer: {\n leftLinks: [{\n \"title\": \"__MSG__COPYRIGHT__\",\n \"href\": \"http://sakaiproject.org/foundation-licenses\",\n \"newWindow\": true\n }, {\n \"title\": \"__MSG__HELP__\",\n \"href\": \"http://sakaiproject.org/node/2307\",\n \"newWindow\": true\n }, {\n \"title\": \"__MSG__ACKNOWLEDGEMENTS__\",\n \"href\": \"/acknowledgements\"\n }, {\n \"title\": \"__MSG__SUGGEST_AN_IMPROVEMENT__\",\n \"href\": \"http://sakaioae.idea.informer.com/\",\n \"newWindow\": true\n }],\n rightLinks: [{\n \"title\": \"__MSG__BROWSE__\",\n \"href\": \"/categories\"\n }, {\n \"title\": \"__MSG__EXPLORE__\",\n \"href\": \"/\"\n }]\n },\n\n /*\n * Are anonymous users allowed to browse/search\n */\n anonAllowed: true,\n /*\n * List of pages that require a logged in user\n */\n requireUser: [\"/me\", \"/dev/me.html\", \"/dev/search_sakai2.html\", \"/create\", \"/dev/createnew.html\"],\n\n /*\n * List of pages that require an anonymous user\n */\n requireAnonymous: [\"/register\", \"/dev/create_new_account.html\"],\n /*\n * List of pages that will be added to requireUser if\n * anonAllowed is false\n */\n requireUserAnonNotAllowed: [\"/me\", \"/dev/me.html\", \"/dev/search_sakai2.html\"],\n /*\n * List of pages that will be added to requireAnonymous if\n * anonAllowed is false\n */\n requireAnonymousAnonNotAllowed: [],\n /*\n * List op pages that require additional processing to determine\n * whether the page can be shown to the current user. These pages\n * are then required to call the sakai.api.Security.showPage\n * themselves\n */\n requireProcessing: [\"/dev/user.html\", \"/me\" ,\"/dev/me.html\", \"/dev/content_profile.html\", \"/dev/content_profile.html\", \"/dev/group_edit.html\", \"/dev/show.html\", \"/content\"],\n\n useLiveSakai2Feeds: false,\n /*\n * List of custom CLE Tool names. This can be used to override the translated\n * tool name in the Sakai 2 Tools Widget drop down, or name a custom CLE tool\n * that has been added to your CLE installation. You can see the list of\n * enabled CLE tools at /var/basiclti/cletools.json, and configure them in\n * Nakamura under the org.sakaiproject.nakamura.basiclti.CLEVirtualToolDataProvider\n * configuration.\n */\n sakai2ToolNames: {\n /* \"sakai.mytoolId\" : \"My Custom Tool Title\" */\n },\n\n displayDebugInfo: true,\n\n /**\n * Section dividers can be added to the directory structure by adding in the following\n * element at the appropriate place:\n * divider1: {\n * \"divider\": true,\n * \"title\": \"Divider title\" [optional],\n * \"cssClass\": \"CSS class to add to items inside of elements beneath the divider [optional]\n * }\n */\n Directory: {\n medicineanddentistry: {\n title: \"__MSG__MEDICINE_AND_DENTISTRY__\",\n children: {\n preclinicalmedicine: {\n title: \"__MSG__PRECLINICAL_MEDICINE__\"\n },\n preclinicaldentistry: {\n title: \"__MSG__PRECLINICAL_DENTISTRY__\"\n },\n clinicalmedicine: {\n title: \"__MSG__CLININCAL_MEDICINE__\"\n },\n clinicaldentistry: {\n title: \"__MSG__CLININCAL_DENTISTRY__\"\n },\n othersinmedicineanddentistry: {\n title: \"__MSG__MEDICINE_AND_DENTISTRY_OTHERS__\"\n }\n }\n },\n biologicalsciences: {\n title: \"__MSG__BIOLOGICAL_SCIENCES__\",\n children: {\n biology: {\n title: \"__MSG__BIOLOGY__\"\n },\n botany: {\n title: \"__MSG__BOTANY__\"\n },\n zoology: {\n title: \"__MSG__ZOOLOGY__\"\n },\n genetics: {\n title: \"__MSG__GENETICS__\"\n },\n microbiology: {\n title: \"__MSG__MICROBIOLOGY__\"\n },\n sportsscience: {\n title: \"__MSG__SPORTS_SCIENCE__\"\n },\n molecularbiologybiophysicsandbiochemistry: {\n title: \"__MSG__MOLECULAR_BIOLOGY__\"\n },\n psychology: {\n title: \"__MSG__PSYCHOLOGY__\"\n },\n othersinbiologicalsciences: {\n title: \"__MSG__BIOLOGICAL_SCIENCES_OTHER__\"\n }\n }\n },\n veterinarysciencesagriculture: {\n title: \"__MSG__VETERINARY_SCIENCES__\",\n children: {\n preclinicalveterinarymedicine: {\n title: \"__MSG__PRE_CLINICAL_VETERINARY__\"\n },\n clinicalveterinarymedicineanddentistry: {\n title: \"__MSG__CLINICAL_VETERINARY__\"\n },\n animalscience: {\n title: \"__MSG__ANIMAL_SCIENCE__\"\n },\n agriculture: {\n title: \"__MSG__AGRICULTURE__\"\n },\n forestry: {\n title: \"__MSG__FORESTRY__\"\n },\n foodandbeveragestudies: {\n title: \"__MSG__FOOD_BEVERAGE__\"\n },\n agriculturalsciences: {\n title: \"__MSG__AGRICULTURAL_SCIENCE__\"\n },\n othersinveterinarysciencesandagriculture: {\n title: \"__MSG__VETERINARY_SCIENCES_OTHER__\"\n }\n }\n },\n physicalsciences: {\n title: \"__MSG__PHYSICAL_SCIENCE__\",\n children: {\n chemistry: {\n title: \"__MSG__CHEMISTRY__\"\n },\n materialsscience: {\n title: \"__MSG__MATERIALS_SCIENCE__\"\n },\n physics: {\n title: \"__MSG__PHYSICS__\"\n },\n forensicandarchaeologicalscience: {\n title: \"__MSG__FORENSIC_ARCHEALOGICAL__\"\n },\n astronomy: {\n title: \"__MSG__ASTRONOMY__\"\n },\n geology: {\n title: \"__MSG__GEOLOGY__\"\n },\n oceansciences: {\n title: \"__MSG__OCEAN_SCIENCE__\"\n },\n othersinphysicalsciences: {\n title: \"__MSG__PHYSICAL_SCIENCE_OTHER__\"\n }\n }\n },\n mathematicalandcomputersciences: {\n title: \"__MSG__MATHEMATICAL_COMPUTER_SCIENCES__\",\n children: {\n mathematics: {\n title: \"__MSG__MATHEMATICS__\"\n },\n operationalresearch: {\n title: \"__MSG__OPERATIONAL_RESEARCH__\"\n },\n statistics: {\n title: \"__MSG__STATISTICS__\"\n },\n computerscience: {\n title: \"__MSG__COMPUTER_SCIENCE__\"\n },\n informationsystems: {\n title: \"__MSG__INFORMATION_SYSTEMS__\"\n },\n softwareengineering: {\n title: \"__MSG__SOFTWARE_ENGINEERING__\"\n },\n artificialintelligence: {\n title: \"__MSG__ARTIFICIAL_INTELLIGENCE__\"\n },\n othersinmathematicalandcomputingsciences: {\n title: \"__MSG__MATHEMATICAL_COMPUTER_SCIENCES_OTHER__\"\n }\n }\n },\n engineering: {\n title: \"__MSG__ENGINEERING__\",\n children: {\n generalengineering: {\n title: \"__MSG__GENERAL_ENGINEERING__\"\n },\n civilengineering: {\n title: \"__MSG__CIVIL_ENGINEERING__\"\n },\n mechanicalengineering: {\n title: \"__MSG__MECHANICAL_ENGINEERING__\"\n },\n aerospaceengineering: {\n title: \"__MSG__AEROSPACE_ENGINEERING__\"\n },\n navalarchitecture: {\n title: \"__MSG__NAVAL_ARCHITECTURE__\"\n },\n electronicandelectricalengineering: {\n title: \"__MSG__ELECTRONIC_ELECTRICAL_ENGINEERING__\"\n },\n productionandmanufacturingengineering: {\n title: \"__MSG__PRODUCTION_MANUFACTURING_ENGINEERING__\"\n },\n chemicalprocessandenergyengineering: {\n title: \"__MSG__CHEMICAL_PROCESS_ENERGY_ENGINEERING__\"\n },\n othersinengineering: {\n title: \"__MSG__ENGINEERING_OTHER__\"\n }\n }\n },\n technologies: {\n title: \"__MSG__TECHNOLOGIES__\",\n children: {\n mineralstechnology: {\n title: \"__MSG__MINERALS_TECHNOLOGY__\"\n },\n metallurgy: {\n title: \"__MSG__METALLURGY__\"\n },\n ceramicsandglasses: {\n title: \"__MSG__CERAMICS_GLASSES__\"\n },\n polymersandtextiles: {\n title: \"__MSG__POLYMERS_TEXTILES__\"\n },\n materialstechnologynototherwisespecified: {\n title: \"__MSG__MATERIALS_TECHNOLOGY_OTHER__\"\n },\n maritimetechnology: {\n title: \"__MSG__MARITIME_TECHNOLOGY__\"\n },\n industrialbiotechnology: {\n title: \"__MSG__INDUSTRIAL_BIOTECHNOLOGY__\"\n },\n othersintechnology: {\n title: \"__MSG__TECHNOLOGIES_OTHER__\"\n }\n }\n },\n architecturebuildingandplanning: {\n title: \"__MSG__ARCHITECTURE_BUILDING_PLANNING__\",\n children: {\n architecture: {\n title: \"__MSG__ARCHITECTURE__\"\n },\n building: {\n title: \"__MSG__BUILDING__\"\n },\n landscapedesign: {\n title: \"__MSG__LANDSCAPE_DESIGN__\"\n },\n planning: {\n title: \"__MSG__PLANNING__\"\n },\n othersinarchitecturebuildingandplanning: {\n title: \"__MSG__ARCHITECTURE_BUILDING_PLANNING_OTHER__\"\n }\n }\n },\n socialstudies: {\n title: \"__MSG__SOCIAL_STUDIES__\",\n children: {\n economics: {\n title: \"__MSG__ECONOMICS__\"\n },\n politics: {\n title: \"__MSG__POLITICS__\"\n },\n sociology: {\n title: \"__MSG__SOCIOLOGY__\"\n },\n socialpolicy: {\n title: \"__MSG__SOCIAL_POLICY__\"\n },\n socialwork: {\n title: \"__MSG__SOCIAL_WORK__\"\n },\n anthropology: {\n title: \"__MSG__ANTHROPOLOGY__\"\n },\n humanandsocialgeography: {\n title: \"__MSG__HUMAN_SOCIAL_GEOGRAPHY__\"\n },\n othersinsocialstudies: {\n title: \"__MSG__SOCIAL_STUDIES_OTHER__\"\n }\n }\n },\n law: {\n title: \"__MSG__LAW__\",\n children: {\n publiclaw: {\n title: \"__MSG__LAW_PUBLIC__\"\n },\n privatelaw: {\n title: \"__MSG__LAW_PRIVATE__\"\n },\n jurisprudence: {\n title: \"__MSG__JURISPRUDENCE__\"\n },\n legalpractice: {\n title: \"__MSG__LEGAL_PRACTICE__\"\n },\n medicallaw: {\n title: \"__MSG__LAW_MEDICAL__\"\n },\n othersinlaw: {\n title: \"__MSG__LAW_OTHER__\"\n }\n }\n },\n businessandadministrativestudies: {\n title: \"__MSG__BUSINESS_ADMINISTRATIVE_STUDIES__\",\n children: {\n businessstudies: {\n title: \"__MSG__BUSINESS_STUDIES__\"\n },\n managementstudies: {\n title: \"__MSG__MANAGEMENTS_STUDIES__\"\n },\n finance: {\n title: \"__MSG__FINANCE__\"\n },\n accounting: {\n title: \"__MSG__ACCOUNTING__\"\n },\n marketing: {\n title: \"__MSG__MARKETING__\"\n },\n humanresourcemanagement: {\n title: \"__MSG__HUMAN_RESOURCE_MANAGEMENT__\"\n },\n officeskills: {\n title: \"__MSG__OFFICE_SKILLS__\"\n },\n tourismtransportandtravel: {\n title: \"__MSG__TOURISM__\"\n },\n othersinbusandadminstudies: {\n title: \"__MSG__BUSINESS_ADMINISTRATIVE_STUDIES_OTHER__\"\n }\n }\n },\n masscommunicationsanddocumentation: {\n title: \"__MSG__MASS_COMMUNICATIONS_DOCUMENTATION__\",\n children: {\n informationservices: {\n title: \"__MSG__INFORMATION_SERVICES__\"\n },\n publicitystudies: {\n title: \"__MSG__PUBLICITY_STUDIES__\"\n },\n mediastudies: {\n title: \"__MSG__MEDIA_STUDIES__\"\n },\n publishing: {\n title: \"__MSG__PUBLISHING__\"\n },\n journalism: {\n title: \"__MSG__JOURNALISM__\"\n },\n othersinmasscommanddoc: {\n title: \"__MSG__MASS_COMMUNICATIONS_DOCUMENTATION_OTHER__\"\n }\n }\n },\n linguisticsclassicsandrelatedsubjects: {\n title: \"__MSG__LINGUISTICS_CLASSICS__\",\n children: {\n linguistics: {\n title: \"__MSG__LINGUISTICS__\"\n },\n comparativeliterarystudies: {\n title: \"__MSG__LINGUISTICS_LITERARY__\"\n },\n englishstudies: {\n title: \"__MSG__LINGUISTICS_ENGLISH__\"\n },\n ancientlanguagestudies: {\n title: \"__MSG__LINGUISTICS_ANCIENT__\"\n },\n celticstudies: {\n title: \"__MSG__LINGUISTICS_CELTIC__\"\n },\n latinstudies: {\n title: \"__MSG__LINGUISTICS_LATIN__\"\n },\n classicalgreekstudies: {\n title: \"__MSG__LINGUISTICS_CLASSICAL_GREEK__\"\n },\n classicalstudies: {\n title: \"__MSG__LINGUISTICS_CLASSICAL__\"\n },\n othersinlinguisticsclassicsandrelsubject: {\n title: \"__MSG__LINGUISTICS_CLASSICS_OTHER__\"\n }\n }\n },\n europeanlanguagesliteratureandrelatedsubjects: {\n title: \"__MSG__EUROPEAN_LANGUAGES__\",\n children: {\n frenchstudies: {\n title: \"__MSG__EUROPEAN_LANGUAGES_FRENCH__\"\n },\n germanstudies: {\n title: \"__MSG__EUROPEAN_LANGUAGES_GERMAN__\"\n },\n italianstudies: {\n title: \"__MSG__EUROPEAN_LANGUAGES_ITALIAN__\"\n },\n spanishstudies: {\n title: \"__MSG__EUROPEAN_LANGUAGES_SPANISH__\"\n },\n portuguesestudies: {\n title: \"__MSG__EUROPEAN_LANGUAGES_PORTUGUESE__\"\n },\n scandinavianstudies: {\n title: \"__MSG__EUROPEAN_LANGUAGES_SCANDINAVIAN__\"\n },\n russianandeasteuropeanstudies: {\n title: \"__MSG__EUROPEAN_LANGUAGES_RUSSIAN__\"\n },\n othersineurolangliteratureandrelsubjects: {\n title: \"__MSG__EUROPEAN_LANGUAGES_OTHER__\"\n }\n }\n },\n easiaticlanguagesliterature: {\n title: \"__MSG__EXOTIC_LANGUAGES__\",\n children: {\n chinesestudies: {\n title: \"__MSG__EXOTIC_LANGUAGES_CHINESE__\"\n },\n japanesestudies: {\n title: \"__MSG__EXOTIC_LANGUAGES_JAPANESE__\"\n },\n southasianstudies: {\n title: \"__MSG__EXOTIC_LANGUAGES_SOUTH_ASIAN__\"\n },\n otherasianstudies: {\n title: \"__MSG__EXOTIC_LANGUAGES_ASIAN_OTHER__\"\n },\n africanstudies: {\n title: \"__MSG__EXOTIC_LANGUAGES_AFRICAN__\"\n },\n modernmiddleeasternstudies: {\n title: \"__MSG__EXOTIC_LANGUAGES_MIDDLE_EAST__\"\n },\n americanstudies: {\n title: \"__MSG__EXOTIC_LANGUAGES_AMERICAN__\"\n },\n australasianstudies: {\n title: \"__MSG__EXOTIC_LANGUAGES_AUSTRALIAN__\"\n },\n othersineasternasiaafriamericaaustralianlang: {\n title: \"__MSG__EXOTIC_LANGUAGES_OTHER__\"\n }\n }\n },\n historicalandphilosophicalstudies: {\n title: \"__MSG__HISTORICAL_PHILOSOPHICAL_STUDIES__\",\n children: {\n historybyperiod: {\n title: \"__MSG__HISTORY_PERIOD__\"\n },\n historybyarea: {\n title: \"__MSG__HISTORY_AREA__\"\n },\n historybytopic: {\n title: \"__MSG__HISTORY_TOPIC__\"\n },\n archaeology: {\n title: \"__MSG__ARCHEOLOGY__\"\n },\n philosophy: {\n title: \"__MSG__PHILOSOPHY__\"\n },\n theologyandreligiousstudies: {\n title: \"__MSG__THEOLOGY_STUDIES__\"\n },\n othersinhistoricalandphilosophicalstudies: {\n title: \"__MSG__HISTORICAL_PHILOSOPHICAL_STUDIES_OTHER__\"\n }\n }\n },\n creativeartsanddesign: {\n title: \"__MSG__CREATIVE_ARTS__\",\n children: {\n fineart: {\n title: \"__MSG__FINE_ART__\"\n },\n designstudies: {\n title: \"__MSG__DESIGN_STUDIES__\"\n },\n music: {\n title: \"__MSG__MUSIC__\"\n },\n drama: {\n title: \"__MSG__DRAMA__\"\n },\n dance: {\n title: \"__MSG__DANCE__\"\n },\n cinematicsandphotography: {\n title: \"__MSG__CINEMATICS_PHOTOGRAPHY__\"\n },\n crafts: {\n title: \"__MSG__CRAFTS__\"\n },\n imaginativewriting: {\n title: \"__MSG__IMAGINITIVE_WRITING__\"\n },\n othersincreativeartsanddesign: {\n title: \"__MSG__CREATIVE_ARTS_OTHER__\"\n }\n }\n },\n education: {\n title: \"__MSG__EDUCATION__\",\n children: {\n trainingteachers: {\n title: \"__MSG__TRAINING_TEACHERS__\"\n },\n researchandstudyskillsineducation: {\n title: \"__MSG__EDUCATION_RESEARCH_STUDY_SKILLS__\"\n },\n academicstudiesineducation: {\n title: \"__MSG__EDUCATION_ACADEMIC_STUDIES__\"\n },\n othersineducation: {\n title: \"__MSG__EDUCATION_OTHER__\"\n }\n }\n }\n },\n\n // Array of css files to load in each page\n skinCSS: [],\n\n Languages: [{\n \"country\": \"CN\",\n \"language\": \"zh\",\n \"displayName\": \"\u4e2d\u6587\"\n }, {\n \"country\": \"NL\",\n \"language\": \"nl\",\n \"displayName\": \"Nederlands\"\n }, {\n \"country\": \"GB\",\n \"language\": \"en\",\n \"displayName\": \"English (United Kingdom)\"\n }, {\n \"country\": \"US\",\n \"language\": \"en\",\n \"displayName\": \"English (United States)\"\n }, {\n \"country\": \"JP\",\n \"language\": \"ja\",\n \"displayName\": \"\u65e5\u672c\u8a9e\"\n }, {\n \"country\": \"HU\",\n \"language\": \"hu\",\n \"displayName\": \"Magyar\"\n }, {\n \"country\": \"KR\",\n \"language\": \"ko\",\n \"displayName\": \"\ud55c\uad6d\uc5b4\"\n }],\n\n // Default Language for the deployment, must be one of the language_COUNTRY pairs that exists above\n defaultLanguage: \"en_US\",\n\n enableChat: false,\n enableCategories: true,\n\n Editor: {\n tinymceLanguagePacks: ['ar','ch','en','gl','id','lb','nb','ru','sv','uk','az','cn','eo','gu','is','lt','nl',\n 'sc','ta','ur','be','cs','es','he','it','lv','nn','se','te','vi','bg','cy','et','hi','ja','mk','no','si',\n 'th','zh-cn','bn','da','eu','hr','ka','ml','pl','sk','tn','zh-tw','br','de','fa','hu','kl','mn','ps','sl',\n 'tr','zh','bs','dv','fi','hy','km','ms','pt','sq','tt','zu','ca','el','fr','ia','ko','my','ro','sr','tw']\n },\n\n defaultSakaiDocContent: \"\",\n\n /*\n * _canEdit: can change the area permissions on this page\n * _reorderOnly: can reorder this item in the navigation, but cannot edit the name of the page\n * _nonEditable: cannot edit the contents of this page\n * _canSubedit:\n */\n\n defaultprivstructure: {\n \"structure0\": {\n \"dashboard\": {\n \"_ref\": \"${refid}0\",\n \"_title\": \"__MSG__MY_DASHBOARD__\",\n \"_order\": 0,\n \"_canEdit\": true,\n \"_reorderOnly\": true,\n \"_nonEditable\": true,\n \"main\": {\n \"_ref\": \"${refid}0\",\n \"_order\": 0,\n \"_title\": \"__MSG__MY_DASHBOARD__\"\n }\n },\n \"messages\": {\n \"_title\": \"__MSG__MY_MESSAGES__\",\n \"_ref\": \"${refid}1\",\n \"_order\": 1,\n \"_canEdit\": true,\n \"_reorderOnly\": true,\n \"_canSubedit\": true,\n \"_nonEditable\": true,\n \"inbox\": {\n \"_ref\": \"${refid}1\",\n \"_order\": 0,\n \"_title\": \"__MSG__INBOX__\",\n \"_nonEditable\": true\n },\n \"invitations\": {\n \"_ref\": \"${refid}2\",\n \"_order\": 1,\n \"_title\": \"__MSG__INVITATIONS__\",\n \"_nonEditable\": true\n },\n \"sent\": {\n \"_ref\": \"${refid}3\",\n \"_order\": 2,\n \"_title\": \"__MSG__SENT__\",\n \"_nonEditable\": true\n },\n \"trash\": {\n \"_ref\": \"${refid}4\",\n \"_order\": 3,\n \"_title\": \"__MSG__TRASH__\",\n \"_nonEditable\": true\n }\n }\n },\n \"${refid}0\": {\n \"page\": \"
            __MSG__MY_DASHBOARD__

            \"\n },\n \"${refid}1\": {\n \"page\": \"
            \"\n },\n \"${refid}2\": {\n \"page\": \"
            \"\n },\n \"${refid}3\": {\n \"page\": \"
            \"\n },\n \"${refid}4\": {\n \"page\": \"
            \"\n },\n \"${refid}5\": {\n \"dashboard\": {\n \"layout\": \"threecolumn\",\n \"columns\": {\n \"column1\": [{\n \"uid\": \"${refid}10\",\n \"visible\": \"block\",\n \"name\": \"recentchangedcontent\"\n }],\n \"column2\": [{\n \"uid\": \"${refid}11\",\n \"visible\": \"block\",\n \"name\": \"recentmemberships\"\n }],\n \"column3\": [{\n \"uid\": \"${refid}12\",\n \"visible\": \"block\",\n \"name\": \"recentcontactsnew\"\n }]\n }\n }\n },\n \"${refid}6\": {\n \"box\": \"inbox\",\n \"category\": \"message\",\n \"title\": \"__MSG__INBOX__\"\n },\n \"${refid}7\": {\n \"box\": \"inbox\",\n \"category\": \"invitation\",\n \"title\": \"__MSG__INVITATIONS__\"\n },\n \"${refid}8\": {\n \"box\": \"outbox\",\n \"category\": \"*\",\n \"title\": \"__MSG__SENT__\"\n },\n \"${refid}9\": {\n \"box\": \"trash\",\n \"category\": \"*\",\n \"title\": \"__MSG__TRASH__\"\n }\n },\n\n /**\n * In order to set permissions on specific private areas, the following parameter should be added:\n * _view: \"anonymous\" // Area is visible to all users by default\n * _view: \"everyone\" // Area is visible to all logged in users by default\n * _view: \"contacts\" // Area is visible to all contacts by default\n * _view: \"private\" // Area is not visible to other users by default\n */\n defaultpubstructure: {\n \"structure0\": {\n \"profile\": {\n \"_title\": \"__MSG__MY_PROFILE__\",\n \"_altTitle\": \"__MSG__MY_PROFILE_OTHER__\",\n \"_order\": 0,\n \"_view\": \"anonymous\",\n \"_reorderOnly\": true,\n \"_nonEditable\": true\n },\n \"library\": {\n \"_ref\": \"${refid}0\",\n \"_order\": 1,\n \"_title\": \"__MSG__MY_LIBRARY__\",\n \"_altTitle\": \"__MSG__MY_LIBRARY_OTHER__\",\n \"_reorderOnly\": true,\n \"_nonEditable\": true,\n \"_view\": \"anonymous\",\n \"main\": {\n \"_ref\": \"${refid}0\",\n \"_order\": 0,\n \"_title\": \"__MSG__MY_LIBRARY__\"\n }\n },\n \"memberships\": {\n \"_title\": \"__MSG__MY_MEMBERSHIPS__\",\n \"_order\": 2,\n \"_ref\": \"${refid}1\",\n \"_altTitle\": \"__MSG__MY_MEMBERSHIPS_OTHER__\",\n \"_reorderOnly\": true,\n \"_nonEditable\": true,\n \"_view\": \"anonymous\",\n \"main\": {\n \"_ref\": \"${refid}1\",\n \"_order\": 0,\n \"_title\": \"__MSG__MY_MEMBERSHIPS__\"\n }\n },\n \"contacts\": {\n \"_title\": \"__MSG__MY_CONTACTS__\",\n \"_order\": 3,\n \"_ref\": \"${refid}2\",\n \"_altTitle\": \"__MSG__MY_CONTACTS_OTHER__\",\n \"_reorderOnly\": true,\n \"_nonEditable\": true,\n \"_view\": \"anonymous\",\n \"main\": {\n \"_ref\": \"${refid}2\",\n \"_order\": 0,\n \"_title\": \"__MSG__MY_CONTACTS__\"\n }\n }\n },\n \"${refid}0\": {\n \"page\": \"
            \"\n },\n \"${refid}1\": {\n \"page\": \"
            \" +\n \"
            \" +\n \"
            \"\n },\n \"${refid}2\": {\n \"page\": \"
            \"\n }\n },\n\n widgets: {\n \"layouts\": {\n \"onecolumn\": {\n \"name\": \"One column\",\n \"widths\": [100],\n \"siteportal\": true\n },\n \"dev\": {\n \"name\": \"Dev Layout\",\n \"widths\": [50, 50],\n \"siteportal\": true\n },\n \"threecolumn\": {\n \"name\": \"Three equal columns\",\n \"widths\": [33, 33, 33],\n \"siteportal\": false\n }\n },\n \"defaults\": {\n \"personalportal\": {\n \"layout\": \"dev\",\n \"columns\": [[\"mygroups\", \"mycontacts\"], [\"mycontent\", \"recentmessages\"]]\n }\n }\n }\n };\n\n return config;\n});\n", "dev/content_profile.html": "\n\n\n \n\n \n \n \n\n \n \n\n \n \n \n\n \n \n \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n \n
            \n
            \n
            \n
            \n
            \n\n \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n\n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n\n \n
            \n\n \n
            \n\n
            \n \n
            \n\n __MSG__CONTENT_PROFILE__\n __MSG__THE_FILE_HAS_BEEN_SUCCESSFULLY_SHARED_WITH__\n __MSG__ALL_SELECTED_USERS_AND_GROUPS_HAVE_BEEN_REMOVED_FROM__\n __MSG__VIEWERS__\n __MSG__MANAGERS__\n __MSG__CONTENT_CANNOT_REMOVE_ALL_MANAGERS__\n\n
            \n\n \n
            \n\n \n \n \n\n \n \n\t\t\n\t\n\n", "dev/create_new_account.html": "\n\n\n \n\n \n \n \n\n \n \n\n \n \n \n\n \n \n \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n\n \n
            \n
            \n
            \n
            \n
            __MSG__SIGN_UP_MESSAGE_1__
            \n
            __MSG__SIGN_UP_MESSAGE_2__
            \n
            __MSG__SIGN_UP_MESSAGE_3__
            \n
            \n
            \n
            \n
            \n
            \n

            __MSG__CREATE_A_NEW_ACCOUNT__

            \n
            \n
            \n \n \n \n \n \n \n
            \n
            \n\n
            \n
            \n \n \n \n \n \n \n
            \n
            \n
            \n
            \n \n
            \n
            \n
            \n
            \n\n
            __MSG__PLEASE_ENTER_YOUR_FIRST_NAME__
            \n
            __MSG__PLEASE_ENTER_YOUR_LAST_NAME__
            \n
            __MSG__PLEASE_ENTER_A_VALID_EMAIL_ADDRESS__
            \n
            __MSG__THIS_IS_AN_INVALID_EMAIL_ADDRESS__
            \n
            __MSG__PLEASE_ENTER_YOUR_USERNAME__
            \n
            __MSG__THE_USERNAME_SHOULD_BE_AT_LEAST_THREE_CHARACTERS_LONG__
            \n
            __MSG__THE_USERNAME_SHOULDNT_CONTAIN_SPACES__
            \n
            __MSG__PLEASE_ENTER_YOUR_PASSWORD__
            \n
            __MSG__YOUR_PASSWORD_SHOULD_BE_AT_LEAST_FOUR_CHARACTERS_LONG__
            \n
            __MSG__PLEASE_REPEART_YOUR_PASSWORD__
            \n
            __MSG__THIS_PASSWORD_DOES_NOT_MATCH_THE_FIRST_ONE__
            \n\n
            \n
            \n
            \n
            __MSG__SIGN_UP_RECOMMEND_NAME_1__,
            __MSG__SIGN_UP_RECOMMEND_INSTITUTION_NYU__
            \n "__MSG__SIGN_UP_RECOMMEND_MESSAGE_1__"\n
            \n
            \n
            \n
            \n
            __MSG__SIGN_UP_RECOMMEND_NAME_2__,
            __MSG__SIGN_UP_RECOMMEND_INSTITUTION_NYU__
            \n "__MSG__SIGN_UP_RECOMMEND_MESSAGE_2__"\n
            \n
            \n
            \n
            \n
            __MSG__SIGN_UP_RECOMMEND_NAME_3__,
            __MSG__SIGN_UP_RECOMMEND_INSTITUTION_NYU__
            \n "__MSG__SIGN_UP_RECOMMEND_MESSAGE_3__"\n
            \n

            __MSG__INSTITUTIONS_USING_SAKAI__

            \n
              \n
            • \"__MSG__SIGN_UP_RECOMMEND_INSTITUTION_NYU__\"
            • \n
            • \"__MSG__SIGN_UP_RECOMMEND_INSTITUTION_STANFORD__\"
            • \n
            • \"__MSG__SIGN_UP_RECOMMEND_INSTITUTION_CAMBRIDGE__\"
            • \n
            • \"__MSG__SIGN_UP_RECOMMEND_INSTITUTION_YALE__\"
            • \n
            • \"__MSG__SIGN_UP_RECOMMEND_INSTITUTION_CSU__\"
            • \n
            • \"__MSG__SIGN_UP_RECOMMEND_INSTITUTION_OXFORD__\"
            • \n
            \n
            \n
            \n
            \n
            \n\n \n
            \n\n \n \n \n\n \n", "dev/createnew.html": "\n\n\n \n\n \n \n \n\n \n \n\n \n \n \n\n \n \n \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n\n \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n\n \n
            \n\n\n \n \n \n \n \n \n \n\n", "dev/css/FSS/fss-base.css": "/*\n * Licensed to the Sakai Foundation (SF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The SF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations under the License.\n */\n\n/* Fluid Base \n * combination of Fluid FSS files from:\n * http://fluidproject.org/releases/1.1.2/infusion-1.1.2.zip\n * version: Infusion 1.1.2\n * \n * Concatenated files contained here:\n * fss-reset.css\n * fss-layout.css\n * fss-text.css\n * \n * Based on version: 2.5.2 of the Yahoo CSS reset, font, and base\n * Copyright (c) 2008, Yahoo! Inc. All rights reserved.\n * Code licensed under the BSD License:\n * http://developer.yahoo.net/yui/license.txt\n * \n * Please see these files in: http://fluidproject.org/releases/1.1.2/infusion-1.1.2-src.zip \n * for usage and full license information\n */\n\n/* Fluid Reset: \n * fss-reset.css \n */\n\ntable{font-size:inherit;font:100%;}\npre,code,kbd,samp,tt{font-family:monospace;*font-size:108%;line-height:100%;}\nhtml{color:#000;background:#FFF;}\nbody,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,code,form,fieldset,legend,input,textarea,p,blockquote,th,td{margin:0;padding:0;}\nfieldset,img{border:0;}\naddress,caption,cite,code,dfn,em,strong,th,var{font-style:normal;font-weight:normal;}\nli{list-style:none;}\ncaption,th{text-align:left;}\nh1,h2,h3,h4,h5,h6{font-size:100%;font-weight:normal;}\nq:before,q:after{content:'';}\nabbr,acronym{border:0;font-variant:normal;}\nsup{vertical-align:text-top;}\nsub{vertical-align:text-bottom;}\nlegend{color:#000;}\nh1{font-size:138.5%;}\nh2{font-size:123.1%;}\nh3{font-size:108%;}\nh1,h2,h3{margin:1em 0;}\nh1,h2,h3,h4,h5,h6,strong{font-weight:bold;}\nabbr,acronym{border-bottom:1px dotted #000;cursor:help;}\nem{font-style:italic;}\nblockquote,ul,ol,dl{margin:1em;}\nol,ul,dl{margin-left:2em;}\nol li{list-style:decimal outside;}\nul li{list-style:disc outside;}\ndl dd{margin-left:1em;}\nth{font-weight:bold;text-align:center;}\ncaption{margin-bottom:.5em;text-align:center;}\np,fieldset,table,pre{margin-bottom:1em;}\ninput[type=text],input[type=password],textarea{width:12.25em;*width:11.9em;}\ninput,textarea,select{font-family:inherit;font-size:inherit;font-weight:inherit;}\nhtml{overflow:auto;font:13px/1.231 arial,helvetica,clean,sans-serif;*font-size:small;}\ninput,textarea,select{*font-size:100%;*font-family:sans-serif;}\ninput{*overflow:visible;*padding:0 1em;}\n:focus{outline:2px solid black;}\n\n/* Fluid Layout: \n * fss-layout.css \n */\n\n.fl-fix{overflow:auto;zoom:1;}\n.fl-push{clear:both;}\n.fl-hidden{visibility:hidden;margin:0;}\n.fl-force-right{float:right;display:inline;}\n.fl-force-left{float:left;display:inline;}\n.fl-centered{margin-left:auto;margin-right:auto;display:block;}\n.fl-container-50{width:50px;}\n.fl-container-100{width:100px;}\n.fl-container-150{width:150px;}\n.fl-container-200{width:200px;}\n.fl-container-250{width:250px;}\n.fl-container-300{width:300px;}\n.fl-container-350{width:350px;}\n.fl-container-400{width:400px;}\n.fl-container-450{width:450px;}\n.fl-container-500{width:500px;}\n.fl-container-550{width:550px;}\n.fl-container-600{width:600px;}\n.fl-container-650{width:650px;}\n.fl-container-700{width:700px;}\n.fl-container-750{width:750px;}\n.fl-container-800{width:800px;}\n.fl-container-850{width:850px;}\n.fl-container-900{width:900px;}\n.fl-container-950{width:950px;}\n.fl-container-1000{width:1000px;}\n.fl-container-auto{width:auto;}\n.fl-container-flex{width:100%;clear:both;}\n.fl-container-flex10{width:10%;}\n.fl-container-flex20{width:20%;}\n.fl-container-flex25{width:25%;}\n.fl-container-flex30{width:30%;}\n.fl-container-flex33{width:33%;}\n.fl-container-flex40{width:40%;}\n.fl-container-flex50{width:50%;}\n.fl-container-flex60{width:60%;}\n.fl-container-flex66{width:66%;}\n.fl-container-flex75{width:75%;}\n.fl-layout-linear *,.fl-layout-linear .fl-linearEnabled{overflow:visible!important;clear:both!important;float:none!important;margin-left:0!important;margin-right:0!important;}\n.fl-layout-linear .fl-container,.fl-layout-linear .fl-container-100,.fl-layout-linear .fl-container-150,.fl-layout-linear .fl-container-200,.fl-layout-linear .fl-container-250,.fl-layout-linear .fl-container-300,.fl-layout-linear .fl-container-400,.fl-layout-linear .fl-container-750,.fl-layout-linear .fl-container-950,.fl-layout-linear .fl-container-auto,.fl-layout-linear .fl-container-flex25,.fl-layout-linear .fl-container-flex30,.fl-layout-linear .fl-container-flex33,.fl-layout-linear .fl-container-flex50,.fl-layout-linear .fl-col,.fl-layout-linear .fl-col-side,.fl-layout-linear .fl-col-flex,.fl-layout-linear .fl-col-main,.fl-layout-linear .fl-col-fixed,.fl-layout-linear .fl-col-justified{width:100%!important;margin:auto;padding:0!important;}\n.fl-layout-linear .fl-force-left,.fl-layout-linear .fl-force-right,.fl-layout-linear li{display:block!important;float:none!important;}\n.fl-layout-linear .fl-linearEnabled{width:100%!important;display:block;}\n.fl-layout-linear .fl-button-left,.fl-layout-linear .fl-button-right{padding:1em;}\n.fl-col-justified{float:left;display:inline;overflow:auto;text-align:justify;}\n.fl-col-flex2,.fl-col-flex3,.fl-col-flex4,.fl-col-flex5{overflow:hidden;zoom:1;}\n.fl-col{float:left;display:inline;}\n.fl-col-flex5 .fl-col{width:18.95%;margin-left:.25%;margin-right:.25%;padding-left:.25%;padding-right:.25%;}\n.fl-col-flex4 .fl-col{width:24%;margin-left:.25%;margin-right:.25%;padding-left:.25%;padding-right:.25%;}\n.fl-col-flex3 .fl-col{width:32.33%;margin-left:.25%;margin-right:.25%;padding-left:.25%;padding-right:.25%;}\n.fl-col-flex2 .fl-col{width:48.85%;margin-left:.25%;margin-right:.25%;padding-left:.25%;padding-right:.25%;}\n.fl-col-mixed,.fl-col-mixed2,.fl-col-mixed3{overflow:auto;zoom:1;}\n.fl-col-mixed .fl-col-side{width:200px;}\n.fl-col-mixed .fl-col-side,.fl-col-mixed .fl-col-main{padding:0 10px;}\n.fl-col-mixed2 .fl-col-side{width:200px;padding:0 10px;float:left;}\n.fl-col-mixed2 .fl-col-main{margin-left:220px;padding:0 10px;}\n.fl-col-mixed3 .fl-col-main{margin:0 220px;}\n.fl-col-fixed,.fl-col-flex{padding:0 10px;}\n.fl-col-mixed .fl-col-fixed{width:200px;padding:0 10px;}\n.fl-col-mixed .fl-col-flex{margin-left:220px;padding:0 10px;}\n.fl-col-mixed-100 .fl-col-fixed{width:100px;}\n.fl-col-mixed-100 .fl-col-flex{margin-left:120px;}\n.fl-col-mixed-150 .fl-col-fixed{width:150px;}\n.fl-col-mixed-150 .fl-col-flex{margin-left:170px;}\n.fl-col-mixed-200 .fl-col-fixed{width:200px;}\n.fl-col-mixed-200 .fl-col-flex{margin-left:220px;}\n.fl-col-mixed-250 .fl-col-fixed{width:250px;}\n.fl-col-mixed-250 .fl-col-flex{margin-left:270px;}\n.fl-col-mixed-300 .fl-col-fixed{width:300px;}\n.fl-col-mixed-300 .fl-col-flex{margin-left:320px;}\n.fl-tabs{margin:10px 0 0 0;border-bottom:1px solid #000;text-align:center;padding-bottom:2px;}\n.fl-tabs li{list-style-type:none;display:inline;}\n.fl-tabs li a{padding:3px 16px 2px;background-color:#fff;margin-left:-5px;*margin-bottom:-6px;zoom:1;border:1px solid #000;color:#999;}\n.fl-tabs-center{text-align:center;}\n.fl-tabs-left{text-align:left;padding-left:10px;}\n.fl-tabs-right{text-align:right;padding-right:15px;}\n.fl-tabs .fl-reorderer-dropMarker{padding:0 3px;background-color:#c00;margin:0 5px 0 -5px;zoom:1;}\n.fl-tabs .fl-tabs-active a{padding:2px 16px;border-bottom:none;color:#000;}\n.fl-tabs-content{padding:5px;}\n@media screen and(-webkit-min-device-pixel-ratio:0){.fl-tabs li a{padding:3px 16px 3px;}\n.fl-tabs .fl-tabs-active a{padding:3px 16px 4px;}\n}\n.fl-listmenu{padding:0;margin:0;border-bottom-width:1px;border-bottom-style:solid;}\n.fl-listmenu li{margin:0;padding:0;list-style-type:none;border-width:1px;border-style:solid;border-bottom:none;}\n.fl-listmenu a{padding:5px 5px;display:block;zoom:1;}\nul.fl-grid,.fl-grid ul{padding:0;margin:0;}\n.fl-grid li{list-style-type:none;display:inline;}\n.fl-grid li{float:left;width:19%;margin:.5%;height:150px;overflow:hidden;position:relative;display:inline;}\n.fl-grid li img{display:block;margin:5px auto;}\n.fl-grid li .caption{position:absolute;left:0;bottom:0;width:100%;text-align:center;height:1em;padding:3px 0;}\n.fl-icon{text-indent:-5000px;overflow:hidden;cursor:pointer;display:block;height:16px;width:16px;margin-left:5px;margin-right:5px;background-position:center center;background-repeat:no-repeat;}\ninput.fl-icon{padding-left:16px;}\n.fl-button-left{float:left;margin-right:10px;padding:0 0 0 16px;background-position:left center;background-repeat:no-repeat;}\n.fl-button-right{float:right;margin-left:10px;padding:0 0 0 16px;background-position:left center;background-repeat:no-repeat;}\n.fl-button-inner{float:left;padding:5px 16px 5px 0;cursor:pointer;background-position:right center;background-repeat:no-repeat;}\n.fl-widget{padding:5px;margin-bottom:10px;}\n.fl-widget .button{margin:0 5px;}\n.fl-grabbable .fl-widget-titlebar{background-position:center top;background-repeat:no-repeat;cursor:move;}\n.fl-widget .fl-widget-titlebar h2{padding:0;margin:0;font-size:105%;}\n.fl-widget .fl-widget-titlebar .fl-button-inner{font-size:.8em;padding-bottom:.2em;padding-top:.2em;}\n.fl-widget .fl-widget-controls{margin:-1.3em 0 1.5em 0;}\n.fl-widget .fl-widget-options{background-color:#D5DBDF;overflow-y:hidden;}\n.fl-widget .fl-widget-options ul{margin:0;padding:0;overflow:hidden;zoom:1;}\n.fl-widget .fl-widget-options li{list-style-type:none;float:left;display:inline;padding:0 5px 0 5px;margin-left:-5px;}\n.fl-widget .fl-widget-options a{margin-right:5px;}\n.fl-widget .fl-widget-content{zoom:1;margin:5px 0 0 0;}\n.fl-widget .empty *{padding-top:10px;margin-left:auto;margin-right:auto;text-align:center;}\n.fl-widget .menu{margin:0;}\n.fl-widget .toggle{width:32px;}\n.fl-widget .on{background-position:left top;}\n.fl-widget .off{background-position:left bottom;}\n.fl-controls-left li{list-style-type:none;text-align:left;}\n.fl-controls-left .fl-label{float:left;text-align:left;width:50%;margin-right:5px;}\n.fl-controls-right li{list-style-type:none;display:block;text-align:left;}\n.fl-controls-right .fl-label{float:left;text-align:right;width:50%;margin-right:5px;}\n.fl-controls-centered li{list-style-type:none;display:block;text-align:left;}\n.fl-controls-centered .fl-label{float:left;text-align:center;width:50%;margin-right:5px;}\n.fl-noBackgroundImages,.fl-noBackgroundImages *{background-image:none!important;}\n.fl-noBackgroundImages .fl-icon{text-indent:0!important;width:auto!important;background-color:transparent!important;}\n.fl-ProgEnhance-enhanced,.fl-progEnhance-enhanced{display:none;}\n.fl-offScreen-hidden{position:absolute;left:-10000px;top:auto;width:1px;height:1px;overflow:hidden;}\n\n/* Fluid Text: \n * fss-text.css \n */\n\n.fl-font-size-70,.fl-font-size-70 body,.fl-font-size-70 input,.fl-font-size-70 select,.fl-font-size-70 textarea{font-size:.7em!important;line-height:1em!important;}\n.fl-font-size-80,.fl-font-size-80 body,.fl-font-size-80 input,.fl-font-size-80 select,.fl-font-size-80 textarea{font-size:.8em!important;line-height:1.1em!important;}\n.fl-font-size-90,.fl-font-size-90 body,.fl-font-size-90 input,.fl-font-size-90 select,.fl-font-size-90 textarea{font-size:.9em!important;line-height:1.2em!important;}\n.fl-font-size-100,.fl-font-size-100 body,.fl-font-size-100 input,.fl-font-size-100 select,.fl-font-size-100 textarea{font-size:1em!important;line-height:1.3em!important;}\n.fl-font-size-110,.fl-font-size-110 body,.fl-font-size-110 input,.fl-font-size-110 select,.fl-font-size-110 textarea{font-size:1.1em!important;line-height:1.4em!important;}\n.fl-font-size-120,.fl-font-size-120 body,.fl-font-size-120 input,.fl-font-size-120 select,.fl-font-size-120 textarea{font-size:1.2em!important;line-height:1.5em!important;}\n.fl-font-size-130,.fl-font-size-130 body,.fl-font-size-130 input,.fl-font-size-130 select,.fl-font-size-130 textarea{font-size:1.3em!important;line-height:1.6em!important;}\n.fl-font-size-140,.fl-font-size-140 body,.fl-font-size-140 input,.fl-font-size-140 select,.fl-font-size-140 textarea{font-size:1.4em!important;line-height:1.7em!important;}\n.fl-font-size-150,.fl-font-size-150 body,.fl-font-size-150 input,.fl-font-size-150 select,.fl-font-size-150 textarea{font-size:1.5em!important;line-height:1.8em!important;}\n@media screen and(-webkit-min-device-pixel-ratio:0){[class~='fl-font-size-70'] input[type=submit],[class~='fl-font-size-70'] input[type=button]{padding:0 1em;}\n[class~='fl-font-size-80'] input[type=submit],[class~='fl-font-size-80'] input[type=button]{font-size:.8em!important;padding:0 1em;}\n[class~='fl-font-size-90'] input[type=submit],[class~='fl-font-size-90'] input[type=button]{font-size:.9em!important;padding:0 1em;}\n[class~='fl-font-size-100'] input[type=submit],[class~='fl-font-size-100'] input[type=button]{font-size:1em!important;padding:0 1em;}\n[class~='fl-font-size-110'] input[type=submit],input[type=submit][class~='fl-font-size-110'],[class~='fl-font-size-110'] input[type=button]{background-color:#fff;font-size:1.1em!important;padding:0 1em;}\n[class~='fl-font-size-120'] input[type=submit],input[type=submit][class~='fl-font-size-120'],[class~='fl-font-size-120'] input[type=button]{background-color:#fff;font-size:1.2em!important;padding:0 1em;}\n[class~='fl-font-size-130'] input[type=submit],input[type=submit][class~='fl-font-size-130'],[class~='fl-font-size-130'] input[type=button]{background-color:#fff;font-size:1.3em!important;padding:0 1em;}\n[class~='fl-font-size-140'] input[type=submit],input[type=submit][class~='fl-font-size-140'],[class~='fl-font-size-140'] input[type=button]{background-color:#fff;font-size:1.4em!important;padding:0 1em;}\n[class~='fl-font-size-150'] input[type=submit],input[type=submit][class~='fl-font-size-150'],[class~='fl-font-size-150'] input[type=button]{background-color:#fff;font-size:1.5em!important;padding:0 1em;}\n[class~='fl-font-serif'] input[type=submit],[class~='fl-font-sans'] input[type=submit],[class~='fl-font-monospace'] input[type=submit],[class~='fl-font-arial'] input[type=submit],[class~='fl-font-verdana'] input[type=submit],[class~='fl-font-times'] input[type=submit],[class~='fl-font-courier'] input[type=submit]{background-color:#fff;padding:0 1em;}\n}\n.fl-font-serif,.fl-font-serif *{font-family:Georgia,Times,\"Times New Roman\",\"Book Antiqua\",serif!important;}\n.fl-font-sans,.fl-font-sans *{font-family:Tahoma,Verdana,Helvetica,sans-serif!important;}\n.fl-font-monospace,.fl-font-monospace *{font-family:\"Courier New,Courier\",monospace!important;}\n.fl-font-arial,.fl-font-arial *{font-family:\"Arial\"!important;}\n.fl-font-verdana,.fl-font-verdana *{font-family:\"Verdana\"!important;}\n.fl-font-times,.fl-font-times *{font-family:Georgia,Times,\"Times New Roman\",serif!important;}\n.fl-font-courier,.fl-font-courier *{font-family:\"Courier New\",Courier,monospace!important;}\n.fl-text-align-left{text-align:left;}\n.fl-text-align-right{text-align:right;}\n.fl-text-align-center{text-align:center;}\n.fl-text-align-justify{text-align:justify;}\n.fl-font-spacing-0,.fl-font-spacing-0 body,.fl-font-spacing-0 input,.fl-font-spacing-0 select,.fl-font-spacing-0 textarea{letter-spacing:0;}\n.fl-font-spacing-1,.fl-font-spacing-1 body,.fl-font-spacing-1 input,.fl-font-spacing-1 select,.fl-font-spacing-1 textarea{letter-spacing:.1em;}\n.fl-font-spacing-2,.fl-font-spacing-2 body,.fl-font-spacing-2 input,.fl-font-spacing-2 select,.fl-font-spacing-2 textarea{letter-spacing:.2em;}\n.fl-font-spacing-3,.fl-font-spacing-3 body,.fl-font-spacing-3 input,.fl-font-spacing-3 select,.fl-font-spacing-3 textarea{letter-spacing:.3em;}\n.fl-font-spacing-4,.fl-font-spacing-4 body,.fl-font-spacing-4 input,.fl-font-spacing-4 select,.fl-font-spacing-4 textarea{letter-spacing:.4em;}\n.fl-font-spacing-5,.fl-font-spacing-5 body,.fl-font-spacing-5 input,.fl-font-spacing-5 select,.fl-font-spacing-5 textarea{letter-spacing:.5em;}\n.fl-font-spacing-6,.fl-font-spacing-6 body,.fl-font-spacing-6 input,.fl-font-spacing-6 select,.fl-font-spacing-6 textarea{letter-spacing:.6em;}\n.fl-text-aqua{color:aqua!important;}\n.fl-text-black{color:black!important;}\n.fl-text-blue{color:blue!important;}\n.fl-text-fuchsia{color:fuchsia!important;}\n.fl-text-gray{color:gray!important;}\n.fl-text-green{color:green!important;}\n.fl-text-lime{color:lime!important;}\n.fl-text-maroon{color:maroon!important;}\n.fl-text-navy{color:navy!important;}\n.fl-text-olive{color:olive!important;}\n.fl-text-purple{color:purple!important;}\n.fl-text-red{color:red!important;}\n.fl-text-silver{color:silver!important;}\n.fl-text-teal{color:teal!important;}\n.fl-text-white{color:white!important;}\n.fl-text-yellow{color:yellow!important;}\n.fl-text-underline{text-decoration:underline!important;}\n.fl-text-bold{font-weight:bold!important;}\n.fl-text-larger{font-size:125%!important;}\n.fl-input-outline{border:2px solid;}\n.fl-highlight-yellow,.fl-highlight-hover-yellow:hover,.fl-highlight-focus-yellow:focus{background-color:#FF0!important;background-image:none!important;}\n.fl-highlight-green,.fl-highlight-hover-green:hover,.fl-highlight-focus-green:focus{background-color:#0F0!important;background-image:none!important;}\n.fl-highlight-blue,.fl-highlight-hover-blue:hover,.fl-highlight-focus-blue:focus{background-color:#00F!important;background-image:none!important;}\n\n", "dev/css/sakai/sakai.base.css": "/**\n * Licensed to the Sakai Foundation (SF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The SF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations under the License.\n */\n\n/*\n * GLOBAL RULES\n */\nbody, button{font-family:Arial, Helvetica, sans-serif;line-height:120%;}\n.section_header{font-weight:bold;border-bottom:1px solid #ebebeb;font-size:17px;padding-bottom:3px;}\n\n/* adding a visible outline on focus for accessibility */\n*:focus{outline:1px dotted #000;}\n/*apply to any container that needs to be rendered off-screen, but available to screen readers*/\n.s3d-aural-text {position: absolute;clip: rect(1px 1px 1px 1px); /* IE6, IE7 */clip: rect(1px, 1px, 1px, 1px);overflow:hidden;width:1px;height:1px;} \n\n/* HTML TAG OVERRIDES - on top of the FSS reset */\nh1{font-size:2em;font-family:Arial,Helvetica,sans-serif;font-weight:bolder;line-height:normal;margin:5px 0px 10px 0;}\n\n/* \n * PAGE LAYOUT\n */\n.fixed-container {padding:0 20px;width: 920px;overflow:hidden;}\n.s3d-header .fixed-container { background-color: #FFF;}\n.s3d-header .fixed-container .decor_left {background:url(\"/dev/images/dashboard_sprite.png\") no-repeat scroll left -10px transparent; float:left; height:5px; margin-left:-20px; width:5px;}\n.s3d-header .fixed-container .decor { background: url(\"/dev/images/dashboard_sprite.png\") no-repeat scroll right -10px transparent; height: 5px; margin-right: -20px; }\n.grep {color:#666 !important;font-weight:bold;}\n.s3d-gray {color:#666;}\n.s3d-lowercase {text-transform: lowercase;}\n\n.block_image_left {float: left;}\n.block_image_right {float: right;}\n\n/* GENERAL WIDGET CSS */\n/*.fl-widget {padding: 0;}\n.fl-widget .fl-widget-titlebar h2 {padding-left:3px}\n.fl-widget .fl-widget-titlebar {background: url(\"/dev/images/dashboard_sprite.png\") no-repeat scroll right -473px transparent; padding: 0 4px 0 0; width: auto; min-height: 39px;}\n.fl-widget .fl-widget-titlebar .widget-titlebar-inner {background: url(\"/dev/images/dashboard_sprite.png\") no-repeat scroll -10px -544px transparent; min-height: 39px;}\n.fl-widget .fl-widget-options ul {margin: 0; padding: 0; width:100%;}\n.fl-widget .fl-widget-titlebar .widget_title {color: #878a8c; font-size: 1.0em; padding: 13px 30px 10px 40px; vertical-align: text-top; word-wrap:break-word;}\n.fl-widget .fl-widget-titlebar .widget_title_icon {display: block; float: left; height: 17px; left: 16px; position: relative; top: 14px; width: 17px;}\n.fl-widget .fl-widget-titlebar .settings {background: url(\"/dev/images/dashboard_sprite.png\") no-repeat scroll -186px -393px transparent; position: relative; height: 18px; margin: 15px 8px 0 0;}\n.fl-widget .fl-widget-options ul li {float: left; margin: 0; padding: 0 6px 0;}\n.fl-widget .fl-widget-options ul li a, .fl-widget .fl-widget-options ul li .s3d-link-button {color: #666; font-size: .85em; font-weight: bold;}\n.fl-widget .fl-widget-options .pipe_divider {font-size: .85em;}\n.fl-widget .fl-widget-content {background-color: #fff; }\n.fl-widget .fl-widget-content ul {margin: 0;}\n.fl-widget .widget-options-inner {padding: 0px 10px 0; min-height:16px; overflow:hidden; *overflow:auto;}\n.hiddenwidget {border-bottom: 3px solid #D5DBDF;}*/\n\n/*\n.fl-widget .widget-titlebar-end {margin-top: -2px;background: url(\"/dev/images/dashboard_sprite.png\") no-repeat scroll -10px -616px transparent;height: 4px;}\n.fl-widget .widget-titlebar-end-inner {background: url(\"/dev/images/dashboard_sprite.png\") no-repeat scroll right -518px transparent;height: 4px;}\n*/\n\n/* Widget settings */\n#widget_settings_menu {position:absolute;top:0;left:0;margin-top:10px;}\n\n.s3d-dropdown-list {background:url(\"/dev/images/dropdown_list_bg.png\") repeat-x scroll left top #F5F5F5;border: 1px solid #aaa;border-radius:5px;-moz-border-radius:5px;-webkit-border-radius:5px;box-shadow:0 0 6px 0 #666;}\n.s3d-dropdown-list ul {padding:0;margin:5px;}\n.s3d-dropdown-list ul li {padding:2px 5px;margin:0;font-size:12px;list-style-type:none;cursor:pointer;}\n.s3d-dropdown-list ul li button, .s3d-dropdown-list ul li a {color:#2683bc;font-size:11px;font-weight:bold;text-decoration:none;}\n.s3d-dropdown-list ul li a:hover {color:#999;}\n.s3d-dropdown-list .s3d-dropdown-list-arrow-up {background:url(\"/dev/images/dropdown_list_arrow_up.png\") no-repeat scroll left top transparent;height:20px;margin-top:-20px;position:absolute;right:8px;width:25px;}\n\n/* NEW WIDGETS */\n.s3d-widget-container .fl-widget-titlebar .settings {position:relative;height:18px;margin:8px 0 0;text-indent:0 !important;color:#666 !important;}\n.s3d-widget-container .fl-widget-titlebar .settings:hover {color:#2683BC !important;}\n.s3d-widget-container {border:solid 1px #dfdfdf;border-top:none;-moz-border-radius:0 0 5px 5px;-webkit-border-radius:0 0 5px 5px;border-radius:0 0 5px 5px;margin-bottom:10px;}\n.s3d-widget-container .s3d-contentpage-title {border-bottom:none;background:url(\"/dev/images/widget_header_bg.png\") repeat-x scroll left top #dddddc;height:34px;line-height:34px;padding:0 12px;color:#666;font-weight:bold;font-size:13px;}\n.s3d-widget-container .s3d-contentpage-title:hover {cursor:pointer}\n.s3d-widget-container .hiddenwidget .s3d-contentpage-title {margin-bottom:0;}\n.s3d-widget-footer {min-height:14px;background-color:#DDDDDC;-moz-border-radius:0 0 5px 5px;-webkit-border-radius:0 0 5px 5px;border-radius:0 0 5px 5px;margin-top:7px;padding:7px 12px;box-shadow:0 1px 0 0 #bbb;}\n.s3d-widget-footer a, .s3d-widget-footer span {float:right;}\n.s3d-widget-footer-divider {font-size: 11px; color: #999999; padding-left: 5px;}\n\n/* Change layout */\n#change_layout_dialog {width: 840px !important; margin-left: -420px !important;}\n#change_layout_dialog .elf-right-up {padding: 25px 0}\n#change_layout_dialog .add-tools-right {width:100%;}\n#change_layout_dialog .layout_container {float:left;padding-left:25px;padding-right:13px;}\n#change_layout_dialog .layout_picker_item {width:114px; height: 62px; border: 2px solid #3399CC; border-right: 2px solid #3399CC; background-color: #EEFFFF;}\n#change_layout_dialog .layout_picker_item_column {border-right: 1px solid #3399CC;}\n#change_layout_dialog .layout_picker_item_radio {margin-left:50px; margin-top:10px;}\n#change_layout_dialog .layout_container_unselected {float:left; padding-left:25px; padding-right:13px;}\n#change_layout_dialog .layout_picker_item_unselected {width:114px; height: 62px; border: 2px solid #dddfe1; border-right: 2px solid #dddfe1; background-color: #F8F8F8;}\n#change_layout_dialog .layout_picker_item_column_unselected {border-right: 1px solid #dddfe1;}\n#change_layout_dialog .layout_picker_item_radio_unselected {margin-left:50px; margin-top: 10px;}\n#change_layout_dialog #layouts_list {display:block;}\n\n/* Add Sakai Goodies */\n#add_goodies_dialog {width:520px; height: 374px; margin-left: -260px;}\n.add_goodies .s3d-button {margin:0; height:23px;}\n.add_goodies .dialog_body {height:308px; overflow-y:auto; overflow-x:hidden; position:relative; width:471px;}\n.add_goodies ul {margin:0;}\n.add_goodies ul li{border-bottom: 1px solid #efefef;line-height:30px;list-style:none;padding:0 12px;}\n.add_goodies ul li:hover{background-color:#dbeefc;}\n.add_goodies .dialog_add_goodies_description {color:#333;font-size:13px;font-weight:normal;}\n.add_goodies .dialog_remove_goodies_title {color:#999;font-size:14px;font-weight:bold;}\n.add_goodies .dialog_remove_goodies_description {color:#999999;font-size:12px;font-weight:100;}\n.add_goodies .dialog_add_goodies_title {color:#333;font-size:13px;font-weight:bold;}\n.add_goodies .remove_add_column {float:right;width:100px;}\n\n/* D&D Classes */\n.ui-draggable, .orderable-hover {cursor:move;}\n.orderable-dragging {opacity:0.2; width:auto;}\n.orderable-selected {}\n.orderable-avatar {background-color:#666666; border:1px solid #666666; height:25px; width:50px; z-index:65535;}\ndiv .orderable-drop-marker {background-color:#FA7019; height:10px !important;}\n.drop-warning {background-color:#FFD7D7; border:2px solid red; display:none; left:10px; margin:5px; padding:10px; position:absolute; top:50px; z-index:65535;}\n.orderable-drop-marker-box {background-color:#FFFFFF; border:2px dashed #AAAAAA; height:200px !important; margin-bottom:1em; width:97%;}\n\n/*\n * INSERT MORE DROPDOWN\n */\n.insert_more_menu{position:absolute;left:5px;top:5px;border:1px solid #ccc;background-color:#fff;font-size:.95em!important;}\n.insert_more_menu_border{border-bottom:1px solid #ccc;}\n.insert_more_menu ul{padding:5px 15px 5px 7px;margin:0;}\n.insert_more_menu li{list-style-type:none;}\n.insert_more_menu_inactive{color:#aaa;}\n\n\n/*\n * DROPDOWN MENU\n */\n.s3d-dropdown-menu {display: inline-block;list-style: none outside none;margin-top:4px;padding:0;cursor:pointer; margin-left:-2px;}\n.s3d-dropdown-menu:hover {background: url(\"/devwidgets/topnavigation/images/topnav_nav_hover.png\") repeat-x scroll left top #3480b2;-moz-border-radius:2px 2px 2px 2px; border-radius:2px 2px 2px 2px; -webkit-border-radius:2px 2px 2px 2px;padding:0px;}\n.s3d-dropdown-menu ul, .s3d-dropdown-menu .s3d-dropdown-menu-content-container {margin:0;padding: 10px 7px;display:block;background-color: #F3F3F3;-moz-border-radius:2px; border-radius:2px; -webkit-border-radius:2px;}\n.s3d-dropdown-menu ul li {display:block; list-style:none;padding:1px;margin:0 2px;cursor:pointer;color:#636363; text-decoration:none; font-weight:normal;}\n.s3d-dropdown-menu ul li:hover {background:url(\"/devwidgets/topnavigation/images/topnav_nav_list_hover.png\") repeat-x scroll left top transparent;}\n.s3d-dropdown-menu ul li a {text-decoration:none;display:block;padding:5px 6px;}\n.s3d-dropdown-menu ul li:hover a {color:#f3f3f3;}\n.s3d-dropdown-menu ul li a {color:#2683bc;font-size:12px;}\n.s3d-dropdown-menu .s3d-dropdown-container {background:url(\"/devwidgets/topnavigation/images/topnav_nav_hover_list_bg.png\") repeat-x scroll left top #0c4e79;-moz-border-radius:0 0 5px 5px; border-radius:0 0 5px 5px; -webkit-border-radius:0 0 5px 5px;-moz-box-shadow:0 10px 10px -3px #333333; -webkit-box-shadow:0 10px 10px -3px #333333; box-shadow:0 10px 10px -3px #333333;position:absolute;z-index:999;min-width:140px;padding:5px;-moz-border-radius:0 2px 2px 2px; border-radius:0 2px 2px 2px; -webkit-border-radius:0 2px 2px 2px;cursor:auto;}\n.s3d-split-line {background-color:none;border:medium none;border-top:1px dotted #d4d4d4;height: 1px;margin: 3px 9px;}\n\n/*\n * MARGINS\n */\n.s3d-margin-top-3 {margin-top: 3px !important;}\n.s3d-margin-top-5 {margin-top: 5px !important;}\n.s3d-margin-top-10 {margin-top: 10px !important;}\n.s3d-margin-top-15 {margin-top: 15px !important;}\n.s3d-margin-top-20 {margin-top: 20px !important;}\n.s3d-button.s3d-margin-top-5 {height:19px;line-height:19px;}\n.s3d-button.s3d-no-margin-top {margin-top:0;height:18px !important;line-height:18px;}\n/* \n * LINKS\n */\na{color:#333;text-decoration:none;}\na:hover{text-decoration:underline;}\n.s3d-add_another_location{clear:both;color:#39C;font-size:13px;font-weight:bold;background:url(/dev/images/icons_sprite.png) no-repeat scroll left -21px transparent;float:left;width:16px;height:16px;display:block;margin-right:6px;}\n.s3d-add_another_location_container{clear:both;display:block;padding:7px 0;width:200px;}\n.s3d-hidden,.i18nable{display:none;}\n.s3d-bold{font-weight:bold;}\na.s3d-regular-links,.s3d-regular-links a, button.s3d-regular-links, .s3d-regular-links button{color:#2683bc;}\na.s3d-widget-links,.s3d-widget-links a, button.s3d-widget-links, .s3d-widget-links button{color:#2683bc; font-size:0.9em;}\n.s3d-regular-light-links,.s3d-regular-light-links a,.s3d-regular-light-links button{color:#058EC4 !important;}\n.s3d-content-type-link a{color:#5FB3D2;}\n.s3d-remove-links{float:right;margin-right:10px;height:16px;}\n.s3d-tab-active a{background-color:#FFF!important;color:#000!important;font-weight:400!important;border-color:#DDD #DDD #EEE;border-style:solid;border-width:1px;}\n\n/* new path used when creating pages */\n.content_container .new_page_path {line-height: 3em;color:#999;}\n.content_container .new_page_path span {color:#000;}\n\n/* PAGE HEADERS */\n.s3d-page-header-top-row {clear:both;margin-bottom:10px;}\n.s3d-page-header-top-row .s3d-search-inputfield {width:220px;}\n.s3d-page-header-top-row .s3d-page-header-sort-area {float:right;}\n.s3d-page-header-top-row .s3d-page-header-sort-area select {border:1px solid #999;}\n.s3d-page-header-bottom-row {line-height:30px;margin-bottom:15px;}\n.s3d-page-header-bottom-row button, .s3d-page-header-bottom-row .s3d-page-header-selectall {margin-top:6px;}\n.s3d-page-header-bottom-row .s3d-page-header-selectall {height:21px !important;line-height:23px;padding:0 6px 0 5px;width:13px;float:left;}\n.s3d-page-header-bottom-row .s3d-button .s3d-page-header-add-to-icon {background: url(\"/dev/images/savecontent_button_icon_16x16.png\") no-repeat scroll left center transparent;display:block;float:right;height:18px;margin-left:5px;width:16px;}\n.s3d-page-header-bottom-row .s3d-button:hover .s3d-page-header-add-to-icon {background:url(\"/dev/images/savecontent_button_icon_16x16_hover.png\") no-repeat scroll left center transparent;}\n.s3d-page-header-bottom-row .s3d-button[disabled]:hover .s3d-page-header-add-to-icon {background: url(\"/dev/images/savecontent_button_icon_16x16.png\") no-repeat scroll left center transparent;}\n\n/* LIST VIEW OPTIONS */\n.s3d-listview-options {float:right;padding:0 !important;height:19px !important;margin-top:4px;margin-left:20px;border-radius:3px !important;-moz-border-radius:3px !important;-webkit-border-radius:3px !important;}\n.s3d-listview-options:hover {background:#fff;box-shadow:0 0 4px -2px #A8A8A8 inset;}\n.s3d-listview-options > div {float:left;height:15px;padding:3px 4px 2px;}\n.s3d-listview-options > div.selected,\n.s3d-listview-options > div:hover {background:url(\"/dev/images/button_header_hover.png\") repeat-x scroll left -1px transparent;box-shadow:0 0 4px -2px #A8A8A8 inset;} \n.s3d-listview-options > div:last-child {border-radius:0 3px 3px 0;}\n.s3d-listview-options > div:first-child {border-radius:3px 0 0 3px;}\n\n/*\n * BUTTONS \n */\n.s3d-sprites-buttons{background-color:#FFF;padding:0;position:absolute;left:0;top:0;display:block;width:106px;margin:0;}\n.s3d-sprites-buttons ul{margin:0;border:1px solid #cbd0d4;-moz-border-radius:4px;-webkit-border-radius:4px;border-radius:4px;}\n.s3d-sprites-buttons ul li{padding:5px 0 5px 9px;list-style-type:none;}\n.s3d-sprites-buttons ul li:hover{background-color:#dbeefc;cursor:pointer;}\n.s3d-sprites-buttons ul li a{font-weight:400;font-size:12px;}\n.s3d-sprites-buttons ul li a:hover{text-decoration:none;}\n.s3d-sprites-buttons ul li.more_option{border-bottom:1px solid #cbd0d4;}\n.s3d-sprites-buttons ul li.more_option.option_last{border-bottom:0;}\n.s3d-sprites-buttons .more_link{background:transparent url(\"/dev/images/more_bg_18.png\") top left no-repeat;padding:1px 21px 2px 12px;}\n\n/* New button style */\n/* General */\n.s3d-button {border-radius:5px 5px 5px 5px;color:#666;height:27px;padding:1px 12px 0;cursor:pointer;font-weight:bold;font-size:11px;text-align:center;margin-right:5px;border:none;}\nbutton.s3d-button:focus {box-shadow:0 0 2px 1px #2683BC;}\na.s3d-button {text-decoration:none;}\n\n/* Link buttons */\n.s3d-link-button {margin:0;padding:0;background: none repeat scroll 0 0 transparent;border: medium none;color:#2683bc;font-family: Arial,Helvetica,sans-serif;font-size:13px;display: inline-block;text-align:left;font-size:11px;}\n.s3d-link-button:disabled {cursor:default !important;}\n.s3d-link-button:focus {box-shadow:none !important;}\n.s3d-link-button:hover {cursor:pointer;text-decoration:none;color:#999;}\n.s3d-link-button::-moz-focus-inner {padding:0;margin:0;border:0;}\n\n/* Header buttons */\n.s3d-button.s3d-header-button {background:#fff;box-shadow:0 0 4px -2px #A8A8A8 inset;border:1px solid #e0e3e5;}\n.s3d-button.s3d-header-button:hover, .s3d-button.s3d-header-button.selected {background:url(\"/dev/images/button_header_hover.png\") repeat-x scroll left -1px transparent;border:1px solid #E0E3E5;box-shadow:none;}\n.s3d-button.s3d-header-button:disabled {background:#fff;cursor:auto;color:#ccc}\n.s3d-button.s3d-header-button:disabled:hover {background:#fff;box-shadow:0 0 4px -2px #A8A8A8 inset;border:1px solid #e0e3e5;}\na.s3d-button.s3d-header-button {height:24px;line-height:24px;}\n\n/* Left pop out buttons */\n.s3d-popout-button-shadow {background:url(\"/dev/images/button_popout_border_shadow.png\") no-repeat scroll left top transparent;float:left;height:56px;margin-left:-10px;margin-top:-12px;position:absolute;width:20px;}\n.s3d-button.s3d-header-button.s3d-popout-button {color:#666;padding:0 5px 0 10px;font-size:13px;height:30px;}\n.s3d-button.s3d-header-button.s3d-popout-button:hover {background:url(\"/dev/images/button_popout_hover.png\") repeat-x scroll left -1px transparent;border:1px solid #31b2eb;color:#fff;}\n.s3d-button.s3d-header-button.s3d-popout-button:disabled {background:#fff;cursor:auto;color:#ccc}\n.s3d-button.s3d-header-button.s3d-popout-button:disabled:hover {background:#fff;;border:1px solid #E0E3E5;box-shadow:0 0 4px -2px #A8A8A8 inset;}\n.s3d-button.s3d-header-button.s3d-popout-button > span {display:inline-block;float:right;font-size:18px;margin-left:4px;}\n\n/* Header buttons, smaller */\n.s3d-button.s3d-header-button.s3d-header-smaller-button,\na.s3d-button.s3d-header-button.s3d-header-smaller-button {font-size:10px;height:23px;padding:0 5px;line-height:19px;}\na.s3d-button.s3d-header-button.s3d-header-smaller-button {display:inline-block;height:22px;padding:0 8px;}\n\n/* Regular in-page buttons */\n.s3d-button.s3d-regular-button{background:url(\"/dev/images/button_regular_default.png\") repeat-x scroll left top transparent;height:24px;padding:0 7px;border:1px solid #e0e3e5;color:#666;box-shadow:0 1px 1px 0 #999;text-shadow:0 2px 3px #fff;}\n.s3d-button.s3d-regular-button:hover{background:url(\"/dev/images/button_regular_hover.png\") repeat-x scroll left top transparent;}\na.s3d-button.s3d-regular-button{height:24px;line-height:24px;}\n\n/* Large in-page buttons */\n.s3d-button.s3d-large-button {background:url(\"/dev/images/button_large_default.png\") repeat-x scroll left top transparent;height:31px;padding:0 7px;border:1px solid #e0e3e5;color:#2683bc;box-shadow:0 1px 1px 0 #999;text-shadow:0 2px 3px #fff;font-size:13px;}\n.s3d-button.s3d-large-button:hover {background:url(\"/dev/images/button_large_hover.png\") repeat-x scroll left top transparent;color:#999;}\n.s3d-button.s3d-large-button.grey {color:#666;}\na.s3d-button.s3d-large-button {line-height:31px;}\n\n/* Overlay buttons */\n.s3d-button.s3d-overlay-button {background:url(\"/dev/images/button_overlay_default.png\") repeat-x scroll left top transparent;border:1px solid #E0E3E5;font-size:11px;font-weight:bold;height:24px;margin-left:15px;box-shadow:0 1px 1px 0 #999;text-shadow:0 2px 3px #fff;color:#2683bc;}\n.s3d-button.s3d-overlay-button:hover {background:url(\"/dev/images/button_overlay_hover.png\") repeat-x scroll left top transparent;}\n.s3d-button.s3d-overlay-button:disabled {color:#ccc;}\n.s3d-button.s3d-overlay-button:disabled:hover {background:url(\"/dev/images/button_overlay_default.png\") repeat-x scroll left top transparent;cursor:auto;}\na.s3d-button.s3d-overlay-button {display:inline-block;height:21px;line-height:21px;}\n\n/* Overlay Action buttons */\n.s3d-button.s3d-overlay-action-button {background:url(\"/dev/images/button_overlay_action_default.png\") repeat-x scroll left top transparent;font-size:11px;font-weight:bold;height:25px;margin-left:15px;box-shadow:0 1px 2px 0 #222;color:#fff;padding:0 5px;}\n.s3d-button.s3d-overlay-action-button:hover, .s3d-button.s3d-overlay-action-button:focus {background:url(\"/dev/images/button_overlay_action_hover.png\") repeat-x scroll left top transparent;color:#22AAE7;}\n.s3d-button.s3d-overlay-action-button:disabled {color:#ccc;}\n.s3d-button.s3d-overlay-action-button:disabled:hover {background:url(\"/dev/images/button_overlay_action_default.png\") repeat-x scroll left top transparent;cursor:auto;}\n\n.s3d-button.s3d-overlay-button.grey, .s3d-button.s3d-overlay-action-button.grey {color:#666;}\n\n/* No text buttons */\n.s3d-button.s3d-button-no-text {padding:0 !important;}\n\n/* Button in another button */\n.s3d-button .s3d-button-in-button {background:url(\"/dev/images/button_in_button_default.png\") repeat-x top left #5d6267;color:#fff;display:inline;height:15px;line-height:15px;margin:0 0 0 5px;padding:2px 4px;border:1px solid #4f4f4f;}\n.s3d-button .s3d-button-in-button-lighter {background:url(\"/dev/images/button_in_button_light_default.png\") repeat-x scroll left top #CBC9C9;border:1px solid #B5B5B5;color:#fff;display:inline;height:12px;line-height:12px;margin:2px 9px 0 -3px;padding:0 4px;float:left;}\n\n.s3d-button.s3d-overlay-action-button .s3d-button-in-button {display:inline-block;margin-top:-3px;}\n\n/*\n * WIDGET LAYOUT\n */\n.s3d-widget-titlebar{background:url(/dev/images/dashboard_sprite.png) no-repeat scroll right -473px transparent;padding:0 10px 0 0;min-height:49px;}\n.s3d-widget-titlebar-inner{background:url(/dev/images/dashboard_sprite.png) no-repeat scroll -10px -570px transparent;padding:0 0 0 5px;min-height:50px;}\n.s3d-widget .s3d-widget-content,.s3d-content{padding:10px 0;margin:0!important;border-left:3px solid #D4DADE;border-right:3px solid #D4DADE;}\n.s3d-widget .s3d-widget-options-footer-left{background:url(/dev/images/dashboard_sprite.png) no-repeat scroll -70px -436px #D5DBDF;height:12px;}\n.s3d-widget-small-content{padding:5px 0!important;}\n.fl-widget { margin-bottom :7px;}\n.fl-widget .fl-widget-options-footer-top{background:url(/dev/images/dashboard_sprite.png) no-repeat scroll -10px -528px #D5DBDF;height:16px;}\n.fl-widget .fl-widget-options .fl-widget-options-top-right{background:url(/dev/images/dashboard_sprite.png) no-repeat scroll right -432px transparent;float:right;height:16px;padding:0 0 7px 14px;width:16px;}\n.s3d-widget .s3d-widget-options-footer-right{background:url(/dev/images/dashboard_sprite.png) no-repeat scroll right -456px #D5DBDF;float:right;height:12px;width:16px;}\n.s3d-widget .s3d-widget-no-options,.s3d-no-options{background:url(/dev/images/dashboard_sprite.png) no-repeat scroll right -1453px transparent;padding:0 5px 0 0;margin:0;}\n.s3d-widget .s3d-widget-no-options-inner,.s3d-no-options-inner{background:url(/dev/images/dashboard_sprite.png) no-repeat scroll -10px -1433px transparent;margin:0;height:6px;}\n\n.fl-col-flex2 .fl-col{margin-left:5px;margin-right:0;padding-left:0;padding-right:0;width:353px;margin-right:8px;}\n.fl-col-flex2 .fl-col:last-child {margin-right:0;}\n.fl-col-flex3 .fl-col{margin-left:5px;margin-right:0;padding-left:0;padding-right:0;width:230px;margin-right:8px;}\n.fl-col-flex3 .fl-col:last-child {margin-right:0;}\n\n.s3d-inset-shadow-container {background-color:#ededed;border:1px solid #ededed;border-radius:5px;-moz-border-radius:5px;-webkit-border-radius:5px;box-shadow:inset 0 5px 5px -5px #888888;-moz-box-shadow:inset 0 5px 5px -5px #888888;-webkit-box-shadow:inset 0 5px 5px -5px #888888;}\n.s3d-outer-shadow-container {background-color:#FFF;border-radius:4px;box-shadow:0 1px 1px 0 #BBB;-moz-box-shadow:0 1px 1px 0 #BBB;-webkit-box-shadow:0 1px 1px 0 #BBB;margin:0 3px 3px 0;padding:15px 13px 11px;}\n\n/*\n * SEARCH BOXES\n */\n.s3d-search-container .s3d-search-inputfield {height: 22px;padding: 0 4px;color: #333;font-size: 12px;border:1px solid #ccc !important;float:left;}\n.s3d-search-container input::-webkit-input-placeholder {color:#7c7b7b;font-style:italic;font-size:11px !important;}\n.s3d-search-container input:-moz-placeholder{color:#7c7b7b;font-style:italic;font-size:11px !important;}\n.s3d-search-container .s3d-search-button {height:25px !important;width:24px;padding:3px 0 0 0 !important;margin-left:2px;background:none !important;border: none !important;box-shadow:none !important;-moz-box-shadow:none !important;-webkit-box-shadow:none !important;}\n.s3d-search-container .s3d-search-button:hover, .s3d-search-container .s3d-search-button:focus {background: url(\"/dev/images/searchbutton_hover_bg.png\") repeat-x top left transparent !important;border:1px solid #ccc !important;}\n.s3d-search-container .s3d-search-button img {margin:0 auto;}\n.s3d-search-container .s3d-search-button .s3d-search-button-icon{margin:0 auto;display:block;width:16px;height:19px;background: url(\"/dev/images/search_icon.png\") no-repeat top left transparent;}\n\n/*\n * NO RESULTS VIEW (When a widget feed doesn't return any results)\n */\n.s3d-no-results-container {background: url(\"/dev/images/noresults_bg.png\") repeat scroll left top transparent;-moz-border-radius:5px;border-radius:5px;padding:20px;margin:30px 0px 0px;list-style:none}\n.s3d-no-results-container .s3d-no-results-arrow-up {background:url(\"/dev/images/noresults_arrow_up.png\") no-repeat top left transparent;position:absolute;margin-top:-44px;width:36px;height:24px;}\n.s3d-no-results-container h1 {color:#666;font-size:18px;font-weight:normal;margin:5px 0 10px 0 !important;}\n.s3d-no-results-container h1 button{font-size:18px;}\n.s3d-no-results-container .s3d-no-results-icon {width:55px;height:50px;float:left;margin:0 12px 0 0;}\n.s3d-no-results-container .s3d-no-results-icon.less-margin {margin:-8px 12px 0 0;}\n\n.s3d-no-results-container .s3d-no-results-magnifier {background:url(\"/dev/images/magnifier_icon_55x55.png\") no-repeat top left transparent;}\n.s3d-no-results-container .s3d-no-results-world {background:url(\"/dev/images/world_icon_55x55.png\") no-repeat top left transparent;}\n.s3d-no-results-container .s3d-no-results-people {background:url(\"/dev/images/person_icon_55x55.png\") no-repeat top left transparent;}\n.s3d-no-results-container .s3d-no-results-content {background:url(\"/dev/images/content_icon_55x55.png\") no-repeat top left transparent;}\n.s3d-no-results-container .s3d-no-results-content-small {background:url(\"/dev/images/content_icon_42x46.png\") no-repeat top left transparent;width:46px;height:42px;}\n.s3d-no-results-container .s3d-no-results-memberships {background:url(\"/dev/images/memberships_icon_60x55.png\") no-repeat top left transparent;width:60px;}\n.s3d-no-results-container .s3d-no-results-memberships-small {background:url(\"/dev/images/memberships_icon_42x46.png\") no-repeat top left transparent;width:46px;height:42px;}\n.s3d-no-results-container .s3d-no-results-contacts {background:url(\"/dev/images/contacts_icon_60x55.png\") no-repeat top left transparent;width:60px;}\n.s3d-no-results-container .s3d-no-results-contacts-small {background:url(\"/dev/images/contacts_icon_42x46.png\") no-repeat top left transparent;width:46px;height:42px;}\n.s3d-no-results-container .s3d-no-results-replied {background:url(\"/dev/images/replied_icon_55x55.png\") no-repeat top left transparent;}\n.s3d-no-results-container .s3d-no-results-trash {background:url(\"/dev/images/trash_icon_55x55.png\") no-repeat top left transparent;}\n.s3d-no-results-container .s3d-no-results-upload {background:url(\"/dev/images/upload_icon_42x46.png\") no-repeat top left transparent;width:46px;height:42px;}\n.s3d-no-results-container .s3d-no-results-search-messages {background:url(\"/dev/images/no-messages-found-icon.png\") no-repeat top left transparent;width:46px;height:42px;}\n.s3d-no-results-container .s3d-no-results-search-world {background:url(\"/dev/images/world_search_icon_55x55.png\") no-repeat scroll left top transparent;}\n.s3d-no-results-container .s3d-no-results-search-people {background:url(\"/dev/images/people_search_icon_55x55.png\") no-repeat scroll left top transparent;}\n.s3d-no-results-container .s3d-no-results-search-content {background:url(\"/dev/images/content_search_icon_55x55.png\") no-repeat scroll left top transparent;}\n.s3d-no-results-container .s3d-no-results-sakai2sites {background:url(\"/dev/images/sakai2_icon_43x40.png\") no-repeat top left transparent;width:46px;height:45px;}\n\n\n\n.s3d-action-icon {width:16px;height:16px;cursor:pointer;}\n.s3d-action-icon.disabled {display:none;}\n\n.s3d-actions-delete {background:url(\"/dev/images/delete_icon_default.png\") no-repeat top left transparent;}\n.s3d-actions-delete:hover {background:url(\"/dev/images/delete_icon_hover.png\") no-repeat top left transparent;}\n\n.s3d-actions-addtolibrary {background:url(\"/dev/images/addtolibrary_icon_default.png\") no-repeat top left transparent; width: 17px; height: 25px;}\n.s3d-actions-addtolibrary:hover {background:url(\"/dev/images/addtolibrary_icon_hover.png\") no-repeat top left transparent;}\n\n.s3d-actions-author {background:url(\"/dev/images/author_icon_default.png\") no-repeat scroll left top transparent;width:32px !important;}\n.s3d-actions-author:hover {background:url(\"/dev/images/author_icon_hover.png\") no-repeat scroll left top transparent;}\n\n.s3d-actions-share {background:url(\"/dev/images/share_icon_default.png\") no-repeat scroll left top transparent; width: 23px !important;}\n.s3d-actions-share:hover {background:url(\"/dev/images/share_icon_hover.png\") no-repeat scroll left top transparent;}\n\n.s3d-actions-message {background:url(\"/dev/images/message_icon_default.png\") no-repeat scroll left top transparent;}\n.s3d-actions-message:hover {background:url(\"/dev/images/message_icon_hover.png\") no-repeat scroll left top transparent;}\n.s3d-button:hover .s3d-actions-message {background:url(\"/dev/images/message_icon_hover.png\") no-repeat scroll left top transparent;}\n.s3d-button:disabled:hover .s3d-actions-message {background:url(\"/dev/images/message_icon_default.png\") no-repeat scroll left top transparent;}\n\n/*\n * CONTENT LAYOUT \n */\n.s3d-header .s3d-fixed-container .s3d-decor-left{background:url(/dev/images/dashboard_sprite.png) no-repeat scroll 0 -10px transparent;float:left;height:5px;margin-left:-20px;overflow:visible;width:5px;}\n.s3d-header .s3d-fixed-container .s3d-decor{background:url(/dev/images/dashboard_sprite.png) no-repeat scroll right -10px transparent;float:right;height:5px;margin-right:-20px;width:5px;position:relative;*right:-15px;}\n.s3d-main-container{background:#fff;}\n\n\n/*\n * CHROME STYLES\n * HEADINGS\n */\n.s3d-site-heading{padding:10px 0;font-weight:bold;color:#454A4F;}\n.s3d-site-heading h1{margin:0;padding:0;}\n\n\n/* PROGRAMMATICALLY SET STYLES\n * styles used to programmatically set placement of widgets on the page\n */\n.inline_class_widget_rightfloat{float:right; padding: 5px 0px 5px 10px;}\n.inline_class_widget_leftfloat{float:left; padding: 5px 10px 5px 0px;}\n\n\n/*\n * ACTIONS\n * links used to trigger an action\n * default styling: bold blue link\n * Variants:\n * - action series: links are inside list items, each list item is separated by a divider\n */\na.s3d-action,.s3d-actions a{color:#2683bc;font-weight:bold;font-size:13px;}\na.s3d-action-seeall{font-size:11px!important;}\n\n/* Primary button */\n.s3d-button-primary{background-position:right -110px;}\n.s3d-button-primary .s3d-button-inner{background-position:left -110px;}\n\n/* Search button */\n.s3d-search-button{padding-right:8px;}\n.s3d-search-button .s3d-button-icon-right{padding-right:22px;background-image:url(/dev/images/dashboard_sprite.png);background-position:42px -394px;display:inline;}\n\n\n/*\n * CONTEXT MENU FOR DROPDOWNS\n */.context_menu{left:18px;padding:0;position:absolute;top:124px;}\n.context_menu img{border:1px solid #555;border-bottom:none;}\n.context_menu ul{margin:0;margin-top:-3px;background-color:#eee;border:1px solid #555;}\n.context_menu ul li{list-style-type:none;}\n.context_menu ul li a{color:#666;font-size:.95em;display:block;padding:2px 20px 2px 4px;}\n\n\n/*\n * INPUT FIELDS\n */\ninput[type=text], input[type=password], input[type=email], input[type=url], textarea{border:1px solid #A9A9A9;}\n\n/*\n * CONTENT AREA TOP TABS\n */.s3d-primary-tabs{background:url(/dev/images/dashboard_sprite.png) no-repeat scroll right -1622px transparent;}\n.s3d-primary-tabs,.s3d-primary-tabs-inner{height:25px;border:none;padding:2px 5px 0;display:block;}\n.s3d-primary-tabs ul.fl-tabs{border:none;padding:0;margin:0;float:right;background:url(/dev/images/dashboard_sprite.png) no-repeat scroll left -1592px transparent;padding-left:20px;}\n.s3d-primary-tabs .fl-tabs-right li{margin-top:3px;}\n.s3d-primary-tabs ul.fl-tabs-left{float:left;padding:1px 0 0 3px;}\n.s3d-primary-tabs ul li{margin:0;margin-top:2px;padding:0;background:transparent;border:none;display:block;float:left;}\n.s3d-primary-tabs ul li a{padding:2px 18px 4px 13px;line-height:20px;background:transparent;border:none;font-weight:bold;color:#000;display:block;float:left;margin:0;position:relative;bottom:0!important;}\n.s3d-primary-tabs ul li.fl-tabs-active,.s3d-primary-tabs ul li.fl-tabs-active a{background-color:#FFF;background-image:url(/dev/images/dashboard_sprite.png);background-attachment:scroll;height:30px;bottom:0!important;position:relative;}\n.s3d-primary-tabs ul li.fl-tabs-active{padding-left:5px;background-position:left -1664px;}\n.s3d-primary-tabs ul li.fl-tabs-active a{background-position:right -1714px;font-weight:400;border:none;padding-left:15px;margin:0;}\n.fl-tab-content{border:none;margin:0;}\n\n\n/*\n * AUTOSUGGEST\n */\n.requireUser ul.as-selections{box-shadow:none;-webkit-box-shadow:none;-moz-box-shadow:none;border:1px solid #a9a9a9;}\nul.as-selections.loading{background:#fff url(../../../dev/images/ajax_load.gif) center center no-repeat;}\nul.as-selections li.as-original input {border:0;}\nul.as-selections textarea.as-input, ul.as-selections input.as-input{border:0;resize:none;}\nul.as-selections textarea.as-input{padding:0;}\n.autosuggest_wrapper{float:left;position:relative;width:100%;}\n.autosuggest_wrapper ul.as-list{top:100%;margin-top:-15px;}\n.autosuggest_wrapper .list_categories{float:right;}\n.autosuggest_wrapper textarea {overflow:hidden;}\n\n/* http://blogs.sitepoint.com/2005/02/26/simple-clearing-of-floats/ */\n.clearfix{overflow:auto;}\n\n\n /*\n * OLD DIALOG LAYOUT\n */\n.dialog{color:#333;display:none;left:50%;margin-left:-250px;position:absolute;top:12%;width:500px;}\n.jqmOverlay{background-color:#000;opacity:0.6 !important}\n\n/* Dialog header */\n.dialog_header{background:url(/dev/images/dashboard_sprite.png) no-repeat scroll right -641px transparent;padding:0 8px 0 0;}\n.dialog_header_inner{background:url(/dev/images/dashboard_sprite.png) no-repeat scroll -10px -819px transparent;}\n.dialog_header h1{color:#fff;display:block;font-size:1.1em;margin:0;padding:15px 20px;}\n.dialog_header .dialog_close_image{background:url(/dev/images/dashboard_sprite.png) no-repeat scroll -40px -641px transparent;cursor:pointer;display:block;height:15px;overflow:hidden;position:absolute;right:20px;top:17px;text-indent:-5000px;width:14px;}\n\n/* Dialog content */\n.dialog_content{background-color:#fff;border-left:3px #454a4f solid;border-right:3px #454a4f solid;padding:7px 20px;}\n.dialog_content h1{font-size:1.1em;font-weight:bold;color:#333;margin:0;padding:5px 0;}\n.dialog_content textarea{height:80px;width:98%;padding: 5px;}\n\n/* Dialog buttons */\n.dialog_buttons{clear:both;margin-top:20px;float:right;}\n\n/* Dialog footer */\n.dialog_footer{background:url(/dev/images/dashboard_sprite.png) no-repeat scroll right -957px transparent;padding:0 8px 0 0;}\n.dialog_footer_inner{background:url(/dev/images/dashboard_sprite.png) no-repeat scroll -10px -937px transparent;height:6px;}\n\n/* Dialog tooltip header */\n.dialog_tooltip_header_arrow{background:url(/dev/images/tour_sprite.png) no-repeat scroll -254px -76px transparent;height:18px;margin:0 0 0 20px;width:35px;}\n.dialog_tooltip_header{background:url(/dev/images/tour_sprite.png) no-repeat scroll right -20px transparent;padding:0 22px 0 0;}\n.dialog_tooltip_header_inner{background:url(/dev/images/tour_sprite.png) no-repeat scroll left top transparent;height:14px;}\n\n/* Dialog tooltip content */\n.dialog_tooltip_close{float:right;}\n.dialog_tooltip_content{background:url(/dev/images/tour_sprite.png) no-repeat scroll left -80px transparent;padding:7px 20px 0;}\n.dialog_tooltip_content h2{font-size:1.1em;font-weight:bold;color:#333;margin:0;padding:0 0 5px;}\n.dialog_tooltip_content p{font-size:.9em;}\n.dialog_tooltip_content textarea{height:80px;width:98%;}\n\n/* Dialog tooltip footer */\n.dialog_tooltip_footer{background:url(/dev/images/tour_sprite.png) no-repeat scroll right -60px transparent;padding:0 22px 0 0;}\n.dialog_tooltip_footer_inner{background:url(/dev/images/tour_sprite.png) no-repeat scroll left -40px transparent;height:14px;}\n.dialog_tooltip_footer_arrow{background:url(/dev/images/tour_sprite.png) no-repeat scroll -217px -80px transparent;width:35px;height:18px;margin:0 0 0 20px;}\n\n/*\n * NEW DIALOG LAYOUT\n */\n.s3d-dialog{color:#333;display:none;left:50%;margin-left:-250px;position:absolute;top:50px;width:500px;}\n.s3d-dialog-container {background-color:#fff; border:1px solid #a9a9a9; -moz-border-radius:5px;border-radius:5px;padding:7px 20px 12px;box-shadow:0 0 10px #000;-moz-box-shadow:0 0 10px #000;-webkit-box-shadow:0 0 10px #000;color:#424242;font-size:12px;}\n.s3d-dialog-container .s3d-dialog-close {background:url(\"/dev/images/dialog_close.png\") no-repeat top left transparent;width:19px;height:17px;float:right;cursor:pointer;margin:-2px -15px 0 0;}\n.s3d-dialog-container .s3d-dialog-close:hover {background:url(\"/dev/images/dialog_close.png\") no-repeat left -19px transparent;}\n.s3d-dialog-container h1.s3d-dialog-header {border-bottom:1px dotted #d4d4d4;color:#666;font-size:19px;font-weight:normal;padding-bottom:11px;margin-bottom:15px;}\n\n/* Widget bar item counts */\n.s3d-counts-outer{padding:3px 2px;background:#fff;border:1px solid #D6D9DB;border-radius:5px;-moz-border-radius:5px;-webkit-border-radius:5px;box-shadow:0 0 4px -2px #A8A8A8 inset;-webkit-box-shadow:0 0 4px -2px #A8A8A8 inset;-moz-box-shadow:0 0 4px -2px #A8A8A8 inset; font-size: 11px; position: relative; top: -1px; margin-left: 5px;}\n.s3d-counts-outer a{padding-right:6px;color:#707070;}\n.s3d-counts-inner{color:#fff;padding:0px 4px;background:#D4D4D4;border:1px solid #CACACA;border-radius:5px;-moz-border-radius:5px;-webkit-border-radius:5px;box-shadow:0 0 4px -2px #A2A2A2 inset;-webkit-box-shadow:0 0 4px -2px #A2A2A2 inset;-moz-box-shadow:0 0 4px -2px #A2A2A2 inset;}\n\n/*\n * CHAT\n */\n.chat_available_status_online{background:url(/dev/images/dashboard_sprite.png) no-repeat scroll -33px -395px transparent;}\n.chat_available_status_busy{background:url(/dev/images/dashboard_sprite.png) no-repeat scroll -63px -395px transparent;}\n.chat_available_status_offline{background:url(/dev/images/dashboard_sprite.png) no-repeat scroll -93px -395px transparent;}\n.chat_available_status_offline,.chat_available_status_busy,.chat_available_status_online{padding-left:15px;}\n\n\n/*\n * LISTS\n */\n.s3d-list-item{list-style:none outside none;padding:5px 0 5px 10px!important;margin:0!important;clear:both;overflow:hidden;}\n.s3d-list-entity-picture{float:left;height:32px;margin-right:10px;width:32px;}\n.s3d-entity-displayname{padding-top:4px;margin:4px 0 0 8px;float:left;}\n.s3d-list-link-full-space{clear:both;height:100%;}\nul li.s3d-list-item:hover{background-color:#f1f9fd;}\n\n.s3d-dropdownlistone-text{padding:0 7px;border-right:none;color:#fff;font-size:11px;}\n.s3d-dropdownlistone-text .dropdownlistone_arrow{background:url(/dev/images/dashboard_sprite.png) no-repeat scroll -149px -394px transparent;padding-right:17px;padding-left:8px;}\n.s3d-dropdownlistone-menu{background-color:#868a8d;line-height:16px;position:absolute;z-index:500;padding:0 0 6px;min-width:100px;}\n.s3d-dropdownlistone-menu div{margin-top:5px;}\n.s3d-dropdownlistone-menu ul{margin:0;padding:0;}\n.s3d-dropdownlistone-menu li{display:block;list-style-type:none;margin:0;padding:3px 5px 6px 13px;}\n.s3d-dropdownlistone-menu li a{border:none;color:#fff;padding:0;}\n.s3d-dropdownlistone-menu li a:hover, .s3d-dropdownlistone-menu li button:hover{color:#ddd;}\n.s3d-dropdownlistone-menu-border{border-bottom:1px solid #777;}\n.s3d-dropdownlistone-link-inactive {color:#aaa;}\n\n.s3d-dropdownlisttwo-text{color: #666666;}\n.s3d-dropdownlisttwo-text span{float:left;}\n.s3d-dropdownlisttwo-text .s3d-dropdownlisttwo-arrow-down{background:url(/dev/images/dashboard_sprite.png) no-repeat scroll -128px -400px transparent;float:left;height: 10px;margin: 6px 0 0 6px;width: 10px;}\n.s3d-dropdownlisttwo-text .s3d-dropdownlisttwo-arrow-up{background:url(/dev/images/dashboard_sprite.png) no-repeat scroll -218px -400px transparent;float:left;height: 10px;margin: 6px 0 0 6px;width: 10px;}\n.s3d-dropdownlisttwo-menu{font-size:.95em!important;left:110px;list-style-image:none;position:absolute;top:29px;z-index:10;margin:0;}\n.s3d-dropdownlisttwo-menu ul{background-color:#fff;border:1px solid #CCC;margin:0;padding:5px 15px 5px 7px;}\n.s3d-dropdownlisttwo-menu li{list-style-type:none;padding:0;}\n\n/*\n * POPOVERS\n */\n.s3d-popover-container {border: 1px solid #EAEBEC;border-top: none;border-radius: 5px;-moz-border-radius: 5px;-webkit-border-radius: 5px;box-shadow: 0px 0px 5px #454545;-moz-box-shadow: 0px 0px 5px #454545;-webkit-box-shadow: 0px 0px 5px #454545;background:url(\"/dev/images/popover_bg.png\") repeat-x scroll left top #f4f4f4;font-size:13px;}\n.s3d-popover-container .s3d-popover-inner {padding:10px;word-wrap:break-word;}\n.s3d-popover-arrowup {background:url(\"/dev/images/popover_arrowup.png\") no-repeat scroll left top transparent;height:13px;margin-left:110px;position:relative;width:33px;}\n\n/* \n * TAGLISTS\n */\n.s3d-taglist-container {max-height:53px;overflow-y:hidden;}\n.s3d-taglist{margin:3px 0 0 20px;text-indent:-20px;}\n.s3d-taglist li{display:inline;list-style:disc;padding: 0;margin:0;list-position:inside}\n.s3d-taglist li a{font-size:11px !important;font-weight:normal !important;}\n.s3d-taglist li:before{content:'\\0020\\00b7\\0020'}\n.s3d-taglist li:first-child:before{content:''}\n.s3d-taglist li:first-child{list-style:none;background:url(\"/devwidgets/entity/images/entity_tags_icon.png\") no-repeat scroll left 1px transparent;padding-left:20px;}\n\n/* \n * HIGHLIGHTED AREAS\n */\n.s3d-highlight_area_background{background-color:#EFF2F4;padding:0 10px;margin:0 0 15px;}\n.s3d-highlight_area_background_tl{height:7px;margin-left:-10px;background:url(/dev/images/dashboard_sprite.png) no-repeat scroll -10px -1037px transparent;}\n.s3d-highlight_area_background_tinner{height:7px;margin-right:-10px;background:url(/dev/images/dashboard_sprite.png) no-repeat scroll right -1047px transparent;}\n.s3d-highlight_area_background_bl{clear:both;height:7px;margin-left:-10px;background:url(/dev/images/dashboard_sprite.png) no-repeat scroll -10px -1057px transparent;}\n.s3d-highlight_area_background_binner{clear:both;height:7px;margin-right:-10px;background:url(/dev/images/dashboard_sprite.png) no-repeat scroll right -1067px transparent;}\n.s3d-highlight_area_background_white_content_tl{height:7px;margin-left:-10px;background:url(/dev/images/dashboard_sprite.png) no-repeat scroll -10px -1198px transparent;}\n.s3d-highlight_area_background_white_content_tinner{height:7px;margin-right:-10px;background:url(/dev/images/dashboard_sprite.png) no-repeat scroll right -1208px transparent;}\n.s3d-highlight_area_background_white_content_bl{clear:both;height:7px;margin-left:-10px;background:url(/dev/images/dashboard_sprite.png) no-repeat scroll -10px -1217px transparent;}\n.s3d-highlight_area_background_white_content_binner{clear:both;height:7px;margin-right:-10px;background:url(/dev/images/dashboard_sprite.png) no-repeat scroll right -1227px transparent;}\n.s3d-highlight_area_background_darker1{background-color:#d5dbdf;padding:0 10px;margin:0 0 15px;}\n.s3d-highlight_area_background_darker1_tl{height:7px;margin-left:-10px;background:url(/dev/images/dashboard_sprite.png) no-repeat scroll -10px -1077px transparent;}\n.s3d-highlight_area_background_darker1_tinner{height:7px;margin-right:-10px;background:url(/dev/images/dashboard_sprite.png) no-repeat scroll right -1087px transparent;}\n.s3d-highlight_area_background_darker1_bl{height:7px;margin-left:-10px;background:url(/dev/images/dashboard_sprite.png) no-repeat scroll -10px -1097px transparent;}\n.s3d-highlight_area_background_darker1_binner{height:7px;margin-right:-10px;background:url(/dev/images/dashboard_sprite.png) no-repeat scroll right -1107px transparent;}\n.s3d-highlight_area_background_darker1_white_content_tl{height:7px;margin-left:-10px;background:url(/dev/images/dashboard_sprite.png) no-repeat scroll -10px -1117px transparent;}\n.s3d-highlight_area_background_darker1_white_content_tinner{height:7px;margin-right:-10px;background:url(/dev/images/dashboard_sprite.png) no-repeat scroll right -1127px transparent;}\n.s3d-highlight_area_background_darker1_white_content_bl{clear:both;height:7px;margin-left:-10px;background:url(/dev/images/dashboard_sprite.png) no-repeat scroll -10px -1137px transparent;}\n.s3d-highlight_area_background_darker1_white_content_binner{clear:both;height:7px;margin-right:-10px;background:url(/dev/images/dashboard_sprite.png) no-repeat scroll right -1147px transparent;}\n\n/*\n * SEARCH\n */\n\n/* SEARCH BAR */\n.s3d-search-bar{margin-left:205px; position: relative; top: -10px;}\n.s3d-search-bar input{color:#6d6d6d !important;width:500px;font-size:1.2em !important;display:block;}\n\n/* SEARCH HEADER */\n.s3d-search-header{text-align:left;font-weight:normal;font-size:1em;color:#666;width:712px;}\n.s3d-search-header{margin-bottom: 5px;padding:5px 5px 8px 10px;background-color:#f5f5f5;border-radius:2px;-moz-border-radius:2px;-webkit-border-radius:2px;box-shadow:0 1px 1px 1px #CCC;-webkit-box-shadow:0 1px 1px 1px #CCC;-moz-box-shadow:0 1px 1px 1px #CCC;}\n.s3d-search-header .s3d-search-header-type{display:inline-block; padding-top: 2px;}\n.s3d-search-header .s3d-search-selects{float:right;}\n.s3d-search-header .s3d-search-selects div{display:inline;float:left;}\n.s3d-search-header .s3d-search-selects select{border: 1px solid #CCCCCC;margin:0;}\n.s3d-search-header .s3d-search-selects .s3d-search-sort{margin-left:10px;}\n\n/* SEARCH REFINE BY TAGS */\n.s3d-search-tag{padding:0;margin:5px 2px 0 2px;}\n.s3d-search-activetags span, .s3d-search-refineby span{display:inline-block;}\n.s3d-search-activetags button{color:#6C6C6C;cursor:pointer;border:1px solid #b4b5b5;border-radius:10px;-moz-border-radius:10px;-webkit-border-radius:10px;background-color:#FEFEFE;}\n.s3d-search-activetags button img{margin-left:8px;}\n.s3d-search-refineby-list{margin-bottom:15px;}\n.s3d-search-refineby .s3d-search-refineby-title{margin-bottom:5px;display:block;color:#64707E;}\n.s3d-search-refineby button{cursor:pointer;color:#585858;border:1px solid #A5BECF;border-radius:10px;-moz-border-radius:10px;-webkit-border-radius:10px;background:url(\"/dev/images/search_tag_button.png\") repeat-x scroll left top #cde6f7;}\n\n/* SEARCH RESULTS */\n.s3d-search-results{display:block; overflow:hidden;width:730px;}\n.s3d-search-results .s3d-search-results-container{margin:10px 0 0;padding:0;border-top: 1px solid #e9e9e9;}\n.s3d-search-result{color:#333;padding:10px;border-bottom: 1px dotted #cccccc;list-style:none}\n.s3d-search-result a img{float:left;padding:0 10px 5px 0;width:40px;}\n.s3d-search-result-right{margin-left:80px;}\n.s3d-search-results .jq_pager{clear:both;border-bottom: 1px solid #e9e9e9;}\n.s3d-search-result-detail-separator{color:#cccccc;margin: 0 5px;}\n.s3d-search-result:hover{background-color:#f2f9fc;}\n\n/* search results common elements in content people and group results */\n.s3d-search-result-content .searchcontent_result_usedin_icon, .s3d-search-result-group .searchgroups_result_usedin_icon{background: url(\"/devwidgets/entity/images/entity_used_by_icon.png\") no-repeat scroll left top transparent;}\n.s3d-search-result-content .searchcontent_result_comments_icon, .s3d-search-result-group .searchgroups_result_comments_icon{background: url(\"/devwidgets/entity/images/entity_comment_icon.png\") no-repeat scroll left top transparent;}\n.s3d-search-result-content .searchcontent_result_left_filler, .s3d-search-result-person .searchpeople_result_left_filler, .s3d-search-result-group .searchgroups_result_left_filler{margin:1px 8px 0 0;display: inline;float: left;height: 25px;width: 17px;}\n.s3d-search-result-content .searchcontent_result_plus, .s3d-search-result-person .searchpeople_result_plus, .s3d-search-result-group .searchgroups_result_plus{color:#e4e4e4;font-size:x-large;font-weight:100;margin:-5px 10px 10px -2px;}\n.s3d-search-result-content .searchcontent_result_icon, .s3d-search-result-person .searchpeople_result_icon, .s3d-search-result-group .searchgroups_result_icon{display:inline-block;height:10px;width:15px;}\n.s3d-search-result-content .searchcontent_result_description, .s3d-search-result-person .searchperson_result_description, .s3d-search-result-group .searchgroup_result_description{word-wrap:break-word;}\n/* search results hide elements used in grid view by default */\n.s3d-search-result-content .searchcontent_result_description_grid, .s3d-search-result-person .searchpeople_result_description_grid, .s3d-search-result-group .searchgroups_result_description_grid,\n.s3d-search-result-name-grid, .s3d-search-result-tag-grid, .s3d-search-result-avatar-large,\n.s3d-search-result-content .searchcontent_result_by_name_grid{display:none;}\n\n/* search results content */\n.s3d-search-result-content .searchcontent_result_description{margin:0 0 5px;color:#333;font-size:11px;padding:6px 0; word-wrap: break-word;}\n.s3d-search-result-content .searchcontent_result_mimetype{font-size:smaller;white-space:pre;text-transform:uppercase;}\n.s3d-search-result-content .searchcontent_result_by{padding:3px 0;font-size:11px;}\n.s3d-search-result-content .searchcontent_result_detail_separator{color:#cccccc;}\n.s3d-search-result-content .searchcontent_result_usedin{margin-top:2px;font-size:11px;}\n.s3d-search-result-content .searchcontent_result_share_icon{display:inline-block;float:right;margin-left:10px;}\n.s3d-search-result-content .searchcontent_result_author_icon{margin-left:8px;display:inline-block;float:right;}\n\n/* search results people */\n.s3d-search-result-person .searchpeople_result_person{margin:5px 8px 10px;padding:10px;width:280px;background-color:#FFF;height:50px;float:left;border:none;overflow:hidden;}\n.s3d-search-result-person .searchpeople_result_person_picture{float:left;display:block;width:48px;height:48px;padding:0;margin:0;}\n.s3d-search-result-person .searchpeople_result_dot{display:block;float:left;position:relative;left:5px;}\n.s3d-search-result-person .searchpeople_result_person_dept{display:block;color:#999;font-size:.85em;margin:0 0 4px 57px;line-height:12px;}\n.s3d-search-result-person .searchpeople_result_person_links{margin-left:57px;}\n.s3d-search-result-person .searchpeople_result_person_link{font-size:.85em;}\n.s3d-search-result-person .searchpeople_result_person_divider{color:#ddd;margin:0 0 0 0px!important;}\n.s3d-search-result-person .searchpeople_result_person_threedots{display:block;width:150px;}\n.s3d-search-result-person .searchpeople_result_counts{padding:3px 0;font-size:11px;}\n.s3d-search-result-person .searchpeople_result_message_icon{display:inline-block;float:right;}\n\n/* search results groups */\n.s3d-search-result-group .searchgroups_result_grouptype {font-size:smaller;white-space:pre;}\n.s3d-search-result-group .searchgroups_result_message_icon{display:inline-block;float:right;}\n.s3d-search-result-group .searchgroups_result_usedin{font-size: 11px;padding:3px 0;}\n.s3d-search-result-group .searchgroups_result_comments_icon{margin-left:8px;}\n.s3d-search-result-group .searchgroups_result_description{color:#333;font-size:.90em;padding:3px 0;word-wrap: break-word;}\n.s3d-search-result-group .searchgroups_result_plus{margin:1px 8px 0 0;display:inline;float:left;height:17px;width:17px;}\n.s3d-search-result-group .searchgroups_result_plus:hover{cursor:pointer;}\n\n/* search results grid */\n.s3d-search-results-grid{border:0 !important;border-top:1px solid #ddd !important;padding-top:5px;border-spacing:10px;}\n.s3d-search-results-grid .s3d-search-result{width:150px;height:232px;overflow:hidden;border: 1px solid #FFFFFF !important;float:left;position:relative;margin:0 8px 8px 0;clear:none;}\n.s3d-search-results-grid .s3d-search-result a img{float:left !important;padding:0 !important;margin-left:24px;width:100px !important;height:100px !important;position:absolute;}\n.s3d-search-results-grid .s3d-search-result-anonuser{display:none !important;}\n.s3d-search-results-grid .s3d-search-result-right{margin:135px 0 0 7px;}\n.s3d-search-results-grid .s3d-search-result-user-functions{position:absolute;float:left !important;margin:110px 0 0 21px !important;}\n.s3d-search-results-grid .s3d-search-result-content .s3d-actions-addtolibrary{margin-right:8px;}\n.s3d-search-results-grid .s3d-search-result-content .s3d-actions-author{margin-right:20px;}\n.s3d-search-results-grid .s3d-search-result-content .searchcontent_result_usedin_line{display:block;margin-bottom:2px;}\n.s3d-search-results-grid .s3d-search-result-group .s3d-actions-message{margin-left:60px;}\n.s3d-search-results-grid .s3d-search-result-group .searchgroups_result_plus{margin-top:-1px;}\n.s3d-search-results-grid .s3d-search-result-person .searchpeople_result_left_filler{margin: 0 70px 0 -50px;}\n.s3d-search-results-grid .s3d-search-result-detail-separator{display:block;}\n.s3d-search-results-grid .s3d-search-result-detail-separator span{display:none;}\n.s3d-search-results-grid .searchpeople_result_description, .s3d-search-results-grid .searchgroups_result_description, .s3d-search-results-grid .searchcontent_result_description,\n.s3d-search-results-grid .s3d-search-result-name, .s3d-search-results-grid .s3d-search-result-tag,\n.s3d-search-results-grid .searchcontent_result_by_name{display:none;}\n.s3d-search-results-grid .searchpeople_result_description_grid, .s3d-search-results-grid .searchgroups_result_description_grid, .s3d-search-results-grid .searchcontent_result_description_grid{display:none;word-wrap:break-word;}\n.s3d-search-results-grid .s3d-search-result-name-grid, .s3d-search-results-grid .s3d-search-result-tag-grid, .s3d-search-results-grid .s3d-search-result-avatar-large,\n.s3d-search-results-grid .searchcontent_result_by_name_grid{display:inline;}\n.s3d-search-results-grid ~ .jq_pager{border:0;}\n.s3d-search-results-grid .s3d-search-result:hover{border: 1px solid #e9e9e9;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;}\n\n/* search results anon user */\n.s3d-search-results-anon .s3d-search-result-user-functions{display:none;}\n.s3d-search-results-anon .s3d-search-result-anonuser{display:inline;float:left;height:15px;width:15px;}\n.s3d-search-results-anon .s3d-search-results-grid .s3d-search-result-right{margin:110px 0 0 0;}\n\n/* Search list or grid view buttons */\n.s3d-search-listview-options {float:right;padding:0!important;height:19px!important;margin-left:20px;}\n.s3d-search-listview-options:hover {background:#fff!important;box-shadow:0 0 4px -2px #A8A8A8 inset!important;}\n.s3d-search-listview-options > div {float:left;height:15px;padding:3px 4px 2px;}\n.s3d-search-listview-options > div.selected, .s3d-search-listview-options > div:hover {background:url(\"/dev/images/button_header_hover.png\") repeat-x scroll left -1px transparent;box-shadow:0 0 4px -2px #A8A8A8 inset;} \n.s3d-search-listview-options .search_view_list {border-radius:0 5px 5px 0;}\n.s3d-search-listview-options .search_view_grid {border-radius:5px 0 0 5px;}\n.s3d-search-listview-options .s3d-action-icon {display:block!important;}\n\n/* Search icons */\n.s3d-search-results-gridview {background:url('/dev/images/search_grid_16x16.png') no-repeat top left transparent;}\n.s3d-search-results-gridview:hover {background:url('/dev/images/search_grid_16x16_hover.png') no-repeat top left transparent;}\n.s3d-search-results-gridview.selected {background:url('/dev/images/search_grid_16x16_hover.png') no-repeat top left transparent;}\n.s3d-search-results-listview {background:url('/dev/images/search_list_16x16.png') no-repeat top left transparent;}\n.s3d-search-results-listview:hover {background:url('/dev/images/search_list_16x16_hover.png') no-repeat top left transparent;}\n.s3d-search-results-listview.selected {background:url('/dev/images/search_list_16x16_hover.png') no-repeat top left transparent;}\n.s3d-search-results-carouselview {background:url('/dev/images/search_carousel_16x16.png') no-repeat top left transparent;margin-top:-2px;}\n.s3d-search-results-carouselview:hover {background:url('/dev/images/search_carousel_16x16_hover.png') no-repeat top left transparent;}\n.s3d-search-results-carouselview.selected {background:url('/dev/images/search_carousel_16x16_hover.png') no-repeat top left transparent;}\n.s3d-search-results-blogview {background:url('/dev/images/search_blog_16x16.png') no-repeat top left transparent;margin-top:-1px;}\n.s3d-search-results-blogview:hover {background:url('/dev/images/search_blog_16x16_hover.png') no-repeat top left transparent;}\n.s3d-search-results-blogview.selected {background:url('/dev/images/search_blog_16x16_hover.png') no-repeat top left transparent;}\n\n/*\n * Progress indicator\n */\n#sakai_progressindicator {margin-top:25px;}\n#sakai_progressindicator h1, #sakai_progressindicator p {text-align:center;}\n#sakai_progressindicator .s3d-inset-shadow-container {height:50px;padding-top:30px;}\n#sakai_progressindicator .s3d-inset-shadow-container img {display:block;height:20px;margin-left:auto;margin-right:auto;width:188px;}\n\n/*\n * ICONS\n */\n.s3d-icon-16{width:16px; height:16px;}\n.s3d-icon-32{width:32px; height:32px;}\n.s3d-icon-40{width:40px; height:40px;}\n.s3d-icon-50{width:50px; height:50px;}\n.s3d-icon-64{width:64px; height:64px;}\n.s3d-icon-128{width:128px; height:128px;}\n.icon-audio-sprite{background:url(/dev/images/icons_sprite.png) no-repeat scroll -958px 0 transparent;}\n.icon-doc-sprite{background:url(/dev/images/icons_sprite.png) no-repeat scroll -112px 0 transparent;}\n.icon-pdf-sprite{background:url(/dev/images/icons_sprite.png) no-repeat scroll -750px 0 transparent;}\n.icon-pps-sprite{background:url(/dev/images/icons_sprite.png) no-repeat scroll -463px 0 transparent;}\n.icon-swf-sprite{background:url(/dev/images/icons_sprite.png) no-repeat scroll -1040px 0 transparent;}\n.icon-zip-sprite{background:url(/dev/images/icons_sprite.png) no-repeat scroll -1056px 0 transparent;}\n.icon-spreadsheet-sprite{background:url(/dev/images/icons_sprite.png) no-repeat scroll -560px 0 transparent;}\n.icon-txt-sprite{background:url(/dev/images/icons_sprite.png) no-repeat scroll -1086px 0 transparent;}\n.icon-image-sprite{background:url(/dev/images/icons_sprite.png) no-repeat scroll -320px 0 transparent;}\n.icon-html-sprite{background:url(/dev/images/icons_sprite.png) no-repeat scroll -302px 0 transparent;}\n.icon-video-sprite{background:url(/dev/images/icons_sprite.png) no-repeat scroll -1118px 0 transparent;}\n.icon-sound-sprite{background:url(/dev/images/icons_sprite.png) no-repeat scroll -622px 0 transparent;}\n.icon-kmultiple-sprite{background:url(/dev/images/icons_sprite.png) no-repeat scroll -430px 0 transparent;}\n.icon-url-sprite{background:url(/dev/images/icons_sprite.png) no-repeat scroll -304px 0 transparent;}\n.icon-sakaidoc-sprite{background:url(/dev/images/icons_sprite.png) no-repeat scroll -1185px 0 transparent;}\n.icon-unknown-sprite{background:url(/dev/images/icons_sprite.png) no-repeat scroll -143px 0 transparent;}\n.icon-collection-sprite{background:url(/dev/images/icons_sprite.png) no-repeat scroll -430px 0 transparent;}\n\n/*\n * Forms and Validation\n */\n.s3d-form-field-wrapper{position:relative;}\n.s3d-form-field-wrapper input, .s3d-form-field-wrapper textarea, .s3d-form-field-wrapper select,.s3d-form-field-wrapper ul.as-selections{float:left;clear:right;margin-bottom:15px;}\n.s3d-form-field-wrapper input, .s3d-form-field-wrapper textarea{width:55%;padding:0 5px;}\n.s3d-form-field-wrapper ul.as-selections input{padding:0px;}\n.s3d-form-field-wrapper textarea{padding:5px;}\n.s3d-form-field-wrapper input.s3d-input-full-width, .s3d-form-field-wrapper textarea.s3d-input-full-width{width:98%;clear:both;}\n.s3d-form-field-wrapper ul.as-selections{padding: 0px 5px;width:98%;}\n.s3d-form-field-wrapper input{height:21px;}\n.s3d-form-field-wrapper label.s3d-input-label{float:left;width:35%;clear:left;text-align:right;padding:5px 2%;color:#666;}\n.s3d-form-field-wrapper label.s3d-input-label-above{width:100%;clear:both;text-align:left;padding:0;}\n.s3d-form-field-wrapper input.s3d-error, .s3d-form-field-wrapper textarea.s3d-error,.s3d-form-field-wrapper input.s3d-error-after, .s3d-form-field-wrapper textarea.s3d-error-after, .s3d-form-field-wrapper ul.as-selections.s3d-error{border:3px solid #cc0000;}\n.s3d-form-field-wrapper span.s3d-error{clear:both;background-color:#cc0000;color:#fff;padding:0 5px;width:55%;float:left;margin-left:39%;border:3px solid #cc0000;font-size:11px;}\n.s3d-form-field-wrapper span.s3d-error-after{clear:both;background-color:#cc0000;color:#fff;padding:0 5px;width:98%;float:left;margin-left:0;border:3px solid #cc0000;font-size:11px;}\n.s3d-form-field-wrapper input::-webkit-input-placeholder, .s3d-form-field-wrapper textarea::-webkit-input-placeholder {color:#aaa;font-size:12px;}\n.s3d-form-field-wrapper input:-moz-placeholder, .s3d-form-field-wrapper textarea:-moz-placeholder {color:#aaa;font-size:12px;}\n\n/*\n * Drag and Drop\n */\n.s3d-draggable-draggingitems {background-color:#1098d5;color:#fff;padding:4px 7px;display:inline-block;font-size:11px;box-shadow:0px 1px 3px 0 #999;-moz-box-shadow:0px 1px 3px 0 #999;-webkit-box-shadow:0px 1px 3px 0 #999;}\n#s3d-draggeditems-container li {background:#e9f4f8;border:2px solid #d5e9f3;border-radius:2px;-moz-border-radius:2px;-webkit-border-radius:2px;margin-bottom:2px;}\n#s3d-draggeditems-container .s3d-draggable-hidden{display:none;}\n", "dev/css/sakai/sakai.corev1.css": "/**\n * Licensed to the Sakai Foundation (SF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The SF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations under the License.\n */\n.s3d-page-column-left{float:left;width:187px;min-height:500px;border-top:solid #d6dadd 1px;background:url(\"/devwidgets/lhnavigation/images/lhnav_bg.png\") repeat-x scroll 0 0 #FEFEFE;}\n.s3d-page-column-right{float:left;width:773px;border-left:1px solid #d6dadd; border-top:1px solid #d6dadd;padding:20px;box-shadow: 3px -10px 7px 0;-moz-box-shadow: 3px -10px 7px 0;-webkit-box-shadow: 3px -10px 7px 0;box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;}\n.s3d-page-fullcolumn-nopadding{width:960px;min-height:100px;border-top:solid #d6dadd 1px;}\n.s3d-page-fullcolumn-padding{width:920px;min-height:100px;border-top:solid #d6dadd 1px; padding: 20px 20px 30px;}\n.s3d-page-content-padding{padding: 10px 0px 20px;}\n.s3d-page-content-lowpadding{padding: 0px 0px 20px;}\n.s3d-page-full{height:100px;}\n.s3d-navigation-container{background: url(\"/devwidgets/topnavigation/images/topnav_bg.png\") repeat-x scroll left top transparent;-moz-box-shadow:0 -5px 9px 6px #555555;-webkit-box-shadow:0 -5px 9px 6px #555555;box-shadow:0 -5px 9px 6px #555555;height: 40px;margin-left: auto;margin-right: auto;position: absolute;width: 100%;z-index: 999;}\n.s3d-page-header{background:url(\"/devwidgets/entity/images/entity_bottom_bordershadow.png\") repeat-x scroll left bottom, url(\"/devwidgets/entity/images/entity_bg.png\") repeat-x scroll left top #f7f7f7;border-bottom: 1px solid #B3B3B4;min-height: 45px;margin-top: 40px;width:960px;}\n.s3d-page-header.collection_modified {padding:0px;height:auto;width:960px;-moz-box-shadow:0 -5px 9px 6px #555555;-webkit-box-shadow:0 -5px 9px 6px #555555;box-shadow:0 -5px 9px 6px #555555;min-height:0;border-bottom:0;}\n.s3d-fixed-container .s3d-container-shadow-left, .s3d-container-shadow-right {background:url(\"/dev/images/container_shadow_left.png\") no-repeat scroll 0 0 transparent;height:346px;position:absolute;width:5px;margin-left:-5px;}\n.s3d-container-shadow-right{background: url(\"/dev/images/container_shadow_right.png\") no-repeat scroll 0 0 transparent;float: right;margin-left:960px;}\n\n/* CSS THAT OVERWRITES MAIN CSS */\n.s3d-main-container {padding: 0px !important;}\n.fixed-container.s3d-main-container{width:960px;}\n.s3d-twocolumn{background-color:#fff;}\n.requireUser, .requireAnon {background: url(\"/dev/images/grey_bg.png\") repeat-x scroll left -91px #f2f2f2 !important;}\n.s3d-header .fixed-container {padding:0 !important; width:960px;}\n.s3d-header .s3d-fixed-container .s3d-decor-left {margin-left:0;}\n.s3d-header .s3d-fixed-container .s3d-decor {margin-right:0;}\n.s3d-header .s3d-fixed-container .s3d-decor-left {background: url(\"/dev/images/pageHeader_tl.png\") no-repeat scroll 0 0 transparent;}\n.s3d-header .s3d-fixed-container .s3d-decor {background: url(\"/dev/images/pageHeader_tr.png\") no-repeat scroll 0 0 transparent;}\n.s3d-header .s3d-navigation-container{min-width:960px;}\n\n/* Page titles */\n.s3d-contentpage-title {border-bottom:5px solid #E1E1E1; color:#424242; font-size:1.25em; padding:8px 0; margin-bottom: 15px;}\n\n/* Page bottom */\n.s3d-bottom-spacer {clear: both; padding-bottom: 40px;}\n", "dev/group.html": "\n\n\n \n\n \n \n \n\n \n \n\n \n \n \n\n \n \n \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n\n \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n\n \n
            \n\n
            \n\n
            \n\n
            \n\n
            \n\n \n
            \n\n \n \n \n\n \n \n\n \n\n", "dev/index.html": "\n\n \n \n \n \n \n \n \n \n \n\n
            __MSG__IE_PLACEHOLDER__
            \n\n \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n \n
            \n\n \n \n \n \n", "dev/javascript/acknowledgements.js": "/*\n * Licensed to the Sakai Foundation (SF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The SF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations under the License.\n */\n\nrequire([\"jquery\",\"sakai/sakai.api.core\"], function($, sakai) {\n\n sakai_global.acknowledgements = function() {\n \n var pubdata = {\t\n \"structure0\": {\n \"featured\": {\n \"_ref\": \"id1\", \n \"_title\": \"Featured\",\n \"_order\": 0,\n \"main\": {\n \"_ref\": \"id2\",\n \"_order\": 0,\n \"_title\": \"Featured\"\n }\n },\n \"ui\": {\n \"_ref\": \"id2\", \n \"_title\": \"UI Technologies\",\n \"_order\": 1,\n \"main\": {\n \"_ref\": \"id2\",\n \"_order\": 0,\n \"_title\": \"UI Technologies\"\n }\n },\n \"nakamura\": {\n \"_title\": \"Back-end Technologies\", \n \"_ref\": \"id3\",\n \"_order\": 2,\n \"main\": {\n \"_ref\": \"id3\",\n \"_order\": 0,\n \"_title\": \"Back-end Technologies\"\n }\n }\n },\n \"id1\": {\n \"page\": $(\"#acknowledgements_featured\").html()\n },\n \"id2\": {\n \"page\": $(\"#acknowledgements_uitech\").html()\n },\n \"id3\": {\n \"page\": $(\"#acknowledgements_backendtech\").html()\n }\n };\n\n var generateNav = function(){\n $(window).trigger(\"lhnav.init\", [pubdata, {}, {}]);\n };\n \n var renderEntity = function(){\n $(window).trigger(\"sakai.entity.init\", [\"acknowledgements\"]);\n };\n\n $(window).bind(\"lhnav.ready\", function(){\n generateNav();\n });\n \n $(window).bind(\"sakai.entity.ready\", function(){\n renderEntity(); \n });\n \n generateNav();\n renderEntity();\n \n };\n\n sakai.api.Widgets.Container.registerForLoad(\"acknowledgements\");\n});\n", "dev/javascript/category.js": "/*\n * Licensed to the Sakai Foundation (SF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The SF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations under the License.\n */\n\nrequire([\"jquery\",\"sakai/sakai.api.core\"], function($, sakai) {\n\n sakai_global.category = sakai_global.category || {};\n\n sakai_global.category = function() {\n\n var originalTitle = document.title;\n var pubdata = {};\n var privdata = {};\n\n // Containers\n var $exploreNavigation = $(\"#explore_navigation\");\n var toplevelId = \"\";\n\n // Templates\n var exploreNavigationTemplate = \"explore_navigation_template\";\n\n /**\n * Create the breadcrumb data and render on screen\n * @param {Object} dirData Object that contains children for the category\n * @param {Array} bbqData Array of IDs fetched with bbq to help identify correct children\n */\n var createBreadcrumb = function(dirData, bbqData){\n if (!dirData){\n sakai.api.Security.send404();\n return false;\n }\n // Create top level breadcrumb\n var breadcrumb = [];\n breadcrumb.push({\n \"title\": sakai.api.i18n.getValueForKey(\"ALL_CATEGORIES\"),\n \"id\": bbqData[0],\n \"link\": true,\n \"url\": \"/categories\"\n });\n breadcrumb.push({\n \"title\": dirData.title,\n \"id\": dirData.id,\n \"link\": bbqData.length - 1\n });\n bbqData.splice(0,1);\n\n // Create children level breadcrumb\n var children = dirData.children[bbqData[0]];\n $.each(bbqData, function(index, item){\n breadcrumb.push({\n \"title\": children.title,\n \"id\": item,\n \"link\": bbqData.length - 1 - index\n });\n if (children.children) {\n children = children.children[bbqData[index]];\n }\n });\n\n $exploreNavigation.html(sakai.api.Util.TemplateRenderer(exploreNavigationTemplate,{\"breadcrumb\": breadcrumb}));\n document.title = originalTitle + \" \" + dirData.title;\n };\n\n /**\n * Generate the navigation object and pass it to the left hand navigation widget\n * @param {Object} navData Contains all data from the category the user is currently viewing\n */\n var generateNav = function(navData){\n\n toplevelId = navData.id;\n\n pubdata = {\n \"structure0\": {}\n };\n privdata = {\n \"structure0\": {}\n };\n\n var rnd = sakai.api.Util.generateWidgetId();\n privdata[\"structure0\"][navData.id] = {\n \"_order\": 0,\n \"_ref\": rnd,\n \"_title\": navData.title\n };\n\n // featuredcontent, featured people and featuredworld random numbers\n var fcRnd = sakai.api.Util.generateWidgetId();\n var fpRnd = sakai.api.Util.generateWidgetId();\n var fwRnd = sakai.api.Util.generateWidgetId();\n privdata[rnd] = {\n page: \"
            \"\n };\n privdata[fcRnd] = {\n category: navData.id,\n title: navData.title\n };\n privdata[fpRnd] = {\n category: navData.id,\n title: navData.title\n };\n privdata[fwRnd] = {\n category: navData.id,\n title: navData.title\n };\n\n var count = 0;\n $.each(navData.children, function(index, item){\n var rnd = sakai.api.Util.generateWidgetId();\n pubdata[\"structure0\"][navData.id + \"-\" + index] = {\n \"_ref\": rnd,\n \"_order\": count,\n \"_title\": item.title,\n \"main\": {\n \"_ref\": rnd,\n \"_order\": 0,\n \"_title\": item.title\n }\n };\n\n // featuredcontent, featured people and featuredworld random numbers\n var fcRnd = sakai.api.Util.generateWidgetId();\n var fpRnd = sakai.api.Util.generateWidgetId();\n var fwRnd = sakai.api.Util.generateWidgetId();\n pubdata[rnd] = {\n page: \"
            \"\n };\n pubdata[fcRnd] = {\n category: navData.id + \"-\" + index,\n title: navData.title + \" \u00bb \" + item.title\n };\n pubdata[fpRnd] = {\n category: navData.id + \"-\" + index,\n title: navData.title + \" \u00bb \" + item.title\n };\n pubdata[fwRnd] = {\n category: navData.id + \"-\" + index,\n title: navData.title + \" \u00bb \" + item.title\n };\n\n count++;\n });\n $(window).trigger(\"lhnav.init\", [pubdata, privdata, {}]);\n };\n\n /**\n * Get the category out of the URL and give it back\n * @return {Array} Array of strings representing the selected hierarchy\n */\n var getCategory = function(){\n var category = $.bbq.getState(\"l\");\n if (category) {\n category = category.split(\"-\");\n }\n return category;\n };\n\n var doInit = function(){\n var category = getCategory();\n if (!$.isArray(category) || !sakai.config.Directory[category[0]]){\n sakai.api.Security.send404();\n return false;\n }\n sakai.config.Directory[category[0]].id = category[0];\n generateNav(sakai.config.Directory[category[0]]);\n createBreadcrumb(sakai.config.Directory[category[0]], category);\n };\n\n $(window).bind(\"lhnav.ready\", function(){\n doInit();\n });\n\n $(window).bind(\"hashchange\", function(e, data){\n var category = getCategory();\n createBreadcrumb(sakai.config.Directory[category[0]], category);\n });\n\n };\n\n sakai.api.Widgets.Container.registerForLoad(\"category\");\n});", "dev/javascript/content_profile.js": "/*\n * Licensed to the Sakai Foundation (SF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The SF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations under the License.\n */\n\nrequire([\"jquery\",\"sakai/sakai.api.core\"], function($, sakai) {\n\n sakai_global.content_profile = function(){\n\n var previous_content_path = false;\n var content_path = \"\"; // The current path of the content\n var ready_event_fired = 0;\n var list_event_fired = false;\n var intervalId;\n\n var showPreview = true;\n var collectionID = false;\n var collectionName = false;\n var isCollection = false;\n\n ///////////////////////////////\n // PRIVATE UTILITY FUNCTIONS //\n ///////////////////////////////\n\n /**\n * Load the content profile for the current content path\n * @param {Boolean} ignoreActivity Flag to also update activity data or not\n */\n var loadContentProfile = function(callback, ignoreActivity){\n // Check whether there is actually a content path in the URL\n if (content_path) {\n // Get the content information, the members and managers and version information\n sakai.api.Content.loadFullProfile(content_path, function(success, data){\n if (success) {\n if (data.results.hasOwnProperty(0)) {\n var contentInfo = false;\n if (data.results[0][\"status\"] === 404){\n sakai.api.Security.send404();\n return;\n } else if (data.results[0][\"status\"] === 403){\n sakai.api.Security.send403();\n return;\n } else {\n contentInfo = $.parseJSON(data.results[0].body);\n if (contentInfo[\"_mimeType\"] && contentInfo[\"_mimeType\"] === \"x-sakai/document\" || contentInfo[\"_mimeType\"] && contentInfo[\"_mimeType\"] === \"x-sakai/collection\"){\n showPreview = false;\n } else {\n switchToOneColumnLayout(false);\n }\n\n var collectionId = $.bbq.getState(\"collectionId\");\n var collectionName = $.bbq.getState(\"collectionName\");\n var currentPath = $.bbq.getState(\"p\");\n if(collectionId && collectionName && currentPath){\n // Show go back to collection link\n $(\"#back_to_collection_button #collection_title\").text(collectionName);\n $(\"#back_to_collection_button\").attr(\"href\", \"/content#p=\" + collectionId + \"/\" + sakai.api.Util.safeURL(collectionName) + \"&item=\" + currentPath.split(\"/\")[0]);\n $(\"#back_to_collection_container\").show(\"slow\");\n } else {\n $(\"#back_to_collection_container\").hide(\"slow\");\n }\n }\n }\n\n sakai.api.Content.parseFullProfile(data.results, function(parsedData){\n parsedData.mode = \"content\";\n sakai_global.content_profile.content_data = parsedData;\n $(window).trigger(\"ready.contentprofile.sakai\", sakai_global.content_profile.content_data);\n if ($.isFunction(callback)) {\n callback(true);\n }\n initEntityWidget();\n\n if (!showPreview){\n renderSakaiDoc(parsedData.data);\n }\n });\n }\n });\n } else {\n sakai.api.Security.send404();\n }\n };\n\n var initEntityWidget = function(){\n if (sakai_global.content_profile.content_data) {\n var context = \"content\";\n if (sakai.data.me.user.anon) {\n type = \"content_anon\";\n } else if (sakai_global.content_profile.content_data.isManager) {\n type = \"content_managed\";\n } else if (sakai_global.content_profile.content_data.isViewer) {\n type = \"content_shared\";\n } else {\n type = \"content_not_shared\";\n }\n $(window).trigger(\"sakai.entity.init\", [context, type, sakai_global.content_profile.content_data]);\n }\n };\n\n $(window).bind(\"sakai.entity.ready\", function(){\n initEntityWidget();\n });\n\n $(window).bind(\"load.content_profile.sakai\", function(e, callback) {\n loadContentProfile(callback);\n });\n\n var handleHashChange = function() {\n content_path = $.bbq.getState(\"p\") || \"\";\n content_path = content_path.split(\"/\");\n content_path = \"/p/\" + content_path[0];\n\n if (content_path != previous_content_path) {\n previous_content_path = content_path;\n globalPageStructure = false;\n loadContentProfile(function(){\n // The request was successful so initialise the entity widget\n if (sakai_global.entity && sakai_global.entity.isReady) {\n $(window).trigger(\"render.entity.sakai\", [\"content\", sakai_global.content_profile.content_data]);\n }\n else {\n $(window).bind(\"ready.entity.sakai\", function(e){\n $(window).trigger(\"render.entity.sakai\", [\"content\", sakai_global.content_profile.content_data]);\n ready_event_fired++;\n });\n }\n // The request was successful so initialise the relatedcontent widget\n if (sakai_global.relatedcontent && sakai_global.relatedcontent.isReady) {\n $(window).trigger(\"render.relatedcontent.sakai\", sakai_global.content_profile.content_data);\n }\n else {\n $(window).bind(\"ready.relatedcontent.sakai\", function(e){\n $(window).trigger(\"render.relatedcontent.sakai\", sakai_global.content_profile.content_data);\n ready_event_fired++;\n });\n }\n // The request was successful so initialise the relatedcontent widget\n if (sakai_global.contentpreview && sakai_global.contentpreview.isReady) {\n if (showPreview) {\n $(window).trigger(\"start.contentpreview.sakai\", sakai_global.content_profile.content_data);\n }\n }\n else {\n $(window).bind(\"ready.contentpreview.sakai\", function(e){\n if (showPreview) {\n $(window).trigger(\"start.contentpreview.sakai\", sakai_global.content_profile.content_data);\n ready_event_fired++;\n }\n });\n }\n // The request was successful so initialise the metadata widget\n if (sakai_global.contentmetadata && sakai_global.contentmetadata.isReady) {\n $(window).trigger(\"render.contentmetadata.sakai\");\n }\n else {\n $(window).bind(\"ready.contentmetadata.sakai\", function(e){\n $(window).trigger(\"render.contentmetadata.sakai\");\n ready_event_fired++;\n });\n } \n sakai.api.Security.showPage();\n\n if(sakai_global.content_profile.content_data.data._mimeType === \"x-sakai/collection\"){\n $(\".collectionviewer_carousel_item.selected\").click();\n }\n\n // rerender comments widget\n $(window).trigger(\"content_profile_hash_change\");\n });\n }\n showPreview = true;\n };\n\n $(\"#entity_content_share\").live(\"click\", function(){\n $(window).trigger(\"init.sharecontent.sakai\");\n return false;\n });\n\n $(\"#entity_content_add_to_library\").live(\"click\", function(){\n sakai.api.Content.addToLibrary(sakai_global.content_profile.content_data.data[\"_path\"], sakai.data.me.user.userid, false, function(){\n $(\"#entity_content_add_to_library\").hide();\n sakai.api.Util.notification.show($(\"#content_profile_add_library_title\").html(), $(\"#content_profile_add_library_body\").html());\n });\n });\n\n ////////////////////\n // Initialisation //\n ////////////////////\n\n /**\n * Initialise the content profile page\n */\n var init = function(){\n // Bind an event to window.onhashchange that, when the history state changes,\n // loads all the information for the current resource\n $(window).bind('hashchange', function(){\n handleHashChange();\n });\n handleHashChange();\n };\n\n // //////////////////////////\n // Dealing with Sakai docs //\n /////////////////////////////\n\n var globalPageStructure = false;\n\n var generateNav = function(pagestructure){\n if (pagestructure) {\n $(window).trigger(\"lhnav.init\", [pagestructure, {}, {\n parametersToCarryOver: {\n \"p\": sakai_global.content_profile.content_data.content_path.replace(\"/p/\", \"\")\n }\n }, sakai_global.content_profile.content_data.content_path]);\n }\n };\n\n $(window).bind(\"lhnav.ready\", function(){\n generateNav(globalPageStructure);\n });\n\n var getPageCount = function(pagestructure){\n var pageCount = 0;\n for (var tl in pagestructure[\"structure0\"]){\n if (pagestructure[\"structure0\"].hasOwnProperty(tl) && tl !== \"_childCount\"){\n pageCount++;\n if (pageCount >= 3){\n return 3;\n }\n for (var ll in pagestructure[\"structure0\"][tl]){\n if (ll.substring(0,1) !== \"_\"){\n pageCount++;\n if (pageCount >= 3){\n return 3;\n }\n }\n }\n }\n }\n return pageCount;\n };\n\n $(window).bind(\"sakai.contentauthoring.needsTwoColumns\", function(){\n switchToTwoColumnLayout(true);\n });\n\n $(window).bind(\"sakai.contentauthoring.needsOneColumn\", function(){\n switchToOneColumnLayout(true);\n });\n\n var setManagerProperty = function(structure, value){\n for (var i in structure){\n if (structure.hasOwnProperty(i)){\n structure[i]._canEdit = value;\n structure[i]._canSubedit = value;\n }\n }\n return structure;\n };\n\n var renderSakaiDoc = function(pagestructure){\n pagestructure = sakai.api.Server.cleanUpSakaiDocObject(pagestructure);\n pagestructure.structure0 = setManagerProperty(pagestructure.structure0, sakai_global.content_profile.content_data.isManager);\n if (getPageCount(pagestructure) >= 3){\n switchToTwoColumnLayout(true);\n } else {\n switchToOneColumnLayout(true);\n }\n globalPageStructure = pagestructure;\n generateNav(pagestructure);\n };\n\n var switchToTwoColumnLayout = function(isSakaiDoc){\n $(\"#content_profile_left_column\").show();\n $(\"#content_profile_main_container\").addClass(\"s3d-twocolumn\");\n $(\"#content_profile_right_container\").addClass(\"s3d-page-column-right\");\n $(\"#content_profile_right_container\").removeClass(\"s3d-page-fullcolumn-padding\");\n $(\"#content_profile_right_metacomments\").removeClass(\"fl-container-650\");\n $(\"#content_profile_right_metacomments\").addClass(\"fl-container-450\");\n if (isSakaiDoc){\n $(\"#content_profile_preview_container\").hide();\n $(\"#content_profile_sakaidoc_container\").show();\n } else {\n $(\"#content_profile_preview_container\").show();\n $(\"#content_profile_sakaidoc_container\").hide();\n }\n };\n\n var switchToOneColumnLayout = function(isSakaiDoc){\n $(\"#content_profile_left_column\").hide();\n $(\"#content_profile_main_container\").removeClass(\"s3d-twocolumn\");\n $(\"#content_profile_right_container\").removeClass(\"s3d-page-column-right\");\n $(\"#content_profile_right_container\").addClass(\"s3d-page-fullcolumn-padding\");\n $(\"#content_profile_right_metacomments\").addClass(\"fl-container-650\");\n $(\"#content_profile_right_metacomments\").removeClass(\"fl-container-450\");\n if (isSakaiDoc){\n $(\"#content_profile_preview_container\").hide();\n $(\"#content_profile_sakaidoc_container\").show();\n } else {\n $(\"#content_profile_preview_container\").show();\n $(\"#content_profile_sakaidoc_container\").hide();\n }\n };\n\n // Initialise the content profile page\n init();\n\n };\n\n sakai.api.Widgets.Container.registerForLoad(\"content_profile\");\n});\n", "dev/javascript/createnew.js": "/*\n * Licensed to the Sakai Foundation (SF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The SF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations under the License.\n */\n\nrequire([\"jquery\",\"sakai/sakai.api.core\"], function($, sakai) {\n\n sakai_global.createnew = function() {\n\n var pubdata = {\n \"structure0\": {}\n };\n\n for (var i = 0; i < sakai.config.worldTemplates.length; i++){\n var category = sakai.config.worldTemplates[i];\n pubdata.structure0[category.id] = {\n \"_order\": i,\n \"_title\": sakai.api.i18n.getValueForKey(category.title),\n \"_ref\": category.id\n };\n pubdata[category.id] = {\n \"page\": \"
            \"\n };\n }\n\n var generateNav = function(){\n $(window).trigger(\"lhnav.init\", [pubdata, {}, {}]);\n };\n\n var renderCreateGroup = function(){\n $(window).trigger(\"sakai.newcreategroup.init\");\n };\n\n $(window).bind(\"lhnav.ready\", function(){\n generateNav();\n });\n\n $(window).bind(\"newcreategroup.ready\", function(){\n renderCreateGroup();\n });\n\n generateNav();\n \n };\n\n sakai.api.Widgets.Container.registerForLoad(\"createnew\");\n});\n", "dev/javascript/search.js": "/*\n * Licensed to the Sakai Foundation (SF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The SF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations under the License.\n */\n\nrequire([\"jquery\",\"sakai/sakai.api.core\"], function($, sakai) {\n\n sakai_global.search = function() {\n var worldsOrderIncrement = 3;\n var searchButton = \"#form .s3d-search-button\";\n var searchInput = \"#form .s3d-search-inputfield\";\n var searchUrl = sakai.config.URL.SEARCH_URL;\n var pubdata = {\n \"structure0\": {\n \"all\": {\n \"_ref\": \"id9574379429432\",\n \"_order\": 0,\n \"_title\": sakai.api.i18n.getValueForKey(\"ALL_TYPES\"),\n \"_url\": searchUrl,\n \"main\": {\n \"_ref\": \"id9574379429432\",\n \"_order\": 0,\n \"_title\": sakai.api.i18n.getValueForKey(\"ALL_TYPES\"),\n \"_url\": searchUrl\n }\n },\n \"content\": {\n \"_ref\": \"id6573920372\",\n \"_order\": 1,\n \"_title\": sakai.api.i18n.getValueForKey(\"CONTENT\"),\n \"_url\": searchUrl,\n \"main\": {\n \"_ref\": \"id6573920372\",\n \"_order\": 0,\n \"_title\": sakai.api.i18n.getValueForKey(\"CONTENT\"),\n \"_url\": searchUrl\n }\n },\n \"people\": {\n \"_title\": sakai.api.i18n.getValueForKey(\"PEOPLE\"),\n \"_ref\": \"id49294509202\",\n \"_order\": 2,\n \"_url\": searchUrl,\n \"main\": {\n \"_ref\": \"id49294509202\",\n \"_order\": 0,\n \"_title\": sakai.api.i18n.getValueForKey(\"PEOPLE\"),\n \"_url\": searchUrl\n }\n }\n },\n \"id9574379429432\": {\n \"page\": \"
            \"\n },\n \"id6573920372\": {\n \"page\": \"
            \"\n },\n \"id49294509202\": {\n \"page\": \"
            \"\n }\n };\n\n for (var c = 0; c < sakai.config.worldTemplates.length; c++) {\n var category = sakai.config.worldTemplates[c];\n var refId = sakai.api.Util.generateWidgetId();\n var title = sakai.api.i18n.getValueForKey(category.titlePlural);\n pubdata.structure0[category.id] = {\n \"_title\": title,\n \"_ref\": refId,\n \"_order\": (c + worldsOrderIncrement),\n \"_url\": searchUrl,\n \"main\": {\n \"_ref\": refId,\n \"_order\": 0,\n \"_title\": title,\n \"_url\": searchUrl\n }\n };\n var searchWidgetId = sakai.api.Util.generateWidgetId();\n pubdata[refId] = {\n \"page\": \"
            \"\n };\n pubdata[searchWidgetId] = {\n \"category\": category.id\n };\n }\n\n var fireSearch = function(){\n $.bbq.pushState({\n \"q\": $(searchInput).val(),\n \"cat\": \"\",\n \"refine\": $.bbq.getState(\"refine\")\n }, 0);\n };\n\n ///////////////////\n // Event binding //\n ///////////////////\n\n var eventBinding = function(){\n $(searchInput).on(\"keydown\", function(ev){\n if (ev.keyCode === 13) {\n fireSearch();\n }\n });\n\n $(searchButton).on(\"click\", function(ev){\n fireSearch();\n });\n };\n\n var generateNav = function(){\n $(window).trigger(\"lhnav.init\", [pubdata, {}, {}]);\n };\n\n var renderEntity = function(){\n $(window).trigger(\"sakai.entity.init\", [\"search\"]);\n };\n\n $(window).bind(\"sakai.entity.ready\", function(){\n renderEntity();\n });\n\n $(window).bind(\"lhnav.ready\", function(){\n generateNav();\n });\n\n renderEntity();\n generateNav();\n eventBinding();\n\n };\n\n sakai.api.Widgets.Container.registerForLoad(\"search\");\n});\n", "dev/javascript/user.js": "/*\n * Licensed to the Sakai Foundation (SF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The SF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations under the License.\n */\n\nrequire([\"jquery\",\"sakai/sakai.api.core\"], function($, sakai) {\n\n sakai_global.profile = sakai_global.profile || {};\n sakai_global.profile.main = sakai_global.profile.main || {};\n $.extend(true, sakai_global.profile.main, {\n config: sakai.config.Profile.configuration.defaultConfig,\n data: {},\n mode: {\n options: [\"view\", \"edit\"],\n value: \"view\"\n }\n });\n\n sakai_global.user = function() {\n\n var privdata = false;\n var pubdata = false;\n var privurl = false;\n var puburl = false;\n var messageCounts = false;\n var isMe = false;\n var entityID = false;\n var isContact = false;\n\n var contextType = false;\n var contextData = false;\n\n var setupProfileSection = function( title, section ) {\n var ret = {\n _ref: sakai.api.Util.generateWidgetId(),\n _order: section.order,\n _altTitle: section.label,\n _title: section.label,\n _nonEditable: true,\n _view: section.permission\n };\n // _reorderOnly is only true for the basic profile\n ret._reorderOnly = title === \"basic\";\n return ret;\n };\n\n var setupProfile = function( structure, isMe ) {\n var firstWidgetRef = \"\";\n var profilestructure = {\n _title: structure.structure0.profile._title,\n _altTitle: structure.structure0.profile._altTitle,\n _order: structure.structure0.profile._order\n };\n if ( isMe ) {\n profilestructure[\"_canEdit\"] = true;\n profilestructure[\"_nonEditable\"] = true;\n profilestructure[\"_reorderOnly\"] = true;\n profilestructure[\"_canSubedit\"] = true;\n }\n var newProfile = true;\n $.each( structure.structure0.profile, function( key, section ) {\n if ( $.isPlainObject( section ) ) {\n newProfile = false;\n }\n });\n if ( newProfile ) {\n structure.structure0.profile = {};\n }\n var initialProfilePost = [];\n var paths = [];\n var permissions = [];\n var updateStructure = false;\n $.each(sakai.config.Profile.configuration.defaultConfig, function(title, section) {\n var widgetUUID = sakai.api.Util.generateWidgetId();\n if ( !newProfile && structure.structure0.profile.hasOwnProperty( title ) ) {\n profilestructure[ title ] = structure.structure0.profile[ title ];\n } else if ( newProfile || !structure.structure0.profile.hasOwnProperty( title )) {\n profilestructure[ title ] = setupProfileSection( title, section );\n if (title !== \"basic\"){\n paths.push(\"/~\" + sakai.data.me.user.userid + \"/public/authprofile/\" + title);\n permissions.push(section.permission);\n }\n if (section.order === 0) {\n firstWidgetRef = profilestructure[ title ]._ref;\n }\n initialProfilePost.push({\n \"url\": \"/~\" + sakai.data.me.user.userid + \"/public/authprofile/\" + title,\n \"method\": \"POST\",\n \"parameters\": {\n \"init\": true\n }\n });\n }\n // Don't need to use these from the profile, gives us more flexibility on the profile itself\n structure[ profilestructure[ title ]._ref ] = {\n page: \"
            \"\n };\n structure[ widgetUUID ] = {\n sectionid: title\n };\n });\n\n // Eliminate extra sections in the profile that are hanging around\n $.each( structure.structure0.profile, function( section_title, section_data ) {\n if ( $.isPlainObject( section_data ) && !profilestructure.hasOwnProperty( section_title ) ) {\n initialProfilePost.push({\n \"url\": \"/~\" + sakai.data.me.user.userid + \"/public/authprofile/\" + section_title,\n \"method\": \"POST\",\n \"parameters\": {\n \":operation\": \"delete\"\n }\n });\n }\n });\n\n if ( isMe && initialProfilePost.length ) {\n updateStructure = true;\n sakai.api.Server.batch(initialProfilePost, function(success, data){\n if (success) {\n sakai.api.Content.setACLsOnPath(paths, permissions, sakai.data.me.user.userid, function(success){\n if (!success){\n debug.error(\"Error setting initial profile ACLs\");\n }\n });\n } else {\n debug.error(\"Error saving initial profile fields\");\n }\n });\n }\n\n structure.structure0.profile = profilestructure;\n structure.structure0.profile._ref = firstWidgetRef;\n return updateStructure;\n };\n\n var continueLoadSpaceData = function(userid){\n var publicToStore = false;\n var privateToStore = false;\n\n // Load public data from /~userid/private/pubspace\n sakai.api.Server.loadJSON(puburl, function(success, data){\n if (!success){\n pubdata = $.extend(true, {}, sakai.config.defaultpubstructure);\n var refid = {\"refid\": sakai.api.Util.generateWidgetId()};\n pubdata = sakai.api.Util.replaceTemplateParameters(refid, pubdata);\n } else {\n pubdata = data;\n pubdata = sakai.api.Server.cleanUpSakaiDocObject(pubdata);\n }\n if (!isMe){\n pubdata.structure0 = setManagerProperty(pubdata.structure0, false);\n for (var i in pubdata.structure0) {\n if (pubdata.structure0.hasOwnProperty(i)){\n pubdata.structure0[i] = determineUserAreaPermissions(pubdata.structure0[i]);\n }\n }\n }\n if ( pubdata.structure0.profile && setupProfile( pubdata, isMe ) ) {\n publicToStore = $.extend(true, {}, pubdata);\n }\n if (isMe){\n sakai.api.Server.loadJSON(privurl, function(success2, data2){\n if (!success2){\n privdata = $.extend(true, {}, sakai.config.defaultprivstructure);\n var refid = {\"refid\": sakai.api.Util.generateWidgetId()};\n privdata = sakai.api.Util.replaceTemplateParameters(refid, privdata);\n privateToStore = $.extend(true, {}, privdata);\n } else {\n privdata = data2;\n privdata = sakai.api.Server.cleanUpSakaiDocObject(privdata);\n }\n if (publicToStore) {\n if ($.isPlainObject(publicToStore.structure0)) {\n publicToStore.structure0 = $.toJSON(publicToStore.structure0);\n }\n sakai.api.Server.saveJSON(puburl, publicToStore);\n }\n if (privateToStore) {\n if ($.isPlainObject(privateToStore.structure0)) {\n privateToStore.structure0 = $.toJSON(privateToStore.structure0);\n }\n sakai.api.Server.saveJSON(privurl, privateToStore);\n }\n pubdata.structure0 = setManagerProperty(pubdata.structure0, true);\n generateNav();\n });\n } else {\n generateNav();\n }\n });\n };\n\n var loadSpaceData = function(){\n var userid;\n if (!entityID || entityID == sakai.data.me.user.userid) {\n isMe = true;\n userid = sakai.data.me.user.userid;\n } else {\n userid = entityID;\n }\n privurl = \"/~\" + sakai.api.Util.safeURL(userid) + \"/private/privspace\";\n puburl = \"/~\" + sakai.api.Util.safeURL(userid) + \"/public/pubspace\";\n if (isMe){\n sakai.api.Communication.getUnreadMessagesCountOverview(\"inbox\", function(success, counts){\n messageCounts = counts;\n continueLoadSpaceData(userid);\n });\n } else {\n continueLoadSpaceData(userid);\n }\n\n };\n\n var addCounts = function(){\n if (pubdata && pubdata.structure0) {\n if (contextData && contextData.profile && contextData.profile.counts) {\n addCount(pubdata, \"library\", contextData.profile.counts[\"contentCount\"]);\n addCount(pubdata, \"memberships\", contextData.profile.counts[\"membershipsCount\"]);\n if (isMe) {\n var contactCount = 0;\n // determine the count of contacts to list in lhnav\n if (sakai.data.me.contacts.ACCEPTED && sakai.data.me.contacts.INVITED){\n contactCount = sakai.data.me.contacts.ACCEPTED + sakai.data.me.contacts.INVITED;\n } else if (sakai.data.me.contacts.ACCEPTED){\n contactCount = sakai.data.me.contacts.ACCEPTED;\n } else if (sakai.data.me.contacts.INVITED){\n contactCount = sakai.data.me.contacts.INVITED;\n }\n addCount(pubdata, \"contacts\", contactCount);\n addCount(privdata, \"messages\", sakai.data.me.messages.unread);\n if (messageCounts && messageCounts.count && messageCounts.count.length) {\n for (var i = 0; i < messageCounts.count.length; i++) {\n if (messageCounts.count[i].group && messageCounts.count[i].group === \"message\") {\n addCount(privdata, \"messages/inbox\", messageCounts.count[i].count);\n }\n if (messageCounts.count[i].group && messageCounts.count[i].group === \"invitation\") {\n addCount(privdata, \"messages/invitations\", messageCounts.count[i].count);\n }\n }\n }\n } else {\n addCount(pubdata, \"contacts\", contextData.profile.counts[\"contactsCount\"]);\n }\n }\n }\n };\n\n var determineUserAreaPermissions = function(structure){\n var permission = structure._view || \"anonymous\";\n if (permission === \"contacts\" && isContact) {\n structure._canView = true;\n } else if (permission === \"everyone\" && !sakai.data.me.user.anon) {\n structure._canView = true;\n } else if (permission === \"anonymous\") {\n structure._canView = true;\n } else {\n structure._canView = false;\n }\n for (var i in structure) {\n if (structure.hasOwnProperty(i) && i.substring(0, 1) !== \"_\") {\n structure[i] = determineUserAreaPermissions(structure[i]);\n }\n }\n return structure;\n };\n\n var setManagerProperty = function(structure, value){\n for (var i in structure){\n if (structure.hasOwnProperty(i) && i.substring(0, 1) !== \"_\" && typeof structure[i] === \"object\") {\n structure[i]._canEdit = value;\n structure[i]._canSubedit = value;\n structure[i] = setManagerProperty(structure[i], value);\n }\n }\n return structure;\n };\n\n var addCount = function(pubdata, pageid, count){\n if (pageid.indexOf(\"/\") !== -1) {\n var split = pageid.split(\"/\");\n if (pubdata.structure0 && pubdata.structure0[split[0]] && pubdata.structure0[split[0]][split[1]]) {\n pubdata.structure0[split[0]][split[1]]._count = count;\n }\n } else {\n if (pubdata.structure0 && pubdata.structure0[pageid]) {\n pubdata.structure0[pageid]._count = count;\n }\n }\n };\n\n var getUserPicture = function(profile, userid){\n var picture = \"\";\n if (profile.picture) {\n var picture_name = $.parseJSON(profile.picture).name;\n picture = \"/~\" + sakai.api.Util.safeURL(userid) + \"/public/profile/\" + picture_name;\n }\n return picture;\n };\n\n var determineContext = function(){\n entityID = sakai.api.Util.extractEntity(window.location.pathname);\n if (entityID && entityID !== sakai.data.me.user.userid){\n sakai.api.User.getUser(entityID, getProfileData);\n } else if (!sakai.data.me.user.anon){\n if (entityID){\n document.location = \"/me\" + window.location.hash;\n return;\n }\n sakai.api.Security.showPage();\n contextType = \"user_me\";\n // Set the profile data object\n sakai_global.profile.main.data = $.extend(true, {}, sakai.data.me.profile);\n sakai_global.profile.main.mode.value = \"edit\";\n contextData = {\n \"profile\": sakai.data.me.profile,\n \"displayName\": sakai.api.User.getDisplayName(sakai.data.me.profile),\n \"userid\": sakai.data.me.user.userid,\n \"picture\": getUserPicture(sakai.data.me.profile, sakai.data.me.user.userid),\n \"addArea\": \"user\"\n };\n document.title = document.title + \" \" + sakai.api.Util.Security.unescapeHTML(contextData.displayName);\n renderEntity();\n loadSpaceData();\n } else {\n sakai.api.Security.sendToLogin();\n }\n };\n\n var getProfileData = function(exists, profile){\n if (!profile) {\n sakai.api.Security.sendToLogin();\n } else {\n sakai.api.Security.showPage();\n // Set the profile data object\n sakai_global.profile.main.data = $.extend(true, {}, profile);\n contextData = {\n \"profile\": profile,\n \"displayName\": sakai.api.User.getDisplayName(profile),\n \"userid\": entityID,\n \"altTitle\": true,\n \"picture\": getUserPicture(profile, entityID)\n };\n document.title = document.title + \" \" + sakai.api.Util.Security.unescapeHTML(contextData.displayName);\n if (sakai.data.me.user.anon) {\n contextType = \"user_anon\";\n renderEntity();\n loadSpaceData();\n } else {\n sakai.api.User.getContacts(checkContact);\n }\n }\n };\n\n var checkContact = function(){\n var contacts = sakai.data.me.mycontacts;\n var isContactInvited = false;\n var isContactPending = false;\n for (var i = 0; i < contacts.length; i++){\n if (contacts[i].profile.userid === entityID){\n if (contacts[i].details[\"sakai:state\"] === \"ACCEPTED\") {\n isContact = true;\n } else if (contacts[i].details[\"sakai:state\"] === \"INVITED\"){\n isContactInvited = true;\n } else if (contacts[i].details[\"sakai:state\"] === \"PENDING\"){\n isContactPending = true;\n }\n }\n }\n if (isContact){\n contextType = \"contact\";\n } else if (isContactInvited){\n contextType = \"contact_invited\";\n } else if (isContactPending){\n contextType = \"contact_pending\";\n } else {\n contextType = \"user_other\";\n }\n renderEntity();\n loadSpaceData();\n };\n\n var generateNav = function(){\n addCounts();\n sakai_global.user.pubdata = pubdata;\n if (contextType && contextType === \"user_me\" && contextData && pubdata && privdata) {\n $(window).trigger(\"lhnav.init\", [pubdata, privdata, contextData, puburl, privurl]);\n } else if (contextType && contextType !== \"user_me\" && contextData && pubdata) {\n $(window).trigger(\"lhnav.init\", [pubdata, false, contextData, puburl, privurl]);\n }\n };\n\n var renderEntity = function(){\n if (contextType && contextData) {\n $(window).trigger(\"sakai.entity.init\", [\"user\", contextType, contextData]);\n }\n };\n\n var showWelcomeNotification = function(){\n var querystring = new Querystring();\n if (querystring.contains(\"welcome\") && querystring.get(\"welcome\") === \"true\" && !sakai.data.me.user.anon){\n sakai.api.Util.notification.show(sakai.api.i18n.getValueForKey(\"WELCOME\") + \" \" + sakai.data.me.profile.basic.elements.firstName.value,sakai.api.i18n.getValueForKey(\"YOU_HAVE_CREATED_AN_ACCOUNT\"));\n }\n };\n\n $(window).bind(\"sakai.addToContacts.requested\", function(ev, userToAdd){\n $('.sakai_addtocontacts_overlay').each(function(index) {\n if (entityID && entityID !== sakai.data.me.user.userid){\n contextType = \"contact_pending\";\n renderEntity();\n }\n });\n });\n\n $(\"#entity_user_accept_invitation\").live(\"click\", function(){\n sakai.api.User.acceptContactInvite(contextData.userid);\n contextType = \"contact\";\n renderEntity();\n });\n\n $(window).bind(\"sakai.entity.ready\", function(){\n renderEntity();\n });\n\n $(window).bind(\"lhnav.ready\", function(){\n generateNav();\n });\n\n $(window).bind(\"updated.counts.lhnav.sakai\", function(){\n sakai.api.User.getUpdatedCounts(sakai.data.me, function(success){\n renderEntity();\n generateNav();\n });\n });\n\n $(window).bind(\"done.newaddcontent.sakai\", function(e, data, library) {\n if (isMe && data && data.length && library === sakai.data.me.user.userid) {\n $(window).trigger(\"lhnav.updateCount\", [\"library\", data.length]);\n }\n });\n\n $(window).bind(\"updated.messageCount.sakai\", function(){\n if (isMe){\n sakai.api.Communication.getUnreadMessagesCountOverview(\"inbox\", function(success, counts){\n messageCounts = counts;\n var totalCount = 0;\n // The structure of these objects make for O(n^2) comparison :(\n $.each(messageCounts.count, function(index, countObj){\n var pageid = \"messages/\";\n if (countObj.group === \"message\"){\n pageid += \"inbox\";\n } else if (countObj.group === \"invitation\"){\n pageid += \"invitations\";\n }\n totalCount += countObj.count;\n $(window).trigger(\"lhnav.updateCount\", [pageid, countObj.count, false]);\n });\n $(window).trigger(\"lhnav.updateCount\", [\"messages\", totalCount, false]);\n }, false);\n }\n });\n\n determineContext();\n renderEntity();\n generateNav();\n showWelcomeNotification();\n\n };\n\n sakai.api.Widgets.Container.registerForLoad(\"user\");\n});\n", "dev/layout1.html": "\n\n\n \n\n \n \n \n\n \n \n\n \n \n\n \n \n \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n\n \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n\n \n
            \n\n\n \n \n \n \n\n", "dev/layout2.html": "\n\n\n \n\n \n \n \n\n \n \n\n \n \n\n \n \n \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n\n \n
            \n
            \n
            \n
            \n \n
            \n
            \n
            \n\n \n
            \n\n\n \n \n\n \n\n"}, "files_after": {"dev/403.html": "\n\n\n \n\n \n \n \n \n\n \n \n \n\n \n \n\n \n\n \n\n \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n \n

            __MSG__NO_ACCOUNT__ __MSG__SIGN_UP__

            \n
            \n
            \n
            __MSG__ARE_YOU_LOOKING_FOR__
            \n
            \n
            \n \n
            \n
            \n
            \n \n
            \n
            \n \n
            \n
            \n\n
            \n
            __MSG__BROWSE_CATEGORIES__
            \n
            \n
            \n
            \n

            __MSG__YOU_CAN_BROWSE_THIS_INSTITUTION__ __MSG__CATEGORIES_LC__ __MSG__WHERE_YOU_CAN_CONNECT_WITH_PEOPLE_VIEW_COURSE_DETAILS_SEARCH_FOR_CONTENT_AND_JOIN_GROUPS__

            \n
            \n
            \n \n
            \n
            \n
            \n
            \n \"__MSG__YOU_ARE_NOT_ALLOWED_TO_SEE_THIS_PAGE__\"\n
            \n

            __MSG__YOU_ARE_NOT_ALLOWED_TO_SEE_THIS_PAGE__

            \n

            __MSG__YOU_TRIED_TO_ACCESS_PAGE_WITHOUT_PERMISSIONS__

            \n\n

            __MSG__WHAT_TO_DO_NOW_HERE_ARE_SOME_SUGGESTIONS__

            \n
            \n \n \n
            \n\n \n \n
            \n
            \n
            \n
            \n \n
            \n\n \n \n\n \n \n \n\n", "dev/404.html": "\n\n\n \n\n \n \n \n \n\n \n \n \n\n \n \n\n \n\n \n\n \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n \n

            __MSG__NO_ACCOUNT__ __MSG__SIGN_UP__

            \n
            \n
            \n
            __MSG__ARE_YOU_LOOKING_FOR__
            \n
            \n
            \n \n
            \n
            \n
            \n \n
            \n
            \n \n
            \n
            \n\n
            \n
            __MSG__BROWSE_CATEGORIES__
            \n
            \n
            \n
            \n

            __MSG__YOU_CAN_BROWSE_THIS_INSTITUTION__ 0 __MSG__CATEGORIES_LC__ __MSG__WHERE_YOU_CAN_CONNECT_WITH_PEOPLE_VIEW_COURSE_DETAILS_SEARCH_FOR_CONTENT_AND_JOIN_GROUPS__

            \n
            \n
            \n \n
            \n
            \n
            \n
            \n \"__MSG__THE_PAGE_YOU_REQUESTED_WAS_NOT_FOUND__\"\n
            \n

            __MSG__THE_PAGE_YOU_REQUESTED_WAS_NOT_FOUND__

            \n

            __MSG__POSSIBLE_REASONS_FOR_THE_PAGE_NOT_BEING_FOUND__

            \n
            \n
            \n
            \n

            __MSG__WHAT_TO_DO_NOW_HERE_ARE_SOME_SUGGESTIONS__

            \n
            \n \n \n
            \n\n \n \n
            \n
            \n
            \n
            \n \n
            \n\n \n \n\n \n \n \n\n", "dev/500.html": "\n\n\n \n\n \n \n \n \n\n \n \n \n\n \n \n\n \n\n \n\n \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n \n

            __MSG__NO_ACCOUNT__ __MSG__SIGN_UP__

            \n
            \n
            \n
            __MSG__ARE_YOU_LOOKING_FOR__
            \n
            \n
            \n \n
            \n
            \n
            \n \n
            \n
            \n \n
            \n
            \n\n
            \n
            __MSG__BROWSE_CATEGORIES__
            \n
            \n
            \n
            \n

            __MSG__YOU_CAN_BROWSE_THIS_INSTITUTION__ __MSG__CATEGORIES_LC__ __MSG__WHERE_YOU_CAN_CONNECT_WITH_PEOPLE_VIEW_COURSE_DETAILS_SEARCH_FOR_CONTENT_AND_JOIN_GROUPS__

            \n
            \n
            \n \n
            \n
            \n
            \n
            \n \"__MSG__OOPS_AN_ERROR_HAS_OCCURRED__\"\n
            \n

            __MSG__OOPS_AN_ERROR_HAS_OCCURRED__

            \n

            \n\n

            __MSG__WHAT_TO_DO_NOW_HERE_ARE_SOME_SUGGESTIONS__

            \n
            \n \n \n
            \n\n \n \n
            \n
            \n
            \n
            \n \n
            \n\n \n \n\n \n \n \n\n", "dev/acknowledgements.html": "\n\n\n \n\n \n \n \n\n \n \n\n \n \n \n \n \n\n \n \n \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n \n \n \n \n
            \n \n
            \n\n \n
            \n
            \n
            \n
            \n \"__MSG__JQUERY__\"\n \"__MSG__JQUERY__\"\n
            \n
            \n

            __MSG__JQUERY_AND_JQUERY_UI__

            \n www.jquery.com

            \n __MSG__JQUERY_IS_A_FAST_AND_CONCISE__\n
            \n
            \n
            \n
            \n\n \n
            \n
            \n
            \n
            \n \"__MSG__APACHE_SLING__\"\n
            \n
            \n

            __MSG__APACHE_SLING__

            \n sling.apache.org

            \n __MSG__APACHE_SLING_IS_A_WEB_FRAMWORK__\n
            \n
            \n
            \n
            \n\n \n
            \n
            \n
            \n
            \n \"__MSG__FLUID_INFUSION__\"\n
            \n
            \n

            __MSG__FLUID_INFUSION__

            \n http://www.fluidproject.org/products/infusion

            \n __MSG__WE_THINK_GOOD_INTERFACES__\n
            \n
            \n
            \n
            \n\n
            \n
            \n
            \n\n \n
            \n __MSG__THE_PRODUCT_INCLUDES_SOFTWARE_FROM__\n\n
            \n

            __MSG__TRIMPATH__

            \n http://code.google.com/p/trimpath/wiki/JavaScriptTemplates\n
            \n __MSG__JAVASCRIPT_TEMPLATES__\n
            \n
            \n

            __MSG__MOXIECODE_SYSTEMS_AB__

            \n tinymce.moxiecode.com\n
            \n __MSG__TINYMCE_JAVASCRIPT_WYSIWYG_EDITOR__\n
            \n
            \n

            __MSG__GOOGLE_INC__

            \n http://code.google.com/p/google-caja/wiki/JsHtmlSanitizer\n
            \n __MSG__JSHTMLSANITIZER_LIBRARY_FROM_THE_CAJA_PROJECT__\n
            \n
            \n

            __MSG__JORDAN_BOESH__

            \n www.boedesign.com\n
            \n __MSG__GRITTER_JQUERY_PLUGIN__\n
            \n
            \n

            __MSG__BRICE_BURGESS__

            \n http://dev.iceburg.net/jquery/jqModal\n
            \n __MSG__JQMODAL_JQUERY_PLUGIN__\n
            \n
            \n

            __MSG__DREW_WILSON__

            \n http://code.drewwilson.com/entry/autosuggest-jquery-plugin\n
            \n __MSG__AUTOSUGGEST_JQUERY_PLUGIN__\n
            \n
            \n

            __MSG__COWBOY_BEN_ALMAN__

            \n http://benalman.com/about/license\n
            \n __MSG__JQUERY_BBQ__\n
            \n
            \n

            __MSG__KLAUS_HARTL__

            \n stilbuero.de\n
            \n __MSG__COOKIE_JQUERY_PLUGIN__\n
            \n
            \n

            __MSG__MIKE_ALSUP__

            \n http://malsup.com/jquery/form\n
            \n __MSG__JQUERY_FORM_PLUGIN__\n
            \n
            \n

            __MSG__MICHAL_WOJCIECHOWSKI__

            \n http://odyniec.net/projects/imgareaselect\n
            \n __MSG__IMGAREASELECT_JQUERY_PLUGIN__\n
            \n
            \n

            __MSG__MIKA_TUUPOLA_DYLAN_VERHEUL__

            \n http://www.appelsiini.net/projects/jeditable\n
            \n __MSG__JEDITABLE_JQUERY_PLUGIN__\n
            \n
            \n

            __MSG__BRANTLEY_HARRIS__

            \n http://code.google.com/p/jquery-json\n
            \n __MSG__JQUERY_JSON_PLUGIN__\n
            \n
            \n

            __MSG__IVAN_BOSZHANOV__

            \n jstree.com\n
            \n __MSG__JSTREE_JQUERY_PLUGIN__\n
            \n
            \n

            __MSG__FYNETWORKS_COM__

            \n http://www.fyneworks.com/jquery/multiple-file-upload\n
            \n __MSG__JQUERY_MULTIPLE_FILE_UPLOAD_PLUGIN__\n
            \n
            \n

            __MSG__JON_PAUL_DAVIES__

            \n http://jonpauldavies.github.com/JQuery/Pager\n
            \n __MSG__JQUERY_PAGER_PLUGIN__\n
            \n
            \n

            __MSG__AUTHOR_JEREMY_HORN__

            \n http://tpgblog.com/ThreeDots\n
            \n __MSG__THREEDOTS_JQUERY_PLUGIN__\n
            \n
            \n

            __MSG__RYAN_MCGEARY__

            \n timeago.yarp.com\n
            \n __MSG__TIMEAGO_JQUERY_PLUGIN__\n
            \n
            \n

            __MSG__JORN_ZAEFFERER__

            \n http://bassistance.de/jquery-plugins/jquery-plugin-validation\n
            \n __MSG__JQUERY_VALIDATION_PLUGIN__\n
            \n
            \n

            __MSG__ADAM_VANDENBERG__

            \n http://adamv.com/dev/javascript/querystring\n
            \n __MSG__QUERYSTRING__\n
            \n
            \n

            __MSG__DOMINIC_MITCHELL__

            \n http://search.cpan.org/~hdm/JavaScript-JSLint-0.06\n
            \n __MSG__JAVASCRIPT_JSLINT__\n
            \n
            \n

            __MSG__MICHAEL_MATHEWS__

            \n http://code.google.com/p/jsdoc-toolkit\n
            \n __MSG__JSDOC_TOOLKIT__\n
            \n
            \n

            __MSG__YAHOO_INC__

            \n http://developer.yahoo.com/yui/compressor\n
            \n __MSG__YUI_COMPRESSOR__\n
            \n
            \n

            __MSG__YUSUKE_KAMIYAMANE__

            \n p.yusukekamiyamane.com\n
            \n __MSG__FUGUE_ICONS__\n
            \n
            \n

            __MSG__MARK_JAMES__

            \n http://www.famfamfam.com/lab/icons/silk\n
            \n __MSG__SILK_ICONS__\n
            \n
            \n

            __MSG__APACHE_SOFTWARE_FOUNDATION__

            \n www.apache.org\n
            \n
            \n
            \n

            __MSG__ANT_CONTRIB__

            \n http://sourceforge.net/projects/ant-contrib\n
            \n
            \n\n
            \n
            \n
            \n\n \n
            \n\n \n
            \n

            __MSG__NAKAMURA_THE_SERVER_PART_OF_SAKAI_3__

            \n
              \n
            • __MSG__APACHE_ARIES_JMX_API__
            • \n
            • __MSG__APACHE_ARIES_JMS_CORE__
            • \n
            • __MSG__APACHE_COMMONS_IO_BUNDLE__
            • \n
            • __MSG__APACHE_DERBY__
            • \n
            • __MSG__APACHE_FELIX_BUNDLE_REPOSITORY__
            • \n
            • __MSG__APACHE_FELIX_CONFIGURATION_ADMIN_SERVICE__
            • \n
            • __MSG__APACHE_FELIX_DECLARATIVE_SERVICES__
            • \n
            • __MSG__APACHE_FELIX_EVENTADMIN__
            • \n
            • __MSG__APACHE_FELIX_FILE_INSTALL__
            • \n
            • __MSG__APACHE_FELIX_HTTP_WHITEBOARD__
            • \n
            • __MSG__APACHE_FELIX_METATYPE_SERVICE__
            • \n
            • __MSG__APACHE_FELIX_WEB_CONSOLE_EVENT_PLUGIN__
            • \n
            • __MSG__APACHE_FELIX_WEB_CONSOLE_MEMORY_USAGE_PLUGIN__
            • \n
            • __MSG__APACHE_FELIX_WEB_MANAGEMENT_CONSOLE__
            • \n
            • __MSG__APACHE_JACKRABBIT_API__
            • \n
            • __MSG__APACHE_SLING_ADAPTER_MANAGER_IMPLEMENTATION__
            • \n
            • __MSG__APACHE_SLING_API__
            • \n
            • __MSG__APACHE_SLING_AUTHENTICATION_SERVICE__
            • \n
            • __MSG__APACHE_SLING_BUNDLE_RESOURCE_PROVIDER__
            • \n
            • __MSG__APACHE_SLING_COMMONS_OSGI_SUPPORT__
            • \n
            • __MSG__APACHE_SLING_DEFAULT_GET_SERVLETS__
            • \n
            • __MSG__APACHE_SLING_DEFAULT_POST_SERVLETS__
            • \n
            • __MSG__APACHE_SLING_DYNAMIC_CLASS_LOADER_SUPPORT__
            • \n
            • __MSG__APACHE_SLING_ENGINE_IMPLEMENTATION__
            • \n
            • __MSG__APACHE_SLING_FILESYSTEM_RESOURCE_PROVIDER__
            • \n
            • __MSG__APACHE_SLING_GROOVY_EXTENSION__
            • \n
            • __MSG__APACHE_SLING_INITIAL_CONTENT_LOADER__
            • \n
            • __MSG__APACHE_SLING_JACKRABBIT_EMBEDDED_REPOSITORY__
            • \n
            • __MSG__APACHE_SLING_JACKRABBIT_JSR_ACCESS_CONTROL_MANAGER_SUPPORT__
            • \n
            • __MSG__APACHE_SLING_JCR_BASE_BUNDLE__
            • \n
            • __MSG__APACHE_SLING_JCR_CLASSLOADER__
            • \n
            • __MSG__APACHE_SLING_JCR_RESOURCE_RESOLVER__
            • \n
            • __MSG__APACHE_SLING_JCR_WEBCONSOLE_BUNDLE__
            • \n
            • __MSG__APACHE_SLING_JSON_LIBRARY__
            • \n
            • __MSG__APACHE_SLING_JSP_TAG_LIBRARY__
            • \n
            • __MSG__APACHE_SLING_LAUNCHPAD_CONTENT__
            • \n
            • __MSG__APACHE_SLING_MIME_TYPE_MAPPING_SUPPORT__
            • \n
            • __MSG__APACHE_SLING_OBJECT_CONTENT_MAPPING__
            • \n
            • __MSG__APACHE_SLING_OPENID_AUTHENTICATION__
            • \n
            • __MSG__APACHE_SLING_OSGI_LOGSERVICE_IMPLEMENTATION__
            • \n
            • __MSG__APACHE_SLING_REPOSITORY_API_BUNDLE__
            • \n
            • __MSG__APACHE_SLING_SCHEDULER_SUPPORT__
            • \n
            • __MSG__APACHE_SLING_SCRIPTING_CORE_IMPLEMENTATION__
            • \n
            • __MSG__APACHE_SLING_SCRIPTING_IMPLEMENTATION_API__
            • \n
            • __MSG__APACHE_SLING_SCRIPTING_JAVASCRIPT_SUPPORT__
            • \n
            • __MSG__APACHE_SLING_SCRIPTING_JSP_SUPPORT__
            • \n
            • __MSG__APACHE_SLING_SERVLET_RESOLVER__
            • \n
            • __MSG__APACHE_SLING_SETTINGS__
            • \n
            • __MSG__APACHE_SLING_THREAD_DUMPER__
            • \n
            • __MSG__APACHE_SLING_THREAD_SUPPORT__
            • \n
            • __MSG__APACHE_SLING_WEB_CONSOLE_BRANDING__
            • \n
            • __MSG__APACHE_SLING_WEB_CONSOLE_SECURITY_PROVIDER__
            • \n
            • __MSG__COMMONS_CODE__
            • \n
            • __MSG__COMMONS_COLLECTIONS__
            • \n
            • __MSG__COMMONS_EMAIL__
            • \n
            • __MSG__COMMONS_FILEUPLOAD__
            • \n
            • __MSG__COMMONS_LANG__
            • \n
            • __MSG__COMMONS_POOL__
            • \n
            • __MSG__CONTENT_REPOSITORY_FOR_JAVATM_TECHNOLOGY_API__
            • \n
            • __MSG__GERONIMO_EJB__
            • \n
            • __MSG__GERONIMO_J2EE_CONNECTOR__
            • \n
            • __MSG__GERONIMO_J2EE_MANAGEMENT__
            • \n
            • __MSG__GERONIMO_JMS__
            • \n
            • __MSG__GERONIMO_JTA__
            • \n
            • __MSG__GROOVY_RUNTIME__
            • \n
            • __MSG__JACKRABBIT_JCR_COMMONS__
            • \n
            • __MSG__JACKRABBIT_JCR_RMI__
            • \n
            • __MSG__JACKRABBIT_SPI__
            • \n
            • __MSG__JACKRABBIT_SPI_COMMONS__
            • \n
            • __MSG__JAXB_API__
            • \n
            • __MSG__NAKAMURA_HTTP_JETTY__
            • \n
            • __MSG__OPS4J_PAX_WEB_SERVICE__
            • \n
            • __MSG__SAKAI_3_UX_LOADER__
            • \n
            • __MSG__SAKAI_NAKAMURA_ACTIVE_MQ_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_ACTIVITY_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_APACHE_COMMONS_HTTPCLIENT_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_AUTHORIZATION_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_BASIC_LTI_CONSUMER_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_BATCH_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_CALENDAR_BASED_EVENTS_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_CAPTCHA_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_CHAT_SERVICES_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_CONFIGURATION_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_CONNECTIONS_MANAGEMENT_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_DATABASE_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_DISCUSSION_MANAGEMENT_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_DOCUMENT_PROXY__
            • \n
            • __MSG__SAKAI_NAKAMURA_DOCUMENTATION_SUPPORT_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_FILES_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_FORM_AUTH_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_GOOGLE_COLLECTIONS__
            • \n
            • __MSG__SAKAI_NAKAMURA_HTTP_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_IMAGE_SERVICE__
            • \n
            • __MSG__SAKAI_NAKAMURA_JAVAX_ACTIVATION_AND_MAIL_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_JAXP_API_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_JCR_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_JSON_LIB_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_LOCKING_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_ME_SERVICE_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_MEMORY_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_MESSAGING_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_MODEL_DIRECTORY__
            • \n
            • __MSG__SAKAI_NAKAMURA_OSGI_TO_JMS_EVENTS_BRIDGE_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_OUTGOING_EMAIL_SENDER__
            • \n
            • __MSG__SAKAI_NAKAMURA_PAGES_STRUCTURED_CONTENT__
            • \n
            • __MSG__SAKAI_NAKAMURA_PERSONAL_SPACE_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_PRESENCE_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_PROFILE_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_PROXY_SERVICE__
            • \n
            • __MSG__SAKAI_NAKAMURA_SAKAI_CLUSTER_TRACKING__
            • \n
            • __MSG__SAKAI_NAKAMURA_SEARCH_SUPPORT_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_SECURITY_LOADER_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_SITE_SERVICE_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_SLING_RESOURCE_EXTENSION BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_SMTP_SERVER__
            • \n
            • __MSG__SAKAI_NAKAMURA_SOLR_BASED_SEARCH_SERVICE__
            • \n
            • __MSG__SAKAI_NAKAMURA_SPARSE_MAP_CONTENT_STORAGE_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_TEMPLATES_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_TIKA_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_TRUSTED_AUTHENTICATION_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_USER_EXTENSIONS_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_UTILITIES__
            • \n
            • __MSG__SAKAI_NAKAMURA_VERSION_EXTENSION_BUNDLE__
            • \n
            • __MSG__SAKAI_NAKAMURA_WOODSTOX_STAX__
            • \n
            • __MSG__SAKAI_NAKAMURA_WORLD_SUPPORT__
            • \n
            \n
            \n\n __MSG__COPYRIGHT_THE_SAKAI_FOUNDATION__\n
            \n
            \n\n \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n\n \n
            \n\n\n \n \n\n \n \n \n\n", "dev/allcategories.html": "\n\n \n \n \n \n \n \n \n \n \n \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            __MSG__ALL_CATEGORIES__
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n \n
            \n\n \n \n \n \n", "dev/category.html": "\n\n \n \n \n \n \n \n \n \n \n \n
            __MSG__IE_PLACEHOLDER__
            \n \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n \n
            \n\n \n \n \n \n", "dev/configuration/config.js": "/*\n * Licensed to the Sakai Foundation (SF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The SF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations under the License.\n */\ndefine(function(){\n var config = {\n URL: {\n // Static URLs\n GATEWAY_URL: \"/\",\n GROUP_DEFAULT_ICON_URL: \"/dev/images/group_avatar_icon_64x64_nob.png\",\n GROUP_DEFAULT_ICON_URL_LARGE: \"/dev/images/group_avatar_icon_100x100_nob.png\",\n I10N_BUNDLE_URL: \"/dev/lib/misc/l10n/cultures/globalize.culture.__CODE__.js\",\n I18N_BUNDLE_ROOT: \"/dev/bundle/\",\n INBOX_URL: \"/me#l=messages/inbox\",\n INVITATIONS_URL: \"/me#l=messages/invitations\",\n LOGOUT_URL: \"/logout\",\n MY_DASHBOARD_URL: \"/me#l=dashboard\",\n PROFILE_EDIT_URL: \"/me#l=profile/basic\",\n SEARCH_ACTIVITY_ALL_URL: \"/var/search/activity/all.json\",\n SEARCH_URL: \"/search\",\n TINY_MCE_CONTENT_CSS: \"/dev/css/FSS/fss-base.css,/dev/css/sakai/main.css,/dev/css/sakai/sakai.corev1.css,/dev/css/sakai/sakai.base.css,/dev/css/sakai/sakai.editor.css,/dev/css/sakai/sakai.content_profile.css\",\n USER_DEFAULT_ICON_URL: \"/dev/images/default_User_icon_50x50.png\",\n USER_DEFAULT_ICON_URL_LARGE: \"/dev/images/default_User_icon_100x100.png\",\n INFINITE_LOADING_ICON: \"/dev/images/Infinite_Scrolling_Loader_v01.gif\",\n\n // Services\n BATCH: \"/system/batch\",\n CAPTCHA_SERVICE: \"/system/captcha\",\n CONTACTS_FIND: \"/var/contacts/find.json\",\n CONTACTS_FIND_STATE: \"/var/contacts/findstate.json\",\n CONTACTS_FIND_ALL: \"/var/contacts/find-all.json\",\n CREATE_USER_SERVICE: \"/system/userManager/user.create.html\",\n DISCUSSION_GETPOSTS_THREADED: \"/var/search/discussions/threaded.json?path=__PATH__&marker=__MARKER__\",\n GOOGLE_CHARTS_API: \"http://chart.apis.google.com/chart\",\n GROUP_CREATE_SERVICE: \"/system/userManager/group.create.json\",\n GROUPS_MANAGER: \"/system/me/managedgroups.json\",\n GROUPS_MEMBER: \"/system/me/groups.json\",\n IMAGE_SERVICE: \"/var/image/cropit\",\n LOGIN_SERVICE: \"/system/sling/formlogin\",\n LOGOUT_SERVICE: \"/system/sling/logout?resource=/index\",\n ME_SERVICE: \"/system/me\",\n MESSAGE_BOX_SERVICE: \"/var/message/box.json\",\n MESSAGE_BOXCATEGORY_SERVICE: \"/var/message/boxcategory.json\",\n MESSAGE_BOXCATEGORY_ALL_SERVICE: \"/var/message/boxcategory-all.json\",\n POOLED_CONTENT_MANAGER: \"/var/search/pool/me/manager.json\",\n POOLED_CONTENT_MANAGER_ALL: \"/var/search/pool/me/manager-all.json\",\n POOLED_CONTENT_VIEWER: \"/var/search/pool/me/viewer.json\",\n POOLED_CONTENT_VIEWER_ALL: \"/var/search/pool/me/viewer-all.json\",\n POOLED_CONTENT_SPECIFIC_USER: \"/var/search/pool/manager-viewer.json\",\n POOLED_CONTENT_ACTIVITY_FEED: \"/var/search/pool/activityfeed.json\",\n PRESENCE_SERVICE: \"/var/presence.json\",\n SAKAI2_TOOLS_SERVICE: \"/var/proxy/s23/site.json?siteid=__SITEID__\",\n WORLD_CREATION_SERVICE: \"/system/world/create\",\n WORLD_INFO_URL: \"/var/templates/worlds.2.json\",\n\n // Replace these in widgets with proper widgetsave functions from magic\n SEARCH_ALL_ENTITIES: \"/var/search/general.json\",\n SEARCH_ALL_ENTITIES_ALL: \"/var/search/general-all.json\",\n SEARCH_ALL_FILES: \"/var/search/pool/all.json\",\n SEARCH_ALL_FILES_ALL: \"/var/search/pool/all-all.json\",\n SEARCH_MY_BOOKMARKS: \"/var/search/files/mybookmarks.json\",\n SEARCH_MY_BOOKMARKS_ALL: \"/var/search/files/mybookmarks-all.json\",\n SEARCH_MY_CONTACTS: \"/var/search/files/mycontacts.json\",\n SEARCH_MY_FILES: \"/var/search/files/myfiles.json\",\n SEARCH_MY_FILES_ALL: \"/var/search/files/myfiles-all.json\",\n SEARCH_GROUP_MEMBERS: \"/var/search/groupmembers.json\",\n SEARCH_GROUP_MEMBERS_ALL: \"/var/search/groupmembers-all.json\",\n SEARCH_GROUPS: \"/var/search/groups.infinity.json\",\n SEARCH_GROUPS_ALL: \"/var/search/groups-all.json\",\n SEARCH_USERS_ACCEPTED: \"/var/contacts/findstate.infinity.json\",\n SEARCH_USERS: \"/var/search/users.infinity.json\",\n SEARCH_USERS_ALL: \"/var/search/users-all.json\",\n SEARCH_USERS_GROUPS: \"/var/search/usersgroups.json\",\n SEARCH_USERS_GROUPS_ALL: \"/var/search/usersgroups-all.json\",\n USER_CHANGEPASS_SERVICE: \"/system/userManager/user/__USERID__.changePassword.html\",\n USER_EXISTENCE_SERVICE: \"/system/userManager/user.exists.html?userid=__USERID__\"\n },\n\n PageTitles: {\n \"prefix\": \"TITLE_PREFIX\",\n \"pages\": {\n /** 403.html **/\n /** 404.html **/\n /** 500.html **/\n /** account_preferences.html **/\n \"/dev/account_preferences.html\": \"ACCOUNT_PREFERENCES\",\n \"/preferences\": \"ACCOUNT_PREFERENCES\",\n /** acknowledgements.html **/\n \"/dev/acknowledgements.html\": \"ACKNOWLEDGEMENTS\",\n \"/acknowledgements\": \"ACKNOWLEDGEMENTS\",\n /** allcategories.html **/\n \"/categories\": \"BROWSE_ALL_CATEGORIES\",\n \"/dev/allcategories.html\": \"BROWSE_ALL_CATEGORIES\",\n /** category.html **/\n /** content_profile.html **/\n \"/dev/content_profile.html\": \"CONTENT_PROFILE\",\n \"/content\": \"CONTENT_PROFILE\",\n /** create_new_account.html **/\n \"/dev/create_new_account.html\": \"CREATE_A_NEW_ACCOUNT\",\n \"/register\": \"CREATE_A_NEW_ACCOUNT\",\n /** explore.html **/\n \"/\": \"EXPLORE\",\n \"/dev\": \"EXPLORE\",\n \"/dev/\": \"EXPLORE\",\n \"/index.html\": \"EXPLORE\",\n \"/dev/explore.html\": \"EXPLORE\",\n \"/index\": \"EXPLORE\",\n /** logout.html **/\n \"/dev/logout.html\": \"LOGGING_OUT\",\n \"/logout\": \"LOGGING_OUT\",\n /** search.html **/\n \"/dev/search.html\": \"SEARCH\",\n \"/search\": \"SEARCH\",\n /** createnew.html **/\n \"/create\": \"CREATE\"\n }\n },\n\n ErrorPage: {\n /*\n * These links are displayed in the 403 and 404 error pages.\n */\n Links: {\n whatToDo: [{\n \"title\": \"EXPLORE_THE_INSTITUTION\",\n \"url\": \"/index\"\n }, {\n \"title\": \"BROWSE_INSTITUTION_CATEGORIES\",\n \"url\": \"/categories\"\n }, {\n \"title\": \"VIEW_THE_INSTITUTION_WEBSITE\",\n \"url\": \"http://sakaiproject.org/\"\n }, {\n \"title\": \"VISIT_THE_SUPPORT_FORUM\",\n \"url\": \"http://sakaiproject.org/\"\n }],\n getInTouch: [{\n \"title\": \"SEND_US_YOUR_FEEDBACK\",\n \"url\": \"http://sakaiproject.org/\"\n }, {\n \"title\": \"CONTACT_SUPPORT\",\n \"url\": \"http://sakaiproject.org/\"\n }]\n }\n },\n\n Domain: {\n /*\n * These domain labels can be used anywhere on the site (i.e in the video\n * widget) to convert common domains into shorter, more readable labels\n * for display purposes.\n */\n Labels: {\n \"youtube.com\": \"YouTube\",\n \"www.youtube.com\": \"YouTube\",\n \"youtube.co.uk\": \"YouTube\",\n \"www.youtube.co.uk\": \"YouTube\",\n \"vimeo.com\": \"Vimeo\",\n \"www.vimeo.com\": \"Vimeo\",\n \"vimeo.co.uk\": \"Vimeo\",\n \"www.vimeo.co.uk\": \"Vimeo\",\n \"video.google.com\": \"Google Video\"\n }\n },\n\n SakaiDomain: window.location.protocol + \"//\" + window.location.host,\n\n Permissions: {\n /*\n * A collection of permission keys and range of values to be referenced\n * for making permissions decisions. The values of properties are only\n * for reference, may not match designs and are not to be placed in the\n * UI (message bundles should be used to match up-to-date designs).\n */\n Groups: {\n joinable: {\n \"manager_add\": \"no\", // Managers add people\n \"user_direct\": \"yes\", // People can automatically join\n \"user_request\": \"withauth\" // People request to join\n },\n visible: {\n \"members\": \"members-only\", // Group members only (includes managers)\n \"allusers\": \"logged-in-only\", // All logged in users\n \"public\": \"public\" // Anyone on the Internet\n },\n \"defaultaccess\": \"public\", // public, logged-in-only or members-only (see above for role description)\n \"defaultjoin\": \"yes\", // no, yes, or withauth (see above for descriptions)\n \"addcontentmanagers\": true // true, false. If set to yes, group managers will be added as manager for a file \n // added to a group library in context of that group\n },\n Content: {\n /*\n * public - anyone\n * everyone - logged in users\n * private - private\n */\n \"defaultaccess\": \"public\" // public, everyone or private (see above for role description)\n },\n Documents: {\n /*\n * public - anyone\n * everyone - logged in users\n * private - private\n */\n \"defaultaccess\": \"public\" // public, everyone or private (see above for role description)\n },\n Links: {\n \"defaultaccess\": \"public\" // public, everyone or private (see above for role description)\n },\n Copyright: {\n types: {\n \"creativecommons\": {\n \"title\": \"CREATIVE_COMMONS_LICENSE\"\n },\n \"copyrighted\": {\n \"title\": \"COPYRIGHTED\"\n },\n \"nocopyright\": {\n \"title\": \"NO_COPYRIGHT\"\n },\n \"licensed\": {\n \"title\": \"LICENSED\"\n },\n \"waivecopyright\": {\n \"title\": \"WAIVE_COPYRIGHT\"\n }\n },\n defaults: {\n \"content\": \"creativecommons\",\n \"sakaidocs\": \"creativecommons\",\n \"links\": \"creativecommons\",\n \"collections\": \"creativecommons\"\n }\n }\n },\n\n allowPasswordChange: true,\n\n Profile: {\n /*\n * This is a collection of profile configuration functions and settings\n * The structure of the config object is identical to the storage object\n * When system/me returns profile data for the logged in user the profile_config and profile_data objects could be merged\n * \"label\": the internationalizable message for the entry label in HTML\n * \"required\": {Boolean} Whether the entry is compulsory or not\n * \"display\": {Boolean} Show the entry in the profile or not\n * \"editable\": {Boolean} Whether or not the entry is editable\n * For a date entry field use \"date\" as the type for MM/dd/yyyy and \"dateITA\" as the type for dd/MM/yyyy\n *\n */\n configuration: {\n\n defaultConfig: {\n\n \"basic\": {\n \"label\": \"__MSG__PROFILE_BASIC_LABEL__\",\n \"required\": true,\n \"display\": true,\n \"access\": \"everybody\",\n \"modifyacl\": false,\n \"permission\": \"anonymous\",\n \"order\": 0,\n \"elements\": {\n \"firstName\": {\n \"label\": \"__MSG__PROFILE_BASIC_FIRSTNAME_LABEL__\",\n \"errorMessage\": \"__MSG__PROFILE_BASIC_FIRSTNAME_ERROR__\",\n \"required\": true,\n \"display\": true,\n \"limitDisplayWidth\": 300\n },\n \"lastName\": {\n \"label\": \"__MSG__PROFILE_BASIC_LASTNAME_LABEL__\",\n \"errorMessage\": \"__MSG__PROFILE_BASIC_LASTNAME_ERROR__\",\n \"required\": true,\n \"display\": true,\n \"limitDisplayWidth\": 300\n },\n \"picture\": {\n \"label\": \"__MSG__PROFILE_BASIC_PICTURE_LABEL__\",\n \"required\": false,\n \"display\": false\n },\n \"preferredName\": {\n \"label\": \"__MSG__PROFILE_BASIC_PREFERREDNAME_LABEL__\",\n \"required\": false,\n \"display\": true\n },\n \"email\": {\n \"label\": \"__MSG__PROFILE_BASIC_EMAIL_LABEL__\",\n \"errorMessage\": \"__MSG__PROFILE_BASIC_EMAIL_ERROR__\",\n \"required\": true,\n \"display\": true,\n \"validation\": \"email\"\n },\n \"status\": {\n \"label\": \"__MSG__PROFILE_BASIC_STATUS_LABEL__\",\n \"required\": false,\n \"display\": false\n },\n \"role\": {\n \"label\": \"__MSG__PROFILE_BASIC_ROLE_LABEL__\",\n \"required\": false,\n \"display\": true,\n \"type\": \"select\",\n \"select_elements\": {\n \"academic_related_staff\": \"__MSG__PROFILE_BASIC_ROLE_ACADEMIC_RELATED_STAFF_LABEL__\",\n \"academic_staff\": \"__MSG__PROFILE_BASIC_ROLE_ACADEMIC_STAFF_LABEL__\",\n \"assistent_staff\": \"__MSG__PROFILE_BASIC_ROLE_ASSISTENT_STAFF_LABEL__\",\n \"graduate_student\": \"__MSG__PROFILE_BASIC_ROLE_GRADUATE_STUDENT_LABEL__\",\n \"undergraduate_student\": \"__MSG__PROFILE_BASIC_ROLE_UNDERGRADUATE_STUDENT_LABEL__\",\n \"non_academic_staff\": \"__MSG__PROFILE_BASIC_ROLE_NON_ACADEMIC_STAFF_LABEL__\",\n \"postgraduate_student\": \"__MSG__PROFILE_BASIC_ROLE_POSTGRADUATE_STUDENT_LABEL__\",\n \"research_staff\": \"__MSG__PROFILE_BASIC_ROLE_RESEARCH_STAFF_LABEL__\",\n \"other\": \"__MSG__PROFILE_BASIC_ROLE_OTHER_LABEL__\"\n }\n },\n \"department\": {\n \"label\": \"__MSG__PROFILE_BASIC_DEPARTMENT_LABEL__\",\n \"required\": false,\n \"display\": true\n },\n \"college\": {\n \"label\": \"__MSG__PROFILE_BASIC_COLLEGE_LABEL__\",\n \"required\": false,\n \"display\": true\n },\n \"tags\": {\n \"label\": \"__MSG__TAGS_AND_CATEGORIES__\",\n \"required\": false,\n \"display\": true,\n \"type\": \"tags\",\n \"tagField\": true\n }\n }\n },\n \"aboutme\": {\n \"label\": \"__MSG__PROFILE_ABOUTME_LABEL__\",\n \"required\": true,\n \"display\": true,\n \"access\": \"everybody\",\n \"modifyacl\": true,\n \"permission\": \"anonymous\",\n \"order\": 1,\n \"elements\": {\n \"aboutme\": {\n \"label\": \"__MSG__PROFILE_ABOUTME_LABEL__\",\n \"required\": false,\n \"display\": true,\n \"type\": \"textarea\"\n },\n \"academicinterests\": {\n \"label\": \"__MSG__PROFILE_ABOUTME_ACADEMICINTERESTS_LABEL__\",\n \"required\": false,\n \"display\": true,\n \"type\": \"textarea\"\n },\n \"personalinterests\": {\n \"label\": \"__MSG__PROFILE_ABOUTME_PERSONALINTERESTS_LABEL__\",\n \"required\": false,\n \"display\": true,\n \"type\": \"textarea\"\n },\n \"hobbies\": {\n \"label\": \"__MSG__PROFILE_ABOUTME_HOBBIES_LABEL__\",\n \"required\": false,\n \"display\": true\n }\n }\n },\n \"publications\": {\n \"label\": \"__MSG__PROFILE_PUBLICATIONS_LABEL__\",\n \"required\": false,\n \"display\": true,\n \"access\": \"everybody\",\n \"modifyacl\": true,\n \"permission\": \"anonymous\",\n \"multiple\": true,\n \"multipleLabel\": \"__MSG__PROFILE_PUBLICATION_LABEL__\",\n \"order\": 2,\n //\"template\": \"profile_section_publications_template\",\n \"elements\": {\n \"maintitle\": {\n \"label\": \"__MSG__PROFILE_PUBLICATIONS_MAIN_TITLE__\",\n \"required\": true,\n \"display\": true,\n \"example\": \"__MSG__PROFILE_PUBLICATIONS_MAIN_TITLE_EXAMPLE__\"\n },\n \"mainauthor\": {\n \"label\": \"__MSG__PROFILE_PUBLICATIONS_MAIN_AUTHOR__\",\n \"required\": true,\n \"display\": true\n },\n \"coauthor\": {\n \"label\": \"__MSG__PROFILE_PUBLICATIONS_CO_AUTHOR__\",\n \"required\": false,\n \"display\": true,\n \"example\": \"__MSG__PROFILE_PUBLICATIONS_CO_AUTHOR_EXAMPLE__\"\n },\n \"publisher\": {\n \"label\": \"__MSG__PROFILE_PUBLICATIONS_PUBLISHER__\",\n \"required\": true,\n \"display\": true\n },\n \"placeofpublication\": {\n \"label\": \"__MSG__PROFILE_PUBLICATIONS_PLACE_OF_PUBLICATION__\",\n \"required\": true,\n \"display\": true\n },\n \"volumetitle\": {\n \"label\": \"__MSG__PROFILE_PUBLICATIONS_VOLUME_TITLE__\",\n \"required\": false,\n \"display\": true\n },\n \"volumeinformation\": {\n \"label\": \"__MSG__PROFILE_PUBLICATIONS_VOLUME_INFORMATION__\",\n \"required\": false,\n \"display\": true,\n \"example\": \"__MSG__PROFILE_PUBLICATIONS_VOLUME_INFORMATION_EXAMPLE__\"\n },\n \"year\": {\n \"label\": \"__MSG__PROFILE_PUBLICATIONS_YEAR__\",\n \"required\": true,\n \"display\": true\n },\n \"number\": {\n \"label\": \"__MSG__PROFILE_PUBLICATIONS_NUMBER__\",\n \"required\": false,\n \"display\": true\n },\n \"series title\": {\n \"label\": \"__MSG__PROFILE_PUBLICATIONS_SERIES_TITLE__\",\n \"required\": false,\n \"display\": true\n },\n \"url\": {\n \"label\": \"__MSG__PROFILE_PUBLICATIONS_URL__\",\n \"required\": false,\n \"display\": true,\n \"validation\": \"appendhttp url\"\n }\n }\n }\n }\n },\n /*\n * set what name to display where only the first name is used\n */\n userFirstNameDisplay: \"firstName\",\n\n /*\n * set how the user's name is displayed across the entire system\n * - values can be compound, like \"firstName lastName\" or singular like \"displayName\"\n */\n userNameDisplay: \"firstName lastName\",\n\n /*\n * the default, if the user doesn't have the userNameDisplay property set in their\n * profile, use this one.\n * Note: the value for userNameDisplay and this value can be the same.\n * If neither exists, nothing will show\n */\n userNameDefaultDisplay: \"firstName lastName\",\n\n /*\n * Set the default user settings in account preferences for automatic tagging\n * and auto-tagged notifications\n */\n defaultAutoTagging: true,\n defaultSendTagMsg: true\n },\n\n Groups: {\n /*\n * Email message that will be sent to group managers when a user requests\n * to join their group.\n * ${user} will be replaced by the name of the requesting user and ${group}\n * will be replaced with the group name.\n */\n JoinRequest: {\n title: \"${user} has requested to join your group: ${group}\",\n body: \"${user} has requested to join your group: ${group}. Use the links below to respond to this request.\"\n }\n },\n\n Relationships: {\n /*\n * Relationships used by the add contacts widget to define what relationship the contacts can have\n */\n \"contacts\": [{\n \"name\": \"__MSG__CLASSMATE__\",\n \"definition\": \"__MSG__IS_MY_CLASSMATE__\",\n \"selected\": true\n }, {\n \"name\": \"__MSG__SUPERVISOR__\",\n \"inverse\": \"__MSG__SUPERVISED__\",\n \"definition\": \"__MSG__IS_MY_SUPERVISOR__\",\n \"selected\": false\n }, {\n \"name\": \"__MSG__SUPERVISED__\",\n \"inverse\": \"__MSG__SUPERVISOR__\",\n \"definition\": \"__MSG__IS_SUPERVISED_BY_ME__\",\n \"selected\": false\n }, {\n \"name\": \"__MSG__LECTURER__\",\n \"inverse\": \"__MSG__STUDENT__\",\n \"definition\": \"__MSG__IS_MY_LECTURER__\",\n \"selected\": false\n }, {\n \"name\": \"__MSG__STUDENT__\",\n \"inverse\": \"__MSG__LECTURER__\",\n \"definition\": \"__MSG__IS_MY_STUDENT__\",\n \"selected\": false\n }, {\n \"name\": \"__MSG__COLLEAGUE__\",\n \"definition\": \"__MSG__IS_MY_COLLEAGUE__\",\n \"selected\": false\n }, {\n \"name\": \"__MSG__COLLEGE_MATE__\",\n \"definition\": \"__MSG__IS_MY_COLLEGE_MATE__\",\n \"selected\": false\n }, {\n \"name\": \"__MSG__SHARES_INTERESTS__\",\n \"definition\": \"__MSG__SHARES_INTEREST_WITH_ME__\",\n \"selected\": false\n }]\n },\n\n SystemTour: {\n \"enableReminders\": true,\n \"reminderIntervalHours\": \"168\"\n },\n\n enableBranding: true,\n\n // Set this to true if you have an authentication system such as CAS\n // that needs to redirect the user's browser on logout\n followLogoutRedirects: false,\n\n // Set this to the hostname of your CLE instance if you're using CAS\n // proxy tickets\n hybridCasHost: false,\n\n Messages: {\n Types: {\n inbox: \"inbox\",\n sent: \"sent\",\n trash: \"trash\"\n },\n Categories: {\n message: \"Message\",\n announcement: \"Announcement\",\n chat: \"Chat\",\n invitation: \"Invitation\"\n },\n Subject: \"subject\",\n Type: \"type\",\n Body: \"body\",\n To: \"to\",\n read: \"read\"\n },\n Extensions:{\n \"docx\":\"application/doc\",\n \"doc\":\"application/doc\",\n \"odt\":\"application/doc\",\n \"ods\":\"application/vnd.ms-excel\",\n \"xls\":\"application/vnd.ms-excel\",\n \"xlsx\":\"application/vnd.ms-excel\",\n \"odp\":\"application/vnd.ms-powerpoint\",\n \"ppt\":\"application/vnd.ms-powerpoint\",\n \"pptx\":\"application/vnd.ms-powerpoint\",\n \"odg\":\"image/jpeg\",\n \"png\":\"image/png\",\n \"jp2\":\"images/jp2\",\n \"jpg\":\"image/jpeg\",\n \"jpeg\":\"image/jpeg\",\n \"bmp\":\"image/bmp\",\n \"gif\":\"image/gif\",\n \"tif\":\"image/tiff\",\n \"tiff\":\"images/tiff\",\n \"pdf\":\"application/x-pdf\",\n \"swf\":\"application/x-shockwave-flash\",\n \"flv\":\"video/x-msvideo\",\n \"mpg\":\"video/x-msvideo\",\n \"mpeg\":\"video/x-msvideo\",\n \"mp4\":\"video/x-msvideo\",\n \"avi\":\"video/x-msvideo\",\n \"mov\":\"video/x-msvideo\",\n \"txt\":\"text/rtf\",\n \"rtf\":\"text/rtf\",\n \"htm\":\"text/html\",\n \"html\":\"text/html\",\n \"wav\": \"audio/x-wav\",\n \"mp3\": \"audio/mpeg\",\n \"tar\": \"application/zip\",\n \"zip\": \"application/zip\",\n \"other\":\"other\"\n },\n MimeTypes: {\n \"application/doc\": {\n cssClass: \"icon-doc-sprite\",\n URL: \"/dev/images/mimetypes/doc.png\",\n description: \"WORD_DOCUMENT\"\n },\n \"application/msword\": {\n cssClass: \"icon-doc-sprite\",\n URL: \"/dev/images/mimetypes/doc.png\",\n description: \"WORD_DOCUMENT\"\n },\n \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\": {\n cssClass: \"icon-doc-sprite\",\n URL: \"/dev/images/mimetypes/doc.png\",\n description: \"WORD_DOCUMENT\"\n },\n \"application/pdf\": {\n cssClass: \"icon-pdf-sprite\",\n URL: \"/dev/images/mimetypes/pdf.png\",\n description: \"PDF_DOCUMENT\"\n },\n \"application/x-download\": {\n cssClass: \"icon-pdf-sprite\",\n URL: \"/dev/images/mimetypes/pdf.png\",\n description: \"PDF_DOCUMENT\"\n },\n \"application/x-pdf\": {\n cssClass: \"icon-pdf-sprite\",\n URL: \"/dev/images/mimetypes/pdf.png\",\n description: \"PDF_DOCUMENT\"\n },\n \"application/vnd.ms-powerpoint\": {\n cssClass: \"icon-pps-sprite\",\n URL: \"/dev/images/mimetypes/pps.png\",\n description: \"POWERPOINT_DOCUMENT\"\n },\n \"application/vnd.openxmlformats-officedocument.presentationml.presentation\": {\n cssClass: \"icon-pps-sprite\",\n URL: \"/dev/images/mimetypes/pps.png\",\n description: \"POWERPOINT_DOCUMENT\"\n },\n \"application/vnd.oasis.opendocument.text\": {\n cssClass: \"icon-doc-sprite\",\n URL: \"/dev/images/mimetypes/doc.png\",\n description: \"OPEN_OFFICE_DOCUMENT\"\n },\n \"application/vnd.oasis.opendocument.presentation\": {\n cssClass: \"icon-pps-sprite\",\n URL: \"/dev/images/mimetypes/pps.png\",\n description: \"OPEN_OFFICE_PRESENTATION\"\n },\n \"application/vnd.oasis.opendocument.spreadsheet\": {\n cssClass: \"icon-pps-sprite\",\n URL: \"/dev/images/mimetypes/spreadsheet.png\",\n description: \"OPEN_OFFICE_SPREADSHEET\"\n },\n\n \"application/x-shockwave-flash\": {\n cssClass: \"icon-swf-sprite\",\n URL: \"/dev/images/mimetypes/swf.png\",\n description: \"FLASH_PLAYER_FILE\"\n },\n \"application/zip\": {\n cssClass: \"icon-zip-sprite\",\n URL: \"/dev/images/mimetypes/zip.png\",\n description: \"ARCHIVE_FILE\"\n },\n \"application/x-zip-compressed\": {\n cssClass: \"icon-zip-sprite\",\n URL: \"/dev/images/mimetypes/zip.png\",\n description: \"ARCHIVE_FILE\"\n },\n \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\": {\n cssClass: \"icon-spreadsheet-sprite\",\n URL: \"/dev/images/mimetypes/spreadsheet.png\",\n description: \"SPREADSHEET_DOCUMENT\"\n },\n \"application/vnd.ms-excel\": {\n cssClass: \"icon-spreadsheet-sprite\",\n URL: \"/dev/images/mimetypes/spreadsheet.png\",\n description: \"SPREADSHEET_DOCUMENT\"\n },\n \"audio/x-wav\": {\n cssClass: \"icon-audio-sprite\",\n URL: \"/dev/images/mimetypes/sound.png\",\n description: \"SOUND_FILE\"\n },\n \"audio/mpeg\": {\n cssClass: \"icon-audio-sprite\",\n URL: \"/dev/images/mimetypes/sound.png\",\n description: \"SOUND_FILE\"\n },\n \"text/plain\": {\n cssClass: \"icon-txt-sprite\",\n URL: \"/dev/images/mimetypes/txt.png\",\n description: \"TEXT_DOCUMENT\"\n },\n \"text/rtf\": {\n cssClass: \"icon-txt-sprite\",\n URL: \"/dev/images/mimetypes/txt.png\",\n description: \"TEXT_DOCUMENT\"\n },\n \"image/png\": {\n cssClass: \"icon-image-sprite\",\n URL: \"/dev/images/mimetypes/images.png\",\n description: \"PNG_IMAGE\"\n },\n \"image/bmp\": {\n cssClass: \"icon-image-sprite\",\n URL: \"/dev/images/mimetypes/images.png\",\n description: \"BMP_IMAGE\"\n },\n \"image/gif\": {\n cssClass: \"icon-image-sprite\",\n URL: \"/dev/images/mimetypes/images.png\",\n description: \"GIF_IMAGE\"\n },\n \"image/jp2\": {\n cssClass: \"icon-image-sprite\",\n URL: \"/dev/images/mimetypes/images.png\",\n description: \"JPG2000_IMAGE\"\n },\n \"image/jpeg\": {\n cssClass: \"icon-image-sprite\",\n URL: \"/dev/images/mimetypes/images.png\",\n description: \"JPG_IMAGE\"\n },\n \"image/pjpeg\": {\n cssClass: \"icon-image-sprite\",\n URL: \"/dev/images/mimetypes/images.png\",\n description: \"JPG_IMAGE\"\n },\n \"image/tiff\": {\n cssClass: \"icon-image-sprite\",\n URL: \"/dev/images/mimetypes/images.png\",\n description: \"TIFF_IMAGE\"\n },\n \"text/html\": {\n cssClass: \"icon-html-sprite\",\n URL: \"/dev/images/mimetypes/html.png\",\n description: \"HTML_DOCUMENT\"\n },\n \"video/x-msvideo\": {\n cssClass: \"icon-video-sprite\",\n URL: \"/dev/images/mimetypes/video.png\",\n description: \"VIDEO_FILE\"\n },\n \"video/mp4\": {\n cssClass: \"icon-video-sprite\",\n URL: \"/dev/images/mimetypes/video.png\",\n description: \"VIDEO_FILE\"\n },\n \"video/quicktime\": {\n cssClass: \"icon-video-sprite\",\n URL: \"/dev/images/mimetypes/video.png\",\n description: \"VIDEO_FILE\"\n },\n \"video/x-ms-wmv\": {\n cssClass: \"icon-video-sprite\",\n URL: \"/dev/images/mimetypes/video.png\",\n description: \"VIDEO_FILE\"\n },\n \"folder\": {\n cssClass: \"icon-kmultiple-sprite\",\n URL: \"/dev/images/mimetypes/kmultiple.png\",\n description: \"FOLDER\"\n },\n \"x-sakai/link\": {\n cssClass: \"icon-url-sprite\",\n URL: \"/dev/images/mimetypes/html.png\",\n description: \"URL_LINK\"\n },\n \"x-sakai/document\": {\n cssClass: \"icon-sakaidoc-sprite\",\n URL: \"/dev/images/mimetypes/sakaidoc.png\",\n description: \"DOCUMENT\"\n },\n \"x-sakai/collection\": {\n cssClass: \"icon-collection-sprite\",\n URL: \"/dev/images/mimetypes/collection2.png\",\n description: \"COLLECTION\"\n },\n \"kaltura/video\": {\n cssClass: \"icon-video-sprite\",\n URL: \"/dev/images/mimetypes/video.png\",\n description: \"VIDEO_FILE\"\n },\n \"kaltura/audio\": {\n cssClass: \"icon-sound-sprite\",\n URL: \"/dev/images/mimetypes/sound.png\",\n description: \"SOUND_FILE\"\n },\n \"other\": {\n cssClass: \"icon-unknown-sprite\",\n URL: \"/dev/images/mimetypes/unknown.png\",\n description: \"OTHER_DOCUMENT\"\n }\n },\n\n Authentication: {\n \"allowInternalAccountCreation\": true,\n \"internal\": true,\n \"external\": [{\n label: \"External Login System 1\",\n url: \"http://external.login1.com/\"\n }, {\n label: \"External Login System 2\",\n url: \"http://external.login2.com/\"\n }],\n \"hideLoginOn\": [\"/dev\", \"/dev/index.html\", \"/dev/create_new_account.html\"]\n },\n\n notification: {\n type: {\n ERROR: {\n image: \"/dev/images/notifications_exclamation_icon.png\",\n time: 10000\n },\n INFORMATION: {\n image: \"/dev/images/notifications_info_icon.png\",\n time: 5000\n }\n }\n },\n\n Navigation: [{\n \"url\": \"/me#l=dashboard\",\n \"id\": \"navigation_you_link\",\n \"anonymous\": false,\n \"label\": \"YOU\",\n \"append\": \"messages\",\n \"subnav\": [{\n \"url\": \"/me#l=dashboard\",\n \"id\": \"subnavigation_home_link\",\n \"label\": \"MY_HOME\"\n }, {\n \"url\": \"/me#l=messages/inbox\",\n \"id\": \"subnavigation_messages_link\",\n \"label\": \"MY_MESSAGES\"\n }, {\n \"id\": \"subnavigation_hr\"\n }, {\n \"url\": \"/me#l=profile/basic\",\n \"id\": \"subnavigation_profile_link\",\n \"label\": \"MY_PROFILE\"\n }, {\n \"url\": \"/me#l=library\",\n \"id\": \"subnavigation_content_link\",\n \"label\": \"MY_LIBRARY\"\n }, {\n \"url\": \"/me#l=memberships\",\n \"id\": \"subnavigation_memberships_link\",\n \"label\": \"MY_MEMBERSHIPS\"\n }, {\n \"url\": \"/me#l=contacts\",\n \"id\": \"subnavigation_contacts_link\",\n \"label\": \"MY_CONTACTS_CAP\"\n }]\n }, {\n \"url\": \"#\",\n \"id\": \"navigation_create_and_add_link\",\n \"anonymous\": false,\n \"label\": \"CREATE_AND_COLLECT\",\n \"append\": \"collections\",\n \"subnav\": [{\n \"id\": \"subnavigation_add_content_link\",\n \"label\": \"ADD_CONTENT\",\n \"url\": \"#\"\n }, {\n \"id\": \"subnavigation_add_collection_link\",\n \"label\": \"ADD_COLLECTION\",\n \"url\": \"#\"\n }, {\n \"id\": \"subnavigation_hr\"\n }]\n }, {\n \"url\": \"/index\",\n \"id\": \"navigation_explore_link\",\n \"anonymous\": false,\n \"label\": \"EXPLORE\",\n \"subnav\": [{\n \"id\": \"subnavigation_explore_categories_link\",\n \"label\": \"BROWSE_ALL_CATEGORIES\",\n \"url\": \"/categories\"\n },{\n \"id\": \"subnavigation_hr\"\n },{\n \"id\": \"subnavigation_explore_content_link\",\n \"label\": \"CONTENT\",\n \"url\": \"/search#l=content\"\n }, {\n \"id\": \"subnavigation_explore_people_link\",\n \"label\": \"PEOPLE\",\n \"url\": \"/search#l=people\"\n }]\n }, {\n \"url\": \"/index\",\n \"id\": \"navigation_anon_explore_link\",\n \"anonymous\": true,\n \"label\": \"EXPLORE\",\n \"subnav\": [{\n \"id\": \"subnavigation_explore_categories_link\",\n \"label\": \"BROWSE_ALL_CATEGORIES\",\n \"url\": \"/categories\"\n },{\n \"id\": \"subnavigation_hr\"\n },{\n \"id\": \"subnavigation_explore_content_link\",\n \"label\": \"CONTENT\",\n \"url\": \"/search#l=content\"\n }, {\n \"id\": \"subnavigation_explore_people_link\",\n \"label\": \"PEOPLE\",\n \"url\": \"/search#l=people\"\n }]\n }, {\n \"url\": \"/register\",\n \"id\": \"navigation_anon_signup_link\",\n \"anonymous\": true,\n \"label\": \"SIGN_UP\"\n }],\n\n Footer: {\n leftLinks: [{\n \"title\": \"__MSG__COPYRIGHT__\",\n \"href\": \"http://sakaiproject.org/foundation-licenses\",\n \"newWindow\": true\n }, {\n \"title\": \"__MSG__HELP__\",\n \"href\": \"http://sakaiproject.org/node/2307\",\n \"newWindow\": true\n }, {\n \"title\": \"__MSG__ACKNOWLEDGEMENTS__\",\n \"href\": \"/acknowledgements\"\n }, {\n \"title\": \"__MSG__SUGGEST_AN_IMPROVEMENT__\",\n \"href\": \"http://sakaioae.idea.informer.com/\",\n \"newWindow\": true\n }],\n rightLinks: [{\n \"title\": \"__MSG__BROWSE__\",\n \"href\": \"/categories\"\n }, {\n \"title\": \"__MSG__EXPLORE__\",\n \"href\": \"/\"\n }]\n },\n\n /*\n * Are anonymous users allowed to browse/search\n */\n anonAllowed: true,\n /*\n * List of pages that require a logged in user\n */\n requireUser: [\"/me\", \"/dev/me.html\", \"/dev/search_sakai2.html\", \"/create\", \"/dev/createnew.html\"],\n\n /*\n * List of pages that require an anonymous user\n */\n requireAnonymous: [\"/register\", \"/dev/create_new_account.html\"],\n /*\n * List of pages that will be added to requireUser if\n * anonAllowed is false\n */\n requireUserAnonNotAllowed: [\"/me\", \"/dev/me.html\", \"/dev/search_sakai2.html\"],\n /*\n * List of pages that will be added to requireAnonymous if\n * anonAllowed is false\n */\n requireAnonymousAnonNotAllowed: [],\n /*\n * List op pages that require additional processing to determine\n * whether the page can be shown to the current user. These pages\n * are then required to call the sakai.api.Security.showPage\n * themselves\n */\n requireProcessing: [\"/dev/user.html\", \"/me\" ,\"/dev/me.html\", \"/dev/content_profile.html\", \"/dev/content_profile.html\", \"/dev/group_edit.html\", \"/dev/show.html\", \"/content\"],\n\n useLiveSakai2Feeds: false,\n /*\n * List of custom CLE Tool names. This can be used to override the translated\n * tool name in the Sakai 2 Tools Widget drop down, or name a custom CLE tool\n * that has been added to your CLE installation. You can see the list of\n * enabled CLE tools at /var/basiclti/cletools.json, and configure them in\n * Nakamura under the org.sakaiproject.nakamura.basiclti.CLEVirtualToolDataProvider\n * configuration.\n */\n sakai2ToolNames: {\n /* \"sakai.mytoolId\" : \"My Custom Tool Title\" */\n },\n\n displayDebugInfo: true,\n\n /**\n * Section dividers can be added to the directory structure by adding in the following\n * element at the appropriate place:\n * divider1: {\n * \"divider\": true,\n * \"title\": \"Divider title\" [optional],\n * \"cssClass\": \"CSS class to add to items inside of elements beneath the divider [optional]\n * }\n */\n Directory: {\n medicineanddentistry: {\n title: \"__MSG__MEDICINE_AND_DENTISTRY__\",\n children: {\n preclinicalmedicine: {\n title: \"__MSG__PRECLINICAL_MEDICINE__\"\n },\n preclinicaldentistry: {\n title: \"__MSG__PRECLINICAL_DENTISTRY__\"\n },\n clinicalmedicine: {\n title: \"__MSG__CLININCAL_MEDICINE__\"\n },\n clinicaldentistry: {\n title: \"__MSG__CLININCAL_DENTISTRY__\"\n },\n othersinmedicineanddentistry: {\n title: \"__MSG__MEDICINE_AND_DENTISTRY_OTHERS__\"\n }\n }\n },\n biologicalsciences: {\n title: \"__MSG__BIOLOGICAL_SCIENCES__\",\n children: {\n biology: {\n title: \"__MSG__BIOLOGY__\"\n },\n botany: {\n title: \"__MSG__BOTANY__\"\n },\n zoology: {\n title: \"__MSG__ZOOLOGY__\"\n },\n genetics: {\n title: \"__MSG__GENETICS__\"\n },\n microbiology: {\n title: \"__MSG__MICROBIOLOGY__\"\n },\n sportsscience: {\n title: \"__MSG__SPORTS_SCIENCE__\"\n },\n molecularbiologybiophysicsandbiochemistry: {\n title: \"__MSG__MOLECULAR_BIOLOGY__\"\n },\n psychology: {\n title: \"__MSG__PSYCHOLOGY__\"\n },\n othersinbiologicalsciences: {\n title: \"__MSG__BIOLOGICAL_SCIENCES_OTHER__\"\n }\n }\n },\n veterinarysciencesagriculture: {\n title: \"__MSG__VETERINARY_SCIENCES__\",\n children: {\n preclinicalveterinarymedicine: {\n title: \"__MSG__PRE_CLINICAL_VETERINARY__\"\n },\n clinicalveterinarymedicineanddentistry: {\n title: \"__MSG__CLINICAL_VETERINARY__\"\n },\n animalscience: {\n title: \"__MSG__ANIMAL_SCIENCE__\"\n },\n agriculture: {\n title: \"__MSG__AGRICULTURE__\"\n },\n forestry: {\n title: \"__MSG__FORESTRY__\"\n },\n foodandbeveragestudies: {\n title: \"__MSG__FOOD_BEVERAGE__\"\n },\n agriculturalsciences: {\n title: \"__MSG__AGRICULTURAL_SCIENCE__\"\n },\n othersinveterinarysciencesandagriculture: {\n title: \"__MSG__VETERINARY_SCIENCES_OTHER__\"\n }\n }\n },\n physicalsciences: {\n title: \"__MSG__PHYSICAL_SCIENCE__\",\n children: {\n chemistry: {\n title: \"__MSG__CHEMISTRY__\"\n },\n materialsscience: {\n title: \"__MSG__MATERIALS_SCIENCE__\"\n },\n physics: {\n title: \"__MSG__PHYSICS__\"\n },\n forensicandarchaeologicalscience: {\n title: \"__MSG__FORENSIC_ARCHEALOGICAL__\"\n },\n astronomy: {\n title: \"__MSG__ASTRONOMY__\"\n },\n geology: {\n title: \"__MSG__GEOLOGY__\"\n },\n oceansciences: {\n title: \"__MSG__OCEAN_SCIENCE__\"\n },\n othersinphysicalsciences: {\n title: \"__MSG__PHYSICAL_SCIENCE_OTHER__\"\n }\n }\n },\n mathematicalandcomputersciences: {\n title: \"__MSG__MATHEMATICAL_COMPUTER_SCIENCES__\",\n children: {\n mathematics: {\n title: \"__MSG__MATHEMATICS__\"\n },\n operationalresearch: {\n title: \"__MSG__OPERATIONAL_RESEARCH__\"\n },\n statistics: {\n title: \"__MSG__STATISTICS__\"\n },\n computerscience: {\n title: \"__MSG__COMPUTER_SCIENCE__\"\n },\n informationsystems: {\n title: \"__MSG__INFORMATION_SYSTEMS__\"\n },\n softwareengineering: {\n title: \"__MSG__SOFTWARE_ENGINEERING__\"\n },\n artificialintelligence: {\n title: \"__MSG__ARTIFICIAL_INTELLIGENCE__\"\n },\n othersinmathematicalandcomputingsciences: {\n title: \"__MSG__MATHEMATICAL_COMPUTER_SCIENCES_OTHER__\"\n }\n }\n },\n engineering: {\n title: \"__MSG__ENGINEERING__\",\n children: {\n generalengineering: {\n title: \"__MSG__GENERAL_ENGINEERING__\"\n },\n civilengineering: {\n title: \"__MSG__CIVIL_ENGINEERING__\"\n },\n mechanicalengineering: {\n title: \"__MSG__MECHANICAL_ENGINEERING__\"\n },\n aerospaceengineering: {\n title: \"__MSG__AEROSPACE_ENGINEERING__\"\n },\n navalarchitecture: {\n title: \"__MSG__NAVAL_ARCHITECTURE__\"\n },\n electronicandelectricalengineering: {\n title: \"__MSG__ELECTRONIC_ELECTRICAL_ENGINEERING__\"\n },\n productionandmanufacturingengineering: {\n title: \"__MSG__PRODUCTION_MANUFACTURING_ENGINEERING__\"\n },\n chemicalprocessandenergyengineering: {\n title: \"__MSG__CHEMICAL_PROCESS_ENERGY_ENGINEERING__\"\n },\n othersinengineering: {\n title: \"__MSG__ENGINEERING_OTHER__\"\n }\n }\n },\n technologies: {\n title: \"__MSG__TECHNOLOGIES__\",\n children: {\n mineralstechnology: {\n title: \"__MSG__MINERALS_TECHNOLOGY__\"\n },\n metallurgy: {\n title: \"__MSG__METALLURGY__\"\n },\n ceramicsandglasses: {\n title: \"__MSG__CERAMICS_GLASSES__\"\n },\n polymersandtextiles: {\n title: \"__MSG__POLYMERS_TEXTILES__\"\n },\n materialstechnologynototherwisespecified: {\n title: \"__MSG__MATERIALS_TECHNOLOGY_OTHER__\"\n },\n maritimetechnology: {\n title: \"__MSG__MARITIME_TECHNOLOGY__\"\n },\n industrialbiotechnology: {\n title: \"__MSG__INDUSTRIAL_BIOTECHNOLOGY__\"\n },\n othersintechnology: {\n title: \"__MSG__TECHNOLOGIES_OTHER__\"\n }\n }\n },\n architecturebuildingandplanning: {\n title: \"__MSG__ARCHITECTURE_BUILDING_PLANNING__\",\n children: {\n architecture: {\n title: \"__MSG__ARCHITECTURE__\"\n },\n building: {\n title: \"__MSG__BUILDING__\"\n },\n landscapedesign: {\n title: \"__MSG__LANDSCAPE_DESIGN__\"\n },\n planning: {\n title: \"__MSG__PLANNING__\"\n },\n othersinarchitecturebuildingandplanning: {\n title: \"__MSG__ARCHITECTURE_BUILDING_PLANNING_OTHER__\"\n }\n }\n },\n socialstudies: {\n title: \"__MSG__SOCIAL_STUDIES__\",\n children: {\n economics: {\n title: \"__MSG__ECONOMICS__\"\n },\n politics: {\n title: \"__MSG__POLITICS__\"\n },\n sociology: {\n title: \"__MSG__SOCIOLOGY__\"\n },\n socialpolicy: {\n title: \"__MSG__SOCIAL_POLICY__\"\n },\n socialwork: {\n title: \"__MSG__SOCIAL_WORK__\"\n },\n anthropology: {\n title: \"__MSG__ANTHROPOLOGY__\"\n },\n humanandsocialgeography: {\n title: \"__MSG__HUMAN_SOCIAL_GEOGRAPHY__\"\n },\n othersinsocialstudies: {\n title: \"__MSG__SOCIAL_STUDIES_OTHER__\"\n }\n }\n },\n law: {\n title: \"__MSG__LAW__\",\n children: {\n publiclaw: {\n title: \"__MSG__LAW_PUBLIC__\"\n },\n privatelaw: {\n title: \"__MSG__LAW_PRIVATE__\"\n },\n jurisprudence: {\n title: \"__MSG__JURISPRUDENCE__\"\n },\n legalpractice: {\n title: \"__MSG__LEGAL_PRACTICE__\"\n },\n medicallaw: {\n title: \"__MSG__LAW_MEDICAL__\"\n },\n othersinlaw: {\n title: \"__MSG__LAW_OTHER__\"\n }\n }\n },\n businessandadministrativestudies: {\n title: \"__MSG__BUSINESS_ADMINISTRATIVE_STUDIES__\",\n children: {\n businessstudies: {\n title: \"__MSG__BUSINESS_STUDIES__\"\n },\n managementstudies: {\n title: \"__MSG__MANAGEMENTS_STUDIES__\"\n },\n finance: {\n title: \"__MSG__FINANCE__\"\n },\n accounting: {\n title: \"__MSG__ACCOUNTING__\"\n },\n marketing: {\n title: \"__MSG__MARKETING__\"\n },\n humanresourcemanagement: {\n title: \"__MSG__HUMAN_RESOURCE_MANAGEMENT__\"\n },\n officeskills: {\n title: \"__MSG__OFFICE_SKILLS__\"\n },\n tourismtransportandtravel: {\n title: \"__MSG__TOURISM__\"\n },\n othersinbusandadminstudies: {\n title: \"__MSG__BUSINESS_ADMINISTRATIVE_STUDIES_OTHER__\"\n }\n }\n },\n masscommunicationsanddocumentation: {\n title: \"__MSG__MASS_COMMUNICATIONS_DOCUMENTATION__\",\n children: {\n informationservices: {\n title: \"__MSG__INFORMATION_SERVICES__\"\n },\n publicitystudies: {\n title: \"__MSG__PUBLICITY_STUDIES__\"\n },\n mediastudies: {\n title: \"__MSG__MEDIA_STUDIES__\"\n },\n publishing: {\n title: \"__MSG__PUBLISHING__\"\n },\n journalism: {\n title: \"__MSG__JOURNALISM__\"\n },\n othersinmasscommanddoc: {\n title: \"__MSG__MASS_COMMUNICATIONS_DOCUMENTATION_OTHER__\"\n }\n }\n },\n linguisticsclassicsandrelatedsubjects: {\n title: \"__MSG__LINGUISTICS_CLASSICS__\",\n children: {\n linguistics: {\n title: \"__MSG__LINGUISTICS__\"\n },\n comparativeliterarystudies: {\n title: \"__MSG__LINGUISTICS_LITERARY__\"\n },\n englishstudies: {\n title: \"__MSG__LINGUISTICS_ENGLISH__\"\n },\n ancientlanguagestudies: {\n title: \"__MSG__LINGUISTICS_ANCIENT__\"\n },\n celticstudies: {\n title: \"__MSG__LINGUISTICS_CELTIC__\"\n },\n latinstudies: {\n title: \"__MSG__LINGUISTICS_LATIN__\"\n },\n classicalgreekstudies: {\n title: \"__MSG__LINGUISTICS_CLASSICAL_GREEK__\"\n },\n classicalstudies: {\n title: \"__MSG__LINGUISTICS_CLASSICAL__\"\n },\n othersinlinguisticsclassicsandrelsubject: {\n title: \"__MSG__LINGUISTICS_CLASSICS_OTHER__\"\n }\n }\n },\n europeanlanguagesliteratureandrelatedsubjects: {\n title: \"__MSG__EUROPEAN_LANGUAGES__\",\n children: {\n frenchstudies: {\n title: \"__MSG__EUROPEAN_LANGUAGES_FRENCH__\"\n },\n germanstudies: {\n title: \"__MSG__EUROPEAN_LANGUAGES_GERMAN__\"\n },\n italianstudies: {\n title: \"__MSG__EUROPEAN_LANGUAGES_ITALIAN__\"\n },\n spanishstudies: {\n title: \"__MSG__EUROPEAN_LANGUAGES_SPANISH__\"\n },\n portuguesestudies: {\n title: \"__MSG__EUROPEAN_LANGUAGES_PORTUGUESE__\"\n },\n scandinavianstudies: {\n title: \"__MSG__EUROPEAN_LANGUAGES_SCANDINAVIAN__\"\n },\n russianandeasteuropeanstudies: {\n title: \"__MSG__EUROPEAN_LANGUAGES_RUSSIAN__\"\n },\n othersineurolangliteratureandrelsubjects: {\n title: \"__MSG__EUROPEAN_LANGUAGES_OTHER__\"\n }\n }\n },\n easiaticlanguagesliterature: {\n title: \"__MSG__EXOTIC_LANGUAGES__\",\n children: {\n chinesestudies: {\n title: \"__MSG__EXOTIC_LANGUAGES_CHINESE__\"\n },\n japanesestudies: {\n title: \"__MSG__EXOTIC_LANGUAGES_JAPANESE__\"\n },\n southasianstudies: {\n title: \"__MSG__EXOTIC_LANGUAGES_SOUTH_ASIAN__\"\n },\n otherasianstudies: {\n title: \"__MSG__EXOTIC_LANGUAGES_ASIAN_OTHER__\"\n },\n africanstudies: {\n title: \"__MSG__EXOTIC_LANGUAGES_AFRICAN__\"\n },\n modernmiddleeasternstudies: {\n title: \"__MSG__EXOTIC_LANGUAGES_MIDDLE_EAST__\"\n },\n americanstudies: {\n title: \"__MSG__EXOTIC_LANGUAGES_AMERICAN__\"\n },\n australasianstudies: {\n title: \"__MSG__EXOTIC_LANGUAGES_AUSTRALIAN__\"\n },\n othersineasternasiaafriamericaaustralianlang: {\n title: \"__MSG__EXOTIC_LANGUAGES_OTHER__\"\n }\n }\n },\n historicalandphilosophicalstudies: {\n title: \"__MSG__HISTORICAL_PHILOSOPHICAL_STUDIES__\",\n children: {\n historybyperiod: {\n title: \"__MSG__HISTORY_PERIOD__\"\n },\n historybyarea: {\n title: \"__MSG__HISTORY_AREA__\"\n },\n historybytopic: {\n title: \"__MSG__HISTORY_TOPIC__\"\n },\n archaeology: {\n title: \"__MSG__ARCHEOLOGY__\"\n },\n philosophy: {\n title: \"__MSG__PHILOSOPHY__\"\n },\n theologyandreligiousstudies: {\n title: \"__MSG__THEOLOGY_STUDIES__\"\n },\n othersinhistoricalandphilosophicalstudies: {\n title: \"__MSG__HISTORICAL_PHILOSOPHICAL_STUDIES_OTHER__\"\n }\n }\n },\n creativeartsanddesign: {\n title: \"__MSG__CREATIVE_ARTS__\",\n children: {\n fineart: {\n title: \"__MSG__FINE_ART__\"\n },\n designstudies: {\n title: \"__MSG__DESIGN_STUDIES__\"\n },\n music: {\n title: \"__MSG__MUSIC__\"\n },\n drama: {\n title: \"__MSG__DRAMA__\"\n },\n dance: {\n title: \"__MSG__DANCE__\"\n },\n cinematicsandphotography: {\n title: \"__MSG__CINEMATICS_PHOTOGRAPHY__\"\n },\n crafts: {\n title: \"__MSG__CRAFTS__\"\n },\n imaginativewriting: {\n title: \"__MSG__IMAGINITIVE_WRITING__\"\n },\n othersincreativeartsanddesign: {\n title: \"__MSG__CREATIVE_ARTS_OTHER__\"\n }\n }\n },\n education: {\n title: \"__MSG__EDUCATION__\",\n children: {\n trainingteachers: {\n title: \"__MSG__TRAINING_TEACHERS__\"\n },\n researchandstudyskillsineducation: {\n title: \"__MSG__EDUCATION_RESEARCH_STUDY_SKILLS__\"\n },\n academicstudiesineducation: {\n title: \"__MSG__EDUCATION_ACADEMIC_STUDIES__\"\n },\n othersineducation: {\n title: \"__MSG__EDUCATION_OTHER__\"\n }\n }\n }\n },\n\n // Array of css files to load in each page\n skinCSS: [],\n\n Languages: [{\n \"country\": \"CN\",\n \"language\": \"zh\",\n \"displayName\": \"\u4e2d\u6587\"\n }, {\n \"country\": \"NL\",\n \"language\": \"nl\",\n \"displayName\": \"Nederlands\"\n }, {\n \"country\": \"GB\",\n \"language\": \"en\",\n \"displayName\": \"English (United Kingdom)\"\n }, {\n \"country\": \"US\",\n \"language\": \"en\",\n \"displayName\": \"English (United States)\"\n }, {\n \"country\": \"JP\",\n \"language\": \"ja\",\n \"displayName\": \"\u65e5\u672c\u8a9e\"\n }, {\n \"country\": \"HU\",\n \"language\": \"hu\",\n \"displayName\": \"Magyar\"\n }, {\n \"country\": \"KR\",\n \"language\": \"ko\",\n \"displayName\": \"\ud55c\uad6d\uc5b4\"\n }],\n\n // Default Language for the deployment, must be one of the language_COUNTRY pairs that exists above\n defaultLanguage: \"en_US\",\n\n enableChat: false,\n enableCategories: true,\n\n Editor: {\n tinymceLanguagePacks: ['ar','ch','en','gl','id','lb','nb','ru','sv','uk','az','cn','eo','gu','is','lt','nl',\n 'sc','ta','ur','be','cs','es','he','it','lv','nn','se','te','vi','bg','cy','et','hi','ja','mk','no','si',\n 'th','zh-cn','bn','da','eu','hr','ka','ml','pl','sk','tn','zh-tw','br','de','fa','hu','kl','mn','ps','sl',\n 'tr','zh','bs','dv','fi','hy','km','ms','pt','sq','tt','zu','ca','el','fr','ia','ko','my','ro','sr','tw']\n },\n\n defaultSakaiDocContent: {\n \"rows\": [\n {\n \"id\": \"id\" + Math.round(Math.random() * 100000000),\n \"columns\": [\n {\n \"width\": 1,\n \"elements\": []\n }\n ]\n }\n ]\n },\n\n /*\n * _canEdit: can change the area permissions on this page\n * _reorderOnly: can reorder this item in the navigation, but cannot edit the name of the page\n * _nonEditable: cannot edit the contents of this page\n * _canSubedit:\n */\n\n defaultprivstructure: {\n \"structure0\": {\n \"dashboard\": {\n \"_ref\": \"${refid}0\",\n \"_title\": \"__MSG__MY_DASHBOARD__\",\n \"_order\": 0,\n \"_canEdit\": true,\n \"_reorderOnly\": true,\n \"_nonEditable\": true,\n \"main\": {\n \"_ref\": \"${refid}0\",\n \"_order\": 0,\n \"_title\": \"__MSG__MY_DASHBOARD__\"\n }\n },\n \"messages\": {\n \"_title\": \"__MSG__MY_MESSAGES__\",\n \"_ref\": \"${refid}1\",\n \"_order\": 1,\n \"_canEdit\": true,\n \"_reorderOnly\": true,\n \"_canSubedit\": true,\n \"_nonEditable\": true,\n \"inbox\": {\n \"_ref\": \"${refid}1\",\n \"_order\": 0,\n \"_title\": \"__MSG__INBOX__\",\n \"_nonEditable\": true\n },\n \"invitations\": {\n \"_ref\": \"${refid}2\",\n \"_order\": 1,\n \"_title\": \"__MSG__INVITATIONS__\",\n \"_nonEditable\": true\n },\n \"sent\": {\n \"_ref\": \"${refid}3\",\n \"_order\": 2,\n \"_title\": \"__MSG__SENT__\",\n \"_nonEditable\": true\n },\n \"trash\": {\n \"_ref\": \"${refid}4\",\n \"_order\": 3,\n \"_title\": \"__MSG__TRASH__\",\n \"_nonEditable\": true\n }\n }\n },\n \"${refid}0\": {\n \"id2506067\": {\n \"htmlblock\": {\n \"content\": \"
            __MSG__MY_DASHBOARD__
            \"\n }\n },\n \"${refid}5\": {\n \"dashboard\": {\n \"layout\": \"threecolumn\",\n \"columns\": {\n \"column1\": [\n {\n \"uid\": \"${refid}10\",\n \"visible\": \"block\",\n \"name\": \"recentchangedcontent\"\n }\n ],\n \"column2\": [\n {\n \"uid\": \"${refid}11\",\n \"visible\": \"block\",\n \"name\": \"recentmemberships\"\n }\n ],\n \"column3\": [\n {\n \"uid\": \"${refid}12\",\n \"visible\": \"block\",\n \"name\": \"recentcontactsnew\"\n }\n ]\n }\n }\n },\n \"rows\": [\n {\n \"id\": \"id8965114\",\n \"columns\": [\n {\n \"width\": 1,\n \"elements\": [\n {\n \"id\": \"id2506067\",\n \"type\": \"htmlblock\"\n },\n {\n \"id\": \"id8321271\",\n \"type\": \"carousel\"\n },\n {\n \"id\": \"${refid}5\",\n \"type\": \"dashboard\"\n }\n ]\n }\n ]\n }\n ]\n },\n \"${refid}1\": {\n \"${refid}6\": {\n \"box\": \"inbox\",\n \"category\": \"message\",\n \"title\": \"__MSG__INBOX__\"\n },\n \"rows\": [\n {\n \"id\": \"id7088118\",\n \"columns\": [\n {\n \"width\": 1,\n \"elements\": [\n {\n \"id\": \"${refid}6\",\n \"type\": \"inbox\"\n }\n ]\n }\n ]\n }\n ]\n },\n \"${refid}2\": {\n \"${refid}7\": {\n \"box\": \"inbox\",\n \"category\": \"invitation\",\n \"title\": \"__MSG__INVITATIONS__\"\n },\n \"rows\": [\n {\n \"id\": \"id6156677\",\n \"columns\": [\n {\n \"width\": 1,\n \"elements\": [\n {\n \"id\": \"${refid}7\",\n \"type\": \"inbox\"\n }\n ]\n }\n ]\n }\n ]\n },\n \"${refid}3\": {\n \"${refid}8\": {\n \"box\": \"outbox\",\n \"category\": \"*\",\n \"title\": \"__MSG__SENT__\"\n },\n \"rows\": [\n {\n \"id\": \"id5268914\",\n \"columns\": [\n {\n \"width\": 1,\n \"elements\": [\n {\n \"id\": \"${refid}8\",\n \"type\": \"inbox\"\n }\n ]\n }\n ]\n }\n ]\n },\n \"${refid}4\": {\n \"${refid}9\": {\n \"box\": \"trash\",\n \"category\": \"*\",\n \"title\": \"__MSG__TRASH__\"\n },\n \"rows\": [\n {\n \"id\": \"id1281420\",\n \"columns\": [\n {\n \"width\": 1,\n \"elements\": [\n {\n \"id\": \"${refid}9\",\n \"type\": \"inbox\"\n }\n ]\n }\n ]\n }\n ]\n }\n },\n\n /**\n * In order to set permissions on specific private areas, the following parameter should be added:\n * _view: \"anonymous\" // Area is visible to all users by default\n * _view: \"everyone\" // Area is visible to all logged in users by default\n * _view: \"contacts\" // Area is visible to all contacts by default\n * _view: \"private\" // Area is not visible to other users by default\n */\n defaultpubstructure: {\n \"structure0\": {\n \"profile\": {\n \"_title\": \"__MSG__MY_PROFILE__\",\n \"_altTitle\": \"__MSG__MY_PROFILE_OTHER__\",\n \"_order\": 0,\n \"_view\": \"anonymous\",\n \"_reorderOnly\": true,\n \"_nonEditable\": true\n },\n \"library\": {\n \"_ref\": \"${refid}0\",\n \"_order\": 1,\n \"_title\": \"__MSG__MY_LIBRARY__\",\n \"_altTitle\": \"__MSG__MY_LIBRARY_OTHER__\",\n \"_reorderOnly\": true,\n \"_nonEditable\": true,\n \"_view\": \"anonymous\",\n \"main\": {\n \"_ref\": \"${refid}0\",\n \"_order\": 0,\n \"_title\": \"__MSG__MY_LIBRARY__\"\n }\n },\n \"memberships\": {\n \"_title\": \"__MSG__MY_MEMBERSHIPS__\",\n \"_order\": 2,\n \"_ref\": \"${refid}1\",\n \"_altTitle\": \"__MSG__MY_MEMBERSHIPS_OTHER__\",\n \"_reorderOnly\": true,\n \"_nonEditable\": true,\n \"_view\": \"anonymous\",\n \"main\": {\n \"_ref\": \"${refid}1\",\n \"_order\": 0,\n \"_title\": \"__MSG__MY_MEMBERSHIPS__\"\n }\n },\n \"contacts\": {\n \"_title\": \"__MSG__MY_CONTACTS__\",\n \"_order\": 3,\n \"_ref\": \"${refid}2\",\n \"_altTitle\": \"__MSG__MY_CONTACTS_OTHER__\",\n \"_reorderOnly\": true,\n \"_nonEditable\": true,\n \"_view\": \"anonymous\",\n \"main\": {\n \"_ref\": \"${refid}2\",\n \"_order\": 0,\n \"_title\": \"__MSG__MY_CONTACTS__\"\n }\n }\n },\n \"${refid}0\": {\n \"rows\": [\n {\n \"id\": \"id89874\",\n \"columns\": [\n {\n \"width\": 1,\n \"elements\": [\n {\n \"id\": \"id5739346\",\n \"type\": \"mylibrary\"\n }\n ]\n }\n ]\n }\n ]\n },\n \"${refid}1\": {\n \"rows\": [\n {\n \"id\": \"id7664610\",\n \"columns\": [\n {\n \"width\": 1,\n \"elements\": [\n {\n \"id\": \"id4347509\",\n \"type\": \"mymemberships\"\n }\n ]\n }\n ]\n }\n ]\n },\n \"${refid}2\": {\n \"rows\": [\n {\n \"id\": \"id293415\",\n \"columns\": [\n {\n \"width\": 1,\n \"elements\": [\n {\n \"id\": \"id6775571\",\n \"type\": \"contacts\"\n }\n ]\n }\n ]\n }\n ]\n }\n },\n\n widgets: {\n \"layouts\": {\n \"onecolumn\": {\n \"name\": \"One column\",\n \"widths\": [100],\n \"siteportal\": true\n },\n \"dev\": {\n \"name\": \"Dev Layout\",\n \"widths\": [50, 50],\n \"siteportal\": true\n },\n \"threecolumn\": {\n \"name\": \"Three equal columns\",\n \"widths\": [33, 33, 33],\n \"siteportal\": false\n }\n },\n \"defaults\": {\n \"personalportal\": {\n \"layout\": \"dev\",\n \"columns\": [[\"mygroups\", \"mycontacts\"], [\"mycontent\", \"recentmessages\"]]\n }\n }\n }\n };\n\n return config;\n});\n", "dev/content_profile.html": "\n\n\n \n\n \n \n \n\n \n \n\n \n \n \n\n \n \n \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n \n
            \n
            \n
            \n
            \n
            \n\n \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n\n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n\n \n
            \n\n
            \n \n
            \n\n __MSG__CONTENT_PROFILE__\n __MSG__THE_FILE_HAS_BEEN_SUCCESSFULLY_SHARED_WITH__\n __MSG__ALL_SELECTED_USERS_AND_GROUPS_HAVE_BEEN_REMOVED_FROM__\n __MSG__VIEWERS__\n __MSG__MANAGERS__\n __MSG__CONTENT_CANNOT_REMOVE_ALL_MANAGERS__\n\n
            \n\n \n
            \n\n \n \n \n\n \n \n\t\t\n\t\n\n", "dev/create_new_account.html": "\n\n\n \n\n \n \n \n\n \n \n\n \n \n \n\n \n \n \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n\n \n
            \n
            \n
            \n
            \n
            __MSG__SIGN_UP_MESSAGE_1__
            \n
            __MSG__SIGN_UP_MESSAGE_2__
            \n
            __MSG__SIGN_UP_MESSAGE_3__
            \n
            \n
            \n
            \n
            \n
            \n

            __MSG__CREATE_A_NEW_ACCOUNT__

            \n
            \n
            \n \n \n \n \n \n \n
            \n
            \n\n
            \n
            \n \n \n \n \n \n \n
            \n
            \n
            \n
            \n \n
            \n
            \n
            \n
            \n\n
            __MSG__PLEASE_ENTER_YOUR_FIRST_NAME__
            \n
            __MSG__PLEASE_ENTER_YOUR_LAST_NAME__
            \n
            __MSG__PLEASE_ENTER_A_VALID_EMAIL_ADDRESS__
            \n
            __MSG__THIS_IS_AN_INVALID_EMAIL_ADDRESS__
            \n
            __MSG__PLEASE_ENTER_YOUR_USERNAME__
            \n
            __MSG__THE_USERNAME_SHOULD_BE_AT_LEAST_THREE_CHARACTERS_LONG__
            \n
            __MSG__THE_USERNAME_SHOULDNT_CONTAIN_SPACES__
            \n
            __MSG__PLEASE_ENTER_YOUR_PASSWORD__
            \n
            __MSG__YOUR_PASSWORD_SHOULD_BE_AT_LEAST_FOUR_CHARACTERS_LONG__
            \n
            __MSG__PLEASE_REPEART_YOUR_PASSWORD__
            \n
            __MSG__THIS_PASSWORD_DOES_NOT_MATCH_THE_FIRST_ONE__
            \n\n
            \n
            \n
            \n
            __MSG__SIGN_UP_RECOMMEND_NAME_1__,
            __MSG__SIGN_UP_RECOMMEND_INSTITUTION_NYU__
            \n "__MSG__SIGN_UP_RECOMMEND_MESSAGE_1__"\n
            \n
            \n
            \n
            \n
            __MSG__SIGN_UP_RECOMMEND_NAME_2__,
            __MSG__SIGN_UP_RECOMMEND_INSTITUTION_NYU__
            \n "__MSG__SIGN_UP_RECOMMEND_MESSAGE_2__"\n
            \n
            \n
            \n
            \n
            __MSG__SIGN_UP_RECOMMEND_NAME_3__,
            __MSG__SIGN_UP_RECOMMEND_INSTITUTION_NYU__
            \n "__MSG__SIGN_UP_RECOMMEND_MESSAGE_3__"\n
            \n

            __MSG__INSTITUTIONS_USING_SAKAI__

            \n
              \n
            • \"__MSG__SIGN_UP_RECOMMEND_INSTITUTION_NYU__\"
            • \n
            • \"__MSG__SIGN_UP_RECOMMEND_INSTITUTION_STANFORD__\"
            • \n
            • \"__MSG__SIGN_UP_RECOMMEND_INSTITUTION_CAMBRIDGE__\"
            • \n
            • \"__MSG__SIGN_UP_RECOMMEND_INSTITUTION_YALE__\"
            • \n
            • \"__MSG__SIGN_UP_RECOMMEND_INSTITUTION_CSU__\"
            • \n
            • \"__MSG__SIGN_UP_RECOMMEND_INSTITUTION_OXFORD__\"
            • \n
            \n
            \n
            \n
            \n
            \n\n \n
            \n\n \n \n \n\n \n", "dev/createnew.html": "\n\n\n \n\n \n \n \n\n \n \n\n \n \n \n\n \n \n \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n\n \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n\n \n
            \n\n \n \n \n \n \n \n \n\n", "dev/css/FSS/fss-base.css": "/*\n * Licensed to the Sakai Foundation (SF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The SF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations under the License.\n */\n\n/* Fluid Base \n * combination of Fluid FSS files from:\n * http://fluidproject.org/releases/1.1.2/infusion-1.1.2.zip\n * version: Infusion 1.1.2\n * \n * Concatenated files contained here:\n * fss-reset.css\n * fss-layout.css\n * fss-text.css\n * \n * Based on version: 2.5.2 of the Yahoo CSS reset, font, and base\n * Copyright (c) 2008, Yahoo! Inc. All rights reserved.\n * Code licensed under the BSD License:\n * http://developer.yahoo.net/yui/license.txt\n * \n * Please see these files in: http://fluidproject.org/releases/1.1.2/infusion-1.1.2-src.zip \n * for usage and full license information\n */\n\n/* Fluid Reset: \n * fss-reset.css \n */\n\ntable{font-size:inherit;font:100%;}\npre,code,kbd,samp,tt{font-family:monospace;*font-size:108%;line-height:100%;}\nhtml{color:#000;background:#FFF;}\nbody,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,code,form,fieldset,legend,input,textarea,p,blockquote,th,td{margin:0;padding:0;}\nfieldset,img{border:0;}\naddress,caption,cite,code,dfn,em,strong,th,var{font-style:normal;font-weight:normal;}\nli{list-style:none;}\ncaption,th{text-align:left;}\nh1,h2,h3,h4,h5,h6{font-size:100%;font-weight:normal;}\nq:before,q:after{content:'';}\nabbr,acronym{border:0;font-variant:normal;}\nsup{vertical-align:text-top;}\nsub{vertical-align:text-bottom;}\nlegend{color:#000;}\nh1{font-size:138.5%;}\nh2{font-size:123.1%;}\nh3{font-size:108%;}\nh1,h2,h3{margin:0.5em 0;}\nh1,h2,h3,h4,h5,h6,strong{font-weight:bold;}\nabbr,acronym{border-bottom:1px dotted #000;cursor:help;}\nem{font-style:italic;}\nblockquote,ul,ol,dl{margin:1em;}\nol,ul,dl{margin-left:2em;}\nol li{list-style:decimal outside;}\nul li{list-style:disc outside;}\ndl dd{margin-left:1em;}\nth{font-weight:bold;text-align:center;}\ncaption{margin-bottom:.5em;text-align:center;}\np,fieldset,table,pre{margin-bottom:1em;}\ninput[type=text],input[type=password],textarea{width:12.25em;*width:11.9em;}\ninput,textarea,select{font-family:inherit;font-size:inherit;font-weight:inherit;}\nhtml{overflow:auto;font:13px/1.231 arial,helvetica,clean,sans-serif;*font-size:small;}\ninput,textarea,select{*font-size:100%;*font-family:sans-serif;}\ninput{*overflow:visible;*padding:0 1em;}\n:focus{outline:2px solid black;}\n\n/* Fluid Layout: \n * fss-layout.css \n */\n\n.fl-fix{overflow:auto;zoom:1;}\n.fl-push{clear:both;}\n.fl-hidden{visibility:hidden;margin:0;}\n.fl-force-right{float:right;display:inline;}\n.fl-force-left{float:left;display:inline;}\n.fl-centered{margin-left:auto;margin-right:auto;display:block;}\n.fl-container-50{width:50px;}\n.fl-container-100{width:100px;}\n.fl-container-150{width:150px;}\n.fl-container-200{width:200px;}\n.fl-container-250{width:250px;}\n.fl-container-300{width:300px;}\n.fl-container-350{width:350px;}\n.fl-container-400{width:400px;}\n.fl-container-450{width:450px;}\n.fl-container-500{width:500px;}\n.fl-container-550{width:550px;}\n.fl-container-600{width:600px;}\n.fl-container-650{width:650px;}\n.fl-container-700{width:700px;}\n.fl-container-750{width:750px;}\n.fl-container-800{width:800px;}\n.fl-container-850{width:850px;}\n.fl-container-900{width:900px;}\n.fl-container-950{width:950px;}\n.fl-container-1000{width:1000px;}\n.fl-container-auto{width:auto;}\n.fl-container-flex{width:100%;clear:both;}\n.fl-container-flex10{width:10%;}\n.fl-container-flex20{width:20%;}\n.fl-container-flex25{width:25%;}\n.fl-container-flex30{width:30%;}\n.fl-container-flex33{width:33%;}\n.fl-container-flex40{width:40%;}\n.fl-container-flex50{width:50%;}\n.fl-container-flex60{width:60%;}\n.fl-container-flex66{width:66%;}\n.fl-container-flex75{width:75%;}\n.fl-layout-linear *,.fl-layout-linear .fl-linearEnabled{overflow:visible!important;clear:both!important;float:none!important;margin-left:0!important;margin-right:0!important;}\n.fl-layout-linear .fl-container,.fl-layout-linear .fl-container-100,.fl-layout-linear .fl-container-150,.fl-layout-linear .fl-container-200,.fl-layout-linear .fl-container-250,.fl-layout-linear .fl-container-300,.fl-layout-linear .fl-container-400,.fl-layout-linear .fl-container-750,.fl-layout-linear .fl-container-950,.fl-layout-linear .fl-container-auto,.fl-layout-linear .fl-container-flex25,.fl-layout-linear .fl-container-flex30,.fl-layout-linear .fl-container-flex33,.fl-layout-linear .fl-container-flex50,.fl-layout-linear .fl-col,.fl-layout-linear .fl-col-side,.fl-layout-linear .fl-col-flex,.fl-layout-linear .fl-col-main,.fl-layout-linear .fl-col-fixed,.fl-layout-linear .fl-col-justified{width:100%!important;margin:auto;padding:0!important;}\n.fl-layout-linear .fl-force-left,.fl-layout-linear .fl-force-right,.fl-layout-linear li{display:block!important;float:none!important;}\n.fl-layout-linear .fl-linearEnabled{width:100%!important;display:block;}\n.fl-layout-linear .fl-button-left,.fl-layout-linear .fl-button-right{padding:1em;}\n.fl-col-justified{float:left;display:inline;overflow:auto;text-align:justify;}\n.fl-col-flex2,.fl-col-flex3,.fl-col-flex4,.fl-col-flex5{overflow:hidden;zoom:1;}\n.fl-col{float:left;display:inline;}\n.fl-col-flex5 .fl-col{width:18.95%;margin-left:.25%;margin-right:.25%;padding-left:.25%;padding-right:.25%;}\n.fl-col-flex4 .fl-col{width:24%;margin-left:.25%;margin-right:.25%;padding-left:.25%;padding-right:.25%;}\n.fl-col-flex3 .fl-col{width:32.33%;margin-left:.25%;margin-right:.25%;padding-left:.25%;padding-right:.25%;}\n.fl-col-flex2 .fl-col{width:48.85%;margin-left:.25%;margin-right:.25%;padding-left:.25%;padding-right:.25%;}\n.fl-col-mixed,.fl-col-mixed2,.fl-col-mixed3{overflow:auto;zoom:1;}\n.fl-col-mixed .fl-col-side{width:200px;}\n.fl-col-mixed .fl-col-side,.fl-col-mixed .fl-col-main{padding:0 10px;}\n.fl-col-mixed2 .fl-col-side{width:200px;padding:0 10px;float:left;}\n.fl-col-mixed2 .fl-col-main{margin-left:220px;padding:0 10px;}\n.fl-col-mixed3 .fl-col-main{margin:0 220px;}\n.fl-col-fixed,.fl-col-flex{padding:0 10px;}\n.fl-col-mixed .fl-col-fixed{width:200px;padding:0 10px;}\n.fl-col-mixed .fl-col-flex{margin-left:220px;padding:0 10px;}\n.fl-col-mixed-100 .fl-col-fixed{width:100px;}\n.fl-col-mixed-100 .fl-col-flex{margin-left:120px;}\n.fl-col-mixed-150 .fl-col-fixed{width:150px;}\n.fl-col-mixed-150 .fl-col-flex{margin-left:170px;}\n.fl-col-mixed-200 .fl-col-fixed{width:200px;}\n.fl-col-mixed-200 .fl-col-flex{margin-left:220px;}\n.fl-col-mixed-250 .fl-col-fixed{width:250px;}\n.fl-col-mixed-250 .fl-col-flex{margin-left:270px;}\n.fl-col-mixed-300 .fl-col-fixed{width:300px;}\n.fl-col-mixed-300 .fl-col-flex{margin-left:320px;}\n.fl-tabs{margin:10px 0 0 0;border-bottom:1px solid #000;text-align:center;padding-bottom:2px;}\n.fl-tabs li{list-style-type:none;display:inline;}\n.fl-tabs li a{padding:3px 16px 2px;background-color:#fff;margin-left:-5px;*margin-bottom:-6px;zoom:1;border:1px solid #000;color:#999;}\n.fl-tabs-center{text-align:center;}\n.fl-tabs-left{text-align:left;padding-left:10px;}\n.fl-tabs-right{text-align:right;padding-right:15px;}\n.fl-tabs .fl-reorderer-dropMarker{padding:0 3px;background-color:#c00;margin:0 5px 0 -5px;zoom:1;}\n.fl-tabs .fl-tabs-active a{padding:2px 16px;border-bottom:none;color:#000;}\n.fl-tabs-content{padding:5px;}\n@media screen and(-webkit-min-device-pixel-ratio:0){.fl-tabs li a{padding:3px 16px 3px;}\n.fl-tabs .fl-tabs-active a{padding:3px 16px 4px;}\n}\n.fl-listmenu{padding:0;margin:0;border-bottom-width:1px;border-bottom-style:solid;}\n.fl-listmenu li{margin:0;padding:0;list-style-type:none;border-width:1px;border-style:solid;border-bottom:none;}\n.fl-listmenu a{padding:5px 5px;display:block;zoom:1;}\nul.fl-grid,.fl-grid ul{padding:0;margin:0;}\n.fl-grid li{list-style-type:none;display:inline;}\n.fl-grid li{float:left;width:19%;margin:.5%;height:150px;overflow:hidden;position:relative;display:inline;}\n.fl-grid li img{display:block;margin:5px auto;}\n.fl-grid li .caption{position:absolute;left:0;bottom:0;width:100%;text-align:center;height:1em;padding:3px 0;}\n.fl-icon{text-indent:-5000px;overflow:hidden;cursor:pointer;display:block;height:16px;width:16px;margin-left:5px;margin-right:5px;background-position:center center;background-repeat:no-repeat;}\ninput.fl-icon{padding-left:16px;}\n.fl-button-left{float:left;margin-right:10px;padding:0 0 0 16px;background-position:left center;background-repeat:no-repeat;}\n.fl-button-right{float:right;margin-left:10px;padding:0 0 0 16px;background-position:left center;background-repeat:no-repeat;}\n.fl-button-inner{float:left;padding:5px 16px 5px 0;cursor:pointer;background-position:right center;background-repeat:no-repeat;}\n.fl-widget{padding:5px;margin-bottom:10px;}\n.fl-widget .button{margin:0 5px;}\n.fl-grabbable .fl-widget-titlebar{background-position:center top;background-repeat:no-repeat;cursor:move;}\n.fl-widget .fl-widget-titlebar h2{padding:0;margin:0;font-size:105%;}\n.fl-widget .fl-widget-titlebar .fl-button-inner{font-size:.8em;padding-bottom:.2em;padding-top:.2em;}\n.fl-widget .fl-widget-controls{margin:-1.3em 0 1.5em 0;}\n.fl-widget .fl-widget-options{background-color:#D5DBDF;overflow-y:hidden;}\n.fl-widget .fl-widget-options ul{margin:0;padding:0;overflow:hidden;zoom:1;}\n.fl-widget .fl-widget-options li{list-style-type:none;float:left;display:inline;padding:0 5px 0 5px;margin-left:-5px;}\n.fl-widget .fl-widget-options a{margin-right:5px;}\n.fl-widget .fl-widget-content{zoom:1;margin:5px 0 0 0;}\n.fl-widget .empty *{padding-top:10px;margin-left:auto;margin-right:auto;text-align:center;}\n.fl-widget .menu{margin:0;}\n.fl-widget .toggle{width:32px;}\n.fl-widget .on{background-position:left top;}\n.fl-widget .off{background-position:left bottom;}\n.fl-controls-left li{list-style-type:none;text-align:left;}\n.fl-controls-left .fl-label{float:left;text-align:left;width:50%;margin-right:5px;}\n.fl-controls-right li{list-style-type:none;display:block;text-align:left;}\n.fl-controls-right .fl-label{float:left;text-align:right;width:50%;margin-right:5px;}\n.fl-controls-centered li{list-style-type:none;display:block;text-align:left;}\n.fl-controls-centered .fl-label{float:left;text-align:center;width:50%;margin-right:5px;}\n.fl-noBackgroundImages,.fl-noBackgroundImages *{background-image:none!important;}\n.fl-noBackgroundImages .fl-icon{text-indent:0!important;width:auto!important;background-color:transparent!important;}\n.fl-ProgEnhance-enhanced,.fl-progEnhance-enhanced{display:none;}\n.fl-offScreen-hidden{position:absolute;left:-10000px;top:auto;width:1px;height:1px;overflow:hidden;}\n\n/* Fluid Text: \n * fss-text.css \n */\n\n.fl-font-size-70,.fl-font-size-70 body,.fl-font-size-70 input,.fl-font-size-70 select,.fl-font-size-70 textarea{font-size:.7em!important;line-height:1em!important;}\n.fl-font-size-80,.fl-font-size-80 body,.fl-font-size-80 input,.fl-font-size-80 select,.fl-font-size-80 textarea{font-size:.8em!important;line-height:1.1em!important;}\n.fl-font-size-90,.fl-font-size-90 body,.fl-font-size-90 input,.fl-font-size-90 select,.fl-font-size-90 textarea{font-size:.9em!important;line-height:1.2em!important;}\n.fl-font-size-100,.fl-font-size-100 body,.fl-font-size-100 input,.fl-font-size-100 select,.fl-font-size-100 textarea{font-size:1em!important;line-height:1.3em!important;}\n.fl-font-size-110,.fl-font-size-110 body,.fl-font-size-110 input,.fl-font-size-110 select,.fl-font-size-110 textarea{font-size:1.1em!important;line-height:1.4em!important;}\n.fl-font-size-120,.fl-font-size-120 body,.fl-font-size-120 input,.fl-font-size-120 select,.fl-font-size-120 textarea{font-size:1.2em!important;line-height:1.5em!important;}\n.fl-font-size-130,.fl-font-size-130 body,.fl-font-size-130 input,.fl-font-size-130 select,.fl-font-size-130 textarea{font-size:1.3em!important;line-height:1.6em!important;}\n.fl-font-size-140,.fl-font-size-140 body,.fl-font-size-140 input,.fl-font-size-140 select,.fl-font-size-140 textarea{font-size:1.4em!important;line-height:1.7em!important;}\n.fl-font-size-150,.fl-font-size-150 body,.fl-font-size-150 input,.fl-font-size-150 select,.fl-font-size-150 textarea{font-size:1.5em!important;line-height:1.8em!important;}\n@media screen and(-webkit-min-device-pixel-ratio:0){[class~='fl-font-size-70'] input[type=submit],[class~='fl-font-size-70'] input[type=button]{padding:0 1em;}\n[class~='fl-font-size-80'] input[type=submit],[class~='fl-font-size-80'] input[type=button]{font-size:.8em!important;padding:0 1em;}\n[class~='fl-font-size-90'] input[type=submit],[class~='fl-font-size-90'] input[type=button]{font-size:.9em!important;padding:0 1em;}\n[class~='fl-font-size-100'] input[type=submit],[class~='fl-font-size-100'] input[type=button]{font-size:1em!important;padding:0 1em;}\n[class~='fl-font-size-110'] input[type=submit],input[type=submit][class~='fl-font-size-110'],[class~='fl-font-size-110'] input[type=button]{background-color:#fff;font-size:1.1em!important;padding:0 1em;}\n[class~='fl-font-size-120'] input[type=submit],input[type=submit][class~='fl-font-size-120'],[class~='fl-font-size-120'] input[type=button]{background-color:#fff;font-size:1.2em!important;padding:0 1em;}\n[class~='fl-font-size-130'] input[type=submit],input[type=submit][class~='fl-font-size-130'],[class~='fl-font-size-130'] input[type=button]{background-color:#fff;font-size:1.3em!important;padding:0 1em;}\n[class~='fl-font-size-140'] input[type=submit],input[type=submit][class~='fl-font-size-140'],[class~='fl-font-size-140'] input[type=button]{background-color:#fff;font-size:1.4em!important;padding:0 1em;}\n[class~='fl-font-size-150'] input[type=submit],input[type=submit][class~='fl-font-size-150'],[class~='fl-font-size-150'] input[type=button]{background-color:#fff;font-size:1.5em!important;padding:0 1em;}\n[class~='fl-font-serif'] input[type=submit],[class~='fl-font-sans'] input[type=submit],[class~='fl-font-monospace'] input[type=submit],[class~='fl-font-arial'] input[type=submit],[class~='fl-font-verdana'] input[type=submit],[class~='fl-font-times'] input[type=submit],[class~='fl-font-courier'] input[type=submit]{background-color:#fff;padding:0 1em;}\n}\n.fl-font-serif,.fl-font-serif *{font-family:Georgia,Times,\"Times New Roman\",\"Book Antiqua\",serif!important;}\n.fl-font-sans,.fl-font-sans *{font-family:Tahoma,Verdana,Helvetica,sans-serif!important;}\n.fl-font-monospace,.fl-font-monospace *{font-family:\"Courier New,Courier\",monospace!important;}\n.fl-font-arial,.fl-font-arial *{font-family:\"Arial\"!important;}\n.fl-font-verdana,.fl-font-verdana *{font-family:\"Verdana\"!important;}\n.fl-font-times,.fl-font-times *{font-family:Georgia,Times,\"Times New Roman\",serif!important;}\n.fl-font-courier,.fl-font-courier *{font-family:\"Courier New\",Courier,monospace!important;}\n.fl-text-align-left{text-align:left;}\n.fl-text-align-right{text-align:right;}\n.fl-text-align-center{text-align:center;}\n.fl-text-align-justify{text-align:justify;}\n.fl-font-spacing-0,.fl-font-spacing-0 body,.fl-font-spacing-0 input,.fl-font-spacing-0 select,.fl-font-spacing-0 textarea{letter-spacing:0;}\n.fl-font-spacing-1,.fl-font-spacing-1 body,.fl-font-spacing-1 input,.fl-font-spacing-1 select,.fl-font-spacing-1 textarea{letter-spacing:.1em;}\n.fl-font-spacing-2,.fl-font-spacing-2 body,.fl-font-spacing-2 input,.fl-font-spacing-2 select,.fl-font-spacing-2 textarea{letter-spacing:.2em;}\n.fl-font-spacing-3,.fl-font-spacing-3 body,.fl-font-spacing-3 input,.fl-font-spacing-3 select,.fl-font-spacing-3 textarea{letter-spacing:.3em;}\n.fl-font-spacing-4,.fl-font-spacing-4 body,.fl-font-spacing-4 input,.fl-font-spacing-4 select,.fl-font-spacing-4 textarea{letter-spacing:.4em;}\n.fl-font-spacing-5,.fl-font-spacing-5 body,.fl-font-spacing-5 input,.fl-font-spacing-5 select,.fl-font-spacing-5 textarea{letter-spacing:.5em;}\n.fl-font-spacing-6,.fl-font-spacing-6 body,.fl-font-spacing-6 input,.fl-font-spacing-6 select,.fl-font-spacing-6 textarea{letter-spacing:.6em;}\n.fl-text-aqua{color:aqua!important;}\n.fl-text-black{color:black!important;}\n.fl-text-blue{color:blue!important;}\n.fl-text-fuchsia{color:fuchsia!important;}\n.fl-text-gray{color:gray!important;}\n.fl-text-green{color:green!important;}\n.fl-text-lime{color:lime!important;}\n.fl-text-maroon{color:maroon!important;}\n.fl-text-navy{color:navy!important;}\n.fl-text-olive{color:olive!important;}\n.fl-text-purple{color:purple!important;}\n.fl-text-red{color:red!important;}\n.fl-text-silver{color:silver!important;}\n.fl-text-teal{color:teal!important;}\n.fl-text-white{color:white!important;}\n.fl-text-yellow{color:yellow!important;}\n.fl-text-underline{text-decoration:underline!important;}\n.fl-text-bold{font-weight:bold!important;}\n.fl-text-larger{font-size:125%!important;}\n.fl-input-outline{border:2px solid;}\n.fl-highlight-yellow,.fl-highlight-hover-yellow:hover,.fl-highlight-focus-yellow:focus{background-color:#FF0!important;background-image:none!important;}\n.fl-highlight-green,.fl-highlight-hover-green:hover,.fl-highlight-focus-green:focus{background-color:#0F0!important;background-image:none!important;}\n.fl-highlight-blue,.fl-highlight-hover-blue:hover,.fl-highlight-focus-blue:focus{background-color:#00F!important;background-image:none!important;}\n\n", "dev/css/sakai/sakai.base.css": "/**\n * Licensed to the Sakai Foundation (SF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The SF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations under the License.\n */\n\n/*\n * GLOBAL RULES\n */\nbody, button{font-family:Arial, Helvetica, sans-serif !important;line-height:120%;}\n.section_header{font-weight:bold;border-bottom:1px solid #ebebeb;font-size:17px;padding-bottom:3px;}\n\n/* adding a visible outline on focus for accessibility */\n*:focus{outline:1px dotted #000;}\n/*apply to any container that needs to be rendered off-screen, but available to screen readers*/\n.s3d-aural-text {position: absolute;clip: rect(1px 1px 1px 1px); /* IE6, IE7 */clip: rect(1px, 1px, 1px, 1px);overflow:hidden;width:1px;height:1px;} \n\n/* HTML TAG OVERRIDES - on top of the FSS reset */\nh1{font-family:Arial,Helvetica,sans-serif;font-size:18px;color:#333;font-weight:bold;line-height:normal;}\nh2{font-family:Arial,Helvetica,sans-serif;font-size:20px;color:#666;}\nh3{font-family:Arial,Helvetica,sans-serif;font-size:18px;color:#666;font-weight:bold;}\nh4{font-family:Arial,Helvetica,sans-serif;font-size:13px;color:#aaa;text-transform:uppercase;}\nh5{font-family:Arial,Helvetica,sans-serif;font-size:18px;color:#aaa;font-weight:bold;}\nh6{font-family:Arial,Helvetica,sans-serif;font-size:18px;color:#aaa;}\nblockquote{font-family:Arial;font-size:14px;color:#666;}\n.caption{font-family:Arial;font-size:11px;color:#666;}\n\n/* \n * PAGE LAYOUT\n */\n.fixed-container {padding:0 20px;width: 920px;overflow:hidden;}\n.s3d-header .fixed-container { background-color: #FFF;}\n.s3d-header .fixed-container .decor_left {background:url(\"/dev/images/dashboard_sprite.png\") no-repeat scroll left -10px transparent; float:left; height:5px; margin-left:-20px; width:5px;}\n.s3d-header .fixed-container .decor { background: url(\"/dev/images/dashboard_sprite.png\") no-repeat scroll right -10px transparent; height: 5px; margin-right: -20px; }\n.grep {color:#666 !important;font-weight:bold;}\n.s3d-gray {color:#666;}\n.s3d-lowercase {text-transform: lowercase;}\n\n.block_image_left {float: left;}\n.block_image_right {float: right;}\n\n/* GENERAL WIDGET CSS */\n/* Widget settings */\n#widget_settings_menu {position:absolute;top:0;left:0;margin-top:10px;}\n\n.s3d-dropdown-list {background:url(\"/dev/images/dropdown_list_bg.png\") repeat-x scroll left top #F5F5F5;border: 1px solid #aaa;border-radius:5px;-moz-border-radius:5px;-webkit-border-radius:5px;box-shadow:0 0 6px 0 #666;}\n.s3d-dropdown-list ul {padding:0;margin:5px;}\n.s3d-dropdown-list ul li {padding:2px 5px;margin:0;font-size:12px;list-style-type:none;cursor:pointer;}\n.s3d-dropdown-list ul li button, .s3d-dropdown-list ul li a {color:#2683bc;font-size:11px;font-weight:bold;text-decoration:none;}\n.s3d-dropdown-list ul li a:hover {color:#999;}\n.s3d-dropdown-list .s3d-dropdown-list-arrow-up {background:url(\"/dev/images/dropdown_list_arrow_up.png\") no-repeat scroll left top transparent;height:20px;margin-top:-20px;position:absolute;right:8px;width:25px;}\n.s3d-dropdown-list .s3d-dropdown-hassubnav {background: url(\"/dev/images/arrow_right.png\") no-repeat right 7px transparent;padding-right: 12px;}\n.s3d-dropdown-list .s3d-dropdown-hassubnav:hover ul {display:block; !important;}\n.s3d-dropdown-list .s3d-dropdown-hassubnav ul {padding:5px; display:none;box-shadow: 2px 0 7px -2px #666;left: 87px;margin-top: -18px;position: absolute;}\n.s3d-dropdown-list .s3d-dropdown-hassubnav ul li {white-space: nowrap;}\n\n/* NEW WIDGETS */\n.s3d-widget-container .fl-widget-titlebar .settings {position:relative;height:18px;margin:8px 0 0;text-indent:0 !important;color:#666 !important;}\n.s3d-widget-container .fl-widget-titlebar .settings:hover {color:#2683BC !important;}\n.s3d-widget-container {border:solid 1px #dfdfdf;border-top:none;-moz-border-radius:0 0 5px 5px;-webkit-border-radius:0 0 5px 5px;border-radius:0 0 5px 5px;margin-bottom:10px;}\n.s3d-widget-container .s3d-contentpage-title {border-bottom:none;background:url(\"/dev/images/widget_header_bg.png\") repeat-x scroll left top #dddddc;height:34px;line-height:34px;padding:0 12px;color:#666;font-weight:bold;font-size:13px;}\n.s3d-widget-container .s3d-contentpage-title:hover {cursor:pointer}\n.s3d-widget-container .hiddenwidget .s3d-contentpage-title {margin-bottom:0;}\n.s3d-widget-footer {min-height:14px;background-color:#DDDDDC;-moz-border-radius:0 0 5px 5px;-webkit-border-radius:0 0 5px 5px;border-radius:0 0 5px 5px;margin-top:7px;padding:7px 12px;box-shadow:0 1px 0 0 #bbb;}\n.s3d-widget-footer a, .s3d-widget-footer span {float:right;}\n.s3d-widget-footer-divider {font-size: 11px; color: #999999; padding-left: 5px;}\n\n/* Change layout */\n#change_layout_dialog {width: 840px !important; margin-left: -420px !important;}\n#change_layout_dialog .elf-right-up {padding: 25px 0}\n#change_layout_dialog .add-tools-right {width:100%;}\n#change_layout_dialog .layout_container {float:left;padding-left:25px;padding-right:13px;}\n#change_layout_dialog .layout_picker_item {width:114px; height: 62px; border: 2px solid #3399CC; border-right: 2px solid #3399CC; background-color: #EEFFFF;}\n#change_layout_dialog .layout_picker_item_column {border-right: 1px solid #3399CC;}\n#change_layout_dialog .layout_picker_item_radio {margin-left:50px; margin-top:10px;}\n#change_layout_dialog .layout_container_unselected {float:left; padding-left:25px; padding-right:13px;}\n#change_layout_dialog .layout_picker_item_unselected {width:114px; height: 62px; border: 2px solid #dddfe1; border-right: 2px solid #dddfe1; background-color: #F8F8F8;}\n#change_layout_dialog .layout_picker_item_column_unselected {border-right: 1px solid #dddfe1;}\n#change_layout_dialog .layout_picker_item_radio_unselected {margin-left:50px; margin-top: 10px;}\n#change_layout_dialog #layouts_list {display:block;}\n\n/* Add Sakai Goodies */\n#add_goodies_dialog {width:520px; height: 374px; margin-left: -260px;}\n.add_goodies .s3d-button {margin:0; height:23px;}\n.add_goodies .dialog_body {height:308px; overflow-y:auto; overflow-x:hidden; position:relative; width:471px;}\n.add_goodies ul {margin:0;}\n.add_goodies ul li{border-bottom: 1px solid #efefef;line-height:30px;list-style:none;padding:0 12px;}\n.add_goodies ul li:hover{background-color:#dbeefc;}\n.add_goodies .dialog_add_goodies_description {color:#333;font-size:13px;font-weight:normal;}\n.add_goodies .dialog_remove_goodies_title {color:#999;font-size:14px;font-weight:bold;}\n.add_goodies .dialog_remove_goodies_description {color:#999999;font-size:12px;font-weight:100;}\n.add_goodies .dialog_add_goodies_title {color:#333;font-size:13px;font-weight:bold;}\n.add_goodies .remove_add_column {float:right;width:100px;}\n\n/* D&D Classes */\n.ui-draggable, .orderable-hover {cursor:move;}\n.orderable-dragging {opacity:0.2; width:auto;}\n.orderable-selected {}\n.orderable-avatar {background-color:#666666; border:1px solid #666666; height:25px; width:50px; z-index:65535;}\ndiv .orderable-drop-marker {background-color:#FA7019; height:10px !important;}\n.drop-warning {background-color:#FFD7D7; border:2px solid red; display:none; left:10px; margin:5px; padding:10px; position:absolute; top:50px; z-index:65535;}\n.orderable-drop-marker-box {background-color:#FFFFFF; border:2px dashed #AAAAAA; height:200px !important; margin-bottom:1em; width:97%;}\n\n/*\n * INSERT MORE DROPDOWN\n */\n.insert_more_menu{position:absolute;left:5px;top:5px;border:1px solid #ccc;background-color:#fff;font-size:.95em!important;}\n.insert_more_menu_border{border-bottom:1px solid #ccc;}\n.insert_more_menu ul{padding:5px 15px 5px 7px;margin:0;}\n.insert_more_menu li{list-style-type:none;}\n.insert_more_menu_inactive{color:#aaa;}\n\n\n/*\n * DROPDOWN MENU\n */\n.s3d-dropdown-menu {display: inline-block;list-style: none outside none;margin-top:4px;padding:0;cursor:pointer; margin-left:-2px;}\n.s3d-dropdown-menu:hover {background: url(\"/devwidgets/topnavigation/images/topnav_nav_hover.png\") repeat-x scroll left top #3480b2;-moz-border-radius:2px 2px 2px 2px; border-radius:2px 2px 2px 2px; -webkit-border-radius:2px 2px 2px 2px;padding:0px;}\n.s3d-dropdown-menu ul, .s3d-dropdown-menu .s3d-dropdown-menu-content-container {margin:0;padding: 10px 7px;display:block;background-color: #F3F3F3;-moz-border-radius:2px; border-radius:2px; -webkit-border-radius:2px;}\n.s3d-dropdown-menu ul li {display:block; list-style:none;padding:1px;margin:0 2px;cursor:pointer;color:#636363; text-decoration:none; font-weight:normal;}\n.s3d-dropdown-menu ul li:hover {background:url(\"/devwidgets/topnavigation/images/topnav_nav_list_hover.png\") repeat-x scroll left top transparent;}\n.s3d-dropdown-menu ul li a {text-decoration:none;display:block;padding:5px 6px;}\n.s3d-dropdown-menu ul li:hover a {color:#f3f3f3;}\n.s3d-dropdown-menu ul li a {color:#2683bc;font-size:12px;}\n.s3d-dropdown-menu .s3d-dropdown-container {background:url(\"/devwidgets/topnavigation/images/topnav_nav_hover_list_bg.png\") repeat-x scroll left top #0c4e79;-moz-border-radius:0 0 5px 5px; border-radius:0 0 5px 5px; -webkit-border-radius:0 0 5px 5px;-moz-box-shadow:0 10px 10px -3px #333333; -webkit-box-shadow:0 10px 10px -3px #333333; box-shadow:0 10px 10px -3px #333333;position:absolute;z-index:999;min-width:140px;padding:5px;-moz-border-radius:0 2px 2px 2px; border-radius:0 2px 2px 2px; -webkit-border-radius:0 2px 2px 2px;cursor:auto;}\n.s3d-split-line {background-color:none;border:medium none;border-top:1px dotted #d4d4d4;height: 1px;margin: 3px 9px;}\n\n/*\n * MARGINS\n */\n.s3d-margin-top-3 {margin-top: 3px !important;}\n.s3d-margin-top-5 {margin-top: 5px !important;}\n.s3d-margin-top-10 {margin-top: 10px !important;}\n.s3d-margin-top-15 {margin-top: 15px !important;}\n.s3d-margin-top-20 {margin-top: 20px !important;}\n.s3d-button.s3d-margin-top-5 {height:19px;line-height:19px;}\n.s3d-button.s3d-no-margin-top {margin-top:0;height:18px !important;line-height:18px;}\n/* \n * LINKS\n */\na{color:#333;text-decoration:none;}\na:hover{text-decoration:underline;}\n.s3d-add_another_location{clear:both;color:#39C;font-size:13px;font-weight:bold;background:url(/dev/images/icons_sprite.png) no-repeat scroll left -21px transparent;float:left;width:16px;height:16px;display:block;margin-right:6px;}\n.s3d-add_another_location_container{clear:both;display:block;padding:7px 0;width:200px;}\n.s3d-hidden,.i18nable{display:none;}\n.s3d-bold{font-weight:bold;}\na.s3d-regular-links,span.s3d-regular-links,.s3d-regular-links a, button.s3d-regular-links, .s3d-regular-links button, .contentauthoring_cell_element a{color:#2683bc;}\na.s3d-widget-links,span.s3d-widget-links,.s3d-widget-links a, button.s3d-widget-links, .s3d-widget-links button{color:#2683bc; font-size:0.9em;}\n.s3d-regular-light-links,.s3d-regular-light-links a,.s3d-regular-light-links button{color:#058EC4 !important;}\n.s3d-content-type-link a{color:#5FB3D2;}\n.s3d-remove-links{float:right;margin-right:10px;height:16px;}\n.s3d-tab-active a{background-color:#FFF!important;color:#000!important;font-weight:400!important;border-color:#DDD #DDD #EEE;border-style:solid;border-width:1px;}\n\n/* new path used when creating pages */\n.content_container .new_page_path {line-height: 3em;color:#999;}\n.content_container .new_page_path span {color:#000;}\n\n/* PAGE HEADERS */\n.s3d-page-header-top-row {clear:both;margin-bottom:10px;}\n.s3d-page-header-top-row .s3d-search-inputfield {width:220px;}\n.s3d-page-header-top-row .s3d-page-header-sort-area {float:right;}\n.s3d-page-header-top-row .s3d-page-header-sort-area select {border:1px solid #999;}\n.s3d-page-header-bottom-row {line-height:30px;margin-bottom:15px;}\n.s3d-page-header-bottom-row button, .s3d-page-header-bottom-row .s3d-page-header-selectall {margin-top:6px;}\n.s3d-page-header-bottom-row .s3d-page-header-selectall {height:21px !important;line-height:23px;padding:0 6px 0 5px;width:13px;float:left;}\n.s3d-page-header-bottom-row .s3d-button .s3d-page-header-add-to-icon {background: url(\"/dev/images/savecontent_button_icon_16x16.png\") no-repeat scroll left center transparent;display:block;float:right;height:18px;margin-left:5px;width:16px;}\n.s3d-page-header-bottom-row .s3d-button:hover .s3d-page-header-add-to-icon {background:url(\"/dev/images/savecontent_button_icon_16x16_hover.png\") no-repeat scroll left center transparent;}\n.s3d-page-header-bottom-row .s3d-button[disabled]:hover .s3d-page-header-add-to-icon {background: url(\"/dev/images/savecontent_button_icon_16x16.png\") no-repeat scroll left center transparent;}\n\n/* LIST VIEW OPTIONS */\n.s3d-listview-options {float:right;padding:0 !important;height:19px !important;margin-top:4px;margin-left:20px;border-radius:3px !important;-moz-border-radius:3px !important;-webkit-border-radius:3px !important;}\n.s3d-listview-options:hover {background:#fff;box-shadow:0 0 4px -2px #A8A8A8 inset;}\n.s3d-listview-options > div {float:left;height:15px;padding:3px 4px 2px;}\n.s3d-listview-options > div.selected,\n.s3d-listview-options > div:hover {background:url(\"/dev/images/button_header_hover.png\") repeat-x scroll left -1px transparent;box-shadow:0 0 4px -2px #A8A8A8 inset;} \n.s3d-listview-options > div:last-child {border-radius:0 3px 3px 0;}\n.s3d-listview-options > div:first-child {border-radius:3px 0 0 3px;}\n\n/*\n * BUTTONS \n */\n.s3d-sprites-buttons{background-color:#FFF;padding:0;position:absolute;left:0;top:0;display:block;width:106px;margin:0;}\n.s3d-sprites-buttons ul{margin:0;border:1px solid #cbd0d4;-moz-border-radius:4px;-webkit-border-radius:4px;border-radius:4px;}\n.s3d-sprites-buttons ul li{padding:5px 0 5px 9px;list-style-type:none;}\n.s3d-sprites-buttons ul li:hover{background-color:#dbeefc;cursor:pointer;}\n.s3d-sprites-buttons ul li a{font-weight:400;font-size:12px;}\n.s3d-sprites-buttons ul li a:hover{text-decoration:none;}\n.s3d-sprites-buttons ul li.more_option{border-bottom:1px solid #cbd0d4;}\n.s3d-sprites-buttons ul li.more_option.option_last{border-bottom:0;}\n.s3d-sprites-buttons .more_link{background:transparent url(\"/dev/images/more_bg_18.png\") top left no-repeat;padding:1px 21px 2px 12px;}\n\n/* New button style */\n/* General */\n.s3d-button {border-radius:5px 5px 5px 5px;color:#666;height:27px;padding:1px 12px 0;cursor:pointer;font-weight:bold;font-size:11px;text-align:center;margin-right:5px;border:none;}\nbutton.s3d-button:focus {box-shadow:0 0 2px 1px #2683BC;}\na.s3d-button {text-decoration:none;}\n\n/* Link buttons */\n.s3d-link-button {margin:0;padding:0;background: none repeat scroll 0 0 transparent;border: medium none;color:#2683bc;font-family: Arial,Helvetica,sans-serif;font-size:13px;display: inline-block;text-align:left;font-size:11px;}\n.s3d-link-button:disabled {cursor:default !important;}\n.s3d-link-button:focus {box-shadow:none !important;}\n.s3d-link-button:hover {cursor:pointer;text-decoration:none;color:#999;}\n.s3d-link-button::-moz-focus-inner {padding:0;margin:0;border:0;}\n\n/* Header buttons */\n.s3d-button.s3d-header-button {background:#fff;box-shadow:0 0 4px -2px #A8A8A8 inset;border:1px solid #e0e3e5;}\n.s3d-button.s3d-header-button:hover, .s3d-button.s3d-header-button.selected {background:url(\"/dev/images/button_header_hover.png\") repeat-x scroll left -1px transparent;border:1px solid #E0E3E5;box-shadow:none;}\n.s3d-button.s3d-header-button:disabled {background:#fff;cursor:auto;color:#ccc}\n.s3d-button.s3d-header-button:disabled:hover {background:#fff;box-shadow:0 0 4px -2px #A8A8A8 inset;border:1px solid #e0e3e5;}\na.s3d-button.s3d-header-button {height:24px;line-height:24px;}\n\n/* Left pop out buttons */\n.s3d-popout-button-shadow {background:url(\"/dev/images/button_popout_border_shadow.png\") no-repeat scroll left top transparent;float:left;height:56px;margin-left:-10px;margin-top:-12px;position:absolute;width:20px;}\n.s3d-button.s3d-header-button.s3d-popout-button {color:#666;padding:0 5px 0 10px;font-size:13px;height:30px;}\n.s3d-button.s3d-header-button.s3d-popout-button:hover {background:url(\"/dev/images/button_popout_hover.png\") repeat-x scroll left -1px transparent;border:1px solid #31b2eb;color:#fff;}\n.s3d-button.s3d-header-button.s3d-popout-button:disabled {background:#fff;cursor:auto;color:#ccc}\n.s3d-button.s3d-header-button.s3d-popout-button:disabled:hover {background:#fff;;border:1px solid #E0E3E5;box-shadow:0 0 4px -2px #A8A8A8 inset;}\n.s3d-button.s3d-header-button.s3d-popout-button > span {display:inline-block;float:right;font-size:18px;margin-left:4px;}\n\n/* Header buttons, smaller */\n.s3d-button.s3d-header-button.s3d-header-smaller-button,\na.s3d-button.s3d-header-button.s3d-header-smaller-button {font-size:10px;height:23px;padding:0 5px;line-height:19px;}\na.s3d-button.s3d-header-button.s3d-header-smaller-button {display:inline-block;height:22px;padding:0 8px;}\n\n/* Regular in-page buttons */\n.s3d-button.s3d-regular-button{background:url(\"/dev/images/button_regular_default.png\") repeat-x scroll left top transparent;height:24px;padding:0 7px;border:1px solid #e0e3e5;color:#666;box-shadow:0 1px 1px 0 #999;text-shadow:0 2px 3px #fff;}\n.s3d-button.s3d-regular-button:hover{background:url(\"/dev/images/button_regular_hover.png\") repeat-x scroll left top transparent;}\na.s3d-button.s3d-regular-button{height:24px;line-height:24px;}\n\n/* Large in-page buttons */\n.s3d-button.s3d-large-button {background:url(\"/dev/images/button_large_default.png\") repeat-x scroll left top transparent;height:31px;padding:0 7px;border:1px solid #e0e3e5;color:#2683bc;box-shadow:0 1px 1px 0 #999;text-shadow:0 2px 3px #fff;font-size:13px;}\n.s3d-button.s3d-large-button:hover {background:url(\"/dev/images/button_large_hover.png\") repeat-x scroll left top transparent;color:#999;}\n.s3d-button.s3d-large-button.grey {color:#666;}\na.s3d-button.s3d-large-button {line-height:31px;}\n\n/* Overlay buttons */\n.s3d-button.s3d-overlay-button {background:url(\"/dev/images/button_overlay_default.png\") repeat-x scroll left top transparent;border:1px solid #E0E3E5;font-size:11px;font-weight:bold;height:24px;margin-left:15px;box-shadow:0 1px 1px 0 #999;text-shadow:0 2px 3px #fff;color:#2683bc;}\n.s3d-button.s3d-overlay-button:hover {background:url(\"/dev/images/button_overlay_hover.png\") repeat-x scroll left top transparent;}\n.s3d-button.s3d-overlay-button:disabled {color:#ccc;}\n.s3d-button.s3d-overlay-button:disabled:hover {background:none !important;border:none !important;cursor:auto;}\na.s3d-button.s3d-overlay-button {display:inline-block;height:21px;line-height:21px;}\n\n/* Overlay Action buttons */\n.s3d-button.s3d-overlay-action-button {background:url(\"/dev/images/button_overlay_action_default.png\") repeat-x scroll left top transparent;font-size:11px;font-weight:bold;height:25px;margin-left:15px;box-shadow:0 1px 2px 0 #222;color:#fff;padding:0 5px;}\n.s3d-button.s3d-overlay-action-button:hover, .s3d-button.s3d-overlay-action-button:focus {background:url(\"/dev/images/button_overlay_action_hover.png\") repeat-x scroll left top transparent;color:#22AAE7;}\n.s3d-button.s3d-overlay-action-button:disabled {color:#ccc;}\n.s3d-button.s3d-overlay-action-button:disabled:hover {background:url(\"/dev/images/button_overlay_action_default.png\") repeat-x scroll left top transparent;cursor:auto;}\n\n.s3d-button.s3d-overlay-button.grey, .s3d-button.s3d-overlay-action-button.grey {color:#666;}\n\n/* No text buttons */\n.s3d-button.s3d-button-no-text {padding:0 !important;}\n\n/* Button in another button */\n.s3d-button .s3d-button-in-button {background:url(\"/dev/images/button_in_button_default.png\") repeat-x top left #5d6267;color:#fff;display:inline;height:15px;line-height:15px;margin:0 0 0 5px;padding:2px 4px;border:1px solid #4f4f4f;}\n.s3d-button .s3d-button-in-button-lighter {background:url(\"/dev/images/button_in_button_light_default.png\") repeat-x scroll left top #CBC9C9;border:1px solid #B5B5B5;color:#fff;display:inline;height:12px;line-height:12px;margin:2px 9px 0 -3px;padding:0 4px;float:left;}\n\n.s3d-button.s3d-overlay-action-button .s3d-button-in-button {display:inline-block;margin-top:-3px;}\n\n/*\n * WIDGET LAYOUT\n */\n.s3d-widget-titlebar{background:url(/dev/images/dashboard_sprite.png) no-repeat scroll right -473px transparent;padding:0 10px 0 0;min-height:49px;}\n.s3d-widget-titlebar-inner{background:url(/dev/images/dashboard_sprite.png) no-repeat scroll -10px -570px transparent;padding:0 0 0 5px;min-height:50px;}\n.s3d-widget .s3d-widget-content,.s3d-content{padding:10px 0;margin:0!important;border-left:3px solid #D4DADE;border-right:3px solid #D4DADE;}\n.s3d-widget .s3d-widget-options-footer-left{background:url(/dev/images/dashboard_sprite.png) no-repeat scroll -70px -436px #D5DBDF;height:12px;}\n.s3d-widget-small-content{padding:5px 0!important;}\n.fl-widget { margin-bottom :7px;}\n.fl-widget .fl-widget-options-footer-top{background:url(/dev/images/dashboard_sprite.png) no-repeat scroll -10px -528px #D5DBDF;height:16px;}\n.fl-widget .fl-widget-options .fl-widget-options-top-right{background:url(/dev/images/dashboard_sprite.png) no-repeat scroll right -432px transparent;float:right;height:16px;padding:0 0 7px 14px;width:16px;}\n.s3d-widget .s3d-widget-options-footer-right{background:url(/dev/images/dashboard_sprite.png) no-repeat scroll right -456px #D5DBDF;float:right;height:12px;width:16px;}\n.s3d-widget .s3d-widget-no-options,.s3d-no-options{background:url(/dev/images/dashboard_sprite.png) no-repeat scroll right -1453px transparent;padding:0 5px 0 0;margin:0;}\n.s3d-widget .s3d-widget-no-options-inner,.s3d-no-options-inner{background:url(/dev/images/dashboard_sprite.png) no-repeat scroll -10px -1433px transparent;margin:0;height:6px;}\n\n.fl-col-flex2 .fl-col{margin-left:5px;margin-right:0;padding-left:0;padding-right:0;width:348px;margin-right:8px;}\n.fl-col-flex2 .fl-col:last-child {margin-right:0;}\n.fl-col-flex3 .fl-col{margin-left:5px;margin-right:0;padding-left:0;padding-right:0;width:228px;margin-right:8px;}\n.fl-col-flex3 .fl-col:last-child {margin-right:0;}\n\n.s3d-inset-shadow-container {background-color:#ededed;border:1px solid #ededed;border-radius:5px;-moz-border-radius:5px;-webkit-border-radius:5px;box-shadow:inset 0 5px 5px -5px #888888;-moz-box-shadow:inset 0 5px 5px -5px #888888;-webkit-box-shadow:inset 0 5px 5px -5px #888888;}\n.s3d-outer-shadow-container {background-color:#FFF;border-radius:4px;box-shadow:0 1px 1px 0 #BBB;-moz-box-shadow:0 1px 1px 0 #BBB;-webkit-box-shadow:0 1px 1px 0 #BBB;margin:0 3px 3px 0;padding:15px 13px 11px;}\n\n/*\n * SEARCH BOXES\n */\n.s3d-search-container .s3d-search-inputfield {height: 22px;padding: 0 4px;color: #333;font-size: 12px;border:1px solid #ccc !important;float:left;}\n.s3d-search-container input::-webkit-input-placeholder {color:#7c7b7b;font-style:italic;font-size:11px !important;}\n.s3d-search-container input:-moz-placeholder{color:#7c7b7b;font-style:italic;font-size:11px !important;}\n.s3d-search-container .s3d-search-button {height:25px !important;width:24px;padding:3px 0 0 0 !important;margin-left:2px;background:none !important;border: none !important;box-shadow:none !important;-moz-box-shadow:none !important;-webkit-box-shadow:none !important;}\n.s3d-search-container .s3d-search-button:hover, .s3d-search-container .s3d-search-button:focus {background: url(\"/dev/images/searchbutton_hover_bg.png\") repeat-x top left transparent !important;border:1px solid #ccc !important;}\n.s3d-search-container .s3d-search-button img {margin:0 auto;}\n.s3d-search-container .s3d-search-button .s3d-search-button-icon{margin:0 auto;display:block;width:16px;height:19px;background: url(\"/dev/images/search_icon.png\") no-repeat top left transparent;}\n\n/*\n * NO RESULTS VIEW (When a widget feed doesn't return any results)\n */\n.s3d-no-results-container {background: url(\"/dev/images/noresults_bg.png\") repeat scroll left top transparent;-moz-border-radius:5px;border-radius:5px;padding:20px;margin:30px 0px 0px;list-style:none}\n.s3d-no-results-container .s3d-no-results-arrow-up {background:url(\"/dev/images/noresults_arrow_up.png\") no-repeat top left transparent;position:absolute;margin-top:-44px;width:36px;height:24px;}\n.s3d-no-results-container h1 {color:#666;font-size:18px;font-weight:normal;margin:5px 0 10px 0 !important;}\n.s3d-no-results-container h1 button{font-size:18px;}\n.s3d-no-results-container .s3d-no-results-icon {width:55px;height:50px;float:left;margin:0 12px 0 0;}\n.s3d-no-results-container .s3d-no-results-icon.less-margin {margin:-8px 12px 0 0;}\n\n.s3d-no-results-container .s3d-no-results-magnifier {background:url(\"/dev/images/magnifier_icon_55x55.png\") no-repeat top left transparent;}\n.s3d-no-results-container .s3d-no-results-world {background:url(\"/dev/images/world_icon_55x55.png\") no-repeat top left transparent;}\n.s3d-no-results-container .s3d-no-results-people {background:url(\"/dev/images/person_icon_55x55.png\") no-repeat top left transparent;}\n.s3d-no-results-container .s3d-no-results-content {background:url(\"/dev/images/content_icon_55x55.png\") no-repeat top left transparent;}\n.s3d-no-results-container .s3d-no-results-content-small {background:url(\"/dev/images/content_icon_42x46.png\") no-repeat top left transparent;width:46px;height:42px;}\n.s3d-no-results-container .s3d-no-results-memberships {background:url(\"/dev/images/memberships_icon_60x55.png\") no-repeat top left transparent;width:60px;}\n.s3d-no-results-container .s3d-no-results-memberships-small {background:url(\"/dev/images/memberships_icon_42x46.png\") no-repeat top left transparent;width:46px;height:42px;}\n.s3d-no-results-container .s3d-no-results-contacts {background:url(\"/dev/images/contacts_icon_60x55.png\") no-repeat top left transparent;width:60px;}\n.s3d-no-results-container .s3d-no-results-contacts-small {background:url(\"/dev/images/contacts_icon_42x46.png\") no-repeat top left transparent;width:46px;height:42px;}\n.s3d-no-results-container .s3d-no-results-replied {background:url(\"/dev/images/replied_icon_55x55.png\") no-repeat top left transparent;}\n.s3d-no-results-container .s3d-no-results-trash {background:url(\"/dev/images/trash_icon_55x55.png\") no-repeat top left transparent;}\n.s3d-no-results-container .s3d-no-results-upload {background:url(\"/dev/images/upload_icon_42x46.png\") no-repeat top left transparent;width:46px;height:42px;}\n.s3d-no-results-container .s3d-no-results-search-messages {background:url(\"/dev/images/no-messages-found-icon.png\") no-repeat top left transparent;width:46px;height:42px;}\n.s3d-no-results-container .s3d-no-results-search-world {background:url(\"/dev/images/world_search_icon_55x55.png\") no-repeat scroll left top transparent;}\n.s3d-no-results-container .s3d-no-results-search-people {background:url(\"/dev/images/people_search_icon_55x55.png\") no-repeat scroll left top transparent;}\n.s3d-no-results-container .s3d-no-results-search-content {background:url(\"/dev/images/content_search_icon_55x55.png\") no-repeat scroll left top transparent;}\n.s3d-no-results-container .s3d-no-results-sakai2sites {background:url(\"/dev/images/sakai2_icon_43x40.png\") no-repeat top left transparent;width:46px;height:45px;}\n\n\n\n.s3d-action-icon {width:16px;height:16px;cursor:pointer; margin-top: -2px;}\n.s3d-action-icon-spacing-right {margin-right:7px;}\n.s3d-action-icon-spacing-left {margin-left:7px;}\n.s3d-action-icon.disabled {display:none;}\n\n.s3d-actions-delete {background:url(\"/dev/images/delete_icon_default.png\") no-repeat top left transparent;}\n.s3d-actions-delete:hover {background:url(\"/dev/images/delete_icon_hover.png\") no-repeat top left transparent;}\n\n.s3d-actions-addtolibrary {background:url(\"/dev/images/addtolibrary_icon_default.png\") no-repeat top left transparent; width: 17px; height: 25px;}\n.s3d-actions-addtolibrary:hover {background:url(\"/dev/images/addtolibrary_icon_hover.png\") no-repeat top left transparent;}\n\n.s3d-actions-author {background:url(\"/dev/images/author_icon_default.png\") no-repeat scroll left top transparent;width:32px !important;}\n.s3d-actions-author:hover {background:url(\"/dev/images/author_icon_hover.png\") no-repeat scroll left top transparent;}\n\n.s3d-actions-share {background:url(\"/dev/images/share_icon_default.png\") no-repeat scroll left top transparent; width: 23px !important;}\n.s3d-actions-share:hover {background:url(\"/dev/images/share_icon_hover.png\") no-repeat scroll left top transparent;}\n\n.s3d-actions-message {background:url(\"/dev/images/message_icon_default.png\") no-repeat scroll left top transparent;}\n.s3d-actions-message:hover {background:url(\"/dev/images/message_icon_hover.png\") no-repeat scroll left top transparent;}\n.s3d-button:hover .s3d-actions-message {background:url(\"/dev/images/message_icon_hover.png\") no-repeat scroll left top transparent;}\n.s3d-button:disabled:hover .s3d-actions-message {background:url(\"/dev/images/message_icon_default.png\") no-repeat scroll left top transparent;}\n\n.s3d-black-check-icon {background:url(\"/dev/images/black_check_icon.png\") no-repeat scroll left top transparent;}\n\n.s3d-above-icon {background:url(\"/dev/images/above_icon_16x16.png\") no-repeat scroll left top transparent;}\n.s3d-below-icon {background:url(\"/dev/images/below_icon_16x16.png\") no-repeat scroll left top transparent;}\n\n/*\n * CONTENT LAYOUT \n */\n.s3d-header .s3d-fixed-container .s3d-decor-left{background:url(/dev/images/dashboard_sprite.png) no-repeat scroll 0 -10px transparent;float:left;height:5px;margin-left:-20px;overflow:visible;width:5px;}\n.s3d-header .s3d-fixed-container .s3d-decor{background:url(/dev/images/dashboard_sprite.png) no-repeat scroll right -10px transparent;float:right;height:5px;margin-right:-20px;width:5px;position:relative;*right:-15px;}\n.s3d-main-container{background:#fff;}\n\n\n/*\n * CHROME STYLES\n * HEADINGS\n */\n.s3d-site-heading{padding:10px 0;font-weight:bold;color:#454A4F;}\n.s3d-site-heading h1{margin:0;padding:0;}\n\n\n/* PROGRAMMATICALLY SET STYLES\n * styles used to programmatically set placement of widgets on the page\n */\n.inline_class_widget_rightfloat{float:right; padding: 5px 0px 5px 10px;}\n.inline_class_widget_leftfloat{float:left; padding: 5px 10px 5px 0px;}\n\n\n/*\n * ACTIONS\n * links used to trigger an action\n * default styling: bold blue link\n * Variants:\n * - action series: links are inside list items, each list item is separated by a divider\n */\na.s3d-action,.s3d-actions a{color:#2683bc;font-weight:bold;font-size:13px;}\na.s3d-action-seeall{font-size:11px!important;}\n\n/* Primary button */\n.s3d-button-primary{background-position:right -110px;}\n.s3d-button-primary .s3d-button-inner{background-position:left -110px;}\n\n/* Search button */\n.s3d-search-button{padding-right:8px;}\n.s3d-search-button .s3d-button-icon-right{padding-right:22px;background-image:url(/dev/images/dashboard_sprite.png);background-position:42px -394px;display:inline;}\n\n\n/*\n * CONTEXT MENU FOR DROPDOWNS\n */.context_menu{left:18px;padding:0;position:absolute;top:124px;}\n.context_menu img{border:1px solid #555;border-bottom:none;}\n.context_menu ul{margin:0;margin-top:-3px;background-color:#eee;border:1px solid #555;}\n.context_menu ul li{list-style-type:none;}\n.context_menu ul li a{color:#666;font-size:.95em;display:block;padding:2px 20px 2px 4px;}\n\n\n/*\n * INPUT FIELDS\n */\ninput[type=text], input[type=password], input[type=email], input[type=url], textarea{border:1px solid #A9A9A9;}\n\n/*\n * CONTENT AREA TOP TABS\n */.s3d-primary-tabs{background:url(/dev/images/dashboard_sprite.png) no-repeat scroll right -1622px transparent;}\n.s3d-primary-tabs,.s3d-primary-tabs-inner{height:25px;border:none;padding:2px 5px 0;display:block;}\n.s3d-primary-tabs ul.fl-tabs{border:none;padding:0;margin:0;float:right;background:url(/dev/images/dashboard_sprite.png) no-repeat scroll left -1592px transparent;padding-left:20px;}\n.s3d-primary-tabs .fl-tabs-right li{margin-top:3px;}\n.s3d-primary-tabs ul.fl-tabs-left{float:left;padding:1px 0 0 3px;}\n.s3d-primary-tabs ul li{margin:0;margin-top:2px;padding:0;background:transparent;border:none;display:block;float:left;}\n.s3d-primary-tabs ul li a{padding:2px 18px 4px 13px;line-height:20px;background:transparent;border:none;font-weight:bold;color:#000;display:block;float:left;margin:0;position:relative;bottom:0!important;}\n.s3d-primary-tabs ul li.fl-tabs-active,.s3d-primary-tabs ul li.fl-tabs-active a{background-color:#FFF;background-image:url(/dev/images/dashboard_sprite.png);background-attachment:scroll;height:30px;bottom:0!important;position:relative;}\n.s3d-primary-tabs ul li.fl-tabs-active{padding-left:5px;background-position:left -1664px;}\n.s3d-primary-tabs ul li.fl-tabs-active a{background-position:right -1714px;font-weight:400;border:none;padding-left:15px;margin:0;}\n.fl-tab-content{border:none;margin:0;}\n\n\n/*\n * AUTOSUGGEST\n */\n.requireUser ul.as-selections{box-shadow:none;-webkit-box-shadow:none;-moz-box-shadow:none;border:1px solid #a9a9a9;}\nul.as-selections.loading{background:#fff url(../../../dev/images/ajax_load.gif) center center no-repeat;}\nul.as-selections li.as-original input {border:0;}\nul.as-selections textarea.as-input, ul.as-selections input.as-input{border:0;resize:none;}\nul.as-selections textarea.as-input{padding:0;}\n.autosuggest_wrapper{float:left;position:relative;width:100%;}\n.autosuggest_wrapper ul.as-list{top:100%;margin-top:-15px;}\n.autosuggest_wrapper .list_categories{float:right;}\n.autosuggest_wrapper textarea {overflow:hidden;}\n\n/* http://blogs.sitepoint.com/2005/02/26/simple-clearing-of-floats/ */\n.clearfix{overflow:auto;}\n\n\n /*\n * OLD DIALOG LAYOUT\n */\n.dialog{color:#333;display:none;left:50%;margin-left:-250px;position:absolute;top:12%;width:500px;}\n.jqmOverlay{background-color:#000;opacity:0.6 !important}\n\n/* Dialog header */\n.dialog_header{background:url(/dev/images/dashboard_sprite.png) no-repeat scroll right -641px transparent;padding:0 8px 0 0;}\n.dialog_header_inner{background:url(/dev/images/dashboard_sprite.png) no-repeat scroll -10px -819px transparent;}\n.dialog_header h1{color:#fff;display:block;font-size:1.1em;margin:0;padding:15px 20px;}\n.dialog_header .dialog_close_image{background:url(/dev/images/dashboard_sprite.png) no-repeat scroll -40px -641px transparent;cursor:pointer;display:block;height:15px;overflow:hidden;position:absolute;right:20px;top:17px;text-indent:-5000px;width:14px;}\n\n/* Dialog content */\n.dialog_content{background-color:#fff;border-left:3px #454a4f solid;border-right:3px #454a4f solid;padding:7px 20px;}\n.dialog_content h1{font-size:1.1em;font-weight:bold;color:#333;margin:0;padding:5px 0;}\n.dialog_content textarea{height:80px;width:98%;padding: 5px;}\n\n/* Dialog buttons */\n.dialog_buttons{clear:both;margin-top:20px;float:right;}\n\n/* Dialog footer */\n.dialog_footer{background:url(/dev/images/dashboard_sprite.png) no-repeat scroll right -957px transparent;padding:0 8px 0 0;}\n.dialog_footer_inner{background:url(/dev/images/dashboard_sprite.png) no-repeat scroll -10px -937px transparent;height:6px;}\n\n/* Dialog tooltip header */\n.dialog_tooltip_header_arrow{background:url(/dev/images/tour_sprite.png) no-repeat scroll -254px -76px transparent;height:18px;margin:0 0 0 20px;width:35px;}\n.dialog_tooltip_header{background:url(/dev/images/tour_sprite.png) no-repeat scroll right -20px transparent;padding:0 22px 0 0;}\n.dialog_tooltip_header_inner{background:url(/dev/images/tour_sprite.png) no-repeat scroll left top transparent;height:14px;}\n\n/* Dialog tooltip content */\n.dialog_tooltip_close{float:right;}\n.dialog_tooltip_content{background:url(/dev/images/tour_sprite.png) no-repeat scroll left -80px transparent;padding:7px 20px 0;}\n.dialog_tooltip_content h2{font-size:1.1em;font-weight:bold;color:#333;margin:0;padding:0 0 5px;}\n.dialog_tooltip_content p{font-size:.9em;}\n.dialog_tooltip_content textarea{height:80px;width:98%;}\n\n/* Dialog tooltip footer */\n.dialog_tooltip_footer{background:url(/dev/images/tour_sprite.png) no-repeat scroll right -60px transparent;padding:0 22px 0 0;}\n.dialog_tooltip_footer_inner{background:url(/dev/images/tour_sprite.png) no-repeat scroll left -40px transparent;height:14px;}\n.dialog_tooltip_footer_arrow{background:url(/dev/images/tour_sprite.png) no-repeat scroll -217px -80px transparent;width:35px;height:18px;margin:0 0 0 20px;}\n\n/*\n * NEW DIALOG LAYOUT\n */\n.s3d-dialog{color:#333;display:none;left:50%;margin-left:-250px;position:absolute;top:50px;width:500px;}\n.s3d-dialog-container {background-color:#fff; border:1px solid #a9a9a9; -moz-border-radius:5px;border-radius:5px;padding:7px 20px 12px;box-shadow:0 0 10px #000;-moz-box-shadow:0 0 10px #000;-webkit-box-shadow:0 0 10px #000;color:#424242;font-size:12px;}\n.s3d-dialog-container .s3d-dialog-close {background:url(\"/dev/images/dialog_close.png\") no-repeat top left transparent;width:19px;height:17px;float:right;cursor:pointer;margin:-2px -15px 0 0;}\n.s3d-dialog-container .s3d-dialog-close:hover {background:url(\"/dev/images/dialog_close.png\") no-repeat left -19px transparent;}\n.s3d-dialog-container h1.s3d-dialog-header {border-bottom:1px dotted #d4d4d4;color:#666;font-size:19px;font-weight:normal;padding-bottom:11px;margin-bottom:15px;}\n\n/* Widget bar item counts */\n.s3d-counts-outer{padding:3px 2px;background:#fff;border:1px solid #D6D9DB;border-radius:5px;-moz-border-radius:5px;-webkit-border-radius:5px;box-shadow:0 0 4px -2px #A8A8A8 inset;-webkit-box-shadow:0 0 4px -2px #A8A8A8 inset;-moz-box-shadow:0 0 4px -2px #A8A8A8 inset; font-size: 11px; position: relative; top: -1px; margin-left: 5px;}\n.s3d-counts-outer a{padding-right:6px;color:#707070;}\n.s3d-counts-inner{color:#fff;padding:0px 4px;background:#D4D4D4;border:1px solid #CACACA;border-radius:5px;-moz-border-radius:5px;-webkit-border-radius:5px;box-shadow:0 0 4px -2px #A2A2A2 inset;-webkit-box-shadow:0 0 4px -2px #A2A2A2 inset;-moz-box-shadow:0 0 4px -2px #A2A2A2 inset;}\n\n/*\n * CHAT\n */\n.chat_available_status_online{background:url(/dev/images/dashboard_sprite.png) no-repeat scroll -33px -395px transparent;}\n.chat_available_status_busy{background:url(/dev/images/dashboard_sprite.png) no-repeat scroll -63px -395px transparent;}\n.chat_available_status_offline{background:url(/dev/images/dashboard_sprite.png) no-repeat scroll -93px -395px transparent;}\n.chat_available_status_offline,.chat_available_status_busy,.chat_available_status_online{padding-left:15px;}\n\n\n/*\n * LISTS\n */\n.s3d-list-item{list-style:none outside none;padding:5px 0 5px 10px!important;margin:0!important;clear:both;overflow:hidden;}\n.s3d-list-entity-picture{float:left;height:32px;margin-right:10px;width:32px;}\n.s3d-entity-displayname{padding-top:4px;margin:4px 0 0 8px;float:left;}\n.s3d-list-link-full-space{clear:both;height:100%;}\nul li.s3d-list-item:hover{background-color:#f1f9fd;}\n\n.s3d-dropdownlistone-text{padding:0 7px;border-right:none;color:#fff;font-size:11px;}\n.s3d-dropdownlistone-text .dropdownlistone_arrow{background:url(/dev/images/dashboard_sprite.png) no-repeat scroll -149px -394px transparent;padding-right:17px;padding-left:8px;}\n.s3d-dropdownlistone-menu{background-color:#868a8d;line-height:16px;position:absolute;z-index:500;padding:0 0 6px;min-width:100px;}\n.s3d-dropdownlistone-menu div{margin-top:5px;}\n.s3d-dropdownlistone-menu ul{margin:0;padding:0;}\n.s3d-dropdownlistone-menu li{display:block;list-style-type:none;margin:0;padding:3px 5px 6px 13px;}\n.s3d-dropdownlistone-menu li a{border:none;color:#fff;padding:0;}\n.s3d-dropdownlistone-menu li a:hover, .s3d-dropdownlistone-menu li button:hover{color:#ddd;}\n.s3d-dropdownlistone-menu-border{border-bottom:1px solid #777;}\n.s3d-dropdownlistone-link-inactive {color:#aaa;}\n\n.s3d-dropdownlisttwo-text{color: #666666;}\n.s3d-dropdownlisttwo-text span{float:left;}\n.s3d-dropdownlisttwo-text .s3d-dropdownlisttwo-arrow-down{background:url(/dev/images/dashboard_sprite.png) no-repeat scroll -128px -400px transparent;float:left;height: 10px;margin: 6px 0 0 6px;width: 10px;}\n.s3d-dropdownlisttwo-text .s3d-dropdownlisttwo-arrow-up{background:url(/dev/images/dashboard_sprite.png) no-repeat scroll -218px -400px transparent;float:left;height: 10px;margin: 6px 0 0 6px;width: 10px;}\n.s3d-dropdownlisttwo-menu{font-size:.95em!important;left:110px;list-style-image:none;position:absolute;top:29px;z-index:10;margin:0;}\n.s3d-dropdownlisttwo-menu ul{background-color:#fff;border:1px solid #CCC;margin:0;padding:5px 15px 5px 7px;}\n.s3d-dropdownlisttwo-menu li{list-style-type:none;padding:0;}\n\n/*\n * POPOVERS\n */\n.s3d-popover-container {border: 1px solid #EAEBEC;border-top: none;border-radius: 5px;-moz-border-radius: 5px;-webkit-border-radius: 5px;box-shadow: 0px 0px 5px #454545;-moz-box-shadow: 0px 0px 5px #454545;-webkit-box-shadow: 0px 0px 5px #454545;background:url(\"/dev/images/popover_bg.png\") repeat-x scroll left top #f4f4f4;font-size:13px;}\n.s3d-popover-container .s3d-popover-inner {padding:10px;word-wrap:break-word;}\n.s3d-popover-arrowup {background:url(\"/dev/images/popover_arrowup.png\") no-repeat scroll left top transparent;height:13px;margin-left:110px;position:relative;width:33px;}\n\n/* \n * TAGLISTS\n */\n.s3d-taglist-container {max-height:53px;overflow-y:hidden;}\n.s3d-taglist{margin:3px 0 0 20px;text-indent:-20px;}\n.s3d-taglist li{display:inline;list-style:disc;padding: 0;margin:0;list-position:inside}\n.s3d-taglist li a{font-size:11px !important;font-weight:normal !important;}\n.s3d-taglist li:before{content:'\\0020\\00b7\\0020'}\n.s3d-taglist li:first-child:before{content:''}\n.s3d-taglist li:first-child{list-style:none;background:url(\"/devwidgets/entity/images/entity_tags_icon.png\") no-repeat scroll left 1px transparent;padding-left:20px;}\n\n/* \n * HIGHLIGHTED AREAS\n */\n.s3d-highlight_area_background{background-color:#EFF2F4;padding:0 10px;margin:0 0 15px;}\n.s3d-highlight_area_background_tl{height:7px;margin-left:-10px;background:url(/dev/images/dashboard_sprite.png) no-repeat scroll -10px -1037px transparent;}\n.s3d-highlight_area_background_tinner{height:7px;margin-right:-10px;background:url(/dev/images/dashboard_sprite.png) no-repeat scroll right -1047px transparent;}\n.s3d-highlight_area_background_bl{clear:both;height:7px;margin-left:-10px;background:url(/dev/images/dashboard_sprite.png) no-repeat scroll -10px -1057px transparent;}\n.s3d-highlight_area_background_binner{clear:both;height:7px;margin-right:-10px;background:url(/dev/images/dashboard_sprite.png) no-repeat scroll right -1067px transparent;}\n.s3d-highlight_area_background_white_content_tl{height:7px;margin-left:-10px;background:url(/dev/images/dashboard_sprite.png) no-repeat scroll -10px -1198px transparent;}\n.s3d-highlight_area_background_white_content_tinner{height:7px;margin-right:-10px;background:url(/dev/images/dashboard_sprite.png) no-repeat scroll right -1208px transparent;}\n.s3d-highlight_area_background_white_content_bl{clear:both;height:7px;margin-left:-10px;background:url(/dev/images/dashboard_sprite.png) no-repeat scroll -10px -1217px transparent;}\n.s3d-highlight_area_background_white_content_binner{clear:both;height:7px;margin-right:-10px;background:url(/dev/images/dashboard_sprite.png) no-repeat scroll right -1227px transparent;}\n.s3d-highlight_area_background_darker1{background-color:#d5dbdf;padding:0 10px;margin:0 0 15px;}\n.s3d-highlight_area_background_darker1_tl{height:7px;margin-left:-10px;background:url(/dev/images/dashboard_sprite.png) no-repeat scroll -10px -1077px transparent;}\n.s3d-highlight_area_background_darker1_tinner{height:7px;margin-right:-10px;background:url(/dev/images/dashboard_sprite.png) no-repeat scroll right -1087px transparent;}\n.s3d-highlight_area_background_darker1_bl{height:7px;margin-left:-10px;background:url(/dev/images/dashboard_sprite.png) no-repeat scroll -10px -1097px transparent;}\n.s3d-highlight_area_background_darker1_binner{height:7px;margin-right:-10px;background:url(/dev/images/dashboard_sprite.png) no-repeat scroll right -1107px transparent;}\n.s3d-highlight_area_background_darker1_white_content_tl{height:7px;margin-left:-10px;background:url(/dev/images/dashboard_sprite.png) no-repeat scroll -10px -1117px transparent;}\n.s3d-highlight_area_background_darker1_white_content_tinner{height:7px;margin-right:-10px;background:url(/dev/images/dashboard_sprite.png) no-repeat scroll right -1127px transparent;}\n.s3d-highlight_area_background_darker1_white_content_bl{clear:both;height:7px;margin-left:-10px;background:url(/dev/images/dashboard_sprite.png) no-repeat scroll -10px -1137px transparent;}\n.s3d-highlight_area_background_darker1_white_content_binner{clear:both;height:7px;margin-right:-10px;background:url(/dev/images/dashboard_sprite.png) no-repeat scroll right -1147px transparent;}\n\n/*\n * SEARCH\n */\n\n/* SEARCH BAR */\n.s3d-search-bar{margin-left:205px; position: relative; top: -10px;}\n.s3d-search-bar input{color:#6d6d6d !important;width:500px;font-size:1.2em !important;display:block;}\n\n/* SEARCH HEADER */\n.s3d-search-header{text-align:left;font-weight:normal;font-size:1em;color:#666;width:700px;}\n.s3d-search-header{margin-bottom: 5px;padding:5px 5px 8px 10px;background-color:#f5f5f5;border-radius:2px;-moz-border-radius:2px;-webkit-border-radius:2px;box-shadow:0 1px 1px 1px #CCC;-webkit-box-shadow:0 1px 1px 1px #CCC;-moz-box-shadow:0 1px 1px 1px #CCC;}\n.s3d-search-header .s3d-search-header-type{display:inline-block; padding-top: 2px;}\n.s3d-search-header .s3d-search-selects{float:right;}\n.s3d-search-header .s3d-search-selects div{display:inline;float:left;}\n.s3d-search-header .s3d-search-selects select{border: 1px solid #CCCCCC;margin:0;}\n.s3d-search-header .s3d-search-selects .s3d-search-sort{margin-left:10px;}\n\n/* SEARCH REFINE BY TAGS */\n.s3d-search-tag{padding:0;margin:5px 2px 0 2px;}\n.s3d-search-activetags span, .s3d-search-refineby span{display:inline-block;}\n.s3d-search-activetags button{color:#6C6C6C;cursor:pointer;border:1px solid #b4b5b5;border-radius:10px;-moz-border-radius:10px;-webkit-border-radius:10px;background-color:#FEFEFE;}\n.s3d-search-activetags button img{margin-left:8px;}\n.s3d-search-refineby-list{margin-bottom:15px;}\n.s3d-search-refineby .s3d-search-refineby-title{margin-bottom:5px;display:block;color:#64707E;}\n.s3d-search-refineby button{cursor:pointer;color:#585858;border:1px solid #A5BECF;border-radius:10px;-moz-border-radius:10px;-webkit-border-radius:10px;background:url(\"/dev/images/search_tag_button.png\") repeat-x scroll left top #cde6f7;}\n\n/* SEARCH RESULTS */\n.s3d-search-results{display:block; overflow:hidden;width:715px;}\n.s3d-search-results .s3d-search-results-container{margin:10px 0 0;padding:0;border-top: 1px solid #e9e9e9;}\n.s3d-search-result{color:#333;padding:10px;border-bottom: 1px dotted #cccccc;list-style:none}\n.s3d-search-result a img{float:left;padding:0 10px 5px 0;width:40px;}\n.s3d-search-result-right{margin-left:80px;}\n.s3d-search-results .jq_pager{clear:both;border-bottom: 1px solid #e9e9e9;}\n.s3d-search-result-detail-separator{color:#cccccc;margin: 0 5px;}\n.s3d-search-result:hover{background-color:#f2f9fc;}\n\n/* search results common elements in content people and group results */\n.s3d-search-result-content .searchcontent_result_usedin_icon, .s3d-search-result-group .searchgroups_result_usedin_icon{background: url(\"/devwidgets/entity/images/entity_used_by_icon.png\") no-repeat scroll left top transparent;}\n.s3d-search-result-content .searchcontent_result_comments_icon, .s3d-search-result-group .searchgroups_result_comments_icon{background: url(\"/devwidgets/entity/images/entity_comment_icon.png\") no-repeat scroll left top transparent;}\n.s3d-search-result-content .searchcontent_result_left_filler, .s3d-search-result-person .searchpeople_result_left_filler, .s3d-search-result-group .searchgroups_result_left_filler{margin:1px 8px 0 0;display: inline;float: left;height: 25px;width: 17px;}\n.s3d-search-result-content .searchcontent_result_plus, .s3d-search-result-person .searchpeople_result_plus, .s3d-search-result-group .searchgroups_result_plus{color:#e4e4e4;font-size:x-large;font-weight:100;margin:-5px 10px 10px -2px;}\n.s3d-search-result-content .searchcontent_result_icon, .s3d-search-result-person .searchpeople_result_icon, .s3d-search-result-group .searchgroups_result_icon{display:inline-block;height:10px;width:15px;}\n.s3d-search-result-content .searchcontent_result_description, .s3d-search-result-person .searchperson_result_description, .s3d-search-result-group .searchgroup_result_description{word-wrap:break-word;}\n/* search results hide elements used in grid view by default */\n.s3d-search-result-content .searchcontent_result_description_grid, .s3d-search-result-person .searchpeople_result_description_grid, .s3d-search-result-group .searchgroups_result_description_grid,\n.s3d-search-result-name-grid, .s3d-search-result-tag-grid, .s3d-search-result-avatar-large,\n.s3d-search-result-content .searchcontent_result_by_name_grid{display:none;}\n\n/* search results content */\n.s3d-search-result-content .searchcontent_result_description{margin:0 0 5px;color:#333;font-size:11px;padding:6px 0; word-wrap: break-word;}\n.s3d-search-result-content .searchcontent_result_mimetype{font-size:smaller;white-space:pre;text-transform:uppercase;}\n.s3d-search-result-content .searchcontent_result_by{padding:3px 0;font-size:11px;}\n.s3d-search-result-content .searchcontent_result_detail_separator{color:#cccccc;}\n.s3d-search-result-content .searchcontent_result_usedin{margin-top:2px;font-size:11px;}\n.s3d-search-result-content .searchcontent_result_share_icon{display:inline-block;float:right;margin-left:10px;}\n.s3d-search-result-content .searchcontent_result_author_icon{margin-left:8px;display:inline-block;float:right;}\n\n/* search results people */\n.s3d-search-result-person .searchpeople_result_person{margin:5px 8px 10px;padding:10px;width:280px;background-color:#FFF;height:50px;float:left;border:none;overflow:hidden;}\n.s3d-search-result-person .searchpeople_result_person_picture{float:left;display:block;width:48px;height:48px;padding:0;margin:0;}\n.s3d-search-result-person .searchpeople_result_dot{display:block;float:left;position:relative;left:5px;}\n.s3d-search-result-person .searchpeople_result_person_dept{display:block;color:#999;font-size:.85em;margin:0 0 4px 57px;line-height:12px;}\n.s3d-search-result-person .searchpeople_result_person_links{margin-left:57px;}\n.s3d-search-result-person .searchpeople_result_person_link{font-size:.85em;}\n.s3d-search-result-person .searchpeople_result_person_divider{color:#ddd;margin:0 0 0 0px!important;}\n.s3d-search-result-person .searchpeople_result_person_threedots{display:block;width:150px;}\n.s3d-search-result-person .searchpeople_result_counts{padding:3px 0;font-size:11px;}\n.s3d-search-result-person .searchpeople_result_message_icon{display:inline-block;float:right;}\n\n/* search results groups */\n.s3d-search-result-group .searchgroups_result_grouptype {font-size:smaller;white-space:pre;}\n.s3d-search-result-group .searchgroups_result_message_icon{display:inline-block;float:right;}\n.s3d-search-result-group .searchgroups_result_usedin{font-size: 11px;padding:3px 0;}\n.s3d-search-result-group .searchgroups_result_comments_icon{margin-left:8px;}\n.s3d-search-result-group .searchgroups_result_description{color:#333;font-size:.90em;padding:3px 0;word-wrap: break-word;}\n.s3d-search-result-group .searchgroups_result_plus{margin:1px 8px 0 0;display:inline;float:left;height:17px;width:17px;}\n.s3d-search-result-group .searchgroups_result_plus:hover{cursor:pointer;}\n\n/* search results grid */\n.s3d-search-results-grid{border:0 !important;border-top:1px solid #ddd !important;padding-top:5px;border-spacing:10px;}\n.s3d-search-results-grid .s3d-search-result{width:150px;height:232px;overflow:hidden;border: 1px solid #FFFFFF !important;float:left;position:relative;margin:0 8px 8px 0;clear:none;}\n.s3d-search-results-grid .s3d-search-result a img{float:left !important;padding:0 !important;margin-left:24px;width:100px !important;height:100px !important;position:absolute;}\n.s3d-search-results-grid .s3d-search-result-anonuser{display:none !important;}\n.s3d-search-results-grid .s3d-search-result-right{margin:135px 0 0 7px;}\n.s3d-search-results-grid .s3d-search-result-user-functions{position:absolute;float:left !important;margin:110px 0 0 21px !important;}\n.s3d-search-results-grid .s3d-search-result-content .s3d-actions-addtolibrary{margin-right:8px;}\n.s3d-search-results-grid .s3d-search-result-content .s3d-actions-author{margin-right:20px;}\n.s3d-search-results-grid .s3d-search-result-content .searchcontent_result_usedin_line{display:block;margin-bottom:2px;}\n.s3d-search-results-grid .s3d-search-result-group .s3d-actions-message{margin-left:60px;}\n.s3d-search-results-grid .s3d-search-result-group .searchgroups_result_plus{margin-top:-1px;}\n.s3d-search-results-grid .s3d-search-result-person .searchpeople_result_left_filler{margin: 0 70px 0 -50px;}\n.s3d-search-results-grid .s3d-search-result-detail-separator{display:block;}\n.s3d-search-results-grid .s3d-search-result-detail-separator span{display:none;}\n.s3d-search-results-grid .searchpeople_result_description, .s3d-search-results-grid .searchgroups_result_description, .s3d-search-results-grid .searchcontent_result_description,\n.s3d-search-results-grid .s3d-search-result-name, .s3d-search-results-grid .s3d-search-result-tag,\n.s3d-search-results-grid .searchcontent_result_by_name{display:none;}\n.s3d-search-results-grid .searchpeople_result_description_grid, .s3d-search-results-grid .searchgroups_result_description_grid, .s3d-search-results-grid .searchcontent_result_description_grid{display:none;word-wrap:break-word;}\n.s3d-search-results-grid .s3d-search-result-name-grid, .s3d-search-results-grid .s3d-search-result-tag-grid, .s3d-search-results-grid .s3d-search-result-avatar-large,\n.s3d-search-results-grid .searchcontent_result_by_name_grid{display:inline;}\n.s3d-search-results-grid ~ .jq_pager{border:0;}\n.s3d-search-results-grid .s3d-search-result:hover{border: 1px solid #e9e9e9;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;}\n\n/* search results anon user */\n.s3d-search-results-anon .s3d-search-result-user-functions{display:none;}\n.s3d-search-results-anon .s3d-search-result-anonuser{display:inline;float:left;height:15px;width:15px;}\n.s3d-search-results-anon .s3d-search-results-grid .s3d-search-result-right{margin:110px 0 0 0;}\n\n/* Search list or grid view buttons */\n.s3d-search-listview-options {float:right;padding:0!important;height:19px!important;margin-left:20px;}\n.s3d-search-listview-options:hover {background:#fff!important;box-shadow:0 0 4px -2px #A8A8A8 inset!important;}\n.s3d-search-listview-options > div {float:left;height:15px;padding:3px 4px 2px;}\n.s3d-search-listview-options > div.selected, .s3d-search-listview-options > div:hover {background:url(\"/dev/images/button_header_hover.png\") repeat-x scroll left -1px transparent;box-shadow:0 0 4px -2px #A8A8A8 inset;} \n.s3d-search-listview-options .search_view_list {border-radius:0 5px 5px 0;}\n.s3d-search-listview-options .search_view_grid {border-radius:5px 0 0 5px;}\n.s3d-search-listview-options .s3d-action-icon {display:block!important;}\n\n/* Search icons */\n.s3d-search-results-gridview {background:url('/dev/images/search_grid_16x16.png') no-repeat top left transparent;}\n.s3d-search-results-gridview:hover {background:url('/dev/images/search_grid_16x16_hover.png') no-repeat top left transparent;}\n.s3d-search-results-gridview.selected {background:url('/dev/images/search_grid_16x16_hover.png') no-repeat top left transparent;}\n.s3d-search-results-listview {background:url('/dev/images/search_list_16x16.png') no-repeat top left transparent;}\n.s3d-search-results-listview:hover {background:url('/dev/images/search_list_16x16_hover.png') no-repeat top left transparent;}\n.s3d-search-results-listview.selected {background:url('/dev/images/search_list_16x16_hover.png') no-repeat top left transparent;}\n.s3d-search-results-carouselview {background:url('/dev/images/search_carousel_16x16.png') no-repeat top left transparent;margin-top:-2px;}\n.s3d-search-results-carouselview:hover {background:url('/dev/images/search_carousel_16x16_hover.png') no-repeat top left transparent;}\n.s3d-search-results-carouselview.selected {background:url('/dev/images/search_carousel_16x16_hover.png') no-repeat top left transparent;}\n.s3d-search-results-blogview {background:url('/dev/images/search_blog_16x16.png') no-repeat top left transparent;margin-top:-1px;}\n.s3d-search-results-blogview:hover {background:url('/dev/images/search_blog_16x16_hover.png') no-repeat top left transparent;}\n.s3d-search-results-blogview.selected {background:url('/dev/images/search_blog_16x16_hover.png') no-repeat top left transparent;}\n\n/*\n * Progress indicator\n */\n#sakai_progressindicator {margin-top:25px;}\n#sakai_progressindicator h1, #sakai_progressindicator p {text-align:center;}\n#sakai_progressindicator .s3d-inset-shadow-container {height:50px;padding-top:30px;}\n#sakai_progressindicator .s3d-inset-shadow-container img {display:block;height:20px;margin-left:auto;margin-right:auto;width:188px;}\n\n/*\n * ICONS\n */\n.s3d-icon-16{width:16px; height:16px;}\n.s3d-icon-25{width:25px; height:25px;}\n.s3d-icon-32{width:32px; height:32px;}\n.s3d-icon-40{width:40px; height:40px;}\n.s3d-icon-50{width:50px; height:50px;}\n.s3d-icon-64{width:64px; height:64px;}\n.s3d-icon-128{width:128px; height:128px;}\n.icon-audio-sprite{background:url(/dev/images/icons_sprite.png) no-repeat scroll -958px 0 transparent;}\n.icon-doc-sprite{background:url(/dev/images/icons_sprite.png) no-repeat scroll -112px 0 transparent;}\n.icon-pdf-sprite{background:url(/dev/images/icons_sprite.png) no-repeat scroll -750px 0 transparent;}\n.icon-pps-sprite{background:url(/dev/images/icons_sprite.png) no-repeat scroll -463px 0 transparent;}\n.icon-swf-sprite{background:url(/dev/images/icons_sprite.png) no-repeat scroll -1040px 0 transparent;}\n.icon-zip-sprite{background:url(/dev/images/icons_sprite.png) no-repeat scroll -1056px 0 transparent;}\n.icon-spreadsheet-sprite{background:url(/dev/images/icons_sprite.png) no-repeat scroll -560px 0 transparent;}\n.icon-txt-sprite{background:url(/dev/images/icons_sprite.png) no-repeat scroll -1086px 0 transparent;}\n.icon-image-sprite{background:url(/dev/images/icons_sprite.png) no-repeat scroll -320px 0 transparent;}\n.icon-html-sprite{background:url(/dev/images/icons_sprite.png) no-repeat scroll -302px 0 transparent;}\n.icon-video-sprite{background:url(/dev/images/icons_sprite.png) no-repeat scroll -1118px 0 transparent;}\n.icon-sound-sprite{background:url(/dev/images/icons_sprite.png) no-repeat scroll -622px 0 transparent;}\n.icon-kmultiple-sprite{background:url(/dev/images/icons_sprite.png) no-repeat scroll -430px 0 transparent;}\n.icon-url-sprite{background:url(/dev/images/icons_sprite.png) no-repeat scroll -304px 0 transparent;}\n.icon-sakaidoc-sprite{background:url(/dev/images/icons_sprite.png) no-repeat scroll -1185px 0 transparent;}\n.icon-unknown-sprite{background:url(/dev/images/icons_sprite.png) no-repeat scroll -143px 0 transparent;}\n.icon-collection-sprite{background:url(/dev/images/icons_sprite.png) no-repeat scroll -430px 0 transparent;}\n\n/*\n * Forms and Validation\n */\n.s3d-form-field-wrapper{position:relative;}\n.s3d-form-field-wrapper input, .s3d-form-field-wrapper textarea, .s3d-form-field-wrapper select,.s3d-form-field-wrapper ul.as-selections{float:left;clear:right;margin-bottom:15px;}\n.s3d-form-field-wrapper input, .s3d-form-field-wrapper textarea{width:55%;padding:0 5px;}\n.s3d-form-field-wrapper ul.as-selections input{padding:0px;}\n.s3d-form-field-wrapper textarea{padding:5px;}\n.s3d-form-field-wrapper input.s3d-input-full-width, .s3d-form-field-wrapper textarea.s3d-input-full-width{width:98%;clear:both;}\n.s3d-form-field-wrapper ul.as-selections{padding: 0px 5px;width:98%;}\n.s3d-form-field-wrapper input{height:21px;}\n.s3d-form-field-wrapper label.s3d-input-label{float:left;width:35%;clear:left;text-align:right;padding:5px 2%;color:#666;}\n.s3d-form-field-wrapper label.s3d-input-label-above{width:100%;clear:both;text-align:left;padding:0;}\n.s3d-form-field-wrapper input.s3d-error, .s3d-form-field-wrapper textarea.s3d-error,.s3d-form-field-wrapper input.s3d-error-after, .s3d-form-field-wrapper textarea.s3d-error-after, .s3d-form-field-wrapper ul.as-selections.s3d-error{border:3px solid #cc0000;}\n.s3d-form-field-wrapper span.s3d-error{clear:both;background-color:#cc0000;color:#fff;padding:0 5px;width:55%;float:left;margin-left:39%;border:3px solid #cc0000;font-size:11px;}\n.s3d-form-field-wrapper span.s3d-error-after{clear:both;background-color:#cc0000;color:#fff;padding:0 5px;width:98%;float:left;margin-left:0;border:3px solid #cc0000;font-size:11px;}\n.s3d-form-field-wrapper input::-webkit-input-placeholder, .s3d-form-field-wrapper textarea::-webkit-input-placeholder {color:#aaa;font-size:12px;}\n.s3d-form-field-wrapper input:-moz-placeholder, .s3d-form-field-wrapper textarea:-moz-placeholder {color:#aaa;font-size:12px;}\n\n/*\n * Drag and Drop\n */\n.s3d-draggable-draggingitems {background-color:#1098d5;color:#fff;padding:4px 7px;display:inline-block;font-size:11px;box-shadow:0px 1px 3px 0 #999;-moz-box-shadow:0px 1px 3px 0 #999;-webkit-box-shadow:0px 1px 3px 0 #999;}\n#s3d-draggeditems-container li {background:#e9f4f8;border:2px solid #d5e9f3;border-radius:2px;-moz-border-radius:2px;-webkit-border-radius:2px;margin-bottom:2px;}\n#s3d-draggeditems-container .s3d-draggable-hidden{display:none;}\n", "dev/css/sakai/sakai.corev1.css": "/**\n * Licensed to the Sakai Foundation (SF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The SF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations under the License.\n */\n.s3d-page-column-left{float:left;width:187px;min-height:500px;border-top:solid #d6dadd 1px;background:url(\"/devwidgets/lhnavigation/images/lhnav_bg.png\") repeat-x scroll 0 0 #FEFEFE;}\n.s3d-page-column-right{float:left;width:773px;border-left:1px solid #d6dadd; border-top:1px solid #d6dadd;padding:0px 0px 20px;box-shadow: 3px -10px 7px 0;-moz-box-shadow: 3px -10px 7px 0;-webkit-box-shadow: 3px -10px 7px 0;box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;}\n/* .s3d-page-fullcolumn-nopadding{width:960px;min-height:100px;border-top:solid #d6dadd 1px;}\n.s3d-page-fullcolumn-padding{width:920px;min-height:100px;border-top:solid #d6dadd 1px; padding: 20px 20px 30px;} \n.s3d-page-full{height:100px;} */\n.s3d-navigation-container{background: url(\"/devwidgets/topnavigation/images/topnav_bg.png\") repeat-x scroll left top transparent;-moz-box-shadow:0 -5px 9px 6px #555555;-webkit-box-shadow:0 -5px 9px 6px #555555;box-shadow:0 -5px 9px 6px #555555;height: 40px;margin-left: auto;margin-right: auto;position: absolute;width: 100%;z-index: 999;}\n.s3d-page-header{background:url(\"/devwidgets/entity/images/entity_bottom_bordershadow.png\") repeat-x scroll left bottom, url(\"/devwidgets/entity/images/entity_bg.png\") repeat-x scroll left top #f7f7f7;border-bottom: 1px solid #B3B3B4;min-height: 45px;margin-top: 40px;width:960px;}\n.s3d-page-header-fullheight {min-height: 70px;}\n.s3d-page-header.collection_modified {padding:0px;height:auto;width:960px;-moz-box-shadow:0 -5px 9px 6px #555555;-webkit-box-shadow:0 -5px 9px 6px #555555;box-shadow:0 -5px 9px 6px #555555;min-height:0;border-bottom:0;}\n.s3d-fixed-container .s3d-container-shadow-left, .s3d-container-shadow-right {background:url(\"/dev/images/container_shadow_left.png\") no-repeat scroll 0 0 transparent;height:346px;position:absolute;width:5px;margin-left:-5px;}\n.s3d-container-shadow-right{background: url(\"/dev/images/container_shadow_right.png\") no-repeat scroll 0 0 transparent;float: right;margin-left:960px;}\n\n/* CSS THAT OVERWRITES MAIN CSS */\n.s3d-main-container {padding: 0px !important;}\n.fixed-container.s3d-main-container{width:960px;}\n.s3d-twocolumn{background-color:#fff;}\n.requireUser, .requireAnon {background: url(\"/dev/images/grey_bg.png\") repeat-x scroll left -91px #f2f2f2 !important;}\n.s3d-header .fixed-container {padding:0 !important; width:960px;}\n.s3d-header .s3d-fixed-container .s3d-decor-left {margin-left:0;}\n.s3d-header .s3d-fixed-container .s3d-decor {margin-right:0;}\n.s3d-header .s3d-fixed-container .s3d-decor-left {background: url(\"/dev/images/pageHeader_tl.png\") no-repeat scroll 0 0 transparent;}\n.s3d-header .s3d-fixed-container .s3d-decor {background: url(\"/dev/images/pageHeader_tr.png\") no-repeat scroll 0 0 transparent;}\n.s3d-header .s3d-navigation-container{min-width:960px;}\n\n/* Page titles */\n.s3d-contentpage-title {border-bottom:5px solid #E1E1E1; color:#424242; font-size:1.25em; padding:8px 0; margin-bottom: 15px;}\n\n/* Page bottom */\n.s3d-bottom-spacer {clear: both; padding-bottom: 40px;}\n", "dev/group.html": "\n\n\n \n\n \n \n \n\n \n \n\n \n \n \n\n \n \n \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n\n \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n\n \n
            \n\n
            \n\n
            \n\n
            \n\n
            \n\n \n
            \n\n \n \n \n\n \n \n\n \n\n", "dev/index.html": "\n\n \n \n \n \n \n \n \n \n \n\n
            __MSG__IE_PLACEHOLDER__
            \n\n \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n \n
            \n\n \n \n \n \n", "dev/javascript/acknowledgements.js": "/*\n * Licensed to the Sakai Foundation (SF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The SF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations under the License.\n */\n\nrequire([\"jquery\",\"sakai/sakai.api.core\"], function($, sakai) {\n\n sakai_global.acknowledgements = function() {\n \n var pubdata = {\n \"structure0\": {\n \"featured\": {\n \"_ref\": \"id1\",\n \"_title\": \"Featured\",\n \"_order\": 0,\n \"main\": {\n \"_ref\": \"id2\",\n \"_order\": 0,\n \"_title\": \"Featured\"\n }\n },\n \"ui\": {\n \"_ref\": \"id2\",\n \"_title\": \"UI Technologies\",\n \"_order\": 1,\n \"main\": {\n \"_ref\": \"id2\",\n \"_order\": 0,\n \"_title\": \"UI Technologies\"\n }\n },\n \"nakamura\": {\n \"_title\": \"Back-end Technologies\",\n \"_ref\": \"id3\",\n \"_order\": 2,\n \"main\": {\n \"_ref\": \"id3\",\n \"_order\": 0,\n \"_title\": \"Back-end Technologies\"\n }\n }\n },\n \"id1\": {\n \"rows\": [\n {\n \"id\": \"id2414417\",\n \"columns\": [\n {\n \"width\": 1,\n \"elements\": [{\n \"type\": \"htmlblock\",\n \"id\": \"id4\"\n }]\n }\n ]\n }\n ],\n \"id4\": {\n \"htmlblock\": {\n \"content\": $(\"#acknowledgements_featured\").html()\n }\n }\n },\n \"id2\": {\n \"rows\": [\n {\n \"id\": \"id3562190\",\n \"columns\": [\n {\n \"width\": 1,\n \"elements\": [{\n \"type\": \"htmlblock\",\n \"id\": \"id5\"\n }]\n }\n ]\n }\n ],\n \"id5\": {\n \"htmlblock\": {\n \"content\": $(\"#acknowledgements_uitech\").html()\n }\n }\n },\n \"id3\": {\n \"rows\": [\n {\n \"id\": \"id6521849\",\n \"columns\": [\n {\n \"width\": 1,\n \"elements\": [{\n \"type\": \"htmlblock\",\n \"id\": \"id6\"\n }]\n }\n ]\n }\n ],\n \"id6\": {\n \"htmlblock\": {\n \"content\": $(\"#acknowledgements_backendtech\").html()\n }\n }\n }\n };\n\n var generateNav = function(){\n $(window).trigger(\"lhnav.init\", [pubdata, {}, {}]);\n };\n \n var renderEntity = function(){\n $(window).trigger(\"sakai.entity.init\", [\"acknowledgements\"]);\n };\n\n $(window).bind(\"lhnav.ready\", function(){\n generateNav();\n });\n \n $(window).bind(\"sakai.entity.ready\", function(){\n renderEntity(); \n });\n \n generateNav();\n renderEntity();\n \n };\n\n sakai.api.Widgets.Container.registerForLoad(\"acknowledgements\");\n});\n", "dev/javascript/category.js": "/*\n * Licensed to the Sakai Foundation (SF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The SF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations under the License.\n */\n\nrequire([\"jquery\",\"sakai/sakai.api.core\"], function($, sakai) {\n\n sakai_global.category = sakai_global.category || {};\n\n sakai_global.category = function() {\n\n var originalTitle = document.title;\n var pubdata = {};\n var privdata = {};\n\n // Containers\n var $exploreNavigation = $(\"#explore_navigation\");\n var toplevelId = \"\";\n\n // Templates\n var exploreNavigationTemplate = \"explore_navigation_template\";\n\n /**\n * Create the breadcrumb data and render on screen\n * @param {Object} dirData Object that contains children for the category\n * @param {Array} bbqData Array of IDs fetched with bbq to help identify correct children\n */\n var createBreadcrumb = function(dirData, bbqData){\n if (!dirData){\n sakai.api.Security.send404();\n return false;\n }\n // Create top level breadcrumb\n var breadcrumb = [];\n breadcrumb.push({\n \"title\": sakai.api.i18n.getValueForKey(\"ALL_CATEGORIES\"),\n \"id\": bbqData[0],\n \"link\": true,\n \"url\": \"/categories\"\n });\n breadcrumb.push({\n \"title\": dirData.title,\n \"id\": dirData.id,\n \"link\": bbqData.length - 1\n });\n bbqData.splice(0,1);\n\n // Create children level breadcrumb\n var children = dirData.children[bbqData[0]];\n $.each(bbqData, function(index, item){\n breadcrumb.push({\n \"title\": children.title,\n \"id\": item,\n \"link\": bbqData.length - 1 - index\n });\n if (children.children) {\n children = children.children[bbqData[index]];\n }\n });\n\n $exploreNavigation.html(sakai.api.Util.TemplateRenderer(exploreNavigationTemplate,{\"breadcrumb\": breadcrumb}));\n document.title = originalTitle + \" \" + dirData.title;\n };\n\n /**\n * Generate the navigation object and pass it to the left hand navigation widget\n * @param {Object} navData Contains all data from the category the user is currently viewing\n */\n var generateNav = function(navData){\n\n toplevelId = navData.id;\n\n pubdata = {\n \"structure0\": {}\n };\n privdata = {\n \"structure0\": {}\n };\n\n var rnd = sakai.api.Util.generateWidgetId();\n privdata[\"structure0\"][navData.id] = {\n \"_order\": 0,\n \"_ref\": rnd,\n \"_title\": navData.title\n };\n\n // featuredcontent, featured people and featuredworld random numbers\n var fcRnd = sakai.api.Util.generateWidgetId();\n var fpRnd = sakai.api.Util.generateWidgetId();\n var fwRnd = sakai.api.Util.generateWidgetId();\n privdata[rnd] = {\n \"rows\": [{\n \"id\": sakai.api.Util.generateWidgetId(),\n \"columns\": [{\n \"width\": 1,\n \"elements\": [\n {\n \"id\": fcRnd,\n \"type\": \"featuredcontent\"\n },\n {\n \"id\": fpRnd,\n \"type\": \"featuredpeople\"\n },\n {\n \"id\": fwRnd,\n \"type\": \"featuredworlds\"\n }\n ]\n }]\n }]\n };\n privdata[rnd][fcRnd] = {\n category: navData.id,\n title: navData.title\n };\n privdata[rnd][fpRnd] = {\n category: navData.id,\n title: navData.title\n };\n privdata[rnd][fwRnd] = {\n category: navData.id,\n title: navData.title\n };\n\n var count = 0;\n $.each(navData.children, function(index, item){\n var rnd = sakai.api.Util.generateWidgetId();\n pubdata[\"structure0\"][navData.id + \"-\" + index] = {\n \"_ref\": rnd,\n \"_order\": count,\n \"_title\": item.title,\n \"main\": {\n \"_ref\": rnd,\n \"_order\": 0,\n \"_title\": item.title\n }\n };\n\n // featuredcontent, featured people and featuredworld random numbers\n var fcRnd = sakai.api.Util.generateWidgetId();\n var fpRnd = sakai.api.Util.generateWidgetId();\n var fwRnd = sakai.api.Util.generateWidgetId();\n pubdata[rnd] = {\n \"rows\": [{\n \"id\": sakai.api.Util.generateWidgetId(),\n \"columns\": [{\n \"width\": 1,\n \"elements\": [\n {\n \"id\": fcRnd,\n \"type\": \"featuredcontent\"\n },\n {\n \"id\": fpRnd,\n \"type\": \"featuredpeople\"\n },\n {\n \"id\": fwRnd,\n \"type\": \"featuredworlds\"\n }\n ]\n }]\n }]\n };\n pubdata[rnd][fcRnd] = {\n category: navData.id + \"-\" + index,\n title: navData.title + \" \u00bb \" + item.title\n };\n pubdata[rnd][fpRnd] = {\n category: navData.id + \"-\" + index,\n title: navData.title + \" \u00bb \" + item.title\n };\n pubdata[rnd][fwRnd] = {\n category: navData.id + \"-\" + index,\n title: navData.title + \" \u00bb \" + item.title\n };\n\n count++;\n });\n $(window).trigger(\"lhnav.init\", [pubdata, privdata, {}]);\n };\n\n /**\n * Get the category out of the URL and give it back\n * @return {Array} Array of strings representing the selected hierarchy\n */\n var getCategory = function(){\n var category = $.bbq.getState(\"l\");\n if (category) {\n category = category.split(\"-\");\n }\n return category;\n };\n\n var doInit = function(){\n var category = getCategory();\n if (!$.isArray(category) || !sakai.config.Directory[category[0]]){\n sakai.api.Security.send404();\n return false;\n }\n sakai.config.Directory[category[0]].id = category[0];\n generateNav(sakai.config.Directory[category[0]]);\n createBreadcrumb(sakai.config.Directory[category[0]], category);\n };\n\n $(window).bind(\"lhnav.ready\", function(){\n doInit();\n });\n\n $(window).bind(\"hashchange\", function(e, data){\n var category = getCategory();\n createBreadcrumb(sakai.config.Directory[category[0]], category);\n });\n\n };\n\n sakai.api.Widgets.Container.registerForLoad(\"category\");\n});", "dev/javascript/content_profile.js": "/*\n * Licensed to the Sakai Foundation (SF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The SF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations under the License.\n */\n\nrequire([\"jquery\",\"sakai/sakai.api.core\"], function($, sakai) {\n\n sakai_global.content_profile = function(){\n\n var previous_content_path = false;\n var content_path = \"\"; // The current path of the content\n var ready_event_fired = 0;\n var list_event_fired = false;\n var intervalId;\n\n var showPreview = true;\n var collectionID = false;\n var collectionName = false;\n var isCollection = false;\n\n ///////////////////////////////\n // PRIVATE UTILITY FUNCTIONS //\n ///////////////////////////////\n\n /**\n * Load the content profile for the current content path\n * @param {Boolean} ignoreActivity Flag to also update activity data or not\n */\n var loadContentProfile = function(callback, ignoreActivity){\n // Check whether there is actually a content path in the URL\n if (content_path) {\n // Get the content information, the members and managers and version information\n sakai.api.Content.loadFullProfile(content_path, function(success, data){\n if (success) {\n if (data.results.hasOwnProperty(0)) {\n var contentInfo = false;\n if (data.results[0][\"status\"] === 404){\n sakai.api.Security.send404();\n return;\n } else if (data.results[0][\"status\"] === 403){\n sakai.api.Security.send403();\n return;\n } else {\n contentInfo = $.parseJSON(data.results[0].body);\n if (contentInfo[\"_mimeType\"] && contentInfo[\"_mimeType\"] === \"x-sakai/document\" || contentInfo[\"_mimeType\"] && contentInfo[\"_mimeType\"] === \"x-sakai/collection\"){\n showPreview = false;\n } else {\n switchToOneColumnLayout(false);\n }\n\n var collectionId = $.bbq.getState(\"collectionId\");\n var collectionName = $.bbq.getState(\"collectionName\");\n var currentPath = $.bbq.getState(\"p\");\n if(collectionId && collectionName && currentPath){\n // Show go back to collection link\n $(\"#back_to_collection_button #collection_title\").text(collectionName);\n $(\"#back_to_collection_button\").attr(\"href\", \"/content#p=\" + collectionId + \"/\" + sakai.api.Util.safeURL(collectionName) + \"&item=\" + currentPath.split(\"/\")[0]);\n $(\"#back_to_collection_container\").show(\"slow\");\n } else {\n $(\"#back_to_collection_container\").hide(\"slow\");\n }\n }\n }\n\n sakai.api.Content.parseFullProfile(data.results, function(parsedData){\n parsedData.mode = \"content\";\n sakai_global.content_profile.content_data = parsedData;\n $(window).trigger(\"ready.contentprofile.sakai\", sakai_global.content_profile.content_data);\n if ($.isFunction(callback)) {\n callback(true);\n }\n initEntityWidget();\n\n if (!showPreview){\n renderSakaiDoc(parsedData.data);\n }\n });\n }\n });\n } else {\n sakai.api.Security.send404();\n }\n };\n\n var initEntityWidget = function(){\n if (sakai_global.content_profile.content_data) {\n var context = \"content\";\n if (sakai.data.me.user.anon) {\n type = \"content_anon\";\n } else if (sakai_global.content_profile.content_data.isManager) {\n type = \"content_managed\";\n } else if (sakai_global.content_profile.content_data.isViewer) {\n type = \"content_shared\";\n } else {\n type = \"content_not_shared\";\n }\n $(window).trigger(\"sakai.entity.init\", [context, type, sakai_global.content_profile.content_data]);\n }\n };\n\n $(window).bind(\"sakai.entity.ready\", function(){\n initEntityWidget();\n });\n\n $(window).bind(\"load.content_profile.sakai\", function(e, callback) {\n loadContentProfile(callback);\n });\n\n var handleHashChange = function() {\n content_path = $.bbq.getState(\"p\") || \"\";\n content_path = content_path.split(\"/\");\n content_path = \"/p/\" + content_path[0];\n\n if (content_path != previous_content_path) {\n previous_content_path = content_path;\n globalPageStructure = false;\n loadContentProfile(function(){\n // The request was successful so initialise the entity widget\n if (sakai_global.entity && sakai_global.entity.isReady) {\n $(window).trigger(\"render.entity.sakai\", [\"content\", sakai_global.content_profile.content_data]);\n }\n else {\n $(window).bind(\"ready.entity.sakai\", function(e){\n $(window).trigger(\"render.entity.sakai\", [\"content\", sakai_global.content_profile.content_data]);\n ready_event_fired++;\n });\n }\n // The request was successful so initialise the relatedcontent widget\n if (sakai_global.relatedcontent && sakai_global.relatedcontent.isReady) {\n $(window).trigger(\"render.relatedcontent.sakai\", sakai_global.content_profile.content_data);\n }\n else {\n $(window).bind(\"ready.relatedcontent.sakai\", function(e){\n $(window).trigger(\"render.relatedcontent.sakai\", sakai_global.content_profile.content_data);\n ready_event_fired++;\n });\n }\n // The request was successful so initialise the relatedcontent widget\n if (sakai_global.contentpreview && sakai_global.contentpreview.isReady) {\n if (showPreview) {\n $(window).trigger(\"start.contentpreview.sakai\", sakai_global.content_profile.content_data);\n }\n }\n else {\n $(window).bind(\"ready.contentpreview.sakai\", function(e){\n if (showPreview) {\n $(window).trigger(\"start.contentpreview.sakai\", sakai_global.content_profile.content_data);\n ready_event_fired++;\n }\n });\n }\n // The request was successful so initialise the metadata widget\n if (sakai_global.contentmetadata && sakai_global.contentmetadata.isReady) {\n $(window).trigger(\"render.contentmetadata.sakai\");\n }\n else {\n $(window).bind(\"ready.contentmetadata.sakai\", function(e){\n $(window).trigger(\"render.contentmetadata.sakai\");\n ready_event_fired++;\n });\n } \n sakai.api.Security.showPage();\n\n if(sakai_global.content_profile.content_data.data._mimeType === \"x-sakai/collection\"){\n $(\".collectionviewer_carousel_item.selected\").click();\n }\n\n // rerender comments widget\n $(window).trigger(\"content_profile_hash_change\");\n });\n }\n showPreview = true;\n };\n\n $(\"#entity_content_share\").live(\"click\", function(){\n $(window).trigger(\"init.sharecontent.sakai\");\n return false;\n });\n\n $(\"#entity_content_add_to_library\").live(\"click\", function(){\n sakai.api.Content.addToLibrary(sakai_global.content_profile.content_data.data[\"_path\"], sakai.data.me.user.userid, false, function(){\n $(\"#entity_content_add_to_library\").hide();\n sakai.api.Util.notification.show($(\"#content_profile_add_library_title\").html(), $(\"#content_profile_add_library_body\").html());\n });\n });\n\n ////////////////////\n // Initialisation //\n ////////////////////\n\n /**\n * Initialise the content profile page\n */\n var init = function(){\n // Bind an event to window.onhashchange that, when the history state changes,\n // loads all the information for the current resource\n $(window).bind('hashchange', function(){\n handleHashChange();\n });\n handleHashChange();\n };\n\n // //////////////////////////\n // Dealing with Sakai docs //\n /////////////////////////////\n\n var globalPageStructure = false;\n\n var generateNav = function(pagestructure){\n if (pagestructure) {\n $(window).trigger(\"lhnav.init\", [pagestructure, {}, {\n parametersToCarryOver: {\n \"p\": sakai_global.content_profile.content_data.content_path.replace(\"/p/\", \"\")\n }\n }, sakai_global.content_profile.content_data.content_path]);\n }\n };\n\n $(window).bind(\"lhnav.ready\", function(){\n generateNav(globalPageStructure);\n });\n\n var getPageCount = function(pagestructure){\n var pageCount = 0;\n for (var tl in pagestructure[\"structure0\"]){\n if (pagestructure[\"structure0\"].hasOwnProperty(tl) && tl !== \"_childCount\"){\n pageCount++;\n if (pageCount >= 3){\n return 3;\n }\n for (var ll in pagestructure[\"structure0\"][tl]){\n if (ll.substring(0,1) !== \"_\"){\n pageCount++;\n if (pageCount >= 3){\n return 3;\n }\n }\n }\n }\n }\n return pageCount;\n };\n\n $(window).bind(\"sakai.contentauthoring.needsTwoColumns\", function(){\n switchToTwoColumnLayout(true);\n });\n\n $(window).bind(\"sakai.contentauthoring.needsOneColumn\", function(){\n switchToOneColumnLayout(true);\n });\n\n var setManagerProperty = function(structure, value){\n for (var i in structure){\n if (structure.hasOwnProperty(i)){\n structure[i]._canEdit = value;\n structure[i]._canSubedit = value;\n }\n }\n return structure;\n };\n\n var renderSakaiDoc = function(pagestructure){\n pagestructure = sakai.api.Content.Migrators.migratePageStructure(sakai.api.Server.cleanUpSakaiDocObject(pagestructure), sakai_global.content_profile.content_data.isManager ? content_path : false);\n pagestructure.structure0 = setManagerProperty(pagestructure.structure0, sakai_global.content_profile.content_data.isManager);\n if (getPageCount(pagestructure) >= 3){\n switchToTwoColumnLayout(true);\n } else {\n switchToOneColumnLayout(true);\n }\n globalPageStructure = pagestructure;\n generateNav(pagestructure);\n };\n\n var switchToTwoColumnLayout = function(isSakaiDoc){\n $(\"#content_profile_left_column\").show();\n $(\"#content_profile_main_container\").addClass(\"s3d-twocolumn\");\n $(\"#content_profile_right_container\").addClass(\"s3d-page-column-right\");\n $(\"#content_profile_right_container\").removeClass(\"s3d-page-fullcolumn-nopadding\");\n $(\"#content_profile_right_metacomments\").removeClass(\"fl-container-650\");\n $(\"#content_profile_right_metacomments\").addClass(\"fl-container-450\");\n if (isSakaiDoc){\n $(\"#content_profile_preview_container\").hide();\n $(\"#content_profile_contentauthoring_container\").show();\n } else {\n $(\"#content_profile_preview_container\").show();\n $(\"#content_profile_contentauthoring_container\").hide();\n }\n };\n\n var switchToOneColumnLayout = function(isSakaiDoc){\n $(\"#content_profile_left_column\").hide();\n $(\"#content_profile_main_container\").removeClass(\"s3d-twocolumn\");\n $(\"#content_profile_right_container\").removeClass(\"s3d-page-column-right\");\n $(\"#content_profile_right_container\").addClass(\"s3d-page-fullcolumn-nopadding\");\n $(\"#content_profile_right_metacomments\").addClass(\"fl-container-650\");\n $(\"#content_profile_right_metacomments\").removeClass(\"fl-container-450\");\n if (isSakaiDoc){\n $(\"#content_profile_preview_container\").hide();\n $(\"#content_profile_contentauthoring_container\").show();\n } else {\n $(\"#content_profile_preview_container\").show();\n $(\"#content_profile_contentauthoring_container\").hide();\n }\n };\n\n // Initialise the content profile page\n init();\n\n };\n\n sakai.api.Widgets.Container.registerForLoad(\"content_profile\");\n});\n", "dev/javascript/createnew.js": "/*\n * Licensed to the Sakai Foundation (SF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The SF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations under the License.\n */\n\nrequire([\"jquery\",\"sakai/sakai.api.core\"], function($, sakai) {\n\n sakai_global.createnew = function() {\n\n var pubdata = {\n \"structure0\": {}\n };\n\n for (var i = 0; i < sakai.config.worldTemplates.length; i++){\n var category = sakai.config.worldTemplates[i];\n var rnd = sakai.api.Util.generateWidgetId();\n pubdata.structure0[category.id] = {\n \"_order\": i,\n \"_title\": sakai.api.i18n.getValueForKey(category.title),\n \"_ref\": rnd\n };\n pubdata[rnd] = {\n \"rows\": [{\n \"id\": sakai.api.Util.generateWidgetId(),\n \"columns\": [{\n \"width\": 1,\n \"elements\": [\n {\n \"id\": category.id,\n \"type\": \"selecttemplate\"\n }\n ]\n }]\n }]\n };\n }\n\n var generateNav = function(){\n $(window).trigger(\"lhnav.init\", [pubdata, {}, {}]);\n };\n\n var renderCreateGroup = function(){\n $(window).trigger(\"sakai.newcreategroup.init\");\n };\n\n $(window).bind(\"lhnav.ready\", function(){\n generateNav();\n });\n\n $(window).bind(\"newcreategroup.ready\", function(){\n renderCreateGroup();\n });\n\n generateNav();\n \n };\n\n sakai.api.Widgets.Container.registerForLoad(\"createnew\");\n});\n", "dev/javascript/search.js": "/*\n * Licensed to the Sakai Foundation (SF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The SF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations under the License.\n */\n\nrequire([\"jquery\",\"sakai/sakai.api.core\"], function($, sakai) {\n\n sakai_global.search = function() {\n var worldsOrderIncrement = 3;\n var searchButton = \"#form .s3d-search-button\";\n var searchInput = \"#form .s3d-search-inputfield\";\n var searchUrl = sakai.config.URL.SEARCH_URL;\n var pubdata = {\n \"structure0\": {\n \"all\": {\n \"_ref\": \"id9574379429432\",\n \"_order\": 0,\n \"_title\": sakai.api.i18n.getValueForKey(\"ALL_TYPES\"),\n \"_url\": searchUrl,\n \"main\": {\n \"_ref\": \"id9574379429432\",\n \"_order\": 0,\n \"_title\": sakai.api.i18n.getValueForKey(\"ALL_TYPES\"),\n \"_url\": searchUrl\n }\n },\n \"content\": {\n \"_ref\": \"id6573920372\",\n \"_order\": 1,\n \"_title\": sakai.api.i18n.getValueForKey(\"CONTENT\"),\n \"_url\": searchUrl,\n \"main\": {\n \"_ref\": \"id6573920372\",\n \"_order\": 0,\n \"_title\": sakai.api.i18n.getValueForKey(\"CONTENT\"),\n \"_url\": searchUrl\n }\n },\n \"people\": {\n \"_title\": sakai.api.i18n.getValueForKey(\"PEOPLE\"),\n \"_ref\": \"id49294509202\",\n \"_order\": 2,\n \"_url\": searchUrl,\n \"main\": {\n \"_ref\": \"id49294509202\",\n \"_order\": 0,\n \"_title\": sakai.api.i18n.getValueForKey(\"PEOPLE\"),\n \"_url\": searchUrl\n }\n }\n },\n \"id9574379429432\": {\n \"rows\": [\n {\n \"id\": \"id4382631\",\n \"columns\": [\n {\n \"width\": 1,\n \"elements\": [\n {\n \"id\": \"id8403845\",\n \"type\": \"searchall\"\n }\n ]\n }\n ]\n }\n ]\n },\n \"id6573920372\": {\n \"rows\": [\n {\n \"id\": \"id1813095\",\n \"columns\": [\n {\n \"width\": 1,\n \"elements\": [\n {\n \"id\": \"id9436392\",\n \"type\": \"searchcontent\"\n }\n ]\n }\n ]\n }\n ]\n },\n \"id49294509202\": {\n \"rows\": [\n {\n \"id\": \"id152530\",\n \"columns\": [\n {\n \"width\": 1,\n \"elements\": [\n {\n \"id\": \"id1187051\",\n \"type\": \"searchpeople\"\n }\n ]\n }\n ]\n }\n ]\n }\n };\n\n for (var c = 0; c < sakai.config.worldTemplates.length; c++) {\n var category = sakai.config.worldTemplates[c];\n var refId = sakai.api.Util.generateWidgetId();\n var title = sakai.api.i18n.getValueForKey(category.titlePlural);\n pubdata.structure0[category.id] = {\n \"_title\": title,\n \"_ref\": refId,\n \"_order\": (c + worldsOrderIncrement),\n \"_url\": searchUrl,\n \"main\": {\n \"_ref\": refId,\n \"_order\": 0,\n \"_title\": title,\n \"_url\": searchUrl\n }\n };\n var searchWidgetId = sakai.api.Util.generateWidgetId();\n pubdata[refId] = {\n \"rows\": [\n {\n \"id\": sakai.api.Util.generateWidgetId(),\n \"columns\": [\n {\n \"width\": 1,\n \"elements\": [\n {\n \"id\": searchWidgetId,\n \"type\": \"searchgroups\"\n }\n ]\n }\n ]\n }\n ]\n };\n pubdata[refId][searchWidgetId] = {\n \"category\": category.id\n };\n }\n\n var fireSearch = function(){\n $.bbq.pushState({\n \"q\": $(searchInput).val(),\n \"cat\": \"\",\n \"refine\": $.bbq.getState(\"refine\")\n }, 0);\n };\n\n ///////////////////\n // Event binding //\n ///////////////////\n\n var eventBinding = function(){\n $(searchInput).on(\"keydown\", function(ev){\n if (ev.keyCode === 13) {\n fireSearch();\n }\n });\n\n $(searchButton).on(\"click\", function(ev){\n fireSearch();\n });\n };\n\n var generateNav = function(){\n $(window).trigger(\"lhnav.init\", [pubdata, {}, {}]);\n };\n\n var renderEntity = function(){\n $(window).trigger(\"sakai.entity.init\", [\"search\"]);\n };\n\n $(window).bind(\"sakai.entity.ready\", function(){\n renderEntity();\n });\n\n $(window).bind(\"lhnav.ready\", function(){\n generateNav();\n });\n\n renderEntity();\n generateNav();\n eventBinding();\n\n };\n\n sakai.api.Widgets.Container.registerForLoad(\"search\");\n});\n", "dev/javascript/user.js": "/*\n * Licensed to the Sakai Foundation (SF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The SF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations under the License.\n */\n\nrequire([\"jquery\",\"sakai/sakai.api.core\"], function($, sakai) {\n\n sakai_global.profile = sakai_global.profile || {};\n sakai_global.profile.main = sakai_global.profile.main || {};\n $.extend(true, sakai_global.profile.main, {\n config: sakai.config.Profile.configuration.defaultConfig,\n data: {},\n mode: {\n options: [\"view\", \"edit\"],\n value: \"view\"\n }\n });\n\n sakai_global.user = function() {\n\n var privdata = false;\n var pubdata = false;\n var privurl = false;\n var puburl = false;\n var messageCounts = false;\n var isMe = false;\n var entityID = false;\n var isContact = false;\n\n var contextType = false;\n var contextData = false;\n\n var setupProfileSection = function( title, section ) {\n var ret = {\n _ref: sakai.api.Util.generateWidgetId(),\n _order: section.order,\n _altTitle: section.label,\n _title: section.label,\n _nonEditable: true,\n _view: section.permission\n };\n // _reorderOnly is only true for the basic profile\n ret._reorderOnly = title === \"basic\";\n return ret;\n };\n\n var setupProfile = function( structure, isMe ) {\n var firstWidgetRef = \"\";\n var profilestructure = {\n _title: structure.structure0.profile._title,\n _altTitle: structure.structure0.profile._altTitle,\n _order: structure.structure0.profile._order\n };\n if ( isMe ) {\n profilestructure[\"_canEdit\"] = true;\n profilestructure[\"_nonEditable\"] = true;\n profilestructure[\"_reorderOnly\"] = true;\n profilestructure[\"_canSubedit\"] = true;\n }\n var newProfile = true;\n $.each( structure.structure0.profile, function( key, section ) {\n if ( $.isPlainObject( section ) ) {\n newProfile = false;\n }\n });\n if ( newProfile ) {\n structure.structure0.profile = {};\n }\n var initialProfilePost = [];\n var paths = [];\n var permissions = [];\n var updateStructure = false;\n $.each(sakai.config.Profile.configuration.defaultConfig, function(title, section) {\n var widgetUUID = sakai.api.Util.generateWidgetId();\n if ( !newProfile && structure.structure0.profile.hasOwnProperty( title ) ) {\n profilestructure[ title ] = structure.structure0.profile[ title ];\n } else if ( newProfile || !structure.structure0.profile.hasOwnProperty( title )) {\n profilestructure[ title ] = setupProfileSection( title, section );\n if (title !== \"basic\"){\n paths.push(\"/~\" + sakai.data.me.user.userid + \"/public/authprofile/\" + title);\n permissions.push(section.permission);\n }\n if (section.order === 0) {\n firstWidgetRef = profilestructure[ title ]._ref;\n }\n initialProfilePost.push({\n \"url\": \"/~\" + sakai.data.me.user.userid + \"/public/authprofile/\" + title,\n \"method\": \"POST\",\n \"parameters\": {\n \"init\": true\n }\n });\n }\n // Don't need to use these from the profile, gives us more flexibility on the profile itself\n structure[profilestructure[ title ]._ref] = {\n rows: [\n {\n \"id\": sakai.api.Util.generateWidgetId(),\n \"columns\": [\n {\n \"width\": 1,\n \"elements\": [\n {\n \"id\": widgetUUID,\n \"type\": \"displayprofilesection\"\n }\n ]\n }\n ]\n }\n ]\n };\n structure[profilestructure[ title ]._ref][widgetUUID] = {\n sectionid: title\n };\n });\n\n // Eliminate extra sections in the profile that are hanging around\n $.each( structure.structure0.profile, function( section_title, section_data ) {\n if ( $.isPlainObject( section_data ) && !profilestructure.hasOwnProperty( section_title ) ) {\n initialProfilePost.push({\n \"url\": \"/~\" + sakai.data.me.user.userid + \"/public/authprofile/\" + section_title,\n \"method\": \"POST\",\n \"parameters\": {\n \":operation\": \"delete\"\n }\n });\n }\n });\n\n if ( isMe && initialProfilePost.length ) {\n updateStructure = true;\n sakai.api.Server.batch(initialProfilePost, function(success, data){\n if (success) {\n sakai.api.Content.setACLsOnPath(paths, permissions, sakai.data.me.user.userid, function(success){\n if (!success){\n debug.error(\"Error setting initial profile ACLs\");\n }\n });\n } else {\n debug.error(\"Error saving initial profile fields\");\n }\n });\n }\n\n structure.structure0.profile = profilestructure;\n structure.structure0.profile._ref = firstWidgetRef;\n return updateStructure;\n };\n\n var continueLoadSpaceData = function(userid){\n var publicToStore = false; var requiresPublicMigration = false;\n var privateToStore = false; var requirePrivateMigration = false;\n\n // Load public data from /~userid/private/pubspace\n sakai.api.Server.loadJSON(puburl, function(success, data){\n if (!success){\n pubdata = $.extend(true, {}, sakai.config.defaultpubstructure);\n var refid = {\"refid\": sakai.api.Util.generateWidgetId()};\n pubdata = sakai.api.Util.replaceTemplateParameters(refid, pubdata);\n } else {\n pubdata = data;\n pubdata = sakai.api.Content.Migrators.migratePageStructure(sakai.api.Server.cleanUpSakaiDocObject(pubdata), isMe ? puburl : false);\n }\n if (!isMe){\n pubdata.structure0 = setManagerProperty(pubdata.structure0, false);\n for (var i in pubdata.structure0) {\n if (pubdata.structure0.hasOwnProperty(i)){\n pubdata.structure0[i] = determineUserAreaPermissions(pubdata.structure0[i]);\n }\n }\n }\n if ( pubdata.structure0.profile && setupProfile( pubdata, isMe ) ) {\n publicToStore = $.extend(true, {}, pubdata);\n }\n if (isMe){\n sakai.api.Server.loadJSON(privurl, function(success2, data2){\n if (!success2){\n privdata = $.extend(true, {}, sakai.config.defaultprivstructure);\n var refid = {\"refid\": sakai.api.Util.generateWidgetId()};\n privdata = sakai.api.Util.replaceTemplateParameters(refid, privdata);\n privateToStore = $.extend(true, {}, privdata);\n } else {\n privdata = data2;\n privdata = sakai.api.Content.Migrators.migratePageStructure(sakai.api.Server.cleanUpSakaiDocObject(privdata), privurl);\n }\n if (publicToStore) {\n if ($.isPlainObject(publicToStore.structure0)) {\n publicToStore.structure0 = $.toJSON(publicToStore.structure0);\n }\n sakai.api.Server.saveJSON(puburl, publicToStore);\n }\n if (privateToStore) {\n if ($.isPlainObject(privateToStore.structure0)) {\n privateToStore.structure0 = $.toJSON(privateToStore.structure0);\n }\n sakai.api.Server.saveJSON(privurl, privateToStore);\n }\n pubdata.structure0 = setManagerProperty(pubdata.structure0, true);\n generateNav();\n });\n } else {\n generateNav();\n }\n });\n };\n\n var loadSpaceData = function(){\n var userid;\n if (!entityID || entityID == sakai.data.me.user.userid) {\n isMe = true;\n userid = sakai.data.me.user.userid;\n } else {\n userid = entityID;\n }\n privurl = \"/~\" + sakai.api.Util.safeURL(userid) + \"/private/privspace\";\n puburl = \"/~\" + sakai.api.Util.safeURL(userid) + \"/public/pubspace\";\n if (isMe){\n sakai.api.Communication.getUnreadMessagesCountOverview(\"inbox\", function(success, counts){\n messageCounts = counts;\n continueLoadSpaceData(userid);\n });\n } else {\n continueLoadSpaceData(userid);\n }\n\n };\n\n var addCounts = function(){\n if (pubdata && pubdata.structure0) {\n if (contextData && contextData.profile && contextData.profile.counts) {\n addCount(pubdata, \"library\", contextData.profile.counts[\"contentCount\"]);\n addCount(pubdata, \"memberships\", contextData.profile.counts[\"membershipsCount\"]);\n if (isMe) {\n var contactCount = 0;\n // determine the count of contacts to list in lhnav\n if (sakai.data.me.contacts.ACCEPTED && sakai.data.me.contacts.INVITED){\n contactCount = sakai.data.me.contacts.ACCEPTED + sakai.data.me.contacts.INVITED;\n } else if (sakai.data.me.contacts.ACCEPTED){\n contactCount = sakai.data.me.contacts.ACCEPTED;\n } else if (sakai.data.me.contacts.INVITED){\n contactCount = sakai.data.me.contacts.INVITED;\n }\n addCount(pubdata, \"contacts\", contactCount);\n addCount(privdata, \"messages\", sakai.data.me.messages.unread);\n if (messageCounts && messageCounts.count && messageCounts.count.length) {\n for (var i = 0; i < messageCounts.count.length; i++) {\n if (messageCounts.count[i].group && messageCounts.count[i].group === \"message\") {\n addCount(privdata, \"messages/inbox\", messageCounts.count[i].count);\n }\n if (messageCounts.count[i].group && messageCounts.count[i].group === \"invitation\") {\n addCount(privdata, \"messages/invitations\", messageCounts.count[i].count);\n }\n }\n }\n } else {\n addCount(pubdata, \"contacts\", contextData.profile.counts[\"contactsCount\"]);\n }\n }\n }\n };\n\n var determineUserAreaPermissions = function(structure){\n var permission = structure._view || \"anonymous\";\n if (permission === \"contacts\" && isContact) {\n structure._canView = true;\n } else if (permission === \"everyone\" && !sakai.data.me.user.anon) {\n structure._canView = true;\n } else if (permission === \"anonymous\") {\n structure._canView = true;\n } else {\n structure._canView = false;\n }\n for (var i in structure) {\n if (structure.hasOwnProperty(i) && i.substring(0, 1) !== \"_\") {\n structure[i] = determineUserAreaPermissions(structure[i]);\n }\n }\n return structure;\n };\n\n var setManagerProperty = function(structure, value){\n for (var i in structure){\n if (structure.hasOwnProperty(i) && i.substring(0, 1) !== \"_\" && typeof structure[i] === \"object\") {\n structure[i]._canEdit = value;\n structure[i]._canSubedit = value;\n structure[i] = setManagerProperty(structure[i], value);\n }\n }\n return structure;\n };\n\n var addCount = function(pubdata, pageid, count){\n if (pageid.indexOf(\"/\") !== -1) {\n var split = pageid.split(\"/\");\n if (pubdata.structure0 && pubdata.structure0[split[0]] && pubdata.structure0[split[0]][split[1]]) {\n pubdata.structure0[split[0]][split[1]]._count = count;\n }\n } else {\n if (pubdata.structure0 && pubdata.structure0[pageid]) {\n pubdata.structure0[pageid]._count = count;\n }\n }\n };\n\n var getUserPicture = function(profile, userid){\n var picture = \"\";\n if (profile.picture) {\n var picture_name = $.parseJSON(profile.picture).name;\n picture = \"/~\" + sakai.api.Util.safeURL(userid) + \"/public/profile/\" + picture_name;\n }\n return picture;\n };\n\n var determineContext = function(){\n entityID = sakai.api.Util.extractEntity(window.location.pathname);\n if (entityID && entityID !== sakai.data.me.user.userid){\n sakai.api.User.getUser(entityID, getProfileData);\n } else if (!sakai.data.me.user.anon){\n if (entityID){\n document.location = \"/me\" + window.location.hash;\n return;\n }\n sakai.api.Security.showPage();\n contextType = \"user_me\";\n // Set the profile data object\n sakai_global.profile.main.data = $.extend(true, {}, sakai.data.me.profile);\n sakai_global.profile.main.mode.value = \"edit\";\n contextData = {\n \"profile\": sakai.data.me.profile,\n \"displayName\": sakai.api.User.getDisplayName(sakai.data.me.profile),\n \"userid\": sakai.data.me.user.userid,\n \"picture\": getUserPicture(sakai.data.me.profile, sakai.data.me.user.userid),\n \"addArea\": \"user\"\n };\n document.title = document.title + \" \" + sakai.api.Util.Security.unescapeHTML(contextData.displayName);\n renderEntity();\n loadSpaceData();\n } else {\n sakai.api.Security.sendToLogin();\n }\n };\n\n var getProfileData = function(exists, profile){\n if (!profile) {\n sakai.api.Security.sendToLogin();\n } else {\n sakai.api.Security.showPage();\n // Set the profile data object\n sakai_global.profile.main.data = $.extend(true, {}, profile);\n contextData = {\n \"profile\": profile,\n \"displayName\": sakai.api.User.getDisplayName(profile),\n \"userid\": entityID,\n \"altTitle\": true,\n \"picture\": getUserPicture(profile, entityID)\n };\n document.title = document.title + \" \" + sakai.api.Util.Security.unescapeHTML(contextData.displayName);\n if (sakai.data.me.user.anon) {\n contextType = \"user_anon\";\n renderEntity();\n loadSpaceData();\n } else {\n sakai.api.User.getContacts(checkContact);\n }\n }\n };\n\n var checkContact = function(){\n var contacts = sakai.data.me.mycontacts;\n var isContactInvited = false;\n var isContactPending = false;\n for (var i = 0; i < contacts.length; i++){\n if (contacts[i].profile.userid === entityID){\n if (contacts[i].details[\"sakai:state\"] === \"ACCEPTED\") {\n isContact = true;\n } else if (contacts[i].details[\"sakai:state\"] === \"INVITED\"){\n isContactInvited = true;\n } else if (contacts[i].details[\"sakai:state\"] === \"PENDING\"){\n isContactPending = true;\n }\n }\n }\n if (isContact){\n contextType = \"contact\";\n } else if (isContactInvited){\n contextType = \"contact_invited\";\n } else if (isContactPending){\n contextType = \"contact_pending\";\n } else {\n contextType = \"user_other\";\n }\n renderEntity();\n loadSpaceData();\n };\n\n var generateNav = function(){\n addCounts();\n sakai_global.user.pubdata = pubdata;\n if (contextType && contextType === \"user_me\" && contextData && pubdata && privdata) {\n $(window).trigger(\"lhnav.init\", [pubdata, privdata, contextData, puburl, privurl]);\n } else if (contextType && contextType !== \"user_me\" && contextData && pubdata) {\n $(window).trigger(\"lhnav.init\", [pubdata, false, contextData, puburl, privurl]);\n }\n };\n\n var renderEntity = function(){\n if (contextType && contextData) {\n $(window).trigger(\"sakai.entity.init\", [\"user\", contextType, contextData]);\n }\n };\n\n var showWelcomeNotification = function(){\n var querystring = new Querystring();\n if (querystring.contains(\"welcome\") && querystring.get(\"welcome\") === \"true\" && !sakai.data.me.user.anon){\n sakai.api.Util.notification.show(sakai.api.i18n.getValueForKey(\"WELCOME\") + \" \" + sakai.data.me.profile.basic.elements.firstName.value,sakai.api.i18n.getValueForKey(\"YOU_HAVE_CREATED_AN_ACCOUNT\"));\n }\n };\n\n $(window).bind(\"sakai.addToContacts.requested\", function(ev, userToAdd){\n $('.sakai_addtocontacts_overlay').each(function(index) {\n if (entityID && entityID !== sakai.data.me.user.userid){\n contextType = \"contact_pending\";\n renderEntity();\n }\n });\n });\n\n $(\"#entity_user_accept_invitation\").live(\"click\", function(){\n sakai.api.User.acceptContactInvite(contextData.userid);\n contextType = \"contact\";\n renderEntity();\n });\n\n $(window).bind(\"sakai.entity.ready\", function(){\n renderEntity();\n });\n\n $(window).bind(\"lhnav.ready\", function(){\n generateNav();\n });\n\n $(window).bind(\"updated.counts.lhnav.sakai\", function(){\n sakai.api.User.getUpdatedCounts(sakai.data.me, function(success){\n renderEntity();\n generateNav();\n });\n });\n\n $(window).bind(\"done.newaddcontent.sakai\", function(e, data, library) {\n if (isMe && data && data.length && library === sakai.data.me.user.userid) {\n $(window).trigger(\"lhnav.updateCount\", [\"library\", data.length]);\n }\n });\n\n $(window).bind(\"updated.messageCount.sakai\", function(){\n if (isMe){\n sakai.api.Communication.getUnreadMessagesCountOverview(\"inbox\", function(success, counts){\n messageCounts = counts;\n var totalCount = 0;\n // The structure of these objects make for O(n^2) comparison :(\n $.each(messageCounts.count, function(index, countObj){\n var pageid = \"messages/\";\n if (countObj.group === \"message\"){\n pageid += \"inbox\";\n } else if (countObj.group === \"invitation\"){\n pageid += \"invitations\";\n }\n totalCount += countObj.count;\n $(window).trigger(\"lhnav.updateCount\", [pageid, countObj.count, false]);\n });\n $(window).trigger(\"lhnav.updateCount\", [\"messages\", totalCount, false]);\n }, false);\n }\n });\n\n determineContext();\n renderEntity();\n generateNav();\n showWelcomeNotification();\n\n };\n\n sakai.api.Widgets.Container.registerForLoad(\"user\");\n});\n", "dev/layout1.html": "\n\n\n \n\n \n \n \n\n \n \n\n \n \n\n \n \n \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n \n
            \n
            \n
            \n\n \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n\n \n
            \n\n\n \n \n \n \n\n", "dev/layout2.html": "\n\n\n \n\n \n \n \n\n \n \n\n \n \n\n \n \n \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n\n \n
            \n
            \n
            \n
            \n \n
            \n
            \n
            \n\n \n
            \n\n\n \n \n\n \n\n", "dev/lib/__tinymce/classes/AddOnManager.js": "/**\n * AddOnManager.js\n *\n * Copyright 2009, Moxiecode Systems AB\n * Released under LGPL License.\n *\n * License: http://tinymce.moxiecode.com/license\n * Contributing: http://tinymce.moxiecode.com/contributing\n */\n\n(function(tinymce) {\n\tvar Dispatcher = tinymce.util.Dispatcher, each = tinymce.each;\n\n\t/**\n\t * This class handles the loading of themes/plugins or other add-ons and their language packs.\n\t *\n\t * @class tinymce.AddOnManager\n\t */\n\ttinymce.create('tinymce.AddOnManager', {\n\t\tAddOnManager : function() {\n\t\t\tvar self = this;\n\n\t\t\tself.items = [];\n\t\t\tself.urls = {};\n\t\t\tself.lookup = {};\n\t\t\tself.onAdd = new Dispatcher(self);\n\t\t},\n\n\t\t/**\n\t\t * Fires when a item is added.\n\t\t *\n\t\t * @event onAdd\n\t\t */\n\n\t\t/**\n\t\t * Returns the specified add on by the short name.\n\t\t *\n\t\t * @method get\n\t\t * @param {String} n Add-on to look for.\n\t\t * @return {tinymce.Theme/tinymce.Plugin} Theme or plugin add-on instance or undefined.\n\t\t */\n\t\tget : function(n) {\n\t\t\tif (this.lookup[n]) {\n\t\t\t\treturn this.lookup[n].instance;\n\t\t\t} else {\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t},\n\n\t\tdependencies : function(n) {\n\t\t\tvar result;\n\t\t\tif (this.lookup[n]) {\n\t\t\t\tresult = this.lookup[n].dependencies;\n\t\t\t}\n\t\t\treturn result || [];\n\t\t},\n\n\t\t/**\n\t\t * Loads a language pack for the specified add-on.\n\t\t *\n\t\t * @method requireLangPack\n\t\t * @param {String} n Short name of the add-on.\n\t\t */\n\t\trequireLangPack : function(n) {\n\t\t\tvar s = tinymce.settings;\n\n\t\t\tif (s && s.language && s.language_load !== false)\n\t\t\t\ttinymce.ScriptLoader.add(this.urls[n] + '/langs/' + s.language + '.js');\n\t\t},\n\n\t\t/**\n\t\t * Adds a instance of the add-on by it's short name.\n\t\t *\n\t\t * @method add\n\t\t * @param {String} id Short name/id for the add-on.\n\t\t * @param {tinymce.Theme/tinymce.Plugin} o Theme or plugin to add.\n\t\t * @return {tinymce.Theme/tinymce.Plugin} The same theme or plugin instance that got passed in.\n\t\t * @example\n\t\t * // Create a simple plugin\n\t\t * tinymce.create('tinymce.plugins.TestPlugin', {\n\t\t * TestPlugin : function(ed, url) {\n\t\t * ed.onClick.add(function(ed, e) {\n\t\t * ed.windowManager.alert('Hello World!');\n\t\t * });\n\t\t * }\n\t\t * });\n\t\t * \n\t\t * // Register plugin using the add method\n\t\t * tinymce.PluginManager.add('test', tinymce.plugins.TestPlugin);\n\t\t * \n\t\t * // Initialize TinyMCE\n\t\t * tinyMCE.init({\n\t\t * ...\n\t\t * plugins : '-test' // Init the plugin but don't try to load it\n\t\t * });\n\t\t */\n\t\tadd : function(id, o, dependencies) {\n\t\t\tthis.items.push(o);\n\t\t\tthis.lookup[id] = {instance:o, dependencies:dependencies};\n\t\t\tthis.onAdd.dispatch(this, id, o);\n\n\t\t\treturn o;\n\t\t},\n\t\tcreateUrl: function(baseUrl, dep) {\n\t\t\tif (typeof dep === \"object\") {\n\t\t\t\treturn dep\n\t\t\t} else {\n\t\t\t\treturn {prefix: baseUrl.prefix, resource: dep, suffix: baseUrl.suffix};\n\t\t\t}\n\t\t},\n\n\t\t/**\n\t \t * Add a set of components that will make up the add-on. Using the url of the add-on name as the base url.\n\t\t * This should be used in development mode. A new compressor/javascript munger process will ensure that the \n\t\t * components are put together into the editor_plugin.js file and compressed correctly.\n\t\t * @param pluginName {String} name of the plugin to load scripts from (will be used to get the base url for the plugins).\n\t\t * @param scripts {Array} Array containing the names of the scripts to load.\n\t \t */\n\t\taddComponents: function(pluginName, scripts) {\n\t\t\tvar pluginUrl = this.urls[pluginName];\n\t\t\ttinymce.each(scripts, function(script){\n\t\t\t\ttinymce.ScriptLoader.add(pluginUrl+\"/\"+script);\t\n\t\t\t});\n\t\t},\n\n\t\t/**\n\t\t * Loads an add-on from a specific url.\n\t\t *\n\t\t * @method load\n\t\t * @param {String} n Short name of the add-on that gets loaded.\n\t\t * @param {String} u URL to the add-on that will get loaded.\n\t\t * @param {function} cb Optional callback to execute ones the add-on is loaded.\n\t\t * @param {Object} s Optional scope to execute the callback in.\n\t\t * @example\n\t\t * // Loads a plugin from an external URL\n\t\t * tinymce.PluginManager.load('myplugin', '/some/dir/someplugin/editor_plugin.js');\n\t\t *\n\t\t * // Initialize TinyMCE\n\t\t * tinyMCE.init({\n\t\t * ...\n\t\t * plugins : '-myplugin' // Don't try to load it again\n\t\t * });\n\t\t */\n\t\tload : function(n, u, cb, s) {\n\t\t\tvar t = this, url = u;\n\n\t\t\tfunction loadDependencies() {\n\t\t\t\tvar dependencies = t.dependencies(n);\n\t\t\t\ttinymce.each(dependencies, function(dep) {\n\t\t\t\t\tvar newUrl = t.createUrl(u, dep);\n\t\t\t\t\tt.load(newUrl.resource, newUrl, undefined, undefined);\n\t\t\t\t});\n\t\t\t\tif (cb) {\n\t\t\t\t\tif (s) {\n\t\t\t\t\t\tcb.call(s);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcb.call(tinymce.ScriptLoader);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (t.urls[n])\n\t\t\t\treturn;\n\t\t\tif (typeof u === \"object\")\n\t\t\t\turl = u.prefix + u.resource + u.suffix;\n\n\t\t\tif (url.indexOf('/') != 0 && url.indexOf('://') == -1)\n\t\t\t\turl = tinymce.baseURL + '/' + url;\n\n\t\t\tt.urls[n] = url.substring(0, url.lastIndexOf('/'));\n\n\t\t\tif (t.lookup[n]) {\n\t\t\t\tloadDependencies();\n\t\t\t} else {\n\t\t\t\ttinymce.ScriptLoader.add(url, loadDependencies, s);\n\t\t\t}\n\t\t}\n\t});\n\n\t// Create plugin and theme managers\n\ttinymce.PluginManager = new tinymce.AddOnManager();\n\ttinymce.ThemeManager = new tinymce.AddOnManager();\n}(tinymce));\n\n/**\n * TinyMCE theme class.\n *\n * @class tinymce.Theme\n */\n\n/**\n * Initializes the theme.\n *\n * @method init\n * @param {tinymce.Editor} editor Editor instance that created the theme instance.\n * @param {String} url Absolute URL where the theme is located. \n */\n\n/**\n * Meta info method, this method gets executed when TinyMCE wants to present information about the theme for example in the about/help dialog.\n *\n * @method getInfo\n * @return {Object} Returns an object with meta information about the theme the current items are longname, author, authorurl, infourl and version.\n */\n\n/**\n * This method is responsible for rendering/generating the overall user interface with toolbars, buttons, iframe containers etc.\n *\n * @method renderUI\n * @param {Object} obj Object parameter containing the targetNode DOM node that will be replaced visually with an editor instance. \n * @return {Object} an object with items like iframeContainer, editorContainer, sizeContainer, deltaWidth, deltaHeight. \n */\n\n/**\n * Plugin base class, this is a pseudo class that describes how a plugin is to be created for TinyMCE. The methods below are all optional.\n *\n * @class tinymce.Plugin\n * @example\n * // Create a new plugin class\n * tinymce.create('tinymce.plugins.ExamplePlugin', {\n * init : function(ed, url) {\n * // Register an example button\n * ed.addButton('example', {\n * title : 'example.desc',\n * onclick : function() {\n * // Display an alert when the user clicks the button\n * ed.windowManager.alert('Hello world!');\n * },\n * 'class' : 'bold' // Use the bold icon from the theme\n * });\n * }\n * });\n * \n * // Register plugin with a short name\n * tinymce.PluginManager.add('example', tinymce.plugins.ExamplePlugin);\n * \n * // Initialize TinyMCE with the new plugin and button\n * tinyMCE.init({\n * ...\n * plugins : '-example', // - means TinyMCE will not try to load it\n * theme_advanced_buttons1 : 'example' // Add the new example button to the toolbar\n * });\n */\n\n/**\n * Initialization function for the plugin. This will be called when the plugin is created. \n *\n * @method init\n * @param {tinymce.Editor} editor Editor instance that created the plugin instance. \n * @param {String} url Absolute URL where the plugin is located. \n * @example\n * // Creates a new plugin class\n * tinymce.create('tinymce.plugins.ExamplePlugin', {\n * init : function(ed, url) {\n * // Register the command so that it can be invoked by using tinyMCE.activeEditor.execCommand('mceExample');\n * ed.addCommand('mceExample', function() {\n * ed.windowManager.open({\n * file : url + '/dialog.htm',\n * width : 320 + ed.getLang('example.delta_width', 0),\n * height : 120 + ed.getLang('example.delta_height', 0),\n * inline : 1\n * }, {\n * plugin_url : url, // Plugin absolute URL\n * some_custom_arg : 'custom arg' // Custom argument\n * });\n * });\n * \n * // Register example button\n * ed.addButton('example', {\n * title : 'example.desc',\n * cmd : 'mceExample',\n * image : url + '/img/example.gif'\n * });\n * \n * // Add a node change handler, selects the button in the UI when a image is selected\n * ed.onNodeChange.add(function(ed, cm, n) {\n * cm.setActive('example', n.nodeName == 'IMG');\n * });\n * }\n * });\n * \n * // Register plugin\n * tinymce.PluginManager.add('example', tinymce.plugins.ExamplePlugin);\n */\n\n/**\n * Meta info method, this method gets executed when TinyMCE wants to present information about the plugin for example in the about/help dialog.\n *\n * @method getInfo\n * @return {Object} Returns an object with meta information about the plugin the current items are longname, author, authorurl, infourl and version.\n * @example \n * // Creates a new plugin class\n * tinymce.create('tinymce.plugins.ExamplePlugin', {\n * // Meta info method\n * getInfo : function() {\n * return {\n * longname : 'Example plugin',\n * author : 'Some author',\n * authorurl : 'http://tinymce.moxiecode.com',\n * infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/example',\n * version : \"1.0\"\n * };\n * }\n * });\n * \n * // Register plugin\n * tinymce.PluginManager.add('example', tinymce.plugins.ExamplePlugin);\n * \n * // Initialize TinyMCE with the new plugin\n * tinyMCE.init({\n * ...\n * plugins : '-example' // - means TinyMCE will not try to load it\n * });\n */\n\n/**\n * Gets called when a new control instance is created.\n *\n * @method createControl\n * @param {String} name Control name to create for example \"mylistbox\" \n * @param {tinymce.ControlManager} controlman Control manager/factory to use to create the control. \n * @return {tinymce.ui.Control} Returns a new control instance or null.\n * @example \n * // Creates a new plugin class\n * tinymce.create('tinymce.plugins.ExamplePlugin', {\n * createControl: function(n, cm) {\n * switch (n) {\n * case 'mylistbox':\n * var mlb = cm.createListBox('mylistbox', {\n * title : 'My list box',\n * onselect : function(v) {\n * tinyMCE.activeEditor.windowManager.alert('Value selected:' + v);\n * }\n * });\n * \n * // Add some values to the list box\n * mlb.add('Some item 1', 'val1');\n * mlb.add('some item 2', 'val2');\n * mlb.add('some item 3', 'val3');\n * \n * // Return the new listbox instance\n * return mlb;\n * }\n * \n * return null;\n * }\n * });\n * \n * // Register plugin\n * tinymce.PluginManager.add('example', tinymce.plugins.ExamplePlugin);\n * \n * // Initialize TinyMCE with the new plugin and button\n * tinyMCE.init({\n * ...\n * plugins : '-example', // - means TinyMCE will not try to load it\n * theme_advanced_buttons1 : 'mylistbox' // Add the new mylistbox control to the toolbar\n * });\n */\n", "dev/lib/__tinymce/classes/ControlManager.js": "/**\r\n * ControlManager.js\r\n *\r\n * Copyright 2009, Moxiecode Systems AB\r\n * Released under LGPL License.\r\n *\r\n * License: http://tinymce.moxiecode.com/license\r\n * Contributing: http://tinymce.moxiecode.com/contributing\r\n */\r\n\r\n(function(tinymce) {\r\n\t// Shorten names\r\n\tvar DOM = tinymce.DOM, Event = tinymce.dom.Event, each = tinymce.each, extend = tinymce.extend;\r\n\r\n\t/**\r\n\t * This class is responsible for managing UI control instances. It's both a factory and a collection for the controls.\r\n\t * @class tinymce.ControlManager\r\n\t */\r\n\ttinymce.create('tinymce.ControlManager', {\r\n\t\t/**\r\n\t\t * Constructs a new control manager instance.\r\n\t\t * Consult the Wiki for more details on this class.\r\n\t\t *\r\n\t\t * @constructor\r\n\t\t * @method ControlManager\r\n\t\t * @param {tinymce.Editor} ed TinyMCE editor instance to add the control to.\r\n\t\t * @param {Object} s Optional settings object for the control manager.\r\n\t\t */\r\n\t\tControlManager : function(ed, s) {\r\n\t\t\tvar t = this, i;\r\n\r\n\t\t\ts = s || {};\r\n\t\t\tt.editor = ed;\r\n\t\t\tt.controls = {};\r\n\t\t\tt.onAdd = new tinymce.util.Dispatcher(t);\r\n\t\t\tt.onPostRender = new tinymce.util.Dispatcher(t);\r\n\t\t\tt.prefix = s.prefix || ed.id + '_';\r\n\t\t\tt._cls = {};\r\n\r\n\t\t\tt.onPostRender.add(function() {\r\n\t\t\t\teach(t.controls, function(c) {\r\n\t\t\t\t\tc.postRender();\r\n\t\t\t\t});\r\n\t\t\t});\r\n\t\t},\r\n\r\n\t\t/**\r\n\t\t * Returns a control by id or undefined it it wasn't found.\r\n\t\t *\r\n\t\t * @method get\r\n\t\t * @param {String} id Control instance name.\r\n\t\t * @return {tinymce.ui.Control} Control instance or undefined.\r\n\t\t */\r\n\t\tget : function(id) {\r\n\t\t\treturn this.controls[this.prefix + id] || this.controls[id];\r\n\t\t},\r\n\r\n\t\t/**\r\n\t\t * Sets the active state of a control by id.\r\n\t\t *\r\n\t\t * @method setActive\r\n\t\t * @param {String} id Control id to set state on.\r\n\t\t * @param {Boolean} s Active state true/false.\r\n\t\t * @return {tinymce.ui.Control} Control instance that got activated or null if it wasn't found.\r\n\t\t */\r\n\t\tsetActive : function(id, s) {\r\n\t\t\tvar c = null;\r\n\r\n\t\t\tif (c = this.get(id))\r\n\t\t\t\tc.setActive(s);\r\n\r\n\t\t\treturn c;\r\n\t\t},\r\n\r\n\t\t/**\r\n\t\t * Sets the dsiabled state of a control by id.\r\n\t\t *\r\n\t\t * @method setDisabled\r\n\t\t * @param {String} id Control id to set state on.\r\n\t\t * @param {Boolean} s Active state true/false.\r\n\t\t * @return {tinymce.ui.Control} Control instance that got disabled or null if it wasn't found.\r\n\t\t */\r\n\t\tsetDisabled : function(id, s) {\r\n\t\t\tvar c = null;\r\n\r\n\t\t\tif (c = this.get(id))\r\n\t\t\t\tc.setDisabled(s);\r\n\r\n\t\t\treturn c;\r\n\t\t},\r\n\r\n\t\t/**\r\n\t\t * Adds a control to the control collection inside the manager.\r\n\t\t *\r\n\t\t * @method add\r\n\t\t * @param {tinymce.ui.Control} Control instance to add to collection.\r\n\t\t * @return {tinymce.ui.Control} Control instance that got passed in.\r\n\t\t */\r\n\t\tadd : function(c) {\r\n\t\t\tvar t = this;\r\n\r\n\t\t\tif (c) {\r\n\t\t\t\tt.controls[c.id] = c;\r\n\t\t\t\tt.onAdd.dispatch(c, t);\r\n\t\t\t}\r\n\r\n\t\t\treturn c;\r\n\t\t},\r\n\r\n\t\t/**\r\n\t\t * Creates a control by name, when a control is created it will automatically add it to the control collection.\r\n\t\t * It first ask all plugins for the specified control if the plugins didn't return a control then the default behavior\r\n\t\t * will be used.\r\n\t\t *\r\n\t\t * @method createControl\r\n\t\t * @param {String} n Control name to create for example \"separator\".\r\n\t\t * @return {tinymce.ui.Control} Control instance that got created and added.\r\n\t\t */\r\n\t\tcreateControl : function(n) {\r\n\t\t\tvar c, t = this, ed = t.editor;\r\n\r\n\t\t\teach(ed.plugins, function(p) {\r\n\t\t\t\tif (p.createControl) {\r\n\t\t\t\t\tc = p.createControl(n, t);\r\n\r\n\t\t\t\t\tif (c)\r\n\t\t\t\t\t\treturn false;\r\n\t\t\t\t}\r\n\t\t\t});\r\n\r\n\t\t\tswitch (n) {\r\n\t\t\t\tcase \"|\":\r\n\t\t\t\tcase \"separator\":\r\n\t\t\t\t\treturn t.createSeparator();\r\n\t\t\t}\r\n\r\n\t\t\tif (!c && ed.buttons && (c = ed.buttons[n]))\r\n\t\t\t\treturn t.createButton(n, c);\r\n\r\n\t\t\treturn t.add(c);\r\n\t\t},\r\n\r\n\t\t/**\r\n\t\t * Creates a drop menu control instance by id.\r\n\t\t *\r\n\t\t * @method createDropMenu\r\n\t\t * @param {String} id Unique id for the new dropdown instance. For example \"some menu\".\r\n\t\t * @param {Object} s Optional settings object for the control.\r\n\t\t * @param {Object} cc Optional control class to use instead of the default one.\r\n\t\t * @return {tinymce.ui.Control} Control instance that got created and added.\r\n\t\t */\r\n\t\tcreateDropMenu : function(id, s, cc) {\r\n\t\t\tvar t = this, ed = t.editor, c, bm, v, cls;\r\n\r\n\t\t\ts = extend({\r\n\t\t\t\t'class' : 'mceDropDown',\r\n\t\t\t\tconstrain : ed.settings.constrain_menus\r\n\t\t\t}, s);\r\n\r\n\t\t\ts['class'] = s['class'] + ' ' + ed.getParam('skin') + 'Skin';\r\n\t\t\tif (v = ed.getParam('skin_variant'))\r\n\t\t\t\ts['class'] += ' ' + ed.getParam('skin') + 'Skin' + v.substring(0, 1).toUpperCase() + v.substring(1);\r\n\r\n\t\t\tid = t.prefix + id;\r\n\t\t\tcls = cc || t._cls.dropmenu || tinymce.ui.DropMenu;\r\n\t\t\tc = t.controls[id] = new cls(id, s);\r\n\t\t\tc.onAddItem.add(function(c, o) {\r\n\t\t\t\tvar s = o.settings;\r\n\r\n\t\t\t\ts.title = ed.getLang(s.title, s.title);\r\n\r\n\t\t\t\tif (!s.onclick) {\r\n\t\t\t\t\ts.onclick = function(v) {\r\n\t\t\t\t\t\tif (s.cmd)\r\n\t\t\t\t\t\t\ted.execCommand(s.cmd, s.ui || false, s.value);\r\n\t\t\t\t\t};\r\n\t\t\t\t}\r\n\t\t\t});\r\n\r\n\t\t\ted.onRemove.add(function() {\r\n\t\t\t\tc.destroy();\r\n\t\t\t});\r\n\r\n\t\t\t// Fix for bug #1897785, #1898007\r\n\t\t\tif (tinymce.isIE) {\r\n\t\t\t\tc.onShowMenu.add(function() {\r\n\t\t\t\t\t// IE 8 needs focus in order to store away a range with the current collapsed caret location\r\n\t\t\t\t\ted.focus();\r\n\r\n\t\t\t\t\tbm = ed.selection.getBookmark(1);\r\n\t\t\t\t});\r\n\r\n\t\t\t\tc.onHideMenu.add(function() {\r\n\t\t\t\t\tif (bm) {\r\n\t\t\t\t\t\ted.selection.moveToBookmark(bm);\r\n\t\t\t\t\t\tbm = 0;\r\n\t\t\t\t\t}\r\n\t\t\t\t});\r\n\t\t\t}\r\n\r\n\t\t\treturn t.add(c);\r\n\t\t},\r\n\r\n\t\t/**\r\n\t\t * Creates a list box control instance by id. A list box is either a native select element or a DOM/JS based list box control. This\r\n\t\t * depends on the use_native_selects settings state.\r\n\t\t *\r\n\t\t * @method createListBox\r\n\t\t * @param {String} id Unique id for the new listbox instance. For example \"styles\".\r\n\t\t * @param {Object} s Optional settings object for the control.\r\n\t\t * @param {Object} cc Optional control class to use instead of the default one.\r\n\t\t * @return {tinymce.ui.Control} Control instance that got created and added.\r\n\t\t */\r\n\t\tcreateListBox : function(id, s, cc) {\r\n\t\t\tvar t = this, ed = t.editor, cmd, c, cls;\r\n\r\n\t\t\tif (t.get(id))\r\n\t\t\t\treturn null;\r\n\r\n\t\t\ts.title = ed.translate(s.title);\r\n\t\t\ts.scope = s.scope || ed;\r\n\r\n\t\t\tif (!s.onselect) {\r\n\t\t\t\ts.onselect = function(v) {\r\n\t\t\t\t\ted.execCommand(s.cmd, s.ui || false, v || s.value);\r\n\t\t\t\t};\r\n\t\t\t}\r\n\r\n\t\t\ts = extend({\r\n\t\t\t\ttitle : s.title,\r\n\t\t\t\t'class' : 'mce_' + id,\r\n\t\t\t\tscope : s.scope,\r\n\t\t\t\tcontrol_manager : t\r\n\t\t\t}, s);\r\n\r\n\t\t\tid = t.prefix + id;\r\n\r\n\r\n\t\t\tfunction useNativeListForAccessibility(ed) {\r\n\t\t\t\treturn ed.settings.use_accessible_selects && !tinymce.isGecko\r\n\t\t\t}\r\n\r\n\t\t\tif (ed.settings.use_native_selects || useNativeListForAccessibility(ed))\r\n\t\t\t\tc = new tinymce.ui.NativeListBox(id, s);\r\n\t\t\telse {\r\n\t\t\t\tcls = cc || t._cls.listbox || tinymce.ui.ListBox;\r\n\t\t\t\tc = new cls(id, s, ed);\r\n\t\t\t}\r\n\r\n\t\t\tt.controls[id] = c;\r\n\r\n\t\t\t// Fix focus problem in Safari\r\n\t\t\tif (tinymce.isWebKit) {\r\n\t\t\t\tc.onPostRender.add(function(c, n) {\r\n\t\t\t\t\t// Store bookmark on mousedown\r\n\t\t\t\t\tEvent.add(n, 'mousedown', function() {\r\n\t\t\t\t\t\ted.bookmark = ed.selection.getBookmark(1);\r\n\t\t\t\t\t});\r\n\r\n\t\t\t\t\t// Restore on focus, since it might be lost\r\n\t\t\t\t\tEvent.add(n, 'focus', function() {\r\n\t\t\t\t\t\ted.selection.moveToBookmark(ed.bookmark);\r\n\t\t\t\t\t\ted.bookmark = null;\r\n\t\t\t\t\t});\r\n\t\t\t\t});\r\n\t\t\t}\r\n\r\n\t\t\tif (c.hideMenu)\r\n\t\t\t\ted.onMouseDown.add(c.hideMenu, c);\r\n\r\n\t\t\treturn t.add(c);\r\n\t\t},\r\n\r\n\t\t/**\r\n\t\t * Creates a button control instance by id.\r\n\t\t *\r\n\t\t * @method createButton\r\n\t\t * @param {String} id Unique id for the new button instance. For example \"bold\".\r\n\t\t * @param {Object} s Optional settings object for the control.\r\n\t\t * @param {Object} cc Optional control class to use instead of the default one.\r\n\t\t * @return {tinymce.ui.Control} Control instance that got created and added.\r\n\t\t */\r\n\t\tcreateButton : function(id, s, cc) {\r\n\t\t\tvar t = this, ed = t.editor, o, c, cls;\r\n\r\n\t\t\tif (t.get(id))\r\n\t\t\t\treturn null;\r\n\r\n\t\t\ts.title = ed.translate(s.title);\r\n\t\t\ts.label = ed.translate(s.label);\r\n\t\t\ts.scope = s.scope || ed;\r\n\r\n\t\t\tif (!s.onclick && !s.menu_button) {\r\n\t\t\t\ts.onclick = function() {\r\n\t\t\t\t\ted.execCommand(s.cmd, s.ui || false, s.value);\r\n\t\t\t\t};\r\n\t\t\t}\r\n\r\n\t\t\ts = extend({\r\n\t\t\t\ttitle : s.title,\r\n\t\t\t\t'class' : 'mce_' + id,\r\n\t\t\t\tunavailable_prefix : ed.getLang('unavailable', ''),\r\n\t\t\t\tscope : s.scope,\r\n\t\t\t\tcontrol_manager : t\r\n\t\t\t}, s);\r\n\r\n\t\t\tid = t.prefix + id;\r\n\r\n\t\t\tif (s.menu_button) {\r\n\t\t\t\tcls = cc || t._cls.menubutton || tinymce.ui.MenuButton;\r\n\t\t\t\tc = new cls(id, s, ed);\r\n\t\t\t\ted.onMouseDown.add(c.hideMenu, c);\r\n\t\t\t} else {\r\n\t\t\t\tcls = t._cls.button || tinymce.ui.Button;\r\n\t\t\t\tc = new cls(id, s, ed);\r\n\t\t\t}\r\n\r\n\t\t\treturn t.add(c);\r\n\t\t},\r\n\r\n\t\t/**\r\n\t\t * Creates a menu button control instance by id.\r\n\t\t *\r\n\t\t * @method createMenuButton\r\n\t\t * @param {String} id Unique id for the new menu button instance. For example \"menu1\".\r\n\t\t * @param {Object} s Optional settings object for the control.\r\n\t\t * @param {Object} cc Optional control class to use instead of the default one.\r\n\t\t * @return {tinymce.ui.Control} Control instance that got created and added.\r\n\t\t */\r\n\t\tcreateMenuButton : function(id, s, cc) {\r\n\t\t\ts = s || {};\r\n\t\t\ts.menu_button = 1;\r\n\r\n\t\t\treturn this.createButton(id, s, cc);\r\n\t\t},\r\n\r\n\t\t/**\r\n\t\t * Creates a split button control instance by id.\r\n\t\t *\r\n\t\t * @method createSplitButton\r\n\t\t * @param {String} id Unique id for the new split button instance. For example \"spellchecker\".\r\n\t\t * @param {Object} s Optional settings object for the control.\r\n\t\t * @param {Object} cc Optional control class to use instead of the default one.\r\n\t\t * @return {tinymce.ui.Control} Control instance that got created and added.\r\n\t\t */\r\n\t\tcreateSplitButton : function(id, s, cc) {\r\n\t\t\tvar t = this, ed = t.editor, cmd, c, cls;\r\n\r\n\t\t\tif (t.get(id))\r\n\t\t\t\treturn null;\r\n\r\n\t\t\ts.title = ed.translate(s.title);\r\n\t\t\ts.scope = s.scope || ed;\r\n\r\n\t\t\tif (!s.onclick) {\r\n\t\t\t\ts.onclick = function(v) {\r\n\t\t\t\t\ted.execCommand(s.cmd, s.ui || false, v || s.value);\r\n\t\t\t\t};\r\n\t\t\t}\r\n\r\n\t\t\tif (!s.onselect) {\r\n\t\t\t\ts.onselect = function(v) {\r\n\t\t\t\t\ted.execCommand(s.cmd, s.ui || false, v || s.value);\r\n\t\t\t\t};\r\n\t\t\t}\r\n\r\n\t\t\ts = extend({\r\n\t\t\t\ttitle : s.title,\r\n\t\t\t\t'class' : 'mce_' + id,\r\n\t\t\t\tscope : s.scope,\r\n\t\t\t\tcontrol_manager : t\r\n\t\t\t}, s);\r\n\r\n\t\t\tid = t.prefix + id;\r\n\t\t\tcls = cc || t._cls.splitbutton || tinymce.ui.SplitButton;\r\n\t\t\tc = t.add(new cls(id, s, ed));\r\n\t\t\ted.onMouseDown.add(c.hideMenu, c);\r\n\r\n\t\t\treturn c;\r\n\t\t},\r\n\r\n\t\t/**\r\n\t\t * Creates a color split button control instance by id.\r\n\t\t *\r\n\t\t * @method createColorSplitButton\r\n\t\t * @param {String} id Unique id for the new color split button instance. For example \"forecolor\".\r\n\t\t * @param {Object} s Optional settings object for the control.\r\n\t\t * @param {Object} cc Optional control class to use instead of the default one.\r\n\t\t * @return {tinymce.ui.Control} Control instance that got created and added.\r\n\t\t */\r\n\t\tcreateColorSplitButton : function(id, s, cc) {\r\n\t\t\tvar t = this, ed = t.editor, cmd, c, cls, bm;\r\n\r\n\t\t\tif (t.get(id))\r\n\t\t\t\treturn null;\r\n\r\n\t\t\ts.title = ed.translate(s.title);\r\n\t\t\ts.scope = s.scope || ed;\r\n\r\n\t\t\tif (!s.onclick) {\r\n\t\t\t\ts.onclick = function(v) {\r\n\t\t\t\t\tif (tinymce.isIE)\r\n\t\t\t\t\t\tbm = ed.selection.getBookmark(1);\r\n\r\n\t\t\t\t\ted.execCommand(s.cmd, s.ui || false, v || s.value);\r\n\t\t\t\t};\r\n\t\t\t}\r\n\r\n\t\t\tif (!s.onselect) {\r\n\t\t\t\ts.onselect = function(v) {\r\n\t\t\t\t\ted.execCommand(s.cmd, s.ui || false, v || s.value);\r\n\t\t\t\t};\r\n\t\t\t}\r\n\r\n\t\t\ts = extend({\r\n\t\t\t\ttitle : s.title,\r\n\t\t\t\t'class' : 'mce_' + id,\r\n\t\t\t\t'menu_class' : ed.getParam('skin') + 'Skin',\r\n\t\t\t\tscope : s.scope,\r\n\t\t\t\tmore_colors_title : ed.getLang('more_colors')\r\n\t\t\t}, s);\r\n\r\n\t\t\tid = t.prefix + id;\r\n\t\t\tcls = cc || t._cls.colorsplitbutton || tinymce.ui.ColorSplitButton;\r\n\t\t\tc = new cls(id, s, ed);\r\n\t\t\ted.onMouseDown.add(c.hideMenu, c);\r\n\r\n\t\t\t// Remove the menu element when the editor is removed\r\n\t\t\ted.onRemove.add(function() {\r\n\t\t\t\tc.destroy();\r\n\t\t\t});\r\n\r\n\t\t\t// Fix for bug #1897785, #1898007\r\n\t\t\tif (tinymce.isIE) {\r\n\t\t\t\tc.onShowMenu.add(function() {\r\n\t\t\t\t\t// IE 8 needs focus in order to store away a range with the current collapsed caret location\r\n\t\t\t\t\ted.focus();\r\n\t\t\t\t\tbm = ed.selection.getBookmark(1);\r\n\t\t\t\t});\r\n\r\n\t\t\t\tc.onHideMenu.add(function() {\r\n\t\t\t\t\tif (bm) {\r\n\t\t\t\t\t\ted.selection.moveToBookmark(bm);\r\n\t\t\t\t\t\tbm = 0;\r\n\t\t\t\t\t}\r\n\t\t\t\t});\r\n\t\t\t}\r\n\r\n\t\t\treturn t.add(c);\r\n\t\t},\r\n\r\n\t\t/**\r\n\t\t * Creates a toolbar container control instance by id.\r\n\t\t *\r\n\t\t * @method createToolbar\r\n\t\t * @param {String} id Unique id for the new toolbar container control instance. For example \"toolbar1\".\r\n\t\t * @param {Object} s Optional settings object for the control.\r\n\t\t * @param {Object} cc Optional control class to use instead of the default one.\r\n\t\t * @return {tinymce.ui.Control} Control instance that got created and added.\r\n\t\t */\r\n\t\tcreateToolbar : function(id, s, cc) {\r\n\t\t\tvar c, t = this, cls;\r\n\r\n\t\t\tid = t.prefix + id;\r\n\t\t\tcls = cc || t._cls.toolbar || tinymce.ui.Toolbar;\r\n\t\t\tc = new cls(id, s, t.editor);\r\n\r\n\t\t\tif (t.get(id))\r\n\t\t\t\treturn null;\r\n\r\n\t\t\treturn t.add(c);\r\n\t\t},\r\n\t\t\r\n\t\tcreateToolbarGroup : function(id, s, cc) {\r\n\t\t\tvar c, t = this, cls;\r\n\t\t\tid = t.prefix + id;\r\n\t\t\tcls = cc || this._cls.toolbarGroup || tinymce.ui.ToolbarGroup;\r\n\t\t\tc = new cls(id, s, t.editor);\r\n\t\t\t\r\n\t\t\tif (t.get(id))\r\n\t\t\t\treturn null;\r\n\t\t\t\r\n\t\t\treturn t.add(c);\r\n\t\t},\r\n\r\n\t\t/**\r\n\t\t * Creates a separator control instance.\r\n\t\t *\r\n\t\t * @method createSeparator\r\n\t\t * @param {Object} cc Optional control class to use instead of the default one.\r\n\t\t * @return {tinymce.ui.Control} Control instance that got created and added.\r\n\t\t */\r\n\t\tcreateSeparator : function(cc) {\r\n\t\t\tvar cls = cc || this._cls.separator || tinymce.ui.Separator;\r\n\r\n\t\t\treturn new cls();\r\n\t\t},\r\n\r\n\t\t/**\r\n\t\t * Overrides a specific control type with a custom class.\r\n\t\t *\r\n\t\t * @method setControlType\r\n\t\t * @param {string} n Name of the control to override for example button or dropmenu.\r\n\t\t * @param {function} c Class reference to use instead of the default one.\r\n\t\t * @return {function} Same as the class reference.\r\n\t\t */\r\n\t\tsetControlType : function(n, c) {\r\n\t\t\treturn this._cls[n.toLowerCase()] = c;\r\n\t\t},\r\n\t\r\n\t\t/**\r\n\t\t * Destroy.\r\n\t\t *\r\n\t\t * @method destroy\r\n\t\t */\r\n\t\tdestroy : function() {\r\n\t\t\teach(this.controls, function(c) {\r\n\t\t\t\tc.destroy();\r\n\t\t\t});\r\n\r\n\t\t\tthis.controls = null;\r\n\t\t}\r\n\t});\r\n})(tinymce);\r\n"}} -{"repo": "siuying/websnap", "pr_number": 6, "title": "Adding wkhtmltoimage-amd64 ", "state": "closed", "merged_at": "2012-12-11T16:50:18Z", "additions": 53, "deletions": 13, "files_changed": ["bin/wkhtml_image_executable.rb", "spec/websnap_spec.rb", "spec/wkhtml_image_executable_spec.rb"], "files_before": {"spec/websnap_spec.rb": "require 'spec_helper'\n\ndescribe WebSnap::Snapper do\n \n context \"initialization\" do\n it \"should accept HTML as the source\" do\n websnap = WebSnap::Snapper.new('

            Oh Hai

            ')\n websnap.source.should be_html\n websnap.source.to_s.should == '

            Oh Hai

            '\n end\n \n it \"should accept a URL as the source\" do\n websnap = WebSnap::Snapper.new('http://google.com')\n websnap.source.should be_url\n websnap.source.to_s.should == 'http://google.com'\n end\n \n it \"should accept a File as the source\" do\n file_path = File.join(SPEC_ROOT,'fixtures','google.html')\n websnap = WebSnap::Snapper.new(File.new(file_path))\n websnap.source.should be_file\n websnap.source.to_s.should == file_path\n end\n \n it \"should parse the options into a cmd line friedly format\" do\n websnap = WebSnap::Snapper.new('html', :'crop-w' => '800', :'crop-h' => '600')\n websnap.options.should have_key('--crop-w')\n end\n\n it \"should provide default options\" do\n websnap = WebSnap::Snapper.new('

            Oh Hai

            ')\n ['--crop-w', '--crop-h', '--crop-x', '--crop-y', '--format'].each do |option|\n websnap.options.should have_key(option)\n end\n end\n end\n \n context \"command\" do\n it \"should contstruct the correct command\" do\n websnap = WebSnap::Snapper.new('html', :'encoding' => 'Big5')\n websnap.command.should include('--encoding Big5')\n end\n\n it \"read the source from stdin if it is html\" do\n websnap = WebSnap::Snapper.new('html')\n websnap.command.should match(/ - -$/)\n end\n \n it \"specify the URL to the source if it is a url\" do\n websnap = WebSnap::Snapper.new('http://google.com')\n websnap.command.should match(/ http:\\/\\/google\\.com -$/)\n end\n \n it \"should specify the path to the source if it is a file\" do\n file_path = File.join(SPEC_ROOT,'fixtures','google.html')\n websnap = WebSnap::Snapper.new(File.new(file_path))\n websnap.command.should match(/ #{file_path} -$/)\n end\n end\n \n context \"#to_bytes\" do\n it \"should generate a PDF of the HTML\" do\n websnap = WebSnap::Snapper.new('html')\n websnap.expects(:to_bytes).returns('PNG')\n png = websnap.to_bytes\n png.should match(/PNG/)\n end\n end\n \n context \"#to_file\" do\n before do\n @file_path = File.join(SPEC_ROOT,'fixtures','test.png')\n File.delete(@file_path) if File.exist?(@file_path)\n end\n \n after do\n File.delete(@file_path)\n end\n \n it \"should create a file with the PNG as content\" do\n websnap = WebSnap::Snapper.new('html')\n websnap.expects(:to_bytes).returns('PNG')\n\n file = websnap.to_file(@file_path)\n file.should be_instance_of(File)\n File.read(file.path).should == 'PNG'\n end\n end\n \nend\n"}, "files_after": {"bin/wkhtml_image_executable.rb": "class WkhtmlImageExecutable\n attr_reader :system_platform\n\n def initialize(args={})\n @system_platform = args[:system_platform] || default_platform\n end\n\n def default_platform\n RUBY_PLATFORM\n end\n\n def binary_wkhtmltoimage\n case @system_platform\n when /x86_64-linux/\n 'wkhtmltoimage-amd64'\n when /linux/\n 'wkhtmltoimage-linux-i386-0.10.0'\n when /darwin/\n 'wkhtmltoimage-osx-i386-0.10.0'\n else\n raise \"No bundled binaries found for your system. Please install wkhtmltopdf.\"\n end\n end\nend\n\n\n", "spec/websnap_spec.rb": "require 'spec_helper'\n\ndescribe WebSnap::Snapper do\n \n context \"initialization\" do\n it \"should accept HTML as the source\" do\n websnap = WebSnap::Snapper.new('

            Oh Hai

            ')\n websnap.source.should be_html\n websnap.source.to_s.should == '

            Oh Hai

            '\n end\n \n it \"should accept a URL as the source\" do\n websnap = WebSnap::Snapper.new('http://google.com')\n websnap.source.should be_url\n websnap.source.to_s.should == 'http://google.com'\n end\n \n it \"should accept a File as the source\" do\n file_path = File.join(SPEC_ROOT,'fixtures','google.html')\n websnap = WebSnap::Snapper.new(File.new(file_path))\n websnap.source.should be_file\n websnap.source.to_s.should == file_path\n end\n \n it \"should parse the options into a cmd line friedly format\" do\n websnap = WebSnap::Snapper.new('html', :'crop-w' => '800', :'crop-h' => '600')\n websnap.options.should have_key('--crop-w')\n end\n\n it \"should provide default options\" do\n websnap = WebSnap::Snapper.new('

            Oh Hai

            ')\n ['--format'].each do |option|\n websnap.options.should have_key(option)\n end\n end\n end\n \n context \"command\" do\n it \"should contstruct the correct command\" do\n websnap = WebSnap::Snapper.new('html', :'encoding' => 'Big5')\n websnap.command.should include('--encoding Big5')\n end\n\n it \"read the source from stdin if it is html\" do\n websnap = WebSnap::Snapper.new('html')\n websnap.command.should match(/ - -$/)\n end\n \n it \"specify the URL to the source if it is a url\" do\n websnap = WebSnap::Snapper.new('http://google.com')\n websnap.command.should match(/ http:\\/\\/google\\.com -$/)\n end\n \n it \"should specify the path to the source if it is a file\" do\n file_path = File.join(SPEC_ROOT,'fixtures','google.html')\n websnap = WebSnap::Snapper.new(File.new(file_path))\n websnap.command.should match(/ #{file_path} -$/)\n end\n end\n \n context \"#to_bytes\" do\n it \"should generate a PDF of the HTML\" do\n websnap = WebSnap::Snapper.new('html')\n websnap.expects(:to_bytes).returns('PNG')\n png = websnap.to_bytes\n png.should match(/PNG/)\n end\n end\n \n context \"#to_file\" do\n before do\n @file_path = File.join(SPEC_ROOT,'fixtures','test.png')\n File.delete(@file_path) if File.exist?(@file_path)\n end\n \n after do\n File.delete(@file_path)\n end\n \n it \"should create a file with the PNG as content\" do\n websnap = WebSnap::Snapper.new('html')\n websnap.expects(:to_bytes).returns('PNG')\n\n file = websnap.to_file(@file_path)\n file.should be_instance_of(File)\n File.read(file.path).should == 'PNG'\n end\n end\n \nend\n", "spec/wkhtml_image_executable_spec.rb": "require 'spec_helper'\nrequire_relative '../bin/wkhtml_image_executable'\n\ndescribe WkhtmlImageExecutable do\n\n it \"should return wkhtmltoimage-amd64 when platform contains 64-linux\" do \n WkhtmlImageExecutable.new({system_platform: \"x86_64-linux\"}).binary_wkhtmltoimage.should eq \"wkhtmltoimage-amd64\"\n end\n \n it \"should return wkhtmltoimage-linux-i386-0.10.0 when platform contains linux\" do \n WkhtmlImageExecutable.new({system_platform: \"linux\"}).binary_wkhtmltoimage.should eq \"wkhtmltoimage-linux-i386-0.10.0\"\n end\n \n it \"should return wkhtmltoimage-osx-i386-0.10.0 when platform contains darwin\" do \n WkhtmlImageExecutable.new({system_platform: \"darwin\"}).binary_wkhtmltoimage.should eq \"wkhtmltoimage-osx-i386-0.10.0\"\n end\n\n it \"should raise execption when platform is not found with a matching \" do\n expect {WkhtmlImageExecutable.new({system_platform: \"magical_unicorns\"}).binary_wkhtmltoimage}.to raise_error\n end\nend\n\n"}} -{"repo": "sbarthelemy/arboris-python", "pr_number": 28, "title": "Remove lonely tab", "state": "closed", "merged_at": null, "additions": 1, "deletions": 1, "files_changed": ["arboris/observers.py"], "files_before": {"arboris/observers.py": "#coding=utf-8\n\"\"\"A set of Observers.\n\"\"\"\n__author__ = (u\"S\u00e9bastien BARTH\u00c9LEMY \",\n \"Joseph SALINI \")\nimport arboris.core\nfrom abc import ABCMeta, abstractmethod, abstractproperty\nfrom numpy import dot, array, eye, linalg, vstack, hstack, zeros, diag\nfrom time import time as _time\nfrom arboris.massmatrix import principalframe\nimport logging\nlogging.basicConfig(level=logging.DEBUG)\n\nclass EnergyMonitor(arboris.core.Observer):\n \"\"\"Compute and store the world energy at each time step.\n\n **Example:**\n\n >>> from arboris.core import World, simulate\n >>> from arboris.robots.simplearm import add_simplearm\n >>> w = World()\n >>> observers = [EnergyMonitor()]\n >>> add_simplearm(w)\n >>> simulate(w, [0,1,2], observers)\n >>> #obs.plot()\n\n \"\"\"\n\n def init(self, world, timeline):\n self._world = world\n self.time = []\n self.kinetic_energy = []\n self.potential_energy = []\n self.mechanichal_energy = []\n self._com_pos = {}\n self._bodies = self._world.ground.iter_descendant_bodies\n for body in self._bodies():\n self._com_pos[body] = principalframe(body.mass)[:,3]\n\n def update(self, dt):\n self.time.append(self._world.current_time)\n Ec = dot(self._world.gvel,\n dot(self._world.mass, self._world.gvel) )/2.\n self.kinetic_energy.append(Ec)\n Ep = 0.\n for body in self._bodies():\n h = dot( dot(body.pose, self._com_pos[body])[0:3], self._world.up)\n Ep += body.mass[3,3] * h\n Ep *= 9.81\n self.potential_energy.append(Ep)\n self.mechanichal_energy.append(Ec+Ep)\n\n def finish(self):\n pass\n\n def plot(self):\n \"\"\"Plot the energy evolution.\n \"\"\"\n from pylab import plot, show, legend, xlabel, ylabel, title\n plot(self.time, self.kinetic_energy)\n plot(self.time, self.potential_energy)\n plot(self.time, self.mechanichal_energy)\n legend(('kinetic','potential','mechanical'))\n title('Energy evolution')\n xlabel('time (s)')\n ylabel('energy (J)')\n show()\n\n\nclass PerfMonitor(arboris.core.Observer):\n \"\"\"\n\n **Example:**\n\n >>> from arboris.core import World, simulate\n >>> from arboris.robots.simplearm import add_simplearm\n >>> w = World()\n >>> obs = PerfMonitor()\n >>> add_simplearm(w)\n >>> simulate(w, [0,1,2], [obs])\n >>> print obs.get_summary() #doctest: +ELLIPSIS\n total computation time (s): ...\n min computation time (s): ...\n mean computation time (s): ...\n max computation time (s): ...\n >>> #obs.plot()\n\n \"\"\"\n def __init__(self, log=False):\n arboris.core.Observer.__init__(self)\n if log:\n self._logger = logging.getLogger(self.__class__.__name__)\n else:\n self._logger = None\n self._last_time = None\n self._computation_time = []\n\n def init(self, world, timeline):\n self._world = world\n self._last_time = _time()\n\n def update(self, dt):\n current_time = _time()\n self._computation_time.append(current_time - self._last_time)\n self._last_time = current_time\n if self._logger is not None:\n self._logger.info('current time (s): %.3f',\n self._world.current_time)\n\n def finish(self):\n pass\n\n def plot(self):\n from pylab import plot, show, xlabel, ylabel, title\n plot(self._computation_time)\n title('Computation time for each simulation time step')\n xlabel('simulation time step')\n ylabel('computation time (s)')\n show()\n\n def get_summary(self):\n total = sum(self._computation_time)\n return \"\"\"total computation time (s): {0}\nmin computation time (s): {1}\nmean computation time (s): {2}\nmax computation time (s): {3}\"\"\".format(\n total,\n min(self._computation_time),\n total/len(self._computation_time),\n max(self._computation_time))\n\n\nclass Hdf5Logger(arboris.core.Observer):\n \"\"\"An observer that saves the simulation data in an hdf5 file.\n\n :param filename: name of the output hdf5 file\n :type filename: str\n :param group: subgroup within the hdf5 file. Defaults to \"/\"\n :type group: str\n :param mode: mode used to open the hdf5 file. Can be 'w' or 'a' (default)\n :type mode: str\n :param save_state: toggle the write of the ``gpos`` and ``gvel`` groups\n :type save_state: bool\n :param save_transforms: toggle the write of the ``transforms`` group\n :type save_transforms: bool\n :param flat: whether to save body of joint poses in the ``transforms`` group\n :type flat: bool\n :param save_model: toggle the write of ``model`` group\n :type save_model: bool\n\n All the simulation data lies in a single user-chosen group, that is denoted\n ``root`` in the following, and which defaults to ``/``. All the data are in\n S.I. units (radians, meters, newtons and seconds).\n\n The hdf5 file has the following layout::\n\n root/timeline (nsteps,)\n root/gpositions/\n root/gvelocities/\n root/model/\n root/transforms/\n\n The ``gvelocities`` group contains the generalized velocities of the\n joints::\n\n NameOfJoint0 (nsteps, joint0.ndof)\n NameOfJoint1 (nsteps, joint1.ndof)\n ...\n\n while the ``gpositions`` group contains their generalized positions.\n\n The ``model`` group contains the matrices from the dynamical model::\n\n gvel (nsteps, ndof)\n gforce (nsteps, ndof)\n mass (nsteps, ndof, ndof)\n nleffects (nsteps, ndof, ndof)\n admittance (nsteps, ndof, ndof)\n\n The ``transforms`` group contains homogeneous transformations,\n useful for viewing an animation of the simulation.\n\n NameOfTransform0 (nsteps, 4, 4)\n NameOfTransform1 (nsteps, 4, 4)\n ...\n\n The name and value of the transforms depends on the ``flat`` parameter.\n If ``flat`` is True, then there is one transform per body, named after the\n body and whose value is the body absolute pose (``Body.pose``).\n If ``flat`` is False, there is one transform per joint, whose value is\n ``Joint.pose`` and whose name is taken from the joint second frame\n (``Joint.frames[1].name``).\n\n \"\"\"\n def __init__(self, filename, group=\"/\", mode='a', save_state=False,\n save_transforms=True, flat=False, save_model=False):\n import h5py\n arboris.core.Observer.__init__(self)\n # hdf5 file handlers\n self._file = h5py.File(filename, mode)\n self._root = self._file\n for g in group.split('/'):\n if g:\n self._root = self._root.require_group(g)\n # what to save\n self._save_state = save_state\n self._save_transforms = save_transforms\n self._flat = flat\n self._save_model = save_model\n\n @property\n def root(self):\n return self._root\n\n def init(self, world, timeline):\n \"\"\"Create the datasets.\n \"\"\"\n self._world = world\n self._nb_steps = len(timeline)-1\n self._current_step = 0\n self._root.require_dataset(\"timeline\", (self._nb_steps,), 'f8')\n if self._save_state:\n self._gpositions = self._root.require_group('gpositions')\n self._gvelocities = self._root.require_group('gvelocities')\n for j in self._world.getjoints():\n self._gpositions.require_dataset(j.name,\n (self._nb_steps,) + j.gpos.shape[:])\n self._gvelocities.require_dataset(j.name,\n (self._nb_steps, j.ndof))\n if self._save_transforms:\n self._arb_transforms = {}\n self._transforms = self._root.require_group('transforms')\n if self._flat:\n for b in self._world.iterbodies():\n self._arb_transforms[b.name] = b\n else:\n for j in self._world.getjoints():\n self._arb_transforms[j.frames[1].name] = j\n for f in self._world.itermovingsubframes():\n self._arb_transforms[f.name] = f\n for k in self._arb_transforms.iterkeys():\n d = self._transforms.require_dataset(k,\n (self._nb_steps, 4,4),\n 'f8')\n if self._save_model:\n self._model = self._root.require_group('transforms')\n ndof = self._world.ndof\n self._model.require_dataset(\"gvel\",\n (self._nb_steps, ndof), 'f8')\n self._model.require_dataset(\"mass\",\n (self._nb_steps, ndof, ndof), 'f8')\n self._model.require_dataset(\"admittance\",\n (self._nb_steps, ndof, ndof), 'f8')\n self._model.require_dataset(\"nleffects\",\n (self._nb_steps, ndof, ndof), 'f8')\n self._model.require_dataset(\"gforce\",\n (self._nb_steps, ndof), 'f8')\n\n def update(self, dt):\n \"\"\"Save the current data (state...).\n \"\"\"\n\tassert self._current_step <= self._nb_steps\n self._root[\"timeline\"][self._current_step] = self._world._current_time\n if self._save_state:\n for j in self._world.getjoints():\n self._gpositions[j.name][self._current_step] = j.gpos\n self._gvelocities[j.name][self._current_step] = j.gvel\n if self._save_transforms:\n for k, v in self._arb_transforms.iteritems():\n if isinstance(v, arboris.core.MovingSubFrame):\n if self._flat:\n pose = v.pose\n else:\n pose = v.bpose\n else:\n pose = v.pose\n self._transforms[k][self._current_step,:,:] = v.pose\n if self._save_model:\n self._model[\"gvel\"][self._current_step,:] = self._world.gvel\n self._model[\"mass\"][self._current_step,:,:] = self._world.mass\n self._model[\"admittance\"][self._current_step,:,:] = \\\n self._world.admittance\n self._model[\"nleffects\"][self._current_step,:,:] = \\\n self._world.nleffects\n self._model[\"gforce\"][self._current_step,:] = self._world.gforce\n self._current_step += 1\n\n def finish(self):\n self._file.close()\n"}, "files_after": {"arboris/observers.py": "#coding=utf-8\n\"\"\"A set of Observers.\n\"\"\"\n__author__ = (u\"S\u00e9bastien BARTH\u00c9LEMY \",\n \"Joseph SALINI \")\nimport arboris.core\nfrom abc import ABCMeta, abstractmethod, abstractproperty\nfrom numpy import dot, array, eye, linalg, vstack, hstack, zeros, diag\nfrom time import time as _time\nfrom arboris.massmatrix import principalframe\nimport logging\nlogging.basicConfig(level=logging.DEBUG)\n\nclass EnergyMonitor(arboris.core.Observer):\n \"\"\"Compute and store the world energy at each time step.\n\n **Example:**\n\n >>> from arboris.core import World, simulate\n >>> from arboris.robots.simplearm import add_simplearm\n >>> w = World()\n >>> observers = [EnergyMonitor()]\n >>> add_simplearm(w)\n >>> simulate(w, [0,1,2], observers)\n >>> #obs.plot()\n\n \"\"\"\n\n def init(self, world, timeline):\n self._world = world\n self.time = []\n self.kinetic_energy = []\n self.potential_energy = []\n self.mechanichal_energy = []\n self._com_pos = {}\n self._bodies = self._world.ground.iter_descendant_bodies\n for body in self._bodies():\n self._com_pos[body] = principalframe(body.mass)[:,3]\n\n def update(self, dt):\n self.time.append(self._world.current_time)\n Ec = dot(self._world.gvel,\n dot(self._world.mass, self._world.gvel) )/2.\n self.kinetic_energy.append(Ec)\n Ep = 0.\n for body in self._bodies():\n h = dot( dot(body.pose, self._com_pos[body])[0:3], self._world.up)\n Ep += body.mass[3,3] * h\n Ep *= 9.81\n self.potential_energy.append(Ep)\n self.mechanichal_energy.append(Ec+Ep)\n\n def finish(self):\n pass\n\n def plot(self):\n \"\"\"Plot the energy evolution.\n \"\"\"\n from pylab import plot, show, legend, xlabel, ylabel, title\n plot(self.time, self.kinetic_energy)\n plot(self.time, self.potential_energy)\n plot(self.time, self.mechanichal_energy)\n legend(('kinetic','potential','mechanical'))\n title('Energy evolution')\n xlabel('time (s)')\n ylabel('energy (J)')\n show()\n\n\nclass PerfMonitor(arboris.core.Observer):\n \"\"\"\n\n **Example:**\n\n >>> from arboris.core import World, simulate\n >>> from arboris.robots.simplearm import add_simplearm\n >>> w = World()\n >>> obs = PerfMonitor()\n >>> add_simplearm(w)\n >>> simulate(w, [0,1,2], [obs])\n >>> print obs.get_summary() #doctest: +ELLIPSIS\n total computation time (s): ...\n min computation time (s): ...\n mean computation time (s): ...\n max computation time (s): ...\n >>> #obs.plot()\n\n \"\"\"\n def __init__(self, log=False):\n arboris.core.Observer.__init__(self)\n if log:\n self._logger = logging.getLogger(self.__class__.__name__)\n else:\n self._logger = None\n self._last_time = None\n self._computation_time = []\n\n def init(self, world, timeline):\n self._world = world\n self._last_time = _time()\n\n def update(self, dt):\n current_time = _time()\n self._computation_time.append(current_time - self._last_time)\n self._last_time = current_time\n if self._logger is not None:\n self._logger.info('current time (s): %.3f',\n self._world.current_time)\n\n def finish(self):\n pass\n\n def plot(self):\n from pylab import plot, show, xlabel, ylabel, title\n plot(self._computation_time)\n title('Computation time for each simulation time step')\n xlabel('simulation time step')\n ylabel('computation time (s)')\n show()\n\n def get_summary(self):\n total = sum(self._computation_time)\n return \"\"\"total computation time (s): {0}\nmin computation time (s): {1}\nmean computation time (s): {2}\nmax computation time (s): {3}\"\"\".format(\n total,\n min(self._computation_time),\n total/len(self._computation_time),\n max(self._computation_time))\n\n\nclass Hdf5Logger(arboris.core.Observer):\n \"\"\"An observer that saves the simulation data in an hdf5 file.\n\n :param filename: name of the output hdf5 file\n :type filename: str\n :param group: subgroup within the hdf5 file. Defaults to \"/\"\n :type group: str\n :param mode: mode used to open the hdf5 file. Can be 'w' or 'a' (default)\n :type mode: str\n :param save_state: toggle the write of the ``gpos`` and ``gvel`` groups\n :type save_state: bool\n :param save_transforms: toggle the write of the ``transforms`` group\n :type save_transforms: bool\n :param flat: whether to save body of joint poses in the ``transforms`` group\n :type flat: bool\n :param save_model: toggle the write of ``model`` group\n :type save_model: bool\n\n All the simulation data lies in a single user-chosen group, that is denoted\n ``root`` in the following, and which defaults to ``/``. All the data are in\n S.I. units (radians, meters, newtons and seconds).\n\n The hdf5 file has the following layout::\n\n root/timeline (nsteps,)\n root/gpositions/\n root/gvelocities/\n root/model/\n root/transforms/\n\n The ``gvelocities`` group contains the generalized velocities of the\n joints::\n\n NameOfJoint0 (nsteps, joint0.ndof)\n NameOfJoint1 (nsteps, joint1.ndof)\n ...\n\n while the ``gpositions`` group contains their generalized positions.\n\n The ``model`` group contains the matrices from the dynamical model::\n\n gvel (nsteps, ndof)\n gforce (nsteps, ndof)\n mass (nsteps, ndof, ndof)\n nleffects (nsteps, ndof, ndof)\n admittance (nsteps, ndof, ndof)\n\n The ``transforms`` group contains homogeneous transformations,\n useful for viewing an animation of the simulation.\n\n NameOfTransform0 (nsteps, 4, 4)\n NameOfTransform1 (nsteps, 4, 4)\n ...\n\n The name and value of the transforms depends on the ``flat`` parameter.\n If ``flat`` is True, then there is one transform per body, named after the\n body and whose value is the body absolute pose (``Body.pose``).\n If ``flat`` is False, there is one transform per joint, whose value is\n ``Joint.pose`` and whose name is taken from the joint second frame\n (``Joint.frames[1].name``).\n\n \"\"\"\n def __init__(self, filename, group=\"/\", mode='a', save_state=False,\n save_transforms=True, flat=False, save_model=False):\n import h5py\n arboris.core.Observer.__init__(self)\n # hdf5 file handlers\n self._file = h5py.File(filename, mode)\n self._root = self._file\n for g in group.split('/'):\n if g:\n self._root = self._root.require_group(g)\n # what to save\n self._save_state = save_state\n self._save_transforms = save_transforms\n self._flat = flat\n self._save_model = save_model\n\n @property\n def root(self):\n return self._root\n\n def init(self, world, timeline):\n \"\"\"Create the datasets.\n \"\"\"\n self._world = world\n self._nb_steps = len(timeline)-1\n self._current_step = 0\n self._root.require_dataset(\"timeline\", (self._nb_steps,), 'f8')\n if self._save_state:\n self._gpositions = self._root.require_group('gpositions')\n self._gvelocities = self._root.require_group('gvelocities')\n for j in self._world.getjoints():\n self._gpositions.require_dataset(j.name,\n (self._nb_steps,) + j.gpos.shape[:])\n self._gvelocities.require_dataset(j.name,\n (self._nb_steps, j.ndof))\n if self._save_transforms:\n self._arb_transforms = {}\n self._transforms = self._root.require_group('transforms')\n if self._flat:\n for b in self._world.iterbodies():\n self._arb_transforms[b.name] = b\n else:\n for j in self._world.getjoints():\n self._arb_transforms[j.frames[1].name] = j\n for f in self._world.itermovingsubframes():\n self._arb_transforms[f.name] = f\n for k in self._arb_transforms.iterkeys():\n d = self._transforms.require_dataset(k,\n (self._nb_steps, 4,4),\n 'f8')\n if self._save_model:\n self._model = self._root.require_group('transforms')\n ndof = self._world.ndof\n self._model.require_dataset(\"gvel\",\n (self._nb_steps, ndof), 'f8')\n self._model.require_dataset(\"mass\",\n (self._nb_steps, ndof, ndof), 'f8')\n self._model.require_dataset(\"admittance\",\n (self._nb_steps, ndof, ndof), 'f8')\n self._model.require_dataset(\"nleffects\",\n (self._nb_steps, ndof, ndof), 'f8')\n self._model.require_dataset(\"gforce\",\n (self._nb_steps, ndof), 'f8')\n\n def update(self, dt):\n \"\"\"Save the current data (state...).\n \"\"\"\n assert self._current_step <= self._nb_steps\n self._root[\"timeline\"][self._current_step] = self._world._current_time\n if self._save_state:\n for j in self._world.getjoints():\n self._gpositions[j.name][self._current_step] = j.gpos\n self._gvelocities[j.name][self._current_step] = j.gvel\n if self._save_transforms:\n for k, v in self._arb_transforms.iteritems():\n if isinstance(v, arboris.core.MovingSubFrame):\n if self._flat:\n pose = v.pose\n else:\n pose = v.bpose\n else:\n pose = v.pose\n self._transforms[k][self._current_step,:,:] = v.pose\n if self._save_model:\n self._model[\"gvel\"][self._current_step,:] = self._world.gvel\n self._model[\"mass\"][self._current_step,:,:] = self._world.mass\n self._model[\"admittance\"][self._current_step,:,:] = \\\n self._world.admittance\n self._model[\"nleffects\"][self._current_step,:,:] = \\\n self._world.nleffects\n self._model[\"gforce\"][self._current_step,:] = self._world.gforce\n self._current_step += 1\n\n def finish(self):\n self._file.close()\n"}} -{"repo": "jugyo/termcolor", "pr_number": 3, "title": "arguments for String#termcolor", "state": "closed", "merged_at": null, "additions": 28, "deletions": 2, "files_changed": ["lib/termcolor.rb", "spec/termcolor_spec.rb"], "files_before": {"lib/termcolor.rb": "# -*- coding: utf-8 -*-\nrequire 'rubygems'\nrequire 'highline'\nrequire 'cgi'\nrequire 'rexml/parsers/streamparser' \nrequire 'rexml/parsers/baseparser' \nrequire 'rexml/streamlistener' \n\nmodule TermColor\n VERSION = '1.2.1'\n include REXML\n\n class << self\n def parse(text)\n listener = MyListener.new \n REXML::Parsers::StreamParser.new(prepare_parse(text), listener).parse\n listener.result\n end\n\n def escape(text)\n escape_or_unescape(:escape, text)\n end\n\n def unescape(text)\n escape_or_unescape(:unescape, text)\n end\n\n def escape_or_unescape(dir=:escape, text)\n h = Hash[*%w(& & < < > > ' ' \" ")]\n h = h.invert if dir == :unescape\n text.gsub(/(#{h.keys.join('|')})/){ h[$1] }\n end\n private :escape_or_unescape\n\n def prepare_parse(text)\n tag_separate text.gsub(/<(\\/?)(\\d+)>/, '<\\1_\\2>')\n end\n\n def tag_separate(text)\n re = /<(\\/*)([^\\W_]+)(?:_(on_[^\\W_]+))*(?:_with_([^\\W_]+))*(?:_and_([^\\W_]+))*>/\n text.gsub(re) do\n matchs = $~.captures\n if matchs.shift.empty?\n tag = ->t{ \"<#{t}>\" }\n else\n matchs.reverse!\n tag = ->t{ \"\" }\n end\n matchs.compact.map { |word| tag[word] }.join\n end\n end\n\n def test(*args)\n args = (0..109).to_a if args.empty?\n args.each_with_index do |color, index|\n print parse(\"<#{color}> #{color} \") + \"\\t\"\n puts if (index + 1) % 10 == 0\n end\n end\n\n def colorize(text, color)\n parse(\"<#{color}>#{escape(text)}\")\n end\n end\n\n class MyListener \n include REXML::StreamListener \n\n attr_reader :result\n def initialize\n @result = ''\n @tag_stack = []\n end\n\n def tag_start(name, attrs)\n esc_seq = to_esc_seq(name)\n if esc_seq\n @result << esc_seq\n @tag_stack.push(name)\n end\n end\n\n def text(text)\n @result << CGI.unescapeHTML(text)\n end\n\n def tag_end(name)\n @tag_stack.pop\n @result << HighLine::CLEAR\n @result << @tag_stack.map{|i| to_esc_seq(i)}.join unless @tag_stack.empty?\n end\n\n def to_esc_seq(name)\n if (HighLine.const_defined?(name.upcase) rescue false)\n HighLine.const_get(name.upcase)\n else\n case name\n when /^([fb])(\\d+)$/\n fb = $1 == 'f' ? 38 : 48\n color = $2.size == 3 ? 16 + $2.to_i(6) : 232 + $2.to_i\n \"\\e[#{fb};5;#{color}m\"\n when /^[^0-9]?(\\d+)$/\n \"\\e[#{$1}m\"\n end\n end\n end\n end\nend\n\nclass String\n def termcolor\n TermColor.parse(self)\n end\nend\n", "spec/termcolor_spec.rb": "# -*- coding: utf-8 -*-\nrequire File.dirname(__FILE__) + '/spec_helper'\n\nmodule TermColor\n describe TermColor do\n before do\n end\n\n it 'should parse 1' do\n text = TermColor.parse('aaaaaaafoobbbbbbbbbccccccccccc')\n puts text\n text.should == \"aaa\\e[31maaaa\\e[1mfoo\\e[0m\\e[31mbb\\e[34mbbbb\\e[0m\\e[31mbbb\\e[0mccc\\e[43mccccc\\e[0mccc\"\n end\n\n it 'should parse 2' do\n text = TermColor.parse('aaaaaaaaaaaaaaaa')\n puts text\n text.should == \"aa\\e[34maaaa\\e[31maa\\e[0m\\e[34maaaa\\e[0ma\\e[0maaa\"\n end\n\n it 'should parse 3' do\n text = TermColor.parse('aaaaaaa<aaa"aaa>aaa&aaaaaaaa')\n puts text\n text.should == \"aa\\e[34maaaaaaaa&aaaaa\\e[0maaa\"\n end\n\n it 'should parse 4' do\n text = TermColor.parse('aa<30>bbbbbbb<32>cccc<90>dddcbaaa')\n puts text\n text.should == \"aa\\e[30mbbbbbbb\\e[32mcccc\\e[90mddd\\e[0m\\e[30m\\e[32mc\\e[0m\\e[30mb\\e[0maaa\"\n end\n\n it 'should parse 5' do\n text = TermColor.parse('aabbbbbbbcccccbaaa')\n puts text\n text.should == \"aa\\e[38;5;67mbbbbbbb\\e[48;5;137mccccc\\e[0m\\e[38;5;67mb\\e[0maaa\"\n end\n\n it 'should parse 6' do\n text = TermColor.parse('aabbbbbbbcccccbaaa')\n puts text\n text.should == \"aa\\e[38;5;244mbbbbbbb\\e[48;5;238mccccc\\e[0m\\e[38;5;244mb\\e[0maaa\"\n end\n\n it 'should raise Error' do\n lambda{ TermColor.parse('aaaaaaaaaaaaaaa') }.should raise_error(REXML::ParseException)\n lambda{ TermColor.parse('aaaaaaaaaaaaaaa') }.should_not raise_error(REXML::ParseException)\n end\n\n it 'should escape text' do\n TermColor.escape('<>&\"\\'').should == \"<>&"'\"\n end\n\n it 'should unescape text' do\n TermColor.unescape(\"<>&"'\").should == '<>&\"\\''\n end\n\n it 'should prepare parse' do\n TermColor.prepare_parse(\"<10>10\").should == '<_10>10'\n TermColor.prepare_parse(\"<32>10\").should == '<_32>10'\n end\n\n it 'should convert to escape sequence' do\n listener = TermColor::MyListener.new\n listener.to_esc_seq('red').should == \"\\e[31m\"\n listener.to_esc_seq('on_red').should == \"\\e[41m\"\n listener.to_esc_seq('foo').should == nil\n listener.to_esc_seq('0').should == \"\\e[0m\"\n listener.to_esc_seq('31').should == \"\\e[31m\"\n listener.to_esc_seq('031').should == \"\\e[031m\"\n listener.to_esc_seq('_0').should == \"\\e[0m\"\n listener.to_esc_seq('_31').should == \"\\e[31m\"\n end\n\n it 'should do colorize' do\n TermColor.colorize('test', :green).should == \"\\e[32mtest\\e[0m\"\n end\n\n it 'should make separate tags for combined-style tag' do\n h = { \"hello, world\" =>\n \"hello, world\",\n \"hello, world\" =>\n \"hello, world\",\n \"hello\" =>\n \"hello\",\n \"hellotermcolor\" =>\n \"hellotermcolor\" }\n h.each_pair do |combined, separated|\n TermColor.prepare_parse(combined).should == separated\n end\n end\n end\nend\n"}, "files_after": {"lib/termcolor.rb": "# -*- coding: utf-8 -*-\nrequire 'rubygems'\nrequire 'highline'\nrequire 'cgi'\nrequire 'rexml/parsers/streamparser' \nrequire 'rexml/parsers/baseparser' \nrequire 'rexml/streamlistener' \n\nmodule TermColor\n VERSION = '1.2.1'\n include REXML\n\n class << self\n def parse(text)\n listener = MyListener.new \n REXML::Parsers::StreamParser.new(prepare_parse(text), listener).parse\n listener.result\n end\n\n def escape(text)\n escape_or_unescape(:escape, text)\n end\n\n def unescape(text)\n escape_or_unescape(:unescape, text)\n end\n\n def escape_or_unescape(dir=:escape, text)\n h = Hash[*%w(& & < < > > ' ' \" ")]\n h = h.invert if dir == :unescape\n text.gsub(/(#{h.keys.join('|')})/){ h[$1] }\n end\n private :escape_or_unescape\n\n def prepare_parse(text)\n tag_separate text.gsub(/<(\\/?)(\\d+)>/, '<\\1_\\2>')\n end\n\n def tag_separate(text)\n re = /<(\\/*)([^\\W_]+)(?:_(on_[^\\W_]+))*(?:_with_([^\\W_]+))*(?:_and_([^\\W_]+))*>/\n text.gsub(re) do\n matchs = $~.captures\n if matchs.shift.empty?\n tag = ->t{ \"<#{t}>\" }\n else\n matchs.reverse!\n tag = ->t{ \"\" }\n end\n matchs.compact.map { |word| tag[word] }.join\n end\n end\n\n def test(*args)\n args = (0..109).to_a if args.empty?\n args.each_with_index do |color, index|\n print parse(\"<#{color}> #{color} \") + \"\\t\"\n puts if (index + 1) % 10 == 0\n end\n end\n\n def colorize(text, color)\n parse(\"<#{color}>#{escape(text)}\")\n end\n end\n\n class MyListener \n include REXML::StreamListener \n\n attr_reader :result\n def initialize\n @result = ''\n @tag_stack = []\n end\n\n def tag_start(name, attrs)\n esc_seq = to_esc_seq(name)\n if esc_seq\n @result << esc_seq\n @tag_stack.push(name)\n end\n end\n\n def text(text)\n @result << CGI.unescapeHTML(text)\n end\n\n def tag_end(name)\n @tag_stack.pop\n @result << HighLine::CLEAR\n @result << @tag_stack.map{|i| to_esc_seq(i)}.join unless @tag_stack.empty?\n end\n\n def to_esc_seq(name)\n if (HighLine.const_defined?(name.upcase) rescue false)\n HighLine.const_get(name.upcase)\n else\n case name\n when /^([fb])(\\d+)$/\n fb = $1 == 'f' ? 38 : 48\n color = $2.size == 3 ? 16 + $2.to_i(6) : 232 + $2.to_i\n \"\\e[#{fb};5;#{color}m\"\n when /^[^0-9]?(\\d+)$/\n \"\\e[#{$1}m\"\n end\n end\n end\n end\nend\n\nclass String\n def termcolor(color=nil, target=nil)\n tagging = ->s{ \"<#{color}>#{s}\" }\n str =\n if color\n case target\n when Range\n dself = self.dup\n dself[target] = tagging[(dself[target])]\n dself\n when String, Symbol\n self.gsub(/#{target.to_s}/) { tagging[$&] }\n else\n tagging[self]\n end\n else\n self\n end\n\n TermColor.parse(str)\n end\nend\n", "spec/termcolor_spec.rb": "# -*- coding: utf-8 -*-\nrequire File.dirname(__FILE__) + '/spec_helper'\n\nmodule TermColor\n describe TermColor do\n before do\n end\n\n it 'should parse 1' do\n text = TermColor.parse('aaaaaaafoobbbbbbbbbccccccccccc')\n puts text\n text.should == \"aaa\\e[31maaaa\\e[1mfoo\\e[0m\\e[31mbb\\e[34mbbbb\\e[0m\\e[31mbbb\\e[0mccc\\e[43mccccc\\e[0mccc\"\n end\n\n it 'should parse 2' do\n text = TermColor.parse('aaaaaaaaaaaaaaaa')\n puts text\n text.should == \"aa\\e[34maaaa\\e[31maa\\e[0m\\e[34maaaa\\e[0ma\\e[0maaa\"\n end\n\n it 'should parse 3' do\n text = TermColor.parse('aaaaaaa<aaa"aaa>aaa&aaaaaaaa')\n puts text\n text.should == \"aa\\e[34maaaaaaaa&aaaaa\\e[0maaa\"\n end\n\n it 'should parse 4' do\n text = TermColor.parse('aa<30>bbbbbbb<32>cccc<90>dddcbaaa')\n puts text\n text.should == \"aa\\e[30mbbbbbbb\\e[32mcccc\\e[90mddd\\e[0m\\e[30m\\e[32mc\\e[0m\\e[30mb\\e[0maaa\"\n end\n\n it 'should parse 5' do\n text = TermColor.parse('aabbbbbbbcccccbaaa')\n puts text\n text.should == \"aa\\e[38;5;67mbbbbbbb\\e[48;5;137mccccc\\e[0m\\e[38;5;67mb\\e[0maaa\"\n end\n\n it 'should parse 6' do\n text = TermColor.parse('aabbbbbbbcccccbaaa')\n puts text\n text.should == \"aa\\e[38;5;244mbbbbbbb\\e[48;5;238mccccc\\e[0m\\e[38;5;244mb\\e[0maaa\"\n end\n\n it 'should raise Error' do\n lambda{ TermColor.parse('aaaaaaaaaaaaaaa') }.should raise_error(REXML::ParseException)\n lambda{ TermColor.parse('aaaaaaaaaaaaaaa') }.should_not raise_error(REXML::ParseException)\n end\n\n it 'should escape text' do\n TermColor.escape('<>&\"\\'').should == \"<>&"'\"\n end\n\n it 'should unescape text' do\n TermColor.unescape(\"<>&"'\").should == '<>&\"\\''\n end\n\n it 'should prepare parse' do\n TermColor.prepare_parse(\"<10>10\").should == '<_10>10'\n TermColor.prepare_parse(\"<32>10\").should == '<_32>10'\n end\n\n it 'should convert to escape sequence' do\n listener = TermColor::MyListener.new\n listener.to_esc_seq('red').should == \"\\e[31m\"\n listener.to_esc_seq('on_red').should == \"\\e[41m\"\n listener.to_esc_seq('foo').should == nil\n listener.to_esc_seq('0').should == \"\\e[0m\"\n listener.to_esc_seq('31').should == \"\\e[31m\"\n listener.to_esc_seq('031').should == \"\\e[031m\"\n listener.to_esc_seq('_0').should == \"\\e[0m\"\n listener.to_esc_seq('_31').should == \"\\e[31m\"\n end\n\n it 'should do colorize' do\n TermColor.colorize('test', :green).should == \"\\e[32mtest\\e[0m\"\n end\n\n it 'should make separate tags for combined-style tag' do\n h = { \"hello, world\" =>\n \"hello, world\",\n \"hello, world\" =>\n \"hello, world\",\n \"hello\" =>\n \"hello\",\n \"hellotermcolor\" =>\n \"hellotermcolor\" }\n h.each_pair do |combined, separated|\n TermColor.prepare_parse(combined).should == separated\n end\n end\n\n it 'should do colorize using String#termcolor' do\n \"ruby\".termcolor.should == \"\\e[31mruby\\e[0m\"\n \"ruby\".termcolor(:red).should == \"ruby\".termcolor\n \"ruby isn't ruby gem\".termcolor(:red, 11..14).should == \"ruby isn't ruby gem\".termcolor\n \"ruby isn't ruby gem\".termcolor(:red, 'ruby').should == \"ruby isn't ruby gem\".termcolor\n \"ruby isn't ruby gem\".termcolor(:red, :ruby).should == \"ruby isn't ruby gem\".termcolor\n \"Ruby isn't Ruby Gem\".termcolor(:red, '[A-Z]+').should == \"Ruby isn't Ruby Gem\".termcolor\n end\n end\nend\n"}} -{"repo": "daaku/nodejs-dotaccess", "pr_number": 3, "title": "Prevent dotaccess lib from throwing exception in browser.", "state": "closed", "merged_at": null, "additions": 9, "deletions": 3, "files_changed": ["lib/dotaccess.js"], "files_before": {"lib/dotaccess.js": "module.exports.set = set\nmodule.exports.unset = unset\nmodule.exports.get = get\n\nfunction parts(key) {\n if (Array.isArray(key)) return key\n return key.split('.')\n}\n\nfunction lookup(obj, key) {\n key = parts(key)\n var lastKey = key.pop()\n for (var i=0, l=key.length; i true\n# field_is_unique :scope => [:other_field, :another_other_field]\nclass Predicates::Unique < Predicates::Base\n attr_accessor :case_sensitive\n attr_accessor :scope\n\n def initialize(attribute, options = {})\n defaults = {\n :scope => [],\n :case_sensitive => false\n }\n super attribute, defaults.merge(options)\n end\n\n def error_message\n @error_message || :taken\n end\n\n def validate(value, record) \n klass = record.class\n \n # merge all the scope fields with this one. they must all be unique together.\n # no special treatment -- case sensitivity applies to all or none.\n values = [scope].flatten.collect{ |attr| [attr, record.send(attr)] }\n values << [@attribute, value]\n\n sql = values.map do |(attr, attr_value)|\n comparison_for(attr, attr_value, klass)\n end\n\n unless record.new_record?\n sql << klass.send(:sanitize_sql, [\"#{klass.quoted_table_name}.#{klass.primary_key} <> ?\", record.id])\n end\n\n !klass.where(sql.join(\" AND \")).exists?\n end\n \n protected\n \n def comparison_for(field, value, klass)\n quoted_field = \"#{klass.quoted_table_name}.#{klass.connection.quote_column_name(field)}\"\n\n if klass.columns_hash[field.to_s].text?\n if case_sensitive\n # case sensitive text comparison in any database\n klass.send(:sanitize_sql, [\"#{quoted_field} #{klass.connection.case_sensitive_equality_operator} ?\", value])\n elsif mysql?(klass.connection)\n # case INsensitive text comparison in mysql - yes this is a database specific optimization. i'm always open to better ways. :)\n klass.send(:sanitize_sql, [\"#{quoted_field} = ?\", value])\n else\n # case INsensitive text comparison in most databases\n klass.send(:sanitize_sql, [\"LOWER(#{quoted_field}) = ?\", value.to_s.downcase])\n end\n else\n # non-text comparison\n klass.send(:sanitize_sql, {field => value})\n end\n end\n \n def mysql?(connection)\n (defined?(ActiveRecord::ConnectionAdapters::MysqlAdapter) and connection.is_a?(ActiveRecord::ConnectionAdapters::MysqlAdapter)) or\n (defined?(ActiveRecord::ConnectionAdapters::Mysql2Adapter) and connection.is_a?(ActiveRecord::ConnectionAdapters::Mysql2Adapter))\n end\nend\n", "lib/semantic_attributes/predicates.rb": "# active record tie-ins\nmodule SemanticAttributes\n module Predicates\n def self.included(base)\n base.class_eval do\n extend ClassMethods\n base.semantic_attributes = SemanticAttributes::Set.new\n attribute_method_suffix '_valid?'\n validate :validate_predicates\n end\n end\n\n def semantic_attributes\n self.class.semantic_attributes\n end\n\n # the validation hook that checks all predicates\n def validate_predicates\n semantic_attributes.each do |attribute|\n applicable_predicates = attribute.predicates.select{|p| validate_predicate?(p)}\n\n next if applicable_predicates.empty?\n\n # skip validations on associations that aren't already loaded\n # note: it's not worth skipping a has_one, since there's no way to distinguish\n # between loaded and absent without a query.\n if reflection = self.class.reflect_on_association(attribute.field.to_sym)\n if reflection.collection?\n next unless self.association(attribute.field).loaded?\n elsif reflection.macro == :belongs_to and self[reflection.foreign_key]\n next unless self.association(attribute.field).loaded?\n end\n end\n\n value = self.send(attribute.field)\n applicable_predicates.each do |predicate|\n if value.blank?\n # it's empty, so add an error or not but either way move along\n self.errors.add(attribute.field, predicate.error) unless predicate.allow_empty?\n next\n end\n\n unless predicate.validate(value, self)\n self.errors.add(attribute.field, predicate.error)\n end\n end\n end\n end\n\n protected\n # Returns true if this attribute would pass validation during the next save.\n # Intended to be called via attribute suffix, like:\n # User#login_valid?\n def attribute_valid?(attr)\n semantic_attributes[attr.to_sym].predicates.all? do |p|\n !validate_predicate?(p) or (self.send(attr).blank? and p.allow_empty?) or p.validate(self.send(attr), self)\n end\n end\n\n # Returns true if the given predicate (for a specific attribute) should be validated.\n def validate_predicate?(predicate)\n case predicate.validate_if\n when Symbol\n return false unless send(predicate.validate_if)\n\n when Proc\n return false unless predicate.validate_if.call(self)\n end\n\n case predicate.validate_on\n when :create\n return false unless new_record?\n\n when :update\n return false if new_record?\n end\n\n true\n end\n\n module ClassMethods\n def semantic_attributes\n @semantic_attributes ||= SemanticAttributes::Set.new\n end\n\n def semantic_attributes=(val)\n @semantic_attributes = val || SemanticAttributes::Set.new\n end\n \n def inherited(klass)\n klass.semantic_attributes = self.semantic_attributes.dup\n super\n end\n\n # Provides sugary syntax for adding and querying predicates\n #\n # The syntax supports the following forms:\n # #{attribute}_is_#{predicate}(options = {})\n # #{attribute}_is_a_#{predicate}(options = {})\n # #{attribute}_is_an_#{predicate}(options = {})\n # #{attribute}_has_#{predicate}(options = {})\n # #{attribute}_has_a_#{predicate}(options = {})\n # #{attribute}_has_an_#{predicate}(options = {})\n #\n # You may also add required-ness into the declaration:\n # #{attribute}_is_a_required_#{predicate}(options = {})\n #\n # If you want to assign a predicate to multiple fields, you may replace the attribute component with the word 'fields', and pass a field list as the first argument, like this:\n # fields_are_#{predicate}(fields = [], options = {})\n #\n # Each form may also have a question mark at the end, to query whether the attribute has the predicate.\n #\n # In order to avoid clashing with other method_missing setups, this syntax is checked *last*, after all other method_missing metaprogramming attempts have failed.\n def method_missing(name, *args)\n begin\n super\n rescue NameError\n if /^(.*)_(is|has|are)_(an?_)?(required_)?([^?]*)(\\?)?$/.match(name.to_s)\n options = args.last.is_a?(Hash) ? args.pop : {}\n options[:or_empty] = false if !$4.nil?\n fields = ($1 == 'fields') ? args.map(&:to_s) : [$1]\n\n predicate = $5\n if $6 == '?'\n self.semantic_attributes[fields.first].has? predicate\n else\n args = [predicate]\n args << options if options\n fields.each do |field|\n # TODO: create a less sugary method that may be used programmatically and takes care of defining the normalization method properly\n define_humanization_method_for field\n define_normalization_method_for field\n self.semantic_attributes[field].add *args\n end\n end\n else\n raise\n end\n end\n end\n\n # Provides a way to pre-validate a single value out of context of\n # an entire record. This is helpful for validating parts of a form\n # before it has been submitted.\n #\n # For values that are (in)valid only in context, such as the common\n # :password_confirmation (which is only valid with a matching :password),\n # additional values may be specified.\n #\n # WARNING: I still have not figured out what to do about differences in\n # validation for new/existing records.\n #\n # Returns first error message if value is expected invalid.\n #\n # Example:\n # User.expected_error_for(:username, \"bob\")\n # => \"has already been taken.\"\n # User.expected_error_for(:username, \"bob2392\")\n # => nil\n # User.expected_error_for(:password_confirmation, \"mismatched\", :password => \"opensesame\")\n # => \"must be the same as password.\"\n def expected_error_for(attribute, value, extra_values = {})\n @record = self.new(extra_values)\n semantic_attributes[attribute.to_sym].predicates.each do |predicate|\n return predicate.error_message unless predicate.validate(value, @record)\n end\n nil\n end\n end\n end\nend\n", "test/test_helper.rb": "ENV[\"RAILS_ENV\"] = \"test\"\n\n# load the support libraries\nrequire 'minitest/autorun'\nrequire 'rubygems'\nrequire 'active_record'\nrequire 'active_record/fixtures'\nrequire 'active_support/time'\n\n# load the code-to-be-tested\nrequire 'semantic_attributes'\n\nTime.zone = 'UTC'\n\n# establish the database connection\nActiveRecord::Base.configurations = YAML::load(IO.read(File.dirname(__FILE__) + '/db/database.yml'))\nActiveRecord::Base.establish_connection(:semantic_attributes_test)\n\n# capture the logging\nActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__) + \"/test.log\")\n\n# load the schema ... silently\nActiveRecord::Migration.verbose = false\nload(File.dirname(__FILE__) + \"/db/schema.rb\")\n\n# load the ActiveRecord models\nrequire File.dirname(__FILE__) + '/db/models'\n\n# configure the TestCase settings\nclass SemanticAttributes::TestCase < ActiveSupport::TestCase\n include ActiveRecord::TestFixtures\n include PluginTestModels\n\n self.use_transactional_fixtures = true\n self.use_instantiated_fixtures = false\n self.fixture_path = File.dirname(__FILE__) + '/fixtures/'\n\n fixtures :all\nend\n\nclass ActiveRecord::Base\n # Aids the management of per-test semantics.\n #\n # Examples:\n #\n # User.stub_semantics_with(:email => :email)\n # User.stub_semantics_with(:email => [:email, :unique])\n # User.stub_semantics_with(:email => {:length => {:above => 5}})\n # User.stub_semantics_with(:email => [:email, {:length => {:above => 5}}])\n def self.stub_semantics_with(attr_predicates = {})\n semantics = SemanticAttributes::Set.new\n attr_predicates.each do |attr, predicates|\n [predicates].flatten.each do |predicate|\n case predicate\n when String, Symbol\n semantics[attr].add(predicate)\n when Hash\n semantics[attr].add(predicate.keys.first, predicate.values.first)\n else\n raise '???'\n end\n end\n end\n\n self.stubs(:semantic_attributes).returns(semantics)\n end\nend\n", "test/unit/validations_test.rb": "require File.expand_path(File.dirname(__FILE__) + '/../test_helper')\n\nclass ValidationsTest < SemanticAttributes::TestCase\n def setup\n User.stub_semantics_with(:login => :required)\n @record = User.new\n @login_required = @record.semantic_attributes['login'].get('required')\n end\n\n def test_validation_hook\n @record.expects(:validate_predicates)\n @record.valid?\n end\n\n def test_validation_errors\n assert !@record.valid?\n assert @record.errors[:login]\n assert_equal ['is required.'], @record.errors[:login]\n end\n\n def test_validate_on_default\n assert_equal :both, @record.semantic_attributes['login'].get('required').validate_on\n end\n\n ##\n ## attr_valid?\n ##\n\n def test_attribute_valid?\n assert !@record.login_valid?\n @record.login = \"foo\"\n assert @record.login_valid?\n end\n\n def test_attribute_valid_with_conditional_validation\n assert !@record.login_valid?\n @record.stubs(:validate_predicate?).returns(false)\n assert @record.login_valid?\n end\n\n ##\n ## validate_predicate?\n ##\n\n def test_validate_predicate_with_validate_if_symbol\n @record.stubs(:no).returns(false)\n @record.stubs(:yes).returns(true)\n\n assert @record.send(:validate_predicate?, @login_required)\n\n @record.semantic_attributes['login'].get('required').validate_if = :no\n assert !@record.send(:validate_predicate?, @login_required)\n\n @record.semantic_attributes['login'].get('required').validate_if = :yes\n assert @record.send(:validate_predicate?, @login_required)\n end\n\n def test_validate_predicate_with_validate_if_proc\n assert @record.send(:validate_predicate?, @login_required)\n\n @record.semantic_attributes['login'].get('required').validate_if = proc {false}\n assert !@record.send(:validate_predicate?, @login_required)\n\n @record.semantic_attributes['login'].get('required').validate_if = proc {true}\n assert @record.send(:validate_predicate?, @login_required)\n end\n\n def test_validate_predicate_with_validate_on_create\n @record = users(:george)\n @record.login = nil\n\n # test assumptions\n assert !@record.new_record?\n assert @record.send(:validate_predicate?, @login_required)\n\n # the test\n @record.semantic_attributes['login'].get('required').validate_on = :create\n assert !@record.send(:validate_predicate?, @login_required)\n end\n\n def test_validate_predicate_with_validate_on_update\n # test assumptions\n assert @record.new_record?\n assert @record.send(:validate_predicate?, @login_required)\n\n # the test\n @record.semantic_attributes['login'].get('required').validate_on = :update\n assert !@record.send(:validate_predicate?, @login_required)\n end\n\n ##\n ## :or_empty\n ##\n\n def test_allow_empty\n User.stub_semantics_with(:login => {:number => {:or_empty => true}})\n\n # empty values should skip the validate method\n predicate = @record.semantic_attributes['login'].get('number')\n predicate.expects(:validate).never\n\n [nil, '', []].each do |empty_value|\n @record.login = empty_value\n assert @record.valid?\n end\n end\n\n def test_disallow_empty\n User.stub_semantics_with(:login => {:number => {:or_empty => false}})\n\n # empty values should skip the validate method\n predicate = @record.semantic_attributes['login'].get('number')\n predicate.expects(:validate).never\n\n [nil, '', []].each do |empty_value|\n @record.login = empty_value\n assert !@record.valid?\n assert @record.errors[:login]\n end\n end\nend\n"}, "files_after": {"lib/predicates/unique.rb": "# Describes an attribute as being unique, possibly within a certain scope.\n#\n# ==Options\n# * :scope [array] - a list of other fields that define the context for uniqueness. it's like defining a multi-column uniqueness constraint.\n# * :case_sensitive [boolean, default false] - whether case matters for uniqueness.\n#\n# ==Examples\n# field_is_unique :case_sensitive => true\n# field_is_unique :scope => [:other_field, :another_other_field]\nclass Predicates::Unique < Predicates::Base\n attr_accessor :case_sensitive\n attr_accessor :scope\n\n def initialize(attribute, options = {})\n defaults = {\n :scope => [],\n :case_sensitive => false\n }\n super attribute, defaults.merge(options)\n end\n\n def error_message\n @error_message || :taken\n end\n\n def validate(value, record)\n klass = record.class\n\n # merge all the scope fields with this one. they must all be unique together.\n # no special treatment -- case sensitivity applies to all or none.\n values = [scope].flatten.collect{ |attr| [attr, record.send(attr)] }\n values << [@attribute, value]\n\n sql = values.map do |(attr, attr_value)|\n comparison_for(attr, attr_value, klass)\n end\n\n unless record.new_record?\n sql << klass.send(:sanitize_sql, [\"#{klass.quoted_table_name}.#{klass.primary_key} <> ?\", record.id])\n end\n\n !klass.where(sql.join(\" AND \")).exists?\n end\n\n protected\n\n def comparison_for(field, value, klass)\n quoted_field = \"#{klass.quoted_table_name}.#{klass.connection.quote_column_name(field)}\"\n\n if klass.columns_hash[field.to_s].text?\n if case_sensitive\n # case sensitive text comparison in any database\n if klass.connection.respond_to?(:case_sensitive_equality_operator)\n # <= Rails 4.1\n comparison = klass.send(:sanitize_sql, [\"#{quoted_field} #{klass.connection.case_sensitive_equality_operator} ?\", value])\n else\n # >= Rails 4.2\n case_sensitive_value = klass.connection.case_sensitive_modifier(value, field)\n case_sensitive_value = case_sensitive_value.to_sql if case_sensitive_value.respond_to?(:to_sql)\n klass.send(:sanitize_sql, [\"#{quoted_field} = ?\", case_sensitive_value])\n end\n elsif mysql?(klass.connection)\n # case INsensitive text comparison in mysql - yes this is a database specific optimization. i'm always open to better ways. :)\n klass.send(:sanitize_sql, [\"#{quoted_field} = ?\", value])\n else\n # case INsensitive text comparison in most databases\n klass.send(:sanitize_sql, [\"LOWER(#{quoted_field}) = ?\", value.to_s.downcase])\n end\n else\n # non-text comparison\n klass.send(:sanitize_sql, [\"#{quoted_field} = ?\", value])\n end\n end\n\n def mysql?(connection)\n (defined?(ActiveRecord::ConnectionAdapters::MysqlAdapter) and connection.is_a?(ActiveRecord::ConnectionAdapters::MysqlAdapter)) or\n (defined?(ActiveRecord::ConnectionAdapters::Mysql2Adapter) and connection.is_a?(ActiveRecord::ConnectionAdapters::Mysql2Adapter))\n end\nend\n", "lib/semantic_attributes/predicates.rb": "# active record tie-ins\nmodule SemanticAttributes\n module Predicates\n def self.included(base)\n base.class_eval do\n extend ClassMethods\n base.semantic_attributes = SemanticAttributes::Set.new\n attribute_method_suffix '_valid?'\n validate :validate_predicates\n end\n end\n\n def semantic_attributes\n self.class.semantic_attributes\n end\n\n # the validation hook that checks all predicates\n def validate_predicates\n semantic_attributes.each do |attribute|\n applicable_predicates = attribute.predicates.select{|p| validate_predicate?(p)}\n\n next if applicable_predicates.empty?\n\n # skip validations on associations that aren't already loaded\n # note: it's not worth skipping a has_one, since there's no way to distinguish\n # between loaded and absent without a query.\n if reflection = self.class.reflect_on_association(attribute.field.to_sym)\n if reflection.collection?\n next unless self.association(attribute.field).loaded?\n elsif reflection.macro == :belongs_to and self[reflection.foreign_key]\n next unless self.association(attribute.field).loaded?\n end\n end\n\n value = self.send(attribute.field)\n applicable_predicates.each do |predicate|\n if value.blank?\n # it's empty, so add an error or not but either way move along\n self.errors.add(attribute.field, predicate.error) unless predicate.allow_empty?\n next\n end\n\n unless predicate.validate(value, self)\n self.errors.add(attribute.field, predicate.error)\n end\n end\n end\n end\n\n protected\n # Returns true if this attribute would pass validation during the next save.\n # Intended to be called via attribute suffix, like:\n # User#login_valid?\n def attribute_valid?(attr)\n semantic_attributes[attr.to_sym].predicates.all? do |p|\n !validate_predicate?(p) or (self.send(attr).blank? and p.allow_empty?) or p.validate(self.send(attr), self)\n end\n end\n\n # Returns true if the given predicate (for a specific attribute) should be validated.\n def validate_predicate?(predicate)\n case predicate.validate_if\n when Symbol\n return false unless send(predicate.validate_if)\n\n when Proc\n return false unless predicate.validate_if.call(self)\n end\n\n case predicate.validate_on\n when :create\n return false unless new_record?\n\n when :update\n return false if new_record?\n end\n\n true\n end\n\n module ClassMethods\n def semantic_attributes\n @semantic_attributes ||= SemanticAttributes::Set.new\n end\n\n def semantic_attributes=(val)\n @semantic_attributes = val || SemanticAttributes::Set.new\n end\n\n def inherited(klass)\n klass.semantic_attributes = self.semantic_attributes.dup\n super\n end\n\n # Provides sugary syntax for adding and querying predicates\n #\n # The syntax supports the following forms:\n # #{attribute}_is_#{predicate}(options = {})\n # #{attribute}_is_a_#{predicate}(options = {})\n # #{attribute}_is_an_#{predicate}(options = {})\n # #{attribute}_has_#{predicate}(options = {})\n # #{attribute}_has_a_#{predicate}(options = {})\n # #{attribute}_has_an_#{predicate}(options = {})\n #\n # You may also add required-ness into the declaration:\n # #{attribute}_is_a_required_#{predicate}(options = {})\n #\n # If you want to assign a predicate to multiple fields, you may replace the attribute component with the word 'fields', and pass a field list as the first argument, like this:\n # fields_are_#{predicate}(fields = [], options = {})\n #\n # Each form may also have a question mark at the end, to query whether the attribute has the predicate.\n #\n # In order to avoid clashing with other method_missing setups, this syntax is checked *last*, after all other method_missing metaprogramming attempts have failed.\n def method_missing(name, *args)\n begin\n super\n rescue NameError\n if /^(.*)_(is|has|are)_(an?_)?(required_)?([^?]*)(\\?)?$/.match(name.to_s)\n options = args.last.is_a?(Hash) ? args.pop : {}\n options[:or_empty] = false if !$4.nil?\n fields = ($1 == 'fields') ? args.map(&:to_s) : [$1]\n\n predicate = $5\n if $6 == '?'\n self.semantic_attributes[fields.first].has? predicate\n else\n args = [predicate]\n args << options if options\n fields.each do |field|\n # TODO: create a less sugary method that may be used programmatically and takes care of defining the normalization method properly\n define_humanization_method_for field\n define_normalization_method_for field\n self.semantic_attributes[field].add *args\n end\n end\n else\n raise\n end\n end\n end\n\n # Provides a way to pre-validate a single value out of context of\n # an entire record. This is helpful for validating parts of a form\n # before it has been submitted.\n #\n # For values that are (in)valid only in context, such as the common\n # :password_confirmation (which is only valid with a matching :password),\n # additional values may be specified.\n #\n # WARNING: I still have not figured out what to do about differences in\n # validation for new/existing records.\n #\n # Returns first error message if value is expected invalid.\n #\n # Example:\n # User.expected_error_for(:username, \"bob\")\n # => \"has already been taken.\"\n # User.expected_error_for(:username, \"bob2392\")\n # => nil\n # User.expected_error_for(:password_confirmation, \"mismatched\", :password => \"opensesame\")\n # => \"must be the same as password.\"\n def expected_error_for(attribute, value, extra_values = {})\n @record = self.new(extra_values)\n semantic_attributes[attribute.to_sym].predicates.each do |predicate|\n return predicate.error_message unless predicate.validate(value, @record)\n end\n nil\n end\n end\n end\nend\n", "test/test_helper.rb": "ENV[\"RAILS_ENV\"] = \"test\"\n\n# load the support libraries\nrequire 'rubygems'\nrequire \"minitest/autorun\"\nrequire \"mocha/mini_test\"\nrequire 'active_record'\nrequire 'active_record/fixtures'\nrequire 'active_support/time'\n\n# load the code-to-be-tested\nrequire 'semantic_attributes'\n\nTime.zone = 'UTC'\n\n# establish the database connection\nActiveRecord::Base.configurations = YAML::load(IO.read(File.dirname(__FILE__) + '/db/database.yml'))\nActiveRecord::Base.establish_connection(:semantic_attributes_test)\n\n# capture the logging\nActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__) + \"/test.log\")\n\n# load the schema ... silently\nActiveRecord::Migration.verbose = false\nload(File.dirname(__FILE__) + \"/db/schema.rb\")\n\n# load the ActiveRecord models\nrequire File.dirname(__FILE__) + '/db/models'\n\n# configure the TestCase settings\nclass SemanticAttributes::TestCase < ActiveSupport::TestCase\n include ActiveRecord::TestFixtures\n include PluginTestModels\n\n self.use_transactional_fixtures = true\n self.use_instantiated_fixtures = false\n self.fixture_path = File.dirname(__FILE__) + '/fixtures/'\n\n fixtures :all\n\n # >= Rails 4.2\n if ActiveSupport.respond_to?(:test_order)\n ActiveSupport.test_order = :random\n end\n\nend\n\nclass ActiveRecord::Base\n # Aids the management of per-test semantics.\n #\n # Examples:\n #\n # User.stub_semantics_with(:email => :email)\n # User.stub_semantics_with(:email => [:email, :unique])\n # User.stub_semantics_with(:email => {:length => {:above => 5}})\n # User.stub_semantics_with(:email => [:email, {:length => {:above => 5}}])\n def self.stub_semantics_with(attr_predicates = {})\n semantics = SemanticAttributes::Set.new\n attr_predicates.each do |attr, predicates|\n [predicates].flatten.each do |predicate|\n case predicate\n when String, Symbol\n semantics[attr].add(predicate)\n when Hash\n semantics[attr].add(predicate.keys.first, predicate.values.first)\n else\n raise '???'\n end\n end\n end\n\n self.stubs(:semantic_attributes).returns(semantics)\n end\nend\n", "test/unit/validations_test.rb": "require File.expand_path(File.dirname(__FILE__) + '/../test_helper')\n\nclass ValidationsTest < SemanticAttributes::TestCase\n def setup\n User.stub_semantics_with(:login => :required)\n @record = User.new\n @login_required = @record.semantic_attributes['login'].get('required')\n end\n\n def test_validation_hook\n @record.expects(:validate_predicates)\n @record.valid?\n end\n\n def test_validation_errors\n assert !@record.valid?\n assert @record.errors[:login]\n assert_equal ['is required.'], @record.errors[:login]\n end\n\n def test_validate_on_default\n assert_equal :both, @record.semantic_attributes['login'].get('required').validate_on\n end\n\n ##\n ## attr_valid?\n ##\n\n def test_attribute_valid?\n assert !@record.login_valid?\n @record.login = \"foo\"\n assert @record.login_valid?\n end\n\n def test_attribute_valid_with_conditional_validation\n assert !@record.login_valid?\n @record.stubs(:validate_predicate?).returns(false)\n assert @record.login_valid?\n end\n\n ##\n ## validate_predicate?\n ##\n\n def test_validate_predicate_with_validate_if_symbol\n @record.stubs(:no).returns(false)\n @record.stubs(:yes).returns(true)\n\n assert @record.send(:validate_predicate?, @login_required)\n\n @record.semantic_attributes['login'].get('required').validate_if = :no\n assert !@record.send(:validate_predicate?, @login_required)\n\n @record.semantic_attributes['login'].get('required').validate_if = :yes\n assert @record.send(:validate_predicate?, @login_required)\n end\n\n def test_validate_predicate_with_validate_if_proc\n assert @record.send(:validate_predicate?, @login_required)\n\n @record.semantic_attributes['login'].get('required').validate_if = proc {false}\n assert !@record.send(:validate_predicate?, @login_required)\n\n @record.semantic_attributes['login'].get('required').validate_if = proc {true}\n assert @record.send(:validate_predicate?, @login_required)\n end\n\n def test_validate_predicate_with_validate_on_create\n @record = users(:george)\n @record.login = nil\n\n # test assumptions\n assert !@record.new_record?\n assert @record.send(:validate_predicate?, @login_required)\n\n # the test\n @record.semantic_attributes['login'].get('required').validate_on = :create\n assert !@record.send(:validate_predicate?, @login_required)\n end\n\n def test_validate_predicate_with_validate_on_update\n # test assumptions\n assert @record.new_record?\n assert @record.send(:validate_predicate?, @login_required)\n\n # the test\n @record.semantic_attributes['login'].get('required').validate_on = :update\n assert !@record.send(:validate_predicate?, @login_required)\n end\n\n ##\n ## :or_empty\n ##\n\n def test_allow_empty\n User.stub_semantics_with(:login => {:number => {:or_empty => true}})\n\n # empty values should skip the validate method\n predicate = @record.semantic_attributes['login'].get('number')\n predicate.expects(:validate).never\n\n [nil, ''].each do |empty_value|\n @record.login = empty_value\n assert @record.valid?\n end\n end\n\n def test_disallow_empty\n User.stub_semantics_with(:login => {:number => {:or_empty => false}})\n\n # empty values should skip the validate method\n predicate = @record.semantic_attributes['login'].get('number')\n predicate.expects(:validate).never\n\n [nil, ''].each do |empty_value|\n @record.login = empty_value\n assert !@record.valid?\n assert @record.errors[:login]\n end\n end\nend\n"}} -{"repo": "bartTC/django-templatesadmin", "pr_number": 13, "title": "Django 1.4 compatibility", "state": "open", "merged_at": null, "additions": 15, "deletions": 16, "files_changed": ["templatesadmin/views.py"], "files_before": {"templatesadmin/views.py": "import os\nimport codecs\nfrom datetime import datetime\nfrom stat import ST_MTIME, ST_CTIME\nfrom re import search\n\nfrom django.conf import settings\nfrom django.contrib.auth.decorators import login_required, user_passes_test\nfrom django.core.exceptions import ImproperlyConfigured\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.core.urlresolvers import reverse\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import render_to_response\nfrom django.template import RequestContext\nfrom django.template.loaders.app_directories import app_template_dirs\nfrom django.utils.translation import ugettext as _\nfrom django.views.decorators.cache import never_cache\n\nfrom templatesadmin.forms import TemplateForm\nfrom templatesadmin import TemplatesAdminException\n\n# Default settings that may be overriden by global settings (settings.py)\nTEMPLATESADMIN_VALID_FILE_EXTENSIONS = getattr(\n settings,\n 'TEMPLATESADMIN_VALID_FILE_EXTENSIONS',\n ('html', 'htm', 'txt', 'css', 'backup',)\n)\n\nTEMPLATESADMIN_GROUP = getattr(\n settings,\n 'TEMPLATESADMIN_GROUP',\n 'TemplateAdmins'\n)\n\nTEMPLATESADMIN_EDITHOOKS = getattr(\n settings,\n 'TEMPLATESADMIN_EDITHOOKS',\n ('templatesadmin.edithooks.dotbackupfiles.DotBackupFilesHook', )\n)\n\nTEMPLATESADMIN_HIDE_READONLY = getattr(\n settings,\n 'TEMPLATESADMIN_HIDE_READONLY',\n False\n)\n\nif str == type(TEMPLATESADMIN_EDITHOOKS):\n TEMPLATESADMIN_EDITHOOKS = (TEMPLATESADMIN_EDITHOOKS,)\n\n_hooks = []\n\nfor path in TEMPLATESADMIN_EDITHOOKS:\n # inspired by django.template.context.get_standard_processors\n i = path.rfind('.')\n module, attr = path[:i], path[i+1:]\n try:\n mod = __import__(module, {}, {}, [attr])\n except ImportError, e:\n raise ImproperlyConfigured('Error importing edithook module %s: \"%s\"' % (module, e))\n try:\n func = getattr(mod, attr)\n except AttributeError:\n raise ImproperlyConfigured('Module \"%s\" does not define a \"%s\" callable request processor' % (module, attr))\n\n _hooks.append(func)\n\nTEMPLATESADMIN_EDITHOOKS = tuple(_hooks)\n\n_fixpath = lambda path: os.path.abspath(os.path.normpath(path))\n\nTEMPLATESADMIN_TEMPLATE_DIRS = getattr(\n settings,\n 'TEMPLATESADMIN_TEMPLATE_DIRS', [\n d for d in list(settings.TEMPLATE_DIRS) + \\\n list(app_template_dirs) if os.path.isdir(d)\n ]\n)\n\nTEMPLATESADMIN_TEMPLATE_DIRS = [_fixpath(dir) for dir in TEMPLATESADMIN_TEMPLATE_DIRS]\n\ndef user_in_templatesadmin_group(user):\n try:\n user.groups.get(name=TEMPLATESADMIN_GROUP)\n return True\n except ObjectDoesNotExist:\n return False\n\n@never_cache\n@user_passes_test(lambda u: user_in_templatesadmin_group(u))\n@login_required\ndef listing(request,\n template_name='templatesadmin/overview.html',\n available_template_dirs=TEMPLATESADMIN_TEMPLATE_DIRS):\n\n template_dict = []\n for templatedir in available_template_dirs:\n for root, dirs, files in os.walk(templatedir):\n for f in sorted([f for f in files if f.rsplit('.')[-1] \\\n in TEMPLATESADMIN_VALID_FILE_EXTENSIONS]):\n full_path = os.path.join(root, f)\n l = {\n 'templatedir': templatedir,\n 'rootpath': root,\n 'abspath': full_path,\n 'modified': datetime.fromtimestamp(os.stat(full_path)[ST_MTIME]),\n 'created': datetime.fromtimestamp(os.stat(full_path)[ST_CTIME]),\n 'writeable': os.access(full_path, os.W_OK)\n }\n\n # Do not fetch non-writeable templates if settings set.\n if (TEMPLATESADMIN_HIDE_READONLY == True and \\\n l['writeable'] == True) or \\\n TEMPLATESADMIN_HIDE_READONLY == False:\n try:\n template_dict += (l,)\n except KeyError:\n template_dict = (l,)\n\n template_context = {\n 'messages': request.user.get_and_delete_messages(),\n 'template_dict': template_dict,\n 'ADMIN_MEDIA_PREFIX': settings.ADMIN_MEDIA_PREFIX,\n }\n\n return render_to_response(template_name, template_context,\n RequestContext(request))\n@never_cache\n@user_passes_test(lambda u: user_in_templatesadmin_group(u))\n@login_required\ndef modify(request,\n path,\n template_name='templatesadmin/edit.html',\n base_form=TemplateForm,\n available_template_dirs=TEMPLATESADMIN_TEMPLATE_DIRS):\n\n template_path = _fixpath(path)\n\n # Check if file is within template-dirs\n if not any([template_path.startswith(templatedir) for templatedir in available_template_dirs]):\n request.user.message_set.create(message=_('Sorry, that file is not available for editing.'))\n return HttpResponseRedirect(reverse('templatesadmin-overview'))\n\n if request.method == 'POST':\n formclass = base_form\n for hook in TEMPLATESADMIN_EDITHOOKS:\n formclass.base_fields.update(hook.contribute_to_form(template_path))\n\n form = formclass(request.POST)\n if form.is_valid():\n content = form.cleaned_data['content']\n\n try:\n for hook in TEMPLATESADMIN_EDITHOOKS:\n pre_save_notice = hook.pre_save(request, form, template_path)\n if pre_save_notice:\n request.user.message_set.create(message=pre_save_notice)\n except TemplatesAdminException, e:\n request.user.message_set.create(message=e.message)\n return HttpResponseRedirect(request.build_absolute_uri())\n\n # Save the template\n try:\n f = open(template_path, 'r')\n file_content = f.read()\n f.close()\n\n # browser tend to strip newlines from \n
            \n
            \n
            \n
            \n\n\n", "www/tupelo-main.js": "(function() {\n var $;\n var __hasProp = Object.prototype.hasOwnProperty;\n\n $ = jQuery;\n\n $(document).ready(function() {\n var ajaxErr, cardClicked, cardPlayed, clearTable, dbg, escapeHtml, eventsOk, gameCreateOk, gameInfoOk, getGameState, getTeamPlayers, hello, leaveOk, leftGame, listGamesOk, listPlayersOk, messageReceived, processEvent, quitOk, registerOk, setState, startOk, stateChanged, states, trickPlayed, tupelo, turnEvent, updateGameLinks, updateGameState, updateHand, updateLists;\n tupelo = {\n game_state: {},\n events: []\n };\n states = {\n initial: {\n show: [\"#register_form\"],\n hide: [\"#quit_form\", \"#games\", \"#players\", \"#my_game\", \"#game\"],\n change: function() {\n var reg;\n reg = $(\"#register_name\");\n reg.addClass(\"initial\");\n reg.val(\"Your name\");\n }\n },\n registered: {\n show: [\"#quit_form\", \"#games\", \"#players\", \"#game_create_form\"],\n hide: [\"#register_form\", \"#my_game\", \"#game\"],\n change: function() {\n if (!(tupelo.list_timer != null)) {\n return tupelo.list_timer = setInterval(updateLists, 5000);\n }\n }\n },\n gameCreated: {\n show: [\"#my_game\"],\n hide: [\"#game_create_form\"]\n },\n inGame: {\n show: [\"#game\"],\n hide: [\"#games\", \"#players\", \"#my_game\"]\n }\n };\n setState = function(state, effectDuration) {\n var elem, st, _i, _j, _len, _len2, _ref, _ref2;\n st = states[state];\n _ref = st.hide;\n for (_i = 0, _len = _ref.length; _i < _len; _i++) {\n elem = _ref[_i];\n $(elem).hide(effectDuration);\n }\n _ref2 = st.show;\n for (_j = 0, _len2 = _ref2.length; _j < _len2; _j++) {\n elem = _ref2[_j];\n $(elem).show(effectDuration);\n }\n if (st.change != null) return st.change();\n };\n escapeHtml = function(str) {\n return str.replace(\"<\", \"<\").replace(\">\", \">\");\n };\n dbg = function() {\n if (T.debug) return $(\"#debug\").html(JSON.stringify(tupelo));\n };\n ajaxErr = function(xhr, astatus, error) {\n var handled, jsonErr;\n handled = false;\n if (xhr.status === 403) {\n jsonErr = eval(\"(\" + xhr.responseText + \")\");\n if (jsonErr.message != null) {\n window.alert(jsonErr.message);\n handled = true;\n }\n } else {\n T.log(\"status: \" + astatus);\n T.log(\"error: \" + error);\n }\n return handled;\n };\n hello = function() {\n return $.ajax({\n url: \"/ajax/hello\",\n success: function(result) {\n T.log(\"Server version: \" + result.version);\n if (result.player != null) {\n tupelo.player = new T.Player(result.player.player_name);\n registerOk(result.player);\n if (result.player.game_id != null) {\n return gameCreateOk(result.player.game_id);\n }\n }\n },\n error: ajaxErr\n });\n };\n updateGameLinks = function(disabledIds) {\n var gameJoinClicked, id, _i, _len;\n gameJoinClicked = function(event) {\n var game_id;\n game_id = this.id.slice(10);\n T.log(\"joining game \" + game_id);\n return $.ajax({\n url: \"/ajax/game/enter\",\n data: {\n akey: tupelo.player.akey,\n game_id: game_id\n },\n success: gameCreateOk,\n error: ajaxErr\n });\n };\n if (tupelo.game_id != null) {\n $(\"button.game_join\").attr(\"disabled\", true);\n return $(\"tr#game_id_\" + tupelo.game_id).addClass(\"highlight\");\n } else {\n for (_i = 0, _len = disabledIds.length; _i < _len; _i++) {\n id = disabledIds[_i];\n $(\"button#\" + id).attr(\"disabled\", true);\n }\n return $(\"button.game_join\").click(gameJoinClicked);\n }\n };\n listGamesOk = function(result) {\n var disabledIds, game_id, html, players, res;\n html = \"\";\n disabledIds = [];\n for (game_id in result) {\n if (!__hasProp.call(result, game_id)) continue;\n html += \"\";\n players = (function() {\n var _i, _len, _ref, _results;\n _ref = result[game_id];\n _results = [];\n for (_i = 0, _len = _ref.length; _i < _len; _i++) {\n res = _ref[_i];\n _results.push(new T.Player().fromObj(res).player_name);\n }\n return _results;\n })();\n html += \"\" + escapeHtml(players.join(\", \")) + \"\";\n html += \"\";\n html += \"\";\n if (players.length === 4) disabledIds.push(\"game_join_\" + game_id);\n }\n $(\"#game_list table tbody\").html(html);\n updateGameLinks(disabledIds);\n return dbg();\n };\n listPlayersOk = function(result) {\n var cls, html, player, plr;\n T.log(result);\n html = \"\";\n for (player in result) {\n if (!__hasProp.call(result, player)) continue;\n plr = new T.Player().fromObj(result[player]);\n if (plr.id !== tupelo.player.id) {\n cls = plr.game_id != null ? \"class=\\\"in_game\\\" \" : \"\";\n html += (\"\";\n html += \"\" + escapeHtml(plr.player_name) + \"\";\n }\n }\n $(\"#player_list table tbody\").html(html);\n return dbg();\n };\n registerOk = function(result) {\n $(\"#name\").val(\"\");\n tupelo.player.id = result.id;\n tupelo.player.akey = result.akey;\n $.cookie(\"akey\", result.akey);\n T.log(tupelo);\n dbg();\n $(\"#game_list table tbody\").html(\"\");\n $(\".my_name\").html(escapeHtml(tupelo.player.player_name));\n updateLists();\n setState(\"registered\", \"fast\");\n return T.log(\"timer created\");\n };\n leftGame = function() {\n if (tupelo.event_fetch_timer != null) {\n tupelo.event_fetch_timer.disable();\n tupelo.event_fetch_timer = null;\n }\n if (tupelo.event_timer != null) {\n clearTimeout(tupelo.event_timer);\n tupelo.event_timer = null;\n }\n tupelo.game_id = null;\n tupelo.game_state = {};\n tupelo.hand = null;\n tupelo.my_turn = null;\n };\n leaveOk = function(result) {\n leftGame();\n dbg();\n updateLists();\n return setState(\"registered\", \"fast\");\n };\n quitOk = function(result) {\n leftGame();\n if (tupelo.list_timer != null) {\n clearInterval(tupelo.list_timer);\n tupelo.list_timer = null;\n }\n $.cookie(\"akey\", null);\n tupelo.player = null;\n T.log(tupelo);\n dbg();\n return setState(\"initial\", \"fast\");\n };\n gameCreateOk = function(result) {\n tupelo.game_id = result;\n T.log(tupelo);\n dbg();\n $(\"p#joined_game\").html(\"joined game \" + tupelo.game_id);\n setState(\"gameCreated\", \"fast\");\n tupelo.event_fetch_timer = new T.Timer(\"/ajax/get_events\", 2000, eventsOk, {\n data: {\n akey: tupelo.player.akey\n }\n });\n return updateLists();\n };\n cardPlayed = function(event) {\n var card, table;\n T.log(\"cardPlayed\");\n table = $(\"#player_\" + event.player.id + \" .table\");\n if (table.length === 0) {\n T.log(\"player not found!\");\n return true;\n }\n card = new T.Card(event.card.suit, event.card.value);\n table.html(\"\" + card.toShortHtml() + \"\");\n table.children().show(500);\n setTimeout(processEvent, 500);\n return false;\n };\n messageReceived = function(event) {\n var eventLog;\n T.log(\"messageReceived\");\n eventLog = $(\"#event_log\");\n eventLog.append(escapeHtml(event.sender) + \": \" + escapeHtml(event.message) + \"\\n\");\n eventLog.scrollTop(eventLog[0].scrollHeight - eventLog.height());\n return true;\n };\n clearTable = function() {\n clearTimeout(tupelo.clear_timeout);\n T.log(\"clearing table\");\n $(\"#game_area .table\").html(\"\");\n $(\"#game_area table tbody\").unbind(\"click\");\n return tupelo.event_timer = setTimeout(processEvent, 0);\n };\n trickPlayed = function(event) {\n T.log(\"trickPlayed\");\n $(\"#game_area table tbody\").click(clearTable);\n tupelo.clear_timeout = setTimeout(clearTable, 5000);\n return false;\n };\n getTeamPlayers = function(team) {\n return [$(\"#table_\" + team + \" .player_name\").html(), $(\"#table_\" + (team + 2) + \" .player_name\").html()];\n };\n updateGameState = function(state) {\n var key, statusStr;\n statusStr = \"\";\n for (key in state) {\n if (!__hasProp.call(state, key)) continue;\n tupelo.game_state[key] = state[key];\n }\n if (state.state === T.VOTING) {\n statusStr = \"VOTING\";\n } else if (state.state === T.ONGOING) {\n if (state.mode === T.NOLO) {\n statusStr = \"NOLO\";\n } else {\n if (state.mode === T.RAMI) statusStr = \"RAMI\";\n }\n }\n statusStr = \"\" + statusStr + \"\";\n statusStr += \"tricks: \" + state.tricks[0] + \" - \" + state.tricks[1] + \"\";\n if (state.score != null) {\n if (state.score[0] > 0) {\n statusStr += \"score: \" + escapeHtml(getTeamPlayers(0).join(\" & \")) + \": \" + state.score[0] + \"\";\n } else if (state.score[1] > 0) {\n statusStr += \"score: \" + escapeHtml(getTeamPlayers(1).join(\" & \")) + \": \" + state.score[1] + \"\";\n } else {\n statusStr += \"score: 0\";\n }\n }\n $(\"#game_status\").html(statusStr);\n if (state.turn_id != null) {\n $(\".player_data .player_name\").removeClass(\"highlight_player\");\n $(\"#player_\" + state.turn_id + \" .player_name\").addClass(\"highlight_player\");\n }\n return dbg();\n };\n cardClicked = function(event) {\n var card, cardId;\n cardId = $(this).find(\".card\").attr(\"id\").slice(5);\n card = tupelo.hand[cardId];\n T.log(card);\n if (card != null) {\n $.ajax({\n url: \"/ajax/game/play_card\",\n success: function(result) {\n tupelo.my_turn = false;\n $(\"#hand .card\").removeClass(\"card_selectable\");\n return getGameState();\n },\n error: function(xhr, astatus, error) {\n if (ajaxErr(xhr, astatus, error) !== true) {\n return window.alert(xhr.status + \" \" + error);\n }\n },\n data: {\n akey: tupelo.player.akey,\n game_id: tupelo.game_id,\n card: JSON.stringify(card)\n }\n });\n }\n return event.preventDefault();\n };\n updateHand = function(newHand) {\n var card, hand, html, i, item, _len;\n html = \"\";\n hand = [];\n for (i = 0, _len = newHand.length; i < _len; i++) {\n item = newHand[i];\n card = new T.Card(item.suit, item.value);\n hand.push(card);\n if (tupelo.my_turn) html += \"\";\n html += (\"\") + card.toShortHtml() + \"\";\n if (tupelo.my_turn) html += \"\";\n }\n tupelo.hand = hand;\n $(\"#hand\").html(html);\n if (tupelo.my_turn) {\n $(\"#hand .card\").addClass(\"card_selectable\");\n return $(\"#hand a\").click(cardClicked);\n }\n };\n getGameState = function() {\n return $.ajax({\n url: \"/ajax/game/get_state\",\n success: function(result) {\n T.log(result);\n if (result.game_state != null) updateGameState(result.game_state);\n if (result.hand != null) return updateHand(result.hand);\n },\n error: ajaxErr,\n data: {\n akey: tupelo.player.akey,\n game_id: tupelo.game_id\n }\n });\n };\n turnEvent = function(event) {\n T.log(\"turnEvent\");\n tupelo.my_turn = true;\n getGameState();\n return true;\n };\n stateChanged = function(event) {\n T.log(\"stateChanged\");\n if (event.game_state.state === T.VOTING) {\n startOk();\n } else if (event.game_state.state === T.ONGOING) {\n $(\"#game_area table tbody\").click(clearTable);\n tupelo.clear_timeout = setTimeout(clearTable, 5000);\n return false;\n }\n return true;\n };\n processEvent = function() {\n var event, handled;\n handled = true;\n if (tupelo.events.length === 0) {\n T.log(\"no events to process\");\n tupelo.event_timer = null;\n return;\n }\n event = tupelo.events.shift();\n if (event.game_state != null) updateGameState(event.game_state);\n switch (event.type) {\n case 1:\n handled = cardPlayed(event);\n break;\n case 2:\n handled = messageReceived(event);\n break;\n case 3:\n handled = trickPlayed(event);\n break;\n case 4:\n handled = turnEvent(event);\n break;\n case 5:\n handled = stateChanged(event);\n break;\n default:\n T.log(\"unknown event \" + event.type);\n }\n if (handled === true) {\n return tupelo.event_timer = setTimeout(processEvent, 0);\n }\n };\n eventsOk = function(result) {\n /*\n if (result.length > 0)\n eventLog = $(\"#event_log\")\n eventLog.append(JSON.stringify(result) + \"\\n\")\n eventLog.scrollTop(eventLog[0].scrollHeight - eventLog.height())\n */\n var event, _i, _len;\n for (_i = 0, _len = result.length; _i < _len; _i++) {\n event = result[_i];\n tupelo.events.push(event);\n }\n if (tupelo.events.length > 0 && !(tupelo.event_timer != null)) {\n tupelo.event_timer = setTimeout(processEvent, 0);\n }\n return dbg();\n };\n gameInfoOk = function(result) {\n var i, index, myIndex, pl, _len, _len2;\n T.log(\"gameInfoOk\");\n T.log(result);\n myIndex = 0;\n for (i = 0, _len = result.length; i < _len; i++) {\n pl = result[i];\n if (pl.id === tupelo.player.id) {\n myIndex = i;\n break;\n }\n }\n for (i = 0, _len2 = result.length; i < _len2; i++) {\n pl = result[i];\n index = (4 + i - myIndex) % 4;\n $(\"#table_\" + index + \" .player_data\").attr(\"id\", \"player_\" + pl.id);\n $(\"#player_\" + pl.id + \" .player_name\").html(escapeHtml(pl.player_name));\n }\n };\n startOk = function(result) {\n if (tupelo.list_timer != null) {\n clearInterval(tupelo.list_timer);\n tupelo.list_timer = null;\n }\n $(\"#event_log\").html(\"\");\n setState(\"inGame\");\n $.ajax({\n url: \"/ajax/game/get_info\",\n success: gameInfoOk,\n error: ajaxErr,\n data: {\n game_id: tupelo.game_id\n }\n });\n getGameState();\n return dbg();\n };\n updateLists = function() {\n $.ajax({\n url: \"/ajax/game/list\",\n success: listGamesOk,\n error: ajaxErr\n });\n return $.ajax({\n url: \"/ajax/player/list\",\n success: listPlayersOk,\n error: ajaxErr,\n data: {\n akey: tupelo.player.akey\n }\n });\n };\n $(\"#echo_ajax\").click(function() {\n var text;\n text = $(\"#echo\").val();\n return $.ajax({\n url: \"/ajax/echo\",\n data: {\n test: text\n },\n success: function(result) {\n $(\"#echo_result\").html(escapeHtml(result));\n return $(\"#echo\").val(\"\");\n },\n error: ajaxErr\n });\n });\n $(\"#register_btn\").click(function() {\n var input, name;\n input = $(\"#register_name\");\n name = input.val();\n if (!name || input.hasClass(\"initial\")) {\n alert(\"Please enter your name first\");\n return;\n }\n tupelo.player = new T.Player(name);\n T.log(tupelo);\n return $.ajax({\n url: \"/ajax/player/register\",\n data: {\n player: JSON.stringify(tupelo.player)\n },\n success: registerOk,\n error: ajaxErr\n });\n });\n $(\"#register_name\").keyup(function(event) {\n if ((event.keyCode || event.which) === 13) return $(\"#register_btn\").click();\n });\n $(\"#register_name\").focus(function(event) {\n if ($(this).hasClass(\"initial\")) {\n $(this).val(\"\");\n return $(this).removeClass(\"initial\");\n }\n });\n $(\"#quit_btn\").click(function() {\n return $.ajax({\n url: \"/ajax/player/quit\",\n data: {\n akey: tupelo.player.akey\n },\n success: quitOk,\n error: function(xhr, astatus, error) {\n if (ajaxErr(xhr, astatus, error) === true) return quitOk();\n }\n });\n });\n $(\".game_leave_btn\").click(function() {\n return $.ajax({\n url: \"/ajax/game/leave\",\n data: {\n akey: tupelo.player.akey,\n game_id: tupelo.game_id\n },\n success: leaveOk,\n error: function(xhr, astatus, error) {\n if (ajaxErr(xhr, astatus, error) === true) return leaveOk();\n }\n });\n });\n $(\"#game_create_btn\").click(function() {\n return $.ajax({\n url: \"/ajax/game/create\",\n data: {\n akey: tupelo.player.akey\n },\n success: gameCreateOk,\n error: ajaxErr\n });\n });\n $(\"#game_start\").click(function() {\n return $.ajax({\n url: \"/ajax/game/start\",\n data: {\n akey: tupelo.player.akey,\n game_id: tupelo.game_id\n },\n success: startOk,\n error: ajaxErr\n });\n });\n $(\"#game_start_with_bots\").click(function() {\n return $.ajax({\n url: \"/ajax/game/start_with_bots\",\n data: {\n akey: tupelo.player.akey,\n game_id: tupelo.game_id\n },\n success: startOk,\n error: ajaxErr\n });\n });\n if (T.debug === true) {\n $(\"#debug\").click(function() {\n return $(this).toggle();\n });\n } else {\n $(\"#debug\").hide();\n }\n $(window).unload(function() {\n if (tupelo.game_id != null) {\n return $.ajax({\n url: \"/ajax/game/leave\",\n async: false,\n data: {\n akey: tupelo.player.akey,\n game_id: tupelo.game_id\n }\n });\n }\n });\n window.onbeforeunload = function(e) {\n var msg;\n if (!(tupelo.game_id != null)) return undefined;\n e = e || window.event;\n msg = \"By leaving the page you will also leave the game.\";\n if (e) e.returnValue = msg;\n return msg;\n };\n hello();\n return setState(\"initial\");\n });\n\n}).call(this);\n"}, "files_after": {"tests/test_common.py": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# vim: set sts=4 sw=4 et:\n\nimport unittest\nfrom tupelo import rpc\nfrom tupelo import common\nfrom tupelo.common import Card, CardSet\nimport threading\nimport copy\nimport time\n\nclass SyncTester(object):\n\n def __init__(self):\n self.lock = threading.Lock()\n self.counter = 0\n\n @common.synchronized_method('lock')\n def sync(self):\n assert self.counter == 0, 'oops, @synchronized_method did not work. '\\\n 'counter is %d' % self.counter\n self.counter += 1\n time.sleep(1)\n assert self.counter == 1, 'oops, @synchronized_method did not work. '\\\n 'counter is %d' % self.counter\n time.sleep(1)\n self.counter -= 1\n assert self.counter == 0, 'oops, @synchronized_method did not work. '\\\n 'counter is %d' % self.counter\n return True\n\n\nclass TestCommon(unittest.TestCase):\n\n def testSuitGlobals(self):\n self.assertTrue(common.HEART > common.CLUB)\n self.assertTrue(common.CLUB > common.DIAMOND)\n self.assertTrue(common.DIAMOND > common.SPADE)\n\n def testSuitRPC(self):\n heart = common.HEART\n encoded = rpc.rpc_encode(heart)\n self.assertEqual(encoded, 3)\n decoded = rpc.rpc_decode(common.Suit, encoded)\n self.assertTrue(isinstance(decoded, common.Suit))\n self.assertEqual(heart.value, decoded.value)\n self.assertEqual(heart.name, decoded.name)\n\n def testCardRPC(self):\n card = Card(common.HEART, 5)\n encoded = rpc.rpc_encode(card)\n self.assertEqual(encoded, {'suit': 3, 'value': 5})\n self.assertFalse(isinstance(encoded, common.Card))\n decoded = rpc.rpc_decode(common.Card, encoded)\n self.assertTrue(isinstance(decoded, common.Card))\n self.assertEqual(card, decoded)\n\n def testCardSet(self):\n deck = CardSet.new_full_deck()\n self.assertTrue(len(deck) == 52)\n for suit in common.ALL_SUITS:\n cards = deck.get_cards(suit=common.HEART)\n self.assertTrue(len(cards) == 13)\n\n for i in range(2, 15):\n cards = deck.get_cards(value=i)\n self.assertTrue(len(cards) == 4)\n\n deck.clear()\n self.assertTrue(len(deck) == 0)\n\n def testCardSetHighest(self):\n cs = CardSet()\n cs.append(Card(common.HEART, 5))\n cs.append(Card(common.HEART, 7))\n cs.append(Card(common.HEART, 11))\n hi = cs.get_highest()\n self.assertEqual(hi.value, 11)\n hi = cs.get_highest(roof=9)\n self.assertEqual(hi.value, 7)\n hi = cs.get_highest(roof=7)\n self.assertEqual(hi.value, 7)\n hi = cs.get_highest(roof=2)\n self.assertTrue(hi is None)\n hi = cs.get_highest(floor=12)\n self.assertTrue(hi is None)\n\n def testCardSetLowest(self):\n cs = CardSet()\n cs.append(Card(common.HEART, 5))\n cs.append(Card(common.HEART, 7))\n cs.append(Card(common.HEART, 11))\n lo = cs.get_lowest()\n self.assertEqual(lo.value, 5)\n lo = cs.get_lowest(floor=9)\n self.assertEqual(lo.value, 11)\n lo = cs.get_lowest(floor=7)\n self.assertEqual(lo.value, 7)\n lo = cs.get_lowest(floor=12)\n self.assertTrue(lo is None)\n lo = cs.get_lowest(roof=2)\n self.assertTrue(lo is None)\n\n def testCardSetSort(self):\n cs = CardSet()\n cs.append(Card(common.HEART, 7))\n cs.append(Card(common.SPADE, 7))\n cs.append(Card(common.HEART, 5))\n cs.sort()\n sorted_cs = CardSet()\n sorted_cs.append(Card(common.SPADE, 7))\n sorted_cs.append(Card(common.HEART, 5))\n sorted_cs.append(Card(common.HEART, 7))\n self.assertEqual(cs, sorted_cs)\n\n def testGameStateRPC(self):\n gs = common.GameState()\n gs.table.append(Card(common.HEART, 5))\n encoded = rpc.rpc_encode(gs)\n gs2 = rpc.rpc_decode(common.GameState, encoded)\n self.assertTrue(isinstance(gs2, common.GameState))\n self.assertTrue(isinstance(gs2.table, gs.table.__class__))\n self.assertEqual(len(gs2.table), len(gs.table))\n self.assertEqual(gs2.table, gs.table)\n\n def testShortUUID(self):\n suuid = common.short_uuid()\n self.assertTrue(isinstance(suuid, str))\n suuid2 = common.short_uuid()\n self.assertNotEqual(suuid, suuid2)\n\n def testSynchronizedMethod(self):\n synctester = SyncTester()\n def _runner():\n synctester.sync()\n\n threads = []\n for i in range(4):\n thread = threading.Thread(None, _runner)\n threads.append(thread)\n thread.start()\n\n for thread in threads:\n thread.join(5.0)\n\nif __name__ == '__main__':\n unittest.main()\n", "tests/test_events.py": "#!/usr/bin/env python\n# vim: set sts=4 sw=4 et:\n\nimport unittest\nfrom tupelo import events\nfrom tupelo import rpc\nfrom tupelo import common\nfrom tupelo import players\n\nclass TestEventsRPC(unittest.TestCase):\n\n def testEvent(self, cls=None):\n cls = events.Event\n e = cls()\n e2 = rpc.rpc_decode(events.Event, rpc.rpc_encode(e))\n self.assertTrue(isinstance(e2, cls))\n self.assertEqual(e.type, e2.type)\n\n def testCardPlayedEmpty(self):\n cls = events.CardPlayedEvent\n e = cls()\n e2 = rpc.rpc_decode(events.Event, rpc.rpc_encode(e))\n self.assertTrue(isinstance(e2, cls))\n self.assertEqual(e.type, e2.type)\n\n def testCardPlayed(self):\n cls = events.CardPlayedEvent\n plr = players.Player('Seppo')\n card = common.Card(common.HEART, 5)\n e = cls(plr, card)\n e2 = rpc.rpc_decode(events.Event, rpc.rpc_encode(e))\n self.assertTrue(isinstance(e2, cls))\n self.assertEqual(e.type, e2.type)\n self.assertEqual(e.player.player_name, e2.player.player_name)\n self.assertEqual(e.card, e2.card)\n self.assertEqual(e2.game_state, None)\n\n def testMessageEmpty(self):\n cls = events.MessageEvent\n e = cls()\n e2 = rpc.rpc_decode(events.Event, rpc.rpc_encode(e))\n self.assertTrue(isinstance(e2, cls))\n self.assertEqual(e.type, e2.type)\n\n def testMessage(self):\n e = events.MessageEvent('from', 'lorem ipsum')\n e2 = rpc.rpc_decode(events.Event, rpc.rpc_encode(e))\n self.assertTrue(isinstance(e2, events.MessageEvent))\n self.assertEqual(e.type, e2.type)\n self.assertEqual(e.sender, e2.sender)\n self.assertEqual(e.message, e2.message)\n\n def testStateChanged(self):\n cls = events.StateChangedEvent\n game_state = common.GameState()\n game_state.status = common.GameState.VOTING\n e = cls(game_state)\n self.assertTrue(e.game_state is not None)\n e2 = rpc.rpc_decode(events.Event, rpc.rpc_encode(e))\n self.assertTrue(isinstance(e2, cls))\n self.assertEqual(e.type, e2.type)\n self.assertEqual(e.game_state, e2.game_state)\n\n def testEventListEmpty(self):\n el = events.EventList()\n self.assertEqual(len(el), 0)\n el2 = rpc.rpc_decode(events.EventList, rpc.rpc_encode(el))\n self.assertTrue(isinstance(el2, events.EventList))\n self.assertEqual(len(el2), 0)\n\n def testEventList(self):\n el = events.EventList()\n el.append(events.MessageEvent('a', 'b'))\n el.append(events.MessageEvent('c', 'd'))\n num = len(el)\n self.assertEqual(num, 2)\n el2 = rpc.rpc_decode(events.EventList, rpc.rpc_encode(el))\n self.assertTrue(isinstance(el2, events.EventList))\n self.assertEqual(len(el2), num)\n for i in range(0, num):\n self.assertEqual(el[i], el2[i])\n\n\nif __name__ == '__main__':\n unittest.main()\n", "tests/test_players.py": "#!/usr/bin/env python\n# vim: set sts=4 sw=4 et:\n\nimport unittest\nimport time\nfrom tupelo import players\nfrom tupelo.common import GameState\n\nclass TestPlayers(unittest.TestCase):\n\n def testThreadedPlayer(self):\n plr = players.ThreadedPlayer('Seppo')\n plr.start()\n self.assertTrue(plr.is_alive())\n plr.game_state.status = GameState.STOPPED\n plr.act(None, None)\n plr.join(5.0) # wait until the thread quits\n self.assertFalse(plr.is_alive())\n\n def testThreadedPlayerStop(self):\n plr = players.ThreadedPlayer('Seppo')\n plr.start()\n time.sleep(0.5)\n self.assertTrue(plr.is_alive())\n plr.stop()\n plr.join(5.0) # wait until the thread quits\n self.assertFalse(plr.is_alive())\n\n def testThreadedPlayerRestart(self):\n plr = players.ThreadedPlayer('Seppo')\n plr.start()\n time.sleep(0.5)\n self.assertTrue(plr.is_alive())\n # trying to start again while running should raise an exception\n self.assertRaises(RuntimeError, plr.start)\n plr.stop()\n plr.join(5.0) # wait until the thread quits\n self.assertFalse(plr.is_alive())\n # restart\n plr.start()\n time.sleep(0.5)\n self.assertTrue(plr.is_alive())\n plr.stop()\n plr.join(5.0) # wait until the thread quits\n self.assertFalse(plr.is_alive())\n\n\nif __name__ == '__main__':\n unittest.main()\n", "tests/test_rpc.py": "#!/usr/bin/env python\n# vim: set sts=4 sw=4 et:\n\nimport unittest\nfrom tupelo import rpc\n\nclass _RPCTestClass(rpc.RPCSerializable):\n rpc_attrs = ('a', 'b')\n a = 1\n b = '2'\n\nclass _CustomClass(object):\n def rpc_encode(self):\n return 'hilipati'\n\n @classmethod\n def rpc_decode(cls, _rpcobj):\n return 'joop'\n\nclass TestRPC(unittest.TestCase):\n\n def testSerializeSimple(self):\n testobj = _RPCTestClass()\n encoded = rpc.rpc_encode(testobj)\n self.assertEqual(encoded, {'a':1, 'b':'2'})\n # change something\n encoded['a'] = 2\n decoded = rpc.rpc_decode(_RPCTestClass, encoded)\n self.assertTrue(isinstance(decoded, _RPCTestClass))\n self.assertEqual(decoded.a, 2)\n\n def testDecodeAttr(self):\n testobj = _RPCTestClass()\n encoded = rpc.rpc_encode(testobj)\n self.assertEqual(encoded, {'a':1, 'b':'2'})\n decoded = _RPCTestClass()\n decoded.rpc_decode_attr(encoded, 'b')\n self.assertEqual(decoded.b, '2')\n\n def testSerializableEqual(self):\n testobj1 = _RPCTestClass()\n testobj2 = _RPCTestClass()\n self.assertEqual(testobj1, testobj2)\n self.assertFalse(testobj1 != testobj2)\n decoded1 = rpc.rpc_decode(_RPCTestClass, rpc.rpc_encode(testobj1))\n decoded2 = rpc.rpc_decode(_RPCTestClass, rpc.rpc_encode(testobj2))\n self.assertEqual(decoded1, decoded2)\n self.assertFalse(decoded1 != decoded2)\n\n def testSerializableEqualWrongType(self):\n testobj1 = _RPCTestClass()\n self.assertNotEqual(testobj1, [])\n self.assertTrue(testobj1 != [])\n self.assertNotEqual(testobj1, 'wrong type')\n self.assertNotEqual(testobj1, None)\n\n def testSerializableNotEqual(self):\n testobj1 = _RPCTestClass()\n testobj2 = _RPCTestClass()\n testobj2.a = 0\n self.assertNotEqual(testobj1, testobj2)\n self.assertFalse(testobj1 == testobj2)\n decoded1 = rpc.rpc_decode(_RPCTestClass, rpc.rpc_encode(testobj1))\n decoded2 = rpc.rpc_decode(_RPCTestClass, rpc.rpc_encode(testobj2))\n self.assertNotEqual(decoded1, decoded2)\n self.assertFalse(decoded1 == decoded2)\n\n def testSerializeCustom(self):\n testobj = _CustomClass()\n encoded = rpc.rpc_encode(testobj)\n self.assertEqual(encoded, 'hilipati')\n decoded = rpc.rpc_decode(_CustomClass, encoded)\n self.assertEqual(decoded, 'joop')\n\n\nif __name__ == '__main__':\n unittest.main()\n", "tests/test_server.py": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# vim: set sts=4 sw=4 et:\n\nimport unittest\nfrom tupelo import rpc\nfrom tupelo.server import TupeloRPCInterface as I\nfrom tupelo.server.jsonapi import TupeloJSONDispatcher as D\nfrom tupelo.players import Player\n\nclass TestTupeloJSONDispatcher(unittest.TestCase):\n\n def testPath2Method(self):\n d = D()\n self.assertEqual(d.json_path_prefix, '/api/') # default\n\n d.json_path_prefix = '/a/'\n self.assertEqual(d.path2method('/a/hello'), 'hello')\n self.assertEqual(d.path2method('/a/hello/again'), 'hello_again')\n self.assertEqual(d.path2method('/a/hello_again'), 'hello_again')\n self.assertEqual(d.path2method('/hello/again'), None)\n\n d.json_path_prefix = None\n self.assertEqual(d.path2method('/hello'), 'hello')\n self.assertEqual(d.path2method('hello'), 'hello')\n self.assertEqual(d.path2method('/hello/there'), 'hello_there')\n self.assertEqual(d.path2method('hello/again'), 'hello_again')\n\n def testParseQString(self):\n d = D()\n d.json_path_prefix = None\n f = d._json_parse_qstring\n self.assertEqual(f('/hello'), ('hello', {}))\n self.assertEqual(f('h?foo=bar'), ('h', {'foo': 'bar'}))\n self.assertEqual(f('h?foo=\"bar\"'), ('h', {'foo': 'bar'}))\n self.assertEqual(f('h?a=1&b=3'), ('h', {'a': 1, 'b': 3}))\n self.assertEqual(f('h?a={\"a\":1, \"b\":[0], \"c\":\"s\"}'), ('h', {'a': {'a':1, 'b':[0], 'c': 's'}}))\n\n def testDispatch(self):\n class MockInterface(object):\n def __init__(self):\n self.callstack = []\n\n def _json_dispatch(self, method, params):\n self.callstack.append((method, params))\n\n mock = MockInterface()\n d = D()\n d.json_path_prefix = '/a/'\n d.register_instance(mock)\n d.json_dispatch('/a/hello', {})\n self.assertEqual(mock.callstack.pop(), ('hello', {}))\n d.json_dispatch('/a/h?a=1&b=2', {})\n self.assertEqual(mock.callstack.pop(), ('h', {'a':1, 'b':2}))\n d.json_dispatch('/a/h?a=1&b=2', {'Cookie': 'akey=b0_S6cNZRFmejfPXV2q6eA'})\n self.assertEqual(mock.callstack.pop(), ('h', {'a':1, 'b':2, 'akey': 'b0_S6cNZRFmejfPXV2q6eA'}))\n\n\nclass TestTupeloRPCInterface(unittest.TestCase):\n\n def _encoded_player(self, name='m\u00f6rk\u00f6'):\n player = Player(name)\n encoded = rpc.rpc_encode(player)\n return encoded\n\n def testRegisterPlayer(self):\n iface = I()\n encoded = self._encoded_player()\n p_data = iface.player_register(encoded)\n self.assertTrue(isinstance(p_data['id'], str))\n self.assertTrue(isinstance(p_data['akey'], str))\n plr = iface._ensure_auth(p_data['akey'])\n self.assertEqual(plr.id, p_data['id'])\n # list players\n players_raw = iface.player_list(p_data['akey'])\n self.assertTrue(isinstance(players_raw, list))\n players = [rpc.rpc_decode(Player, pl) for pl in players_raw]\n me = None\n for pl in players:\n if pl.id == p_data['id']:\n me = pl\n break\n self.assertTrue(me is not None)\n self.assertEqual(me.player_name, encoded['player_name'])\n iface._clear_auth()\n\n def testHelloEmpty(self):\n iface = I()\n hello = iface.hello()\n self.assertTrue(isinstance(hello, dict))\n self.assertTrue('version' in hello)\n self.assertTrue(isinstance(hello['version'], str))\n self.assertFalse('player' in hello)\n self.assertFalse('game' in hello)\n\n def testGame(self):\n iface = I()\n gamelist = iface.game_list()\n self.assertTrue(isinstance(gamelist, dict))\n self.assertEqual(len(gamelist), 0)\n # register\n p_encoded = self._encoded_player()\n p_data = iface.player_register(p_encoded)\n # create game\n g_id = iface.game_create(p_data['akey'])\n # list\n gamelist = iface.game_list()\n self.assertTrue(str(g_id) in gamelist)\n players_raw = gamelist[str(g_id)]\n self.assertTrue(isinstance(players_raw, list))\n # decode\n players = [rpc.rpc_decode(Player, pl) for pl in players_raw]\n self.assertTrue(p_data['id'] in [pl.id for pl in players])\n # get_info\n info = iface.game_get_info(g_id)\n self.assertTrue(info == players_raw)\n # leave\n ret = iface.player_quit(p_data['akey'])\n self.assertEqual(ret, True)\n # after the only player leaves, the game should get deleted\n gamelist = iface.game_list()\n self.assertFalse(g_id in gamelist)\n\n def testFullGame(self):\n iface = I()\n plrs = []\n for i in range(1, 5):\n plrs.append(self._encoded_player(str(i)))\n\n p_datas = []\n for p in plrs:\n p_datas.append(iface.player_register(p))\n\n g_id = iface.game_create(p_datas[0]['akey'])\n ret = iface.game_enter(p_datas[1]['akey'], g_id)\n self.assertEqual(ret, g_id)\n ret = iface.game_enter(p_datas[2]['akey'], g_id)\n self.assertEqual(ret, g_id)\n ret = iface.game_enter(p_datas[3]['akey'], g_id)\n self.assertEqual(ret, g_id)\n\n gamelist = iface.game_list()\n self.assertTrue(str(g_id) in gamelist)\n players = gamelist[str(g_id)]\n self.assertEqual(len(players), len(p_datas))\n # decode\n players = [rpc.rpc_decode(Player, pl) for pl in players]\n for p_data in p_datas:\n self.assertTrue(p_data['id'] in [pl.id for pl in players])\n\n state = iface.game_get_state(p_datas[0]['akey'], g_id)\n self.assertTrue('game_state' in state)\n self.assertEqual(state['game_state']['status'], 0)\n\n try:\n ret = iface.game_start(p_datas[0]['akey'], g_id)\n self.assertEqual(ret, True)\n\n state = iface.game_get_state(p_datas[0]['akey'], g_id)\n self.assertTrue('game_state' in state)\n self.assertEqual(state['game_state']['status'], 1)\n self.assertTrue('hand' in state)\n\n ret = iface.game_leave(p_datas[0]['akey'], g_id)\n self.assertEqual(ret, True)\n\n for p_data in p_datas:\n ret = iface.player_quit(p_data['akey'])\n self.assertEqual(ret, True)\n\n finally:\n for game in iface.games:\n game._reset()\n\n\nif __name__ == '__main__':\n unittest.main()\n", "tupelo/common.py": "#!/usr/bin/env python\n# vim: set sts=4 sw=4 et:\n\nimport random\nimport copy\nimport uuid\nimport base64\nfrom functools import wraps\nfrom . import rpc\n\n# game mode\nNOLO = 0\nRAMI = 1\n\nTURN_NONE = -1\n\ndef simple_decorator(decorator):\n \"\"\"This decorator can be used to turn simple functions\n into well-behaved decorators, so long as the decorators\n are fairly simple. If a decorator expects a function and\n returns a function (no descriptors), and if it doesn't\n modify function attributes or docstring, then it is\n eligible to use this. Simply apply @simple_decorator to\n your decorator and it will automatically preserve the\n docstring and function attributes of functions to which\n it is applied.\"\"\"\n def new_decorator(func):\n decf = decorator(func)\n decf.__name__ = func.__name__\n decf.__doc__ = func.__doc__\n decf.__dict__.update(func.__dict__)\n return decf\n # Now a few lines needed to make simple_decorator itself\n # be a well-behaved decorator.\n new_decorator.__name__ = decorator.__name__\n new_decorator.__doc__ = decorator.__doc__\n new_decorator.__dict__.update(decorator.__dict__)\n return new_decorator\n\n@simple_decorator\ndef traced(func):\n \"\"\"\n A decorator for tracing func calls.\n \"\"\"\n def wrapper(*args, **kwargs):\n print((\"DEBUG: entering %s()\" % func.__name__))\n retval = func(*args, **kwargs)\n return retval\n\n return wrapper\n\ndef synchronized_method(lock_name):\n \"\"\"\n Simple synchronization decorator for methods.\n \"\"\"\n def decorator(func):\n @wraps(func)\n def wrapper(self, *args, **kwargs):\n lock = self.__getattribute__(lock_name)\n lock.acquire()\n try:\n return func(self, *args, **kwargs)\n finally:\n lock.release()\n\n return wrapper\n\n return decorator\n\ndef short_uuid():\n \"\"\"\n Generate a short, random unique ID.\n\n Returns a string (base64 encoded UUID).\n \"\"\"\n return base64.urlsafe_b64encode(uuid.uuid4().bytes).decode().replace('=', '')\n\n\nclass TupeloException(Exception):\n \"\"\"\n Base class for new exceptions.\n \"\"\"\n def __init__(self, message=None):\n self.message = message\n\n\nclass GameError(TupeloException):\n \"\"\"\n Generic error class for game errors.\n \"\"\"\n rpc_code = 1\n\n\nclass RuleError(TupeloException):\n \"\"\"\n Error for breaking the game rules.\n \"\"\"\n rpc_code = 2\n\n\nclass ProtocolError(TupeloException):\n \"\"\"\n Error for problems in using the RPC protocol.\n \"\"\"\n rpc_code = 3\n\n\nclass UserQuit(GameError):\n \"\"\"\n Exception for indicating that user quits the game.\n \"\"\"\n pass\n\n\nclass Suit():\n \"\"\"\n Class for suits.\n \"\"\"\n def __init__(self, value, name, char=''):\n self.name = name\n self.value = value\n self.char = char\n\n def __eq__(self, other):\n return self.value == other.value\n\n def __ne__(self, other):\n return self.value != other.value\n\n def __lt__(self, other):\n return self.value < other.value\n\n def __le__(self, other):\n return self.value <= other.value\n\n def __gt__(self, other):\n return self.value > other.value\n\n def __ge__(self, other):\n return self.value >= other.value\n\n def rpc_encode(self):\n return self.value\n\n @classmethod\n def rpc_decode(cls, value):\n return _get_suit(value)\n\n def __str__(self):\n \"\"\"\n Get the 'unofficial' string representation.\n \"\"\"\n return self.name\n\nHEART = Suit(3, 'hearts', '\\u2665')\nCLUB = Suit(2, 'clubs', '\\u2663')\nDIAMOND = Suit(1, 'diamonds', '\\u2666')\nSPADE = Suit(0, 'spades', '\\u2660')\n\nALL_SUITS = [SPADE, DIAMOND, CLUB, HEART]\n\ndef _get_suit(value: int) -> Suit:\n try:\n return ALL_SUITS[value]\n except IndexError:\n raise ValueError(\"Suit not found\")\n\nclass Card(rpc.RPCSerializable):\n \"\"\"\n Class that represents a single card.\n \"\"\"\n _chars = {11:'J', 12:'Q', 13:'K', 14:'A'}\n rpc_attrs = ('suit', 'value', 'played_by')\n\n def __init__(self, suit: Suit, value: int):\n super().__init__()\n self.suit = suit\n self.value = value\n self.potential_owners = list(range(0, 4))\n self.played_by = None\n\n @classmethod\n def rpc_decode(cls, rpcobj) -> 'Card':\n card = Card(Suit.rpc_decode(rpcobj['suit']), rpcobj['value'])\n if 'played_by' in rpcobj:\n card.played_by = rpcobj['played_by']\n\n return card\n\n def __eq__(self, other):\n return self.suit == other.suit and self.value == other.value\n\n def __ne__(self, other):\n return self.suit != other.suit or self.value != other.value\n\n def __lt__(self, other):\n return self._cmp_value < other._cmp_value\n\n def __le__(self, other):\n return self._cmp_value <= other._cmp_value\n\n def __gt__(self, other):\n return self._cmp_value > other._cmp_value\n\n def __ge__(self, other):\n return self._cmp_value >= other._cmp_value\n\n def __repr__(self):\n \"\"\"\n Get the official string representation of the object.\n \"\"\"\n return f''\n\n @property\n def _cmp_value(self) -> int:\n \"\"\"Get the integer value that can be used for comparing and sorting cards.\"\"\"\n return self.suit.value * 13 + self.value\n\n def __str__(self):\n return '%s%s' % (self.char, self.suit.char)\n\n @property\n def char(self):\n \"\"\"\n Get the character corresponding to the card value.\n \"\"\"\n if self.value in self._chars:\n return self._chars[self.value]\n return str(self.value)\n\n\nclass CardSet(list, rpc.RPCSerializable):\n \"\"\"\n A set of cards.\n \"\"\"\n @staticmethod\n def new_full_deck():\n \"\"\"\n Create a full deck of cards.\n \"\"\"\n deck = CardSet()\n for suit in ALL_SUITS:\n for val in range(2, 15):\n deck.append(Card(suit, val))\n\n return deck\n\n def __sub__(self, other):\n \"\"\"\n \"\"\"\n result = copy.copy(self)\n for elem in other:\n try:\n result.remove(elem)\n except ValueError:\n continue\n return result\n\n def rpc_encode(self):\n return [rpc.rpc_encode(card) for card in self]\n\n @classmethod\n def rpc_decode(cls, rpcobj):\n cset = cls()\n for card in rpcobj:\n cset.append(rpc.rpc_decode(Card, card))\n return cset\n\n def get_cards(self, **kwargs):\n \"\"\"\n Get cards from the set.\n\n Supported keyword args:\n - suit: get cards having the given suit\n - value: get cards having the given value\n \"\"\"\n result = CardSet()\n for card in self:\n if 'suit' in kwargs and card.suit != kwargs['suit']:\n continue\n\n if 'value' in kwargs and card.value != kwargs['value']:\n continue\n\n result.append(card)\n return result\n\n def shuffle(self):\n \"\"\"\n Shuffle the CardSet to a random order.\n \"\"\"\n random.shuffle(self)\n\n def take(self, card):\n \"\"\"\n Take a selected card from the set.\n \"\"\"\n self.remove(card)\n return card\n\n def clear(self):\n \"\"\"\n Clear this set.\n \"\"\"\n del self[:]\n\n def deal(self, cardsets):\n \"\"\"\n Deal this CardSet into cardsets.\n \"\"\"\n while len(self) > 0:\n for cset in cardsets:\n try:\n cset.append(self.pop(0))\n except IndexError:\n break\n\n def get_highest(self, **kwargs):\n \"\"\"\n Get the card with the highest value.\n \"\"\"\n highest = None\n roof = None\n floor = None\n\n if 'roof' in kwargs:\n roof = kwargs['roof']\n\n if 'floor' in kwargs:\n floor = kwargs['floor']\n\n for card in self:\n if floor is not None and card.value < floor:\n continue\n if roof is not None and card.value > roof:\n continue\n if highest is None or card.value > highest.value:\n highest = card\n\n return highest\n\n def get_lowest(self, **kwargs):\n \"\"\"\n Get the card with the lowest value.\n \"\"\"\n lowest = None\n roof = None\n floor = None\n\n if 'roof' in kwargs:\n roof = kwargs['roof']\n\n if 'floor' in kwargs:\n floor = kwargs['floor']\n\n for card in self:\n if floor is not None and card.value < floor:\n continue\n if roof is not None and card.value > roof:\n continue\n if lowest is None or card.value < lowest.value:\n lowest = card\n\n return lowest\n\nclass GameState(rpc.RPCSerializable):\n \"\"\"\n State of a single game.\n \"\"\"\n rpc_attrs = ('status', 'mode', 'table:CardSet', 'score', 'tricks', 'turn',\n 'turn_id', 'dealer')\n\n # statuses\n OPEN = 0\n VOTING = 1\n ONGOING = 2\n STOPPED = 3\n\n def __init__(self):\n super().__init__()\n self.status = GameState.OPEN\n self.mode = NOLO\n self.table = CardSet()\n self.score = [0, 0]\n self.tricks = [0, 0]\n self.rami_chosen_by = None # Player\n self.turn = 0\n self.turn_id = 0\n self.dealer = 0\n\n def update(self, new_state):\n \"\"\"\n Update the state from a new state object.\n \"\"\"\n for attr in self.__dict__:\n if hasattr(new_state, attr):\n setattr(self, attr, getattr(new_state, attr))\n\n def next_in_turn(self, thenext=None):\n \"\"\"\n Set the next player in turn.\n \"\"\"\n if thenext is None:\n self.turn = (self.turn + 1) % 4\n else:\n self.turn = (thenext) % 4\n\n def __str__(self):\n statusstr = {GameState.OPEN: 'OPEN', GameState.STOPPED: 'STOPPED',\n GameState.VOTING: 'VOTING', GameState.ONGOING: 'ONGOING'}\n modestr = {NOLO: 'NOLO', RAMI: 'RAMI'}\n return \"state: %s, mode: %s, score: %s, tricks: %s, dealer: %d\" % \\\n (statusstr[self.status], modestr[self.mode], str(self.score),\n str(self.tricks), self.dealer)\n\n", "tupelo/events.py": "#!/usr/bin/env python\n# vim: set sts=4 sw=4 et:\n\nfrom typing import Optional\nfrom enum import IntEnum\nfrom .rpc import RPCSerializable, rpc_encode, rpc_decode\n\nclass EventType(IntEnum):\n NONE = 0\n CARD_PLAYED = 1\n MESSAGE = 2\n TRICK_PLAYED = 3\n TURN = 4\n STATE_CHANGED = 5\n\n def rpc_encode(self):\n return int(self)\n\n\nclass Event(RPCSerializable):\n \"\"\"\n Class for events.\n \"\"\"\n type = EventType.NONE\n rpc_attrs = ('type',)\n\n @classmethod\n def rpc_decode(cls, rpcobj):\n \"\"\"\n Decode an rpc object into an Event instance.\n \"\"\"\n for subcls in cls.__subclasses__():\n if getattr(subcls, 'type') == rpcobj['type']:\n return rpc_decode(subcls, rpcobj)\n\n return cls.rpc_decode_simple(rpcobj)\n\n\nclass CardPlayedEvent(Event):\n \"\"\"\n A card has been played.\n \"\"\"\n type = EventType.CARD_PLAYED\n rpc_attrs = Event.rpc_attrs + ('player:Player', 'card:Card', 'game_state:GameState')\n\n def __init__(self, player=None, card=None, game_state=None):\n self.player = player\n self.card = card\n self.game_state = game_state\n\n\nclass MessageEvent(Event):\n \"\"\"\n A message.\n \"\"\"\n type = EventType.MESSAGE\n rpc_attrs = Event.rpc_attrs + ('sender', 'message')\n\n def __init__(self, sender: Optional[str] = None, message: Optional[str] = None):\n self.sender = sender\n self.message = message\n\n\nclass TrickPlayedEvent(Event):\n \"\"\"\n A trick (tikki/kasa) has been played.\n \"\"\"\n type = EventType.TRICK_PLAYED\n rpc_attrs = Event.rpc_attrs + ('player:Player', 'game_state:GameState')\n\n def __init__(self, player=None, game_state=None):\n self.player = player\n self.game_state = game_state\n\n\nclass TurnEvent(Event):\n \"\"\"\n It is the player's turn to do something.\n \"\"\"\n type = EventType.TURN\n rpc_attrs = Event.rpc_attrs + ('game_state:GameState',)\n\n def __init__(self, game_state=None):\n self.game_state = game_state\n\n\nclass StateChangedEvent(Event):\n \"\"\"\n Game state has changed.\n \"\"\"\n type = EventType.STATE_CHANGED\n rpc_attrs = Event.rpc_attrs + ('game_state:GameState',)\n\n def __init__(self, game_state=None):\n self.game_state = game_state\n\n\nclass EventList(list, RPCSerializable):\n \"\"\"\n Class for event lists.\n \"\"\"\n def rpc_encode(self):\n return [rpc_encode(event) for event in self]\n\n @classmethod\n def rpc_decode(cls, rpcobj):\n elist = cls()\n for event in rpcobj:\n elist.append(rpc_decode(Event, event))\n return elist\n\n", "tupelo/game.py": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# vim: set sts=4 sw=4 et:\n\nimport threading\nimport sys\nimport copy\nimport logging\nfrom typing import Optional, List\n\nfrom .common import CardSet, Card\nfrom .common import NOLO, RAMI, DIAMOND, HEART\nfrom .common import TURN_NONE\nfrom .common import RuleError, GameError, GameState\nfrom .common import synchronized_method\nfrom .players import Player, ThreadedPlayer\n\nlogger = logging.getLogger()\n\nclass GameController():\n \"\"\"\n The controller class that runs everything.\n \"\"\"\n\n def __init__(self):\n super().__init__()\n self.players = []\n self.state = GameState()\n self.shutdown_event = threading.Event()\n self.id = None\n self.lock_start = threading.Lock()\n\n def register_player(self, player: Player):\n \"\"\"\n Register a new Player.\n \"\"\"\n if player.id in [pl.id for pl in self.players]:\n raise GameError('Player already registered to game')\n\n if len(self.players) == 4:\n raise GameError('Already 4 players registered')\n\n self.players.append(player)\n # TODO: should we generate UUIDs instead?\n if player.id is None:\n player.id = str(self.players.index(player))\n\n player.team = self.players.index(player) % 2\n\n def player_leave(self, player_id: int):\n \"\"\"\n Player leaves the game.\n \"\"\"\n self._send_msg('Player %s quit' % player_id)\n plr = self.get_player(player_id)\n if plr:\n self.players.remove(plr)\n plr.hand.clear()\n plr.stop() # stops the thread in case of ThreadedPlayer\n\n # reset the game unless we are still in OPEN state\n if self.state.status != GameState.OPEN:\n self._reset()\n\n def player_quit(self, player_id: int):\n \"\"\"\n Leave and quit the game.\n \"\"\"\n self.player_leave(player_id)\n self.shutdown_event.set()\n\n def get_player(self, player_id: int) -> Optional[Player]:\n \"\"\"\n Get player by id.\n \"\"\"\n for plr in self.players:\n if plr.id == player_id:\n return plr\n\n return None\n\n def _get_player_in_turn(self, turn: int) -> Optional[Player]:\n \"\"\"\n Get player who is in turn.\n \"\"\"\n if turn >= 0:\n return self.players[turn % 4]\n\n return None\n\n def _next_in_turn(self, thenext: Optional[int] = None):\n \"\"\"\n Set the next player in turn.\n \"\"\"\n self.state.next_in_turn(thenext)\n self.state.turn_id = self._get_player_in_turn(self.state.turn).id\n\n def _set_state(self, new_status: int):\n \"\"\"\n Change the game state.\n \"\"\"\n self.state.status = new_status\n for player in self.players:\n player.state_changed(self.state)\n\n def _stop_players(self):\n \"\"\"\n Stop all running players.\n \"\"\"\n self._set_state(GameState.STOPPED)\n for player in self.players:\n if player:\n player.act(self, self.state)\n\n for player in self.players:\n if player and isinstance(player, ThreadedPlayer):\n if player.is_alive() and player.thread is not threading.current_thread():\n player.join()\n\n def _reset(self):\n \"\"\"\n Reset the game.\n \"\"\"\n logger.info('Resetting')\n self._stop_players()\n self.players = []\n self.state = GameState()\n\n def _get_team_players(self, team: int) -> List[Player]:\n \"\"\"\n Get players in a team.\n \"\"\"\n return [player for player in self.players if player.team == team]\n\n def _get_team_str(self, team: int) -> str:\n \"\"\"\n Get team string representation.\n \"\"\"\n plrs = self._get_team_players(team)\n return '%d (%s)' % (team + 1, ', '.join([pl.player_name for pl in plrs]))\n\n def _send_msg(self, msg: str):\n \"\"\"\n Send a message to all players.\n \"\"\"\n logger.debug(msg)\n for player in self.players:\n player.send_message('', msg)\n\n @synchronized_method('lock_start')\n def start_game(self):\n \"\"\"\n Start the game.\n \"\"\"\n if self.state.status != GameState.OPEN:\n raise GameError('Game already started')\n\n if len(self.players) < 4:\n raise GameError('Not enough players')\n\n for player in self.players:\n player.start()\n\n self._start_new_hand()\n\n def wait_for_shutdown(self):\n \"\"\"\n Wait for shutdown event and shut down after it.\n \"\"\"\n self.shutdown_event.wait()\n self.shutdown()\n\n def _signal_act(self):\n \"\"\"\n Tell the player who is in turn to act.\n \"\"\"\n self._get_player_in_turn(self.state.turn).act(self, self.state)\n\n def _start_new_hand(self):\n \"\"\"\n Start a new hand.\n \"\"\"\n logger.info('New hand')\n self.state.tricks = [0, 0]\n\n # create a full deck\n deck = CardSet.new_full_deck()\n\n logger.debug('deck is %s', str(deck))\n deck.shuffle()\n logger.debug('shuffled deck %s', str(deck))\n\n deck.deal([player.hand for player in self.players])\n\n for player in self.players:\n player.hand.sort()\n logger.debug(\"%s's hand: %s\", player.player_name,\n str(player.hand))\n\n # voting\n self.state.mode = NOLO\n self.state.rami_chosen_by = None\n self._set_state(GameState.VOTING)\n\n # uncomment following to skip voting\n #self._set_state(GameState.ONGOING)\n # start the game\n self._next_in_turn(self.state.dealer + 1)\n self._signal_act()\n\n def _trick_played(self):\n \"\"\"\n A trick (4 cards) has been played.\n \"\"\"\n table = self.state.table\n high = table.get_cards(suit=table[0].suit).get_highest()\n high_played_by = self.get_player(high.played_by)\n team = high_played_by.team\n self._send_msg('Team %s takes this trick' % (self._get_team_str(team)))\n self.state.tricks[team] += 1\n self._send_msg('Tricks: %s' % self.state.tricks)\n # send signals\n for plr in self.players:\n plr.trick_played(high_played_by, self.state)\n\n self.state.table.clear()\n\n # do we have a winner?\n if self.state.tricks[0] + self.state.tricks[1] == 13:\n self._hand_played()\n else:\n self._next_in_turn(self.players.index(high_played_by))\n self._signal_act()\n\n def _hand_played(self):\n \"\"\"\n A hand has been played.\n \"\"\"\n\n if self.state.mode == NOLO:\n if self.state.tricks[0] < self.state.tricks[1]:\n winner = 0\n loser = 1\n else:\n winner = 1\n loser = 0\n score = (7 - self.state.tricks[winner]) * 4\n else:\n if self.state.tricks[0] > self.state.tricks[1]:\n winner = 0\n loser = 1\n else:\n winner = 1\n loser = 0\n if self.state.rami_chosen_by and self.state.rami_chosen_by.team != winner:\n self._send_msg(\"Double points for taking opponent's rami!\")\n score = (self.state.tricks[winner] - 6) * 8\n else:\n score = (self.state.tricks[winner] - 6) * 4\n\n self._send_msg('Team %s won this hand with %d tricks' %\n (self._get_team_str(winner), self.state.tricks[winner]))\n\n if self.state.score[loser] > 0:\n self._send_msg('Team %s fell down' % (self._get_team_str(loser)))\n self.state.score = [0, 0]\n else:\n self.state.score[winner] += score\n if self.state.score[winner] > 52:\n self._send_msg('Team %s won with score %d!' %\n (self._get_team_str(winner), self.state.score[winner]))\n self.shutdown_event.set()\n return\n else:\n self._send_msg('Team %s is at %d' %\n (self._get_team_str(winner), self.state.score[winner]))\n\n self.state.dealer = (self.state.dealer + 1) % 4\n self._start_new_hand()\n\n def shutdown(self):\n \"\"\"\n Shutdown the game.\n \"\"\"\n self._stop_players()\n sys.exit(0)\n\n def _vote_card(self, player: Player, card: Card):\n \"\"\"\n Player votes with a card.\n \"\"\"\n table = self.state.table\n\n card = copy.copy(card)\n card.played_by = player.id\n table.append(card)\n # fire signals\n for plr in self.players:\n plr.card_played(player, card, self.state)\n\n if card.suit == DIAMOND or card.suit == HEART:\n self.state.mode = RAMI\n self.state.rami_chosen_by = player\n self._next_in_turn(self.players.index(player) - 1)\n self._begin_game()\n elif len(table) == 4:\n self.state.mode = NOLO\n self._next_in_turn()\n self._begin_game()\n else:\n self._next_in_turn()\n\n self._signal_act()\n\n def _begin_game(self):\n if self.state.mode == RAMI:\n self._send_msg('Rami it is')\n else:\n self._send_msg('Nolo it is')\n\n self._send_msg('Game on, %s begins!' % self._get_player_in_turn(self.state.turn))\n\n self.state.table.clear()\n self._set_state(GameState.ONGOING)\n\n def play_card(self, player: Player, card: Card):\n \"\"\"\n Play one card on the table.\n \"\"\"\n if self._get_player_in_turn(self.state.turn).id != player.id:\n raise RuleError('Not your turn')\n\n table = self.state.table\n\n if self.state.status == GameState.VOTING:\n self._vote_card(player, card)\n\n elif self.state.status == GameState.ONGOING:\n # make sure that suit is followed\n if len(table) > 0 and card.suit != table[0].suit:\n if len(player.hand.get_cards(suit=table[0].suit)) > 0:\n raise RuleError('Suit must be followed')\n\n # make sure that the player actually has the card\n try:\n table.append(player.hand.take(card))\n card.played_by = player.id\n except ValueError:\n raise RuleError('Invalid card')\n\n if len(table) == 4:\n # TODO: there must be a better way for this\n turn_backup = self.state.turn\n self.state.turn = TURN_NONE\n # fire signals with temporary state\n # this is to let clients know that all four cards have been played\n # and it's nobody's turn yet\n for plr in self.players:\n plr.card_played(player, card, self.state)\n\n self.state.turn = turn_backup\n self._trick_played()\n else:\n self._next_in_turn()\n # fire signals\n for plr in self.players:\n plr.card_played(player, card, self.state)\n self._signal_act()\n\n", "tupelo/players.py": "#!/usr/bin/env python\n# vim: set sts=4 sw=4 et:\n\nimport threading\nfrom .common import Card, CardSet, SPADE, CLUB, HEART, DIAMOND\nfrom .common import NOLO, RAMI\nfrom .common import RuleError, UserQuit, GameState\nfrom .rpc import RPCSerializable\n\nclass Player(RPCSerializable):\n \"\"\"\n Base class for players.\n \"\"\"\n rpc_attrs = ('id', 'player_name', 'team')\n\n def __init__(self, name:str):\n super().__init__()\n self.id = None\n self.player_name = name\n self.hand = CardSet()\n self.team: int = 0\n self.controller = None\n self.game_state = GameState()\n\n def __repr__(self):\n return '<%s: %s>' % (self.__class__.__name__, self.player_name)\n\n def __getstate__(self):\n \"\"\"\n Make Player classes safe for pickling and deepcopying.\n \"\"\"\n state = {}\n for key, _ in self.iter_rpc_attrs():\n state[key] = getattr(self, key)\n\n return state\n\n @classmethod\n def rpc_decode(cls, rpcobj: dict) -> 'Player':\n \"\"\"\n Decode an RPC-form object into an instance of cls.\n \"\"\"\n player = cls(rpcobj['player_name'])\n for attr, atype in cls.iter_rpc_attrs():\n if attr != 'player_name':\n player.rpc_decode_attr(rpcobj, attr, atype)\n\n return player\n\n def start(self):\n \"\"\"\n Start the player.\n \"\"\"\n pass\n\n def stop(self):\n \"\"\"\n Stop the player.\n \"\"\"\n pass\n\n def card_played(self, player: 'Player', card: Card, game_state: GameState):\n \"\"\"\n Signal that a card has been played by the given player.\n \"\"\"\n pass\n\n def trick_played(self, player, game_state: GameState):\n \"\"\"\n Signal that a trick has been played. \"player\" had the winning card.\n \"\"\"\n pass\n\n def state_changed(self, game_state: GameState):\n \"\"\"\n Signal that the game state has changed, e.g. from VOTING to ONGOING.\n \"\"\"\n pass\n\n def vote(self):\n \"\"\"\n Vote for rami or nolo.\n \"\"\"\n print('Not implemented!')\n raise NotImplementedError()\n\n def play_card(self):\n \"\"\"\n Play one card.\n \"\"\"\n print('Not implemented!')\n raise NotImplementedError()\n\n def send_message(self, sender, msg: str):\n \"\"\"\n \"\"\"\n print('Not implemented!')\n raise NotImplementedError()\n\n def act(self, controller, game_state: GameState):\n \"\"\"\n Do something.\n\n This is an event handler that updates\n the game state and wakes up the thread.\n \"\"\"\n print('Not implemented!')\n raise NotImplementedError()\n\n\nclass ThreadedPlayer(Player):\n\n def __init__(self, name):\n Player.__init__(self, name)\n self.thread = self._create_thread()\n self.turn_event = threading.Event()\n self.stop_flag = False\n\n def _create_thread(self):\n \"\"\"\n Create a new thread for this player.\n \"\"\"\n return threading.Thread(None, self.run, self.player_name)\n\n def wait_for_turn(self):\n \"\"\"\n Wait for this player's turn.\n \"\"\"\n #print \"%s waiting for my turn\" % self\n self.turn_event.wait()\n #print \"%s it's about time!\" % self\n self.turn_event.clear()\n\n def is_alive(self):\n \"\"\"\n Return true if the player thread is alive.\n \"\"\"\n if self.thread is not None:\n return self.thread.isAlive()\n\n return False\n\n def start(self):\n \"\"\"\n (Re)start the player thread.\n \"\"\"\n if self.thread is None:\n self.thread = self._create_thread()\n\n # try to handle restart attempts\n try:\n return self.thread.start()\n except RuntimeError:\n # if the thread is still running, the exception is valid\n if self.is_alive():\n raise\n\n self.thread = self._create_thread()\n return self.thread.start()\n\n def join(self, timeout=5.0):\n \"\"\"\n Join the player thread, if one exists.\n \"\"\"\n if self.thread is None:\n return\n\n return self.thread.join(timeout)\n\n def run(self):\n \"\"\"\n The real work is here.\n \"\"\"\n print(('%s starting' % self))\n self.stop_flag = False\n while True:\n\n self.wait_for_turn()\n\n if self.game_state.status == GameState.STOPPED or \\\n self.stop_flag == True:\n break\n elif self.game_state.status == GameState.VOTING:\n try:\n self.vote()\n except UserQuit as error:\n print(('UserQuit:', error))\n self.controller.player_quit(self.id)\n break\n except Exception as error:\n print(('Error:', error))\n raise\n elif self.game_state.status == GameState.ONGOING:\n try:\n self.play_card()\n except UserQuit as error:\n print(('UserQuit:', error))\n self.controller.player_quit(self.id)\n break\n except Exception as error:\n print(('Error:', error))\n raise\n else:\n print((\"Warning: unknown status %d\" % self.game_state.status))\n\n print(('%s exiting' % self))\n\n def stop(self):\n \"\"\"\n Try to stop the thread, regardless of the state.\n \"\"\"\n self.stop_flag = True\n self.turn_event.set()\n\n def act(self, controller, game_state: GameState):\n \"\"\"\n Do something.\n\n This is an event handler that updates\n the game state and wakes up the thread.\n \"\"\"\n self.controller = controller\n self.game_state.update(game_state)\n self.turn_event.set()\n\nclass DummyBotPlayer(ThreadedPlayer):\n \"\"\"\n Dummy robot player.\n \"\"\"\n\n def send_message(self, sender, msg):\n \"\"\"\n Robots don't care about messages.\n \"\"\"\n pass\n\n def vote(self):\n \"\"\"\n Vote for rami or nolo.\n \"\"\"\n # simple algorithm\n score = 0\n for card in self.hand:\n if card.value > 10:\n score += card.value - 10\n\n if score > 16:\n # rami, red cards\n choices = self.hand.get_cards(suit=HEART)\n choices.extend(self.hand.get_cards(suit=DIAMOND))\n else:\n # nolo, black cards\n choices = self.hand.get_cards(suit=SPADE)\n choices.extend(self.hand.get_cards(suit=CLUB))\n\n if len(choices) == 0:\n choices = self.hand\n\n best = None\n for card in choices:\n if best is None or abs(6 - card.value) < abs(6 - best.value):\n best = card\n\n try:\n #print '%s voting %s' % (self, best)\n self.controller.play_card(self, best)\n except RuleError as error:\n print('Oops', error)\n raise\n\n def play_card(self):\n state = self.game_state\n\n # pick a card, how hard can it be?\n card = None\n if len(state.table) == 0:\n choices = self.hand\n else:\n choices = self.hand.get_cards(suit=state.table[0].suit)\n\n if state.mode == NOLO:\n if len(choices) == 0:\n # \"sakaus\"\n # should be \"worst score\"\n card = self.hand.get_highest()\n else:\n # real dumb\n card = choices.get_lowest()\n if len(state.table) > 0:\n high = state.table.get_cards(suit=state.table[0].suit).get_highest()\n high_played_by = self.controller.get_player(high.played_by)\n if high_played_by.team == self.team:\n # we may be getting this trick...\n if len(state.table) == 3:\n # and i'm the last to play\n card = choices.get_highest()\n else:\n # i'm third\n # TODO: should also consider higher cards\n candidate = choices.get_highest(roof=high.value)\n if candidate is not None:\n card = candidate\n else:\n # might have to take this one\n card = choices.get_highest()\n else:\n # the opponent may get this trick, play under\n candidate = choices.get_highest(roof=high.value)\n if candidate is not None:\n card = candidate\n else:\n # cannot go under...\n if len(state.table) == 3:\n # and i'm the last to play\n card = choices.get_highest()\n else:\n pass\n\n elif state.mode == RAMI:\n if len(choices) == 0:\n # should be \"worst score\" or \"least value\"\n card = self.hand.get_lowest()\n else:\n # real dumb\n card = choices.get_highest()\n if len(state.table) > 0:\n high = state.table.get_cards(suit=state.table[0].suit).get_highest()\n high_played_by = self.controller.get_player(high.played_by)\n if high_played_by.team == self.team:\n # we may be getting this trick...\n card = choices.get_lowest()\n else:\n if len(state.table) == 3:\n # i'm the last to play\n # take it as cheap as possible, if possible\n candidate = choices.get_lowest(floor=high.value)\n if candidate is not None:\n card = candidate\n else:\n card = choices.get_lowest()\n else:\n # i'm second or third\n candidate = choices.get_highest(floor=high.value)\n if candidate is not None:\n card = candidate\n else:\n # but I cannot take it...\n card = choices.get_lowest()\n\n try:\n #print '%s playing %s' % (self, card)\n self.controller.play_card(self, card)\n except RuleError as error:\n print('Oops', error)\n raise\n\n\nclass CountingBotPlayer(DummyBotPlayer):\n \"\"\"\n Robot player that counts played cards.\n \"\"\"\n\n def __init__(self, name):\n super().__init__(name)\n self.cards_left = CardSet()\n\n def vote(self):\n \"\"\"\n Vote for rami or nolo.\n \"\"\"\n self.cards_left = CardSet.new_full_deck() - self.hand\n super(CountingBotPlayer, self).vote()\n\n def card_played(self, player: Player, card: Card, game_state: GameState):\n \"\"\"\n Signal that a card has been played by the given player.\n \"\"\"\n if player == self:\n return\n\n if game_state.status == GameState.VOTING:\n pass\n elif game_state.status == GameState.ONGOING:\n #print \"removing %s from %s\" %(card, self.cards_left)\n try:\n self.cards_left.remove(card)\n except ValueError:\n print(\"Oops: removing card %s failed\" % card)\n # TODO: we sometimes get this with CountingBotPlayer\n\n\nclass CliPlayer(ThreadedPlayer):\n \"\"\"\n Command line interface human player.\n \"\"\"\n\n def echo(self, message: str = \"\", end=\"\\n\"):\n \"\"\"Print a message for the user.\"\"\"\n print(message, end=end)\n\n def _pick_card(self, prompt='Pick a card'):\n \"\"\"\n Pick one card from the player's hand.\n \"\"\"\n self.echo(\"Your hand:\")\n self.echo(' '.join('%3s' % (card) for card in self.hand))\n for i in range(0, len(self.hand)):\n self.echo('%3d ' % (i + 1), end=' ')\n self.echo()\n\n card_ok = False\n card = None\n while not card_ok:\n try:\n uinput = input('%s (1-%d) --> ' % (prompt, len(self.hand)))\n try:\n index = int(uinput) - 1\n if index < 0:\n raise IndexError()\n card = self.hand[index]\n card_ok = True\n except (IndexError, ValueError):\n self.echo(\"Invalid choice `%s'\" % uinput)\n except EOFError:\n #error.message = 'EOF received from command line'\n #error.args = error.message,\n #raise error\n raise EOFError('EOF received from command line')\n\n return card\n\n def vote(self):\n \"\"\"\n Vote for rami or nolo.\n \"\"\"\n self.echo('Voting')\n card_played = False\n while not card_played:\n try:\n card = self._pick_card()\n self.echo('Voting with %s' % (card))\n self.controller.play_card(self, card)\n card_played = True\n except RuleError as error:\n self.echo('Oops: %s' % error)\n except EOFError:\n raise UserQuit('EOF from command line')\n\n def play_card(self):\n \"\"\"\n Play one card.\n \"\"\"\n state = self.game_state\n\n # print table\n if state.mode == NOLO:\n self.echo('Playing nolo')\n elif state.mode == RAMI:\n self.echo('Playing rami')\n else:\n self.echo('Unknown mode %d' % state.mode)\n\n self.echo('Table:')\n for card in state.table:\n try:\n plr = '%s: ' % self.controller.get_player(card.played_by).player_name\n except:\n # showing the (random) player ID is not very intuitive\n plr = ''\n self.echo('%s%s' % (plr, card))\n\n card_played = False\n while not card_played:\n try:\n card = self._pick_card('Card to play')\n self.echo('Playing %s' % (card))\n self.controller.play_card(self, card)\n card_played = True\n except RuleError as error:\n self.echo('Oops: %s' % error)\n except EOFError:\n raise UserQuit('EOF from command line')\n\n def card_played(self, player: Player, card: Card, game_state: GameState):\n \"\"\"\n Event handler for a played card.\n \"\"\"\n if player.id == self.id:\n player_str = 'You'\n else:\n player_str = '%s' % player\n\n if game_state.status == GameState.VOTING:\n self.echo('%s voted %s' % (player_str, card))\n else:\n self.echo('%s played %s' % (player_str, card))\n\n def send_message(self, sender: str, msg: str):\n \"\"\"\n Send a message to this player.\n \"\"\"\n if sender is not None:\n self.echo('%s: %s' % (sender, msg))\n else:\n self.echo('%s' % msg)\n\n", "tupelo/rpc.py": "#!/usr/bin/env python\n# vim: set sts=4 sw=4 et:\n\nfrom typing import Union\n\ndef rpc_encode(obj):\n \"\"\"\n Encode an object into RPC-safe form.\n \"\"\"\n try:\n return obj.rpc_encode()\n except AttributeError:\n return obj\n\ndef rpc_decode(cls, rpcobj):\n \"\"\"\n Decode an RPC-form object into an instance of cls.\n \"\"\"\n try:\n return cls.rpc_decode(rpcobj)\n except AttributeError:\n return rpcobj\n\ndef _memoize(func, cache={}):\n def decf(*args, **kwargs):\n key = (func, tuple(args), frozenset(list(kwargs.items())))\n if key not in cache:\n cache[key] = func(*args, **kwargs)\n return cache[key]\n return decf\n\ndef _itersubclasses(cls, _seen=None):\n \"\"\"\n itersubclasses(cls)\n\n Generator over all subclasses of a given class, in depth first order.\n \"\"\"\n if not isinstance(cls, type):\n raise TypeError('itersubclasses must be called with '\n 'new-style classes, not %.100r' % cls)\n if _seen is None:\n _seen = set()\n try:\n subs = cls.__subclasses__()\n except TypeError: # fails only when cls is type\n subs = cls.__subclasses__(cls)\n for sub in subs:\n if sub not in _seen:\n _seen.add(sub)\n yield sub\n for subsub in _itersubclasses(sub, _seen):\n yield subsub\n\nclass RPCSerializable():\n \"\"\"\n Base class for objects that are serializable into\n an RPC-safe form.\n \"\"\"\n rpc_attrs = None\n rpc_type = None\n\n def __eq__(self, other):\n if not self.rpc_attrs:\n return super().__eq__(other)\n\n if self.rpc_type:\n try:\n if self.rpc_type != other.rpc_type:\n return False\n except AttributeError:\n return False\n\n for attr, _ in self.iter_rpc_attrs():\n try:\n if getattr(self, attr) != getattr(other, attr):\n return False\n except AttributeError:\n return False\n\n return True\n\n def __ne__(self, other):\n return not self.__eq__(other)\n\n @classmethod\n def iter_rpc_attrs(cls):\n \"\"\"\n Generator for iterating rpc_attrs with attr and type separated.\n \"\"\"\n if not cls.rpc_attrs:\n return\n\n iterator = iter(cls.rpc_attrs or tuple())\n while 1:\n try:\n data = next(iterator).split(':')\n except StopIteration:\n return\n\n if len(data) == 1:\n data.append(None)\n yield (data[0], data[1])\n\n def rpc_encode(self) -> Union[dict, 'RPCSerializable']:\n \"\"\"\n Encode an instance of RPCSerializable into an rpc object.\n \"\"\"\n if self.rpc_attrs:\n rpcobj = {}\n for attr, _ in self.iter_rpc_attrs():\n rpcform = None\n try:\n rpcform = rpc_encode(getattr(self, attr))\n except AttributeError:\n pass\n\n if rpcform is not None:\n rpcobj[attr] = rpcform\n\n return rpcobj\n # default behaviour\n return self\n\n @classmethod\n def rpc_decode_simple(cls, rpcobj):\n \"\"\"\n Default decode method.\n \"\"\"\n if cls.rpc_attrs:\n instance = cls()\n for attr, atype in cls.iter_rpc_attrs():\n instance.rpc_decode_attr(rpcobj, attr, atype)\n\n return instance\n else:\n return rpcobj\n\n @classmethod\n def rpc_decode(cls, rpcobj) -> 'RPCSerializable':\n \"\"\"\n Decode an rpc object into an instance of cls.\n \"\"\"\n return cls.rpc_decode_simple(rpcobj)\n\n def rpc_decode_attr(self, rpcobj: dict, attr: str, atype=None):\n \"\"\"\n Decode one attribute.\n \"\"\"\n if attr in rpcobj:\n attr_cls = self.get_class_for_type(atype)\n if attr_cls:\n setattr(self, attr,\n rpc_decode(attr_cls, rpcobj[attr]))\n else:\n setattr(self, attr, rpcobj[attr])\n\n @classmethod\n @_memoize\n def get_class_for_type(cls, atype):\n if atype is None:\n return None\n\n # try first if some class has a overridden type\n for sub in _itersubclasses(RPCSerializable):\n if sub.rpc_type == atype:\n return sub\n # then try with class name\n for sub in _itersubclasses(RPCSerializable):\n if sub.__name__ == atype:\n return sub\n\n return None\n\n", "tupelo/server/__init__.py": "\nfrom .server import *", "tupelo/server/jsonapi.py": "from typing import Optional\nimport json\nimport http.cookies\nimport urllib.parse\ntry:\n from urllib.parse import parse_qs\nexcept:\n from cgi import parse_qs\nfrom tupelo.common import ProtocolError\n\n\nclass TupeloJSONDispatcher():\n \"\"\"\n Simple JSON dispatcher mixin that calls the methods of \"instance\" member.\n \"\"\"\n\n json_path_prefix = '/api/'\n\n def __init__(self):\n self.instance = None\n\n def _json_parse_headers(self, headers) -> dict:\n \"\"\"\n Parse the HTTP headers and extract any params from them.\n \"\"\"\n params = {}\n # we support just 'akey' cookie\n cookie = http.cookies.SimpleCookie(headers.get('Cookie'))\n if 'akey' in cookie:\n params['akey'] = cookie['akey'].value\n\n return params\n\n def path2method(self, path: str) -> Optional[str]:\n \"\"\"\n Convert a request path to a method name.\n \"\"\"\n if self.json_path_prefix:\n if path.startswith(self.json_path_prefix):\n return path[len(self.json_path_prefix):].replace('/', '_')\n return None\n else:\n return path.lstrip('/').replace('/', '_')\n\n def _json_parse_qstring(self, qstring: str):\n \"\"\"\n Parse a query string into method and parameters.\n\n Return a tuple of (method_name, params).\n \"\"\"\n parsed = urllib.parse.urlparse(qstring)\n path = parsed[2]\n params = parse_qs(parsed[4])\n # use only the first value of any given parameter\n for k, v in list(params.items()):\n # try to decode a json parameter\n # if it fails, fall back to plain string\n try:\n params[k] = json.loads(v[0])\n except:\n params[k] = v[0]\n\n return (self.path2method(path), params)\n\n def register_instance(self, instance):\n \"\"\"\n Register the target object instance.\n \"\"\"\n self.instance = instance\n\n def json_dispatch(self, qstring: str, headers, body=None) -> str:\n \"\"\"\n Dispatch a JSON method call to the interface instance.\n \"\"\"\n method, qs_params = self._json_parse_qstring(qstring)\n if not method:\n raise ProtocolError('No such method')\n # alternatively, take params from body\n if not qs_params and body:\n (_, qs_params) = self._json_parse_qstring('?' + body.decode())\n\n # the querystring params override header params\n params = self._json_parse_headers(headers)\n params.update(qs_params)\n\n return json.dumps(self.instance._json_dispatch(method, params))\n", "tupelo/server/server.py": "#!/usr/bin/env python\n# vim: set sts=4 sw=4 et:\n\nimport copy\nimport logging\nimport queue\nimport xmlrpc.server\nimport inspect\nimport json\n\nfrom .xmlrpc import error2fault\nfrom tupelo.rpc import rpc_encode, rpc_decode\nfrom tupelo.common import Card, GameError, RuleError, ProtocolError, traced, short_uuid, simple_decorator, GameState\nfrom tupelo.game import GameController\nfrom tupelo.events import EventList, CardPlayedEvent, MessageEvent, TrickPlayedEvent, TurnEvent, StateChangedEvent\nfrom tupelo.players import Player, DummyBotPlayer\nfrom .jsonapi import TupeloJSONDispatcher\n\nDEFAULT_PORT = 8052\n\nVERSION_MAJOR = 0\nVERSION_MINOR = 1\nVERSION_STRING = \"%d.%d\" % (VERSION_MAJOR, VERSION_MINOR)\n\nlogger = logging.getLogger(__name__)\n\n@simple_decorator\ndef authenticated(fn):\n \"\"\"\n Method decorator to verify that the client sent a valid authentication\n key.\n \"\"\"\n def wrapper(self, akey, *args, **kwargs):\n self._ensure_auth(akey)\n try:\n retval = fn(self, *args, **kwargs)\n finally:\n self._clear_auth()\n\n return retval\n\n # copy argspec from wrapped function\n wrapper.argspec = inspect.getfullargspec(fn)\n # and add our extra arg\n wrapper.argspec.args.insert(0, 'akey')\n return wrapper\n\ndef _game_get_rpc_info(game):\n \"\"\"\n Get RPC info for a GameController instance.\n TODO: does not belong here.\n \"\"\"\n return [rpc_encode(player) for player in game.players]\n\n\n\nclass TupeloRequestHandler(xmlrpc.server.SimpleXMLRPCRequestHandler):\n \"\"\"\n Custom request handler class to support ajax/json API and XML-RPC, depending on the request path.\n \"\"\"\n\n rpc_paths = ('/RPC2',)\n json_paths = (TupeloJSONDispatcher.json_path_prefix,) # /api\n\n @traced\n def do_GET(self):\n for path in self.json_paths:\n if self.path.startswith(path):\n return self.handle_json_request()\n\n # XML-RPC supports only POST\n self.report_404()\n\n @traced\n def do_POST(self):\n for path in self.json_paths:\n if self.path.startswith(path):\n return self.handle_json_request(self.get_body())\n\n return super().do_POST()\n\n def get_body(self):\n try:\n # We read the body in chunks to avoid straining\n # socket.read(); around the 10 or 15Mb mark, some platforms\n # begin to have problems (bug #792570).\n max_chunk_size = 10*1024*1024\n size_remaining = int(self.headers[\"content-length\"])\n L = []\n while size_remaining:\n chunk_size = min(size_remaining, max_chunk_size)\n chunk = self.rfile.read(chunk_size)\n if not chunk:\n break\n L.append(chunk)\n size_remaining -= len(L[-1])\n data = b''.join(L)\n\n data = self.decode_request_content(data)\n return data\n\n except Exception as e: # This should only happen if the module is buggy\n # internal error, report as HTTP server error\n self.send_response(500)\n\n @traced\n def handle_json_request(self, body=None):\n try:\n response = self.server.json_dispatch(self.path, self.headers, body=body).encode()\n except ProtocolError as err:\n self.report_404()\n return\n except (GameError, RuleError) as err:\n logger.exception(err)\n self.send_response(403) # forbidden\n response_obj = {'code': err.rpc_code,\n 'message': str(err)}\n response = json.dumps(response_obj).encode()\n self.send_header(\"Content-type\", \"application/json\")\n self.send_header(\"Content-length\", str(len(response)))\n self.send_header(\"X-Error-Code\", str(err.rpc_code))\n self.send_header(\"X-Error-Message\", str(err))\n self.end_headers()\n\n self.wfile.write(response)\n # shut down the connection\n self.wfile.flush()\n self.connection.shutdown(1)\n except Exception as err:\n logger.exception(err)\n self.send_response(500)\n self.end_headers()\n else:\n self.send_response(200)\n self.send_header(\"Content-type\", \"application/json\")\n self.send_header(\"Content-length\", str(len(response)))\n self.send_header(\"Cache-Control\", \"no-cache\")\n self.send_header(\"Pragma\", \"no-cache\")\n\n self.end_headers()\n self.wfile.write(response)\n\n # shut down the connection\n self.wfile.flush()\n self.connection.shutdown(1)\n\nclass TupeloServer(xmlrpc.server.SimpleXMLRPCServer, TupeloJSONDispatcher):\n \"\"\"\n Custom server class that combines XML-RPC and JSON servers.\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n nargs = (args[0:1] or (None,)) + (TupeloRequestHandler,) + args[2:]\n xmlrpc.server.SimpleXMLRPCServer.__init__(self, *nargs, **kwargs)\n TupeloJSONDispatcher.__init__(self)\n rpciface = TupeloRPCInterface()\n self.register_instance(rpciface)\n\n def shutdown_games(self):\n \"\"\"\n Shut down all the games running on this instance.\n \"\"\"\n for game in self.instance.games:\n game.shutdown()\n\n\nclass TupeloRPCInterface():\n \"\"\"\n The RPC interface for the tupelo server.\n \"\"\"\n\n def __init__(self):\n super().__init__()\n self.players = []\n self.games = []\n self.methods = self._get_methods()\n self.authenticated_player = None\n\n def _get_methods(self):\n \"\"\"\n Get a list of RPC methods that this object supports.\n\n Return a dict of method_name => [argument names]\n \"\"\"\n method_names = [f for f in dir(self) if not f.startswith('_')]\n methods = dict()\n for mname in method_names:\n func = getattr(self, mname)\n if callable(func):\n # check if it is a decorated method\n if hasattr(func, 'argspec'):\n methods[mname] = func.argspec[0]\n else:\n methods[mname] = inspect.getfullargspec(func)[0]\n\n # remove 'self' from signature\n if 'self' in methods[mname]:\n methods[mname].remove('self')\n\n return methods\n\n def _get_player(self, player_id: int):\n \"\"\"\n Get player by id.\n \"\"\"\n for plr in self.players:\n if plr.id == player_id:\n return plr\n\n raise GameError('Player (ID %s) does not exist' % player_id)\n\n def _register_player(self, player: 'RPCProxyPlayer'):\n \"\"\"\n Register a new player to the server (internal function).\n \"\"\"\n # generate a (public) ID and (private) access token\n player.id = short_uuid()\n player.akey = short_uuid()\n self.players.append(player)\n return player.rpc_encode(private=True)\n\n def _ensure_auth(self, akey: str):\n \"\"\"\n Check the given authentication (session) key and set self.authenticated_player.\n\n Raises GameError if akey is not valid.\n \"\"\"\n for plr in self.players:\n if plr.akey == akey:\n self.authenticated_player = plr\n return self.authenticated_player\n\n raise GameError(\"Invalid authentication key\")\n\n def _clear_auth(self):\n \"\"\"\n Clear info about the authenticated player.\n \"\"\"\n self.authenticated_player = None\n\n def _get_game(self, game_id: str):\n \"\"\"\n Get game by id or raise an error.\n \"\"\"\n for game in self.games:\n if game.id == game_id:\n return game\n\n raise GameError('Game %s does not exist' % game_id)\n\n def echo(self, test):\n return test\n\n @error2fault\n def _dispatch(self, method, params):\n \"\"\"\n Dispatch an XML-RPC call.\n \"\"\"\n realname = method.replace('.', '_')\n if realname in list(self.methods.keys()):\n func = getattr(self, realname)\n return func(*params)\n\n raise ProtocolError('Method \"%s\" is not supported' % method)\n\n def _json_dispatch(self, method, kwparams):\n \"\"\"\n Dispatch a json method call to method with kwparams.\n \"\"\"\n if method in list(self.methods.keys()):\n func = getattr(self, method)\n # strip out invalid params\n for k in list(kwparams.keys()):\n if k not in self.methods[method]:\n del kwparams[k]\n try:\n return func(**kwparams)\n except TypeError as err:\n raise ProtocolError(str(err))\n\n raise ProtocolError('Method \"%s\" is not supported' % method)\n\n ### PUBLIC METHODS\n\n def hello(self, akey=None):\n \"\"\"\n Client says hello.\n\n Return a dict with server version and player/game info if the akey\n was valid.\n \"\"\"\n response = {'version': VERSION_STRING}\n try:\n self._ensure_auth(akey)\n except:\n pass\n\n # is the akey valid?\n if self.authenticated_player is not None:\n plr = self.authenticated_player\n response['player'] = plr.rpc_encode(private=True)\n if plr.game:\n response['game'] = _game_get_rpc_info(plr.game)\n\n self._clear_auth()\n return response\n\n def player_register(self, player):\n \"\"\"\n Register a new player to the server.\n\n Return the player id.\n \"\"\"\n player_obj = RPCProxyPlayer.rpc_decode(player)\n return self._register_player(player_obj)\n\n @authenticated\n def player_quit(self):\n \"\"\"\n Player quits.\n \"\"\"\n player = self.authenticated_player\n game = player.game\n # leave the game. Does not necessarily end the game.\n if game:\n try:\n self.game_leave(self.authenticated_player.akey, game.id)\n except GameError:\n pass\n\n self.players.remove(player)\n # without allow_none, XML-RPC methods must always return something\n return True\n\n @authenticated\n def player_list(self):\n \"\"\"\n List all players on server.\n \"\"\"\n return [rpc_encode(player) for player in self.players]\n\n def game_list(self, status=None):\n \"\"\"\n List all games on server that are in the given state.\n \"\"\"\n response = {}\n if status is not None:\n status = int(status)\n\n # TODO: add game state, joinable yes/no, password?\n for game in self.games:\n if status is None or game.state.status == status:\n response[str(game.id)] = _game_get_rpc_info(game)\n\n return response\n\n @authenticated\n def game_create(self):\n \"\"\"\n Create a new game and enter it.\n\n Return the game id.\n \"\"\"\n game = GameController()\n # TODO: slight chance of race\n self.games.append(game)\n game.id = short_uuid()\n try:\n self.game_enter(self.authenticated_player.akey, game.id)\n except GameError:\n self.games.remove(game)\n raise\n\n return game.id\n\n @authenticated\n def game_enter(self, game_id: str):\n \"\"\"\n Register a new player to the game.\n\n Return game ID\n \"\"\"\n game = self._get_game(game_id)\n player = self.authenticated_player\n if player.game:\n raise GameError(\"Player is already in a game\")\n\n game.register_player(player)\n player.game = game\n return game_id\n\n @authenticated\n def game_leave(self, game_id: str):\n \"\"\"\n Leave the game. Does not necessarily end the game.\n \"\"\"\n game = self._get_game(game_id)\n player = self.authenticated_player\n game.player_leave(player.id)\n player.game = None\n # if the game was terminated we need to kill the old game instance\n if len(game.players) == 0:\n self.games.remove(game)\n\n return True\n\n @authenticated\n def game_get_state(self, game_id: str):\n \"\"\"\n Get the state of a game for given player.\n \"\"\"\n game = self._get_game(game_id)\n response = {}\n response['game_state'] = rpc_encode(game.state)\n response['hand'] = rpc_encode(self.authenticated_player.hand)\n return response\n\n def game_get_info(self, game_id: str):\n \"\"\"\n Get the (static) information of a game.\n \"\"\"\n game = self._get_game(game_id)\n return _game_get_rpc_info(game)\n\n @authenticated\n def get_events(self):\n \"\"\"\n Get the list of new events for given player.\n \"\"\"\n return rpc_encode(self.authenticated_player.pop_events())\n\n @authenticated\n def game_start(self, game_id: str):\n \"\"\"\n Start a game.\n \"\"\"\n game = self._get_game(game_id)\n game.start_game()\n return True\n\n @authenticated\n def game_start_with_bots(self, game_id: str):\n \"\"\"\n Start a game with bots.\n \"\"\"\n game = self._get_game(game_id)\n i = 1\n while len(game.players) < 4:\n # register bots only to game so that we don't need to unregister them\n game.register_player(DummyBotPlayer('Robotti %d' % i))\n i += 1\n\n return self.game_start(self.authenticated_player.akey, game_id)\n\n @authenticated\n def game_play_card(self, game_id: str, card):\n \"\"\"\n Play one card in given game, by given player.\n \"\"\"\n game = self._get_game(game_id)\n player = self.authenticated_player\n game.play_card(player, rpc_decode(Card, card))\n return True\n\n\nclass RPCProxyPlayer(Player):\n \"\"\"\n Server-side class for remote/RPC players.\n \"\"\"\n def __init__(self, name):\n super().__init__(name)\n self.events = queue.Queue()\n self.game = None\n self.akey = None\n\n def rpc_encode(self, private=False) -> dict:\n rpcobj = Player.rpc_encode(self)\n # don't encode the game object, just the ID\n if self.game:\n rpcobj['game_id'] = rpc_encode(self.game.id)\n\n if private:\n if self.akey:\n rpcobj['akey'] = self.akey\n\n return rpcobj\n\n def vote(self):\n self.play_card()\n\n def play_card(self):\n self.send_event(TurnEvent(copy.deepcopy(self.game_state)))\n\n def card_played(self, player, card, game_state):\n self.send_event(CardPlayedEvent(player, card, copy.deepcopy(game_state)))\n\n def trick_played(self, player, game_state):\n self.send_event(TrickPlayedEvent(player, copy.deepcopy(game_state)))\n\n def state_changed(self, game_state):\n self.send_event(StateChangedEvent(copy.deepcopy(game_state)))\n\n def send_message(self, sender, msg):\n self.send_event(MessageEvent(sender, msg))\n\n def send_event(self, event):\n self.events.put(event)\n\n def pop_events(self):\n eventlist = EventList()\n try:\n while True:\n eventlist.append(self.events.get_nowait())\n except queue.Empty:\n pass\n\n return eventlist\n\n def act(self, controller, game_state: GameState):\n self.controller = controller\n self.game_state.update(game_state)\n if self.game_state.status == GameState.STOPPED:\n return\n elif self.game_state.status == GameState.VOTING:\n self.vote()\n elif self.game_state.status == GameState.ONGOING:\n self.play_card()\n else:\n logger.warning(\"Warning: unknown status %d\", self.game_state.status)\n\n", "tupelo/server/xmlrpc.py": "#!/usr/bin/env python\n# vim: set sts=4 sw=4 et:\n\nimport time\nimport xmlrpc.client\nfrom tupelo import players\nfrom tupelo import rpc\nfrom tupelo.common import GameState, CardSet, GameError, RuleError, ProtocolError, simple_decorator\nfrom tupelo.events import EventList, CardPlayedEvent, MessageEvent, TrickPlayedEvent, TurnEvent, StateChangedEvent\n\n@simple_decorator\ndef error2fault(func):\n \"\"\"\n Catch known exceptions and translate them to \n XML-RPC faults.\n \"\"\"\n def catcher(*args):\n try:\n return func(*args)\n except GameError as error:\n raise xmlrpc.client.Fault(GameError.rpc_code, str(error))\n except RuleError as error:\n raise xmlrpc.client.Fault(RuleError.rpc_code, str(error))\n except ProtocolError as error:\n raise xmlrpc.client.Fault(ProtocolError.rpc_code, str(error))\n return catcher\n\n@simple_decorator\ndef fault2error(func):\n \"\"\"\n Catch known XML-RPC faults and translate them to \n custom exceptions.\n \"\"\"\n def catcher(*args):\n try:\n return func(*args)\n except xmlrpc.client.Fault as error:\n error_classes = (GameError, RuleError, ProtocolError)\n for klass in error_classes:\n if error.faultCode == klass.rpc_code:\n raise klass(error.faultString)\n\n raise error\n\n return catcher\n\n\nclass XMLRPCCliPlayer(players.CliPlayer):\n \"\"\"\n XML-RPC command line interface human player.\n \"\"\"\n def __init__(self, player_name):\n players.CliPlayer.__init__(self, player_name)\n self.game_state = GameState()\n self.hand = None\n\n def handle_event(self, event):\n if isinstance(event, CardPlayedEvent):\n self.card_played(event.player, event.card, event.game_state)\n elif isinstance(event, MessageEvent):\n self.send_message(event.sender, event.message)\n elif isinstance(event, TrickPlayedEvent):\n self.trick_played(event.player, event.game_state)\n elif isinstance(event, TurnEvent):\n self.game_state.update(event.game_state)\n state = self.controller.get_state(self.id)\n self.hand = state['hand']\n self.game_state.update(state['game_state'])\n elif isinstance(event, StateChangedEvent):\n self.game_state.update(event.game_state)\n else:\n print(\"unknown event: %s\" % event)\n\n def wait_for_turn(self):\n \"\"\"\n Wait for this player's turn.\n \"\"\"\n while True:\n\n time.sleep(0.5)\n\n if self.controller is not None:\n events = self.controller.get_events(self.id)\n for event in events:\n self.handle_event(event)\n\n if self.game_state.turn_id == self.id:\n break\n\n\nclass XMLRPCProxyController():\n \"\"\"\n Client-side proxy object for the server/GameController.\n \"\"\"\n def __init__(self, server_uri):\n super(XMLRPCProxyController, self).__init__()\n if not server_uri.startswith('http://') and \\\n not server_uri.startswith('https://'):\n server_uri = 'http://' + server_uri\n\n self.server = xmlrpc.client.ServerProxy(server_uri)\n self.game_id = None\n self.akey = None\n\n @fault2error\n def play_card(self, _player, card):\n self.server.game.play_card(self.akey, self.game_id, rpc.rpc_encode(card))\n\n @fault2error\n def get_events(self, _player_id):\n return rpc.rpc_decode(EventList, self.server.get_events(self.akey))\n\n @fault2error\n def get_state(self, _player_id):\n state = self.server.game.get_state(self.akey, self.game_id)\n state['game_state'] = rpc.rpc_decode(GameState, state['game_state'])\n state['hand'] = rpc.rpc_decode(CardSet, state['hand'])\n return state\n\n @fault2error\n def player_quit(self, _player_id):\n self.server.player.quit(self.akey)\n\n @fault2error\n def register_player(self, player):\n player.controller = self\n plr_data = self.server.player.register(rpc.rpc_encode(player))\n player.id = plr_data['id']\n self.akey = plr_data['akey']\n\n @fault2error\n def start_game_with_bots(self):\n return self.server.game.start_with_bots(self.akey, self.game_id)\n\n @fault2error\n def create_game(self):\n self.game_id = self.server.game.create(self.akey)\n return self.game_id\n\n", "www/index.html": "\n\n\n\n\n\n\n \n\n\n\n\nTupelo\n\n\n
            \n
            \ntupelo\n
            \n
            \n

            \n\n\n

            \n
            \n
            \n

            \nSigned on as \n

            \n
            \n
            \n
            \n
            \n
            \n

            list of games

            \n
            \n\n\n\n
            \n
            \n
            \n\n
            \n
            \n
            \n

            players online

            \n
            \n\n\n\n
            \n
            \n
            \n
            \n

            \n\n\n\n
            \n
            \n
            \n
            \n\n\n\n\n\n\n
            \n
            \n
            \n

            log

            \n\n
            \n
            \n
            \n
            \n\n\n", "www/tupelo-main.js": "// Generated by CoffeeScript 2.5.1\n(function() {\n // tupelo-main.coffee\n // vim: sts=2 sw=2 et:\n var $,\n hasProp = {}.hasOwnProperty;\n\n $ = jQuery;\n\n $(document).ready(function() {\n var ajaxErr, cardClicked, cardPlayed, clearTable, dbg, escapeHtml, eventsOk, gameCreateOk, gameInfoOk, getGameState, getTeamPlayers, hello, leaveOk, leftGame, listGamesOk, listPlayersOk, messageReceived, processEvent, quitOk, registerOk, request, setState, startOk, stateChanged, states, trickPlayed, tupelo, turnEvent, updateGameLinks, updateGameState, updateHand, updateLists;\n // status object\n tupelo = {\n game_state: {},\n events: [],\n config: {\n serverBaseUrl: \"/api\"\n }\n };\n states = {\n initial: {\n show: [\"#register_form\"],\n hide: [\"#quit_form\", \"#games\", \"#players\", \"#my_game\", \"#game\"],\n change: function() {\n var reg;\n reg = $(\"#register_name\");\n reg.addClass(\"initial\");\n reg.val(\"Your name\");\n }\n },\n registered: {\n show: [\"#quit_form\", \"#games\", \"#players\", \"#game_create_form\"],\n hide: [\"#register_form\", \"#my_game\", \"#game\"],\n change: function() {\n if (tupelo.list_timer == null) {\n return tupelo.list_timer = setInterval(updateLists, 5000);\n }\n }\n },\n gameCreated: {\n show: [\"#my_game\"],\n hide: [\"#game_create_form\"]\n },\n inGame: {\n show: [\"#game\"],\n hide: [\"#games\", \"#players\", \"#my_game\"]\n }\n };\n // change the current state\n setState = function(state, effectDuration) {\n var elem, j, k, len, len1, ref, ref1, st;\n st = states[state];\n ref = st.hide;\n for (j = 0, len = ref.length; j < len; j++) {\n elem = ref[j];\n $(elem).hide(effectDuration);\n }\n ref1 = st.show;\n for (k = 0, len1 = ref1.length; k < len1; k++) {\n elem = ref1[k];\n $(elem).show(effectDuration);\n }\n if (st.change != null) {\n return st.change();\n }\n };\n escapeHtml = function(str) {\n return str.replace(\"<\", \"<\").replace(\">\", \">\");\n };\n dbg = function() {\n if (T.debug) {\n return $(\"#debug\").html(JSON.stringify(tupelo));\n }\n };\n // generic ajax error callback\n ajaxErr = function(xhr, astatus, error) {\n var handled, jsonErr;\n handled = false;\n // 403 is for game and rule errors\n if (xhr.status === 403) {\n // parse from json\n jsonErr = eval(\"(\" + xhr.responseText + \")\");\n if (jsonErr.message != null) {\n window.alert(jsonErr.message);\n handled = true;\n }\n } else {\n T.log(\"status: \" + astatus);\n T.log(\"error: \" + error);\n }\n return handled;\n };\n request = function(opts) {\n opts.url = tupelo.config.serverBaseUrl + opts.url;\n opts.error = opts.error || ajaxErr;\n return $.ajax(opts);\n };\n hello = function() {\n return request({\n url: \"/hello\",\n success: function(result) {\n T.log(\"Server version: \" + result.version);\n // are we already logged in?\n if (result.player != null) {\n tupelo.player = new T.Player(result.player.player_name);\n registerOk(result.player);\n // are we in a game?\n if (result.player.game_id != null) {\n return gameCreateOk(result.player.game_id);\n }\n }\n }\n });\n };\n updateGameLinks = function(disabledIds) {\n var gameJoinClicked, id, j, len;\n gameJoinClicked = function(event) {\n var game_id;\n // \"game_join_ID\"\n game_id = this.id.slice(10);\n T.log(\"joining game \" + game_id);\n return request({\n url: \"/game/enter\",\n data: {\n akey: tupelo.player.akey,\n game_id: game_id\n },\n success: gameCreateOk\n });\n };\n if (tupelo.game_id != null) {\n $(\"button.game_join\").attr(\"disabled\", true);\n return $(\"tr#game_id_\" + tupelo.game_id).addClass(\"highlight\");\n } else {\n for (j = 0, len = disabledIds.length; j < len; j++) {\n id = disabledIds[j];\n $(\"button#\" + id).attr(\"disabled\", true);\n }\n return $(\"button.game_join\").click(gameJoinClicked);\n }\n };\n listGamesOk = function(result) {\n var disabledIds, game_id, html, players, res;\n //T.log \"listGamesOk\"\n //T.log result\n html = \"\";\n disabledIds = [];\n for (game_id in result) {\n if (!hasProp.call(result, game_id)) continue;\n html += ``;\n //players = []\n //for res in result[game_id]\n // plr = new T.Player().fromObj res\n // players.push plr.player_name\n players = (function() {\n var j, len, ref, results;\n ref = result[game_id];\n results = [];\n for (j = 0, len = ref.length; j < len; j++) {\n res = ref[j];\n results.push(new T.Player().fromObj(res).player_name);\n }\n return results;\n })();\n html += \"\" + escapeHtml(players.join(\", \")) + \"\";\n html += \"\";\n html += \"\";\n if (players.length === 4) {\n disabledIds.push(`game_join_${game_id}`);\n }\n }\n $(\"#game_list table tbody\").html(html);\n updateGameLinks(disabledIds);\n return dbg();\n };\n listPlayersOk = function(result) {\n var cls, html, player, plr;\n T.log(result);\n html = \"\";\n for (player in result) {\n if (!hasProp.call(result, player)) continue;\n plr = new T.Player().fromObj(result[player]);\n if (plr.id !== tupelo.player.id) {\n cls = plr.game_id != null ? \"class=\\\"in_game\\\" \" : \"\";\n html += `\";\n html += \"\" + escapeHtml(plr.player_name) + \"\";\n }\n }\n $(\"#player_list table tbody\").html(html);\n return dbg();\n };\n registerOk = function(result) {\n $(\"#name\").val(\"\");\n tupelo.player.id = result.id;\n tupelo.player.akey = result.akey;\n Cookies.set(\"akey\", result.akey);\n T.log(tupelo);\n dbg();\n // clear game list if there was one previously\n $(\"#game_list table tbody\").html(\"\");\n $(\".my_name\").html(escapeHtml(tupelo.player.player_name));\n updateLists();\n setState(\"registered\", \"fast\");\n return T.log(\"timer created\");\n };\n leftGame = function() {\n if (tupelo.event_fetch_timer != null) {\n tupelo.event_fetch_timer.disable();\n tupelo.event_fetch_timer = null;\n }\n if (tupelo.event_timer != null) {\n clearTimeout(tupelo.event_timer);\n tupelo.event_timer = null;\n }\n tupelo.game_id = null;\n tupelo.game_state = {};\n tupelo.hand = null;\n tupelo.my_turn = null;\n };\n leaveOk = function(result) {\n leftGame();\n dbg();\n updateLists();\n return setState(\"registered\", \"fast\");\n };\n quitOk = function(result) {\n leftGame();\n if (tupelo.list_timer != null) {\n clearInterval(tupelo.list_timer);\n tupelo.list_timer = null;\n }\n Cookies.remove(\"akey\");\n tupelo.player = null;\n T.log(tupelo);\n dbg();\n return setState(\"initial\", \"fast\");\n };\n gameCreateOk = function(result) {\n tupelo.game_id = result;\n T.log(tupelo);\n dbg();\n $(\"p#joined_game\").html(`joined game ${tupelo.game_id}`);\n setState(\"gameCreated\", \"fast\");\n tupelo.event_fetch_timer = new T.Timer(tupelo.config.serverBaseUrl + \"/get_events\", 2000, eventsOk, {\n data: {\n akey: tupelo.player.akey\n }\n });\n return updateLists();\n };\n cardPlayed = function(event) {\n var card, table;\n T.log(\"cardPlayed\");\n //T.log event\n table = $(\"#player_\" + event.player.id + \" .table\");\n if (table.length === 0) {\n T.log(\"player not found!\");\n return true;\n }\n //table.hide()\n card = new T.Card(event.card.suit, event.card.value);\n table.html(\"\" + card.toShortHtml() + \"\");\n table.children().show(500);\n setTimeout(processEvent, 500);\n return false;\n };\n messageReceived = function(event) {\n var eventLog;\n T.log(\"messageReceived\");\n eventLog = $(\"#event_log\");\n eventLog.append(escapeHtml(event.sender) + \": \" + escapeHtml(event.message) + \"\\n\");\n eventLog.scrollTop(eventLog[0].scrollHeight - eventLog.height());\n return true;\n };\n // clear the table and resume event processing\n // called either from timeout or click event\n clearTable = function() {\n clearTimeout(tupelo.clear_timeout);\n T.log(\"clearing table\");\n $(\"#game_area .table\").html(\"\");\n $(\"#game_area table tbody\").unbind(\"click\");\n // re-enable event processing\n return tupelo.event_timer = setTimeout(processEvent, 0);\n };\n //T.log(\"trickPlayed: set event_timer to \" + tupelo.event_timer)\n trickPlayed = function(event) {\n T.log(\"trickPlayed\");\n // TODO: highlight the highest card\n // allow the user to clear the table and proceed by clicking the table\n $(\"#game_area table tbody\").click(clearTable);\n // setting timeout to show the played trick for a longer time\n tupelo.clear_timeout = setTimeout(clearTable, 5000);\n return false; // this event is not handled yet\n };\n getTeamPlayers = function(team) {\n // TODO: should we store these in JS instead of the DOM?\n return [$(\"#table_\" + team + \" .player_name\").html(), $(\"#table_\" + (team + 2) + \" .player_name\").html()];\n };\n updateGameState = function(state) {\n var key, statusStr;\n statusStr = \"\";\n for (key in state) {\n if (!hasProp.call(state, key)) continue;\n tupelo.game_state[key] = state[key];\n }\n // show game status (voting, nolo, rami)\n if (state.status === T.VOTING) {\n statusStr = \"VOTING\";\n } else if (state.status === T.ONGOING) {\n if (state.mode === T.NOLO) {\n statusStr = \"NOLO\";\n } else {\n if (state.mode === T.RAMI) {\n statusStr = \"RAMI\";\n }\n }\n }\n statusStr = `${statusStr}`;\n statusStr += \"tricks: \" + state.tricks[0] + \" - \" + state.tricks[1] + \"\";\n if (state.score != null) {\n if (state.score[0] > 0) {\n statusStr += \"score: \" + escapeHtml(getTeamPlayers(0).join(\" & \")) + \": \" + state.score[0] + \"\";\n } else if (state.score[1] > 0) {\n statusStr += \"score: \" + escapeHtml(getTeamPlayers(1).join(\" & \")) + \": \" + state.score[1] + \"\";\n } else {\n statusStr += \"score: 0\";\n }\n }\n $(\"#game_status\").html(statusStr);\n // highlight the player in turn\n if (state.turn_id != null) {\n $(\".player_data .player_name\").removeClass(\"highlight_player\");\n $(\"#player_\" + state.turn_id + \" .player_name\").addClass(\"highlight_player\");\n }\n return dbg();\n };\n cardClicked = function(event) {\n var card, cardId;\n // id is \"card_X\"\n cardId = $(this).find(\".card\").attr(\"id\").slice(5);\n card = tupelo.hand[cardId];\n T.log(card);\n if (card != null) {\n request({\n url: \"/game/play_card\",\n success: function(result) {\n tupelo.my_turn = false;\n $(\"#hand .card\").removeClass(\"card_selectable\");\n // TODO: after playing a hand, this shows the next hand too quickly\n return getGameState();\n },\n error: function(xhr, astatus, error) {\n if (ajaxErr(xhr, astatus, error) !== true) {\n return window.alert(xhr.status + \" \" + error);\n }\n },\n data: {\n akey: tupelo.player.akey,\n game_id: tupelo.game_id,\n card: JSON.stringify(card)\n }\n });\n }\n return event.preventDefault();\n };\n updateHand = function(newHand) {\n var card, hand, html, i, item, j, len;\n html = \"\";\n hand = [];\n for (i = j = 0, len = newHand.length; j < len; i = ++j) {\n item = newHand[i];\n card = new T.Card(item.suit, item.value);\n hand.push(card);\n if (tupelo.my_turn) {\n html += \"\";\n }\n html += `` + card.toShortHtml() + \"\";\n if (tupelo.my_turn) {\n html += \"\";\n }\n }\n tupelo.hand = hand;\n $(\"#hand\").html(html);\n if (tupelo.my_turn) {\n $(\"#hand .card\").addClass(\"card_selectable\");\n return $(\"#hand a\").click(cardClicked);\n }\n };\n getGameState = function() {\n return request({\n url: \"/game/get_state\",\n success: function(result) {\n T.log(result);\n if (result.game_state != null) {\n updateGameState(result.game_state);\n }\n if (result.hand != null) {\n return updateHand(result.hand);\n }\n },\n data: {\n akey: tupelo.player.akey,\n game_id: tupelo.game_id\n }\n });\n };\n turnEvent = function(event) {\n T.log(\"turnEvent\");\n tupelo.my_turn = true; // enables click callbacks for cards in hand\n getGameState();\n return true;\n };\n stateChanged = function(event) {\n T.log(\"stateChanged\");\n if (event.game_state.status === T.VOTING) { // game started!\n startOk();\n } else if (event.game_state.status === T.ONGOING) { // VOTING -> ONGOING\n // allow the user to clear the table and proceed by clicking the table\n $(\"#game_area table tbody\").click(clearTable);\n // setting timeout to show the voted cards for a longer time\n tupelo.clear_timeout = setTimeout(clearTable, 5000);\n return false;\n }\n return true;\n };\n processEvent = function() {\n var event, handled;\n handled = true;\n if (tupelo.events.length === 0) {\n T.log(\"no events to process\");\n tupelo.event_timer = null;\n return;\n }\n event = tupelo.events.shift();\n if (event.game_state != null) {\n updateGameState(event.game_state);\n }\n switch (event.type) {\n case 1:\n handled = cardPlayed(event);\n break;\n case 2:\n handled = messageReceived(event);\n break;\n case 3:\n handled = trickPlayed(event);\n break;\n case 4:\n handled = turnEvent(event);\n break;\n case 5:\n handled = stateChanged(event);\n break;\n default:\n T.log(\"unknown event \" + event.type);\n }\n if (handled === true) {\n return tupelo.event_timer = setTimeout(processEvent, 0);\n }\n };\n eventsOk = function(result) {\n var event, j, len;\n for (j = 0, len = result.length; j < len; j++) {\n event = result[j];\n /*\n if (result.length > 0)\n eventLog = $(\"#event_log\")\n eventLog.append(JSON.stringify(result) + \"\\n\")\n eventLog.scrollTop(eventLog[0].scrollHeight - eventLog.height())\n */\n // push events to queue\n tupelo.events.push(event);\n }\n if (tupelo.events.length > 0 && (tupelo.event_timer == null)) {\n tupelo.event_timer = setTimeout(processEvent, 0);\n }\n return dbg();\n };\n gameInfoOk = function(result) {\n var i, index, j, k, len, len1, myIndex, pl;\n T.log(\"gameInfoOk\");\n T.log(result);\n myIndex = 0;\n// find my index\n for (i = j = 0, len = result.length; j < len; i = ++j) {\n pl = result[i];\n if (pl.id === tupelo.player.id) {\n myIndex = i;\n break;\n }\n }\n for (i = k = 0, len1 = result.length; k < len1; i = ++k) {\n pl = result[i];\n // place where the player goes when /me is always at the bottom\n index = (4 + i - myIndex) % 4;\n // set player id and name\n $(\"#table_\" + index + \" .player_data\").attr(\"id\", \"player_\" + pl.id);\n $(\"#player_\" + pl.id + \" .player_name\").html(escapeHtml(pl.player_name));\n }\n };\n startOk = function(result) {\n if (tupelo.list_timer != null) {\n clearInterval(tupelo.list_timer);\n tupelo.list_timer = null;\n }\n $(\"#event_log\").html(\"\");\n setState(\"inGame\");\n request({\n url: \"/game/get_info\",\n success: gameInfoOk,\n data: {\n game_id: tupelo.game_id\n }\n });\n getGameState();\n return dbg();\n };\n updateLists = function() {\n request({\n url: \"/game/list\",\n success: listGamesOk\n });\n return request({\n url: \"/player/list\",\n success: listPlayersOk,\n data: {\n akey: tupelo.player.akey\n }\n });\n };\n // bind DOM events\n $(\"#echo_ajax\").click(function() {\n var text;\n text = $(\"#echo\").val();\n return request({\n url: \"/echo\",\n data: {\n test: text\n },\n success: function(result) {\n $(\"#echo_result\").html(escapeHtml(result));\n return $(\"#echo\").val(\"\");\n }\n });\n });\n $(\"#register_btn\").click(function() {\n var input, name;\n input = $(\"#register_name\");\n name = input.val();\n if (!name || input.hasClass(\"initial\")) {\n alert(\"Please enter your name first\");\n return;\n }\n tupelo.player = new T.Player(name);\n T.log(tupelo);\n return request({\n url: \"/player/register\",\n data: {\n player: JSON.stringify(tupelo.player)\n },\n success: registerOk\n });\n });\n // sign in by pressing enter\n $(\"#register_name\").keyup(function(event) {\n if ((event.keyCode || event.which) === 13) {\n return $(\"#register_btn\").click();\n }\n });\n $(\"#register_name\").focus(function(event) {\n if ($(this).hasClass(\"initial\")) {\n $(this).val(\"\");\n return $(this).removeClass(\"initial\");\n }\n });\n $(\"#quit_btn\").click(function() {\n return request({\n url: \"/player/quit\",\n data: {\n akey: tupelo.player.akey\n },\n success: quitOk,\n error: function(xhr, astatus, error) {\n if (ajaxErr(xhr, astatus, error) === true) {\n return quitOk();\n }\n }\n });\n });\n $(\".game_leave_btn\").click(function() {\n // TODO: should we cancel timers already here?\n return request({\n url: \"/game/leave\",\n data: {\n akey: tupelo.player.akey,\n game_id: tupelo.game_id\n },\n success: leaveOk,\n error: function(xhr, astatus, error) {\n if (ajaxErr(xhr, astatus, error) === true) {\n return leaveOk();\n }\n }\n });\n });\n $(\"#game_create_btn\").click(function() {\n // TODO: should we cancel timers already here?\n return request({\n url: \"/game/create\",\n data: {\n akey: tupelo.player.akey\n },\n success: gameCreateOk\n });\n });\n $(\"#game_start\").click(function() {\n return request({\n url: \"/game/start\",\n data: {\n akey: tupelo.player.akey,\n game_id: tupelo.game_id\n },\n success: startOk\n });\n });\n $(\"#game_start_with_bots\").click(function() {\n return request({\n url: \"/game/start_with_bots\",\n data: {\n akey: tupelo.player.akey,\n game_id: tupelo.game_id\n },\n success: startOk\n });\n });\n if (T.debug === true) {\n $(\"#debug\").click(function() {\n return $(this).toggle();\n });\n } else {\n $(\"#debug\").hide();\n }\n // leave the game when the user leaves the page\n $(window).unload(function() {\n if (tupelo.game_id != null) {\n return request({\n url: \"/game/leave\",\n async: false,\n data: {\n akey: tupelo.player.akey,\n game_id: tupelo.game_id\n }\n });\n }\n });\n // show a confirmation if the browser supports it\n window.onbeforeunload = function(e) {\n var msg;\n if (tupelo.game_id == null) {\n return undefined; // no dialog\n }\n e = e || window.event;\n msg = \"By leaving the page you will also leave the game.\";\n if (e) {\n e.returnValue = msg;\n }\n return msg;\n };\n // and finally, contact the server\n hello();\n return setState(\"initial\");\n });\n\n}).call(this);\n"}} -{"repo": "jaytoday/Django-Socialauth", "pr_number": 1, "title": "Update from original - master", "state": "closed", "merged_at": "2023-12-28T17:40:20Z", "additions": 4166, "deletions": 1092, "files_changed": ["example_project/__init__.py", "example_project/commentor/__init__.py", "example_project/commentor/models.py", "example_project/commentor/templates/commentor/index.html", "example_project/commentor/tests.py", "example_project/commentor/urls.py", "example_project/commentor/views.py", "example_project/example/__init__.py", "example_project/example/admin.py", "example_project/example/models.py", "example_project/example/templates/comments/example/form.html", "example_project/example/templates/comments/example/list.html", "example_project/example/templates/example/post_detail.html", "example_project/example/templates/example/post_list.html", "example_project/example/tests.py", "example_project/example/urls.py", "example_project/example/views.py", "example_project/example_comments/__init__.py", "example_project/example_comments/models.py", "example_project/example_comments/tests.py", "example_project/example_comments/views.py", "example_project/localsettings.example.py", "example_project/manage.py"], "files_before": {}, "files_after": {"example_project/__init__.py": "", "example_project/commentor/__init__.py": "", "example_project/commentor/models.py": "from django.db import models\n\nclass Comment(models.Model):\n comment = models.TextField()\n", "example_project/commentor/templates/commentor/index.html": "{% extends 'base.html' %}\n\n{% block main_content %}\n\nEnter Comment\n\n{% if user.is_authenticated %}\n\n

            You are currently logged in as {{ user.username }}

            \n\n
            \n {{ form }}\n \n
            \nLogout\n{% else %}\n\nLogin\n\n{% endif %}\n\n\n{% for comment in comments %}\n\n

            \n {{ comment.comment }}\n

            \n\n{% endfor %}\n\n{% endblock %}", "example_project/commentor/tests.py": "\"\"\"\nThis file demonstrates two different styles of tests (one doctest and one\nunittest). These will both pass when you run \"manage.py test\".\n\nReplace these with more appropriate tests for your application.\n\"\"\"\n\nfrom django.test import TestCase\n\nclass SimpleTest(TestCase):\n def test_basic_addition(self):\n \"\"\"\n Tests that 1 + 1 always equals 2.\n \"\"\"\n self.failUnlessEqual(1 + 1, 2)\n\n__test__ = {\"doctest\": \"\"\"\nAnother way to test that 1 + 1 is equal to 2.\n\n>>> 1 + 1 == 2\nTrue\n\"\"\"}\n\n", "example_project/commentor/urls.py": "", "example_project/commentor/views.py": "from django.contrib.auth.decorators import login_required\nfrom django.http import HttpResponseRedirect\nfrom commentor.models import Comment\nfrom django.template import RequestContext\nfrom django import forms\nfrom django.shortcuts import render_to_response\n\n@login_required\ndef leave_comment(request):\n form = CommentForm()\n if request.POST:\n form = CommentForm(data = request.POST)\n if form.is_valid():\n form.save()\n return HttpResponseRedirect('.')\n \n payload = {'form':form, 'comments':Comment.objects.all()}\n return render_to_response('commentor/index.html', payload, RequestContext(request))\n \nclass CommentForm(forms.ModelForm):\n class Meta:\n model = Comment", "example_project/example/__init__.py": "", "example_project/example/admin.py": "from models import Post\nfrom django.contrib import admin\n\nadmin.site.register(Post)\n\n", "example_project/example/models.py": "from django.db import models\nfrom django.contrib.auth.models import User\n# Create your models here.\n\nclass Post(models.Model):\n author = models.ForeignKey(User)\n date = models.DateTimeField()\n title = models.CharField(max_length=100)\n post = models.TextField()\n\n def __unicode__(self):\n return self.title\n", "example_project/example/templates/comments/example/form.html": "{% load comments i18n %}\n\n
            {% csrf_token %}\n {% if next %}{% endif %}\n {% for field in form %}\n {% if field.is_hidden %}\n {{ field }}\n {% else %}\n {% if field.errors %}{{ field.errors }}{% endif %}\n \n {{ field.label_tag }} {{ field }}\n

            \n {% endif %}\n {% endfor %}\n \n

            \n \n \n

            \n\n", "example_project/example/templates/comments/example/list.html": "
            \n {% for comment in comment_list %}\n
            \n

            {{ comment.comment }}

            \n
            \n
            \n on {{ comment.submit_date|date }} at {{ comment.submit_date|time }} by {{ comment.name }}\n
            \n {% endfor %}\n
            \n", "example_project/example/templates/example/post_detail.html": "{% load comments socialauth_tags %}\n\n

            {{ post }}

            \n

            {{ post.post }}

            \n
            \n posted by {{ post.author }} on {{ post.date|date }} at {{ post.date|time }}\n
            \n
            \n Comments:\n
            \n {% render_comment_list for post %}\n
            \n {% if request.user.username %}\n Comment as {% get_calculated_username request.user %} \n (Not {% get_calculated_username request.user %}?)\n {% render_comment_form for post %}\n {% else %}\n Login to comment\n {% endif %}\n", "example_project/example/templates/example/post_list.html": "{% load comments %}\n{{ latest }}\n{% if object_list %}\n {% for post in object_list %}\n

            {{ post }}

            \n

            {{ post.post }}

            \n {% get_comment_count for post as comment_count %}\n {{ post.author }} wrote {{ post.post|wordcount }} words on {{ post.date|date }} at {{ post.date|time }}\n
            \n \n {{ comment_count }} comments\n \n {% endfor %}\n{% else %}\n Add a new blog post\n{% endif %}\n", "example_project/example/tests.py": "\"\"\"\nThis file demonstrates two different styles of tests (one doctest and one\nunittest). These will both pass when you run \"manage.py test\".\n\nReplace these with more appropriate tests for your application.\n\"\"\"\n\nfrom django.test import TestCase\n\nclass SimpleTest(TestCase):\n def test_basic_addition(self):\n \"\"\"\n Tests that 1 + 1 always equals 2.\n \"\"\"\n self.failUnlessEqual(1 + 1, 2)\n\n__test__ = {\"doctest\": \"\"\"\nAnother way to test that 1 + 1 is equal to 2.\n\n>>> 1 + 1 == 2\nTrue\n\"\"\"}\n\n", "example_project/example/urls.py": "from django.conf.urls.defaults import *\nfrom models import Post\n\nurlpatterns = patterns('',\n url(r'^(?P\\d+)$', 'example.views.post_detail'),\n url(r'^$', 'django.views.generic.list_detail.object_list',\n { 'queryset' : Post.objects.all() }\n ),\n)\n", "example_project/example/views.py": "# Create your views here.\nfrom django.shortcuts import render_to_response, get_object_or_404\nfrom django.http import HttpResponseRedirect\nfrom django.contrib.comments.models import Comment\nfrom models import Post\nfrom django.template import RequestContext\n\ndef comment_posted(request):\n comment_id = request.GET['c']\n post_id = Comment.objects.get(id=comment_id).content_object.id\n return HttpResponseRedirect('/blog/'+str(post_id))\n\ndef post_detail(request, post_id):\n post = get_object_or_404(Post, pk=post_id)\n return render_to_response('example/post_detail.html', {'post': post}, context_instance=RequestContext(request))\n", "example_project/example_comments/__init__.py": "from django import forms\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.contrib.comments.forms import CommentDetailsForm\n\nclass CommentForm(CommentDetailsForm):\n name = forms.CharField(widget=forms.HiddenInput, required=False)\n email = forms.EmailField(widget=forms.HiddenInput, required=False)\n url = forms.URLField(widget=forms.HiddenInput, required=False)\n\n\ndef get_form():\n return CommentForm\n", "example_project/example_comments/models.py": "from django.db import models\n\n# Create your models here.\n", "example_project/example_comments/tests.py": "\"\"\"\nThis file demonstrates two different styles of tests (one doctest and one\nunittest). These will both pass when you run \"manage.py test\".\n\nReplace these with more appropriate tests for your application.\n\"\"\"\n\nfrom django.test import TestCase\n\nclass SimpleTest(TestCase):\n def test_basic_addition(self):\n \"\"\"\n Tests that 1 + 1 always equals 2.\n \"\"\"\n self.failUnlessEqual(1 + 1, 2)\n\n__test__ = {\"doctest\": \"\"\"\nAnother way to test that 1 + 1 is equal to 2.\n\n>>> 1 + 1 == 2\nTrue\n\"\"\"}\n\n", "example_project/example_comments/views.py": "# Create your views here.\n\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.comments.views.comments import post_comment as old_post_comment\n\n@login_required\ndef post_comment(request):\n return old_post_comment(request)\n", "example_project/localsettings.example.py": "OPENID_REDIRECT_NEXT = '/accounts/openid/done/'\n\nOPENID_SREG = {\"requred\": \"nickname, email, fullname\",\n \"optional\":\"postcode, country\",\n \"policy_url\": \"\"}\n\n#example should be something more like the real thing, i think\nOPENID_AX = [{\"type_uri\": \"http://axschema.org/contact/email\",\n \"count\": 1,\n \"required\": True,\n \"alias\": \"email\"},\n {\"type_uri\": \"http://axschema.org/schema/fullname\",\n \"count\":1 ,\n \"required\": False,\n \"alias\": \"fname\"}]\n\nOPENID_AX_PROVIDER_MAP = {'Google': {'email': 'http://axschema.org/contact/email',\n 'firstname': 'http://axschema.org/namePerson/first',\n 'lastname': 'http://axschema.org/namePerson/last'},\n 'Default': {'email': 'http://axschema.org/contact/email',\n 'fullname': 'http://axschema.org/namePerson',\n 'nickname': 'http://axschema.org/namePerson/friendly'}\n }\n\nTWITTER_CONSUMER_KEY = ''\nTWITTER_CONSUMER_SECRET = ''\n\nFACEBOOK_APP_ID = ''\nFACEBOOK_API_KEY = ''\nFACEBOOK_SECRET_KEY = ''\n\nLINKEDIN_CONSUMER_KEY = ''\nLINKEDIN_CONSUMER_SECRET = ''\n\nGITHUB_CLIENT_ID = ''\nGITHUB_CLIENT_SECRET = ''\n\nFOURSQUARE_CONSUMER_KEY = ''\nFOURSQUARE_CONSUMER_SECRET = ''\nFOURSQUARE_REGISTERED_REDIRECT_URI = ''\n\n## if any of this information is desired for your app\nFACEBOOK_EXTENDED_PERMISSIONS = (\n #'publish_stream',\n #'create_event',\n #'rsvp_event',\n #'sms',\n #'offline_access',\n #'email',\n #'read_stream',\n #'user_about_me',\n #'user_activites',\n #'user_birthday',\n #'user_education_history',\n #'user_events',\n #'user_groups',\n #'user_hometown',\n #'user_interests',\n #'user_likes',\n #'user_location',\n #'user_notes',\n #'user_online_presence',\n #'user_photo_video_tags',\n #'user_photos',\n #'user_relationships',\n #'user_religion_politics',\n #'user_status',\n #'user_videos',\n #'user_website',\n #'user_work_history',\n #'read_friendlists',\n #'read_requests',\n #'friend_about_me',\n #'friend_activites',\n #'friend_birthday',\n #'friend_education_history',\n #'friend_events',\n #'friend_groups',\n #'friend_hometown',\n #'friend_interests',\n #'friend_likes',\n #'friend_location',\n #'friend_notes',\n #'friend_online_presence',\n #'friend_photo_video_tags',\n #'friend_photos',\n #'friend_relationships',\n #'friend_religion_politics',\n #'friend_status',\n #'friend_videos',\n #'friend_website',\n #'friend_work_history',\n)\n\n\nAUTHENTICATION_BACKENDS = (\n 'django.contrib.auth.backends.ModelBackend',\n 'socialauth.auth_backends.OpenIdBackend',\n 'socialauth.auth_backends.TwitterBackend',\n 'socialauth.auth_backends.FacebookBackend',\n 'socialauth.auth_backends.LinkedInBackend',\n 'socialauth.auth_backends.GithubBackend',\n 'socialauth.auth_backends.FoursquareBackend',\n)\n", "example_project/manage.py": "#!/usr/bin/env python\nfrom django.core.management import execute_manager\ntry:\n import settings # Assumed to be in the same directory.\nexcept ImportError:\n import sys\n sys.stderr.write(\"Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\\nYou'll have to run django-admin.py, passing it your settings module.\\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\\n\" % __file__)\n sys.exit(1)\n\nif __name__ == \"__main__\":\n execute_manager(settings)\n"}} -{"repo": "pixelb/scripts", "pr_number": 19, "title": "Add --css-only and --body-only args", "state": "closed", "merged_at": null, "additions": 66, "deletions": 51, "files_changed": ["scripts/ansi2html.sh"], "files_before": {"scripts/ansi2html.sh": "#!/bin/sh\n\n# Convert ANSI (terminal) colours and attributes to HTML\n\n# Licence: LGPLv2\n# Author:\n# http://www.pixelbeat.org/docs/terminal_colours/\n# Examples:\n# ls -l --color=always | ansi2html.sh > ls.html\n# git show --color | ansi2html.sh > last_change.html\n# Generally one can use the `script` util to capture full terminal output.\n# Changes:\n# V0.1, 24 Apr 2008, Initial release\n# V0.2, 01 Jan 2009, Phil Harnish \n# Support `git diff --color` output by\n# matching ANSI codes that specify only\n# bold or background colour.\n# P@draigBrady.com\n# Support `ls --color` output by stripping\n# redundant leading 0s from ANSI codes.\n# Support `grep --color=always` by stripping\n# unhandled ANSI codes (specifically ^[[K).\n# V0.3, 20 Mar 2009, http://eexpress.blog.ubuntu.org.cn/\n# Remove cat -v usage which mangled non ascii input.\n# Cleanup regular expressions used.\n# Support other attributes like reverse, ...\n# P@draigBrady.com\n# Correctly nest tags (even across lines).\n# Add a command line option to use a dark background.\n# Strip more terminal control codes.\n# V0.4, 17 Sep 2009, P@draigBrady.com\n# Handle codes with combined attributes and color.\n# Handle isolated attributes with css.\n# Strip more terminal control codes.\n# V0.23, 22 Dec 2015\n# http://github.com/pixelb/scripts/commits/master/scripts/ansi2html.sh\n\ngawk --version >/dev/null || exit 1\n\nif [ \"$1\" = \"--version\" ]; then\n printf '0.22\\n' && exit\nfi\n\nif [ \"$1\" = \"--help\" ]; then\n printf '%s\\n' \\\n'This utility converts ANSI codes in data passed to stdin\nIt has 2 optional parameters:\n --bg=dark --palette=linux|solarized|tango|xterm\nE.g.: ls -l --color=always | ansi2html.sh --bg=dark > ls.html' >&2\n exit\nfi\n\n[ \"$1\" = \"--bg=dark\" ] && { dark_bg=yes; shift; }\n\nif [ \"$1\" = \"--palette=solarized\" ]; then\n # See http://ethanschoonover.com/solarized\n P0=073642; P1=D30102; P2=859900; P3=B58900;\n P4=268BD2; P5=D33682; P6=2AA198; P7=EEE8D5;\n P8=002B36; P9=CB4B16; P10=586E75; P11=657B83;\n P12=839496; P13=6C71C4; P14=93A1A1; P15=FDF6E3;\n shift;\nelif [ \"$1\" = \"--palette=solarized-xterm\" ]; then\n # Above mapped onto the xterm 256 color palette\n P0=262626; P1=AF0000; P2=5F8700; P3=AF8700;\n P4=0087FF; P5=AF005F; P6=00AFAF; P7=E4E4E4;\n P8=1C1C1C; P9=D75F00; P10=585858; P11=626262;\n P12=808080; P13=5F5FAF; P14=8A8A8A; P15=FFFFD7;\n shift;\nelif [ \"$1\" = \"--palette=tango\" ]; then\n # Gnome default\n P0=000000; P1=CC0000; P2=4E9A06; P3=C4A000;\n P4=3465A4; P5=75507B; P6=06989A; P7=D3D7CF;\n P8=555753; P9=EF2929; P10=8AE234; P11=FCE94F;\n P12=729FCF; P13=AD7FA8; P14=34E2E2; P15=EEEEEC;\n shift;\nelif [ \"$1\" = \"--palette=xterm\" ]; then\n P0=000000; P1=CD0000; P2=00CD00; P3=CDCD00;\n P4=0000EE; P5=CD00CD; P6=00CDCD; P7=E5E5E5;\n P8=7F7F7F; P9=FF0000; P10=00FF00; P11=FFFF00;\n P12=5C5CFF; P13=FF00FF; P14=00FFFF; P15=FFFFFF;\n shift;\nelse # linux console\n P0=000000; P1=AA0000; P2=00AA00; P3=AA5500;\n P4=0000AA; P5=AA00AA; P6=00AAAA; P7=AAAAAA;\n P8=555555; P9=FF5555; P10=55FF55; P11=FFFF55;\n P12=5555FF; P13=FF55FF; P14=55FFFF; P15=FFFFFF;\n [ \"$1\" = \"--palette=linux\" ] && shift\nfi\n\n[ \"$1\" = \"--bg=dark\" ] && { dark_bg=yes; shift; }\n\n# Mac OSX's GNU sed is installed as gsed\n# use e.g. homebrew 'gnu-sed' to get it\nif ! sed --version >/dev/null 2>&1; then\n if gsed --version >/dev/null 2>&1; then\n alias sed=gsed\n else\n echo \"Error, can't find an acceptable GNU sed.\" >&2\n exit 1\n fi\nfi\n\nprintf '%s' \"\n\n\n\n\n\n\n
            \n'\n\np='\\x1b\\['        #shortcut to match escape codes\n\n# Handle various xterm control sequences.\n# See /usr/share/doc/xterm-*/ctlseqs.txt\nsed \"\n# escape ampersand and quote\ns#&#\\&#g; s#\\\"#\\"#g;\ns#\\x1b[^\\x1b]*\\x1b\\\\\\##g  # strip anything between \\e and ST\ns#\\x1b][0-9]*;[^\\a]*\\a##g # strip any OSC (xterm title etc.)\n\ns#\\r\\$## # strip trailing \\r\n\n# strip other non SGR escape sequences\ns#[\\x07]##g\ns#\\x1b[]>=\\][0-9;]*##g\ns#\\x1bP+.\\{5\\}##g\n# Mark cursor positioning codes \\\"Jr;c;\ns#${p}\\([0-9]\\{1,2\\}\\)G#\\\"J;\\1;#g\ns#${p}\\([0-9]\\{1,2\\}\\);\\([0-9]\\{1,2\\}\\)H#\\\"J\\1;\\2;#g\n\n# Mark clear as \\\"Cn where n=1 is screen and n=0 is to end-of-line\ns#${p}H#\\\"C1;#g\ns#${p}K#\\\"C0;#g\n# Mark Cursor move columns as \\\"Mn where n is +ve for right, -ve for left\ns#${p}C#\\\"M1;#g\ns#${p}\\([0-9]\\{1,\\}\\)C#\\\"M\\1;#g\ns#${p}\\([0-9]\\{1,\\}\\)D#\\\"M-\\1;#g\ns#${p}\\([0-9]\\{1,\\}\\)P#\\\"X\\1;#g\n\ns#${p}[0-9;?]*[^0-9;?m]##g\n\n\" |\n\n# Normalize the input before transformation\nsed \"\n# escape HTML (ampersand and quote done above)\ns#>#\\>#g; s#<#\\<#g;\n\n# normalize SGR codes a little\n\n# split 256 colors out and mark so that they're not\n# recognised by the following 'split combined' line\n:e\ns#${p}\\([0-9;]\\{1,\\}\\);\\([34]8;5;[0-9]\\{1,3\\}\\)m#${p}\\1m${p}\u00ac\\2m#g; t e\ns#${p}\\([34]8;5;[0-9]\\{1,3\\}\\)m#${p}\u00ac\\1m#g;\n\n:c\ns#${p}\\([0-9]\\{1,\\}\\);\\([0-9;]\\{1,\\}\\)m#${p}\\1m${p}\\2m#g; t c   # split combined\ns#${p}0\\([0-7]\\)#${p}\\1#g                                 #strip leading 0\ns#${p}1m\\(\\(${p}[4579]m\\)*\\)#\\1${p}1m#g                   #bold last (with clr)\ns#${p}m#${p}0m#g                                          #add leading 0 to norm\n\n# undo any 256 color marking\ns#${p}\u00ac\\([34]8;5;[0-9]\\{1,3\\}\\)m#${p}\\1m#g;\n\n# map 16 color codes to color + bold\ns#${p}9\\([0-7]\\)m#${p}3\\1m${p}1m#g;\ns#${p}10\\([0-7]\\)m#${p}4\\1m${p}1m#g;\n\n# change 'reset' code to \\\"R\ns#${p}0m#\\\"R;#g\n\" |\n\n# Convert SGR sequences to HTML\nsed \"\n# common combinations to minimise html (optional)\n:f\ns#${p}3[0-7]m${p}3\\([0-7]\\)m#${p}3\\1m#g; t f\n:b\ns#${p}4[0-7]m${p}4\\([0-7]\\)m#${p}4\\1m#g; t b\ns#${p}3\\([0-7]\\)m${p}4\\([0-7]\\)m##g\ns#${p}4\\([0-7]\\)m${p}3\\([0-7]\\)m##g\n\ns#${p}1m##g\ns#${p}4m##g\ns#${p}5m##g\ns#${p}7m##g\ns#${p}9m##g\ns#${p}3\\([0-9]\\)m##g\ns#${p}4\\([0-9]\\)m##g\n\ns#${p}38;5;\\([0-9]\\{1,3\\}\\)m##g\ns#${p}48;5;\\([0-9]\\{1,3\\}\\)m##g\n\ns#${p}[0-9;]*m##g # strip unhandled codes\n\" |\n\n# Convert alternative character set and handle cursor movement codes\n# Note we convert here, as if we do at start we have to worry about avoiding\n# conversion of SGR codes etc., whereas doing here we only have to\n# avoid conversions of stuff between &...; or <...>\n#\n# Note we could use sed to do this based around:\n#   sed 'y/abcdefghijklmnopqrstuvwxyz{}`~/\u2592\u2409\u240c\u240d\u240a\u00b0\u00b1\u2424\u240b\u2518\u2510\u250c\u2514\u253c\u23ba\u23bb\u2500\u23bc\u23bd\u251c\u2524\u2534\u252c\u2502\u2264\u2265\u03c0\u00a3\u25c6\u00b7/'\n# However that would be very awkward as we need to only conv some input.\n# The basic scheme that we do in the awk script below is:\n#  1. enable transliterate once \"T1; is seen\n#  2. disable once \"T0; is seen (may be on diff line)\n#  3. never transliterate between &; or <> chars\n#  4. track x,y movements and active display mode at each position\n#  5. buffer line/screen and dump when required\nsed \"\n# change 'smacs' and 'rmacs' to \\\"T1 and \\\"T0 to simplify matching.\ns#\\x1b(0#\\\"T1;#g;\ns#\\x0E#\\\"T1;#g;\n\ns#\\x1b(B#\\\"T0;#g\ns#\\x0F#\\\"T0;#g\n\" |\n(\ngawk '\nfunction dump_line(l,del,c,blanks,ret) {\n  for(c=1;c\")\n  for(i=1;i<=spc;i++) {\n    rm=rm?rm:(a[i]!=attr[i]\">\")\n    if(rm) {\n      ret=ret \"\"\n      delete a[i];\n    }\n  }\n  for(i=1;i\"\n    if(a[i]!=attr[i]) {\n      a[i]=attr[i]\n      ret = ret attr[i]\n    }\n  }\n  return ret\n}\n\nfunction encode(string,start,end,i,ret,pos,sc,buf) {\n   if(!end) end=length(string);\n   if(!start) start=1;\n   state=3\n   for(i=1;i<=length(string);i++) {\n     c=substr(string,i,1)\n     if(state==2) {\n       sc=sc c\n       if(c==\";\") {\n          c=sc\n          state=last_mode\n       } else continue\n     } else {\n       if(c==\"\\r\") { x=1; continue }\n       if(c==\"<\") {\n         # Change attributes - store current active\n         # attributes in span array\n         split(substr(string,i),cord,\">\");\n         i+=length(cord[1])\n         span[++spc]=cord[1] \">\"\n         continue\n       }\n       else if(c==\"&\") {\n         # All goes to single position till we see a semicolon\n         sc=c\n         state=2\n         continue\n       }\n       else if(c==\"\\b\") {\n          # backspace move insertion point back 1\n          if(spc) attr[x,y]=atos(span)\n          x=x>1?x-1:1\n          continue\n       }\n       else if(c==\"\\\"\") {\n          split(substr(string,i+2),cord,\";\")\n          cc=substr(string,i+1,1);\n          if(cc==\"T\") {\n              # Transliterate on/off\n              if(cord[1]==1&&state==3) last_mode=state=4\n              if(cord[1]==0&&state==4) last_mode=state=3\n          }\n          else if(cc==\"C\") {\n              # Clear\n              if(cord[1]+0) {\n                # Screen - if Recording dump screen\n                if(dumpStatus==dsActive) ret=ret dump_screen()\n                dumpStatus=dsActive\n                delete dump\n                delete attr\n                x=y=1\n              } else {\n                # To end of line\n                for(pos=x;posmaxY) maxY=y\n                # Change y - start recording\n                dumpStatus=dumpStatus?dumpStatus:dsReset\n              }\n          }\n          else if(cc==\"M\") {\n              # Move left/right on current line\n              x+=cord[1]\n          }\n          else if(cc==\"X\") {\n              # delete on right\n              for(pos=x;pos<=maxX;pos++) {\n                nx=pos+cord[1]\n                if(nx=start&&i<=end&&c in Trans) c=Trans[c]\n     }\n     if(dumpStatus==dsReset) {\n       delete dump\n       delete attr\n       ret=ret\"\\n\"\n       dumpStatus=dsActive\n     }\n     if(dumpStatus==dsNew) {\n       # After moving/clearing we are now ready to write\n       # somthing to the screen so start recording now\n       ret=ret\"\\n\"\n       dumpStatus=dsActive\n     }\n     if(dumpStatus==dsActive||dumpStatus==dsOff) {\n       dump[x,y] = c\n       if(!spc) delete attr[x,y]\n       else attr[x,y] = atos(span)\n       if(++x>maxX) maxX=x;\n     }\n    }\n    # End of line if dumping increment y and set x back to first col\n    x=1\n    if(!dumpStatus) return ret dump_line(y,1);\n    else if(++y>maxY) maxY=y;\n    return ret\n}\nBEGIN{\n  OFS=FS\n  # dump screen status\n  dsOff=0    # Not dumping screen contents just write output direct\n  dsNew=1    # Just after move/clear waiting for activity to start recording\n  dsReset=2  # Screen cleared build new empty buffer and record\n  dsActive=3 # Currently recording\n  F=\"abcdefghijklmnopqrstuvwxyz{}`~\"\n  T=\"\u2592\u2409\u240c\u240d\u240a\u00b0\u00b1\u2424\u240b\u2518\u2510\u250c\u2514\u253c\u23ba\u23bb\u2500\u23bc\u23bd\u251c\u2524\u2534\u252c\u2502\u2264\u2265\u03c0\u00a3\u25c6\u00b7\"\n  maxX=80\n  delete cur;\n  x=y=1\n  for(i=1;i<=length(F);i++)Trans[substr(F,i,1)]=substr(T,i,1);\n}\n\n{ $0=encode($0) }\n1\nEND {\n  if(dumpStatus) {\n    print dump_screen();\n  }\n}'\n)\n\nprintf '
            \n\n\\n'\n"}, "files_after": {"scripts/ansi2html.sh": "#!/bin/sh\n\n# Convert ANSI (terminal) colours and attributes to HTML\n\n# Licence: LGPLv2\n# Author:\n# http://www.pixelbeat.org/docs/terminal_colours/\n# Examples:\n# ls -l --color=always | ansi2html.sh > ls.html\n# git show --color | ansi2html.sh > last_change.html\n# Generally one can use the `script` util to capture full terminal output.\n# Changes:\n# V0.1, 24 Apr 2008, Initial release\n# V0.2, 01 Jan 2009, Phil Harnish \n# Support `git diff --color` output by\n# matching ANSI codes that specify only\n# bold or background colour.\n# P@draigBrady.com\n# Support `ls --color` output by stripping\n# redundant leading 0s from ANSI codes.\n# Support `grep --color=always` by stripping\n# unhandled ANSI codes (specifically ^[[K).\n# V0.3, 20 Mar 2009, http://eexpress.blog.ubuntu.org.cn/\n# Remove cat -v usage which mangled non ascii input.\n# Cleanup regular expressions used.\n# Support other attributes like reverse, ...\n# P@draigBrady.com\n# Correctly nest tags (even across lines).\n# Add a command line option to use a dark background.\n# Strip more terminal control codes.\n# V0.4, 17 Sep 2009, P@draigBrady.com\n# Handle codes with combined attributes and color.\n# Handle isolated attributes with css.\n# Strip more terminal control codes.\n# V0.23, 22 Dec 2015\n# http://github.com/pixelb/scripts/commits/master/scripts/ansi2html.sh\n\ngawk --version >/dev/null || exit 1\n\nif [ \"$1\" = \"--version\" ]; then\n printf '0.22\\n' && exit\nfi\n\nusage()\n{\nprintf '%s\\n' \\\n'This utility converts ANSI codes in data passed to stdin\nIt has 4 optional parameters:\n--bg=dark --palette=linux|solarized|tango|xterm [--css-only|--body-only]\nE.g.: ls -l --color=always | ansi2html.sh --bg=dark > ls.html' >&2\n exit\n}\n\nif [ \"$1\" = \"--help\" ]; then\n usage\nfi\n\nprocessArg()\n{\n [ \"$1\" = \"--bg=dark\" ] && { dark_bg=yes; return; }\n [ \"$1\" = \"--css-only\" ] && { css_only=yes; return; }\n [ \"$1\" = \"--body-only\" ] && { body_only=yes; return; }\n if [ \"$1\" = \"--palette=solarized\" ]; then\n # See http://ethanschoonover.com/solarized\n P0=073642; P1=D30102; P2=859900; P3=B58900;\n P4=268BD2; P5=D33682; P6=2AA198; P7=EEE8D5;\n P8=002B36; P9=CB4B16; P10=586E75; P11=657B83;\n P12=839496; P13=6C71C4; P14=93A1A1; P15=FDF6E3;\n return;\n elif [ \"$1\" = \"--palette=solarized-xterm\" ]; then\n # Above mapped onto the xterm 256 color palette\n P0=262626; P1=AF0000; P2=5F8700; P3=AF8700;\n P4=0087FF; P5=AF005F; P6=00AFAF; P7=E4E4E4;\n P8=1C1C1C; P9=D75F00; P10=585858; P11=626262;\n P12=808080; P13=5F5FAF; P14=8A8A8A; P15=FFFFD7;\n return;\n elif [ \"$1\" = \"--palette=tango\" ]; then\n # Gnome default\n P0=000000; P1=CC0000; P2=4E9A06; P3=C4A000;\n P4=3465A4; P5=75507B; P6=06989A; P7=D3D7CF;\n P8=555753; P9=EF2929; P10=8AE234; P11=FCE94F;\n P12=729FCF; P13=AD7FA8; P14=34E2E2; P15=EEEEEC;\n return;\n elif [ \"$1\" = \"--palette=xterm\" ]; then\n P0=000000; P1=CD0000; P2=00CD00; P3=CDCD00;\n P4=0000EE; P5=CD00CD; P6=00CDCD; P7=E5E5E5;\n P8=7F7F7F; P9=FF0000; P10=00FF00; P11=FFFF00;\n P12=5C5CFF; P13=FF00FF; P14=00FFFF; P15=FFFFFF;\n return;\n else # linux console\n P0=000000; P1=AA0000; P2=00AA00; P3=AA5500;\n P4=0000AA; P5=AA00AA; P6=00AAAA; P7=AAAAAA;\n P8=555555; P9=FF5555; P10=55FF55; P11=FFFF55;\n P12=5555FF; P13=FF55FF; P14=55FFFF; P15=FFFFFF;\n [ \"$1\" = \"--palette=linux\" ] && return;\n fi\n}\n\nprocessArg #defaults\nfor var in \"$@\"; do processArg $var; done\n[ \"$css_only\" ] && [ \"$body_only\" ] && usage\n\n# Mac OSX's GNU sed is installed as gsed\n# use e.g. homebrew 'gnu-sed' to get it\nif ! sed --version >/dev/null 2>&1; then\n if gsed --version >/dev/null 2>&1; then\n alias sed=gsed\n else\n echo \"Error, can't find an acceptable GNU sed.\" >&2\n exit 1\n fi\nfi\n\n[ \"$css_only\" ] || [ \"$body_only\" ] || printf '%s' \"\n\n\n\n\n\n\n
            \n'\n[ \"$body_only\" ] && printf '%s\\n' 'Be sure to use  and 
            ' >&2\n\np='\\x1b\\['        #shortcut to match escape codes\n\n# Handle various xterm control sequences.\n# See /usr/share/doc/xterm-*/ctlseqs.txt\nsed \"\n# escape ampersand and quote\ns#&#\\&#g; s#\\\"#\\"#g;\ns#\\x1b[^\\x1b]*\\x1b\\\\\\##g  # strip anything between \\e and ST\ns#\\x1b][0-9]*;[^\\a]*\\a##g # strip any OSC (xterm title etc.)\n\ns#\\r\\$## # strip trailing \\r\n\n# strip other non SGR escape sequences\ns#[\\x07]##g\ns#\\x1b[]>=\\][0-9;]*##g\ns#\\x1bP+.\\{5\\}##g\n# Mark cursor positioning codes \\\"Jr;c;\ns#${p}\\([0-9]\\{1,2\\}\\)G#\\\"J;\\1;#g\ns#${p}\\([0-9]\\{1,2\\}\\);\\([0-9]\\{1,2\\}\\)H#\\\"J\\1;\\2;#g\n\n# Mark clear as \\\"Cn where n=1 is screen and n=0 is to end-of-line\ns#${p}H#\\\"C1;#g\ns#${p}K#\\\"C0;#g\n# Mark Cursor move columns as \\\"Mn where n is +ve for right, -ve for left\ns#${p}C#\\\"M1;#g\ns#${p}\\([0-9]\\{1,\\}\\)C#\\\"M\\1;#g\ns#${p}\\([0-9]\\{1,\\}\\)D#\\\"M-\\1;#g\ns#${p}\\([0-9]\\{1,\\}\\)P#\\\"X\\1;#g\n\ns#${p}[0-9;?]*[^0-9;?m]##g\n\n\" |\n\n# Normalize the input before transformation\nsed \"\n# escape HTML (ampersand and quote done above)\ns#>#\\>#g; s#<#\\<#g;\n\n# normalize SGR codes a little\n\n# split 256 colors out and mark so that they're not\n# recognised by the following 'split combined' line\n:e\ns#${p}\\([0-9;]\\{1,\\}\\);\\([34]8;5;[0-9]\\{1,3\\}\\)m#${p}\\1m${p}\u00ac\\2m#g; t e\ns#${p}\\([34]8;5;[0-9]\\{1,3\\}\\)m#${p}\u00ac\\1m#g;\n\n:c\ns#${p}\\([0-9]\\{1,\\}\\);\\([0-9;]\\{1,\\}\\)m#${p}\\1m${p}\\2m#g; t c   # split combined\ns#${p}0\\([0-7]\\)#${p}\\1#g                                 #strip leading 0\ns#${p}1m\\(\\(${p}[4579]m\\)*\\)#\\1${p}1m#g                   #bold last (with clr)\ns#${p}m#${p}0m#g                                          #add leading 0 to norm\n\n# undo any 256 color marking\ns#${p}\u00ac\\([34]8;5;[0-9]\\{1,3\\}\\)m#${p}\\1m#g;\n\n# map 16 color codes to color + bold\ns#${p}9\\([0-7]\\)m#${p}3\\1m${p}1m#g;\ns#${p}10\\([0-7]\\)m#${p}4\\1m${p}1m#g;\n\n# change 'reset' code to \\\"R\ns#${p}0m#\\\"R;#g\n\" |\n\n# Convert SGR sequences to HTML\nsed \"\n# common combinations to minimise html (optional)\n:f\ns#${p}3[0-7]m${p}3\\([0-7]\\)m#${p}3\\1m#g; t f\n:b\ns#${p}4[0-7]m${p}4\\([0-7]\\)m#${p}4\\1m#g; t b\ns#${p}3\\([0-7]\\)m${p}4\\([0-7]\\)m##g\ns#${p}4\\([0-7]\\)m${p}3\\([0-7]\\)m##g\n\ns#${p}1m##g\ns#${p}4m##g\ns#${p}5m##g\ns#${p}7m##g\ns#${p}9m##g\ns#${p}3\\([0-9]\\)m##g\ns#${p}4\\([0-9]\\)m##g\n\ns#${p}38;5;\\([0-9]\\{1,3\\}\\)m##g\ns#${p}48;5;\\([0-9]\\{1,3\\}\\)m##g\n\ns#${p}[0-9;]*m##g # strip unhandled codes\n\" |\n\n# Convert alternative character set and handle cursor movement codes\n# Note we convert here, as if we do at start we have to worry about avoiding\n# conversion of SGR codes etc., whereas doing here we only have to\n# avoid conversions of stuff between &...; or <...>\n#\n# Note we could use sed to do this based around:\n#   sed 'y/abcdefghijklmnopqrstuvwxyz{}`~/\u2592\u2409\u240c\u240d\u240a\u00b0\u00b1\u2424\u240b\u2518\u2510\u250c\u2514\u253c\u23ba\u23bb\u2500\u23bc\u23bd\u251c\u2524\u2534\u252c\u2502\u2264\u2265\u03c0\u00a3\u25c6\u00b7/'\n# However that would be very awkward as we need to only conv some input.\n# The basic scheme that we do in the awk script below is:\n#  1. enable transliterate once \"T1; is seen\n#  2. disable once \"T0; is seen (may be on diff line)\n#  3. never transliterate between &; or <> chars\n#  4. track x,y movements and active display mode at each position\n#  5. buffer line/screen and dump when required\nsed \"\n# change 'smacs' and 'rmacs' to \\\"T1 and \\\"T0 to simplify matching.\ns#\\x1b(0#\\\"T1;#g;\ns#\\x0E#\\\"T1;#g;\n\ns#\\x1b(B#\\\"T0;#g\ns#\\x0F#\\\"T0;#g\n\" |\n(\ngawk '\nfunction dump_line(l,del,c,blanks,ret) {\n  for(c=1;c\")\n  for(i=1;i<=spc;i++) {\n    rm=rm?rm:(a[i]!=attr[i]\">\")\n    if(rm) {\n      ret=ret \"\"\n      delete a[i];\n    }\n  }\n  for(i=1;i\"\n    if(a[i]!=attr[i]) {\n      a[i]=attr[i]\n      ret = ret attr[i]\n    }\n  }\n  return ret\n}\n\nfunction encode(string,start,end,i,ret,pos,sc,buf) {\n   if(!end) end=length(string);\n   if(!start) start=1;\n   state=3\n   for(i=1;i<=length(string);i++) {\n     c=substr(string,i,1)\n     if(state==2) {\n       sc=sc c\n       if(c==\";\") {\n          c=sc\n          state=last_mode\n       } else continue\n     } else {\n       if(c==\"\\r\") { x=1; continue }\n       if(c==\"<\") {\n         # Change attributes - store current active\n         # attributes in span array\n         split(substr(string,i),cord,\">\");\n         i+=length(cord[1])\n         span[++spc]=cord[1] \">\"\n         continue\n       }\n       else if(c==\"&\") {\n         # All goes to single position till we see a semicolon\n         sc=c\n         state=2\n         continue\n       }\n       else if(c==\"\\b\") {\n          # backspace move insertion point back 1\n          if(spc) attr[x,y]=atos(span)\n          x=x>1?x-1:1\n          continue\n       }\n       else if(c==\"\\\"\") {\n          split(substr(string,i+2),cord,\";\")\n          cc=substr(string,i+1,1);\n          if(cc==\"T\") {\n              # Transliterate on/off\n              if(cord[1]==1&&state==3) last_mode=state=4\n              if(cord[1]==0&&state==4) last_mode=state=3\n          }\n          else if(cc==\"C\") {\n              # Clear\n              if(cord[1]+0) {\n                # Screen - if Recording dump screen\n                if(dumpStatus==dsActive) ret=ret dump_screen()\n                dumpStatus=dsActive\n                delete dump\n                delete attr\n                x=y=1\n              } else {\n                # To end of line\n                for(pos=x;posmaxY) maxY=y\n                # Change y - start recording\n                dumpStatus=dumpStatus?dumpStatus:dsReset\n              }\n          }\n          else if(cc==\"M\") {\n              # Move left/right on current line\n              x+=cord[1]\n          }\n          else if(cc==\"X\") {\n              # delete on right\n              for(pos=x;pos<=maxX;pos++) {\n                nx=pos+cord[1]\n                if(nx=start&&i<=end&&c in Trans) c=Trans[c]\n     }\n     if(dumpStatus==dsReset) {\n       delete dump\n       delete attr\n       ret=ret\"\\n\"\n       dumpStatus=dsActive\n     }\n     if(dumpStatus==dsNew) {\n       # After moving/clearing we are now ready to write\n       # somthing to the screen so start recording now\n       ret=ret\"\\n\"\n       dumpStatus=dsActive\n     }\n     if(dumpStatus==dsActive||dumpStatus==dsOff) {\n       dump[x,y] = c\n       if(!spc) delete attr[x,y]\n       else attr[x,y] = atos(span)\n       if(++x>maxX) maxX=x;\n     }\n    }\n    # End of line if dumping increment y and set x back to first col\n    x=1\n    if(!dumpStatus) return ret dump_line(y,1);\n    else if(++y>maxY) maxY=y;\n    return ret\n}\nBEGIN{\n  OFS=FS\n  # dump screen status\n  dsOff=0    # Not dumping screen contents just write output direct\n  dsNew=1    # Just after move/clear waiting for activity to start recording\n  dsReset=2  # Screen cleared build new empty buffer and record\n  dsActive=3 # Currently recording\n  F=\"abcdefghijklmnopqrstuvwxyz{}`~\"\n  T=\"\u2592\u2409\u240c\u240d\u240a\u00b0\u00b1\u2424\u240b\u2518\u2510\u250c\u2514\u253c\u23ba\u23bb\u2500\u23bc\u23bd\u251c\u2524\u2534\u252c\u2502\u2264\u2265\u03c0\u00a3\u25c6\u00b7\"\n  maxX=80\n  delete cur;\n  x=y=1\n  for(i=1;i<=length(F);i++)Trans[substr(F,i,1)]=substr(T,i,1);\n}\n\n{ $0=encode($0) }\n1\nEND {\n  if(dumpStatus) {\n    print dump_screen();\n  }\n}'\n)\n\n[ \"$body_only\" ] || printf '
            \n\n\\n'\n"}} -{"repo": "joblib/joblib", "pr_number": 1585, "title": "Do not allow pickle.load in read_array by default", "state": "closed", "merged_at": null, "additions": 51, "deletions": 23, "files_changed": ["examples/compressors_comparison.py", "joblib/numpy_pickle.py", "joblib/test/test_numpy_pickle.py"], "files_before": {"examples/compressors_comparison.py": "\"\"\"\n===============================\nImproving I/O using compressors\n===============================\n\nThis example compares the compressors available in Joblib. In the example,\nZlib, LZMA and LZ4 compression only are used but Joblib also supports BZ2 and\nGZip compression methods.\nFor each compared compression method, this example dumps and reloads a\ndataset fetched from an online machine-learning database. This gives 3\ninformation: the size on disk of the compressed data, the time spent to dump\nand the time spent to reload the data from disk.\n\"\"\"\n\nimport os\nimport os.path\nimport time\n\n###############################################################################\n# Get some data from real-world use cases\n# ---------------------------------------\n#\n# First fetch the benchmark dataset from an online machine-learning database\n# and load it in a pandas dataframe.\n\nimport pandas as pd\n\nurl = \"https://github.com/joblib/dataset/raw/main/kddcup.data.gz\"\nnames = (\"duration, protocol_type, service, flag, src_bytes, \"\n \"dst_bytes, land, wrong_fragment, urgent, hot, \"\n \"num_failed_logins, logged_in, num_compromised, \"\n \"root_shell, su_attempted, num_root, \"\n \"num_file_creations, \").split(', ')\n\ndata = pd.read_csv(url, names=names, nrows=1e6)\n\n###############################################################################\n# Dump and load the dataset without compression\n# ---------------------------------------------\n#\n# This gives reference values for later comparison.\n\nfrom joblib import dump, load\n\npickle_file = './pickle_data.joblib'\n\n###############################################################################\n# Start by measuring the time spent for dumping the raw data:\nstart = time.time()\nwith open(pickle_file, 'wb') as f:\n dump(data, f)\nraw_dump_duration = time.time() - start\nprint(\"Raw dump duration: %0.3fs\" % raw_dump_duration)\n\n###############################################################################\n# Then measure the size of the raw dumped data on disk:\nraw_file_size = os.stat(pickle_file).st_size / 1e6\nprint(\"Raw dump file size: %0.3fMB\" % raw_file_size)\n\n###############################################################################\n# Finally measure the time spent for loading the raw data:\nstart = time.time()\nwith open(pickle_file, 'rb') as f:\n load(f)\nraw_load_duration = time.time() - start\nprint(\"Raw load duration: %0.3fs\" % raw_load_duration)\n\n###############################################################################\n# Dump and load the dataset using the Zlib compression method\n# -----------------------------------------------------------\n#\n# The compression level is using the default value, 3, which is, in general, a\n# good compromise between compression and speed.\n\n###############################################################################\n# Start by measuring the time spent for dumping of the zlib data:\n\nstart = time.time()\nwith open(pickle_file, 'wb') as f:\n dump(data, f, compress='zlib')\nzlib_dump_duration = time.time() - start\nprint(\"Zlib dump duration: %0.3fs\" % zlib_dump_duration)\n\n###############################################################################\n# Then measure the size of the zlib dump data on disk:\n\nzlib_file_size = os.stat(pickle_file).st_size / 1e6\nprint(\"Zlib file size: %0.3fMB\" % zlib_file_size)\n\n###############################################################################\n# Finally measure the time spent for loading the compressed dataset:\n\nstart = time.time()\nwith open(pickle_file, 'rb') as f:\n load(f)\nzlib_load_duration = time.time() - start\nprint(\"Zlib load duration: %0.3fs\" % zlib_load_duration)\n\n###############################################################################\n# .. note:: The compression format is detected automatically by Joblib.\n# The compression format is identified by the standard magic number present\n# at the beginning of the file. Joblib uses this information to determine\n# the compression method used.\n# This is the case for all compression methods supported by Joblib.\n\n###############################################################################\n# Dump and load the dataset using the LZMA compression method\n# -----------------------------------------------------------\n#\n# LZMA compression method has a very good compression rate but at the cost\n# of being very slow.\n# In this example, a light compression level, e.g. 3, is used to speed up a\n# bit the dump/load cycle.\n\n###############################################################################\n# Start by measuring the time spent for dumping the lzma data:\n\nstart = time.time()\nwith open(pickle_file, 'wb') as f:\n dump(data, f, compress=('lzma', 3))\nlzma_dump_duration = time.time() - start\nprint(\"LZMA dump duration: %0.3fs\" % lzma_dump_duration)\n\n###############################################################################\n# Then measure the size of the lzma dump data on disk:\n\nlzma_file_size = os.stat(pickle_file).st_size / 1e6\nprint(\"LZMA file size: %0.3fMB\" % lzma_file_size)\n\n###############################################################################\n# Finally measure the time spent for loading the lzma data:\n\nstart = time.time()\nwith open(pickle_file, 'rb') as f:\n load(f)\nlzma_load_duration = time.time() - start\nprint(\"LZMA load duration: %0.3fs\" % lzma_load_duration)\n\n###############################################################################\n# Dump and load the dataset using the LZ4 compression method\n# ----------------------------------------------------------\n#\n# LZ4 compression method is known to be one of the fastest available\n# compression method but with a compression rate a bit lower than Zlib. In\n# most of the cases, this method is a good choice.\n\n###############################################################################\n# .. note:: In order to use LZ4 compression with Joblib, the\n# `lz4 `_ package must be installed\n# on the system.\n\n###############################################################################\n# Start by measuring the time spent for dumping the lz4 data:\n\nstart = time.time()\nwith open(pickle_file, 'wb') as f:\n dump(data, f, compress='lz4')\nlz4_dump_duration = time.time() - start\nprint(\"LZ4 dump duration: %0.3fs\" % lz4_dump_duration)\n\n###############################################################################\n# Then measure the size of the lz4 dump data on disk:\n\nlz4_file_size = os.stat(pickle_file).st_size / 1e6\nprint(\"LZ4 file size: %0.3fMB\" % lz4_file_size)\n\n###############################################################################\n# Finally measure the time spent for loading the lz4 data:\n\nstart = time.time()\nwith open(pickle_file, 'rb') as f:\n load(f)\nlz4_load_duration = time.time() - start\nprint(\"LZ4 load duration: %0.3fs\" % lz4_load_duration)\n\n###############################################################################\n# Comparing the results\n# ---------------------\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nN = 4\nload_durations = (raw_load_duration, lz4_load_duration, zlib_load_duration,\n lzma_load_duration)\ndump_durations = (raw_dump_duration, lz4_dump_duration, zlib_dump_duration,\n lzma_dump_duration)\nfile_sizes = (raw_file_size, lz4_file_size, zlib_file_size, lzma_file_size)\nind = np.arange(N)\nwidth = 0.5\n\nplt.figure(1, figsize=(5, 4))\np1 = plt.bar(ind, dump_durations, width)\np2 = plt.bar(ind, load_durations, width, bottom=dump_durations)\nplt.ylabel('Time in seconds')\nplt.title('Dump and load durations')\nplt.xticks(ind, ('Raw', 'LZ4', 'Zlib', 'LZMA'))\nplt.yticks(np.arange(0, lzma_load_duration + lzma_dump_duration))\nplt.legend((p1[0], p2[0]), ('Dump duration', 'Load duration'))\n\n###############################################################################\n# Compared with other compressors, LZ4 is clearly the fastest, especially for\n# dumping compressed data on disk. In this particular case, it can even be\n# faster than the raw dump.\n# Also note that dump and load durations depend on the I/O speed of the\n# underlying storage: for example, with SSD hard drives the LZ4 compression\n# will be slightly slower than raw dump/load, whereas with spinning hard disk\n# drives (HDD) or remote storage (NFS), LZ4 is faster in general.\n#\n# LZMA and Zlib, even if always slower for dumping data, are quite fast when\n# re-loading compressed data from disk.\n\nplt.figure(2, figsize=(5, 4))\nplt.bar(ind, file_sizes, width, log=True)\nplt.ylabel('File size in MB')\nplt.xticks(ind, ('Raw', 'LZ4', 'Zlib', 'LZMA'))\n\n###############################################################################\n# Compressed data obviously takes a lot less space on disk than raw data. LZMA\n# is the best compression method in terms of compression rate. Zlib also has a\n# better compression rate than LZ4.\n\nplt.show()\n\n###############################################################################\n# Clear the pickle file\n# ---------------------\n\nimport os\nos.remove(pickle_file)\n", "joblib/numpy_pickle.py": "\"\"\"Utilities for fast persistence of big data, with optional compression.\"\"\"\n\n# Author: Gael Varoquaux \n# Copyright (c) 2009 Gael Varoquaux\n# License: BSD Style, 3 clauses.\n\nimport pickle\nimport os\nimport warnings\nimport io\nfrom pathlib import Path\n\nfrom .compressor import lz4, LZ4_NOT_INSTALLED_ERROR\nfrom .compressor import _COMPRESSORS, register_compressor, BinaryZlibFile\nfrom .compressor import (ZlibCompressorWrapper, GzipCompressorWrapper,\n BZ2CompressorWrapper, LZMACompressorWrapper,\n XZCompressorWrapper, LZ4CompressorWrapper)\nfrom .numpy_pickle_utils import Unpickler, Pickler\nfrom .numpy_pickle_utils import _read_fileobject, _write_fileobject\nfrom .numpy_pickle_utils import _read_bytes, BUFFER_SIZE\nfrom .numpy_pickle_utils import _ensure_native_byte_order\nfrom .numpy_pickle_compat import load_compatibility\nfrom .numpy_pickle_compat import NDArrayWrapper\n# For compatibility with old versions of joblib, we need ZNDArrayWrapper\n# to be visible in the current namespace.\n# Explicitly skipping next line from flake8 as it triggers an F401 warning\n# which we don't care.\nfrom .numpy_pickle_compat import ZNDArrayWrapper # noqa\nfrom .backports import make_memmap\n\n# Register supported compressors\nregister_compressor('zlib', ZlibCompressorWrapper())\nregister_compressor('gzip', GzipCompressorWrapper())\nregister_compressor('bz2', BZ2CompressorWrapper())\nregister_compressor('lzma', LZMACompressorWrapper())\nregister_compressor('xz', XZCompressorWrapper())\nregister_compressor('lz4', LZ4CompressorWrapper())\n\n\n###############################################################################\n# Utility objects for persistence.\n\n# For convenience, 16 bytes are used to be sure to cover all the possible\n# dtypes' alignments. For reference, see:\n# https://numpy.org/devdocs/dev/alignment.html\nNUMPY_ARRAY_ALIGNMENT_BYTES = 16\n\n\nclass NumpyArrayWrapper(object):\n \"\"\"An object to be persisted instead of numpy arrays.\n\n This object is used to hack into the pickle machinery and read numpy\n array data from our custom persistence format.\n More precisely, this object is used for:\n * carrying the information of the persisted array: subclass, shape, order,\n dtype. Those ndarray metadata are used to correctly reconstruct the array\n with low level numpy functions.\n * determining if memmap is allowed on the array.\n * reading the array bytes from a file.\n * reading the array using memorymap from a file.\n * writing the array bytes to a file.\n\n Attributes\n ----------\n subclass: numpy.ndarray subclass\n Determine the subclass of the wrapped array.\n shape: numpy.ndarray shape\n Determine the shape of the wrapped array.\n order: {'C', 'F'}\n Determine the order of wrapped array data. 'C' is for C order, 'F' is\n for fortran order.\n dtype: numpy.ndarray dtype\n Determine the data type of the wrapped array.\n allow_mmap: bool\n Determine if memory mapping is allowed on the wrapped array.\n Default: False.\n \"\"\"\n\n def __init__(self, subclass, shape, order, dtype, allow_mmap=False,\n numpy_array_alignment_bytes=NUMPY_ARRAY_ALIGNMENT_BYTES):\n \"\"\"Constructor. Store the useful information for later.\"\"\"\n self.subclass = subclass\n self.shape = shape\n self.order = order\n self.dtype = dtype\n self.allow_mmap = allow_mmap\n # We make numpy_array_alignment_bytes an instance attribute to allow us\n # to change our mind about the default alignment and still load the old\n # pickles (with the previous alignment) correctly\n self.numpy_array_alignment_bytes = numpy_array_alignment_bytes\n\n def safe_get_numpy_array_alignment_bytes(self):\n # NumpyArrayWrapper instances loaded from joblib <= 1.1 pickles don't\n # have an numpy_array_alignment_bytes attribute\n return getattr(self, 'numpy_array_alignment_bytes', None)\n\n def write_array(self, array, pickler):\n \"\"\"Write array bytes to pickler file handle.\n\n This function is an adaptation of the numpy write_array function\n available in version 1.10.1 in numpy/lib/format.py.\n \"\"\"\n # Set buffer size to 16 MiB to hide the Python loop overhead.\n buffersize = max(16 * 1024 ** 2 // array.itemsize, 1)\n if array.dtype.hasobject:\n # We contain Python objects so we cannot write out the data\n # directly. Instead, we will pickle it out with version 2 of the\n # pickle protocol.\n pickle.dump(array, pickler.file_handle, protocol=2)\n else:\n numpy_array_alignment_bytes = \\\n self.safe_get_numpy_array_alignment_bytes()\n if numpy_array_alignment_bytes is not None:\n current_pos = pickler.file_handle.tell()\n pos_after_padding_byte = current_pos + 1\n padding_length = numpy_array_alignment_bytes - (\n pos_after_padding_byte % numpy_array_alignment_bytes)\n # A single byte is written that contains the padding length in\n # bytes\n padding_length_byte = int.to_bytes(\n padding_length, length=1, byteorder='little')\n pickler.file_handle.write(padding_length_byte)\n\n if padding_length != 0:\n padding = b'\\xff' * padding_length\n pickler.file_handle.write(padding)\n\n for chunk in pickler.np.nditer(array,\n flags=['external_loop',\n 'buffered',\n 'zerosize_ok'],\n buffersize=buffersize,\n order=self.order):\n pickler.file_handle.write(chunk.tobytes('C'))\n\n def read_array(self, unpickler):\n \"\"\"Read array from unpickler file handle.\n\n This function is an adaptation of the numpy read_array function\n available in version 1.10.1 in numpy/lib/format.py.\n \"\"\"\n if len(self.shape) == 0:\n count = 1\n else:\n # joblib issue #859: we cast the elements of self.shape to int64 to\n # prevent a potential overflow when computing their product.\n shape_int64 = [unpickler.np.int64(x) for x in self.shape]\n count = unpickler.np.multiply.reduce(shape_int64)\n # Now read the actual data.\n if self.dtype.hasobject:\n # The array contained Python objects. We need to unpickle the data.\n array = pickle.load(unpickler.file_handle)\n else:\n numpy_array_alignment_bytes = \\\n self.safe_get_numpy_array_alignment_bytes()\n if numpy_array_alignment_bytes is not None:\n padding_byte = unpickler.file_handle.read(1)\n padding_length = int.from_bytes(\n padding_byte, byteorder='little')\n if padding_length != 0:\n unpickler.file_handle.read(padding_length)\n\n # This is not a real file. We have to read it the\n # memory-intensive way.\n # crc32 module fails on reads greater than 2 ** 32 bytes,\n # breaking large reads from gzip streams. Chunk reads to\n # BUFFER_SIZE bytes to avoid issue and reduce memory overhead\n # of the read. In non-chunked case count < max_read_count, so\n # only one read is performed.\n max_read_count = BUFFER_SIZE // min(BUFFER_SIZE,\n self.dtype.itemsize)\n\n array = unpickler.np.empty(count, dtype=self.dtype)\n for i in range(0, count, max_read_count):\n read_count = min(max_read_count, count - i)\n read_size = int(read_count * self.dtype.itemsize)\n data = _read_bytes(unpickler.file_handle,\n read_size, \"array data\")\n array[i:i + read_count] = \\\n unpickler.np.frombuffer(data, dtype=self.dtype,\n count=read_count)\n del data\n\n if self.order == 'F':\n array.shape = self.shape[::-1]\n array = array.transpose()\n else:\n array.shape = self.shape\n\n # Detect byte order mismatch and swap as needed.\n return _ensure_native_byte_order(array)\n\n def read_mmap(self, unpickler):\n \"\"\"Read an array using numpy memmap.\"\"\"\n current_pos = unpickler.file_handle.tell()\n offset = current_pos\n numpy_array_alignment_bytes = \\\n self.safe_get_numpy_array_alignment_bytes()\n\n if numpy_array_alignment_bytes is not None:\n padding_byte = unpickler.file_handle.read(1)\n padding_length = int.from_bytes(padding_byte, byteorder='little')\n # + 1 is for the padding byte\n offset += padding_length + 1\n\n if unpickler.mmap_mode == 'w+':\n unpickler.mmap_mode = 'r+'\n\n marray = make_memmap(unpickler.filename,\n dtype=self.dtype,\n shape=self.shape,\n order=self.order,\n mode=unpickler.mmap_mode,\n offset=offset)\n # update the offset so that it corresponds to the end of the read array\n unpickler.file_handle.seek(offset + marray.nbytes)\n\n if (numpy_array_alignment_bytes is None and\n current_pos % NUMPY_ARRAY_ALIGNMENT_BYTES != 0):\n message = (\n f'The memmapped array {marray} loaded from the file '\n f'{unpickler.file_handle.name} is not byte aligned. '\n 'This may cause segmentation faults if this memmapped array '\n 'is used in some libraries like BLAS or PyTorch. '\n 'To get rid of this warning, regenerate your pickle file '\n 'with joblib >= 1.2.0. '\n 'See https://github.com/joblib/joblib/issues/563 '\n 'for more details'\n )\n warnings.warn(message)\n\n return _ensure_native_byte_order(marray)\n\n def read(self, unpickler):\n \"\"\"Read the array corresponding to this wrapper.\n\n Use the unpickler to get all information to correctly read the array.\n\n Parameters\n ----------\n unpickler: NumpyUnpickler\n\n Returns\n -------\n array: numpy.ndarray\n\n \"\"\"\n # When requested, only use memmap mode if allowed.\n if unpickler.mmap_mode is not None and self.allow_mmap:\n array = self.read_mmap(unpickler)\n else:\n array = self.read_array(unpickler)\n\n # Manage array subclass case\n if (hasattr(array, '__array_prepare__') and\n self.subclass not in (unpickler.np.ndarray,\n unpickler.np.memmap)):\n # We need to reconstruct another subclass\n new_array = unpickler.np.core.multiarray._reconstruct(\n self.subclass, (0,), 'b')\n return new_array.__array_prepare__(array)\n else:\n return array\n\n###############################################################################\n# Pickler classes\n\n\nclass NumpyPickler(Pickler):\n \"\"\"A pickler to persist big data efficiently.\n\n The main features of this object are:\n * persistence of numpy arrays in a single file.\n * optional compression with a special care on avoiding memory copies.\n\n Attributes\n ----------\n fp: file\n File object handle used for serializing the input object.\n protocol: int, optional\n Pickle protocol used. Default is pickle.DEFAULT_PROTOCOL.\n \"\"\"\n\n dispatch = Pickler.dispatch.copy()\n\n def __init__(self, fp, protocol=None):\n self.file_handle = fp\n self.buffered = isinstance(self.file_handle, BinaryZlibFile)\n\n # By default we want a pickle protocol that only changes with\n # the major python version and not the minor one\n if protocol is None:\n protocol = pickle.DEFAULT_PROTOCOL\n\n Pickler.__init__(self, self.file_handle, protocol=protocol)\n # delayed import of numpy, to avoid tight coupling\n try:\n import numpy as np\n except ImportError:\n np = None\n self.np = np\n\n def _create_array_wrapper(self, array):\n \"\"\"Create and returns a numpy array wrapper from a numpy array.\"\"\"\n order = 'F' if (array.flags.f_contiguous and\n not array.flags.c_contiguous) else 'C'\n allow_mmap = not self.buffered and not array.dtype.hasobject\n\n kwargs = {}\n try:\n self.file_handle.tell()\n except io.UnsupportedOperation:\n kwargs = {'numpy_array_alignment_bytes': None}\n\n wrapper = NumpyArrayWrapper(type(array),\n array.shape, order, array.dtype,\n allow_mmap=allow_mmap,\n **kwargs)\n\n return wrapper\n\n def save(self, obj):\n \"\"\"Subclass the Pickler `save` method.\n\n This is a total abuse of the Pickler class in order to use the numpy\n persistence function `save` instead of the default pickle\n implementation. The numpy array is replaced by a custom wrapper in the\n pickle persistence stack and the serialized array is written right\n after in the file. Warning: the file produced does not follow the\n pickle format. As such it can not be read with `pickle.load`.\n \"\"\"\n if self.np is not None and type(obj) in (self.np.ndarray,\n self.np.matrix,\n self.np.memmap):\n if type(obj) is self.np.memmap:\n # Pickling doesn't work with memmapped arrays\n obj = self.np.asanyarray(obj)\n\n # The array wrapper is pickled instead of the real array.\n wrapper = self._create_array_wrapper(obj)\n Pickler.save(self, wrapper)\n\n # A framer was introduced with pickle protocol 4 and we want to\n # ensure the wrapper object is written before the numpy array\n # buffer in the pickle file.\n # See https://www.python.org/dev/peps/pep-3154/#framing to get\n # more information on the framer behavior.\n if self.proto >= 4:\n self.framer.commit_frame(force=True)\n\n # And then array bytes are written right after the wrapper.\n wrapper.write_array(obj, self)\n return\n\n return Pickler.save(self, obj)\n\n\nclass NumpyUnpickler(Unpickler):\n \"\"\"A subclass of the Unpickler to unpickle our numpy pickles.\n\n Attributes\n ----------\n mmap_mode: str\n The memorymap mode to use for reading numpy arrays.\n file_handle: file_like\n File object to unpickle from.\n filename: str\n Name of the file to unpickle from. It should correspond to file_handle.\n This parameter is required when using mmap_mode.\n np: module\n Reference to numpy module if numpy is installed else None.\n\n \"\"\"\n\n dispatch = Unpickler.dispatch.copy()\n\n def __init__(self, filename, file_handle, mmap_mode=None):\n # The next line is for backward compatibility with pickle generated\n # with joblib versions less than 0.10.\n self._dirname = os.path.dirname(filename)\n\n self.mmap_mode = mmap_mode\n self.file_handle = file_handle\n # filename is required for numpy mmap mode.\n self.filename = filename\n self.compat_mode = False\n Unpickler.__init__(self, self.file_handle)\n try:\n import numpy as np\n except ImportError:\n np = None\n self.np = np\n\n def load_build(self):\n \"\"\"Called to set the state of a newly created object.\n\n We capture it to replace our place-holder objects, NDArrayWrapper or\n NumpyArrayWrapper, by the array we are interested in. We\n replace them directly in the stack of pickler.\n NDArrayWrapper is used for backward compatibility with joblib <= 0.9.\n \"\"\"\n Unpickler.load_build(self)\n\n # For backward compatibility, we support NDArrayWrapper objects.\n if isinstance(self.stack[-1], (NDArrayWrapper, NumpyArrayWrapper)):\n if self.np is None:\n raise ImportError(\"Trying to unpickle an ndarray, \"\n \"but numpy didn't import correctly\")\n array_wrapper = self.stack.pop()\n # If any NDArrayWrapper is found, we switch to compatibility mode,\n # this will be used to raise a DeprecationWarning to the user at\n # the end of the unpickling.\n if isinstance(array_wrapper, NDArrayWrapper):\n self.compat_mode = True\n self.stack.append(array_wrapper.read(self))\n\n # Be careful to register our new method.\n dispatch[pickle.BUILD[0]] = load_build\n\n\n###############################################################################\n# Utility functions\n\ndef dump(value, filename, compress=0, protocol=None, cache_size=None):\n \"\"\"Persist an arbitrary Python object into one file.\n\n Read more in the :ref:`User Guide `.\n\n Parameters\n ----------\n value: any Python object\n The object to store to disk.\n filename: str, pathlib.Path, or file object.\n The file object or path of the file in which it is to be stored.\n The compression method corresponding to one of the supported filename\n extensions ('.z', '.gz', '.bz2', '.xz' or '.lzma') will be used\n automatically.\n compress: int from 0 to 9 or bool or 2-tuple, optional\n Optional compression level for the data. 0 or False is no compression.\n Higher value means more compression, but also slower read and\n write times. Using a value of 3 is often a good compromise.\n See the notes for more details.\n If compress is True, the compression level used is 3.\n If compress is a 2-tuple, the first element must correspond to a string\n between supported compressors (e.g 'zlib', 'gzip', 'bz2', 'lzma'\n 'xz'), the second element must be an integer from 0 to 9, corresponding\n to the compression level.\n protocol: int, optional\n Pickle protocol, see pickle.dump documentation for more details.\n cache_size: positive int, optional\n This option is deprecated in 0.10 and has no effect.\n\n Returns\n -------\n filenames: list of strings\n The list of file names in which the data is stored. If\n compress is false, each array is stored in a different file.\n\n See Also\n --------\n joblib.load : corresponding loader\n\n Notes\n -----\n Memmapping on load cannot be used for compressed files. Thus\n using compression can significantly slow down loading. In\n addition, compressed files take up extra memory during\n dump and load.\n\n \"\"\"\n\n if Path is not None and isinstance(filename, Path):\n filename = str(filename)\n\n is_filename = isinstance(filename, str)\n is_fileobj = hasattr(filename, \"write\")\n\n compress_method = 'zlib' # zlib is the default compression method.\n if compress is True:\n # By default, if compress is enabled, we want the default compress\n # level of the compressor.\n compress_level = None\n elif isinstance(compress, tuple):\n # a 2-tuple was set in compress\n if len(compress) != 2:\n raise ValueError(\n 'Compress argument tuple should contain exactly 2 elements: '\n '(compress method, compress level), you passed {}'\n .format(compress))\n compress_method, compress_level = compress\n elif isinstance(compress, str):\n compress_method = compress\n compress_level = None # Use default compress level\n compress = (compress_method, compress_level)\n else:\n compress_level = compress\n\n if compress_method == 'lz4' and lz4 is None:\n raise ValueError(LZ4_NOT_INSTALLED_ERROR)\n\n if (compress_level is not None and\n compress_level is not False and\n compress_level not in range(10)):\n # Raising an error if a non valid compress level is given.\n raise ValueError(\n 'Non valid compress level given: \"{}\". Possible values are '\n '{}.'.format(compress_level, list(range(10))))\n\n if compress_method not in _COMPRESSORS:\n # Raising an error if an unsupported compression method is given.\n raise ValueError(\n 'Non valid compression method given: \"{}\". Possible values are '\n '{}.'.format(compress_method, _COMPRESSORS))\n\n if not is_filename and not is_fileobj:\n # People keep inverting arguments, and the resulting error is\n # incomprehensible\n raise ValueError(\n 'Second argument should be a filename or a file-like object, '\n '%s (type %s) was given.'\n % (filename, type(filename))\n )\n\n if is_filename and not isinstance(compress, tuple):\n # In case no explicit compression was requested using both compression\n # method and level in a tuple and the filename has an explicit\n # extension, we select the corresponding compressor.\n\n # unset the variable to be sure no compression level is set afterwards.\n compress_method = None\n for name, compressor in _COMPRESSORS.items():\n if filename.endswith(compressor.extension):\n compress_method = name\n\n if compress_method in _COMPRESSORS and compress_level == 0:\n # we choose the default compress_level in case it was not given\n # as an argument (using compress).\n compress_level = None\n\n if cache_size is not None:\n # Cache size is deprecated starting from version 0.10\n warnings.warn(\"Please do not set 'cache_size' in joblib.dump, \"\n \"this parameter has no effect and will be removed. \"\n \"You used 'cache_size={}'\".format(cache_size),\n DeprecationWarning, stacklevel=2)\n\n if compress_level != 0:\n with _write_fileobject(filename, compress=(compress_method,\n compress_level)) as f:\n NumpyPickler(f, protocol=protocol).dump(value)\n elif is_filename:\n with open(filename, 'wb') as f:\n NumpyPickler(f, protocol=protocol).dump(value)\n else:\n NumpyPickler(filename, protocol=protocol).dump(value)\n\n # If the target container is a file object, nothing is returned.\n if is_fileobj:\n return\n\n # For compatibility, the list of created filenames (e.g with one element\n # after 0.10.0) is returned by default.\n return [filename]\n\n\ndef _unpickle(fobj, filename=\"\", mmap_mode=None):\n \"\"\"Internal unpickling function.\"\"\"\n # We are careful to open the file handle early and keep it open to\n # avoid race-conditions on renames.\n # That said, if data is stored in companion files, which can be\n # the case with the old persistence format, moving the directory\n # will create a race when joblib tries to access the companion\n # files.\n unpickler = NumpyUnpickler(filename, fobj, mmap_mode=mmap_mode)\n obj = None\n try:\n obj = unpickler.load()\n if unpickler.compat_mode:\n warnings.warn(\"The file '%s' has been generated with a \"\n \"joblib version less than 0.10. \"\n \"Please regenerate this pickle file.\"\n % filename,\n DeprecationWarning, stacklevel=3)\n except UnicodeDecodeError as exc:\n # More user-friendly error message\n new_exc = ValueError(\n 'You may be trying to read with '\n 'python 3 a joblib pickle generated with python 2. '\n 'This feature is not supported by joblib.')\n new_exc.__cause__ = exc\n raise new_exc\n return obj\n\n\ndef load_temporary_memmap(filename, mmap_mode, unlink_on_gc_collect):\n from ._memmapping_reducer import JOBLIB_MMAPS, add_maybe_unlink_finalizer\n obj = load(filename, mmap_mode)\n JOBLIB_MMAPS.add(obj.filename)\n if unlink_on_gc_collect:\n add_maybe_unlink_finalizer(obj)\n return obj\n\n\ndef load(filename, mmap_mode=None):\n \"\"\"Reconstruct a Python object from a file persisted with joblib.dump.\n\n Read more in the :ref:`User Guide `.\n\n WARNING: joblib.load relies on the pickle module and can therefore\n execute arbitrary Python code. It should therefore never be used\n to load files from untrusted sources.\n\n Parameters\n ----------\n filename: str, pathlib.Path, or file object.\n The file object or path of the file from which to load the object\n mmap_mode: {None, 'r+', 'r', 'w+', 'c'}, optional\n If not None, the arrays are memory-mapped from the disk. This\n mode has no effect for compressed files. Note that in this\n case the reconstructed object might no longer match exactly\n the originally pickled object.\n\n Returns\n -------\n result: any Python object\n The object stored in the file.\n\n See Also\n --------\n joblib.dump : function to save an object\n\n Notes\n -----\n\n This function can load numpy array files saved separately during the\n dump. If the mmap_mode argument is given, it is passed to np.load and\n arrays are loaded as memmaps. As a consequence, the reconstructed\n object might not match the original pickled object. Note that if the\n file was saved with compression, the arrays cannot be memmapped.\n \"\"\"\n if Path is not None and isinstance(filename, Path):\n filename = str(filename)\n\n if hasattr(filename, \"read\"):\n fobj = filename\n filename = getattr(fobj, 'name', '')\n with _read_fileobject(fobj, filename, mmap_mode) as fobj:\n obj = _unpickle(fobj)\n else:\n with open(filename, 'rb') as f:\n with _read_fileobject(f, filename, mmap_mode) as fobj:\n if isinstance(fobj, str):\n # if the returned file object is a string, this means we\n # try to load a pickle file generated with an version of\n # Joblib so we load it with joblib compatibility function.\n return load_compatibility(fobj)\n\n obj = _unpickle(fobj, filename, mmap_mode)\n return obj\n", "joblib/test/test_numpy_pickle.py": "\"\"\"Test the numpy pickler as a replacement of the standard pickler.\"\"\"\n\nimport copy\nimport os\nimport random\nimport re\nimport io\nimport sys\nimport warnings\nimport gzip\nimport zlib\nimport bz2\nimport pickle\nimport socket\nfrom contextlib import closing\nimport mmap\nfrom pathlib import Path\n\ntry:\n import lzma\nexcept ImportError:\n lzma = None\n\nimport pytest\n\nfrom joblib.test.common import np, with_numpy, with_lz4, without_lz4\nfrom joblib.test.common import with_memory_profiler, memory_used\nfrom joblib.testing import parametrize, raises, warns\n\n# numpy_pickle is not a drop-in replacement of pickle, as it takes\n# filenames instead of open files as arguments.\nfrom joblib import numpy_pickle, register_compressor\nfrom joblib.test import data\n\nfrom joblib.numpy_pickle_utils import _IO_BUFFER_SIZE\nfrom joblib.numpy_pickle_utils import _detect_compressor\nfrom joblib.numpy_pickle_utils import _is_numpy_array_byte_order_mismatch\nfrom joblib.numpy_pickle_utils import _ensure_native_byte_order\nfrom joblib.compressor import (_COMPRESSORS, _LZ4_PREFIX, CompressorWrapper,\n LZ4_NOT_INSTALLED_ERROR, BinaryZlibFile)\n\n\n###############################################################################\n# Define a list of standard types.\n# Borrowed from dill, initial author: Micheal McKerns:\n# http://dev.danse.us/trac/pathos/browser/dill/dill_test2.py\n\ntypelist = []\n\n# testing types\n_none = None\ntypelist.append(_none)\n_type = type\ntypelist.append(_type)\n_bool = bool(1)\ntypelist.append(_bool)\n_int = int(1)\ntypelist.append(_int)\n_float = float(1)\ntypelist.append(_float)\n_complex = complex(1)\ntypelist.append(_complex)\n_string = str(1)\ntypelist.append(_string)\n_tuple = ()\ntypelist.append(_tuple)\n_list = []\ntypelist.append(_list)\n_dict = {}\ntypelist.append(_dict)\n_builtin = len\ntypelist.append(_builtin)\n\n\ndef _function(x):\n yield x\n\n\nclass _class:\n def _method(self):\n pass\n\n\nclass _newclass(object):\n def _method(self):\n pass\n\n\ntypelist.append(_function)\ntypelist.append(_class)\ntypelist.append(_newclass) # \n_instance = _class()\ntypelist.append(_instance)\n_object = _newclass()\ntypelist.append(_object) # \n\n\n###############################################################################\n# Tests\n\n@parametrize('compress', [0, 1])\n@parametrize('member', typelist)\ndef test_standard_types(tmpdir, compress, member):\n # Test pickling and saving with standard types.\n filename = tmpdir.join('test.pkl').strpath\n numpy_pickle.dump(member, filename, compress=compress)\n _member = numpy_pickle.load(filename)\n # We compare the pickled instance to the reloaded one only if it\n # can be compared to a copied one\n if member == copy.deepcopy(member):\n assert member == _member\n\n\ndef test_value_error():\n # Test inverting the input arguments to dump\n with raises(ValueError):\n numpy_pickle.dump('foo', dict())\n\n\n@parametrize('wrong_compress', [-1, 10, dict()])\ndef test_compress_level_error(wrong_compress):\n # Verify that passing an invalid compress argument raises an error.\n exception_msg = ('Non valid compress level given: '\n '\"{0}\"'.format(wrong_compress))\n with raises(ValueError) as excinfo:\n numpy_pickle.dump('dummy', 'foo', compress=wrong_compress)\n excinfo.match(exception_msg)\n\n\n@with_numpy\n@parametrize('compress', [False, True, 0, 3, 'zlib'])\ndef test_numpy_persistence(tmpdir, compress):\n filename = tmpdir.join('test.pkl').strpath\n rnd = np.random.RandomState(0)\n a = rnd.random_sample((10, 2))\n # We use 'a.T' to have a non C-contiguous array.\n for index, obj in enumerate(((a,), (a.T,), (a, a), [a, a, a])):\n filenames = numpy_pickle.dump(obj, filename, compress=compress)\n\n # All is cached in one file\n assert len(filenames) == 1\n # Check that only one file was created\n assert filenames[0] == filename\n # Check that this file does exist\n assert os.path.exists(filenames[0])\n\n # Unpickle the object\n obj_ = numpy_pickle.load(filename)\n # Check that the items are indeed arrays\n for item in obj_:\n assert isinstance(item, np.ndarray)\n # And finally, check that all the values are equal.\n np.testing.assert_array_equal(np.array(obj), np.array(obj_))\n\n # Now test with an array subclass\n obj = np.memmap(filename + 'mmap', mode='w+', shape=4, dtype=np.float64)\n filenames = numpy_pickle.dump(obj, filename, compress=compress)\n # All is cached in one file\n assert len(filenames) == 1\n\n obj_ = numpy_pickle.load(filename)\n if (type(obj) is not np.memmap and\n hasattr(obj, '__array_prepare__')):\n # We don't reconstruct memmaps\n assert isinstance(obj_, type(obj))\n\n np.testing.assert_array_equal(obj_, obj)\n\n # Test with an object containing multiple numpy arrays\n obj = ComplexTestObject()\n filenames = numpy_pickle.dump(obj, filename, compress=compress)\n # All is cached in one file\n assert len(filenames) == 1\n\n obj_loaded = numpy_pickle.load(filename)\n assert isinstance(obj_loaded, type(obj))\n np.testing.assert_array_equal(obj_loaded.array_float, obj.array_float)\n np.testing.assert_array_equal(obj_loaded.array_int, obj.array_int)\n np.testing.assert_array_equal(obj_loaded.array_obj, obj.array_obj)\n\n\n@with_numpy\ndef test_numpy_persistence_bufferred_array_compression(tmpdir):\n big_array = np.ones((_IO_BUFFER_SIZE + 100), dtype=np.uint8)\n filename = tmpdir.join('test.pkl').strpath\n numpy_pickle.dump(big_array, filename, compress=True)\n arr_reloaded = numpy_pickle.load(filename)\n\n np.testing.assert_array_equal(big_array, arr_reloaded)\n\n\n@with_numpy\ndef test_memmap_persistence(tmpdir):\n rnd = np.random.RandomState(0)\n a = rnd.random_sample(10)\n filename = tmpdir.join('test1.pkl').strpath\n numpy_pickle.dump(a, filename)\n b = numpy_pickle.load(filename, mmap_mode='r')\n\n assert isinstance(b, np.memmap)\n\n # Test with an object containing multiple numpy arrays\n filename = tmpdir.join('test2.pkl').strpath\n obj = ComplexTestObject()\n numpy_pickle.dump(obj, filename)\n obj_loaded = numpy_pickle.load(filename, mmap_mode='r')\n assert isinstance(obj_loaded, type(obj))\n assert isinstance(obj_loaded.array_float, np.memmap)\n assert not obj_loaded.array_float.flags.writeable\n assert isinstance(obj_loaded.array_int, np.memmap)\n assert not obj_loaded.array_int.flags.writeable\n # Memory map not allowed for numpy object arrays\n assert not isinstance(obj_loaded.array_obj, np.memmap)\n np.testing.assert_array_equal(obj_loaded.array_float,\n obj.array_float)\n np.testing.assert_array_equal(obj_loaded.array_int,\n obj.array_int)\n np.testing.assert_array_equal(obj_loaded.array_obj,\n obj.array_obj)\n\n # Test we can write in memmapped arrays\n obj_loaded = numpy_pickle.load(filename, mmap_mode='r+')\n assert obj_loaded.array_float.flags.writeable\n obj_loaded.array_float[0:10] = 10.0\n assert obj_loaded.array_int.flags.writeable\n obj_loaded.array_int[0:10] = 10\n\n obj_reloaded = numpy_pickle.load(filename, mmap_mode='r')\n np.testing.assert_array_equal(obj_reloaded.array_float,\n obj_loaded.array_float)\n np.testing.assert_array_equal(obj_reloaded.array_int,\n obj_loaded.array_int)\n\n # Test w+ mode is caught and the mode has switched to r+\n numpy_pickle.load(filename, mmap_mode='w+')\n assert obj_loaded.array_int.flags.writeable\n assert obj_loaded.array_int.mode == 'r+'\n assert obj_loaded.array_float.flags.writeable\n assert obj_loaded.array_float.mode == 'r+'\n\n\n@with_numpy\ndef test_memmap_persistence_mixed_dtypes(tmpdir):\n # loading datastructures that have sub-arrays with dtype=object\n # should not prevent memmapping on fixed size dtype sub-arrays.\n rnd = np.random.RandomState(0)\n a = rnd.random_sample(10)\n b = np.array([1, 'b'], dtype=object)\n construct = (a, b)\n filename = tmpdir.join('test.pkl').strpath\n numpy_pickle.dump(construct, filename)\n a_clone, b_clone = numpy_pickle.load(filename, mmap_mode='r')\n\n # the floating point array has been memory mapped\n assert isinstance(a_clone, np.memmap)\n\n # the object-dtype array has been loaded in memory\n assert not isinstance(b_clone, np.memmap)\n\n\n@with_numpy\ndef test_masked_array_persistence(tmpdir):\n # The special-case picker fails, because saving masked_array\n # not implemented, but it just delegates to the standard pickler.\n rnd = np.random.RandomState(0)\n a = rnd.random_sample(10)\n a = np.ma.masked_greater(a, 0.5)\n filename = tmpdir.join('test.pkl').strpath\n numpy_pickle.dump(a, filename)\n b = numpy_pickle.load(filename, mmap_mode='r')\n assert isinstance(b, np.ma.masked_array)\n\n\n@with_numpy\ndef test_compress_mmap_mode_warning(tmpdir):\n # Test the warning in case of compress + mmap_mode\n rnd = np.random.RandomState(0)\n a = rnd.random_sample(10)\n this_filename = tmpdir.join('test.pkl').strpath\n numpy_pickle.dump(a, this_filename, compress=1)\n with warns(UserWarning) as warninfo:\n numpy_pickle.load(this_filename, mmap_mode='r+')\n debug_msg = \"\\n\".join([str(w) for w in warninfo])\n warninfo = [w.message for w in warninfo]\n assert len(warninfo) == 1, debug_msg\n assert (\n str(warninfo[0]) ==\n 'mmap_mode \"r+\" is not compatible with compressed '\n f'file {this_filename}. \"r+\" flag will be ignored.'\n )\n\n\n@with_numpy\n@parametrize('cache_size', [None, 0, 10])\ndef test_cache_size_warning(tmpdir, cache_size):\n # Check deprecation warning raised when cache size is not None\n filename = tmpdir.join('test.pkl').strpath\n rnd = np.random.RandomState(0)\n a = rnd.random_sample((10, 2))\n\n warnings.simplefilter(\"always\")\n with warnings.catch_warnings(record=True) as warninfo:\n numpy_pickle.dump(a, filename, cache_size=cache_size)\n expected_nb_warnings = 1 if cache_size is not None else 0\n assert len(warninfo) == expected_nb_warnings\n for w in warninfo:\n assert w.category == DeprecationWarning\n assert (str(w.message) ==\n \"Please do not set 'cache_size' in joblib.dump, this \"\n \"parameter has no effect and will be removed. You \"\n \"used 'cache_size={0}'\".format(cache_size))\n\n\n@with_numpy\n@with_memory_profiler\n@parametrize('compress', [True, False])\ndef test_memory_usage(tmpdir, compress):\n # Verify memory stays within expected bounds.\n filename = tmpdir.join('test.pkl').strpath\n small_array = np.ones((10, 10))\n big_array = np.ones(shape=100 * int(1e6), dtype=np.uint8)\n\n for obj in (small_array, big_array):\n size = obj.nbytes / 1e6\n obj_filename = filename + str(np.random.randint(0, 1000))\n mem_used = memory_used(numpy_pickle.dump,\n obj, obj_filename, compress=compress)\n\n # The memory used to dump the object shouldn't exceed the buffer\n # size used to write array chunks (16MB).\n write_buf_size = _IO_BUFFER_SIZE + 16 * 1024 ** 2 / 1e6\n assert mem_used <= write_buf_size\n\n mem_used = memory_used(numpy_pickle.load, obj_filename)\n # memory used should be less than array size + buffer size used to\n # read the array chunk by chunk.\n read_buf_size = 32 + _IO_BUFFER_SIZE # MiB\n assert mem_used < size + read_buf_size\n\n\n@with_numpy\ndef test_compressed_pickle_dump_and_load(tmpdir):\n expected_list = [np.arange(5, dtype=np.dtype('i8')),\n np.arange(5, dtype=np.dtype('f8')),\n np.array([1, 'abc', {'a': 1, 'b': 2}], dtype='O'),\n np.arange(256, dtype=np.uint8).tobytes(),\n u\"C'est l'\\xe9t\\xe9 !\"]\n\n fname = tmpdir.join('temp.pkl.gz').strpath\n\n dumped_filenames = numpy_pickle.dump(expected_list, fname, compress=1)\n assert len(dumped_filenames) == 1\n result_list = numpy_pickle.load(fname)\n for result, expected in zip(result_list, expected_list):\n if isinstance(expected, np.ndarray):\n expected = _ensure_native_byte_order(expected)\n assert result.dtype == expected.dtype\n np.testing.assert_equal(result, expected)\n else:\n assert result == expected\n\n\ndef _check_pickle(filename, expected_list, mmap_mode=None):\n \"\"\"Helper function to test joblib pickle content.\n\n Note: currently only pickles containing an iterable are supported\n by this function.\n \"\"\"\n version_match = re.match(r'.+py(\\d)(\\d).+', filename)\n py_version_used_for_writing = int(version_match.group(1))\n\n py_version_to_default_pickle_protocol = {2: 2, 3: 3}\n pickle_reading_protocol = py_version_to_default_pickle_protocol.get(3, 4)\n pickle_writing_protocol = py_version_to_default_pickle_protocol.get(\n py_version_used_for_writing, 4)\n if pickle_reading_protocol >= pickle_writing_protocol:\n try:\n with warnings.catch_warnings(record=True) as warninfo:\n warnings.simplefilter('always')\n warnings.filterwarnings(\n 'ignore', module='numpy',\n message='The compiler package is deprecated')\n result_list = numpy_pickle.load(filename, mmap_mode=mmap_mode)\n filename_base = os.path.basename(filename)\n expected_nb_deprecation_warnings = 1 if (\n \"_0.9\" in filename_base or \"_0.8.4\" in filename_base) else 0\n\n expected_nb_user_warnings = 3 if (\n re.search(\"_0.1.+.pkl$\", filename_base) and\n mmap_mode is not None) else 0\n expected_nb_warnings = \\\n expected_nb_deprecation_warnings + expected_nb_user_warnings\n assert len(warninfo) == expected_nb_warnings\n\n deprecation_warnings = [\n w for w in warninfo if issubclass(\n w.category, DeprecationWarning)]\n user_warnings = [\n w for w in warninfo if issubclass(\n w.category, UserWarning)]\n for w in deprecation_warnings:\n assert (str(w.message) ==\n \"The file '{0}' has been generated with a joblib \"\n \"version less than 0.10. Please regenerate this \"\n \"pickle file.\".format(filename))\n\n for w in user_warnings:\n escaped_filename = re.escape(filename)\n assert re.search(\n f\"memmapped.+{escaped_filename}.+segmentation fault\",\n str(w.message))\n\n for result, expected in zip(result_list, expected_list):\n if isinstance(expected, np.ndarray):\n expected = _ensure_native_byte_order(expected)\n assert result.dtype == expected.dtype\n np.testing.assert_equal(result, expected)\n else:\n assert result == expected\n except Exception as exc:\n # When trying to read with python 3 a pickle generated\n # with python 2 we expect a user-friendly error\n if py_version_used_for_writing == 2:\n assert isinstance(exc, ValueError)\n message = ('You may be trying to read with '\n 'python 3 a joblib pickle generated with python 2.')\n assert message in str(exc)\n elif filename.endswith('.lz4') and with_lz4.args[0]:\n assert isinstance(exc, ValueError)\n assert LZ4_NOT_INSTALLED_ERROR in str(exc)\n else:\n raise\n else:\n # Pickle protocol used for writing is too high. We expect a\n # \"unsupported pickle protocol\" error message\n try:\n numpy_pickle.load(filename)\n raise AssertionError('Numpy pickle loading should '\n 'have raised a ValueError exception')\n except ValueError as e:\n message = 'unsupported pickle protocol: {0}'.format(\n pickle_writing_protocol)\n assert message in str(e.args)\n\n\n@with_numpy\ndef test_joblib_pickle_across_python_versions():\n # We need to be specific about dtypes in particular endianness\n # because the pickles can be generated on one architecture and\n # the tests run on another one. See\n # https://github.com/joblib/joblib/issues/279.\n expected_list = [np.arange(5, dtype=np.dtype('i8'), ('', '>f8')]),\n np.arange(3, dtype=np.dtype('>i8')),\n np.arange(3, dtype=np.dtype('>f8'))]\n\n # Verify the byteorder mismatch is correctly detected.\n for array in be_arrays:\n if sys.byteorder == 'big':\n assert not _is_numpy_array_byte_order_mismatch(array)\n else:\n assert _is_numpy_array_byte_order_mismatch(array)\n converted = _ensure_native_byte_order(array)\n if converted.dtype.fields:\n for f in converted.dtype.fields.values():\n f[0].byteorder == '='\n else:\n assert converted.dtype.byteorder == \"=\"\n\n # List of numpy arrays with little endian byteorder.\n le_arrays = [np.array([(1, 2.0), (3, 4.0)],\n dtype=[('', ' size\n np.testing.assert_array_equal(obj, memmaps)\n\n\ndef test_register_compressor(tmpdir):\n # Check that registering compressor file works.\n compressor_name = 'test-name'\n compressor_prefix = 'test-prefix'\n\n class BinaryCompressorTestFile(io.BufferedIOBase):\n pass\n\n class BinaryCompressorTestWrapper(CompressorWrapper):\n\n def __init__(self):\n CompressorWrapper.__init__(self, obj=BinaryCompressorTestFile,\n prefix=compressor_prefix)\n\n register_compressor(compressor_name, BinaryCompressorTestWrapper())\n\n assert (_COMPRESSORS[compressor_name].fileobj_factory ==\n BinaryCompressorTestFile)\n assert _COMPRESSORS[compressor_name].prefix == compressor_prefix\n\n # Remove this dummy compressor file from extra compressors because other\n # tests might fail because of this\n _COMPRESSORS.pop(compressor_name)\n\n\n@parametrize('invalid_name', [1, (), {}])\ndef test_register_compressor_invalid_name(invalid_name):\n # Test that registering an invalid compressor name is not allowed.\n with raises(ValueError) as excinfo:\n register_compressor(invalid_name, None)\n excinfo.match(\"Compressor name should be a string\")\n\n\ndef test_register_compressor_invalid_fileobj():\n # Test that registering an invalid file object is not allowed.\n\n class InvalidFileObject():\n pass\n\n class InvalidFileObjectWrapper(CompressorWrapper):\n def __init__(self):\n CompressorWrapper.__init__(self, obj=InvalidFileObject,\n prefix=b'prefix')\n\n with raises(ValueError) as excinfo:\n register_compressor('invalid', InvalidFileObjectWrapper())\n\n excinfo.match(\"Compressor 'fileobj_factory' attribute should implement \"\n \"the file object interface\")\n\n\nclass AnotherZlibCompressorWrapper(CompressorWrapper):\n\n def __init__(self):\n CompressorWrapper.__init__(self, obj=BinaryZlibFile, prefix=b'prefix')\n\n\nclass StandardLibGzipCompressorWrapper(CompressorWrapper):\n\n def __init__(self):\n CompressorWrapper.__init__(self, obj=gzip.GzipFile, prefix=b'prefix')\n\n\ndef test_register_compressor_already_registered():\n # Test registration of existing compressor files.\n compressor_name = 'test-name'\n\n # register a test compressor\n register_compressor(compressor_name, AnotherZlibCompressorWrapper())\n\n with raises(ValueError) as excinfo:\n register_compressor(compressor_name,\n StandardLibGzipCompressorWrapper())\n excinfo.match(\"Compressor '{}' already registered.\"\n .format(compressor_name))\n\n register_compressor(compressor_name, StandardLibGzipCompressorWrapper(),\n force=True)\n\n assert compressor_name in _COMPRESSORS\n assert _COMPRESSORS[compressor_name].fileobj_factory == gzip.GzipFile\n\n # Remove this dummy compressor file from extra compressors because other\n # tests might fail because of this\n _COMPRESSORS.pop(compressor_name)\n\n\n@with_lz4\ndef test_lz4_compression(tmpdir):\n # Check that lz4 can be used when dependency is available.\n import lz4.frame\n compressor = 'lz4'\n assert compressor in _COMPRESSORS\n assert _COMPRESSORS[compressor].fileobj_factory == lz4.frame.LZ4FrameFile\n\n fname = tmpdir.join('test.pkl').strpath\n data = 'test data'\n numpy_pickle.dump(data, fname, compress=compressor)\n\n with open(fname, 'rb') as f:\n assert f.read(len(_LZ4_PREFIX)) == _LZ4_PREFIX\n assert numpy_pickle.load(fname) == data\n\n # Test that LZ4 is applied based on file extension\n numpy_pickle.dump(data, fname + '.lz4')\n with open(fname, 'rb') as f:\n assert f.read(len(_LZ4_PREFIX)) == _LZ4_PREFIX\n assert numpy_pickle.load(fname) == data\n\n\n@without_lz4\ndef test_lz4_compression_without_lz4(tmpdir):\n # Check that lz4 cannot be used when dependency is not available.\n fname = tmpdir.join('test.nolz4').strpath\n data = 'test data'\n msg = LZ4_NOT_INSTALLED_ERROR\n with raises(ValueError) as excinfo:\n numpy_pickle.dump(data, fname, compress='lz4')\n excinfo.match(msg)\n\n with raises(ValueError) as excinfo:\n numpy_pickle.dump(data, fname + '.lz4')\n excinfo.match(msg)\n\n\nprotocols = [pickle.DEFAULT_PROTOCOL]\nif pickle.HIGHEST_PROTOCOL != pickle.DEFAULT_PROTOCOL:\n protocols.append(pickle.HIGHEST_PROTOCOL)\n\n\n@with_numpy\n@parametrize('protocol', protocols)\ndef test_memmap_alignment_padding(tmpdir, protocol):\n # Test that memmaped arrays returned by numpy.load are correctly aligned\n fname = tmpdir.join('test.mmap').strpath\n\n a = np.random.randn(2)\n numpy_pickle.dump(a, fname, protocol=protocol)\n memmap = numpy_pickle.load(fname, mmap_mode='r')\n assert isinstance(memmap, np.memmap)\n np.testing.assert_array_equal(a, memmap)\n assert (\n memmap.ctypes.data % numpy_pickle.NUMPY_ARRAY_ALIGNMENT_BYTES == 0)\n assert memmap.flags.aligned\n\n array_list = [\n np.random.randn(2), np.random.randn(2),\n np.random.randn(2), np.random.randn(2)\n ]\n\n # On Windows OSError 22 if reusing the same path for memmap ...\n fname = tmpdir.join('test1.mmap').strpath\n numpy_pickle.dump(array_list, fname, protocol=protocol)\n l_reloaded = numpy_pickle.load(fname, mmap_mode='r')\n\n for idx, memmap in enumerate(l_reloaded):\n assert isinstance(memmap, np.memmap)\n np.testing.assert_array_equal(array_list[idx], memmap)\n assert (\n memmap.ctypes.data % numpy_pickle.NUMPY_ARRAY_ALIGNMENT_BYTES == 0)\n assert memmap.flags.aligned\n\n array_dict = {\n 'a0': np.arange(2, dtype=np.uint8),\n 'a1': np.arange(3, dtype=np.uint8),\n 'a2': np.arange(5, dtype=np.uint8),\n 'a3': np.arange(7, dtype=np.uint8),\n 'a4': np.arange(11, dtype=np.uint8),\n 'a5': np.arange(13, dtype=np.uint8),\n 'a6': np.arange(17, dtype=np.uint8),\n 'a7': np.arange(19, dtype=np.uint8),\n 'a8': np.arange(23, dtype=np.uint8),\n }\n\n # On Windows OSError 22 if reusing the same path for memmap ...\n fname = tmpdir.join('test2.mmap').strpath\n numpy_pickle.dump(array_dict, fname, protocol=protocol)\n d_reloaded = numpy_pickle.load(fname, mmap_mode='r')\n\n for key, memmap in d_reloaded.items():\n assert isinstance(memmap, np.memmap)\n np.testing.assert_array_equal(array_dict[key], memmap)\n assert (\n memmap.ctypes.data % numpy_pickle.NUMPY_ARRAY_ALIGNMENT_BYTES == 0)\n assert memmap.flags.aligned\n"}, "files_after": {"examples/compressors_comparison.py": "\"\"\"\n===============================\nImproving I/O using compressors\n===============================\n\nThis example compares the compressors available in Joblib. In the example,\nZlib, LZMA and LZ4 compression only are used but Joblib also supports BZ2 and\nGZip compression methods.\nFor each compared compression method, this example dumps and reloads a\ndataset fetched from an online machine-learning database. This gives 3\ninformation: the size on disk of the compressed data, the time spent to dump\nand the time spent to reload the data from disk.\n\"\"\"\n\nimport os\nimport os.path\nimport time\n\n###############################################################################\n# Get some data from real-world use cases\n# ---------------------------------------\n#\n# First fetch the benchmark dataset from an online machine-learning database\n# and load it in a pandas dataframe.\n\nimport pandas as pd\n\nurl = \"https://github.com/joblib/dataset/raw/main/kddcup.data.gz\"\nnames = (\"duration, protocol_type, service, flag, src_bytes, \"\n \"dst_bytes, land, wrong_fragment, urgent, hot, \"\n \"num_failed_logins, logged_in, num_compromised, \"\n \"root_shell, su_attempted, num_root, \"\n \"num_file_creations, \").split(', ')\n\ndata = pd.read_csv(url, names=names, nrows=1e6)\n\n###############################################################################\n# Dump and load the dataset without compression\n# ---------------------------------------------\n#\n# This gives reference values for later comparison.\n\nfrom joblib import dump, load\n\npickle_file = './pickle_data.joblib'\n\n###############################################################################\n# Start by measuring the time spent for dumping the raw data:\nstart = time.time()\nwith open(pickle_file, 'wb') as f:\n dump(data, f)\nraw_dump_duration = time.time() - start\nprint(\"Raw dump duration: %0.3fs\" % raw_dump_duration)\n\n###############################################################################\n# Then measure the size of the raw dumped data on disk:\nraw_file_size = os.stat(pickle_file).st_size / 1e6\nprint(\"Raw dump file size: %0.3fMB\" % raw_file_size)\n\n###############################################################################\n# Finally measure the time spent for loading the raw data:\nstart = time.time()\nwith open(pickle_file, 'rb') as f:\n load(f, allow_pickle=True)\nraw_load_duration = time.time() - start\nprint(\"Raw load duration: %0.3fs\" % raw_load_duration)\n\n###############################################################################\n# Dump and load the dataset using the Zlib compression method\n# -----------------------------------------------------------\n#\n# The compression level is using the default value, 3, which is, in general, a\n# good compromise between compression and speed.\n\n###############################################################################\n# Start by measuring the time spent for dumping of the zlib data:\n\nstart = time.time()\nwith open(pickle_file, 'wb') as f:\n dump(data, f, compress='zlib')\nzlib_dump_duration = time.time() - start\nprint(\"Zlib dump duration: %0.3fs\" % zlib_dump_duration)\n\n###############################################################################\n# Then measure the size of the zlib dump data on disk:\n\nzlib_file_size = os.stat(pickle_file).st_size / 1e6\nprint(\"Zlib file size: %0.3fMB\" % zlib_file_size)\n\n###############################################################################\n# Finally measure the time spent for loading the compressed dataset:\n\nstart = time.time()\nwith open(pickle_file, 'rb') as f:\n load(f, allow_pickle=True)\nzlib_load_duration = time.time() - start\nprint(\"Zlib load duration: %0.3fs\" % zlib_load_duration)\n\n###############################################################################\n# .. note:: The compression format is detected automatically by Joblib.\n# The compression format is identified by the standard magic number present\n# at the beginning of the file. Joblib uses this information to determine\n# the compression method used.\n# This is the case for all compression methods supported by Joblib.\n\n###############################################################################\n# Dump and load the dataset using the LZMA compression method\n# -----------------------------------------------------------\n#\n# LZMA compression method has a very good compression rate but at the cost\n# of being very slow.\n# In this example, a light compression level, e.g. 3, is used to speed up a\n# bit the dump/load cycle.\n\n###############################################################################\n# Start by measuring the time spent for dumping the lzma data:\n\nstart = time.time()\nwith open(pickle_file, 'wb') as f:\n dump(data, f, compress=('lzma', 3))\nlzma_dump_duration = time.time() - start\nprint(\"LZMA dump duration: %0.3fs\" % lzma_dump_duration)\n\n###############################################################################\n# Then measure the size of the lzma dump data on disk:\n\nlzma_file_size = os.stat(pickle_file).st_size / 1e6\nprint(\"LZMA file size: %0.3fMB\" % lzma_file_size)\n\n###############################################################################\n# Finally measure the time spent for loading the lzma data:\n\nstart = time.time()\nwith open(pickle_file, 'rb') as f:\n load(f, allow_pickle=True)\nlzma_load_duration = time.time() - start\nprint(\"LZMA load duration: %0.3fs\" % lzma_load_duration)\n\n###############################################################################\n# Dump and load the dataset using the LZ4 compression method\n# ----------------------------------------------------------\n#\n# LZ4 compression method is known to be one of the fastest available\n# compression method but with a compression rate a bit lower than Zlib. In\n# most of the cases, this method is a good choice.\n\n###############################################################################\n# .. note:: In order to use LZ4 compression with Joblib, the\n# `lz4 `_ package must be installed\n# on the system.\n\n###############################################################################\n# Start by measuring the time spent for dumping the lz4 data:\n\nstart = time.time()\nwith open(pickle_file, 'wb') as f:\n dump(data, f, compress='lz4')\nlz4_dump_duration = time.time() - start\nprint(\"LZ4 dump duration: %0.3fs\" % lz4_dump_duration)\n\n###############################################################################\n# Then measure the size of the lz4 dump data on disk:\n\nlz4_file_size = os.stat(pickle_file).st_size / 1e6\nprint(\"LZ4 file size: %0.3fMB\" % lz4_file_size)\n\n###############################################################################\n# Finally measure the time spent for loading the lz4 data:\n\nstart = time.time()\nwith open(pickle_file, 'rb') as f:\n load(f, allow_pickle=True)\nlz4_load_duration = time.time() - start\nprint(\"LZ4 load duration: %0.3fs\" % lz4_load_duration)\n\n###############################################################################\n# Comparing the results\n# ---------------------\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nN = 4\nload_durations = (raw_load_duration, lz4_load_duration, zlib_load_duration,\n lzma_load_duration)\ndump_durations = (raw_dump_duration, lz4_dump_duration, zlib_dump_duration,\n lzma_dump_duration)\nfile_sizes = (raw_file_size, lz4_file_size, zlib_file_size, lzma_file_size)\nind = np.arange(N)\nwidth = 0.5\n\nplt.figure(1, figsize=(5, 4))\np1 = plt.bar(ind, dump_durations, width)\np2 = plt.bar(ind, load_durations, width, bottom=dump_durations)\nplt.ylabel('Time in seconds')\nplt.title('Dump and load durations')\nplt.xticks(ind, ('Raw', 'LZ4', 'Zlib', 'LZMA'))\nplt.yticks(np.arange(0, lzma_load_duration + lzma_dump_duration))\nplt.legend((p1[0], p2[0]), ('Dump duration', 'Load duration'))\n\n###############################################################################\n# Compared with other compressors, LZ4 is clearly the fastest, especially for\n# dumping compressed data on disk. In this particular case, it can even be\n# faster than the raw dump.\n# Also note that dump and load durations depend on the I/O speed of the\n# underlying storage: for example, with SSD hard drives the LZ4 compression\n# will be slightly slower than raw dump/load, whereas with spinning hard disk\n# drives (HDD) or remote storage (NFS), LZ4 is faster in general.\n#\n# LZMA and Zlib, even if always slower for dumping data, are quite fast when\n# re-loading compressed data from disk.\n\nplt.figure(2, figsize=(5, 4))\nplt.bar(ind, file_sizes, width, log=True)\nplt.ylabel('File size in MB')\nplt.xticks(ind, ('Raw', 'LZ4', 'Zlib', 'LZMA'))\n\n###############################################################################\n# Compressed data obviously takes a lot less space on disk than raw data. LZMA\n# is the best compression method in terms of compression rate. Zlib also has a\n# better compression rate than LZ4.\n\nplt.show()\n\n###############################################################################\n# Clear the pickle file\n# ---------------------\n\nimport os\nos.remove(pickle_file)\n", "joblib/numpy_pickle.py": "\"\"\"Utilities for fast persistence of big data, with optional compression.\"\"\"\n\n# Author: Gael Varoquaux \n# Copyright (c) 2009 Gael Varoquaux\n# License: BSD Style, 3 clauses.\n\nimport pickle\nimport os\nimport warnings\nimport io\nfrom pathlib import Path\n\nfrom .compressor import lz4, LZ4_NOT_INSTALLED_ERROR\nfrom .compressor import _COMPRESSORS, register_compressor, BinaryZlibFile\nfrom .compressor import (ZlibCompressorWrapper, GzipCompressorWrapper,\n BZ2CompressorWrapper, LZMACompressorWrapper,\n XZCompressorWrapper, LZ4CompressorWrapper)\nfrom .numpy_pickle_utils import Unpickler, Pickler\nfrom .numpy_pickle_utils import _read_fileobject, _write_fileobject\nfrom .numpy_pickle_utils import _read_bytes, BUFFER_SIZE\nfrom .numpy_pickle_utils import _ensure_native_byte_order\nfrom .numpy_pickle_compat import load_compatibility\nfrom .numpy_pickle_compat import NDArrayWrapper\n# For compatibility with old versions of joblib, we need ZNDArrayWrapper\n# to be visible in the current namespace.\n# Explicitly skipping next line from flake8 as it triggers an F401 warning\n# which we don't care.\nfrom .numpy_pickle_compat import ZNDArrayWrapper # noqa\nfrom .backports import make_memmap\n\n# Register supported compressors\nregister_compressor('zlib', ZlibCompressorWrapper())\nregister_compressor('gzip', GzipCompressorWrapper())\nregister_compressor('bz2', BZ2CompressorWrapper())\nregister_compressor('lzma', LZMACompressorWrapper())\nregister_compressor('xz', XZCompressorWrapper())\nregister_compressor('lz4', LZ4CompressorWrapper())\n\n\n###############################################################################\n# Utility objects for persistence.\n\n# For convenience, 16 bytes are used to be sure to cover all the possible\n# dtypes' alignments. For reference, see:\n# https://numpy.org/devdocs/dev/alignment.html\nNUMPY_ARRAY_ALIGNMENT_BYTES = 16\n\n\nclass NumpyArrayWrapper(object):\n \"\"\"An object to be persisted instead of numpy arrays.\n\n This object is used to hack into the pickle machinery and read numpy\n array data from our custom persistence format.\n More precisely, this object is used for:\n * carrying the information of the persisted array: subclass, shape, order,\n dtype. Those ndarray metadata are used to correctly reconstruct the array\n with low level numpy functions.\n * determining if memmap is allowed on the array.\n * reading the array bytes from a file.\n * reading the array using memorymap from a file.\n * writing the array bytes to a file.\n\n Attributes\n ----------\n subclass: numpy.ndarray subclass\n Determine the subclass of the wrapped array.\n shape: numpy.ndarray shape\n Determine the shape of the wrapped array.\n order: {'C', 'F'}\n Determine the order of wrapped array data. 'C' is for C order, 'F' is\n for fortran order.\n dtype: numpy.ndarray dtype\n Determine the data type of the wrapped array.\n allow_mmap: bool\n Determine if memory mapping is allowed on the wrapped array.\n Default: False.\n allow_pickle: bool\n Determine if pickle.load is allowed on the wrapped array.\n Default: False.\n \"\"\"\n\n def __init__(self, subclass, shape, order, dtype,\n allow_mmap=False, allow_pickle=False,\n numpy_array_alignment_bytes=NUMPY_ARRAY_ALIGNMENT_BYTES):\n \"\"\"Constructor. Store the useful information for later.\"\"\"\n self.subclass = subclass\n self.shape = shape\n self.order = order\n self.dtype = dtype\n self.allow_mmap = allow_mmap\n self.allow_pickle = allow_pickle\n # We make numpy_array_alignment_bytes an instance attribute to allow us\n # to change our mind about the default alignment and still load the old\n # pickles (with the previous alignment) correctly\n self.numpy_array_alignment_bytes = numpy_array_alignment_bytes\n\n def safe_get_numpy_array_alignment_bytes(self):\n # NumpyArrayWrapper instances loaded from joblib <= 1.1 pickles don't\n # have an numpy_array_alignment_bytes attribute\n return getattr(self, 'numpy_array_alignment_bytes', None)\n\n def write_array(self, array, pickler):\n \"\"\"Write array bytes to pickler file handle.\n\n This function is an adaptation of the numpy write_array function\n available in version 1.10.1 in numpy/lib/format.py.\n \"\"\"\n # Set buffer size to 16 MiB to hide the Python loop overhead.\n buffersize = max(16 * 1024 ** 2 // array.itemsize, 1)\n if array.dtype.hasobject:\n # We contain Python objects so we cannot write out the data\n # directly. Instead, we will pickle it out with version 2 of the\n # pickle protocol.\n pickle.dump(array, pickler.file_handle, protocol=2)\n else:\n numpy_array_alignment_bytes = \\\n self.safe_get_numpy_array_alignment_bytes()\n if numpy_array_alignment_bytes is not None:\n current_pos = pickler.file_handle.tell()\n pos_after_padding_byte = current_pos + 1\n padding_length = numpy_array_alignment_bytes - (\n pos_after_padding_byte % numpy_array_alignment_bytes)\n # A single byte is written that contains the padding length in\n # bytes\n padding_length_byte = int.to_bytes(\n padding_length, length=1, byteorder='little')\n pickler.file_handle.write(padding_length_byte)\n\n if padding_length != 0:\n padding = b'\\xff' * padding_length\n pickler.file_handle.write(padding)\n\n for chunk in pickler.np.nditer(array,\n flags=['external_loop',\n 'buffered',\n 'zerosize_ok'],\n buffersize=buffersize,\n order=self.order):\n pickler.file_handle.write(chunk.tobytes('C'))\n\n def read_array(self, unpickler, allow_pickle=False):\n \"\"\"Read array from unpickler file handle.\n\n This function is an adaptation of the numpy read_array function\n available in version 1.10.1 in numpy/lib/format.py.\n \"\"\"\n if len(self.shape) == 0:\n count = 1\n else:\n # joblib issue #859: we cast the elements of self.shape to int64 to\n # prevent a potential overflow when computing their product.\n shape_int64 = [unpickler.np.int64(x) for x in self.shape]\n count = unpickler.np.multiply.reduce(shape_int64)\n # Now read the actual data.\n if self.dtype.hasobject:\n if not allow_pickle:\n raise ValueError(\"Object arrays cannot be loaded when \"\n \"allow_pickle=False\")\n # The array contained Python objects. We need to unpickle the data.\n array = pickle.load(unpickler.file_handle)\n else:\n numpy_array_alignment_bytes = \\\n self.safe_get_numpy_array_alignment_bytes()\n if numpy_array_alignment_bytes is not None:\n padding_byte = unpickler.file_handle.read(1)\n padding_length = int.from_bytes(\n padding_byte, byteorder='little')\n if padding_length != 0:\n unpickler.file_handle.read(padding_length)\n\n # This is not a real file. We have to read it the\n # memory-intensive way.\n # crc32 module fails on reads greater than 2 ** 32 bytes,\n # breaking large reads from gzip streams. Chunk reads to\n # BUFFER_SIZE bytes to avoid issue and reduce memory overhead\n # of the read. In non-chunked case count < max_read_count, so\n # only one read is performed.\n max_read_count = BUFFER_SIZE // min(BUFFER_SIZE,\n self.dtype.itemsize)\n\n array = unpickler.np.empty(count, dtype=self.dtype)\n for i in range(0, count, max_read_count):\n read_count = min(max_read_count, count - i)\n read_size = int(read_count * self.dtype.itemsize)\n data = _read_bytes(unpickler.file_handle,\n read_size, \"array data\")\n array[i:i + read_count] = \\\n unpickler.np.frombuffer(data, dtype=self.dtype,\n count=read_count)\n del data\n\n if self.order == 'F':\n array.shape = self.shape[::-1]\n array = array.transpose()\n else:\n array.shape = self.shape\n\n # Detect byte order mismatch and swap as needed.\n return _ensure_native_byte_order(array)\n\n def read_mmap(self, unpickler):\n \"\"\"Read an array using numpy memmap.\"\"\"\n current_pos = unpickler.file_handle.tell()\n offset = current_pos\n numpy_array_alignment_bytes = \\\n self.safe_get_numpy_array_alignment_bytes()\n\n if numpy_array_alignment_bytes is not None:\n padding_byte = unpickler.file_handle.read(1)\n padding_length = int.from_bytes(padding_byte, byteorder='little')\n # + 1 is for the padding byte\n offset += padding_length + 1\n\n if unpickler.mmap_mode == 'w+':\n unpickler.mmap_mode = 'r+'\n\n marray = make_memmap(unpickler.filename,\n dtype=self.dtype,\n shape=self.shape,\n order=self.order,\n mode=unpickler.mmap_mode,\n offset=offset)\n # update the offset so that it corresponds to the end of the read array\n unpickler.file_handle.seek(offset + marray.nbytes)\n\n if (numpy_array_alignment_bytes is None and\n current_pos % NUMPY_ARRAY_ALIGNMENT_BYTES != 0):\n message = (\n f'The memmapped array {marray} loaded from the file '\n f'{unpickler.file_handle.name} is not byte aligned. '\n 'This may cause segmentation faults if this memmapped array '\n 'is used in some libraries like BLAS or PyTorch. '\n 'To get rid of this warning, regenerate your pickle file '\n 'with joblib >= 1.2.0. '\n 'See https://github.com/joblib/joblib/issues/563 '\n 'for more details'\n )\n warnings.warn(message)\n\n return _ensure_native_byte_order(marray)\n\n def read(self, unpickler, allow_pickle=False):\n \"\"\"Read the array corresponding to this wrapper.\n\n Use the unpickler to get all information to correctly read the array.\n\n Parameters\n ----------\n unpickler: NumpyUnpickler\n\n Returns\n -------\n array: numpy.ndarray\n\n \"\"\"\n # When requested, only use memmap mode if allowed.\n if unpickler.mmap_mode is not None and self.allow_mmap:\n array = self.read_mmap(unpickler)\n else:\n array = self.read_array(unpickler, allow_pickle)\n\n # Manage array subclass case\n if (hasattr(array, '__array_prepare__') and\n self.subclass not in (unpickler.np.ndarray,\n unpickler.np.memmap)):\n # We need to reconstruct another subclass\n new_array = unpickler.np.core.multiarray._reconstruct(\n self.subclass, (0,), 'b')\n return new_array.__array_prepare__(array)\n else:\n return array\n\n###############################################################################\n# Pickler classes\n\n\nclass NumpyPickler(Pickler):\n \"\"\"A pickler to persist big data efficiently.\n\n The main features of this object are:\n * persistence of numpy arrays in a single file.\n * optional compression with a special care on avoiding memory copies.\n\n Attributes\n ----------\n fp: file\n File object handle used for serializing the input object.\n protocol: int, optional\n Pickle protocol used. Default is pickle.DEFAULT_PROTOCOL.\n \"\"\"\n\n dispatch = Pickler.dispatch.copy()\n\n def __init__(self, fp, protocol=None):\n self.file_handle = fp\n self.buffered = isinstance(self.file_handle, BinaryZlibFile)\n\n # By default we want a pickle protocol that only changes with\n # the major python version and not the minor one\n if protocol is None:\n protocol = pickle.DEFAULT_PROTOCOL\n\n Pickler.__init__(self, self.file_handle, protocol=protocol)\n # delayed import of numpy, to avoid tight coupling\n try:\n import numpy as np\n except ImportError:\n np = None\n self.np = np\n\n def _create_array_wrapper(self, array):\n \"\"\"Create and returns a numpy array wrapper from a numpy array.\"\"\"\n order = 'F' if (array.flags.f_contiguous and\n not array.flags.c_contiguous) else 'C'\n allow_mmap = not self.buffered and not array.dtype.hasobject\n\n kwargs = {}\n try:\n self.file_handle.tell()\n except io.UnsupportedOperation:\n kwargs = {'numpy_array_alignment_bytes': None}\n\n wrapper = NumpyArrayWrapper(type(array),\n array.shape, order, array.dtype,\n allow_mmap=allow_mmap,\n **kwargs)\n\n return wrapper\n\n def save(self, obj):\n \"\"\"Subclass the Pickler `save` method.\n\n This is a total abuse of the Pickler class in order to use the numpy\n persistence function `save` instead of the default pickle\n implementation. The numpy array is replaced by a custom wrapper in the\n pickle persistence stack and the serialized array is written right\n after in the file. Warning: the file produced does not follow the\n pickle format. As such it can not be read with `pickle.load`.\n \"\"\"\n if self.np is not None and type(obj) in (self.np.ndarray,\n self.np.matrix,\n self.np.memmap):\n if type(obj) is self.np.memmap:\n # Pickling doesn't work with memmapped arrays\n obj = self.np.asanyarray(obj)\n\n # The array wrapper is pickled instead of the real array.\n wrapper = self._create_array_wrapper(obj)\n Pickler.save(self, wrapper)\n\n # A framer was introduced with pickle protocol 4 and we want to\n # ensure the wrapper object is written before the numpy array\n # buffer in the pickle file.\n # See https://www.python.org/dev/peps/pep-3154/#framing to get\n # more information on the framer behavior.\n if self.proto >= 4:\n self.framer.commit_frame(force=True)\n\n # And then array bytes are written right after the wrapper.\n wrapper.write_array(obj, self)\n return\n\n return Pickler.save(self, obj)\n\n\nclass NumpyUnpickler(Unpickler):\n \"\"\"A subclass of the Unpickler to unpickle our numpy pickles.\n\n Attributes\n ----------\n mmap_mode: str\n The memorymap mode to use for reading numpy arrays.\n file_handle: file_like\n File object to unpickle from.\n filename: str\n Name of the file to unpickle from. It should correspond to file_handle.\n This parameter is required when using mmap_mode.\n np: module\n Reference to numpy module if numpy is installed else None.\n allow_pickle: bool\n Determine if pickle.load is allowed on the wrapped array.\n Default: False.\n\n \"\"\"\n\n dispatch = Unpickler.dispatch.copy()\n\n def __init__(self, filename, file_handle, mmap_mode=None,\n allow_pickle=False):\n # The next line is for backward compatibility with pickle generated\n # with joblib versions less than 0.10.\n self._dirname = os.path.dirname(filename)\n\n self.mmap_mode = mmap_mode\n self.allow_pickle = allow_pickle\n self.file_handle = file_handle\n # filename is required for numpy mmap mode.\n self.filename = filename\n self.compat_mode = False\n Unpickler.__init__(self, self.file_handle)\n try:\n import numpy as np\n except ImportError:\n np = None\n self.np = np\n\n def load_build(self):\n \"\"\"Called to set the state of a newly created object.\n\n We capture it to replace our place-holder objects, NDArrayWrapper or\n NumpyArrayWrapper, by the array we are interested in. We\n replace them directly in the stack of pickler.\n NDArrayWrapper is used for backward compatibility with joblib <= 0.9.\n \"\"\"\n Unpickler.load_build(self)\n\n # For backward compatibility, we support NDArrayWrapper objects.\n if isinstance(self.stack[-1], (NDArrayWrapper, NumpyArrayWrapper)):\n if self.np is None:\n raise ImportError(\"Trying to unpickle an ndarray, \"\n \"but numpy didn't import correctly\")\n array_wrapper = self.stack.pop()\n # If any NDArrayWrapper is found, we switch to compatibility mode,\n # this will be used to raise a DeprecationWarning to the user at\n # the end of the unpickling.\n if isinstance(array_wrapper, NDArrayWrapper):\n self.compat_mode = True\n data = array_wrapper.read(self)\n else:\n data = array_wrapper.read(self, allow_pickle=self.allow_pickle)\n\n self.stack.append(data)\n\n # Be careful to register our new method.\n dispatch[pickle.BUILD[0]] = load_build\n\n\n###############################################################################\n# Utility functions\n\ndef dump(value, filename, compress=0, protocol=None, cache_size=None):\n \"\"\"Persist an arbitrary Python object into one file.\n\n Read more in the :ref:`User Guide `.\n\n Parameters\n ----------\n value: any Python object\n The object to store to disk.\n filename: str, pathlib.Path, or file object.\n The file object or path of the file in which it is to be stored.\n The compression method corresponding to one of the supported filename\n extensions ('.z', '.gz', '.bz2', '.xz' or '.lzma') will be used\n automatically.\n compress: int from 0 to 9 or bool or 2-tuple, optional\n Optional compression level for the data. 0 or False is no compression.\n Higher value means more compression, but also slower read and\n write times. Using a value of 3 is often a good compromise.\n See the notes for more details.\n If compress is True, the compression level used is 3.\n If compress is a 2-tuple, the first element must correspond to a string\n between supported compressors (e.g 'zlib', 'gzip', 'bz2', 'lzma'\n 'xz'), the second element must be an integer from 0 to 9, corresponding\n to the compression level.\n protocol: int, optional\n Pickle protocol, see pickle.dump documentation for more details.\n cache_size: positive int, optional\n This option is deprecated in 0.10 and has no effect.\n\n Returns\n -------\n filenames: list of strings\n The list of file names in which the data is stored. If\n compress is false, each array is stored in a different file.\n\n See Also\n --------\n joblib.load : corresponding loader\n\n Notes\n -----\n Memmapping on load cannot be used for compressed files. Thus\n using compression can significantly slow down loading. In\n addition, compressed files take up extra memory during\n dump and load.\n\n \"\"\"\n\n if Path is not None and isinstance(filename, Path):\n filename = str(filename)\n\n is_filename = isinstance(filename, str)\n is_fileobj = hasattr(filename, \"write\")\n\n compress_method = 'zlib' # zlib is the default compression method.\n if compress is True:\n # By default, if compress is enabled, we want the default compress\n # level of the compressor.\n compress_level = None\n elif isinstance(compress, tuple):\n # a 2-tuple was set in compress\n if len(compress) != 2:\n raise ValueError(\n 'Compress argument tuple should contain exactly 2 elements: '\n '(compress method, compress level), you passed {}'\n .format(compress))\n compress_method, compress_level = compress\n elif isinstance(compress, str):\n compress_method = compress\n compress_level = None # Use default compress level\n compress = (compress_method, compress_level)\n else:\n compress_level = compress\n\n if compress_method == 'lz4' and lz4 is None:\n raise ValueError(LZ4_NOT_INSTALLED_ERROR)\n\n if (compress_level is not None and\n compress_level is not False and\n compress_level not in range(10)):\n # Raising an error if a non valid compress level is given.\n raise ValueError(\n 'Non valid compress level given: \"{}\". Possible values are '\n '{}.'.format(compress_level, list(range(10))))\n\n if compress_method not in _COMPRESSORS:\n # Raising an error if an unsupported compression method is given.\n raise ValueError(\n 'Non valid compression method given: \"{}\". Possible values are '\n '{}.'.format(compress_method, _COMPRESSORS))\n\n if not is_filename and not is_fileobj:\n # People keep inverting arguments, and the resulting error is\n # incomprehensible\n raise ValueError(\n 'Second argument should be a filename or a file-like object, '\n '%s (type %s) was given.'\n % (filename, type(filename))\n )\n\n if is_filename and not isinstance(compress, tuple):\n # In case no explicit compression was requested using both compression\n # method and level in a tuple and the filename has an explicit\n # extension, we select the corresponding compressor.\n\n # unset the variable to be sure no compression level is set afterwards.\n compress_method = None\n for name, compressor in _COMPRESSORS.items():\n if filename.endswith(compressor.extension):\n compress_method = name\n\n if compress_method in _COMPRESSORS and compress_level == 0:\n # we choose the default compress_level in case it was not given\n # as an argument (using compress).\n compress_level = None\n\n if cache_size is not None:\n # Cache size is deprecated starting from version 0.10\n warnings.warn(\"Please do not set 'cache_size' in joblib.dump, \"\n \"this parameter has no effect and will be removed. \"\n \"You used 'cache_size={}'\".format(cache_size),\n DeprecationWarning, stacklevel=2)\n\n if compress_level != 0:\n with _write_fileobject(filename, compress=(compress_method,\n compress_level)) as f:\n NumpyPickler(f, protocol=protocol).dump(value)\n elif is_filename:\n with open(filename, 'wb') as f:\n NumpyPickler(f, protocol=protocol).dump(value)\n else:\n NumpyPickler(filename, protocol=protocol).dump(value)\n\n # If the target container is a file object, nothing is returned.\n if is_fileobj:\n return\n\n # For compatibility, the list of created filenames (e.g with one element\n # after 0.10.0) is returned by default.\n return [filename]\n\n\ndef _unpickle(fobj, filename=\"\", mmap_mode=None, allow_pickle=False):\n \"\"\"Internal unpickling function.\"\"\"\n # We are careful to open the file handle early and keep it open to\n # avoid race-conditions on renames.\n # That said, if data is stored in companion files, which can be\n # the case with the old persistence format, moving the directory\n # will create a race when joblib tries to access the companion\n # files.\n unpickler = NumpyUnpickler(filename, fobj, mmap_mode=mmap_mode,\n allow_pickle=allow_pickle)\n obj = None\n try:\n obj = unpickler.load()\n if unpickler.compat_mode:\n warnings.warn(\"The file '%s' has been generated with a \"\n \"joblib version less than 0.10. \"\n \"Please regenerate this pickle file.\"\n % filename,\n DeprecationWarning, stacklevel=3)\n except UnicodeDecodeError as exc:\n # More user-friendly error message\n new_exc = ValueError(\n 'You may be trying to read with '\n 'python 3 a joblib pickle generated with python 2. '\n 'This feature is not supported by joblib.')\n new_exc.__cause__ = exc\n raise new_exc\n return obj\n\n\ndef load_temporary_memmap(filename, mmap_mode, unlink_on_gc_collect):\n from ._memmapping_reducer import JOBLIB_MMAPS, add_maybe_unlink_finalizer\n obj = load(filename, mmap_mode)\n JOBLIB_MMAPS.add(obj.filename)\n if unlink_on_gc_collect:\n add_maybe_unlink_finalizer(obj)\n return obj\n\n\ndef load(filename, mmap_mode=None, allow_pickle=False):\n \"\"\"Reconstruct a Python object from a file persisted with joblib.dump.\n\n Read more in the :ref:`User Guide `.\n\n WARNING: joblib.load relies on the pickle module and can therefore\n execute arbitrary Python code. It should therefore never be used\n to load files from untrusted sources.\n\n Parameters\n ----------\n filename: str, pathlib.Path, or file object.\n The file object or path of the file from which to load the object\n mmap_mode: {None, 'r+', 'r', 'w+', 'c'}, optional\n If not None, the arrays are memory-mapped from the disk. This\n mode has no effect for compressed files. Note that in this\n case the reconstructed object might no longer match exactly\n the originally pickled object.\n allow_pickle: bool\n Determine if pickle.load is allowed on the wrapped array.\n Default: False.\n\n Returns\n -------\n result: any Python object\n The object stored in the file.\n\n See Also\n --------\n joblib.dump : function to save an object\n\n Notes\n -----\n\n This function can load numpy array files saved separately during the\n dump. If the mmap_mode argument is given, it is passed to np.load and\n arrays are loaded as memmaps. As a consequence, the reconstructed\n object might not match the original pickled object. Note that if the\n file was saved with compression, the arrays cannot be memmapped.\n \"\"\"\n if Path is not None and isinstance(filename, Path):\n filename = str(filename)\n\n if hasattr(filename, \"read\"):\n fobj = filename\n filename = getattr(fobj, 'name', '')\n with _read_fileobject(fobj, filename, mmap_mode) as fobj:\n obj = _unpickle(fobj, allow_pickle=allow_pickle)\n else:\n with open(filename, 'rb') as f:\n with _read_fileobject(f, filename, mmap_mode) as fobj:\n if isinstance(fobj, str):\n # if the returned file object is a string, this means we\n # try to load a pickle file generated with an version of\n # Joblib so we load it with joblib compatibility function.\n return load_compatibility(fobj)\n\n obj = _unpickle(fobj, filename, mmap_mode,\n allow_pickle)\n return obj\n", "joblib/test/test_numpy_pickle.py": "\"\"\"Test the numpy pickler as a replacement of the standard pickler.\"\"\"\n\nimport copy\nimport os\nimport random\nimport re\nimport io\nimport sys\nimport warnings\nimport gzip\nimport zlib\nimport bz2\nimport pickle\nimport socket\nfrom contextlib import closing\nimport mmap\nfrom pathlib import Path\n\ntry:\n import lzma\nexcept ImportError:\n lzma = None\n\nimport pytest\n\nfrom joblib.test.common import np, with_numpy, with_lz4, without_lz4\nfrom joblib.test.common import with_memory_profiler, memory_used\nfrom joblib.testing import parametrize, raises, warns\n\n# numpy_pickle is not a drop-in replacement of pickle, as it takes\n# filenames instead of open files as arguments.\nfrom joblib import numpy_pickle, register_compressor\nfrom joblib.test import data\n\nfrom joblib.numpy_pickle_utils import _IO_BUFFER_SIZE\nfrom joblib.numpy_pickle_utils import _detect_compressor\nfrom joblib.numpy_pickle_utils import _is_numpy_array_byte_order_mismatch\nfrom joblib.numpy_pickle_utils import _ensure_native_byte_order\nfrom joblib.compressor import (_COMPRESSORS, _LZ4_PREFIX, CompressorWrapper,\n LZ4_NOT_INSTALLED_ERROR, BinaryZlibFile)\n\n\n###############################################################################\n# Define a list of standard types.\n# Borrowed from dill, initial author: Micheal McKerns:\n# http://dev.danse.us/trac/pathos/browser/dill/dill_test2.py\n\ntypelist = []\n\n# testing types\n_none = None\ntypelist.append(_none)\n_type = type\ntypelist.append(_type)\n_bool = bool(1)\ntypelist.append(_bool)\n_int = int(1)\ntypelist.append(_int)\n_float = float(1)\ntypelist.append(_float)\n_complex = complex(1)\ntypelist.append(_complex)\n_string = str(1)\ntypelist.append(_string)\n_tuple = ()\ntypelist.append(_tuple)\n_list = []\ntypelist.append(_list)\n_dict = {}\ntypelist.append(_dict)\n_builtin = len\ntypelist.append(_builtin)\n\n\ndef _function(x):\n yield x\n\n\nclass _class:\n def _method(self):\n pass\n\n\nclass _newclass(object):\n def _method(self):\n pass\n\n\ntypelist.append(_function)\ntypelist.append(_class)\ntypelist.append(_newclass) # \n_instance = _class()\ntypelist.append(_instance)\n_object = _newclass()\ntypelist.append(_object) # \n\n\n###############################################################################\n# Tests\n\n@parametrize('compress', [0, 1])\n@parametrize('member', typelist)\ndef test_standard_types(tmpdir, compress, member):\n # Test pickling and saving with standard types.\n filename = tmpdir.join('test.pkl').strpath\n numpy_pickle.dump(member, filename, compress=compress)\n _member = numpy_pickle.load(filename)\n # We compare the pickled instance to the reloaded one only if it\n # can be compared to a copied one\n if member == copy.deepcopy(member):\n assert member == _member\n\n\ndef test_value_error():\n # Test inverting the input arguments to dump\n with raises(ValueError):\n numpy_pickle.dump('foo', dict())\n\n\n@parametrize('wrong_compress', [-1, 10, dict()])\ndef test_compress_level_error(wrong_compress):\n # Verify that passing an invalid compress argument raises an error.\n exception_msg = ('Non valid compress level given: '\n '\"{0}\"'.format(wrong_compress))\n with raises(ValueError) as excinfo:\n numpy_pickle.dump('dummy', 'foo', compress=wrong_compress)\n excinfo.match(exception_msg)\n\n\n@with_numpy\n@parametrize('compress', [False, True, 0, 3, 'zlib'])\ndef test_numpy_persistence(tmpdir, compress):\n filename = tmpdir.join('test.pkl').strpath\n rnd = np.random.RandomState(0)\n a = rnd.random_sample((10, 2))\n # We use 'a.T' to have a non C-contiguous array.\n for index, obj in enumerate(((a,), (a.T,), (a, a), [a, a, a])):\n filenames = numpy_pickle.dump(obj, filename, compress=compress)\n\n # All is cached in one file\n assert len(filenames) == 1\n # Check that only one file was created\n assert filenames[0] == filename\n # Check that this file does exist\n assert os.path.exists(filenames[0])\n\n # Unpickle the object\n obj_ = numpy_pickle.load(filename)\n # Check that the items are indeed arrays\n for item in obj_:\n assert isinstance(item, np.ndarray)\n # And finally, check that all the values are equal.\n np.testing.assert_array_equal(np.array(obj), np.array(obj_))\n\n # Now test with an array subclass\n obj = np.memmap(filename + 'mmap', mode='w+', shape=4, dtype=np.float64)\n filenames = numpy_pickle.dump(obj, filename, compress=compress)\n # All is cached in one file\n assert len(filenames) == 1\n\n obj_ = numpy_pickle.load(filename)\n if (type(obj) is not np.memmap and\n hasattr(obj, '__array_prepare__')):\n # We don't reconstruct memmaps\n assert isinstance(obj_, type(obj))\n\n np.testing.assert_array_equal(obj_, obj)\n\n # Test with an object containing multiple numpy arrays\n obj = ComplexTestObject()\n filenames = numpy_pickle.dump(obj, filename, compress=compress)\n # All is cached in one file\n assert len(filenames) == 1\n\n obj_loaded = numpy_pickle.load(filename, allow_pickle=True)\n assert isinstance(obj_loaded, type(obj))\n np.testing.assert_array_equal(obj_loaded.array_float, obj.array_float)\n np.testing.assert_array_equal(obj_loaded.array_int, obj.array_int)\n np.testing.assert_array_equal(obj_loaded.array_obj, obj.array_obj)\n\n\n@with_numpy\ndef test_numpy_persistence_bufferred_array_compression(tmpdir):\n big_array = np.ones((_IO_BUFFER_SIZE + 100), dtype=np.uint8)\n filename = tmpdir.join('test.pkl').strpath\n numpy_pickle.dump(big_array, filename, compress=True)\n arr_reloaded = numpy_pickle.load(filename)\n\n np.testing.assert_array_equal(big_array, arr_reloaded)\n\n\n@with_numpy\ndef test_memmap_persistence(tmpdir):\n rnd = np.random.RandomState(0)\n a = rnd.random_sample(10)\n filename = tmpdir.join('test1.pkl').strpath\n numpy_pickle.dump(a, filename)\n b = numpy_pickle.load(filename, mmap_mode='r')\n\n assert isinstance(b, np.memmap)\n\n # Test with an object containing multiple numpy arrays\n filename = tmpdir.join('test2.pkl').strpath\n obj = ComplexTestObject()\n numpy_pickle.dump(obj, filename)\n obj_loaded = numpy_pickle.load(filename, mmap_mode='r',\n allow_pickle=True)\n assert isinstance(obj_loaded, type(obj))\n assert isinstance(obj_loaded.array_float, np.memmap)\n assert not obj_loaded.array_float.flags.writeable\n assert isinstance(obj_loaded.array_int, np.memmap)\n assert not obj_loaded.array_int.flags.writeable\n # Memory map not allowed for numpy object arrays\n assert not isinstance(obj_loaded.array_obj, np.memmap)\n np.testing.assert_array_equal(obj_loaded.array_float,\n obj.array_float)\n np.testing.assert_array_equal(obj_loaded.array_int,\n obj.array_int)\n np.testing.assert_array_equal(obj_loaded.array_obj,\n obj.array_obj)\n\n # Test we can write in memmapped arrays\n obj_loaded = numpy_pickle.load(filename, mmap_mode='r+',\n allow_pickle=True)\n assert obj_loaded.array_float.flags.writeable\n obj_loaded.array_float[0:10] = 10.0\n assert obj_loaded.array_int.flags.writeable\n obj_loaded.array_int[0:10] = 10\n\n obj_reloaded = numpy_pickle.load(filename, mmap_mode='r',\n allow_pickle=True)\n np.testing.assert_array_equal(obj_reloaded.array_float,\n obj_loaded.array_float)\n np.testing.assert_array_equal(obj_reloaded.array_int,\n obj_loaded.array_int)\n\n # Test w+ mode is caught and the mode has switched to r+\n numpy_pickle.load(filename, mmap_mode='w+', allow_pickle=True)\n assert obj_loaded.array_int.flags.writeable\n assert obj_loaded.array_int.mode == 'r+'\n assert obj_loaded.array_float.flags.writeable\n assert obj_loaded.array_float.mode == 'r+'\n\n\n@with_numpy\ndef test_memmap_persistence_mixed_dtypes(tmpdir):\n # loading datastructures that have sub-arrays with dtype=object\n # should not prevent memmapping on fixed size dtype sub-arrays.\n rnd = np.random.RandomState(0)\n a = rnd.random_sample(10)\n b = np.array([1, 'b'], dtype=object)\n construct = (a, b)\n filename = tmpdir.join('test.pkl').strpath\n numpy_pickle.dump(construct, filename)\n a_clone, b_clone = numpy_pickle.load(filename, mmap_mode='r',\n allow_pickle=True)\n\n # the floating point array has been memory mapped\n assert isinstance(a_clone, np.memmap)\n\n # the object-dtype array has been loaded in memory\n assert not isinstance(b_clone, np.memmap)\n\n\n@with_numpy\ndef test_masked_array_persistence(tmpdir):\n # The special-case picker fails, because saving masked_array\n # not implemented, but it just delegates to the standard pickler.\n rnd = np.random.RandomState(0)\n a = rnd.random_sample(10)\n a = np.ma.masked_greater(a, 0.5)\n filename = tmpdir.join('test.pkl').strpath\n numpy_pickle.dump(a, filename)\n b = numpy_pickle.load(filename, mmap_mode='r')\n assert isinstance(b, np.ma.masked_array)\n\n\n@with_numpy\ndef test_compress_mmap_mode_warning(tmpdir):\n # Test the warning in case of compress + mmap_mode\n rnd = np.random.RandomState(0)\n a = rnd.random_sample(10)\n this_filename = tmpdir.join('test.pkl').strpath\n numpy_pickle.dump(a, this_filename, compress=1)\n with warns(UserWarning) as warninfo:\n numpy_pickle.load(this_filename, mmap_mode='r+')\n debug_msg = \"\\n\".join([str(w) for w in warninfo])\n warninfo = [w.message for w in warninfo]\n assert len(warninfo) == 1, debug_msg\n assert (\n str(warninfo[0]) ==\n 'mmap_mode \"r+\" is not compatible with compressed '\n f'file {this_filename}. \"r+\" flag will be ignored.'\n )\n\n\n@with_numpy\n@parametrize('cache_size', [None, 0, 10])\ndef test_cache_size_warning(tmpdir, cache_size):\n # Check deprecation warning raised when cache size is not None\n filename = tmpdir.join('test.pkl').strpath\n rnd = np.random.RandomState(0)\n a = rnd.random_sample((10, 2))\n\n warnings.simplefilter(\"always\")\n with warnings.catch_warnings(record=True) as warninfo:\n numpy_pickle.dump(a, filename, cache_size=cache_size)\n expected_nb_warnings = 1 if cache_size is not None else 0\n assert len(warninfo) == expected_nb_warnings\n for w in warninfo:\n assert w.category == DeprecationWarning\n assert (str(w.message) ==\n \"Please do not set 'cache_size' in joblib.dump, this \"\n \"parameter has no effect and will be removed. You \"\n \"used 'cache_size={0}'\".format(cache_size))\n\n\n@with_numpy\n@with_memory_profiler\n@parametrize('compress', [True, False])\ndef test_memory_usage(tmpdir, compress):\n # Verify memory stays within expected bounds.\n filename = tmpdir.join('test.pkl').strpath\n small_array = np.ones((10, 10))\n big_array = np.ones(shape=100 * int(1e6), dtype=np.uint8)\n\n for obj in (small_array, big_array):\n size = obj.nbytes / 1e6\n obj_filename = filename + str(np.random.randint(0, 1000))\n mem_used = memory_used(numpy_pickle.dump,\n obj, obj_filename, compress=compress)\n\n # The memory used to dump the object shouldn't exceed the buffer\n # size used to write array chunks (16MB).\n write_buf_size = _IO_BUFFER_SIZE + 16 * 1024 ** 2 / 1e6\n assert mem_used <= write_buf_size\n\n mem_used = memory_used(numpy_pickle.load, obj_filename)\n # memory used should be less than array size + buffer size used to\n # read the array chunk by chunk.\n read_buf_size = 32 + _IO_BUFFER_SIZE # MiB\n assert mem_used < size + read_buf_size\n\n\n@with_numpy\ndef test_compressed_pickle_dump_and_load(tmpdir):\n expected_list = [np.arange(5, dtype=np.dtype('i8')),\n np.arange(5, dtype=np.dtype('f8')),\n np.array([1, 'abc', {'a': 1, 'b': 2}], dtype='O'),\n np.arange(256, dtype=np.uint8).tobytes(),\n u\"C'est l'\\xe9t\\xe9 !\"]\n\n fname = tmpdir.join('temp.pkl.gz').strpath\n\n dumped_filenames = numpy_pickle.dump(expected_list, fname, compress=1)\n assert len(dumped_filenames) == 1\n result_list = numpy_pickle.load(fname, allow_pickle=True)\n for result, expected in zip(result_list, expected_list):\n if isinstance(expected, np.ndarray):\n expected = _ensure_native_byte_order(expected)\n assert result.dtype == expected.dtype\n np.testing.assert_equal(result, expected)\n else:\n assert result == expected\n\n\ndef _check_pickle(filename, expected_list, mmap_mode=None):\n \"\"\"Helper function to test joblib pickle content.\n\n Note: currently only pickles containing an iterable are supported\n by this function.\n \"\"\"\n version_match = re.match(r'.+py(\\d)(\\d).+', filename)\n py_version_used_for_writing = int(version_match.group(1))\n\n py_version_to_default_pickle_protocol = {2: 2, 3: 3}\n pickle_reading_protocol = py_version_to_default_pickle_protocol.get(3, 4)\n pickle_writing_protocol = py_version_to_default_pickle_protocol.get(\n py_version_used_for_writing, 4)\n if pickle_reading_protocol >= pickle_writing_protocol:\n try:\n with warnings.catch_warnings(record=True) as warninfo:\n warnings.simplefilter('always')\n warnings.filterwarnings(\n 'ignore', module='numpy',\n message='The compiler package is deprecated')\n result_list = numpy_pickle.load(filename,\n mmap_mode=mmap_mode,\n allow_pickle=True)\n filename_base = os.path.basename(filename)\n expected_nb_deprecation_warnings = 1 if (\n \"_0.9\" in filename_base or \"_0.8.4\" in filename_base) else 0\n\n expected_nb_user_warnings = 3 if (\n re.search(\"_0.1.+.pkl$\", filename_base) and\n mmap_mode is not None) else 0\n expected_nb_warnings = \\\n expected_nb_deprecation_warnings + expected_nb_user_warnings\n assert len(warninfo) == expected_nb_warnings\n\n deprecation_warnings = [\n w for w in warninfo if issubclass(\n w.category, DeprecationWarning)]\n user_warnings = [\n w for w in warninfo if issubclass(\n w.category, UserWarning)]\n for w in deprecation_warnings:\n assert (str(w.message) ==\n \"The file '{0}' has been generated with a joblib \"\n \"version less than 0.10. Please regenerate this \"\n \"pickle file.\".format(filename))\n\n for w in user_warnings:\n escaped_filename = re.escape(filename)\n assert re.search(\n f\"memmapped.+{escaped_filename}.+segmentation fault\",\n str(w.message))\n\n for result, expected in zip(result_list, expected_list):\n if isinstance(expected, np.ndarray):\n expected = _ensure_native_byte_order(expected)\n assert result.dtype == expected.dtype\n np.testing.assert_equal(result, expected)\n else:\n assert result == expected\n except Exception as exc:\n # When trying to read with python 3 a pickle generated\n # with python 2 we expect a user-friendly error\n if py_version_used_for_writing == 2:\n assert isinstance(exc, ValueError)\n message = ('You may be trying to read with '\n 'python 3 a joblib pickle generated with python 2.')\n assert message in str(exc)\n elif filename.endswith('.lz4') and with_lz4.args[0]:\n assert isinstance(exc, ValueError)\n assert LZ4_NOT_INSTALLED_ERROR in str(exc)\n else:\n raise\n else:\n # Pickle protocol used for writing is too high. We expect a\n # \"unsupported pickle protocol\" error message\n try:\n numpy_pickle.load(filename)\n raise AssertionError('Numpy pickle loading should '\n 'have raised a ValueError exception')\n except ValueError as e:\n message = 'unsupported pickle protocol: {0}'.format(\n pickle_writing_protocol)\n assert message in str(e.args)\n\n\n@with_numpy\ndef test_joblib_pickle_across_python_versions():\n # We need to be specific about dtypes in particular endianness\n # because the pickles can be generated on one architecture and\n # the tests run on another one. See\n # https://github.com/joblib/joblib/issues/279.\n expected_list = [np.arange(5, dtype=np.dtype('i8'), ('', '>f8')]),\n np.arange(3, dtype=np.dtype('>i8')),\n np.arange(3, dtype=np.dtype('>f8'))]\n\n # Verify the byteorder mismatch is correctly detected.\n for array in be_arrays:\n if sys.byteorder == 'big':\n assert not _is_numpy_array_byte_order_mismatch(array)\n else:\n assert _is_numpy_array_byte_order_mismatch(array)\n converted = _ensure_native_byte_order(array)\n if converted.dtype.fields:\n for f in converted.dtype.fields.values():\n f[0].byteorder == '='\n else:\n assert converted.dtype.byteorder == \"=\"\n\n # List of numpy arrays with little endian byteorder.\n le_arrays = [np.array([(1, 2.0), (3, 4.0)],\n dtype=[('', ' size\n np.testing.assert_array_equal(obj, memmaps)\n\n\ndef test_register_compressor(tmpdir):\n # Check that registering compressor file works.\n compressor_name = 'test-name'\n compressor_prefix = 'test-prefix'\n\n class BinaryCompressorTestFile(io.BufferedIOBase):\n pass\n\n class BinaryCompressorTestWrapper(CompressorWrapper):\n\n def __init__(self):\n CompressorWrapper.__init__(self, obj=BinaryCompressorTestFile,\n prefix=compressor_prefix)\n\n register_compressor(compressor_name, BinaryCompressorTestWrapper())\n\n assert (_COMPRESSORS[compressor_name].fileobj_factory ==\n BinaryCompressorTestFile)\n assert _COMPRESSORS[compressor_name].prefix == compressor_prefix\n\n # Remove this dummy compressor file from extra compressors because other\n # tests might fail because of this\n _COMPRESSORS.pop(compressor_name)\n\n\n@parametrize('invalid_name', [1, (), {}])\ndef test_register_compressor_invalid_name(invalid_name):\n # Test that registering an invalid compressor name is not allowed.\n with raises(ValueError) as excinfo:\n register_compressor(invalid_name, None)\n excinfo.match(\"Compressor name should be a string\")\n\n\ndef test_register_compressor_invalid_fileobj():\n # Test that registering an invalid file object is not allowed.\n\n class InvalidFileObject():\n pass\n\n class InvalidFileObjectWrapper(CompressorWrapper):\n def __init__(self):\n CompressorWrapper.__init__(self, obj=InvalidFileObject,\n prefix=b'prefix')\n\n with raises(ValueError) as excinfo:\n register_compressor('invalid', InvalidFileObjectWrapper())\n\n excinfo.match(\"Compressor 'fileobj_factory' attribute should implement \"\n \"the file object interface\")\n\n\nclass AnotherZlibCompressorWrapper(CompressorWrapper):\n\n def __init__(self):\n CompressorWrapper.__init__(self, obj=BinaryZlibFile, prefix=b'prefix')\n\n\nclass StandardLibGzipCompressorWrapper(CompressorWrapper):\n\n def __init__(self):\n CompressorWrapper.__init__(self, obj=gzip.GzipFile, prefix=b'prefix')\n\n\ndef test_register_compressor_already_registered():\n # Test registration of existing compressor files.\n compressor_name = 'test-name'\n\n # register a test compressor\n register_compressor(compressor_name, AnotherZlibCompressorWrapper())\n\n with raises(ValueError) as excinfo:\n register_compressor(compressor_name,\n StandardLibGzipCompressorWrapper())\n excinfo.match(\"Compressor '{}' already registered.\"\n .format(compressor_name))\n\n register_compressor(compressor_name, StandardLibGzipCompressorWrapper(),\n force=True)\n\n assert compressor_name in _COMPRESSORS\n assert _COMPRESSORS[compressor_name].fileobj_factory == gzip.GzipFile\n\n # Remove this dummy compressor file from extra compressors because other\n # tests might fail because of this\n _COMPRESSORS.pop(compressor_name)\n\n\n@with_lz4\ndef test_lz4_compression(tmpdir):\n # Check that lz4 can be used when dependency is available.\n import lz4.frame\n compressor = 'lz4'\n assert compressor in _COMPRESSORS\n assert _COMPRESSORS[compressor].fileobj_factory == lz4.frame.LZ4FrameFile\n\n fname = tmpdir.join('test.pkl').strpath\n data = 'test data'\n numpy_pickle.dump(data, fname, compress=compressor)\n\n with open(fname, 'rb') as f:\n assert f.read(len(_LZ4_PREFIX)) == _LZ4_PREFIX\n assert numpy_pickle.load(fname) == data\n\n # Test that LZ4 is applied based on file extension\n numpy_pickle.dump(data, fname + '.lz4')\n with open(fname, 'rb') as f:\n assert f.read(len(_LZ4_PREFIX)) == _LZ4_PREFIX\n assert numpy_pickle.load(fname) == data\n\n\n@without_lz4\ndef test_lz4_compression_without_lz4(tmpdir):\n # Check that lz4 cannot be used when dependency is not available.\n fname = tmpdir.join('test.nolz4').strpath\n data = 'test data'\n msg = LZ4_NOT_INSTALLED_ERROR\n with raises(ValueError) as excinfo:\n numpy_pickle.dump(data, fname, compress='lz4')\n excinfo.match(msg)\n\n with raises(ValueError) as excinfo:\n numpy_pickle.dump(data, fname + '.lz4')\n excinfo.match(msg)\n\n\nprotocols = [pickle.DEFAULT_PROTOCOL]\nif pickle.HIGHEST_PROTOCOL != pickle.DEFAULT_PROTOCOL:\n protocols.append(pickle.HIGHEST_PROTOCOL)\n\n\n@with_numpy\n@parametrize('protocol', protocols)\ndef test_memmap_alignment_padding(tmpdir, protocol):\n # Test that memmaped arrays returned by numpy.load are correctly aligned\n fname = tmpdir.join('test.mmap').strpath\n\n a = np.random.randn(2)\n numpy_pickle.dump(a, fname, protocol=protocol)\n memmap = numpy_pickle.load(fname, mmap_mode='r')\n assert isinstance(memmap, np.memmap)\n np.testing.assert_array_equal(a, memmap)\n assert (\n memmap.ctypes.data % numpy_pickle.NUMPY_ARRAY_ALIGNMENT_BYTES == 0)\n assert memmap.flags.aligned\n\n array_list = [\n np.random.randn(2), np.random.randn(2),\n np.random.randn(2), np.random.randn(2)\n ]\n\n # On Windows OSError 22 if reusing the same path for memmap ...\n fname = tmpdir.join('test1.mmap').strpath\n numpy_pickle.dump(array_list, fname, protocol=protocol)\n l_reloaded = numpy_pickle.load(fname, mmap_mode='r')\n\n for idx, memmap in enumerate(l_reloaded):\n assert isinstance(memmap, np.memmap)\n np.testing.assert_array_equal(array_list[idx], memmap)\n assert (\n memmap.ctypes.data % numpy_pickle.NUMPY_ARRAY_ALIGNMENT_BYTES == 0)\n assert memmap.flags.aligned\n\n array_dict = {\n 'a0': np.arange(2, dtype=np.uint8),\n 'a1': np.arange(3, dtype=np.uint8),\n 'a2': np.arange(5, dtype=np.uint8),\n 'a3': np.arange(7, dtype=np.uint8),\n 'a4': np.arange(11, dtype=np.uint8),\n 'a5': np.arange(13, dtype=np.uint8),\n 'a6': np.arange(17, dtype=np.uint8),\n 'a7': np.arange(19, dtype=np.uint8),\n 'a8': np.arange(23, dtype=np.uint8),\n }\n\n # On Windows OSError 22 if reusing the same path for memmap ...\n fname = tmpdir.join('test2.mmap').strpath\n numpy_pickle.dump(array_dict, fname, protocol=protocol)\n d_reloaded = numpy_pickle.load(fname, mmap_mode='r')\n\n for key, memmap in d_reloaded.items():\n assert isinstance(memmap, np.memmap)\n np.testing.assert_array_equal(array_dict[key], memmap)\n assert (\n memmap.ctypes.data % numpy_pickle.NUMPY_ARRAY_ALIGNMENT_BYTES == 0)\n assert memmap.flags.aligned\n"}} -{"repo": "jmcnevin/rubypants", "pr_number": 19, "title": "[Style] Align if modifiers based on surrounding code", "state": "closed", "merged_at": "2018-04-04T16:25:14Z", "additions": 19, "deletions": 19, "files_changed": ["lib/rubypants.rb"], "files_before": {"lib/rubypants.rb": "require_relative 'version'\n\nclass RubyPants < String\n extend RubyPantsVersion\n\n # Create a new RubyPants instance with the text in +string+.\n #\n # Allowed elements in the options array:\n #\n # 0 :: do nothing\n # 1 :: enable all, using only em-dash shortcuts\n # 2 :: enable all, using old school en- and em-dash shortcuts (*default*)\n # 3 :: enable all, using inverted old school en and em-dash shortcuts\n # -1 :: stupefy (translate HTML entities to their ASCII-counterparts)\n #\n # If you don't like any of these defaults, you can pass symbols to change\n # RubyPants' behavior:\n #\n # :quotes :: quotes\n # :backticks :: backtick quotes (``double'' only)\n # :allbackticks :: backtick quotes (``double'' and `single')\n # :dashes :: dashes\n # :oldschool :: old school dashes\n # :inverted :: inverted old school dashes\n # :ellipses :: ellipses\n # :prevent_breaks :: use nbsp and word-joiner to avoid breaking\n # before dashes and ellipses\n # :named_entities :: used named entities instead of the default\n # decimal entities (see below)\n # :convertquotes :: convert " entities to\n # \"\n # :stupefy :: translate RubyPants HTML entities\n # to their ASCII counterparts.\n #\n # In addition, you can customize the HTML entities that will be injected by\n # passing in a hash for the final argument. The defaults for these entities\n # are as follows:\n #\n # :single_left_quote :: \n # :double_left_quote :: \n # :single_right_quote :: \n # :double_right_quote :: \n # :em_dash :: \n # :en_dash :: \n # :ellipsis :: \n # :non_breaking_space ::  \n # :word_joiner :: \n #\n # If the :named_entities option is used, the default entities are\n # as follows:\n #\n # :single_left_quote :: \n # :double_left_quote :: \n # :single_right_quote :: \n # :double_right_quote :: \n # :em_dash :: \n # :en_dash :: \n # :ellipsis :: \n # :non_breaking_space ::  \n # :word_joiner :: \n #\n # If the :character_entities option is used, RubyPants will\n # emit Unicode characters directly, rather than HTML entities. By default\n # this excludes the space characters (non-breaking space and\n # word-joiner). To additionally emit Unicode space characters, use the\n # :character_spaces option.\n #\n def initialize(string, options=[2], entities = {})\n super string\n\n @options = [*options]\n @entities = default_entities\n @entities.merge!(named_entities) if @options.include?(:named_entities)\n @entities.merge!(character_entities) if @options.include?(:character_entities)\n @entities.merge!(character_spaces) if @options.include?(:character_spaces)\n @entities.merge!(entities)\n end\n\n # Apply SmartyPants transformations.\n def to_html\n do_quotes = do_backticks = do_dashes = do_ellipses = do_stupify = nil\n convert_quotes = prevent_breaks = nil\n\n if @options.include?(0)\n # Do nothing.\n return self\n elsif @options.include?(1)\n # Do everything, turn all options on.\n do_quotes = do_backticks = do_ellipses = true\n do_dashes = :normal\n elsif @options.include?(2)\n # Do everything, turn all options on, use old school dash shorthand.\n do_quotes = do_backticks = do_ellipses = true\n do_dashes = :oldschool\n elsif @options.include?(3)\n # Do everything, turn all options on, use inverted old school\n # dash shorthand.\n do_quotes = do_backticks = do_ellipses = true\n do_dashes = :inverted\n elsif @options.include?(-1)\n do_stupefy = true\n end\n\n # Explicit flags override numeric flag groups.\n do_quotes = true if @options.include?(:quotes)\n do_backticks = true if @options.include?(:backticks)\n do_backticks = :both if @options.include?(:allbackticks)\n do_dashes = :normal if @options.include?(:dashes)\n do_dashes = :oldschool if @options.include?(:oldschool)\n do_dashes = :inverted if @options.include?(:inverted)\n prevent_breaks = true if @options.include?(:prevent_breaks)\n do_ellipses = true if @options.include?(:ellipses)\n convert_quotes = true if @options.include?(:convertquotes)\n do_stupefy = true if @options.include?(:stupefy)\n\n # Parse the HTML\n tokens = tokenize\n\n # Keep track of when we're inside
             or  tags.\n    in_pre = nil\n\n    # Here is the result stored in.\n    result = \"\"\n\n    # This is a cheat, used to get some context for one-character\n    # tokens that consist of just a quote char. What we do is remember\n    # the last character of the previous text token, to use as context\n    # to curl single- character quote tokens correctly.\n    prev_token_last_char = nil\n\n    tokens.each do |token|\n      if token.first == :tag\n        result << token[1]\n        if token[1].end_with? '/>'\n          # ignore self-closing tags\n        elsif token[1] =~ %r!\\A<(/?)(pre|code|kbd|script|style|math)[\\s>]!\n          if $1 == '' && ! in_pre\n            in_pre = $2\n          elsif $1 == '/' && $2 == in_pre\n            in_pre = nil\n          end\n        end\n      else\n        t = token[1]\n\n        # Remember last char of this token before processing.\n        last_char = t[-1].chr\n\n        unless in_pre\n          t = process_escapes t\n\n          t.gsub!(/"/, '\"')  if convert_quotes\n\n          if do_dashes\n            t = educate_dashes t, prevent_breaks            if do_dashes == :normal\n            t = educate_dashes_oldschool t, prevent_breaks  if do_dashes == :oldschool\n            t = educate_dashes_inverted t, prevent_breaks   if do_dashes == :inverted\n          end\n\n          t = educate_ellipses t, prevent_breaks  if do_ellipses\n\n          # Note: backticks need to be processed before quotes.\n          if do_backticks\n            t = educate_backticks t\n            t = educate_single_backticks t  if do_backticks == :both\n          end\n\n          if do_quotes\n            if t == \"'\"\n              # Special case: single-character ' token\n              if prev_token_last_char =~ /\\S/\n                t = entity(:single_right_quote)\n              else\n                t = entity(:single_left_quote)\n              end\n            elsif t == '\"'\n              # Special case: single-character \" token\n              if prev_token_last_char =~ /\\S/\n                t = entity(:double_right_quote)\n              else\n                t = entity(:double_left_quote)\n              end\n            else\n              # Normal case:\n              t = educate_quotes t\n            end\n          end\n\n          t = stupefy_entities t  if do_stupefy\n        end\n\n        prev_token_last_char = last_char\n        result << t\n      end\n    end\n\n    # Done\n    result\n  end\n\n  protected\n\n  # Return the string, with after processing the following backslash\n  # escape sequences. This is useful if you want to force a \"dumb\" quote\n  # or other character to appear.\n  #\n  # Escaped are:\n  #      \\\\    \\\"    \\'    \\.    \\-    \\`\n  #\n  def process_escapes(str)\n    str.\n      gsub('\\\\\\\\', '\').\n      gsub('\\\"',   '"').\n      gsub(\"\\\\\\'\", ''').\n      gsub('\\.',   '.').\n      gsub('\\-',   '-').\n      gsub('\\`',   '`')\n  end\n\n  def self.n_of(n, x)\n    x = Regexp.escape(x)\n    /(?[[:space:]]*)#{patt}/\n    str.gsub(patt) do\n      spaces = if prevent_breaks && $~['spaces'].length > 0\n                 entity(:non_breaking_space) # * $~['spaces'].length\n               elsif prevent_breaks\n                 entity(:word_joiner)\n               else\n                 $~['spaces']\n               end\n      spaces + repl\n    end\n  end\n\n  # Return the string, with each instance of \"--\" translated to an\n  # em-dash HTML entity.\n  #\n  def educate_dashes(str, prevent_breaks=false)\n    educate(str, DOUBLE_DASH, entity(:em_dash), prevent_breaks)\n  end\n\n  # Return the string, with each instance of \"--\" translated to an\n  # en-dash HTML entity, and each \"---\" translated to an\n  # em-dash HTML entity.\n  #\n  def educate_dashes_oldschool(str, prevent_breaks=false)\n    str = educate(str, TRIPLE_DASH, entity(:em_dash), prevent_breaks)\n    educate(str, DOUBLE_DASH, entity(:en_dash), prevent_breaks)\n  end\n\n  # Return the string, with each instance of \"--\" translated\n  # to an em-dash HTML entity, and each \"---\" translated to\n  # an en-dash HTML entity. Two reasons why: First, unlike the en- and\n  # em-dash syntax supported by +educate_dashes_oldschool+, it's\n  # compatible with existing entries written before SmartyPants 1.1,\n  # back when \"--\" was only used for em-dashes.  Second,\n  # em-dashes are more common than en-dashes, and so it sort of makes\n  # sense that the shortcut should be shorter to type. (Thanks to\n  # Aaron Swartz for the idea.)\n  #\n  def educate_dashes_inverted(str, prevent_breaks=false)\n    str = educate(str, TRIPLE_DASH, entity(:en_dash), prevent_breaks)\n    educate(str, DOUBLE_DASH, entity(:em_dash), prevent_breaks)\n  end\n\n  # Return the string, with each instance of \"...\" translated\n  # to an ellipsis HTML entity. Also converts the case where there are\n  # spaces between the dots.\n  #\n  def educate_ellipses(str, prevent_breaks=false)\n    str = educate(str, RubyPants.n_of(3, '.'), entity(:ellipsis), prevent_breaks)\n    educate(str, /(?``backticks''\"-style single quotes\n  # translated into HTML curly quote entities.\n  #\n  def educate_backticks(str)\n    str.\n      gsub(\"``\", entity(:double_left_quote)).\n      gsub(\"''\", entity(:double_right_quote))\n  end\n\n  # Return the string, with \"`backticks'\"-style single quotes\n  # translated into HTML curly quote entities.\n  #\n  def educate_single_backticks(str)\n    str.\n      gsub(\"`\", entity(:single_left_quote)).\n      gsub(\"'\", entity(:single_right_quote))\n  end\n\n  # Return the string, with \"educated\" curly quote HTML entities.\n  #\n  def educate_quotes(str)\n    punct_class = '[!\"#\\$\\%\\'()*+,\\-.\\/:;<=>?\\@\\[\\\\\\\\\\]\\^_`{|}~]'\n\n    str = str.dup\n\n    # Special case if the very first character is a quote followed by\n    # punctuation at a non-word-break. Close the quotes by brute\n    # force:\n    str.gsub!(/^'(?=#{punct_class}\\B)/,\n              entity(:single_right_quote))\n    str.gsub!(/^\"(?=#{punct_class}\\B)/,\n              entity(:double_right_quote))\n\n    # Special case for double sets of quotes, e.g.:\n    #   

            He said, \"'Quoted' words in a larger quote.\"

            \n str.gsub!(/\"'(?=\\w)/,\n \"#{entity(:double_left_quote)}#{entity(:single_left_quote)}\")\n str.gsub!(/'\"(?=\\w)/,\n \"#{entity(:single_left_quote)}#{entity(:double_left_quote)}\")\n\n # Special case for decade abbreviations (the '80s):\n str.gsub!(/'(?=\\d\\ds)/,\n entity(:single_right_quote))\n\n close_class = %![^\\ \\t\\r\\n\\\\[\\{\\(\\-]!\n dec_dashes = \"#{entity(:en_dash)}|#{entity(:em_dash)}\"\n\n # Get most opening single quotes:\n str.gsub!(/([[:space:]]| |--|&[mn]dash;|#{dec_dashes}|ȁ[34];)'(?=\\w)/,\n '\\1' + entity(:single_left_quote))\n\n # Single closing quotes:\n str.gsub!(/(#{close_class})'/,\n '\\1' + entity(:single_right_quote))\n str.gsub!(/'(\\s|s\\b|$)/,\n entity(:single_right_quote) + '\\1')\n\n # Any remaining single quotes should be opening ones:\n str.gsub!(/'/,\n entity(:single_left_quote))\n\n # Get most opening double quotes:\n str.gsub!(/([[:space:]]| |--|&[mn]dash;|#{dec_dashes}|ȁ[34];)\"(?=\\w)/,\n '\\1' + entity(:double_left_quote))\n\n # Double closing quotes:\n str.gsub!(/(#{close_class})\"/,\n '\\1' + entity(:double_right_quote))\n str.gsub!(/\"(\\s|s\\b|$)/,\n entity(:double_right_quote) + '\\1')\n\n # Any remaining quotes should be opening ones:\n str.gsub!(/\"/,\n entity(:double_left_quote))\n\n str\n end\n\n # Return the string, with each RubyPants HTML entity translated to\n # its ASCII counterpart.\n #\n # Note: This is not reversible (but exactly the same as in SmartyPants)\n #\n def stupefy_entities(str)\n new_str = str.dup\n\n {\n :en_dash => '-',\n :em_dash => '--',\n :single_left_quote => \"'\",\n :single_right_quote => \"'\",\n :double_left_quote => '\"',\n :double_right_quote => '\"',\n :ellipsis => '...'\n }.each do |k,v|\n new_str.gsub!(/#{entity(k)}/, v)\n end\n\n new_str\n end\n\n # Return an array of the tokens comprising the string. Each token is\n # either a tag (possibly with nested, tags contained therein, such\n # as \">, or a run of text between\n # tags. Each element of the array is a two-element array; the first\n # is either :tag or :text; the second is the actual value.\n #\n # Based on the _tokenize() subroutine from Brad Choate's\n # MTRegex plugin. \n #\n # This is actually the easier variant using tag_soup, as used by\n # Chad Miller in the Python port of SmartyPants.\n #\n def tokenize\n tag_soup = /([^<]*)(|<[^>]*>)/m\n\n tokens = []\n\n prev_end = 0\n\n scan(tag_soup) do\n tokens << [:text, $1] if $1 != \"\"\n tokens << [:tag, $2]\n prev_end = $~.end(0)\n end\n\n if prev_end < size\n tokens << [:text, self[prev_end..-1]]\n end\n\n tokens\n end\n\n def default_entities\n {\n :single_left_quote => \"‘\",\n :double_left_quote => \"“\",\n :single_right_quote => \"’\",\n :double_right_quote => \"”\",\n :em_dash => \"—\",\n :en_dash => \"–\",\n :ellipsis => \"…\",\n :non_breaking_space => \" \",\n :word_joiner => \"⁠\",\n }\n end\n\n def named_entities\n {\n :single_left_quote => '‘',\n :double_left_quote => \"“\",\n :single_right_quote => \"’\",\n :double_right_quote => \"”\",\n :em_dash => \"—\",\n :en_dash => \"–\",\n :ellipsis => \"…\",\n :non_breaking_space => \" \",\n # :word_joiner => N/A,\n }\n end\n\n def character_entities\n {\n :single_left_quote => \"\\u2018\",\n :double_left_quote => \"\\u201C\",\n :single_right_quote => \"\\u2019\",\n :double_right_quote => \"\\u201D\",\n :em_dash => \"\\u2014\",\n :en_dash => \"\\u2013\",\n :ellipsis => \"\\u2026\",\n }\n end\n\n def character_spaces\n {\n :non_breaking_space => \"\\u00A0\",\n :word_joiner => \"\\u2060\",\n }\n end\n\n def entity(key)\n @entities[key]\n end\nend\n"}, "files_after": {"lib/rubypants.rb": "require_relative 'version'\n\nclass RubyPants < String\n extend RubyPantsVersion\n\n # Create a new RubyPants instance with the text in +string+.\n #\n # Allowed elements in the options array:\n #\n # 0 :: do nothing\n # 1 :: enable all, using only em-dash shortcuts\n # 2 :: enable all, using old school en- and em-dash shortcuts (*default*)\n # 3 :: enable all, using inverted old school en and em-dash shortcuts\n # -1 :: stupefy (translate HTML entities to their ASCII-counterparts)\n #\n # If you don't like any of these defaults, you can pass symbols to change\n # RubyPants' behavior:\n #\n # :quotes :: quotes\n # :backticks :: backtick quotes (``double'' only)\n # :allbackticks :: backtick quotes (``double'' and `single')\n # :dashes :: dashes\n # :oldschool :: old school dashes\n # :inverted :: inverted old school dashes\n # :ellipses :: ellipses\n # :prevent_breaks :: use nbsp and word-joiner to avoid breaking\n # before dashes and ellipses\n # :named_entities :: used named entities instead of the default\n # decimal entities (see below)\n # :convertquotes :: convert " entities to\n # \"\n # :stupefy :: translate RubyPants HTML entities\n # to their ASCII counterparts.\n #\n # In addition, you can customize the HTML entities that will be injected by\n # passing in a hash for the final argument. The defaults for these entities\n # are as follows:\n #\n # :single_left_quote :: \n # :double_left_quote :: \n # :single_right_quote :: \n # :double_right_quote :: \n # :em_dash :: \n # :en_dash :: \n # :ellipsis :: \n # :non_breaking_space ::  \n # :word_joiner :: \n #\n # If the :named_entities option is used, the default entities are\n # as follows:\n #\n # :single_left_quote :: \n # :double_left_quote :: \n # :single_right_quote :: \n # :double_right_quote :: \n # :em_dash :: \n # :en_dash :: \n # :ellipsis :: \n # :non_breaking_space ::  \n # :word_joiner :: \n #\n # If the :character_entities option is used, RubyPants will\n # emit Unicode characters directly, rather than HTML entities. By default\n # this excludes the space characters (non-breaking space and\n # word-joiner). To additionally emit Unicode space characters, use the\n # :character_spaces option.\n #\n def initialize(string, options=[2], entities = {})\n super string\n\n @options = [*options]\n @entities = default_entities\n @entities.merge!(named_entities) if @options.include?(:named_entities)\n @entities.merge!(character_entities) if @options.include?(:character_entities)\n @entities.merge!(character_spaces) if @options.include?(:character_spaces)\n @entities.merge!(entities)\n end\n\n # Apply SmartyPants transformations.\n def to_html\n do_quotes = do_backticks = do_dashes = do_ellipses = do_stupify = nil\n convert_quotes = prevent_breaks = nil\n\n if @options.include?(0)\n # Do nothing.\n return self\n elsif @options.include?(1)\n # Do everything, turn all options on.\n do_quotes = do_backticks = do_ellipses = true\n do_dashes = :normal\n elsif @options.include?(2)\n # Do everything, turn all options on, use old school dash shorthand.\n do_quotes = do_backticks = do_ellipses = true\n do_dashes = :oldschool\n elsif @options.include?(3)\n # Do everything, turn all options on, use inverted old school\n # dash shorthand.\n do_quotes = do_backticks = do_ellipses = true\n do_dashes = :inverted\n elsif @options.include?(-1)\n do_stupefy = true\n end\n\n # Explicit flags override numeric flag groups.\n do_quotes = true if @options.include?(:quotes)\n do_backticks = true if @options.include?(:backticks)\n do_backticks = :both if @options.include?(:allbackticks)\n do_dashes = :normal if @options.include?(:dashes)\n do_dashes = :oldschool if @options.include?(:oldschool)\n do_dashes = :inverted if @options.include?(:inverted)\n prevent_breaks = true if @options.include?(:prevent_breaks)\n do_ellipses = true if @options.include?(:ellipses)\n convert_quotes = true if @options.include?(:convertquotes)\n do_stupefy = true if @options.include?(:stupefy)\n\n # Parse the HTML\n tokens = tokenize\n\n # Keep track of when we're inside
             or  tags.\n    in_pre = nil\n\n    # Here is the result stored in.\n    result = \"\"\n\n    # This is a cheat, used to get some context for one-character\n    # tokens that consist of just a quote char. What we do is remember\n    # the last character of the previous text token, to use as context\n    # to curl single- character quote tokens correctly.\n    prev_token_last_char = nil\n\n    tokens.each do |token|\n      if token.first == :tag\n        result << token[1]\n        if token[1].end_with? '/>'\n          # ignore self-closing tags\n        elsif token[1] =~ %r!\\A<(/?)(pre|code|kbd|script|style|math)[\\s>]!\n          if $1 == '' && ! in_pre\n            in_pre = $2\n          elsif $1 == '/' && $2 == in_pre\n            in_pre = nil\n          end\n        end\n      else\n        t = token[1]\n\n        # Remember last char of this token before processing.\n        last_char = t[-1].chr\n\n        unless in_pre\n          t = process_escapes t\n\n          t.gsub!(/"/, '\"') if convert_quotes\n\n          if do_dashes\n            t = educate_dashes t, prevent_breaks           if do_dashes == :normal\n            t = educate_dashes_oldschool t, prevent_breaks if do_dashes == :oldschool\n            t = educate_dashes_inverted t, prevent_breaks  if do_dashes == :inverted\n          end\n\n          t = educate_ellipses t, prevent_breaks if do_ellipses\n\n          # Note: backticks need to be processed before quotes.\n          if do_backticks\n            t = educate_backticks t\n            t = educate_single_backticks t if do_backticks == :both\n          end\n\n          if do_quotes\n            if t == \"'\"\n              # Special case: single-character ' token\n              if prev_token_last_char =~ /\\S/\n                t = entity(:single_right_quote)\n              else\n                t = entity(:single_left_quote)\n              end\n            elsif t == '\"'\n              # Special case: single-character \" token\n              if prev_token_last_char =~ /\\S/\n                t = entity(:double_right_quote)\n              else\n                t = entity(:double_left_quote)\n              end\n            else\n              # Normal case:\n              t = educate_quotes t\n            end\n          end\n\n          t = stupefy_entities t if do_stupefy\n        end\n\n        prev_token_last_char = last_char\n        result << t\n      end\n    end\n\n    # Done\n    result\n  end\n\n  protected\n\n  # Return the string, with after processing the following backslash\n  # escape sequences. This is useful if you want to force a \"dumb\" quote\n  # or other character to appear.\n  #\n  # Escaped are:\n  #      \\\\    \\\"    \\'    \\.    \\-    \\`\n  #\n  def process_escapes(str)\n    str.\n      gsub('\\\\\\\\', '\').\n      gsub('\\\"',   '"').\n      gsub(\"\\\\\\'\", ''').\n      gsub('\\.',   '.').\n      gsub('\\-',   '-').\n      gsub('\\`',   '`')\n  end\n\n  def self.n_of(n, x)\n    x = Regexp.escape(x)\n    /(?[[:space:]]*)#{patt}/\n    str.gsub(patt) do\n      spaces = if prevent_breaks && $~['spaces'].length > 0\n                 entity(:non_breaking_space) # * $~['spaces'].length\n               elsif prevent_breaks\n                 entity(:word_joiner)\n               else\n                 $~['spaces']\n               end\n      spaces + repl\n    end\n  end\n\n  # Return the string, with each instance of \"--\" translated to an\n  # em-dash HTML entity.\n  #\n  def educate_dashes(str, prevent_breaks=false)\n    educate(str, DOUBLE_DASH, entity(:em_dash), prevent_breaks)\n  end\n\n  # Return the string, with each instance of \"--\" translated to an\n  # en-dash HTML entity, and each \"---\" translated to an\n  # em-dash HTML entity.\n  #\n  def educate_dashes_oldschool(str, prevent_breaks=false)\n    str = educate(str, TRIPLE_DASH, entity(:em_dash), prevent_breaks)\n    educate(str, DOUBLE_DASH, entity(:en_dash), prevent_breaks)\n  end\n\n  # Return the string, with each instance of \"--\" translated\n  # to an em-dash HTML entity, and each \"---\" translated to\n  # an en-dash HTML entity. Two reasons why: First, unlike the en- and\n  # em-dash syntax supported by +educate_dashes_oldschool+, it's\n  # compatible with existing entries written before SmartyPants 1.1,\n  # back when \"--\" was only used for em-dashes.  Second,\n  # em-dashes are more common than en-dashes, and so it sort of makes\n  # sense that the shortcut should be shorter to type. (Thanks to\n  # Aaron Swartz for the idea.)\n  #\n  def educate_dashes_inverted(str, prevent_breaks=false)\n    str = educate(str, TRIPLE_DASH, entity(:en_dash), prevent_breaks)\n    educate(str, DOUBLE_DASH, entity(:em_dash), prevent_breaks)\n  end\n\n  # Return the string, with each instance of \"...\" translated\n  # to an ellipsis HTML entity. Also converts the case where there are\n  # spaces between the dots.\n  #\n  def educate_ellipses(str, prevent_breaks=false)\n    str = educate(str, RubyPants.n_of(3, '.'), entity(:ellipsis), prevent_breaks)\n    educate(str, /(?``backticks''\"-style single quotes\n  # translated into HTML curly quote entities.\n  #\n  def educate_backticks(str)\n    str.\n      gsub(\"``\", entity(:double_left_quote)).\n      gsub(\"''\", entity(:double_right_quote))\n  end\n\n  # Return the string, with \"`backticks'\"-style single quotes\n  # translated into HTML curly quote entities.\n  #\n  def educate_single_backticks(str)\n    str.\n      gsub(\"`\", entity(:single_left_quote)).\n      gsub(\"'\", entity(:single_right_quote))\n  end\n\n  # Return the string, with \"educated\" curly quote HTML entities.\n  #\n  def educate_quotes(str)\n    punct_class = '[!\"#\\$\\%\\'()*+,\\-.\\/:;<=>?\\@\\[\\\\\\\\\\]\\^_`{|}~]'\n\n    str = str.dup\n\n    # Special case if the very first character is a quote followed by\n    # punctuation at a non-word-break. Close the quotes by brute\n    # force:\n    str.gsub!(/^'(?=#{punct_class}\\B)/,\n              entity(:single_right_quote))\n    str.gsub!(/^\"(?=#{punct_class}\\B)/,\n              entity(:double_right_quote))\n\n    # Special case for double sets of quotes, e.g.:\n    #   

            He said, \"'Quoted' words in a larger quote.\"

            \n str.gsub!(/\"'(?=\\w)/,\n \"#{entity(:double_left_quote)}#{entity(:single_left_quote)}\")\n str.gsub!(/'\"(?=\\w)/,\n \"#{entity(:single_left_quote)}#{entity(:double_left_quote)}\")\n\n # Special case for decade abbreviations (the '80s):\n str.gsub!(/'(?=\\d\\ds)/,\n entity(:single_right_quote))\n\n close_class = %![^\\ \\t\\r\\n\\\\[\\{\\(\\-]!\n dec_dashes = \"#{entity(:en_dash)}|#{entity(:em_dash)}\"\n\n # Get most opening single quotes:\n str.gsub!(/([[:space:]]| |--|&[mn]dash;|#{dec_dashes}|ȁ[34];)'(?=\\w)/,\n '\\1' + entity(:single_left_quote))\n\n # Single closing quotes:\n str.gsub!(/(#{close_class})'/,\n '\\1' + entity(:single_right_quote))\n str.gsub!(/'(\\s|s\\b|$)/,\n entity(:single_right_quote) + '\\1')\n\n # Any remaining single quotes should be opening ones:\n str.gsub!(/'/,\n entity(:single_left_quote))\n\n # Get most opening double quotes:\n str.gsub!(/([[:space:]]| |--|&[mn]dash;|#{dec_dashes}|ȁ[34];)\"(?=\\w)/,\n '\\1' + entity(:double_left_quote))\n\n # Double closing quotes:\n str.gsub!(/(#{close_class})\"/,\n '\\1' + entity(:double_right_quote))\n str.gsub!(/\"(\\s|s\\b|$)/,\n entity(:double_right_quote) + '\\1')\n\n # Any remaining quotes should be opening ones:\n str.gsub!(/\"/,\n entity(:double_left_quote))\n\n str\n end\n\n # Return the string, with each RubyPants HTML entity translated to\n # its ASCII counterpart.\n #\n # Note: This is not reversible (but exactly the same as in SmartyPants)\n #\n def stupefy_entities(str)\n new_str = str.dup\n\n {\n :en_dash => '-',\n :em_dash => '--',\n :single_left_quote => \"'\",\n :single_right_quote => \"'\",\n :double_left_quote => '\"',\n :double_right_quote => '\"',\n :ellipsis => '...'\n }.each do |k,v|\n new_str.gsub!(/#{entity(k)}/, v)\n end\n\n new_str\n end\n\n # Return an array of the tokens comprising the string. Each token is\n # either a tag (possibly with nested, tags contained therein, such\n # as
            \">, or a run of text between\n # tags. Each element of the array is a two-element array; the first\n # is either :tag or :text; the second is the actual value.\n #\n # Based on the _tokenize() subroutine from Brad Choate's\n # MTRegex plugin. \n #\n # This is actually the easier variant using tag_soup, as used by\n # Chad Miller in the Python port of SmartyPants.\n #\n def tokenize\n tag_soup = /([^<]*)(|<[^>]*>)/m\n\n tokens = []\n\n prev_end = 0\n\n scan(tag_soup) do\n tokens << [:text, $1] if $1 != \"\"\n tokens << [:tag, $2]\n prev_end = $~.end(0)\n end\n\n if prev_end < size\n tokens << [:text, self[prev_end..-1]]\n end\n\n tokens\n end\n\n def default_entities\n {\n :single_left_quote => \"‘\",\n :double_left_quote => \"“\",\n :single_right_quote => \"’\",\n :double_right_quote => \"”\",\n :em_dash => \"—\",\n :en_dash => \"–\",\n :ellipsis => \"…\",\n :non_breaking_space => \" \",\n :word_joiner => \"⁠\",\n }\n end\n\n def named_entities\n {\n :single_left_quote => '‘',\n :double_left_quote => \"“\",\n :single_right_quote => \"’\",\n :double_right_quote => \"”\",\n :em_dash => \"—\",\n :en_dash => \"–\",\n :ellipsis => \"…\",\n :non_breaking_space => \" \",\n # :word_joiner => N/A,\n }\n end\n\n def character_entities\n {\n :single_left_quote => \"\\u2018\",\n :double_left_quote => \"\\u201C\",\n :single_right_quote => \"\\u2019\",\n :double_right_quote => \"\\u201D\",\n :em_dash => \"\\u2014\",\n :en_dash => \"\\u2013\",\n :ellipsis => \"\\u2026\",\n }\n end\n\n def character_spaces\n {\n :non_breaking_space => \"\\u00A0\",\n :word_joiner => \"\\u2060\",\n }\n end\n\n def entity(key)\n @entities[key]\n end\nend\n"}} -{"repo": "ryan-allen/modelling", "pr_number": 3, "title": "Use GitHub Actions for CI", "state": "closed", "merged_at": null, "additions": 51, "deletions": 32, "files_changed": ["lib/modelling.rb", "spec/modelling_spec.rb"], "files_before": {"lib/modelling.rb": "require 'modelling/version'\nrequire 'ostruct'\n\nmodule Modelling\n\n def self.included(receiver)\n receiver.extend ClassMethods\n end\n\n module ClassMethods\n def inherited(descendant)\n descendant.instance_variable_set(:@members, members.dup)\n super\n end\n\n def attributes(*args)\n generate_accessors_from_args(args, Proc.new { nil })\n end\n\n def collections(*args)\n generate_accessors_from_args(args, Proc.new { Array.new })\n end\n\n def maps(*args)\n generate_accessors_from_args(args, Proc.new { Hash.new })\n end\n\n def structs(*args)\n generate_accessors_from_args(args, Proc.new { OpenStruct.new })\n end\n\n def members\n @members ||= {}\n end\n \n def accessors\n @accessors ||= []\n end\n\n private\n\n def generate_accessors_from_args(args, default_initializer)\n names_to_initializer = args.last.is_a?(Hash) ? args.pop : {}\n args.each do |name|\n names_to_initializer[name] = default_initializer\n end\n generate_accessors(names_to_initializer)\n end\n\n def generate_accessors(names_to_initializer)\n names_to_initializer.each do |name, initializer|\n create_accessor(name)\n if initializer.is_a?(Proc)\n members[name] = initializer\n else\n members[name] = Proc.new { initializer.new }\n end\n end\n end\n\n def create_accessor(name)\n accessors << name\n instance_eval { attr_accessor name }\n end\n\n end\n\n def members\n self.class.members\n end\n\n def initialize(args = {})\n members.each do |accessor, initializer|\n if initializer.arity > 0\n send \"#{accessor}=\", initializer.call(self)\n else\n send \"#{accessor}=\", initializer.call\n end\n end\n args.each { |name, value| send \"#{name}=\", value }\n end\n \n def attributes\n hash = {}\n self.class.accessors.each do |method_name|\n hash[method_name] = send(method_name)\n end\n hash\n end\n \n def inspect\n attributes_as_nice_string = attributes.collect { |name, value|\n \"#{name}: #{attribute_for_inspect(value)}\"\n }.compact.join(\", \")\n \"#<#{self.class} #{attributes_as_nice_string}>\"\n end\n \n def attribute_for_inspect(value)\n if value.is_a?(String) && value.length > 50\n \"#{value[0..50]}...\".inspect\n elsif value.is_a?(Date) || value.is_a?(Time)\n %(\"#{value.to_s(:db)}\")\n elsif value.class.included_modules.include?(Modelling)\n \"#<#{value.class.to_s}>\"\n else\n value.inspect\n end\n end\n \nend", "spec/modelling_spec.rb": "require 'bundler'\nBundler.require\n$: << '.'\nrequire 'modelling'\n\nclass User\n include Modelling\n attributes :name, :age\n collections :fav_colours, :biggest_gripes, :test => lambda { 3 }\nend\n\nclass NonSpecificUser < User\nend\n\nclass MyArray < Array; end\nclass MyHash < Hash; end\n\nclass Car\n include Modelling\n attributes :name => Proc.new { |car| String.new(car.class.to_s) }\n collections :doors => MyArray\nend\n\nclass SuperCar < Car\n attributes :bhp => Proc.new { 400 }\nend\n\nclass Site\n include Modelling\n maps :users => MyHash\nend\n\nclass Bike\n include Modelling\n attributes :manufacturer\n maps :stickers\n structs :features\nend\n\nclass LambdaTest\n include Modelling\n attributes :lambda => lambda { \"boo\" }\nend\n\ndescribe Modelling do\n\n specify 'user has name' do\n user = User.new\n user.name = 'Ryan'\n user.name.should eq 'Ryan'\n end\n\n specify 'user has age' do\n user = User.new\n user.age = 24\n user.age.should eq 24\n end\n\n specify 'user has fav colours collection' do\n user = User.new\n user.fav_colours = [:green, :yellow]\n user.fav_colours.should eq [:green, :yellow]\n end\n\n specify 'user has biggest gripes collection' do\n user = User.new\n user.biggest_gripes = [:mediocrity, :CUB_beer]\n user.biggest_gripes.should eq [:mediocrity, :CUB_beer]\n end\n\n specify 'attributes are initialized as nil' do\n user = User.new\n user.name.should be_nil\n user.age.should be_nil\n end\n\n specify 'collections are initialized as empty array' do\n user = User.new\n user.fav_colours.should be_empty\n user.biggest_gripes.should be_empty\n end\n\n it 'can initialize with attributes' do\n user = User.new(:name => 'Ryan')\n user.name.should eq 'Ryan'\n end\n\n it 'can initialize with collections' do\n user = User.new(:biggest_gripes => [:mediocrity, :CUB_beer])\n user.biggest_gripes.should eq [:mediocrity, :CUB_beer]\n end\n\n specify 'car has doors and all is good' do\n car = Car.new\n car.doors.should be_empty\n end\n\n specify 'bike does not bunk on having no collection' do\n bike = Bike.new(:manufacturer => 'Kawasaki')\n # if nothing is rased, we fixed the bug\n end\n\n specify 'bike has map of stickers' do\n Bike.new.stickers.should be_empty\n end\n \n specify 'cars doors is a my array' do\n Car.new.doors.should be_instance_of MyArray\n end\n \n specify 'sites users is a my hash' do\n Site.new.users.should be_instance_of MyHash\n end\n \n it 'can initialize with proc and get reference to new instance' do\n car = Car.new\n car.name.should eq String.new(car.class.to_s)\n end\n\n specify 'bike has features' do\n bike = Bike.new\n bike.features.should be_instance_of OpenStruct\n end\n\n it 'doesnt fail when lambdas with no args are used' do\n LambdaTest.new.lambda.should eq 'boo'\n end\n \n specify 'tracks list of accessors' do\n User.accessors.should include :name, :age\n end\n \n specify 'provides a Hash of attributes and values' do\n User.new.attributes.key?(:name).should be_true\n User.new.attributes.key?(:age).should be_true\n User.new(:name => \"Joe\").attributes[:name].should eq \"Joe\"\n end\n \n specify 'converts the attributes hash to a string for inspect' do\n u = User.new(:name => \"Joe\")\n u.inspect.should == \"#\"\n end\n \n context 'circular references' do\n \n before do\n class FirstModel\n include Modelling\n attributes :test => lambda { |me| OtherModel.new(me) }\n end\n\n class OtherModel\n include Modelling\n attributes :owner\n def initialize(owner)\n @owner = owner\n end\n end\n end\n \n it 'should not raise an error when inspecting' do\n expect { FirstModel.new.inspect }.should_not raise_error(SystemStackError)\n end\n \n it 'should show the class name instead of inspecting referenced models' do\n FirstModel.new.inspect.should include(\"#\")\n end\n \n end\n \n \n \n context 'inheritence' do\n let(:car) { Car.new }\n let(:super_car) { SuperCar.new }\n\n it 'inherits attributes' do\n super_car.doors.should be_instance_of MyArray\n super_car.name.should eq \"SuperCar\"\n end\n\n it 'allows extra attributes' do\n super_car.bhp.should eq 400\n end\n\n it 'doesnt mess up the super classes members' do\n car.should_not respond_to(:bhp)\n car.should respond_to(:doors)\n car.should respond_to(:name)\n end\n\n specify 'non specific user inherits attributes' do\n user = NonSpecificUser.new(:name => 'Ryan you cocktard')\n user.name.should eq 'Ryan you cocktard'\n end\n end\nend\n"}, "files_after": {"lib/modelling.rb": "require 'modelling/version'\nrequire 'ostruct'\nrequire 'time'\n\nmodule Modelling\n\n def self.included(receiver)\n receiver.extend ClassMethods\n end\n\n module ClassMethods\n def inherited(descendant)\n descendant.instance_variable_set(:@members, members.dup)\n super\n end\n\n def attributes(*args)\n generate_accessors_from_args(args, Proc.new { nil })\n end\n\n def collections(*args)\n generate_accessors_from_args(args, Proc.new { Array.new })\n end\n\n def maps(*args)\n generate_accessors_from_args(args, Proc.new { Hash.new })\n end\n\n def structs(*args)\n generate_accessors_from_args(args, Proc.new { OpenStruct.new })\n end\n\n def members\n @members ||= {}\n end\n \n def accessors\n @accessors ||= []\n end\n\n private\n\n def generate_accessors_from_args(args, default_initializer)\n names_to_initializer = args.last.is_a?(Hash) ? args.pop : {}\n args.each do |name|\n names_to_initializer[name] = default_initializer\n end\n generate_accessors(names_to_initializer)\n end\n\n def generate_accessors(names_to_initializer)\n names_to_initializer.each do |name, initializer|\n create_accessor(name)\n if initializer.is_a?(Proc)\n members[name] = initializer\n else\n members[name] = Proc.new { initializer.new }\n end\n end\n end\n\n def create_accessor(name)\n accessors << name\n instance_eval { attr_accessor name }\n end\n\n end\n\n def members\n self.class.members\n end\n\n def initialize(args = {})\n members.each do |accessor, initializer|\n if initializer.arity > 0\n send \"#{accessor}=\", initializer.call(self)\n else\n send \"#{accessor}=\", initializer.call\n end\n end\n args.each { |name, value| send \"#{name}=\", value }\n end\n \n def attributes\n hash = {}\n self.class.accessors.each do |method_name|\n hash[method_name] = send(method_name)\n end\n hash\n end\n \n def inspect\n attributes_as_nice_string = attributes.collect { |name, value|\n \"#{name}: #{attribute_for_inspect(value)}\"\n }.compact.join(\", \")\n \"#<#{self.class} #{attributes_as_nice_string}>\"\n end\n \n def attribute_for_inspect(value)\n if value.is_a?(String) && value.length > 50\n \"#{value[0..50]}...\".inspect\n elsif value.is_a?(Date) || value.is_a?(Time)\n %(\"#{value.to_s(:db)}\")\n elsif value.class.included_modules.include?(Modelling)\n \"#<#{value.class.to_s}>\"\n else\n value.inspect\n end\n end\n \nend", "spec/modelling_spec.rb": "require 'bundler'\nBundler.require\n$: << '.'\nrequire 'modelling'\n\nclass User\n include Modelling\n attributes :name, :age\n collections :fav_colours, :biggest_gripes, :test => lambda { 3 }\nend\n\nclass NonSpecificUser < User\nend\n\nclass MyArray < Array; end\nclass MyHash < Hash; end\n\nclass Car\n include Modelling\n attributes :name => Proc.new { |car| String.new(car.class.to_s) }\n collections :doors => MyArray\nend\n\nclass SuperCar < Car\n attributes :bhp => Proc.new { 400 }\nend\n\nclass Site\n include Modelling\n maps :users => MyHash\nend\n\nclass Bike\n include Modelling\n attributes :manufacturer\n maps :stickers\n structs :features\nend\n\nclass LambdaTest\n include Modelling\n attributes :lambda => lambda { \"boo\" }\nend\n\nRSpec.describe Modelling do\n\n specify 'user has name' do\n user = User.new\n user.name = 'Ryan'\n expect(user.name).to eq 'Ryan'\n end\n\n specify 'user has age' do\n user = User.new\n user.age = 24\n expect(user.age).to eq 24\n end\n\n specify 'user has fav colours collection' do\n user = User.new\n user.fav_colours = [:green, :yellow]\n expect(user.fav_colours).to eq [:green, :yellow]\n end\n\n specify 'user has biggest gripes collection' do\n user = User.new\n user.biggest_gripes = [:mediocrity, :CUB_beer]\n expect(user.biggest_gripes).to eq [:mediocrity, :CUB_beer]\n end\n\n specify 'attributes are initialized as nil' do\n user = User.new\n expect(user.name).to be_nil\n expect(user.age).to be_nil\n end\n\n specify 'collections are initialized as empty array' do\n user = User.new\n expect(user.fav_colours).to be_empty\n expect(user.biggest_gripes).to be_empty\n end\n\n it 'can initialize with attributes' do\n user = User.new(:name => 'Ryan')\n expect(user.name).to eq 'Ryan'\n end\n\n it 'can initialize with collections' do\n user = User.new(:biggest_gripes => [:mediocrity, :CUB_beer])\n expect(user.biggest_gripes).to eq [:mediocrity, :CUB_beer]\n end\n\n specify 'car has doors and all is good' do\n car = Car.new\n expect(car.doors).to be_empty\n end\n\n specify 'bike does not bunk on having no collection' do\n bike = Bike.new(:manufacturer => 'Kawasaki')\n # if nothing is rased, we fixed the bug\n end\n\n specify 'bike has map of stickers' do\n expect(Bike.new.stickers).to be_empty\n end\n \n specify 'cars doors is a my array' do\n expect(Car.new.doors).to be_instance_of MyArray\n end\n \n specify 'sites users is a my hash' do\n expect(Site.new.users).to be_instance_of MyHash\n end\n \n it 'can initialize with proc and get reference to new instance' do\n car = Car.new\n expect(car.name).to eq String.new(car.class.to_s)\n end\n\n specify 'bike has features' do\n bike = Bike.new\n expect(bike.features).to be_instance_of OpenStruct\n end\n\n it 'doesnt fail when lambdas with no args are used' do\n expect(LambdaTest.new.lambda).to eq 'boo'\n end\n \n specify 'tracks list of accessors' do\n expect(User.accessors).to include :name, :age\n end\n \n specify 'provides a Hash of attributes and values' do\n expect(User.new.attributes.key?(:name)).to be true\n expect(User.new.attributes.key?(:age)).to be true\n expect(User.new(:name => \"Joe\").attributes[:name]).to eq \"Joe\"\n end\n \n specify 'converts the attributes hash to a string for inspect' do\n u = User.new(:name => \"Joe\")\n expect(u.inspect).to eq(\"#\")\n end\n \n context 'circular references' do\n \n before do\n class FirstModel\n include Modelling\n attributes :test => lambda { |me| OtherModel.new(me) }\n end\n\n class OtherModel\n include Modelling\n attributes :owner\n def initialize(owner)\n @owner = owner\n end\n end\n end\n \n it 'should not raise an error when inspecting' do\n expect { FirstModel.new.inspect }.not_to raise_error\n end\n \n it 'should show the class name instead of inspecting referenced models' do\n expect(FirstModel.new.inspect).to include(\"#\")\n end\n \n end\n \n \n \n context 'inheritence' do\n let(:car) { Car.new }\n let(:super_car) { SuperCar.new }\n\n it 'inherits attributes' do\n expect(super_car.doors).to be_instance_of MyArray\n expect(super_car.name).to eq \"SuperCar\"\n end\n\n it 'allows extra attributes' do\n expect(super_car.bhp).to eq 400\n end\n\n it 'doesnt mess up the super classes members' do\n expect(car).not_to respond_to(:bhp)\n expect(car).to respond_to(:doors)\n expect(car).to respond_to(:name)\n end\n\n specify 'non specific user inherits attributes' do\n user = NonSpecificUser.new(:name => 'Ryan you cocktard')\n expect(user.name).to eq 'Ryan you cocktard'\n end\n end\nend\n"}} -{"repo": "mozilla/addon-sdk", "pr_number": 2045, "title": "Bug 1246107 - A spell error of delimeters in mozrunner/__init__.py", "state": "closed", "merged_at": null, "additions": 1, "deletions": 1, "files_changed": ["python-lib/mozrunner/__init__.py"], "files_before": {"python-lib/mozrunner/__init__.py": "# This Source Code Form is subject to the terms of the Mozilla Public\n# License, v. 2.0. If a copy of the MPL was not distributed with this\n# file, You can obtain one at http://mozilla.org/MPL/2.0/.\n\nimport os\nimport sys\nimport copy\nimport tempfile\nimport signal\nimport commands\nimport zipfile\nimport optparse\nimport killableprocess\nimport subprocess\nimport platform\nimport shutil\nfrom StringIO import StringIO\nfrom xml.dom import minidom\n\nfrom distutils import dir_util\nfrom time import sleep\n\n# conditional (version-dependent) imports\ntry:\n import simplejson\nexcept ImportError:\n import json as simplejson\n\nimport logging\nlogger = logging.getLogger(__name__)\n\n# Use dir_util for copy/rm operations because shutil is all kinds of broken\ncopytree = dir_util.copy_tree\nrmtree = dir_util.remove_tree\n\ndef findInPath(fileName, path=os.environ['PATH']):\n dirs = path.split(os.pathsep)\n for dir in dirs:\n if os.path.isfile(os.path.join(dir, fileName)):\n return os.path.join(dir, fileName)\n if os.name == 'nt' or sys.platform == 'cygwin':\n if os.path.isfile(os.path.join(dir, fileName + \".exe\")):\n return os.path.join(dir, fileName + \".exe\")\n return None\n\nstdout = sys.stdout\nstderr = sys.stderr\nstdin = sys.stdin\n\ndef run_command(cmd, env=None, **kwargs):\n \"\"\"Run the given command in killable process.\"\"\"\n killable_kwargs = {'stdout':stdout ,'stderr':stderr, 'stdin':stdin}\n killable_kwargs.update(kwargs)\n\n if sys.platform != \"win32\":\n return killableprocess.Popen(cmd, preexec_fn=lambda : os.setpgid(0, 0),\n env=env, **killable_kwargs)\n else:\n return killableprocess.Popen(cmd, env=env, **killable_kwargs)\n\ndef getoutput(l):\n tmp = tempfile.mktemp()\n x = open(tmp, 'w')\n subprocess.call(l, stdout=x, stderr=x)\n x.close(); x = open(tmp, 'r')\n r = x.read() ; x.close()\n os.remove(tmp)\n return r\n\ndef get_pids(name, minimun_pid=0):\n \"\"\"Get all the pids matching name, exclude any pids below minimum_pid.\"\"\"\n if os.name == 'nt' or sys.platform == 'cygwin':\n import wpk\n\n pids = wpk.get_pids(name)\n\n else:\n data = getoutput(['ps', 'ax']).splitlines()\n pids = [int(line.split()[0]) for line in data if line.find(name) is not -1]\n\n matching_pids = [m for m in pids if m > minimun_pid]\n return matching_pids\n\ndef makedirs(name):\n\n head, tail = os.path.split(name)\n if not tail:\n head, tail = os.path.split(head)\n if head and tail and not os.path.exists(head):\n try:\n makedirs(head)\n except OSError, e:\n pass\n if tail == os.curdir: # xxx/newdir/. exists if xxx/newdir exists\n return\n try:\n os.mkdir(name)\n except:\n pass\n\n# addon_details() copied from mozprofile\ndef addon_details(install_rdf_fh):\n \"\"\"\n returns a dictionary of details about the addon\n - addon_path : path to the addon directory\n Returns:\n {'id': u'rainbow@colors.org', # id of the addon\n 'version': u'1.4', # version of the addon\n 'name': u'Rainbow', # name of the addon\n 'unpack': # whether to unpack the addon\n \"\"\"\n\n details = {\n 'id': None,\n 'unpack': False,\n 'name': None,\n 'version': None\n }\n\n def get_namespace_id(doc, url):\n attributes = doc.documentElement.attributes\n namespace = \"\"\n for i in range(attributes.length):\n if attributes.item(i).value == url:\n if \":\" in attributes.item(i).name:\n # If the namespace is not the default one remove 'xlmns:'\n namespace = attributes.item(i).name.split(':')[1] + \":\"\n break\n return namespace\n\n def get_text(element):\n \"\"\"Retrieve the text value of a given node\"\"\"\n rc = []\n for node in element.childNodes:\n if node.nodeType == node.TEXT_NODE:\n rc.append(node.data)\n return ''.join(rc).strip()\n\n doc = minidom.parse(install_rdf_fh)\n\n # Get the namespaces abbreviations\n em = get_namespace_id(doc, \"http://www.mozilla.org/2004/em-rdf#\")\n rdf = get_namespace_id(doc, \"http://www.w3.org/1999/02/22-rdf-syntax-ns#\")\n\n description = doc.getElementsByTagName(rdf + \"Description\").item(0)\n for node in description.childNodes:\n # Remove the namespace prefix from the tag for comparison\n entry = node.nodeName.replace(em, \"\")\n if entry in details.keys():\n details.update({ entry: get_text(node) })\n\n # turn unpack into a true/false value\n if isinstance(details['unpack'], basestring):\n details['unpack'] = details['unpack'].lower() == 'true'\n\n return details\n\nclass Profile(object):\n \"\"\"Handles all operations regarding profile. Created new profiles, installs extensions,\n sets preferences and handles cleanup.\"\"\"\n\n def __init__(self, binary=None, profile=None, addons=None,\n preferences=None):\n\n self.binary = binary\n\n self.create_new = not(bool(profile))\n if profile:\n self.profile = profile\n else:\n self.profile = self.create_new_profile(self.binary)\n\n self.addons_installed = []\n self.addons = addons or []\n\n ### set preferences from class preferences\n preferences = preferences or {}\n if hasattr(self.__class__, 'preferences'):\n self.preferences = self.__class__.preferences.copy()\n else:\n self.preferences = {}\n self.preferences.update(preferences)\n\n for addon in self.addons:\n self.install_addon(addon)\n\n self.set_preferences(self.preferences)\n\n def create_new_profile(self, binary):\n \"\"\"Create a new clean profile in tmp which is a simple empty folder\"\"\"\n profile = tempfile.mkdtemp(suffix='.mozrunner')\n return profile\n\n def unpack_addon(self, xpi_zipfile, addon_path):\n for name in xpi_zipfile.namelist():\n if name.endswith('/'):\n makedirs(os.path.join(addon_path, name))\n else:\n if not os.path.isdir(os.path.dirname(os.path.join(addon_path, name))):\n makedirs(os.path.dirname(os.path.join(addon_path, name)))\n data = xpi_zipfile.read(name)\n f = open(os.path.join(addon_path, name), 'wb')\n f.write(data) ; f.close()\n zi = xpi_zipfile.getinfo(name)\n os.chmod(os.path.join(addon_path,name), (zi.external_attr>>16))\n\n def install_addon(self, path):\n \"\"\"Installs the given addon or directory of addons in the profile.\"\"\"\n\n extensions_path = os.path.join(self.profile, 'extensions')\n if not os.path.exists(extensions_path):\n os.makedirs(extensions_path)\n\n addons = [path]\n if not path.endswith('.xpi') and not os.path.exists(os.path.join(path, 'install.rdf')):\n addons = [os.path.join(path, x) for x in os.listdir(path)]\n\n for addon in addons:\n if addon.endswith('.xpi'):\n xpi_zipfile = zipfile.ZipFile(addon, \"r\")\n details = addon_details(StringIO(xpi_zipfile.read('install.rdf')))\n addon_path = os.path.join(extensions_path, details[\"id\"])\n if details.get(\"unpack\", True):\n self.unpack_addon(xpi_zipfile, addon_path)\n self.addons_installed.append(addon_path)\n else:\n shutil.copy(addon, addon_path + '.xpi')\n else:\n # it's already unpacked, but we need to extract the id so we\n # can copy it\n details = addon_details(open(os.path.join(addon, \"install.rdf\"), \"rb\"))\n addon_path = os.path.join(extensions_path, details[\"id\"])\n shutil.copytree(addon, addon_path, symlinks=True)\n\n def set_preferences(self, preferences):\n \"\"\"Adds preferences dict to profile preferences\"\"\"\n prefs_file = os.path.join(self.profile, 'user.js')\n # Ensure that the file exists first otherwise create an empty file\n if os.path.isfile(prefs_file):\n f = open(prefs_file, 'a+')\n else:\n f = open(prefs_file, 'w')\n\n f.write('\\n#MozRunner Prefs Start\\n')\n\n pref_lines = ['user_pref(%s, %s);' %\n (simplejson.dumps(k), simplejson.dumps(v) ) for k, v in\n preferences.items()]\n for line in pref_lines:\n f.write(line+'\\n')\n f.write('#MozRunner Prefs End\\n')\n f.flush() ; f.close()\n\n def pop_preferences(self):\n \"\"\"\n pop the last set of preferences added\n returns True if popped\n \"\"\"\n\n # our magic markers\n delimeters = ('#MozRunner Prefs Start', '#MozRunner Prefs End')\n\n lines = file(os.path.join(self.profile, 'user.js')).read().splitlines()\n def last_index(_list, value):\n \"\"\"\n returns the last index of an item;\n this should actually be part of python code but it isn't\n \"\"\"\n for index in reversed(range(len(_list))):\n if _list[index] == value:\n return index\n s = last_index(lines, delimeters[0])\n e = last_index(lines, delimeters[1])\n\n # ensure both markers are found\n if s is None:\n assert e is None, '%s found without %s' % (delimeters[1], delimeters[0])\n return False # no preferences found\n elif e is None:\n assert e is None, '%s found without %s' % (delimeters[0], delimeters[1])\n\n # ensure the markers are in the proper order\n assert e > s, '%s found at %s, while %s found at %s' (delimeter[1], e, delimeter[0], s)\n\n # write the prefs\n cleaned_prefs = '\\n'.join(lines[:s] + lines[e+1:])\n f = file(os.path.join(self.profile, 'user.js'), 'w')\n f.write(cleaned_prefs)\n f.close()\n return True\n\n def clean_preferences(self):\n \"\"\"Removed preferences added by mozrunner.\"\"\"\n while True:\n if not self.pop_preferences():\n break\n\n def clean_addons(self):\n \"\"\"Cleans up addons in the profile.\"\"\"\n for addon in self.addons_installed:\n if os.path.isdir(addon):\n rmtree(addon)\n\n def cleanup(self):\n \"\"\"Cleanup operations on the profile.\"\"\"\n def oncleanup_error(function, path, excinfo):\n #TODO: How should we handle this?\n print \"Error Cleaning up: \" + str(excinfo[1])\n if self.create_new:\n shutil.rmtree(self.profile, False, oncleanup_error)\n else:\n self.clean_preferences()\n self.clean_addons()\n\nclass FirefoxProfile(Profile):\n \"\"\"Specialized Profile subclass for Firefox\"\"\"\n preferences = {# Don't automatically update the application\n 'app.update.enabled' : False,\n # Don't restore the last open set of tabs if the browser has crashed\n 'browser.sessionstore.resume_from_crash': False,\n # Don't check for the default web browser\n 'browser.shell.checkDefaultBrowser' : False,\n # Don't warn on exit when multiple tabs are open\n 'browser.tabs.warnOnClose' : False,\n # Don't warn when exiting the browser\n 'browser.warnOnQuit': False,\n # Only install add-ons from the profile and the app folder\n 'extensions.enabledScopes' : 5,\n # Don't automatically update add-ons\n 'extensions.update.enabled' : False,\n # Don't open a dialog to show available add-on updates\n 'extensions.update.notifyUser' : False,\n }\n\n # The possible names of application bundles on Mac OS X, in order of\n # preference from most to least preferred.\n # Note: Nightly is obsolete, as it has been renamed to FirefoxNightly,\n # but it will still be present if users update an older nightly build\n # via the app update service.\n bundle_names = ['Firefox', 'FirefoxNightly', 'Nightly']\n\n # The possible names of binaries, in order of preference from most to least\n # preferred.\n @property\n def names(self):\n if sys.platform == 'darwin':\n return ['firefox', 'nightly', 'shiretoko']\n if (sys.platform == 'linux2') or (sys.platform in ('sunos5', 'solaris')):\n return ['firefox', 'mozilla-firefox', 'iceweasel']\n if os.name == 'nt' or sys.platform == 'cygwin':\n return ['firefox']\n\nclass ThunderbirdProfile(Profile):\n preferences = {'extensions.update.enabled' : False,\n 'extensions.update.notifyUser' : False,\n 'browser.shell.checkDefaultBrowser' : False,\n 'browser.tabs.warnOnClose' : False,\n 'browser.warnOnQuit': False,\n 'browser.sessionstore.resume_from_crash': False,\n }\n\n # The possible names of application bundles on Mac OS X, in order of\n # preference from most to least preferred.\n bundle_names = [\"Thunderbird\", \"Shredder\"]\n\n # The possible names of binaries, in order of preference from most to least\n # preferred.\n names = [\"thunderbird\", \"shredder\"]\n\n\nclass Runner(object):\n \"\"\"Handles all running operations. Finds bins, runs and kills the process.\"\"\"\n\n def __init__(self, binary=None, profile=None, cmdargs=[], env=None,\n kp_kwargs={}):\n if binary is None:\n self.binary = self.find_binary()\n elif sys.platform == 'darwin' and binary.find('Contents/MacOS/') == -1:\n self.binary = os.path.join(binary, 'Contents/MacOS/%s-bin' % self.names[0])\n else:\n self.binary = binary\n\n if not os.path.exists(self.binary):\n raise Exception(\"Binary path does not exist \"+self.binary)\n\n if sys.platform == 'linux2' and self.binary.endswith('-bin'):\n dirname = os.path.dirname(self.binary)\n if os.environ.get('LD_LIBRARY_PATH', None):\n os.environ['LD_LIBRARY_PATH'] = '%s:%s' % (os.environ['LD_LIBRARY_PATH'], dirname)\n else:\n os.environ['LD_LIBRARY_PATH'] = dirname\n\n # Disable the crash reporter by default\n os.environ['MOZ_CRASHREPORTER_NO_REPORT'] = '1'\n\n self.profile = profile\n\n self.cmdargs = cmdargs\n if env is None:\n self.env = copy.copy(os.environ)\n self.env.update({'MOZ_NO_REMOTE':\"1\",})\n else:\n self.env = env\n self.kp_kwargs = kp_kwargs or {}\n\n def find_binary(self):\n \"\"\"Finds the binary for self.names if one was not provided.\"\"\"\n binary = None\n if sys.platform in ('linux2', 'sunos5', 'solaris') \\\n or sys.platform.startswith('freebsd'):\n for name in reversed(self.names):\n binary = findInPath(name)\n elif os.name == 'nt' or sys.platform == 'cygwin':\n\n # find the default executable from the windows registry\n try:\n import _winreg\n except ImportError:\n pass\n else:\n sam_flags = [0]\n # KEY_WOW64_32KEY etc only appeared in 2.6+, but that's OK as\n # only 2.6+ has functioning 64bit builds.\n if hasattr(_winreg, \"KEY_WOW64_32KEY\"):\n if \"64 bit\" in sys.version:\n # a 64bit Python should also look in the 32bit registry\n sam_flags.append(_winreg.KEY_WOW64_32KEY)\n else:\n # possibly a 32bit Python on 64bit Windows, so look in\n # the 64bit registry incase there is a 64bit app.\n sam_flags.append(_winreg.KEY_WOW64_64KEY)\n for sam_flag in sam_flags:\n try:\n # assumes self.app_name is defined, as it should be for\n # implementors\n keyname = r\"Software\\Mozilla\\Mozilla %s\" % self.app_name\n sam = _winreg.KEY_READ | sam_flag\n app_key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, keyname, 0, sam)\n version, _type = _winreg.QueryValueEx(app_key, \"CurrentVersion\")\n version_key = _winreg.OpenKey(app_key, version + r\"\\Main\")\n path, _ = _winreg.QueryValueEx(version_key, \"PathToExe\")\n return path\n except _winreg.error:\n pass\n\n # search for the binary in the path \n for name in reversed(self.names):\n binary = findInPath(name)\n if sys.platform == 'cygwin':\n program_files = os.environ['PROGRAMFILES']\n else:\n program_files = os.environ['ProgramFiles']\n\n if binary is None:\n for bin in [(program_files, 'Mozilla Firefox', 'firefox.exe'),\n (os.environ.get(\"ProgramFiles(x86)\"),'Mozilla Firefox', 'firefox.exe'),\n (program_files, 'Nightly', 'firefox.exe'),\n (os.environ.get(\"ProgramFiles(x86)\"),'Nightly', 'firefox.exe'),\n (program_files, 'Aurora', 'firefox.exe'),\n (os.environ.get(\"ProgramFiles(x86)\"),'Aurora', 'firefox.exe')\n ]:\n path = os.path.join(*bin)\n if os.path.isfile(path):\n binary = path\n break\n elif sys.platform == 'darwin':\n for bundle_name in self.bundle_names:\n # Look for the application bundle in the user's home directory\n # or the system-wide /Applications directory. If we don't find\n # it in one of those locations, we move on to the next possible\n # bundle name.\n appdir = os.path.join(\"~/Applications/%s.app\" % bundle_name)\n if not os.path.isdir(appdir):\n appdir = \"/Applications/%s.app\" % bundle_name\n if not os.path.isdir(appdir):\n continue\n\n # Look for a binary with any of the possible binary names\n # inside the application bundle.\n for binname in self.names:\n binpath = os.path.join(appdir,\n \"Contents/MacOS/%s-bin\" % binname)\n if (os.path.isfile(binpath)):\n binary = binpath\n break\n\n if binary:\n break\n\n if binary is None:\n raise Exception('Mozrunner could not locate your binary, you will need to set it.')\n return binary\n\n @property\n def command(self):\n \"\"\"Returns the command list to run.\"\"\"\n cmd = [self.binary, '-profile', self.profile.profile]\n # On i386 OS X machines, i386+x86_64 universal binaries need to be told\n # to run as i386 binaries. If we're not running a i386+x86_64 universal\n # binary, then this command modification is harmless.\n if sys.platform == 'darwin':\n if hasattr(platform, 'architecture') and platform.architecture()[0] == '32bit':\n cmd = ['arch', '-i386'] + cmd\n return cmd\n\n def get_repositoryInfo(self):\n \"\"\"Read repository information from application.ini and platform.ini.\"\"\"\n import ConfigParser\n\n config = ConfigParser.RawConfigParser()\n dirname = os.path.dirname(self.binary)\n repository = { }\n\n for entry in [['application', 'App'], ['platform', 'Build']]:\n (file, section) = entry\n config.read(os.path.join(dirname, '%s.ini' % file))\n\n for entry in [['SourceRepository', 'repository'], ['SourceStamp', 'changeset']]:\n (key, id) = entry\n\n try:\n repository['%s_%s' % (file, id)] = config.get(section, key);\n except:\n repository['%s_%s' % (file, id)] = None\n\n return repository\n\n def start(self):\n \"\"\"Run self.command in the proper environment.\"\"\"\n if self.profile is None:\n self.profile = self.profile_class()\n self.process_handler = run_command(self.command+self.cmdargs, self.env, **self.kp_kwargs)\n\n def wait(self, timeout=None):\n \"\"\"Wait for the browser to exit.\"\"\"\n self.process_handler.wait(timeout=timeout)\n\n if sys.platform != 'win32':\n for name in self.names:\n for pid in get_pids(name, self.process_handler.pid):\n self.process_handler.pid = pid\n self.process_handler.wait(timeout=timeout)\n\n def kill(self, kill_signal=signal.SIGTERM):\n \"\"\"Kill the browser\"\"\"\n if sys.platform != 'win32':\n self.process_handler.kill()\n for name in self.names:\n for pid in get_pids(name, self.process_handler.pid):\n self.process_handler.pid = pid\n self.process_handler.kill()\n else:\n try:\n self.process_handler.kill(group=True)\n # On windows, it sometimes behooves one to wait for dust to settle\n # after killing processes. Let's try that.\n # TODO: Bug 640047 is invesitgating the correct way to handle this case\n self.process_handler.wait(timeout=10)\n except Exception, e:\n logger.error('Cannot kill process, '+type(e).__name__+' '+e.message)\n\n def stop(self):\n self.kill()\n\nclass FirefoxRunner(Runner):\n \"\"\"Specialized Runner subclass for running Firefox.\"\"\"\n\n app_name = 'Firefox'\n profile_class = FirefoxProfile\n\n # The possible names of application bundles on Mac OS X, in order of\n # preference from most to least preferred.\n # Note: Nightly is obsolete, as it has been renamed to FirefoxNightly,\n # but it will still be present if users update an older nightly build\n # only via the app update service.\n bundle_names = ['Firefox', 'FirefoxNightly', 'Nightly']\n\n @property\n def names(self):\n if sys.platform == 'darwin':\n return ['firefox', 'nightly', 'shiretoko']\n if sys.platform in ('linux2', 'sunos5', 'solaris') \\\n or sys.platform.startswith('freebsd'):\n return ['firefox', 'mozilla-firefox', 'iceweasel']\n if os.name == 'nt' or sys.platform == 'cygwin':\n return ['firefox']\n\nclass ThunderbirdRunner(Runner):\n \"\"\"Specialized Runner subclass for running Thunderbird\"\"\"\n\n app_name = 'Thunderbird'\n profile_class = ThunderbirdProfile\n\n # The possible names of application bundles on Mac OS X, in order of\n # preference from most to least preferred.\n bundle_names = [\"Thunderbird\", \"Shredder\"]\n\n # The possible names of binaries, in order of preference from most to least\n # preferred.\n names = [\"thunderbird\", \"shredder\"]\n\nclass CLI(object):\n \"\"\"Command line interface.\"\"\"\n\n runner_class = FirefoxRunner\n profile_class = FirefoxProfile\n module = \"mozrunner\"\n\n parser_options = {(\"-b\", \"--binary\",): dict(dest=\"binary\", help=\"Binary path.\",\n metavar=None, default=None),\n ('-p', \"--profile\",): dict(dest=\"profile\", help=\"Profile path.\",\n metavar=None, default=None),\n ('-a', \"--addons\",): dict(dest=\"addons\", \n help=\"Addons paths to install.\",\n metavar=None, default=None),\n (\"--info\",): dict(dest=\"info\", default=False,\n action=\"store_true\",\n help=\"Print module information\")\n }\n\n def __init__(self):\n \"\"\" Setup command line parser and parse arguments \"\"\"\n self.metadata = self.get_metadata_from_egg()\n self.parser = optparse.OptionParser(version=\"%prog \" + self.metadata[\"Version\"])\n for names, opts in self.parser_options.items():\n self.parser.add_option(*names, **opts)\n (self.options, self.args) = self.parser.parse_args()\n\n if self.options.info:\n self.print_metadata()\n sys.exit(0)\n \n # XXX should use action='append' instead of rolling our own\n try:\n self.addons = self.options.addons.split(',')\n except:\n self.addons = []\n \n def get_metadata_from_egg(self):\n import pkg_resources\n ret = {}\n dist = pkg_resources.get_distribution(self.module)\n if dist.has_metadata(\"PKG-INFO\"):\n for line in dist.get_metadata_lines(\"PKG-INFO\"):\n key, value = line.split(':', 1)\n ret[key] = value\n if dist.has_metadata(\"requires.txt\"):\n ret[\"Dependencies\"] = \"\\n\" + dist.get_metadata(\"requires.txt\") \n return ret\n \n def print_metadata(self, data=(\"Name\", \"Version\", \"Summary\", \"Home-page\", \n \"Author\", \"Author-email\", \"License\", \"Platform\", \"Dependencies\")):\n for key in data:\n if key in self.metadata:\n print key + \": \" + self.metadata[key]\n\n def create_runner(self):\n \"\"\" Get the runner object \"\"\"\n runner = self.get_runner(binary=self.options.binary)\n profile = self.get_profile(binary=runner.binary,\n profile=self.options.profile,\n addons=self.addons)\n runner.profile = profile\n return runner\n\n def get_runner(self, binary=None, profile=None):\n \"\"\"Returns the runner instance for the given command line binary argument\n the profile instance returned from self.get_profile().\"\"\"\n return self.runner_class(binary, profile)\n\n def get_profile(self, binary=None, profile=None, addons=None, preferences=None):\n \"\"\"Returns the profile instance for the given command line arguments.\"\"\"\n addons = addons or []\n preferences = preferences or {}\n return self.profile_class(binary, profile, addons, preferences)\n\n def run(self):\n runner = self.create_runner()\n self.start(runner)\n runner.profile.cleanup()\n\n def start(self, runner):\n \"\"\"Starts the runner and waits for Firefox to exitor Keyboard Interrupt.\n Shoule be overwritten to provide custom running of the runner instance.\"\"\"\n runner.start()\n print 'Started:', ' '.join(runner.command)\n try:\n runner.wait()\n except KeyboardInterrupt:\n runner.stop()\n\n\ndef cli():\n CLI().run()\n"}, "files_after": {"python-lib/mozrunner/__init__.py": "# This Source Code Form is subject to the terms of the Mozilla Public\n# License, v. 2.0. If a copy of the MPL was not distributed with this\n# file, You can obtain one at http://mozilla.org/MPL/2.0/.\n\nimport os\nimport sys\nimport copy\nimport tempfile\nimport signal\nimport commands\nimport zipfile\nimport optparse\nimport killableprocess\nimport subprocess\nimport platform\nimport shutil\nfrom StringIO import StringIO\nfrom xml.dom import minidom\n\nfrom distutils import dir_util\nfrom time import sleep\n\n# conditional (version-dependent) imports\ntry:\n import simplejson\nexcept ImportError:\n import json as simplejson\n\nimport logging\nlogger = logging.getLogger(__name__)\n\n# Use dir_util for copy/rm operations because shutil is all kinds of broken\ncopytree = dir_util.copy_tree\nrmtree = dir_util.remove_tree\n\ndef findInPath(fileName, path=os.environ['PATH']):\n dirs = path.split(os.pathsep)\n for dir in dirs:\n if os.path.isfile(os.path.join(dir, fileName)):\n return os.path.join(dir, fileName)\n if os.name == 'nt' or sys.platform == 'cygwin':\n if os.path.isfile(os.path.join(dir, fileName + \".exe\")):\n return os.path.join(dir, fileName + \".exe\")\n return None\n\nstdout = sys.stdout\nstderr = sys.stderr\nstdin = sys.stdin\n\ndef run_command(cmd, env=None, **kwargs):\n \"\"\"Run the given command in killable process.\"\"\"\n killable_kwargs = {'stdout':stdout ,'stderr':stderr, 'stdin':stdin}\n killable_kwargs.update(kwargs)\n\n if sys.platform != \"win32\":\n return killableprocess.Popen(cmd, preexec_fn=lambda : os.setpgid(0, 0),\n env=env, **killable_kwargs)\n else:\n return killableprocess.Popen(cmd, env=env, **killable_kwargs)\n\ndef getoutput(l):\n tmp = tempfile.mktemp()\n x = open(tmp, 'w')\n subprocess.call(l, stdout=x, stderr=x)\n x.close(); x = open(tmp, 'r')\n r = x.read() ; x.close()\n os.remove(tmp)\n return r\n\ndef get_pids(name, minimun_pid=0):\n \"\"\"Get all the pids matching name, exclude any pids below minimum_pid.\"\"\"\n if os.name == 'nt' or sys.platform == 'cygwin':\n import wpk\n\n pids = wpk.get_pids(name)\n\n else:\n data = getoutput(['ps', 'ax']).splitlines()\n pids = [int(line.split()[0]) for line in data if line.find(name) is not -1]\n\n matching_pids = [m for m in pids if m > minimun_pid]\n return matching_pids\n\ndef makedirs(name):\n\n head, tail = os.path.split(name)\n if not tail:\n head, tail = os.path.split(head)\n if head and tail and not os.path.exists(head):\n try:\n makedirs(head)\n except OSError, e:\n pass\n if tail == os.curdir: # xxx/newdir/. exists if xxx/newdir exists\n return\n try:\n os.mkdir(name)\n except:\n pass\n\n# addon_details() copied from mozprofile\ndef addon_details(install_rdf_fh):\n \"\"\"\n returns a dictionary of details about the addon\n - addon_path : path to the addon directory\n Returns:\n {'id': u'rainbow@colors.org', # id of the addon\n 'version': u'1.4', # version of the addon\n 'name': u'Rainbow', # name of the addon\n 'unpack': # whether to unpack the addon\n \"\"\"\n\n details = {\n 'id': None,\n 'unpack': False,\n 'name': None,\n 'version': None\n }\n\n def get_namespace_id(doc, url):\n attributes = doc.documentElement.attributes\n namespace = \"\"\n for i in range(attributes.length):\n if attributes.item(i).value == url:\n if \":\" in attributes.item(i).name:\n # If the namespace is not the default one remove 'xlmns:'\n namespace = attributes.item(i).name.split(':')[1] + \":\"\n break\n return namespace\n\n def get_text(element):\n \"\"\"Retrieve the text value of a given node\"\"\"\n rc = []\n for node in element.childNodes:\n if node.nodeType == node.TEXT_NODE:\n rc.append(node.data)\n return ''.join(rc).strip()\n\n doc = minidom.parse(install_rdf_fh)\n\n # Get the namespaces abbreviations\n em = get_namespace_id(doc, \"http://www.mozilla.org/2004/em-rdf#\")\n rdf = get_namespace_id(doc, \"http://www.w3.org/1999/02/22-rdf-syntax-ns#\")\n\n description = doc.getElementsByTagName(rdf + \"Description\").item(0)\n for node in description.childNodes:\n # Remove the namespace prefix from the tag for comparison\n entry = node.nodeName.replace(em, \"\")\n if entry in details.keys():\n details.update({ entry: get_text(node) })\n\n # turn unpack into a true/false value\n if isinstance(details['unpack'], basestring):\n details['unpack'] = details['unpack'].lower() == 'true'\n\n return details\n\nclass Profile(object):\n \"\"\"Handles all operations regarding profile. Created new profiles, installs extensions,\n sets preferences and handles cleanup.\"\"\"\n\n def __init__(self, binary=None, profile=None, addons=None,\n preferences=None):\n\n self.binary = binary\n\n self.create_new = not(bool(profile))\n if profile:\n self.profile = profile\n else:\n self.profile = self.create_new_profile(self.binary)\n\n self.addons_installed = []\n self.addons = addons or []\n\n ### set preferences from class preferences\n preferences = preferences or {}\n if hasattr(self.__class__, 'preferences'):\n self.preferences = self.__class__.preferences.copy()\n else:\n self.preferences = {}\n self.preferences.update(preferences)\n\n for addon in self.addons:\n self.install_addon(addon)\n\n self.set_preferences(self.preferences)\n\n def create_new_profile(self, binary):\n \"\"\"Create a new clean profile in tmp which is a simple empty folder\"\"\"\n profile = tempfile.mkdtemp(suffix='.mozrunner')\n return profile\n\n def unpack_addon(self, xpi_zipfile, addon_path):\n for name in xpi_zipfile.namelist():\n if name.endswith('/'):\n makedirs(os.path.join(addon_path, name))\n else:\n if not os.path.isdir(os.path.dirname(os.path.join(addon_path, name))):\n makedirs(os.path.dirname(os.path.join(addon_path, name)))\n data = xpi_zipfile.read(name)\n f = open(os.path.join(addon_path, name), 'wb')\n f.write(data) ; f.close()\n zi = xpi_zipfile.getinfo(name)\n os.chmod(os.path.join(addon_path,name), (zi.external_attr>>16))\n\n def install_addon(self, path):\n \"\"\"Installs the given addon or directory of addons in the profile.\"\"\"\n\n extensions_path = os.path.join(self.profile, 'extensions')\n if not os.path.exists(extensions_path):\n os.makedirs(extensions_path)\n\n addons = [path]\n if not path.endswith('.xpi') and not os.path.exists(os.path.join(path, 'install.rdf')):\n addons = [os.path.join(path, x) for x in os.listdir(path)]\n\n for addon in addons:\n if addon.endswith('.xpi'):\n xpi_zipfile = zipfile.ZipFile(addon, \"r\")\n details = addon_details(StringIO(xpi_zipfile.read('install.rdf')))\n addon_path = os.path.join(extensions_path, details[\"id\"])\n if details.get(\"unpack\", True):\n self.unpack_addon(xpi_zipfile, addon_path)\n self.addons_installed.append(addon_path)\n else:\n shutil.copy(addon, addon_path + '.xpi')\n else:\n # it's already unpacked, but we need to extract the id so we\n # can copy it\n details = addon_details(open(os.path.join(addon, \"install.rdf\"), \"rb\"))\n addon_path = os.path.join(extensions_path, details[\"id\"])\n shutil.copytree(addon, addon_path, symlinks=True)\n\n def set_preferences(self, preferences):\n \"\"\"Adds preferences dict to profile preferences\"\"\"\n prefs_file = os.path.join(self.profile, 'user.js')\n # Ensure that the file exists first otherwise create an empty file\n if os.path.isfile(prefs_file):\n f = open(prefs_file, 'a+')\n else:\n f = open(prefs_file, 'w')\n\n f.write('\\n#MozRunner Prefs Start\\n')\n\n pref_lines = ['user_pref(%s, %s);' %\n (simplejson.dumps(k), simplejson.dumps(v) ) for k, v in\n preferences.items()]\n for line in pref_lines:\n f.write(line+'\\n')\n f.write('#MozRunner Prefs End\\n')\n f.flush() ; f.close()\n\n def pop_preferences(self):\n \"\"\"\n pop the last set of preferences added\n returns True if popped\n \"\"\"\n\n # our magic markers\n delimeters = ('#MozRunner Prefs Start', '#MozRunner Prefs End')\n\n lines = file(os.path.join(self.profile, 'user.js')).read().splitlines()\n def last_index(_list, value):\n \"\"\"\n returns the last index of an item;\n this should actually be part of python code but it isn't\n \"\"\"\n for index in reversed(range(len(_list))):\n if _list[index] == value:\n return index\n s = last_index(lines, delimeters[0])\n e = last_index(lines, delimeters[1])\n\n # ensure both markers are found\n if s is None:\n assert e is None, '%s found without %s' % (delimeters[1], delimeters[0])\n return False # no preferences found\n elif e is None:\n assert e is None, '%s found without %s' % (delimeters[0], delimeters[1])\n\n # ensure the markers are in the proper order\n assert e > s, '%s found at %s, while %s found at %s' % (delimeters[1], e, delimeters[0], s)\n\n # write the prefs\n cleaned_prefs = '\\n'.join(lines[:s] + lines[e+1:])\n f = file(os.path.join(self.profile, 'user.js'), 'w')\n f.write(cleaned_prefs)\n f.close()\n return True\n\n def clean_preferences(self):\n \"\"\"Removed preferences added by mozrunner.\"\"\"\n while True:\n if not self.pop_preferences():\n break\n\n def clean_addons(self):\n \"\"\"Cleans up addons in the profile.\"\"\"\n for addon in self.addons_installed:\n if os.path.isdir(addon):\n rmtree(addon)\n\n def cleanup(self):\n \"\"\"Cleanup operations on the profile.\"\"\"\n def oncleanup_error(function, path, excinfo):\n #TODO: How should we handle this?\n print \"Error Cleaning up: \" + str(excinfo[1])\n if self.create_new:\n shutil.rmtree(self.profile, False, oncleanup_error)\n else:\n self.clean_preferences()\n self.clean_addons()\n\nclass FirefoxProfile(Profile):\n \"\"\"Specialized Profile subclass for Firefox\"\"\"\n preferences = {# Don't automatically update the application\n 'app.update.enabled' : False,\n # Don't restore the last open set of tabs if the browser has crashed\n 'browser.sessionstore.resume_from_crash': False,\n # Don't check for the default web browser\n 'browser.shell.checkDefaultBrowser' : False,\n # Don't warn on exit when multiple tabs are open\n 'browser.tabs.warnOnClose' : False,\n # Don't warn when exiting the browser\n 'browser.warnOnQuit': False,\n # Only install add-ons from the profile and the app folder\n 'extensions.enabledScopes' : 5,\n # Don't automatically update add-ons\n 'extensions.update.enabled' : False,\n # Don't open a dialog to show available add-on updates\n 'extensions.update.notifyUser' : False,\n }\n\n # The possible names of application bundles on Mac OS X, in order of\n # preference from most to least preferred.\n # Note: Nightly is obsolete, as it has been renamed to FirefoxNightly,\n # but it will still be present if users update an older nightly build\n # via the app update service.\n bundle_names = ['Firefox', 'FirefoxNightly', 'Nightly']\n\n # The possible names of binaries, in order of preference from most to least\n # preferred.\n @property\n def names(self):\n if sys.platform == 'darwin':\n return ['firefox', 'nightly', 'shiretoko']\n if (sys.platform == 'linux2') or (sys.platform in ('sunos5', 'solaris')):\n return ['firefox', 'mozilla-firefox', 'iceweasel']\n if os.name == 'nt' or sys.platform == 'cygwin':\n return ['firefox']\n\nclass ThunderbirdProfile(Profile):\n preferences = {'extensions.update.enabled' : False,\n 'extensions.update.notifyUser' : False,\n 'browser.shell.checkDefaultBrowser' : False,\n 'browser.tabs.warnOnClose' : False,\n 'browser.warnOnQuit': False,\n 'browser.sessionstore.resume_from_crash': False,\n }\n\n # The possible names of application bundles on Mac OS X, in order of\n # preference from most to least preferred.\n bundle_names = [\"Thunderbird\", \"Shredder\"]\n\n # The possible names of binaries, in order of preference from most to least\n # preferred.\n names = [\"thunderbird\", \"shredder\"]\n\n\nclass Runner(object):\n \"\"\"Handles all running operations. Finds bins, runs and kills the process.\"\"\"\n\n def __init__(self, binary=None, profile=None, cmdargs=[], env=None,\n kp_kwargs={}):\n if binary is None:\n self.binary = self.find_binary()\n elif sys.platform == 'darwin' and binary.find('Contents/MacOS/') == -1:\n self.binary = os.path.join(binary, 'Contents/MacOS/%s-bin' % self.names[0])\n else:\n self.binary = binary\n\n if not os.path.exists(self.binary):\n raise Exception(\"Binary path does not exist \"+self.binary)\n\n if sys.platform == 'linux2' and self.binary.endswith('-bin'):\n dirname = os.path.dirname(self.binary)\n if os.environ.get('LD_LIBRARY_PATH', None):\n os.environ['LD_LIBRARY_PATH'] = '%s:%s' % (os.environ['LD_LIBRARY_PATH'], dirname)\n else:\n os.environ['LD_LIBRARY_PATH'] = dirname\n\n # Disable the crash reporter by default\n os.environ['MOZ_CRASHREPORTER_NO_REPORT'] = '1'\n\n self.profile = profile\n\n self.cmdargs = cmdargs\n if env is None:\n self.env = copy.copy(os.environ)\n self.env.update({'MOZ_NO_REMOTE':\"1\",})\n else:\n self.env = env\n self.kp_kwargs = kp_kwargs or {}\n\n def find_binary(self):\n \"\"\"Finds the binary for self.names if one was not provided.\"\"\"\n binary = None\n if sys.platform in ('linux2', 'sunos5', 'solaris') \\\n or sys.platform.startswith('freebsd'):\n for name in reversed(self.names):\n binary = findInPath(name)\n elif os.name == 'nt' or sys.platform == 'cygwin':\n\n # find the default executable from the windows registry\n try:\n import _winreg\n except ImportError:\n pass\n else:\n sam_flags = [0]\n # KEY_WOW64_32KEY etc only appeared in 2.6+, but that's OK as\n # only 2.6+ has functioning 64bit builds.\n if hasattr(_winreg, \"KEY_WOW64_32KEY\"):\n if \"64 bit\" in sys.version:\n # a 64bit Python should also look in the 32bit registry\n sam_flags.append(_winreg.KEY_WOW64_32KEY)\n else:\n # possibly a 32bit Python on 64bit Windows, so look in\n # the 64bit registry incase there is a 64bit app.\n sam_flags.append(_winreg.KEY_WOW64_64KEY)\n for sam_flag in sam_flags:\n try:\n # assumes self.app_name is defined, as it should be for\n # implementors\n keyname = r\"Software\\Mozilla\\Mozilla %s\" % self.app_name\n sam = _winreg.KEY_READ | sam_flag\n app_key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, keyname, 0, sam)\n version, _type = _winreg.QueryValueEx(app_key, \"CurrentVersion\")\n version_key = _winreg.OpenKey(app_key, version + r\"\\Main\")\n path, _ = _winreg.QueryValueEx(version_key, \"PathToExe\")\n return path\n except _winreg.error:\n pass\n\n # search for the binary in the path \n for name in reversed(self.names):\n binary = findInPath(name)\n if sys.platform == 'cygwin':\n program_files = os.environ['PROGRAMFILES']\n else:\n program_files = os.environ['ProgramFiles']\n\n if binary is None:\n for bin in [(program_files, 'Mozilla Firefox', 'firefox.exe'),\n (os.environ.get(\"ProgramFiles(x86)\"),'Mozilla Firefox', 'firefox.exe'),\n (program_files, 'Nightly', 'firefox.exe'),\n (os.environ.get(\"ProgramFiles(x86)\"),'Nightly', 'firefox.exe'),\n (program_files, 'Aurora', 'firefox.exe'),\n (os.environ.get(\"ProgramFiles(x86)\"),'Aurora', 'firefox.exe')\n ]:\n path = os.path.join(*bin)\n if os.path.isfile(path):\n binary = path\n break\n elif sys.platform == 'darwin':\n for bundle_name in self.bundle_names:\n # Look for the application bundle in the user's home directory\n # or the system-wide /Applications directory. If we don't find\n # it in one of those locations, we move on to the next possible\n # bundle name.\n appdir = os.path.join(\"~/Applications/%s.app\" % bundle_name)\n if not os.path.isdir(appdir):\n appdir = \"/Applications/%s.app\" % bundle_name\n if not os.path.isdir(appdir):\n continue\n\n # Look for a binary with any of the possible binary names\n # inside the application bundle.\n for binname in self.names:\n binpath = os.path.join(appdir,\n \"Contents/MacOS/%s-bin\" % binname)\n if (os.path.isfile(binpath)):\n binary = binpath\n break\n\n if binary:\n break\n\n if binary is None:\n raise Exception('Mozrunner could not locate your binary, you will need to set it.')\n return binary\n\n @property\n def command(self):\n \"\"\"Returns the command list to run.\"\"\"\n cmd = [self.binary, '-profile', self.profile.profile]\n # On i386 OS X machines, i386+x86_64 universal binaries need to be told\n # to run as i386 binaries. If we're not running a i386+x86_64 universal\n # binary, then this command modification is harmless.\n if sys.platform == 'darwin':\n if hasattr(platform, 'architecture') and platform.architecture()[0] == '32bit':\n cmd = ['arch', '-i386'] + cmd\n return cmd\n\n def get_repositoryInfo(self):\n \"\"\"Read repository information from application.ini and platform.ini.\"\"\"\n import ConfigParser\n\n config = ConfigParser.RawConfigParser()\n dirname = os.path.dirname(self.binary)\n repository = { }\n\n for entry in [['application', 'App'], ['platform', 'Build']]:\n (file, section) = entry\n config.read(os.path.join(dirname, '%s.ini' % file))\n\n for entry in [['SourceRepository', 'repository'], ['SourceStamp', 'changeset']]:\n (key, id) = entry\n\n try:\n repository['%s_%s' % (file, id)] = config.get(section, key);\n except:\n repository['%s_%s' % (file, id)] = None\n\n return repository\n\n def start(self):\n \"\"\"Run self.command in the proper environment.\"\"\"\n if self.profile is None:\n self.profile = self.profile_class()\n self.process_handler = run_command(self.command+self.cmdargs, self.env, **self.kp_kwargs)\n\n def wait(self, timeout=None):\n \"\"\"Wait for the browser to exit.\"\"\"\n self.process_handler.wait(timeout=timeout)\n\n if sys.platform != 'win32':\n for name in self.names:\n for pid in get_pids(name, self.process_handler.pid):\n self.process_handler.pid = pid\n self.process_handler.wait(timeout=timeout)\n\n def kill(self, kill_signal=signal.SIGTERM):\n \"\"\"Kill the browser\"\"\"\n if sys.platform != 'win32':\n self.process_handler.kill()\n for name in self.names:\n for pid in get_pids(name, self.process_handler.pid):\n self.process_handler.pid = pid\n self.process_handler.kill()\n else:\n try:\n self.process_handler.kill(group=True)\n # On windows, it sometimes behooves one to wait for dust to settle\n # after killing processes. Let's try that.\n # TODO: Bug 640047 is invesitgating the correct way to handle this case\n self.process_handler.wait(timeout=10)\n except Exception, e:\n logger.error('Cannot kill process, '+type(e).__name__+' '+e.message)\n\n def stop(self):\n self.kill()\n\nclass FirefoxRunner(Runner):\n \"\"\"Specialized Runner subclass for running Firefox.\"\"\"\n\n app_name = 'Firefox'\n profile_class = FirefoxProfile\n\n # The possible names of application bundles on Mac OS X, in order of\n # preference from most to least preferred.\n # Note: Nightly is obsolete, as it has been renamed to FirefoxNightly,\n # but it will still be present if users update an older nightly build\n # only via the app update service.\n bundle_names = ['Firefox', 'FirefoxNightly', 'Nightly']\n\n @property\n def names(self):\n if sys.platform == 'darwin':\n return ['firefox', 'nightly', 'shiretoko']\n if sys.platform in ('linux2', 'sunos5', 'solaris') \\\n or sys.platform.startswith('freebsd'):\n return ['firefox', 'mozilla-firefox', 'iceweasel']\n if os.name == 'nt' or sys.platform == 'cygwin':\n return ['firefox']\n\nclass ThunderbirdRunner(Runner):\n \"\"\"Specialized Runner subclass for running Thunderbird\"\"\"\n\n app_name = 'Thunderbird'\n profile_class = ThunderbirdProfile\n\n # The possible names of application bundles on Mac OS X, in order of\n # preference from most to least preferred.\n bundle_names = [\"Thunderbird\", \"Shredder\"]\n\n # The possible names of binaries, in order of preference from most to least\n # preferred.\n names = [\"thunderbird\", \"shredder\"]\n\nclass CLI(object):\n \"\"\"Command line interface.\"\"\"\n\n runner_class = FirefoxRunner\n profile_class = FirefoxProfile\n module = \"mozrunner\"\n\n parser_options = {(\"-b\", \"--binary\",): dict(dest=\"binary\", help=\"Binary path.\",\n metavar=None, default=None),\n ('-p', \"--profile\",): dict(dest=\"profile\", help=\"Profile path.\",\n metavar=None, default=None),\n ('-a', \"--addons\",): dict(dest=\"addons\", \n help=\"Addons paths to install.\",\n metavar=None, default=None),\n (\"--info\",): dict(dest=\"info\", default=False,\n action=\"store_true\",\n help=\"Print module information\")\n }\n\n def __init__(self):\n \"\"\" Setup command line parser and parse arguments \"\"\"\n self.metadata = self.get_metadata_from_egg()\n self.parser = optparse.OptionParser(version=\"%prog \" + self.metadata[\"Version\"])\n for names, opts in self.parser_options.items():\n self.parser.add_option(*names, **opts)\n (self.options, self.args) = self.parser.parse_args()\n\n if self.options.info:\n self.print_metadata()\n sys.exit(0)\n \n # XXX should use action='append' instead of rolling our own\n try:\n self.addons = self.options.addons.split(',')\n except:\n self.addons = []\n \n def get_metadata_from_egg(self):\n import pkg_resources\n ret = {}\n dist = pkg_resources.get_distribution(self.module)\n if dist.has_metadata(\"PKG-INFO\"):\n for line in dist.get_metadata_lines(\"PKG-INFO\"):\n key, value = line.split(':', 1)\n ret[key] = value\n if dist.has_metadata(\"requires.txt\"):\n ret[\"Dependencies\"] = \"\\n\" + dist.get_metadata(\"requires.txt\") \n return ret\n \n def print_metadata(self, data=(\"Name\", \"Version\", \"Summary\", \"Home-page\", \n \"Author\", \"Author-email\", \"License\", \"Platform\", \"Dependencies\")):\n for key in data:\n if key in self.metadata:\n print key + \": \" + self.metadata[key]\n\n def create_runner(self):\n \"\"\" Get the runner object \"\"\"\n runner = self.get_runner(binary=self.options.binary)\n profile = self.get_profile(binary=runner.binary,\n profile=self.options.profile,\n addons=self.addons)\n runner.profile = profile\n return runner\n\n def get_runner(self, binary=None, profile=None):\n \"\"\"Returns the runner instance for the given command line binary argument\n the profile instance returned from self.get_profile().\"\"\"\n return self.runner_class(binary, profile)\n\n def get_profile(self, binary=None, profile=None, addons=None, preferences=None):\n \"\"\"Returns the profile instance for the given command line arguments.\"\"\"\n addons = addons or []\n preferences = preferences or {}\n return self.profile_class(binary, profile, addons, preferences)\n\n def run(self):\n runner = self.create_runner()\n self.start(runner)\n runner.profile.cleanup()\n\n def start(self, runner):\n \"\"\"Starts the runner and waits for Firefox to exitor Keyboard Interrupt.\n Shoule be overwritten to provide custom running of the runner instance.\"\"\"\n runner.start()\n print 'Started:', ' '.join(runner.command)\n try:\n runner.wait()\n except KeyboardInterrupt:\n runner.stop()\n\n\ndef cli():\n CLI().run()\n"}} -{"repo": "aeschright/calagator", "pr_number": 1, "title": "Rical remodel", "state": "closed", "merged_at": "2010-10-30T23:43:55Z", "additions": 1, "deletions": 1, "files_changed": ["app/models/source_parser/ical.rb"], "files_before": {"app/models/source_parser/ical.rb": "class SourceParser # :nodoc:\n # == SourceParser::Ical\n #\n # Reads iCalendar events.\n #\n # Example:\n # abstract_events = SourceParser::Ical.to_abstract_events('http://upcoming.yahoo.com/calendar/v2/event/349225')\n #\n # Sample sources:\n # http://upcoming.yahoo.com/calendar/v2/event/349225\n # webcal://appendix.23ae.com/calendars/AlternateHolidays.ics\n # http://appendix.23ae.com/calendars/AlternateHolidays.ics\n class Ical < Base\n label :iCalendar\n\n # Override Base::read_url to handle \"webcal\" scheme addresses.\n def self.read_url(url)\n super(url.gsub(/^webcal:/, 'http:'))\n end\n \n # Helper to set the start and end dates correctly depending on whether it's a floating or fixed timezone\n def self.dates_for_tz(component, event)\n if component.dtstart_property.tzid.nil?\n event.start_time = Time.parse(component.dtstart_property.value)\n if component.dtend_property.nil?\n if component.duration\n event.end_time = component.duration_property.add_to_date_time_value(event.start_time)\n else\n event.end_time = event.start_time\n end\n else\n event.end_time = Time.parse(component.dtend_property.value)\n end\n else\n event.start_time = component.dtstart\n event.end_time = component.dtend\n end\n rescue RiCal::InvalidTimezoneIdentifier\n event.start_time = Time.parse(component.dtstart_property.to_s)\n event.end_time = Time.parse(component.dtend_property.to_s)\n end\n\n CALENDAR_CONTENT_RE = /^BEGIN:VCALENDAR.*?^END:VCALENDAR/m\n EVENT_CONTENT_RE = /^BEGIN:VEVENT.*?^END:VEVENT/m\n EVENT_DTSTART_RE = /^DTSTART.*?:([^\\r\\n$]+)/m\n EVENT_DTEND_RE = /^DTEND.*?:([^\\r\\n$]+)/m\n VENUE_CONTENT_RE = /^BEGIN:VVENUE$.*?^END:VVENUE$/m\n VENUE_CONTENT_BEGIN_RE = /^BEGIN:VVENUE$/m\n VENUE_CONTENT_END_RE = /^END:VVENUE$/m\n IS_UPCOMING_RE = /^PRODID:\\W+Upcoming/m\n\n # Return an Array of AbstractEvent instances extracted from an iCalendar input.\n #\n # Options:\n # * :url -- URL of iCalendar data to import\n # * :content -- String of iCalendar data to import\n # * :skip_old -- Should old events be skipped? Default is true.\n def self.to_abstract_events(opts={})\n # Skip old events by default\n \n opts[:skip_old] = true unless opts[:skip_old] == false\n cutoff = Time.now.yesterday\n\n content = content_for(opts).gsub(/\\r\\n/, \"\\n\")\n\n # Provide special handling for Upcoming's broken implementation of iCalendar\n if content.match(IS_UPCOMING_RE)\n # Strip out superflous self-referential Upcoming link\n content.sub!(%r{\\s*\\[\\s*Full details at http://upcoming.yahoo.com/event/\\d+/?\\s*\\]\\s*}m, '')\n\n # Fix newlines in DESCRIPTION, replace them with escaped '\\n' strings.\n matches = content.scan(/^(DESCRIPTION:.+?)(?:^\\w+[:;])/m)\n matches.each do |match|\n content.sub!(match[0], match[0].strip.gsub(/\\n/, '\\n')+\"\\r\\n\")\n end\n end\n\n events = []\n content_calendars = RiCal.parse_string(content)\n content_calendars.each do |content_calendar|\n content_calendar.events.each_with_index do |component, index|\n next if opts[:skip_old] && (component.dtend || component.dtstart).to_time < cutoff\n event = AbstractEvent.new\n event.title = component.summary\n event.description = component.description\n event.url = component.url\n\n SourceParser::Ical.dates_for_tz(component, event)\n\n content_venues = content_calendar.to_s.scan(VENUE_CONTENT_RE)\n\n content_venue = \\\n begin\n if content_calendar.to_s.match(%r{VALUE=URI:http://upcoming.yahoo.com/})\n # Special handling for Upcoming, where each event maps 1:1 to a venue\n content_venues[index]\n else\n begin \n # finding the event venue id - VVENUE=V0-001-001423875-1@eventful.com\n venue_uid = component.location_property.params[\"VVENUE\"]\n # finding in the content_venues array an item matching the uid\n venue_uid ? content_venues.find{|content_venue| content_venue.match(/^UID:#{venue_uid}$/m)} : nil\n rescue Exception => e\n # Ignore\n RAILS_DEFAULT_LOGGER.info(\"SourceParser::Ical.to_abstract_events : Failed to parse content_venue for non-Upcoming event -- #{e}\")\n nil\n end\n end\n end\n\n event.location = to_abstract_location(content_venue, :fallback => component.location)\n events << event\n end\n end\n\n return events\n end\n\n\n # Return an AbstractLocation extracted from an iCalendar input.\n #\n # Arguments:\n # * value - String with iCalendar data to parse which contains a Vvenue item.\n #\n # Options:\n # * :fallback - String to use as the title for the location if the +value+ doesn't contain a Vvenue.\n def self.to_abstract_location(value, opts={})\n value = \"\" if value.nil?\n a = AbstractLocation.new\n \n # VVENUE entries are considered just Vcards,\n # treating them as such.\n if vcard_content = value.scan(VENUE_CONTENT_RE).first\n \n vcard_hash = parse_vcard_content(vcard_content)\n\n a.title = vcard_hash['NAME']\n a.street_address = vcard_hash['ADDRESS']\n a.locality = vcard_hash['CITY']\n a.region = vcard_hash['REGION']\n a.postal_code = vcard_hash['POSTALCODE']\n a.country = vcard_hash['COUNTRY']\n\n a.latitude, a.longitude = vcard_hash['GEO'].split(/;/).map(&:to_f)\n\n return a\n end\n \n if opts[:fallback].blank?\n return nil\n else\n a.title = opts[:fallback]\n return a\n end\n end\n \n\n\n # Return a vcard_hash from vcard content.\n #\n # Arguments:\n # * value - String with content\n #\n #\n \n def self.parse_vcard_content(value)\n vcards = RiCal.parse_string(value)\n #constrain to 1 vcard per vvenue\n vcard = vcards.first\n # this is an interesting call here\n # RiCal export of nonstandard-outside-of-RFC2445\n # VVENUE into lines\n \n vcard_lines = vcard.export_properties_to(STDOUT)\n # munges vcard lines \n vcard_hash = v_card_munge(vcard_lines)\n\n return vcard_hash \n end\n\n\n # Return a vcard_hash from vcard_lines.\n #\n # Arguments:\n # * value - vcard_lines\n #\n # \n # \n\n def self.v_card_munge(value)\n vcard_hash = value.mash do |line|\n # predeclare key, value in case no match\n key = ''\n value = ''\n # if line is of the form key:value\n # where the line has at least one colon\n # do a non-greedy capture of chars not colon\n # followed by a promiscuous match of remaining chars \n if line.match(/^([^:]+?):(.*)$/)\n key = $1\n value = $2\n # if the key has a semi-colon, it is, by spec, \n # followed by a meta-qualifier; \n # in all cases, we only want the key and not the qualifier\n # split always at least returns one item\n # which will always be the item we want\n # we only want the first: drop the second on match semi-colon\n key = key.split(';').first\n end\n [key, value]\n end\n return vcard_hash\n end\n\n #\n end\nend\n\n\n"}, "files_after": {"app/models/source_parser/ical.rb": "class SourceParser # :nodoc:\n # == SourceParser::Ical\n #\n # Reads iCalendar events.\n #\n # Example:\n # abstract_events = SourceParser::Ical.to_abstract_events('http://upcoming.yahoo.com/calendar/v2/event/349225')\n #\n # Sample sources:\n # http://upcoming.yahoo.com/calendar/v2/event/349225\n # webcal://appendix.23ae.com/calendars/AlternateHolidays.ics\n # http://appendix.23ae.com/calendars/AlternateHolidays.ics\n class Ical < Base\n label :iCalendar\n\n # Override Base::read_url to handle \"webcal\" scheme addresses.\n def self.read_url(url)\n super(url.gsub(/^webcal:/, 'http:'))\n end\n \n # Helper to set the start and end dates correctly depending on whether it's a floating or fixed timezone\n def self.dates_for_tz(component, event)\n if component.dtstart_property.tzid.nil?\n event.start_time = Time.parse(component.dtstart_property.value)\n if component.dtend_property.nil?\n if component.duration\n event.end_time = component.duration_property.add_to_date_time_value(event.start_time)\n else\n event.end_time = event.start_time\n end\n else\n event.end_time = Time.parse(component.dtend_property.value)\n end\n else\n event.start_time = component.dtstart\n event.end_time = component.dtend\n end\n rescue RiCal::InvalidTimezoneIdentifier\n event.start_time = Time.parse(component.dtstart_property.to_s)\n event.end_time = Time.parse(component.dtend_property.to_s)\n end\n\n CALENDAR_CONTENT_RE = /^BEGIN:VCALENDAR.*?^END:VCALENDAR/m\n EVENT_CONTENT_RE = /^BEGIN:VEVENT.*?^END:VEVENT/m\n EVENT_DTSTART_RE = /^DTSTART.*?:([^\\r\\n$]+)/m\n EVENT_DTEND_RE = /^DTEND.*?:([^\\r\\n$]+)/m\n VENUE_CONTENT_RE = /^BEGIN:VVENUE$.*?^END:VVENUE$/m\n VENUE_CONTENT_BEGIN_RE = /^BEGIN:VVENUE$/m\n VENUE_CONTENT_END_RE = /^END:VVENUE$/m\n IS_UPCOMING_RE = /^PRODID:\\W+Upcoming/m\n\n # Return an Array of AbstractEvent instances extracted from an iCalendar input.\n #\n # Options:\n # * :url -- URL of iCalendar data to import\n # * :content -- String of iCalendar data to import\n # * :skip_old -- Should old events be skipped? Default is true.\n def self.to_abstract_events(opts={})\n # Skip old events by default\n \n opts[:skip_old] = true unless opts[:skip_old] == false\n cutoff = Time.now.yesterday\n\n content = content_for(opts).gsub(/\\r\\n/, \"\\n\")\n\n # Provide special handling for Upcoming's broken implementation of iCalendar\n if content.match(IS_UPCOMING_RE)\n # Strip out superflous self-referential Upcoming link\n content.sub!(%r{\\s*\\[\\s*Full details at http://upcoming.yahoo.com/event/\\d+/?\\s*\\]\\s*}m, '')\n\n # Fix newlines in DESCRIPTION, replace them with escaped '\\n' strings.\n matches = content.scan(/^(DESCRIPTION:.+?)(?:^\\w+[:;])/m)\n matches.each do |match|\n content.sub!(match[0], match[0].strip.gsub(/\\n/, '\\n')+\"\\r\\n\")\n end\n end\n\n events = []\n content_calendars = RiCal.parse_string(content)\n content_calendars.each do |content_calendar|\n content_calendar.events.each_with_index do |component, index|\n next if opts[:skip_old] && (component.dtend || component.dtstart).to_time < cutoff\n event = AbstractEvent.new\n event.title = component.summary\n event.description = component.description\n event.url = component.url\n\n SourceParser::Ical.dates_for_tz(component, event)\n\n content_venues = content_calendar.to_s.scan(VENUE_CONTENT_RE)\n\n content_venue = \\\n begin\n if content_calendar.to_s.match(%r{VALUE=URI:http://upcoming.yahoo.com/})\n # Special handling for Upcoming, where each event maps 1:1 to a venue\n content_venues[index]\n else\n begin \n # finding the event venue id - VVENUE=V0-001-001423875-1@eventful.com\n venue_uid = component.location_property.params[\"VVENUE\"]\n # finding in the content_venues array an item matching the uid\n venue_uid ? content_venues.find{|content_venue| content_venue.match(/^UID:#{venue_uid}$/m)} : nil\n rescue Exception => e\n # Ignore\n RAILS_DEFAULT_LOGGER.info(\"SourceParser::Ical.to_abstract_events : Failed to parse content_venue for non-Upcoming event -- #{e}\")\n nil\n end\n end\n end\n\n event.location = to_abstract_location(content_venue, :fallback => component.location)\n events << event\n end\n end\n\n return events\n end\n\n\n # Return an AbstractLocation extracted from an iCalendar input.\n #\n # Arguments:\n # * value - String with iCalendar data to parse which contains a Vvenue item.\n #\n # Options:\n # * :fallback - String to use as the title for the location if the +value+ doesn't contain a Vvenue.\n def self.to_abstract_location(value, opts={})\n value = \"\" if value.nil?\n a = AbstractLocation.new\n \n # VVENUE entries are considered just Vcards,\n # treating them as such.\n if vcard_content = value.scan(VENUE_CONTENT_RE).first\n \n vcard_hash = parse_vcard_content(vcard_content)\n\n a.title = vcard_hash['NAME']\n a.street_address = vcard_hash['ADDRESS']\n a.locality = vcard_hash['CITY']\n a.region = vcard_hash['REGION']\n a.postal_code = vcard_hash['POSTALCODE']\n a.country = vcard_hash['COUNTRY']\n\n a.latitude, a.longitude = vcard_hash['GEO'].split(/;/).map(&:to_f)\n\n return a\n end\n \n if opts[:fallback].blank?\n return nil\n else\n a.title = opts[:fallback]\n return a\n end\n end\n \n\n\n # Return a vcard_hash from vcard content.\n #\n # Arguments:\n # * value - String with content\n #\n #\n \n def self.parse_vcard_content(value)\n vcards = RiCal.parse_string(value)\n #constrain to 1 vcard per vvenue\n vcard = vcards.first\n # this is an interesting call here\n # RiCal export of nonstandard-outside-of-RFC2445\n # VVENUE into lines\n \n vcard_lines = vcard.export_properties_to(StringIO.new(''))\n # munges vcard lines \n vcard_hash = v_card_munge(vcard_lines)\n\n return vcard_hash \n end\n\n\n # Return a vcard_hash from vcard_lines.\n #\n # Arguments:\n # * value - vcard_lines\n #\n # \n # \n\n def self.v_card_munge(value)\n vcard_hash = value.mash do |line|\n # predeclare key, value in case no match\n key = ''\n value = ''\n # if line is of the form key:value\n # where the line has at least one colon\n # do a non-greedy capture of chars not colon\n # followed by a promiscuous match of remaining chars \n if line.match(/^([^:]+?):(.*)$/)\n key = $1\n value = $2\n # if the key has a semi-colon, it is, by spec, \n # followed by a meta-qualifier; \n # in all cases, we only want the key and not the qualifier\n # split always at least returns one item\n # which will always be the item we want\n # we only want the first: drop the second on match semi-colon\n key = key.split(';').first\n end\n [key, value]\n end\n return vcard_hash\n end\n\n #\n end\nend\n\n\n"}} -{"repo": "mozilla/zamboni", "pr_number": 3542, "title": "Remove solitude auth check from monitor Bug 1311724", "state": "closed", "merged_at": "2016-12-19T17:54:25Z", "additions": 0, "deletions": 14, "files_changed": ["mkt/site/monitors.py"], "files_before": {"mkt/site/monitors.py": "import os\nimport socket\nimport StringIO\nimport tempfile\nimport time\nimport traceback\n\nfrom django.conf import settings\n\nimport commonware.log\nimport elasticsearch\nimport requests\nfrom cache_nuggets.lib import memoize\nfrom PIL import Image\n\nfrom lib.crypto import packaged, receipt\nfrom lib.crypto.packaged import SigningError as PackageSigningError\nfrom lib.crypto.receipt import SigningError\nfrom lib.pay_server import client\nfrom mkt.site.storage_utils import local_storage\n\n\nmonitor_log = commonware.log.getLogger('z.monitor')\n\n\ndef memcache():\n memcache = getattr(settings, 'CACHES', {}).get('default')\n memcache_results = []\n status = ''\n if memcache and 'memcache' in memcache['BACKEND']:\n hosts = memcache['LOCATION']\n using_twemproxy = False\n if not isinstance(hosts, (tuple, list)):\n hosts = [hosts]\n for host in hosts:\n ip, port = host.split(':')\n\n if ip == '127.0.0.1':\n using_twemproxy = True\n\n try:\n s = socket.socket()\n s.connect((ip, int(port)))\n except Exception, e:\n result = False\n status = 'Failed to connect to memcached (%s): %s' % (host, e)\n monitor_log.critical(status)\n else:\n result = True\n finally:\n s.close()\n\n memcache_results.append((ip, port, result))\n if (not using_twemproxy and len(hosts) > 1 and\n len(memcache_results) < 2):\n # If the number of requested hosts is greater than 1, but less\n # than 2 replied, raise an error.\n status = ('2+ memcache servers are required.'\n '%s available') % len(memcache_results)\n monitor_log.warning(status)\n\n # If we are in debug mode, don't worry about checking for memcache.\n elif settings.DEBUG:\n return status, []\n\n if not memcache_results:\n status = 'Memcache is not configured'\n monitor_log.info(status)\n\n return status, memcache_results\n\n\ndef libraries():\n # Check Libraries and versions\n libraries_results = []\n status = ''\n try:\n Image.new('RGB', (16, 16)).save(StringIO.StringIO(), 'JPEG')\n libraries_results.append(('PIL+JPEG', True, 'Got it!'))\n except Exception, e:\n msg = \"Failed to create a jpeg image: %s\" % e\n libraries_results.append(('PIL+JPEG', False, msg))\n\n try:\n import M2Crypto # NOQA\n libraries_results.append(('M2Crypto', True, 'Got it!'))\n except ImportError:\n libraries_results.append(('M2Crypto', False, 'Failed to import'))\n\n if settings.SPIDERMONKEY:\n if os.access(settings.SPIDERMONKEY, os.R_OK):\n libraries_results.append(('Spidermonkey is ready!', True, None))\n # TODO: see if it works?\n else:\n msg = \"You said spidermonkey was at (%s)\" % settings.SPIDERMONKEY\n libraries_results.append(('Spidermonkey', False, msg))\n # If settings are debug and spidermonkey is empty,\n # thorw this error.\n elif settings.DEBUG and not settings.SPIDERMONKEY:\n msg = 'SPIDERMONKEY is empty'\n libraries_results.append(('Spidermonkey', True, msg))\n else:\n msg = \"Please set SPIDERMONKEY in your settings file.\"\n libraries_results.append(('Spidermonkey', False, msg))\n\n missing_libs = [l for l, s, m in libraries_results if not s]\n if missing_libs:\n status = 'missing libs: %s' % \",\".join(missing_libs)\n return status, libraries_results\n\n\ndef elastic():\n es = elasticsearch.Elasticsearch(hosts=settings.ES_HOSTS)\n elastic_results = None\n status = ''\n try:\n health = es.cluster.health()\n if health['status'] == 'red':\n status = 'ES is red'\n elastic_results = health\n except elasticsearch.ElasticsearchException:\n monitor_log.exception('Failed to communicate with ES')\n elastic_results = {'error': traceback.format_exc()}\n status = 'traceback'\n\n return status, elastic_results\n\n\ndef path():\n # Check file paths / permissions\n rw = (settings.TMP_PATH,\n settings.NETAPP_STORAGE,\n settings.UPLOADS_PATH,\n settings.ADDONS_PATH,\n settings.GUARDED_ADDONS_PATH,\n settings.ADDON_ICONS_PATH,\n settings.WEBSITE_ICONS_PATH,\n settings.PREVIEWS_PATH,\n settings.REVIEWER_ATTACHMENTS_PATH,)\n r = [os.path.join(settings.ROOT, 'locale')]\n filepaths = [(path, os.R_OK | os.W_OK, \"We want read + write\")\n for path in rw]\n filepaths += [(path, os.R_OK, \"We want read\") for path in r]\n filepath_results = []\n filepath_status = True\n\n for path, perms, notes in filepaths:\n path_exists = os.path.exists(path)\n path_perms = os.access(path, perms)\n filepath_status = filepath_status and path_exists and path_perms\n filepath_results.append((path, path_exists, path_perms, notes))\n\n key_exists = os.path.exists(settings.WEBAPPS_RECEIPT_KEY)\n key_perms = os.access(settings.WEBAPPS_RECEIPT_KEY, os.R_OK)\n filepath_status = filepath_status and key_exists and key_perms\n filepath_results.append(('settings.WEBAPPS_RECEIPT_KEY',\n key_exists, key_perms, 'We want read'))\n\n status = filepath_status\n status = ''\n if not filepath_status:\n status = 'check main status page for broken perms'\n\n return status, filepath_results\n\n\n# The signer check actually asks the signing server to sign something. Do this\n# once per nagios check, once per web head might be a bit much. The memoize\n# slows it down a bit, by caching the result for 15 seconds.\n@memoize('monitors-signer', time=15)\ndef receipt_signer():\n destination = getattr(settings, 'SIGNING_SERVER', None)\n if not destination:\n return '', 'Signer is not configured.'\n\n # Just send some test data into the signer.\n now = int(time.time())\n not_valid = (settings.SITE_URL + '/not-valid')\n data = {'detail': not_valid, 'exp': now + 3600, 'iat': now,\n 'iss': settings.SITE_URL,\n 'product': {'storedata': 'id=1', 'url': u'http://not-valid.com'},\n 'nbf': now, 'typ': 'purchase-receipt',\n 'reissue': not_valid,\n 'user': {'type': 'directed-identifier',\n 'value': u'something-not-valid'},\n 'verify': not_valid\n }\n\n try:\n result = receipt.sign(data)\n except SigningError as err:\n msg = 'Error on signing (%s): %s' % (destination, err)\n return msg, msg\n\n try:\n cert, rest = receipt.crack(result)\n except Exception as err:\n msg = 'Error on cracking receipt (%s): %s' % (destination, err)\n return msg, msg\n\n # Check that the certs used to sign the receipts are not about to expire.\n limit = now + (60 * 60 * 24) # One day.\n if cert['exp'] < limit:\n msg = 'Cert will expire soon (%s)' % destination\n return msg, msg\n\n cert_err_msg = 'Error on checking public cert (%s): %s'\n location = cert['iss']\n try:\n resp = requests.get(location, timeout=5, stream=False)\n except Exception as err:\n msg = cert_err_msg % (location, err)\n return msg, msg\n\n if not resp.ok:\n msg = cert_err_msg % (location, resp.reason)\n return msg, msg\n\n cert_json = resp.json()\n if not cert_json or 'jwk' not in cert_json:\n msg = cert_err_msg % (location, 'Not valid JSON/JWK')\n return msg, msg\n\n return '', 'Signer working and up to date'\n\n\n# Like the receipt signer above this asks the packaged app signing\n# service to sign one for us.\n@memoize('monitors-package-signer', time=60)\ndef package_signer():\n destination = getattr(settings, 'SIGNED_APPS_SERVER', None)\n if not destination:\n return '', 'Signer is not configured.'\n app_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),\n 'nagios_check_packaged_app.zip')\n signed_path = tempfile.mktemp()\n try:\n packaged.sign_app(local_storage.open(app_path), signed_path, None,\n False, local=True)\n return '', 'Package signer working'\n except PackageSigningError, e:\n msg = 'Error on package signing (%s): %s' % (destination, e)\n return msg, msg\n finally:\n local_storage.delete(signed_path)\n\n\n# Not called settings to avoid conflict with django.conf.settings.\ndef settings_check():\n required = ['APP_PURCHASE_KEY', 'APP_PURCHASE_TYP', 'APP_PURCHASE_AUD',\n 'APP_PURCHASE_SECRET']\n for key in required:\n if not getattr(settings, key):\n msg = 'Missing required value %s' % key\n return msg, msg\n\n return '', 'Required settings ok'\n\n\ndef solitude():\n try:\n res = client.api.services.request.get()\n except Exception as err:\n return repr(err), repr(err)\n auth = res.get('authenticated', None)\n if auth != 'marketplace':\n msg = 'Solitude authenticated as: %s' % auth\n return msg, msg\n\n return '', 'Solitude authentication ok'\n"}, "files_after": {"mkt/site/monitors.py": "import os\nimport socket\nimport StringIO\nimport tempfile\nimport time\nimport traceback\n\nfrom django.conf import settings\n\nimport commonware.log\nimport elasticsearch\nimport requests\nfrom cache_nuggets.lib import memoize\nfrom PIL import Image\n\nfrom lib.crypto import packaged, receipt\nfrom lib.crypto.packaged import SigningError as PackageSigningError\nfrom lib.crypto.receipt import SigningError\nfrom mkt.site.storage_utils import local_storage\n\n\nmonitor_log = commonware.log.getLogger('z.monitor')\n\n\ndef memcache():\n memcache = getattr(settings, 'CACHES', {}).get('default')\n memcache_results = []\n status = ''\n if memcache and 'memcache' in memcache['BACKEND']:\n hosts = memcache['LOCATION']\n using_twemproxy = False\n if not isinstance(hosts, (tuple, list)):\n hosts = [hosts]\n for host in hosts:\n ip, port = host.split(':')\n\n if ip == '127.0.0.1':\n using_twemproxy = True\n\n try:\n s = socket.socket()\n s.connect((ip, int(port)))\n except Exception, e:\n result = False\n status = 'Failed to connect to memcached (%s): %s' % (host, e)\n monitor_log.critical(status)\n else:\n result = True\n finally:\n s.close()\n\n memcache_results.append((ip, port, result))\n if (not using_twemproxy and len(hosts) > 1 and\n len(memcache_results) < 2):\n # If the number of requested hosts is greater than 1, but less\n # than 2 replied, raise an error.\n status = ('2+ memcache servers are required.'\n '%s available') % len(memcache_results)\n monitor_log.warning(status)\n\n # If we are in debug mode, don't worry about checking for memcache.\n elif settings.DEBUG:\n return status, []\n\n if not memcache_results:\n status = 'Memcache is not configured'\n monitor_log.info(status)\n\n return status, memcache_results\n\n\ndef libraries():\n # Check Libraries and versions\n libraries_results = []\n status = ''\n try:\n Image.new('RGB', (16, 16)).save(StringIO.StringIO(), 'JPEG')\n libraries_results.append(('PIL+JPEG', True, 'Got it!'))\n except Exception, e:\n msg = \"Failed to create a jpeg image: %s\" % e\n libraries_results.append(('PIL+JPEG', False, msg))\n\n try:\n import M2Crypto # NOQA\n libraries_results.append(('M2Crypto', True, 'Got it!'))\n except ImportError:\n libraries_results.append(('M2Crypto', False, 'Failed to import'))\n\n if settings.SPIDERMONKEY:\n if os.access(settings.SPIDERMONKEY, os.R_OK):\n libraries_results.append(('Spidermonkey is ready!', True, None))\n # TODO: see if it works?\n else:\n msg = \"You said spidermonkey was at (%s)\" % settings.SPIDERMONKEY\n libraries_results.append(('Spidermonkey', False, msg))\n # If settings are debug and spidermonkey is empty,\n # thorw this error.\n elif settings.DEBUG and not settings.SPIDERMONKEY:\n msg = 'SPIDERMONKEY is empty'\n libraries_results.append(('Spidermonkey', True, msg))\n else:\n msg = \"Please set SPIDERMONKEY in your settings file.\"\n libraries_results.append(('Spidermonkey', False, msg))\n\n missing_libs = [l for l, s, m in libraries_results if not s]\n if missing_libs:\n status = 'missing libs: %s' % \",\".join(missing_libs)\n return status, libraries_results\n\n\ndef elastic():\n es = elasticsearch.Elasticsearch(hosts=settings.ES_HOSTS)\n elastic_results = None\n status = ''\n try:\n health = es.cluster.health()\n if health['status'] == 'red':\n status = 'ES is red'\n elastic_results = health\n except elasticsearch.ElasticsearchException:\n monitor_log.exception('Failed to communicate with ES')\n elastic_results = {'error': traceback.format_exc()}\n status = 'traceback'\n\n return status, elastic_results\n\n\ndef path():\n # Check file paths / permissions\n rw = (settings.TMP_PATH,\n settings.NETAPP_STORAGE,\n settings.UPLOADS_PATH,\n settings.ADDONS_PATH,\n settings.GUARDED_ADDONS_PATH,\n settings.ADDON_ICONS_PATH,\n settings.WEBSITE_ICONS_PATH,\n settings.PREVIEWS_PATH,\n settings.REVIEWER_ATTACHMENTS_PATH,)\n r = [os.path.join(settings.ROOT, 'locale')]\n filepaths = [(path, os.R_OK | os.W_OK, \"We want read + write\")\n for path in rw]\n filepaths += [(path, os.R_OK, \"We want read\") for path in r]\n filepath_results = []\n filepath_status = True\n\n for path, perms, notes in filepaths:\n path_exists = os.path.exists(path)\n path_perms = os.access(path, perms)\n filepath_status = filepath_status and path_exists and path_perms\n filepath_results.append((path, path_exists, path_perms, notes))\n\n key_exists = os.path.exists(settings.WEBAPPS_RECEIPT_KEY)\n key_perms = os.access(settings.WEBAPPS_RECEIPT_KEY, os.R_OK)\n filepath_status = filepath_status and key_exists and key_perms\n filepath_results.append(('settings.WEBAPPS_RECEIPT_KEY',\n key_exists, key_perms, 'We want read'))\n\n status = filepath_status\n status = ''\n if not filepath_status:\n status = 'check main status page for broken perms'\n\n return status, filepath_results\n\n\n# The signer check actually asks the signing server to sign something. Do this\n# once per nagios check, once per web head might be a bit much. The memoize\n# slows it down a bit, by caching the result for 15 seconds.\n@memoize('monitors-signer', time=15)\ndef receipt_signer():\n destination = getattr(settings, 'SIGNING_SERVER', None)\n if not destination:\n return '', 'Signer is not configured.'\n\n # Just send some test data into the signer.\n now = int(time.time())\n not_valid = (settings.SITE_URL + '/not-valid')\n data = {'detail': not_valid, 'exp': now + 3600, 'iat': now,\n 'iss': settings.SITE_URL,\n 'product': {'storedata': 'id=1', 'url': u'http://not-valid.com'},\n 'nbf': now, 'typ': 'purchase-receipt',\n 'reissue': not_valid,\n 'user': {'type': 'directed-identifier',\n 'value': u'something-not-valid'},\n 'verify': not_valid\n }\n\n try:\n result = receipt.sign(data)\n except SigningError as err:\n msg = 'Error on signing (%s): %s' % (destination, err)\n return msg, msg\n\n try:\n cert, rest = receipt.crack(result)\n except Exception as err:\n msg = 'Error on cracking receipt (%s): %s' % (destination, err)\n return msg, msg\n\n # Check that the certs used to sign the receipts are not about to expire.\n limit = now + (60 * 60 * 24) # One day.\n if cert['exp'] < limit:\n msg = 'Cert will expire soon (%s)' % destination\n return msg, msg\n\n cert_err_msg = 'Error on checking public cert (%s): %s'\n location = cert['iss']\n try:\n resp = requests.get(location, timeout=5, stream=False)\n except Exception as err:\n msg = cert_err_msg % (location, err)\n return msg, msg\n\n if not resp.ok:\n msg = cert_err_msg % (location, resp.reason)\n return msg, msg\n\n cert_json = resp.json()\n if not cert_json or 'jwk' not in cert_json:\n msg = cert_err_msg % (location, 'Not valid JSON/JWK')\n return msg, msg\n\n return '', 'Signer working and up to date'\n\n\n# Like the receipt signer above this asks the packaged app signing\n# service to sign one for us.\n@memoize('monitors-package-signer', time=60)\ndef package_signer():\n destination = getattr(settings, 'SIGNED_APPS_SERVER', None)\n if not destination:\n return '', 'Signer is not configured.'\n app_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),\n 'nagios_check_packaged_app.zip')\n signed_path = tempfile.mktemp()\n try:\n packaged.sign_app(local_storage.open(app_path), signed_path, None,\n False, local=True)\n return '', 'Package signer working'\n except PackageSigningError, e:\n msg = 'Error on package signing (%s): %s' % (destination, e)\n return msg, msg\n finally:\n local_storage.delete(signed_path)\n\n\n# Not called settings to avoid conflict with django.conf.settings.\ndef settings_check():\n required = ['APP_PURCHASE_KEY', 'APP_PURCHASE_TYP', 'APP_PURCHASE_AUD',\n 'APP_PURCHASE_SECRET']\n for key in required:\n if not getattr(settings, key):\n msg = 'Missing required value %s' % key\n return msg, msg\n\n return '', 'Required settings ok'\n"}} -{"repo": "kurtjx/SNORQL", "pr_number": 4, "title": "Configurable SNORQL instance and webjar creation", "state": "open", "merged_at": null, "additions": 135, "deletions": 13, "files_changed": ["snorql/index.html", "snorql/snorql.js"], "files_before": {"snorql/index.html": "\n\n\n \n Snorql: A SPARQL Explorer\n \n \n \n \n \n \n \n\n \n
            \n

            Snorql: A SPARQL Explorer

            \n
            \n\n
            \n\n
            \n

            GRAPH:

            \n

            \n Default graph.\n List named graphs\n

            \n
            \n\n
            \n

            GRAPH:

            \n

            \n Named graph goes here.\n Switch back to default graph\n

            \n
            \n\n
            \n

            SPARQL:

            \n
            \n      
            \n \n \n \n \n
            \n
            \n \n Results:\n \n \n XSLT stylesheet URL:\n \n \n \n \n
            \n
            \n\n
            \n
            \n
            \n\n
            Powered by Snorql
            \n \n\n", "snorql/snorql.js": "var snorql = new Snorql();\n\nString.prototype.trim = function () {\n return this.replace(/^\\s*/, \"\").replace(/\\s*$/, \"\");\n}\n\nString.prototype.startsWith = function(str) {\n\treturn (this.match(\"^\"+str) == str);\n}\n\nfunction Snorql() {\n // modify this._endpoint to point to your SPARQL endpoint\n this._endpoint = document.location.href.match(/^([^?]*)snorql\\//)[1] + 'sparql';\n // modify these to your likeing\n this._poweredByLink = 'http://www4.wiwiss.fu-berlin.de/bizer/d2r-server/';\n this._poweredByLabel = 'D2R Server';\n this._enableNamedGraphs = false;\n\n this._browserBase = null;\n this._namespaces = {};\n this._graph = null;\n this._xsltDOM = null;\n\n this.start = function() {\n // TODO: Extract a QueryType class\n this.setBrowserBase(document.location.href.replace(/\\?.*/, ''));\n this._displayEndpointURL();\n this._displayPoweredBy();\n this.setNamespaces(D2R_namespacePrefixes);\n this.updateOutputMode();\n var match = document.location.href.match(/\\?(.*)/);\n var queryString = match ? match[1] : '';\n if (!queryString) {\n document.getElementById('querytext').value = 'SELECT DISTINCT * WHERE {\\n ?s ?p ?o\\n}\\nLIMIT 10';\n this._updateGraph(null, false);\n return;\n }\n var graph = queryString.match(/graph=([^&]*)/);\n graph = graph ? decodeURIComponent(graph[1]) : null;\n this._updateGraph(graph, false);\n var browse = queryString.match(/browse=([^&]*)/);\n var querytext = null;\n if (browse && browse[1] == 'superclasses') {\n var resultTitle = 'List of all super classes:';\n var querytext = 'SELECT DISTINCT ?class\\n' +\n 'WHERE { [] rdfs:subClassOf ?class }\\n' +\n 'ORDER BY ?class';\n var query = 'PREFIX rdfs: \\n' + querytext;\n }\n if (browse && browse[1] == 'classes') {\n var resultTitle = 'List of all classes:';\n var query = 'SELECT DISTINCT ?class\\n' +\n 'WHERE { [] a ?class }\\n' +\n 'ORDER BY ?class';\n }\n if (browse && browse[1] == 'properties') {\n var resultTitle = 'List of all properties:';\n var query = 'SELECT DISTINCT ?property\\n' +\n 'WHERE { [] ?property [] }\\n' +\n 'ORDER BY ?property';\n }\n if (browse && browse[1] == 'graphs') {\n var resultTitle = 'List of all named graphs:';\n var querytext = 'SELECT DISTINCT ?namedgraph ?label\\n' +\n 'WHERE {\\n' +\n ' GRAPH ?namedgraph { ?s ?p ?o }\\n' +\n ' OPTIONAL { ?namedgraph rdfs:label ?label }\\n' +\n '}\\n' +\n 'ORDER BY ?namedgraph';\n var query = 'PREFIX rdfs: \\n' + querytext;\n }\n var match = queryString.match(/property=([^&]*)/);\n if (match) {\n var resultTitle = 'All uses of property ' + decodeURIComponent(match[1]) + ':';\n var query = 'SELECT DISTINCT ?resource ?value\\n' +\n 'WHERE { ?resource <' + decodeURIComponent(match[1]) + '> ?value }\\n' +\n 'ORDER BY ?resource ?value';\n }\n var match = queryString.match(/class=([^&]*)/);\n if (match) {\n var resultTitle = 'All instances of class ' + decodeURIComponent(match[1]) + ':';\n var query = 'SELECT DISTINCT ?instance\\n' +\n 'WHERE { ?instance a <' + decodeURIComponent(match[1]) + '> }\\n' +\n 'ORDER BY ?instance';\n }\n var match = queryString.match(/describe=([^&]*)/);\n if (match) {\n var resultTitle = 'Description of ' + decodeURIComponent(match[1]) + ':';\n var query = 'SELECT DISTINCT ?property ?hasValue ?isValueOf\\n' +\n 'WHERE {\\n' +\n ' { <' + decodeURIComponent(match[1]) + '> ?property ?hasValue }\\n' +\n ' UNION\\n' +\n ' { ?isValueOf ?property <' + decodeURIComponent(match[1]) + '> }\\n' +\n '}\\n' +\n 'ORDER BY (!BOUND(?hasValue)) ?property ?hasValue ?isValueOf';\n }\n if (queryString.match(/query=/)) {\n var resultTitle = 'SPARQL results:';\n querytext = this._betterUnescape(queryString.match(/query=([^&]*)/)[1]);\n var query = prefixes + querytext;\n }\n if (!querytext) {\n querytext = query;\n }\n document.getElementById('querytext').value = querytext;\n this.displayBusyMessage();\n var service = new SPARQL.Service(this._endpoint);\n if (this._graph) {\n service.addDefaultGraph(this._graph);\n }\n\n // AndyL changed MIME type and success callback depending on query form...\n var dummy = this;\n \n \t var exp = /^\\s*(?:PREFIX\\s+\\w*:\\s+<[^>]*>\\s*)*(\\w+)\\s*.*/i;\n \t var match = exp.exec(querytext);\n \t if (match) {\n\t if (match[1].toUpperCase() == 'ASK') {\n\t \tservice.setOutput('boolean');\n\t \tvar successFunc = function(value) {\n\t dummy.displayBooleanResult(value, resultTitle);\n\t };\n\t } else if (match[1].toUpperCase() == 'CONSTRUCT' || match[1].toUpperCase() == 'DESCRIBE'){ // construct describe\n\t \t\tservice.setOutput('rdf'); // !json\n\t \t\tvar successFunc = function(model) {\n\t dummy.displayRDFResult(model, resultTitle);\n\t };\n\t } else {\n\t \tservice.setRequestHeader('Accept', 'application/sparql-results+json,*/*');\n\t \tservice.setOutput('json');\n\t \tvar successFunc = function(json) {\n\t \t\tdummy.displayJSONResult(json, resultTitle);\n\t \t};\n\t }\n \t }\n \t \n service.query(query, {\n success: successFunc,\n failure: function(report) {\n var message = report.responseText.match(/
            ([\\s\\S]*)<\\/pre>/);\n                if (message) {\n                    dummy.displayErrorMessage(message[1]);\n                } else {\n                    dummy.displayErrorMessage(report.responseText);\n                }\n            }\n        });\n    }\n\n    this.setBrowserBase = function(url) {\n        this._browserBase = url;\n    }\n\n    this._displayEndpointURL = function() {\n        var newTitle = 'Snorql: Exploring ' + this._endpoint;\n        this._display(document.createTextNode(newTitle), 'title');\n        document.title = newTitle;\n    }\n\n    this._displayPoweredBy = function() {\n        $('poweredby').href = this._poweredByLink;\n        $('poweredby').update(this._poweredByLabel);\n    }\n\n    this.setNamespaces = function(namespaces) {\n        this._namespaces = namespaces;\n        this._display(document.createTextNode(this._getPrefixes()), 'prefixestext');\n    }\n\n    this.switchToGraph = function(uri) {\n        this._updateGraph(uri, true);\n    }\n\n    this.switchToDefaultGraph = function() {\n        this._updateGraph(null, true);\n    }\n\n    this._updateGraph = function(uri, effect) {\n        if (!this._enableNamedGraphs) {\n            $('default-graph-section').hide();\n            $('named-graph-section').hide();\n            $('browse-named-graphs-link').hide();\n            return;\n        }\n        var changed = (uri != this._graph);\n        this._graph = uri;\n        var el = document.getElementById('graph-uri');\n        el.disabled = (this._graph == null);\n        el.value = this._graph;\n        if (this._graph == null) {\n            var show = 'default-graph-section';\n            var hide = 'named-graph-section';\n            $$('a.graph-link').each(function(link) {\n                match = link.href.match(/^(.*)[&?]graph=/);\n                if (match) link.href = match[1];\n            });\n        } else {\n            var show = 'named-graph-section';\n            var hide = 'default-graph-section';\n            $('selected-named-graph').update(this._graph);\n            var uri = this._graph;\n            $$('a.graph-link').each(function(link) {\n                match = link.href.match(/^(.*)[&?]graph=/);\n                if (!match) link.href = link.href + '&graph=' + uri;\n            });\n        }\n        $(hide).hide();\n        $(show).show();\n        if (effect && changed) {\n            new Effect.Highlight(show,\n                {startcolor: '#ffff00', endcolor: '#ccccff', resotrecolor: '#ccccff'});\n        }\n        $('graph-uri').disabled = (this._graph == null);\n        $('graph-uri').value = this._graph;\n    }\n\n    this.updateOutputMode = function() {\n        if (this._xsltDOM == null) {\n            this._xsltDOM = document.getElementById('xsltinput');\n        }\n        var el = document.getElementById('xsltcontainer');\n        while (el.childNodes.length > 0) {\n            el.removeChild(el.firstChild);\n        }\n        if (this._selectedOutputMode() == 'xslt') {\n            el.appendChild(this._xsltDOM);\n        }\n    }\n\n    this.resetQuery = function() {\n        document.location = this._browserBase;\n    }\n\n    this.submitQuery = function() {\n        var mode = this._selectedOutputMode();\n        if (mode == 'browse') {\n            document.getElementById('queryform').action = this._browserBase;\n            document.getElementById('query').value = document.getElementById('querytext').value;\n        } else {\n            document.getElementById('query').value = this._getPrefixes() + document.getElementById('querytext').value;\n            document.getElementById('queryform').action = this._endpoint;\n        }\n        document.getElementById('jsonoutput').disabled = (mode != 'json');\n        document.getElementById('stylesheet').disabled = (mode != 'xslt' || !document.getElementById('xsltstylesheet').value);\n        if (mode == 'xslt') {\n            document.getElementById('stylesheet').value = document.getElementById('xsltstylesheet').value;\n        }\n        document.getElementById('queryform').submit();\n    }\n\n    this.displayBusyMessage = function() {\n        var busy = document.createElement('div');\n        busy.className = 'busy';\n        busy.appendChild(document.createTextNode('Executing query ...'));\n        this._display(busy, 'result');\n    }\n\n    this.displayErrorMessage = function(message) {\n        var pre = document.createElement('pre');\n        pre.innerHTML = message;\n        this._display(pre, 'result');\n    }\n\n    this.displayBooleanResult = function(value, resultTitle) {\n        var div = document.createElement('div');\n        var title = document.createElement('h2');\n        title.appendChild(document.createTextNode(resultTitle));\n        div.appendChild(title);\n        if (value)\n        \tdiv.appendChild(document.createTextNode(\"TRUE\"));\n        else\n        \tdiv.appendChild(document.createTextNode(\"FALSE\"));\n        this._display(div, 'result');\n        this._updateGraph(this._graph); // refresh links in new result\n    }\n    \n    this.displayRDFResult = function(model, resultTitle) {\n        var div = document.createElement('div');\n        var title = document.createElement('h2');\n        title.appendChild(document.createTextNode(resultTitle));\n        div.appendChild(title);\n        div.appendChild(new RDFXMLFormatter(model));\n        this._display(div, 'result');\n        this._updateGraph(this._graph); // refresh links in new result - necessary for boolean?\n    }\n    \n    this.displayJSONResult = function(json, resultTitle) {\n        var div = document.createElement('div');\n        var title = document.createElement('h2');\n        title.appendChild(document.createTextNode(resultTitle));\n        div.appendChild(title);\n        if (json.results.bindings.length == 0) {\n            var p = document.createElement('p');\n            p.className = 'empty';\n            p.appendChild(document.createTextNode('[no results]'));\n            div.appendChild(p);\n        } else {\n            div.appendChild(new SPARQLResultFormatter(json, this._namespaces).toDOM());\n        }\n        this._display(div, 'result');\n        this._updateGraph(this._graph); // refresh links in new result\n    }\n\n    this._display = function(node, whereID) {\n        var where = document.getElementById(whereID);\n        if (!where) {\n            alert('ID not found: ' + whereID);\n            return;\n        }\n        while (where.firstChild) {\n            where.removeChild(where.firstChild);\n        }\n        if (node == null) return;\n        where.appendChild(node);\n    }\n\n    this._selectedOutputMode = function() {\n        return document.getElementById('selectoutput').value;\n    }\n\n    this._getPrefixes = function() {\n        prefixes = '';\n        for (prefix in this._namespaces) {\n            var uri = this._namespaces[prefix];\n            prefixes = prefixes + 'PREFIX ' + prefix + ': <' + uri + '>\\n';\n        }\n        return prefixes;\n    }\n\n    this._betterUnescape = function(s) {\n        return unescape(s.replace(/\\+/g, ' '));\n    }\n}\n\n\n/*\n * RDFXMLFormatter\n * \n * maybe improve...\n */\nfunction RDFXMLFormatter(string) {\n\tvar pre = document.createElement('pre');\n\tpre.appendChild(document.createTextNode(string));\n\treturn pre;\n}\n\n/*\n===========================================================================\nSPARQLResultFormatter: Renders a SPARQL/JSON result set into an HTML table.\n\nvar namespaces = { 'xsd': '', 'foaf': 'http://xmlns.com/foaf/0.1' };\nvar formatter = new SPARQLResultFormatter(json, namespaces);\nvar tableObject = formatter.toDOM();\n*/\nfunction SPARQLResultFormatter(json, namespaces) {\n    this._json = json;\n    this._variables = this._json.head.vars;\n    this._results = this._json.results.bindings;\n    this._namespaces = namespaces;\n\n    this.toDOM = function() {\n        var table = document.createElement('table');\n        table.className = 'queryresults';\n        table.appendChild(this._createTableHeader());\n        for (var i = 0; i < this._results.length; i++) {\n            table.appendChild(this._createTableRow(this._results[i], i));\n        }\n        return table;\n    }\n\n    // TODO: Refactor; non-standard link makers should be passed into the class by the caller\n    this._getLinkMaker = function(varName) {\n        if (varName == 'property') {\n            return function(uri) { return '?property=' + encodeURIComponent(uri); };\n        } else if (varName == 'class') {\n            return function(uri) { return '?class=' + encodeURIComponent(uri); };\n        } else {\n            return function(uri) { return '?describe=' + encodeURIComponent(uri); };\n        }\n    }\n\n    this._createTableHeader = function() {\n        var tr = document.createElement('tr');\n        var hasNamedGraph = false;\n        for (var i = 0; i < this._variables.length; i++) {\n            var th = document.createElement('th');\n            th.appendChild(document.createTextNode(this._variables[i]));\n            tr.appendChild(th);\n            if (this._variables[i] == 'namedgraph') {\n                hasNamedGraph = true;\n            }\n        }\n        if (hasNamedGraph) {\n            var th = document.createElement('th');\n            th.appendChild(document.createTextNode(' '));\n            tr.insertBefore(th, tr.firstChild);\n        }\n        return tr;\n    }\n\n    this._createTableRow = function(binding, rowNumber) {\n        var tr = document.createElement('tr');\n        if (rowNumber % 2) {\n            tr.className = 'odd';\n        } else {\n            tr.className = 'even';\n        }\n        var namedGraph = null;\n        for (var i = 0; i < this._variables.length; i++) {\n            var varName = this._variables[i];\n            td = document.createElement('td');\n            td.appendChild(this._formatNode(binding[varName], varName));\n            tr.appendChild(td);\n            if (this._variables[i] == 'namedgraph') {\n                namedGraph = binding[varName];\n            }\n        }\n        if (namedGraph) {\n            var link = document.createElement('a');\n            link.href = 'javascript:snorql.switchToGraph(\\'' + namedGraph.value + '\\')';\n            link.appendChild(document.createTextNode('Switch'));\n            var td = document.createElement('td');\n            td.appendChild(link);\n            tr.insertBefore(td, tr.firstChild);\n        }\n        return tr;\n    }\n\n    this._formatNode = function(node, varName) {\n        if (!node) {\n            return this._formatUnbound(node, varName);\n        }\n        if (node.type == 'uri') {\n            return this._formatURI(node, varName);\n        }\n        if (node.type == 'bnode') {\n            return this._formatBlankNode(node, varName);\n        }\n        if (node.type == 'literal') {\n            return this._formatPlainLiteral(node, varName);\n        }\n        if (node.type == 'typed-literal') {\n            return this._formatTypedLiteral(node, varName);\n        }\n        return document.createTextNode('???');\n    }\n\n    this._formatURI = function(node, varName) {\n        var span = document.createElement('span');\n        span.className = 'uri';\n        var a = document.createElement('a');\n        a.href = this._getLinkMaker(varName)(node.value);\n        a.title = '<' + node.value + '>';\n        a.className = 'graph-link';\n        var qname = this._toQName(node.value);\n        if (qname) {\n            a.appendChild(document.createTextNode(qname));\n            span.appendChild(a);\n        } else {\n            a.appendChild(document.createTextNode(node.value));\n            span.appendChild(document.createTextNode('<'));\n            span.appendChild(a);\n            span.appendChild(document.createTextNode('>'));\n        }\n        match = node.value.match(/^(https?|ftp|mailto|irc|gopher|news):/);\n        if (match) {\n            span.appendChild(document.createTextNode(' '));\n            var externalLink = document.createElement('a');\n            externalLink.href = node.value;\n            img = document.createElement('img');\n            img.src = 'link.png';\n            img.alt = '[' + match[1] + ']';\n            img.title = 'Go to Web page';\n            externalLink.appendChild(img);\n            span.appendChild(externalLink);\n        }\n        return span;\n    }\n\n    this._formatPlainLiteral = function(node, varName) {\n        var text = '\"' + node.value + '\"';\n        if (node['xml:lang']) {\n            text += '@' + node['xml:lang'];\n        }\n        return document.createTextNode(text);\n    }\n\n    this._formatTypedLiteral = function(node, varName) {\n        var text = '\"' + node.value + '\"';\n        if (node.datatype) {\n            text += '^^' + this._toQNameOrURI(node.datatype);\n        }\n        if (this._isNumericXSDType(node.datatype)) {\n            var span = document.createElement('span');\n            span.title = text;\n            span.appendChild(document.createTextNode(node.value));\n            return span;\n        }\n        return document.createTextNode(text);\n    }\n\n    this._formatBlankNode = function(node, varName) {\n        return document.createTextNode('_:' + node.value);\n    }\n\n    this._formatUnbound = function(node, varName) {\n        var span = document.createElement('span');\n        span.className = 'unbound';\n        span.title = 'Unbound'\n        span.appendChild(document.createTextNode('-'));\n        return span;\n    }\n\n    this._toQName = function(uri) {\n        for (prefix in this._namespaces) {\n            var nsURI = this._namespaces[prefix];\n            if (uri.indexOf(nsURI) == 0) {\n                return prefix + ':' + uri.substring(nsURI.length);\n            }\n        }\n        return null;\n    }\n\n    this._toQNameOrURI = function(uri) {\n        var qName = this._toQName(uri);\n        return (qName == null) ? '<' + uri + '>' : qName;\n    }\n\n    this._isNumericXSDType = function(datatypeURI) {\n        for (i = 0; i < this._numericXSDTypes.length; i++) {\n            if (datatypeURI == this._xsdNamespace + this._numericXSDTypes[i]) {\n                return true;\n            }\n        }\n        return false;\n    }\n    this._xsdNamespace = 'http://www.w3.org/2001/XMLSchema#';\n    this._numericXSDTypes = ['long', 'decimal', 'float', 'double', 'int',\n        'short', 'byte', 'integer', 'nonPositiveInteger', 'negativeInteger',\n        'nonNegativeInteger', 'positiveInteger', 'unsignedLong',\n        'unsignedInt', 'unsignedShort', 'unsignedByte'];\n}\n"}, "files_after": {"snorql/index.html": "\n\n\n  \n    Snorql: A SPARQL Explorer\n    \n    \n    \n    \n    \n    \n    \n  \n\n  \n    
            \n

            Snorql: A SPARQL Explorer

            \n
            \n\n
            \n

            Browse:

            \n \n
            \n\n
            \n

            GRAPH:

            \n

            \n Default graph.\n List named graphs\n

            \n
            \n\n
            \n

            GRAPH:

            \n

            \n Named graph goes here.\n Switch back to default graph\n

            \n
            \n\n
            \n

            SPARQL:

            \n
            \n      
            \n \n \n \n \n
            \n
            \n \n Results:\n \n \n XSLT stylesheet URL:\n \n \n \n \n
            \n
            \n\n
            \n
            \n
            \n\n
            Powered by Snorql
            \n \n\n", "snorql/snorql.js": "\nString.prototype.trim = function () {\n return this.replace(/^\\s*/, \"\").replace(/\\s*$/, \"\");\n}\n\nString.prototype.startsWith = function(str) {\n\treturn (this.match(\"^\"+str) == str);\n}\n\nfunction Snorql(options) {\n options = options || {};\n\n this._endpoint = options['endpoint'] || undefined;\n\n this._poweredByLink = options['poweredByLink'] || 'http://www4.wiwiss.fu-berlin.de/bizer/d2r-server/';\n this._poweredByLabel = options['poweredByLabel'] || 'D2R Server';\n this._enableNamedGraphs = options['enableNamedGraphs'] || false;\n\n this._browserBase = options['browserBase'] || null;\n this._namespaces = options['namespaces'] || D2R_namespacePrefixes;\n this._graph = options['graph'] || null;\n this._xsltDOM = options['xsltDOM'] || null;\n\n this.start = function() {\n // TODO: Extract a QueryType class\n this.setBrowserBase(document.location.href.replace(/\\?.*/, ''));\n this._displayEndpointURL();\n this._displayPoweredBy();\n this.setNamespaces(this._namespaces);\n this.updateOutputMode();\n var match = document.location.href.match(/\\?(.*)/);\n var queryString = match ? match[1] : '';\n if (!queryString) {\n document.getElementById('querytext').value = 'SELECT DISTINCT * WHERE {\\n ?s ?p ?o\\n}\\nLIMIT 10';\n this._updateGraph(null, false);\n return;\n }\n var graph = queryString.match(/graph=([^&]*)/);\n graph = graph ? decodeURIComponent(graph[1]) : null;\n this._updateGraph(graph, false);\n var browse = queryString.match(/browse=([^&]*)/);\n var querytext = null;\n if (browse && browse[1] == 'superclasses') {\n var resultTitle = 'List of all super classes:';\n var querytext = 'SELECT DISTINCT ?class\\n' +\n 'WHERE { [] rdfs:subClassOf ?class }\\n' +\n 'ORDER BY ?class';\n var query = 'PREFIX rdfs: \\n' + querytext;\n }\n if (browse && browse[1] == 'classes') {\n var resultTitle = 'List of all classes:';\n var query = 'SELECT DISTINCT ?class\\n' +\n 'WHERE { [] a ?class }\\n' +\n 'ORDER BY ?class';\n }\n if (browse && browse[1] == 'properties') {\n var resultTitle = 'List of all properties:';\n var query = 'SELECT DISTINCT ?property\\n' +\n 'WHERE { [] ?property [] }\\n' +\n 'ORDER BY ?property';\n }\n if (browse && browse[1] == 'graphs') {\n var resultTitle = 'List of all named graphs:';\n var querytext = 'SELECT DISTINCT ?namedgraph ?label\\n' +\n 'WHERE {\\n' +\n ' GRAPH ?namedgraph { ?s ?p ?o }\\n' +\n ' OPTIONAL { ?namedgraph rdfs:label ?label }\\n' +\n '}\\n' +\n 'ORDER BY ?namedgraph';\n var query = 'PREFIX rdfs: \\n' + querytext;\n }\n var match = queryString.match(/property=([^&]*)/);\n if (match) {\n var resultTitle = 'All uses of property ' + decodeURIComponent(match[1]) + ':';\n var query = 'SELECT DISTINCT ?resource ?value\\n' +\n 'WHERE { ?resource <' + decodeURIComponent(match[1]) + '> ?value }\\n' +\n 'ORDER BY ?resource ?value';\n }\n var match = queryString.match(/class=([^&]*)/);\n if (match) {\n var resultTitle = 'All instances of class ' + decodeURIComponent(match[1]) + ':';\n var query = 'SELECT DISTINCT ?instance\\n' +\n 'WHERE { ?instance a <' + decodeURIComponent(match[1]) + '> }\\n' +\n 'ORDER BY ?instance';\n }\n var match = queryString.match(/describe=([^&]*)/);\n if (match) {\n var resultTitle = 'Description of ' + decodeURIComponent(match[1]) + ':';\n var query = 'SELECT DISTINCT ?property ?hasValue ?isValueOf\\n' +\n 'WHERE {\\n' +\n ' { <' + decodeURIComponent(match[1]) + '> ?property ?hasValue }\\n' +\n ' UNION\\n' +\n ' { ?isValueOf ?property <' + decodeURIComponent(match[1]) + '> }\\n' +\n '}\\n' +\n 'ORDER BY (!BOUND(?hasValue)) ?property ?hasValue ?isValueOf';\n }\n if (queryString.match(/query=/)) {\n var resultTitle = 'SPARQL results:';\n querytext = this._betterUnescape(queryString.match(/query=([^&]*)/)[1]);\n var query = prefixes + querytext;\n }\n if (!querytext) {\n querytext = query;\n }\n document.getElementById('querytext').value = querytext;\n this.displayBusyMessage();\n if (!this._endpoint) {\n this.displayErrorMessage(\"No SPARQL Endpoint provided!\");\n return;\n }\n var service = new SPARQL.Service(this._endpoint);\n if (this._graph) {\n service.addDefaultGraph(this._graph);\n }\n\n // AndyL changed MIME type and success callback depending on query form...\n var dummy = this;\n \n \t var exp = /^\\s*(?:PREFIX\\s+\\w*:\\s+<[^>]*>\\s*)*(\\w+)\\s*.*/i;\n \t var match = exp.exec(querytext);\n \t if (match) {\n\t if (match[1].toUpperCase() == 'ASK') {\n\t \tservice.setOutput('boolean');\n\t \tvar successFunc = function(value) {\n\t dummy.displayBooleanResult(value, resultTitle);\n\t };\n\t } else if (match[1].toUpperCase() == 'CONSTRUCT' || match[1].toUpperCase() == 'DESCRIBE'){ // construct describe\n\t \t\tservice.setOutput('rdf'); // !json\n\t \t\tvar successFunc = function(model) {\n\t dummy.displayRDFResult(model, resultTitle);\n\t };\n\t } else {\n\t \tservice.setRequestHeader('Accept', 'application/sparql-results+json,*/*');\n\t \tservice.setOutput('json');\n\t \tvar successFunc = function(json) {\n\t \t\tdummy.displayJSONResult(json, resultTitle);\n\t \t};\n\t }\n \t }\n \t \n service.query(query, {\n success: successFunc,\n failure: function(report) {\n var message = report.responseText.match(/
            ([\\s\\S]*)<\\/pre>/);\n                if (message) {\n                    dummy.displayErrorMessage(message[1]);\n                } else {\n                    dummy.displayErrorMessage(report.responseText);\n                }\n            }\n        });\n    }\n\n    this.setBrowserBase = function(url) {\n        this._browserBase = url;\n    }\n\n    this._displayEndpointURL = function() {\n        var newTitle = 'Snorql: Exploring ' + this._endpoint;\n        this._display(document.createTextNode(newTitle), 'title');\n        document.title = newTitle;\n    }\n\n    this._displayPoweredBy = function() {\n        $('poweredby').href = this._poweredByLink;\n        $('poweredby').update(this._poweredByLabel);\n    }\n\n    this.setNamespaces = function(namespaces) {\n        this._namespaces = namespaces;\n        this._display(document.createTextNode(this._getPrefixes()), 'prefixestext');\n    }\n\n    this.switchToGraph = function(uri) {\n        this._updateGraph(uri, true);\n    }\n\n    this.switchToDefaultGraph = function() {\n        this._updateGraph(null, true);\n    }\n\n    this._updateGraph = function(uri, effect) {\n        if (!this._enableNamedGraphs) {\n            $('default-graph-section').hide();\n            $('named-graph-section').hide();\n            $('browse-named-graphs-link').hide();\n            return;\n        }\n        var changed = (uri != this._graph);\n        this._graph = uri;\n        var el = document.getElementById('graph-uri');\n        el.disabled = (this._graph == null);\n        el.value = this._graph;\n        if (this._graph == null) {\n            var show = 'default-graph-section';\n            var hide = 'named-graph-section';\n            $$('a.graph-link').each(function(link) {\n                match = link.href.match(/^(.*)[&?]graph=/);\n                if (match) link.href = match[1];\n            });\n        } else {\n            var show = 'named-graph-section';\n            var hide = 'default-graph-section';\n            $('selected-named-graph').update(this._graph);\n            var uri = this._graph;\n            $$('a.graph-link').each(function(link) {\n                match = link.href.match(/^(.*)[&?]graph=/);\n                if (!match) link.href = link.href + '&graph=' + uri;\n            });\n        }\n        $(hide).hide();\n        $(show).show();\n        if (effect && changed) {\n            new Effect.Highlight(show,\n                {startcolor: '#ffff00', endcolor: '#ccccff', resotrecolor: '#ccccff'});\n        }\n        $('graph-uri').disabled = (this._graph == null);\n        $('graph-uri').value = this._graph;\n    }\n\n    this.updateOutputMode = function() {\n        if (this._xsltDOM == null) {\n            this._xsltDOM = document.getElementById('xsltinput');\n        }\n        var el = document.getElementById('xsltcontainer');\n        while (el.childNodes.length > 0) {\n            el.removeChild(el.firstChild);\n        }\n        if (this._selectedOutputMode() == 'xslt') {\n            el.appendChild(this._xsltDOM);\n        }\n    }\n\n    this.resetQuery = function() {\n        document.location = this._browserBase;\n    }\n\n    this.submitQuery = function() {\n        if (!this._endpoint) {\n            this.displayErrorMessage(\"No SPARQL Endpoint defined!\");\n        }\n\n        var mode = this._selectedOutputMode();\n        if (mode == 'browse') {\n            document.getElementById('queryform').action = this._browserBase;\n            document.getElementById('query').value = document.getElementById('querytext').value;\n        } else {\n            document.getElementById('query').value = this._getPrefixes() + document.getElementById('querytext').value;\n            document.getElementById('queryform').action = this._endpoint;\n        }\n        document.getElementById('jsonoutput').disabled = (mode != 'json');\n        document.getElementById('stylesheet').disabled = (mode != 'xslt' || !document.getElementById('xsltstylesheet').value);\n        if (mode == 'xslt') {\n            document.getElementById('stylesheet').value = document.getElementById('xsltstylesheet').value;\n        }\n        document.getElementById('queryform').submit();\n    }\n\n    this.displayBusyMessage = function() {\n        var busy = document.createElement('div');\n        busy.className = 'busy';\n        busy.appendChild(document.createTextNode('Executing query ...'));\n        this._display(busy, 'result');\n    }\n\n    this.displayErrorMessage = function(message) {\n        var pre = document.createElement('pre');\n        pre.innerHTML = message;\n        this._display(pre, 'result');\n    }\n\n    this.displayBooleanResult = function(value, resultTitle) {\n        var div = document.createElement('div');\n        var title = document.createElement('h2');\n        title.appendChild(document.createTextNode(resultTitle));\n        div.appendChild(title);\n        if (value)\n        \tdiv.appendChild(document.createTextNode(\"TRUE\"));\n        else\n        \tdiv.appendChild(document.createTextNode(\"FALSE\"));\n        this._display(div, 'result');\n        this._updateGraph(this._graph); // refresh links in new result\n    }\n    \n    this.displayRDFResult = function(model, resultTitle) {\n        var div = document.createElement('div');\n        var title = document.createElement('h2');\n        title.appendChild(document.createTextNode(resultTitle));\n        div.appendChild(title);\n        div.appendChild(new RDFXMLFormatter(model));\n        this._display(div, 'result');\n        this._updateGraph(this._graph); // refresh links in new result - necessary for boolean?\n    }\n    \n    this.displayJSONResult = function(json, resultTitle) {\n        var div = document.createElement('div');\n        var title = document.createElement('h2');\n        title.appendChild(document.createTextNode(resultTitle));\n        div.appendChild(title);\n        if (json.results.bindings.length == 0) {\n            var p = document.createElement('p');\n            p.className = 'empty';\n            p.appendChild(document.createTextNode('[no results]'));\n            div.appendChild(p);\n        } else {\n            div.appendChild(new SPARQLResultFormatter(json, this._namespaces).toDOM());\n        }\n        this._display(div, 'result');\n        this._updateGraph(this._graph); // refresh links in new result\n    }\n\n    this._display = function(node, whereID) {\n        var where = document.getElementById(whereID);\n        if (!where) {\n            alert('ID not found: ' + whereID);\n            return;\n        }\n        while (where.firstChild) {\n            where.removeChild(where.firstChild);\n        }\n        if (node == null) return;\n        where.appendChild(node);\n    }\n\n    this._selectedOutputMode = function() {\n        return document.getElementById('selectoutput').value;\n    }\n\n    this._getPrefixes = function() {\n        prefixes = '';\n        for (prefix in this._namespaces) {\n            var uri = this._namespaces[prefix];\n            prefixes = prefixes + 'PREFIX ' + prefix + ': <' + uri + '>\\n';\n        }\n        return prefixes;\n    }\n\n    this._betterUnescape = function(s) {\n        return unescape(s.replace(/\\+/g, ' '));\n    }\n}\n\n\n/*\n * RDFXMLFormatter\n * \n * maybe improve...\n */\nfunction RDFXMLFormatter(string) {\n\tvar pre = document.createElement('pre');\n\tpre.appendChild(document.createTextNode(string));\n\treturn pre;\n}\n\n/*\n===========================================================================\nSPARQLResultFormatter: Renders a SPARQL/JSON result set into an HTML table.\n\nvar namespaces = { 'xsd': '', 'foaf': 'http://xmlns.com/foaf/0.1' };\nvar formatter = new SPARQLResultFormatter(json, namespaces);\nvar tableObject = formatter.toDOM();\n*/\nfunction SPARQLResultFormatter(json, namespaces) {\n    this._json = json;\n    this._variables = this._json.head.vars;\n    this._results = this._json.results.bindings;\n    this._namespaces = namespaces;\n\n    this.toDOM = function() {\n        var table = document.createElement('table');\n        table.className = 'queryresults';\n        table.appendChild(this._createTableHeader());\n        for (var i = 0; i < this._results.length; i++) {\n            table.appendChild(this._createTableRow(this._results[i], i));\n        }\n        return table;\n    }\n\n    // TODO: Refactor; non-standard link makers should be passed into the class by the caller\n    this._getLinkMaker = function(varName) {\n        if (varName == 'property') {\n            return function(uri) { return '?property=' + encodeURIComponent(uri); };\n        } else if (varName == 'class') {\n            return function(uri) { return '?class=' + encodeURIComponent(uri); };\n        } else {\n            return function(uri) { return '?describe=' + encodeURIComponent(uri); };\n        }\n    }\n\n    this._createTableHeader = function() {\n        var tr = document.createElement('tr');\n        var hasNamedGraph = false;\n        for (var i = 0; i < this._variables.length; i++) {\n            var th = document.createElement('th');\n            th.appendChild(document.createTextNode(this._variables[i]));\n            tr.appendChild(th);\n            if (this._variables[i] == 'namedgraph') {\n                hasNamedGraph = true;\n            }\n        }\n        if (hasNamedGraph) {\n            var th = document.createElement('th');\n            th.appendChild(document.createTextNode(' '));\n            tr.insertBefore(th, tr.firstChild);\n        }\n        return tr;\n    }\n\n    this._createTableRow = function(binding, rowNumber) {\n        var tr = document.createElement('tr');\n        if (rowNumber % 2) {\n            tr.className = 'odd';\n        } else {\n            tr.className = 'even';\n        }\n        var namedGraph = null;\n        for (var i = 0; i < this._variables.length; i++) {\n            var varName = this._variables[i];\n            td = document.createElement('td');\n            td.appendChild(this._formatNode(binding[varName], varName));\n            tr.appendChild(td);\n            if (this._variables[i] == 'namedgraph') {\n                namedGraph = binding[varName];\n            }\n        }\n        if (namedGraph) {\n            var link = document.createElement('a');\n            link.href = 'javascript:snorql.switchToGraph(\\'' + namedGraph.value + '\\')';\n            link.appendChild(document.createTextNode('Switch'));\n            var td = document.createElement('td');\n            td.appendChild(link);\n            tr.insertBefore(td, tr.firstChild);\n        }\n        return tr;\n    }\n\n    this._formatNode = function(node, varName) {\n        if (!node) {\n            return this._formatUnbound(node, varName);\n        }\n        if (node.type == 'uri') {\n            return this._formatURI(node, varName);\n        }\n        if (node.type == 'bnode') {\n            return this._formatBlankNode(node, varName);\n        }\n        if (node.type == 'literal') {\n            return this._formatPlainLiteral(node, varName);\n        }\n        if (node.type == 'typed-literal') {\n            return this._formatTypedLiteral(node, varName);\n        }\n        return document.createTextNode('???');\n    }\n\n    this._formatURI = function(node, varName) {\n        var span = document.createElement('span');\n        span.className = 'uri';\n        var a = document.createElement('a');\n        a.href = this._getLinkMaker(varName)(node.value);\n        a.title = '<' + node.value + '>';\n        a.className = 'graph-link';\n        var qname = this._toQName(node.value);\n        if (qname) {\n            a.appendChild(document.createTextNode(qname));\n            span.appendChild(a);\n        } else {\n            a.appendChild(document.createTextNode(node.value));\n            span.appendChild(document.createTextNode('<'));\n            span.appendChild(a);\n            span.appendChild(document.createTextNode('>'));\n        }\n        match = node.value.match(/^(https?|ftp|mailto|irc|gopher|news):/);\n        if (match) {\n            span.appendChild(document.createTextNode(' '));\n            var externalLink = document.createElement('a');\n            externalLink.href = node.value;\n            img = document.createElement('img');\n            img.src = 'link.png';\n            img.alt = '[' + match[1] + ']';\n            img.title = 'Go to Web page';\n            externalLink.appendChild(img);\n            span.appendChild(externalLink);\n        }\n        return span;\n    }\n\n    this._formatPlainLiteral = function(node, varName) {\n        var text = '\"' + node.value + '\"';\n        if (node['xml:lang']) {\n            text += '@' + node['xml:lang'];\n        }\n        return document.createTextNode(text);\n    }\n\n    this._formatTypedLiteral = function(node, varName) {\n        var text = '\"' + node.value + '\"';\n        if (node.datatype) {\n            text += '^^' + this._toQNameOrURI(node.datatype);\n        }\n        if (this._isNumericXSDType(node.datatype)) {\n            var span = document.createElement('span');\n            span.title = text;\n            span.appendChild(document.createTextNode(node.value));\n            return span;\n        }\n        return document.createTextNode(text);\n    }\n\n    this._formatBlankNode = function(node, varName) {\n        return document.createTextNode('_:' + node.value);\n    }\n\n    this._formatUnbound = function(node, varName) {\n        var span = document.createElement('span');\n        span.className = 'unbound';\n        span.title = 'Unbound'\n        span.appendChild(document.createTextNode('-'));\n        return span;\n    }\n\n    this._toQName = function(uri) {\n        for (prefix in this._namespaces) {\n            var nsURI = this._namespaces[prefix];\n            if (uri.indexOf(nsURI) == 0) {\n                return prefix + ':' + uri.substring(nsURI.length);\n            }\n        }\n        return null;\n    }\n\n    this._toQNameOrURI = function(uri) {\n        var qName = this._toQName(uri);\n        return (qName == null) ? '<' + uri + '>' : qName;\n    }\n\n    this._isNumericXSDType = function(datatypeURI) {\n        for (i = 0; i < this._numericXSDTypes.length; i++) {\n            if (datatypeURI == this._xsdNamespace + this._numericXSDTypes[i]) {\n                return true;\n            }\n        }\n        return false;\n    }\n    this._xsdNamespace = 'http://www.w3.org/2001/XMLSchema#';\n    this._numericXSDTypes = ['long', 'decimal', 'float', 'double', 'int',\n        'short', 'byte', 'integer', 'nonPositiveInteger', 'negativeInteger',\n        'nonNegativeInteger', 'positiveInteger', 'unsignedLong',\n        'unsignedInt', 'unsignedShort', 'unsignedByte'];\n}\n"}}
            -{"repo": "jamescarr/braintree_node", "pr_number": 1, "title": "Hi! I fixed some calls to \"sys\" for you!", "state": "open", "merged_at": null, "additions": 12, "deletions": 12, "files_changed": ["lib/braintree.js", "lib/braintree/http.js", "spec/spec_helper.js"], "files_before": {"lib/braintree.js": "var sys = require(\"sys\"),\n    Config = require(\"./braintree/config\").Config,\n    Environment = require(\"./braintree/environment\").Environment,\n    Gateway = require(\"./braintree/gateway\").Gateway,\n    TransactionGateway = require(\"./braintree/transaction_gateway\").TransactionGateway;\n    AuthenticationError = require(\"./braintree/exceptions/authentication_error\").AuthenticationError,\n    errorTypes = require(\"./braintree/exceptions/error_types\");\n\nif (process.version !== 'v0.2.0') {\n  sys.puts('WARNING: node.js version ' + process.version + ' has not been tested with the braintree library');\n}\n\nvar connect = function(config) {\n  var gateway = Gateway(Config(config));\n  return {\n    transaction: TransactionGateway(gateway)\n  };\n};\n\nexports.connect = connect;\nexports.version = '0.1.0';\nexports.AuthenticationError = AuthenticationError;\nexports.Environment = Environment;\nexports.errorTypes = errorTypes;\n", "lib/braintree/http.js": "var sys = require('sys'),\n    http = require('http'),\n    Buffer = require('buffer').Buffer,\n    base64 = require('base64'),\n    braintree = require('../braintree'),\n    AuthenticationError = require('./exceptions/authentication_error').AuthenticationError,\n    UnexpectedError = require('./exceptions/unexpected_error').UnexpectedError;\n\nvar Http = function (config) {\n  var my = {\n    config: config\n  };\n\n  var request = function (method, url, body, callback) {\n    var client = http.createClient(\n      my.config.environment.port,\n      my.config.environment.server,\n      my.config.environment.ssl\n    );\n    var headers = {\n      'Authorization': base64.encode(new Buffer(my.config.public_key + ':' + my.config.private_key)),\n      'X-ApiVersion': '2',\n      'Accept': 'application/json',\n      'Content-Type': 'application/json',\n      'User-Agent': 'client Node ' + braintree.version\n    };\n    if (body) {\n      var requestBody = JSON.stringify(body);\n      headers['Content-Length'] = requestBody.length.toString();\n    }\n    var request = client.request(method, my.config.baseMerchantPath + url, headers);\n    if (body) { request.write(requestBody); }\n    request.end();\n    request.on('response', function (response) {\n      var body = '';\n      response.on('data', function (responseBody) {\n        body += responseBody;\n      });\n      response.on('end', function () {\n        if (response.statusCode == 401) {\n          callback(AuthenticationError(), null);\n        } else if (response.statusCode == 200 || response.statusCode == 201 || response.statusCode == 422) {\n          callback(null, JSON.parse(body));\n        } else {\n          callback(UnexpectedError('Unexpected HTTP response: ' + response.statusCode), null);\n        }\n      });\n    });\n  };\n\n  return {\n    post: function (url, body, callback) {\n      request('POST', url, body, callback);\n    },\n\n    put: function (url, body, callback) {\n      request('PUT', url, body, callback);\n    }\n  };\n};\n\nexports.Http = Http;\n", "spec/spec_helper.js": "GLOBAL.sys = require('sys');\nGLOBAL.vows = require('vows');\nGLOBAL.assert = require('assert');\n\nGLOBAL.inspect = function (object) {\n  sys.puts(sys.inspect(object));\n};\n\nGLOBAL.braintree = require('./../lib/braintree');\n\nvar defaultConfig = {\n  environment: braintree.Environment.Development,\n  merchantId: 'integration_merchant_id',\n  publicKey: 'integration_public_key',\n  privateKey: 'integration_private_key'\n};\n\nvar defaultGateway = braintree.connect(defaultConfig);\n\nGLOBAL.specHelper = {\n  defaultConfig: defaultConfig,\n  defaultGateway: defaultGateway\n}\n"}, "files_after": {"lib/braintree.js": "var util = require('util'),\n    Config = require(\"./braintree/config\").Config,\n    Environment = require(\"./braintree/environment\").Environment,\n    Gateway = require(\"./braintree/gateway\").Gateway,\n    TransactionGateway = require(\"./braintree/transaction_gateway\").TransactionGateway;\n    AuthenticationError = require(\"./braintree/exceptions/authentication_error\").AuthenticationError,\n    errorTypes = require(\"./braintree/exceptions/error_types\");\n\nif (process.version !== 'v0.2.0') {\n  util.puts('WARNING: node.js version ' + process.version + ' has not been tested with the braintree library');\n}\n\nvar connect = function(config) {\n  var gateway = Gateway(Config(config));\n  return {\n    transaction: TransactionGateway(gateway)\n  };\n};\n\nexports.connect = connect;\nexports.version = '0.1.0';\nexports.AuthenticationError = AuthenticationError;\nexports.Environment = Environment;\nexports.errorTypes = errorTypes;\n", "lib/braintree/http.js": "var util = require('util'),\n    http = require('http'),\n    Buffer = require('buffer').Buffer,\n    base64 = require('base64'),\n    braintree = require('../braintree'),\n    AuthenticationError = require('./exceptions/authentication_error').AuthenticationError,\n    UnexpectedError = require('./exceptions/unexpected_error').UnexpectedError;\n\nvar Http = function (config) {\n  var my = {\n    config: config\n  };\n\n  var request = function (method, url, body, callback) {\n    var client = http.createClient(\n      my.config.environment.port,\n      my.config.environment.server,\n      my.config.environment.ssl\n    );\n    var headers = {\n      'Authorization': base64.encode(new Buffer(my.config.public_key + ':' + my.config.private_key)),\n      'X-ApiVersion': '2',\n      'Accept': 'application/json',\n      'Content-Type': 'application/json',\n      'User-Agent': 'client Node ' + braintree.version\n    };\n    if (body) {\n      var requestBody = JSON.stringify(body);\n      headers['Content-Length'] = requestBody.length.toString();\n    }\n    var request = client.request(method, my.config.baseMerchantPath + url, headers);\n    if (body) { request.write(requestBody); }\n    request.end();\n    request.on('response', function (response) {\n      var body = '';\n      response.on('data', function (responseBody) {\n        body += responseBody;\n      });\n      response.on('end', function () {\n        if (response.statusCode == 401) {\n          callback(AuthenticationError(), null);\n        } else if (response.statusCode == 200 || response.statusCode == 201 || response.statusCode == 422) {\n          callback(null, JSON.parse(body));\n        } else {\n          callback(UnexpectedError('Unexpected HTTP response: ' + response.statusCode), null);\n        }\n      });\n    });\n  };\n\n  return {\n    post: function (url, body, callback) {\n      request('POST', url, body, callback);\n    },\n\n    put: function (url, body, callback) {\n      request('PUT', url, body, callback);\n    }\n  };\n};\n\nexports.Http = Http;\n", "spec/spec_helper.js": "GLOBAL.util = require('util');\nGLOBAL.vows = require('vows');\nGLOBAL.assert = require('assert');\n\nGLOBAL.inspect = function (object) {\n  util.puts(util.inspect(object));\n};\n\nGLOBAL.braintree = require('./../lib/braintree');\n\nvar defaultConfig = {\n  environment: braintree.Environment.Development,\n  merchantId: 'integration_merchant_id',\n  publicKey: 'integration_public_key',\n  privateKey: 'integration_private_key'\n};\n\nvar defaultGateway = braintree.connect(defaultConfig);\n\nGLOBAL.specHelper = {\n  defaultConfig: defaultConfig,\n  defaultGateway: defaultGateway\n}\n"}}
            -{"repo": "kevinwbaker/Echelon", "pr_number": 8, "title": "error", "state": "open", "merged_at": null, "additions": 2180, "deletions": 1937, "files_changed": ["echelon.sql", "echelon/actions/autosuggest.php", "echelon/actions/b3/ban.php", "echelon/actions/b3/comment.php", "echelon/actions/b3/editban.php", "echelon/actions/b3/greeting.php", "echelon/actions/b3/level.php", "echelon/actions/b3/unban.php", "echelon/actions/blacklist.php", "echelon/actions/edit-me.php", "echelon/actions/settings-game.php", "echelon/actions/settings-server.php", "echelon/actions/settings.php", "echelon/actions/user-add.php", "echelon/active.php", "echelon/adminkicks.php", "echelon/admins.php", "echelon/banlist.php", "echelon/bans.php", "echelon/classes/dbl-class.php", "echelon/classes/members-class.php", "echelon/classes/mysql-class.php", "echelon/classes/plugins-class.php", "echelon/clientdetails.php", "echelon/clients.php", "echelon/css/cd.css", "echelon/css/home.css", "echelon/css/login.css"], "files_before": {"echelon.sql": "/*\r\nMySQL Data Transfer\r\nSource Host: localhost\r\nSource Database: echelon\r\nTarget Host: localhost\r\nTarget Database: echelon\r\nDate: 13/08/2010 00:47:01\r\n*/\r\n\r\nSET FOREIGN_KEY_CHECKS=0;\r\n-- ----------------------------\r\n-- Table structure for ech_blacklist\r\n-- ----------------------------\r\nDROP TABLE IF EXISTS `ech_blacklist`;\r\nCREATE TABLE `ech_blacklist` (\n  `id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,\n  `ip` varchar(24) NOT NULL,\n  `active` tinyint(4) DEFAULT NULL,\n  `reason` varchar(255) DEFAULT NULL,\n  `time_add` int(32) unsigned DEFAULT NULL,\n  `admin_id` smallint(6) unsigned DEFAULT NULL,\n  PRIMARY KEY (`id`),\n  KEY `ip` (`ip`,`active`)\n) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;\r\n\r\n-- ----------------------------\r\n-- Table structure for ech_config\r\n-- ----------------------------\r\nDROP TABLE IF EXISTS `ech_config`;\r\nCREATE TABLE `ech_config` (\n  `id` smallint(6) NOT NULL AUTO_INCREMENT,\n  `name` varchar(25) NOT NULL,\n  `value` varchar(255) NOT NULL,\n  PRIMARY KEY (`id`),\n  KEY `i_config` (`name`,`value`)\n) ENGINE=MyISAM AUTO_INCREMENT=17 DEFAULT CHARSET=latin1;\r\n\r\n-- ----------------------------\r\n-- Table structure for ech_games\r\n-- ----------------------------\r\nDROP TABLE IF EXISTS `ech_games`;\r\nCREATE TABLE `ech_games` (\n  `id` smallint(8) unsigned NOT NULL AUTO_INCREMENT,\n  `name` varchar(255) NOT NULL,\n  `game` varchar(255) NOT NULL,\n  `name_short` varchar(255) DEFAULT NULL,\n  `num_srvs` smallint(9) NOT NULL,\n  `db_host` varchar(255) NOT NULL,\n  `db_user` varchar(255) NOT NULL,\n  `db_pw` varchar(255) DEFAULT NULL,\n  `db_name` varchar(255) NOT NULL,\n  `plugins` varchar(255) DEFAULT NULL,\n  PRIMARY KEY (`id`),\n  KEY `i_games` (`name`,`num_srvs`)\n) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;\r\n\r\n-- ----------------------------\r\n-- Table structure for ech_groups\r\n-- ----------------------------\r\nDROP TABLE IF EXISTS `ech_groups`;\r\nCREATE TABLE `ech_groups` (\n  `id` smallint(4) unsigned NOT NULL AUTO_INCREMENT,\n  `name` varchar(32) NOT NULL,\n  `namep` varchar(255) DEFAULT NULL,\n  `premissions` varchar(512) NOT NULL,\n  PRIMARY KEY (`id`,`name`),\n  KEY `i_name` (`name`,`namep`)\n) ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=latin1;\r\n\r\n-- ----------------------------\r\n-- Table structure for ech_links\r\n-- ----------------------------\r\nDROP TABLE IF EXISTS `ech_links`;\r\nCREATE TABLE `ech_links` (\n  `id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,\n  `url` varchar(255) NOT NULL,\n  `name` varchar(80) DEFAULT NULL,\n  `title` varchar(255) DEFAULT NULL,\n  PRIMARY KEY (`id`),\n  UNIQUE KEY `i_url` (`url`)\n) ENGINE=MyISAM AUTO_INCREMENT=7 DEFAULT CHARSET=latin1;\r\n\r\n-- ----------------------------\r\n-- Table structure for ech_logs\r\n-- ----------------------------\r\nDROP TABLE IF EXISTS `ech_logs`;\r\nCREATE TABLE `ech_logs` (\n  `id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,\n  `type` varchar(64) DEFAULT NULL,\n  `msg` varchar(255) DEFAULT '',\n  `client_id` smallint(5) DEFAULT NULL,\n  `user_id` smallint(5) DEFAULT NULL,\n  `time_add` int(32) DEFAULT NULL,\n  `game_id` mediumint(10) DEFAULT NULL,\n  PRIMARY KEY (`id`),\n  KEY `i_logs` (`client_id`,`user_id`)\n) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;\r\n\r\n-- ----------------------------\r\n-- Table structure for ech_permissions\r\n-- ----------------------------\r\nDROP TABLE IF EXISTS `ech_permissions`;\r\nCREATE TABLE `ech_permissions` (\n  `id` mediumint(6) NOT NULL AUTO_INCREMENT,\n  `name` varchar(50) NOT NULL,\n  `description` varchar(255) DEFAULT NULL,\n  PRIMARY KEY (`id`,`name`),\n  UNIQUE KEY `name` (`name`)\n) ENGINE=MyISAM AUTO_INCREMENT=28 DEFAULT CHARSET=latin1;\r\n\r\n-- ----------------------------\r\n-- Table structure for ech_servers\r\n-- ----------------------------\r\nDROP TABLE IF EXISTS `ech_servers`;\r\nCREATE TABLE `ech_servers` (\n  `id` int(5) unsigned NOT NULL AUTO_INCREMENT,\n  `game` smallint(5) NOT NULL,\n  `name` varchar(100) NOT NULL,\n  `ip` varchar(15) NOT NULL,\n  `pb_active` tinyint(1) NOT NULL,\n  `rcon_pass` varchar(50) NOT NULL,\n  `rcon_ip` varchar(26) NOT NULL,\n  `rcon_port` int(5) NOT NULL,\n  PRIMARY KEY (`id`),\n  KEY `game` (`game`)\n) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;\r\n\r\n-- ----------------------------\r\n-- Table structure for ech_user_keys\r\n-- ----------------------------\r\nDROP TABLE IF EXISTS `ech_user_keys`;\r\nCREATE TABLE `ech_user_keys` (\n  `reg_key` varchar(40) NOT NULL,\n  `ech_group` smallint(4) NOT NULL,\n  `admin_id` smallint(5) unsigned NOT NULL,\n  `comment` varchar(500) DEFAULT NULL,\n  `time_add` mediumint(24) unsigned DEFAULT NULL,\n  `email` varchar(160) NOT NULL,\n  `active` tinyint(4) NOT NULL,\n  PRIMARY KEY (`reg_key`),\n  KEY `i_regkey` (`active`,`email`)\n) ENGINE=MyISAM DEFAULT CHARSET=latin1;\r\n\r\n-- ----------------------------\r\n-- Table structure for ech_users\r\n-- ----------------------------\r\nDROP TABLE IF EXISTS `ech_users`;\r\nCREATE TABLE `ech_users` (\n  `id` smallint(6) unsigned NOT NULL AUTO_INCREMENT,\n  `username` varchar(32) NOT NULL,\n  `display` varchar(32) DEFAULT NULL,\n  `email` varchar(32) DEFAULT NULL,\n  `password` varchar(64) NOT NULL,\n  `salt` varchar(12) NOT NULL,\n  `ip` varchar(24) DEFAULT NULL,\n  `ech_group` smallint(4) unsigned NOT NULL DEFAULT '1',\n  `admin_id` smallint(6) unsigned NOT NULL DEFAULT '0',\n  `first_seen` int(24) DEFAULT NULL,\n  `last_seen` int(24) DEFAULT NULL,\n  PRIMARY KEY (`id`),\n  UNIQUE KEY `username` (`username`),\n  UNIQUE KEY `password` (`password`),\n  KEY `salt` (`salt`),\n  KEY `i_group` (`ech_group`)\n) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;\r\n\r\n-- ----------------------------\r\n-- Records \r\n-- ----------------------------\r\nINSERT INTO `ech_config` VALUES ('1', 'name', 'Development');\r\nINSERT INTO `ech_config` VALUES ('2', 'num_games', '0');\r\nINSERT INTO `ech_config` VALUES ('3', 'limit_rows', '50');\r\nINSERT INTO `ech_config` VALUES ('4', 'min_pw_len', '8');\r\nINSERT INTO `ech_config` VALUES ('5', 'user_key_expire', '14');\r\nINSERT INTO `ech_config` VALUES ('6', 'email', 'admin@example.com');\r\nINSERT INTO `ech_config` VALUES ('7', 'admin_name', 'Admin');\r\nINSERT INTO `ech_config` VALUES ('8', 'https', '0');\r\nINSERT INTO `ech_config` VALUES ('9', 'allow_ie', '1');\r\nINSERT INTO `ech_config` VALUES ('10', 'time_format', 'D, d/m/y (H:i)');\r\nINSERT INTO `ech_config` VALUES ('11', 'time_zone', 'Europe/Dublin');\r\nINSERT INTO `ech_config` VALUES ('12', 'email_header', 'Hello %name%, This is an email from the Echelon admins.');\r\nINSERT INTO `ech_config` VALUES ('13', 'email_footer', 'Thanks, the %ech_name% Echelon Team');\r\nINSERT INTO `ech_config` VALUES ('14', 'pw_req_level', '1');\r\nINSERT INTO `ech_config` VALUES ('15', 'pw_req_level_group', '64');\r\nINSERT INTO `ech_config` VALUES ('16', 'reg_clan_tags', '=(e)=,=(eG)=,=(eGO)=,{KGB}');\r\nINSERT INTO `ech_groups` VALUES ('1', 'visitor', 'Visitor', '1,2,4,5');\r\nINSERT INTO `ech_groups` VALUES ('2', 'siteadmin', 'Site Admin', '1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27');\r\nINSERT INTO `ech_groups` VALUES ('3', 'senioradmin', 'Senior Admin', '1,2,3,4,5,8,12,14,16,17,20,21,22,23,24');\r\nINSERT INTO `ech_groups` VALUES ('4', 'admin', 'Admin', '1,2,3,4,5,8,16,17,20,21,22');\r\nINSERT INTO `ech_groups` VALUES ('5', 'mod', 'Moderator', '1,2,3,4,5,8,16,22');\r\nINSERT INTO `ech_links` VALUES ('1', 'http://wiki.bigbrotherbot.net/doku.php/echelon', 'Echelon Help Wiki', 'Documentation for the installation and use of Echelon');\r\nINSERT INTO `ech_links` VALUES ('2', 'http://echelon.bigbrotherbot.net/', 'Echelon Home', 'Home site of Echelon project, check here for development news, updates, and information regarding Echelon');\r\nINSERT INTO `ech_links` VALUES ('3', 'http://eire32designs.com', 'Eire32 Site', 'The developers site');\r\nINSERT INTO `ech_links` VALUES ('4', 'http://www.bigbrotherbot.net/forums/', 'B3 Site', 'Home of bigbrother bot');\r\nINSERT INTO `ech_links` VALUES ('5', 'http://cback.de/', 'CTracker', 'Anti-worm and anti-injection attack protection');\r\nINSERT INTO `ech_links` VALUES ('6', 'http://dryicons.com/', 'DryIcons', 'Thanks for the use of the nav icons!');\r\nINSERT INTO `ech_permissions` VALUES ('1', 'login', 'Allows the user to login');\r\nINSERT INTO `ech_permissions` VALUES ('2', 'clients', 'Allows the user to view the client listing');\r\nINSERT INTO `ech_permissions` VALUES ('3', 'chatlogs', 'Allows the user to view Chatlogs');\r\nINSERT INTO `ech_permissions` VALUES ('4', 'penalties', 'Allows the user to view the Penalty Listing pages');\r\nINSERT INTO `ech_permissions` VALUES ('5', 'admins', 'Allows the user to view the Admins Pages');\r\nINSERT INTO `ech_permissions` VALUES ('6', 'manage_settings', 'Allows the user to Manage Echelon Settings.');\r\nINSERT INTO `ech_permissions` VALUES ('7', 'chats_edit_tables', 'Allows the user to edit chatlogger settings');\r\nINSERT INTO `ech_permissions` VALUES ('8', 'logs', 'Allows the user to view Logs');\r\nINSERT INTO `ech_permissions` VALUES ('9', 'edit_user', 'Allows the user to edit other Echelon users');\r\nINSERT INTO `ech_permissions` VALUES ('10', 'add_user', 'Allows the user to Add Echelon Users');\r\nINSERT INTO `ech_permissions` VALUES ('11', 'manage_servers', 'Allows the user to Manage Servers');\r\nINSERT INTO `ech_permissions` VALUES ('12', 'ban', 'Allows the user to Ban');\r\nINSERT INTO `ech_permissions` VALUES ('13', 'edit_mask', 'Allows the user to Edit User Level Masks');\r\nINSERT INTO `ech_permissions` VALUES ('14', 'siteadmin', 'Allows the user to  control the site blacklist and other admin actions');\r\nINSERT INTO `ech_permissions` VALUES ('15', 'edit_perms', 'Allows the user to the premissions of user groups and users');\r\nINSERT INTO `ech_permissions` VALUES ('16', 'comment', 'Allows a user to add a comment to a client');\r\nINSERT INTO `ech_permissions` VALUES ('17', 'greeting', 'Allows the user to change the greeting of a client');\r\nINSERT INTO `ech_permissions` VALUES ('18', 'edit_client_level', 'Allows user to change a players B3 level');\r\nINSERT INTO `ech_permissions` VALUES ('19', 'edit_ban', 'Allows user to edit a B3 ban');\r\nINSERT INTO `ech_permissions` VALUES ('20', 'view_ip', 'Allows the user to view players IP addresses');\r\nINSERT INTO `ech_permissions` VALUES ('21', 'view_full_guid', 'Allow the user to view players full GUID for clients');\r\nINSERT INTO `ech_permissions` VALUES ('22', 'view_half_guid', 'Allow the user to view half of the player GUID for clients');\r\nINSERT INTO `ech_permissions` VALUES ('23', 'unban', 'Allows user to remove a B3 Ban');\r\nINSERT INTO `ech_permissions` VALUES ('24', 'edit_xlrstats', 'Allows user to edit a client\\'s XLRStats information (hidden, fixed name)');\r\nINSERT INTO `ech_permissions` VALUES ('25', 'ctime', 'Allows user to view CTime information');\r\nINSERT INTO `ech_permissions` VALUES ('26', 'see_update_msg', 'Shows this user the Echelon needs updating message');\r\nINSERT INTO `ech_permissions` VALUES ('27', 'chats_talk_back', 'Allows the user to talk back to the server using the Chats Plugin');", "echelon/actions/autosuggest.php": " 0) {\r\n\r\n\t$query = \"SELECT name FROM clients WHERE UPPER(name) LIKE '\". $string .\"%' ORDER BY name LIMIT 10\";\r\n\t$stmt = $db->mysql->prepare($query);\r\n\t$stmt->execute();\r\n\t$stmt->store_result();\r\n\t\r\n\tif($stmt->num_rows) {\r\n\t\r\n\t\t$stmt->bind_result($name);\r\n\t\r\n\t\techo '
              ';\r\n\t\t\twhile ($stmt->fetch()) :\r\n\t\t\t\techo '
            1. '.$name.'
            2. ';\r\n\t\t\tendwhile;\r\n\t\techo '
            ';\r\n\t\t\r\n\t} else { // else try more flexible query\r\n\t\t\r\n\t\t$query_2 = \"SELECT name FROM clients WHERE SOUNDEX(name) = SOUNDEX('%%\". $string .\"%%') ORDER BY name LIMIT 10\";\r\n\t\t$stmt = $db->mysql->prepare($query_2);\r\n\t\t$stmt->execute();\r\n\t\t$stmt->store_result();\r\n\t\t\t\t\r\n\t\tif($stmt->num_rows) { // if something return data\r\n\t\t\r\n\t\t\t$stmt->bind_result($name);\r\n\t\t\r\n\t\t\techo '
              ';\r\n\t\t\twhile ($stmt->fetch()) :\r\n\t\t\t\techo '
            1. '.$name.'
            2. ';\r\n\t\t\tendwhile;\r\n\t\t\techo '
            ';\r\n\t\t\t\r\n\t\t} else { // if nothing try even more flexible query\r\n\t\t\r\n\t\t\t$query_3 = \"SELECT name FROM clients WHERE SUBSTRING(SOUNDEX(name),2) = SUBSTRING(SOUNDEX('%%%\". $string .\"%%%'),2) ORDER BY name LIMIT 10\";\r\n\t\t\t$stmt = $db->mysql->prepare($query_3);\r\n\t\t\t$stmt->execute();\r\n\t\t\t$stmt->store_result();\r\n\t\t\t\r\n\t\t\tif($stmt->num_rows) { // if something return data\r\n\t\t\t\r\n\t\t\t\t$stmt->bind_result($name);\r\n\t\t\t\r\n\t\t\t\techo '
              ';\r\n\t\t\t\twhile ($result = $query_3->fetch_object()) :\r\n\t\t\t\t\techo '
            1. '.$name.'
            2. ';\r\n\t\t\t\tendwhile;\r\n\t\t\t\techo '
            ';\r\n\t\t\t\t\r\n\t\t\t} else { // if nothing try even more flexible query\r\n\t\t\t\t\r\n\t\t\t\techo '
            1. There are no matches to your search
            ';\r\n\t\t\t\r\n\t\t\t} // show error if nothing gotten overal\r\n\t\t\r\n\t\t} // end if two returned nothing!\r\n\t\r\n\t} // end if query one returned nothing !\r\n\r\n\techo '
            1. There was nothing in the search box
            ';\r\n}\r\n\r\n?>", "echelon/actions/b3/ban.php": "name . ' ['. $mem->id .'])'; // since this ban goes down as a B3 ban, tag on some user information (display name and echelon user id)\r\n\r\n## Add Ban to the penalty table ##\r\n$result = $db->penClient($type, $client_id, $duration, $reason, $data, $time_expire);\r\n\t\r\n## Make PB ban to server if Pb is enabled ##\r\nif($is_pb_ban == true) :\r\n\t$i = 1;\r\n\twhile($i <= $game_num_srvs) :\r\n\r\n\t\tif($config['games'][$game]['servers'][$i]['pb_active'] == '1') :\r\n\t\t\t// get the rcon information from the massive config array\r\n\t\t\t$rcon_pass = $config['game']['servers'][$i]['rcon_pass'];\r\n\t\t\t$rcon_ip = $config['game']['servers'][$i]['rcon_ip'];\r\n\t\t\t$rcon_port = $config['game']['servers'][$i]['rcon_port'];\r\n\t\t\t$c_ip = trim($c_ip);\r\n\t\t\r\n\t\t\t// PB_SV_BanGuid [guid] [player_name] [IP_Address] [reason]\r\n\t\t\t$command = \"pb_sv_banguid \" . $pbid . \" \" . $c_name . \" \" . $c_ip . \" \" . $reason;\r\n\t\t\trcon($rcon_ip, $rcon_port, $rcon_pass, $command); // send the ban command\r\n\t\t\tsleep(1); // sleep for 1 sec in ordere to the give server some time\r\n\t\t\t$command_upd = \"pb_sv_updbanfile\"; // we need to update the ban files\r\n\t\t\trcon($rcon_ip, $rcon_port, $rcon_pass, $command_upd); // send the ban file update command\r\n\t\tendif;\r\n\r\n\t\t$i++;\r\n\tendwhile;\r\nendif; // end if a $is_pb_ban == true\r\n\r\nif($result)\r\n\tsendGood('Ban added to banlist and to the DB');\r\nelse\r\n\tsendBack('Something went wrong the ban was not added');\r\n\r\nexit;", "echelon/actions/b3/comment.php": "addEchLog('Comment', $comment, $cid, $mem->id, $game);\r\nif($result)\r\n\tsendGood('Comment added');\r\nelse\r\n\tsendBack('There is a problem, your comment was not added to the database');", "echelon/actions/b3/editban.php": "mysql->prepare($query) or die('DB Error');\r\n$stmt->bind_param('siisi', $type, $duration, $time_expire, $reason, $ban_id);\r\n$stmt->execute();\r\n\r\nif($stmt->affected_rows > 0)\r\n\t$results = true;\r\nelse\r\n\tsendBack('Something went wrong');\r\n\r\n## If a permaban send unban rcon command (the ban will still be enforced then by the B3 DB ##\r\nif($type == 'Ban') :\r\n\t\r\n\t## Loop thro server for this game and send unban command and update ban file\r\n\t$i = 1;\r\n\twhile($i <= $game_num_srvs) :\r\n\r\n\t\tif($config['games'][$game]['servers'][$i]['pb_active'] == '1') {\r\n\t\t\t// get the rcon information from the massive config array\r\n\t\t\t$rcon_pass = $config['game']['servers'][$i]['rcon_pass'];\r\n\t\t\t$rcon_ip = $config['game']['servers'][$i]['rcon_ip'];\r\n\t\t\t$rcon_port = $config['game']['servers'][$i]['rcon_port'];\r\n\t\t\r\n\t\t\t// PB_SV_BanGuid [guid] [player_name] [IP_Address] [reason]\r\n\t\t\t$command = \"pb_sv_unbanguid \" . $pbid;\r\n\t\t\trcon($rcon_ip, $rcon_port, $rcon_pass, $command); // send the ban command\r\n\t\t\tsleep(1); // sleep for 1 sec in ordere to the give server some time\r\n\t\t\t$command_upd = \"pb_sv_updbanfile\"; // we need to update the ban files\r\n\t\t\trcon($rcon_ip, $rcon_port, $rcon_pass, $command_upd); // send the ban file update command\r\n\t\t}\r\n\r\n\t\t$i++;\r\n\tendwhile;\r\n\r\nendif;\r\n\r\n// set comment for the edit ban action\r\n$comment = 'A ban for this user was edited';\r\n\r\n## Query ##\r\n$result = $dbl->addEchLog('Edit Ban', $comment, $cid, $mem->id);\r\n\r\nif($results)\r\n\tsendGood('Ban edited');\r\nelse\r\n\tsendBack('NO!');\r\n\r\nexit;", "echelon/actions/b3/greeting.php": "addEchLog('Greeting', $comment, $client_id, $mem->id);\t\r\n\t\t\r\n\t## Query ##\r\n\t$query = \"UPDATE clients SET greeting = ? WHERE id = ? LIMIT 1\";\r\n\t$stmt = $db->mysql->prepare($query) or sendBack('Database Error');\r\n\t$stmt->bind_param('si', $greeting, $client_id);\r\n\t$stmt->execute();\r\n\tif($stmt->affected_rows)\r\n\t\tsendGood('Greeting has been updated');\r\n\telse\r\n\t\tsendBack('Greeting was not updated');\r\n\t\r\n\t$stmt->close(); // close connection\r\n\r\nelse :\r\n\r\n\tset_error('Please do not call that page directly, thank you.');\r\n\tsend('../../index.php');\r\n\r\nendif;", "echelon/actions/b3/level.php": "getB3Groups();\r\n\r\n// change around the recieved data\r\n$b3_groups_id = array();\r\nforeach($b3_groups as $group) :\r\n\tarray_push($b3_groups_id, $group['id']); // make an array of all the group_bits that exsist\r\n\t$b3_groups_name[$group['id']] = $group['name']; // make an array of group_bits to matching names\r\nendforeach;\r\n\r\n// Check if the group_bits provided match a known group (Known groups is a list of groups pulled from the DB -- this allow more control for custom groups)\r\nif(!in_array($level, $b3_groups_id))\r\n\tsendBack('That group does not exist, please submit a real group');\r\n\r\n## Check that authorisation passsword is correct ##\r\nif($config['cosmos']['pw_req_level'] == 1 && !$is_mask) : // if requiring a pw auth for edit-level is on or off\r\n\tif($level >= $config['cosmos']['pw_req_level_group']) // site setting to see if only certain levels need a pw check and if the selected level is above the threshold\r\n\t\t$mem->reAuthUser($password, $dbl);\r\nendif;\r\n\r\n## Add Echelon Log ##\r\n$level_name = $b3_groups_name[$level];\r\n$old_level_name = $b3_groups_name[$old_level];\r\n\r\nif(!$is_mask)\r\n\t$comment = 'User level changed from '. $old_level_name .' to '. $level_name;\r\nelse\r\n\t$comment = 'Mask level changed from '. $old_level_name .' to '. $level_name;\r\n\r\n$dbl->addEchLog('Level Change', $comment, $client_id, $mem->id);\r\n\r\n## Query Section ##\r\nif(!$is_mask)\r\n\t$query = \"UPDATE clients SET group_bits = ? WHERE id = ? LIMIT 1\";\r\nelse\r\n\t$query = \"UPDATE clients SET mask_level = ? WHERE id = ? LIMIT 1\";\r\n\t\r\n$stmt = $db->mysql->prepare($query) or sendBack('Database Error');\r\n$stmt->bind_param('ii', $level, $client_id);\r\n$stmt->execute();\r\n\r\nif($is_mask)\r\n\t$msg_st = 'Mask';\r\nelse\r\n\t$msg_st = 'User';\r\n\r\nif($stmt->affected_rows)\r\n\tsendGood($msg_st.' level has been changed');\r\nelse\r\n\tsendBack($msg_st.' level was not changed');\r\n\r\n$stmt->close(); // close connection", "echelon/actions/b3/unban.php": "makePenInactive($ban_id);\r\n\r\nif(!$results) // if bad send back warning\r\n\tsendBack('Penalty has not been removed');\r\n\t\r\n## If a permaban send unban rcon command ##\r\nif($type == 'Ban') :\r\n\r\n\t## Get the PBID of the client ##\r\n\t$pbid = $db->getPBIDfromPID($pen_id);\r\n\t\r\n\t## Loop thro server for this game and send unban command and update ban file\r\n\t$i = 1;\r\n\twhile($i <= $game_num_srvs) :\r\n\r\n\t\tif($config['game']['servers'][$i]['pb_active'] == '1') {\r\n\t\t\t// get the rcon information from the massive config array\r\n\t\t\t$rcon_pass = $config['game']['servers'][$i]['rcon_pass'];\r\n\t\t\t$rcon_ip = $config['game']['servers'][$i]['rcon_ip'];\r\n\t\t\t$rcon_port = $config['game']['servers'][$i]['rcon_port'];\r\n\t\t\r\n\t\t\t// PB_SV_BanGuid [guid] [player_name] [IP_Address] [reason]\r\n\t\t\t$command = \"pb_sv_unbanguid \" . $pbid;\r\n\t\t\trcon($rcon_ip, $rcon_port, $rcon_pass, $command); // send the ban command\r\n\t\t\tsleep(1); // sleep for 1 sec in ordere to the give server some time\r\n\t\t\t$command_upd = \"pb_sv_updbanfile\"; // we need to update the ban files\r\n\t\t\trcon($rcon_ip, $rcon_port, $rcon_pass, $command_upd); // send the ban file update command\r\n\t\t}\r\n\r\n\t\t$i++;\r\n\tendwhile;\r\n\r\nendif;\r\n\r\nif($results) // if good results send back good message\r\n\tsendGood('Penalty has been deactivated');\r\n\t\r\nexit;", "echelon/actions/blacklist.php": "BLactive($bl_id, false); // run query to deact BL ban\r\n\tsendGood('This blacklist ban has been de-activated');\r\n\texit; // no need to continue\r\n\r\n} elseif($_POST['react']) { // if this is a re-activation request\r\n\r\n\t$bl_id = $_POST['id'];\r\n\tif(!verifyFormToken('act'.$bl_id, $tokens)) // verify token\r\n\t\tifTokenBad('BL De-activate'); // if bad log and send error\r\n\t\r\n\t$dbl->BLactive($bl_id, true); // run query to reactivate BL ban\r\n\tsendGood('This blacklist ban has been re-activiated');\r\n\texit; // no need to continue\r\n\r\n} elseif($_POST['ip']) { // if this is an add request\r\n\t\r\n\tif(!verifyFormToken('addbl', $tokens)) // verify token\r\n\t\tifTokenBad('BL Add'); // if bad log, add hack counter and throw error\r\n\t\r\n\t// set and clean vars\r\n\t$reason = cleanvar($_POST['reason']);\r\n\t$ip = cleanvar($_POST['ip']);\r\n\t\r\n\t// check for empty inputs\r\n\temptyInput($reason, 'the reason');\r\n\temptyInput($ip, 'IP Address');\r\n\t\r\n\t// if reason is default comment msg, send back with error\r\n\tif($reason == \"Enter a reason for this ban...\")\r\n\t\tsendBack('You must add a reason as to why this IP ban is being added');\r\n\t\r\n\t// check if it is a valid IP address\r\n\tif(!filter_var($ip, FILTER_VALIDATE_IP))\r\n\t\tsendBack('That IP address is not valid');\r\n\t\t\r\n\t$whitelist = array('token','reason','ip'); // allow form fields to be sent\r\n\r\n\t// Building an array with the $_POST-superglobal \r\n\tforeach ($_POST as $key=>$item) {\r\n\t\tif(!in_array($key, $whitelist)) {\r\n\t\t\thack(1); // plus 1 to hack counter\r\n\t\t\twriteLog('Add BL - Unknown form fields provided'); // make note of event\r\n\t\t\tsendBack('Unknown Information sent.');\r\n\t\t\texit;\r\n\t\t}\r\n\t} // end foreach\r\n\t\r\n\t## Query Section ##\r\n\t$result = $dbl->blacklist($ip, $reason, $mem->id);\r\n\tif(!$result) // if false\r\n\t\tsendBack('That IP was not added to the blacklist');\r\n\t\r\n\t// if got this far we are doing well so lets send back a good message\r\n\tsendGood('The IP has been added to the banlist');\r\n\texit; // no need to continue\r\n\r\n} else { // if this page was not posted and a user indirectly ends up on this page then sent to SA page with error\r\n\tset_error('Please do not load that page without submitting the ban IP address form');\r\n\tsend('../sa.php');\r\n}", "echelon/actions/edit-me.php": "name || $email != $mem->email) // sent display name does not match session and same with email\r\n\t$is_change_display_email = true; // this is a change request\r\nelse \r\n\t$is_change_display_email = false; // this is not a change request\r\n\r\n// if display/email not changed and its not a change pw request then return\r\nif( (!$is_change_display_email) && (!$is_change_pw) ) \r\n\tsendBack('You didn\\'t change anything, so Echelon has done nothing');\r\n\r\n## Query Section ##\r\n//$mem->reAuthUser($cur_pw, $dbl); // check user current password is correct\r\n\r\nif($is_change_display_email) : // if the display or email have been altered edit them if not skip this section\r\n\t// update display name and email\r\n\t$results = $dbl->editMe($display, $email, $mem->id);\r\n\tif(!$results) { // if false (if nothing happened)\r\n\t\tsendBack('There was an error updating your email and display name');\r\n\t} else { // its been changed so we must update the session vars\r\n\t\t$_SESSION['email'] = $email;\r\n\t\t$_SESSION['name'] = $display;\r\n\t\t$mem->setName($display);\r\n\t\t$mem->setEmail($email);\r\n\t}\r\nendif;\r\n\r\n## if a change pw request ##\r\nif($is_change_pw) : \r\n\r\n\t$result = $mem->genAndSetNewPW($pass1, $mem->id, $min_pw_len); // function to generate and set a new password\r\n\t\r\n\tif(is_string($result)) // result is either true (success) or an error message (string)\r\n\t\tsendBack($result); \r\nendif;\r\n\r\n ## return good ##\r\nsendGood('Your user information has been successfully updated');", "echelon/actions/settings-game.php": "connect_error) // send back with a failed connection message\r\n\tsendBack('Database Connection Error\r\n\t\t\t\t

            The connection information you supplied is incorrect.
            '.$db_test->connect_error.'

            '); \r\n\r\n## Update DB ##\r\nif($is_add) : // add game queries\r\n\t$result = $dbl->addGame($name, $game_type, $name_short, $db_host, $db_user, $db_pw, $db_name);\r\n\tif(!$result) // if everything is okay\r\n\t\tsendBack('There is a problem, the game information was not saved.');\r\n\t\r\n\t$dbl->addGameCount(); // Add one to the game counter in config table\t\r\n\t\r\nelse : // edit game queries\r\n\t$mem->reAuthUser($password, $dbl);\r\n\t$result = $dbl->setGameSettings($game, $name, $name_short, $db_user, $db_host, $db_name, $db_pw, $change_db_pw, $enabled); // update the settings in the DB\r\n\tif(!$result)\r\n\t\tsendBack('Something did not update. Did you edit anything?');\r\nendif;\r\n\r\n## Return with result message\r\nif($is_add) {\r\n\tset_good('Game Added');\r\n\tsend('../settings-games.php');\r\n} else \r\n\tsendGood('Your settings have been updated');\r\n", "echelon/actions/settings-server.php": "delServer($sid);\r\n\tif(!$result)\r\n\t\tsendBack('There was a problem with deleting the server');\r\n\t\r\n\t$result = $dbl->delServerUpdateGames($game_id);\r\n\tif(!$result)\r\n\t\tsendBack('There was a problem with deleting the server');\r\n\t\r\n\tsendGood('The server has been deleted');\r\n\t\r\n\texit; // stop - no need to load the rest of the page\r\n\r\nendif;\r\n\r\n## Check that the form was posted and that the user did not just stumble here ##\r\nif(!isset($_POST['server-settings-sub'])) :\r\n\tset_error('Please do not call that page directly, thank you.');\r\n\tsend('../index.php');\r\nendif;\r\n\r\n## What type of request is it ##\r\nif($_POST['type'] == 'add')\r\n\t$is_add = true;\r\nelseif($_POST['type'] == 'edit')\r\n\t$is_add = false;\r\nelse\r\n\tsendBack('Missing Data');\r\n\r\n## Check Token ##\r\nif($is_add) { // if add server request\r\n\tif(verifyFormToken('addserver', $tokens) == false) // verify token\r\n\t\tifTokenBad('Add Server');\r\n} else { // if edit server settings\r\n\tif(verifyFormToken('editserversettings', $tokens) == false) // verify token\r\n\t\tifTokenBad('Server Settings Edit');\r\n}\r\n\r\n## Get Vars ##\r\n$name = cleanvar($_POST['name']);\r\n$ip = cleanvar($_POST['ip']);\r\n$pb = cleanvar($_POST['pb']);\r\n// DB Vars\r\n$rcon_ip = cleanvar($_POST['rcon-ip']);\r\n$rcon_port = cleanvar($_POST['rcon-port']);\r\n$rcon_pw_cng = cleanvar($_POST['cng-pw']);\r\n$rcon_pw = cleanvar($_POST['rcon-pass']);\r\n$server_id = cleanvar($_POST['server']);\r\n\r\nif($is_add)\r\n\t$game_id = cleanvar($_POST['game-id']);\r\n\r\n// Whether to change RCON PW or not\r\nif($rcon_pw_cng == 'on')\r\n\t$change_rcon_pw = true;\r\nelse\r\n\t$change_rcon_pw = false;\r\n\t\r\n// Whether to change DB PW or not\r\nif($pb == 'on')\r\n\t$pb = 1;\r\nelse\r\n\t$pb = 0;\r\n\r\n## Check for empty vars ##\r\nemptyInput($name, 'server name');\r\nemptyInput($ip, 'server IP');\r\nemptyInput($rcon_ip, 'Rcon IP');\r\nemptyInput($rcon_port, 'Rcon Port');\r\nif($change_rcon_pw == true)\r\n\temptyInput($rcon_pw, 'Rcon password');\r\n\r\n// check that the rcon_ip is valid\r\nif(!filter_var($rcon_ip, FILTER_VALIDATE_IP))\r\n\tsendBack('That Rcon IP Address is not valid');\r\n\t\r\n// check that the rcon_ip is valid\r\nif( (!filter_var($ip, FILTER_VALIDATE_IP)))\r\n\tsendBack('That server IP Address is not valid');\r\n\t\r\n// Check Port is a number between 4-5 digits\r\nif( (!is_numeric($rcon_port)) || (!preg_match('/^[0-9]{4,5}$/', $rcon_port)) )\r\n\tsendBack('Rcon Port must be a number between 4-5 digits');\r\n\r\nif($is_add) : // if is add server request\r\n\tif(!is_numeric($game_id)) // game_id is a digit\r\n\t\tsendBack('Invalid data sent');\r\nendif;\r\n\t\r\n## Update DB ##\r\nif($is_add) :\r\n\t$result = $dbl->addServer($game_id, $name, $ip, $pb, $rcon_ip, $rcon_port, $rcon_pw);\r\n\t$dbl->addServerUpdateGames($game_id);\r\nelse :\r\n\t$result = $dbl->setServerSettings($server_id, $name, $ip, $pb, $rcon_ip, $rcon_port, $rcon_pw, $change_rcon_pw); // update the settings in the DB\r\nendif;\r\n\r\nif(!$result)\r\n\tsendBack('Something did not update');\r\n\r\n## Return ##\r\nif($is_add) {\r\n\tset_good('Server '. $name .' has been added to the database records');\r\n\tsend('../settings-server.php');\r\n} else\r\n\tsendGood('Your settings have been updated');\r\n", "echelon/actions/settings.php": "reAuthUser($password, $dbl);\r\n\t\r\n## Create array of sent vars ##\r\n$sent_settings = array(\r\n\t'name' => $f_name,\r\n\t'limit_rows' => $f_limit_rows,\r\n\t'min_pw_len' => $f_min_pw_len,\r\n\t'user_key_expire' => $f_user_key_expire,\r\n\t'email' => $f_email,\r\n\t'admin_name' => $f_admin_name,\r\n\t'https' => $f_https,\r\n\t'allow_ie' => $f_allow_ie,\r\n\t'time_format' => $f_time_format,\r\n\t'time_zone' => $f_time_zone, \r\n\t'email_header' => $f_email_header,\r\n\t'email_footer' => $f_email_footer,\r\n);\r\n\r\n## What needs updating ##\r\n// Check the values sent by the form against what is stored in the database to find out what needs to be updated\r\n// rather than just updating every config settings in the DB\r\n$settings_table = $dbl->getSettings('cosmos'); // get the values of the settings from the config db table\r\n\r\nif(!$no_games) :\r\n\t$sent_settings['pw_req_level'] = $f_pw_req_level;\r\n\t$sent_settings['pw_req_level_group'] = $f_pw_req_level_group;\r\nelse:\t\r\n\t$sent_settings['pw_req_level'] = $settings_table['pw_req_level'];\r\n\t$sent_settings['pw_req_level_group'] = $settings_table['pw_req_level_group'];\r\nendif;\r\n\r\nforeach($sent_settings as $key => $value) :\r\n\tif($sent_settings[$key] != $settings_table[$key])\r\n\t\t$updates[$key] = $value;\r\nendforeach;\r\n\r\n## Update DB ##\r\nforeach($updates as $key => $value) :\r\n\tif($key == 'limit_rows' || $key == 'min_pw_len' || $key == 'user_key_expire' || $key == 'pw_req_level')\r\n\t\t$value_type = 'i';\r\n\telse\r\n\t\t$value_type = 's';\r\n\t\t\r\n\tif($key != 'num_games') // num_games is the only cosmos setting not to be changed by this page\r\n\t\t$result = $dbl->setSettings($value, $key, $value_type); /// update the settings in the DB\r\n\t\r\n\tif($result == false)\r\n\t\tsendBack('Something did not update');\r\n\r\nendforeach;\r\n\r\n## Return ##\r\nsendGood('Your settings have been updated');\r\n", "echelon/actions/user-add.php": "';\r\n$body .= '

            Echelon User Key

            ';\r\n$body .= $config['cosmos']['email_header'];\r\n$body .= 'This is the key you will need to use to register on Echelon. \r\n\t\t\tRegister here.
            ';\r\n$body .= 'Registration Key: '.$user_key;\r\n$body .= $config['cosmos']['email_footer'];\r\n$body .= '';\r\n\r\n// replace %ech_name% in body of email with var from config\r\n$body = preg_replace('#%ech_name%#', $config['cosmos']['name'], $body);\r\n// replace %name%\r\n$body = preg_replace('#%name%#', 'new user', $body);\r\n\r\n$headers = \"From: echelon@\".$_SERVER['HTTP_HOST'].\"\\r\\n\";\r\n$headers .= \"Reply-To: \". EMAIL .\"\\r\\n\";\r\n$headers .= \"MIME-Version: 1.0\\r\\n\";\r\n$headers .= \"Content-Type: text/html; charset=ISO-8859-1\\r\\n\";\r\n$subject = \"Echelon User Registration\";\r\n\r\n// send email\r\nif(!mail($email, $subject, $body, $headers))\r\n\tsendback('There was a problem sending the email.');\r\n\t\r\n## run query to add key to the DB ##\r\n$add_user = $dbl->addEchKey($user_key, $email, $comment, $group, $mem->id);\r\nif(!$add_user)\r\n\tsendBack('There was a problem adding the key into the database');\r\n\r\n// all good send back good message\r\nsendGood('Key Setup and Email has been sent to user');", "echelon/active.php": "= 8\r\n\tAND c.group_bits <=64 AND(%d - c.time_edit > %d*60*60*24 )\", $time, $length);\r\n\r\n$query .= sprintf(\"ORDER BY %s \", $orderby);\r\n\r\n## Append this section to all queries since it is the same for all ##\r\nif($order == \"DESC\")\r\n\t$query .= \" DESC\"; // set to desc \r\nelse\r\n\t$query .= \" ASC\"; // default to ASC if nothing adds up\r\n\r\n$query_limit = sprintf(\"%s LIMIT %s, %s\", $query, $start_row, $limit_rows); // add limit section\r\n\r\n## Require Header ##\r\nrequire 'inc/header.php'; \r\n\r\nif(!$db->error) :\r\n?>\r\n\r\n admins who could be deemed as inactive\">\r\n\t\r\n\t\r\n\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\r\n\t\r\n\t\r\n\t\t\r\n\t\t\t\r\n\t\t\r\n\t\r\n\t\r\n\t 0) { // query contains stuff\r\n\t \r\n\t\tforeach($data_set as $info): // get data from query and loop\r\n\t\t\t$cid = $info['id'];\r\n\t\t\t$name = $info['name'];\r\n\t\t\t$level = $info['level'];\r\n\t\t\t$connections = $info['connections'];\r\n\t\t\t$time_edit = $info['time_edit'];\r\n\t\t\t\r\n\t\t\t## Change to human readable\t\t\r\n\t\t\t$time_diff = time_duration($time - $time_edit, 'yMwd');\t\t\r\n\t\t\t$time_edit = date($tformat, $time_edit); // this must be after the time_diff\r\n\t\t\t$client_link = clientLink($name, $cid);\r\n\r\n\t\t\t$alter = alter();\r\n\t\r\n\t\t\t// setup heredoc (table data)\t\t\t\r\n\t\t\t$data = <<\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\nEOD;\r\n\r\n\t\t\techo $data;\r\n\t\tendforeach;\r\n\t\t\r\n\t\t$no_data = false;\r\n\t} else {\r\n\t\t$no_data = true;\r\n\t\techo '';\r\n\t} // end if query contains information\r\n\t?>\r\n\t\r\n
            Inactive AdminsThere are admins who have not been seen by B3 for\r\n\t\t
            \r\n\t\t\t\r\n\t\t
            \r\n\t
            Name\r\n\t\t\t\t\r\n\t\t\tClient-id\r\n\t\t\t\t\r\n\t\t\tLevel\r\n\t\t\t\t\r\n\t\t\tConnections\r\n\t\t\t\t\r\n\t\t\tLast Seen\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\tDuration\r\n\t\t\t
            Click client name to see details
            $client_link@$cid$level$connections$time_edit$time_diff
            There are no admins that have been in active for more than '. $length . ' days.
            \r\n\r\n", "echelon/adminkicks.php": "error) :\r\n?>\r\n kicks made by admins in a servers\">\r\n\t\r\n\t\r\n\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\r\n\t\r\n\t\r\n\t\t\r\n\t\t\t\r\n\t\t\r\n\t\r\n\t\r\n\t 0) : // query contains stuff\r\n\r\n\t\tforeach($data_set as $data): // get data from query and loop\r\n\t\t\t$time_add = $data['time_add'];\r\n\t\t\t$reason = tableClean($data['reason']);\r\n\t\t\t$client_id = $data['target_id'];\r\n\t\t\t$client_name = tableClean($data['target_name']);\r\n\t\t\t$admin_id = $data['admin_id'];\r\n\t\t\t$admin_name = tableClean($data['admins_name']);\r\n\r\n\t\t\t## Tidt data to make more human friendly\r\n\t\t\tif($time_expire != '-1')\r\n\t\t\t\t$duration_read = time_duration($duration*60); // all penalty durations are stored in minutes, so multiple by 60 in order to get seconds\r\n\t\t\telse\r\n\t\t\t\t$duration_read = '';\r\n\r\n\t\t\t$time_add_read = date($tformat, $time_add);\r\n\t\t\t$reason_read = removeColorCode($reason);\r\n\t\t\t$client_link = clientLink($client_name, $client_id);\r\n\t\t\t$admin_link = clientLink($admin_name, $admin_id);\r\n\t\t\t\r\n\t\t\t## Row color\r\n\t\t\t$alter = alter();\r\n\r\n\t\t\t// setup heredoc (table data)\t\t\t\r\n\t\t\t$data = <<\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\nEOD;\r\n\r\n\t\techo $data;\r\n\t\tendforeach;\r\n\telse:\r\n\t\t$no_data = true;\r\n\t\techo '';\r\n\tendif; // no records\r\n\t?>\r\n\t\r\n
            Admin KicksThere are kicks that have been added by admins
            Client\r\n\t\t\t\t\r\n\t\t\tKicked At\r\n\t\t\t\t\r\n\t\t\tReason\r\n\t\t\t\tAdmin\r\n\t\t\t\t\r\n\t\t\t
            $client_link$time_add_read$reason_read$admin_link
            There are no kicks in the database
            \r\n\r\n", "echelon/admins.php": "= 8 ORDER BY %s\", $orderby);\r\n\r\n## Append this section to all queries since it is the same for all ##\r\n$order = strtoupper($order); // force uppercase to stop inconsistentcies\r\nif($order == \"DESC\")\r\n\t$query .= \" DESC\"; // set to desc \r\nelse\r\n\t$query .= \" ASC\"; // default to ASC if nothing adds up\r\n\r\n$query_limit = sprintf(\"%s LIMIT %s, %s\", $query, $start_row, $limit_rows); // add limit section\r\n\r\n## Require Header ##\t\r\nrequire 'inc/header.php';\r\n\r\nif(!$db->error) :\r\n?>\r\n\r\n\r\n\t\r\n\t\r\n\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\r\n\t\r\n\t\r\n\t\t\r\n\t\t\t\r\n\t\t\r\n\t\r\n\t\r\n\t 0) : // query contains stuff\r\n\t \r\n\t\tforeach($data_set as $data): // get data from query and loop\r\n\t\t\t$cid = $data['id'];\r\n\t\t\t$name = $data['name'];\r\n\t\t\t$level = $data['level'];\r\n\t\t\t$connections = $data['connections'];\r\n\t\t\t$time_edit = $data['time_edit'];\r\n\t\t\t\r\n\t\t\t## Change to human readable\t\t\r\n\t\t\t$time_edit_read = date($tformat, $time_edit); // this must be after the time_diff\r\n\t\t\t$client_link = clientLink($name, $cid);\r\n\t\t\t\r\n\t\t\t## row color\r\n\t\t\t$alter = alter();\r\n\t\r\n\t\t\t// setup heredoc (table data)\t\t\t\r\n\t\t\t$data = <<\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\nEOD;\r\n\r\n\t\t\techo $data;\r\n\t\tendforeach;\r\n\t\t\r\n\t\t$no_data = false;\r\n\telse:\r\n\t\t$no_data = true;\r\n\t\techo '';\r\n\tendif; // no records\r\n\t?>\r\n\t\r\n
            Admin ListingA list of all registered admins
            Name\r\n\t\t\t\t\r\n\t\t\tLevel\r\n\t\t\t\t\r\n\t\t\tClient-id\r\n\t\t\t\t\r\n\t\t\tConnections\r\n\t\t\t\t\r\n\t\t\tLast Seen\r\n\t\t\t\t\r\n\t\t\t
            $client_link$level@$cid$connections$time_edit_read
            There are no registered admins
            \r\n\r\n", "echelon/banlist.php": "Install');\r\n\r\nrequire 'classes/dbl-class.php'; // class to preform all DB related actions\r\n$dbl = DBL::getInstance(); // start connection to the local Echelon DB\r\n\r\n$games_list = $dbl->gamesBanlist();\r\n\r\n$num_games = $games_list['num_rows'];\r\n\r\nif($num_games > 0) :\r\n\r\n\trequire 'classes/mysql-class.php'; // class to preform all B3 DB related actions\r\n\t\r\n\theader(\"Content-type: text/plain\");\r\n\theader(\"Cache-Control: no-store, no-cache\");\r\n\techo \"\\n\";\r\n\techo \"//------------------------------------------------------\\n\";\r\n\techo \"// BAN LIST\\n\";\r\n\techo \"//------------------------------------------------------\\n\";\r\n\techo \"// Generated : \" . date(DATE_ATOM, time()) . \"\\n\";\r\n\techo \"//------------------------------------------------------\\n\";\r\n\techo \"//\\n\";\r\n\techo \"// Cut & paste into your banlist.txt or save it to use it directly. \\n\";\r\n\techo \"// The -1 places the ban forever.\\n\";\r\n\techo \"// The 0 in IPs prevents IP changing : the ban is made for all the IP mask ( from 0 to 255 ).\\n\";\r\n\techo \"// You need to set g_filterban to 1 on your server ( add g_filterban 1 to your cfg )\\n\";\r\n\techo \"//\\n\";\r\n\techo \"//------------------------------------------------------\\n\";\r\n\techo \"\\n\";\r\n\t\t\r\n\tforeach($games_list['data'] as $game) :\r\n\r\n\t\t$db = new DB_B3($game['db_host'], $game['db_user'], $game['db_pw'], $game['db_name'], true);\r\n\t\t\r\n\t\t$banInfo = new gameBanInfo($game['name']);\r\n\t\t\r\n\tendforeach;\r\n\t\r\nendif;\r\n\r\nclass gameBanInfo {\r\n \r\n\tprivate $game_name;\r\n\tprivate $banCount = 0;\r\n \r\n\tpublic function __construct($game_name) {\r\n\t\t$this->game_name = $game_name; // log the game name\r\n\t\t\r\n\t\t$results = $this->getBanFromDB(); // get the data from the db\r\n\t\t\r\n\t\t$this->banCount = $results['num_rows']; // find out how many bans there are\r\n\t\t\r\n\t\t$this->writeBans($results['data']); // spit out the results\r\n\t}\r\n\t\r\n\tpublic function destruct() {\r\n\t\t$this->banCount = 0;\r\n\t}\r\n\t\r\n\tprivate function getBanCount() {\r\n\t\treturn $this->banCount;\r\n\t}\r\n \r\n\tprivate function getBanFromDB() {\r\n\t\tglobal $db;\r\n\r\n\t\t$sql = \"SELECT p.id, p.type, p.time_add, p.reason, p.inactive, c.name, c.ip FROM penalties p, clients c WHERE p.type = 'Ban' AND inactive = 0 AND p.client_id = c.id AND p.time_expire = -1 AND c.ip != '' ORDER BY p.id DESC\";\r\n\t\t$results = $db->query($sql);\r\n\t\treturn $results;\r\n\t}\r\n \r\n\tpublic function writeBans($data) {\r\n\t\tglobal $config;\r\n\r\n\t\techo \"\\n\"; \r\n\t\techo \"\\n\";\r\n\t\techo \"---------------------------------------------------------------\\n\";\r\n\t\techo \"// Permanent bans from \" . $this->game_name . \" \\n\";\r\n\t\techo \"// There are \". $this->getBanCount() .\" permanent bans for this game \\n\";\r\n\t\tforeach ($data as $ban) :\r\n\t\t\t$text = preg_replace('/(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.\\d{1,3}/','$1.$2.$3.0',$ban['ip']) . ':-1 // ';\r\n\t\t\t$text .= $ban['name'];\r\n\t\t\t$text .= ' banned on ' . date('d/m/Y (H:i)',$ban['time_add']);\r\n\t\t\t$text .= ', reason : ' . $ban['reason'];\r\n\t\t\techo $text . \"\\n\";\r\n\t\tendforeach;\r\n\t} \r\n\r\n}\r\n", "echelon/bans.php": " 0 AND p.client_id = target.id AND p.admin_id = c.id\";\r\nelse\r\n\t$query = \"SELECT p.type, p.time_add, p.time_expire, p.reason, p.data, p.duration, p.client_id, c.name as client_name FROM penalties p LEFT JOIN clients c ON p.client_id = c.id WHERE p.admin_id = 0 AND (p.type = 'Ban' OR p.type = 'TempBan') AND p.inactive = 0\";\r\n\r\n\r\n$query .= sprintf(\" ORDER BY %s \", $orderby);\r\n\r\n## Append this section to all queries since it is the same for all ##\r\nif($order == \"DESC\")\r\n\t$query .= \" DESC\"; // set to desc \r\nelse\r\n\t$query .= \" ASC\"; // default to ASC if nothing adds up\r\n\r\n$query_limit = sprintf(\"%s LIMIT %s, %s\", $query, $start_row, $limit_rows); // add limit section\r\n\r\n## Require Header ##\t\r\nrequire 'inc/header.php';\r\n\r\nif(!$db->error) :\r\n\r\nif($type_admin) :\r\n\techo '';\r\n\t\techo '';\r\nelse :\r\n\techo '
            Admin BansThere are '. $total_rows .' active bans/tempbans that have been added by admins
            ';\r\n\t\techo '';\r\nendif;\r\n?>\r\n\r\n\t\r\n\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\tAdmin'; // only the admin type needs this header line ?>\r\n\t\t\r\n\t\r\n\t\r\n\t\t\r\n\t\t\t'; // admin type has 7 cols\r\n\t\t\t\telse \r\n\t\t\t\t\techo ''; // the b3 type has only 6 cols\r\n\t\t\t?>\r\n\t\t\r\n\t\r\n\t\r\n\t 0) { // query contains stuff\r\n\r\n\t\tforeach($data_set as $data): // get data from query and loop\r\n\t\t\t$type = $data['type'];\r\n\t\t\t$time_add = $data['time_add'];\r\n\t\t\t$time_expire = $data['time_expire'];\r\n\t\t\t$reason = tableClean($data['reason']);\r\n\t\t\t$pen_data = tableClean($data['data']);\r\n\t\t\t$duration = $data['duration'];\r\n\t\t\t$client_id = $data['client_id'];\r\n\t\t\t$client_name = tableClean($data['client_name']);\r\n\t\t\t\r\n\t\t\tif($type_admin) { // only admin type needs these lines\r\n\t\t\t\t$admin_id = $data['admins_id'];\r\n\t\t\t\t$admin_name = tableClean($data['admins_name']);\r\n\t\t\t}\r\n\r\n\t\t\t## Tidt data to make more human friendly\r\n\t\t\tif($time_expire != '-1')\r\n\t\t\t\t$duration_read = time_duration($duration*60); // all penalty durations are stored in minutes, so multiple by 60 in order to get seconds\r\n\t\t\telse\r\n\t\t\t\t$duration_read = '';\r\n\r\n\t\t\t$time_expire_read = timeExpirePen($time_expire);\r\n\t\t\t$time_add_read = date($tformat, $time_add);\r\n\t\t\t$reason_read = removeColorCode($reason);\r\n\t\t\t\r\n\t\t\tif($type_admin) // admin cell only needed for admin type\r\n\t\t\t\t$admin = '';\r\n\t\t\telse\r\n\t\t\t\t$admin = NULL;\r\n\r\n\t\t\t## Row color\r\n\t\t\t$alter = alter();\r\n\t\t\t\t\r\n\t\t\t$client = clientLink($client_name, $client_id);\r\n\r\n\t\t\t// setup heredoc (table data)\t\t\t\r\n\t\t\t$data = <<\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t$admin\r\n\t\t\t\r\nEOD;\r\n\r\n\t\t\techo $data;\r\n\t\tendforeach;\r\n\t\t\r\n\t\t$no_data = false;\r\n\t} else {\r\n\t\t$no_data = true;\r\n\t\tif($type_admin) // slight chnages between different page types\r\n\t\t\techo '';\r\n\t\telse\r\n\t\t\techo '';\r\n\t} // end if query contains\r\n\t?>\r\n\t\r\n
            B3 BansThere are '. $total_rows .' active bans/tempbans that have been added by the B3 bot
            Target\r\n\t\t\t\t\r\n\t\t\tType\r\n\t\t\t\t\r\n\t\t\tAdded\r\n\t\t\t\t\r\n\t\t\tDuration\r\n\t\t\t\t\r\n\t\t\tExpires\r\n\t\t\t\t\r\n\t\t\tReason
            '. clientLink($admin_name, $admin_id) .'$client$type$time_add_read$duration_read$time_expire_read$reason_read\r\n\t\t\t\t\t
            $pen_data\r\n\t\t\t\t
            There no tempbans or bans made by admins in the database
            There no tempbans or bans made by the B3 bot in the database
            \r\n\r\n", "echelon/classes/dbl-class.php": "install = $install;\r\n\t\t\r\n\t\ttry { \r\n\t\t\t$this->connectDB(); // try to connect to the database\r\n\t\t\t\r\n\t\t} catch (Exception $e) {\r\n\t\t\r\n\t\t\tif($this->install) // if this is an install test return message\r\n\t\t\t\t$this->install_error = $e->getMessage();\r\n\t\t\telse\r\n\t\t\t\tdie($e->getMessage());\r\n\t\t\t\r\n\t\t} // end try/catch\r\n\t\t\r\n\t} // end construct\r\n\t\r\n\t// Do not allow the clone operation\r\n private function __clone() { }\r\n\r\n\t/**\r\n * Makes the connection to the DB or throws error\r\n */\r\n private function connectDB () {\r\n\t\tif($this->mysql != NULL) // if it is set/created (default starts at NULL)\r\n\t\t\t@$this->mysql->close();\r\n\r\n $this->mysql = @new mysqli(DBL_HOSTNAME, DBL_USERNAME, DBL_PASSWORD, DBL_DB); // block any error on connect, it will be caught in the next line and handled properly\r\n\t\t\r\n\t\tif(mysqli_connect_errno()) : // if the connection error is on then throw exception\r\n\r\n\t\t\tif($this->install) :\r\n\t\t\t\t$error_msg = 'Database Connection Error\r\n\t\t\t\t\t

            '.mysqli_connect_error().'
            \r\n\t\t\t\t\tThe connection information you supplied is incorrect. Please try again.

            ';\r\n\t\t\t\r\n\t\t\telseif(DB_CON_ERROR_SHOW) : // only if settings say show to con error, will we show it, else just say error\r\n\t\t\t\t$error_msg = '

            Database Connection Error

            \r\n\t\t\t\t\t

            '.mysqli_connect_error().'
            \r\n\t\t\t\t\tSince we have encountered a database error, Echelon is shutting down.

            ';\r\n\t\t\t\t\t\t\t\t\r\n\t\t\telse :\r\n\t\t\t\t$error_msg = '

            Database Problem

            \r\n\t\t\t\t\t

            Since we have encountered a database error, Echelon is shutting down.

            ';\r\n\t\t\t\t\t\t\t\t\r\n\t\t\tendif;\r\n\r\n\t\t\tthrow new Exception($error_msg);\r\n\t\tendif;\r\n\t\t\r\n } // end connect\r\n\t\r\n\t/**\r\n * __destruct : Destructor for class, closes the MySQL connection\r\n */\r\n public function __destruct() {\r\n if ($this->mysql != NULL) // if it is set/created (defalt starts at NULL)\r\n @$this->mysql->close(); // close the connection\r\n }\r\n\t\r\n\t/**\r\n\t * Handy Query function\r\n\t *\r\n\t * @param string $sql - the SQL query to execute\r\n\t * @param bool $fetch - fetch the data rows or not\r\n\t * @param string $type - typpe of query this is \r\n\t */\r\n\tprivate function query($sql, $fetch = true, $type = 'select') {\r\n\r\n\t\tif($this->error)\r\n\t\t\treturn false;\r\n\t\t\r\n\t\ttry {\r\n\t\t\r\n\t\t\tif($stmt = $this->mysql->prepare($sql))\r\n\t\t\t\t$stmt->execute();\r\n\t\t\telse\r\n\t\t\t\tthrow new Exception('');\r\n\r\n\t\t} catch (Exception $e) {\r\n\t\t\r\n\t\t\t$this->error = true; // there is an error\r\n\t\t\tif($this->error_on) // if detailed errors work\r\n\t\t\t\t$this->error_msg = \"MySQL Query Error (#\". $this->mysql->errno .\"): \". $this->mysql->error;\r\n\t\t\telse\r\n\t\t\t\t$this->error_msg = $this->error_sec;\r\n\r\n\t\t\treturn;\r\n\t\t}\r\n\t\t\r\n\t\t## setup results array\r\n\t\t$results = array();\r\n\t\t$results['data'] = array();\r\n\t\t\r\n\t\t## do certain things depending on type of query\r\n\t\tswitch($type) { \r\n\t\t\tcase 'select': // if type is a select query\r\n\t\t\t\t$stmt->store_result();\r\n\t\t\t\t$results['num_rows'] = $stmt->num_rows(); // find the number of rows retrieved\r\n\t\t\tbreak;\r\n\t\t\t\r\n\t\t\tcase 'update':\r\n\t\t\tcase 'insert': // if insert or update find the number of rows affected by the query\r\n\t\t\t\t$results['affected_rows'] = $stmt->affected_rows(); \r\n\t\t\tbreak;\r\n\t\t}\r\n\t\t\r\n\t\t## fetch the results\r\n\t\tif($fetch) : // only fetch data if we need it\r\n\t\t\r\n\t\t\t$meta = $stmt->result_metadata();\r\n\r\n\t\t\twhile ($field = $meta->fetch_field()) :\r\n\t\t\t\t$parameters[] = &$row[$field->name];\r\n\t\t\tendwhile;\r\n\r\n\t\t\tcall_user_func_array(array($stmt, 'bind_result'), $parameters);\r\n\r\n\t\t\twhile ($stmt->fetch()) :\r\n\t\t\t\tforeach($row as $key => $val) {\r\n\t\t\t\t\t$x[$key] = $val;\r\n\t\t\t\t}\r\n\t\t\t\t$results['data'][] = $x;\r\n\t\t\tendwhile;\r\n\r\n\t\tendif;\r\n\t\t\r\n\t\t## return and close off connections\r\n\t\treturn $results;\r\n\t\t$results->close();\r\n\t\t$stmt->close();\r\n\t\t\r\n\t} // end query()\r\n\t\r\n\t/***************************\r\n\t\r\n\t\tStart Query Functions\r\n\t\r\n\t****************************/\r\n\t\r\n\t\r\n\t/**\r\n\t * Gets an array of data for the settings form\r\n\t *\r\n\t * @param string $cat - category of settigs to retrieve\r\n\t * @return array\r\n\t */\r\n\tfunction getSettings() {\r\n $query = \"SELECT SQL_CACHE name, value FROM ech_config\";\r\n $stmt = $this->mysql->prepare($query) or die('Database Error');\r\n\t\t$stmt->execute();\r\n\t\t\r\n\t\t$stmt->store_result();\r\n\t\t$stmt->bind_result($name, $value);\r\n \r\n\t\t$settings = array();\r\n\t\t\r\n while($stmt->fetch()) : // get results\r\n $settings[$name] = $value;\r\n endwhile;\r\n\t\t\r\n\t\t$stmt->close();\r\n\t\t\r\n return $settings;\r\n }\r\n\t\r\n\tfunction getGameInfo($game) {\r\n\t\r\n\t\t$query = \"SELECT SQL_CACHE id, game, name, name_short, num_srvs, db_host, db_user, db_pw, db_name, plugins FROM ech_games WHERE id = ?\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error');\r\n\t\t$stmt->bind_param('i', $game);\r\n\t\t$stmt->execute();\r\n\t\t\r\n\t\t$stmt->bind_result($id, $game, $name, $name_short, $num_srvs, $db_host, $db_user, $db_pw, $db_name, $plugins);\r\n $stmt->fetch(); // get results\t\t\r\n\t\t\r\n\t\t$game = array(\r\n\t\t\t'id' => $id,\r\n\t\t\t'game' => $game,\r\n\t\t\t'name' => $name,\r\n\t\t\t'name_short' => $name_short,\r\n\t\t\t'num_srvs' => $num_srvs,\r\n\t\t\t'db_host' => $db_host,\r\n\t\t\t'db_user' => $db_user,\r\n\t\t\t'db_pw' => $db_pw,\r\n\t\t\t'db_name' => $db_name,\r\n\t\t\t'plugins' => $plugins\r\n\t\t);\r\n\t\t\r\n\t\treturn $game;\r\n\t}\r\n \r\n\t/**\r\n\t * Update the settings\r\n\t *\r\n\t * @param string/int $value - the new value for the setting\r\n\t * @param string $name - the name of the settings\r\n\t * @param string $value_type - wheather the value provided is a string or an int\r\n\t * @return bool\r\n\t */\r\n function setSettings($value, $name, $value_type) {\r\n \r\n\t\t$query = \"UPDATE ech_config SET value = ? WHERE name = ? LIMIT 1\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error');\r\n\t\t$stmt->bind_param($value_type.'s', $value, $name);\r\n\t\t$stmt->execute();\r\n\t\t\r\n\t\t$affect = $stmt->affected_rows;\r\n\t\t$stmt->close();\r\n\t\t\r\n\t\tif($affect > 0)\r\n\t\t\treturn true;\r\n\t\telse\r\n\t\t\treturn false;\r\n }\r\n\t\r\n\t/**\r\n\t * Update game settings\r\n\t *\r\n\t * @return bool\r\n\t */\r\n function setGameSettings($game, $name, $name_short, $db_user, $db_host, $db_name, $db_pw, $change_db_pw, $plugins) {\r\n\t\t\r\n\t\t$query = \"UPDATE ech_games SET name = ?, name_short = ?, db_host = ?, db_user = ?, db_name = ?, plugins = ?\";\r\n\t\t\r\n\t\tif($change_db_pw) // if the DB password is to be chnaged\r\n\t\t\t$query .= \", db_pw = ?\";\r\n\r\n\t\t$query .= \" WHERE id = ? LIMIT 1\";\r\n\t\t\t\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error');\r\n\t\tif($change_db_pw) // if change DB PW append var\r\n\t\t\t$stmt->bind_param('sssssssi', $name, $name_short, $db_host, $db_user, $db_name, $plugins, $db_pw, $game);\r\n\t\telse // else var info not needed in bind_param\r\n\t\t\t$stmt->bind_param('ssssssi', $name, $name_short, $db_host, $db_user, $db_name, $plugins, $game);\r\n\t\t$stmt->execute();\r\n\t\t\r\n\t\tif($stmt->affected_rows > 0)\r\n\t\t\treturn true;\r\n\t\telse\r\n\t\t\treturn false;\r\n }\r\n\t\r\n\t/**\r\n\t * Add a Game to the Echelon list\r\n\t *\r\n\t * @param string $name - name of the game\r\n\t * @param string $game - the game type (eg. cod4, cod2, bfbc2)\r\n\t * @param string $name_short - short name for the game\r\n\t * @param string $db_host - database host\r\n\t * @param string $db_user - database user\r\n\t * @param string $db_pw - database password\r\n\t * @param string $db_name - database name\r\n\t * @return bool\r\n\t */\r\n\tfunction addGame($name, $game, $name_short, $db_host, $db_user, $db_pw, $db_name) {\r\n\t\t// id, name, game, name_short, num_srvs, db_host, db_user, db_pw, db_name\r\n\t\t$query = \"INSERT INTO ech_games (name, game, name_short, num_srvs, db_host, db_user, db_pw, db_name) VALUES(?, ?, ?, 0, ?, ?, ?, ?)\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error:'. $this->mysql->error);\r\n\t\t$stmt->bind_param('sssssss', $name, $game, $name_short, $db_host, $db_user, $db_pw, $db_name);\r\n\t\t$stmt->execute();\r\n\t\t\r\n\t\tif($stmt->affected_rows > 0)\r\n\t\t\treturn true;\r\n\t\telse\r\n\t\t\treturn false;\r\n\t}\r\n\t\r\n\tfunction addGameCount() {\r\n\t\t$query = \"UPDATE ech_config SET value = (value + 1) WHERE name = 'num_games' LIMIT 1\";\r\n\t\t$result = $this->mysql->query($query) or die('Database Error');\r\n\t\t\r\n\t\treturn $result;\r\n\t}\r\n\t\r\n\tfunction getServers($cur_game) {\r\n\t\t$query = \"SELECT SQL_CACHE id, name, ip, pb_active, rcon_pass, rcon_ip, rcon_port FROM ech_servers WHERE game = ?\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error');\r\n\t\t$stmt->bind_param('i', $cur_game);\r\n\t\t$stmt->execute();\r\n\t\t$stmt->bind_result($id, $name, $ip, $pb_active, $rcon_pass, $rcon_ip, $rcon_port); // bind results into vars\r\n\r\n\t\twhile($stmt->fetch()) : // get results and store in an array\r\n\t\t\t$servers[] = array(\r\n\t\t\t\t'id' => $id,\r\n\t\t\t\t'name' => $name,\r\n\t\t\t\t'ip' => $ip,\r\n\t\t\t\t'pb_active' => $pb_active,\r\n\t\t\t\t'rcon_pass' => $rcon_pass,\r\n\t\t\t\t'rcon_ip' => $rcon_ip,\r\n\t\t\t\t'rcon_port' => $rcon_port\r\n\t\t\t);\r\n\t\tendwhile;\r\n\t\t\r\n\t\t$stmt->close();\r\n\t\treturn $servers;\r\n\t}\r\n\t\r\n\tfunction getServer($id) {\r\n\t\t$query = \"SELECT game, name, ip, pb_active, rcon_pass, rcon_ip, rcon_port FROM ech_servers WHERE id = ?\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error');\r\n\t\t$stmt->bind_param('i', $id);\r\n\t\t$stmt->execute();\r\n\t\t$stmt->bind_result($game, $name, $ip, $pb_active, $rcon_pass, $rcon_ip, $rcon_port); // bind results into vars\r\n\r\n\t\twhile($stmt->fetch()) : // get results and store in an array\r\n\t\t\t$server = array(\r\n\t\t\t\t'game' => $game,\r\n\t\t\t\t'name' => $name,\r\n\t\t\t\t'ip' => $ip,\r\n\t\t\t\t'pb_active' => $pb_active,\r\n\t\t\t\t'rcon_pass' => $rcon_pass,\r\n\t\t\t\t'rcon_ip' => $rcon_ip,\r\n\t\t\t\t'rcon_port' => $rcon_port\r\n\t\t\t);\r\n\t\tendwhile;\r\n\t\t\r\n\t\t$stmt->close();\r\n\t\treturn $server;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Gets a list of all the servers from all the games for the servers table\r\n\t *\r\n\t * @param string $orderby - what var to order by\r\n\t * @param string $order - which way to order (ASC/DESC)\r\n\t * @return bool\r\n\t */\r\n\tfunction getServerList($orderby, $order) {\r\n\t\t\t\r\n\t\t$query = \"SELECT s.id, s.name, s.ip, s.game, s.pb_active, g.name as g_name FROM ech_servers s LEFT JOIN ech_games g ON s.game = g.id ORDER BY \".$orderby.\" \".$order;\r\n\t\t$result = $this->mysql->query($query);\r\n\t\t$num_rows = $result->num_rows;\r\n\t\t\r\n\t\tif($num_rows > 0) :\r\n\t\t\twhile($row = $result->fetch_object()) : // get results\t\t\r\n\t\t\t\t$servers[] = array(\r\n\t\t\t\t\t'id' => $row->id,\r\n\t\t\t\t\t'game' => $row->game,\r\n\t\t\t\t\t'name' => $row->name,\r\n\t\t\t\t\t'ip' => $row->ip,\r\n\t\t\t\t\t'pb_active' => $row->pb_active,\r\n\t\t\t\t\t'game_name' => $row->g_name\r\n\t\t\t\t);\r\n\t\t\tendwhile;\r\n\t\t\t\r\n\t\t\treturn $servers; // return the information\r\n\t\t\t\r\n\t\telse :\r\n\t\t\treturn false;\r\n\t\t\r\n\t\tendif;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Update server settings\r\n\t *\r\n\t * @return bool\r\n\t */\r\n function setServerSettings($server_id, $name, $ip, $pb, $rcon_ip, $rcon_port, $rcon_pw, $change_rcon_pw) {\r\n\t\t\r\n\t\t$query = \"UPDATE ech_servers SET name = ?, ip = ?, pb_active = ?, rcon_ip = ?, rcon_port = ?\";\r\n\t\t\r\n\t\tif($change_rcon_pw) // if the DB password is to be chnaged\r\n\t\t\t$query .= \", rcon_pass = ?\";\r\n\r\n\t\t$query .= \" WHERE id = ? LIMIT 1\";\r\n\t\t\t\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error');\r\n\t\tif($change_rcon_pw) // if change RCON PW append\r\n\t\t\t$stmt->bind_param('ssisisi', $name, $ip, $pb, $rcon_ip, $rcon_port, $rcon_pw, $server_id);\r\n\t\telse // else info not needed in bind_param\r\n\t\t\t$stmt->bind_param('ssisii', $name, $ip, $pb, $rcon_ip, $rcon_port, $server_id);\r\n\t\t$stmt->execute();\r\n\t\t\r\n\t\tif($stmt->affected_rows > 0)\r\n\t\t\treturn true;\r\n\t\telse\r\n\t\t\treturn false;\t\r\n }\r\n\t\r\n\t/**\r\n\t * Add a server\r\n\t *\r\n\t * @return bool\r\n\t */\r\n function addServer($game_id, $name, $ip, $pb, $rcon_ip, $rcon_port, $rcon_pw) {\r\n\t\t\r\n\t\t// id, game, name, ip, pb_active, rcon_pass, rcon_ip, rcon_port\r\n\t\t$query = \"INSERT INTO ech_servers VALUES(NULL, ?, ?, ?, ?, ?, ?, ?)\";\r\n\t\t\t\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error');\r\n\t\t$stmt->bind_param('ississi', $game_id, $name, $ip, $pb, $rcon_pw, $rcon_ip, $rcon_port);\r\n\t\t$stmt->execute();\r\n\t\t\r\n\t\t$affect = $stmt->affected_rows;\r\n\t\t$stmt->close();\r\n\t\t\r\n\t\tif($affect > 0)\r\n\t\t\treturn true;\r\n\t\telse\r\n\t\t\treturn false;\t\r\n }\r\n\t\r\n\t/**\r\n\t * After adding a server we need to update the games table to add 1 to num_srvs\r\n\t *\r\n\t * @param int $game_id - the id of the game that is to be updated\r\n\t */\r\n\tfunction addServerUpdateGames($game_id) {\r\n\t\t$query = \"UPDATE ech_games SET num_srvs = (num_srvs + 1) WHERE id = ? LIMIT 1\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error:'. $this->mysql->error);;\r\n\t\t$stmt->bind_param('i', $game_id);\r\n\t\t$stmt->execute();\r\n\t\t\r\n\t\t$affect = $stmt->affected_rows;\r\n\t\t$stmt->close();\r\n\t\t\r\n\t\tif($affect > 0)\r\n\t\t\treturn true;\r\n\t\telse\r\n\t\t\treturn false;\r\n\t}\r\n\t\r\n\tfunction delServerUpdateGames($game_id) {\r\n\t\t$query = \"UPDATE ech_games SET num_srvs = (num_srvs - 1) WHERE id = ? LIMIT 1\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error:'. $this->mysql->error);;\r\n\t\t$stmt->bind_param('i', $game_id);\r\n\t\t$stmt->execute();\r\n\t\t\r\n\t\t$affect = $stmt->affected_rows;\r\n\t\t$stmt->close();\r\n\t\t\r\n\t\tif($affect > 0)\r\n\t\t\treturn true;\r\n\t\telse\r\n\t\t\treturn false;\r\n\t}\r\n\t\r\n\tfunction getGamesList() {\r\n\t\t$query = \"SELECT SQL_CACHE id, name, name_short FROM ech_games ORDER BY id ASC\";\r\n\t\t$results = $this->mysql->query($query) or die('Database error');\r\n\t\t\r\n\t\twhile($row = $results->fetch_object()) :\t\r\n\t\t\t$games[] = array(\r\n\t\t\t\t'id' => $row->id,\r\n\t\t\t\t'name' => $row->name,\r\n\t\t\t\t'name_short' => $row->name_short\r\n\t\t\t);\r\n\t\tendwhile;\r\n\t\treturn $games;\r\n\t}\r\n\t\r\n\t/**\r\n\t * This function gets the salt value from the users table by using a clients username\r\n\t *\r\n\t * @param string $username - username of the user you want to find the salt of\r\n\t * @return string/false\r\n\t */\r\n\tfunction getUserSalt($username) {\r\n\t\t\r\n\t\t$query = \"SELECT salt FROM ech_users WHERE username = ?\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error');\r\n\t\t$stmt->bind_param('s', $username);\r\n\t\t$stmt->execute(); // run query\r\n\t\t\r\n\t\t$stmt->store_result(); // store results\r\n\t\t$stmt->bind_result($salt); // store result\r\n\t\t$stmt->fetch(); // get the one result result\r\n\r\n\t\tif($stmt->num_rows == 1)\r\n\t\t\treturn $salt;\r\n\t\telse\r\n\t\t\treturn false;\r\n\t\t\r\n\t\t$stmt->free_result();\r\n\t\t$stmt->close();\r\n\t}\r\n\t\r\n\t/**\r\n\t * This function returns an array of permissions for users\r\n\t *\r\n\t * @return array\r\n\t */\r\n\tfunction getPermissions($get_desc = true) {\r\n\t\r\n\t\tif($get_desc)\r\n\t\t\t$query = \"SELECT * FROM ech_permissions\";\r\n\t\telse\r\n\t\t\t$query = \"SELECT id, name FROM ech_permissions\";\r\n\t\t\t\r\n\t\t$query .= \" ORDER BY id ASC\";\r\n\t\t\t\r\n\t\t$results = $this->mysql->query($query);\r\n\t\t\r\n\t\twhile($row = $results->fetch_object()) : // get results\r\n\t\t\r\n\t\t\tif($get_desc) : // if get desc then return desc in results\r\n\t\t\t\t$perms[] = array(\r\n\t\t\t\t\t'id' => $row->id,\r\n\t\t\t\t\t'name' => $row->name,\r\n\t\t\t\t\t'desc' => $row->description\r\n\t\t\t\t);\r\n\t\t\t\t\r\n\t\t\telse : // else dont return the desc of the perm\r\n\t\t\t\t$perms[] = array(\r\n\t\t\t\t\t'id' => $row->id,\r\n\t\t\t\t\t'name' => $row->name,\r\n\t\t\t\t);\r\n\t\t\tendif;\r\n\t\t\t\r\n\t\tendwhile;\r\n\t\treturn $perms;\r\n\t}\r\n \r\n\t/**\r\n\t * This function validates user login info and if correct to return some user info\r\n\t *\r\n\t * @param string $username - username of user for login validation\r\n\t * @param string $pw - password of user for login validation\r\n\t * @return array/false\r\n\t */\r\n\tfunction login($username, $pw) {\r\n\r\n\t\t$query = \"SELECT u.id, u.ip, u.last_seen, u.display, u.email, u.ech_group, g.premissions FROM ech_users u LEFT JOIN ech_groups g ON u.ech_group = g.id WHERE u.username = ? AND u.password = ? LIMIT 1\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error');\r\n\t\t$stmt->bind_param('ss', $username, $pw);\r\n\t\t$stmt->execute(); // run query\r\n\t\t\r\n\t\t$stmt->store_result(); // store results\t\r\n\t\t$stmt->bind_result($id, $ip, $last_seen, $name, $email, $group, $perms); // store results\r\n\t\t$stmt->fetch(); // get results\r\n\r\n\t\tif($stmt->num_rows == 1):\r\n\t\t\t$results = array($id, $ip, $last_seen, $name, $email, $group, $perms);\r\n\t\t\treturn $results; // yes log them in\r\n\t\telse :\r\n\t\t\treturn false;\r\n\t\tendif;\r\n\t\t\r\n\t\t$stmt->free_result();\r\n\t\t$stmt->close();\r\n\t}\r\n\t\r\n\t/**\r\n\t * This function updates user records with new IP address and time last seen\r\n\t *\r\n\t * @param string $ip - current IP address to upodate DB records\r\n\t * @param int $id - id of the current user \r\n\t */\r\n\tfunction newUserInfo($ip, $id) { // updates user records with new IP, time of login and sets active to 1 if needed\r\n\t\t\r\n\t\t$time = time();\r\n\t\t$query = \"UPDATE ech_users SET ip = ?, last_seen = ? WHERE id = ?\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error');\r\n\t\t$stmt->bind_param('sii', $ip, $time, $id);\r\n\t\t$stmt->execute(); // run query\r\n\t\t$stmt->close(); // close connection\r\n\t}\r\n\t\r\n\t/**\r\n\t * This function checks to see if the current user IP is on the blacklist\r\n\t *\r\n\t * @param string $ip - IP addrss of current user to check of current BL\r\n\t * @return bool\r\n\t */\r\n\tfunction checkBlacklist($ip) {\r\n\r\n\t\t$query = \"SELECT id FROM ech_blacklist WHERE ip = ? AND active = 1 LIMIT 1\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database error');\r\n\t\t$stmt->bind_param('s', $ip);\r\n\t\t$stmt->execute();\r\n\r\n\t\t$stmt->store_result();\r\n\t\t\r\n\t\tif($stmt->num_rows > 0)\r\n\t\t\treturn true;\r\n\t\t\r\n\t\t$stmt->free_result();\r\n\t\t$stmt->close();\r\n\t\t\r\n\t\treturn false;\r\n\t}\r\n\r\n\t/**\r\n\t * Blacklist a user's IP address\r\n\t *\r\n\t * @param string $ip - IP address you wish to ban\r\n\t * @param string $comment [optional] - Comment about reason for ban\r\n\t * @param int $admin - id of the admin who added the ban (0 if auto added)\r\n\t */\r\n\tfunction blacklist($ip, $comment = 'Auto Added Ban', $admin = 0) { // add an Ip to the blacklist\r\n\t\t$comment = cleanvar($comment);\r\n\t\t$time = time();\r\n\t\t// id, ip, active, reason, time_add, admin_id\r\n\t\t$query = \"INSERT INTO ech_blacklist VALUES(NULL, ?, 1, ?, ?, ?)\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database error');\r\n\t\t$stmt->bind_param('ssii', $ip, $comment, $time, $admin);\r\n\t\t$stmt->execute(); // run query\r\n\t\t\r\n\t\t$affect = $stmt->affected_rows;\r\n\t\t$stmt->close();\r\n\t\t\r\n\t\tif($affect > 0)\r\n\t\t\treturn true;\r\n\t\telse\r\n\t\t\treturn false;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Get an array of data about the Blacklist for a table\r\n\t *\r\n\t * @return array\r\n\t */\r\n\tfunction getBL() { // return the rows of info for the BL table\r\n\r\n\t\t$query = \"SELECT bl.id, bl.ip, bl.active, bl.reason, bl.time_add, u.display \r\n\t\t\t\t\tFROM ech_blacklist bl LEFT JOIN ech_users u ON bl.admin_id = u.id \r\n\t\t\t\t\tORDER BY active ASC\";\t\r\n\t\t\r\n\t\t$results = $this->query($query);\r\n\t\t\r\n\t\treturn $results;\r\n\t}\r\n\t\r\n\t/**\r\n\t * De/Re-actives a Blacklist Ban\r\n\t *\r\n\t * @param int $id - id of the ban\r\n\t * @param bool $active - weather to activate or deactivate\r\n\t */\r\n\tfunction BLactive($id, $active = true) {\r\n\r\n\t\tif($active == false)\r\n\t\t\t$active = 0;\r\n\t\telse\r\n\t\t\t$active = 1;\r\n\r\n\t\t$query = \"UPDATE ech_blacklist SET active = ? WHERE id = ? LIMIT 1\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error');\r\n\t\t$stmt->bind_param('ii', $active, $id);\r\n\t\t$stmt->execute(); // run query\r\n\t\t$stmt->close(); // close connection\r\n\r\n\t} // end BLactive\r\n\r\n\t/**\r\n\t * Gets an array of data for the users table\r\n\t *\r\n\t * @return array\r\n\t */\r\n\tfunction getUsers() { // gets an array of all the users basic info\r\n\r\n\t\t$query = \"SELECT u.id, u.display, u.email, u.ip, u.first_seen, u.last_seen, g.namep FROM ech_users u LEFT JOIN ech_groups g ON u.ech_group = g.id ORDER BY id ASC\";\r\n\t\t\r\n\t\t$users = $this->query($query);\r\n\t\t\r\n\t\treturn $users;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Gets a list of all currently valid registration keys\r\n\t *\r\n\t * @param $key_expire - the setting for how many days a key is valid for\r\n\t * @return array\r\n\t */\r\n\tfunction getKeys($key_expire) {\r\n\t\t$limit_seconds = $key_expire*24*60*60; // user_key_limit is sent in days so we must convert it\r\n\t\t$time = time();\r\n\t\t$expires = $time+$limit_seconds;\r\n\t\t$query = \"SELECT k.reg_key, k.email, k.comment, k.time_add, k.admin_id, u.display \r\n\t\t\t\t FROM ech_user_keys k LEFT JOIN ech_users u ON k.admin_id = u.id\r\n\t\t\t\t WHERE k.active = 1 AND k.time_add < ? AND comment != 'PW' ORDER BY time_add ASC\";\r\n\r\n\t\t$reg_keys = $this->query($query);\r\n\t\t\r\n\t\treturn $reg_keys;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Check a username is not already in use\r\n\t *\r\n\t * @param string $username - username to check\r\n\t * @return bool\r\n\t */\r\n\tfunction checkUsername($username) {\r\n\r\n\t\t$query = \"SELECT username FROM ech_users WHERE username = ? LIMIT 1\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error');\r\n\t\t$stmt->bind_param('s', $username);\r\n\t\t$stmt->execute(); // run query\r\n\t\t$stmt->store_result(); // store query\r\n\t\t\r\n\t\tif($stmt->num_rows >= 1) // if there is a row\r\n\t\t\treturn false;\r\n\t\telse\r\n\t\t\treturn true;\r\n\t\t\r\n\t\t$stmt->free_result();\r\n\t\t$stmt->close();\r\n\t}\r\n\t\r\n\t/**\r\n\t * Find the users pasword salt by using their id\r\n\t *\r\n\t * @param int $user_id\r\n\t * @return string/false\r\n\t */\r\n\tfunction getUserSaltById($user_id) {\r\n\t\t\r\n\t\t$query = \"SELECT salt FROM ech_users WHERE id = ? LIMIT 1\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error');\r\n\t\t$stmt->bind_param('s', $user_id);\r\n\t\t$stmt->execute(); // run query\r\n\t\t\r\n\t\t$stmt->store_result(); // store results // needed for num_rows\r\n\t\t$stmt->bind_result($salt); // store result\r\n\t\t$stmt->fetch(); // get the one result result\r\n\r\n\t\tif($stmt->num_rows == 1)\r\n\t\t\treturn $salt;\r\n\t\telse\r\n\t\t\treturn false;\r\n\t\t\r\n\t\t$stmt->free_result();\r\n\t\t$stmt->close();\r\n\t}\r\n\t\r\n\t/**\r\n\t * Checks that a users password is correct (needed to verify user idenity with edit me page)\r\n\t *\r\n\t * @param int $user_id - id of the user\r\n\t * @param string $hash_pw - hashed version of the pw (including the salt in the hash)\r\n\t * @return bool\r\n\t */\r\n\tfunction validateUserRequest($user_id, $hash_pw) { // see if the supplied password matches that of the supplied user id\r\n\t\t$query = \"SELECT id FROM ech_users WHERE id = ? AND password = ? LIMIT 1\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error');\r\n\t\t$stmt->bind_param('is', $user_id, $hash_pw);\r\n\t\t$stmt->execute();\r\n\t\t$stmt->store_result(); // needed to allow num_rows to buffer\r\n\t\t\r\n\t\tif($stmt->num_rows == 1)\r\n\t\t\treturn true; // the person exists\r\n\t\telse\r\n\t\t\treturn false; // person does not exist\r\n\t\t\t\r\n\t\t$stmt->free_result();\r\n\t\t$stmt->close();\r\n\t}\r\n\t\r\n\t/**\r\n\t * Allows a user to edit their display name and email\r\n\t *\r\n\t * @param string $name - new display name\r\n\t * @param string $email - new email address\r\n\t * @param int $user_id - id of the user to update\r\n\t * @return bool\r\n\t */\r\n\tfunction editMe($name, $email, $user_id) {\r\n\t\t$query = \"UPDATE ech_users SET display = ?, email = ? WHERE id = ? LIMIT 1\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error');\r\n\t\t$stmt->bind_param('ssi', $name, $email, $user_id);\r\n\t\t$stmt->execute();\r\n\t\t\r\n\t\tif($stmt->affected_rows != 1) \r\n\t\t\treturn false; // if nothing happened\r\n\t\telse\r\n\t\t\treturn true; // retrun true (it happened)\r\n\t\t\r\n\t\t$stmt->close(); // close connection\r\n\t}\r\n\t\r\n\t/**\r\n\t * Allows user to edit their password\r\n\t *\r\n\t * @param string $password_new - new password in hash form\r\n\t * @param string $salt_new - the new salt for that user\r\n\t * @param int $user_id - id of the user to update\r\n\t * @return bool\r\n\t */\r\n\tfunction editMePW($password_new, $salt_new, $user_id) { // update a user with a new pw and salt\r\n\t\t$query = \"UPDATE ech_users SET password = ?, salt = ? WHERE id = ? LIMIT 1\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error');\r\n\t\t$stmt->bind_param('ssi', $password_new, $salt_new, $user_id);\r\n\t\t$stmt->execute();\r\n\t\t\r\n\t\tif($stmt->affected_rows != 1)\r\n\t\t\treturn false;\r\n\t\telse\r\n\t\t\treturn true;\r\n\r\n\t\t$stmt->close();\r\n\t}\r\n\t\r\n\t/**\r\n\t * Add a key key to the user_keys table to allow registration\r\n\t *\r\n\t * @param string $user_key - unique key (40 char hash)\r\n\t * @param string $email - email address of the user the key is for\r\n\t * @param string $comment - comment as to why the user was added\r\n\t * @param int $perms - value of perms this user is allowed access to\r\n\t * @param int $admin_id - id of the admin who added this key\r\n\t * @return bool\r\n\t */\r\n\tfunction addEchKey($user_key, $email, $comment, $group, $admin_id) {\r\n\t\t$time = time();\r\n\t\t// key, ech_group, admin_id, comment, time_add, email, active\r\n\t\t$query = \"INSERT INTO ech_user_keys VALUES(?, ?, ?, ?, ?, ?, 1)\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error');\r\n\t\t$stmt->bind_param('siisis', $user_key, $group, $admin_id, $comment, $time, $email);\r\n\t\t$stmt->execute();\r\n\t\t\r\n\t\tif($stmt->affected_rows)\r\n\t\t\treturn true;\r\n\t\telse\r\n\t\t\treturn false;\r\n\t\t\r\n\t\t$stmt->close();\r\n\t}\r\n\t\r\n\t/**\r\n\t * Delete a registration key\r\n\t *\r\n\t * @param string $key - unique key to delete\r\n\t * @return bool\r\n\t */\r\n\tfunction delKey($key) {\r\n\t\r\n\t\t$query = \"DELETE FROM ech_user_keys WHERE reg_key = ? LIMIT 1\";\r\n\t\t$stmt = $this->mysql->prepare($query);\r\n\t\t$stmt->bind_param('s', $key);\r\n\t\t$stmt->execute();\r\n\t\t\r\n\t\tif($stmt->affected_rows)\r\n\t\t\treturn true;\r\n\t\telse\r\n\t\t\treturn false;\r\n\t\t\t\r\n\t\t$stmt->close();\r\n\t}\r\n\t\r\n\t/**\r\n\t * Edit a registration key's comment\r\n\t *\r\n\t * @param string $key - unique key to delete\r\n\t * @param string $comment - the new comment text\r\n\t * @param int $admin_id - the admin who created the key is the only person who can edit the key\r\n\t * @return bool\r\n\t */\r\n\tfunction editKeyComment($key, $comment, $admin_id){\r\n\t\r\n\t\t$query = \"UPDATE ech_user_keys SET comment = ? WHERE reg_key = ? AND admin_id = ? LIMIT 1\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error');\r\n\t\t$stmt->bind_param('ssi', $comment, $key, $admin_id);\r\n\t\t$stmt->execute();\r\n\t\t\r\n\t\tif($stmt->affected_rows)\r\n\t\t\treturn true;\r\n\t\telse\r\n\t\t\treturn false;\r\n\t\t\t\r\n\t\t$stmt->close();\r\n\t}\r\n\t\r\n\t/**\r\n\t * Verify that the supplied user key, email are valid, that the key has not expired or already been used\r\n\t *\r\n\t * @param string $key - unique key to search for\r\n\t * @param string $email - email address connected with each key\r\n\t * @param string $key_expire - lenght in days of how long a key is active for\r\n\t * @return bool\r\n\t */\r\n\tfunction verifyRegKey($key, $email, $key_expire) {\r\n\t\t$limit_seconds = $key_expire*24*60*60; // user_key_limit is sent in days so we must convert it\r\n\t\t$time = time();\r\n\t\t$expires = $time+$limit_seconds;\r\n\t\r\n\t\t$query = \"SELECT reg_key, email FROM ech_user_keys WHERE reg_key = ? AND email = ? AND active = 1 AND time_add < ? LIMIT 1\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error');\r\n\t\t$stmt->bind_param('ssi', $key, $email, $expires);\r\n\t\t$stmt->execute();\r\n\t\t\r\n\t\t$stmt->store_result(); // store results\r\n\r\n\t\tif($stmt->num_rows == 1)\r\n\t\t\treturn true;\r\n\t\telse\r\n\t\t\treturn false;\r\n\t\t\r\n\t\t$stmt->free_result();\r\n\t\t$stmt->close();\r\n\t}\r\n\t\r\n\t/**\r\n\t * Find the perms and admin_id assoc with that unique key\r\n\t *\r\n\t * @param string $key - unique key to search with\r\n\t * @return string\r\n\t */\r\n\tfunction getGroupAndIdWithKey($key) {\r\n\t\r\n\t\t$query = \"SELECT ech_group, admin_id FROM ech_user_keys WHERE reg_key = ? LIMIT 1\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error');\r\n\t\t$stmt->bind_param('s', $key);\r\n\t\t$stmt->execute();\r\n\t\t$stmt->bind_result($group, $admin_id); // store results\t\r\n\t\t$stmt->fetch();\r\n\t\t\r\n\t\t$result = array($group, $admin_id);\r\n\t\t$stmt->free_result();\r\n\t\t$stmt->close();\r\n\t\t\r\n\t\treturn $result;\r\n\t}\r\n\t\r\n\tfunction getIdWithKey($key) {\r\n\t\r\n\t\t$query = \"SELECT admin_id FROM ech_user_keys WHERE reg_key = ? LIMIT 1\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error');\r\n\t\t$stmt->bind_param('s', $key);\r\n\t\t$stmt->execute();\r\n\t\t$stmt->store_result();\r\n\t\t\r\n\t\tif($stmt->num_rows == 1) {\r\n\t\t\t$stmt->bind_result($value); // store results\t\r\n\t\t\t$stmt->fetch();\r\n\t\t\t$stmt->free_result();\r\n\t\t\t$stmt->close();\r\n\t\t\treturn $value;\r\n\t\t} else\r\n\t\t\treturn false;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Gets an array of data for the settings form\r\n\t *\r\n\t * @param string $key - the key to deactive\r\n\t * @return bool\r\n\t */\r\n\tfunction deactiveKey($key) {\r\n\t\t$query = \"UPDATE ech_user_keys SET active = 0 WHERE reg_key = ? LIMIT 1\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error');\r\n\t\t$stmt->bind_param('s', $key);\r\n\t\t$stmt->execute();\r\n\t\t\r\n\t\t$affect = $stmt->affected_rows;\r\n\t\t\r\n\t\t$stmt->close();\r\n\t\t\r\n\t\tif($affect == 1)\r\n\t\t\treturn true;\r\n\t\telse\r\n\t\t\treturn false;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Add the user information the users table\r\n\t *\r\n\t * @param string $username - username of user\r\n\t * @param string $display - display name of user\r\n\t * @param string $email - email of user\r\n\t * @param string $password - password\r\n\t * @param string $salt - salt string for the password\r\n\t * @param string $group - group for the user\r\n\t * @param string $admin_id - id of the admin who added the user key\r\n\t * @return bool\r\n\t */\r\n\tfunction addUser($username, $display, $email, $password, $salt, $group, $admin_id) {\r\n\t\t$time = time();\r\n\t\t// id, username, display, email, password, salt, ip, group, admin_id, first_seen, last_seen\r\n\t\t$query = \"INSERT INTO ech_users VALUES(NULL, ?, ?, ?, ?, ?, NULL, ?, ?, ?, NULL)\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error');\r\n\t\t$stmt->bind_param('sssssiii', $username, $display, $email, $password, $salt, $group, $admin_id, $time);\r\n\t\t$stmt->execute();\r\n\t\t\r\n\t\tif($stmt->affected_rows)\r\n\t\t\treturn true;\r\n\t\telse\r\n\t\t\treturn false;\r\n\t\t\r\n\t\t$stmt->close();\r\n\t}\r\n\r\n\t/**\r\n\t * Deletes a user\r\n\t *\r\n\t * @param string $id - id of user to deactive\r\n\t * @return bool\r\n\t */\r\n\tfunction delUser($user_id) {\r\n\t\t$query = \"DELETE FROM ech_users WHERE id = ? LIMIT 1\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error');\r\n\t\t$stmt->bind_param('i', $user_id);\r\n\t\t$stmt->execute();\r\n\t\t\r\n\t\t$affect = $stmt->affected_rows;\r\n\t\t\r\n\t\t$stmt->close();\r\n\t\t\r\n\t\tif($affect == 1)\r\n\t\t\treturn true;\r\n\t\telse\r\n\t\t\treturn false;\r\n\t}\r\n\t\r\n\tfunction editUser($id, $username, $display, $email, $ech_group) {\r\n\t\t$query = \"UPDATE ech_users SET username = ?, display = ?, email = ?, ech_group = ? WHERE id = ? LIMIT 1\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error');\r\n\t\t$stmt->bind_param('sssii', $username, $display, $email, $ech_group, $id);\r\n\t\t$stmt->execute();\r\n\t\t\r\n\t\tif($stmt->affected_rows == 1)\r\n\t\t\treturn true;\r\n\t\telse\r\n\t\t\treturn false;\r\n\t\t\t\r\n\t\t$stmt->close();\r\n\t}\r\n\t\r\n\t/**\r\n\t * Gets a user's details (for SA view/edit)\r\n\t *\r\n\t * @param string $id - id of user\r\n\t * @return array\r\n\t */\r\n\tfunction getUserDetails($id) {\r\n\t\t$query = \"SELECT u.username, u.display, u.email, u.ip, u.ech_group, u.admin_id, u.first_seen, u.last_seen, a.display \r\n\t\t\t\t FROM ech_users u LEFT JOIN ech_users a ON u.admin_id = a.id WHERE u.id = ? LIMIT 1\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error');\r\n\t\t$stmt->bind_param('i', $id);\r\n\t\t$stmt->execute();\r\n\t\r\n\t\t$stmt->store_result();\r\n\t\t$stmt->bind_result($username, $display, $email, $ip, $group, $admin_id, $first_seen, $last_seen, $admin_name);\r\n\t\t$stmt->fetch();\r\n\r\n\t\tif($stmt->num_rows == 1) :\r\n\t\t\t$data = array($username, $display, $email, $ip, $group, $admin_id, $first_seen, $last_seen, $admin_name);\r\n\t\t\treturn $data;\r\n\t\telse :\r\n\t\t\treturn false;\r\n\t\tendif;\r\n\t\t\r\n\t\t$stmt->free_result();\r\n\t\t$stmt->close();\r\n\t}\r\n\t\r\n\tfunction getUserDetailsEdit($id) {\r\n\t\t$query = \"SELECT username, display, email, ech_group FROM ech_users WHERE id = ? LIMIT 1\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error');\r\n\t\t$stmt->bind_param('i', $id);\r\n\t\t$stmt->execute();\r\n\t\r\n\t\t$stmt->store_result();\r\n\t\t$stmt->bind_result($username, $display, $email, $group_id);\r\n\t\t$stmt->fetch();\r\n\r\n\t\tif($stmt->num_rows == 1) :\r\n\t\t\t$data = array($username, $display, $email, $group_id);\r\n\t\t\treturn $data;\r\n\t\telse :\r\n\t\t\treturn false;\r\n\t\tendif;\r\n\t\t\r\n\t\t$stmt->free_result();\r\n\t\t$stmt->close();\r\n\t}\r\n\t\r\n\t/**\r\n\t * Verifies if a user name and email exist\r\n\t *\r\n\t * @param string $name - username of user\r\n\t * @param string $email - email address of user\r\n\t * @return int($user_id)/bool(false)\r\n\t */\r\n\tfunction verifyUser($name, $email) {\r\n\t\r\n\t\t$query = \"SELECT id FROM ech_users WHERE username = ? AND email = ? LIMIT 1\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error');\r\n\t\t$stmt->bind_param('ss', $name, $email);\r\n\t\t$stmt->execute();\r\n\t\t\r\n\t\t$stmt->store_result();\r\n\t\tif($stmt->num_rows == 1) {\r\n\t\t\t$stmt->bind_result($user_id);\r\n\t\t\t$stmt->fetch();\r\n\t\t\treturn $user_id;\r\n\t\t} else {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\t$stmt->free_result();\r\n\t\t$stmt->close();\r\n\t}\r\n\t\r\n\t/**\r\n\t * Gets an array of the echelon groups\r\n\t *\r\n\t * @return array\r\n\t */\r\n\tfunction getGroups() {\r\n\t\t$query = \"SELECT id, namep FROM ech_groups ORDER BY id ASC\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error');\r\n\t\t$stmt->execute();\r\n\t\t$stmt->bind_result($id, $display);\r\n\t\t\r\n\t\twhile($stmt->fetch()) :\r\n\t\t\t$groups[] = array(\r\n\t\t\t\t'id' => $id,\r\n\t\t\t\t'display' => $display\r\n\t\t\t);\r\n\t\tendwhile;\r\n\t\t\r\n\t\t$stmt->close();\r\n\t\treturn $groups;\t\r\n\t}\r\n\t\r\n\tfunction getGroupInfo($group_id) {\r\n\t\t$query = \"SELECT namep, premissions FROM ech_groups WHERE id = ? LIMIT 1\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('DB Error');\r\n\t\t$stmt->bind_param('i', $group_id);\r\n\t\t$stmt->execute();\r\n\t\t\r\n\t\t$stmt->bind_result($display, $perms);\r\n\t\t$stmt->fetch();\r\n\t\t$result = array($display, $perms);\r\n\t\t\r\n\t\t$stmt->close();\r\n\t\treturn $result;\r\n\t}\r\n\t\r\n\tfunction getEchLogs($id, $game_id = NULL, $type = 'client') {\r\n\t\t$query = \"SELECT log.id, log.type, log.msg, log.client_id, log.user_id, log.time_add, log.game_id, u.display \r\n\t\t\t\t FROM ech_logs log LEFT JOIN ech_users u ON log.user_id = u.id \";\r\n\t\t\r\n\t\tif($type == 'admin')\r\n\t\t\t$query .= \"WHERE user_id = ?\";\r\n\t\telse\r\n\t\t\t$query .= \"WHERE client_id = ? AND game_id = ?\";\r\n\t\t\t\r\n\t\t$query .= \" ORDER BY log.time_add DESC\";\r\n\t\t\t\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error');\r\n\t\tif($type == 'admin')\r\n\t\t\t$stmt->bind_param('i', $id);\r\n\t\telse\r\n\t\t\t$stmt->bind_param('ii', $id, $game_id);\r\n\t\t$stmt->execute();\r\n\t\t\r\n\t\t$stmt->store_result();\r\n\t\t$stmt->bind_result($id, $type, $msg, $client_id, $user_id, $time_add, $game_id, $user_name);\r\n\t\t\r\n\t\twhile($stmt->fetch()) :\r\n\t\t\t$ech_logs[] = array(\r\n\t\t\t\t'id' => $id,\r\n\t\t\t\t'type' => $type,\r\n\t\t\t\t'msg' => $msg,\r\n\t\t\t\t'client_id' => $client_id,\r\n\t\t\t\t'user_id' => $user_id,\r\n\t\t\t\t'user_name' => $user_name,\r\n\t\t\t\t'game_id' => $game_id,\r\n\t\t\t\t'time_add' => $time_add\r\n\t\t\t); \t\r\n\t\tendwhile;\r\n\t\t\r\n\t\t$stmt->close();\r\n\t\treturn $ech_logs;\r\n\t}\r\n\t\r\n\tfunction addEchLog($type, $comment, $cid, $user_id, $game_id) {\r\n\t\t// id, type, msg, client_id, user_id, time_add, game_id\r\n\t\t$query = \"INSERT INTO ech_logs VALUES(NULL, ?, ?, ?, ?, UNIX_TIMESTAMP(), ?)\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error');\r\n\t\t$stmt->bind_param('ssiii', $type, $comment, $cid, $user_id, $game_id);\r\n\t\t$stmt->execute();\r\n\t\t\r\n\t\t$affect = $stmt->affected_rows;\r\n\t\t\r\n\t\t$stmt->close();\r\n\t\t\r\n\t\tif($affect == 1)\r\n\t\t\treturn true;\r\n\t\telse\r\n\t\t\treturn false;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Gets an array of the external links from the db\r\n\t */\r\n\tfunction getLinks() {\r\n\t\t$query = \"SELECT * FROM ech_links\";\r\n\t\t\r\n\t\t$links = $this->query($query);\r\n\t\t\r\n\t\treturn $links;\r\n\t}\r\n\t\r\n\tfunction setGroupPerms($group_id, $perms) {\r\n\t\t$query = \"UPDATE ech_groups SET premissions = ? WHERE id = ? LIMIT 1\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('DB Error');\r\n\t\t$stmt->bind_param('si', $perms, $group_id);\r\n\t\t$stmt->execute();\r\n\t\t\r\n\t\t$affect = $stmt->affected_rows;\r\n\t\t\r\n\t\t$stmt->close();\r\n\t\t\r\n\t\tif($affect == 1)\r\n\t\t\treturn true;\r\n\t\telse\r\n\t\t\treturn false;\r\n\t}\r\n\t\r\n\tfunction addGroup($name, $slug, $perms) {\r\n\t\t$query = \"INSERT INTO ech_groups VALUES(NULL, ?, ?, ?)\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('DB Error');\r\n\t\t$stmt->bind_param('sss', $name, $slug, $perms);\r\n\t\t$stmt->execute();\r\n\t\t\r\n\t\t$affect = $stmt->affected_rows;\r\n\t\t$stmt->close();\r\n\t\t\r\n\t\tif($affect == 1)\r\n\t\t\treturn true;\r\n\t\telse\t\r\n\t\t\treturn false;\r\n\t}\r\n\t\r\n\tfunction delServer($id) {\r\n\t\t$query = \"DELETE FROM ech_servers WHERE id = ? LIMIT 1\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('DB Error');\r\n\t\t$stmt->bind_param('i', $id);\r\n\t\t$stmt->execute();\r\n\t\t\r\n\t\t$affect = $stmt->affected_rows;\r\n\t\t$stmt->close();\r\n\t\t\r\n\t\tif($affect == 1)\r\n\t\t\treturn true;\r\n\t\telse\r\n\t\t\treturn false;\r\n\t}\r\n\t\r\n\tfunction gamesBanList() {\r\n\t\t$query = \"SELECT id, name, db_host, db_user, db_pw, db_name FROM ech_games\";\r\n\t\r\n\t\t$data = $this->query($query);\r\n\t\t\r\n\t\treturn $data;\r\n\t}\r\n\r\n} // end class", "echelon/classes/members-class.php": "id = $user_id;\r\n\t$this->name = $name;\r\n\t$this->email = $email;\r\n}\r\n\r\n/**\r\n * Sets the class name var\r\n */\r\nfunction setName($name) {\r\n\t$this->name = $name;\r\n\t$_SESSION['name'] = $this->name;\r\n}\r\n\r\n/**\r\n * Sets the class email var\r\n */\r\nfunction setEmail($email) {\r\n\t$this->email = $email;\r\n\t$_SESSION['email'] = $this->email;\r\n}\r\n\r\n/**\r\n * Checks if a user is logged in or not\r\n *\r\n * @return bool\r\n */\r\nfunction loggedIn() { // are they logged in\r\n\tif($_SESSION['auth']) // if authorised allow access\r\n\t\treturn true;\r\n\telse\r\n\t\treturn false; // if not authorised\r\n}\r\n\r\n/**\r\n * Checks if a user has the rights to view this page, is not locked/banned or not logged in\r\n *\r\n * @param string $name - permission name\r\n */\r\nfunction auth($name) {\r\n\tlocked(); // stop blocked people from acessing\t\r\n\tif(!$this->loggedIn()) { // if not authorised/logged in\r\n\t\tset_error('Please login to Echelon');\r\n\t\tsendLogin();\r\n\t\texit;\r\n\t}\r\n\tif(!$this->reqLevel($name)) { // if users level is less than needed access, deny entry, and cause error\r\n\t\tset_error('You do not have the correct privilages to view that page');\r\n\t\tsendHome();\r\n\t\texit;\r\n\t}\r\n}\r\n\r\nfunction reqLevel($name) {\r\n\t$perm_required = $_SESSION['perms'][$name];\r\n\tif(!$perm_required) // if users level is less than needed access return false\r\n\t\treturn false;\r\n\telse\r\n\t\treturn true;\r\n}\r\n\r\n/**\r\n * Takes password and generates salt and hash. Then updates their password in the DB\r\n *\r\n * @param string $password - the new password the user\r\n * @param int $user_id - the id of the user that is being edited\r\n * @param int $min_pw_len - min len of password\r\n * @return bool(true)/string(error)\r\n */\r\nfunction genAndSetNewPW($password, $user_id, $min_pw_len) {\r\n\r\n\t// get the DB instance pointer\r\n\t$dbl = DBL::getInstance();\r\n\t\r\n\t// check that the supplied password meets the required password policy for strong passwords\r\n\tif(!$this->pwStrength($password, $min_pw_len)) { // false: not strong enough\r\n\t\treturn 'The password you supplied is not strong enough, a password must be longer than '. $min_pw_len .' character and should follow this policy.';\r\n\t\texit;\r\n\t}\r\n\t\r\n\t// generate a new salt for the user\r\n\t$salt_new = genSalt();\r\n\t\r\n\t// find the hash of the supplied password and the new salt\r\n\t$password_hash = genPW($password, $salt_new);\r\n\t\r\n\t// update the user with new password and new salt\r\n\t$results_pw = $dbl->editMePW($password_hash, $salt_new, $user_id);\r\n\tif($results_pw == false) {\r\n\t\treturn 'There was an error changing your password';\r\n\t} else\r\n\t\treturn true;\r\n}\r\n\r\n/**\r\n * Echo out the display name in a link, if the display name is not set echo guest.\r\n */\r\nfunction displayName() {\r\n\r\n\tif($this->name == '')\r\n\t\techo 'Guest';\r\n\telse\r\n\t\techo ''. $this->name .'';\r\n\t\t\r\n\treturn;\r\n}\r\n\r\n/**\r\n * Echo out the time the user was last seen, if there is no time echo out a welcome\r\n *\r\n * @param string $time - time format (default is availble)\r\n */\r\nfunction lastSeen($time_format = 'd M y') {\r\n\r\n\tif($_SESSION['last_seen'] != '')\r\n\t\techo 'Last Seen: '. date($time_format, $_SESSION['last_seen']);\r\n\telse\r\n\t\techo 'Welcome to Echelon!';\r\n}\r\n\r\n/**\r\n * Gets a users gravatar from gravatar.com\r\n *\r\n * @param string $email - email address of the current user\r\n * @return string\r\n */\r\nfunction getGravatar($email) {\r\n\t$size = 32;\r\n\r\n\t$https = detectSSL();\r\n\t\r\n\tif($https) {\r\n\t\t$grav_url = \"https://secure.gravatar.com/avatar.php?\r\n\t\tgravatar_id=\".md5( strtolower($email) );\r\n\t} else {\r\n\t\t$grav_url = \"http://www.gravatar.com/avatar/\" . md5( strtolower( $email ) );\r\n\t}\r\n\t\r\n\t$gravatar = '\r\n\t\t\t\r\n\t\t\t\t\"\"\r\n\t\t\t\r\n\t\t';\r\n\t\r\n\treturn $gravatar;\r\n}\r\n\r\n/**\r\n * Using a user's password this func sees if the user inputed the right password for action verification\r\n *\r\n * @param string $password\r\n */\r\nfunction reAuthUser($password, $dbl) {\r\n\r\n\t// Check to see if this person is real\r\n\t$salt = $dbl->getUserSaltById($this->id);\r\n\r\n\tif($salt == false) // only returns false if no salt found, ie. user does not exist\r\n\t\tsendBack('There is a problem, you do not seem to exist!');\r\n\r\n\t$hash_pw = genPW($password, $salt); // hash the inputted pw with the returned salt\r\n\r\n\t// Check to see that the supplied password is correct\r\n\t$validate = $dbl->validateUserRequest($this->id, $hash_pw);\r\n\tif(!$validate) {\r\n\t\thack(1); // add one to hack counter to stop brute force\r\n\t\tsendBack('You have supplied an incorrect current password');\r\n\t}\r\n\t\r\n}\r\n\r\n/**\r\n * Checks if the password is strong enough - uses mutliple checks\r\n *\r\n * @param string $password - the password you wish to check\r\n * @param int $min_pw_len - minimun lenght a password can be\r\n * @return bool (false: not strong enough/ true strong enough)\r\n */\r\nfunction pwStrength($password, $min_pw_len = 8) {\r\n\r\n\t$length = strlen($password); // get the length of the password \r\n\r\n\t$power = 0; // start at 0\r\n\r\n\t// if password is shorter than min required lenght return false\r\n\tif($length < $min_pw_len)\r\n\t\treturn false;\r\n\r\n // check if password is not all lower case \r\n if(strtolower($password) != $password)\r\n $power++;\r\n \r\n // check if password is not all upper case \r\n if(strtoupper($password) == $password)\r\n $power++;\r\n\r\n // check string length is 8-16 chars \r\n if($length >= 8 && $length <= 16)\r\n $power++;\r\n\r\n // check if lenth is 17 - 25 chars \r\n if($length >= 17 && $length <=25)\r\n $power += 2;\r\n\r\n // check if length greater than 25 chars \r\n if($length > 25)\r\n $power += 3;\r\n \r\n // get the numbers in the password \r\n preg_match_all('/[0-9]/', $password, $numbers);\r\n $power += count($numbers[0]);\r\n\r\n // check for special chars \r\n preg_match_all('/[|!@#$%&*\\/=?,;.:\\-_+~^\\\\\\]/', $password, $specialchars);\r\n $spec = sizeof($specialchars[0]);\r\n\tif($spec < 2)\r\n\t\t$power--;\r\n\telseif($spec >= 2)\r\n\t\t$power++;\r\n\telseif(($spec > 4) && ($spec <= 5))\r\n\t\t$power += 2;\r\n\telseif(($spec >= 5) && ($lenght/5 >= 2)) // the second part here is a check to that half the password isn't special characters\r\n\t\t$power += 3;\r\n\telse\r\n\t\t$power;\r\n\t\r\n\r\n // get the number of unique chars \r\n $chars = str_split($password);\r\n $num_unique_chars = sizeof( array_unique($chars) );\r\n $power += floor(($num_unique_chars / 2));\r\n\t\r\n\tif($power > 10)\r\n\t\t$power = 10;\r\n\t\r\n\t// if the password is strong enough return true, else return false\r\n\tif($power >= 5)\r\n\t\treturn true;\r\n\telse\r\n\t\treturn false;\r\n\r\n}\r\n\r\n\r\n#############################\r\n} // end class", "echelon/classes/mysql-class.php": "host = $host;\r\n\t\t$this->user = $user;\r\n\t\t$this->pass = $pass;\r\n\t\t$this->name = $name;\r\n\t\t$this->error_on = $error_on;\r\n\r\n\t\ttry { // try to connect to the DB or die with an error\r\n\t\t\t$this->connectDB();\r\n\t\t\t\t\r\n\t\t} catch (Exception $e) {\r\n\t\t\t// get exception information\r\n\t\t\t$error_msg = strip_tags($e->getMessage());\r\n\t\t\t$code = $e->getCode();\r\n\t\t\t\r\n\t\t\t// log info\r\n\t\t\techLog('mysqlconnect', $error_msg, $code);\r\n\t\t\t\r\n\t\t\t// set vars for outside class\r\n\t\t\t$this->error = true;\r\n\t\t\t$this->error_msg = $error_msg;\r\n\t\t\t\r\n\t\t} // end catch\r\n\t\t\r\n\t} // end constructor function\r\n\t\r\n\t// Do not allow the clone operation\r\n private function __clone() { }\r\n\t\r\n\t/**\r\n\t * If access to a protected or private function is called\r\n\t */\r\n\tpublic function __call($name, $arg) {\r\n\t\techLog('error', 'System tried to access function '. $name .', a private or protected function in class '. get_class($this)); // log error\r\n\t\techo \"\" . $name . \" is a private function that cannot be accessed outside the B3 MySQL class\"; // error out error\r\n }\r\n\t\r\n\t/**\r\n * __destruct : Destructor for class, closes the MySQL connection\r\n */\r\n public function __destruct() {\r\n if($this->mysql != NULL) // if it is set/created (defalt starts at NULL)\r\n @$this->mysql->close(); // close the connection\r\n\t\t\r\n\t\t$this->instance = NULL;\r\n }\r\n\t\r\n\t/**\r\n * Makes the connection to the DB or throws error\r\n */\r\n private function connectDB() {\r\n\t\r\n\t\tif($this->mysql != NULL) // if it is set/created (defalt starts at NULL)\r\n\t\t\t@$this->mysql->close();\r\n\t\t\r\n\t\t// Create new connection\r\n $this->mysql = @new mysqli($this->host, $this->user, $this->pass, $this->name);\r\n\t\t\r\n\t\t// if there was a connection error \r\n\t\tif (mysqli_connect_errno()) : // NOTE: we are using the procedural method here because of a problem with the OOP method before PHP 5.2.9\r\n\r\n\t\t\t$code = @$this->mysql->connect_errno; // not all versions of PHP respond nicely to this\r\n\t\t\tif(empty($code)) // so if it does not then \r\n\t\t\t\t$code = 1; // set to 1\r\n\t\t\r\n\t\t\tif($this->error_on) // only if settings say show to con error, will we show it, else just say error\r\n\t\t\t\t$error_msg = 'B3 Database Connection Error: (#'. $code .') '.mysqli_connect_error();\r\n\t\t\telse\r\n\t\t\t\t$error_msg = $this->error_sec;\r\n\t\t\t\t\r\n\t\t\t$traces = NULL;\r\n\t\t\t$log_success = echLog('mysql', $error_msg, $code, $traces);\r\n\t\t\tif(!$log_success)\r\n\t\t\t\tdie('Could not log fatal error');\r\n\t\t\t\t\r\n\t\t\tthrow new Exception($error_msg, $code); // throw new mysql typed exception\r\n\t\t\t\r\n\t\tendif;\r\n }\r\n\t\r\n\t/**\r\n\t * Handy Query function\r\n\t *\r\n\t * @param string $sql - the SQL query to execute\r\n\t * @param bool $fetch - fetch the data rows or not\r\n\t * @param string $type - typpe of query this is \r\n\t */\r\n\tpublic function query($sql, $fetch = true, $type = 'select') {\r\n\r\n\t\tif($mysql = NULL || $this->error)\r\n\t\t\treturn false;\r\n\t\t\r\n\t\ttry {\r\n\t\t\r\n\t\t\tif($stmt = $this->mysql->prepare($sql))\r\n\t\t\t\t$stmt->execute();\r\n\t\t\telse\r\n\t\t\t\tthrow new MysqlException($this->mysql->error, $this->mysql->errno);\r\n\r\n\t\t} catch (MysqlException $e) {\r\n\t\t\r\n\t\t\t$this->error = true; // there is an error\r\n\t\t\tif($this->error_on) // if detailed errors work\r\n\t\t\t\t$this->error_msg = \"MySQL Query Error (#\". $this->mysql->errno .\"): \". $this->mysql->error;\r\n\t\t\telse\r\n\t\t\t\t$this->error_msg = $this->error_sec;\r\n\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\t\r\n\t\t## setup results array\r\n\t\t$results = array();\r\n\t\t$results['data'] = array();\r\n\t\t\r\n\t\t## do certain things depending on type of query\r\n\t\tswitch($type) { \r\n\t\t\tcase 'select': // if type is a select query\r\n\t\t\t\t$stmt->store_result();\r\n\t\t\t\t$results['num_rows'] = $stmt->num_rows(); // find the number of rows retrieved\r\n\t\t\tbreak;\r\n\t\t\t\r\n\t\t\tcase 'update':\r\n\t\t\tcase 'insert': // if insert or update find the number of rows affected by the query\r\n\t\t\t\t$results['affected_rows'] = $stmt->affected_rows(); \r\n\t\t\tbreak;\r\n\t\t}\r\n\t\t\r\n\t\t## fetch the results\r\n\t\tif($fetch) : // only fetch data if we need it\r\n\t\t\r\n\t\t\t$meta = $stmt->result_metadata();\r\n\r\n\t\t\twhile ($field = $meta->fetch_field()) :\r\n\t\t\t\t$parameters[] = &$row[$field->name];\r\n\t\t\tendwhile;\r\n\r\n\t\t\tcall_user_func_array(array($stmt, 'bind_result'), $parameters);\r\n\r\n\t\t\twhile ($stmt->fetch()) :\r\n\t\t\t\tforeach($row as $key => $val) {\r\n\t\t\t\t\t$x[$key] = $val;\r\n\t\t\t\t}\r\n\t\t\t\t$results['data'][] = $x;\r\n\t\t\tendwhile;\r\n\r\n\t\tendif;\r\n\t\t\r\n\t\t## return and close off connections\r\n\t\treturn $results;\r\n\t\t$results->close();\r\n\t\t$stmt->close();\r\n\t\t\r\n\t} // end query()\r\n\t\r\n\tfunction getB3Groups() {\r\n\t\t$query = \"SELECT id, name FROM groups ORDER BY id ASC\";\r\n\t\t$stmt = $this->mysql->prepare($query);\r\n\t\t$stmt->execute();\r\n\t\t$stmt->bind_result($id, $name);\r\n\t\t\r\n\t\twhile($stmt->fetch()) :\r\n\t\t\t$groups[] = array(\r\n\t\t\t\t'id' => $id,\r\n\t\t\t\t'name' => $name\r\n\t\t\t); \t\r\n\t\tendwhile;\r\n\t\r\n\t\t$stmt->close();\r\n\t\treturn $groups;\t\r\n\t}\r\n\t\r\n\tfunction getB3GroupsLevel() {\r\n\t\t$query = \"SELECT id FROM groups ORDER BY id ASC\";\r\n\t\t$stmt = $this->mysql->prepare($query);\r\n\t\t$stmt->execute();\r\n\t\t$stmt->bind_result($id);\r\n\t\t\r\n\t\t$groups = array();\r\n\t\t\r\n\t\twhile($stmt->fetch()) :\r\n\t\t\tarray_push($groups, $id);\r\n\t\tendwhile;\r\n\t\r\n\t\t$stmt->close();\r\n\t\treturn $groups;\t\r\n\t\r\n\t}\r\n\t\r\n\t/**\r\n\t * insert a penalty into the penalty table in the B3 DB\r\n\t *\r\n\t * @param string $type - type of penalty\r\n\t * @param int $cid - client_id who is getting the penalty\r\n\t * @param int $duration - duration of pen\r\n\t * @param string $reason - reason for pen\r\n\t * @param string $data - some additional data\r\n\t * @param int $time_expire - time (unix time) for when the pen will expire\r\n\t * @return bool\r\n\t */\r\n\tfunction penClient($type, $cid, $duration, $reason, $data, $time_expire) {\r\n\t\r\n\t\t// id(), type, client_id, admin_id(0), duration, inactive(0), keyword(Echelon), reason, data, time_add(time), time_edit(time), time_expire\r\n\t\t$query = \"INSERT INTO penalties (type, client_id, admin_id, duration, inactive, keyword, reason, data, time_add, time_edit, time_expire) VALUES(?, ?, 0, ?, 0, 'Echelon', ?, ?, UNIX_TIMESTAMP(), UNIX_TIMESTAMP(), ?)\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('MySQL Error');\r\n\t\t$stmt->bind_param('siissi', $type, $cid, $duration, $reason, $data, $time_expire);\r\n\t\t$stmt->execute();\r\n\t\t\r\n\t\tif($stmt->affected_rows > 0) // if something happened\r\n\t\t\treturn true;\r\n\t\telse\r\n\t\t\treturn false;\r\n\t\t\t\r\n\t\t$stmt->close();\r\n\t}\r\n\t\r\n\t/**\r\n\t * Deactive a penalty\r\n\t *\r\n\t * @param string $pen_id - id of penalty to deactive\r\n\t * @return bool\r\n\t */\r\n\tfunction makePenInactive($pen_id) {\r\n\t\t$query = \"UPDATE penalties SET inactive = 1 WHERE id = ? LIMIT 1\";\r\n\t\t$stmt = $this->mysql->prepare($query);\r\n\t\t$stmt->bind_param('i', $pen_id);\r\n\t\t$stmt->execute();\r\n\t\t\r\n\t\tif($stmt->affected_rows > 0)\r\n\t\t\treturn true;\r\n\t\telse\r\n\t\t\treturn false;\r\n\t\t\t\r\n\t\t$stmt->close();\r\n\t\r\n\t}\r\n\t\r\n\t/**\r\n\t * Get the pbid of the client from a penalty id\r\n\t *\r\n\t * @param string $pen_id - id of penalty to search with\r\n\t * @return string - pbid of the client\r\n\t */\r\n\tfunction getPBIDfromPID($pen_id) {\r\n\t\t$query = \"SELECT c.pbid FROM penalties p LEFT JOIN clients c ON p.client_id = c.id WHERE p.id = ? LIMIT 1\";\r\n\t\t$stmt = $this->mysql->prepare($query);\r\n\t\t$stmt->bind_param('i', $pen_id);\r\n\t\t$stmt->execute();\r\n\t\t\r\n\t\t$stmt->store_result();\r\n\t\t$stmt->bind_result($pbid);\r\n\t\t$stmt->fetch();\r\n\t\t$stmt->free_result();\r\n\t\t$stmt->close();\r\n\t\r\n\t\treturn $pbid;\r\n\t}\r\n\r\n#############################\r\n#############################\r\n} // end class\r\n\r\n/**\r\n * Exceptions class for the B3 DB\r\n *\r\n */\r\nclass MysqlException extends Exception {\r\n\r\n\tprivate $ex_error;\r\n\tprivate $ex_errno;\r\n\r\n\tpublic function __construct($error, $errno) {\r\n\t\t\r\n\t\t// get sent vars\r\n\t\t$this->ex_error = $error;\r\n\t\t$this->ex_errno = $errno;\r\n\t\t\r\n\t\t// get exception information from parent class\r\n\t\t$traces = parent::getTraceAsString();\r\n\t\t\r\n\t\t// find error message and code\r\n\t\t$code = $this->ex_errno;\r\n\t\t$message = $this->ex_error;\r\n\t\t\r\n\t\t// log error message\r\n\t\t$log_success = echLog('mysql', $message, $code, $traces);\r\n\t\tif(!$log_success)\r\n\t\t\tdie('Could not log fatal error');\r\n\r\n\t\t// call parent constructor\r\n\t\tparent::__construct($message, $code);\r\n\t}\r\n\r\n}", "echelon/classes/plugins-class.php": "name = $name;\r\n\t}\r\n\t\r\n\tpublic function __destruct() {\r\n\t}\r\n\t\r\n\tprotected function setTitle($title) {\r\n\t\t$this->title = $title;\r\n\t}\r\n\t\r\n\tprotected function setVersion($version) {\r\n\t\t$this->version = $version;\r\n\t}\r\n\t\r\n\tpublic static function setPluginsClass($value) {\r\n\t\tself::$plugins_class = $value;\r\n\t}\r\n\t\r\n\tprotected function getTitle() {\r\n\t\treturn $this->title;\r\n\t}\r\n\t\r\n\tprotected function getName() {\r\n\t\treturn $this->name;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Internal function: in the case of fatal error die with plugin name and error message\r\n\t */\r\n\tprotected function error($msg) {\r\n\t\tdie($this->getName().' Plugin Error: '. $msg);\r\n\t}\r\n\t\r\n\t/**\r\n\t * This function display information from plugins in the CD's bio area\r\n\t *\r\n\t * @param array $plugins_class - an array of pointers to the class of the plugins\r\n\t */\r\n\tfunction displayCDBio() {\r\n\t\tforeach(self::$plugins_class as $plugin) :\r\n\t\t\tif(method_exists($plugin, 'returnClientBio')) {\r\n\t\t\t\t$content = $plugin->returnClientBio();\r\n\t\t\t\techo $content;\r\n\t\t\t}\r\n\t\tendforeach;\r\n\t}\r\n\t\r\n\t/**\r\n\t * This function display the tab of any plugin added forms on the clientdetails page\r\n\t *\r\n\t * @param array $plugins_class - an array of pointers to the class of the plugins\r\n\t */\r\n\tfunction displayCDFormTab() {\r\n\t\tforeach(self::$plugins_class as $plugin) :\r\n\t\t\tif(method_exists($plugin, 'returnClientFormTab')) {\r\n\t\t\t\t$content = $plugin->returnClientFormTab();\r\n\t\t\t\techo $content;\r\n\t\t\t}\r\n\t\tendforeach;\r\n\t}\r\n\t\r\n\t/**\r\n\t * This function display forms on the clientdetails page added by any plugins\r\n\t *\r\n\t * @param array $plugins_class - an array of pointers to the class of the plugins\r\n\t */\r\n\tfunction displayCDForm($cid = 0) {\r\n\t\tforeach(self::$plugins_class as $plugin) :\r\n\t\t\tif(method_exists($plugin, 'returnClientForm')) {\r\n\t\t\t\t$content = $plugin->returnClientForm($cid);\r\n\t\t\t\techo $content;\r\n\t\t\t}\r\n\t\tendforeach;\r\n\t}\r\n\t\r\n\t/**\r\n\t * For each plugin check if they want to add a link\r\n\t */\r\n\tfunction displayNav() {\r\n\t\tforeach(self::$plugins_class as $plugin) :\r\n\t\t\tif(method_exists($plugin, 'returnNav')) {\r\n\t\t\t\t$content = $plugin->returnNav();\r\n\t\t\t\techo $content;\r\n\t\t\t}\r\n\t\tendforeach;\r\n\t}\r\n\t\r\n\t/**\r\n\t * For each plugin check if they want to append something to the end of the CD page\r\n\t */\r\n\tfunction displayCDlogs($cid) {\r\n\t\tforeach(self::$plugins_class as $plugin) :\r\n\t\t\tif(method_exists($plugin, 'returnClientLogs')) {\r\n\t\t\t\t$content = $plugin->returnClientlogs($cid);\r\n\t\t\t\techo $content;\r\n\t\t\t}\r\n\t\tendforeach;\r\n\t}\r\n\t\r\n\t/**\r\n\t * For each plugin check if they need to include a css file\r\n\t */\r\n\tfunction getCSS() {\r\n\t\tforeach(self::$plugins_class as $plugin) :\r\n\t\t\tif(method_exists($plugin, 'returnCSS')) {\r\n\t\t\t\t$content = $plugin->returnCSS();\r\n\t\t\t\techo $content;\r\n\t\t\t}\r\n\t\tendforeach;\r\n\t}\r\n\t\r\n\t/**\r\n\t * For each plugin check if they need to include a JS file\r\n\t */\r\n\tfunction getJS() {\r\n\t\tforeach(self::$plugins_class as $plugin) :\r\n\t\t\tif(method_exists($plugin, 'returnJS')) {\r\n\t\t\t\t$content = $plugin->returnJS();\r\n\t\t\t\techo $content;\r\n\t\t\t}\r\n\t\tendforeach;\r\n\t}\r\n\r\n\r\n} // end class", "echelon/clientdetails.php": "mysql->prepare($query) or die('Database Error '. $db->mysql->error);\r\n$stmt->bind_param('i', $cid);\r\n$stmt->execute();\r\n$stmt->bind_result($ip, $connections, $guid, $name, $mask_level, $greeting, $time_add, $time_edit, $group_bits, $user_group);\r\n$stmt->fetch();\r\n$stmt->close();\r\n\r\n## Require Header ##\r\n$page_title .= ' '.$name; // add the clinets name to the end of the title\r\n\r\nrequire 'inc/header.php';\r\n?>\r\n\r\n\t\r\n\t\r\n\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\r\n\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\r\n\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\r\n\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\r\n\t\r\n
            \"\"Everything B3 knows about
            Name@id
            Level\r\n\t\t\t\tConnections
            GUID\r\n\t\t\t\treqLevel('view_full_guid')) { // if allowed to see the full guid\r\n\t\t\t\t\t\tif($guid_len == 32) \r\n\t\t\t\t\t\t\tguidCheckLink($guid);\r\n\t\t\t\t\t\telse \r\n\t\t\t\t\t\t\techo $guid.' ['. $guid_len .']';\r\n\t\t\t\t\r\n\t\t\t\t\t} elseif($mem->reqLevel('view_half_guid')) { // if allowed to see the last 8 chars of guid\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tif($guid_len == 32) {\r\n\t\t\t\t\t\t\t$half_guid = substr($guid, -8); // get the last 8 characters of the guid\r\n\t\t\t\t\t\t\tguidCheckLink($half_guid);\r\n\t\t\t\t\t\t} else\r\n\t\t\t\t\t\t\techo $guid.' ['. $guid_len .']';\r\n\t\t\t\t\t\r\n\t\t\t\t\t} else { // if not allowed to see any part of the guid\r\n\t\t\t\t\t\techo '(You do not have access to see the GUID)';\r\n\t\t\t\t\t}\r\n\t\t\t\t?>\r\n\t\t\t\tIP Address\r\n\t\t\t\t\treqLevel('view_ip')) :\r\n\t\t\t\t\t\tif ($ip != \"\") { ?>\r\n\t\t\t\t\t\t\t&t=ip\" title=\"Search for other users with this IP adreess\">\r\n\t\t\t\t\t\t\t\t  \r\n\t\t\t\t\t\t\t\" title=\"Whois IP Search\">\"W\"\r\n\t\t\t\t\t\t\t\t  \r\n\t\t\t\t\t\t\t\" title=\"Show Location of IP origin on map\">\"L\"\r\n\t\t\t\t\t\r\n\t\t\t\t
            First SeenLast Seen
            \r\n\r\ndisplayCDBio();\r\n\r\n##############################\r\n?>\r\n\r\n\r\n\r\n\r\n
            \r\n\t\r\n\t
            \r\n\t\treqLevel('comment')) :\r\n\t\t\t$comment_token = genFormToken('comment');\t\r\n\t\t?>\r\n\t\t
            \r\n\t\t\t\r\n\t\t\t
            \r\n\t\t\t\t
            \r\n\t\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t\t
            \r\n\t\t\t\t\t\r\n\t\t\t\t\" />\r\n\t\t\t\t\" />\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t
            \r\n\t\t
            \r\n\t\treqLevel('greeting')) :\r\n\t\t\t$greeting_token = genFormToken('greeting');\r\n\t\t?>\r\n\t\t
            \r\n\t\t\t
            \r\n\t\t\t\t
            \r\n\t\t\t\t\t
            \r\n\t\t\t\t\t\r\n\t\t\t\t\" />\r\n\t\t\t\t\" />\r\n\t\t\t\t\r\n\t\t\t
            \r\n\t\t
            \r\n\t\treqLevel('ban')) :\r\n\t\t\t$ban_token = genFormToken('ban');\r\n\t\t?>\r\n\t\t
            \r\n\t\t\t
            \r\n\t\t\r\n\t\t\t\t
            \r\n\t\t\t\t\tType\r\n\t\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t\t\t
            \r\n\t\t\t\t\t\r\n\t\t\t\t\t
            \r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t
            \r\n\t\t\t\t
            \r\n\t\t\t\t
            \r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t\" />\r\n\t\t\t\t\" />\r\n\t\t\t\t\" />\r\n\t\t\t\t\" />\r\n\t\t\t\t\" />\r\n\t\t\t\t\r\n\t\t\t
            \r\n\t\t
            \r\n\t\tgetB3Groups(); // get a list of all B3 groups from the B3 DB\r\n\t\t\t\r\n\t\t\tif($mem->reqLevel('edit_client_level')) :\r\n\t\t\t$level_token = genFormToken('level');\r\n\t\t?>\r\n\t\t
            \r\n\t\t\t
            \r\n\t\t\t\t\r\n\t\t\t\t\t
            \r\n\t\t\t\t\t\r\n\t\t\t\t
            \r\n\t\t\t\t\t\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t
            \r\n\t\t\t\t
            \r\n\t\t\t\t\t\r\n\t\t\t\t\" />\r\n\t\t\t\t\" />\r\n\t\t\t\t\" />\r\n\t\t\t\t\r\n\t\t\t
            \r\n\t\t
            \r\n\t\treqLevel('edit_mask')) : \r\n\t\t\t$mask_lvl_token = genFormToken('mask');\r\n\t\t?>\r\n\t\t
            \r\n\t\t\t
            \r\n\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\" />\r\n\t\t\t\t\" />\r\n\t\t\t\t\" />\r\n\t\t\t\t\r\n\t\t\t
            \r\n\t\t
            \r\n\t\tdisplayCDForm($cid)\r\n\t\t\t\r\n\t\t?>\r\n\t
            \r\n
            \r\n\r\n\r\n\r\n

            Aliases

            \r\n\r\n\t\r\n\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\r\n\t\r\n\t\r\n\t\t\r\n\t\r\n\t\r\n\tmysql->prepare($query) or die('Alias Database Query Error'. $db->mysql->error);\r\n\t\t$stmt->bind_param('i', $cid);\r\n\t\t$stmt->execute();\r\n\t\t$stmt->bind_result($alias, $num_used, $time_add, $time_edit);\r\n\t\t\r\n\t\t$stmt->store_result(); // needed for the $stmt->num_rows call\r\n\r\n\t\tif($stmt->num_rows) :\r\n\t\t\t\r\n\t\t\twhile($stmt->fetch()) :\r\n\t\r\n\t\t\t\t$time_add = date($tformat, $time_add);\r\n\t\t\t\t$time_edit = date($tformat, $time_edit);\r\n\t\t\t\t\r\n\t\t\t\t$alter = alter();\r\n\t\t\t\t\r\n\t\t\t\t$token_del = genFormToken('del'.$id);\t\t\r\n\t\t\t\t\r\n\t\t\t\t// setup heredoc (table data)\t\t\t\r\n\t\t\t\t$data = <<\r\n\t\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t\r\nEOD;\r\n\t\t\t\techo $data;\r\n\t\t\t\r\n\t\t\tendwhile;\r\n\t\t\r\n\t\telse : // if there are no aliases connected with this user then put out a small and short message\r\n\t\t\r\n\t\t\techo '';\r\n\t\t\r\n\t\tendif;\r\n\t?>\r\n\t\r\n
            AliasTimes UsedFirst UsedLast Used
            $alias$num_used$time_add$time_edit
            '.$name.' has no aliaises.
            \r\n\r\n\r\n\r\ngetEchLogs($cid, $game);\r\n\t\r\n\t$count = count($ech_logs);\r\n\tif($count > 0) : // if there are records\r\n?>\r\n\t

            Echelon Logs

            \r\n\t\r\n\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\r\n\t\t\r\n\t\t\t\r\n\t\t\r\n\t\t\r\n\t\t\t\r\n\t\t\r\n\t
            idTypeMessageTime AddedAdmin
            \r\n\r\n\r\n\r\n\r\n
            \r\n\t

            Penalties \"Open\"

            \r\n\t\r\n\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\r\n\t\t\r\n\t\t\t\r\n\t\t\r\n\t\t\r\n\t\t\t\r\n\t\t\r\n\t
            TypeAddedDurationExpiresReasonAdmin
            \r\n
            \r\n\r\n\r\n\r\n
            \r\n\t

            Admin Actions \"Open\"

            \r\n\t\r\n\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\r\n\t\t\r\n\t\t\t\r\n\t\t\r\n\t\t\r\n\t\t\t\r\n\t\t\r\n\t
            TypeAddedDurationExpiresReasonAdmin
            \r\n
            \r\n\r\ndisplayCDlogs($cid);\r\n\r\n// Close page off with the footer\r\nrequire 'inc/footer.php'; \r\n?>", "echelon/clients.php": "error) :\r\n?>\r\n\r\n
            \r\n\tClient Search\r\n\t
            \r\n\t\r\n\t\t\"Loading....\"\r\n\t\r\n\t\t\" />\r\n\t\t\r\n\t\t
            \r\n\t\t\t
             
            \r\n\t\t
            \r\n\t\t\r\n\t\t\r\n\t\t\r\n\t\t\r\n\t
            \r\n
            \r\n\r\n players who have connected to the server at one time or another.\">\r\n\t\r\n\t\r\n\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\r\n\t\r\n\t\r\n\t\t\r\n\t\t\t\r\n\t\t\r\n\t\r\n\t\r\n\t 0) : // query contains stuff\r\n\t \r\n\t\tforeach($data_set as $client): // get data from query and loop\r\n\t\t\t$cid = $client['id'];\r\n\t\t\t$name = $client['name'];\r\n\t\t\t$level = $client['level'];\r\n\t\t\t$connections = $client['connections'];\r\n\t\t\t$time_edit = $client['time_edit'];\r\n\t\t\t$time_add = $client['time_add'];\r\n\t\t\t\r\n\t\t\t$time_add = date($tformat, $time_add);\r\n\t\t\t$time_edit = date($tformat, $time_edit);\r\n\t\t\t\r\n\t\t\t$alter = alter();\r\n\t\t\t\t\r\n\t\t\t$client = clientLink($name, $cid);\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t// setup heredoc (table data)\t\t\t\r\n\t\t\t$data = <<\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\nEOD;\r\n\r\n\t\techo $data;\r\n\t\tendforeach;\r\n\telse :\r\n\t\t$no_data = true;\r\n\t\r\n\t\techo '';\r\n\tendif; // no records\r\n\t?>\r\n\t\r\n
            Client Listings\r\n\t\t\r\n\t\t\t'.$search_string.' there are '. $total_rows .'.';\r\n\t\t\telseif($search_type == 'alias')\r\n\t\t\t\techo 'You are searching all clients names for '.$search_string.' there are '. $total_rows .'.';\r\n\t\t\telseif($search_type == 'pbid')\r\n\t\t\t\techo 'You are searching all clients Punkbuster Guids for '.$search_string.' there are '. $total_rows .'.';\r\n\t\t\telseif($search_type == 'id')\r\n\t\t\t\techo 'You are searching all clients B3 IDs for '.$search_string.' there are '. $total_rows .'.';\r\n\t\t\telseif($search_type == 'ip')\r\n\t\t\t\techo 'You are searching all clients IP addresses for '.$search_string.' there are '. $total_rows .'.';\r\n\t\t\telse\r\n\t\t\t\techo 'A list of all players who have ever connected to the server.';\r\n\t\t\t?>\r\n\t\t\r\n\t
            Name\r\n\t\t\t\t\r\n\t\t\tClient-id\r\n\t\t\t\t\r\n\t\t\tLevel\r\n\t\t\t\t\r\n\t\t\tConnections\r\n\t\t\t\t\r\n\t\t\tFirst Seen\r\n\t\t\t\t\r\n\t\t\tLast Seen\r\n\t\t\t\t\r\n\t\t\t
            Click client name to see details
            $client@$cid$level$connections$time_add$time_edit
            ';\r\n\t\tif($is_search == false)\r\n\t\t\techo 'There are no clients in the database.';\r\n\t\telse\r\n\t\t\techo 'Your search for '.$search_string.' has returned no results.';\r\n\t\techo '
            \r\n\r\n", "echelon/css/cd.css": "/* Client Details Page Styling */\r\n@media screen {\r\n\r\ntable.cd-table { margin-bottom: 25px; border: none; }\r\n\t.cd-table tbody tr { border-bottom: 1px solid #F4F4F4; }\r\n\t.cd-table tbody tr th { width: 15%; background: none; border: none; text-align: right; }\r\n\t.cd-table tbody tr td { width: 35%; border: none; }\r\n\r\ndiv#actions { margin-bottom: 25px; }\r\n\r\nul.cd-tabs { display: block; margin-left: 10px; height: 26px; }\r\nul.cd-tabs li { display: block; float: left; margin: 0 6px; background: #ddd; border: 1px solid #CCC; -moz-border-radius: 5px 5px 0 0; -webkit-border-radius: 5px 5px 0 0; box-shadow: 4px -1px 6px #EDEDED; -webkit-box-shadow: 4px -1px 6px #EDEDED; -moz-box-shadow: 4px -1px 6px #EDEDED; }\r\nul.cd-tabs li.cd-active, ul.cd-tabs li.chat-active { padding-bottom: 3px; border-bottom: none; background: #f3f3f3; box-shadow: none; -webkit-box-shadow: none; -moz-box-shadow: none; }\r\nul.cd-tabs li a { padding: 4px 9px; font-size: 15px; color: #999; display: block; }\r\nul.cd-tabs li a:hover { color: #666; text-decoration: none; cursor: pointer; }\r\n\r\n#actions-box { background: #f3f3f3; padding: 15px; border: 1px solid #CCC; -moz-border-radius: 7px; -webkit-border-radius: 7px; }\r\n.act-slide { display: none; }\r\n#cd-act-comment { display: block; }\r\n\r\n#chats-box { background: #f3f3f3; padding: 15px; border: 1px solid #CCC; -moz-border-radius: 7px; -webkit-border-radius: 7px; }\r\n.chat-content { display: none; }\r\n#chat-tab-0 { display: block; }\r\n\r\n.xlr { height: 7px; }\r\n\r\n.cd-h { margin: 20px 0 4px; border-bottom: 1px solid #efefef; padding-bottom: 3px; }\r\n.cd-open-close:hover, .cd-slide, #cd-h-admin:hover, #cd-h-pen:hover { cursor: pointer; }\r\nimg.cd-open { float: right; padding: 3px; margin: 8px; }\r\n\r\n.cd-table-fold { display: none; }\r\n#cd-tr-load-pen td { text-align: center; }\r\n#cd-tr-load-pen:hover { background : #fff; }\r\n.load-large { margin: 15px; }\r\n\r\n#eb-reason, #reason { width: 350px; }\r\ninput.dur { width: 60px; }\r\n\r\n.unban-form { width: 18px; display: inline; }\r\n.edit-ban:hover { cursor: pointer; }\t\t\r\n.eb-fs { display: block; float: none !important; width: 93% !important; }\r\n\r\n#edit-ban { margin: 25px; }\r\n\r\n/* ColorBox Core Style */\r\n#colorbox, #cboxOverlay, #cboxWrapper{position:absolute; top:0; left:0; z-index:9999; overflow:hidden;}\r\n#cboxOverlay{position:fixed; width:100%; height:100%;}\r\n#cboxMiddleLeft, #cboxBottomLeft{clear:left;}\r\n#cboxContent{position:relative; overflow:visible;}\r\n#cboxLoadedContent{overflow:auto;}\r\n#cboxLoadedContent iframe{display:none; width:100%; height:100%; border:0;}\r\n#cboxTitle{margin:0;}\r\n#cboxLoadingOverlay, #cboxLoadingGraphic{position:absolute; top:0; left:0; width:100%;}\r\n#cboxPrevious, #cboxNext, #cboxClose, #cboxSlideshow{cursor:pointer;}\r\n\r\n#cboxOverlay{background:#000;}\r\n\r\n#colorbox{}\r\n #cboxTopLeft{width:14px; height:14px; background:url(../images/colorbox/controls.png) 0 0 no-repeat;}\r\n #cboxTopCenter{height:14px; background:url(../images/colorbox/border.png) top left repeat-x;}\r\n #cboxTopRight{width:14px; height:14px; background:url(../images/colorbox/controls.png) -36px 0 no-repeat;}\r\n #cboxBottomLeft{width:14px; height:43px; background:url(../images/colorbox/controls.png) 0 -32px no-repeat;}\r\n #cboxBottomCenter{height:43px; background:url(../images/colorbox/border.png) bottom left repeat-x;}\r\n #cboxBottomRight{width:14px; height:43px; background:url(../images/colorbox/controls.png) -36px -32px no-repeat;}\r\n #cboxMiddleLeft{width:14px; background:url(../images/colorbox/controls.png) -175px 0 repeat-y;}\r\n #cboxMiddleRight{width:14px; background:url(../images/colorbox/controls.png) -211px 0 repeat-y;}\r\n #cboxContent{background:#fff;}\r\n #cboxLoadedContent{margin-bottom:5px;}\r\n #cboxLoadingOverlay{background:url(../images/colorbox/loading_background.png) center center no-repeat;}\r\n #cboxLoadingGraphic{background:url(../images/colorbox/loading.gif) center center no-repeat;}\r\n #cboxTitle{position:absolute; bottom:-25px; left:0; text-align:center; width:100%; font-weight:bold; color:#7C7C7C;}\r\n #cboxCurrent{position:absolute; bottom:-25px; left:58px; font-weight:bold; color:#7C7C7C;}\r\n \r\n #cboxPrevious, #cboxNext, #cboxClose, #cboxSlideshow{position:absolute; bottom:-29px; background:url(../images/colorbox/controls.png) 0px 0px no-repeat; width:23px; height:23px; text-indent:-9999px;}\r\n #cboxPrevious{left:0px; background-position: -51px -25px;}\r\n #cboxPrevious.hover{background-position:-51px 0px;}\r\n #cboxNext{left:27px; background-position:-75px -25px;}\r\n #cboxNext.hover{background-position:-75px 0px;}\r\n #cboxClose{right:0; background-position:-100px -25px;}\r\n #cboxClose.hover{background-position:-100px 0px;}\r\n \r\n .cboxSlideshow_on #cboxSlideshow{background-position:-125px 0px; right:27px;}\r\n .cboxSlideshow_on #cboxSlideshow.hover{background-position:-150px 0px;}\r\n .cboxSlideshow_off #cboxSlideshow{background-position:-150px -25px; right:27px;}\r\n .cboxSlideshow_off #cboxSlideshow.hover{background-position:-125px 0px;}\r\n\t\r\n}\t\r\n@media print {\r\n\r\nbody { width:100% !important; margin:0 !important; padding:0 !important; line-height: 1.4; word-spacing:1.1pt; letter-spacing:0.2pt; font-family: Garamond,\"Times New Roman\", serif; color: #000; background: none; font-size: 12pt; }\r\nh1,h2,h3,h4,h5,h6 { font-family: Helvetica, Arial, sans-serif; }\r\nh1{font-size:19pt;}\r\nh2{font-size:17pt;}\r\nh3{font-size:15pt;}\r\nh4,h5,h6{font-size:12pt;}\r\ncode { font: 10pt Courier, monospace; } \r\nblockquote { margin: 1.3em; padding: 1em; font-size: 10pt; }\r\nhr { background-color: #ccc; }\r\nimg { display: block; margin: 1em 0; }\r\na img { border: none; }\r\ntable { margin: 1px; text-align:left; }\r\nth { border-bottom: 1px solid #333; font-weight: bold; }\r\ntd { border-bottom: 1px solid #333; }\r\nth,td { padding: 4px 10px 4px 0; }\r\ntfoot { font-style: italic; }\r\ncaption { background: #fff; margin-bottom:2em; text-align:left; }\r\nthead {display: table-header-group;}\r\ntr { page-break-inside: avoid;} \r\na { text-decoration: none; color: black; }\r\n\r\n#menu, #actions, .foot-nav, caption, .cd-open, #content-lower, .unban-form, .edit-ban { display: none; }\r\n\r\n}\r\n", "echelon/css/home.css": "/* Home Page CSS Styling */\r\n\r\n.index-block { width: 45%; margin: 10px; float: left; }\r\n.index-block h3 { text-align: center; padding-bottom: 4px; margin-bottom: 6px; border-bottom: 1px solid #efefef; }\r\n.index-block ul { list-style-position: outside; margin-left: 20px; }\r\n.index-block ul li { margin: 2px 0; }\r\n\r\n.links-list { list-style-type: circle; }\r\n.links-list li { display: iblock; margin: 3px 0; padding: 1px; border-bottom: 1px solid #efefef; }\r\n\r\n.padd { padding: 10px 0 10px 20px; font-size: 14px; }\r\n\r\np.welcome { margin: 10px; }\r\n\tp.welcome small { padding-left: 20px; }", "echelon/css/login.css": "/* CSS */\r\n.trys { border-bottom: 1px solid #fefefe; margin-bottom: 6px; padding-bottom: 2px; }\r\n#login-field { width: 45%; }\r\n#login-form { width: 325px; margin: 0 auto; }\r\nlabel { margin-right: 10px; display: inline-block; width: 80px; text-align: right; }\r\ndiv.lower { margin-top: 8px; border-top: 1px solid #ccc; }\r\n\t.links-lower { font-size: 14px; margin-left: 7px; }\r\n\t\t.links-lower a { font-style: italic; }\r\n\t.lower input { margin: 5px 15px; float: right; }\r\nspan.sep { color: #ededed; margin: 0 4px; }\r\ninput { margin: 10px 4px; }"}, "files_after": {"echelon.sql": "/*\r\nMySQL Data Transfer\r\nSource Host: localhost\r\nSource Database: echelon\r\nTarget Host: localhost\r\nTarget Database: echelon\r\nDate: 13/08/2010 00:47:01\r\n*/\r\n\r\nSET FOREIGN_KEY_CHECKS=0;\r\n-- ----------------------------\r\n-- Table structure for ech_blacklist\r\n-- ----------------------------\r\nDROP TABLE IF EXISTS `ech_blacklist`;\r\nCREATE TABLE `ech_blacklist` (\r\n `id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,\r\n `ip` varchar(24) NOT NULL,\r\n `active` tinyint(4) DEFAULT NULL,\r\n `reason` varchar(255) DEFAULT NULL,\r\n `time_add` int(32) unsigned DEFAULT NULL,\r\n `admin_id` smallint(6) unsigned DEFAULT NULL,\r\n PRIMARY KEY (`id`),\r\n KEY `ip` (`ip`,`active`)\r\n) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;\r\n\r\n-- ----------------------------\r\n-- Table structure for ech_config\r\n-- ----------------------------\r\nDROP TABLE IF EXISTS `ech_config`;\r\nCREATE TABLE `ech_config` (\r\n `id` smallint(6) NOT NULL AUTO_INCREMENT,\r\n `name` varchar(25) NOT NULL,\r\n `value` varchar(255) NOT NULL,\r\n PRIMARY KEY (`id`),\r\n KEY `i_config` (`name`,`value`)\r\n) ENGINE=MyISAM AUTO_INCREMENT=17 DEFAULT CHARSET=latin1;\r\n\r\n-- ----------------------------\r\n-- Table structure for ech_games\r\n-- ----------------------------\r\nDROP TABLE IF EXISTS `ech_games`;\r\nCREATE TABLE `ech_games` (\r\n `id` smallint(8) unsigned NOT NULL AUTO_INCREMENT,\r\n `name` varchar(255) NOT NULL,\r\n `game` varchar(255) NOT NULL,\r\n `name_short` varchar(255) DEFAULT NULL,\r\n `num_srvs` smallint(9) NOT NULL,\r\n `db_host` varchar(255) NOT NULL,\r\n `db_user` varchar(255) NOT NULL,\r\n `db_pw` varchar(255) DEFAULT NULL,\r\n `db_name` varchar(255) NOT NULL,\r\n `plugins` varchar(255) DEFAULT NULL,\r\n PRIMARY KEY (`id`),\r\n KEY `i_games` (`name`,`num_srvs`)\r\n) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;\r\n\r\n-- ----------------------------\r\n-- Table structure for ech_groups\r\n-- ----------------------------\r\nDROP TABLE IF EXISTS `ech_groups`;\r\nCREATE TABLE `ech_groups` (\r\n `id` smallint(4) unsigned NOT NULL AUTO_INCREMENT,\r\n `name` varchar(32) NOT NULL,\r\n `namep` varchar(255) DEFAULT NULL,\r\n `premissions` varchar(512) NOT NULL,\r\n PRIMARY KEY (`id`,`name`),\r\n KEY `i_name` (`name`,`namep`)\r\n) ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=latin1;\r\n\r\n-- ----------------------------\r\n-- Table structure for ech_links\r\n-- ----------------------------\r\nDROP TABLE IF EXISTS `ech_links`;\r\nCREATE TABLE `ech_links` (\r\n `id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,\r\n `url` varchar(255) NOT NULL,\r\n `name` varchar(80) DEFAULT NULL,\r\n `title` varchar(255) DEFAULT NULL,\r\n PRIMARY KEY (`id`),\r\n UNIQUE KEY `i_url` (`url`)\r\n) ENGINE=MyISAM AUTO_INCREMENT=7 DEFAULT CHARSET=latin1;\r\n\r\n-- ----------------------------\r\n-- Table structure for ech_logs\r\n-- ----------------------------\r\nDROP TABLE IF EXISTS `ech_logs`;\r\nCREATE TABLE `ech_logs` (\r\n `id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,\r\n `type` varchar(64) DEFAULT NULL,\r\n `msg` varchar(255) DEFAULT '',\r\n `client_id` mediumint(5) DEFAULT NULL,\r\n `user_id` smallint(5) DEFAULT NULL,\r\n `time_add` int(32) DEFAULT NULL,\r\n `game_id` mediumint(10) DEFAULT NULL,\r\n PRIMARY KEY (`id`),\r\n KEY `i_logs` (`client_id`,`user_id`)\r\n) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;\r\n\r\n-- ----------------------------\r\n-- Table structure for ech_permissions\r\n-- ----------------------------\r\nDROP TABLE IF EXISTS `ech_permissions`;\r\nCREATE TABLE `ech_permissions` (\r\n `id` mediumint(6) NOT NULL AUTO_INCREMENT,\r\n `name` varchar(50) NOT NULL,\r\n `description` varchar(255) DEFAULT NULL,\r\n PRIMARY KEY (`id`,`name`),\r\n UNIQUE KEY `name` (`name`)\r\n) ENGINE=MyISAM AUTO_INCREMENT=28 DEFAULT CHARSET=latin1;\r\n\r\n-- ----------------------------\r\n-- Table structure for ech_servers\r\n-- ----------------------------\r\nDROP TABLE IF EXISTS `ech_servers`;\r\nCREATE TABLE `ech_servers` (\r\n `id` int(5) unsigned NOT NULL AUTO_INCREMENT,\r\n `game` smallint(5) NOT NULL,\r\n `name` varchar(100) NOT NULL,\r\n `ip` varchar(15) NOT NULL,\r\n `pb_active` tinyint(1) NOT NULL,\r\n `rcon_pass` varchar(50) NOT NULL,\r\n `rcon_ip` varchar(26) NOT NULL,\r\n `rcon_port` int(5) NOT NULL,\r\n PRIMARY KEY (`id`),\r\n KEY `game` (`game`)\r\n) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;\r\n\r\n-- ----------------------------\r\n-- Table structure for ech_user_keys\r\n-- ----------------------------\r\nDROP TABLE IF EXISTS `ech_user_keys`;\r\nCREATE TABLE `ech_user_keys` (\r\n `reg_key` varchar(40) NOT NULL,\r\n `ech_group` smallint(4) NOT NULL,\r\n `admin_id` smallint(5) unsigned NOT NULL,\r\n `comment` varchar(500) DEFAULT NULL,\r\n `time_add` int(24) DEFAULT NULL,\r\n `email` varchar(160) NOT NULL,\r\n `active` tinyint(4) NOT NULL,\r\n PRIMARY KEY (`reg_key`),\r\n KEY `i_regkey` (`active`,`email`)\r\n) ENGINE=MyISAM DEFAULT CHARSET=latin1;\r\n\r\n-- ----------------------------\r\n-- Table structure for ech_users\r\n-- ----------------------------\r\nDROP TABLE IF EXISTS `ech_users`;\r\nCREATE TABLE `ech_users` (\r\n `id` smallint(6) unsigned NOT NULL AUTO_INCREMENT,\r\n `username` varchar(32) NOT NULL,\r\n `display` varchar(32) DEFAULT NULL,\r\n `email` varchar(32) DEFAULT NULL,\r\n `password` varchar(64) NOT NULL,\r\n `salt` varchar(12) NOT NULL,\r\n `ip` varchar(24) DEFAULT NULL,\r\n `ech_group` smallint(4) unsigned NOT NULL DEFAULT '1',\r\n `admin_id` smallint(6) unsigned NOT NULL DEFAULT '0',\r\n `first_seen` int(24) DEFAULT NULL,\r\n `last_seen` int(24) DEFAULT NULL,\r\n `timezone` varchar(32) DEFAULT NULL,\r\n PRIMARY KEY (`id`),\r\n UNIQUE KEY `username` (`username`),\r\n UNIQUE KEY `password` (`password`),\r\n KEY `salt` (`salt`),\r\n KEY `i_group` (`ech_group`)\r\n) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;\r\n\r\n-- ----------------------------\r\n-- Records \r\n-- ----------------------------\r\nINSERT INTO `ech_config` VALUES ('1', 'name', 'Development');\r\nINSERT INTO `ech_config` VALUES ('2', 'num_games', '0');\r\nINSERT INTO `ech_config` VALUES ('3', 'limit_rows', '50');\r\nINSERT INTO `ech_config` VALUES ('4', 'min_pw_len', '8');\r\nINSERT INTO `ech_config` VALUES ('5', 'user_key_expire', '14');\r\nINSERT INTO `ech_config` VALUES ('6', 'email', 'admin@example.com');\r\nINSERT INTO `ech_config` VALUES ('7', 'admin_name', 'Admin');\r\nINSERT INTO `ech_config` VALUES ('8', 'https', '0');\r\nINSERT INTO `ech_config` VALUES ('9', 'allow_ie', '1');\r\nINSERT INTO `ech_config` VALUES ('10', 'time_format', 'D, d/m/y (H:i)');\r\nINSERT INTO `ech_config` VALUES ('11', 'time_zone', 'Europe/Dublin');\r\nINSERT INTO `ech_config` VALUES ('12', 'email_header', 'Hello %name%, This is an email from the Echelon admins.');\r\nINSERT INTO `ech_config` VALUES ('13', 'email_footer', 'Thanks, the %ech_name% Echelon Team');\r\nINSERT INTO `ech_config` VALUES ('14', 'pw_req_level', '1');\r\nINSERT INTO `ech_config` VALUES ('15', 'pw_req_level_group', '64');\r\nINSERT INTO `ech_config` VALUES ('16', 'reg_clan_tags', '=(e)=,=(eG)=,=(eGO)=,{KGB}');\r\nINSERT INTO `ech_config` VALUES ('17', 'newsfeed', 'Echelon has been updated. Please report errors at https://github.com/miltann/Echelon-2. -WatchMiltan');\r\nINSERT INTO `ech_groups` VALUES ('1', 'visitor', 'Visitor', '1,2,4,5');\r\nINSERT INTO `ech_groups` VALUES ('2', 'siteadmin', 'Site Admin', '1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28');\r\nINSERT INTO `ech_groups` VALUES ('3', 'senioradmin', 'Senior Admin', '1,2,3,4,5,8,12,14,16,17,20,21,22,23,24,28');\r\nINSERT INTO `ech_groups` VALUES ('4', 'admin', 'Admin', '1,2,3,4,5,8,16,17,20,21,22,28');\r\nINSERT INTO `ech_groups` VALUES ('5', 'mod', 'Moderator', '1,2,3,4,5,8,16,22');\r\nINSERT INTO `ech_links` VALUES ('1', 'http://wiki.bigbrotherbot.net/doku.php/echelon', 'Echelon Help Wiki', 'Documentation for the installation and use of Echelon');\r\nINSERT INTO `ech_links` VALUES ('2', 'http://echelon.bigbrotherbot.net/', 'Echelon Home', 'Home site of Echelon project, check here for development news, updates, and information regarding Echelon');\r\nINSERT INTO `ech_links` VALUES ('3', 'http://eire32designs.com', 'Eire32 Site', 'The developers site');\r\nINSERT INTO `ech_links` VALUES ('4', 'http://www.bigbrotherbot.net/forums/', 'B3 Site', 'Home of bigbrother bot');\r\nINSERT INTO `ech_links` VALUES ('5', 'http://cback.de/', 'CTracker', 'Anti-worm and anti-injection attack protection');\r\nINSERT INTO `ech_links` VALUES ('6', 'http://dryicons.com/', 'DryIcons', 'Thanks for the use of the nav icons!');\r\nINSERT INTO `ech_permissions` VALUES ('1', 'login', 'Allows the user to login');\r\nINSERT INTO `ech_permissions` VALUES ('2', 'clients', 'Allows the user to view the client listing');\r\nINSERT INTO `ech_permissions` VALUES ('3', 'chatlogs', 'Allows the user to view Chatlogs');\r\nINSERT INTO `ech_permissions` VALUES ('4', 'penalties', 'Allows the user to view the Penalty Listing pages');\r\nINSERT INTO `ech_permissions` VALUES ('5', 'admins', 'Allows the user to view the Admins Pages');\r\nINSERT INTO `ech_permissions` VALUES ('6', 'manage_settings', 'Allows the user to Manage Echelon Settings.');\r\nINSERT INTO `ech_permissions` VALUES ('7', 'chats_edit_tables', 'Allows the user to edit chatlogger settings');\r\nINSERT INTO `ech_permissions` VALUES ('8', 'logs', 'Allows the user to view Logs');\r\nINSERT INTO `ech_permissions` VALUES ('9', 'edit_user', 'Allows the user to edit other Echelon users');\r\nINSERT INTO `ech_permissions` VALUES ('10', 'add_user', 'Allows the user to Add Echelon Users');\r\nINSERT INTO `ech_permissions` VALUES ('11', 'manage_servers', 'Allows the user to Manage Servers');\r\nINSERT INTO `ech_permissions` VALUES ('12', 'ban', 'Allows the user to Ban');\r\nINSERT INTO `ech_permissions` VALUES ('13', 'edit_mask', 'Allows the user to Edit User Level Masks');\r\nINSERT INTO `ech_permissions` VALUES ('14', 'siteadmin', 'Allows the user to control the site blacklist and other admin actions');\r\nINSERT INTO `ech_permissions` VALUES ('15', 'edit_perms', 'Allows the user to the premissions of user groups and users');\r\nINSERT INTO `ech_permissions` VALUES ('16', 'comment', 'Allows a user to add a comment to a client');\r\nINSERT INTO `ech_permissions` VALUES ('17', 'greeting', 'Allows the user to change the greeting of a client');\r\nINSERT INTO `ech_permissions` VALUES ('18', 'edit_client_level', 'Allows user to change a players B3 level');\r\nINSERT INTO `ech_permissions` VALUES ('19', 'edit_ban', 'Allows user to edit a B3 ban');\r\nINSERT INTO `ech_permissions` VALUES ('20', 'view_ip', 'Allows the user to view players IP addresses');\r\nINSERT INTO `ech_permissions` VALUES ('21', 'view_full_guid', 'Allow the user to view players full GUID for clients');\r\nINSERT INTO `ech_permissions` VALUES ('22', 'view_half_guid', 'Allow the user to view half of the player GUID for clients');\r\nINSERT INTO `ech_permissions` VALUES ('23', 'unban', 'Allows user to remove a B3 Ban');\r\nINSERT INTO `ech_permissions` VALUES ('24', 'edit_xlrstats', 'Allows user to edit a client\\'s XLRStats information (hidden, fixed name)');\r\nINSERT INTO `ech_permissions` VALUES ('25', 'ctime', 'Allows user to view CTime information');\r\nINSERT INTO `ech_permissions` VALUES ('26', 'see_update_msg', 'Shows this user the Echelon needs updating message');\r\nINSERT INTO `ech_permissions` VALUES ('27', 'chats_talk_back', 'Allows the user to talk back to the server using the Chats Plugin');\r\nINSERT INTO `ech_permissions` VALUES ('28', 'permban', 'Allows user to permban player.');\r\n", "echelon/actions/autosuggest.php": " 0) {\r\n\r\n\t$query = \"SELECT name FROM clients WHERE UPPER(name) LIKE '\". $string .\"%' ORDER BY name LIMIT 10\";\r\n\t$stmt = $db->mysql->prepare($query);\r\n\t$stmt->execute();\r\n\t$stmt->store_result();\r\n\t\r\n\tif($stmt->num_rows) {\r\n\t\r\n\t\t$stmt->bind_result($name);\r\n\t\r\n\t\techo '
              ';\r\n\t\t\twhile ($stmt->fetch()) :\r\n\t\t\t\techo '
            1. '.$name.'
            2. ';\r\n\t\t\tendwhile;\r\n\t\techo '
            ';\r\n\t\t\r\n\t} else { // else try more flexible query\r\n\t\t\r\n\t\t$query_2 = \"SELECT name FROM clients WHERE SOUNDEX(name) = SOUNDEX('%%\". $string .\"%%') ORDER BY name LIMIT 10\";\r\n\t\t$stmt = $db->mysql->prepare($query_2);\r\n\t\t$stmt->execute();\r\n\t\t$stmt->store_result();\r\n\t\t\t\t\r\n\t\tif($stmt->num_rows) { // if something return data\r\n\t\t\r\n\t\t\t$stmt->bind_result($name);\r\n\t\t\r\n\t\t\techo '
              ';\r\n\t\t\twhile ($stmt->fetch()) :\r\n\t\t\t\techo '
            • '.$name.'
            • ';\r\n\t\t\tendwhile;\r\n\t\t\techo '
            ';\r\n\t\t\t\r\n\t\t} else { // if nothing try even more flexible query\r\n\t\t\r\n\t\t\t$query_3 = \"SELECT name FROM clients WHERE SUBSTRING(SOUNDEX(name),2) = SUBSTRING(SOUNDEX('%%%\". $string .\"%%%'),2) ORDER BY name LIMIT 10\";\r\n\t\t\t$stmt = $db->mysql->prepare($query_3);\r\n\t\t\t$stmt->execute();\r\n\t\t\t$stmt->store_result();\r\n\t\t\t\r\n\t\t\tif($stmt->num_rows) { // if something return data\r\n\t\t\t\r\n\t\t\t\t$stmt->bind_result($name);\r\n\t\t\t\r\n\t\t\t\techo '
              ';\r\n\t\t\t\twhile ($result = $query_3->fetch_object()) :\r\n\t\t\t\t\techo '
            • '.$name.'
            • ';\r\n\t\t\t\tendwhile;\r\n\t\t\t\techo '
            ';\r\n\t\t\t\t\r\n\t\t\t} else { // if nothing try even more flexible query\r\n\t\t\t\t\r\n\t\t\t\techo '
            • There are no matches to your search
            ';\r\n\t\t\t\r\n\t\t\t} // show error if nothing gotten overal\r\n\t\t\r\n\t\t} // end if two returned nothing!\r\n\t\r\n\t} // end if query one returned nothing !\r\n\r\n}\r\n\r\n?>", "echelon/actions/b3/ban.php": "reqLevel('permban') AND $duration_secs > 86400)\r\n sendBack('You can not chose a duration bigger than 1 day.');\r\n \r\n\t$time_expire = time() + $duration_secs; // time_expire is current time plus the duration in seconds\r\n\r\n} // end if pb/tempban var setup\r\n\r\n$data = '(Echelon: '. $mem->name . ' ['. $mem->id .'])'; // since this ban goes down as a B3 ban, tag on some user information (display name and echelon user id)\r\n\r\n## Add Ban to the penalty table ##\r\n$result = $db->penClient($type, $client_id, $duration, $reason, $data, $time_expire);\r\n\t\r\n## Make PB ban to server if Pb is enabled ##\r\nif($is_pb_ban == true) :\r\n\t$i = 1;\r\n\twhile($i <= $game_num_srvs) :\r\n\r\n\t\tif($config['games'][$game]['servers'][$i]['pb_active'] == '1') :\r\n\t\t\t// get the rcon information from the massive config array\r\n\t\t\t$rcon_pass = $config['game']['servers'][$i]['rcon_pass'];\r\n\t\t\t$rcon_ip = $config['game']['servers'][$i]['rcon_ip'];\r\n\t\t\t$rcon_port = $config['game']['servers'][$i]['rcon_port'];\r\n\t\t\t$c_ip = trim($c_ip);\r\n\t\t\r\n\t\t\t// PB_SV_BanGuid [guid] [player_name] [IP_Address] [reason]\r\n\t\t\t$command = \"pb_sv_banguid \" . $pbid . \" \" . $c_name . \" \" . $c_ip . \" \" . $reason;\r\n rcon($rcon_ip, $rcon_port, $rcon_pass, $command); // send the ban command\r\n\t\t\tsleep(1); // sleep for 1 sec in ordere to the give server some time\r\n\t\t\t$command_upd = \"pb_sv_updbanfile\"; // we need to update the ban files\r\n\t\t\trcon($rcon_ip, $rcon_port, $rcon_pass, $command_upd); // send the ban file update command\r\n\t\tendif;\r\n\r\n\t\t$i++;\r\n\tendwhile;\r\nendif;\r\n\r\ntry {\r\n $i = 1;\r\n while($i <= $game_num_srvs) :\r\n // not bulletproof, get client-id from \"status\" and kick using that instead of name. \r\n // thanks androiderpwnz ;)\r\n $rcon_pass = $config['game']['servers'][$i]['rcon_pass'];\r\n $rcon_ip = $config['game']['servers'][$i]['rcon_ip'];\r\n $rcon_port = $config['game']['servers'][$i]['rcon_port'];\r\n \r\n $command = \"drop \" . $c_name. \" \".$reason;\r\n rcon($rcon_ip, $rcon_port, $rcon_pass, $command); // send the ban command\r\n\r\n $i++;\r\n endwhile;\r\n}\r\n\r\n//catch exception\r\ncatch(Exception $e) {\r\n sendBack($e);\r\n}\r\n\r\n\r\nif($result)\r\n\tsendGood('Ban has been added to the database.');\r\nelse\r\n\tsendBack('Something went wrong the ban was not added');\r\n\r\nexit;", "echelon/actions/b3/comment.php": "name;\r\n\r\n// Check for empties\r\nemptyInput($comment, 'comment');\r\nemptyInput($cid, 'client id not sent');\r\n\r\n## Check sent client_id is a number ##\r\nif(!isID($cid))\r\n\tsendBack('Invalid data sent, ban not added');\r\n\r\n\r\n\r\n## Query ##\r\n$result = $dbl->addEchLog('Comment', $comment, $cid, $mem->id, $game);\r\n\r\n$query = $db->penClient('Notice', $cid, '0', $comment, $adminname, '-1');\r\nif($query)\r\n\tsendGood('Comment added.');\r\nelse\r\n\tsendBack('There is a problem, your comment was not added to the database.');", "echelon/actions/b3/editban.php": "mysql->prepare($query) or die('DB Error');\r\n$stmt->bind_param('siisi', $type, $duration, $time_expire, $reason, $ban_id);\r\n$stmt->execute();\r\n\r\nif($stmt->affected_rows > 0)\r\n\t$results = true;\r\nelse\r\n\tsendBack('Something went wrong');\r\n\r\n## If a permaban send unban rcon command (the ban will still be enforced then by the B3 DB ##\r\nif($type == 'Ban') :\r\n\t\r\n\t## Loop thro server for this game and send unban command and update ban file\r\n\t$i = 1;\r\n\twhile($i <= $game_num_srvs) :\r\n\r\n\t\tif($config['games'][$game]['servers'][$i]['pb_active'] == '1') {\r\n\t\t\t// get the rcon information from the massive config array\r\n\t\t\t$rcon_pass = $config['game']['servers'][$i]['rcon_pass'];\r\n\t\t\t$rcon_ip = $config['game']['servers'][$i]['rcon_ip'];\r\n\t\t\t$rcon_port = $config['game']['servers'][$i]['rcon_port'];\r\n\t\t\r\n\t\t\t// PB_SV_BanGuid [guid] [player_name] [IP_Address] [reason]\r\n\t\t\t$command = \"pb_sv_unbanguid \" . $pbid;\r\n\t\t\trcon($rcon_ip, $rcon_port, $rcon_pass, $command); // send the ban command\r\n\t\t\tsleep(1); // sleep for 1 sec in ordere to the give server some time\r\n\t\t\t$command_upd = \"pb_sv_updbanfile\"; // we need to update the ban files\r\n\t\t\trcon($rcon_ip, $rcon_port, $rcon_pass, $command_upd); // send the ban file update command\r\n\t\t}\r\n\r\n\t\t$i++;\r\n\tendwhile;\r\n\r\nendif;\r\n\r\n// set comment for the edit ban action\r\n$comment = 'A ban for this user was edited';\r\n\r\n## Query ##\r\n$result = $dbl->addEchLog('Edit Ban', $comment, $cid, $mem->id, $game);\r\n\r\nif($results)\r\n\tsendGood('Ban edited');\r\nelse\r\n\tsendBack('NO!');\r\n\r\nexit;", "echelon/actions/b3/greeting.php": "addEchLog('Greeting', $comment, $client_id, $mem->id, $game);\t\r\n\t\t\r\n\t## Query ##\r\n\t$query = \"UPDATE clients SET greeting = ? WHERE id = ? LIMIT 1\";\r\n\t$stmt = $db->mysql->prepare($query) or sendBack('Database Error.');\r\n\t$stmt->bind_param('si', $greeting, $client_id);\r\n\t$stmt->execute();\r\n\tif($stmt->affected_rows)\r\n\t\tsendGood('Greeting has been updated.');\r\n\telse\r\n\t\tsendBack('Greeting was not updated.');\r\n\t\r\n\t$stmt->close(); // close connection\r\n\r\nelse :\r\n\r\n\tset_error('Please do not call that page directly, thank you.');\r\n\tsend('../../index.php');\r\n\r\nendif;", "echelon/actions/b3/level.php": "getB3Groups();\r\n\r\n// change around the recieved data\r\n$b3_groups_id = array();\r\nforeach($b3_groups as $group) :\r\n\tarray_push($b3_groups_id, $group['id']); // make an array of all the group_bits that exsist\r\n\t$b3_groups_name[$group['id']] = $group['name']; // make an array of group_bits to matching names\r\nendforeach;\r\n\r\n// Check if the group_bits provided match a known group (Known groups is a list of groups pulled from the DB -- this allow more control for custom groups)\r\nif(!in_array($level, $b3_groups_id))\r\n\tsendBack('That group does not exist, please submit a real group');\r\n\r\n## Check that authorisation passsword is correct ##\r\nif($config['cosmos']['pw_req_level'] == 1 && !$is_mask) : // if requiring a pw auth for edit-level is on or off\r\n\tif($level >= $config['cosmos']['pw_req_level_group']) // site setting to see if only certain levels need a pw check and if the selected level is above the threshold\r\n\t\t$mem->reAuthUser($password, $dbl);\r\nendif;\r\n\r\n## Add Echelon Log ##\r\n$level_name = $b3_groups_name[$level];\r\n$old_level_name = $b3_groups_name[$old_level];\r\nif($old_level_name == \"\")\r\n $old_level_name == 'Un-Registered';\r\n \r\nif(!$is_mask)\r\n\t$comment = 'User level changed from '. $old_level_name .' to '. $level_name;\r\nelse\r\n\t$comment = 'Mask level changed from '. $old_level_name .' to '. $level_name;\r\n\r\n\r\n$dbl->addEchLog('Level Change', $comment, $client_id, $mem->id, $game);\r\n\r\n## Query Section ##\r\nif(!$is_mask)\r\n\t$query = \"UPDATE clients SET group_bits = ? WHERE id = ? LIMIT 1\";\r\nelse\r\n\t$query = \"UPDATE clients SET mask_level = ? WHERE id = ? LIMIT 1\";\r\n\t\r\n$stmt = $db->mysql->prepare($query) or sendBack('Database Error');\r\n$stmt->bind_param('ii', $level, $client_id);\r\n$stmt->execute();\r\n\r\nif($is_mask)\r\n\t$msg_st = 'Mask';\r\nelse\r\n\t$msg_st = 'User';\r\n\r\nif($stmt->affected_rows)\r\n\tsendGood($msg_st.' level has been changed');\r\nelse\r\n\tsendBack($msg_st.' level was not changed');\r\n\r\n$stmt->close(); // close connection", "echelon/actions/b3/unban.php": "makePenInactive($ban_id);\r\n\r\nif(!$results) // if bad send back warning\r\n\tsendBack('Penalty has not been removed');\r\n\t\r\n$guid = $db->getGUIDfromPID($ban_id);\r\n$i = 1; \r\nif($i <= $game_num_srvs) : // only needs to be sent once, if a shared db is used\r\n \r\n $rcon_pass = $config['game']['servers'][$i]['rcon_pass'];\r\n $rcon_ip = $config['game']['servers'][$i]['rcon_ip'];\r\n $rcon_port = $config['game']['servers'][$i]['rcon_port'];\r\n \r\n $command = \"unban \" .$guid;\r\n rcon($rcon_ip, $rcon_port, $rcon_pass, $command); // send the ban command\r\nendif;\r\n \r\n \r\n## If a permban send unban rcon command ##\r\nif($type == 'Ban' AND $config['game']['servers'][$i]['pb_active'] == '1') :\r\n\r\n\t## Get the PBID of the client ##\r\n\t$pbid = $db->getPBIDfromPID($ban_id);\r\n\t\r\n\t## Loop thro server for this game and send unban command and update ban file\r\n\t$i = 1;\r\n\twhile($i <= $game_num_srvs) :\r\n\r\n\t\tif($config['game']['servers'][$i]['pb_active'] == '1') {\r\n\t\t\t// get the rcon information from the massive config array\r\n\t\t\t$rcon_pass = $config['game']['servers'][$i]['rcon_pass'];\r\n\t\t\t$rcon_ip = $config['game']['servers'][$i]['rcon_ip'];\r\n\t\t\t$rcon_port = $config['game']['servers'][$i]['rcon_port'];\r\n\t\t\r\n\t\t\t// PB_SV_BanGuid [guid] [player_name] [IP_Address] [reason]\r\n\t\t\t$command = \"pb_sv_unbanguid \" . $pbid;\r\n\t\t\trcon($rcon_ip, $rcon_port, $rcon_pass, $command); // send the ban command\r\n\t\t\tsleep(1); // sleep for 1 sec in ordere to the give server some time\r\n\t\t\t$command_upd = \"pb_sv_updbanfile\"; // we need to update the ban files\r\n\t\t\trcon($rcon_ip, $rcon_port, $rcon_pass, $command_upd); // send the ban file update command\r\n\t\t}\r\n\r\n\t\t$i++;\r\n\tendwhile;\r\n\r\nendif;\r\n\r\n$comment = 'Unbanned Ban-ID '.$ban_id;\r\n$dbl->addEchLog('Unban', $comment, $cid, $mem->id, $game);\r\n\r\nif($results) // if good results send back good message\r\n\tsendGood('Penalty has been deactivated.');\r\n\t\r\nexit;\r\n", "echelon/actions/blacklist.php": "BLactive($bl_id, false); // run query to deact BL ban\r\n\tsendGood('This blacklist ban has been de-activated');\r\n\texit; // no need to continue\r\n\r\n} elseif($_POST['react']) { // if this is a re-activation request\r\n\r\n\t$bl_id = $_POST['id'];\r\n\tif(!verifyFormToken('act'.$bl_id, $tokens)) // verify token\r\n\t\tifTokenBad('BL De-activate'); // if bad log and send error\r\n\t\r\n\t$dbl->BLactive($bl_id, true); // run query to reactivate BL ban\r\n\tsendGood('This blacklist ban has been re-activiated');\r\n\texit; // no need to continue\r\n\r\n} elseif($_POST['ip']) { // if this is an add request\r\n\t\r\n\tif(!verifyFormToken('addbl', $tokens)) // verify token\r\n\t\tifTokenBad('BL Add'); // if bad log, add hack counter and throw error\r\n\t\r\n\t// set and clean vars\r\n\t$reason = cleanvar($_POST['reason']);\r\n\t$ip = cleanvar($_POST['ip']);\r\n\t\r\n\t// check for empty inputs\r\n\temptyInput($reason, 'the reason');\r\n\temptyInput($ip, 'IP Address');\r\n\t\r\n\t// if reason is default comment msg, send back with error\r\n\tif($reason == \"Enter a reason for this ban...\")\r\n\t\tsendBack('You must add a reason as to why this IP ban is being added');\r\n\t\r\n\t// check if it is a valid IP address\r\n\tif(!filter_var($ip, FILTER_VALIDATE_IP))\r\n\t\tsendBack('That IP address is not valid');\r\n\t\t\r\n\t$whitelist = array('token','reason','ip'); // allow form fields to be sent\r\n\r\n\t// Building an array with the $_POST-superglobal \r\n\tforeach ($_POST as $key=>$item) {\r\n\t\tif(!in_array($key, $whitelist)) {\r\n\t\t\thack(1); // plus 1 to hack counter\r\n\t\t\twriteLog('Add BL - Unknown form fields provided'); // make note of event\r\n\t\t\tsendBack('Unknown Information sent.');\r\n\t\t\texit;\r\n\t\t}\r\n\t} // end foreach\r\n\t\r\n\t## Query Section ##\r\n\t$result = $dbl->blacklist($ip, $reason, $mem->id);\r\n\tif(!$result) // if false\r\n\t\tsendBack('That IP was not added to the blacklist.');\r\n\t\r\n\t// if got this far we are doing well so lets send back a good message\r\n\tsendGood('The IP has been added to the banlist.');\r\n\texit; // no need to continue\r\n\r\n} else { // if this page was not posted and a user indirectly ends up on this page then sent to SA page with error\r\n\tsend('../sa.php');\r\n set_error('Please do not load that page without submitting the ban IP address form.');\r\n}", "echelon/actions/edit-me.php": "name || $email != $mem->email || $timezone != $_SESSION['timezone']) // sent display name does not match session and same with email\r\n\t$is_change_display_email = true; // this is a change request\r\nelse \r\n\t$is_change_display_email = false; // this is not a change request\r\n\r\n// if display/email not changed and its not a change pw request then return\r\nif( (!$is_change_display_email) && (!$is_change_pw) ) \r\n\tsendBack('You didn\\'t change anything, so Echelon has done nothing');\r\n\r\n## Query Section ##\r\n//$mem->reAuthUser($cur_pw, $dbl); // check user current password is correct\r\n\r\nif($is_change_display_email) : // if the display or email have been altered edit them if not skip this section\r\n\t// update display name and email\r\n\t$results = $dbl->editMe($display, $email, $timezone, $mem->id);\r\n\tif(!$results) { // if false (if nothing happened)\r\n\t\tsendBack('There was an error updating your email and display name');\r\n\t} else { // its been changed so we must update the session vars\r\n\t\t$_SESSION['email'] = $email;\r\n\t\t$_SESSION['name'] = $display;\r\n $_SESSION['timezone'] = $timezone;\r\n\t\t$mem->setName($display);\r\n\t\t$mem->setEmail($email);\r\n\t}\r\nendif;\r\n\r\n## if a change pw request ##\r\nif($is_change_pw) : \r\n\r\n\t$result = $mem->genAndSetNewPW($pass1, $mem->id, $min_pw_len); // function to generate and set a new password\r\n\t\r\n\tif(is_string($result)) // result is either true (success) or an error message (string)\r\n\t\tsendBack($result); \r\nendif;\r\n\r\n ## return good ##\r\nsendGood('Your user information has been successfully updated');", "echelon/actions/settings-game.php": "connect_error)) // send back with a failed connection message\r\n\tsendBack('Database Connection Error\r\n\t\t\t\t

            The connection information you supplied is incorrect.
            '.$db_test->connect_error.'

            '); \r\n\r\n## Update DB ##\r\nif($is_add) : // add game queries\r\n\t$result = $dbl->addGame($name, $game_type, $name_short, $db_host, $db_user, $db_pw, $db_name);\r\n\tif(!$result) // if everything is okay\r\n\t\tsendBack('There is a problem, the game information was not saved.');\r\n\t\r\n\t$dbl->addGameCount(); // Add one to the game counter in config table\t\r\n\t\r\nelse : // edit game queries\r\n\t$mem->reAuthUser($password, $dbl);\r\n\t$result = $dbl->setGameSettings($game, $name, $name_short, $db_user, $db_host, $db_name, $db_pw, $change_db_pw, $enabled); // update the settings in the DB\r\n\tif(!$result)\r\n\t\tsendBack('Something did not update. Did you edit anything?');\r\nendif;\r\n\r\n## Return with result message\r\nif($is_add) {\r\n\tset_good('Game Added');\r\n\tsend('../settings-games.php');\r\n} else \r\n\tsendGood('Your settings have been updated');\r\n", "echelon/actions/settings-server.php": "delServer($sid);\r\n\tif(!$result)\r\n\t\tsendBack('There was a problem with deleting the server.');\r\n\t\r\n\t$result = $dbl->delServerUpdateGames($game_id);\r\n\tif(!$result)\r\n\t\tsendBack('There was a problem with deleting the server.');\r\n\t\r\n\tsendGood('The server has been deleted.');\r\n\t\r\n\texit; // stop - no need to load the rest of the page\r\n\r\nendif;\r\n\r\n## Check that the form was posted and that the user did not just stumble here ##\r\nif(!isset($_POST['server-settings-sub'])) :\r\n\tset_error('Please do not call that page directly, thank you.');\r\n\tsend('../index.php');\r\nendif;\r\n\r\n## What type of request is it ##\r\nif($_POST['type'] == 'add')\r\n\t$is_add = true;\r\nelseif($_POST['type'] == 'edit')\r\n\t$is_add = false;\r\nelse\r\n\tsendBack('Missing Data');\r\n\r\n## Check Token ##\r\nif($is_add) { // if add server request\r\n\tif(verifyFormToken('addserver', $tokens) == false) // verify token\r\n\t\tifTokenBad('Add Server');\r\n} else { // if edit server settings\r\n\tif(verifyFormToken('editserversettings', $tokens) == false) // verify token\r\n\t\tifTokenBad('Server Settings Edit');\r\n}\r\n\r\n## Get Vars ##\r\n$name = cleanvar($_POST['name']);\r\n$ip = cleanvar($_POST['ip']);\r\n$pb = cleanvar($_POST['pb']);\r\n// DB Vars\r\n$rcon_ip = cleanvar($_POST['rcon-ip']);\r\n$rcon_port = cleanvar($_POST['rcon-port']);\r\n$rcon_pw_cng = cleanvar($_POST['cng-pw']);\r\n$rcon_pw = cleanvar($_POST['rcon-pass']);\r\n$server_id = cleanvar($_POST['server']);\r\n\r\nif($is_add)\r\n\t$game_id = cleanvar($_POST['game-id']);\r\n\r\n// Whether to change RCON PW or not\r\nif($rcon_pw_cng == 'on')\r\n\t$change_rcon_pw = true;\r\nelse\r\n\t$change_rcon_pw = false;\r\n\t\r\n// Whether to change DB PW or not\r\nif($pb == 'on')\r\n\t$pb = 1;\r\nelse\r\n\t$pb = 0;\r\n\r\n## Check for empty vars ##\r\nemptyInput($name, 'server name');\r\nemptyInput($ip, 'server IP');\r\nemptyInput($rcon_ip, 'Rcon IP');\r\nemptyInput($rcon_port, 'Rcon Port');\r\nif($change_rcon_pw == true)\r\n\temptyInput($rcon_pw, 'Rcon password');\r\n\r\n// check that the rcon_ip is valid\r\nif(!filter_var($rcon_ip, FILTER_VALIDATE_IP))\r\n\tsendBack('That RCON IP Address is not valid.');\r\n\t\r\n// check that the rcon_ip is valid\r\nif( (!filter_var($ip, FILTER_VALIDATE_IP)))\r\n\tsendBack('That server IP Address is not valid.');\r\n\t\r\n// Check Port is a number between 4-5 digits\r\nif( (!is_numeric($rcon_port)) || (!preg_match('/^[0-9]{4,5}$/', $rcon_port)) )\r\n\tsendBack('Rcon Port must be a number between 4-5 digits');\r\n\r\nif($is_add) : // if is add server request\r\n\tif(!is_numeric($game_id)) // game_id is a digit\r\n\t\tsendBack('Invalid data sent.');\r\nendif;\r\n\t\r\n## Update DB ##\r\nif($is_add) :\r\n\t$result = $dbl->addServer($game_id, $name, $ip, $pb, $rcon_ip, $rcon_port, $rcon_pw);\r\n\t$dbl->addServerUpdateGames($game_id);\r\nelse :\r\n\t$result = $dbl->setServerSettings($server_id, $name, $ip, $pb, $rcon_ip, $rcon_port, $rcon_pw, $change_rcon_pw); // update the settings in the DB\r\nendif;\r\n\r\nif(!$result)\r\n\tsendBack('Something did not update');\r\n\r\n## Return ##\r\nif($is_add) {\r\n\tset_good('Server '. $name .' has been added to the database records.');\r\n\tsend('../settings-server.php');\r\n} else\r\n\tsendGood('Your settings have been updated.');\r\n", "echelon/actions/settings.php": "reAuthUser($password, $dbl);\r\n\t\r\n## Create array of sent vars ##\r\n$sent_settings = array(\r\n\t'name' => $f_name,\r\n\t'limit_rows' => $f_limit_rows,\r\n\t'min_pw_len' => $f_min_pw_len,\r\n\t'user_key_expire' => $f_user_key_expire,\r\n\t'email' => $f_email,\r\n\t'admin_name' => $f_admin_name,\r\n\t'https' => $f_https,\r\n\t'allow_ie' => $f_allow_ie,\r\n\t'time_format' => $f_time_format,\r\n\t'time_zone' => $f_time_zone, \r\n\t'email_header' => $f_email_header,\r\n\t'email_footer' => $f_email_footer,\r\n 'newsfeed' => $f_newsfeed,\r\n);\r\n\r\n## What needs updating ##\r\n// Check the values sent by the form against what is stored in the database to find out what needs to be updated\r\n// rather than just updating every config settings in the DB\r\n$settings_table = $dbl->getSettings('cosmos'); // get the values of the settings from the config db table\r\n\r\nif(!$no_games) :\r\n\t$sent_settings['pw_req_level'] = $f_pw_req_level;\r\n\t$sent_settings['pw_req_level_group'] = $f_pw_req_level_group;\r\nelse:\t\r\n\t$sent_settings['pw_req_level'] = $settings_table['pw_req_level'];\r\n\t$sent_settings['pw_req_level_group'] = $settings_table['pw_req_level_group'];\r\nendif;\r\n\r\nforeach($sent_settings as $key => $value) :\r\n\tif($sent_settings[$key] != $settings_table[$key])\r\n\t\t$updates[$key] = $value;\r\nendforeach;\r\n\r\n## Update DB ##\r\nforeach($updates as $key => $value) :\r\n\tif($key == 'limit_rows' || $key == 'min_pw_len' || $key == 'user_key_expire' || $key == 'pw_req_level')\r\n\t\t$value_type = 'i';\r\n\telse\r\n\t\t$value_type = 's';\r\n\t\t\r\n\tif($key != 'num_games') // num_games is the only cosmos setting not to be changed by this page\r\n\t\t$result = $dbl->setSettings($value, $key, $value_type); /// update the settings in the DB\r\n\t\r\n\tif($result == false)\r\n\t\tsendBack('Something did not update');\r\n\r\nendforeach;\r\n\r\n## Return ##\r\nsendGood('Your settings have been updated');\r\n", "echelon/actions/user-add.php": "';\r\n$body .= '

            Echelon User Key

            ';\r\n$body .= $config['cosmos']['email_header'];\r\n$body .= 'This is the key you will need to use to register on Echelon. \r\n\t\t\tRegister here.
            ';\r\n$body .= 'Registration Key: '.$user_key;\r\n$body .= $config['cosmos']['email_footer'];\r\n$body .= '';\r\n\r\n// replace %ech_name% in body of email with var from config\r\n$body = preg_replace('#%ech_name%#', $config['cosmos']['name'], $body);\r\n// replace %name%\r\n$body = preg_replace('#%name%#', 'new user', $body);\r\n\r\n$headers = 'MIME-Version: 1.0' . \"\\r\\n\"; \r\n$headers = \"From: echelon@\".$_SERVER['HTTP_HOST'].\"\\r\\n\";\r\n$headers .= \"Reply-To: \". EMAIL .\"\\r\\n\";\r\n$headers .= 'Content-type: text/html; charset=iso-8859-1' . \"\\r\\n\"; \r\n$subject = \"Echelon User Registration\";\r\n\r\n\r\n// send email\r\n#try {\r\n#mail($email, $subject, $body, $headers);\r\n# sendGood('Mail sent.');\r\n#} catch (Exception $e) {\r\n# sendBack('Caught exception: ', $e->getMessage(), \".\");\r\n#}\r\n\r\n#if(!mail($email, $subject, $body, $headers))\r\n#\tsendback('There was a problem sending the email.');\r\n\t\r\n## run query to add key to the DB ##\r\n$add_user = $dbl->addEchKey($user_key, $email, $comment, $group, $mem->id);\r\nif(!$add_user)\r\n\tsendBack('There was a problem adding the key into the database');\r\n\r\n// all good send back good message\r\n#sendGood('Key Setup and Email has been sent to user');\r\nsendGood('Send this link to user:\r\n\t\t\t\"http://'.$_SERVER['SERVER_NAME'].PATH.'register.php?key='.$user_key.'&email='.$email.'\"');", "echelon/active.php": "= 8\r\n\tAND(%d - c.time_edit > %d*60*60*24 )\", $time, $length);\r\n\r\n$query .= sprintf(\"ORDER BY %s \", $orderby);\r\n\r\n## Append this section to all queries since it is the same for all ##\r\nif($order == \"DESC\")\r\n\t$query .= \" DESC\"; // set to desc \r\nelse\r\n\t$query .= \" ASC\"; // default to ASC if nothing adds up\r\n\r\n$query_limit = sprintf(\"%s LIMIT %s, %s\", $query, $start_row, $limit_rows); // add limit section\r\n\r\n## Require Header ##\r\nrequire 'inc/header.php'; \r\n\r\nif(!$db->error) :\r\n?>\r\n\r\n
            \r\n
            \r\n
            Inactive Admins
            \r\n
            \r\n\r\n\t\t\r\n
            \r\n There are admins who have not been seen by B3 for\r\n\t\t\t\r\n
            \r\n\t\t\r\n\t\r\n\t\r\n\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\r\n\t\r\n\t\r\n\t\t\r\n\t\t\t\r\n\t\t\r\n\t\r\n\t\r\n\t 0) { // query contains stuff\r\n\t \r\n\t\tforeach($data_set as $info): // get data from query and loop\r\n\t\t\t$cid = $info['id'];\r\n\t\t\t$name = $info['name'];\r\n\t\t\t$level = $info['level'];\r\n\t\t\t$connections = $info['connections'];\r\n\t\t\t$time_edit = $info['time_edit'];\r\n\t\t\t\r\n\t\t\t## Change to human readable\t\t\r\n\t\t\t$time_diff = time_duration($time - $time_edit, 'yMwd');\t\t\r\n\t\t\t$time_edit = date($tformat, $time_edit); // this must be after the time_diff\r\n\t\t\t$client_link = clientLink($name, $cid);\r\n\r\n\t\t\t$alter = alter();\r\n\t\r\n\t\t\t// setup heredoc (table data)\t\t\t\r\n\t\t\t$data = <<\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\nEOD;\r\n\r\n\t\t\techo $data;\r\n\t\tendforeach;\r\n\t\t\r\n\t\t$no_data = false;\r\n\t} else {\r\n\t\t$no_data = true;\r\n\t\techo '';\r\n\t} // end if query contains information\r\n\t?>\r\n\t\r\n
            Name\r\n\t\t\t\t\r\n\t\t\tClient-ID\r\n\t\t\t\t\r\n\t\t\tLevel\r\n\t\t\t\t\r\n\t\t\tConnections\r\n\t\t\t\t\r\n\t\t\tLast Seen\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\tDuration\r\n\t\t\t
            Click client name to see details.
            $client_link@$cid$level$connections$time_edit$time_diff
            There are no admins that have been in active for more than '. $length . ' days.
            \r\n
            \r\n\r\n", "echelon/adminkicks.php": "error) :\r\n?>\r\n
            \r\n
            \r\n
            \r\n
            Admin Kicks
            \r\n
            \r\n \r\n\t\r\n\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\r\n\t\r\n\t\r\n\t\t\r\n\t\t\t\r\n\t\t\r\n\t\r\n\t\r\n\t 0) : // query contains stuff\r\n\r\n\t\tforeach($data_set as $data): // get data from query and loop\r\n\t\t\t$time_add = $data['time_add'];\r\n\t\t\t$reason = tableClean($data['reason']);\r\n\t\t\t$client_id = $data['target_id'];\r\n\t\t\t$client_name = tableClean($data['target_name']);\r\n\t\t\t$admin_id = $data['admin_id'];\r\n\t\t\t$admin_name = tableClean($data['admins_name']);\r\n\r\n\t\t\t## Tidt data to make more human friendly\r\n\t\t\tif($time_expire != '-1')\r\n\t\t\t\t$duration_read = time_duration($duration*60); // all penalty durations are stored in minutes, so multiple by 60 in order to get seconds\r\n\t\t\telse\r\n\t\t\t\t$duration_read = '';\r\n\r\n\t\t\t$time_add_read = date($tformat, $time_add);\r\n\t\t\t$reason_read = removeColorCode($reason);\r\n\t\t\t$client_link = clientLink($client_name, $client_id);\r\n\t\t\t$admin_link = clientLink($admin_name, $admin_id);\r\n\t\t\t\r\n\t\t\t## Row color\r\n\t\t\t$alter = alter();\r\n\r\n\t\t\t// setup heredoc (table data)\t\t\t\r\n\t\t\t$data = <<\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\nEOD;\r\n\r\n\t\techo $data;\r\n\t\tendforeach;\r\n\telse:\r\n\t\t$no_data = true;\r\n\t\techo '';\r\n\tendif; // no records\r\n\t?>\r\n\t\r\n
            Client\r\n\t\t\t\t\r\n\t\t\tKicked At\r\n\t\t\t\t\r\n\t\t\tReason\r\n\t\t\t\tAdmin\r\n\t\t\t\t\r\n\t\t\t
            $client_link$time_add_read$reason_read$admin_link
            There are no kicks in the database
            \r\n
            \r\n\r\n", "echelon/admins.php": "= 8 ORDER BY %s\", $orderby);\r\n\r\n## Append this section to all queries since it is the same for all ##\r\n$order = strtoupper($order); // force uppercase to stop inconsistentcies\r\nif($order == \"DESC\")\r\n\t$query .= \" DESC\"; // set to desc \r\nelse\r\n\t$query .= \" ASC\"; // default to ASC if nothing adds up\r\n\r\n$query_limit = sprintf(\"%s LIMIT %s, %s\", $query, $start_row, $limit_rows); // add limit section\r\n\r\n## Require Header ##\t\r\nrequire 'inc/header.php';\r\n\r\nif(!$db->error) :\r\n?>\r\n
            \r\n
            \r\n
            Admin Listing
            \r\n
            \r\n\r\n\t\r\n\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\r\n\t\r\n\t\r\n\t\t\r\n\t\t\t\r\n\t\t\r\n\t\r\n\t\r\n\t 0) : // query contains stuff\r\n\t \r\n\t\tforeach($data_set as $data): // get data from query and loop\r\n\t\t\t$cid = $data['id'];\r\n\t\t\t$name = $data['name'];\r\n\t\t\t$level = $data['level'];\r\n\t\t\t$connections = $data['connections'];\r\n\t\t\t$time_edit = $data['time_edit'];\r\n\t\t\t\r\n\t\t\t## Change to human readable\t\t\r\n\t\t\t$time_edit_read = date($tformat, $time_edit); // this must be after the time_diff\r\n\t\t\t$client_link = clientLink($name, $cid);\r\n\t\t\t\r\n\t\t\t## row color\r\n\t\t\t$alter = alter();\r\n\t\r\n\t\t\t// setup heredoc (table data)\t\t\t\r\n\t\t\t$data = <<\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\nEOD;\r\n\r\n\t\t\techo $data;\r\n\t\tendforeach;\r\n\t\t\r\n\t\t$no_data = false;\r\n\telse:\r\n\t\t$no_data = true;\r\n\t\techo '';\r\n\tendif; // no records\r\n\t?>\r\n\t\r\n
            Name\r\n\t\t\t\t\r\n\t\t\tLevel\r\n\t\t\t\t\r\n\t\t\tClient-id\r\n\t\t\t\t\r\n\t\t\tConnections\r\n\t\t\t\t\r\n\t\t\tLast Seen\r\n\t\t\t\t\r\n\t\t\t
            $client_link$level@$cid$connections$time_edit_read
            There are no registered admins
            \r\n
            \r\n", "echelon/bans.php": " 0 AND p.client_id = target.id AND p.admin_id = c.id\";\r\nelse\r\n\t$query = \"SELECT p.type, p.time_add, p.time_expire, p.reason, p.data, p.duration, p.client_id, c.name as client_name FROM penalties p LEFT JOIN clients c ON p.client_id = c.id WHERE p.admin_id = 0 AND (p.type = 'Ban' OR p.type = 'TempBan' OR p.type = 'Kick') AND p.inactive = 0\";\r\n\r\n\r\n$query .= sprintf(\" ORDER BY %s \", $orderby);\r\n\r\n## Append this section to all queries since it is the same for all ##\r\nif($order == \"DESC\")\r\n\t$query .= \" DESC\"; // set to desc \r\nelse\r\n\t$query .= \" ASC\"; // default to ASC if nothing adds up\r\n\r\n$query_limit = sprintf(\"%s LIMIT %s, %s\", $query, $start_row, $limit_rows); // add limit section\r\n\r\n## Require Header ##\t\r\nrequire 'inc/header.php';\r\n\r\n?>\r\n
            \r\n
            \r\nerror) :\r\n\r\nif($type_admin) :\r\n echo '
            Admin Bans
            ';\r\nelse:\r\n echo '
            B3 Bans & Kicks
            ';\r\nendif;\r\n?>\r\n
            \r\n\r\n\r\n\t\r\n\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\tAdmin'; // only the admin type needs this header line ?>\r\n\t\t\r\n\t\r\n\t\r\n\t\t\r\n\t\t\t'; // admin type has 7 cols\r\n\t\t\t\telse \r\n\t\t\t\t\techo ''; // the b3 type has only 6 cols\r\n\t\t\t?>\r\n\t\t\r\n\t\r\n\t\r\n\t 0) { // query contains stuff\r\n\r\n\t\tforeach($data_set as $data): // get data from query and loop\r\n\t\t\t$type = $data['type'];\r\n\t\t\t$time_add = $data['time_add'];\r\n\t\t\t$time_expire = $data['time_expire'];\r\n\t\t\t$reason = tableClean($data['reason']);\r\n\t\t\t$pen_data = tableClean($data['data']);\r\n\t\t\t$duration = $data['duration'];\r\n\t\t\t$client_id = $data['client_id'];\r\n\t\t\t$client_name = tableClean($data['client_name']);\r\n\t\t\t\r\n\t\t\tif($type_admin) { // only admin type needs these lines\r\n\t\t\t\t$admin_id = $data['admins_id'];\r\n\t\t\t\t$admin_name = tableClean($data['admins_name']);\r\n\t\t\t}\r\n\r\n\t\t\t## Tidt data to make more human friendly\r\n\t\t\tif($time_expire != '-1')\r\n\t\t\t\t$duration_read = time_duration($duration*60); // all penalty durations are stored in minutes, so multiple by 60 in order to get seconds\r\n\t\t\telse\r\n\t\t\t\t$duration_read = '';\r\n\r\n\t\t\tif($type == 'Kick')\r\n\t\t\t\t$time_expire_read = '(Kick Only)'; \r\n elseif ($type == 'Notice')\r\n $time_expire_read = ''; \r\n\t\t\telse\r\n\t\t\t\t$time_expire_read = timeExpirePen($time_expire);\r\n \r\n\t\t\t\r\n\t\t\t$time_add_read = date($tformat, $time_add);\r\n\t\t\t$reason_read = removeColorCode($reason);\r\n\t\t\t\r\n\t\t\tif($type_admin) // admin cell only needed for admin type\r\n\t\t\t\t$admin = '';\r\n\t\t\telse\r\n\t\t\t\t$admin = NULL;\r\n\r\n\t\t\t## Row color\r\n\t\t\t$alter = alter();\r\n\t\t\t\t\r\n\t\t\t$client = clientLink($client_name, $client_id);\r\n\r\n\t\t\t// setup heredoc (table data)\t\t\t\r\n\t\t\t$data = <<\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t$admin\r\n\t\t\t\r\nEOD;\r\n\r\n\t\t\techo $data;\r\n\t\tendforeach;\r\n\t\t\r\n\t\t$no_data = false;\r\n\t} else {\r\n\t\t$no_data = true;\r\n\t\tif($type_admin) // slight chnages between different page types\r\n\t\t\techo '';\r\n\t\telse\r\n\t\t\techo '';\r\n\t} // end if query contains\r\n\t?>\r\n\t\r\n
            Target\r\n\t\t\t\t\r\n\t\t\tType\r\n\t\t\t\t\r\n\t\t\tAdded\r\n\t\t\t\t\r\n\t\t\tDuration\r\n\t\t\t\t\r\n\t\t\tExpires\r\n\t\t\t\t\r\n\t\t\tReason
            '. clientLink($admin_name, $admin_id) .'$client$type$time_add_read$duration_read$time_expire_read$reason_read\r\n\t\t\t\t\t
            $pen_data\r\n\t\t\t\t
            There no tempbans or bans made by admins in the database
            There no tempbans or bans made by the B3 bot in the database
            \r\n
            \r\n\r\n", "echelon/classes/dbl-class.php": "install = $install;\r\n\t\t\r\n\t\ttry { \r\n\t\t\t$this->connectDB(); // try to connect to the database\r\n\t\t\t\r\n\t\t} catch (Exception $e) {\r\n\t\t\r\n\t\t\tif($this->install) // if this is an install test return message\r\n\t\t\t\t$this->install_error = $e->getMessage();\r\n\t\t\telse\r\n\t\t\t\tdie($e->getMessage());\r\n\t\t\t\r\n\t\t} // end try/catch\r\n\t\t\r\n\t} // end construct\r\n\t\r\n\t// Do not allow the clone operation\r\n private function __clone() { }\r\n\r\n\t/**\r\n * Makes the connection to the DB or throws error\r\n */\r\n private function connectDB () {\r\n\t\tif($this->mysql != NULL) // if it is set/created (default starts at NULL)\r\n\t\t\t@$this->mysql->close();\r\n\r\n $this->mysql = @new mysqli(DBL_HOSTNAME, DBL_USERNAME, DBL_PASSWORD, DBL_DB); // block any error on connect, it will be caught in the next line and handled properly\r\n\t\t\r\n\t\tif(mysqli_connect_errno()) : // if the connection error is on then throw exception\r\n\r\n\t\t\tif($this->install) :\r\n\t\t\t\t$error_msg = 'Database Connection Error\r\n\t\t\t\t\t

            '.mysqli_connect_error().'
            \r\n\t\t\t\t\tThe connection information you supplied is incorrect. Please try again.

            ';\r\n\t\t\t\r\n\t\t\telseif(DB_CON_ERROR_SHOW) : // only if settings say show to con error, will we show it, else just say error\r\n\t\t\t\t$error_msg = '

            Database Connection Error

            \r\n\t\t\t\t\t

            '.mysqli_connect_error().'
            \r\n\t\t\t\t\tSince we have encountered a database error, Echelon is shutting down.

            ';\r\n\t\t\t\t\t\t\t\t\r\n\t\t\telse :\r\n\t\t\t\t$error_msg = '

            Database Problem

            \r\n\t\t\t\t\t

            Since we have encountered a database error, Echelon is shutting down.

            ';\r\n\t\t\t\t\t\t\t\t\r\n\t\t\tendif;\r\n\r\n\t\t\tthrow new Exception($error_msg);\r\n\t\tendif;\r\n\t\t\r\n } // end connect\r\n\t\r\n\t/**\r\n * __destruct : Destructor for class, closes the MySQL connection\r\n */\r\n public function __destruct() {\r\n if ($this->mysql != NULL) // if it is set/created (defalt starts at NULL)\r\n @$this->mysql->close(); // close the connection\r\n }\r\n\t\r\n\t/**\r\n\t * Handy Query function\r\n\t *\r\n\t * @param string $sql - the SQL query to execute\r\n\t * @param bool $fetch - fetch the data rows or not\r\n\t * @param string $type - typpe of query this is \r\n\t */\r\n\tprivate function query($sql, $fetch = true, $type = 'select') {\r\n\r\n\t\tif($this->error)\r\n\t\t\treturn false;\r\n\t\t\r\n\t\ttry {\r\n\t\t\r\n\t\t\tif($stmt = $this->mysql->prepare($sql))\r\n\t\t\t\t$stmt->execute();\r\n\t\t\telse\r\n\t\t\t\tthrow new Exception('');\r\n\r\n\t\t} catch (Exception $e) {\r\n\t\t\r\n\t\t\t$this->error = true; // there is an error\r\n\t\t\tif($this->error_on) // if detailed errors work\r\n\t\t\t\t$this->error_msg = \"MySQL Query Error (#\". $this->mysql->errno .\"): \". $this->mysql->error;\r\n\t\t\telse\r\n\t\t\t\t$this->error_msg = $this->error_sec;\r\n\r\n\t\t\treturn;\r\n\t\t}\r\n\t\t\r\n\t\t## setup results array\r\n\t\t$results = array();\r\n\t\t$results['data'] = array();\r\n\t\t\r\n\t\t## do certain things depending on type of query\r\n\t\tswitch($type) { \r\n\t\t\tcase 'select': // if type is a select query\r\n\t\t\t\t$stmt->store_result();\r\n\t\t\t\t$results['num_rows'] = $stmt->num_rows(); // find the number of rows retrieved\r\n\t\t\tbreak;\r\n\t\t\t\r\n\t\t\tcase 'update':\r\n\t\t\tcase 'insert': // if insert or update find the number of rows affected by the query\r\n\t\t\t\t$results['affected_rows'] = $stmt->affected_rows(); \r\n\t\t\tbreak;\r\n\t\t}\r\n\t\t\r\n\t\t## fetch the results\r\n\t\tif($fetch) : // only fetch data if we need it\r\n\t\t\r\n\t\t\t$meta = $stmt->result_metadata();\r\n\r\n\t\t\twhile ($field = $meta->fetch_field()) :\r\n\t\t\t\t$parameters[] = &$row[$field->name];\r\n\t\t\tendwhile;\r\n\r\n\t\t\tcall_user_func_array(array($stmt, 'bind_result'), $parameters);\r\n\r\n\t\t\twhile ($stmt->fetch()) :\r\n\t\t\t\tforeach($row as $key => $val) {\r\n\t\t\t\t\t$x[$key] = $val;\r\n\t\t\t\t}\r\n\t\t\t\t$results['data'][] = $x;\r\n\t\t\tendwhile;\r\n\r\n\t\tendif;\r\n\t\t\r\n\t\t## return and close off connections\r\n\t\treturn $results;\r\n\t\t$results->close();\r\n\t\t$stmt->close();\r\n\t\t\r\n\t} // end query()\r\n\t\r\n\t/***************************\r\n\t\r\n\t\tStart Query Functions\r\n\t\r\n\t****************************/\r\n\t\r\n\t\r\n\t/**\r\n\t * Gets an array of data for the settings form\r\n\t *\r\n\t * @param string $cat - category of settigs to retrieve\r\n\t * @return array\r\n\t */\r\n\tfunction getSettings() {\r\n $query = \"SELECT name, value FROM ech_config\";\r\n $stmt = $this->mysql->prepare($query) or die('Database Error');\r\n\t\t$stmt->execute();\r\n\t\t\r\n\t\t$stmt->store_result();\r\n\t\t$stmt->bind_result($name, $value);\r\n \r\n\t\t$settings = array();\r\n\t\t\r\n while($stmt->fetch()) : // get results\r\n $settings[$name] = $value;\r\n endwhile;\r\n\t\t\r\n\t\t$stmt->close();\r\n\t\t\r\n return $settings;\r\n }\r\n\t\r\n\tfunction getGameInfo($game) {\r\n\t\r\n\t\t$query = \"SELECT id, game, name, name_short, num_srvs, db_host, db_user, db_pw, db_name, plugins FROM ech_games WHERE id = ?\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error');\r\n\t\t$stmt->bind_param('i', $game);\r\n\t\t$stmt->execute();\r\n\t\t\r\n\t\t$stmt->bind_result($id, $game, $name, $name_short, $num_srvs, $db_host, $db_user, $db_pw, $db_name, $plugins);\r\n $stmt->fetch(); // get results\t\t\r\n\t\t\r\n\t\t$game = array(\r\n\t\t\t'id' => $id,\r\n\t\t\t'game' => $game,\r\n\t\t\t'name' => $name,\r\n\t\t\t'name_short' => $name_short,\r\n\t\t\t'num_srvs' => $num_srvs,\r\n\t\t\t'db_host' => $db_host,\r\n\t\t\t'db_user' => $db_user,\r\n\t\t\t'db_pw' => $db_pw,\r\n\t\t\t'db_name' => $db_name,\r\n\t\t\t'plugins' => $plugins\r\n\t\t);\r\n\t\t\r\n\t\treturn $game;\r\n\t}\r\n \r\n\t/**\r\n\t * Update the settings\r\n\t *\r\n\t * @param string/int $value - the new value for the setting\r\n\t * @param string $name - the name of the settings\r\n\t * @param string $value_type - wheather the value provided is a string or an int\r\n\t * @return bool\r\n\t */\r\n function setSettings($value, $name, $value_type) {\r\n \r\n\t\t$query = \"UPDATE ech_config SET value = ? WHERE name = ? LIMIT 1\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error');\r\n\t\t$stmt->bind_param($value_type.'s', $value, $name);\r\n\t\t$stmt->execute();\r\n\t\t\r\n\t\t$affect = $stmt->affected_rows;\r\n\t\t$stmt->close();\r\n\t\t\r\n\t\tif($affect > 0)\r\n\t\t\treturn true;\r\n\t\telse\r\n\t\t\treturn false;\r\n }\r\n \r\n\t/**\r\n\t * Add new settings to Echelon (ech_config)\r\n\t *\r\n\t * @param string/int $value - the new value for the setting\r\n\t * @param string $name - the name of the settings\r\n\t * @param string $value_type - wheather the value provided is a string or an int\r\n\t * @return bool\r\n\t */\r\n function addSettings($value, $name, $value_type) {\r\n \r\n\t\t$query = \"INSERT INTO ech_config (id, value, name) VALUES (NULL, ?, ?)\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error');\r\n\t\t$stmt->bind_param($value_type.'s', $value, $name);\r\n\t\t$stmt->execute();\r\n\t\t\r\n\t\t$affect = $stmt->affected_rows;\r\n\t\t$stmt->close();\r\n\t\t\r\n\t\tif($affect > 0)\r\n\t\t\treturn true;\r\n\t\telse\r\n\t\t\treturn false;\r\n }\r\n\t\r\n\t/**\r\n\t * Update game settings\r\n\t *\r\n\t * @return bool\r\n\t */\r\n function setGameSettings($game, $name, $name_short, $db_user, $db_host, $db_name, $db_pw, $change_db_pw, $plugins) {\r\n\t\t\r\n\t\t$query = \"UPDATE ech_games SET name = ?, name_short = ?, db_host = ?, db_user = ?, db_name = ?, plugins = ?\";\r\n\t\t\r\n\t\tif($change_db_pw) // if the DB password is to be chnaged\r\n\t\t\t$query .= \", db_pw = ?\";\r\n\r\n\t\t$query .= \" WHERE id = ? LIMIT 1\";\r\n\t\t\t\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error');\r\n\t\tif($change_db_pw) // if change DB PW append var\r\n\t\t\t$stmt->bind_param('sssssssi', $name, $name_short, $db_host, $db_user, $db_name, $plugins, $db_pw, $game);\r\n\t\telse // else var info not needed in bind_param\r\n\t\t\t$stmt->bind_param('ssssssi', $name, $name_short, $db_host, $db_user, $db_name, $plugins, $game);\r\n\t\t$stmt->execute();\r\n\t\t\r\n\t\tif($stmt->affected_rows > 0)\r\n\t\t\treturn true;\r\n\t\telse\r\n\t\t\treturn false;\r\n }\r\n\t\r\n\t/**\r\n\t * Add a Game to the Echelon list\r\n\t *\r\n\t * @param string $name - name of the game\r\n\t * @param string $game - the game type (eg. cod4, cod2, bfbc2)\r\n\t * @param string $name_short - short name for the game\r\n\t * @param string $db_host - database host\r\n\t * @param string $db_user - database user\r\n\t * @param string $db_pw - database password\r\n\t * @param string $db_name - database name\r\n\t * @return bool\r\n\t */\r\n\tfunction addGame($name, $game, $name_short, $db_host, $db_user, $db_pw, $db_name) {\r\n\t\t// id, name, game, name_short, num_srvs, db_host, db_user, db_pw, db_name\r\n\t\t$query = \"INSERT INTO ech_games (name, game, name_short, num_srvs, db_host, db_user, db_pw, db_name) VALUES(?, ?, ?, 0, ?, ?, ?, ?)\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error:'. $this->mysql->error);\r\n\t\t$stmt->bind_param('sssssss', $name, $game, $name_short, $db_host, $db_user, $db_pw, $db_name);\r\n\t\t$stmt->execute();\r\n\t\t\r\n\t\tif($stmt->affected_rows > 0)\r\n\t\t\treturn true;\r\n\t\telse\r\n\t\t\treturn false;\r\n\t}\r\n\t\r\n\tfunction addGameCount() {\r\n\t\t$query = \"UPDATE ech_config SET value = (value + 1) WHERE name = 'num_games' LIMIT 1\";\r\n\t\t$result = $this->mysql->query($query) or die('Database Error');\r\n\t\t\r\n\t\treturn $result;\r\n\t}\r\n\t\r\n\tfunction getServers($cur_game) {\r\n\t\t$query = \"SELECT id, name, ip, pb_active, rcon_pass, rcon_ip, rcon_port FROM ech_servers WHERE game = ?\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error');\r\n\t\t$stmt->bind_param('i', $cur_game);\r\n\t\t$stmt->execute();\r\n\t\t$stmt->bind_result($id, $name, $ip, $pb_active, $rcon_pass, $rcon_ip, $rcon_port); // bind results into vars\r\n\r\n\t\twhile($stmt->fetch()) : // get results and store in an array\r\n\t\t\t$servers[] = array(\r\n\t\t\t\t'id' => $id,\r\n\t\t\t\t'name' => $name,\r\n\t\t\t\t'ip' => $ip,\r\n\t\t\t\t'pb_active' => $pb_active,\r\n\t\t\t\t'rcon_pass' => $rcon_pass,\r\n\t\t\t\t'rcon_ip' => $rcon_ip,\r\n\t\t\t\t'rcon_port' => $rcon_port\r\n\t\t\t);\r\n\t\tendwhile;\r\n\t\t\r\n\t\t$stmt->close();\r\n\t\treturn $servers;\r\n\t}\r\n\t\r\n\tfunction getServer($id) {\r\n\t\t$query = \"SELECT game, name, ip, pb_active, rcon_pass, rcon_ip, rcon_port FROM ech_servers WHERE id = ?\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error');\r\n\t\t$stmt->bind_param('i', $id);\r\n\t\t$stmt->execute();\r\n\t\t$stmt->bind_result($game, $name, $ip, $pb_active, $rcon_pass, $rcon_ip, $rcon_port); // bind results into vars\r\n\r\n\t\twhile($stmt->fetch()) : // get results and store in an array\r\n\t\t\t$server = array(\r\n\t\t\t\t'game' => $game,\r\n\t\t\t\t'name' => $name,\r\n\t\t\t\t'ip' => $ip,\r\n\t\t\t\t'pb_active' => $pb_active,\r\n\t\t\t\t'rcon_pass' => $rcon_pass,\r\n\t\t\t\t'rcon_ip' => $rcon_ip,\r\n\t\t\t\t'rcon_port' => $rcon_port\r\n\t\t\t);\r\n\t\tendwhile;\r\n\t\t\r\n\t\t$stmt->close();\r\n\t\treturn $server;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Gets a list of all the servers from all the games for the servers table\r\n\t *\r\n\t * @param string $orderby - what var to order by\r\n\t * @param string $order - which way to order (ASC/DESC)\r\n\t * @return bool\r\n\t */\r\n\tfunction getServerList($orderby, $order) {\r\n\t\t\t\r\n\t\t$query = \"SELECT s.id, s.name, s.ip, s.game, s.pb_active, g.name as g_name FROM ech_servers s LEFT JOIN ech_games g ON s.game = g.id ORDER BY \".$orderby.\" \".$order;\r\n\t\t$result = $this->mysql->query($query);\r\n\t\t$num_rows = $result->num_rows;\r\n\t\t\r\n\t\tif($num_rows > 0) :\r\n\t\t\twhile($row = $result->fetch_object()) : // get results\t\t\r\n\t\t\t\t$servers[] = array(\r\n\t\t\t\t\t'id' => $row->id,\r\n\t\t\t\t\t'game' => $row->game,\r\n\t\t\t\t\t'name' => $row->name,\r\n\t\t\t\t\t'ip' => $row->ip,\r\n\t\t\t\t\t'pb_active' => $row->pb_active,\r\n\t\t\t\t\t'game_name' => $row->g_name\r\n\t\t\t\t);\r\n\t\t\tendwhile;\r\n\t\t\t\r\n\t\t\treturn $servers; // return the information\r\n\t\t\t\r\n\t\telse :\r\n\t\t\treturn false;\r\n\t\t\r\n\t\tendif;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Update server settings\r\n\t *\r\n\t * @return bool\r\n\t */\r\n function setServerSettings($server_id, $name, $ip, $pb, $rcon_ip, $rcon_port, $rcon_pw, $change_rcon_pw) {\r\n\t\t\r\n\t\t$query = \"UPDATE ech_servers SET name = ?, ip = ?, pb_active = ?, rcon_ip = ?, rcon_port = ?\";\r\n\t\t\r\n\t\tif($change_rcon_pw) // if the DB password is to be chnaged\r\n\t\t\t$query .= \", rcon_pass = ?\";\r\n\r\n\t\t$query .= \" WHERE id = ? LIMIT 1\";\r\n\t\t\t\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error');\r\n\t\tif($change_rcon_pw) // if change RCON PW append\r\n\t\t\t$stmt->bind_param('ssisisi', $name, $ip, $pb, $rcon_ip, $rcon_port, $rcon_pw, $server_id);\r\n\t\telse // else info not needed in bind_param\r\n\t\t\t$stmt->bind_param('ssisii', $name, $ip, $pb, $rcon_ip, $rcon_port, $server_id);\r\n\t\t$stmt->execute();\r\n\t\t\r\n\t\tif($stmt->affected_rows > 0)\r\n\t\t\treturn true;\r\n\t\telse\r\n\t\t\treturn false;\t\r\n }\r\n\t\r\n\t/**\r\n\t * Add a server\r\n\t *\r\n\t * @return bool\r\n\t */\r\n function addServer($game_id, $name, $ip, $pb, $rcon_ip, $rcon_port, $rcon_pw) {\r\n\t\t\r\n\t\t// id, game, name, ip, pb_active, rcon_pass, rcon_ip, rcon_port\r\n\t\t$query = \"INSERT INTO ech_servers VALUES(NULL, ?, ?, ?, ?, ?, ?, ?)\";\r\n\t\t\t\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error');\r\n\t\t$stmt->bind_param('ississi', $game_id, $name, $ip, $pb, $rcon_pw, $rcon_ip, $rcon_port);\r\n\t\t$stmt->execute();\r\n\t\t\r\n\t\t$affect = $stmt->affected_rows;\r\n\t\t$stmt->close();\r\n\t\t\r\n\t\tif($affect > 0)\r\n\t\t\treturn true;\r\n\t\telse\r\n\t\t\treturn false;\t\r\n }\r\n\t\r\n\t/**\r\n\t * After adding a server we need to update the games table to add 1 to num_srvs\r\n\t *\r\n\t * @param int $game_id - the id of the game that is to be updated\r\n\t */\r\n\tfunction addServerUpdateGames($game_id) {\r\n\t\t$query = \"UPDATE ech_games SET num_srvs = (num_srvs + 1) WHERE id = ? LIMIT 1\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error:'. $this->mysql->error);;\r\n\t\t$stmt->bind_param('i', $game_id);\r\n\t\t$stmt->execute();\r\n\t\t\r\n\t\t$affect = $stmt->affected_rows;\r\n\t\t$stmt->close();\r\n\t\t\r\n\t\tif($affect > 0)\r\n\t\t\treturn true;\r\n\t\telse\r\n\t\t\treturn false;\r\n\t}\r\n\t\r\n\tfunction delServerUpdateGames($game_id) {\r\n\t\t$query = \"UPDATE ech_games SET num_srvs = (num_srvs - 1) WHERE id = ? LIMIT 1\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error:'. $this->mysql->error);;\r\n\t\t$stmt->bind_param('i', $game_id);\r\n\t\t$stmt->execute();\r\n\t\t\r\n\t\t$affect = $stmt->affected_rows;\r\n\t\t$stmt->close();\r\n\t\t\r\n\t\tif($affect > 0)\r\n\t\t\treturn true;\r\n\t\telse\r\n\t\t\treturn false;\r\n\t}\r\n\t\r\n\tfunction getGamesList() {\r\n\t\t$query = \"SELECT id, name, name_short FROM ech_games ORDER BY id ASC\";\r\n\t\t$results = $this->mysql->query($query) or die('Database error');\r\n\t\t\r\n\t\twhile($row = $results->fetch_object()) :\t\r\n\t\t\t$games[] = array(\r\n\t\t\t\t'id' => $row->id,\r\n\t\t\t\t'name' => $row->name,\r\n\t\t\t\t'name_short' => $row->name_short\r\n\t\t\t);\r\n\t\tendwhile;\r\n\t\treturn $games;\r\n\t}\r\n\t\r\n\t/**\r\n\t * This function gets the salt value from the users table by using a clients username\r\n\t *\r\n\t * @param string $username - username of the user you want to find the salt of\r\n\t * @return string/false\r\n\t */\r\n\tfunction getUserSalt($username) {\r\n\t\t\r\n\t\t$query = \"SELECT salt FROM ech_users WHERE username = ?\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error');\r\n\t\t$stmt->bind_param('s', $username);\r\n\t\t$stmt->execute(); // run query\r\n\t\t\r\n\t\t$stmt->store_result(); // store results\r\n\t\t$stmt->bind_result($salt); // store result\r\n\t\t$stmt->fetch(); // get the one result result\r\n\r\n\t\tif($stmt->num_rows == 1)\r\n\t\t\treturn $salt;\r\n\t\telse\r\n\t\t\treturn false;\r\n\t\t\r\n\t\t$stmt->free_result();\r\n\t\t$stmt->close();\r\n\t}\r\n\t\r\n\t/**\r\n\t * This function returns an array of permissions for users\r\n\t *\r\n\t * @return array\r\n\t */\r\n\tfunction getPermissions($get_desc = true) {\r\n\t\r\n\t\tif($get_desc)\r\n\t\t\t$query = \"SELECT * FROM ech_permissions\";\r\n\t\telse\r\n\t\t\t$query = \"SELECT id, name FROM ech_permissions\";\r\n\t\t\t\r\n\t\t$query .= \" ORDER BY id ASC\";\r\n\t\t\t\r\n\t\t$results = $this->mysql->query($query);\r\n\t\t\r\n\t\twhile($row = $results->fetch_object()) : // get results\r\n\t\t\r\n\t\t\tif($get_desc) : // if get desc then return desc in results\r\n\t\t\t\t$perms[] = array(\r\n\t\t\t\t\t'id' => $row->id,\r\n\t\t\t\t\t'name' => $row->name,\r\n\t\t\t\t\t'desc' => $row->description\r\n\t\t\t\t);\r\n\t\t\t\t\r\n\t\t\telse : // else dont return the desc of the perm\r\n\t\t\t\t$perms[] = array(\r\n\t\t\t\t\t'id' => $row->id,\r\n\t\t\t\t\t'name' => $row->name,\r\n\t\t\t\t);\r\n\t\t\tendif;\r\n\t\t\t\r\n\t\tendwhile;\r\n\t\treturn $perms;\r\n\t}\r\n \r\n\t/**\r\n\t * This function validates user login info and if correct to return some user info\r\n\t *\r\n\t * @param string $username - username of user for login validation\r\n\t * @param string $pw - password of user for login validation\r\n\t * @return array/false\r\n\t */\r\n\tfunction login($username, $pw) {\r\n\r\n\t\t$query = \"SELECT u.id, u.ip, u.last_seen, u.display, u.email, u.ech_group, g.premissions, u.timezone FROM ech_users u LEFT JOIN ech_groups g ON u.ech_group = g.id WHERE u.username = ? AND u.password = ? LIMIT 1\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error');\r\n\t\t$stmt->bind_param('ss', $username, $pw);\r\n\t\t$stmt->execute(); // run query\r\n\t\t\r\n\t\t$stmt->store_result(); // store results\t\r\n\t\t$stmt->bind_result($id, $ip, $last_seen, $name, $email, $group, $perms, $timezone); // store results\r\n\t\t$stmt->fetch(); // get results\r\n\r\n\t\tif($stmt->num_rows == 1):\r\n\t\t\t$results = array($id, $ip, $last_seen, $name, $email, $group, $perms, $timezone);\r\n\t\t\treturn $results; // yes log them in\r\n\t\telse :\r\n\t\t\treturn false;\r\n\t\tendif;\r\n\t\t\r\n\t\t$stmt->free_result();\r\n\t\t$stmt->close();\r\n\t}\r\n\t\r\n\t/**\r\n\t * This function updates user records with new IP address and time last seen\r\n\t *\r\n\t * @param string $ip - current IP address to upodate DB records\r\n\t * @param int $id - id of the current user \r\n\t */\r\n\tfunction newUserInfo($ip, $id) { // updates user records with new IP, time of login and sets active to 1 if needed\r\n\t\t\r\n\t\t$time = time();\r\n\t\t$query = \"UPDATE ech_users SET ip = ?, last_seen = ? WHERE id = ?\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error');\r\n\t\t$stmt->bind_param('sii', $ip, $time, $id);\r\n\t\t$stmt->execute(); // run query\r\n\t\t$stmt->close(); // close connection\r\n\t}\r\n\t\r\n\t/**\r\n\t * This function checks to see if the current user IP is on the blacklist\r\n\t *\r\n\t * @param string $ip - IP addrss of current user to check of current BL\r\n\t * @return bool\r\n\t */\r\n\tfunction checkBlacklist($ip) {\r\n\r\n\t\t$query = \"SELECT id FROM ech_blacklist WHERE ip = ? AND active = 1 LIMIT 1\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database error');\r\n\t\t$stmt->bind_param('s', $ip);\r\n\t\t$stmt->execute();\r\n\r\n\t\t$stmt->store_result();\r\n\t\t\r\n\t\tif($stmt->num_rows > 0)\r\n\t\t\treturn true;\r\n\t\t\r\n\t\t$stmt->free_result();\r\n\t\t$stmt->close();\r\n\t\t\r\n\t\treturn false;\r\n\t}\r\n\r\n\t/**\r\n\t * Blacklist a user's IP address\r\n\t *\r\n\t * @param string $ip - IP address you wish to ban\r\n\t * @param string $comment [optional] - Comment about reason for ban\r\n\t * @param int $admin - id of the admin who added the ban (0 if auto added)\r\n\t */\r\n\tfunction blacklist($ip, $comment = 'Auto Added Ban', $admin = 0) { // add an Ip to the blacklist\r\n\t\t$comment = cleanvar($comment);\r\n\t\t$time = time();\r\n\t\t// id, ip, active, reason, time_add, admin_id\r\n\t\t$query = \"INSERT INTO ech_blacklist VALUES(NULL, ?, 1, ?, ?, ?)\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database error');\r\n\t\t$stmt->bind_param('ssii', $ip, $comment, $time, $admin);\r\n\t\t$stmt->execute(); // run query\r\n\t\t\r\n\t\t$affect = $stmt->affected_rows;\r\n\t\t$stmt->close();\r\n\t\t\r\n\t\tif($affect > 0)\r\n\t\t\treturn true;\r\n\t\telse\r\n\t\t\treturn false;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Get an array of data about the Blacklist for a table\r\n\t *\r\n\t * @return array\r\n\t */\r\n\tfunction getBL() { // return the rows of info for the BL table\r\n\r\n\t\t$query = \"SELECT bl.id, bl.ip, bl.active, bl.reason, bl.time_add, u.display \r\n\t\t\t\t\tFROM ech_blacklist bl LEFT JOIN ech_users u ON bl.admin_id = u.id \r\n\t\t\t\t\tORDER BY active ASC\";\t\r\n\t\t\r\n\t\t$results = $this->query($query);\r\n\t\t\r\n\t\treturn $results;\r\n\t}\r\n\t\r\n\t/**\r\n\t * De/Re-actives a Blacklist Ban\r\n\t *\r\n\t * @param int $id - id of the ban\r\n\t * @param bool $active - weather to activate or deactivate\r\n\t */\r\n\tfunction BLactive($id, $active = true) {\r\n\r\n\t\tif($active == false)\r\n\t\t\t$active = 0;\r\n\t\telse\r\n\t\t\t$active = 1;\r\n\r\n\t\t$query = \"UPDATE ech_blacklist SET active = ? WHERE id = ? LIMIT 1\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error');\r\n\t\t$stmt->bind_param('ii', $active, $id);\r\n\t\t$stmt->execute(); // run query\r\n\t\t$stmt->close(); // close connection\r\n\r\n\t} // end BLactive\r\n\r\n\t/**\r\n\t * Gets an array of data for the users table\r\n\t *\r\n\t * @return array\r\n\t */\r\n\tfunction getUsers() { // gets an array of all the users basic info\r\n\r\n\t\t$query = \"SELECT u.id, u.display, u.email, u.ip, u.first_seen, u.last_seen, g.namep FROM ech_users u LEFT JOIN ech_groups g ON u.ech_group = g.id ORDER BY id ASC\";\r\n\t\t\r\n\t\t$users = $this->query($query);\r\n\t\t\r\n\t\treturn $users;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Gets a list of all currently valid registration keys\r\n\t *\r\n\t * @param $key_expire - the setting for how many days a key is valid for\r\n\t * @return array\r\n\t */\r\n\tfunction getKeys($key_expire) {\r\n\t\t$limit_seconds = $key_expire*24*60*60; // user_key_limit is sent in days so we must convert it\r\n\t\t$time = time();\r\n\t\t$expires = $time+$limit_seconds;\r\n\t\t$query = \"SELECT k.reg_key, k.email, k.comment, k.time_add, k.admin_id, u.display \r\n\t\t\t\t FROM ech_user_keys k LEFT JOIN ech_users u ON k.admin_id = u.id\r\n\t\t\t\t WHERE k.active = 1 AND comment != 'PW' ORDER BY time_add ASC\";\r\n\r\n\t\t$reg_keys = $this->query($query);\r\n\t\t\r\n\t\treturn $reg_keys;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Check a username is not already in use\r\n\t *\r\n\t * @param string $username - username to check\r\n\t * @return bool\r\n\t */\r\n\tfunction checkUsername($username) {\r\n\r\n\t\t$query = \"SELECT username FROM ech_users WHERE username = ? LIMIT 1\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error');\r\n\t\t$stmt->bind_param('s', $username);\r\n\t\t$stmt->execute(); // run query\r\n\t\t$stmt->store_result(); // store query\r\n\t\t\r\n\t\tif($stmt->num_rows >= 1) // if there is a row\r\n\t\t\treturn false;\r\n\t\telse\r\n\t\t\treturn true;\r\n\t\t\r\n\t\t$stmt->free_result();\r\n\t\t$stmt->close();\r\n\t}\r\n\t\r\n\t/**\r\n\t * Find the users pasword salt by using their id\r\n\t *\r\n\t * @param int $user_id\r\n\t * @return string/false\r\n\t */\r\n\tfunction getUserSaltById($user_id) {\r\n\t\t\r\n\t\t$query = \"SELECT salt FROM ech_users WHERE id = ? LIMIT 1\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error');\r\n\t\t$stmt->bind_param('s', $user_id);\r\n\t\t$stmt->execute(); // run query\r\n\t\t\r\n\t\t$stmt->store_result(); // store results // needed for num_rows\r\n\t\t$stmt->bind_result($salt); // store result\r\n\t\t$stmt->fetch(); // get the one result result\r\n\r\n\t\tif($stmt->num_rows == 1)\r\n\t\t\treturn $salt;\r\n\t\telse\r\n\t\t\treturn false;\r\n\t\t\r\n\t\t$stmt->free_result();\r\n\t\t$stmt->close();\r\n\t}\r\n\t\r\n\t/**\r\n\t * Checks that a users password is correct (needed to verify user idenity with edit me page)\r\n\t *\r\n\t * @param int $user_id - id of the user\r\n\t * @param string $hash_pw - hashed version of the pw (including the salt in the hash)\r\n\t * @return bool\r\n\t */\r\n\tfunction validateUserRequest($user_id, $hash_pw) { // see if the supplied password matches that of the supplied user id\r\n\t\t$query = \"SELECT id FROM ech_users WHERE id = ? AND password = ? LIMIT 1\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error');\r\n\t\t$stmt->bind_param('is', $user_id, $hash_pw);\r\n\t\t$stmt->execute();\r\n\t\t$stmt->store_result(); // needed to allow num_rows to buffer\r\n\t\t\r\n\t\tif($stmt->num_rows == 1)\r\n\t\t\treturn true; // the person exists\r\n\t\telse\r\n\t\t\treturn false; // person does not exist\r\n\t\t\t\r\n\t\t$stmt->free_result();\r\n\t\t$stmt->close();\r\n\t}\r\n\t\r\n\t/**\r\n\t * Allows a user to edit their display name and email\r\n\t *\r\n\t * @param string $name - new display name\r\n\t * @param string $email - new email address\r\n\t * @param int $user_id - id of the user to update\r\n\t * @return bool\r\n\t */\r\n\tfunction editMe($name, $email, $timezone, $user_id) {\r\n\t\t$query = \"UPDATE ech_users SET display = ?, email = ?, timezone = ? WHERE id = ? LIMIT 1\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error');\r\n\t\t$stmt->bind_param('sssi', $name, $email, $timezone, $user_id);\r\n\t\t$stmt->execute();\r\n\t\t\r\n\t\tif($stmt->affected_rows != 1) \r\n\t\t\treturn false; // if nothing happened\r\n\t\telse\r\n\t\t\treturn true; // retrun true (it happened)\r\n\t\t\r\n\t\t$stmt->close(); // close connection\r\n\t}\r\n\t\r\n\t/**\r\n\t * Allows user to edit their password\r\n\t *\r\n\t * @param string $password_new - new password in hash form\r\n\t * @param string $salt_new - the new salt for that user\r\n\t * @param int $user_id - id of the user to update\r\n\t * @return bool\r\n\t */\r\n\tfunction editMePW($password_new, $salt_new, $user_id) { // update a user with a new pw and salt\r\n\t\t$query = \"UPDATE ech_users SET password = ?, salt = ? WHERE id = ? LIMIT 1\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error');\r\n\t\t$stmt->bind_param('ssi', $password_new, $salt_new, $user_id);\r\n\t\t$stmt->execute();\r\n\t\t\r\n\t\tif($stmt->affected_rows != 1)\r\n\t\t\treturn false;\r\n\t\telse\r\n\t\t\treturn true;\r\n\r\n\t\t$stmt->close();\r\n\t}\r\n\t\r\n\t/**\r\n\t * Add a key key to the user_keys table to allow registration\r\n\t *\r\n\t * @param string $user_key - unique key (40 char hash)\r\n\t * @param string $email - email address of the user the key is for\r\n\t * @param string $comment - comment as to why the user was added\r\n\t * @param int $perms - value of perms this user is allowed access to\r\n\t * @param int $admin_id - id of the admin who added this key\r\n\t * @return bool\r\n\t */\r\n\tfunction addEchKey($user_key, $email, $comment, $group, $admin_id) {\r\n\t\t$time = time();\r\n\t\t// key, ech_group, admin_id, comment, time_add, email, active\r\n\t\t$query = \"INSERT INTO ech_user_keys VALUES(?, ?, ?, ?, ?, ?, 1)\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error');\r\n\t\t$stmt->bind_param('siisis', $user_key, $group, $admin_id, $comment, $time, $email);\r\n\t\t$stmt->execute();\r\n\t\t\r\n\t\tif($stmt->affected_rows)\r\n\t\t\treturn true;\r\n\t\telse\r\n\t\t\treturn false;\r\n\t\t\r\n\t\t$stmt->close();\r\n\t}\r\n\t\r\n\t/**\r\n\t * Delete a registration key\r\n\t *\r\n\t * @param string $key - unique key to delete\r\n\t * @return bool\r\n\t */\r\n\tfunction delKey($key) {\r\n\t\r\n\t\t$query = \"DELETE FROM ech_user_keys WHERE reg_key = ? LIMIT 1\";\r\n\t\t$stmt = $this->mysql->prepare($query);\r\n\t\t$stmt->bind_param('s', $key);\r\n\t\t$stmt->execute();\r\n\t\t\r\n\t\tif($stmt->affected_rows)\r\n\t\t\treturn true;\r\n\t\telse\r\n\t\t\treturn false;\r\n\t\t\t\r\n\t\t$stmt->close();\r\n\t}\r\n\t\r\n\t/**\r\n\t * Edit a registration key's comment\r\n\t *\r\n\t * @param string $key - unique key to delete\r\n\t * @param string $comment - the new comment text\r\n\t * @param int $admin_id - the admin who created the key is the only person who can edit the key\r\n\t * @return bool\r\n\t */\r\n\tfunction editKeyComment($key, $comment, $admin_id){\r\n\t\r\n\t\t$query = \"UPDATE ech_user_keys SET comment = ? WHERE reg_key = ? AND admin_id = ? LIMIT 1\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error');\r\n\t\t$stmt->bind_param('ssi', $comment, $key, $admin_id);\r\n\t\t$stmt->execute();\r\n\t\t\r\n\t\tif($stmt->affected_rows)\r\n\t\t\treturn true;\r\n\t\telse\r\n\t\t\treturn false;\r\n\t\t\t\r\n\t\t$stmt->close();\r\n\t}\r\n\t\r\n\t/**\r\n\t * Verify that the supplied user key, email are valid, that the key has not expired or already been used\r\n\t *\r\n\t * @param string $key - unique key to search for\r\n\t * @param string $email - email address connected with each key\r\n\t * @param string $key_expire - lenght in days of how long a key is active for\r\n\t * @return bool\r\n\t */\r\n\tfunction verifyRegKey($key, $email, $key_expire) {\r\n\t\t$limit_seconds = $key_expire*24*60*60; // user_key_limit is sent in days so we must convert it\r\n\t\t$time = time();\r\n\t\t$expires = $time+$limit_seconds;\r\n\t\r\n\t\t$query = \"SELECT reg_key, email FROM ech_user_keys WHERE reg_key = ? AND email = ? AND active = 1 AND time_add < ? LIMIT 1\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error');\r\n\t\t$stmt->bind_param('ssi', $key, $email, $expires);\r\n\t\t$stmt->execute();\r\n\t\t\r\n\t\t$stmt->store_result(); // store results\r\n\r\n\t\tif($stmt->num_rows == 1)\r\n\t\t\treturn true;\r\n\t\telse\r\n\t\t\treturn false;\r\n\t\t\r\n\t\t$stmt->free_result();\r\n\t\t$stmt->close();\r\n\t}\r\n\t\r\n\t/**\r\n\t * Find the perms and admin_id assoc with that unique key\r\n\t *\r\n\t * @param string $key - unique key to search with\r\n\t * @return string\r\n\t */\r\n\tfunction getGroupAndIdWithKey($key) {\r\n\t\r\n\t\t$query = \"SELECT ech_group, admin_id FROM ech_user_keys WHERE reg_key = ? LIMIT 1\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error');\r\n\t\t$stmt->bind_param('s', $key);\r\n\t\t$stmt->execute();\r\n\t\t$stmt->bind_result($group, $admin_id); // store results\t\r\n\t\t$stmt->fetch();\r\n\t\t\r\n\t\t$result = array($group, $admin_id);\r\n\t\t$stmt->free_result();\r\n\t\t$stmt->close();\r\n\t\t\r\n\t\treturn $result;\r\n\t}\r\n\t\r\n\tfunction getIdWithKey($key) {\r\n\t\r\n\t\t$query = \"SELECT admin_id FROM ech_user_keys WHERE reg_key = ? LIMIT 1\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error');\r\n\t\t$stmt->bind_param('s', $key);\r\n\t\t$stmt->execute();\r\n\t\t$stmt->store_result();\r\n\t\t\r\n\t\tif($stmt->num_rows == 1) {\r\n\t\t\t$stmt->bind_result($value); // store results\t\r\n\t\t\t$stmt->fetch();\r\n\t\t\t$stmt->free_result();\r\n\t\t\t$stmt->close();\r\n\t\t\treturn $value;\r\n\t\t} else\r\n\t\t\treturn false;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Gets an array of data for the settings form\r\n\t *\r\n\t * @param string $key - the key to deactive\r\n\t * @return bool\r\n\t */\r\n\tfunction deactiveKey($key) {\r\n\t\t$query = \"UPDATE ech_user_keys SET active = 0 WHERE reg_key = ? LIMIT 1\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error');\r\n\t\t$stmt->bind_param('s', $key);\r\n\t\t$stmt->execute();\r\n\t\t\r\n\t\t$affect = $stmt->affected_rows;\r\n\t\t\r\n\t\t$stmt->close();\r\n\t\t\r\n\t\tif($affect == 1)\r\n\t\t\treturn true;\r\n\t\telse\r\n\t\t\treturn false;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Add the user information the users table\r\n\t *\r\n\t * @param string $username - username of user\r\n\t * @param string $display - display name of user\r\n\t * @param string $email - email of user\r\n\t * @param string $password - password\r\n\t * @param string $salt - salt string for the password\r\n\t * @param string $group - group for the user\r\n\t * @param string $admin_id - id of the admin who added the user key\r\n * @param string $timezone - timezone support\r\n\t * @return bool\r\n\t */\r\n\tfunction addUser($username, $display, $email, $password, $salt, $group, $admin_id) {\r\n\t\t$time = time();\r\n\t\t// id, username, display, email, password, salt, ip, group, admin_id, first_seen, last_seen, timezone\r\n\t\t$query = \"INSERT INTO ech_users VALUES(NULL, ?, ?, ?, ?, ?, NULL, ?, ?, ?, NULL, NULL)\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error');\r\n\t\t$stmt->bind_param('sssssiii', $username, $display, $email, $password, $salt, $group, $admin_id, $time);\r\n\t\t$stmt->execute();\r\n\t\t\r\n\t\tif($stmt->affected_rows)\r\n\t\t\treturn true;\r\n\t\telse\r\n\t\t\treturn false;\r\n\t\t\r\n\t\t$stmt->close();\r\n\t}\r\n\r\n\t/**\r\n\t * Deletes a user\r\n\t *\r\n\t * @param string $id - id of user to deactive\r\n\t * @return bool\r\n\t */\r\n\tfunction delUser($user_id) {\r\n\t\t$query = \"DELETE FROM ech_users WHERE id = ? LIMIT 1\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error');\r\n\t\t$stmt->bind_param('i', $user_id);\r\n\t\t$stmt->execute();\r\n\t\t\r\n\t\t$affect = $stmt->affected_rows;\r\n\t\t\r\n\t\t$stmt->close();\r\n\t\t\r\n\t\tif($affect == 1)\r\n\t\t\treturn true;\r\n\t\telse\r\n\t\t\treturn false;\r\n\t}\r\n\t\r\n\tfunction editUser($id, $username, $display, $email, $ech_group) {\r\n\t\t$query = \"UPDATE ech_users SET username = ?, display = ?, email = ?, ech_group = ? WHERE id = ? LIMIT 1\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error');\r\n\t\t$stmt->bind_param('sssii', $username, $display, $email, $ech_group, $id);\r\n\t\t$stmt->execute();\r\n\t\t\r\n\t\tif($stmt->affected_rows == 1)\r\n\t\t\treturn true;\r\n\t\telse\r\n\t\t\treturn false;\r\n\t\t\t\r\n\t\t$stmt->close();\r\n\t}\r\n\t\r\n\t/**\r\n\t * Gets a user's details (for SA view/edit)\r\n\t *\r\n\t * @param string $id - id of user\r\n\t * @return array\r\n\t */\r\n\tfunction getUserDetails($id) {\r\n\t\t$query = \"SELECT u.username, u.display, u.email, u.ip, u.ech_group, u.admin_id, u.first_seen, u.last_seen, a.display \r\n\t\t\t\t FROM ech_users u LEFT JOIN ech_users a ON u.admin_id = a.id WHERE u.id = ? LIMIT 1\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error');\r\n\t\t$stmt->bind_param('i', $id);\r\n\t\t$stmt->execute();\r\n\t\r\n\t\t$stmt->store_result();\r\n\t\t$stmt->bind_result($username, $display, $email, $ip, $group, $admin_id, $first_seen, $last_seen, $admin_name);\r\n\t\t$stmt->fetch();\r\n\r\n\t\tif($stmt->num_rows == 1) :\r\n\t\t\t$data = array($username, $display, $email, $ip, $group, $admin_id, $first_seen, $last_seen, $admin_name);\r\n\t\t\treturn $data;\r\n\t\telse :\r\n\t\t\treturn false;\r\n\t\tendif;\r\n\t\t\r\n\t\t$stmt->free_result();\r\n\t\t$stmt->close();\r\n\t}\r\n\t\r\n\tfunction getUserDetailsEdit($id) {\r\n\t\t$query = \"SELECT username, display, email, ech_group FROM ech_users WHERE id = ? LIMIT 1\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error');\r\n\t\t$stmt->bind_param('i', $id);\r\n\t\t$stmt->execute();\r\n\t\r\n\t\t$stmt->store_result();\r\n\t\t$stmt->bind_result($username, $display, $email, $group_id);\r\n\t\t$stmt->fetch();\r\n\r\n\t\tif($stmt->num_rows == 1) :\r\n\t\t\t$data = array($username, $display, $email, $group_id);\r\n\t\t\treturn $data;\r\n\t\telse :\r\n\t\t\treturn false;\r\n\t\tendif;\r\n\t\t\r\n\t\t$stmt->free_result();\r\n\t\t$stmt->close();\r\n\t}\r\n\t\r\n\t/**\r\n\t * Verifies if a user name and email exist\r\n\t *\r\n\t * @param string $name - username of user\r\n\t * @param string $email - email address of user\r\n\t * @return int($user_id)/bool(false)\r\n\t */\r\n\tfunction verifyUser($name, $email) {\r\n\t\r\n\t\t$query = \"SELECT id FROM ech_users WHERE username = ? AND email = ? LIMIT 1\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error');\r\n\t\t$stmt->bind_param('ss', $name, $email);\r\n\t\t$stmt->execute();\r\n\t\t\r\n\t\t$stmt->store_result();\r\n\t\tif($stmt->num_rows == 1) {\r\n\t\t\t$stmt->bind_result($user_id);\r\n\t\t\t$stmt->fetch();\r\n\t\t\treturn $user_id;\r\n\t\t} else {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\t$stmt->free_result();\r\n\t\t$stmt->close();\r\n\t}\r\n\t\r\n\t/**\r\n\t * Gets an array of the echelon groups\r\n\t *\r\n\t * @return array\r\n\t */\r\n\tfunction getGroups() {\r\n\t\t$query = \"SELECT id, namep FROM ech_groups ORDER BY id ASC\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error');\r\n\t\t$stmt->execute();\r\n\t\t$stmt->bind_result($id, $display);\r\n\t\t\r\n\t\twhile($stmt->fetch()) :\r\n\t\t\t$groups[] = array(\r\n\t\t\t\t'id' => $id,\r\n\t\t\t\t'display' => $display\r\n\t\t\t);\r\n\t\tendwhile;\r\n\t\t\r\n\t\t$stmt->close();\r\n\t\treturn $groups;\t\r\n\t}\r\n\t\r\n\tfunction getGroupInfo($group_id) {\r\n\t\t$query = \"SELECT namep, premissions FROM ech_groups WHERE id = ? LIMIT 1\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('DB Error');\r\n\t\t$stmt->bind_param('i', $group_id);\r\n\t\t$stmt->execute();\r\n\t\t\r\n\t\t$stmt->bind_result($display, $perms);\r\n\t\t$stmt->fetch();\r\n\t\t$result = array($display, $perms);\r\n\t\t\r\n\t\t$stmt->close();\r\n\t\treturn $result;\r\n\t}\r\n\t\r\n\tfunction getEchLogs($id, $game_id = NULL, $type = 'client') {\r\n\t\t$query = \"SELECT log.id, log.type, log.msg, log.client_id, log.user_id, log.time_add, log.game_id, u.display \r\n\t\t\t\t FROM ech_logs log LEFT JOIN ech_users u ON log.user_id = u.id \";\r\n\t\t\r\n\t\tif($type == 'admin')\r\n\t\t\t$query .= \"WHERE user_id = ?\";\r\n\t\telse\r\n\t\t\t$query .= \"WHERE client_id = ? AND game_id = ?\";\r\n\t\t\t\r\n\t\t$query .= \" ORDER BY log.time_add DESC\";\r\n\t\t\t\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error');\r\n\t\tif($type == 'admin')\r\n\t\t\t$stmt->bind_param('i', $id);\r\n\t\telse\r\n\t\t\t$stmt->bind_param('ii', $id, $game_id);\r\n\t\t$stmt->execute();\r\n\t\t\r\n\t\t$stmt->store_result();\r\n\t\t$stmt->bind_result($id, $type, $msg, $client_id, $user_id, $time_add, $game_id, $user_name);\r\n\t\t\r\n\t\twhile($stmt->fetch()) :\r\n\t\t\t$ech_logs[] = array(\r\n\t\t\t\t'id' => $id,\r\n\t\t\t\t'type' => $type,\r\n\t\t\t\t'msg' => $msg,\r\n\t\t\t\t'client_id' => $client_id,\r\n\t\t\t\t'user_id' => $user_id,\r\n\t\t\t\t'user_name' => $user_name,\r\n\t\t\t\t'game_id' => $game_id,\r\n\t\t\t\t'time_add' => $time_add\r\n\t\t\t); \t\r\n\t\tendwhile;\r\n\t\t\r\n\t\t$stmt->close();\r\n\t\treturn $ech_logs;\r\n\t}\r\n\t\r\n\tfunction addEchLog($type, $comment, $cid, $user_id, $game_id) {\r\n\t\t// id, type, msg, client_id, user_id, time_add, game_id\r\n\t\t$query = \"INSERT INTO ech_logs VALUES(NULL, ?, ?, ?, ?, UNIX_TIMESTAMP(), ?)\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('Database Error');\r\n\t\t$stmt->bind_param('ssiii', $type, $comment, $cid, $user_id, $game_id);\r\n\t\t$stmt->execute();\r\n\t\t\r\n\t\t$affect = $stmt->affected_rows;\r\n\t\t\r\n\t\t$stmt->close();\r\n\t\t\r\n\t\tif($affect == 1)\r\n\t\t\treturn true;\r\n\t\telse\r\n\t\t\treturn false;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Gets an array of the external links from the db\r\n\t */\r\n\tfunction getLinks() {\r\n\t\t$query = \"SELECT * FROM ech_links\";\r\n\t\t\r\n\t\t$links = $this->query($query);\r\n\t\t\r\n\t\treturn $links;\r\n\t}\r\n\t\r\n\tfunction setGroupPerms($group_id, $perms) {\r\n\t\t$query = \"UPDATE ech_groups SET premissions = ? WHERE id = ? LIMIT 1\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('DB Error');\r\n\t\t$stmt->bind_param('si', $perms, $group_id);\r\n\t\t$stmt->execute();\r\n\t\t\r\n\t\t$affect = $stmt->affected_rows;\r\n\t\t\r\n\t\t$stmt->close();\r\n\t\t\r\n\t\tif($affect == 1)\r\n\t\t\treturn true;\r\n\t\telse\r\n\t\t\treturn false;\r\n\t}\r\n\t\r\n\tfunction addGroup($name, $slug, $perms) {\r\n\t\t$query = \"INSERT INTO ech_groups VALUES(NULL, ?, ?, ?)\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('DB Error');\r\n\t\t$stmt->bind_param('sss', $name, $slug, $perms);\r\n\t\t$stmt->execute();\r\n\t\t\r\n\t\t$affect = $stmt->affected_rows;\r\n\t\t$stmt->close();\r\n\t\t\r\n\t\tif($affect == 1)\r\n\t\t\treturn true;\r\n\t\telse\t\r\n\t\t\treturn false;\r\n\t}\r\n\t\r\n\tfunction delServer($id) {\r\n\t\t$query = \"DELETE FROM ech_servers WHERE id = ? LIMIT 1\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('DB Error');\r\n\t\t$stmt->bind_param('i', $id);\r\n\t\t$stmt->execute();\r\n\t\t\r\n\t\t$affect = $stmt->affected_rows;\r\n\t\t$stmt->close();\r\n\t\t\r\n\t\tif($affect == 1)\r\n\t\t\treturn true;\r\n\t\telse\r\n\t\t\treturn false;\r\n\t}\r\n\t\r\n\tfunction gamesBanList() {\r\n\t\t$query = \"SELECT id, name, db_host, db_user, db_pw, db_name FROM ech_games\";\r\n\t\r\n\t\t$data = $this->query($query);\r\n\t\t\r\n\t\treturn $data;\r\n\t}\r\n\r\n} // end class\r\n", "echelon/classes/members-class.php": "id = $user_id;\r\n\t$this->name = $name;\r\n\t$this->email = $email;\r\n}\r\n\r\n/**\r\n * Sets the class name var\r\n */\r\nfunction setName($name) {\r\n\t$this->name = $name;\r\n\t$_SESSION['name'] = $this->name;\r\n}\r\n\r\n/**\r\n * Sets the class email var\r\n */\r\nfunction setEmail($email) {\r\n\t$this->email = $email;\r\n\t$_SESSION['email'] = $this->email;\r\n}\r\n\r\n/**\r\n * Checks if a user is logged in or not\r\n *\r\n * @return bool\r\n */\r\nfunction loggedIn() { // are they logged in\r\n\tif($_SESSION['auth']) // if authorised allow access\r\n\t\treturn true;\r\n\telse\r\n\t\treturn false; // if not authorised\r\n}\r\n\r\n/**\r\n * Checks if a user has the rights to view this page, is not locked/banned or not logged in\r\n *\r\n * @param string $name - permission name\r\n */\r\nfunction auth($name) {\r\n\tlocked(); // stop blocked people from acessing\t\r\n\tif(!$this->loggedIn()) { // if not authorised/logged in\r\n\t\t//set_error('Please login to Echelon');\r\n\t\tsendLogin();\r\n\t\texit;\r\n\t}\r\n\tif(!$this->reqLevel($name)) { // if users level is less than needed access, deny entry, and cause error\r\n\t\tset_error('You do not have the correct privilages to view that page');\r\n\t\tsendHome();\r\n\t\texit;\r\n\t}\r\n}\r\n\r\nfunction reqLevel($name) {\r\n\t$perm_required = $_SESSION['perms'][$name];\r\n\tif(!$perm_required) // if users level is less than needed access return false\r\n\t\treturn false;\r\n\telse\r\n\t\treturn true;\r\n}\r\n\r\n/**\r\n * Takes password and generates salt and hash. Then updates their password in the DB\r\n *\r\n * @param string $password - the new password the user\r\n * @param int $user_id - the id of the user that is being edited\r\n * @param int $min_pw_len - min len of password\r\n * @return bool(true)/string(error)\r\n */\r\nfunction genAndSetNewPW($password, $user_id, $min_pw_len) {\r\n\r\n\t// get the DB instance pointer\r\n\t$dbl = DBL::getInstance();\r\n\t\r\n\t// check that the supplied password meets the required password policy for strong passwords\r\n\tif(!$this->pwStrength($password, $min_pw_len)) { // false: not strong enough\r\n\t\treturn 'The password you supplied is not strong enough, a password must be longer than '. $min_pw_len .' character and should follow this policy.';\r\n\t\texit;\r\n\t}\r\n\t\r\n\t// generate a new salt for the user\r\n\t$salt_new = genSalt();\r\n\t\r\n\t// find the hash of the supplied password and the new salt\r\n\t$password_hash = genPW($password, $salt_new);\r\n\t\r\n\t// update the user with new password and new salt\r\n\t$results_pw = $dbl->editMePW($password_hash, $salt_new, $user_id);\r\n\tif($results_pw == false) {\r\n\t\treturn 'There was an error changing your password';\r\n\t} else\r\n\t\treturn true;\r\n}\r\n\r\n/**\r\n * Echo out the display name in a link, if the display name is not set echo guest.\r\n */\r\nfunction displayName() {\r\n\r\n\tif($this->name == '')\r\n\t\techo 'Guest';\r\n\telse\r\n\t\t#echo ''. $this->name .'';\r\n echo $this->name;\r\n\t\t\r\n\treturn;\r\n}\r\n\r\n/**\r\n * Echo out the time the user was last seen, if there is no time echo out a welcome\r\n *\r\n * @param string $time - time format (default is availble)\r\n */\r\nfunction lastSeen($time_format = 'd M y') {\r\n\r\n\tif($_SESSION['last_seen'] != '')\r\n\t\techo date($time_format, $_SESSION['last_seen']);\r\n\telse\r\n\t\treturn NULL;\r\n}\r\n\r\n\r\n/**\r\n * Using a user's password this func sees if the user inputed the right password for action verification\r\n *\r\n * @param string $password\r\n */\r\nfunction reAuthUser($password, $dbl) {\r\n\r\n\t// Check to see if this person is real\r\n\t$salt = $dbl->getUserSaltById($this->id);\r\n\r\n\tif($salt == false) // only returns false if no salt found, ie. user does not exist\r\n\t\tsendBack('There is a problem, you do not seem to exist!');\r\n\r\n\t$hash_pw = genPW($password, $salt); // hash the inputted pw with the returned salt\r\n\r\n\t// Check to see that the supplied password is correct\r\n\t$validate = $dbl->validateUserRequest($this->id, $hash_pw);\r\n\tif(!$validate) {\r\n\t\thack(1); // add one to hack counter to stop brute force\r\n\t\tsendBack('You have supplied an incorrect current password');\r\n\t}\r\n\t\r\n}\r\n\r\n/**\r\n * Checks if the password is strong enough - uses mutliple checks\r\n *\r\n * @param string $password - the password you wish to check\r\n * @param int $min_pw_len - minimun lenght a password can be\r\n * @return bool (false: not strong enough/ true strong enough)\r\n */\r\nfunction pwStrength($password, $min_pw_len = 8) {\r\n\r\n\t$length = strlen($password); // get the length of the password \r\n\r\n\t$power = 0; // start at 0\r\n\r\n\t// if password is shorter than min required lenght return false\r\n\tif($length < $min_pw_len)\r\n\t\treturn false;\r\n\r\n // check if password is not all lower case \r\n if(strtolower($password) != $password)\r\n $power++;\r\n \r\n // check if password is not all upper case \r\n if(strtoupper($password) == $password)\r\n $power++;\r\n\r\n // check string length is 8-16 chars \r\n if($length >= 8 && $length <= 16)\r\n $power++;\r\n\r\n // check if lenth is 17 - 25 chars \r\n if($length >= 17 && $length <=25)\r\n $power += 2;\r\n\r\n // check if length greater than 25 chars \r\n if($length > 25)\r\n $power += 3;\r\n \r\n // get the numbers in the password \r\n preg_match_all('/[0-9]/', $password, $numbers);\r\n $power += count($numbers[0]);\r\n\r\n // check for special chars \r\n preg_match_all('/[|!@#$%&*\\/=?,;.:\\-_+~^\\\\\\]/', $password, $specialchars);\r\n $spec = sizeof($specialchars[0]);\r\n\tif($spec < 2)\r\n\t\t$power--;\r\n\telseif($spec >= 2)\r\n\t\t$power++;\r\n\telseif(($spec > 4) && ($spec <= 5))\r\n\t\t$power += 2;\r\n\telseif(($spec >= 5) && ($lenght/5 >= 2)) // the second part here is a check to that half the password isn't special characters\r\n\t\t$power += 3;\r\n\telse\r\n\t\t$power;\r\n\t\r\n\r\n // get the number of unique chars \r\n $chars = str_split($password);\r\n $num_unique_chars = sizeof( array_unique($chars) );\r\n $power += floor(($num_unique_chars / 2));\r\n\t\r\n\tif($power > 10)\r\n\t\t$power = 10;\r\n\t\r\n\t// if the password is strong enough return true, else return false\r\n\tif($power >= 5)\r\n\t\treturn true;\r\n\telse\r\n\t\treturn false;\r\n\r\n}\r\n\r\n\r\n#############################\r\n} // end class", "echelon/classes/mysql-class.php": "host = $host;\r\n\t\t$this->user = $user;\r\n\t\t$this->pass = $pass;\r\n\t\t$this->name = $name;\r\n\t\t$this->error_on = $error_on;\r\n\r\n\t\ttry { // try to connect to the DB or die with an error\r\n\t\t\t$this->connectDB();\r\n\t\t\t\t\r\n\t\t} catch (Exception $e) {\r\n\t\t\t// get exception information\r\n\t\t\t$error_msg = strip_tags($e->getMessage());\r\n\t\t\t$code = $e->getCode();\r\n\t\t\t\r\n\t\t\t// log info\r\n\t\t\techLog('mysqlconnect', $error_msg, $code);\r\n\t\t\t\r\n\t\t\t// set vars for outside class\r\n\t\t\t$this->error = true;\r\n\t\t\t$this->error_msg = $error_msg;\r\n\t\t\t\r\n\t\t} // end catch\r\n\t\t\r\n\t} // end constructor function\r\n\t\r\n\t// Do not allow the clone operation\r\n private function __clone() { }\r\n\t\r\n\t/**\r\n\t * If access to a protected or private function is called\r\n\t */\r\n\tpublic function __call($name, $arg) {\r\n\t\techLog('error', 'System tried to access function '. $name .', a private or protected function in class '. get_class($this)); // log error\r\n\t\techo \"\" . $name . \" is a private function that cannot be accessed outside the B3 MySQL class\"; // error out error\r\n }\r\n\t\r\n\t/**\r\n * __destruct : Destructor for class, closes the MySQL connection\r\n */\r\n public function __destruct() {\r\n if($this->mysql != NULL) // if it is set/created (defalt starts at NULL)\r\n @$this->mysql->close(); // close the connection\r\n\t\t//$this->instance = NULL;\r\n }\r\n\t\r\n\t/**\r\n * Makes the connection to the DB or throws error\r\n */\r\n private function connectDB() {\r\n\t\r\n\t\tif($this->mysql != NULL) // if it is set/created (defalt starts at NULL)\r\n\t\t\t@$this->mysql->close();\r\n\t\t\r\n\t\t// Create new connection\r\n $this->mysql = @new mysqli($this->host, $this->user, $this->pass, $this->name);\r\n\t\t\r\n\t\t// if there was a connection error \r\n\t\tif (mysqli_connect_errno()) : // NOTE: we are using the procedural method here because of a problem with the OOP method before PHP 5.2.9\r\n\r\n\t\t\t$code = @$this->mysql->connect_errno; // not all versions of PHP respond nicely to this\r\n\t\t\tif(empty($code)) // so if it does not then \r\n\t\t\t\t$code = 1; // set to 1\r\n\t\t\r\n\t\t\tif($this->error_on) // only if settings say show to con error, will we show it, else just say error\r\n\t\t\t\t$error_msg = 'B3 Database Connection Error: (#'. $code .') '.mysqli_connect_error();\r\n\t\t\telse\r\n\t\t\t\t$error_msg = $this->error_sec;\r\n\t\t\t\t\r\n\t\t\t$traces = NULL;\r\n\t\t\t$log_success = echLog('mysql', $error_msg, $code, $traces);\r\n\t\t\tif(!$log_success)\r\n\t\t\t\tdie('Could not log fatal error');\r\n\t\t\t\t\r\n\t\t\tthrow new Exception($error_msg, $code); // throw new mysql typed exception\r\n\t\t\t\r\n\t\tendif;\r\n }\r\n\t\r\n\t/**\r\n\t * Handy Query function\r\n\t *\r\n\t * @param string $sql - the SQL query to execute\r\n\t * @param bool $fetch - fetch the data rows or not\r\n\t * @param string $type - typpe of query this is \r\n\t */\r\n\tpublic function query($sql, $fetch = true, $type = 'select') {\r\n\r\n\t\tif($mysql = NULL || $this->error)\r\n\t\t\treturn false;\r\n\t\t\r\n\t\ttry {\r\n\t\t\r\n\t\t\tif($stmt = $this->mysql->prepare($sql))\r\n\t\t\t\t$stmt->execute();\r\n\t\t\telse\r\n\t\t\t\tthrow new MysqlException($this->mysql->error, $this->mysql->errno);\r\n\r\n\t\t} catch (MysqlException $e) {\r\n\t\t\r\n\t\t\t$this->error = true; // there is an error\r\n\t\t\tif($this->error_on) // if detailed errors work\r\n\t\t\t\t$this->error_msg = \"MySQL Query Error (#\". $this->mysql->errno .\"): \". $this->mysql->error;\r\n\t\t\telse\r\n\t\t\t\t$this->error_msg = $this->error_sec;\r\n\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\t\r\n\t\t## setup results array\r\n\t\t$results = array();\r\n\t\t$results['data'] = array();\r\n\t\t\r\n\t\t## do certain things depending on type of query\r\n\t\tswitch($type) { \r\n\t\t\tcase 'select': // if type is a select query\r\n\t\t\t\t$stmt->store_result();\r\n\t\t\t\t$results['num_rows'] = $stmt->num_rows(); // find the number of rows retrieved\r\n\t\t\tbreak;\r\n\t\t\t\r\n\t\t\tcase 'update':\r\n\t\t\tcase 'insert': // if insert or update find the number of rows affected by the query\r\n\t\t\t\t$results['affected_rows'] = $stmt->affected_rows(); \r\n\t\t\tbreak;\r\n\t\t}\r\n\t\t\r\n\t\t## fetch the results\r\n\t\tif($fetch) : // only fetch data if we need it\r\n\t\t\r\n\t\t\t$meta = $stmt->result_metadata();\r\n\r\n\t\t\twhile ($field = $meta->fetch_field()) :\r\n\t\t\t\t$parameters[] = &$row[$field->name];\r\n\t\t\tendwhile;\r\n\r\n\t\t\tcall_user_func_array(array($stmt, 'bind_result'), $parameters);\r\n\r\n\t\t\twhile ($stmt->fetch()) :\r\n\t\t\t\tforeach($row as $key => $val) {\r\n\t\t\t\t\t$x[$key] = $val;\r\n\t\t\t\t}\r\n\t\t\t\t$results['data'][] = $x;\r\n\t\t\tendwhile;\r\n\r\n\t\tendif;\r\n\t\t\r\n\t\t## return and close off connections\r\n\t\treturn $results;\r\n\t\t$results->close();\r\n\t\t$stmt->close();\r\n\t\t\r\n\t} // end query()\r\n\t\r\n\tfunction getB3Groups() {\r\n\t\t$query = \"SELECT id, name FROM groups ORDER BY id ASC\";\r\n\t\t$stmt = $this->mysql->prepare($query);\r\n\t\t$stmt->execute();\r\n\t\t$stmt->bind_result($id, $name);\r\n\t\t\r\n\t\twhile($stmt->fetch()) :\r\n\t\t\t$groups[] = array(\r\n\t\t\t\t'id' => $id,\r\n\t\t\t\t'name' => $name\r\n\t\t\t); \t\r\n\t\tendwhile;\r\n\t\r\n\t\t$stmt->close();\r\n\t\treturn $groups;\t\r\n\t}\r\n\t\r\n\tfunction getB3GroupsLevel() {\r\n\t\t$query = \"SELECT id FROM groups ORDER BY id ASC\";\r\n\t\t$stmt = $this->mysql->prepare($query);\r\n\t\t$stmt->execute();\r\n\t\t$stmt->bind_result($id);\r\n\t\t\r\n\t\t$groups = array();\r\n\t\t\r\n\t\twhile($stmt->fetch()) :\r\n\t\t\tarray_push($groups, $id);\r\n\t\tendwhile;\r\n\t\r\n\t\t$stmt->close();\r\n\t\treturn $groups;\t\r\n\t\r\n\t}\r\n\t\r\n\t/**\r\n\t * insert a penalty into the penalty table in the B3 DB\r\n\t *\r\n\t * @param string $type - type of penalty\r\n\t * @param int $cid - client_id who is getting the penalty\r\n\t * @param int $duration - duration of pen\r\n\t * @param string $reason - reason for pen\r\n\t * @param string $data - some additional data\r\n\t * @param int $time_expire - time (unix time) for when the pen will expire\r\n\t * @return bool\r\n\t */\r\n\tfunction penClient($type, $cid, $duration, $reason, $data, $time_expire) {\r\n\t\r\n\t\t// id(), type, client_id, admin_id(0), duration, inactive(0), keyword(Echelon), reason, data, time_add(time), time_edit(time), time_expire\r\n\t\t$query = \"INSERT INTO penalties (type, client_id, admin_id, duration, inactive, keyword, reason, data, time_add, time_edit, time_expire) VALUES(?, ?, 0, ?, 0, 'Echelon', ?, ?, UNIX_TIMESTAMP(), UNIX_TIMESTAMP(), ?)\";\r\n\t\t$stmt = $this->mysql->prepare($query) or die('MySQL Error');\r\n\t\t$stmt->bind_param('siissi', $type, $cid, $duration, $reason, $data, $time_expire);\r\n\t\t$stmt->execute();\r\n\t\t\r\n\t\tif($stmt->affected_rows > 0) // if something happened\r\n\t\t\treturn true;\r\n\t\telse\r\n\t\t\treturn false;\r\n\t\t\t\r\n\t\t$stmt->close();\r\n\t}\r\n\t\r\n\t/**\r\n\t * Deactive a penalty\r\n\t *\r\n\t * @param string $pen_id - id of penalty to deactive\r\n\t * @return bool\r\n\t */\r\n\tfunction makePenInactive($pen_id) {\r\n\t\t$query = \"UPDATE penalties SET inactive = 1 WHERE id = ? LIMIT 1\";\r\n\t\t$stmt = $this->mysql->prepare($query);\r\n\t\t$stmt->bind_param('i', $pen_id);\r\n\t\t$stmt->execute();\r\n\t\t\r\n\t\tif($stmt->affected_rows > 0)\r\n\t\t\treturn true;\r\n\t\telse\r\n\t\t\treturn false;\r\n\t\t\t\r\n\t\t$stmt->close();\r\n\t\r\n\t}\r\n\t\r\n\t/**\r\n\t * Get the pbid of the client from a penalty id\r\n\t *\r\n\t * @param string $pen_id - id of penalty to search with\r\n\t * @return string - pbid of the client\r\n\t */\r\n\tfunction getPBIDfromPID($pen_id) {\r\n\t\t$query = \"SELECT c.pbid FROM penalties p LEFT JOIN clients c ON p.client_id = c.id WHERE p.id = ? LIMIT 1\";\r\n\t\t$stmt = $this->mysql->prepare($query);\r\n\t\t$stmt->bind_param('i', $pen_id);\r\n\t\t$stmt->execute();\r\n\t\t\r\n\t\t$stmt->store_result();\r\n\t\t$stmt->bind_result($pbid);\r\n\t\t$stmt->fetch();\r\n\t\t$stmt->free_result();\r\n\t\t$stmt->close();\r\n\t\r\n\t\treturn $pbid;\r\n\t}\r\n \r\n /**\r\n\t * Get the guid of the client from a penalty id, similar to pbid\r\n\t *\r\n\t * @param string $pen_id - id of penalty to search with\r\n\t * @return string - guid of the client\r\n\t */\r\n function getGUIDfromPID($pen_id) {\r\n\t\t$query = \"SELECT c.guid FROM penalties p LEFT JOIN clients c ON p.client_id = c.id WHERE p.id = ? LIMIT 1\";\r\n\t\t$stmt = $this->mysql->prepare($query);\r\n\t\t$stmt->bind_param('i', $pen_id);\r\n\t\t$stmt->execute();\r\n\t\t\r\n\t\t$stmt->store_result();\r\n\t\t$stmt->bind_result($guid);\r\n\t\t$stmt->fetch();\r\n\t\t$stmt->free_result();\r\n\t\t$stmt->close();\r\n\t\r\n\t\treturn $guid;\r\n\t}\r\n\r\n#############################\r\n#############################\r\n} // end class\r\n\r\n/**\r\n * Exceptions class for the B3 DB\r\n *\r\n */\r\nclass MysqlException extends Exception {\r\n\r\n\tprivate $ex_error;\r\n\tprivate $ex_errno;\r\n\r\n\tpublic function __construct($error, $errno) {\r\n\t\t\r\n\t\t// get sent vars\r\n\t\t$this->ex_error = $error;\r\n\t\t$this->ex_errno = $errno;\r\n\t\t\r\n\t\t// get exception information from parent class\r\n\t\t$traces = parent::getTraceAsString();\r\n\t\t\r\n\t\t// find error message and code\r\n\t\t$code = $this->ex_errno;\r\n\t\t$message = $this->ex_error;\r\n\t\t\r\n\t\t// log error message\r\n\t\t$log_success = echLog('mysql', $message, $code, $traces);\r\n\t\tif(!$log_success)\r\n\t\t\tdie('Could not log fatal error');\r\n\r\n\t\t// call parent constructor\r\n\t\tparent::__construct($message, $code);\r\n\t}\r\n\r\n}", "echelon/classes/plugins-class.php": "name = $name;\r\n\t}\r\n\t\r\n\tpublic function __destruct() {\r\n\t}\r\n\t\r\n\tprotected function setTitle($title) {\r\n\t\t$this->title = $title;\r\n\t}\r\n\t\r\n\tprotected function setVersion($version) {\r\n\t\t$this->version = $version;\r\n\t}\r\n\t\r\n\tpublic static function setPluginsClass($value) {\r\n\t\tself::$plugins_class = $value;\r\n\t}\r\n\t\r\n\tprotected function getTitle() {\r\n\t\treturn $this->title;\r\n\t}\r\n\t\r\n\tprotected function getName() {\r\n\t\treturn $this->name;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Internal function: in the case of fatal error die with plugin name and error message\r\n\t */\r\n\tprotected function error($msg) {\r\n\t\tdie($this->getName().' Plugin Error: '. $msg);\r\n\t}\r\n\t\r\n\t/**\r\n\t * This function display information from plugins in the CD's bio area\r\n\t *\r\n\t * @param array $plugins_class - an array of pointers to the class of the plugins\r\n\t */\r\n\tfunction displayCDBio() {\r\n\t\tforeach(self::$plugins_class as $plugin) :\r\n\t\t\tif(method_exists($plugin, 'returnClientBio')) {\r\n $content = $plugin->returnClientBio();\r\n if (!(empty($content)))\r\n echo $content;\r\n else\r\n return NULL;\r\n\t\t\t}\r\n\t\tendforeach;\r\n\t}\r\n\t\r\n\t/**\r\n\t * This function display the tab of any plugin added forms on the clientdetails page\r\n\t *\r\n\t * @param array $plugins_class - an array of pointers to the class of the plugins\r\n\t */\r\n\tfunction displayCDFormTab() {\r\n\t\tforeach(self::$plugins_class as $plugin) :\r\n\t\t\tif(method_exists($plugin, 'returnClientFormTab')) {\r\n\t\t\t\t$content = '
          • ' .$plugin->returnClientFormTab(). '
          • ';\r\n if (!(empty($plugin->returnClientBio())))\r\n echo $content;\r\n\t\t\t}\r\n\t\tendforeach;\r\n\t}\r\n\r\n # For plugins like xlrstats\r\n\tfunction displayCDFormNavTab() {\r\n\t\tforeach(self::$plugins_class as $plugin) :\r\n\t\t\tif(method_exists($plugin, 'returnClientNavTab')) {\r\n\t\t\t\t$content = $plugin->returnClientNavTab();\r\n if (!(empty($plugin->returnClientBio())))\r\n echo '
          • '.$content.'
          • ';\r\n\t\t\t}\r\n\t\tendforeach;\r\n\t}\r\n \r\n\t# For logging plugins like chatlogger\r\n\tfunction displayCDFormNavTabLog($cid = 0) {\r\n\t\tforeach(self::$plugins_class as $plugin) :\r\n\t\t\tif(method_exists($plugin, 'returnClientNavTabLog')) {\r\n\t\t\t\t$content = $plugin->returnClientNavTabLog();\r\n #if ($plugin->returnClientLogs($cid))\r\n echo '
          • '.$content.'
          • ';\r\n\t\t\t}\r\n\t\tendforeach;\r\n\t}\r\n\t\r\n\t/**\r\n\t * This function display forms on the clientdetails page added by any plugins\r\n\t *\r\n\t * @param array $plugins_class - an array of pointers to the class of the plugins\r\n\t */\r\n\tfunction displayCDForm($cid = 0) {\r\n\t\tforeach(self::$plugins_class as $plugin) :\r\n\t\t\tif(method_exists($plugin, 'returnClientForm')) {\r\n\t\t\t\t$content = $plugin->returnClientForm($cid);\r\n\t\t\t\techo $content;\r\n\t\t\t}\r\n\t\tendforeach;\r\n\t}\r\n\t\r\n\t/**\r\n\t * For each plugin check if they want to add a link\r\n\t */\r\n\tfunction displayNav() {\r\n\t\tforeach(self::$plugins_class as $plugin) :\r\n\t\t\tif(method_exists($plugin, 'returnNav')) {\r\n\t\t\t\t$content = $plugin->returnNav();\r\n\t\t\t\techo $content;\r\n\t\t\t}\r\n\t\tendforeach;\r\n\t}\r\n\t\r\n function NavExists() {\r\n foreach(self::$plugins_class as $plugin) :\r\n\t\t\tif(method_exists($plugin, 'returnNav')) {\r\n\t\t\t\treturn True;\r\n\t\t\t}\r\n\t\tendforeach;\r\n }\r\n \r\n\t/**\r\n\t * For each plugin check if they want to append something to the end of the CD page\r\n\t */\r\n\tfunction displayCDlogs($cid) {\r\n\t\tforeach(self::$plugins_class as $plugin) :\r\n\t\t\tif(method_exists($plugin, 'returnClientLogs')) {\r\n\t\t\t\t$content = $plugin->returnClientLogs($cid);\r\n\t\t\t\techo $content;\r\n\t\t\t}\r\n\t\tendforeach;\r\n\t}\r\n\t\r\n\t/**\r\n\t * For each plugin check if they need to include a css file\r\n\t */\r\n\tfunction getCSS() {\r\n\t\tforeach(self::$plugins_class as $plugin) :\r\n\t\t\tif(method_exists($plugin, 'returnCSS')) {\r\n\t\t\t\t$content = $plugin->returnCSS();\r\n\t\t\t\techo $content;\r\n\t\t\t}\r\n\t\tendforeach;\r\n\t}\r\n\t\r\n\t/**\r\n\t * For each plugin check if they need to include a JS file\r\n\t */\r\n\tfunction getJS() {\r\n\t\tforeach(self::$plugins_class as $plugin) :\r\n\t\t\tif(method_exists($plugin, 'returnJS')) {\r\n\t\t\t\t$content = $plugin->returnJS();\r\n\t\t\t\techo $content;\r\n\t\t\t}\r\n\t\tendforeach;\r\n\t}\r\n\r\n\r\n} // end class\r\n", "echelon/clientdetails.php": "mysql->prepare($query) or die('Database Error '. $db->mysql->error);\r\n$stmt->bind_param('i', $cid);\r\n$stmt->execute();\r\n$stmt->bind_result($ip, $connections, $guid, $name, $mask_level, $greeting, $time_add, $time_edit, $group_bits, $user_group);\r\n$stmt->fetch();\r\n$stmt->close();\r\n\r\n## Require Header ##\r\n$page_title .= ' '.$name; // add the clinets name to the end of the title\r\n\r\nrequire 'inc/header.php';\r\n?>\r\n
            \r\n
            \r\n
            \r\n
            Client Information
            \r\n
            \r\n\r\n\t\r\n\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t \r\n\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\r\n\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\r\n\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\r\n\t\r\n
            Name   \r\n \r\n clientdetails.php?id=&game=')\" src=\"images/link.png\" width=\"16\" height=\"16\" alt=\"W\">\r\n @ID
            Level\r\n\t\t\t\tConnections
            GUID\r\n\t\t\t\treqLevel('view_full_guid')) { // if allowed to see the full guid\r\n\t\t\t\t\t\tif($guid_len == 32) \r\n\t\t\t\t\t\t\tguidCheckLink($guid);\r\n\t\t\t\t\t\telse \r\n\t\t\t\t\t\t\techo $guid.' ['. $guid_len .']';\r\n\t\t\t\t\r\n\t\t\t\t\t} elseif($mem->reqLevel('view_half_guid')) { // if allowed to see the last 8 chars of guid\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tif($guid_len == 32) {\r\n\t\t\t\t\t\t\t$half_guid = substr($guid, -8); // get the last 8 characters of the guid\r\n\t\t\t\t\t\t\tguidCheckLink($half_guid);\r\n\t\t\t\t\t\t} else\r\n\t\t\t\t\t\t\techo $guid.' ['. $guid_len .']';\r\n\t\t\t\t\t\r\n\t\t\t\t\t} else { // if not allowed to see any part of the guid\r\n\t\t\t\t\t\techo '(You do not have access to see the GUID)';\r\n\t\t\t\t\t}\r\n\t\t\t\t?>\r\n\t\t\t\tIP Address\r\n\t\t\t\t\treqLevel('view_ip')) :\r\n\t\t\t\t\t\tif ($ip != \"\") { ?>\r\n\t\t\t\t\t\t\t&t=ip\" title=\"Search for other users with this IP address\">\r\n\t\t\t\t\t\t\t\t  \r\n\t\t\t\t\t\t\t\" title=\"Whois IP Search\">\"W\"\r\n\t\t\t\t\t\t\t\t  \r\n\t\t\t\t\t\t\t\" title=\"Show Location of IP origin on map\">\"L\"\r\n\t\t\t\t\t\r\n\t\t\t\t
            First SeenLast Seen
            \r\n
            \r\n\r\n\r\n\r\n
            \r\n
            \r\n
            \r\n
              \r\n\t\treqLevel('ban')) { ?>
            • Ban
            • \r\n\t\treqLevel('edit_client_level')) { ?>
            • Set Level
            • \r\n\t\treqLevel('edit_mask')) { ?>
            • Mask Level
            • \r\n reqLevel('greeting')) { ?>
            • Greeting
            • \r\n reqLevel('comment')) { ?>
            • Comment
            • \r\n\t\tdisplayCDFormTab();\r\n\t\t?>\r\n
            \r\n
            \r\n
            \r\n
            \r\n
            \r\n \r\n reqLevel('ban')) :\r\n $ban_token = genFormToken('ban');\r\n\t\t?>\r\n
            \r\n\t\t
            \r\n\t\t\t
            \r\n reqLevel('permban')) :\r\n ?>\r\n
            \r\n \r\n
            \r\n \r\n
            \r\n
            \r\n \r\n \r\n
            \r\n \r\n \r\n
            \r\n
            \r\n \t\r\n \r\n
            \r\n \r\n
            \r\n
            \r\n \r\n \r\n\t\t\t\t
            \r\n \r\n
            \r\n \r\n
            \r\n
            \r\n\t\t\t\t\" />\r\n\t\t\t\t\" />\r\n\t\t\t\t\" />\r\n\t\t\t\t\" />\r\n\t\t\t\t\" />\r\n\t\t\t\t\r\n\t\t\t
            \r\n\t\t
            \r\n
            \r\n\t\tgetB3Groups();\r\n \r\n if($mem->reqLevel('edit_client_level')) :\r\n\t\t\t$level_token = genFormToken('level');\r\n\t\t?>\r\n
            \r\n
            \r\n\t\t\t
            \r\n
            \r\n\t\t\t\t\r\n
            \r\n\t\t\t\t\t\r\n
            \r\n
            \r\n\t\t\t\t\t\r\n\t\t\t\t
            \r\n\t\t\t\t\t\r\n
            \r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t
            \r\n\t\t\t\t
            \r\n\t\t\t\t\t\r\n\t\t\t\t\" />\r\n\t\t\t\t\" />\r\n\t\t\t\t\" />\r\n\t\t\t\t\r\n\t\t\t
            \r\n\t\t
            \r\n
            \r\n\t\treqLevel('edit_mask')) : \r\n\t\t\t$mask_lvl_token = genFormToken('mask');\r\n\t\t?>\r\n
            \r\n
            \r\n\t\t\t
            \r\n
            \r\n \r\n
            \r\n\t\t\t\t\t\r\n
            \r\n\t\t\t\t\" />\r\n\t\t\t\t\" />\r\n\t\t\t\t\" />\r\n\t\t\t\t\r\n\t\t\t
            \r\n\t\t
            \r\n
            \r\n\t\treqLevel('greeting')) :\r\n\t\t\t$greeting_token = genFormToken('greeting');\r\n\t\t?>\r\n
            \r\n
            \r\n\r\n\t\t\t
            \r\n
            \r\n\t\t\t\t\r\n
            \r\n \r\n
            \r\n
            \t\r\n\t\t\t\t\" />\r\n\t\t\t\t\" />\r\n\t\t\t\t\r\n\t\t\t
            \r\n\t\t
            \r\n
            \r\n\t\treqLevel('comment')) :\r\n\t\t\t$comment_token = genFormToken('comment');\t\r\n\t\t?>\r\n
            \r\n
            \r\n
            \r\n
            \r\n \r\n
            \r\n \r\n
            \r\n
            \r\n \" />\r\n \" />\r\n \r\n
            \r\n
            \r\n
            \r\n\t\tdisplayCDForm($cid)\r\n\t\t\t\r\n\t\t?>\r\n\t
            \r\n
            \r\n
            \r\n
            \r\n
            \r\n\r\n\r\n\r\n
            \r\n
            \r\n
            \r\n
              \r\n
            • \r\n
              Penalties
              \r\n
            • \r\n
            • \r\n
              Client Aliases
              \r\n
            • \r\nreqLevel('view_ip')) : ?>\r\n
            • \r\n
              IP Aliases
              \r\n
            • \r\n\r\n
            • \r\n
              Admin Actions
              \r\n
            • \r\ngetEchLogs($cid, $game);\r\n\t\r\n\t$count = count((array)$ech_logs);\r\n\tif($count > 0) : // if there are records\r\n?>\r\n
            • \r\n
              Echelon Logs
              \r\n
            • \r\ndisplayCDFormNavTab($cid);\r\n $plugins->displayCDFormNavTabLog($cid);\r\n?> \r\n
            \r\n
            \r\n
            \r\n
            \r\n\r\n
            \r\n\t\r\n\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\r\n\t\t\r\n\t\t\t\r\n\t\t\r\n\t\t\r\n\t\t\t\r\n\t\t\r\n\t
            Ban IDTypeAddedDurationExpiresReasonAdmin
            \r\n
            \r\n\r\n\r\n
            \r\n\r\n\t\r\n\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\r\n\t\r\n\t\r\n\t\t\r\n\t\r\n\t\r\n\tmysql->prepare($query) or die('Alias Database Query Error'. $db->mysql->error);\r\n\t\t$stmt->bind_param('i', $cid);\r\n\t\t$stmt->execute();\r\n\t\t$stmt->bind_result($alias, $num_used, $time_add, $time_edit);\r\n\t\t\r\n\t\t$stmt->store_result(); // needed for the $stmt->num_rows call\r\n\r\n\t\tif($stmt->num_rows) :\r\n\t\t\t\r\n\t\t\twhile($stmt->fetch()) :\r\n\t\r\n\t\t\t\t$time_add = date($tformat, $time_add);\r\n\t\t\t\t$time_edit = date($tformat, $time_edit);\r\n\t\t\t\t\r\n\t\t\t\t$alter = alter();\r\n\t\t\t\t\r\n\t\t\t\t$token_del = genFormToken('del'.$id);\t\t\r\n\t\t\t\t\r\n\t\t\t\t// setup heredoc (table data)\t\t\t\r\n\t\t\t\t$data = <<\r\n\t\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t\r\nEOD;\r\n\t\t\t\techo $data;\r\n\t\t\t\r\n\t\t\tendwhile;\r\n\t\t\r\n\t\telse : // if there are no aliases connected with this user then put out a small and short message\r\n\t\t\r\n\t\t\techo '';\r\n\t\t\r\n\t\tendif;\r\n\t?>\r\n\t\r\n
            AliasTimes UsedFirst UsedLast Used
            $alias$num_used$time_add$time_edit
            '.$name.' has no aliases.
            \r\n
            \r\n\r\n\r\nreqLevel('view_ip')) : ?>\r\n
            \r\n\r\n\t\r\n\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\r\n\t\r\n\t\r\n\t\t\r\n\t\r\n\t\r\n\tmysql->prepare($query) or die('IP-Alias Database Query Error'. $db->mysql->error);\r\n\t\t$stmt->bind_param('i', $cid);\r\n\t\t$stmt->execute();\r\n\t\t$stmt->bind_result($alias, $num_used, $time_add, $time_edit);\r\n\t\t\r\n\t\t$stmt->store_result(); // needed for the $stmt->num_rows call\r\n\r\n\t\tif($stmt->num_rows) :\r\n\t\t\t\r\n\t\t\twhile($stmt->fetch()) :\r\n\t\r\n\t\t\t\t$time_add = date($tformat, $time_add);\r\n\t\t\t\t$time_edit = date($tformat, $time_edit);\r\n\t\t\t\t\r\n\t\t\t\t$alter = alter();\r\n\t\t\t\t\r\n\t\t\t\t$token_del = genFormToken('del'.$id);\t\t\r\n\t\t\t\t// setup heredoc (table data)\t\t\t\r\n\t\t\t\t$data = <<\r\n\t\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t\r\nEOD;\r\n\t\t\t\techo $data;\r\n\t\t\t\r\n\t\t\tendwhile;\r\n\t\t\r\n\t\telse : // if there are no aliases connected with this user then put out a small and short message\r\n\t\t\r\n\t\t\techo '';\r\n\t\t\r\n\t\tendif;\r\n\t?>\r\n\t\r\n
            IP-AliasTimes UsedFirst UsedLast Used
            $alias$num_used$time_add$time_edit
            '.$name.' has no IP-aliases.
            \r\n
            \r\n\r\n\r\n\r\n
            \r\n\t\r\n\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\r\n\t\t\r\n\t\t\t\r\n\t\t\r\n\t\t\r\n\t\t\t\r\n\t\t\r\n\t
            IDTypeAddedDurationExpiresReasonAdmin
            \r\n
            \r\n\r\n\r\n\r\ngetEchLogs($cid, $game);\r\n\t\r\n\t$count = count((array)$ech_logs);\r\n\tif($count > 0) : // if there are records\r\n?>\r\n
            \r\n\t\r\n\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\r\n\t\t\r\n\t\t\t\r\n\t\t\r\n\t\t\r\n\t\t\t\r\n\t\t\r\n\t
            IDTypeMessageTime AddedAdmin
            \r\n
            \r\n\r\n\r\n\r\n\r\n
            \r\ndisplayCDBio();?>\r\n
            \r\n\r\n
            \r\ndisplayCDlogs($cid);?>\r\n
            \r\n\r\n
            \r\n
            \r\n
            \r\n
            \r\n\r\n\r\n", "echelon/clients.php": "error) :\r\n?>\r\n\r\n
            \r\n
            \r\n
            \r\n
            Client Listings\r\n \r\n
            \r\n \t\t\t'.$search_string.'. There are '. $total_rows .' entries matching your request.';\r\n\t\t\telseif($search_type == 'alias')\r\n\t\t\t\techo 'You are searching all clients names for '.$search_string.'. There are '. $total_rows .' entries matching your request.';\r\n elseif($search_type == 'aliastable')\r\n\t\t\t\techo 'You are searching all alias names for '.$search_string.'. There are '. $total_rows .' entries matching your request.';\r\n elseif($search_type == 'ipaliastable')\r\n\t\t\t\techo 'You are searching all client IP-alias names for '.$search_string.'. There are '. $total_rows .' entries matching your request.';\r\n\t\t\telseif($search_type == 'guid')\r\n\t\t\t\techo 'You are searching all clients GUIDs for '.$search_string.'. There are '. $total_rows .' entries matching your request.';\r\n\t\t\telseif($search_type == 'id')\r\n\t\t\t\techo 'You are searching all clients B3 IDs for '.$search_string.'. There are '. $total_rows .' entries matching your request.';\r\n\t\t\telseif($search_type == 'ip')\r\n\t\t\t\techo 'You are searching all clients IP addresses for '.$search_string.'. There are '. $total_rows .' entries matching your request.';\r\n\t\t\t?>\r\n
            \r\n
            \r\n \r\n\t\r\n\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\r\n\t\r\n\t\r\n\t\t\r\n\t\t\t\r\n\t\t\r\n\t\r\n\t\r\n\t 0) : // query contains stuff\r\n\t \r\n\t\tforeach($data_set as $client): // get data from query and loop\r\n\t\t\t$cid = $client['id'];\r\n\t\t\t$name = $client['name'];\r\n\t\t\t$level = $client['level'];\r\n\t\t\t$connections = $client['connections'];\r\n\t\t\t$time_edit = $client['time_edit'];\r\n\t\t\t$time_add = $client['time_add'];\r\n\t\t\t\r\n\t\t\t$time_add = date($tformat, $time_add);\r\n\t\t\t$time_edit = date($tformat, $time_edit);\r\n\t\t\t\r\n\t\t\t$alter = alter();\r\n\t\t\t\t\r\n\t\t\t$client = clientLink($name, $cid);\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t// setup heredoc (table data)\t\t\t\r\n\t\t\t$data = <<\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\nEOD;\r\n\r\n\t\techo $data;\r\n\t\tendforeach;\r\n\telse :\r\n\t\t$no_data = true;\r\n\t\r\n\t\techo '';\r\n\tendif; // no records\r\n\t?>\r\n\t\r\n
            Name\r\n\t\t\t\t\r\n\t\t\tClient-ID\r\n\t\t\t\t\r\n\t\t\tLevel\r\n\t\t\t\t\r\n\t\t\tConnections\r\n\t\t\t\t\r\n\t\t\tFirst Seen\r\n\t\t\t\t\r\n\t\t\tLast Seen\r\n\t\t\t\t\r\n\t\t\t
            Click client name to see details.
            $client@$cid$level$connections$time_add$time_edit
            ';\r\n\t\tif($is_search == false)\r\n\t\t\techo 'There are no clients in the database.';\r\n\t\telse\r\n\t\t\techo 'Your search for '.$search_string.' has returned no results. Maybe try an Alias/IP-Alias search?';\r\n\t\techo '
            \r\n
            \r\n\r\n", "echelon/css/cd.css": "/* Client Details Page Styling */\r\n@media screen {\r\n\r\ntable.cd-table { margin-bottom: 25px; border: none; }\r\n\t.cd-table tbody tr { border-bottom: 1px solid #F4F4F4; }\r\n\t.cd-table tbody tr th { width: 15%; background: none; border: none; text-align: right; }\r\n\t.cd-table tbody tr td { width: 35%; border: none; }\r\n\r\ndiv#actions { margin-bottom: 25px; }\r\n\r\nul.cd-tabs { display: block; margin-left: 10px; height: 26px; }\r\nul.cd-tabs li { display: block; float: left; margin: 0 6px; background: #ddd; border: 1px solid #CCC; -moz-border-radius: 5px 5px 0 0; -webkit-border-radius: 5px 5px 0 0; box-shadow: 4px -1px 6px #EDEDED; -webkit-box-shadow: 4px -1px 6px #EDEDED; -moz-box-shadow: 4px -1px 6px #EDEDED; }\r\nul.cd-tabs li.cd-active, ul.cd-tabs li.chat-active { padding-bottom: 3px; border-bottom: none; background: #f3f3f3; box-shadow: none; -webkit-box-shadow: none; -moz-box-shadow: none; }\r\nul.cd-tabs li a { padding: 4px 9px; font-size: 15px; color: #999; display: block; }\r\nul.cd-tabs li a:hover { color: #666; text-decoration: none; cursor: pointer; }\r\n\r\n#actions-box { background: #f3f3f3; padding: 15px; border: 1px solid #CCC; -moz-border-radius: 7px; -webkit-border-radius: 7px; }\r\n.act-slide { display: none; }\r\n#cd-act-comment { display: block; }\r\n\r\n#chats-box { background: #f3f3f3; padding: 15px; border: 1px solid #CCC; -moz-border-radius: 7px; -webkit-border-radius: 7px; }\r\n.chat-content { display: none; }\r\n#chat-tab-0 { display: block; }\r\n\r\n.xlr { height: 7px; }\r\n\r\n.cd-h { margin: 20px 0 4px; border-bottom: 1px solid #efefef; padding-bottom: 3px; }\r\n.cd-open-close:hover, .cd-slide, #cd-h-admin:hover, #cd-h-pen:hover { cursor: pointer; }\r\nimg.cd-open { float: right; padding: 3px; margin: 8px; }\r\n\r\n.cd-table-fold { display: none; }\r\n#cd-tr-load-pen td { text-align: center; }\r\n#cd-tr-load-pen:hover { background : #fff; }\r\n.load-large { margin: 15px; }\r\n\r\n#eb-reason, #reason { width: 350px; }\r\ninput.dur { width: 60px; }\r\n\r\n.unban-form { width: 18px; display: inline; }\r\n.edit-ban:hover { cursor: pointer; }\t\t\r\n.eb-fs { display: block; float: none !important; width: 93% !important; }\r\n\r\n#edit-ban { margin: 25px; }\r\n\r\n/* ColorBox Core Style */\r\n#colorbox, #cboxOverlay, #cboxWrapper{position:absolute; top:0; left:0; z-index:9999; overflow:hidden;}\r\n#cboxOverlay{position:fixed; width:100%; height:100%;}\r\n#cboxMiddleLeft, #cboxBottomLeft{clear:left;}\r\n#cboxContent{position:relative; overflow:visible;}\r\n#cboxLoadedContent{overflow:auto;}\r\n#cboxLoadedContent iframe{display:none; width:100%; height:100%; border:0;}\r\n#cboxTitle{margin:0;}\r\n#cboxLoadingOverlay, #cboxLoadingGraphic{position:absolute; top:0; left:0; width:100%;}\r\n#cboxPrevious, #cboxNext, #cboxClose, #cboxSlideshow{cursor:pointer;}\r\n\r\n#cboxOverlay{background:#000;}\r\n\r\n#colorbox{}\r\n #cboxTopLeft{width:14px; height:14px; background:url(../images/colorbox/controls.png) 0 0 no-repeat;}\r\n #cboxTopCenter{height:14px; background:url(../images/colorbox/border.png) top left repeat-x;}\r\n #cboxTopRight{width:14px; height:14px; background:url(../images/colorbox/controls.png) -36px 0 no-repeat;}\r\n #cboxBottomLeft{width:14px; height:43px; background:url(../images/colorbox/controls.png) 0 -32px no-repeat;}\r\n #cboxBottomCenter{height:43px; background:url(../images/colorbox/border.png) bottom left repeat-x;}\r\n #cboxBottomRight{width:14px; height:43px; background:url(../images/colorbox/controls.png) -36px -32px no-repeat;}\r\n #cboxMiddleLeft{width:14px; background:url(../images/colorbox/controls.png) -175px 0 repeat-y;}\r\n #cboxMiddleRight{width:14px; background:url(../images/colorbox/controls.png) -211px 0 repeat-y;}\r\n #cboxContent{background:#fff;}\r\n #cboxLoadedContent{margin-bottom:5px;}\r\n #cboxLoadingOverlay{background:url(../images/colorbox/loading_background.png) center center no-repeat;}\r\n #cboxLoadingGraphic{background:url(../images/colorbox/loading.gif) center center no-repeat;}\r\n #cboxTitle{position:absolute; bottom:-25px; left:0; text-align:center; width:100%; font-weight:bold; color:#7C7C7C;}\r\n #cboxCurrent{position:absolute; bottom:-25px; left:58px; font-weight:bold; color:#7C7C7C;}\r\n \r\n #cboxPrevious, #cboxNext, #cboxClose, #cboxSlideshow{position:absolute; bottom:-29px; background:url(../images/colorbox/controls.png) 0px 0px no-repeat; width:23px; height:23px; text-indent:-9999px;}\r\n #cboxPrevious{left:0px; background-position: -51px -25px;}\r\n #cboxPrevious.hover{background-position:-51px 0px;}\r\n #cboxNext{left:27px; background-position:-75px -25px;}\r\n #cboxNext.hover{background-position:-75px 0px;}\r\n #cboxClose{right:0; background-position:-100px -25px;}\r\n #cboxClose.hover{background-position:-100px 0px;}\r\n \r\n .cboxSlideshow_on #cboxSlideshow{background-position:-125px 0px; right:27px;}\r\n .cboxSlideshow_on #cboxSlideshow.hover{background-position:-150px 0px;}\r\n .cboxSlideshow_off #cboxSlideshow{background-position:-150px -25px; right:27px;}\r\n .cboxSlideshow_off #cboxSlideshow.hover{background-position:-125px 0px;}\r\n\t\r\n}\t\r\n@media print {\r\n\r\nbody { width:100% !important; margin:0 !important; padding:0 !important; line-height: 1.4; word-spacing:1.1pt; letter-spacing:0.2pt; font-family: Georgia, \"Trebuchet MS\", Helvetica, sans-serif; color: #000; background: none; font-size: 12pt; }\r\nh1,h2,h3,h4,h5,h6 { font-family: Georgia, \"Trebuchet MS\", Helvetica, sans-serif; }\r\nh1{font-size:19pt;}\r\nh2{font-size:17pt;}\r\nh3{font-size:15pt;}\r\nh4,h5,h6{font-size:12pt;}\r\ncode { font: 10pt Courier, monospace; } \r\nblockquote { margin: 1.3em; padding: 1em; font-size: 10pt; }\r\nhr { background-color: #ccc; }\r\nimg { display: block; margin: 1em 0; }\r\na img { border: none; }\r\ntable { margin: 1px; text-align:left; }\r\nth { border-bottom: 1px solid #333; font-weight: bold; }\r\ntd { border-bottom: 1px solid #333; }\r\nth,td { padding: 4px 10px 4px 0; }\r\ntfoot { font-style: italic; }\r\ncaption { background: #fff; margin-bottom:2em; text-align:left; }\r\nthead {display: table-header-group;}\r\ntr { page-break-inside: avoid;} \r\na { text-decoration: none; color: black; }\r\n\r\n#menu, #actions, .foot-nav, caption, .cd-open, #content-lower, .unban-form, .edit-ban { display: none; }\r\n\r\n}\r\n"}} +{"repo": "schamane/node-syslog", "pr_number": 34, "title": "Build an empty addon on win32", "state": "closed", "merged_at": null, "additions": 29, "deletions": 5, "files_changed": ["node-syslog.js", "test.js"], "files_before": {"node-syslog.js": "var SyslogWrapper = require('./build/Release/syslog');\n\n/*\n * export Syslog as module\n */\nmodule.exports = {\n\ninit: SyslogWrapper.init,\nlog: SyslogWrapper.log,\nsetMask: SyslogWrapper.setMask,\nclose: SyslogWrapper.close,\nversion: '1.1.7',\n\n/*\n * facilities\n */\nLOG_KERN\t\t: (0<<3),\nLOG_USER\t\t: (1<<3),\nLOG_MAIL\t\t: (2<<3),\nLOG_DAEMON\t\t: (3<<3),\nLOG_AUTH\t\t: (4<<3),\nLOG_SYSLOG\t\t: (5<<3),\nLOG_LPR\t\t\t: (6<<3),\nLOG_NEWS\t\t: (7<<3),\nLOG_UUCP\t\t: (8<<3),\nLOG_LOCAL0\t\t: (16<<3),\nLOG_LOCAL1\t\t: (17<<3),\nLOG_LOCAL2\t\t: (18<<3),\nLOG_LOCAL3\t\t: (19<<3),\nLOG_LOCAL4\t\t: (20<<3),\nLOG_LOCAL5\t\t: (21<<3),\nLOG_LOCAL6\t\t: (22<<3),\nLOG_LOCAL7\t\t: (23<<3),\n\n/*\n * option flag for openlog\n */\nLOG_PID\t\t\t: 0x01,\nLOG_CONS\t\t: 0x02,\nLOG_ODELAY\t\t: 0x04,\nLOG_NDELAY\t\t: 0x08,\nLOG_NOWAIT\t\t: 0x10,\nLOG_PERROR\t\t: 0x20,\n/*\n * priorities\n */\nLOG_EMERG\t\t: 0,\nLOG_ALERT\t\t: 1,\nLOG_CRIT\t\t: 2,\nLOG_ERR\t\t\t: 3,\nLOG_WARNING\t\t: 4,\nLOG_NOTICE\t\t: 5,\nLOG_INFO\t\t: 6,\nLOG_DEBUG\t\t: 7\n};\n\n/*\n * Attach destroy handling\n *\n * XXX(sam) consider using AtExit: joyent/node#e4a8d261\n */\nprocess.on('exit', function() {\n\tSyslogWrapper.close();\n});\n", "test.js": "var assert = require('assert');\nvar Syslog = require('./node-syslog');\n\nassert.throws(function() {\n Syslog.init();\n}, Error);\n\nSyslog.init(\"node-syslog-test\", Syslog.LOG_PID | Syslog.LOG_ODELAY, Syslog.LOG_LOCAL0);\nSyslog.log(Syslog.LOG_INFO, \"news info log test\");\nSyslog.log(Syslog.LOG_ERR, \"news log error test\");\nSyslog.log(Syslog.LOG_DEBUG, \"Last log message as debug: \" + new Date());\nSyslog.close();\n\nconsole.log('PASS');\n"}, "files_after": {"node-syslog.js": "var SyslogWrapper = require('./build/Release/syslog');\n\n/*\n * export Syslog as module\n */\nmodule.exports = {\n\ninit: SyslogWrapper.init,\nlog: SyslogWrapper.log,\nsetMask: SyslogWrapper.setMask,\nclose: SyslogWrapper.close,\nversion: '1.1.7',\n\n/*\n * facilities\n */\nLOG_KERN\t\t: (0<<3),\nLOG_USER\t\t: (1<<3),\nLOG_MAIL\t\t: (2<<3),\nLOG_DAEMON\t\t: (3<<3),\nLOG_AUTH\t\t: (4<<3),\nLOG_SYSLOG\t\t: (5<<3),\nLOG_LPR\t\t\t: (6<<3),\nLOG_NEWS\t\t: (7<<3),\nLOG_UUCP\t\t: (8<<3),\nLOG_LOCAL0\t\t: (16<<3),\nLOG_LOCAL1\t\t: (17<<3),\nLOG_LOCAL2\t\t: (18<<3),\nLOG_LOCAL3\t\t: (19<<3),\nLOG_LOCAL4\t\t: (20<<3),\nLOG_LOCAL5\t\t: (21<<3),\nLOG_LOCAL6\t\t: (22<<3),\nLOG_LOCAL7\t\t: (23<<3),\n\n/*\n * option flag for openlog\n */\nLOG_PID\t\t\t: 0x01,\nLOG_CONS\t\t: 0x02,\nLOG_ODELAY\t\t: 0x04,\nLOG_NDELAY\t\t: 0x08,\nLOG_NOWAIT\t\t: 0x10,\nLOG_PERROR\t\t: 0x20,\n/*\n * priorities\n */\nLOG_EMERG\t\t: 0,\nLOG_ALERT\t\t: 1,\nLOG_CRIT\t\t: 2,\nLOG_ERR\t\t\t: 3,\nLOG_WARNING\t\t: 4,\nLOG_NOTICE\t\t: 5,\nLOG_INFO\t\t: 6,\nLOG_DEBUG\t\t: 7\n};\n\n/*\n * Attach destroy handling\n *\n * XXX(sam) consider using AtExit: joyent/node#e4a8d261\n */\nif (SyslogWrapper.close) {\n\tprocess.on('exit', function() {\n\t\tSyslogWrapper.close();\n\t});\n}\n", "test.js": "var assert = require('assert');\nvar Syslog = require('./node-syslog');\n\nif (process.platform == \"win32\") {\n assert(Syslog.init === undefined);\n console.log('PASS');\n return;\n}\n\nassert.throws(function() {\n Syslog.init();\n}, Error);\n\nSyslog.init(\"node-syslog-test\", Syslog.LOG_PID | Syslog.LOG_ODELAY, Syslog.LOG_LOCAL0);\nSyslog.log(Syslog.LOG_INFO, \"news info log test\");\nSyslog.log(Syslog.LOG_ERR, \"news log error test\");\nSyslog.log(Syslog.LOG_DEBUG, \"Last log message as debug: \" + new Date());\nSyslog.close();\n\nconsole.log('PASS');\n"}} +{"repo": "trel/MPACT", "pr_number": 1, "title": "Php7", "state": "closed", "merged_at": "2021-05-07T04:46:11Z", "additions": 483, "deletions": 431, "files_changed": ["mpact.php", "mpact_include.php"], "files_before": {"mpact.php": " \"N/A\",\n \"-1\" => \"N/A\",\n \"0\" => \"Incomplete - Not_Inspected\",\n \"1\" => \"Incomplete - Inspected\",\n \"2\" => \"Incomplete - Ambiguous\",\n \"3\" => \"Complete - Except Indecipherables\",\n \"4\" => \"Fully Complete\"\n);\n\n$inspectioncodes = array(\n NULL => \"N/A\",\n \"0\" => \"No\",\n \"1\" => \"Yes\"\n);\n\n$degree_types = array(\n \"Unknown\",\n \"Unknown - Investigated\",\n \"A.L.A.\",\n \"B.A.\",\n \"B.S.\",\n \"B.L.S.\",\n \"L.L.B.\",\n \"H.A.\",\n \"M.A.\",\n \"M.S.\",\n \"M.F.A.\",\n \"M.P.A.\",\n \"D.E.A.\",\n \"Ed.M.\",\n \"F.L.A. (by thesis)\",\n \"LL.M.\",\n \"LL.D.\",\n \"M.L.S.\",\n \"D.S.N.\",\n \"D.S.W.\",\n \"D.Engr.\",\n \"D.Lib.\",\n \"Ed.D.\",\n \"Th.D.\",\n \"Pharm.D.\",\n \"D.Sc.\",\n \"D.L.S.\",\n \"J.D.\",\n \"M.D.\",\n \"Ph.D.\"\n);\n\n// Begin Session\nsession_start();\n\n// Delete server session if client cookie doesn't exist\nif (!isset($_COOKIE['MPACT_userid'])){\n unset($_SESSION['MPACT']);\n}\n\n// Check for good cookie (and expired session) - (re)set session values accordingly\nif (isset($_COOKIE['MPACT_userid']) && !isset($_SESSION['MPACT'])){\n $query = \"SELECT id, username, fullname FROM users WHERE id='\".$_COOKIE['MPACT_userid'].\"'\";\n $result = mysql_query($query) or die(mysql_error());\n $line = mysql_fetch_array($result);\n $_SESSION['MPACT']['userid'] = $line['id'];\n $_SESSION['MPACT']['username'] = $line['username'];\n $_SESSION['MPACT']['fullname'] = $line['fullname'];\n}\n\n###############################################\n// DISPLAY SOMETHING - something from the URL\nif ($_SERVER['REQUEST_METHOD'] == 'GET')\n{\n // Display header\n xhtml_web_header();\n\n// echo \"-----\\n\";\n// print_r($_COOKIE);\n// echo \"-----\\n\";\n// print_r($_SESSION);\n// echo \"-----\\n\";\n if (isset($_GET['op']))\n {\n switch ($_GET['op'])\n {\n ###############################################\n case \"login\";\n\n $host_info = get_environment_info();\n if ($host_info['hostname'] == \"sils\"){\n # no logins here - go to dev server\n action_box(\"No Logins Here...\",2,$_SERVER['SCRIPT_NAME']);\n }\n else{\n if (!isset($_SESSION['MPACT']['userid'])){\n # login form\n echo \"

            Welcome

            \\n\";\n echo \"

            Please login if you have an account.

            \\n\";\n echo \"
            \\n\";\n echo \"\\n\";\n echo \"\\n\";\n echo \"\\n\";\n echo \"\\n\";\n echo \"\\n\";\n echo \"

            Username:

            Password:

                 
            \\n\";\n echo \"
            \";\n }\n else{\n # um, already logged in...\n action_box(\"Already Logged In...\",2,$_SERVER['SCRIPT_NAME']);\n }\n }\n\n break;\n ###############################################\n case \"logout\";\n\n setcookie('MPACT_userid',$_SESSION['MPACT']['userid'],time()-1000);\n unset($_SESSION['MPACT']);\n action_box(\"Logged Out\",2,$_SERVER['SCRIPT_NAME']);\n\n break;\n ###############################################\n case \"glossary\";\n\n if ( isset($_GET['id']) ){\n show_glossaryterm($_GET['id']);\n }\n else\n {\n show_glossary();\n }\n\n break;\n ###############################################\n case \"admin\";\n\n if (is_admin())\n {\n echo \"

            Administrator Pages

            \\n\";\n\n echo \"\\n\";\n echo \"\\n\";\n echo \"
            \\n\";\n\n echo \"

            \\n\";\n echo \"Show Logs\\n\";\n echo \"

            \\n\";\n\n echo \"

            \\n\";\n echo \"Show Orphans\\n\";\n echo \"
            \\n\";\n echo \"Citation Correlation\\n\";\n echo \"

            \\n\";\n\n echo \"

            \\n\";\n echo \"People with Multiple Dissertations (Errors in DB)\\n\";\n echo \"
            \\n\";\n echo \"Year 0000\\n\";\n echo \"

            \\n\";\n\n echo \"

            \\n\";\n echo \"Add a New Person to the Database\\n\";\n echo \"

            \\n\";\n\n echo \"
            \\n\";\n\n echo \"

            \\n\";\n echo \"No Title/Abstract\\n\";\n echo \"
            \\n\";\n echo \"LIS, No Title/Abstract\\n\";\n echo \"
            \\n\";\n echo \"LIS, No Title\\n\";\n echo \"
            \\n\";\n echo \"LIS, No Abstract\\n\";\n echo \"
            \\n\";\n echo \"
            \\n\";\n echo \"LIS, No Committee\\n\";\n echo \"

            \\n\";\n\n echo \"
            \\n\";\n\n echo \"

            \\n\";\n echo \"LIS, Graduates By Year\\n\";\n echo \"
            \\n\";\n echo \"LIS History\\n\";\n echo \"

            \\n\";\n\n echo \"

            \\n\";\n echo \"LIS Professors Summary\\n\";\n echo \"
            \\n\";\n echo \"LIS Professors with MPACT\\n\";\n echo \"
            \\n\";\n echo \"LIS Professors and their Degrees (large CSV)\\n\";\n echo \"
            \\n\";\n echo \"LIS Professors with Unknown Degree\\n\";\n echo \"
            \\n\";\n echo \"LIS Professors with Unknown-Investigated Degree\\n\";\n echo \"
            \\n\";\n echo \"LIS Professors without Dissertations\\n\";\n echo \"
            \\n\";\n echo \"LIS Professors without LIS Dissertations\\n\";\n echo \"

            \\n\";\n\n echo \"
            \\n\";\n\n echo \"
            \";\n\n show_alphabet();\n\n }\n else\n {\n not_admin();\n }\n\n break;\n ###############################################\n case \"glossary_edit\";\n\n if ( isset($_GET['id']) && is_admin() ){\n\n echo \"

            Edit a Glossary Definition

            \\n\";\n\n $query = \"SELECT id, term, definition FROM glossary WHERE id='\".$_GET['id'].\"'\";\n $result = mysql_query($query) or die(mysql_error());\n\n while ( $line = mysql_fetch_array($result)) {\n $results['term'] = $line['term'];\n $results['definition'] = $line['definition'];\n }\n\n echo \"

            \";\n\n echo \"

            \\n\";\n echo \"\\n\";\n echo \"\\n\";\n echo \"\\n\";\n\n echo \"\".$results['term'].\":
            \\n\";\n echo \"\\n\";\n echo \"
            \\n\";\n echo \"\";\n echo \"
            \";\n\n echo \"

            \";\n\n\n }\n else\n {\n not_admin();\n }\n\n break;\n ###############################################\n case \"show_tree\":\n\n if (!$_GET['id']){action_box(\"No ID given.\");}\n else\n {\n draw_tree((int)$_GET['id']);\n }\n\n break;\n\n ###############################################\n case \"show_graph\":\n\n if (!$_GET['id']){action_box(\"No ID given.\");}\n else\n {\n echo \"

            \\n\";\n echo \"Advisors and Advisees of \".get_person_link($_GET['id']);\n echo \"

            \\n\";\n draw_graph((int)$_GET['id']);\n }\n\n break;\n\n ###############################################\n case \"statistics\":\n\n echo \"

            \\n\";\n echo \"LIS Incomplete - \\n\";\n echo \"Top A -\\n\";\n echo \"Top C -\\n\";\n echo \"Top A+C -\\n\";\n echo \"Top T -\\n\";\n echo \"Top G -\\n\";\n echo \"Top W -\\n\";\n echo \"Top TD -\\n\";\n echo \"Top TA\\n\";\n echo \"

            \\n\";\n\n echo \"

            Overall MPACT Statistics

            \\n\";\n\n echo \"\\n\";\n\n # disciplines\n $query = \"SELECT count(*) as disciplinecount FROM disciplines\";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n extract($line);\n }\n echo \"\\n\";\n\n # schools\n $query = \"SELECT count(*) as schoolcount FROM schools\";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n extract($line);\n }\n echo \"\\n\";\n\n # diss\n $query = \"SELECT count(*) as disscount FROM dissertations\";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n extract($line);\n }\n echo \"\\n\";\n\n # a\n $query = \"SELECT count(*) as advisorcount FROM advisorships\";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n extract($line);\n }\n echo \"\\n\";\n\n # c\n $query = \"SELECT count(*) as committeeshipscount FROM committeeships\";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n extract($line);\n }\n echo \"\\n\";\n\n # full\n $query = \"SELECT count(*) as peoplecount FROM people\";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n extract($line);\n }\n echo \"\\n\";\n echo \"
            Disciplines\".$disciplinecount.\"
            Schools\".$schoolcount.\"
            Dissertations\".$disscount.\"
            Advisorships\".$advisorcount.\"
            Committeeships\".$committeeshipscount.\"
            People\".$peoplecount.\"
            \\n\";\n\n\n # dissertations by country\n echo \"

            \\n\";\n echo \"

            Dissertations by Country:


            \\n\";\n $query = \"SELECT count(*) as dissnone FROM dissertations WHERE school_id IN (SELECT id FROM schools WHERE country = \\\"\\\")\";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n extract($line);\n }\n $query = \"SELECT count(*) as dissusa FROM dissertations WHERE school_id IN (SELECT id FROM schools WHERE country = \\\"USA\\\")\";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n extract($line);\n }\n $query = \"SELECT count(*) as disscanada FROM dissertations WHERE school_id IN (SELECT id FROM schools WHERE country = \\\"Canada\\\")\";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n extract($line);\n }\n $query = \"SELECT count(*) as dissother FROM dissertations WHERE school_id IN\n (SELECT id FROM schools WHERE (country != \\\"\\\" AND country != \\\"USA\\\" AND country != \\\"Canada\\\"))\";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n extract($line);\n }\n echo \"\\n\";\n echo \"\n \n \\n\";\n echo \"\n \n \\n\";\n echo \"\n \n \\n\";\n echo \"\n \n \\n\";\n echo \"\n \n \\n\";\n echo \"
            USA\".$dissusa.\"\".sprintf(\"%.2f\",100*$dissusa/$disscount).\"%\".sprintf(\"%.2f\",100*($dissusa)/$disscount).\"%
            Canada\".$disscanada.\"\".sprintf(\"%.2f\",100*$disscanada/$disscount).\"%\".sprintf(\"%.2f\",100*($dissusa+$disscanada)/$disscount).\"%
            Other\".$dissother.\"\".sprintf(\"%.2f\",100*$dissother/$disscount).\"%\".sprintf(\"%.2f\",100*($dissusa+$disscanada+$dissother)/$disscount).\"%
            None Listed\".$dissnone.\"\".sprintf(\"%.2f\",100*$dissnone/$disscount).\"%\".sprintf(\"%.2f\",100*($dissusa+$disscanada+$dissother+$dissnone)/$disscount).\"%
            Total\".$disscount.\"\".sprintf(\"%.2f\",100*$disscount/$disscount).\"%
            \\n\";\n\n # dissertations by year\n echo \"

            \\n\";\n echo \"

            Dissertations by Year:


            \\n\";\n $query = \"SELECT completedyear, count(*) as disscount FROM dissertations GROUP BY completedyear\";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $counts[$line['completedyear']] = $line['disscount'];\n }\n echo \"\\n\";\n echo \"\\n\";\n foreach ($counts as $one => $two)\n {\n echo \"\\n\";\n }\n echo \"\";\n echo \"\\n\";\n foreach ($counts as $one => $two)\n {\n echo \"\\n\";\n }\n echo \"\";\n echo \"
            \";\n if ($one%10==0)\n {\n echo $one;\n }\n echo \"
            \\n\";\n\n break;\n\n\n ###############################################\n case \"show_logs\":\n\n if (is_admin())\n {\n echo \"

            Recent Activity

            \\n\";\n\n if (isset($_GET['offset']))\n {\n $entries = get_logs($_GET['offset']);\n }\n else\n {\n $entries = get_logs();\n }\n echo \"\\n\";\n foreach ($entries as $entry)\n {\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\\n\";\n }\n echo \"
            \".$entry['logged_at'].\"
            \".$entry['ip'].\"
            \".$entry['user'].\"\".$entry['message'].\"
            \\n\";\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"find_multi_dissertations\":\n\n if (is_admin())\n {\n echo \"

            People With Multiple Dissertations (db needs to be edited by hand)

            \\n\";\n \n $query = \"SELECT\n count(d.id) as howmany,\n d.id, d.person_id, d.completedyear, d.status,\n d.title, d.abstract, d.notes, d.school_id, d.discipline_id\n FROM\n dissertations d\n GROUP BY\n d.person_id\n ORDER BY\n howmany DESC\n \";\n $result = mysql_query($query) or die(mysql_error());\n\n $dissertations = array();\n while ( $line = mysql_fetch_array($result)) {\n $dissertations[] = $line;\n }\n $multicount = 0;\n echo \"

            \\n\";\n foreach ($dissertations as $d)\n {\n if ($d['howmany'] > 1)\n {\n print \"person id = \".$d['person_id'];\n print \"
            \";\n print \"
            \";\n $multicount++;\n }\n }\n if ($multicount == 0)\n {\n print \" - None - database is clear.\";\n }\n echo \"

            \\n\";\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"find_zero_year\":\n\n if (is_admin())\n {\n echo \"

            Dissertations from the year 0000

            \\n\";\n \n $query = \"SELECT\n d.id, d.person_id, d.school_id, d.discipline_id, d.completedyear\n FROM\n dissertations d\n WHERE\n d.completedyear = '0000'\n \";\n $result = mysql_query($query) or die(mysql_error());\n\n $dissertations = array();\n while ( $line = mysql_fetch_array($result)) {\n $dissertations[] = $line;\n }\n $zerocount = 0;\n echo \"\";\n foreach ($dissertations as $d)\n {\n $zerocount++;\n # get school\n $query = \"SELECT fullname\n FROM\n schools\n WHERE id = '\".$d['school_id'].\"'\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $schoolname = $line['fullname'];\n }\n # get degree\n $query = \"SELECT degree\n FROM\n people\n WHERE id = '\".$d['person_id'].\"'\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $degree = $line['degree'];\n }\n $discipline = find_discipline($d['discipline_id']);\n echo \"\";\n echo \"\";\n echo \"\";\n print \"\";\n print \"\";\n print \"\";\n print \"\";\n }\n if ($zerocount == 0)\n {\n print \"\";\n }\n echo \"
            $zerocount.\".get_person_link($d['person_id']).\"$degree\".$discipline['title'].\"$schoolname
            None - database is clear.
            \\n\";\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"find_no_title_lis\":\n\n if (is_admin())\n {\n echo \"

            LIS Dissertations Without Title

            \\n\";\n \n $query = \"SELECT\n d.id, d.person_id, d.school_id, d.completedyear\n FROM\n dissertations d\n WHERE\n d.discipline_id = 1 AND\n ( d.title = '' )\n ORDER BY\n d.school_id\n \";\n $result = mysql_query($query) or die(mysql_error());\n\n $dissertations = array();\n while ( $line = mysql_fetch_array($result)) {\n $dissertations[] = $line;\n }\n $zerocount = 0;\n echo \"

            \\n\";\n foreach ($dissertations as $d)\n {\n $zerocount++;\n print \"$zerocount. \";\n echo get_person_link($d['person_id']);\n $thisperson = find_persons_school($d['person_id']);\n print \" - \".$thisperson['school'];\n print \" (\".$d['completedyear'].\")\";\n print \"
            \";\n }\n if ($zerocount == 0)\n {\n print \" - None - All LIS dissertations have titles.\";\n }\n echo \"

            \\n\";\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"find_no_abstract_lis\":\n\n if (is_admin())\n {\n echo \"

            LIS Dissertations Without Abstract

            \\n\";\n \n $query = \"SELECT\n d.id, d.person_id, d.school_id, d.completedyear\n FROM\n dissertations d\n WHERE\n d.discipline_id = 1 AND\n ( d.abstract = '' )\n ORDER BY\n d.school_id\n \";\n $result = mysql_query($query) or die(mysql_error());\n\n $dissertations = array();\n while ( $line = mysql_fetch_array($result)) {\n $dissertations[] = $line;\n }\n $zerocount = 0;\n echo \"

            \\n\";\n foreach ($dissertations as $d)\n {\n $zerocount++;\n print \"$zerocount. \";\n echo get_person_link($d['person_id']);\n $thisperson = find_persons_school($d['person_id']);\n print \" - \".$thisperson['school'];\n print \" (\".$d['completedyear'].\")\";\n print \"
            \";\n }\n if ($zerocount == 0)\n {\n print \" - None - All LIS dissertations have abstracts.\";\n }\n echo \"

            \\n\";\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"find_no_title_abstract\":\n\n if (is_admin())\n {\n echo \"

            Dissertations Without Title/Abstract

            \\n\";\n \n $query = \"SELECT\n d.id, d.person_id, d.school_id, d.completedyear\n FROM\n dissertations d\n WHERE\n d.title = '' OR d.abstract = ''\n ORDER BY\n d.school_id\n \";\n $result = mysql_query($query) or die(mysql_error());\n\n $dissertations = array();\n while ( $line = mysql_fetch_array($result)) {\n $dissertations[] = $line;\n }\n $zerocount = 0;\n echo \"

            \\n\";\n foreach ($dissertations as $d)\n {\n $zerocount++;\n print \"$zerocount. \";\n echo get_person_link($d['person_id']);\n $thisperson = find_persons_school($d['person_id']);\n print \" - \".$thisperson['school'];\n print \" (\".$d['completedyear'].\")\";\n print \"
            \";\n }\n if ($zerocount == 0)\n {\n print \" - None - All dissertations have titles and abstracts.\";\n }\n echo \"

            \\n\";\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"find_no_title_abstract_lis\":\n\n if (is_admin())\n {\n echo \"

            LIS Dissertations Without Title/Abstract

            \\n\";\n \n $query = \"SELECT\n d.id, d.person_id, d.school_id, d.completedyear\n FROM\n dissertations d\n WHERE\n d.discipline_id = 1 AND\n ( d.title = '' OR d.abstract = '' )\n ORDER BY\n d.school_id\n \";\n $result = mysql_query($query) or die(mysql_error());\n\n $dissertations = array();\n while ( $line = mysql_fetch_array($result)) {\n $dissertations[] = $line;\n }\n $zerocount = 0;\n echo \"

            \\n\";\n foreach ($dissertations as $d)\n {\n $zerocount++;\n print \"$zerocount. \";\n echo get_person_link($d['person_id']);\n $thisperson = find_persons_school($d['person_id']);\n print \" - \".$thisperson['school'];\n print \" (\".$d['completedyear'].\")\";\n print \"
            \";\n }\n if ($zerocount == 0)\n {\n print \" - None - All LIS dissertations have titles and abstracts.\";\n }\n echo \"

            \\n\";\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"lis_profs_unknown_degree\":\n \n if (is_admin())\n {\n echo \"

            LIS Professors with Unknown Degree

            \\n\";\n \n # advisors or committee members with unknown degree,\n # that served on an lis dissertation\n\n # get list of LIS dissertations\n $query = \"SELECT\n d.id\n FROM\n dissertations d\n WHERE\n d.discipline_id = '1'\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $lis_dissertations[] = $line['id'];\n }\n\n $lis_with_unknown = array();\n\n # get advisors for each diss, check for advisor's degree\n # if unknown degree, save\n foreach ($lis_dissertations as $id){\n $advisors = array();\n $query = \"SELECT person_id\n FROM advisorships\n WHERE dissertation_id = $id\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $advisors[] = $line['person_id'];\n }\n foreach($advisors as $aid){\n $adv = find_person($aid);\n if ($adv['degree'] == \"Unknown\"){\n $lis_with_unknown[] = $aid;\n }\n }\n }\n\n # get committeeships for each diss, check for comm's degree\n # if unknown degree, save\n foreach ($lis_dissertations as $id){\n $committeemembers = array();\n $query = \"SELECT person_id\n FROM committeeships\n WHERE dissertation_id = $id\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $committeemembers[] = $line['person_id'];\n }\n foreach($committeemembers as $cid){\n $com = find_person($cid);\n if ($com['degree'] == \"Unknown\"){\n $lis_with_unknown[] = $cid;\n }\n }\n }\n\n # uniquify\n $lis_with_unknown = array_unique($lis_with_unknown);\n\n # print them out\n echo \"

            \\n\";\n $count = 0;\n foreach($lis_with_unknown as $pid){\n $count++;\n $person = find_person($pid);\n print \"$count. \";\n print get_person_link($pid);\n print \"
            \\n\";\n }\n if ($count == 0)\n {\n print \" - None\";\n }\n echo \"

            \\n\";\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"lis_profs_unknowninvestigated\":\n case \"lis_profs_unknowninvestigated_degree\":\n \n# if (is_admin())\n# {\n echo \"

            LIS Professors with Unknown-Investigated Degree

            \\n\";\n \n # advisors or committee members with unknown-investigated degree,\n # that served on an lis dissertation\n\n # get list of LIS dissertations\n $query = \"SELECT\n d.id\n FROM\n dissertations d\n WHERE\n d.discipline_id = '1'\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $lis_dissertations[] = $line['id'];\n }\n\n $lis_with_unknown = array();\n\n # get advisors for each diss, check for advisor's degree\n # if unknown degree, save\n foreach ($lis_dissertations as $id){\n $advisors = array();\n $query = \"SELECT person_id\n FROM advisorships\n WHERE dissertation_id = $id\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $advisors[] = $line['person_id'];\n }\n foreach($advisors as $aid){\n $adv = find_person($aid);\n if ($adv['degree'] == \"Unknown - Investigated\"){\n $lis_with_unknown[] = $aid;\n }\n }\n }\n\n # get committeeships for each diss, check for comm's degree\n # if unknown degree, save\n foreach ($lis_dissertations as $id){\n $committeemembers = array();\n $query = \"SELECT person_id\n FROM committeeships\n WHERE dissertation_id = $id\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $committeemembers[] = $line['person_id'];\n }\n foreach($committeemembers as $cid){\n $com = find_person($cid);\n if ($com['degree'] == \"Unknown - Investigated\"){\n $lis_with_unknown[] = $cid;\n }\n }\n }\n\n # uniquify\n $lis_with_unknown = array_unique($lis_with_unknown);\n\n # print them out\n echo \"

            \\n\";\n $count = 0;\n foreach($lis_with_unknown as $pid){\n $count++;\n $person = find_person($pid);\n print \"$count. \";\n print get_person_link($pid);\n $advisorcount = count(find_advisorships_under_person($pid));\n $commcount = count(find_committeeships_under_person($pid));\n $totalcommitteeships = $advisorcount + $commcount;\n if ($totalcommitteeships > 1){print \"\";}\n print \" : $advisorcount + $commcount = $totalcommitteeships\";\n if ($totalcommitteeships > 1){print \"\";}\n print \"
            \\n\";\n $allcommitteeships += $totalcommitteeships;\n }\n if ($count == 0)\n {\n print \" - None\";\n }\n\n print \"
            TOTAL COMMITTEESHIPS = $allcommitteeships
            \";\n\n echo \"

            \\n\";\n\n# }\n# else\n# {\n# not_admin();\n# }\n\n break;\n\n\n ###############################################\n case \"lis_profswithoutdiss\":\n\n if (is_admin())\n {\n echo \"

            LIS Professors without Dissertations

            \\n\";\n \n # advisors or committee members with no dissertation,\n # that served on an lis dissertation\n\n # get list of LIS dissertations\n $query = \"SELECT\n d.id\n FROM\n dissertations d\n WHERE\n d.discipline_id = '1'\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $lis_dissertations[] = $line['id'];\n }\n # get advisors for each diss\n $advisors = array();\n foreach ($lis_dissertations as $id){\n $query = \"SELECT person_id\n FROM advisorships\n WHERE dissertation_id = $id\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $advisors[] = $line['person_id'];\n }\n }\n # get committeeships for each diss\n $committeemembers = array();\n foreach ($lis_dissertations as $id){\n $query = \"SELECT person_id\n FROM committeeships\n WHERE dissertation_id = $id\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $committeemembers[] = $line['person_id'];\n }\n }\n $total = array_merge($advisors,$committeemembers);\n $unique = array_unique($total);\n\n $unique_list = implode(\",\",$unique);\n $listed = array();\n $query = \"SELECT person_id\n FROM dissertations\n WHERE\n person_id IN ($unique_list)\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $listed[] = $line['person_id'];\n }\n $notlisted = array_diff($unique,$listed);\n\n # print them out\n echo \"

            \\n\";\n $count = 0;\n foreach($notlisted as $pid){\n $count++;\n print \"$count. \";\n print get_person_link($pid);\n print \"
            \\n\";\n }\n if ($count == 0)\n {\n print \" - None\";\n }\n echo \"

            \\n\";\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"lis_profs_degrees\":\n\n if (is_admin())\n {\n echo \"

            LIS Professors and their Degrees

            \\n\";\n\n # get list of LIS dissertations\n $query = \"SELECT\n d.id\n FROM\n dissertations d\n WHERE\n d.discipline_id = '1'\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $lis_dissertations[] = $line['id'];\n }\n\n print \"

            Copy and Paste the text below into a .csv file.

            \";\n\n # big loop\n print \"
            \\n\";\n          print \"
            \";\n print \"Count,DissID,DissYear,DissLastName,DissFirstName,DissSchool,DissCountry,AdvisorID,AdvisorType,AdvisorLastName,AdvisorFirstName,\";\n print \"AdvisorDegree,AdvisorYear,AdvisorDiscipline,AdvisorSchool,AdvisorCountry\\n\";\n $count = 0;\n foreach($lis_dissertations as $did){\n # loop through advisors\n $query = \"SELECT person_id\n FROM advisorships\n WHERE dissertation_id = $did\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n\n # advisor line\n\n # Count\n $count++;\n print \"\\\"$count\\\",\";\n # DissID\n print \"\\\"$did\\\",\";\n # DissYear\n $diss = find_dissertation($did);\n print \"\\\"\".$diss['completedyear'].\"\\\",\";\n # DissLastName\n $author = find_person($diss['person_id']);\n print \"\\\"\".$author['lastname'].\"\\\",\";\n # DissFirstName\n print \"\\\"\".$author['firstname'].\"\\\",\";\n # DissSchool\n $school = find_school($diss['school_id']);\n print \"\\\"\".$school['fullname'].\"\\\",\";\n # DissCountry\n print \"\\\"\".$school['country'].\"\\\",\";\n # AdvisorID\n $pid = $line['person_id'];\n print \"\\\"$pid\\\",\";\n # AdvisorType\n print \"\\\"Advisor\\\",\";\n # AdvisorLastName\n $person = find_person($pid);\n print \"\\\"\".$person['lastname'].\"\\\",\";\n # AdvisorFirstName\n print \"\\\"\".$person['firstname'].\"\\\",\";\n # AdvisorDegree\n print \"\\\"\".$person['degree'].\"\\\",\";\n $diss = find_dissertation_by_person($pid);\n if ($diss){\n # AdvisorYear\n print \"\\\"\".$diss['completedyear'].\"\\\",\";\n # AdvisorDiscipline\n $disc = find_discipline($diss['discipline_id']);\n print \"\\\"\".$disc['title'].\"\\\",\";\n # AdvisorSchool\n $school = find_school($diss['school_id']);\n print \"\\\"\".$school['fullname'].\"\\\",\";\n # AdvisorCountry\n print \"\\\"\".$school['country'].\"\\\"\";\n }\n else{\n # no dissertation for this person\n print \"\\\"\\\",\";\n print \"\\\"\\\",\";\n print \"\\\"\\\",\";\n print \"\\\"\\\"\";\n }\n print \"\\n\";\n\n }\n # loop through committeeships\n $query = \"SELECT person_id\n FROM committeeships\n WHERE dissertation_id = $did\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n\n # committeeship line\n\n # Count\n $count++;\n print \"\\\"$count\\\",\";\n # DissID\n print \"\\\"$did\\\",\";\n # DissYear\n $diss = find_dissertation($did);\n print \"\\\"\".$diss['completedyear'].\"\\\",\";\n # DissLastName\n $author = find_person($diss['person_id']);\n print \"\\\"\".$author['lastname'].\"\\\",\";\n # DissFirstName\n print \"\\\"\".$author['firstname'].\"\\\",\";\n # DissSchool\n $school = find_school($diss['school_id']);\n print \"\\\"\".$school['fullname'].\"\\\",\";\n # DissCountry\n print \"\\\"\".$school['country'].\"\\\",\";\n # AdvisorID\n $pid = $line['person_id'];\n print \"\\\"$pid\\\",\";\n # AdvisorType\n print \"\\\"Committee\\\",\";\n # AdvisorLastName\n $person = find_person($pid);\n print \"\\\"\".$person['lastname'].\"\\\",\";\n # AdvisorFirstName\n print \"\\\"\".$person['firstname'].\"\\\",\";\n # AdvisorDegree\n print \"\\\"\".$person['degree'].\"\\\",\";\n $diss = find_dissertation_by_person($pid);\n if ($diss){\n # AdvisorYear\n print \"\\\"\".$diss['completedyear'].\"\\\",\";\n # AdvisorDiscipline\n $disc = find_discipline($diss['discipline_id']);\n print \"\\\"\".$disc['title'].\"\\\",\";\n # AdvisorSchool\n $school = find_school($diss['school_id']);\n print \"\\\"\".$school['fullname'].\"\\\",\";\n # AdvisorCountry\n print \"\\\"\".$school['country'].\"\\\"\";\n }\n else{\n # no dissertation for this person\n print \"\\\"\\\",\";\n print \"\\\"\\\",\";\n print \"\\\"\\\",\";\n print \"\\\"\\\"\";\n }\n print \"\\n\";\n\n }\n }\n echo \"
            \\n\";\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"lis_profsnotfromlis\":\n\n if (is_admin())\n {\n\n echo \"

            LIS Professors without LIS Dissertations

            \\n\";\n\n # and then once the data collection is done\n # cassidy wants a list of all the people who were advisors and committee\n # members for lis, but were not themselves lis\n\n # get list of LIS dissertations\n $query = \"SELECT\n d.id\n FROM\n dissertations d\n WHERE\n d.discipline_id = '1'\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $lis_dissertations[] = $line['id'];\n }\n # get advisors for each diss\n $advisors = array();\n foreach ($lis_dissertations as $id){\n $query = \"SELECT person_id\n FROM advisorships\n WHERE dissertation_id = $id\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $advisors[] = $line['person_id'];\n }\n }\n # get committeeships for each diss\n $committeemembers = array();\n foreach ($lis_dissertations as $id){\n $query = \"SELECT person_id\n FROM committeeships\n WHERE dissertation_id = $id\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $committeemembers[] = $line['person_id'];\n }\n }\n $total = array_merge($advisors,$committeemembers);\n $unique = array_unique($total);\n\n $unique_list = implode(\",\",$unique);\n $listed = array();\n $query = \"SELECT person_id\n FROM dissertations\n WHERE\n person_id IN ($unique_list)\n AND\n discipline_id = '1'\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $listed[] = $line['person_id'];\n }\n $notlisted = array_diff($unique,$listed);\n\n # print them out\n echo \"

            \\n\";\n $count = 0;\n foreach($notlisted as $pid){\n $count++;\n print \"$count. \";\n print get_person_link($pid);\n print \"
            \\n\";\n }\n if ($count == 0)\n {\n print \" - None\";\n }\n echo \"

            \\n\";\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"lis_nocommittee\":\n\n if (is_admin())\n {\n\n echo \"

            LIS Dissertations with no committee

            \\n\";\n\n # get list of LIS dissertations\n $query = \"SELECT\n d.id\n FROM\n dissertations d\n WHERE\n d.discipline_id = '1'\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $lis_dissertations[] = $line['id'];\n }\n # get advisors for each diss\n $advisors = array();\n foreach ($lis_dissertations as $id){\n $query = \"SELECT count(*) as howmany\n FROM advisorships\n WHERE dissertation_id = $id\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n if ($line['howmany'] > 0){$hascomm[] = $id;};\n }\n }\n # get committeeships for each diss\n $committeemembers = array();\n foreach ($lis_dissertations as $id){\n $query = \"SELECT count(*) as howmany\n FROM committeeships\n WHERE dissertation_id = $id\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n if ($line['howmany'] > 0){$hascomm[] = $id;};\n }\n }\n $unique = array_unique($hascomm);\n $nocomm = array_diff($lis_dissertations,$unique);\n\n # print them out\n echo \"

            \\n\";\n $count = 0;\n foreach($nocomm as $did){\n $count++;\n print \"$count. \";\n $d = find_dissertation($did);\n print get_person_link($d['person_id']);\n print \"
            \\n\";\n }\n if ($count == 0)\n {\n print \" - None\";\n }\n echo \"

            \\n\";\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"lis_profs_with_mpact\":\n\n if (is_admin())\n {\n echo \"

            LIS Professors With MPACT

            \\n\";\n \n # advisors or committee members\n # that served on an lis dissertation\n\n\n # get list of LIS dissertations\n $query = \"SELECT\n d.id\n FROM\n dissertations d\n WHERE\n d.discipline_id = '1'\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $lis_dissertations[] = $line['id'];\n }\n \n # get advisors for each diss\n $advisors = array();\n foreach ($lis_dissertations as $id){\n $query = \"SELECT person_id\n FROM advisorships\n WHERE dissertation_id = $id\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $advisors[] = $line['person_id'];\n }\n }\n\n # get committeeships for each diss\n $committeemembers = array();\n foreach ($lis_dissertations as $id){\n $query = \"SELECT person_id\n FROM committeeships\n WHERE dissertation_id = $id\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $committeemembers[] = $line['person_id'];\n }\n }\n\n $total = array_merge($advisors,$committeemembers);\n\n $unique = array_unique($total);\n\n echo \"
            \\n\";\n          echo \"Count|Name|Year|A|C|A+C|T\\n\";\n          foreach ($unique as $prof){\n            $mpact = mpact_scores($prof);\n            $person = find_person($prof);\n            $dissertation = find_dissertation_by_person($prof);\n            # count\n            $count += 1;\n            echo \"$count\";\n            echo \"|\";\n            # name\n            echo $person['fullname'];\n            echo \"|\";\n            # year\n            echo $dissertation['completedyear'];\n            echo \"|\";\n            # a\n            echo $mpact['A'];\n            echo \"|\";\n            # c\n            echo $mpact['C'];\n            echo \"|\";\n            # a+c\n            echo $mpact['AC'];\n            echo \"|\";\n            # t\n            echo $mpact['T'];\n            echo \"\\n\";\n          }\n          echo \"
            \\n\";\n }\n\n break;\n\n ###############################################\n case \"lis_profs_summary\":\n \n if (is_admin())\n {\n echo \"

            LIS Professors Summary

            \\n\";\n \n # advisors or committee members\n # that served on an lis dissertation\n\n echo \"\\n\";\n\n # get list of LIS dissertations\n $query = \"SELECT\n d.id\n FROM\n dissertations d\n WHERE\n d.discipline_id = '1'\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $lis_dissertations[] = $line['id'];\n }\n echo \"\\n\";\n \n # get advisors for each diss\n $advisors = array();\n foreach ($lis_dissertations as $id){\n $query = \"SELECT person_id\n FROM advisorships\n WHERE dissertation_id = $id\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $advisors[] = $line['person_id'];\n }\n }\n echo \"\\n\";\n\n # get committeeships for each diss\n $committeemembers = array();\n foreach ($lis_dissertations as $id){\n $query = \"SELECT person_id\n FROM committeeships\n WHERE dissertation_id = $id\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $committeemembers[] = $line['person_id'];\n }\n }\n echo \"\\n\";\n\n $total = array_merge($advisors,$committeemembers);\n echo \"\\n\";\n\n $unique = array_unique($total);\n echo \"\\n\";\n\n $unique_list = implode(\",\",$unique);\n $known = array();\n $query = \"SELECT person_id\n FROM dissertations\n WHERE\n person_id IN ($unique_list)\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $known[] = $line['person_id'];\n }\n echo \"\\n\";\n echo \"\\n\";\n\n $query = \"SELECT count(*) as howmany\n FROM dissertations\n WHERE\n person_id IN ($unique_list)\n AND\n discipline_id != 16\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $howmany = $line['howmany'];\n }\n echo \"\\n\";\n\n $query = \"SELECT count(*) as howmany\n FROM dissertations\n WHERE\n person_id IN ($unique_list)\n AND\n completedyear != 0000\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $howmany = $line['howmany'];\n }\n echo \"\\n\";\n\n $query = \"SELECT count(*) as howmany\n FROM dissertations\n WHERE\n person_id IN ($unique_list)\n AND\n completedyear != 107\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $howmany = $line['howmany'];\n }\n echo \"\\n\";\n\n echo \"
            Total LIS Dissertations\".count($lis_dissertations).\"
            Total LIS Dissertation Advisorships\";\n echo count($advisors);\n echo \"
            Total LIS Dissertation Committeeships\";\n echo count($committeemembers);\n echo \"
            Total LIS Dissertation Advisorships and Committeeships:\";\n echo count($total);\n echo \"
            Total number of unique advisor/committee members on LIS dissertations:\";\n\n echo count($unique);\n echo \"
            \";\n echo \"Subset of \".count($unique).\" without a listed dissertation:\";\n echo count(array_diff($unique,$known));\n echo \"
            Subset of \".count($unique).\" with a listed dissertation:\";\n echo count($known);\n echo \"
            - Subset of \".count($known).\" with known discipline:\";\n echo $howmany;\n echo \"
            - Subset of \".count($known).\" with known year:\";\n echo $howmany;\n echo \"
            - Subset of \".count($known).\" with known school:\";\n echo $howmany;\n echo \"
            \\n\";\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"lis_allyears\":\n\n if (is_admin())\n {\n echo \"

            LIS, Graduates By Year

            \\n\";\n print \"
            \\n\";\n\n            # get list of dissertations\n            $query = \"SELECT\n                      d.id, d.person_id, d.completedyear\n                    FROM\n                      dissertations d\n                    WHERE\n                      d.discipline_id = '1'\n                    ORDER BY\n                      d.completedyear ASC,\n                      d.school_id ASC\n                    \";\n            $result = mysql_query($query) or die(mysql_error());\n            $schools = array();\n            $count = 0;\n            while ( $line = mysql_fetch_array($result)) {\n              $dissertation = find_dissertation($line['id']);\n              $person = find_person($line['person_id']);\n              $schoolinfo = find_persons_school($line['person_id']);\n              $count++;\n              print $count;\n              print \"|\";\n              print $line['completedyear'];\n              print \"|\";\n              print $schoolinfo['school'];\n              print \"|\";\n              print $person['fullname'];\n#              print \"|\";\n#              print $dissertation['title'];\n#              print \"|\";\n#              print $dissertation['abstract'];\n              print \"\\n\";\n            }\n\n            print \"
            \\n\";\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"lis_history\":\n\n if (is_admin())\n {\n echo \"

            LIS Dissertations by School by Year

            \\n\";\n\n $firstyear = 1920;\n $lastyear = 2008;\n\n print \"
            \\n\";\n            print \"school|\";\n            for ($i = $firstyear; $i <= $lastyear; $i++)\n            {\n                print \"$i|\";\n            }\n            print \"\\n\";\n\n            # get list of schools (all of them)\n            $query = \"SELECT\n                    s.id, s.fullname\n                    FROM\n                      schools s\n                    ORDER BY\n                      s.fullname\n                    \";\n            $result = mysql_query($query) or die(mysql_error());\n            $schools = array();\n            while ( $line = mysql_fetch_array($result)) {\n              $schools[] = $line;\n            }\n            foreach ($schools as $s)\n            {\n              # loop through each school and find count by year\n              $query = \"SELECT\n                    d.id, d.person_id, d.completedyear, COUNT(d.completedyear) AS yeartotal\n                    FROM\n                      dissertations d\n                    WHERE\n                      d.discipline_id = '1' AND\n                      d.school_id = '\".$s['id'].\"'\n                    GROUP BY\n                      d.completedyear\n                  \";\n              $result = mysql_query($query) or die(mysql_error());\n\n              print $s['fullname'].\"|\";\n              $d = array();\n              while ( $line = mysql_fetch_array($result)) {\n                $d[$s['id']][$line['completedyear']] = $line['yeartotal'];\n              }\n\n              # walk through all years, and print out counts for this school\n              for ($i = $firstyear; $i <= $lastyear; $i++)\n              {\n                if ($d[$s['id']][$i] > 0)\n                  print $d[$s['id']][$i].\"|\";\n                else\n                  print \"0|\";\n              }\n              print \"\\n\";\n            }\n\n            print \"
            \";\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"lis_incomplete\":\n\n echo \"

            Incomplete LIS Dissertation Listings

            \\n\";\n\n $discipline_id = 1; # hard coded for LIS\n $schools = find_schools($discipline_id);\n\n foreach ($schools as $one => $two)\n {\n\n $year_conferred = array();\n $degree_status = array();\n\n $query = \"SELECT d.person_id, d.completedyear, d.status\n FROM\n dissertations d,\n schools s,\n people p,\n names n\n WHERE\n s.id = '$one' AND\n d.discipline_id = '$discipline_id' AND\n d.school_id = s.id AND\n d.person_id = p.id AND\n p.preferred_name_id = n.id AND\n d.status < 4\n ORDER BY\n s.id ASC, d.completedyear ASC, n.lastname ASC, n.firstname ASC\n \";\n\n $result = mysql_query($query) or die(mysql_error());\n $resultcount = 0;\n\n while ( $line = mysql_fetch_array($result)) {\n $resultcount++;\n extract($line);\n $year_conferred[$person_id] = $completedyear;\n $degree_status[$person_id] = $status;\n }\n\n if ($resultcount > 0)\n {\n echo \"

            $two

            \\n\";\n }\n\n $incompletecount = 0;\n echo \"\";\n foreach ($year_conferred as $person => $year)\n {\n $incompletecount++;\n $printme = \"\\n\";\n $printme .= \"\\n\";\n\n $printme .= \"\\n\";\n $printme .= \"\\n\";\n\n echo $printme;\n }\n echo \"
            $incompletecount. \";\n $printme .= \"\".get_person_link($person).\" ($year)\".$statuscodes[$degree_status[$person]].\"
            \";\n\n }\n echo \"

            \";\n\n break;\n\n ###############################################\n case \"all_edges\":\n\n if (is_admin())\n {\n echo \"

            All Dissertations and Mentor Relationships

            \\n\";\n\n print \"
            \\n\";\n            print \"mentor|role|protege|year|school\\n\";\n\n            # each dissertation\n            $query = \"SELECT id, person_id, completedyear, school_id FROM dissertations\";\n            $result = mysql_query($query) or die(mysql_error());\n            while ( $line = mysql_fetch_array($result)) {\n              extract($line);\n              $student = find_person($person_id);\n              $query2 = \"SELECT fullname as schoolname FROM schools WHERE id = '$school_id'\";\n              $result2 = mysql_query($query2) or die(mysql_error());\n              $line2 = mysql_fetch_array($result2);\n              extract($line2);\n              print $student['fullname'].\"|dissertation|null|$completedyear|$schoolname\\n\";\n              # get advisorships\n              $advisors = find_advisors_for_person($person_id);\n              foreach ($advisors as $mentor_id){\n                $mentor = find_person($mentor_id);\n                print $mentor['fullname'].\"|advisorship|\".$student['fullname'].\"|$completedyear|$schoolname\\n\";\n              }\n              # get committeeships\n              $committee = find_committee_for_person($person_id);\n              foreach ($committee as $mentor_id){\n                $mentor = find_person($mentor_id);\n                print $mentor['fullname'].\"|committeeship|\".$student['fullname'].\"|$completedyear|$schoolname\\n\";\n              }\n            }\n            print \"
            \";\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"citation_correlation\":\n\n if (is_admin())\n {\n echo \"

            Citation Correlation Data

            \\n\";\n\n $correlated_ids = array(\n 953,\n 2098,\n# 5086, bc\n 3659,\n# 1329, dalhousie\n 5087,\n 478,\n 3094,\n 3497,\n 4784,\n 1250,\n 5088,\n 5089,\n 5090,\n 4657,\n# 5091, mcdowell, not phd yet\n 5092,\n 5093,\n 5094,\n 2668,\n 4076,\n 2683,\n 3978,\n 2425,\n 3645,\n 2660,\n 2233,\n 2665,\n 1310,\n 2548,\n 2708,\n 2592,\n 4648,\n 5095,\n 5096,\n 4654,\n 5097,\n 5098,\n 1234,\n 1299,\n 1294,\n 3062,\n 3110,\n 1283,\n 1220,\n 874,\n 584,\n 3127,\n 1142,\n 3116,\n 5099,\n 5100,\n 1025,\n 486,\n 3130,\n 1321,\n 5101,\n 4502,\n 5102,\n 535,\n 5160, # koohang\n 2673,\n 5103,\n 5104,\n 1950,\n 3972,\n 3278,\n 5105,\n 3571,\n 5106,\n 3994,\n 1504,\n 4181,\n 3140,\n 2323, # benoit added\n 5107,\n 800,\n 4438,\n 5108,\n 5109,\n 4760,\n 2570,\n 1866,\n 3238,\n 1846,\n 1806,\n 2527,\n 3703,\n 4758,\n 3683,\n 3846,\n 2603,\n 4011,\n 2343,\n 2329,\n 5110,\n 5111,\n 4706,\n 2761,\n 1413,\n 3028,\n 3590,\n 3668,\n 2883,\n 3063,\n 3091,\n 1705,\n 3031,\n# gary again 486,\n 3979,\n 3018,\n 1855,\n 3409,\n 2747,\n 3093,\n 3065,\n 3060,\n 1685,\n 2114,\n 5112,\n# moore rm 5113,\n 2309,\n# liu rm 2215,\n 4086,\n 4013,\n 1573\n );\n\n echo \"\\n\";\n echo \"\n \n \n \n \n \n \n \n \n \n \\n\";\n $counter = 0;\n foreach ($correlated_ids as $one)\n {\n $counter++;\n echo \"\";\n echo \"\";\n echo \"\";\n $scores = mpact_scores($one);\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\\n\";\n }\n echo \"
            -NameACA+CFMIFMEFMI/(A+C)FME/(A+C)
            $counter.\";\n echo get_person_link($one);\n echo \"\".$scores['A'].\"\".$scores['C'].\"\".$scores['AC'].\"\".$scores['FMI'].\"\".$scores['FME'].\"\".$scores['FMIdivFULL'].\"\".$scores['FMEdivFULL'].\"
            \\n\";\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"top_a\":\n case \"top_c\":\n case \"top_ac\":\n case \"top_g\":\n case \"top_td\":\n case \"top_w\":\n case \"top_t\":\n case \"top_ta\":\n\n $list_type = strtoupper(substr($_GET['op'],4));\n echo \"

            Top \";\n if ($list_type == \"TD\"){echo \"TD\";}\n else if ($list_type == \"TA\"){echo \"TA\";}\n else if ($list_type == \"AC\"){echo \"A+C\";}\n else {echo $list_type;}\n echo \" List

            \\n\";\n $score_type = strtolower($list_type).\"_score\";\n $people = find_all_people();\n foreach ($people as $p)\n {\n $scores[$p] = find_mpact_score($p,$score_type);\n }\n # zero out indecipherables\n $scores[28] = 0;\n $scores[391] = 0;\n asort($scores);\n $scores = array_reverse($scores, true);\n $top = narray_slice($scores, 0, 100); #calls custom function, end of mpact_include (passes true)\n $count = 0;\n $lasttotal = 0;\n echo \"\\n\";\n foreach ($top as $one => $two)\n {\n $count++;\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\\n\";\n $lasttotal = $two;\n }\n echo \"
            \";\n if ($two != $lasttotal){echo $count.\".\";}\n echo \"\";\n echo get_person_link($one);\n echo \"\";\n echo $two;\n echo \"
            \\n\";\n break;\n\n ###############################################\n case \"create_discipline\":\n\n if (is_admin())\n {\n echo \"

            Creating a New Discipline

            \\n\";\n\n echo \"

            \";\n\n echo \"

            \\n\";\n echo \"\\n\";\n\n echo \"\";\n echo \"\";\n\n\n echo \"\";\n echo \"\";\n echo \"\";\n\n echo \"
            Title
            \";\n\n echo \"\";\n echo \"
            \";\n\n echo \"

            \";\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"edit_discipline\":\n\n if (is_admin())\n {\n if (!$_GET['id']){action_box(\"No ID given.\");}\n elseif (!is_empty_discipline($_GET['id']))\n {\n action_box(\"Discipline must be empty to edit...\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_disciplines\");\n }\n else{\n \n $query = \"SELECT title FROM disciplines WHERE id=\".$_GET['id'];\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n extract($line);\n }\n\n echo \"

            Editing a Discipline

            \\n\";\n\n echo \"

            \";\n\n echo \"

            \\n\";\n echo \"\\n\";\n echo \"\\n\";\n\n echo \"\";\n echo \"\";\n\n\n echo \"\";\n echo \"\";\n echo \"\";\n\n echo \"
            Title
            \";\n\n echo \"\";\n echo \"
            \";\n\n echo \"

            \";\n }\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"create_school\":\n\n if (is_admin())\n {\n echo \"

            Creating a New School

            \\n\";\n\n echo \"

            \";\n\n echo \"

            \\n\";\n echo \"\\n\";\n\n echo \"\";\n echo \"\";\n\n\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n\n echo \"
            FullnameCountry
            \";\n\n echo \"\";\n echo \"
            \";\n\n echo \"

            \";\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"edit_school\":\n\n if (is_admin())\n {\n if (!$_GET['id']){action_box(\"No ID given.\");}\n elseif (!is_empty_school($_GET['id']))\n {\n action_box(\"School must be empty to edit...\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_schools\");\n }\n else{\n \n $query = \"SELECT fullname, country FROM schools WHERE id=\".$_GET['id'];\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n extract($line);\n }\n\n echo \"

            Editing a School

            \\n\";\n\n echo \"

            \";\n\n echo \"

            \\n\";\n echo \"\\n\";\n echo \"\\n\";\n\n echo \"\";\n echo \"\";\n\n\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n\n echo \"
            FullnameCountry
            \";\n\n echo \"\";\n echo \"
            \";\n\n echo \"

            \";\n }\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"create_person\":\n\n if (is_admin())\n {\n echo \"

            Creating a New Person

            \\n\";\n\n echo \"

            \";\n\n echo \"

            \\n\";\n echo \"\\n\";\n\n echo \"\";\n echo \"\";\n\n\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n\n echo \"
            FirstMiddleLastSuffixDegree
            \";\n echo \"\\n\";\n echo \"
            \";\n\n echo \"\";\n echo \"
            \";\n\n echo \"

            \";\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"add_mentor\":\n\n if (is_admin())\n {\n echo \"

            Add a New Person to the Database

            \\n\";\n\n echo \"

            Adding a Mentor

            \\n\";\n\n echo \"
            \\n\";\n echo \"\\n\";\n echo \"\\n\";\n\n echo \"

            \";\n\n echo \"Mentor Type:
            \\n\";\n echo \" Advisor
            \\n\";\n echo \" Committee Member\\n\";\n echo \"

            \\n\";\n\n echo \"Mentor:
            \\n\";\n echo \"\\n\";\n\n echo \"

            \\n\";\n\n echo \"Student:
            \\n\". get_person_link($_GET['id']);\n echo \"

            \\n\";\n\n echo \"\";\n\n echo \"

            \";\n echo \"
            \";\n\n draw_tree($_GET['id']);\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"add_student\":\n\n if (is_admin())\n {\n echo \"

            Add a New Person to the Database

            \\n\";\n\n echo \"

            Adding a Student

            \\n\";\n\n echo \"
            \\n\";\n echo \"\\n\";\n echo \"\\n\";\n\n echo \"

            \";\n\n echo \"Mentor Type:
            \\n\";\n echo \" Advisor
            \\n\";\n echo \" Committee Member\\n\";\n echo \"

            \\n\";\n \n echo \"Mentor:
            \\n\". get_person_link($_GET['id']);\n echo \"

            \\n\";\n \n\n echo \"Student:
            \\n\";\n echo \"\\n\";\n\n echo \"

            \\n\";\n echo \"\";\n\n echo \"

            \";\n echo \"
            \";\n\n draw_tree($_GET['id']);\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n\n\n ###############################################\n case \"remove_mentor\":\n\n if (is_admin())\n {\n echo \"

            Removing a Mentor

            \\n\";\n\n echo \"
            \\n\";\n echo \"\\n\";\n echo \"\\n\";\n echo \"\\n\";\n echo \"\\n\";\n\n echo \"

            \";\n\n echo \"Are you sure you want to remove this mentor relationship?

            \\n\";\n if ($_GET['type'] == \"A\"){echo \"Advisor: \";}\n if ($_GET['type'] == \"C\"){echo \"Commitee Member: \";}\n echo get_person_link(intval($_GET['mentor_id'])).\"
            \\n\";\n echo \"Student: \".get_person_link(intval($_GET['student_id'])).\"
            \\n\";\n echo \"
            \\n\";\n\n echo \"\";\n echo \" If NOT, please go BACK\";\n\n echo \"

            \";\n echo \"
            \";\n\n draw_tree(intval($_GET['student_id']));\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"add_url\";\n\n if (is_admin())\n {\n echo \"

            Adding a Reference URL

            \\n\";\n\n echo \"
            \\n\";\n echo \"\\n\";\n echo \"\\n\";\n\n echo \"

            \";\n\n echo \"\\n\";\n echo \"\\n\";\n echo \"\\n\";\n echo \"
            URL:
            Description:
            \\n\";\n\n echo \"\";\n\n echo \"

            \";\n echo \"
            \";\n\n draw_tree(intval($_GET['id']));\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"edit_url\";\n\n if (is_admin())\n {\n $url = find_url(intval($_GET['id']));\n echo \"

            Editing a Reference URL

            \\n\";\n\n echo \"
            \\n\";\n echo \"\\n\";\n echo \"\\n\";\n\n echo \"

            \";\n\n echo \"\\n\";\n echo \"\\n\";\n echo \"\\n\";\n echo \"\\n\";\n echo \"
            URL:
            Description:
            Last Updated:\".$url['updated_at'].\"
            \\n\";\n\n echo \"\";\n\n echo \"

            \";\n echo \"
            \";\n\n draw_tree($url['person_id']);\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"delete_url\";\n\n if (is_admin())\n {\n $url = find_url(intval($_GET['id']));\n echo \"

            Deleting a Reference URL

            \\n\";\n\n echo \"
            \\n\";\n echo \"\\n\";\n echo \"\\n\";\n\n echo \"

            \";\n\n echo \"Are you sure you want to delete this Reference URL?

            \\n\";\n echo \"\\n\";\n echo \"\\n\";\n echo \"\\n\";\n echo \"\\n\";\n echo \"
            URL:\".$url['url'].\"
            Description:\".$url['description'].\"
            Last Updated:\".$url['updated_at'].\"
            \\n\";\n echo \"
            \\n\";\n\n echo \"\";\n echo \" If NOT, please go BACK\";\n\n echo \"

            \";\n echo \"
            \";\n\n draw_tree($url['person_id']);\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"edit_degree\":\n\n if (is_admin())\n {\n if (!$_GET['id']){action_box(\"No ID given.\");}\n else\n {\n\n $person = find_person($_GET['id']);\n\n echo \"

            Editing a Degree

            \";\n echo \"

            \";\n\n echo \"

            \";\n echo \"\";\n echo \"\";\n\n\n echo \"\";\n echo \"\";\n\n\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n\n echo \"
            NameDegree
            \".$person['fullname'].\"\";\n echo \"\\n\";\n echo \"
            \";\n\n echo \"\";\n\n echo \"
            \";\n\n echo \"

            \";\n\n\n echo \"
            \";\n draw_tree($_GET['id']);\n echo \"
            \";\n\n\n\n }\n }\n else\n {\n not_admin();\n }\n\n break;\n\n\n ###############################################\n case \"add_name\":\n\n if (is_admin())\n {\n if (!$_GET['id']){action_box(\"No ID given.\");}\n else\n {\n\n $person = find_person($_GET['id']);\n\n echo \"

            Adding an Alias

            \";\n echo \"

            \";\n\n echo \"

            \";\n echo \"\";\n echo \"\";\n \n\n echo \"\";\n echo \"\";\n\n\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n\n echo \"
            FirstMiddleLastSuffix
            \";\n\n echo \"\";\n\n echo \"
            \";\n\n echo \"

            \";\n\n\n echo \"
            \";\n draw_tree($_GET['id']);\n echo \"
            \";\n\n\n\n }\n }\n else\n {\n not_admin();\n }\n \n break;\n \n ###############################################\n case \"edit_name\":\n\n if (is_admin())\n {\n if (!$_GET['id']){action_box(\"No ID given.\");}\n else\n {\n\n $person = find_person($_GET['id']);\n\n echo \"

            Editing a Name

            \";\n echo \"

            \";\n\n echo \"

            \";\n echo \"\";\n echo \"\";\n echo \"\";\n\n\n echo \"\";\n echo \"\";\n\n\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n\n echo \"
            FirstMiddleLastSuffix
            \";\n\n echo \"\";\n\n echo \"
            \";\n\n echo \"

            \";\n\n\n echo \"
            \";\n draw_tree($_GET['id']);\n echo \"
            \";\n\n\n\n }\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"create_dissertation\":\n\n if (is_admin())\n {\n\n $disciplines = find_disciplines();\n $schools = find_schools();\n\n if (!$_GET['person_id']){action_box(\"No ID given.\");}\n else\n {\n\n $person = find_person($_GET['person_id']);\n if (!$person)\n {\n action_box(\"Person not found.\");\n }\n else{\n\n echo \"

            CREATE DISSERTATION

            \\n\";\n\n echo \"
            \";\n echo \"\";\n echo \"\";\n\n echo \"

            \";\n echo get_person_link($person['id']);\n echo \"
            \";\n\n echo \"Degree: \\n\";\n echo \"
            \";\n\n echo \"Status: \\n\";\n echo \"
            \";\n\n echo \"Discipline: \\n\";\n echo \"
            \";\n\n\n echo \"School: \";\n echo \"\\n\";\n echo \"
            Year:\\n\";\n echo \"
            \";\n echo \"Title:

            \";\n echo \"Abstract:

            \";\n echo \"\";\n echo \"

            \";\n\n echo \"
            \";\n\n echo \"

            \";\n echo \"Currently:\";\n echo \"

            \";\n echo \"
            \";\n draw_tree($person['id']);\n echo \"
            \";\n }\n\n }\n }\n else\n {\n not_admin();\n }\n\n break;\n\n\n ###############################################\n case \"edit_dissertation\":\n\n if (is_admin())\n {\n if (!$_GET['id']){action_box(\"No ID given.\");}\n else\n {\n\n $disciplines = find_disciplines();\n $schools = find_schools();\n $dissertation = find_dissertation(intval($_GET['id']));\n if (!$dissertation)\n {\n action_box(\"Dissertation not found.\");\n }\n else{\n \n $person = find_person($dissertation['person_id']);\n\n echo \"

            EDIT DISSERTATION DETAILS

            \\n\";\n\n echo \"
            \";\n echo \"\";\n echo \"\";\n echo \"\";\n\n echo \"

            \";\n echo get_person_link($person['id']);\n echo \"
            \";\n \n echo \"Degree: \\n\";\n echo \"
            \";\n\n echo \"Status: \\n\";\n echo \"
            \";\n\n echo \"Discipline: \\n\";\n echo \"
            \";\n\n echo \"School: \\n\";\n\n echo \"
            Year:\\n\";\n echo \"
            \";\n echo \"Title:

            \";\n echo \"Abstract:

            \";\n echo \"Admin Notes:

            \";\n echo \"\";\n echo \"

            \";\n\n echo \"
            \";\n\n echo \"

            \";\n echo \"Currently:\";\n echo \"

            \";\n echo \"
            \";\n draw_tree($person['id']);\n echo \"
            \";\n }\n\n }\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"delete_name\":\n\n if (is_admin())\n {\n if (!$_GET['id']){action_box(\"No ID given.\");}\n else\n {\n\n $person = find_name($_GET['name']);\n\n echo \"

            \";\n\n echo \"Are you sure you want to delete this name?\";\n\n echo \"

            \\n\";\n echo \"\\n\";\n echo \"\\n\";\n echo \"\";\n \n echo \"

            \";\n echo \"[ \".$person['firstname'].\" \".$person['middlename'].\" \".$person['lastname'].\" \".$person['suffix'].\" ]
            \"; \n echo \"

            \";\n\n\n echo \"

            \";\n echo \"\";\n echo \"   Cancel

            \";\n\n echo \"
            \";\n\n echo \"

            \";\n\n\n\n\n }\n }\n else\n {\n not_admin();\n }\n\n break;\n \n ###############################################\n case \"set_preferred_name\":\n\n if (is_admin())\n {\n\n set_preferred_name($_GET['id'],$_GET['name']);\n\n action_box(\"Preferred Name Selected\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_tree&id=\".$_GET['id']);\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"recalculate_mpact\":\n\n if (is_admin()){\n\n # recalculate MPACT scores for passed person id\n calculate_scores($_GET['id']);\n\n action_box(\"MPACT Scores Recalculated\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_tree&id=\".$_GET['id']);\n\n }\n else\n {\n not_admin();\n } \n\n break;\n\n ###############################################\n case \"show_orphans\":\n\n if (is_admin())\n {\n\n $orphans = find_orphans();\n\n echo \"

            Orphans

            \\n\";\n\n echo \"

            \\n\";\n $counter = 0;\n foreach ($orphans as $orphan)\n {\n $counter++;\n echo $counter.\" \";\n echo get_person_link($orphan['person_id']);\n echo \" (Delete from Database)\";\n echo \"
            \\n\";\n }\n if ($counter < 1){echo \" - No orphans at this time.\";}\n echo \"

            \\n\";\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"delete_person\":\n\n if (is_admin())\n {\n if (!$_GET['id']){action_box(\"No ID given.\");}\n else\n {\n\n if (is_orphan($_GET['id']))\n {\n echo \"

            \";\n\n echo \"Are you sure you want to delete this person?\";\n\n echo \"

            \\n\";\n echo \"\\n\";\n echo \"\\n\";\n\n echo \"

            \";\n echo get_person_link($_GET['id']);\n echo \"

            \";\n\n\n echo \"

            \";\n echo \"

            \\n\";\n echo \"\";\n echo \"   Cancel

            \";\n\n echo \"
            \";\n\n echo \"

            \";\n }\n else\n {\n action_box(\"This person cannot be deleted.\");\n }\n }\n }\n else\n {\n not_admin();\n }\n\n break;\n\n\n ###############################################\n case \"show_disciplines\":\n\n $statustotals = array(0,0,0,0,0);\n $disciplines = find_disciplines();\n $disciplinecounts = find_discipline_counts();\n\n if (is_admin()){\n echo \"

            Add a New Discipline to the Database

            \\n\";\n }\n\n echo \"

            Disciplines Represented Across All Schools

            \\n\";\n\n echo \"

            \\n\";\n echo \"\\n\";\n echo \"\";\n echo \"\";\n foreach (range(0,4) as $one)\n {\n echo \"\";\n }\n echo \"\";\n foreach ($disciplines as $one => $two)\n {\n echo \"\";\n echo \"\";\n $statuscounts = find_discipline_statuses($one);\n foreach (range(0,4) as $three)\n {\n $statustotals[$three] += $statuscounts[$three];\n if (!isset($disciplinecounts[$one]) || $disciplinecounts[$one]==0)\n {\n $fraction = 0;\n }\n else\n {\n $fraction = 100*$statuscounts[$three]/intval($disciplinecounts[$one]);\n }\n echo \"\";\n }\n echo \"\\n\";\n }\n # summary line\n echo \"\";\n echo \"\";\n echo \"\";\n foreach (range(0,4) as $three)\n {\n $fraction = 100*$statustotals[$three]/array_sum($disciplinecounts);\n echo \"\";\n }\n echo \"\";\n echo \"
            Discipline$statuscodes[$one]
            $two (\".intval($disciplinecounts[$one]).\")\".$statuscounts[$three];\n if ($fraction != 0)\n {\n echo \" (\".sprintf(\"%.1f\",$fraction).\"%)\";\n }\n echo \"
            ------------------
            \";\n echo count($disciplines).\" Disciplines (\".array_sum($disciplinecounts).\" dissertations)\";\n echo \"\".$statustotals[$three];\n if ($fraction != 0)\n {\n echo \" (\".sprintf(\"%.1f\",$fraction).\"%)\";\n }\n echo \"
            \\n\";\n echo \"

            \\n\";\n\n break;\n\n ###############################################\n case \"show_discipline\":\n\n if (!$_GET['id']){action_box(\"No ID given.\");}\n else\n {\n\n $discipline_id = intval($_GET['id']);\n\n # Show Discipline Name\n $query = \"SELECT d.title as disciplinename\n FROM disciplines d\n WHERE\n d.id = '$discipline_id'\n \";\n\n $result = mysql_query($query) or die(mysql_error());\n \n while ( $line = mysql_fetch_array($result)) {\n extract($line);\n }\n\n echo \"

            $disciplinename

            \";\n\n # Show Histograph\n $counts = array();\n echo \"

            \\n\";\n echo \"Dissertations by Year:
            \\n\";\n $query = \"SELECT completedyear, count(*) as disscount FROM dissertations WHERE discipline_id='$discipline_id' GROUP BY completedyear\";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $counts[$line['completedyear']] = $line['disscount'];\n }\n if (count($counts)>0)\n {\n $bigyear = max($counts);\n echo \"\\n\";\n echo \"\\n\";\n foreach ($counts as $one => $two)\n {\n $height=$two*intval(200/$bigyear);\n echo \"\\n\";\n }\n echo \"\";\n echo \"\\n\";\n foreach ($counts as $one => $two)\n {\n echo \"\\n\";\n }\n echo \"\";\n echo \"
            \";\n if ($one%10==0)\n {\n echo $one;\n }\n echo \"
            \\n\";\n }\n echo \"

            \\n\";\n }\n\n $schools = find_schools($discipline_id);\n $dissertation_count = 0;\n $statustotals = array(0,0,0,0,0);\n echo \"

            Schools Represented

            \\n\";\n\n echo \"

            \\n\";\n echo \"\\n\";\n echo \"\";\n echo \"\";\n foreach (range(0,4) as $one)\n {\n echo \"\";\n }\n echo \"\";\n foreach ($schools as $one => $two)\n {\n $statuscounts = find_dept_statuses($one,$discipline_id);\n $dissertation_count += array_sum($statuscounts);\n echo \"\";\n echo \"\";\n foreach (range(0,4) as $three)\n {\n $statustotals[$three] += $statuscounts[$three];\n $fraction = 100*$statuscounts[$three]/array_sum($statuscounts);\n echo \"\";\n }\n echo \"\\n\";\n }\n # summary line\n echo \"\";\n echo \"\";\n echo \"\";\n foreach (range(0,4) as $three)\n {\n\n if (array_sum($statustotals)==0)\n {\n $fraction = 0;\n }\n else\n {\n $fraction = 100*$statustotals[$three]/array_sum($statustotals);\n }\n echo \"\";\n }\n echo \"\";\n echo \"
            School$statuscodes[$one]
            $two (\".array_sum($statuscounts).\")\".$statuscounts[$three];\n if ($fraction != 0)\n {\n echo \" (\".sprintf(\"%.1f\",$fraction).\"%)\";\n }\n echo \"
            ------------------
            \";\n echo count($schools).\" Schools ($dissertation_count dissertations)\";\n echo \"\".$statustotals[$three];\n if ($fraction != 0)\n {\n echo \" (\".sprintf(\"%.1f\",$fraction).\"%)\";\n }\n echo \"
            \\n\";\n echo \"

            \\n\";\n\n # link to edit the discipline name\n if (is_empty_discipline($_GET['id']))\n {\n echo \"

            \";\n echo \"

            Edit Discipline Name

            \\n\";\n }\n\n break;\n\n ###############################################\n case \"show_school\":\n\n if (!$_GET['id']){action_box(\"No ID given.\");}\n else\n {\n\n $school_id = intval($_GET['id']);\n\n # Show School Name\n $query = \"SELECT s.fullname as schoolname, s.country\n FROM schools s\n WHERE\n s.id = '$school_id'\n \";\n\n $result = mysql_query($query) or die(mysql_error());\n \n while ( $line = mysql_fetch_array($result)) {\n extract($line);\n }\n\n echo \"

            $schoolname ($country)

            \";\n\n # Show Histograph\n echo \"

            \\n\";\n echo \"Dissertations by Year:
            \\n\";\n $query = \"SELECT completedyear, count(*) as disscount FROM dissertations WHERE school_id='$school_id' GROUP BY completedyear\";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $counts[$line['completedyear']] = $line['disscount'];\n }\n $bigyear = max($counts);\n echo \"\\n\";\n echo \"\\n\";\n foreach ($counts as $one => $two)\n {\n $height=$two*intval(200/$bigyear);\n echo \"\\n\";\n }\n echo \"\";\n echo \"\\n\";\n foreach ($counts as $one => $two)\n {\n echo \"\\n\";\n }\n echo \"\";\n echo \"
            \";\n if ($one%10==0)\n {\n echo $one;\n }\n echo \"
            \\n\";\n echo \"

            \\n\";\n\n\n $disciplines = find_disciplines($school_id);\n $dissertation_count = 0;\n $statustotals = array(0,0,0,0,0);\n echo \"

            Disciplines Represented

            \\n\";\n\n echo \"

            \\n\";\n echo \"\\n\";\n echo \"\";\n echo \"\";\n foreach (range(0,4) as $one)\n {\n echo \"\";\n }\n echo \"\";\n foreach ($disciplines as $one => $two)\n {\n $statuscounts = find_dept_statuses($school_id,$one);\n $dissertation_count += array_sum($statuscounts);\n echo \"\";\n echo \"\";\n foreach (range(0,4) as $three)\n {\n $statustotals[$three] += $statuscounts[$three];\n $fraction = 100*$statuscounts[$three]/array_sum($statuscounts);\n echo \"\";\n }\n echo \"\\n\";\n }\n # summary line\n echo \"\";\n echo \"\";\n echo \"\";\n foreach (range(0,4) as $three)\n {\n $fraction = 100*$statustotals[$three]/array_sum($statustotals);\n echo \"\";\n }\n echo \"\";\n echo \"
            Discipline$statuscodes[$one]
            $two (\".array_sum($statuscounts).\")\".$statuscounts[$three];\n if ($fraction != 0)\n {\n echo \" (\".sprintf(\"%.1f\",$fraction).\"%)\";\n }\n echo \"
            ------------------
            \";\n echo count($disciplines).\" Disciplines ($dissertation_count dissertations)\";\n echo \"\".$statustotals[$three];\n if ($fraction != 0)\n {\n echo \" (\".sprintf(\"%.1f\",$fraction).\"%)\";\n }\n echo \"
            \\n\";\n echo \"

            \\n\";\n }\n\n # link to edit the school info\n if (is_empty_school($_GET['id']))\n {\n echo \"

            \";\n echo \"

            Edit School Information

            \\n\";\n }\n\n break;\n\n ###############################################\n case \"show_schools\":\n\n $statustotals = array(0,0,0,0,0);\n $schools = find_schools();\n $schoolcounts = find_school_counts();\n\n if (is_admin()){\n echo \"

            Add a New School to the Database

            \\n\";\n }\n echo \"

            Schools Represented Across All Disciplines

            \\n\";\n\n echo \"

            \\n\";\n echo \"\\n\";\n echo \"\";\n echo \"\";\n foreach (range(0,4) as $one)\n {\n echo \"\";\n }\n echo \"\";\n foreach ($schools as $one => $two)\n {\n echo \"\";\n echo \"\";\n $statuscounts = find_school_statuses($one);\n foreach (range(0,4) as $three)\n {\n $statustotals[$three] += $statuscounts[$three];\n if (intval($schoolcounts[$one]) == 0){\n $fraction = 0;\n }\n else{\n $fraction = 100*$statuscounts[$three]/intval($schoolcounts[$one]);\n }\n echo \"\";\n }\n echo \"\\n\";\n }\n # summary line\n echo \"\";\n echo \"\";\n echo \"\";\n foreach (range(0,4) as $three)\n {\n $fraction = 100*$statustotals[$three]/array_sum($schoolcounts);\n echo \"\";\n }\n echo \"\";\n echo \"
            School$statuscodes[$one]
            $two (\".intval($schoolcounts[$one]).\")\".$statuscounts[$three];\n if ($fraction != 0)\n {\n echo \" (\".sprintf(\"%.1f\",$fraction).\"%)\";\n }\n echo \"
            ------------------
            \";\n echo count($schools).\" Schools (\".array_sum($schoolcounts).\" dissertations)\";\n echo \"\".$statustotals[$three];\n if ($fraction != 0)\n {\n echo \" (\".sprintf(\"%.1f\",$fraction).\"%)\";\n }\n echo \"
            \\n\";\n echo \"

            \\n\";\n\n break;\n\n ###############################################\n case \"show_department\":\n\n if (!$_GET['d'] || !$_GET['s']){action_box(\"No ID given.\");}\n else\n {\n\n $school_id = $_GET['s'];\n $discipline_id = $_GET['d'];\n \n\n # Show Discipline Name\n $query = \"SELECT d.title as disciplinename\n FROM disciplines d\n WHERE\n d.id = '$discipline_id'\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n extract($line);\n }\n # Show School Name\n $query = \"SELECT s.fullname as schoolname, s.country\n FROM schools s\n WHERE\n s.id = '$school_id'\n \";\n $result = mysql_query($query) or die(mysql_error());\n \n while ( $line = mysql_fetch_array($result)) {\n extract($line);\n }\n\n echo \"\n

            \n $disciplinename\n @\n $schoolname ($country)\n

            \n \";\n\n # Advisor and Committee Activity\n echo \"

            Dissertation Activity and MPACT Scores (click table headings to sort)

            \";\n \n echo \"

            \";\n $theprofs = find_profs_at_dept($school_id,$discipline_id);\n if (count($theprofs)>0)\n {\n $sortedprofs = array();\n $proflist = \"\";\n $query = \"SELECT id FROM people WHERE id IN (\";\n foreach ($theprofs as $prof){$proflist .= \"$prof,\";}\n $proflist = rtrim($proflist, \",\");\n $query .= \"$proflist) ORDER BY ac_score DESC\";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $sortedprofs[] = $line['id'];\n }\n $profcount = 0;\n echo \"\\n\";\n echo \"\n \n \n \n \n \n \n \n \n \n \n \\n\";\n foreach ($sortedprofs as $one)\n {\n echo \"\";\n $profcount++;\n echo \"\";\n echo \"\";\n $scores = mpact_scores($one);\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\\n\";\n }\n echo \"
            -NameACA+CGTTATDW
            $profcount.\";\n echo get_person_link($one);\n echo \"\".$scores['A'].\"\".$scores['C'].\"\".$scores['AC'].\"\".$scores['G'].\"\".$scores['T'].\"\".$scores['TA'].\"\".$scores['TD'].\"\".$scores['W'].\"
            \\n\";\n echo \"

            \";\n }\n else\n {\n echo \"

            - None Listed

            \\n\";\n }\n echo \"
            \";\n\n\n\n\n # Dissertations Conferred\n echo \"

            Dissertations Conferred

            \";\n\n\n\n\n # Show Histograph\n echo \"

            \\n\";\n echo \"Dissertations by Year:
            \\n\";\n $query = \"SELECT completedyear, count(*) as disscount\n FROM dissertations\n WHERE\n school_id='$school_id' AND\n discipline_id=$discipline_id\n GROUP BY\n completedyear\";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $counts[$line['completedyear']] = $line['disscount'];\n }\n echo \"\\n\";\n echo \"\\n\";\n foreach ($counts as $one => $two)\n {\n $height=$two*10;\n echo \"\\n\";\n }\n echo \"\";\n echo \"\\n\";\n foreach ($counts as $one => $two)\n {\n echo \"\\n\";\n }\n echo \"\";\n echo \"
            \";\n if ($one%10==0)\n {\n echo $one;\n }\n echo \"
            \\n\";\n echo \"

            \\n\";\n\n\n\n\n\n $query = \"SELECT d.person_id, d.completedyear, d.status\n FROM\n dissertations d,\n schools s,\n people p,\n names n\n WHERE\n s.id = '$school_id' AND\n d.discipline_id = '$discipline_id' AND\n d.school_id = s.id AND\n d.person_id = p.id AND\n p.preferred_name_id = n.id\n ORDER BY\n d.completedyear ASC, n.lastname ASC, n.firstname ASC \n \";\n\n $result = mysql_query($query) or die(mysql_error());\n\n while ( $line = mysql_fetch_array($result)) {\n extract($line);\n $year_conferred[$person_id] = $completedyear;\n $degree_status[$person_id] = $status;\n }\n\n $schoolcount = 0;\n echo \"

            \";\n foreach ($year_conferred as $person => $year)\n {\n $schoolcount++;\n echo \"
            $schoolcount. \";\n echo get_person_link($person);\n echo \" ($year)\";\n if ($degree_status[$person] < 4)\n {\n echo \" ---------------------------------- \".$statuscodes[$degree_status[$person]];\n }\n }\n echo \"

            \";\n\n }\n\n break;\n \n ###############################################\n default:\n // oops - not supposed to be here\n action_box(\"invalid action\",1);\n }\n }\n else\n {\n\n if (isset($_GET['show']))\n {\n if ($_GET['show'] == \"all\")\n {\n $alphabet_limiter = \"\"; // set it to show everything\n }\n else\n {\n $alphabet_limiter = $_GET['show'];\n }\n\n show_alphabet();\n\n if (is_admin())\n {\n echo \"

            Add a New Person to the Database

            \\n\";\n }\n\n if (is_admin()){\n echo \"
            \";\n echo \"\";\n echo \"\";\n echo \"\";\n }\n\n // GET ALL DISSERTATIONS IN A HASH\n $disciplines = find_disciplines();\n $query = \"SELECT id, person_id, discipline_id FROM dissertations\";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $graduates[$line['person_id']] = $line['discipline_id'];\n }\n\n // LOOP THROUGH ALL PEOPLE FOR THIS LETTER\n echo \"\\n\";\n echo \"\\n\";\n if (is_admin()){echo \"\\n\";}\n echo \"\\n\";\n echo \"\\n\";\n echo \"\\n\";\n echo \"\\n\";\n echo \"\\n\";\n\n $query = \"SELECT n.id, n.firstname,\n n.middlename, n.lastname, n.suffix,\n p.id as person_id\n FROM names n, people p\n WHERE\n n.id = p.preferred_name_id AND\n n.lastname LIKE '\".$alphabet_limiter.\"%'\n ORDER BY n.lastname ASC, n.firstname ASC\n \";\n\n $result = mysql_query($query) or die(mysql_error());\n\n $rowcount = 0;\n while ( $line = mysql_fetch_array($result)) {\n extract($line);\n\n $rowcount++;\n\n echo \"\";\n if (is_admin()){\n echo \"\";\n }\n echo \"\";\n echo \"\";\n $discipline = isset($graduates[$person_id]) ? $disciplines[$graduates[$person_id]] : \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n\n if (is_admin()){\n if ($rowcount % 25 == 0){\n echo \"\";\n }\n }\n\n }\n\n echo \"
            MergeCountLast NameFull NameDissertation Discipline
            $rowcount.$lastname$firstname $middlename $lastname $suffix$discipline
            \\n\";\n\n if (is_admin()){\n echo \"\";\n echo \"
            \";\n }\n\n echo \"

            \\n\";\n\n show_alphabet();\n\n }\n else\n {\n // DISPLAY THE FRONT PAGE\n\n action_box(\"Front Page...\",0.1,\"./\");\n\n }\n\n }\n\n}\n\n\n\n\n\n\n\n\n\n###############################################\n// SOMETHING WAS SUBMITTED - through a form\nelse\n{\n\n if ($_POST['op'] != \"login\"){\n // Display header\n xhtml_web_header();\n }\n\n switch ($_POST['op'])\n {\n ###############################################\n case \"login\";\n\n $host_info = get_environment_info();\n if ($host_info['hostname'] == \"sils\"){\n # no logins here - go to dev server\n action_box(\"No Logins Here...\",2,$_SERVER['SCRIPT_NAME']);\n }\n else{\n # check credentials / start session\n $query = \"SELECT id, username, fullname FROM users\n WHERE username = '\".addslashes($_POST['username']).\"'\n AND password = '\".addslashes($_POST['password']).\"'\";\n $result = mysql_query($query) or die(mysql_error());\n $line = mysql_fetch_array($result);\n if (isset($line['id'])){\n # save cookie info for one week\n setcookie('MPACT_userid',$line['id'],time()+60*60*24*7);\n # redirect\n header(\"Location: \".$_SERVER['SCRIPT_NAME']);\n }\n else{\n // Display header\n xhtml_web_header();\n # incorrect credentials\n action_box(\"Please try again...\",2,$_SERVER['SCRIPT_NAME'].\"?op=login\");\n }\n }\n\n break;\n\n ###############################################\n case \"glossary_edit\";\n if (is_admin())\n {\n\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n $query = \"UPDATE glossary\n SET\n definition = '\".$_POST['definition'].\"'\n WHERE\n id = '\".$_POST['id'].\"'\n \";\n $result = mysql_query($query) or die(mysql_error());\n\n # log it\n mpact_logger(\"updated glossary [\".$_POST['term'].\" (\".$_POST['id'].\")] to (\".$_POST['definition'].\")\");\n\n action_box(\"Definition Saved\",2,$_SERVER['SCRIPT_NAME'].\"?op=glossary\");\n }\n else\n {\n not_admin();\n }\n break;\n\n ###############################################\n case \"merge_confirm\":\n \n if (is_admin()){\n\n echo \"
            \";\n echo \"\";\n echo \"\";\n \n foreach ($_POST['mergers'] as $one)\n {\n echo \"
            \";\n echo \"

            [$one]

            \";\n echo draw_tree( $one );\n echo \"\";\n echo \"
            \";\n } \n\n echo \"\";\n echo \"
            \";\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"search\":\n\n $results = people_search($_POST['q']);\n\n if (count($results) > 0)\n {\n echo \"

            People Search Results for [\".$_POST['q'].\"]:

            \";\n }\n\n echo \"

            \\n\";\n $count = 0;\n foreach ($results as $person_id)\n {\n $count++;\n $schoolinfo = find_persons_school($person_id);\n echo \"$count. \".get_person_link($person_id);\n if ($schoolinfo['completedyear'])\n {\n echo \" - \".$schoolinfo['school'].\" (\".$schoolinfo['completedyear'].\")\";\n }\n echo \"
            \\n\";\n }\n if ($count < 1)\n {\n echo \"

            \\n\";\n echo \"There were no results for [\".$_POST['q'].\"].\";\n if (strlen($_POST['q']) < 2)\n {\n echo \"

            \\n\";\n echo \"Please use at least two characters to search.\";\n }\n else\n {\n if (is_admin()){\n echo \"

            \\n\";\n echo \"

            Add a New Person to the Database

            \\n\";\n }\n }\n echo \"

            \\n\";\n }\n\n echo \"

            \\n\";\n\n break;\n\n ###############################################\n case \"search_title_abstract\":\n\n $results = title_abstract_search($_POST['qta']);\n\n if (count($results) > 0)\n {\n echo \"

            Title/Abstract Search Results for [\".$_POST['qta'].\"]:

            \";\n }\n\n echo \"

            \\n\";\n $count = 0;\n foreach ($results as $person_id)\n {\n $count++;\n $schoolinfo = find_persons_school($person_id);\n echo \"$count. \".get_person_link($person_id);\n if ($schoolinfo['completedyear'])\n {\n echo \" - \".$schoolinfo['school'].\" (\".$schoolinfo['completedyear'].\")\";\n }\n echo \"
            \\n\";\n }\n if ($count < 1)\n {\n echo \"

            \\n\";\n echo \"There were no results for [\".$_POST['qta'].\"].\";\n if (strlen($_POST['qta']) < 2)\n {\n echo \"

            \\n\";\n echo \"Please use at least two characters to search.\";\n }\n else\n {\n if (is_admin()){\n echo \"

            \\n\";\n }\n }\n echo \"

            \\n\";\n }\n\n echo \"

            \\n\";\n\n break;\n\n ###############################################\n case \"search_notes\":\n\n if (is_admin()){\n\n $results = notes_search($_POST['qn']);\n\n if (count($results) > 0)\n {\n echo \"

            Admin Notes Search Results for [\".$_POST['qn'].\"]:

            \";\n }\n\n echo \"

            \\n\";\n $count = 0;\n foreach ($results as $person_id)\n {\n $count++;\n $schoolinfo = find_persons_school($person_id);\n echo \"$count. \".get_person_link($person_id);\n if ($schoolinfo['completedyear'])\n {\n echo \" - \".$schoolinfo['school'].\" (\".$schoolinfo['completedyear'].\")\";\n }\n echo \"
            \\n\";\n }\n if ($count < 1)\n {\n echo \"

            \\n\";\n echo \"There were no results for [\".$_POST['qm'].\"].\";\n if (strlen($_POST['qn']) < 2)\n {\n echo \"

            \\n\";\n echo \"Please use at least two characters to search.\";\n }\n else\n {\n if (is_admin()){\n echo \"

            \\n\";\n }\n }\n echo \"

            \\n\";\n }\n\n echo \"

            \\n\";\n }\n else\n {\n not_admin();\n } \n\n break;\n\n ###############################################\n case \"merge_doit\":\n \n if (is_admin()){\n\n # delete the family tree's dotgraphs of each person\n foreach ($_POST['mergers'] as $one)\n {\n delete_associated_dotgraphs($one);\n }\n\n # pop off one of the people_ids\n $into = array_pop($_POST['mergers']);\n\n # merge each remaining person into the one above\n foreach ($_POST['mergers'] as $one)\n {\n merge_two_people($one,$into);\n }\n\n # recalculate MPACT scores for merged person id\n calculate_scores($into);\n\n action_box(\"Merge was Successful\",2,$_SERVER['SCRIPT_NAME'].\"?show=\".$_POST['show']);\n\n }\n else\n {\n not_admin();\n } \n\n break;\n\n \n ###############################################\n case \"create_discipline\":\n\n if (is_admin()){\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n if ($_POST['title'] == \"\")\n {\n action_box(\"Need to have at least a Discipline Title.\",3,$_SERVER['SCRIPT_NAME'].\"?op=create_discipline\");\n }\n elseif (is_duplicate_discipline($_POST['title']))\n {\n action_box(\"Discipline (\".$_POST['title'].\") already exists.\",3,$_SERVER['SCRIPT_NAME'].\"?op=show_disciplines\");\n }\n else\n {\n \n # Create Discipline\n $query = \"INSERT disciplines\n SET\n title = '\".$_POST['title'].\"'\n \";\n $result = mysql_query($query) or die(mysql_error());\n\n # Get the just created discipline_id\n $query = \"SELECT id as new_discipline_id, title FROM disciplines\n WHERE\n title = '\".$_POST['title'].\"'\n ORDER BY id DESC\n LIMIT 1\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n extract($line);\n }\n # log it\n mpact_logger(\"created discipline[\".$new_discipline_id.\"] (\".$title.\")\");\n\n action_box(\"Discipline Created\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_disciplines\");\n\n }\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"edit_discipline\":\n\n if (is_admin()){\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n if ($_POST['title'] == \"\")\n {\n action_box(\"Need to have at least a Discipline Title.\",3,$_SERVER['SCRIPT_NAME'].\"?op=edit_discipline&id=\".$_POST['discipline_id'].\"\");\n }\n elseif (is_duplicate_discipline($_POST['title']))\n {\n action_box(\"Discipline (\".$_POST['title'].\") already exists.\",3,$_SERVER['SCRIPT_NAME'].\"?op=show_disciplines\");\n }\n else\n {\n\n # Edit Discipline\n $query = \"UPDATE disciplines\n SET\n title = '\".$_POST['title'].\"'\n WHERE\n id = '\".$_POST['discipline_id'].\"'\n \";\n $result = mysql_query($query) or die(mysql_error());\n\n # log it\n mpact_logger(\"edited discipline[\".$_POST['discipline_id'].\"] (\".$_POST['title'].\")\");\n\n action_box(\"Discipline Edited\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_disciplines\");\n\n }\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"create_school\":\n\n if (is_admin()){\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n $_POST = array_map('trim',$_POST);\n\n if ($_POST['fullname'] == \"\" || $_POST['country'] == \"\")\n {\n action_box(\"Need to have at least a School name and Country.\",3,$_SERVER['SCRIPT_NAME'].\"?op=create_school\");\n }\n elseif (is_duplicate_school($_POST['fullname']))\n {\n action_box(\"School (\".$_POST['fullname'].\") already exists.\",3,$_SERVER['SCRIPT_NAME'].\"?op=show_schools\");\n }\n else\n {\n\n # Create School\n $query = \"INSERT schools\n SET\n fullname = '\".$_POST['fullname'].\"',\n country = '\".$_POST['country'].\"'\n \";\n $result = mysql_query($query) or die(mysql_error());\n\n # Get the just created school_id\n $query = \"SELECT id as new_school_id, fullname FROM schools\n WHERE\n fullname = '\".$_POST['fullname'].\"'\n ORDER BY id DESC\n LIMIT 1\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n extract($line);\n }\n # log it\n mpact_logger(\"created school[\".$new_school_id.\"] (\".$fullname.\")\");\n\n action_box(\"School Created\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_schools\");\n\n }\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"edit_school\":\n\n if (is_admin()){\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n if ($_POST['fullname'] == \"\" || $_POST['country'] == \"\")\n {\n action_box(\"Need to have at least a School name and Country.\",3,$_SERVER['SCRIPT_NAME'].\"?op=edit_school&id=\".$_POST['school_id'].\"\");\n }\n elseif (is_duplicate_school($_POST['fullname']))\n {\n action_box(\"School (\".$_POST['fullname'].\") already exists.\",3,$_SERVER['SCRIPT_NAME'].\"?op=show_schools\");\n }\n else\n {\n\n # Edit School\n $query = \"UPDATE schools\n SET\n fullname = '\".$_POST['fullname'].\"',\n country = '\".$_POST['country'].\"'\n WHERE\n id = '\".$_POST['school_id'].\"'\n \";\n $result = mysql_query($query) or die(mysql_error());\n\n # log it\n mpact_logger(\"edited school[\".$_POST['school_id'].\"] (\".$_POST['fullname'].\")\");\n\n action_box(\"School Edited\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_schools\");\n\n }\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"create_person\":\n\n if (is_admin()){\n\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n if ($_POST['lastname'] == \"\")\n {\n action_box(\"Need to have at least a Last Name.\",3,$_SERVER['SCRIPT_NAME'].\"?op=create_person\");\n }\n else\n {\n # Create Name\n $query = \"INSERT names\n SET\n firstname = '\".$_POST['firstname'].\"',\n middlename = '\".$_POST['middlename'].\"',\n lastname = '\".$_POST['lastname'].\"',\n suffix = '\".$_POST['suffix'].\"'\n \";\n $result = mysql_query($query) or die(mysql_error());\n\n # Get the just created name_id\n $query = \"SELECT id as new_name_id FROM names\n WHERE\n firstname = '\".$_POST['firstname'].\"' AND\n middlename = '\".$_POST['middlename'].\"' AND\n lastname = '\".$_POST['lastname'].\"' AND\n suffix = '\".$_POST['suffix'].\"'\n ORDER BY id DESC\n LIMIT 1\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n extract($line);\n }\n\n # Create Person with new_name_id\n $query = \"INSERT people\n SET\n preferred_name_id = '\".$new_name_id.\"',\n degree = '\".$_POST['degree'].\"'\n \";\n $result = mysql_query($query) or die(mysql_error());\n\n # Get the just created person_id\n $query = \"SELECT id as new_person_id FROM people\n WHERE\n preferred_name_id = '\".$new_name_id.\"'\n ORDER BY id DESC\n LIMIT 1\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n extract($line);\n }\n\n # Sync them together with new_person_id\n $query = \"UPDATE names\n SET\n person_id = '\".$new_person_id.\"'\n WHERE\n id = '\".$new_name_id.\"'\n \";\n $result = mysql_query($query) or die(mysql_error());\n\n $after = find_person($new_person_id);\n\n action_box(\"Person Created\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_tree&id=\".$new_person_id);\n\n # log it\n mpact_logger(\"created person[\".$new_person_id.\"] (\".$after['fullname'].\")\");\n\n }\n }\n else\n {\n not_admin();\n }\n\n break;\n\n\n ###############################################\n case \"remove_mentor\":\n\n if (is_admin()){\n\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n if (remove_mentor($_POST['mentor_type'],$_POST['student_id'],$_POST['mentor_id']))\n {\n action_box(\"Mentor Removed\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_tree&id=\".$_POST['student_id']);\n }\n else\n {\n action_box(\"Nope.\");\n }\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n\n ###############################################\n case \"add_mentor\":\n\n if (is_admin()){\n\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n add_mentor($_POST['mentor_type'],$_POST['student_id'],$_POST['mentor_id']);\n\n action_box(\"Mentor Added\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_tree&id=\".$_POST['student_id']);\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n\n ###############################################\n case \"add_student\":\n\n if (is_admin()){\n\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n add_mentor($_POST['mentor_type'],$_POST['student_id'],$_POST['mentor_id']);\n\n action_box(\"Student Added\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_tree&id=\".$_POST['mentor_id']);\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n\n ###############################################\n case \"add_name\":\n \n if (is_admin()){\n\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n $person = find_person($_POST['id']);\n\n $query = \"INSERT names\n SET\n firstname = '\".$_POST['firstname'].\"',\n middlename = '\".$_POST['middlename'].\"',\n lastname = '\".$_POST['lastname'].\"',\n suffix = '\".$_POST['suffix'].\"',\n person_id = '\".$_POST['id'].\"'\n \";\n\n $result = mysql_query($query) or die(mysql_error());\n\n # get the just created name_id\n $query = \"SELECT id as new_name_id FROM names\n WHERE\n firstname = '\".$_POST['firstname'].\"' AND\n middlename = '\".$_POST['middlename'].\"' AND\n lastname = '\".$_POST['lastname'].\"' AND\n suffix = '\".$_POST['suffix'].\"'\n ORDER BY id DESC\n LIMIT 1\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n extract($line);\n }\n \n # find that full name from the DB\n $added = find_name($new_name_id);\n\n action_box(\"Name Added\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_tree&id=\".$_POST['id']);\n # log it\n mpact_logger(\"added name (\".$added['fullname'].\") for person[\".$_POST['id'].\"] (\".$person['fullname'].\")\");\n }\n else\n {\n not_admin();\n }\n \n break;\n\n ###############################################\n case \"edit_name\":\n\n if (is_admin()){\n\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n $before = find_name($_POST['name_id']);\n \n $query = \"UPDATE names\n SET\n firstname = '\".$_POST['firstname'].\"',\n middlename = '\".$_POST['middlename'].\"',\n lastname = '\".$_POST['lastname'].\"',\n suffix = '\".$_POST['suffix'].\"'\n WHERE\n id = '\".$_POST['name_id'].\"' AND\n person_id = '\".$_POST['id'].\"'\n \";\n\n $result = mysql_query($query) or die(mysql_error());\n\n $after = find_name($_POST['name_id']);\n\n # delete dotgraph for this person\n delete_associated_dotgraphs($_POST['id']);\n\n action_box(\"Name Saved\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_tree&id=\".$_POST['id']);\n # log it\n mpact_logger(\"edited name[\".$_POST['name_id'].\"] for person[\".$_POST['id'].\"] from (\".$before['fullname'].\") to (\".$after['fullname'].\")\");\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"add_url\":\n\n if (is_admin()){\n\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n $person = find_person(intval($_POST['person_id']));\n\n $query = \"INSERT urls\n SET\n url = '\".$_POST['url'].\"',\n description = '\".$_POST['description'].\"',\n updated_at = now(),\n person_id = '\".$_POST['person_id'].\"'\n \";\n\n $result = mysql_query($query) or die(mysql_error());\n\n action_box(\"Reference URL Added\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_tree&id=\".$_POST['person_id'].\"#urls\");\n # log it\n mpact_logger(\"added URL[\".substr($_POST['url'], 0, 30).\"] for person[\".$_POST['person_id'].\"] (\".$person['fullname'].\")\");\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"edit_url\":\n\n if (is_admin()){\n\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n $url = find_url(intval($_POST['id']));\n $person = find_person($url['person_id']);\n\n $query = \"UPDATE urls\n SET\n url = '\".$_POST['url'].\"',\n description = '\".$_POST['description'].\"',\n updated_at = now()\n WHERE\n id = '\".$_POST['id'].\"'\n \";\n\n $result = mysql_query($query) or die(mysql_error());\n\n action_box(\"Reference URL Edited\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_tree&id=\".$url['person_id'].\"#urls\");\n # log it\n mpact_logger(\"edited URL[\".substr($_POST['url'], 0, 30).\"] for person[\".$url['person_id'].\"] (\".$person['fullname'].\")\");\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"delete_url\":\n\n if (is_admin()){\n\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n $url = find_url(intval($_POST['id']));\n $person = find_person($url['person_id']);\n\n $query = \"DELETE FROM urls\n WHERE\n id = '\".$_POST['id'].\"'\n \";\n\n $result = mysql_query($query) or die(mysql_error());\n\n action_box(\"Reference URL Deleted\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_tree&id=\".$url['person_id'].\"#urls\");\n # log it\n mpact_logger(\"deleted URL[\".substr($url['url'], 0, 30).\"] for person[\".$url['person_id'].\"] (\".$person['fullname'].\")\");\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"edit_degree\":\n\n if (is_admin()){\n\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n $person = find_person(intval($_POST['id']));\n\n $query = \"UPDATE people\n SET\n degree = '\".$_POST['degree'].\"'\n WHERE\n id = '\".$_POST['id'].\"'\n \";\n\n $result = mysql_query($query) or die(mysql_error());\n\n action_box(\"Degree Edited\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_tree&id=\".$person['id']);\n # log it\n mpact_logger(\"edited degree[\".$_POST['degree'].\"] for person[\".$person['id'].\"] (\".$person['fullname'].\")\");\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"create_dissertation\":\n\n if (is_admin()){\n\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n $schools = find_schools();\n\n $person = find_person($_POST['person_id']);\n\n $query = \"INSERT INTO dissertations\n SET\n person_id = '\".$_POST['person_id'].\"',\n discipline_id = '\".$_POST['discipline_id'].\"',\n school_id = '\".$_POST['school_id'].\"',\n completedyear = '\".$_POST['completedyear'].\"',\n status = '\".$_POST['status'].\"',\n title = '\".$_POST['title'].\"',\n abstract = '\".$_POST['abstract'].\"'\n \";\n\n $result = mysql_query($query) or die(mysql_error());\n\n $query = \"UPDATE people\n SET degree = '\".$_POST['degree'].\"'\n WHERE\n id = '\".$_POST['person_id'].\"'\";\n\n $result = mysql_query($query) or die(mysql_error());\n\n action_box(\"Dissertation Created\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_tree&id=\".$_POST['person_id']);\n # log it\n $dissertation = find_dissertation_by_person($_POST['person_id']);\n mpact_logger(\"create dissertation[\".$dissertation['id'].\"] (\".$person['fullname'].\") with school[\".$dissertation['school_id'].\"] (\".$schools[$dissertation['school_id']].\") in year(\".$dissertation['completedyear'].\") with status (\".$statuscodes[$_POST['status']].\")\");\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n\n ###############################################\n case \"edit_dissertation\":\n\n if (is_admin()){\n\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n $disciplines = find_disciplines();\n $schools = find_schools();\n\n $dissertation = find_dissertation($_POST['id']);\n $person = find_person($dissertation['person_id']);\n\n $query = \"UPDATE dissertations\n SET\n school_id = '\".$_POST['school_id'].\"',\n discipline_id = '\".$_POST['discipline_id'].\"',\n completedyear = '\".$_POST['completedyear'].\"',\n status = '\".$_POST['status'].\"',\n notes = '\".$_POST['notes'].\"',\n title = '\".$_POST['title'].\"',\n abstract = '\".$_POST['abstract'].\"'\n WHERE\n id = '\".$_POST['id'].\"'\n \";\n\n $result = mysql_query($query) or die(mysql_error());\n\n $query = \"UPDATE people\n SET degree = '\".$_POST['degree'].\"'\n WHERE\n id = '\".$_POST['person_id'].\"'\";\n\n $result = mysql_query($query) or die(mysql_error());\n\n action_box(\"Dissertation Saved\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_tree&id=\".$_POST['person_id']);\n # log it\n mpact_logger(\"edit dissertation[\".$_POST['id'].\"] (\".$person['fullname'].\") from school[\".$dissertation['school_id'].\"] (\".$schools[$dissertation['school_id']].\") in year(\".$dissertation['completedyear'].\") to school[\".$_POST['school_id'].\"] (\".$schools[$_POST['school_id']].\") in year(\".$_POST['completedyear'].\")\");\n # look for changes\n # degree\n if ($person['degree'] != $_POST['degree'])\n {\n mpact_logger($dissertation['id'].\" updated degree [\".$_POST['degree'].\"]\",\"dissertation\");\n }\n # discipline\n if ($dissertation['discipline_id'] != $_POST['discipline_id'])\n {\n mpact_logger($dissertation['id'].\" updated discipline [\".$_POST['discipline_id'].\" (\".$disciplines[$_POST['discipline_id']].\")]\",\"dissertation\");\n }\n # school\n if ($dissertation['school_id'] != $_POST['school_id'])\n {\n mpact_logger($dissertation['id'].\" updated school [\".$_POST['school_id'].\" (\".$schools[$_POST['school_id']].\")]\",\"dissertation\");\n }\n # year\n if ($dissertation['completedyear'] != $_POST['completedyear'])\n {\n mpact_logger($dissertation['id'].\" updated completedyear [\".$_POST['completedyear'].\"]\",\"dissertation\");\n }\n # title\n if ($dissertation['title'] != $_POST['title'])\n {\n mpact_logger($dissertation['id'].\" updated title [\".$_POST['title'].\"]\",\"dissertation\");\n }\n # abstract\n if ($dissertation['abstract'] != $_POST['abstract'])\n {\n mpact_logger($dissertation['id'].\" updated abstract [\".$_POST['abstract'].\"]\",\"dissertation\");\n }\n # status\n if ($dissertation['status'] != $_POST['status'])\n {\n mpact_logger($dissertation['id'].\" updated status [\".$statuscodes[$_POST['status']].\"]\",\"dissertation\");\n }\n # status\n if ($dissertation['notes'] != $_POST['notes'])\n {\n mpact_logger($dissertation['id'].\" updated notes [\".$_POST['notes'].\"]\",\"dissertation\");\n }\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"delete_person\":\n\n if (is_admin()){\n\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n if (delete_person($_POST['id']))\n {\n action_box(\"Person Deleted\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_tree&id=\".$_POST['id']); \n }\n \n }\n else\n {\n not_admin();\n }\n\n break;\n\n\n ###############################################\n case \"delete_name\":\n \n if (is_admin()){\n\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n $name = find_name($_POST['name_id']);\n $person = find_person($_POST['id']);\n\n $query = \"DELETE FROM names\n WHERE\n id = '\".$_POST['name_id'].\"' AND\n person_id = '\".$_POST['id'].\"'\n \";\n\n $result = mysql_query($query) or die(mysql_error());\n\n action_box(\"Name Deleted\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_tree&id=\".$_POST['id']);\n\n # log it\n mpact_logger(\"deleted name[\".$_POST['name_id'].\"] (\".$name['fullname'].\") from person[\".$person['id'].\"] (\".$person['fullname'].\")\");\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"edit_school\":\n \n break;\n\n ###############################################\n default:\n // oops - not supposed to be here\n action_box(\"oops, back to the front page...\",2);\n\n\n }\n\n\n}\n\nxhtml_web_footer();\n\n?>\n", "mpact_include.php": " $val)\n foreach ($aSubtrahends as $aSubtrahend)\n if (array_key_exists($key, $aSubtrahend))\n unset ($ar1[$key]);\n return $ar1;\n}\n\n# -------------------------------------------------------------------------------\nfunction action_box($message,$bounce = \"0\",$location = \"index.php\"){\n\n echo \"\n

            \n $message\n

            \n

            \n \";\n\n if ($bounce != \"0\"){\n echo \"\n \n

            \n Forwarding in $bounce seconds (or click here to do the same)\n

            \n \";\n }\n\n} \n\n# -------------------------------------------------------------------------------\nfunction xhtml_orig_web_header(){\n \n # make search box happy\n if (!isset($_POST['q'])){$_POST['q'] = \"\";}\n if (!isset($_POST['qta'])){$_POST['qta'] = \"\";}\n if (!isset($_POST['qn'])){$_POST['qn'] = \"\";}\n\n # print out header info\n echo \"\n \n \n \n \n MPACT\n \n \n \n \n\n \n \n \n \n \n \n \n \n \n
            \n \n \n \n \n \n
            \n
            \n MPACT -\n Database -\n \n People Search: \n
            -\n
            \n \n Title/Abstract Search: \n
            \n\";\n if (is_admin()){\n echo \" -
            \n \n Admin Notes Search: \n
            \";\n }\n echo \"
            \n\";\n if (is_admin()){\n echo $_SESSION['MPACT']['fullname'].\" (\".$_SESSION['MPACT']['username'].\") - Logout\";\n }\n else{\n $host_info = get_environment_info();\n if ($host_info['hostname'] != \"sils\"){\n echo \"Login\";\n }\n }\necho \"\n
            \n

            \n\n \";\n\n\n}\n\n# -------------------------------------------------------------------------------\nfunction xhtml_web_header(){\n \n # make search box happy\n if (!isset($_POST['q'])){$_POST['q'] = \"\";}\n if (!isset($_POST['qta'])){$_POST['qta'] = \"\";}\n if (!isset($_POST['qn'])){$_POST['qn'] = \"\";}\n\n # print out header info\n echo \"\n \n \n \n \n MPACT\n \n \n \n \n \n \n\";\n\necho \"

            \";\nif (is_admin()){\n echo $_SESSION['MPACT']['fullname'].\" (\".$_SESSION['MPACT']['username'].\") - Logout\";\n}\nelse{\n echo \"Login\";\n}\necho \"

            \";\necho \"
            \";\n\necho \"\n
            \n \n \n \n \n \n \n\n \n \n \n
            \n \n \n \n \n Publications  • \n Project Statistics\n
            \n
            \n Glossary  • \n Schools  • \n Disciplines\n
            \n
            \n \n People Search: \n
            \n    \n
            \n \n Title/Abstract Search: \n
            \";\nif (is_admin()){\n echo \"

            Administrator Pages\";\n echo \"
            \n \n Admin Notes Search: \n
            \";\n}\necho \"
            \n \n
            \n
            \n\n
            \n
            \n\n
            \n\n \";\n\n\n}\n\n# -------------------------------------------------------------------------------\nfunction xhtml_web_footer(){\n echo \"\n\n
            \n\n \n \n\";\n}\n\n# -------------------------------------------------------------------------------\nfunction is_email_valid ($address)\n{\n\n\t# http://www.zend.com/codex.php?id=285&single=1\n\n return (preg_match(\n '/^[-!#$%&\\'*+\\\\.\\/0-9=?A-Z^_`{|}~]+'. // the user name\n '@'. // the ubiquitous at-sign\n '([-0-9A-Z]+\\.)+' . // host, sub-, and domain names\n '([0-9A-Z]){2,4}$/i', // top-level domain (TLD)\n trim($address)));\n}\n\n# -------------------------------------------------------------------------------\nfunction find_glossaryterms()\n{\n $query = \"SELECT id, term, definition FROM glossary\";\n $result = mysql_query($query) or die(mysql_error());\n $glossaryterms = array();\n while ( $line = mysql_fetch_array($result)) {\n $glossaryterms['ids'][$line['term']] = $line['id'];\n $glossaryterms['defs'][$line['id']] = $line['definition'];\n }\n return $glossaryterms;\n}\n\n# -------------------------------------------------------------------------------\nfunction show_glossary()\n{\n $query = \"SELECT id, term, definition FROM glossary ORDER BY term ASC\";\n $result = mysql_query($query) or die(mysql_error());\n\n $results = array();\n while ( $line = mysql_fetch_array($result)) {\n array_push($results,$line);\n }\n\n echo \"

            Glossary

            \\n\";\n\n echo \"

            \\n\";\n\n foreach ($results as $one)\n {\n echo \"\".$one['term'].\": \";\n echo $one['definition'];\n if (is_admin())\n {\n echo \" EDIT \";\n }\n echo \"

            \";\n }\n\n echo \"

            \\n\";\n\n}\n\n# -------------------------------------------------------------------------------\nfunction show_glossaryterm($id)\n{\n $query = \"SELECT id, term, definition FROM glossary WHERE id = $id\";\n $result = mysql_query($query) or die(mysql_error());\n\n $results = array();\n while ( $line = mysql_fetch_array($result)) {\n $glossaryterm = $line;\n }\n\n echo \"

            Full Glossary Listing

            \";\n\n echo \"

            Glossary

            \\n\";\n\n echo \"

            \\n\";\n\n echo \"\".$glossaryterm['term'].\": \";\n echo $glossaryterm['definition'];\n if (is_admin())\n {\n echo \" EDIT \";\n }\n echo \"

            \";\n\n echo \"

            \\n\";\n\n}\n\n# -------------------------------------------------------------------------------\nfunction show_alphabet()\n{\n\n $alphabet_letters = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n $alphabet = preg_split('//', $alphabet_letters, -1, PREG_SPLIT_NO_EMPTY);\n\n echo \"
            \\n\";\n echo \"

            Dissertation Authors and Mentors by Last Name

            \";\n echo \"

            \";\n foreach ($alphabet as $letter)\n {\n if ($letter != \"A\"){echo \" - \";}\n echo \"$letter\";\n }\n echo \"

            \";\n echo \"
            \\n\";\n}\n\n# -------------------------------------------------------------------------------\nfunction search_box($q=\"\")\n{\n echo \"
            \\n\";\n echo \"\\n\";\n echo \"

            People Search: \";\n if ($q)\n {\n echo \"\\n\"; \n }\n else\n {\n echo \"\\n\"; \n }\n echo \"

            \\n\";\n echo \"
            \\n\";\n}\n\n# -------------------------------------------------------------------------------\nfunction people_search($q)\n{\n $q = trim($q);\n if (!get_magic_quotes_gpc()) {$q = addslashes($q);}\n $results = array();\n if (strlen($q) < 2){\n return $results;\n }\n\n $pieces = split(\" \",$q);\n# print_r($pieces);\n if (count($pieces) == 2)\n {\n# echo \" --------- two pieces\";\n $query = \"SELECT n.id as name_id, p.id as person_id\n FROM\n names n, people p\n WHERE\n (\n\n (n.firstname LIKE '%\".$pieces[0].\"%' OR\n n.middlename LIKE '%\".$pieces[0].\"%' OR\n n.lastname LIKE '%\".$pieces[0].\"%' OR\n n.suffix LIKE '%\".$pieces[0].\"%')\n \n AND\n \n (n.firstname LIKE '%\".$pieces[1].\"%' OR\n n.middlename LIKE '%\".$pieces[1].\"%' OR\n n.lastname LIKE '%\".$pieces[1].\"%' OR\n n.suffix LIKE '%\".$pieces[1].\"%')\n \n )\n AND\n n.person_id = p.id\n GROUP BY\n p.id\n ORDER BY\n n.lastname, n.suffix, n.firstname, n.middlename\n \";\n }\n elseif (count($pieces) == 3)\n {\n# echo \" --------- three pieces\";\n $query = \"SELECT n.id as name_id, p.id as person_id\n FROM\n names n, people p\n WHERE\n (\n\n (n.firstname LIKE '%\".$pieces[0].\"%' OR\n n.middlename LIKE '%\".$pieces[0].\"%' OR\n n.lastname LIKE '%\".$pieces[0].\"%' OR\n n.suffix LIKE '%\".$pieces[0].\"%')\n \n AND\n\n (n.firstname LIKE '%\".$pieces[1].\"%' OR\n n.middlename LIKE '%\".$pieces[1].\"%' OR\n n.lastname LIKE '%\".$pieces[1].\"%' OR\n n.suffix LIKE '%\".$pieces[1].\"%')\n\n AND\n\n (n.firstname LIKE '%\".$pieces[2].\"%' OR\n n.middlename LIKE '%\".$pieces[2].\"%' OR\n n.lastname LIKE '%\".$pieces[2].\"%' OR\n n.suffix LIKE '%\".$pieces[2].\"%')\n \n )\n AND\n n.person_id = p.id\n GROUP BY\n p.id\n ORDER BY\n n.lastname, n.suffix, n.firstname, n.middlename\n \";\n }\n else\n {\n# echo \" --- regular search - single piece\";\n $query = \"SELECT n.id as name_id, p.id as person_id\n FROM\n names n, people p\n WHERE\n (\n\n (n.firstname LIKE '%\".$q.\"%' OR\n n.middlename LIKE '%\".$q.\"%' OR\n n.lastname LIKE '%\".$q.\"%' OR\n n.suffix LIKE '%\".$q.\"%')\n\n )\n AND\n n.person_id = p.id\n GROUP BY\n p.id\n ORDER BY\n n.lastname, n.suffix, n.firstname, n.middlename\n \";\n }\n $result = mysql_query($query) or die(mysql_error());\n\n while ( $line = mysql_fetch_array($result)) {\n array_push($results,$line['person_id']);\n }\n return $results;\n}\n\n# -------------------------------------------------------------------------------\nfunction title_abstract_search($q)\n{\n $q = trim($q);\n if (!get_magic_quotes_gpc()) {$q = addslashes($q);}\n $results = array();\n if (strlen($q) < 2){\n return $results;\n }\n\n $pieces = split(\" \",$q);\n# print_r($pieces);\n if (count($pieces) == 2)\n {\n# echo \" --------- two pieces\";\n $query = \"SELECT d.person_id\n FROM\n names n, dissertations d\n WHERE\n (\n\n (d.title LIKE '%\".$pieces[0].\"%' OR\n d.abstract LIKE '%\".$pieces[0].\"%')\n \n AND\n\n (d.title LIKE '%\".$pieces[1].\"%' OR\n d.abstract LIKE '%\".$pieces[1].\"%')\n \n )\n AND\n n.person_id = d.person_id\n GROUP BY\n d.id\n ORDER BY\n n.lastname, n.suffix, n.firstname, n.middlename\n \";\n }\n elseif (count($pieces) == 3)\n {\n# echo \" --------- three pieces\";\n $query = \"SELECT d.person_id\n FROM\n names n, dissertations d\n WHERE\n (\n\n (d.title LIKE '%\".$pieces[0].\"%' OR\n d.abstract LIKE '%\".$pieces[0].\"%')\n \n AND\n\n (d.title LIKE '%\".$pieces[1].\"%' OR\n d.abstract LIKE '%\".$pieces[1].\"%')\n\n AND\n\n (d.title LIKE '%\".$pieces[2].\"%' OR\n d.abstract LIKE '%\".$pieces[2].\"%')\n \n )\n AND\n n.person_id = d.person_id\n GROUP BY\n d.id\n ORDER BY\n n.lastname, n.suffix, n.firstname, n.middlename\n \";\n }\n else\n {\n# echo \" --- regular search - single piece\";\n $query = \"SELECT d.person_id\n FROM\n names n, dissertations d\n WHERE\n (\n\n (d.title LIKE '%\".$q.\"%' OR\n d.abstract LIKE '%\".$q.\"%')\n\n )\n AND\n n.person_id = d.person_id\n GROUP BY\n d.id\n ORDER BY\n n.lastname, n.suffix, n.firstname, n.middlename\n \";\n }\n $result = mysql_query($query) or die(mysql_error());\n\n while ( $line = mysql_fetch_array($result)) {\n array_push($results,$line['person_id']);\n }\n return $results;\n}\n\n# -------------------------------------------------------------------------------\nfunction notes_search($q)\n{\n $q = trim($q);\n if (!get_magic_quotes_gpc()) {$q = addslashes($q);}\n $results = array();\n if (strlen($q) < 2){\n return $results;\n }\n\n $pieces = split(\" \",$q);\n# print_r($pieces);\n if (count($pieces) == 2)\n {\n# echo \" --------- two pieces\";\n $query = \"SELECT d.person_id\n FROM\n names n, dissertations d\n WHERE\n (\n\n (d.notes LIKE '%\".$pieces[0].\"%')\n \n AND\n\n (d.notes LIKE '%\".$pieces[1].\"%')\n \n )\n AND\n n.person_id = d.person_id\n GROUP BY\n d.id\n ORDER BY\n n.lastname, n.suffix, n.firstname, n.middlename\n \";\n }\n elseif (count($pieces) == 3)\n {\n# echo \" --------- three pieces\";\n $query = \"SELECT d.person_id\n FROM\n names n, dissertations d\n WHERE\n (\n\n (d.notes LIKE '%\".$pieces[0].\"%')\n \n AND\n\n (d.notes LIKE '%\".$pieces[1].\"%')\n\n AND\n\n (d.notes LIKE '%\".$pieces[2].\"%')\n \n )\n AND\n n.person_id = d.person_id\n GROUP BY\n d.id\n ORDER BY\n n.lastname, n.suffix, n.firstname, n.middlename\n \";\n }\n else\n {\n# echo \" --- regular search - single piece\";\n $query = \"SELECT d.person_id\n FROM\n names n, dissertations d\n WHERE\n (\n\n (d.notes LIKE '%\".$q.\"%')\n\n )\n AND\n n.person_id = d.person_id\n GROUP BY\n d.id\n ORDER BY\n n.lastname, n.suffix, n.firstname, n.middlename\n \";\n }\n $result = mysql_query($query) or die(mysql_error());\n\n while ( $line = mysql_fetch_array($result)) {\n array_push($results,$line['person_id']);\n }\n return $results;\n}\n\n# -------------------------------------------------------------------------------\nfunction encode_linebreaks($bigtext)\n{\n # from http://us3.php.net/str_replace\n $order = array(\"\\r\\n\", \"\\n\", \"\\r\");\n $replace = '
            ';\n // Processes \\r\\n's first so they aren't converted twice.\n $with_breaks = str_replace($order, $replace, $bigtext);\n return $with_breaks;\n}\n\n# -------------------------------------------------------------------------------\nfunction get_logs($offset=\"0\")\n{\n# echo \"[$offset]\";\n $query = \"SELECT * FROM logs ORDER BY id DESC LIMIT 100\";\n if ($offset != \"\"){$query .= \" OFFSET $offset\";}\n $result = mysql_query($query) or die(mysql_error());\n\n# echo $query;\n $entries = array();\n $counter = 0;\n while ( $line = mysql_fetch_array($result)) {\n $counter++;\n $entries[$counter] = $line;\n }\n return $entries;\n}\n\n\n# -------------------------------------------------------------------------------\nfunction get_dissertation_history($id)\n{\n $query = \"SELECT * FROM logs\n WHERE type='dissertation' AND message LIKE '$id %'\n ORDER BY id DESC\";\n $result = mysql_query($query) or die(mysql_error());\n\n# echo $query;\n $entries = array();\n $counter = 0;\n while ( $line = mysql_fetch_array($result)) {\n $counter++;\n $entries[$counter] = $line;\n }\n return $entries;\n}\n\n\n# -------------------------------------------------------------------------------\nfunction find_all_people()\n{\n # return array of all people_ids in database (slow....)\n # all people\n $query = \"SELECT id as person_id FROM people\";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $people[] = $line['person_id'];\n }\n return $people;\n}\n\n# -------------------------------------------------------------------------------\nfunction get_person_link($person_id)\n{\n\n $disciplines = find_disciplines();\n $person = find_person($person_id);\n\n $fullname = trim($person['firstname'].\" \".$person['middlename'].\" \".$person['lastname'].\" \".$person['suffix']);\n\n $dissertation = find_dissertation_by_person($person_id);\n $discipline = isset($dissertation['discipline_id']) ? $disciplines[$dissertation['discipline_id']] : \"\";\n \n $link = \"\".$fullname.\"\";\n\n return $link;\n\n}\n\n# -------------------------------------------------------------------------------\nfunction find_orphans()\n{\n\n # finding people with no dissertation and no students\n\n # all people\n $query = \"SELECT\n p.id as person_id, n.firstname, n.middlename, n.lastname, n.suffix\n FROM\n people p, names n\n WHERE\n p.preferred_name_id = n.id\n ORDER BY n.lastname,n.firstname,n.middlename\n \";\n\n $result = mysql_query($query) or die(mysql_error());\n\n while ( $line = mysql_fetch_array($result)) {\n $people[$line['person_id']] = $line;\n# echo \" \".$line['person_id'].\"
            \\n\";\n }\n \n echo \"people: \".count($people).\"
            \\n\";\n\n # with dissertations only\n $query = \"SELECT\n p.id as person_id\n FROM\n people p, dissertations d\n WHERE\n d.person_id = p.id\n \";\n\n $result = mysql_query($query) or die(mysql_error());\n\n while ( $line = mysql_fetch_array($result)) {\n $with_dissertations[$line['person_id']] = $line;\n# echo \" \".$line['person_id'].\"
            \\n\";\n }\n\n echo \"dissertations: \".count($with_dissertations).\"
            \\n\";\n\n # all people - dissertations = teachers only\n $potentialmentors = array_key_diff($people,$with_dissertations);\n\n echo \"potential mentors: \".count($potentialmentors).\"
            \\n\";\n\n # orphans = teachers who don't have students\n # get advisorships\n $query = \"SELECT person_id FROM advisorships\";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $advisors[$line['person_id']] = $line;\n }\n echo \"advisors: \".count($advisors).\"
            \\n\";\n # get committeeships\n $query = \"SELECT person_id FROM committeeships\";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n $committeemembers[$line['person_id']] = $line;\n }\n echo \"committeemembers: \".count($committeemembers).\"
            \\n\";\n # subtract advisorships from teachers\n $potentialmentors = array_key_diff($potentialmentors,$advisors);\n # subtract committeeships from remaining teachers\n $orphans = array_key_diff($potentialmentors,$committeemembers);\n echo \"orphans: \".count($orphans).\"
            \\n\";\n\n return $orphans;\n\n}\n\n# -------------------------------------------------------------------------------\nfunction is_orphan($person_id)\n{\n # confirm person exists\n $query = \"SELECT * FROM people WHERE id = '\".$person_id.\"'\";\n $result = mysql_query($query) or die(mysql_error());\n $line = mysql_fetch_array($result);\n if (!$line['id']){echo \"not a person\";return 0;}\n # confirm no dissertation\n $query = \"SELECT * FROM dissertations WHERE person_id = '\".$person_id.\"'\";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n echo \"found a dissertation\";\n return 0;\n }\n # confirm not a committeemember\n $query = \"SELECT * FROM committeeships WHERE person_id = '\".$person_id.\"'\";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n echo \"found a committeeship\";\n return 0;\n }\n # confirm not an advisor\n $query = \"SELECT * FROM advisorships WHERE person_id = '\".$person_id.\"'\";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n echo \"found an advisorship\";\n return 0;\n }\n return 1;\n}\n# -------------------------------------------------------------------------------\nfunction delete_person($person_id)\n{\n if (is_orphan($person_id))\n {\n $before = find_person($person_id);\n # delete all names\n $query = \"DELETE FROM names WHERE person_id = '\".$person_id.\"'\";\n $result = mysql_query($query) or die(mysql_error());\n # delete the person\n $query = \"DELETE FROM people WHERE id = '\".$person_id.\"' LIMIT 1\";\n $result = mysql_query($query) or die(mysql_error());\n # log it\n mpact_logger(\"deleted person[\".$person_id.\"] (\".$before['fullname'].\")\");\n return 1;\n }\n else\n {\n action_box(\"Not an orphan - Cannot delete this person.\");\n return 0;\n }\n}\n# -------------------------------------------------------------------------------\nfunction remove_duplicate_names($person_id)\n{\n\n $names = array();\n $deleteme = array();\n\n\n $before = find_person($person_id);\n\n // get the preferred_name_id\n $query = \"SELECT preferred_name_id\n FROM people\n WHERE id = '\".$person_id.\"'\n \";\n \n $result = mysql_query($query) or die(mysql_error());\n\n while ( $line = mysql_fetch_array($result)) {\n extract($line);\n }\n\n // get the full preferred_name\n $query = \"SELECT * FROM names\n WHERE\n id = '\".$preferred_name_id.\"'\n \";\n\n $result = mysql_query($query) or die(mysql_error());\n\n while ( $line = mysql_fetch_array($result)) {\n $fullname = \"\".$line['firstname'].\" \".$line['middlename'].\" \".$line['lastname'].\" \".$line['suffix'].\"\";\n $names[$fullname] = $line['id']; \n }\n\n // get the rest of the names for this person\n $query = \"SELECT * FROM names\n WHERE\n person_id = '\".$person_id.\"' AND\n id != '\".$preferred_name_id.\"'\n \";\n\n $result = mysql_query($query) or die(mysql_error());\n\n while ( $line = mysql_fetch_array($result)) {\n $fullname = \"\".$line['firstname'].\" \".$line['middlename'].\" \".$line['lastname'].\" \".$line['suffix'].\"\";\n if (isset($names[$fullname]))\n {\n $deleteme[] = $line['id'];\n }\n else\n {\n $names[$fullname] = $line['id']; \n }\n }\n\n // delete each deleteme id\n foreach ($deleteme as $one)\n {\n $query = \"DELETE FROM names\n WHERE\n id = '\".$one.\"'\n \";\n\n $result = mysql_query($query) or die(mysql_error());\n }\n\n # log it\n mpact_logger(\"removed duplicate names for person[\".$person_id.\"] (\".$before['fullname'].\")\");\n\n}\n\n# -------------------------------------------------------------------------------\nfunction add_mentor($type,$student_id,$mentor_id)\n{\n $student = find_person($student_id);\n $mentor = find_person($mentor_id);\n $dissertation = find_dissertation_by_person($student_id);\n\n if ($type == \"A\")\n {\n # find existing advisors for this student\n $advisors = find_advisors_for_person($student_id);\n # if new/different - then add them to the student's dissertation\n if (in_array($mentor_id,$advisors))\n {\n # skip - already listed as advisor\n }\n else\n {\n $query = \"INSERT advisorships\n SET\n dissertation_id = '\".$dissertation['id'].\"',\n person_id = '\".$mentor_id.\"'\n \";\n# echo $query;\n $result = mysql_query($query) or die(mysql_error());\n # recalculate scores for both\n calculate_scores($student_id);\n calculate_scores($mentor_id);\n # log it\n mpact_logger(\"add advisorship between mentor[\".$mentor_id.\"] (\".$mentor['fullname'].\") to dissertation[\".$dissertation['id'].\"] (\".$student['fullname'].\")\");\n # delete existing dotgraphs - they'll need to be regenerated\n # has to happen after we add the advisor link itself\n delete_associated_dotgraphs($student_id);\n }\n }\n elseif ($type == \"C\")\n {\n # find existing committee members for this student\n $committee = find_committee_for_person($student_id);\n # if new/different - then add them to the student's dissertation \n if (in_array($mentor_id,$committee))\n {\n # skip - already on committee\n }\n else\n {\n $query = \"INSERT committeeships\n SET\n dissertation_id = '\".$dissertation['id'].\"',\n person_id = '\".$mentor_id.\"'\n \";\n# echo $query;\n $result = mysql_query($query) or die(mysql_error());\n # recalculate scores for both\n calculate_scores($student_id);\n calculate_scores($mentor_id);\n # log it\n mpact_logger(\"add committeeship between mentor[\".$mentor_id.\"] (\".$mentor['fullname'].\") to dissertation[\".$dissertation['id'].\"] (\".$student['fullname'].\")\");\n }\n }\n else\n {\n # nothing\n }\n}\n\n# -------------------------------------------------------------------------------\nfunction remove_mentor($type,$student_id,$mentor_id)\n{\n $dissertation = find_dissertation_by_person($student_id);\n\n $student = find_person($student_id);\n $mentor = find_person($mentor_id);\n\n if ($type == \"A\")\n {\n # find dissertation id\n $dissertation = find_dissertation_by_person($student_id);\n # find existing advisors for this student\n $advisors = find_advisors_for_person($student_id);\n # if found in db, remove them\n if (!in_array($mentor_id,$advisors))\n {\n echo \"not an advisor for this student\";\n return 0;\n }\n else\n {\n # delete existing dotgraphs - they'll need to be regenerated\n # has to happen before we delete the advisor link itself\n delete_associated_dotgraphs($student_id);\n # delete the advisorship\n $query = \"DELETE FROM advisorships\n WHERE\n person_id = '\".$mentor_id.\"' AND\n dissertation_id = '\".$dissertation['id'].\"'\n LIMIT 1\n \";\n $result = mysql_query($query) or die(mysql_error());\n # recalculate scores for both\n calculate_scores($student_id);\n calculate_scores($mentor_id);\n # log it\n mpact_logger(\"remove advisorship between mentor[\".$mentor_id.\"] (\".$mentor['fullname'].\") to dissertation[\".$dissertation['id'].\"] (\".$student['fullname'].\")\");\n return 1;\n }\n }\n elseif ($type == \"C\")\n {\n # find dissertation id\n $dissertation = find_dissertation_by_person($student_id);\n # find existing committee members for this student\n $committee = find_committee_for_person($student_id);\n # if found in db, remove them \n if (!in_array($mentor_id,$committee))\n {\n echo \"not on committee for this student\";\n return 0;\n }\n else\n {\n $query = \"DELETE FROM committeeships\n WHERE\n person_id = '\".$mentor_id.\"' AND\n dissertation_id = '\".$dissertation['id'].\"'\n LIMIT 1\n \";\n $result = mysql_query($query) or die(mysql_error());\n # recalculate scores for both\n calculate_scores($student_id);\n calculate_scores($mentor_id);\n # log it\n mpact_logger(\"remove advisorship between mentor[\".$mentor_id.\"] (\".$mentor['fullname'].\") to dissertation[\".$dissertation['id'].\"] (\".$student['fullname'].\")\");\n return 1;\n }\n }\n else\n {\n echo \"has to be A or C, dude\";\n return 0;\n }\n\n}\n\n# -------------------------------------------------------------------------------\nfunction find_all_people_for_selectbox($with_dissertation=\"0\")\n{\n if ($with_dissertation == \"0\")\n {\n $query = \"SELECT\n p.id as person_id, n.firstname, n.middlename, n.lastname, n.suffix\n FROM\n people p, names n\n WHERE\n p.preferred_name_id = n.id\n ORDER BY n.lastname,n.firstname,n.middlename\n \"; \n }\n else\n {\n $query = \"SELECT\n p.id as person_id, n.firstname, n.middlename, n.lastname, n.suffix\n FROM\n people p, names n, dissertations d\n WHERE\n p.preferred_name_id = n.id AND\n d.person_id = p.id\n ORDER BY n.lastname,n.firstname,n.middlename\n \";\n }\n // echo $query;\n $result = mysql_query($query) or die(mysql_error());\n\n while ( $line = mysql_fetch_array($result)) {\n $people[$line['person_id']] = $line;\n }\n\n return $people;\n}\n\n# -------------------------------------------------------------------------------\nfunction merge_two_people($from_id, $into_id)\n{\n\n $from_person = find_person($from_id);\n $into_person = find_person($into_id);\n \n\n $query = \"UPDATE advisorships\n SET\n person_id = '\".$into_person['id'].\"'\n WHERE\n person_id = '\".$from_person['id'].\"'\n \";\n \n $result = mysql_query($query) or die(mysql_error());\n\n $query = \"UPDATE dissertations\n SET\n person_id = '\".$into_person['id'].\"'\n WHERE\n person_id = '\".$from_person['id'].\"'\n \";\n \n $result = mysql_query($query) or die(mysql_error());\n\n $query = \"UPDATE committeeships\n SET\n person_id = '\".$into_person['id'].\"'\n WHERE\n person_id = '\".$from_person['id'].\"'\n \";\n \n $result = mysql_query($query) or die(mysql_error());\n\n $query = \"UPDATE urls\n SET\n person_id = '\".$into_person['id'].\"'\n WHERE\n person_id = '\".$from_person['id'].\"'\n \";\n \n $result = mysql_query($query) or die(mysql_error());\n\n // move each 'from' name to the 'into' person\n \n $query = \"UPDATE names\n SET\n person_id = '\".$into_person['id'].\"'\n WHERE\n person_id = '\".$from_person['id'].\"'\n \";\n\n $result = mysql_query($query) or die(mysql_error());\n\n // remove any new duplicates in the names table\n \n remove_duplicate_names($into_person['id']); \n\n // remove 'from' person from the database\n \n $query = \"DELETE FROM people\n WHERE\n id = '\".$from_person['id'].\"'\n \";\n\n $result = mysql_query($query) or die(mysql_error());\n\n # log it\n mpact_logger(\"merged two people [\".$from_id.\"] (\".$from_person['fullname'].\") and [\".$into_id.\"] (\".$into_person['fullname'].\")\");\n\n\n}\n\n# -------------------------------------------------------------------------------\nfunction find_aliases($person_id)\n{\n\n $query = \"SELECT preferred_name_id\n FROM people\n WHERE id = '\".$person_id.\"'\n \";\n\n $result = mysql_query($query) or die(mysql_error());\n\n while ( $line = mysql_fetch_array($result)) {\n extract($line);\n }\n\n $names = array();\n $query = \"SELECT\n n.firstname, n.middlename,\n n.lastname, n.suffix, n.id\n FROM\n names n\n WHERE\n n.person_id = '\".$person_id.\"'\n \";\n\n $result = mysql_query($query) or die(mysql_error());\n\n while ( $line = mysql_fetch_array($result)) {\n $names[$line['id']] = $line;\n }\n\n unset($names[$preferred_name_id]);\n \n return $names;\n}\n\n# -------------------------------------------------------------------------------\nfunction find_person($person_id)\n{\n $query = \"SELECT\n n.firstname, n.middlename,\n n.lastname, n.suffix, p.degree,\n p.id, p.preferred_name_id\n FROM\n names n, people p\n WHERE\n p.preferred_name_id = n.id AND\n p.id = \".$person_id.\"\n \";\n $result = mysql_query($query) or die(mysql_error());\n\n while ( $line = mysql_fetch_array($result)) {\n $person = $line;\n $person['fullname'] = $person['firstname'];\n if ($person['middlename'] != \"\"){$person['fullname'] .= \" \".$person['middlename'];}\n if ($person['lastname'] != \"\"){$person['fullname'] .= \" \".$person['lastname'];}\n if ($person['suffix'] != \"\"){$person['fullname'] .= \" \".$person['suffix'];}\n }\n\n return $person;\n}\n\n# -------------------------------------------------------------------------------\nfunction find_url($url_id)\n{\n\n $url_id = intval($url_id);\n $query = \"SELECT\n u.id, u.url, u.description, u.updated_at, u.person_id\n FROM\n urls u\n WHERE\n u.id = '\".$url_id.\"'\n \";\n $result = mysql_query($query) or die(mysql_error());\n\n while ( $line = mysql_fetch_array($result)) {\n $url = $line;\n }\n\n return $url;\n\n}\n\n# -------------------------------------------------------------------------------\nfunction find_urls_by_person($person_id)\n{\n\n $person_id = intval($person_id);\n $query = \"SELECT\n u.id, u.url, u.description, u.updated_at, u.person_id\n FROM\n urls u\n WHERE\n u.person_id = '\".$person_id.\"'\n \";\n $result = mysql_query($query) or die(mysql_error());\n\n $urls = array();\n while ( $line = mysql_fetch_array($result)) {\n $urls[$line['id']] = $line;\n }\n\n return $urls;\n\n}\n\n# -------------------------------------------------------------------------------\nfunction find_dissertation($dissertation_id)\n{\n\n $dissertation_id = intval($dissertation_id);\n $query = \"SELECT\n d.id, d.person_id, d.completedyear, d.status,\n d.title, d.abstract, d.notes, d.school_id, d.discipline_id\n FROM\n dissertations d\n WHERE\n d.id = '\".$dissertation_id.\"'\n \";\n $result = mysql_query($query) or die(mysql_error());\n\n $dissertation = array();\n while ( $line = mysql_fetch_array($result)) {\n $dissertation = $line;\n }\n\n return $dissertation;\n}\n\n# -------------------------------------------------------------------------------\nfunction find_dissertation_by_person($person_id)\n{\n\n $person_id = intval($person_id);\n $query = \"SELECT\n d.id, d.person_id, d.completedyear, d.status,\n d.title, d.abstract, d.notes, d.school_id, d.discipline_id\n FROM\n dissertations d\n WHERE\n d.person_id = '\".$person_id.\"'\n \";\n $result = mysql_query($query) or die(mysql_error());\n\n $dissertation = array();\n while ( $line = mysql_fetch_array($result)) {\n $dissertation = $line;\n }\n\n return $dissertation;\n}\n\n# -------------------------------------------------------------------------------\nfunction find_name($name_id)\n{\n $query = \"SELECT\n n.firstname, n.middlename,\n n.lastname, n.suffix\n FROM\n names n\n WHERE\n n.id = \".$name_id.\"\n \";\n $result = mysql_query($query) or die(mysql_error());\n\n while ( $line = mysql_fetch_array($result)) {\n $name = $line;\n $name['fullname'] = $name['firstname'];\n if ($name['middlename'] != \"\"){$name['fullname'] .= \" \".$name['middlename'];}\n if ($name['lastname'] != \"\"){$name['fullname'] .= \" \".$name['lastname'];}\n if ($name['suffix'] != \"\"){$name['fullname'] .= \" \".$name['suffix'];}\n }\n\n return $name;\n}\n\n# -------------------------------------------------------------------------------\nfunction find_discipline($discipline_id)\n{\n $discipline_id = intval($discipline_id);\n $query = \"SELECT\n d.title, d.description\n FROM\n disciplines d\n WHERE\n d.id = \".$discipline_id.\"\n \";\n $result = mysql_query($query) or die(mysql_error());\n\n while ( $line = mysql_fetch_array($result)) {\n $discipline = $line;\n }\n\n return $discipline;\n}\n\n# -------------------------------------------------------------------------------\nfunction find_ancestors_for_group($groupofpeople)\n{\n $originalgroup = $groupofpeople;\n // find advisors, and if they're new, add them to the list and recurse\n foreach ($originalgroup as $person)\n {\n $advisors = find_advisors_for_person($person);\n foreach ($advisors as $one)\n {\n $groupofpeople[] = $one;\n }\n }\n $groupofpeople = array_unique($groupofpeople);\n if (count(array_diff($groupofpeople,$originalgroup)) > 0)\n {\n return find_ancestors_for_group($groupofpeople);\n }\n else\n {\n return $originalgroup;\n }\n}\n\n# -------------------------------------------------------------------------------\nfunction find_descendents_for_group($groupofpeople)\n{\n $originalgroup = $groupofpeople;\n // find descendents, and if they're new, add them to the list and recurse\n foreach ($originalgroup as $person)\n {\n $advisees = find_advisorships_under_person($person);\n foreach ($advisees as $one)\n {\n $groupofpeople[] = $one;\n }\n }\n $groupofpeople = array_unique($groupofpeople);\n if (count(array_diff($groupofpeople,$originalgroup)) > 0)\n {\n return find_descendents_for_group($groupofpeople);\n }\n else\n {\n return $originalgroup;\n }\n}\n\n# -------------------------------------------------------------------------------\nfunction T_score($person)\n{\n # total number of descendants (nodes) in a person's tree\n $group = array($person);\n $total = count(find_descendents_for_group($group)); # including self\n $descendents = $total - 1; # minus self\n return $descendents;\n}\n\n# -------------------------------------------------------------------------------\nfunction find_mpact_score($person,$score_type)\n{\n $query = \"SELECT $score_type as score FROM people WHERE id='$person'\";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n extract($line);\n }\n return $score;\n}\n\n# -------------------------------------------------------------------------------\nfunction FMI_score($person)\n{\n $FMI_score = count(find_advisorships_under_person($person));\n# print \"person $person -- fmi $FMI_score
            \";\n $committeeships = find_committeeships_under_person($person);\n foreach ($committeeships as $one)\n {\n $numA = count(find_advisors_for_person($one));\n# echo \" - #A [$numA] ----
            \";\n $numC = count(find_committee_for_person($one));\n# echo \"#C [$numC] ---- \\n\";\n $FMI_score += 1/($numA + $numC);\n# echo \"
            \";\n }\n // echo \"fractional mentorship, inclusive (FMI = A + eachC(1/(#A+#C)) )
            \\n\";\n return round($FMI_score,3);\n}\n\n# -------------------------------------------------------------------------------\nfunction FME_score($person)\n{\n $FME_score = count(find_advisorships_under_person($person));\n# print \"person $person -- fme $FME_score
            \";\n $committeeships = find_committeeships_under_person($person);\n foreach ($committeeships as $one)\n {\n $numC = count(find_committee_for_person($one));\n# echo \"#C [$numC] ---- \\n\";\n $FME_score += 1/($numC);\n# echo \"
            \";\n }\n // echo \"fractional mentorship, inclusive (FMI = A + eachC(1/(#A+#C)) )
            \\n\";\n return round($FME_score,3);\n}\n\n# -------------------------------------------------------------------------------\nfunction TA_score($person)\n{\n # total number of descendants who have advised students themselves\n $without_students = array();\n $descendents = find_descendents_for_group(array($person)); # including self\n foreach ($descendents as $d)\n {\n if (count(find_descendents_for_group(array($d))) == 1)\n {\n $without_students[] = $d;\n }\n }\n $descendents_who_advised = array_diff($descendents,$without_students); # including self\n return max(count($descendents_who_advised) - 1,0); # minus self\n}\n\n# -------------------------------------------------------------------------------\nfunction W_score($person)\n{\n # should handle multigenerational advisorships correctly...\n\n # return the max of the widths of each generation of descendents\n $descendents = array_diff(find_descendents_for_group(array($person)),array($person)); # without self # 16\n $gencount = 1;\n $advisees = find_advisorships_under_person($person); #5\n $gen_widths[$gencount] = count($advisees);\n $remaining = array_diff($descendents,$advisees); # 11\n# print \"$gencount <-- gen
            \";\n# print count($advisees).\" advisees - \";\n# print_r($advisees);\n# print \"
            \";\n# print \"
            \";\n# print count($remaining).\" remaining - \";\n# print_r($remaining);\n# print \"
            \";\n# print \"
            \";\n while (count($remaining) > 0)\n {\n $gencount++;\n# print \"$gencount <-- gen
            \";\n $advisees = advisees_of_group($advisees);\n $gen_widths[$gencount] = count($advisees);\n $remaining = array_diff($remaining,$advisees);\n# print count($advisees).\" advisees - \";\n# print_r($advisees);\n# print \"
            \";\n# print \"
            \";\n# print count($remaining).\" remaining - \";\n# print_r($remaining);\n# print \"
            \";\n# print \"
            \";\n }\n# print_r($gen_widths);\n return max($gen_widths);\n}\n\n# -------------------------------------------------------------------------------\nfunction TD_score($person)\n{\n # there is currently a bug in this implementation\n # if a student has two advisors, and they, themselves are related by mentorship\n # this algorithm currently counts gen_width based on advisee count only\n # since $td is calculated based on gen_width values, TD will be missing data\n # A is advisor to B and C\n # B is advisor to C\n # A should have a TD score of 2 (full credit for both advisees)\n # upon further reflection, perhaps this is working correctly, by accident\n\n # return the decayed score\n $descendents = array_diff(find_descendents_for_group(array($person)),array($person)); # without self # 16\n $gencount = 1;\n $advisees = find_advisorships_under_person($person); #5\n $gen_widths[$gencount] = count($advisees);\n $remaining = array_diff($descendents,$advisees); # 11\n while (count($remaining) > 0)\n {\n $gencount++;\n $advisees = advisees_of_group($advisees);\n $gen_widths[$gencount] = count($advisees);\n $remaining = array_diff($remaining,$advisees);\n }\n# print_r($gen_widths);\n $td = 0;\n foreach($gen_widths as $one => $two)\n {\n $num = $two;\n $den = (pow(2,($one-1)));\n $f = $num/$den;\n# print \"$num/$den = $f
            \";\n $td = $td + $f;\n }\n return $td;\n}\n\n# -------------------------------------------------------------------------------\nfunction G_score($person)\n{\n # there is currently a bug in this implementation\n # if a student has two advisors, and they, themselves are related by mentorship\n # this algorithm currently misses a generation in the calculation of G\n # A is advisor to B and C\n # B is advisor to C\n # A should have a G score of 2, but will only be calculated a 1\n\n\n # return the number of generations of descendents\n $descendents = array_diff(find_descendents_for_group(array($person)),array($person)); # without self # 16\n $gencount = 1;\n $advisees = find_advisorships_under_person($person); #5\n $gen_widths[$gencount] = count($advisees);\n $remaining = array_diff($descendents,$advisees); # 11\n while (count($remaining) > 0)\n {\n $gencount++;\n $advisees = advisees_of_group($advisees);\n $gen_widths[$gencount] = count($advisees);\n $remaining = array_diff($remaining,$advisees);\n }\n if ($gen_widths[1] == 0)\n {\n return 0;\n }\n else\n {\n return count($gen_widths);\n }\n}\n\n# -------------------------------------------------------------------------------\nfunction advisees_of_group($group)\n{\n # W helper function\n $advisees = array();\n foreach ($group as $one)\n {\n $advisees[] = find_advisorships_under_person($one);\n }\n $advisees = flattenArray($advisees);\n# print_r($advisees);\n# print \" <-- advisees of group
            \";\n return $advisees;\n}\n\n# -------------------------------------------------------------------------------\nfunction flattenArray($array) \n{\n $flatArray = array();\n foreach( $array as $subElement ) {\n if( is_array($subElement) )\n $flatArray = array_merge($flatArray, flattenArray($subElement));\n else\n $flatArray[] = $subElement;\n }\n return $flatArray;\n}\n\n# -------------------------------------------------------------------------------\nfunction calculate_scores($person_id)\n{\n $A_score = count(find_advisorships_under_person($person_id));\n $C_score = count(find_committeeships_under_person($person_id));\n $AC_score = $A_score + $C_score;\n $G_score = G_score($person_id);\n $W_score = W_score($person_id);\n $T_score = T_score($person_id);\n $TA_score = TA_score($person_id);\n $TD_score = TD_score($person_id);\n $FMI_score = FMI_score($person_id);\n $FME_score = FME_score($person_id);\n\n $query = \"UPDATE people\n SET\n a_score = '$A_score',\n c_score = '$C_score',\n ac_score = '$AC_score',\n g_score = '$G_score',\n w_score = '$W_score',\n t_score = '$T_score',\n ta_score = '$TA_score',\n td_score = '$TD_score',\n fmi_score = '$FMI_score',\n fme_score = '$FME_score',\n scores_calculated = now()\n WHERE\n id = \".$person_id.\"\n \";\n $result = mysql_query($query) or die(mysql_error());\n}\n\n# -------------------------------------------------------------------------------\nfunction mpact_scores($passed_person)\n{\n $glossaryterms = find_glossaryterms();\n\n $query = \"SELECT\n a_score, c_score, ac_score, g_score, w_score,\n t_score, ta_score, td_score, fmi_score, fme_score,\n scores_calculated\n FROM people\n WHERE id = \".$passed_person.\"\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result)) {\n extract($line);\n }\n \n $mpact['A'] = $a_score;\n $mpact['C'] = $c_score;\n $mpact['AC'] = $ac_score;\n $scores_output = \"A = $a_score
            \\n\";\n $scores_output .= \"C = $c_score
            \\n\";\n $scores_output .= \"A+C = $ac_score
            \\n\";\n\n $mpact['FMI'] = $fmi_score;\n $mpact['FME'] = $fme_score;\n $FMIdivFULL = ($ac_score>0) ? $fmi_score / $ac_score : 0;\n $FMIdivFULL = round($FMIdivFULL,3);\n $mpact['FMIdivFULL'] = $FMIdivFULL;\n $FMEdivFULL = ($ac_score>0) ? $fme_score / $ac_score : 0;\n $FMEdivFULL = round($FMEdivFULL,3);\n $mpact['FMEdivFULL'] = $FMEdivFULL;\n if (is_admin())\n {\n $scores_output .= \"FMI = $fmi_score
            \\n\";\n $scores_output .= \"FME = $fme_score
            \\n\";\n $scores_output .= \"FMI/(A+C) = $FMIdivFULL
            \\n\";\n $scores_output .= \"FME/(A+C) = $FMEdivFULL
            \\n\";\n }\n\n $mpact['T'] = $t_score;\n $scores_output .= \"T = $t_score
            \\n\";\n $mpact['G'] = $g_score;\n $scores_output .= \"G = $g_score
            \\n\";\n $mpact['W'] = $w_score;\n $scores_output .= \"W = $w_score
            \\n\";\n $mpact['TD'] = $td_score;\n $scores_output .= \"D']].\"\\\">TD = $td_score
            \\n\";\n $mpact['TA'] = $ta_score;\n $scores_output .= \"A']].\"\\\">TA = $ta_score
            \\n\";\n $scores_output .= \"calculated $scores_calculated
            \\n\";\n $mpact['output'] = $scores_output;\n\n return $mpact;\n}\n\n# -------------------------------------------------------------------------------\nfunction find_advisors_for_person($person_id)\n{\n\n // get person's own advisor(s)\n\n $listing = array();\n\n\n $query = \"SELECT a.person_id\n FROM\n dissertations d,\n advisorships a\n WHERE\n d.person_id = \".$person_id.\" AND\n a.dissertation_id = d.id\n \";\n\n $result = mysql_query($query) or die(mysql_error());\n \n while ( $line = mysql_fetch_array($result))\n {\n $listing[] = $line['person_id'];\n }\n\n return $listing;\n}\n\n# -------------------------------------------------------------------------------\nfunction find_committee_for_person($person_id)\n{\n\n // get person's own committee member(s)\n\n $listing = array();\n\n $query = \"SELECT c.person_id\n FROM\n dissertations d,\n committeeships c\n WHERE\n d.person_id = \".$person_id.\" AND\n c.dissertation_id = d.id\n \";\n\n $result = mysql_query($query) or die(mysql_error());\n \n while ( $line = mysql_fetch_array($result))\n {\n $listing[] = $line['person_id'];\n }\n\n return $listing;\n}\n\n# -------------------------------------------------------------------------------\nfunction find_advisorships_under_person($person_id)\n{\n\n // get person's advisorships (below)\n\n $listing = array();\n\n $query = \"SELECT d.person_id\n FROM\n dissertations d,\n advisorships a\n WHERE\n a.person_id = \".$person_id.\" AND\n a.dissertation_id = d.id\n ORDER BY\n d.completedyear ASC\n \";\n\n $result = mysql_query($query) or die(mysql_error());\n \n while ( $line = mysql_fetch_array($result))\n {\n $listing[] = $line['person_id'];\n }\n\n return $listing;\n}\n\n# -------------------------------------------------------------------------------\nfunction find_committeeships_under_person($person_id)\n{\n\n // get person's committeeships (below)\n\n $listing = array();\n\n $query = \"SELECT d.person_id\n FROM\n dissertations d,\n committeeships c\n WHERE\n c.person_id = '\".$person_id.\"' AND\n c.dissertation_id = d.id\n ORDER BY\n d.completedyear\n \";\n\n $result = mysql_query($query) or die(mysql_error());\n \n while ( $line = mysql_fetch_array($result))\n {\n $listing[] = $line['person_id'];\n }\n\n return $listing;\n}\n\n# -------------------------------------------------------------------------------\nfunction set_preferred_name($person_id,$name_id)\n{\n\n # delete current family tree of dotgraphs\n delete_associated_dotgraphs($person_id);\n\n # set it\n\n $listing = array();\n\n $before = find_person($person_id);\n\n $query = \"UPDATE people\n SET\n preferred_name_id = '\".$name_id.\"'\n WHERE\n id = '\".$person_id.\"'\n \";\n\n $result = mysql_query($query) or die(mysql_error());\n\n $after = find_person($person_id);\n\n # log it\n mpact_logger(\"set preferred name for person[\".$person_id.\"] from name[\".$before['preferred_name_id'].\"] (\".$before['fullname'].\") to name[\".$name_id.\"] (\".$after['fullname'].\")\");\n}\n\n# -------------------------------------------------------------------------------\nfunction generate_profs_at_dept($school_id,$discipline_id)\n{\n\n $dissertations = array();\n $listing = array();\n $advisors = array();\n $committeemembers = array();\n\n // get all dissertations at this dept\n\n $query = \"SELECT d.id\n FROM dissertations d, schools s\n WHERE\n d.school_id = s.id AND\n s.id = '\".$school_id.\"' AND\n d.discipline_id = '\".$discipline_id.\"'\n \";\n\n $result = mysql_query($query) or die(mysql_error());\n\n while ( $line = mysql_fetch_array($result))\n {\n $dissertations[] = $line['id'];\n }\n\n if (count($dissertations)>0)\n {\n // get all advisors for these dissertations\n\n $query = \"SELECT a.person_id\n FROM dissertations d, advisorships a\n WHERE\n a.dissertation_id IN (\";\n $query .= implode(\", \", $dissertations);\n $query .= \") AND\n a.dissertation_id = d.id\";\n\n $result = mysql_query($query) or die(mysql_error());\n\n while ( $line = mysql_fetch_array($result))\n {\n $advisors[$line['person_id']] = $line['person_id'];\n }\n \n // get all committeemembers for these dissertations\n\n $query = \"SELECT c.person_id\n FROM dissertations d, committeeships c\n WHERE\n c.dissertation_id IN (\";\n $query .= implode(\", \", $dissertations);\n $query .= \") AND\n c.dissertation_id = d.id\";\n\n $result = mysql_query($query) or die(mysql_error());\n\n while ( $line = mysql_fetch_array($result))\n {\n $committeemembers[$line['person_id']] = $line['person_id'];\n }\n }\n\n // return the combined list (uniquified when combined)\n\n// echo \"\\na - \".count($advisors);\n// echo \"\\nc - \".count($committeemembers);\n $listing = $advisors + $committeemembers;\n// echo \"\\ncombined before - \".count($listing);\n return $listing;\n\n}\n\n# -------------------------------------------------------------------------------\nfunction find_profs_at_dept($school_id,$discipline_id)\n{\n $query = \"SELECT professors\n FROM profs_at_dept\n WHERE\n school_id = '$school_id' AND\n discipline_id = '$discipline_id'\n \";\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result))\n {\n $listing = unserialize($line['professors']);\n }\n return $listing;\n\n}\n\n# -------------------------------------------------------------------------------\nfunction find_disciplines($school_id=null)\n{\n\n $disciplines = array();\n if ($school_id)\n {\n // get all disciplines at this school\n $query = \"SELECT d.id, d.title\n FROM\n disciplines d, schools s, dissertations diss\n WHERE\n diss.school_id = s.id AND\n diss.discipline_id = d.id AND\n s.id = '$school_id'\n ORDER BY\n d.title\n \";\n }\n else\n {\n $query = \"SELECT id, title\n FROM\n disciplines d\n ORDER BY\n title\n \";\n }\n $result = mysql_query($query) or die(mysql_error());\n\n while ( $line = mysql_fetch_array($result))\n {\n $disciplines[$line['id']] = $line['title'];\n }\n\n if (isset($disciplines))\n {\n return $disciplines;\n }\n}\n\n# -------------------------------------------------------------------------------\nfunction is_duplicate_discipline($title)\n{\n $disciplinefound = 0;\n\n $query = \"SELECT id FROM disciplines WHERE title = '$title'\";\n $result = mysql_query($query) or die(mysql_error());\n\n while ( $line = mysql_fetch_array($result))\n {\n $disciplinefound = $line['id'];\n }\n\n if ($disciplinefound > 0){\n return true;\n }\n\n return false;\n}\n\n# -------------------------------------------------------------------------------\nfunction is_empty_discipline($discipline_id)\n{\n $query = \"SELECT count(*) as howmany FROM dissertations WHERE discipline_id = $discipline_id\";\n $result = mysql_query($query) or die(mysql_error());\n\n while ( $line = mysql_fetch_array($result))\n {\n extract($line);\n }\n\n if ($howmany > 0){\n return false;\n }\n\n return true;\n}\n\n# -------------------------------------------------------------------------------\nfunction is_duplicate_school($fullname)\n{\n $schoolfound = 0;\n\n $query = \"SELECT id FROM schools WHERE fullname = '$fullname'\";\n $result = mysql_query($query) or die(mysql_error());\n\n while ( $line = mysql_fetch_array($result))\n {\n $schoolfound = $line['id'];\n }\n\n if ($schoolfound > 0){\n return true;\n }\n\n return false;\n}\n\n# -------------------------------------------------------------------------------\nfunction is_empty_school($school_id)\n{\n $query = \"SELECT count(*) as howmany FROM dissertations WHERE school_id = $school_id\";\n $result = mysql_query($query) or die(mysql_error());\n\n while ( $line = mysql_fetch_array($result))\n {\n extract($line);\n }\n\n if ($howmany > 0){\n return false;\n }\n\n return true;\n}\n\n# -------------------------------------------------------------------------------\nfunction find_discipline_counts()\n{\n \n // get all discipline counts from the database\n\n $disciplinecounts = array();\n \n $query = \"SELECT discipline_id, count(*) as disciplinecount\n FROM dissertations\n GROUP BY discipline_id\n \";\n \n $result = mysql_query($query) or die(mysql_error());\n\n while ( $line = mysql_fetch_array($result))\n {\n $disciplinecounts[$line['discipline_id']] = $line['disciplinecount'];\n }\n\n if (isset($disciplinecounts))\n {\n return $disciplinecounts;\n }\n}\n\n# -------------------------------------------------------------------------------\nfunction find_discipline_statuses($discipline_id)\n{\n\n // get status counts for this discipline\n\n GLOBAL $statuscodes;\n\n $statuscounts = array();\n \n $query = \"SELECT status, count(*) as disciplinecount\n FROM dissertations\n WHERE discipline_id='$discipline_id'\n GROUP BY status\n \";\n\n $result = mysql_query($query) or die(mysql_error());\n\n while ( $line = mysql_fetch_array($result))\n {\n $statuscounts[$line['status']] = $line['disciplinecount'];\n }\n\n foreach (range(0,4) as $one)\n {\n if (!isset($statuscounts[$one]))\n {\n $statuscounts[$one] = 0;\n }\n }\n return $statuscounts;\n}\n\n# -------------------------------------------------------------------------------\nfunction find_dept_counts($school_id,$discipline_id)\n{\n \n // get all department counts from the database\n\n $deptcounts = array();\n \n $query = \"SELECT discipline_id, count(*) as disciplinecount\n FROM dissertations\n GROUP BY discipline_id\n \";\n \n $result = mysql_query($query) or die(mysql_error());\n\n while ( $line = mysql_fetch_array($result))\n {\n $deptcounts[$line['discipline_id']] = $line['disciplinecount'];\n }\n\n if (isset($deptcounts))\n {\n return $deptcounts;\n }\n}\n\n# -------------------------------------------------------------------------------\nfunction find_dept_statuses($school_id,$discipline_id)\n{\n\n // get status counts for this school in this discipline\n\n GLOBAL $statuscodes;\n\n $statuscounts = array();\n \n $query = \"SELECT status, count(*) as disciplinecount\n FROM dissertations\n WHERE\n discipline_id='$discipline_id' AND\n school_id='$school_id'\n GROUP BY status\n \";\n\n $result = mysql_query($query) or die(mysql_error());\n\n while ( $line = mysql_fetch_array($result))\n {\n $statuscounts[$line['status']] = $line['disciplinecount'];\n }\n\n foreach (range(0,4) as $one)\n {\n if (!isset($statuscounts[$one]))\n {\n $statuscounts[$one] = 0;\n }\n }\n return $statuscounts;\n}\n\n# -------------------------------------------------------------------------------\nfunction find_schools($discipline_id=null)\n{\n // get all schools in a discipline (or all disciplines)\n $schools = array();\n if ($discipline_id)\n {\n // look up schools at dissertations in this discipline\n $query = \"SELECT s.id, s.fullname\n FROM\n dissertations d, schools s\n WHERE\n d.school_id = s.id AND\n d.discipline_id = '$discipline_id'\n GROUP BY\n d.school_id\n ORDER BY\n s.fullname ASC\n \";\n }\n else\n {\n $query = \"SELECT id, fullname\n FROM\n schools s\n ORDER BY fullname\n \";\n }\n $result = mysql_query($query) or die(mysql_error());\n while ( $line = mysql_fetch_array($result))\n {\n $schools[$line['id']] = $line['fullname'];\n }\n\n if (isset($schools))\n {\n return $schools;\n }\n}\n\n# -------------------------------------------------------------------------------\nfunction find_school_counts()\n{\n \n // get all school dissertation counts from the database\n\n $schoolcounts = array();\n \n $query = \"SELECT school_id, count(*) as disscount\n FROM dissertations\n GROUP BY school_id\n \";\n \n $result = mysql_query($query) or die(mysql_error());\n\n while ( $line = mysql_fetch_array($result))\n {\n $schoolcounts[$line['school_id']] = $line['disscount'];\n }\n\n if (isset($schoolcounts))\n {\n return $schoolcounts;\n }\n}\n\n# -------------------------------------------------------------------------------\nfunction find_school_statuses($school_id)\n{\n\n // get status counts for this school\n\n GLOBAL $statuscodes;\n\n $statuscounts = array();\n \n $query = \"SELECT status, count(*) as disscount\n FROM dissertations\n WHERE school_id='$school_id'\n GROUP BY status\n \";\n\n $result = mysql_query($query) or die(mysql_error());\n\n while ( $line = mysql_fetch_array($result))\n {\n $statuscounts[$line['status']] = $line['disscount'];\n }\n\n foreach (range(0,4) as $one)\n {\n if (!isset($statuscounts[$one]))\n {\n $statuscounts[$one] = 0;\n }\n }\n return $statuscounts;\n}\n\n\n# -------------------------------------------------------------------------------\nfunction find_persons_school($passed_person)\n{\n\n // get person's degree school\n\n $query = \"SELECT\n d.id as dissertation_id,\n d.completedyear,\n d.title,\n d.abstract,\n s.fullname,\n s.country,\n s.id as schoolid\n FROM\n dissertations d,\n schools s\n WHERE\n d.person_id = \".$passed_person.\" AND\n d.school_id = s.id\n \";\n\n $result = mysql_query($query) or die(mysql_error());\n \n while ( $line = mysql_fetch_array($result)) {\n $thisperson['dissertation_id'] = $line['dissertation_id'];\n $thisperson['completedyear'] = $line['completedyear'];\n $thisperson['title'] = $line['title'];\n $thisperson['abstract'] = $line['abstract'];\n $thisperson['country'] = $line['country'];\n $thisperson['school'] = $line['fullname'];\n $thisperson['schoolid'] = $line['schoolid'];\n }\n\n if (isset($thisperson))\n {\n return $thisperson;\n }\n}\n\n# -------------------------------------------------------------------------------\nfunction find_school($school_id)\n{\n\n // get school\n\n $query = \"SELECT\n s.fullname,\n s.country\n FROM\n schools s\n WHERE\n s.id = \".$school_id.\"\n \";\n\n $result = mysql_query($query) or die(mysql_error());\n \n while ( $line = mysql_fetch_array($result)) {\n $school['country'] = $line['country'];\n $school['fullname'] = $line['fullname'];\n }\n\n if (isset($school))\n {\n return $school;\n }\n}\n\n# -------------------------------------------------------------------------------\nfunction get_environment_info()\n{\n $host_info = array();\n $hostname = $_SERVER['SERVER_NAME'];\n if ($hostname == \"\"){$hostname = exec(hostname);}\n# echo \"hostname = [$hostname]
            \";\n if ($hostname == \"www.ibiblio.org\" || $hostname == \"www-dev.ibiblio.org\" || $hostname == \"login1.ibiblio.org\")\n {\n # the main install on ibiblio\n $host_info['hostname'] = \"ibiblio\";\n $host_info['ownername'] = \"mpact\";\n $host_info['dotlocation'] = \"/export/sunsite/users/mpact/terrelllocal/bin/dot\";\n $host_info['appdir'] = \"/public/html/mpact\";\n $host_info['webdir'] = \"http://www.ibiblio.org/mpact\";\n $host_info['dotcachedir'] = \"dotgraphs\";\n $host_info['dotfiletype'] = \"png\";\n $host_info['dotfontface'] = \"Times-Roman\";\n }\n else if ($hostname == \"trel.dyndns.org\")\n {\n # my local development machine\n $host_info['hostname'] = \"home\";\n $host_info['ownername'] = \"trel\";\n $host_info['dotlocation'] = \"/sw/bin/dot\";\n $host_info['appdir'] = \"/Library/WebServer/Documents/MPACTlocal/app\";\n $host_info['webdir'] = \"http://trel.dyndns.org:9000/mpactlocal/app\";\n $host_info['dotcachedir'] = \"dotgraphs\";\n $host_info['dotfiletype'] = \"png\";\n $host_info['dotfontface'] = \"cour\";\n }\n else if ($hostname == \"localhost.com\" || $hostname == \"trelpancake\")\n {\n # my laptop\n $host_info['hostname'] = \"laptop\";\n $host_info['ownername'] = \"trel\";\n $host_info['dotlocation'] = \"/opt/local/bin/dot\";\n $host_info['appdir'] = \"/Users/trel/Sites/MPACT\";\n $host_info['webdir'] = \"http://localhost.com/~trel/MPACT\";\n $host_info['dotcachedir'] = \"dotgraphs\";\n $host_info['dotfiletype'] = \"png\";\n $host_info['dotfontface'] = \"cour\";\n }\n else\n {\n # unknown host\n #exit;\n }\n\n return $host_info;\n}\n\n# -------------------------------------------------------------------------------\nfunction delete_associated_dotgraphs($passed_person)\n{\n $host_info = get_environment_info();\n $group = array($passed_person);\n $ancestors = find_ancestors_for_group($group);\n $descendents = find_descendents_for_group($group);\n $entire_family_tree = array_unique($ancestors + $descendents);\n foreach ($entire_family_tree as $one)\n {\n # set the filenames\n $dotfilename = $host_info['appdir'].\"/\".$host_info['dotcachedir'].\"/$one.dot\";\n $imagefilename = $host_info['appdir'].\"/\".$host_info['dotcachedir'].\"/$one.\".$host_info['dotfiletype'];\n $imagemapfilename = $host_info['appdir'].\"/\".$host_info['dotcachedir'].\"/$one.map\";\n # delete each if they exist\n if (file_exists($dotfilename))\n {\n `rm $dotfilename`;\n }\n if (file_exists($imagefilename))\n {\n `rm $imagefilename`;\n }\n if (file_exists($imagemapfilename))\n {\n `rm $imagemapfilename`;\n }\n # mark as 'dirty' so cronjob can recreate images\n mark_record_as_dirty($one);\n }\n}\n\n# -------------------------------------------------------------------------------\nfunction mark_record_as_dirty($passed_person)\n{\n # mark database record for this person as dirty\n # a cronjob will pick these up and regenerate their dotgraphs\n # gets around permission issues on the server if necessary\n $query = \"UPDATE people SET regenerate_dotgraph = '1' WHERE id = '\".$passed_person.\"'\";\n $result = mysql_query($query) or die(mysql_error());\n}\n\n# -------------------------------------------------------------------------------\nfunction narray_slice($array, $offset, $length) {\n # http://us3.php.net/manual/en/function.array-slice.php#73882\n\n //Check if this version already supports it\n if (str_replace('.', '', PHP_VERSION) >= 502)\n return array_slice($array, $offset, $length, true);\n\n foreach ($array as $key => $value) {\n\n if ($a >= $offset && $a - $offset <= $length)\n $output_array[$key] = $value;\n $a++;\n\n }\n return $output_array;\n}\n\n# -------------------------------------------------------------------------------\nfunction generate_dotfile($passed_person){\n $a = find_person($passed_person);\n if ($a == null)\n {\n return 0;\n }\n else\n {\n $dotfilecontents = \"\";\n $dotfilecontents .= \"digraph familytree\\n\";\n $dotfilecontents .= \"{\\n\";\n $dotfilecontents .= \"rankdir=\\\"LR\\\"\\n\";\n $dotfilecontents .= \"node [fontname = Times, fontsize=10, shape = rect, height=.15]\\n\";\n # ancestors\n $upgroup = array();\n $upgroup[] = $passed_person;\n $ancestors = find_ancestors_for_group($upgroup);\n foreach ($ancestors as $one)\n {\n $person = find_person($one);\n $dotfilecontents .= \"$one [label = \\\"\".$person['fullname'].\"\\\" URL=\\\"mpact.php?op=show_tree&id=\".$one.\"\\\"];\\n\";\n $advisors = find_advisors_for_person($one);\n foreach ($advisors as $adv)\n {\n $dotfilecontents .= \"$adv -> $one;\\n\";\n }\n }\n # descendents\n $downgroup = array();\n $downgroup[] = $passed_person;\n $descendents = find_descendents_for_group($downgroup);\n foreach ($descendents as $one)\n {\n $person = find_person($one);\n $dotfilecontents .= \"$one [label = \\\"\".$person['fullname'].\"\\\" URL=\\\"mpact.php?op=show_tree&id=\".$one.\"\\\"\";\n if ($one == $passed_person){\n $dotfilecontents .= \" color=\\\"red\\\" style=\\\"filled\\\" fillcolor=\\\"grey\\\"\";\n }\n $dotfilecontents .= \"];\\n\";\n $advisees = find_advisorships_under_person($one);\n foreach ($advisees as $adv)\n {\n $dotfilecontents .= \"$one -> $adv;\\n\";\n }\n }\n $dotfilecontents .= \"}\\n\";\n\n return $dotfilecontents;\n }\n}\n\n# -------------------------------------------------------------------------------\nfunction draw_tree_dotgraph($passed_person)\n{\n $person = $passed_person;\n $host_info = get_environment_info();\n if (isset($host_info['appdir']))\n {\n $webfilename = generate_dotgraph($person);\n if ($webfilename == \"marked_as_dirty\"){\n echo \"generating graph, please reload\";\n }\n else{\n echo \"\\\"Directed
            \";\n }\n }\n else\n {\n echo \"graphics libraries are not configured\";\n }\n}\n\n# -------------------------------------------------------------------------------\nfunction generate_dotgraph($passed_person, $forcenew=\"no\")\n{\n $person = $passed_person;\n $host_info = get_environment_info();\n# print_r($host_info);\n $appcache = $host_info['appdir'].\"/\".$host_info['dotcachedir'];\n $webcache = $host_info['webdir'].\"/\".$host_info['dotcachedir'];\n $appfilename = \"$appcache/$person.\".$host_info['dotfiletype'];\n# echo \"appfilename = $appfilename
            \\n\";\n $dotfilename = \"$appcache/$person.dot\";\n# echo \"dotfilename = $dotfilename
            \\n\";\n $webfilename = \"$webcache/$person.\".$host_info['dotfiletype'];\n# echo \"webfilename = $webfilename
            \\n\";\n $appimagemap = \"$appcache/$person.map\";\n# echo \"appimagemap = $appimagemap
            \\n\";\n\n if (!file_exists($appfilename)) {\n # assumption is that the cachedir exists... (run setupmpact.sh)\n # generate dotfile\n if (!file_exists($dotfilename) or $forcenew == \"force\") {\n# print \" - creating dotfile...\\n\";\n $dotfilecontents = generate_dotfile($person);\n $fh = fopen($dotfilename, 'w');\n fwrite($fh, $dotfilecontents);\n fclose($fh);\n exec(\"chmod 666 $dotfilename\");\n }\n # generate graph\n $getandgenerategraph = \"/bin/cat $dotfilename | \".$host_info['dotlocation'].\" -Nfontname=\".$host_info['dotfontface'].\" -Gcharset=latin1 -Tcmapx -o$appimagemap -T\".$host_info['dotfiletype'].\" -o$appfilename 2>&1\";\n# echo \"getandgenerategraph = $getandgenerategraph
            \";\n exec($getandgenerategraph);\n exec(\"chmod 666 $appimagemap\");\n exec(\"chmod 666 $appfilename\");\n if (!file_exists($appfilename)) {\n # mark as dirty if it didn't work\n mark_record_as_dirty($person);\n return \"marked_as_dirty\";\n }\n }\n else\n {\n# echo \"SHOWING CACHED COPY
            \";\n }\n\n return $webfilename;\n}\n\n# -------------------------------------------------------------------------------\nfunction draw_graph($passed_person)\n{\n if (!$passed_person){action_box(\"No ID given.\");}\n\n $person = $passed_person;\n $host_info = get_environment_info();\n if (isset($host_info['appdir']))\n {\n $appcache = $host_info['appdir'].\"/\".$host_info['dotcachedir'];\n $webcache = $host_info['webdir'].\"/\".$host_info['dotcachedir'];\n $appfilename = \"$appcache/$person.\".$host_info['dotfiletype'];\n #echo \"appfilename = $appfilename
            \";\n $webfilename = \"$webcache/$person.\".$host_info['dotfiletype'];\n #echo \"webfilename = $webfilename
            \";\n $appimagemap = \"$appcache/$person.map\";\n #echo \"appimagemap = $appimagemap
            \";\n\n\n echo \"\";\n echo file_get_contents($appimagemap);\n }\n else\n {\n echo \"graphics libraries are not configured\";\n }\n}\n\n# -------------------------------------------------------------------------------\nfunction draw_tree($passed_person)\n{\n GLOBAL $statuscodes;\n GLOBAL $inspectioncodes;\n\n // shows a person\n\n if (!$passed_person){action_box(\"No ID given.\");}\n else\n {\n $personcount = 0;\n $thisperson = array();\n $dissertation = array();\n\n // get person's preferred name\n\n $query = \"SELECT\n n.firstname, n.middlename,\n n.lastname, n.suffix, p.degree\n FROM\n names n, people p\n WHERE\n p.preferred_name_id = n.id AND\n p.id = '\".$passed_person.\"'\n \";\n $result = mysql_query($query) or die(mysql_error());\n \n while ( $line = mysql_fetch_array($result)) {\n $thisperson['firstname'] = $line['firstname'];\n $thisperson['middlename'] = $line['middlename'];\n $thisperson['lastname'] = $line['lastname'];\n $thisperson['suffix'] = $line['suffix'];\n $thisperson['degree'] = $line['degree'];\n $personcount++;\n }\n\n $schoolinfo = find_persons_school($passed_person);\n $thisperson['dissertation_id'] = $schoolinfo['dissertation_id'];\n $thisperson['completedyear'] = $schoolinfo['completedyear'];\n $thisperson['country'] = $schoolinfo['country'];\n $thisperson['school'] = $schoolinfo['school'];\n $thisperson['schoolid'] = $schoolinfo['schoolid'];\n\n if ($thisperson['dissertation_id'] == \"\")\n {\n $thisperson['status'] = \"\";\n $thisperson['notes'] = \"\";\n $thisperson['title'] = \"N/A\";\n $thisperson['abstract'] = \"N/A\";\n $thisperson['abstract_html'] = \"N/A\";\n }\n else\n {\n $dissertation = find_dissertation($thisperson['dissertation_id']);\n $thisperson['status'] = $dissertation['status'];\n $thisperson['notes'] = $dissertation['notes'];\n $thisperson['discipline_id'] = $dissertation['discipline_id'];\n $thisperson['title'] = $dissertation['title'];\n $thisperson['abstract'] = $dissertation['abstract'];\n $thisperson['abstract_html'] = encode_linebreaks($dissertation['abstract']);\n if ($thisperson['title'] == \"\") { $thisperson['title'] = \"N/A\";}\n if ($thisperson['abstract'] == \"\")\n {\n $thisperson['abstract'] = \"N/A\";\n $thisperson['abstract_html'] = \"N/A\";\n }\n }\n\n $thisperson['advisors'] = find_advisors_for_person($passed_person);\n $thisperson['cmembers'] = find_committee_for_person($passed_person);\n $thisperson['advisorships'] = find_advisorships_under_person($passed_person);\n $thisperson['committeeships'] = find_committeeships_under_person($passed_person);\n\n\n if ($personcount < 1)\n {\n action_box(\"Person \".$passed_person.\" Not Found\");\n }\n else\n {\n\n echo \"
            \\n\";\n\n # Name / Aliases\n $count = 0;\n $printme = \"\";\n $fullname = $thisperson['firstname'].\" \".$thisperson['middlename'].\" \".$thisperson['lastname'].\" \".$thisperson['suffix'];\n $printme .= \"

            Dissertation Information for $fullname

            \";\n $printme .= \"

            \";\n if (is_admin())\n {\n if (isset($thisperson['completedyear']))\n {\n $printme .= \" (Edit)\";\n }\n else\n {\n $printme .= \" (Create Dissertation for $fullname)\";\n }\n $printme .= \"
            \\n\";\n }\n $printme .= \"

            \";\n $printme .= \"

            \";\n $printme .= \"NAME: \";\n if (is_admin())\n {\n $printme .= \"(Add)\";\n }\n $printme .= \"
            \";\n $printme .= \" - \";\n $printme .= get_person_link($passed_person);\n if (is_admin())\n {\n $printme .= \" (Edit)\";\n }\n $printme .= \"
            \\n\";\n\n $aliases = 0;\n foreach (find_aliases($passed_person) as $one)\n {\n $printme .= \" - (Alias) \";\n $printme .= $one['firstname'].\" \";\n $printme .= $one['middlename'].\" \";\n $printme .= $one['lastname'].\" \";\n $printme .= $one['suffix'].\" \";\n if (is_admin())\n {\n $printme .= \"(Set as Primary)\";\n $printme .= \" (Delete)\";\n }\n $printme .= \"
            \";\n $aliases++;\n }\n $printme .= \"

            \";\n echo $printme;\n\n # Degree\n $printme = \"

            \\n\";\n $printme .= \"DEGREE:
            \\n\";\n $printme .= \" - \".$thisperson['degree'];\n if (is_admin())\n {\n $printme .= \" (Edit)\";\n }\n $printme .= \"

            \";\n echo $printme;\n\n # Discipline\n $printme = \"

            \\n\";\n $printme .= \"DISCIPLINE:
            \\n\";\n if (isset($thisperson['discipline_id']))\n {\n $discipline = find_discipline($thisperson['discipline_id']);\n $printme .= \" - \".$discipline['title'].\"\";\n if (is_admin())\n {\n $printme .= \" (Edit)\";\n }\n }\n else\n {\n $printme .= \" - None\";\n if (is_admin())\n {\n $printme .= \" (Create Dissertation for $fullname)\";\n }\n }\n $printme .= \"

            \";\n echo $printme;\n\n # School\n $printme = \"

            \\n\";\n $printme .= \"SCHOOL:
            \\n\";\n if (isset($thisperson['completedyear']))\n {\n $printme .= \" - \".$thisperson['school'].\" (\".$thisperson['country'].\") (\".$thisperson['completedyear'].\")\";\n if (is_admin())\n {\n $printme .= \" (Edit)\";\n }\n }\n else\n {\n $printme .= \" - None\";\n if (is_admin())\n {\n $printme .= \" (Create Dissertation for $fullname)\";\n }\n }\n $printme .= \"

            \\n\";\n echo $printme;\n\n\n # Advisors\n $count = 0;\n $printme = \"\";\n $printme .= \"

            \";\n $printme .= \"ADVISORS: \";\n if (is_admin() && isset($thisperson['completedyear']))\n {\n $printme .= \" (Add)\";\n }\n $printme .= \"
            \";\n if (isset($thisperson['advisors'])){\n foreach ($thisperson['advisors'] as $one)\n {\n $printme .= \" - \";\n $printme .= get_person_link($one);\n if (is_admin())\n {\n $printme .= \" (Remove)\";\n }\n $printme .= \"
            \";\n $count++;\n }\n }\n if ($count < 1){$printme .= \" - None\";}\n $printme .= \"

            \";\n echo $printme;\n\n # Committee Members\n $count = 0;\n $printme = \"\";\n $printme .= \"

            \";\n $printme .= \"COMMITTEE MEMBERS: \";\n if (is_admin() && isset($thisperson['completedyear']))\n {\n $printme .= \" (Add)\";\n }\n $printme .= \"
            \";\n if (isset($thisperson['cmembers'])){\n foreach ($thisperson['cmembers'] as $one)\n {\n $printme .= \" - \";\n $printme .= get_person_link($one);\n if (is_admin())\n {\n $printme .= \" (Remove)\";\n }\n $printme .= \"
            \";\n $count++;\n }\n }\n if ($count < 1){$printme .= \" - None\";}\n $printme .= \"

            \\n\\n\";\n\n # Admin Notes\n if (is_admin())\n {\n if ($thisperson['notes'] != \"\")\n {\n $printme .= \"

            \";\n $printme .= \"\\n\";\n $printme .= \"\\n\";\n $printme .= \"
            \\n\";\n $printme .= \"Admin Notes: \".$thisperson['notes'].\"
            \\n\";\n $printme .= \"
            \\n\";\n $printme .= \"

            \\n\\n\";\n }\n }\n\n $glossaryterms = find_glossaryterms();\n # Status and Inspection\n $printme .= \"

            \";\n $printme .= \"MPACT Status: \".$statuscodes[$thisperson['status']].\"
            \\n\";\n $printme .= \"

            \\n\\n\";\n\n # Title and Abstract\n $printme .= \"

            \";\n $printme .= \"Title: \".$thisperson['title'].\"
            \";\n $printme .= \"

            \\n\";\n $printme .= \"

            \";\n $printme .= \"Abstract: \".$thisperson['abstract_html'].\"
            \";\n $printme .= \"

            \\n\\n\";\n\n # print it all out...\n echo $printme;\n\n # URLS\n\n if (is_admin())\n {\n $urls = find_urls_by_person($passed_person);\n echo \"

            \\n\";\n echo \"REFERENCE URLS\";\n echo \" (Add)\";\n echo \"
            \\n\";\n if (count($urls) > 0)\n {\n echo \"\\n\";\n }\n else\n {\n echo \" - None\\n\";\n }\n foreach ($urls as $one)\n {\n echo \"\\n\";\n echo \"\\n\";\n echo \"\\n\";\n }\n if (count($urls) > 0)\n {\n echo \"
            Updated: \".$one['updated_at'].\"\";\n echo \" (Edit)\";\n echo \" (Delete)\";\n echo \"
            \".$one['url'].\"
            \".$one['description'].\"
            \\n\";\n }\n echo \"

            \\n\";\n }\n\n # EDIT HISTORY\n \n if (is_admin())\n {\n $entries = get_dissertation_history($thisperson['dissertation_id']);\n if (count($entries) > 0)\n {\n echo \"

            \\n\";\n echo \"EDIT HISTORY (Show/Hide)\\n\";\n echo \"\";\n echo \"\\n\";\n }\n\n foreach ($entries as $one)\n {\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\\n\";\n }\n if (count($entries) > 0)\n {\n echo \"
            \".$one['logged_at'].\"\".$one['user'].\"\".$one['message'].\"
            \\n\";\n echo \"

            \\n\";\n }\n }\n\n\n\n echo \"
            \\n\";\n\n # MPACT Scores\n $printme = \"\";\n $printme .= \"

            MPACT Scores for $fullname

            \";\n $printme .= \"

            \";\n $mpact = mpact_scores($passed_person);\n $printme .= $mpact['output'];\n $printme .= \"

            \\n\";\n if (is_admin())\n {\n $printme .= \"

            (Recalculate)

            \";\n }\n echo $printme;\n\n # Draw FamilyTree Graph for this person\n echo \"

            Advisors and Advisees Graph

            \\n\";\n echo \"

            \";\n draw_tree_dotgraph($passed_person);\n echo \"

            \";\n\n echo \"
            \\n\";\n\n\n # Students\n echo \"

            Students under $fullname

            \\n\\n\";\n\n # Advisees\n $count = 0;\n $printme = \"\";\n $printme .= \"

            \";\n $printme .= \"ADVISEES: \";\n if (is_admin())\n {\n $printme .= \" (Add)\";\n }\n $printme .= \"
            \";\n if (isset($thisperson['advisorships'])){\n foreach ($thisperson['advisorships'] as $one)\n {\n $printme .= \" - \";\n $printme .= get_person_link($one);\n $schoolinfo = find_persons_school($one);\n if (isset($schoolinfo['completedyear']))\n {\n $printme .= \" - \".$schoolinfo['school'].\" (\".$schoolinfo['completedyear'].\")\";\n }\n if (is_admin())\n {\n $printme .= \" (Remove)\";\n }\n $printme .= \"
            \";\n $count++;\n }\n }\n if ($count < 1){$printme .= \" - None\";}\n $printme .= \"

            \\n\";\n echo $printme;\n\n # Committeeships\n $ccount = 0;\n $printme = \"\";\n $printme .= \"

            \";\n $printme .= \"COMMITTEESHIPS: \";\n if (is_admin())\n {\n $printme .= \" (Add)\";\n }\n $printme .= \"
            \";\n if (isset($thisperson['committeeships'])){\n foreach ($thisperson['committeeships'] as $one)\n {\n $printme .= \" - \";\n $printme .= get_person_link($one);\n $schoolinfo = find_persons_school($one);\n if (isset($schoolinfo['completedyear']))\n {\n $printme .= \" - \".$schoolinfo['school'].\" (\".$schoolinfo['completedyear'].\")\";\n }\n if (is_admin())\n {\n $printme .= \" (Remove)\";\n }\n $printme .= \"
            \";\n $count++;\n }\n }\n if ($count < 1){$printme .= \" - None\";}\n $printme .= \"

            \";\n echo $printme;\n\n }\n \n }\n\n\n}\n\n\n?>\n"}, "files_after": {"mpact.php": " \"N/A\",\n \"-1\" => \"N/A\",\n \"0\" => \"Incomplete - Not_Inspected\",\n \"1\" => \"Incomplete - Inspected\",\n \"2\" => \"Incomplete - Ambiguous\",\n \"3\" => \"Complete - Except Indecipherables\",\n \"4\" => \"Fully Complete\"\n);\n\n$inspectioncodes = array(\n NULL => \"N/A\",\n \"0\" => \"No\",\n \"1\" => \"Yes\"\n);\n\n$degree_types = array(\n \"Unknown\",\n \"Unknown - Investigated\",\n \"A.L.A.\",\n \"B.A.\",\n \"B.S.\",\n \"B.L.S.\",\n \"L.L.B.\",\n \"H.A.\",\n \"M.A.\",\n \"M.S.\",\n \"M.F.A.\",\n \"M.P.A.\",\n \"D.E.A.\",\n \"Ed.M.\",\n \"F.L.A. (by thesis)\",\n \"LL.M.\",\n \"LL.D.\",\n \"M.L.S.\",\n \"D.S.N.\",\n \"D.S.W.\",\n \"D.Engr.\",\n \"D.Lib.\",\n \"Ed.D.\",\n \"Th.D.\",\n \"Pharm.D.\",\n \"D.Sc.\",\n \"D.L.S.\",\n \"J.D.\",\n \"M.D.\",\n \"Ph.D.\"\n);\n\n// Begin Session\nsession_start();\n\n// Delete server session if client cookie doesn't exist\nif (!isset($_COOKIE['MPACT_userid'])){\n unset($_SESSION['MPACT']);\n}\n\n// Check for good cookie (and expired session) - (re)set session values accordingly\nif (isset($_COOKIE['MPACT_userid']) && !isset($_SESSION['MPACT'])){\n $query = \"SELECT id, username, fullname FROM users WHERE id='\".$_COOKIE['MPACT_userid'].\"'\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n $line = mysqli_fetch_array($result);\n $_SESSION['MPACT']['userid'] = $line['id'];\n $_SESSION['MPACT']['username'] = $line['username'];\n $_SESSION['MPACT']['fullname'] = $line['fullname'];\n}\n\n###############################################\n// DISPLAY SOMETHING - something from the URL\nif ($_SERVER['REQUEST_METHOD'] == 'GET')\n{\n // Display header\n xhtml_web_header();\n\n// echo \"-----\\n\";\n// print_r($_COOKIE);\n// echo \"-----\\n\";\n// print_r($_SESSION);\n// echo \"-----\\n\";\n if (isset($_GET['op']))\n {\n switch ($_GET['op'])\n {\n ###############################################\n case \"login\";\n\n $host_info = get_environment_info();\n if ($host_info['hostname'] == \"sils\"){\n # no logins here - go to dev server\n action_box(\"No Logins Here...\",2,$_SERVER['SCRIPT_NAME']);\n }\n else{\n if (!isset($_SESSION['MPACT']['userid'])){\n # login form\n echo \"

            Welcome

            \\n\";\n echo \"

            Please login if you have an account.

            \\n\";\n echo \"
            \\n\";\n echo \"\\n\";\n echo \"\\n\";\n echo \"\\n\";\n echo \"\\n\";\n echo \"\\n\";\n echo \"

            Username:

            Password:

                 
            \\n\";\n echo \"
            \";\n }\n else{\n # um, already logged in...\n action_box(\"Already Logged In...\",2,$_SERVER['SCRIPT_NAME']);\n }\n }\n\n break;\n ###############################################\n case \"logout\";\n\n setcookie('MPACT_userid',$_SESSION['MPACT']['userid'],time()-1000);\n unset($_SESSION['MPACT']);\n action_box(\"Logged Out\",2,$_SERVER['SCRIPT_NAME']);\n\n break;\n ###############################################\n case \"glossary\";\n\n if ( isset($_GET['id']) ){\n show_glossaryterm($_GET['id']);\n }\n else\n {\n show_glossary();\n }\n\n break;\n ###############################################\n case \"admin\";\n\n if (is_admin())\n {\n echo \"

            Administrator Pages

            \\n\";\n\n echo \"\\n\";\n echo \"\\n\";\n echo \"
            \\n\";\n\n echo \"

            \\n\";\n echo \"Show Logs\\n\";\n echo \"

            \\n\";\n\n echo \"

            \\n\";\n echo \"Show Orphans\\n\";\n echo \"
            \\n\";\n echo \"Citation Correlation\\n\";\n echo \"

            \\n\";\n\n echo \"

            \\n\";\n echo \"People with Multiple Dissertations (Errors in DB)\\n\";\n echo \"
            \\n\";\n echo \"Year 0000\\n\";\n echo \"

            \\n\";\n\n echo \"

            \\n\";\n echo \"Add a New Person to the Database\\n\";\n echo \"

            \\n\";\n\n echo \"
            \\n\";\n\n echo \"

            \\n\";\n echo \"No Title/Abstract\\n\";\n echo \"
            \\n\";\n echo \"LIS, No Title/Abstract\\n\";\n echo \"
            \\n\";\n echo \"LIS, No Title\\n\";\n echo \"
            \\n\";\n echo \"LIS, No Abstract\\n\";\n echo \"
            \\n\";\n echo \"
            \\n\";\n echo \"LIS, No Committee\\n\";\n echo \"

            \\n\";\n\n echo \"
            \\n\";\n\n echo \"

            \\n\";\n echo \"LIS, Graduates By Year\\n\";\n echo \"
            \\n\";\n echo \"LIS History\\n\";\n echo \"

            \\n\";\n\n echo \"

            \\n\";\n echo \"LIS Professors Summary\\n\";\n echo \"
            \\n\";\n echo \"LIS Professors with MPACT\\n\";\n echo \"
            \\n\";\n echo \"LIS Professors and their Degrees (large CSV)\\n\";\n echo \"
            \\n\";\n echo \"LIS Professors with Unknown Degree\\n\";\n echo \"
            \\n\";\n echo \"LIS Professors with Unknown-Investigated Degree\\n\";\n echo \"
            \\n\";\n echo \"LIS Professors without Dissertations\\n\";\n echo \"
            \\n\";\n echo \"LIS Professors without LIS Dissertations\\n\";\n echo \"

            \\n\";\n\n echo \"
            \\n\";\n\n echo \"
            \";\n\n show_alphabet();\n\n }\n else\n {\n not_admin();\n }\n\n break;\n ###############################################\n case \"glossary_edit\";\n\n if ( isset($_GET['id']) && is_admin() ){\n\n echo \"

            Edit a Glossary Definition

            \\n\";\n\n $query = \"SELECT id, term, definition FROM glossary WHERE id='\".$_GET['id'].\"'\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result)) {\n $results['term'] = $line['term'];\n $results['definition'] = $line['definition'];\n }\n\n echo \"

            \";\n\n echo \"

            \\n\";\n echo \"\\n\";\n echo \"\\n\";\n echo \"\\n\";\n\n echo \"\".$results['term'].\":
            \\n\";\n echo \"\\n\";\n echo \"
            \\n\";\n echo \"\";\n echo \"
            \";\n\n echo \"

            \";\n\n\n }\n else\n {\n not_admin();\n }\n\n break;\n ###############################################\n case \"show_tree\":\n\n if (!$_GET['id']){action_box(\"No ID given.\");}\n else\n {\n draw_tree((int)$_GET['id']);\n }\n\n break;\n\n ###############################################\n case \"show_graph\":\n\n if (!$_GET['id']){action_box(\"No ID given.\");}\n else\n {\n echo \"

            \\n\";\n echo \"Advisors and Advisees of \".get_person_link($_GET['id']);\n echo \"

            \\n\";\n draw_graph((int)$_GET['id']);\n }\n\n break;\n\n ###############################################\n case \"statistics\":\n\n echo \"

            \\n\";\n echo \"LIS Incomplete - \\n\";\n echo \"Top A -\\n\";\n echo \"Top C -\\n\";\n echo \"Top A+C -\\n\";\n echo \"Top T -\\n\";\n echo \"Top G -\\n\";\n echo \"Top W -\\n\";\n echo \"Top TD -\\n\";\n echo \"Top TA\\n\";\n echo \"

            \\n\";\n\n echo \"

            Overall MPACT Statistics

            \\n\";\n\n echo \"\\n\";\n\n # disciplines\n $query = \"SELECT count(*) as disciplinecount FROM disciplines\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n extract($line);\n }\n echo \"\\n\";\n\n # schools\n $query = \"SELECT count(*) as schoolcount FROM schools\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n extract($line);\n }\n echo \"\\n\";\n\n # diss\n $query = \"SELECT count(*) as disscount FROM dissertations\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n extract($line);\n }\n echo \"\\n\";\n\n # a\n $query = \"SELECT count(*) as advisorcount FROM advisorships\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n extract($line);\n }\n echo \"\\n\";\n\n # c\n $query = \"SELECT count(*) as committeeshipscount FROM committeeships\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n extract($line);\n }\n echo \"\\n\";\n\n # full\n $query = \"SELECT count(*) as peoplecount FROM people\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n extract($line);\n }\n echo \"\\n\";\n echo \"
            Disciplines\".$disciplinecount.\"
            Schools\".$schoolcount.\"
            Dissertations\".$disscount.\"
            Advisorships\".$advisorcount.\"
            Committeeships\".$committeeshipscount.\"
            People\".$peoplecount.\"
            \\n\";\n\n\n # dissertations by country\n echo \"

            \\n\";\n echo \"

            Dissertations by Country:


            \\n\";\n $query = \"SELECT count(*) as dissnone FROM dissertations WHERE school_id IN (SELECT id FROM schools WHERE country = \\\"\\\")\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n extract($line);\n }\n $query = \"SELECT count(*) as dissusa FROM dissertations WHERE school_id IN (SELECT id FROM schools WHERE country = \\\"USA\\\")\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n extract($line);\n }\n $query = \"SELECT count(*) as disscanada FROM dissertations WHERE school_id IN (SELECT id FROM schools WHERE country = \\\"Canada\\\")\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n extract($line);\n }\n $query = \"SELECT count(*) as dissother FROM dissertations WHERE school_id IN\n (SELECT id FROM schools WHERE (country != \\\"\\\" AND country != \\\"USA\\\" AND country != \\\"Canada\\\"))\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n extract($line);\n }\n echo \"\\n\";\n echo \"\n \n \\n\";\n echo \"\n \n \\n\";\n echo \"\n \n \\n\";\n echo \"\n \n \\n\";\n echo \"\n \n \\n\";\n echo \"
            USA\".$dissusa.\"\".sprintf(\"%.2f\",100*$dissusa/$disscount).\"%\".sprintf(\"%.2f\",100*($dissusa)/$disscount).\"%
            Canada\".$disscanada.\"\".sprintf(\"%.2f\",100*$disscanada/$disscount).\"%\".sprintf(\"%.2f\",100*($dissusa+$disscanada)/$disscount).\"%
            Other\".$dissother.\"\".sprintf(\"%.2f\",100*$dissother/$disscount).\"%\".sprintf(\"%.2f\",100*($dissusa+$disscanada+$dissother)/$disscount).\"%
            None Listed\".$dissnone.\"\".sprintf(\"%.2f\",100*$dissnone/$disscount).\"%\".sprintf(\"%.2f\",100*($dissusa+$disscanada+$dissother+$dissnone)/$disscount).\"%
            Total\".$disscount.\"\".sprintf(\"%.2f\",100*$disscount/$disscount).\"%
            \\n\";\n\n # dissertations by year\n echo \"

            \\n\";\n echo \"

            Dissertations by Year:


            \\n\";\n $query = \"SELECT completedyear, count(*) as disscount FROM dissertations GROUP BY completedyear\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $counts[$line['completedyear']] = $line['disscount'];\n }\n ksort($counts);\n echo \"\\n\";\n echo \"\\n\";\n foreach ($counts as $one => $two)\n {\n echo \"\\n\";\n }\n echo \"\";\n echo \"\\n\";\n foreach ($counts as $one => $two)\n {\n echo \"\\n\";\n }\n echo \"\";\n echo \"
            \";\n if ($one%10==0)\n {\n echo $one;\n }\n echo \"
            \\n\";\n\n break;\n\n\n ###############################################\n case \"show_logs\":\n\n if (is_admin())\n {\n echo \"

            Recent Activity

            \\n\";\n\n if (isset($_GET['offset']))\n {\n $entries = get_logs($_GET['offset']);\n }\n else\n {\n $entries = get_logs();\n }\n echo \"\\n\";\n foreach ($entries as $entry)\n {\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\\n\";\n }\n echo \"
            \".$entry['logged_at'].\"
            \".$entry['ip'].\"
            \".$entry['user'].\"\".$entry['message'].\"
            \\n\";\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"find_multi_dissertations\":\n\n if (is_admin())\n {\n echo \"

            People With Multiple Dissertations (db needs to be edited by hand)

            \\n\";\n\n $query = \"SELECT\n count(d.id) as howmany,\n d.id, d.person_id, d.completedyear, d.status,\n d.title, d.abstract, d.notes, d.school_id, d.discipline_id\n FROM\n dissertations d\n GROUP BY\n d.person_id\n ORDER BY\n howmany DESC\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n $dissertations = array();\n while ( $line = mysqli_fetch_array($result)) {\n $dissertations[] = $line;\n }\n $multicount = 0;\n echo \"

            \\n\";\n foreach ($dissertations as $d)\n {\n if ($d['howmany'] > 1)\n {\n print \"person id = \".$d['person_id'];\n print \"
            \";\n print \"
            \";\n $multicount++;\n }\n }\n if ($multicount == 0)\n {\n print \" - None - database is clear.\";\n }\n echo \"

            \\n\";\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"find_zero_year\":\n\n if (is_admin())\n {\n echo \"

            Dissertations from the year 0000

            \\n\";\n\n $query = \"SELECT\n d.id, d.person_id, d.school_id, d.discipline_id, d.completedyear\n FROM\n dissertations d\n WHERE\n d.completedyear = '0000'\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n $dissertations = array();\n while ( $line = mysqli_fetch_array($result)) {\n $dissertations[] = $line;\n }\n $zerocount = 0;\n echo \"\";\n foreach ($dissertations as $d)\n {\n $zerocount++;\n # get school\n $query = \"SELECT fullname\n FROM\n schools\n WHERE id = '\".$d['school_id'].\"'\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $schoolname = $line['fullname'];\n }\n # get degree\n $query = \"SELECT degree\n FROM\n people\n WHERE id = '\".$d['person_id'].\"'\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $degree = $line['degree'];\n }\n $discipline = find_discipline($d['discipline_id']);\n echo \"\";\n echo \"\";\n echo \"\";\n print \"\";\n print \"\";\n print \"\";\n print \"\";\n }\n if ($zerocount == 0)\n {\n print \"\";\n }\n echo \"
            $zerocount.\".get_person_link($d['person_id']).\"$degree\".$discipline['title'].\"$schoolname
            None - database is clear.
            \\n\";\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"find_no_title_lis\":\n\n if (is_admin())\n {\n echo \"

            LIS Dissertations Without Title

            \\n\";\n\n $query = \"SELECT\n d.id, d.person_id, d.school_id, d.completedyear\n FROM\n dissertations d\n WHERE\n d.discipline_id = 1 AND\n ( d.title = '' )\n ORDER BY\n d.school_id\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n $dissertations = array();\n while ( $line = mysqli_fetch_array($result)) {\n $dissertations[] = $line;\n }\n $zerocount = 0;\n echo \"

            \\n\";\n foreach ($dissertations as $d)\n {\n $zerocount++;\n print \"$zerocount. \";\n echo get_person_link($d['person_id']);\n $thisperson = find_persons_school($d['person_id']);\n print \" - \".$thisperson['school'];\n print \" (\".$d['completedyear'].\")\";\n print \"
            \";\n }\n if ($zerocount == 0)\n {\n print \" - None - All LIS dissertations have titles.\";\n }\n echo \"

            \\n\";\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"find_no_abstract_lis\":\n\n if (is_admin())\n {\n echo \"

            LIS Dissertations Without Abstract

            \\n\";\n\n $query = \"SELECT\n d.id, d.person_id, d.school_id, d.completedyear\n FROM\n dissertations d\n WHERE\n d.discipline_id = 1 AND\n ( d.abstract = '' )\n ORDER BY\n d.school_id\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n $dissertations = array();\n while ( $line = mysqli_fetch_array($result)) {\n $dissertations[] = $line;\n }\n $zerocount = 0;\n echo \"

            \\n\";\n foreach ($dissertations as $d)\n {\n $zerocount++;\n print \"$zerocount. \";\n echo get_person_link($d['person_id']);\n $thisperson = find_persons_school($d['person_id']);\n print \" - \".$thisperson['school'];\n print \" (\".$d['completedyear'].\")\";\n print \"
            \";\n }\n if ($zerocount == 0)\n {\n print \" - None - All LIS dissertations have abstracts.\";\n }\n echo \"

            \\n\";\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"find_no_title_abstract\":\n\n if (is_admin())\n {\n echo \"

            Dissertations Without Title/Abstract

            \\n\";\n\n $query = \"SELECT\n d.id, d.person_id, d.school_id, d.completedyear\n FROM\n dissertations d\n WHERE\n d.title = '' OR d.abstract = ''\n ORDER BY\n d.school_id\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n $dissertations = array();\n while ( $line = mysqli_fetch_array($result)) {\n $dissertations[] = $line;\n }\n $zerocount = 0;\n echo \"

            \\n\";\n foreach ($dissertations as $d)\n {\n $zerocount++;\n print \"$zerocount. \";\n echo get_person_link($d['person_id']);\n $thisperson = find_persons_school($d['person_id']);\n print \" - \".$thisperson['school'];\n print \" (\".$d['completedyear'].\")\";\n print \"
            \";\n }\n if ($zerocount == 0)\n {\n print \" - None - All dissertations have titles and abstracts.\";\n }\n echo \"

            \\n\";\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"find_no_title_abstract_lis\":\n\n if (is_admin())\n {\n echo \"

            LIS Dissertations Without Title/Abstract

            \\n\";\n\n $query = \"SELECT\n d.id, d.person_id, d.school_id, d.completedyear\n FROM\n dissertations d\n WHERE\n d.discipline_id = 1 AND\n ( d.title = '' OR d.abstract = '' )\n ORDER BY\n d.school_id\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n $dissertations = array();\n while ( $line = mysqli_fetch_array($result)) {\n $dissertations[] = $line;\n }\n $zerocount = 0;\n echo \"

            \\n\";\n foreach ($dissertations as $d)\n {\n $zerocount++;\n print \"$zerocount. \";\n echo get_person_link($d['person_id']);\n $thisperson = find_persons_school($d['person_id']);\n print \" - \".$thisperson['school'];\n print \" (\".$d['completedyear'].\")\";\n print \"
            \";\n }\n if ($zerocount == 0)\n {\n print \" - None - All LIS dissertations have titles and abstracts.\";\n }\n echo \"

            \\n\";\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"lis_profs_unknown_degree\":\n\n if (is_admin())\n {\n echo \"

            LIS Professors with Unknown Degree

            \\n\";\n\n # advisors or committee members with unknown degree,\n # that served on an lis dissertation\n\n # get list of LIS dissertations\n $query = \"SELECT\n d.id\n FROM\n dissertations d\n WHERE\n d.discipline_id = '1'\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $lis_dissertations[] = $line['id'];\n }\n\n $lis_with_unknown = array();\n\n # get advisors for each diss, check for advisor's degree\n # if unknown degree, save\n foreach ($lis_dissertations as $id){\n $advisors = array();\n $query = \"SELECT person_id\n FROM advisorships\n WHERE dissertation_id = $id\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $advisors[] = $line['person_id'];\n }\n foreach($advisors as $aid){\n $adv = find_person($aid);\n if ($adv['degree'] == \"Unknown\"){\n $lis_with_unknown[] = $aid;\n }\n }\n }\n\n # get committeeships for each diss, check for comm's degree\n # if unknown degree, save\n foreach ($lis_dissertations as $id){\n $committeemembers = array();\n $query = \"SELECT person_id\n FROM committeeships\n WHERE dissertation_id = $id\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $committeemembers[] = $line['person_id'];\n }\n foreach($committeemembers as $cid){\n $com = find_person($cid);\n if ($com['degree'] == \"Unknown\"){\n $lis_with_unknown[] = $cid;\n }\n }\n }\n\n # uniquify\n $lis_with_unknown = array_unique($lis_with_unknown);\n\n # print them out\n echo \"

            \\n\";\n $count = 0;\n foreach($lis_with_unknown as $pid){\n $count++;\n $person = find_person($pid);\n print \"$count. \";\n print get_person_link($pid);\n print \"
            \\n\";\n }\n if ($count == 0)\n {\n print \" - None\";\n }\n echo \"

            \\n\";\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"lis_profs_unknowninvestigated\":\n case \"lis_profs_unknowninvestigated_degree\":\n\n# if (is_admin())\n# {\n echo \"

            LIS Professors with Unknown-Investigated Degree

            \\n\";\n\n # advisors or committee members with unknown-investigated degree,\n # that served on an lis dissertation\n\n # get list of LIS dissertations\n $query = \"SELECT\n d.id\n FROM\n dissertations d\n WHERE\n d.discipline_id = '1'\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $lis_dissertations[] = $line['id'];\n }\n\n $lis_with_unknown = array();\n\n # get advisors for each diss, check for advisor's degree\n # if unknown degree, save\n foreach ($lis_dissertations as $id){\n $advisors = array();\n $query = \"SELECT person_id\n FROM advisorships\n WHERE dissertation_id = $id\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $advisors[] = $line['person_id'];\n }\n foreach($advisors as $aid){\n $adv = find_person($aid);\n if ($adv['degree'] == \"Unknown - Investigated\"){\n $lis_with_unknown[] = $aid;\n }\n }\n }\n\n # get committeeships for each diss, check for comm's degree\n # if unknown degree, save\n foreach ($lis_dissertations as $id){\n $committeemembers = array();\n $query = \"SELECT person_id\n FROM committeeships\n WHERE dissertation_id = $id\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $committeemembers[] = $line['person_id'];\n }\n foreach($committeemembers as $cid){\n $com = find_person($cid);\n if ($com['degree'] == \"Unknown - Investigated\"){\n $lis_with_unknown[] = $cid;\n }\n }\n }\n\n # uniquify\n $lis_with_unknown = array_unique($lis_with_unknown);\n\n # print them out\n echo \"

            \\n\";\n $count = 0;\n foreach($lis_with_unknown as $pid){\n $count++;\n $person = find_person($pid);\n print \"$count. \";\n print get_person_link($pid);\n $advisorcount = count(find_advisorships_under_person($pid));\n $commcount = count(find_committeeships_under_person($pid));\n $totalcommitteeships = $advisorcount + $commcount;\n if ($totalcommitteeships > 1){print \"\";}\n print \" : $advisorcount + $commcount = $totalcommitteeships\";\n if ($totalcommitteeships > 1){print \"\";}\n print \"
            \\n\";\n $allcommitteeships += $totalcommitteeships;\n }\n if ($count == 0)\n {\n print \" - None\";\n }\n\n print \"
            TOTAL COMMITTEESHIPS = $allcommitteeships
            \";\n\n echo \"

            \\n\";\n\n# }\n# else\n# {\n# not_admin();\n# }\n\n break;\n\n\n ###############################################\n case \"lis_profswithoutdiss\":\n\n if (is_admin())\n {\n echo \"

            LIS Professors without Dissertations

            \\n\";\n\n # advisors or committee members with no dissertation,\n # that served on an lis dissertation\n\n # get list of LIS dissertations\n $query = \"SELECT\n d.id\n FROM\n dissertations d\n WHERE\n d.discipline_id = '1'\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $lis_dissertations[] = $line['id'];\n }\n # get advisors for each diss\n $advisors = array();\n foreach ($lis_dissertations as $id){\n $query = \"SELECT person_id\n FROM advisorships\n WHERE dissertation_id = $id\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $advisors[] = $line['person_id'];\n }\n }\n # get committeeships for each diss\n $committeemembers = array();\n foreach ($lis_dissertations as $id){\n $query = \"SELECT person_id\n FROM committeeships\n WHERE dissertation_id = $id\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $committeemembers[] = $line['person_id'];\n }\n }\n $total = array_merge($advisors,$committeemembers);\n $unique = array_unique($total);\n\n $unique_list = implode(\",\",$unique);\n $listed = array();\n $query = \"SELECT person_id\n FROM dissertations\n WHERE\n person_id IN ($unique_list)\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $listed[] = $line['person_id'];\n }\n $notlisted = array_diff($unique,$listed);\n\n # print them out\n echo \"

            \\n\";\n $count = 0;\n foreach($notlisted as $pid){\n $count++;\n print \"$count. \";\n print get_person_link($pid);\n print \"
            \\n\";\n }\n if ($count == 0)\n {\n print \" - None\";\n }\n echo \"

            \\n\";\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"lis_profs_degrees\":\n\n if (is_admin())\n {\n echo \"

            LIS Professors and their Degrees

            \\n\";\n\n # get list of LIS dissertations\n $query = \"SELECT\n d.id\n FROM\n dissertations d\n WHERE\n d.discipline_id = '1'\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $lis_dissertations[] = $line['id'];\n }\n\n print \"

            Copy and Paste the text below into a .csv file.

            \";\n\n # big loop\n print \"
            \\n\";\n          print \"
            \";\n print \"Count,DissID,DissYear,DissLastName,DissFirstName,DissSchool,DissCountry,AdvisorID,AdvisorType,AdvisorLastName,AdvisorFirstName,\";\n print \"AdvisorDegree,AdvisorYear,AdvisorDiscipline,AdvisorSchool,AdvisorCountry\\n\";\n $count = 0;\n foreach($lis_dissertations as $did){\n # loop through advisors\n $query = \"SELECT person_id\n FROM advisorships\n WHERE dissertation_id = $did\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n\n # advisor line\n\n # Count\n $count++;\n print \"\\\"$count\\\",\";\n # DissID\n print \"\\\"$did\\\",\";\n # DissYear\n $diss = find_dissertation($did);\n print \"\\\"\".$diss['completedyear'].\"\\\",\";\n # DissLastName\n $author = find_person($diss['person_id']);\n print \"\\\"\".$author['lastname'].\"\\\",\";\n # DissFirstName\n print \"\\\"\".$author['firstname'].\"\\\",\";\n # DissSchool\n $school = find_school($diss['school_id']);\n print \"\\\"\".$school['fullname'].\"\\\",\";\n # DissCountry\n print \"\\\"\".$school['country'].\"\\\",\";\n # AdvisorID\n $pid = $line['person_id'];\n print \"\\\"$pid\\\",\";\n # AdvisorType\n print \"\\\"Advisor\\\",\";\n # AdvisorLastName\n $person = find_person($pid);\n print \"\\\"\".$person['lastname'].\"\\\",\";\n # AdvisorFirstName\n print \"\\\"\".$person['firstname'].\"\\\",\";\n # AdvisorDegree\n print \"\\\"\".$person['degree'].\"\\\",\";\n $diss = find_dissertation_by_person($pid);\n if ($diss){\n # AdvisorYear\n print \"\\\"\".$diss['completedyear'].\"\\\",\";\n # AdvisorDiscipline\n $disc = find_discipline($diss['discipline_id']);\n print \"\\\"\".$disc['title'].\"\\\",\";\n # AdvisorSchool\n $school = find_school($diss['school_id']);\n print \"\\\"\".$school['fullname'].\"\\\",\";\n # AdvisorCountry\n print \"\\\"\".$school['country'].\"\\\"\";\n }\n else{\n # no dissertation for this person\n print \"\\\"\\\",\";\n print \"\\\"\\\",\";\n print \"\\\"\\\",\";\n print \"\\\"\\\"\";\n }\n print \"\\n\";\n\n }\n # loop through committeeships\n $query = \"SELECT person_id\n FROM committeeships\n WHERE dissertation_id = $did\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n\n # committeeship line\n\n # Count\n $count++;\n print \"\\\"$count\\\",\";\n # DissID\n print \"\\\"$did\\\",\";\n # DissYear\n $diss = find_dissertation($did);\n print \"\\\"\".$diss['completedyear'].\"\\\",\";\n # DissLastName\n $author = find_person($diss['person_id']);\n print \"\\\"\".$author['lastname'].\"\\\",\";\n # DissFirstName\n print \"\\\"\".$author['firstname'].\"\\\",\";\n # DissSchool\n $school = find_school($diss['school_id']);\n print \"\\\"\".$school['fullname'].\"\\\",\";\n # DissCountry\n print \"\\\"\".$school['country'].\"\\\",\";\n # AdvisorID\n $pid = $line['person_id'];\n print \"\\\"$pid\\\",\";\n # AdvisorType\n print \"\\\"Committee\\\",\";\n # AdvisorLastName\n $person = find_person($pid);\n print \"\\\"\".$person['lastname'].\"\\\",\";\n # AdvisorFirstName\n print \"\\\"\".$person['firstname'].\"\\\",\";\n # AdvisorDegree\n print \"\\\"\".$person['degree'].\"\\\",\";\n $diss = find_dissertation_by_person($pid);\n if ($diss){\n # AdvisorYear\n print \"\\\"\".$diss['completedyear'].\"\\\",\";\n # AdvisorDiscipline\n $disc = find_discipline($diss['discipline_id']);\n print \"\\\"\".$disc['title'].\"\\\",\";\n # AdvisorSchool\n $school = find_school($diss['school_id']);\n print \"\\\"\".$school['fullname'].\"\\\",\";\n # AdvisorCountry\n print \"\\\"\".$school['country'].\"\\\"\";\n }\n else{\n # no dissertation for this person\n print \"\\\"\\\",\";\n print \"\\\"\\\",\";\n print \"\\\"\\\",\";\n print \"\\\"\\\"\";\n }\n print \"\\n\";\n\n }\n }\n echo \"
            \\n\";\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"lis_profsnotfromlis\":\n\n if (is_admin())\n {\n\n echo \"

            LIS Professors without LIS Dissertations

            \\n\";\n\n # and then once the data collection is done\n # cassidy wants a list of all the people who were advisors and committee\n # members for lis, but were not themselves lis\n\n # get list of LIS dissertations\n $query = \"SELECT\n d.id\n FROM\n dissertations d\n WHERE\n d.discipline_id = '1'\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $lis_dissertations[] = $line['id'];\n }\n # get advisors for each diss\n $advisors = array();\n foreach ($lis_dissertations as $id){\n $query = \"SELECT person_id\n FROM advisorships\n WHERE dissertation_id = $id\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $advisors[] = $line['person_id'];\n }\n }\n # get committeeships for each diss\n $committeemembers = array();\n foreach ($lis_dissertations as $id){\n $query = \"SELECT person_id\n FROM committeeships\n WHERE dissertation_id = $id\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $committeemembers[] = $line['person_id'];\n }\n }\n $total = array_merge($advisors,$committeemembers);\n $unique = array_unique($total);\n\n $unique_list = implode(\",\",$unique);\n $listed = array();\n $query = \"SELECT person_id\n FROM dissertations\n WHERE\n person_id IN ($unique_list)\n AND\n discipline_id = '1'\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $listed[] = $line['person_id'];\n }\n $notlisted = array_diff($unique,$listed);\n\n # print them out\n echo \"

            \\n\";\n $count = 0;\n foreach($notlisted as $pid){\n $count++;\n print \"$count. \";\n print get_person_link($pid);\n print \"
            \\n\";\n }\n if ($count == 0)\n {\n print \" - None\";\n }\n echo \"

            \\n\";\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"lis_nocommittee\":\n\n if (is_admin())\n {\n\n echo \"

            LIS Dissertations with no committee

            \\n\";\n\n # get list of LIS dissertations\n $query = \"SELECT\n d.id\n FROM\n dissertations d\n WHERE\n d.discipline_id = '1'\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $lis_dissertations[] = $line['id'];\n }\n # get advisors for each diss\n $advisors = array();\n foreach ($lis_dissertations as $id){\n $query = \"SELECT count(*) as howmany\n FROM advisorships\n WHERE dissertation_id = $id\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n if ($line['howmany'] > 0){$hascomm[] = $id;};\n }\n }\n # get committeeships for each diss\n $committeemembers = array();\n foreach ($lis_dissertations as $id){\n $query = \"SELECT count(*) as howmany\n FROM committeeships\n WHERE dissertation_id = $id\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n if ($line['howmany'] > 0){$hascomm[] = $id;};\n }\n }\n $unique = array_unique($hascomm);\n $nocomm = array_diff($lis_dissertations,$unique);\n\n # print them out\n echo \"

            \\n\";\n $count = 0;\n foreach($nocomm as $did){\n $count++;\n print \"$count. \";\n $d = find_dissertation($did);\n print get_person_link($d['person_id']);\n print \"
            \\n\";\n }\n if ($count == 0)\n {\n print \" - None\";\n }\n echo \"

            \\n\";\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"lis_profs_with_mpact\":\n\n if (is_admin())\n {\n echo \"

            LIS Professors With MPACT

            \\n\";\n\n # advisors or committee members\n # that served on an lis dissertation\n\n\n # get list of LIS dissertations\n $query = \"SELECT\n d.id\n FROM\n dissertations d\n WHERE\n d.discipline_id = '1'\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $lis_dissertations[] = $line['id'];\n }\n\n # get advisors for each diss\n $advisors = array();\n foreach ($lis_dissertations as $id){\n $query = \"SELECT person_id\n FROM advisorships\n WHERE dissertation_id = $id\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $advisors[] = $line['person_id'];\n }\n }\n\n # get committeeships for each diss\n $committeemembers = array();\n foreach ($lis_dissertations as $id){\n $query = \"SELECT person_id\n FROM committeeships\n WHERE dissertation_id = $id\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $committeemembers[] = $line['person_id'];\n }\n }\n\n $total = array_merge($advisors,$committeemembers);\n\n $unique = array_unique($total);\n\n echo \"
            \\n\";\n          echo \"Count|Name|Year|A|C|A+C|T\\n\";\n          foreach ($unique as $prof){\n            $mpact = mpact_scores($prof);\n            $person = find_person($prof);\n            $dissertation = find_dissertation_by_person($prof);\n            # count\n            $count += 1;\n            echo \"$count\";\n            echo \"|\";\n            # name\n            echo $person['fullname'];\n            echo \"|\";\n            # year\n            echo $dissertation['completedyear'];\n            echo \"|\";\n            # a\n            echo $mpact['A'];\n            echo \"|\";\n            # c\n            echo $mpact['C'];\n            echo \"|\";\n            # a+c\n            echo $mpact['AC'];\n            echo \"|\";\n            # t\n            echo $mpact['T'];\n            echo \"\\n\";\n          }\n          echo \"
            \\n\";\n }\n\n break;\n\n ###############################################\n case \"lis_profs_summary\":\n\n if (is_admin())\n {\n echo \"

            LIS Professors Summary

            \\n\";\n\n # advisors or committee members\n # that served on an lis dissertation\n\n echo \"\\n\";\n\n # get list of LIS dissertations\n $query = \"SELECT\n d.id\n FROM\n dissertations d\n WHERE\n d.discipline_id = '1'\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $lis_dissertations[] = $line['id'];\n }\n echo \"\\n\";\n\n # get advisors for each diss\n $advisors = array();\n foreach ($lis_dissertations as $id){\n $query = \"SELECT person_id\n FROM advisorships\n WHERE dissertation_id = $id\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $advisors[] = $line['person_id'];\n }\n }\n echo \"\\n\";\n\n # get committeeships for each diss\n $committeemembers = array();\n foreach ($lis_dissertations as $id){\n $query = \"SELECT person_id\n FROM committeeships\n WHERE dissertation_id = $id\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $committeemembers[] = $line['person_id'];\n }\n }\n echo \"\\n\";\n\n $total = array_merge($advisors,$committeemembers);\n echo \"\\n\";\n\n $unique = array_unique($total);\n echo \"\\n\";\n\n $unique_list = implode(\",\",$unique);\n $known = array();\n $query = \"SELECT person_id\n FROM dissertations\n WHERE\n person_id IN ($unique_list)\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $known[] = $line['person_id'];\n }\n echo \"\\n\";\n echo \"\\n\";\n\n $query = \"SELECT count(*) as howmany\n FROM dissertations\n WHERE\n person_id IN ($unique_list)\n AND\n discipline_id != 16\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $howmany = $line['howmany'];\n }\n echo \"\\n\";\n\n $query = \"SELECT count(*) as howmany\n FROM dissertations\n WHERE\n person_id IN ($unique_list)\n AND\n completedyear != 0000\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $howmany = $line['howmany'];\n }\n echo \"\\n\";\n\n $query = \"SELECT count(*) as howmany\n FROM dissertations\n WHERE\n person_id IN ($unique_list)\n AND\n completedyear != 107\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $howmany = $line['howmany'];\n }\n echo \"\\n\";\n\n echo \"
            Total LIS Dissertations\".count($lis_dissertations).\"
            Total LIS Dissertation Advisorships\";\n echo count($advisors);\n echo \"
            Total LIS Dissertation Committeeships\";\n echo count($committeemembers);\n echo \"
            Total LIS Dissertation Advisorships and Committeeships:\";\n echo count($total);\n echo \"
            Total number of unique advisor/committee members on LIS dissertations:\";\n\n echo count($unique);\n echo \"
            \";\n echo \"Subset of \".count($unique).\" without a listed dissertation:\";\n echo count(array_diff($unique,$known));\n echo \"
            Subset of \".count($unique).\" with a listed dissertation:\";\n echo count($known);\n echo \"
            - Subset of \".count($known).\" with known discipline:\";\n echo $howmany;\n echo \"
            - Subset of \".count($known).\" with known year:\";\n echo $howmany;\n echo \"
            - Subset of \".count($known).\" with known school:\";\n echo $howmany;\n echo \"
            \\n\";\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"lis_allyears\":\n\n if (is_admin())\n {\n echo \"

            LIS, Graduates By Year

            \\n\";\n print \"
            \\n\";\n\n            # get list of dissertations\n            $query = \"SELECT\n                      d.id, d.person_id, d.completedyear\n                    FROM\n                      dissertations d\n                    WHERE\n                      d.discipline_id = '1'\n                    ORDER BY\n                      d.completedyear ASC,\n                      d.school_id ASC\n                    \";\n            $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n            $schools = array();\n            $count = 0;\n            while ( $line = mysqli_fetch_array($result)) {\n              $dissertation = find_dissertation($line['id']);\n              $person = find_person($line['person_id']);\n              $schoolinfo = find_persons_school($line['person_id']);\n              $count++;\n              print $count;\n              print \"|\";\n              print $line['completedyear'];\n              print \"|\";\n              print $schoolinfo['school'];\n              print \"|\";\n              print $person['fullname'];\n#              print \"|\";\n#              print $dissertation['title'];\n#              print \"|\";\n#              print $dissertation['abstract'];\n              print \"\\n\";\n            }\n\n            print \"
            \\n\";\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"lis_history\":\n\n if (is_admin())\n {\n echo \"

            LIS Dissertations by School by Year

            \\n\";\n\n $firstyear = 1920;\n $lastyear = 2008;\n\n print \"
            \\n\";\n            print \"school|\";\n            for ($i = $firstyear; $i <= $lastyear; $i++)\n            {\n                print \"$i|\";\n            }\n            print \"\\n\";\n\n            # get list of schools (all of them)\n            $query = \"SELECT\n                    s.id, s.fullname\n                    FROM\n                      schools s\n                    ORDER BY\n                      s.fullname\n                    \";\n            $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n            $schools = array();\n            while ( $line = mysqli_fetch_array($result)) {\n              $schools[] = $line;\n            }\n            foreach ($schools as $s)\n            {\n              # loop through each school and find count by year\n              $query = \"SELECT\n                    d.id, d.person_id, d.completedyear, COUNT(d.completedyear) AS yeartotal\n                    FROM\n                      dissertations d\n                    WHERE\n                      d.discipline_id = '1' AND\n                      d.school_id = '\".$s['id'].\"'\n                    GROUP BY\n                      d.completedyear\n                  \";\n              $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n              print $s['fullname'].\"|\";\n              $d = array();\n              while ( $line = mysqli_fetch_array($result)) {\n                $d[$s['id']][$line['completedyear']] = $line['yeartotal'];\n              }\n\n              # walk through all years, and print out counts for this school\n              for ($i = $firstyear; $i <= $lastyear; $i++)\n              {\n                if ($d[$s['id']][$i] > 0)\n                  print $d[$s['id']][$i].\"|\";\n                else\n                  print \"0|\";\n              }\n              print \"\\n\";\n            }\n\n            print \"
            \";\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"lis_incomplete\":\n\n echo \"

            Incomplete LIS Dissertation Listings

            \\n\";\n\n $discipline_id = 1; # hard coded for LIS\n $schools = find_schools($discipline_id);\n\n foreach ($schools as $one => $two)\n {\n\n $year_conferred = array();\n $degree_status = array();\n\n $query = \"SELECT d.person_id, d.completedyear, d.status\n FROM\n dissertations d,\n schools s,\n people p,\n names n\n WHERE\n s.id = '$one' AND\n d.discipline_id = '$discipline_id' AND\n d.school_id = s.id AND\n d.person_id = p.id AND\n p.preferred_name_id = n.id AND\n d.status < 4\n ORDER BY\n s.id ASC, d.completedyear ASC, n.lastname ASC, n.firstname ASC\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n $resultcount = 0;\n\n while ( $line = mysqli_fetch_array($result)) {\n $resultcount++;\n extract($line);\n $year_conferred[$person_id] = $completedyear;\n $degree_status[$person_id] = $status;\n }\n\n if ($resultcount > 0)\n {\n echo \"

            $two

            \\n\";\n }\n\n $incompletecount = 0;\n echo \"\";\n foreach ($year_conferred as $person => $year)\n {\n $incompletecount++;\n $printme = \"\\n\";\n $printme .= \"\\n\";\n\n $printme .= \"\\n\";\n $printme .= \"\\n\";\n\n echo $printme;\n }\n echo \"
            $incompletecount. \";\n $printme .= \"\".get_person_link($person).\" ($year)\".$statuscodes[$degree_status[$person]].\"
            \";\n\n }\n echo \"

            \";\n\n break;\n\n ###############################################\n case \"all_edges\":\n\n if (is_admin())\n {\n echo \"

            All Dissertations and Mentor Relationships

            \\n\";\n\n print \"
            \\n\";\n            print \"mentor|role|protege|year|school\\n\";\n\n            # each dissertation\n            $query = \"SELECT id, person_id, completedyear, school_id FROM dissertations\";\n            $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n            while ( $line = mysqli_fetch_array($result)) {\n              extract($line);\n              $student = find_person($person_id);\n              $query2 = \"SELECT fullname as schoolname FROM schools WHERE id = '$school_id'\";\n              $result2 = mysql_query($query2) or die(mysql_error());\n              $line2 = mysqli_fetch_array($result2);\n              extract($line2);\n              print $student['fullname'].\"|dissertation|null|$completedyear|$schoolname\\n\";\n              # get advisorships\n              $advisors = find_advisors_for_person($person_id);\n              foreach ($advisors as $mentor_id){\n                $mentor = find_person($mentor_id);\n                print $mentor['fullname'].\"|advisorship|\".$student['fullname'].\"|$completedyear|$schoolname\\n\";\n              }\n              # get committeeships\n              $committee = find_committee_for_person($person_id);\n              foreach ($committee as $mentor_id){\n                $mentor = find_person($mentor_id);\n                print $mentor['fullname'].\"|committeeship|\".$student['fullname'].\"|$completedyear|$schoolname\\n\";\n              }\n            }\n            print \"
            \";\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"citation_correlation\":\n\n if (is_admin())\n {\n echo \"

            Citation Correlation Data

            \\n\";\n\n $correlated_ids = array(\n 953,\n 2098,\n# 5086, bc\n 3659,\n# 1329, dalhousie\n 5087,\n 478,\n 3094,\n 3497,\n 4784,\n 1250,\n 5088,\n 5089,\n 5090,\n 4657,\n# 5091, mcdowell, not phd yet\n 5092,\n 5093,\n 5094,\n 2668,\n 4076,\n 2683,\n 3978,\n 2425,\n 3645,\n 2660,\n 2233,\n 2665,\n 1310,\n 2548,\n 2708,\n 2592,\n 4648,\n 5095,\n 5096,\n 4654,\n 5097,\n 5098,\n 1234,\n 1299,\n 1294,\n 3062,\n 3110,\n 1283,\n 1220,\n 874,\n 584,\n 3127,\n 1142,\n 3116,\n 5099,\n 5100,\n 1025,\n 486,\n 3130,\n 1321,\n 5101,\n 4502,\n 5102,\n 535,\n 5160, # koohang\n 2673,\n 5103,\n 5104,\n 1950,\n 3972,\n 3278,\n 5105,\n 3571,\n 5106,\n 3994,\n 1504,\n 4181,\n 3140,\n 2323, # benoit added\n 5107,\n 800,\n 4438,\n 5108,\n 5109,\n 4760,\n 2570,\n 1866,\n 3238,\n 1846,\n 1806,\n 2527,\n 3703,\n 4758,\n 3683,\n 3846,\n 2603,\n 4011,\n 2343,\n 2329,\n 5110,\n 5111,\n 4706,\n 2761,\n 1413,\n 3028,\n 3590,\n 3668,\n 2883,\n 3063,\n 3091,\n 1705,\n 3031,\n# gary again 486,\n 3979,\n 3018,\n 1855,\n 3409,\n 2747,\n 3093,\n 3065,\n 3060,\n 1685,\n 2114,\n 5112,\n# moore rm 5113,\n 2309,\n# liu rm 2215,\n 4086,\n 4013,\n 1573\n );\n\n echo \"\\n\";\n echo \"\n \n \n \n \n \n \n \n \n \n \\n\";\n $counter = 0;\n foreach ($correlated_ids as $one)\n {\n $counter++;\n echo \"\";\n echo \"\";\n echo \"\";\n $scores = mpact_scores($one);\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\\n\";\n }\n echo \"
            -NameACA+CFMIFMEFMI/(A+C)FME/(A+C)
            $counter.\";\n echo get_person_link($one);\n echo \"\".$scores['A'].\"\".$scores['C'].\"\".$scores['AC'].\"\".$scores['FMI'].\"\".$scores['FME'].\"\".$scores['FMIdivFULL'].\"\".$scores['FMEdivFULL'].\"
            \\n\";\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"top_a\":\n case \"top_c\":\n case \"top_ac\":\n case \"top_g\":\n case \"top_td\":\n case \"top_w\":\n case \"top_t\":\n case \"top_ta\":\n\n $list_type = strtoupper(substr($_GET['op'],4));\n echo \"

            Top \";\n if ($list_type == \"TD\"){echo \"TD\";}\n else if ($list_type == \"TA\"){echo \"TA\";}\n else if ($list_type == \"AC\"){echo \"A+C\";}\n else {echo $list_type;}\n echo \" List

            \\n\";\n $score_type = strtolower($list_type).\"_score\";\n $people = find_all_people();\n foreach ($people as $p)\n {\n $scores[$p] = find_mpact_score($p,$score_type);\n }\n # zero out indecipherables\n $scores[28] = 0;\n $scores[391] = 0;\n asort($scores);\n $scores = array_reverse($scores, true);\n $top = narray_slice($scores, 0, 100); #calls custom function, end of mpact_include (passes true)\n $count = 0;\n $lasttotal = 0;\n echo \"\\n\";\n foreach ($top as $one => $two)\n {\n $count++;\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\\n\";\n $lasttotal = $two;\n }\n echo \"
            \";\n if ($two != $lasttotal){echo $count.\".\";}\n echo \"\";\n echo get_person_link($one);\n echo \"\";\n echo $two;\n echo \"
            \\n\";\n break;\n\n ###############################################\n case \"create_discipline\":\n\n if (is_admin())\n {\n echo \"

            Creating a New Discipline

            \\n\";\n\n echo \"

            \";\n\n echo \"

            \\n\";\n echo \"\\n\";\n\n echo \"\";\n echo \"\";\n\n\n echo \"\";\n echo \"\";\n echo \"\";\n\n echo \"
            Title
            \";\n\n echo \"\";\n echo \"
            \";\n\n echo \"

            \";\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"edit_discipline\":\n\n if (is_admin())\n {\n if (!$_GET['id']){action_box(\"No ID given.\");}\n elseif (!is_empty_discipline($_GET['id']))\n {\n action_box(\"Discipline must be empty to edit...\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_disciplines\");\n }\n else{\n\n $query = \"SELECT title FROM disciplines WHERE id=\".$_GET['id'];\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n extract($line);\n }\n\n echo \"

            Editing a Discipline

            \\n\";\n\n echo \"

            \";\n\n echo \"

            \\n\";\n echo \"\\n\";\n echo \"\\n\";\n\n echo \"\";\n echo \"\";\n\n\n echo \"\";\n echo \"\";\n echo \"\";\n\n echo \"
            Title
            \";\n\n echo \"\";\n echo \"
            \";\n\n echo \"

            \";\n }\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"create_school\":\n\n if (is_admin())\n {\n echo \"

            Creating a New School

            \\n\";\n\n echo \"

            \";\n\n echo \"

            \\n\";\n echo \"\\n\";\n\n echo \"\";\n echo \"\";\n\n\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n\n echo \"
            FullnameCountry
            \";\n\n echo \"\";\n echo \"
            \";\n\n echo \"

            \";\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"edit_school\":\n\n if (is_admin())\n {\n if (!$_GET['id']){action_box(\"No ID given.\");}\n elseif (!is_empty_school($_GET['id']))\n {\n action_box(\"School must be empty to edit...\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_schools\");\n }\n else{\n\n $query = \"SELECT fullname, country FROM schools WHERE id=\".$_GET['id'];\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n extract($line);\n }\n\n echo \"

            Editing a School

            \\n\";\n\n echo \"

            \";\n\n echo \"

            \\n\";\n echo \"\\n\";\n echo \"\\n\";\n\n echo \"\";\n echo \"\";\n\n\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n\n echo \"
            FullnameCountry
            \";\n\n echo \"\";\n echo \"
            \";\n\n echo \"

            \";\n }\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"create_person\":\n\n if (is_admin())\n {\n echo \"

            Creating a New Person

            \\n\";\n\n echo \"

            \";\n\n echo \"

            \\n\";\n echo \"\\n\";\n\n echo \"\";\n echo \"\";\n\n\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n\n echo \"
            FirstMiddleLastSuffixDegree
            \";\n echo \"\\n\";\n echo \"
            \";\n\n echo \"\";\n echo \"
            \";\n\n echo \"

            \";\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"add_mentor\":\n\n if (is_admin())\n {\n echo \"

            Add a New Person to the Database

            \\n\";\n\n echo \"

            Adding a Mentor

            \\n\";\n\n echo \"
            \\n\";\n echo \"\\n\";\n echo \"\\n\";\n\n echo \"

            \";\n\n echo \"Mentor Type:
            \\n\";\n echo \" Advisor
            \\n\";\n echo \" Committee Member\\n\";\n echo \"

            \\n\";\n\n echo \"Mentor:
            \\n\";\n echo \"\\n\";\n\n echo \"

            \\n\";\n\n echo \"Student:
            \\n\". get_person_link($_GET['id']);\n echo \"

            \\n\";\n\n echo \"\";\n\n echo \"

            \";\n echo \"
            \";\n\n draw_tree($_GET['id']);\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"add_student\":\n\n if (is_admin())\n {\n echo \"

            Add a New Person to the Database

            \\n\";\n\n echo \"

            Adding a Student

            \\n\";\n\n echo \"
            \\n\";\n echo \"\\n\";\n echo \"\\n\";\n\n echo \"

            \";\n\n echo \"Mentor Type:
            \\n\";\n echo \" Advisor
            \\n\";\n echo \" Committee Member\\n\";\n echo \"

            \\n\";\n\n echo \"Mentor:
            \\n\". get_person_link($_GET['id']);\n echo \"

            \\n\";\n\n\n echo \"Student:
            \\n\";\n echo \"\\n\";\n\n echo \"

            \\n\";\n echo \"\";\n\n echo \"

            \";\n echo \"
            \";\n\n draw_tree($_GET['id']);\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n\n\n ###############################################\n case \"remove_mentor\":\n\n if (is_admin())\n {\n echo \"

            Removing a Mentor

            \\n\";\n\n echo \"
            \\n\";\n echo \"\\n\";\n echo \"\\n\";\n echo \"\\n\";\n echo \"\\n\";\n\n echo \"

            \";\n\n echo \"Are you sure you want to remove this mentor relationship?

            \\n\";\n if ($_GET['type'] == \"A\"){echo \"Advisor: \";}\n if ($_GET['type'] == \"C\"){echo \"Commitee Member: \";}\n echo get_person_link(intval($_GET['mentor_id'])).\"
            \\n\";\n echo \"Student: \".get_person_link(intval($_GET['student_id'])).\"
            \\n\";\n echo \"
            \\n\";\n\n echo \"\";\n echo \" If NOT, please go BACK\";\n\n echo \"

            \";\n echo \"
            \";\n\n draw_tree(intval($_GET['student_id']));\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"add_url\";\n\n if (is_admin())\n {\n echo \"

            Adding a Reference URL

            \\n\";\n\n echo \"
            \\n\";\n echo \"\\n\";\n echo \"\\n\";\n\n echo \"

            \";\n\n echo \"\\n\";\n echo \"\\n\";\n echo \"\\n\";\n echo \"
            URL:
            Description:
            \\n\";\n\n echo \"\";\n\n echo \"

            \";\n echo \"
            \";\n\n draw_tree(intval($_GET['id']));\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"edit_url\";\n\n if (is_admin())\n {\n $url = find_url(intval($_GET['id']));\n echo \"

            Editing a Reference URL

            \\n\";\n\n echo \"
            \\n\";\n echo \"\\n\";\n echo \"\\n\";\n\n echo \"

            \";\n\n echo \"\\n\";\n echo \"\\n\";\n echo \"\\n\";\n echo \"\\n\";\n echo \"
            URL:
            Description:
            Last Updated:\".$url['updated_at'].\"
            \\n\";\n\n echo \"\";\n\n echo \"

            \";\n echo \"
            \";\n\n draw_tree($url['person_id']);\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"delete_url\";\n\n if (is_admin())\n {\n $url = find_url(intval($_GET['id']));\n echo \"

            Deleting a Reference URL

            \\n\";\n\n echo \"
            \\n\";\n echo \"\\n\";\n echo \"\\n\";\n\n echo \"

            \";\n\n echo \"Are you sure you want to delete this Reference URL?

            \\n\";\n echo \"\\n\";\n echo \"\\n\";\n echo \"\\n\";\n echo \"\\n\";\n echo \"
            URL:\".$url['url'].\"
            Description:\".$url['description'].\"
            Last Updated:\".$url['updated_at'].\"
            \\n\";\n echo \"
            \\n\";\n\n echo \"\";\n echo \" If NOT, please go BACK\";\n\n echo \"

            \";\n echo \"
            \";\n\n draw_tree($url['person_id']);\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"edit_degree\":\n\n if (is_admin())\n {\n if (!$_GET['id']){action_box(\"No ID given.\");}\n else\n {\n\n $person = find_person($_GET['id']);\n\n echo \"

            Editing a Degree

            \";\n echo \"

            \";\n\n echo \"

            \";\n echo \"\";\n echo \"\";\n\n\n echo \"\";\n echo \"\";\n\n\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n\n echo \"
            NameDegree
            \".$person['fullname'].\"\";\n echo \"\\n\";\n echo \"
            \";\n\n echo \"\";\n\n echo \"
            \";\n\n echo \"

            \";\n\n\n echo \"
            \";\n draw_tree($_GET['id']);\n echo \"
            \";\n\n\n\n }\n }\n else\n {\n not_admin();\n }\n\n break;\n\n\n ###############################################\n case \"add_name\":\n\n if (is_admin())\n {\n if (!$_GET['id']){action_box(\"No ID given.\");}\n else\n {\n\n $person = find_person($_GET['id']);\n\n echo \"

            Adding an Alias

            \";\n echo \"

            \";\n\n echo \"

            \";\n echo \"\";\n echo \"\";\n\n\n echo \"\";\n echo \"\";\n\n\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n\n echo \"
            FirstMiddleLastSuffix
            \";\n\n echo \"\";\n\n echo \"
            \";\n\n echo \"

            \";\n\n\n echo \"
            \";\n draw_tree($_GET['id']);\n echo \"
            \";\n\n\n\n }\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"edit_name\":\n\n if (is_admin())\n {\n if (!$_GET['id']){action_box(\"No ID given.\");}\n else\n {\n\n $person = find_person($_GET['id']);\n\n echo \"

            Editing a Name

            \";\n echo \"

            \";\n\n echo \"

            \";\n echo \"\";\n echo \"\";\n echo \"\";\n\n\n echo \"\";\n echo \"\";\n\n\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n\n echo \"
            FirstMiddleLastSuffix
            \";\n\n echo \"\";\n\n echo \"
            \";\n\n echo \"

            \";\n\n\n echo \"
            \";\n draw_tree($_GET['id']);\n echo \"
            \";\n\n\n\n }\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"create_dissertation\":\n\n if (is_admin())\n {\n\n $disciplines = find_disciplines();\n $schools = find_schools();\n\n if (!$_GET['person_id']){action_box(\"No ID given.\");}\n else\n {\n\n $person = find_person($_GET['person_id']);\n if (!$person)\n {\n action_box(\"Person not found.\");\n }\n else{\n\n echo \"

            CREATE DISSERTATION

            \\n\";\n\n echo \"
            \";\n echo \"\";\n echo \"\";\n\n echo \"

            \";\n echo get_person_link($person['id']);\n echo \"
            \";\n\n echo \"Degree: \\n\";\n echo \"
            \";\n\n echo \"Status: \\n\";\n echo \"
            \";\n\n echo \"Discipline: \\n\";\n echo \"
            \";\n\n\n echo \"School: \";\n echo \"\\n\";\n echo \"
            Year:\\n\";\n echo \"
            \";\n echo \"Title:

            \";\n echo \"Abstract:

            \";\n echo \"\";\n echo \"

            \";\n\n echo \"
            \";\n\n echo \"

            \";\n echo \"Currently:\";\n echo \"

            \";\n echo \"
            \";\n draw_tree($person['id']);\n echo \"
            \";\n }\n\n }\n }\n else\n {\n not_admin();\n }\n\n break;\n\n\n ###############################################\n case \"edit_dissertation\":\n\n if (is_admin())\n {\n if (!$_GET['id']){action_box(\"No ID given.\");}\n else\n {\n\n $disciplines = find_disciplines();\n $schools = find_schools();\n $dissertation = find_dissertation(intval($_GET['id']));\n if (!$dissertation)\n {\n action_box(\"Dissertation not found.\");\n }\n else{\n\n $person = find_person($dissertation['person_id']);\n\n echo \"

            EDIT DISSERTATION DETAILS

            \\n\";\n\n echo \"
            \";\n echo \"\";\n echo \"\";\n echo \"\";\n\n echo \"

            \";\n echo get_person_link($person['id']);\n echo \"
            \";\n\n echo \"Degree: \\n\";\n echo \"
            \";\n\n echo \"Status: \\n\";\n echo \"
            \";\n\n echo \"Discipline: \\n\";\n echo \"
            \";\n\n echo \"School: \\n\";\n\n echo \"
            Year:\\n\";\n echo \"
            \";\n echo \"Title:

            \";\n echo \"Abstract:

            \";\n echo \"Admin Notes:

            \";\n echo \"\";\n echo \"

            \";\n\n echo \"
            \";\n\n echo \"

            \";\n echo \"Currently:\";\n echo \"

            \";\n echo \"
            \";\n draw_tree($person['id']);\n echo \"
            \";\n }\n\n }\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"delete_name\":\n\n if (is_admin())\n {\n if (!$_GET['id']){action_box(\"No ID given.\");}\n else\n {\n\n $person = find_name($_GET['name']);\n\n echo \"

            \";\n\n echo \"Are you sure you want to delete this name?\";\n\n echo \"

            \\n\";\n echo \"\\n\";\n echo \"\\n\";\n echo \"\";\n\n echo \"

            \";\n echo \"[ \".$person['firstname'].\" \".$person['middlename'].\" \".$person['lastname'].\" \".$person['suffix'].\" ]
            \";\n echo \"

            \";\n\n\n echo \"

            \";\n echo \"\";\n echo \"   Cancel

            \";\n\n echo \"
            \";\n\n echo \"

            \";\n\n\n\n\n }\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"set_preferred_name\":\n\n if (is_admin())\n {\n\n set_preferred_name($_GET['id'],$_GET['name']);\n\n action_box(\"Preferred Name Selected\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_tree&id=\".$_GET['id']);\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"recalculate_mpact\":\n\n if (is_admin()){\n\n # recalculate MPACT scores for passed person id\n calculate_scores($_GET['id']);\n\n action_box(\"MPACT Scores Recalculated\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_tree&id=\".$_GET['id']);\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"show_orphans\":\n\n if (is_admin())\n {\n\n $orphans = find_orphans();\n\n echo \"

            Orphans

            \\n\";\n\n echo \"

            \\n\";\n $counter = 0;\n foreach ($orphans as $orphan)\n {\n $counter++;\n echo $counter.\" \";\n echo get_person_link($orphan['person_id']);\n echo \" (Delete from Database)\";\n echo \"
            \\n\";\n }\n if ($counter < 1){echo \" - No orphans at this time.\";}\n echo \"

            \\n\";\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"delete_person\":\n\n if (is_admin())\n {\n if (!$_GET['id']){action_box(\"No ID given.\");}\n else\n {\n\n if (is_orphan($_GET['id']))\n {\n echo \"

            \";\n\n echo \"Are you sure you want to delete this person?\";\n\n echo \"

            \\n\";\n echo \"\\n\";\n echo \"\\n\";\n\n echo \"

            \";\n echo get_person_link($_GET['id']);\n echo \"

            \";\n\n\n echo \"

            \";\n echo \"

            \\n\";\n echo \"\";\n echo \"   Cancel

            \";\n\n echo \"
            \";\n\n echo \"

            \";\n }\n else\n {\n action_box(\"This person cannot be deleted.\");\n }\n }\n }\n else\n {\n not_admin();\n }\n\n break;\n\n\n ###############################################\n case \"show_disciplines\":\n\n $statustotals = array(0,0,0,0,0);\n $disciplines = find_disciplines();\n $disciplinecounts = find_discipline_counts();\n\n if (is_admin()){\n echo \"

            Add a New Discipline to the Database

            \\n\";\n }\n\n echo \"

            Disciplines Represented Across All Schools

            \\n\";\n\n echo \"

            \\n\";\n echo \"\\n\";\n echo \"\";\n echo \"\";\n foreach (range(0,4) as $one)\n {\n echo \"\";\n }\n echo \"\";\n foreach ($disciplines as $one => $two)\n {\n echo \"\";\n echo \"\";\n $statuscounts = find_discipline_statuses($one);\n foreach (range(0,4) as $three)\n {\n $statustotals[$three] += $statuscounts[$three];\n if (!isset($disciplinecounts[$one]) || $disciplinecounts[$one]==0)\n {\n $fraction = 0;\n }\n else\n {\n $fraction = 100*$statuscounts[$three]/intval($disciplinecounts[$one]);\n }\n echo \"\";\n }\n echo \"\\n\";\n }\n # summary line\n echo \"\";\n echo \"\";\n echo \"\";\n foreach (range(0,4) as $three)\n {\n $fraction = 100*$statustotals[$three]/array_sum($disciplinecounts);\n echo \"\";\n }\n echo \"\";\n echo \"
            Discipline$statuscodes[$one]
            $two (\".intval($disciplinecounts[$one]).\")\".$statuscounts[$three];\n if ($fraction != 0)\n {\n echo \" (\".sprintf(\"%.1f\",$fraction).\"%)\";\n }\n echo \"
            ------------------
            \";\n echo count($disciplines).\" Disciplines (\".array_sum($disciplinecounts).\" dissertations)\";\n echo \"\".$statustotals[$three];\n if ($fraction != 0)\n {\n echo \" (\".sprintf(\"%.1f\",$fraction).\"%)\";\n }\n echo \"
            \\n\";\n echo \"

            \\n\";\n\n break;\n\n ###############################################\n case \"show_discipline\":\n\n if (!$_GET['id']){action_box(\"No ID given.\");}\n else\n {\n\n $discipline_id = intval($_GET['id']);\n\n # Show Discipline Name\n $query = \"SELECT d.title as disciplinename\n FROM disciplines d\n WHERE\n d.id = '$discipline_id'\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result)) {\n extract($line);\n }\n\n echo \"

            $disciplinename

            \";\n\n # Show Histograph\n $counts = array();\n echo \"

            \\n\";\n echo \"Dissertations by Year:
            \\n\";\n $query = \"SELECT completedyear, count(*) as disscount FROM dissertations WHERE discipline_id='$discipline_id' GROUP BY completedyear\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $counts[$line['completedyear']] = $line['disscount'];\n }\n if (count($counts)>0)\n {\n $bigyear = max($counts);\n echo \"\\n\";\n echo \"\\n\";\n foreach ($counts as $one => $two)\n {\n $height=$two*intval(200/$bigyear);\n echo \"\\n\";\n }\n echo \"\";\n echo \"\\n\";\n foreach ($counts as $one => $two)\n {\n echo \"\\n\";\n }\n echo \"\";\n echo \"
            \";\n if ($one%10==0)\n {\n echo $one;\n }\n echo \"
            \\n\";\n }\n echo \"

            \\n\";\n }\n\n $schools = find_schools($discipline_id);\n $dissertation_count = 0;\n $statustotals = array(0,0,0,0,0);\n echo \"

            Schools Represented

            \\n\";\n\n echo \"

            \\n\";\n echo \"\\n\";\n echo \"\";\n echo \"\";\n foreach (range(0,4) as $one)\n {\n echo \"\";\n }\n echo \"\";\n foreach ($schools as $one => $two)\n {\n $statuscounts = find_dept_statuses($one,$discipline_id);\n $dissertation_count += array_sum($statuscounts);\n echo \"\";\n echo \"\";\n foreach (range(0,4) as $three)\n {\n $statustotals[$three] += $statuscounts[$three];\n $fraction = 100*$statuscounts[$three]/array_sum($statuscounts);\n echo \"\";\n }\n echo \"\\n\";\n }\n # summary line\n echo \"\";\n echo \"\";\n echo \"\";\n foreach (range(0,4) as $three)\n {\n\n if (array_sum($statustotals)==0)\n {\n $fraction = 0;\n }\n else\n {\n $fraction = 100*$statustotals[$three]/array_sum($statustotals);\n }\n echo \"\";\n }\n echo \"\";\n echo \"
            School$statuscodes[$one]
            $two (\".array_sum($statuscounts).\")\".$statuscounts[$three];\n if ($fraction != 0)\n {\n echo \" (\".sprintf(\"%.1f\",$fraction).\"%)\";\n }\n echo \"
            ------------------
            \";\n echo count($schools).\" Schools ($dissertation_count dissertations)\";\n echo \"\".$statustotals[$three];\n if ($fraction != 0)\n {\n echo \" (\".sprintf(\"%.1f\",$fraction).\"%)\";\n }\n echo \"
            \\n\";\n echo \"

            \\n\";\n\n # link to edit the discipline name\n if (is_empty_discipline($_GET['id']))\n {\n echo \"

            \";\n echo \"

            Edit Discipline Name

            \\n\";\n }\n\n break;\n\n ###############################################\n case \"show_school\":\n\n if (!$_GET['id']){action_box(\"No ID given.\");}\n else\n {\n\n $school_id = intval($_GET['id']);\n\n # Show School Name\n $query = \"SELECT s.fullname as schoolname, s.country\n FROM schools s\n WHERE\n s.id = '$school_id'\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result)) {\n extract($line);\n }\n\n echo \"

            $schoolname ($country)

            \";\n\n # Show Histograph\n echo \"

            \\n\";\n echo \"Dissertations by Year:
            \\n\";\n $query = \"SELECT completedyear, count(*) as disscount FROM dissertations WHERE school_id='$school_id' GROUP BY completedyear\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $counts[$line['completedyear']] = $line['disscount'];\n }\n $bigyear = max($counts);\n echo \"\\n\";\n echo \"\\n\";\n foreach ($counts as $one => $two)\n {\n $height=$two*intval(200/$bigyear);\n echo \"\\n\";\n }\n echo \"\";\n echo \"\\n\";\n foreach ($counts as $one => $two)\n {\n echo \"\\n\";\n }\n echo \"\";\n echo \"
            \";\n if ($one%10==0)\n {\n echo $one;\n }\n echo \"
            \\n\";\n echo \"

            \\n\";\n\n\n $disciplines = find_disciplines($school_id);\n $dissertation_count = 0;\n $statustotals = array(0,0,0,0,0);\n echo \"

            Disciplines Represented

            \\n\";\n\n echo \"

            \\n\";\n echo \"\\n\";\n echo \"\";\n echo \"\";\n foreach (range(0,4) as $one)\n {\n echo \"\";\n }\n echo \"\";\n foreach ($disciplines as $one => $two)\n {\n $statuscounts = find_dept_statuses($school_id,$one);\n $dissertation_count += array_sum($statuscounts);\n echo \"\";\n echo \"\";\n foreach (range(0,4) as $three)\n {\n $statustotals[$three] += $statuscounts[$three];\n $fraction = 100*$statuscounts[$three]/array_sum($statuscounts);\n echo \"\";\n }\n echo \"\\n\";\n }\n # summary line\n echo \"\";\n echo \"\";\n echo \"\";\n foreach (range(0,4) as $three)\n {\n $fraction = 100*$statustotals[$three]/array_sum($statustotals);\n echo \"\";\n }\n echo \"\";\n echo \"
            Discipline$statuscodes[$one]
            $two (\".array_sum($statuscounts).\")\".$statuscounts[$three];\n if ($fraction != 0)\n {\n echo \" (\".sprintf(\"%.1f\",$fraction).\"%)\";\n }\n echo \"
            ------------------
            \";\n echo count($disciplines).\" Disciplines ($dissertation_count dissertations)\";\n echo \"\".$statustotals[$three];\n if ($fraction != 0)\n {\n echo \" (\".sprintf(\"%.1f\",$fraction).\"%)\";\n }\n echo \"
            \\n\";\n echo \"

            \\n\";\n }\n\n # link to edit the school info\n if (is_empty_school($_GET['id']))\n {\n echo \"

            \";\n echo \"

            Edit School Information

            \\n\";\n }\n\n break;\n\n ###############################################\n case \"show_schools\":\n\n $statustotals = array(0,0,0,0,0);\n $schools = find_schools();\n $schoolcounts = find_school_counts();\n\n if (is_admin()){\n echo \"

            Add a New School to the Database

            \\n\";\n }\n echo \"

            Schools Represented Across All Disciplines

            \\n\";\n\n echo \"

            \\n\";\n echo \"\\n\";\n echo \"\";\n echo \"\";\n foreach (range(0,4) as $one)\n {\n echo \"\";\n }\n echo \"\";\n foreach ($schools as $one => $two)\n {\n echo \"\";\n echo \"\";\n $statuscounts = find_school_statuses($one);\n foreach (range(0,4) as $three)\n {\n $statustotals[$three] += $statuscounts[$three];\n if (intval($schoolcounts[$one]) == 0){\n $fraction = 0;\n }\n else{\n $fraction = 100*$statuscounts[$three]/intval($schoolcounts[$one]);\n }\n echo \"\";\n }\n echo \"\\n\";\n }\n # summary line\n echo \"\";\n echo \"\";\n echo \"\";\n foreach (range(0,4) as $three)\n {\n $fraction = 100*$statustotals[$three]/array_sum($schoolcounts);\n echo \"\";\n }\n echo \"\";\n echo \"
            School$statuscodes[$one]
            $two (\".intval($schoolcounts[$one]).\")\".$statuscounts[$three];\n if ($fraction != 0)\n {\n echo \" (\".sprintf(\"%.1f\",$fraction).\"%)\";\n }\n echo \"
            ------------------
            \";\n echo count($schools).\" Schools (\".array_sum($schoolcounts).\" dissertations)\";\n echo \"\".$statustotals[$three];\n if ($fraction != 0)\n {\n echo \" (\".sprintf(\"%.1f\",$fraction).\"%)\";\n }\n echo \"
            \\n\";\n echo \"

            \\n\";\n\n break;\n\n ###############################################\n case \"show_department\":\n\n if (!$_GET['d'] || !$_GET['s']){action_box(\"No ID given.\");}\n else\n {\n\n $school_id = $_GET['s'];\n $discipline_id = $_GET['d'];\n\n\n # Show Discipline Name\n $query = \"SELECT d.title as disciplinename\n FROM disciplines d\n WHERE\n d.id = '$discipline_id'\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n extract($line);\n }\n # Show School Name\n $query = \"SELECT s.fullname as schoolname, s.country\n FROM schools s\n WHERE\n s.id = '$school_id'\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result)) {\n extract($line);\n }\n\n echo \"\n

            \n $disciplinename\n @\n $schoolname ($country)\n

            \n \";\n\n # Advisor and Committee Activity\n echo \"

            Dissertation Activity and MPACT Scores (click table headings to sort)

            \";\n\n echo \"

            \";\n $theprofs = find_profs_at_dept($school_id,$discipline_id);\n if (count($theprofs)>0)\n {\n $sortedprofs = array();\n $proflist = \"\";\n $query = \"SELECT id FROM people WHERE id IN (\";\n foreach ($theprofs as $prof){$proflist .= \"$prof,\";}\n $proflist = rtrim($proflist, \",\");\n $query .= \"$proflist) ORDER BY ac_score DESC\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $sortedprofs[] = $line['id'];\n }\n $profcount = 0;\n echo \"\\n\";\n echo \"\n \n \n \n \n \n \n \n \n \n \n \\n\";\n foreach ($sortedprofs as $one)\n {\n echo \"\";\n $profcount++;\n echo \"\";\n echo \"\";\n $scores = mpact_scores($one);\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\\n\";\n }\n echo \"
            -NameACA+CGTTATDW
            $profcount.\";\n echo get_person_link($one);\n echo \"\".$scores['A'].\"\".$scores['C'].\"\".$scores['AC'].\"\".$scores['G'].\"\".$scores['T'].\"\".$scores['TA'].\"\".$scores['TD'].\"\".$scores['W'].\"
            \\n\";\n echo \"

            \";\n }\n else\n {\n echo \"

            - None Listed

            \\n\";\n }\n echo \"
            \";\n\n\n\n\n # Dissertations Conferred\n echo \"

            Dissertations Conferred

            \";\n\n\n\n\n # Show Histograph\n echo \"

            \\n\";\n echo \"Dissertations by Year:
            \\n\";\n $query = \"SELECT completedyear, count(*) as disscount\n FROM dissertations\n WHERE\n school_id='$school_id' AND\n discipline_id=$discipline_id\n GROUP BY\n completedyear\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $counts[$line['completedyear']] = $line['disscount'];\n }\n echo \"\\n\";\n echo \"\\n\";\n foreach ($counts as $one => $two)\n {\n $height=$two*10;\n echo \"\\n\";\n }\n echo \"\";\n echo \"\\n\";\n foreach ($counts as $one => $two)\n {\n echo \"\\n\";\n }\n echo \"\";\n echo \"
            \";\n if ($one%10==0)\n {\n echo $one;\n }\n echo \"
            \\n\";\n echo \"

            \\n\";\n\n\n\n\n\n $query = \"SELECT d.person_id, d.completedyear, d.status\n FROM\n dissertations d,\n schools s,\n people p,\n names n\n WHERE\n s.id = '$school_id' AND\n d.discipline_id = '$discipline_id' AND\n d.school_id = s.id AND\n d.person_id = p.id AND\n p.preferred_name_id = n.id\n ORDER BY\n d.completedyear ASC, n.lastname ASC, n.firstname ASC\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result)) {\n extract($line);\n $year_conferred[$person_id] = $completedyear;\n $degree_status[$person_id] = $status;\n }\n\n $schoolcount = 0;\n echo \"

            \";\n foreach ($year_conferred as $person => $year)\n {\n $schoolcount++;\n echo \"
            $schoolcount. \";\n echo get_person_link($person);\n echo \" ($year)\";\n if ($degree_status[$person] < 4)\n {\n echo \" ---------------------------------- \".$statuscodes[$degree_status[$person]];\n }\n }\n echo \"

            \";\n\n }\n\n break;\n\n ###############################################\n default:\n // oops - not supposed to be here\n action_box(\"invalid action\",1);\n }\n }\n else\n {\n\n if (isset($_GET['show']))\n {\n if ($_GET['show'] == \"all\")\n {\n $alphabet_limiter = \"\"; // set it to show everything\n }\n else\n {\n $alphabet_limiter = $_GET['show'];\n }\n\n show_alphabet();\n\n if (is_admin())\n {\n echo \"

            Add a New Person to the Database

            \\n\";\n }\n\n if (is_admin()){\n echo \"
            \";\n echo \"\";\n echo \"\";\n echo \"\";\n }\n\n // GET ALL DISSERTATIONS IN A HASH\n $disciplines = find_disciplines();\n $query = \"SELECT id, person_id, discipline_id FROM dissertations\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $graduates[$line['person_id']] = $line['discipline_id'];\n }\n\n // LOOP THROUGH ALL PEOPLE FOR THIS LETTER\n echo \"\\n\";\n echo \"\\n\";\n if (is_admin()){echo \"\\n\";}\n echo \"\\n\";\n echo \"\\n\";\n echo \"\\n\";\n echo \"\\n\";\n echo \"\\n\";\n\n $query = \"SELECT n.id, n.firstname,\n n.middlename, n.lastname, n.suffix,\n p.id as person_id\n FROM names n, people p\n WHERE\n n.id = p.preferred_name_id AND\n n.lastname LIKE '\".$alphabet_limiter.\"%'\n ORDER BY n.lastname ASC, n.firstname ASC\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n $rowcount = 0;\n while ( $line = mysqli_fetch_array($result)) {\n extract($line);\n\n $rowcount++;\n\n echo \"\";\n if (is_admin()){\n echo \"\";\n }\n echo \"\";\n echo \"\";\n $discipline = isset($graduates[$person_id]) ? $disciplines[$graduates[$person_id]] : \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n\n if (is_admin()){\n if ($rowcount % 25 == 0){\n echo \"\";\n }\n }\n\n }\n\n echo \"
            MergeCountLast NameFull NameDissertation Discipline
            $rowcount.$lastname$firstname $middlename $lastname $suffix$discipline
            \\n\";\n\n if (is_admin()){\n echo \"\";\n echo \"
            \";\n }\n\n echo \"

            \\n\";\n\n show_alphabet();\n\n }\n else\n {\n // DISPLAY THE FRONT PAGE\n\n action_box(\"Front Page...\",0.1,\"./\");\n\n }\n\n }\n\n}\n\n\n\n\n\n\n\n\n\n###############################################\n// SOMETHING WAS SUBMITTED - through a form\nelse\n{\n\n if ($_POST['op'] != \"login\"){\n // Display header\n xhtml_web_header();\n }\n\n switch ($_POST['op'])\n {\n ###############################################\n case \"login\";\n\n $host_info = get_environment_info();\n if ($host_info['hostname'] == \"sils\"){\n # no logins here - go to dev server\n action_box(\"No Logins Here...\",2,$_SERVER['SCRIPT_NAME']);\n }\n else{\n # check credentials / start session\n $query = \"SELECT id, username, fullname FROM users\n WHERE username = '\".addslashes($_POST['username']).\"'\n AND password = '\".addslashes($_POST['password']).\"'\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n $line = mysqli_fetch_array($result);\n if (isset($line['id'])){\n # save cookie info for one week\n setcookie('MPACT_userid',$line['id'],time()+60*60*24*7);\n # redirect\n header(\"Location: \".$_SERVER['SCRIPT_NAME']);\n }\n else{\n // Display header\n xhtml_web_header();\n # incorrect credentials\n action_box(\"Please try again...\",2,$_SERVER['SCRIPT_NAME'].\"?op=login\");\n }\n }\n\n break;\n\n ###############################################\n case \"glossary_edit\";\n if (is_admin())\n {\n\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n $query = \"UPDATE glossary\n SET\n definition = '\".$_POST['definition'].\"'\n WHERE\n id = '\".$_POST['id'].\"'\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n # log it\n mpact_logger(\"updated glossary [\".$_POST['term'].\" (\".$_POST['id'].\")] to (\".$_POST['definition'].\")\");\n\n action_box(\"Definition Saved\",2,$_SERVER['SCRIPT_NAME'].\"?op=glossary\");\n }\n else\n {\n not_admin();\n }\n break;\n\n ###############################################\n case \"merge_confirm\":\n\n if (is_admin()){\n\n echo \"
            \";\n echo \"\";\n echo \"\";\n\n foreach ($_POST['mergers'] as $one)\n {\n echo \"
            \";\n echo \"

            [$one]

            \";\n echo draw_tree( $one );\n echo \"\";\n echo \"
            \";\n }\n\n echo \"\";\n echo \"
            \";\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"search\":\n\n $results = people_search($_POST['q']);\n\n if (count($results) > 0)\n {\n echo \"

            People Search Results for [\".$_POST['q'].\"]:

            \";\n }\n\n echo \"

            \\n\";\n $count = 0;\n foreach ($results as $person_id)\n {\n $count++;\n $schoolinfo = find_persons_school($person_id);\n echo \"$count. \".get_person_link($person_id);\n if ($schoolinfo['completedyear'])\n {\n echo \" - \".$schoolinfo['school'].\" (\".$schoolinfo['completedyear'].\")\";\n }\n echo \"
            \\n\";\n }\n if ($count < 1)\n {\n echo \"

            \\n\";\n echo \"There were no results for [\".$_POST['q'].\"].\";\n if (strlen($_POST['q']) < 2)\n {\n echo \"

            \\n\";\n echo \"Please use at least two characters to search.\";\n }\n else\n {\n if (is_admin()){\n echo \"

            \\n\";\n echo \"

            Add a New Person to the Database

            \\n\";\n }\n }\n echo \"

            \\n\";\n }\n\n echo \"

            \\n\";\n\n break;\n\n ###############################################\n case \"search_title_abstract\":\n\n $results = title_abstract_search($_POST['qta']);\n\n if (count($results) > 0)\n {\n echo \"

            Title/Abstract Search Results for [\".$_POST['qta'].\"]:

            \";\n }\n\n echo \"

            \\n\";\n $count = 0;\n foreach ($results as $person_id)\n {\n $count++;\n $schoolinfo = find_persons_school($person_id);\n echo \"$count. \".get_person_link($person_id);\n if ($schoolinfo['completedyear'])\n {\n echo \" - \".$schoolinfo['school'].\" (\".$schoolinfo['completedyear'].\")\";\n }\n echo \"
            \\n\";\n }\n if ($count < 1)\n {\n echo \"

            \\n\";\n echo \"There were no results for [\".$_POST['qta'].\"].\";\n if (strlen($_POST['qta']) < 2)\n {\n echo \"

            \\n\";\n echo \"Please use at least two characters to search.\";\n }\n else\n {\n if (is_admin()){\n echo \"

            \\n\";\n }\n }\n echo \"

            \\n\";\n }\n\n echo \"

            \\n\";\n\n break;\n\n ###############################################\n case \"search_notes\":\n\n if (is_admin()){\n\n $results = notes_search($_POST['qn']);\n\n if (count($results) > 0)\n {\n echo \"

            Admin Notes Search Results for [\".$_POST['qn'].\"]:

            \";\n }\n\n echo \"

            \\n\";\n $count = 0;\n foreach ($results as $person_id)\n {\n $count++;\n $schoolinfo = find_persons_school($person_id);\n echo \"$count. \".get_person_link($person_id);\n if ($schoolinfo['completedyear'])\n {\n echo \" - \".$schoolinfo['school'].\" (\".$schoolinfo['completedyear'].\")\";\n }\n echo \"
            \\n\";\n }\n if ($count < 1)\n {\n echo \"

            \\n\";\n echo \"There were no results for [\".$_POST['qm'].\"].\";\n if (strlen($_POST['qn']) < 2)\n {\n echo \"

            \\n\";\n echo \"Please use at least two characters to search.\";\n }\n else\n {\n if (is_admin()){\n echo \"

            \\n\";\n }\n }\n echo \"

            \\n\";\n }\n\n echo \"

            \\n\";\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"merge_doit\":\n\n if (is_admin()){\n\n # delete the family tree's dotgraphs of each person\n foreach ($_POST['mergers'] as $one)\n {\n delete_associated_dotgraphs($one);\n }\n\n # pop off one of the people_ids\n $into = array_pop($_POST['mergers']);\n\n # merge each remaining person into the one above\n foreach ($_POST['mergers'] as $one)\n {\n merge_two_people($one,$into);\n }\n\n # recalculate MPACT scores for merged person id\n calculate_scores($into);\n\n action_box(\"Merge was Successful\",2,$_SERVER['SCRIPT_NAME'].\"?show=\".$_POST['show']);\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n\n ###############################################\n case \"create_discipline\":\n\n if (is_admin()){\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n if ($_POST['title'] == \"\")\n {\n action_box(\"Need to have at least a Discipline Title.\",3,$_SERVER['SCRIPT_NAME'].\"?op=create_discipline\");\n }\n elseif (is_duplicate_discipline($_POST['title']))\n {\n action_box(\"Discipline (\".$_POST['title'].\") already exists.\",3,$_SERVER['SCRIPT_NAME'].\"?op=show_disciplines\");\n }\n else\n {\n\n # Create Discipline\n $query = \"INSERT disciplines\n SET\n title = '\".$_POST['title'].\"'\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n # Get the just created discipline_id\n $query = \"SELECT id as new_discipline_id, title FROM disciplines\n WHERE\n title = '\".$_POST['title'].\"'\n ORDER BY id DESC\n LIMIT 1\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n extract($line);\n }\n # log it\n mpact_logger(\"created discipline[\".$new_discipline_id.\"] (\".$title.\")\");\n\n action_box(\"Discipline Created\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_disciplines\");\n\n }\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"edit_discipline\":\n\n if (is_admin()){\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n if ($_POST['title'] == \"\")\n {\n action_box(\"Need to have at least a Discipline Title.\",3,$_SERVER['SCRIPT_NAME'].\"?op=edit_discipline&id=\".$_POST['discipline_id'].\"\");\n }\n elseif (is_duplicate_discipline($_POST['title']))\n {\n action_box(\"Discipline (\".$_POST['title'].\") already exists.\",3,$_SERVER['SCRIPT_NAME'].\"?op=show_disciplines\");\n }\n else\n {\n\n # Edit Discipline\n $query = \"UPDATE disciplines\n SET\n title = '\".$_POST['title'].\"'\n WHERE\n id = '\".$_POST['discipline_id'].\"'\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n # log it\n mpact_logger(\"edited discipline[\".$_POST['discipline_id'].\"] (\".$_POST['title'].\")\");\n\n action_box(\"Discipline Edited\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_disciplines\");\n\n }\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"create_school\":\n\n if (is_admin()){\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n $_POST = array_map('trim',$_POST);\n\n if ($_POST['fullname'] == \"\" || $_POST['country'] == \"\")\n {\n action_box(\"Need to have at least a School name and Country.\",3,$_SERVER['SCRIPT_NAME'].\"?op=create_school\");\n }\n elseif (is_duplicate_school($_POST['fullname']))\n {\n action_box(\"School (\".$_POST['fullname'].\") already exists.\",3,$_SERVER['SCRIPT_NAME'].\"?op=show_schools\");\n }\n else\n {\n\n # Create School\n $query = \"INSERT schools\n SET\n fullname = '\".$_POST['fullname'].\"',\n country = '\".$_POST['country'].\"'\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n # Get the just created school_id\n $query = \"SELECT id as new_school_id, fullname FROM schools\n WHERE\n fullname = '\".$_POST['fullname'].\"'\n ORDER BY id DESC\n LIMIT 1\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n extract($line);\n }\n # log it\n mpact_logger(\"created school[\".$new_school_id.\"] (\".$fullname.\")\");\n\n action_box(\"School Created\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_schools\");\n\n }\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"edit_school\":\n\n if (is_admin()){\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n if ($_POST['fullname'] == \"\" || $_POST['country'] == \"\")\n {\n action_box(\"Need to have at least a School name and Country.\",3,$_SERVER['SCRIPT_NAME'].\"?op=edit_school&id=\".$_POST['school_id'].\"\");\n }\n elseif (is_duplicate_school($_POST['fullname']))\n {\n action_box(\"School (\".$_POST['fullname'].\") already exists.\",3,$_SERVER['SCRIPT_NAME'].\"?op=show_schools\");\n }\n else\n {\n\n # Edit School\n $query = \"UPDATE schools\n SET\n fullname = '\".$_POST['fullname'].\"',\n country = '\".$_POST['country'].\"'\n WHERE\n id = '\".$_POST['school_id'].\"'\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n # log it\n mpact_logger(\"edited school[\".$_POST['school_id'].\"] (\".$_POST['fullname'].\")\");\n\n action_box(\"School Edited\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_schools\");\n\n }\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"create_person\":\n\n if (is_admin()){\n\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n if ($_POST['lastname'] == \"\")\n {\n action_box(\"Need to have at least a Last Name.\",3,$_SERVER['SCRIPT_NAME'].\"?op=create_person\");\n }\n else\n {\n # Create Name\n $query = \"INSERT names\n SET\n firstname = '\".$_POST['firstname'].\"',\n middlename = '\".$_POST['middlename'].\"',\n lastname = '\".$_POST['lastname'].\"',\n suffix = '\".$_POST['suffix'].\"'\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n # Get the just created name_id\n $query = \"SELECT id as new_name_id FROM names\n WHERE\n firstname = '\".$_POST['firstname'].\"' AND\n middlename = '\".$_POST['middlename'].\"' AND\n lastname = '\".$_POST['lastname'].\"' AND\n suffix = '\".$_POST['suffix'].\"'\n ORDER BY id DESC\n LIMIT 1\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n extract($line);\n }\n\n # Create Person with new_name_id\n $query = \"INSERT people\n SET\n preferred_name_id = '\".$new_name_id.\"',\n degree = '\".$_POST['degree'].\"'\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n # Get the just created person_id\n $query = \"SELECT id as new_person_id FROM people\n WHERE\n preferred_name_id = '\".$new_name_id.\"'\n ORDER BY id DESC\n LIMIT 1\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n extract($line);\n }\n\n # Sync them together with new_person_id\n $query = \"UPDATE names\n SET\n person_id = '\".$new_person_id.\"'\n WHERE\n id = '\".$new_name_id.\"'\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n $after = find_person($new_person_id);\n\n action_box(\"Person Created\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_tree&id=\".$new_person_id);\n\n # log it\n mpact_logger(\"created person[\".$new_person_id.\"] (\".$after['fullname'].\")\");\n\n }\n }\n else\n {\n not_admin();\n }\n\n break;\n\n\n ###############################################\n case \"remove_mentor\":\n\n if (is_admin()){\n\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n if (remove_mentor($_POST['mentor_type'],$_POST['student_id'],$_POST['mentor_id']))\n {\n action_box(\"Mentor Removed\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_tree&id=\".$_POST['student_id']);\n }\n else\n {\n action_box(\"Nope.\");\n }\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n\n ###############################################\n case \"add_mentor\":\n\n if (is_admin()){\n\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n add_mentor($_POST['mentor_type'],$_POST['student_id'],$_POST['mentor_id']);\n\n action_box(\"Mentor Added\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_tree&id=\".$_POST['student_id']);\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n\n ###############################################\n case \"add_student\":\n\n if (is_admin()){\n\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n add_mentor($_POST['mentor_type'],$_POST['student_id'],$_POST['mentor_id']);\n\n action_box(\"Student Added\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_tree&id=\".$_POST['mentor_id']);\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n\n ###############################################\n case \"add_name\":\n\n if (is_admin()){\n\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n $person = find_person($_POST['id']);\n\n $query = \"INSERT names\n SET\n firstname = '\".$_POST['firstname'].\"',\n middlename = '\".$_POST['middlename'].\"',\n lastname = '\".$_POST['lastname'].\"',\n suffix = '\".$_POST['suffix'].\"',\n person_id = '\".$_POST['id'].\"'\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n # get the just created name_id\n $query = \"SELECT id as new_name_id FROM names\n WHERE\n firstname = '\".$_POST['firstname'].\"' AND\n middlename = '\".$_POST['middlename'].\"' AND\n lastname = '\".$_POST['lastname'].\"' AND\n suffix = '\".$_POST['suffix'].\"'\n ORDER BY id DESC\n LIMIT 1\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n extract($line);\n }\n\n # find that full name from the DB\n $added = find_name($new_name_id);\n\n action_box(\"Name Added\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_tree&id=\".$_POST['id']);\n # log it\n mpact_logger(\"added name (\".$added['fullname'].\") for person[\".$_POST['id'].\"] (\".$person['fullname'].\")\");\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"edit_name\":\n\n if (is_admin()){\n\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n $before = find_name($_POST['name_id']);\n\n $query = \"UPDATE names\n SET\n firstname = '\".$_POST['firstname'].\"',\n middlename = '\".$_POST['middlename'].\"',\n lastname = '\".$_POST['lastname'].\"',\n suffix = '\".$_POST['suffix'].\"'\n WHERE\n id = '\".$_POST['name_id'].\"' AND\n person_id = '\".$_POST['id'].\"'\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n $after = find_name($_POST['name_id']);\n\n # delete dotgraph for this person\n delete_associated_dotgraphs($_POST['id']);\n\n action_box(\"Name Saved\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_tree&id=\".$_POST['id']);\n # log it\n mpact_logger(\"edited name[\".$_POST['name_id'].\"] for person[\".$_POST['id'].\"] from (\".$before['fullname'].\") to (\".$after['fullname'].\")\");\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"add_url\":\n\n if (is_admin()){\n\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n $person = find_person(intval($_POST['person_id']));\n\n $query = \"INSERT urls\n SET\n url = '\".$_POST['url'].\"',\n description = '\".$_POST['description'].\"',\n updated_at = now(),\n person_id = '\".$_POST['person_id'].\"'\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n action_box(\"Reference URL Added\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_tree&id=\".$_POST['person_id'].\"#urls\");\n # log it\n mpact_logger(\"added URL[\".substr($_POST['url'], 0, 30).\"] for person[\".$_POST['person_id'].\"] (\".$person['fullname'].\")\");\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"edit_url\":\n\n if (is_admin()){\n\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n $url = find_url(intval($_POST['id']));\n $person = find_person($url['person_id']);\n\n $query = \"UPDATE urls\n SET\n url = '\".$_POST['url'].\"',\n description = '\".$_POST['description'].\"',\n updated_at = now()\n WHERE\n id = '\".$_POST['id'].\"'\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n action_box(\"Reference URL Edited\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_tree&id=\".$url['person_id'].\"#urls\");\n # log it\n mpact_logger(\"edited URL[\".substr($_POST['url'], 0, 30).\"] for person[\".$url['person_id'].\"] (\".$person['fullname'].\")\");\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"delete_url\":\n\n if (is_admin()){\n\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n $url = find_url(intval($_POST['id']));\n $person = find_person($url['person_id']);\n\n $query = \"DELETE FROM urls\n WHERE\n id = '\".$_POST['id'].\"'\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n action_box(\"Reference URL Deleted\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_tree&id=\".$url['person_id'].\"#urls\");\n # log it\n mpact_logger(\"deleted URL[\".substr($url['url'], 0, 30).\"] for person[\".$url['person_id'].\"] (\".$person['fullname'].\")\");\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"edit_degree\":\n\n if (is_admin()){\n\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n $person = find_person(intval($_POST['id']));\n\n $query = \"UPDATE people\n SET\n degree = '\".$_POST['degree'].\"'\n WHERE\n id = '\".$_POST['id'].\"'\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n action_box(\"Degree Edited\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_tree&id=\".$person['id']);\n # log it\n mpact_logger(\"edited degree[\".$_POST['degree'].\"] for person[\".$person['id'].\"] (\".$person['fullname'].\")\");\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"create_dissertation\":\n\n if (is_admin()){\n\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n $schools = find_schools();\n\n $person = find_person($_POST['person_id']);\n\n $query = \"INSERT INTO dissertations\n SET\n person_id = '\".$_POST['person_id'].\"',\n discipline_id = '\".$_POST['discipline_id'].\"',\n school_id = '\".$_POST['school_id'].\"',\n completedyear = '\".$_POST['completedyear'].\"',\n status = '\".$_POST['status'].\"',\n title = '\".$_POST['title'].\"',\n abstract = '\".$_POST['abstract'].\"'\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n $query = \"UPDATE people\n SET degree = '\".$_POST['degree'].\"'\n WHERE\n id = '\".$_POST['person_id'].\"'\";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n action_box(\"Dissertation Created\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_tree&id=\".$_POST['person_id']);\n # log it\n $dissertation = find_dissertation_by_person($_POST['person_id']);\n mpact_logger(\"create dissertation[\".$dissertation['id'].\"] (\".$person['fullname'].\") with school[\".$dissertation['school_id'].\"] (\".$schools[$dissertation['school_id']].\") in year(\".$dissertation['completedyear'].\") with status (\".$statuscodes[$_POST['status']].\")\");\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n\n ###############################################\n case \"edit_dissertation\":\n\n if (is_admin()){\n\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n $disciplines = find_disciplines();\n $schools = find_schools();\n\n $dissertation = find_dissertation($_POST['id']);\n $person = find_person($dissertation['person_id']);\n\n $query = \"UPDATE dissertations\n SET\n school_id = '\".$_POST['school_id'].\"',\n discipline_id = '\".$_POST['discipline_id'].\"',\n completedyear = '\".$_POST['completedyear'].\"',\n status = '\".$_POST['status'].\"',\n notes = '\".$_POST['notes'].\"',\n title = '\".$_POST['title'].\"',\n abstract = '\".$_POST['abstract'].\"'\n WHERE\n id = '\".$_POST['id'].\"'\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n $query = \"UPDATE people\n SET degree = '\".$_POST['degree'].\"'\n WHERE\n id = '\".$_POST['person_id'].\"'\";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n action_box(\"Dissertation Saved\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_tree&id=\".$_POST['person_id']);\n # log it\n mpact_logger(\"edit dissertation[\".$_POST['id'].\"] (\".$person['fullname'].\") from school[\".$dissertation['school_id'].\"] (\".$schools[$dissertation['school_id']].\") in year(\".$dissertation['completedyear'].\") to school[\".$_POST['school_id'].\"] (\".$schools[$_POST['school_id']].\") in year(\".$_POST['completedyear'].\")\");\n # look for changes\n # degree\n if ($person['degree'] != $_POST['degree'])\n {\n mpact_logger($dissertation['id'].\" updated degree [\".$_POST['degree'].\"]\",\"dissertation\");\n }\n # discipline\n if ($dissertation['discipline_id'] != $_POST['discipline_id'])\n {\n mpact_logger($dissertation['id'].\" updated discipline [\".$_POST['discipline_id'].\" (\".$disciplines[$_POST['discipline_id']].\")]\",\"dissertation\");\n }\n # school\n if ($dissertation['school_id'] != $_POST['school_id'])\n {\n mpact_logger($dissertation['id'].\" updated school [\".$_POST['school_id'].\" (\".$schools[$_POST['school_id']].\")]\",\"dissertation\");\n }\n # year\n if ($dissertation['completedyear'] != $_POST['completedyear'])\n {\n mpact_logger($dissertation['id'].\" updated completedyear [\".$_POST['completedyear'].\"]\",\"dissertation\");\n }\n # title\n if ($dissertation['title'] != $_POST['title'])\n {\n mpact_logger($dissertation['id'].\" updated title [\".$_POST['title'].\"]\",\"dissertation\");\n }\n # abstract\n if ($dissertation['abstract'] != $_POST['abstract'])\n {\n mpact_logger($dissertation['id'].\" updated abstract [\".$_POST['abstract'].\"]\",\"dissertation\");\n }\n # status\n if ($dissertation['status'] != $_POST['status'])\n {\n mpact_logger($dissertation['id'].\" updated status [\".$statuscodes[$_POST['status']].\"]\",\"dissertation\");\n }\n # status\n if ($dissertation['notes'] != $_POST['notes'])\n {\n mpact_logger($dissertation['id'].\" updated notes [\".$_POST['notes'].\"]\",\"dissertation\");\n }\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"delete_person\":\n\n if (is_admin()){\n\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n if (delete_person($_POST['id']))\n {\n action_box(\"Person Deleted\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_tree&id=\".$_POST['id']);\n }\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n\n ###############################################\n case \"delete_name\":\n\n if (is_admin()){\n\n if (!get_magic_quotes_gpc()) {$_POST = array_map('addslashes',$_POST);}\n\n $name = find_name($_POST['name_id']);\n $person = find_person($_POST['id']);\n\n $query = \"DELETE FROM names\n WHERE\n id = '\".$_POST['name_id'].\"' AND\n person_id = '\".$_POST['id'].\"'\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n action_box(\"Name Deleted\",2,$_SERVER['SCRIPT_NAME'].\"?op=show_tree&id=\".$_POST['id']);\n\n # log it\n mpact_logger(\"deleted name[\".$_POST['name_id'].\"] (\".$name['fullname'].\") from person[\".$person['id'].\"] (\".$person['fullname'].\")\");\n\n }\n else\n {\n not_admin();\n }\n\n break;\n\n ###############################################\n case \"edit_school\":\n\n break;\n\n ###############################################\n default:\n // oops - not supposed to be here\n action_box(\"oops, back to the front page...\",2);\n\n\n }\n\n\n}\n\nxhtml_web_footer();\n\n?>\n", "mpact_include.php": " $val)\n foreach ($aSubtrahends as $aSubtrahend)\n if (array_key_exists($key, $aSubtrahend))\n unset ($ar1[$key]);\n return $ar1;\n}\n\n# -------------------------------------------------------------------------------\nfunction action_box($message,$bounce = \"0\",$location = \"index.php\"){\n\n echo \"\n

            \n $message\n

            \n

            \n \";\n\n if ($bounce != \"0\"){\n echo \"\n \n

            \n Forwarding in $bounce seconds (or click here to do the same)\n

            \n \";\n }\n\n}\n\n# -------------------------------------------------------------------------------\nfunction xhtml_orig_web_header(){\n\n # make search box happy\n if (!isset($_POST['q'])){$_POST['q'] = \"\";}\n if (!isset($_POST['qta'])){$_POST['qta'] = \"\";}\n if (!isset($_POST['qn'])){$_POST['qn'] = \"\";}\n\n # print out header info\n echo \"\n\n \n \n \n MPACT\n\n \n \n \n\n \n \n\n \n\n \n \n \n\n
            \n \n \n \n \n \n
            \n
            \n MPACT -\n Database -\n \n People Search: \n
            -\n
            \n \n Title/Abstract Search: \n
            \n\";\n if (is_admin()){\n echo \" -
            \n \n Admin Notes Search: \n
            \";\n }\n echo \"
            \n\";\n if (is_admin()){\n echo $_SESSION['MPACT']['fullname'].\" (\".$_SESSION['MPACT']['username'].\") - Logout\";\n }\n else{\n $host_info = get_environment_info();\n if ($host_info['hostname'] != \"sils\"){\n echo \"Login\";\n }\n }\necho \"\n
            \n

            \n\n \";\n\n\n}\n\n# -------------------------------------------------------------------------------\nfunction xhtml_web_header(){\n\n # make search box happy\n if (!isset($_POST['q'])){$_POST['q'] = \"\";}\n if (!isset($_POST['qta'])){$_POST['qta'] = \"\";}\n if (!isset($_POST['qn'])){$_POST['qn'] = \"\";}\n\n # print out header info\n echo \"\n\n \n \n \n MPACT\n \n \n \n \n \n\n\";\n\necho \"

            \";\nif (is_admin()){\n echo $_SESSION['MPACT']['fullname'].\" (\".$_SESSION['MPACT']['username'].\") - Logout\";\n}\nelse{\n echo \"Login\";\n}\necho \"

            \";\necho \"
            \";\n\necho \"\n
            \n \n \n\n \n\n \n\n \n\n \n
            \n \n \n \n \n Publications  • \n Project Statistics\n
            \n
            \n Glossary  • \n Schools  • \n Disciplines\n
            \n
            \n \n People Search: \n
            \n    \n
            \n \n Title/Abstract Search: \n
            \";\nif (is_admin()){\n echo \"

            Administrator Pages\";\n echo \"
            \n \n Admin Notes Search: \n
            \";\n}\necho \"
            \n \n
            \n
            \n\n
            \n
            \n\n
            \n\n \";\n\n\n}\n\n# -------------------------------------------------------------------------------\nfunction xhtml_web_footer(){\n echo \"\n\n
            \n\n \n \n\";\n}\n\n# -------------------------------------------------------------------------------\nfunction is_email_valid ($address)\n{\n\n\t# http://www.zend.com/codex.php?id=285&single=1\n\n return (preg_match(\n '/^[-!#$%&\\'*+\\\\.\\/0-9=?A-Z^_`{|}~]+'. // the user name\n '@'. // the ubiquitous at-sign\n '([-0-9A-Z]+\\.)+' . // host, sub-, and domain names\n '([0-9A-Z]){2,4}$/i', // top-level domain (TLD)\n trim($address)));\n}\n\n# -------------------------------------------------------------------------------\nfunction find_glossaryterms()\n{\n global $dbh;\n $query = \"SELECT id, term, definition FROM glossary\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n $glossaryterms = array();\n while ( $line = mysqli_fetch_array($result)) {\n $glossaryterms['ids'][$line['term']] = $line['id'];\n $glossaryterms['defs'][$line['id']] = $line['definition'];\n }\n return $glossaryterms;\n}\n\n# -------------------------------------------------------------------------------\nfunction show_glossary()\n{\n global $dbh;\n $query = \"SELECT id, term, definition FROM glossary ORDER BY term ASC\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n $results = array();\n while ( $line = mysqli_fetch_array($result)) {\n array_push($results,$line);\n }\n\n echo \"

            Glossary

            \\n\";\n\n echo \"

            \\n\";\n\n foreach ($results as $one)\n {\n echo \"\".$one['term'].\": \";\n echo $one['definition'];\n if (is_admin())\n {\n echo \" EDIT \";\n }\n echo \"

            \";\n }\n\n echo \"

            \\n\";\n\n}\n\n# -------------------------------------------------------------------------------\nfunction show_glossaryterm($id)\n{\n global $dbh;\n $query = \"SELECT id, term, definition FROM glossary WHERE id = $id\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n $results = array();\n while ( $line = mysqli_fetch_array($result)) {\n $glossaryterm = $line;\n }\n\n echo \"

            Full Glossary Listing

            \";\n\n echo \"

            Glossary

            \\n\";\n\n echo \"

            \\n\";\n\n echo \"\".$glossaryterm['term'].\": \";\n echo $glossaryterm['definition'];\n if (is_admin())\n {\n echo \" EDIT \";\n }\n echo \"

            \";\n\n echo \"

            \\n\";\n\n}\n\n# -------------------------------------------------------------------------------\nfunction show_alphabet()\n{\n\n $alphabet_letters = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n $alphabet = preg_split('//', $alphabet_letters, -1, PREG_SPLIT_NO_EMPTY);\n\n echo \"
            \\n\";\n echo \"

            Dissertation Authors and Mentors by Last Name

            \";\n echo \"

            \";\n foreach ($alphabet as $letter)\n {\n if ($letter != \"A\"){echo \" - \";}\n echo \"$letter\";\n }\n echo \"

            \";\n echo \"
            \\n\";\n}\n\n# -------------------------------------------------------------------------------\nfunction search_box($q=\"\")\n{\n echo \"
            \\n\";\n echo \"\\n\";\n echo \"

            People Search: \";\n if ($q)\n {\n echo \"\\n\";\n }\n else\n {\n echo \"\\n\";\n }\n echo \"

            \\n\";\n echo \"
            \\n\";\n}\n\n# -------------------------------------------------------------------------------\nfunction people_search($q)\n{\n global $dbh;\n $q = trim($q);\n if (!get_magic_quotes_gpc()) {$q = addslashes($q);}\n $results = array();\n if (strlen($q) < 2){\n return $results;\n }\n\n $pieces = explode(\" \",$q);\n# print_r($pieces);\n if (count($pieces) == 2)\n {\n# echo \" --------- two pieces\";\n $query = \"SELECT n.id as name_id, p.id as person_id\n FROM\n names n, people p\n WHERE\n (\n\n (n.firstname LIKE '%\".$pieces[0].\"%' OR\n n.middlename LIKE '%\".$pieces[0].\"%' OR\n n.lastname LIKE '%\".$pieces[0].\"%' OR\n n.suffix LIKE '%\".$pieces[0].\"%')\n\n AND\n\n (n.firstname LIKE '%\".$pieces[1].\"%' OR\n n.middlename LIKE '%\".$pieces[1].\"%' OR\n n.lastname LIKE '%\".$pieces[1].\"%' OR\n n.suffix LIKE '%\".$pieces[1].\"%')\n\n )\n AND\n n.person_id = p.id\n GROUP BY\n p.id\n ORDER BY\n n.lastname, n.suffix, n.firstname, n.middlename\n \";\n }\n elseif (count($pieces) == 3)\n {\n# echo \" --------- three pieces\";\n $query = \"SELECT n.id as name_id, p.id as person_id\n FROM\n names n, people p\n WHERE\n (\n\n (n.firstname LIKE '%\".$pieces[0].\"%' OR\n n.middlename LIKE '%\".$pieces[0].\"%' OR\n n.lastname LIKE '%\".$pieces[0].\"%' OR\n n.suffix LIKE '%\".$pieces[0].\"%')\n\n AND\n\n (n.firstname LIKE '%\".$pieces[1].\"%' OR\n n.middlename LIKE '%\".$pieces[1].\"%' OR\n n.lastname LIKE '%\".$pieces[1].\"%' OR\n n.suffix LIKE '%\".$pieces[1].\"%')\n\n AND\n\n (n.firstname LIKE '%\".$pieces[2].\"%' OR\n n.middlename LIKE '%\".$pieces[2].\"%' OR\n n.lastname LIKE '%\".$pieces[2].\"%' OR\n n.suffix LIKE '%\".$pieces[2].\"%')\n\n )\n AND\n n.person_id = p.id\n GROUP BY\n p.id\n ORDER BY\n n.lastname, n.suffix, n.firstname, n.middlename\n \";\n }\n else\n {\n# echo \" --- regular search - single piece\";\n $query = \"SELECT n.id as name_id, p.id as person_id\n FROM\n names n, people p\n WHERE\n (\n\n (n.firstname LIKE '%\".$q.\"%' OR\n n.middlename LIKE '%\".$q.\"%' OR\n n.lastname LIKE '%\".$q.\"%' OR\n n.suffix LIKE '%\".$q.\"%')\n\n )\n AND\n n.person_id = p.id\n GROUP BY\n p.id\n ORDER BY\n n.lastname, n.suffix, n.firstname, n.middlename\n \";\n }\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result)) {\n array_push($results,$line['person_id']);\n }\n return $results;\n}\n\n# -------------------------------------------------------------------------------\nfunction title_abstract_search($q)\n{\n global $dbh;\n $q = trim($q);\n if (!get_magic_quotes_gpc()) {$q = addslashes($q);}\n $results = array();\n if (strlen($q) < 2){\n return $results;\n }\n\n $pieces = explode(\" \",$q);\n# print_r($pieces);\n if (count($pieces) == 2)\n {\n# echo \" --------- two pieces\";\n $query = \"SELECT d.person_id\n FROM\n names n, dissertations d\n WHERE\n (\n\n (d.title LIKE '%\".$pieces[0].\"%' OR\n d.abstract LIKE '%\".$pieces[0].\"%')\n\n AND\n\n (d.title LIKE '%\".$pieces[1].\"%' OR\n d.abstract LIKE '%\".$pieces[1].\"%')\n\n )\n AND\n n.person_id = d.person_id\n GROUP BY\n d.id\n ORDER BY\n n.lastname, n.suffix, n.firstname, n.middlename\n \";\n }\n elseif (count($pieces) == 3)\n {\n# echo \" --------- three pieces\";\n $query = \"SELECT d.person_id\n FROM\n names n, dissertations d\n WHERE\n (\n\n (d.title LIKE '%\".$pieces[0].\"%' OR\n d.abstract LIKE '%\".$pieces[0].\"%')\n\n AND\n\n (d.title LIKE '%\".$pieces[1].\"%' OR\n d.abstract LIKE '%\".$pieces[1].\"%')\n\n AND\n\n (d.title LIKE '%\".$pieces[2].\"%' OR\n d.abstract LIKE '%\".$pieces[2].\"%')\n\n )\n AND\n n.person_id = d.person_id\n GROUP BY\n d.id\n ORDER BY\n n.lastname, n.suffix, n.firstname, n.middlename\n \";\n }\n else\n {\n# echo \" --- regular search - single piece\";\n $query = \"SELECT d.person_id\n FROM\n names n, dissertations d\n WHERE\n (\n\n (d.title LIKE '%\".$q.\"%' OR\n d.abstract LIKE '%\".$q.\"%')\n\n )\n AND\n n.person_id = d.person_id\n GROUP BY\n d.id\n ORDER BY\n n.lastname, n.suffix, n.firstname, n.middlename\n \";\n }\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result)) {\n array_push($results,$line['person_id']);\n }\n return $results;\n}\n\n# -------------------------------------------------------------------------------\nfunction notes_search($q)\n{\n global $dbh;\n $q = trim($q);\n if (!get_magic_quotes_gpc()) {$q = addslashes($q);}\n $results = array();\n if (strlen($q) < 2){\n return $results;\n }\n\n $pieces = explode(\" \",$q);\n# print_r($pieces);\n if (count($pieces) == 2)\n {\n# echo \" --------- two pieces\";\n $query = \"SELECT d.person_id\n FROM\n names n, dissertations d\n WHERE\n (\n\n (d.notes LIKE '%\".$pieces[0].\"%')\n\n AND\n\n (d.notes LIKE '%\".$pieces[1].\"%')\n\n )\n AND\n n.person_id = d.person_id\n GROUP BY\n d.id\n ORDER BY\n n.lastname, n.suffix, n.firstname, n.middlename\n \";\n }\n elseif (count($pieces) == 3)\n {\n# echo \" --------- three pieces\";\n $query = \"SELECT d.person_id\n FROM\n names n, dissertations d\n WHERE\n (\n\n (d.notes LIKE '%\".$pieces[0].\"%')\n\n AND\n\n (d.notes LIKE '%\".$pieces[1].\"%')\n\n AND\n\n (d.notes LIKE '%\".$pieces[2].\"%')\n\n )\n AND\n n.person_id = d.person_id\n GROUP BY\n d.id\n ORDER BY\n n.lastname, n.suffix, n.firstname, n.middlename\n \";\n }\n else\n {\n# echo \" --- regular search - single piece\";\n $query = \"SELECT d.person_id\n FROM\n names n, dissertations d\n WHERE\n (\n\n (d.notes LIKE '%\".$q.\"%')\n\n )\n AND\n n.person_id = d.person_id\n GROUP BY\n d.id\n ORDER BY\n n.lastname, n.suffix, n.firstname, n.middlename\n \";\n }\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result)) {\n array_push($results,$line['person_id']);\n }\n return $results;\n}\n\n# -------------------------------------------------------------------------------\nfunction encode_linebreaks($bigtext)\n{\n # from http://us3.php.net/str_replace\n $order = array(\"\\r\\n\", \"\\n\", \"\\r\");\n $replace = '
            ';\n // Processes \\r\\n's first so they aren't converted twice.\n $with_breaks = str_replace($order, $replace, $bigtext);\n return $with_breaks;\n}\n\n# -------------------------------------------------------------------------------\nfunction get_logs($offset=\"0\")\n{\n global $dbh;\n# echo \"[$offset]\";\n $query = \"SELECT * FROM logs ORDER BY id DESC LIMIT 100\";\n if ($offset != \"\"){$query .= \" OFFSET $offset\";}\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n# echo $query;\n $entries = array();\n $counter = 0;\n while ( $line = mysqli_fetch_array($result)) {\n $counter++;\n $entries[$counter] = $line;\n }\n return $entries;\n}\n\n\n# -------------------------------------------------------------------------------\nfunction get_dissertation_history($id)\n{\n global $dbh;\n $query = \"SELECT * FROM logs\n WHERE type='dissertation' AND message LIKE '$id %'\n ORDER BY id DESC\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n# echo $query;\n $entries = array();\n $counter = 0;\n while ( $line = mysqli_fetch_array($result)) {\n $counter++;\n $entries[$counter] = $line;\n }\n return $entries;\n}\n\n\n# -------------------------------------------------------------------------------\nfunction find_all_people()\n{\n global $dbh;\n # return array of all people_ids in database (slow....)\n # all people\n $query = \"SELECT id as person_id FROM people\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $people[] = $line['person_id'];\n }\n return $people;\n}\n\n# -------------------------------------------------------------------------------\nfunction get_person_link($person_id)\n{\n\n $disciplines = find_disciplines();\n $person = find_person($person_id);\n\n $fullname = trim($person['firstname'].\" \".$person['middlename'].\" \".$person['lastname'].\" \".$person['suffix']);\n\n $dissertation = find_dissertation_by_person($person_id);\n $discipline = isset($dissertation['discipline_id']) ? $disciplines[$dissertation['discipline_id']] : \"\";\n\n $link = \"\".$fullname.\"\";\n\n return $link;\n\n}\n\n# -------------------------------------------------------------------------------\nfunction find_orphans()\n{\n global $dbh;\n\n # finding people with no dissertation and no students\n\n # all people\n $query = \"SELECT\n p.id as person_id, n.firstname, n.middlename, n.lastname, n.suffix\n FROM\n people p, names n\n WHERE\n p.preferred_name_id = n.id\n ORDER BY n.lastname,n.firstname,n.middlename\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result)) {\n $people[$line['person_id']] = $line;\n# echo \" \".$line['person_id'].\"
            \\n\";\n }\n\n echo \"people: \".count($people).\"
            \\n\";\n\n # with dissertations only\n $query = \"SELECT\n p.id as person_id\n FROM\n people p, dissertations d\n WHERE\n d.person_id = p.id\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result)) {\n $with_dissertations[$line['person_id']] = $line;\n# echo \" \".$line['person_id'].\"
            \\n\";\n }\n\n echo \"dissertations: \".count($with_dissertations).\"
            \\n\";\n\n # all people - dissertations = teachers only\n $potentialmentors = array_key_diff($people,$with_dissertations);\n\n echo \"potential mentors: \".count($potentialmentors).\"
            \\n\";\n\n # orphans = teachers who don't have students\n # get advisorships\n $query = \"SELECT person_id FROM advisorships\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $advisors[$line['person_id']] = $line;\n }\n echo \"advisors: \".count($advisors).\"
            \\n\";\n # get committeeships\n $query = \"SELECT person_id FROM committeeships\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n $committeemembers[$line['person_id']] = $line;\n }\n echo \"committeemembers: \".count($committeemembers).\"
            \\n\";\n # subtract advisorships from teachers\n $potentialmentors = array_key_diff($potentialmentors,$advisors);\n # subtract committeeships from remaining teachers\n $orphans = array_key_diff($potentialmentors,$committeemembers);\n echo \"orphans: \".count($orphans).\"
            \\n\";\n\n return $orphans;\n\n}\n\n# -------------------------------------------------------------------------------\nfunction is_orphan($person_id)\n{\n global $dbh;\n # confirm person exists\n $query = \"SELECT * FROM people WHERE id = '\".$person_id.\"'\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n $line = mysqli_fetch_array($result);\n if (!$line['id']){echo \"not a person\";return 0;}\n # confirm no dissertation\n $query = \"SELECT * FROM dissertations WHERE person_id = '\".$person_id.\"'\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n echo \"found a dissertation\";\n return 0;\n }\n # confirm not a committeemember\n $query = \"SELECT * FROM committeeships WHERE person_id = '\".$person_id.\"'\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n echo \"found a committeeship\";\n return 0;\n }\n # confirm not an advisor\n $query = \"SELECT * FROM advisorships WHERE person_id = '\".$person_id.\"'\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n echo \"found an advisorship\";\n return 0;\n }\n return 1;\n}\n# -------------------------------------------------------------------------------\nfunction delete_person($person_id)\n{\n global $dbh;\n if (is_orphan($person_id))\n {\n $before = find_person($person_id);\n # delete all names\n $query = \"DELETE FROM names WHERE person_id = '\".$person_id.\"'\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n # delete the person\n $query = \"DELETE FROM people WHERE id = '\".$person_id.\"' LIMIT 1\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n # log it\n mpact_logger(\"deleted person[\".$person_id.\"] (\".$before['fullname'].\")\");\n return 1;\n }\n else\n {\n action_box(\"Not an orphan - Cannot delete this person.\");\n return 0;\n }\n}\n# -------------------------------------------------------------------------------\nfunction remove_duplicate_names($person_id)\n{\n global $dbh;\n\n $names = array();\n $deleteme = array();\n\n\n $before = find_person($person_id);\n\n // get the preferred_name_id\n $query = \"SELECT preferred_name_id\n FROM people\n WHERE id = '\".$person_id.\"'\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result)) {\n extract($line);\n }\n\n // get the full preferred_name\n $query = \"SELECT * FROM names\n WHERE\n id = '\".$preferred_name_id.\"'\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result)) {\n $fullname = \"\".$line['firstname'].\" \".$line['middlename'].\" \".$line['lastname'].\" \".$line['suffix'].\"\";\n $names[$fullname] = $line['id'];\n }\n\n // get the rest of the names for this person\n $query = \"SELECT * FROM names\n WHERE\n person_id = '\".$person_id.\"' AND\n id != '\".$preferred_name_id.\"'\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result)) {\n $fullname = \"\".$line['firstname'].\" \".$line['middlename'].\" \".$line['lastname'].\" \".$line['suffix'].\"\";\n if (isset($names[$fullname]))\n {\n $deleteme[] = $line['id'];\n }\n else\n {\n $names[$fullname] = $line['id'];\n }\n }\n\n // delete each deleteme id\n foreach ($deleteme as $one)\n {\n $query = \"DELETE FROM names\n WHERE\n id = '\".$one.\"'\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n }\n\n # log it\n mpact_logger(\"removed duplicate names for person[\".$person_id.\"] (\".$before['fullname'].\")\");\n\n}\n\n# -------------------------------------------------------------------------------\nfunction add_mentor($type,$student_id,$mentor_id)\n{\n global $dbh;\n $student = find_person($student_id);\n $mentor = find_person($mentor_id);\n $dissertation = find_dissertation_by_person($student_id);\n\n if ($type == \"A\")\n {\n # find existing advisors for this student\n $advisors = find_advisors_for_person($student_id);\n # if new/different - then add them to the student's dissertation\n if (in_array($mentor_id,$advisors))\n {\n # skip - already listed as advisor\n }\n else\n {\n $query = \"INSERT advisorships\n SET\n dissertation_id = '\".$dissertation['id'].\"',\n person_id = '\".$mentor_id.\"'\n \";\n# echo $query;\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n # recalculate scores for both\n calculate_scores($student_id);\n calculate_scores($mentor_id);\n # log it\n mpact_logger(\"add advisorship between mentor[\".$mentor_id.\"] (\".$mentor['fullname'].\") to dissertation[\".$dissertation['id'].\"] (\".$student['fullname'].\")\");\n # delete existing dotgraphs - they'll need to be regenerated\n # has to happen after we add the advisor link itself\n delete_associated_dotgraphs($student_id);\n }\n }\n elseif ($type == \"C\")\n {\n # find existing committee members for this student\n $committee = find_committee_for_person($student_id);\n # if new/different - then add them to the student's dissertation\n if (in_array($mentor_id,$committee))\n {\n # skip - already on committee\n }\n else\n {\n $query = \"INSERT committeeships\n SET\n dissertation_id = '\".$dissertation['id'].\"',\n person_id = '\".$mentor_id.\"'\n \";\n# echo $query;\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n # recalculate scores for both\n calculate_scores($student_id);\n calculate_scores($mentor_id);\n # log it\n mpact_logger(\"add committeeship between mentor[\".$mentor_id.\"] (\".$mentor['fullname'].\") to dissertation[\".$dissertation['id'].\"] (\".$student['fullname'].\")\");\n }\n }\n else\n {\n # nothing\n }\n}\n\n# -------------------------------------------------------------------------------\nfunction remove_mentor($type,$student_id,$mentor_id)\n{\n global $dbh;\n $dissertation = find_dissertation_by_person($student_id);\n\n $student = find_person($student_id);\n $mentor = find_person($mentor_id);\n\n if ($type == \"A\")\n {\n # find dissertation id\n $dissertation = find_dissertation_by_person($student_id);\n # find existing advisors for this student\n $advisors = find_advisors_for_person($student_id);\n # if found in db, remove them\n if (!in_array($mentor_id,$advisors))\n {\n echo \"not an advisor for this student\";\n return 0;\n }\n else\n {\n # delete existing dotgraphs - they'll need to be regenerated\n # has to happen before we delete the advisor link itself\n delete_associated_dotgraphs($student_id);\n # delete the advisorship\n $query = \"DELETE FROM advisorships\n WHERE\n person_id = '\".$mentor_id.\"' AND\n dissertation_id = '\".$dissertation['id'].\"'\n LIMIT 1\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n # recalculate scores for both\n calculate_scores($student_id);\n calculate_scores($mentor_id);\n # log it\n mpact_logger(\"remove advisorship between mentor[\".$mentor_id.\"] (\".$mentor['fullname'].\") to dissertation[\".$dissertation['id'].\"] (\".$student['fullname'].\")\");\n return 1;\n }\n }\n elseif ($type == \"C\")\n {\n # find dissertation id\n $dissertation = find_dissertation_by_person($student_id);\n # find existing committee members for this student\n $committee = find_committee_for_person($student_id);\n # if found in db, remove them\n if (!in_array($mentor_id,$committee))\n {\n echo \"not on committee for this student\";\n return 0;\n }\n else\n {\n $query = \"DELETE FROM committeeships\n WHERE\n person_id = '\".$mentor_id.\"' AND\n dissertation_id = '\".$dissertation['id'].\"'\n LIMIT 1\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n # recalculate scores for both\n calculate_scores($student_id);\n calculate_scores($mentor_id);\n # log it\n mpact_logger(\"remove advisorship between mentor[\".$mentor_id.\"] (\".$mentor['fullname'].\") to dissertation[\".$dissertation['id'].\"] (\".$student['fullname'].\")\");\n return 1;\n }\n }\n else\n {\n echo \"has to be A or C, dude\";\n return 0;\n }\n\n}\n\n# -------------------------------------------------------------------------------\nfunction find_all_people_for_selectbox($with_dissertation=\"0\")\n{\n global $dbh;\n if ($with_dissertation == \"0\")\n {\n $query = \"SELECT\n p.id as person_id, n.firstname, n.middlename, n.lastname, n.suffix\n FROM\n people p, names n\n WHERE\n p.preferred_name_id = n.id\n ORDER BY n.lastname,n.firstname,n.middlename\n \";\n }\n else\n {\n $query = \"SELECT\n p.id as person_id, n.firstname, n.middlename, n.lastname, n.suffix\n FROM\n people p, names n, dissertations d\n WHERE\n p.preferred_name_id = n.id AND\n d.person_id = p.id\n ORDER BY n.lastname,n.firstname,n.middlename\n \";\n }\n // echo $query;\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result)) {\n $people[$line['person_id']] = $line;\n }\n\n return $people;\n}\n\n# -------------------------------------------------------------------------------\nfunction merge_two_people($from_id, $into_id)\n{\n global $dbh;\n\n $from_person = find_person($from_id);\n $into_person = find_person($into_id);\n\n\n $query = \"UPDATE advisorships\n SET\n person_id = '\".$into_person['id'].\"'\n WHERE\n person_id = '\".$from_person['id'].\"'\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n $query = \"UPDATE dissertations\n SET\n person_id = '\".$into_person['id'].\"'\n WHERE\n person_id = '\".$from_person['id'].\"'\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n $query = \"UPDATE committeeships\n SET\n person_id = '\".$into_person['id'].\"'\n WHERE\n person_id = '\".$from_person['id'].\"'\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n $query = \"UPDATE urls\n SET\n person_id = '\".$into_person['id'].\"'\n WHERE\n person_id = '\".$from_person['id'].\"'\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n // move each 'from' name to the 'into' person\n\n $query = \"UPDATE names\n SET\n person_id = '\".$into_person['id'].\"'\n WHERE\n person_id = '\".$from_person['id'].\"'\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n // remove any new duplicates in the names table\n\n remove_duplicate_names($into_person['id']);\n\n // remove 'from' person from the database\n\n $query = \"DELETE FROM people\n WHERE\n id = '\".$from_person['id'].\"'\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n # log it\n mpact_logger(\"merged two people [\".$from_id.\"] (\".$from_person['fullname'].\") and [\".$into_id.\"] (\".$into_person['fullname'].\")\");\n\n\n}\n\n# -------------------------------------------------------------------------------\nfunction find_aliases($person_id)\n{\n global $dbh;\n\n $query = \"SELECT preferred_name_id\n FROM people\n WHERE id = '\".$person_id.\"'\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result)) {\n extract($line);\n }\n\n $names = array();\n $query = \"SELECT\n n.firstname, n.middlename,\n n.lastname, n.suffix, n.id\n FROM\n names n\n WHERE\n n.person_id = '\".$person_id.\"'\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result)) {\n $names[$line['id']] = $line;\n }\n\n unset($names[$preferred_name_id]);\n\n return $names;\n}\n\n# -------------------------------------------------------------------------------\nfunction find_person($person_id)\n{\n global $dbh;\n $query = \"SELECT\n n.firstname, n.middlename,\n n.lastname, n.suffix, p.degree,\n p.id, p.preferred_name_id\n FROM\n names n, people p\n WHERE\n p.preferred_name_id = n.id AND\n p.id = \".$person_id.\"\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result)) {\n $person = $line;\n $person['fullname'] = $person['firstname'];\n if ($person['middlename'] != \"\"){$person['fullname'] .= \" \".$person['middlename'];}\n if ($person['lastname'] != \"\"){$person['fullname'] .= \" \".$person['lastname'];}\n if ($person['suffix'] != \"\"){$person['fullname'] .= \" \".$person['suffix'];}\n }\n\n return $person;\n}\n\n# -------------------------------------------------------------------------------\nfunction find_url($url_id)\n{\n global $dbh;\n\n $url_id = intval($url_id);\n $query = \"SELECT\n u.id, u.url, u.description, u.updated_at, u.person_id\n FROM\n urls u\n WHERE\n u.id = '\".$url_id.\"'\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result)) {\n $url = $line;\n }\n\n return $url;\n\n}\n\n# -------------------------------------------------------------------------------\nfunction find_urls_by_person($person_id)\n{\n global $dbh;\n\n $person_id = intval($person_id);\n $query = \"SELECT\n u.id, u.url, u.description, u.updated_at, u.person_id\n FROM\n urls u\n WHERE\n u.person_id = '\".$person_id.\"'\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n $urls = array();\n while ( $line = mysqli_fetch_array($result)) {\n $urls[$line['id']] = $line;\n }\n\n return $urls;\n\n}\n\n# -------------------------------------------------------------------------------\nfunction find_dissertation($dissertation_id)\n{\n global $dbh;\n\n $dissertation_id = intval($dissertation_id);\n $query = \"SELECT\n d.id, d.person_id, d.completedyear, d.status,\n d.title, d.abstract, d.notes, d.school_id, d.discipline_id\n FROM\n dissertations d\n WHERE\n d.id = '\".$dissertation_id.\"'\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n $dissertation = array();\n while ( $line = mysqli_fetch_array($result)) {\n $dissertation = $line;\n }\n\n return $dissertation;\n}\n\n# -------------------------------------------------------------------------------\nfunction find_dissertation_by_person($person_id)\n{\n global $dbh;\n\n $person_id = intval($person_id);\n $query = \"SELECT\n d.id, d.person_id, d.completedyear, d.status,\n d.title, d.abstract, d.notes, d.school_id, d.discipline_id\n FROM\n dissertations d\n WHERE\n d.person_id = '\".$person_id.\"'\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n $dissertation = array();\n while ( $line = mysqli_fetch_array($result)) {\n $dissertation = $line;\n }\n\n return $dissertation;\n}\n\n# -------------------------------------------------------------------------------\nfunction find_name($name_id)\n{\n global $dbh;\n $query = \"SELECT\n n.firstname, n.middlename,\n n.lastname, n.suffix\n FROM\n names n\n WHERE\n n.id = \".$name_id.\"\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result)) {\n $name = $line;\n $name['fullname'] = $name['firstname'];\n if ($name['middlename'] != \"\"){$name['fullname'] .= \" \".$name['middlename'];}\n if ($name['lastname'] != \"\"){$name['fullname'] .= \" \".$name['lastname'];}\n if ($name['suffix'] != \"\"){$name['fullname'] .= \" \".$name['suffix'];}\n }\n\n return $name;\n}\n\n# -------------------------------------------------------------------------------\nfunction find_discipline($discipline_id)\n{\n global $dbh;\n $discipline_id = intval($discipline_id);\n $query = \"SELECT\n d.title, d.description\n FROM\n disciplines d\n WHERE\n d.id = \".$discipline_id.\"\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result)) {\n $discipline = $line;\n }\n\n return $discipline;\n}\n\n# -------------------------------------------------------------------------------\nfunction find_ancestors_for_group($groupofpeople)\n{\n $originalgroup = $groupofpeople;\n // find advisors, and if they're new, add them to the list and recurse\n foreach ($originalgroup as $person)\n {\n $advisors = find_advisors_for_person($person);\n foreach ($advisors as $one)\n {\n $groupofpeople[] = $one;\n }\n }\n $groupofpeople = array_unique($groupofpeople);\n if (count(array_diff($groupofpeople,$originalgroup)) > 0)\n {\n return find_ancestors_for_group($groupofpeople);\n }\n else\n {\n return $originalgroup;\n }\n}\n\n# -------------------------------------------------------------------------------\nfunction find_descendents_for_group($groupofpeople)\n{\n $originalgroup = $groupofpeople;\n // find descendents, and if they're new, add them to the list and recurse\n foreach ($originalgroup as $person)\n {\n $advisees = find_advisorships_under_person($person);\n foreach ($advisees as $one)\n {\n $groupofpeople[] = $one;\n }\n }\n $groupofpeople = array_unique($groupofpeople);\n if (count(array_diff($groupofpeople,$originalgroup)) > 0)\n {\n return find_descendents_for_group($groupofpeople);\n }\n else\n {\n return $originalgroup;\n }\n}\n\n# -------------------------------------------------------------------------------\nfunction T_score($person)\n{\n # total number of descendants (nodes) in a person's tree\n $group = array($person);\n $total = count(find_descendents_for_group($group)); # including self\n $descendents = $total - 1; # minus self\n return $descendents;\n}\n\n# -------------------------------------------------------------------------------\nfunction find_mpact_score($person,$score_type)\n{\n global $dbh;\n $query = \"SELECT $score_type as score FROM people WHERE id='$person'\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n extract($line);\n }\n return $score;\n}\n\n# -------------------------------------------------------------------------------\nfunction FMI_score($person)\n{\n $FMI_score = count(find_advisorships_under_person($person));\n# print \"person $person -- fmi $FMI_score
            \";\n $committeeships = find_committeeships_under_person($person);\n foreach ($committeeships as $one)\n {\n $numA = count(find_advisors_for_person($one));\n# echo \" - #A [$numA] ----
            \";\n $numC = count(find_committee_for_person($one));\n# echo \"#C [$numC] ---- \\n\";\n $FMI_score += 1/($numA + $numC);\n# echo \"
            \";\n }\n // echo \"fractional mentorship, inclusive (FMI = A + eachC(1/(#A+#C)) )
            \\n\";\n return round($FMI_score,3);\n}\n\n# -------------------------------------------------------------------------------\nfunction FME_score($person)\n{\n $FME_score = count(find_advisorships_under_person($person));\n# print \"person $person -- fme $FME_score
            \";\n $committeeships = find_committeeships_under_person($person);\n foreach ($committeeships as $one)\n {\n $numC = count(find_committee_for_person($one));\n# echo \"#C [$numC] ---- \\n\";\n $FME_score += 1/($numC);\n# echo \"
            \";\n }\n // echo \"fractional mentorship, inclusive (FMI = A + eachC(1/(#A+#C)) )
            \\n\";\n return round($FME_score,3);\n}\n\n# -------------------------------------------------------------------------------\nfunction TA_score($person)\n{\n # total number of descendants who have advised students themselves\n $without_students = array();\n $descendents = find_descendents_for_group(array($person)); # including self\n foreach ($descendents as $d)\n {\n if (count(find_descendents_for_group(array($d))) == 1)\n {\n $without_students[] = $d;\n }\n }\n $descendents_who_advised = array_diff($descendents,$without_students); # including self\n return max(count($descendents_who_advised) - 1,0); # minus self\n}\n\n# -------------------------------------------------------------------------------\nfunction W_score($person)\n{\n # should handle multigenerational advisorships correctly...\n\n # return the max of the widths of each generation of descendents\n $descendents = array_diff(find_descendents_for_group(array($person)),array($person)); # without self # 16\n $gencount = 1;\n $advisees = find_advisorships_under_person($person); #5\n $gen_widths[$gencount] = count($advisees);\n $remaining = array_diff($descendents,$advisees); # 11\n# print \"$gencount <-- gen
            \";\n# print count($advisees).\" advisees - \";\n# print_r($advisees);\n# print \"
            \";\n# print \"
            \";\n# print count($remaining).\" remaining - \";\n# print_r($remaining);\n# print \"
            \";\n# print \"
            \";\n while (count($remaining) > 0)\n {\n $gencount++;\n# print \"$gencount <-- gen
            \";\n $advisees = advisees_of_group($advisees);\n $gen_widths[$gencount] = count($advisees);\n $remaining = array_diff($remaining,$advisees);\n# print count($advisees).\" advisees - \";\n# print_r($advisees);\n# print \"
            \";\n# print \"
            \";\n# print count($remaining).\" remaining - \";\n# print_r($remaining);\n# print \"
            \";\n# print \"
            \";\n }\n# print_r($gen_widths);\n return max($gen_widths);\n}\n\n# -------------------------------------------------------------------------------\nfunction TD_score($person)\n{\n # there is currently a bug in this implementation\n # if a student has two advisors, and they, themselves are related by mentorship\n # this algorithm currently counts gen_width based on advisee count only\n # since $td is calculated based on gen_width values, TD will be missing data\n # A is advisor to B and C\n # B is advisor to C\n # A should have a TD score of 2 (full credit for both advisees)\n # upon further reflection, perhaps this is working correctly, by accident\n\n # return the decayed score\n $descendents = array_diff(find_descendents_for_group(array($person)),array($person)); # without self # 16\n $gencount = 1;\n $advisees = find_advisorships_under_person($person); #5\n $gen_widths[$gencount] = count($advisees);\n $remaining = array_diff($descendents,$advisees); # 11\n while (count($remaining) > 0)\n {\n $gencount++;\n $advisees = advisees_of_group($advisees);\n $gen_widths[$gencount] = count($advisees);\n $remaining = array_diff($remaining,$advisees);\n }\n# print_r($gen_widths);\n $td = 0;\n foreach($gen_widths as $one => $two)\n {\n $num = $two;\n $den = (pow(2,($one-1)));\n $f = $num/$den;\n# print \"$num/$den = $f
            \";\n $td = $td + $f;\n }\n return $td;\n}\n\n# -------------------------------------------------------------------------------\nfunction G_score($person)\n{\n # there is currently a bug in this implementation\n # if a student has two advisors, and they, themselves are related by mentorship\n # this algorithm currently misses a generation in the calculation of G\n # A is advisor to B and C\n # B is advisor to C\n # A should have a G score of 2, but will only be calculated a 1\n\n\n # return the number of generations of descendents\n $descendents = array_diff(find_descendents_for_group(array($person)),array($person)); # without self # 16\n $gencount = 1;\n $advisees = find_advisorships_under_person($person); #5\n $gen_widths[$gencount] = count($advisees);\n $remaining = array_diff($descendents,$advisees); # 11\n while (count($remaining) > 0)\n {\n $gencount++;\n $advisees = advisees_of_group($advisees);\n $gen_widths[$gencount] = count($advisees);\n $remaining = array_diff($remaining,$advisees);\n }\n if ($gen_widths[1] == 0)\n {\n return 0;\n }\n else\n {\n return count($gen_widths);\n }\n}\n\n# -------------------------------------------------------------------------------\nfunction advisees_of_group($group)\n{\n # W helper function\n $advisees = array();\n foreach ($group as $one)\n {\n $advisees[] = find_advisorships_under_person($one);\n }\n $advisees = flattenArray($advisees);\n# print_r($advisees);\n# print \" <-- advisees of group
            \";\n return $advisees;\n}\n\n# -------------------------------------------------------------------------------\nfunction flattenArray($array)\n{\n $flatArray = array();\n foreach( $array as $subElement ) {\n if( is_array($subElement) )\n $flatArray = array_merge($flatArray, flattenArray($subElement));\n else\n $flatArray[] = $subElement;\n }\n return $flatArray;\n}\n\n# -------------------------------------------------------------------------------\nfunction calculate_scores($person_id)\n{\n global $dbh;\n $A_score = count(find_advisorships_under_person($person_id));\n $C_score = count(find_committeeships_under_person($person_id));\n $AC_score = $A_score + $C_score;\n $G_score = G_score($person_id);\n $W_score = W_score($person_id);\n $T_score = T_score($person_id);\n $TA_score = TA_score($person_id);\n $TD_score = TD_score($person_id);\n $FMI_score = FMI_score($person_id);\n $FME_score = FME_score($person_id);\n\n $query = \"UPDATE people\n SET\n a_score = '$A_score',\n c_score = '$C_score',\n ac_score = '$AC_score',\n g_score = '$G_score',\n w_score = '$W_score',\n t_score = '$T_score',\n ta_score = '$TA_score',\n td_score = '$TD_score',\n fmi_score = '$FMI_score',\n fme_score = '$FME_score',\n scores_calculated = now()\n WHERE\n id = \".$person_id.\"\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n}\n\n# -------------------------------------------------------------------------------\nfunction mpact_scores($passed_person)\n{\n global $dbh;\n $glossaryterms = find_glossaryterms();\n\n $query = \"SELECT\n a_score, c_score, ac_score, g_score, w_score,\n t_score, ta_score, td_score, fmi_score, fme_score,\n scores_calculated\n FROM people\n WHERE id = \".$passed_person.\"\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result)) {\n extract($line);\n }\n\n $mpact['A'] = $a_score;\n $mpact['C'] = $c_score;\n $mpact['AC'] = $ac_score;\n $scores_output = \"A = $a_score
            \\n\";\n $scores_output .= \"C = $c_score
            \\n\";\n $scores_output .= \"A+C = $ac_score
            \\n\";\n\n $mpact['FMI'] = $fmi_score;\n $mpact['FME'] = $fme_score;\n $FMIdivFULL = ($ac_score>0) ? $fmi_score / $ac_score : 0;\n $FMIdivFULL = round($FMIdivFULL,3);\n $mpact['FMIdivFULL'] = $FMIdivFULL;\n $FMEdivFULL = ($ac_score>0) ? $fme_score / $ac_score : 0;\n $FMEdivFULL = round($FMEdivFULL,3);\n $mpact['FMEdivFULL'] = $FMEdivFULL;\n if (is_admin())\n {\n $scores_output .= \"FMI = $fmi_score
            \\n\";\n $scores_output .= \"FME = $fme_score
            \\n\";\n $scores_output .= \"FMI/(A+C) = $FMIdivFULL
            \\n\";\n $scores_output .= \"FME/(A+C) = $FMEdivFULL
            \\n\";\n }\n\n $mpact['T'] = $t_score;\n $scores_output .= \"T = $t_score
            \\n\";\n $mpact['G'] = $g_score;\n $scores_output .= \"G = $g_score
            \\n\";\n $mpact['W'] = $w_score;\n $scores_output .= \"W = $w_score
            \\n\";\n $mpact['TD'] = $td_score;\n $scores_output .= \"D']].\"\\\">TD = $td_score
            \\n\";\n $mpact['TA'] = $ta_score;\n $scores_output .= \"A']].\"\\\">TA = $ta_score
            \\n\";\n $scores_output .= \"calculated $scores_calculated
            \\n\";\n $mpact['output'] = $scores_output;\n\n return $mpact;\n}\n\n# -------------------------------------------------------------------------------\nfunction find_advisors_for_person($person_id)\n{\n global $dbh;\n\n // get person's own advisor(s)\n\n $listing = array();\n\n\n $query = \"SELECT a.person_id\n FROM\n dissertations d,\n advisorships a\n WHERE\n d.person_id = \".$person_id.\" AND\n a.dissertation_id = d.id\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result))\n {\n $listing[] = $line['person_id'];\n }\n\n return $listing;\n}\n\n# -------------------------------------------------------------------------------\nfunction find_committee_for_person($person_id)\n{\n global $dbh;\n\n // get person's own committee member(s)\n\n $listing = array();\n\n $query = \"SELECT c.person_id\n FROM\n dissertations d,\n committeeships c\n WHERE\n d.person_id = \".$person_id.\" AND\n c.dissertation_id = d.id\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result))\n {\n $listing[] = $line['person_id'];\n }\n\n return $listing;\n}\n\n# -------------------------------------------------------------------------------\nfunction find_advisorships_under_person($person_id)\n{\n global $dbh;\n\n // get person's advisorships (below)\n\n $listing = array();\n\n $query = \"SELECT d.person_id\n FROM\n dissertations d,\n advisorships a\n WHERE\n a.person_id = \".$person_id.\" AND\n a.dissertation_id = d.id\n ORDER BY\n d.completedyear ASC\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result))\n {\n $listing[] = $line['person_id'];\n }\n\n return $listing;\n}\n\n# -------------------------------------------------------------------------------\nfunction find_committeeships_under_person($person_id)\n{\n global $dbh;\n\n // get person's committeeships (below)\n\n $listing = array();\n\n $query = \"SELECT d.person_id\n FROM\n dissertations d,\n committeeships c\n WHERE\n c.person_id = '\".$person_id.\"' AND\n c.dissertation_id = d.id\n ORDER BY\n d.completedyear\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result))\n {\n $listing[] = $line['person_id'];\n }\n\n return $listing;\n}\n\n# -------------------------------------------------------------------------------\nfunction set_preferred_name($person_id,$name_id)\n{\n global $dbh;\n\n # delete current family tree of dotgraphs\n delete_associated_dotgraphs($person_id);\n\n # set it\n\n $listing = array();\n\n $before = find_person($person_id);\n\n $query = \"UPDATE people\n SET\n preferred_name_id = '\".$name_id.\"'\n WHERE\n id = '\".$person_id.\"'\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n $after = find_person($person_id);\n\n # log it\n mpact_logger(\"set preferred name for person[\".$person_id.\"] from name[\".$before['preferred_name_id'].\"] (\".$before['fullname'].\") to name[\".$name_id.\"] (\".$after['fullname'].\")\");\n}\n\n# -------------------------------------------------------------------------------\nfunction generate_profs_at_dept($school_id,$discipline_id)\n{\n global $dbh;\n\n $dissertations = array();\n $listing = array();\n $advisors = array();\n $committeemembers = array();\n\n // get all dissertations at this dept\n\n $query = \"SELECT d.id\n FROM dissertations d, schools s\n WHERE\n d.school_id = s.id AND\n s.id = '\".$school_id.\"' AND\n d.discipline_id = '\".$discipline_id.\"'\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result))\n {\n $dissertations[] = $line['id'];\n }\n\n if (count($dissertations)>0)\n {\n // get all advisors for these dissertations\n\n $query = \"SELECT a.person_id\n FROM dissertations d, advisorships a\n WHERE\n a.dissertation_id IN (\";\n $query .= implode(\", \", $dissertations);\n $query .= \") AND\n a.dissertation_id = d.id\";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result))\n {\n $advisors[$line['person_id']] = $line['person_id'];\n }\n\n // get all committeemembers for these dissertations\n\n $query = \"SELECT c.person_id\n FROM dissertations d, committeeships c\n WHERE\n c.dissertation_id IN (\";\n $query .= implode(\", \", $dissertations);\n $query .= \") AND\n c.dissertation_id = d.id\";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result))\n {\n $committeemembers[$line['person_id']] = $line['person_id'];\n }\n }\n\n // return the combined list (uniquified when combined)\n\n// echo \"\\na - \".count($advisors);\n// echo \"\\nc - \".count($committeemembers);\n $listing = $advisors + $committeemembers;\n// echo \"\\ncombined before - \".count($listing);\n return $listing;\n\n}\n\n# -------------------------------------------------------------------------------\nfunction find_profs_at_dept($school_id,$discipline_id)\n{\n global $dbh;\n $query = \"SELECT professors\n FROM profs_at_dept\n WHERE\n school_id = '$school_id' AND\n discipline_id = '$discipline_id'\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result))\n {\n $listing = unserialize($line['professors']);\n }\n return $listing;\n\n}\n\n# -------------------------------------------------------------------------------\nfunction find_disciplines($school_id=null)\n{\n global $dbh;\n\n $disciplines = array();\n if ($school_id)\n {\n // get all disciplines at this school\n $query = \"SELECT d.id, d.title\n FROM\n disciplines d, schools s, dissertations diss\n WHERE\n diss.school_id = s.id AND\n diss.discipline_id = d.id AND\n s.id = '$school_id'\n ORDER BY\n d.title\n \";\n }\n else\n {\n $query = \"SELECT id, title\n FROM\n disciplines d\n ORDER BY\n title\n \";\n }\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result))\n {\n $disciplines[$line['id']] = $line['title'];\n }\n\n if (isset($disciplines))\n {\n return $disciplines;\n }\n}\n\n# -------------------------------------------------------------------------------\nfunction is_duplicate_discipline($title)\n{\n global $dbh;\n $disciplinefound = 0;\n\n $query = \"SELECT id FROM disciplines WHERE title = '$title'\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result))\n {\n $disciplinefound = $line['id'];\n }\n\n if ($disciplinefound > 0){\n return true;\n }\n\n return false;\n}\n\n# -------------------------------------------------------------------------------\nfunction is_empty_discipline($discipline_id)\n{\n global $dbh;\n $query = \"SELECT count(*) as howmany FROM dissertations WHERE discipline_id = $discipline_id\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result))\n {\n extract($line);\n }\n\n if ($howmany > 0){\n return false;\n }\n\n return true;\n}\n\n# -------------------------------------------------------------------------------\nfunction is_duplicate_school($fullname)\n{\n global $dbh;\n $schoolfound = 0;\n\n $query = \"SELECT id FROM schools WHERE fullname = '$fullname'\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result))\n {\n $schoolfound = $line['id'];\n }\n\n if ($schoolfound > 0){\n return true;\n }\n\n return false;\n}\n\n# -------------------------------------------------------------------------------\nfunction is_empty_school($school_id)\n{\n global $dbh;\n $query = \"SELECT count(*) as howmany FROM dissertations WHERE school_id = $school_id\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result))\n {\n extract($line);\n }\n\n if ($howmany > 0){\n return false;\n }\n\n return true;\n}\n\n# -------------------------------------------------------------------------------\nfunction find_discipline_counts()\n{\n global $dbh;\n\n // get all discipline counts from the database\n\n $disciplinecounts = array();\n\n $query = \"SELECT discipline_id, count(*) as disciplinecount\n FROM dissertations\n GROUP BY discipline_id\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result))\n {\n $disciplinecounts[$line['discipline_id']] = $line['disciplinecount'];\n }\n\n if (isset($disciplinecounts))\n {\n return $disciplinecounts;\n }\n}\n\n# -------------------------------------------------------------------------------\nfunction find_discipline_statuses($discipline_id)\n{\n global $dbh;\n\n // get status counts for this discipline\n\n GLOBAL $statuscodes;\n\n $statuscounts = array();\n\n $query = \"SELECT status, count(*) as disciplinecount\n FROM dissertations\n WHERE discipline_id='$discipline_id'\n GROUP BY status\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result))\n {\n $statuscounts[$line['status']] = $line['disciplinecount'];\n }\n\n foreach (range(0,4) as $one)\n {\n if (!isset($statuscounts[$one]))\n {\n $statuscounts[$one] = 0;\n }\n }\n return $statuscounts;\n}\n\n# -------------------------------------------------------------------------------\nfunction find_dept_counts($school_id,$discipline_id)\n{\n global $dbh;\n\n // get all department counts from the database\n\n $deptcounts = array();\n\n $query = \"SELECT discipline_id, count(*) as disciplinecount\n FROM dissertations\n GROUP BY discipline_id\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result))\n {\n $deptcounts[$line['discipline_id']] = $line['disciplinecount'];\n }\n\n if (isset($deptcounts))\n {\n return $deptcounts;\n }\n}\n\n# -------------------------------------------------------------------------------\nfunction find_dept_statuses($school_id,$discipline_id)\n{\n global $dbh;\n\n // get status counts for this school in this discipline\n\n GLOBAL $statuscodes;\n\n $statuscounts = array();\n\n $query = \"SELECT status, count(*) as disciplinecount\n FROM dissertations\n WHERE\n discipline_id='$discipline_id' AND\n school_id='$school_id'\n GROUP BY status\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result))\n {\n $statuscounts[$line['status']] = $line['disciplinecount'];\n }\n\n foreach (range(0,4) as $one)\n {\n if (!isset($statuscounts[$one]))\n {\n $statuscounts[$one] = 0;\n }\n }\n return $statuscounts;\n}\n\n# -------------------------------------------------------------------------------\nfunction find_schools($discipline_id=null)\n{\n global $dbh;\n // get all schools in a discipline (or all disciplines)\n $schools = array();\n if ($discipline_id)\n {\n // look up schools at dissertations in this discipline\n $query = \"SELECT s.id, s.fullname\n FROM\n dissertations d, schools s\n WHERE\n d.school_id = s.id AND\n d.discipline_id = '$discipline_id'\n GROUP BY\n d.school_id\n ORDER BY\n s.fullname ASC\n \";\n }\n else\n {\n $query = \"SELECT id, fullname\n FROM\n schools s\n ORDER BY fullname\n \";\n }\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n while ( $line = mysqli_fetch_array($result))\n {\n $schools[$line['id']] = $line['fullname'];\n }\n\n if (isset($schools))\n {\n return $schools;\n }\n}\n\n# -------------------------------------------------------------------------------\nfunction find_school_counts()\n{\n global $dbh;\n\n // get all school dissertation counts from the database\n\n $schoolcounts = array();\n\n $query = \"SELECT school_id, count(*) as disscount\n FROM dissertations\n GROUP BY school_id\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result))\n {\n $schoolcounts[$line['school_id']] = $line['disscount'];\n }\n\n if (isset($schoolcounts))\n {\n return $schoolcounts;\n }\n}\n\n# -------------------------------------------------------------------------------\nfunction find_school_statuses($school_id)\n{\n global $dbh;\n\n // get status counts for this school\n\n GLOBAL $statuscodes;\n\n $statuscounts = array();\n\n $query = \"SELECT status, count(*) as disscount\n FROM dissertations\n WHERE school_id='$school_id'\n GROUP BY status\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result))\n {\n $statuscounts[$line['status']] = $line['disscount'];\n }\n\n foreach (range(0,4) as $one)\n {\n if (!isset($statuscounts[$one]))\n {\n $statuscounts[$one] = 0;\n }\n }\n return $statuscounts;\n}\n\n\n# -------------------------------------------------------------------------------\nfunction find_persons_school($passed_person)\n{\n global $dbh;\n\n // get person's degree school\n\n $query = \"SELECT\n d.id as dissertation_id,\n d.completedyear,\n d.title,\n d.abstract,\n s.fullname,\n s.country,\n s.id as schoolid\n FROM\n dissertations d,\n schools s\n WHERE\n d.person_id = \".$passed_person.\" AND\n d.school_id = s.id\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result)) {\n $thisperson['dissertation_id'] = $line['dissertation_id'];\n $thisperson['completedyear'] = $line['completedyear'];\n $thisperson['title'] = $line['title'];\n $thisperson['abstract'] = $line['abstract'];\n $thisperson['country'] = $line['country'];\n $thisperson['school'] = $line['fullname'];\n $thisperson['schoolid'] = $line['schoolid'];\n }\n\n if (isset($thisperson))\n {\n return $thisperson;\n }\n}\n\n# -------------------------------------------------------------------------------\nfunction find_school($school_id)\n{\n global $dbh;\n\n // get school\n\n $query = \"SELECT\n s.fullname,\n s.country\n FROM\n schools s\n WHERE\n s.id = \".$school_id.\"\n \";\n\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result)) {\n $school['country'] = $line['country'];\n $school['fullname'] = $line['fullname'];\n }\n\n if (isset($school))\n {\n return $school;\n }\n}\n\n# -------------------------------------------------------------------------------\nfunction get_environment_info()\n{\n $host_info = array();\n $hostname = $_SERVER['SERVER_NAME'];\n if ($hostname == \"\"){$hostname = exec(hostname);}\n# echo \"hostname = [$hostname]
            \";\n if ($hostname == \"www.ibiblio.org\" || $hostname == \"www-dev.ibiblio.org\" || $hostname == \"login1.ibiblio.org\")\n {\n # the main install on ibiblio\n $host_info['hostname'] = \"ibiblio\";\n $host_info['ownername'] = \"mpact\";\n $host_info['dotlocation'] = \"/export/sunsite/users/mpact/terrelllocal/bin/dot\";\n $host_info['appdir'] = \"/public/html/mpact\";\n $host_info['webdir'] = \"http://www.ibiblio.org/mpact\";\n $host_info['dotcachedir'] = \"dotgraphs\";\n $host_info['dotfiletype'] = \"png\";\n $host_info['dotfontface'] = \"Times-Roman\";\n }\n else if ($hostname == \"trel.dyndns.org\")\n {\n # my local development machine\n $host_info['hostname'] = \"home\";\n $host_info['ownername'] = \"trel\";\n $host_info['dotlocation'] = \"/sw/bin/dot\";\n $host_info['appdir'] = \"/Library/WebServer/Documents/MPACTlocal/app\";\n $host_info['webdir'] = \"http://trel.dyndns.org:9000/mpactlocal/app\";\n $host_info['dotcachedir'] = \"dotgraphs\";\n $host_info['dotfiletype'] = \"png\";\n $host_info['dotfontface'] = \"cour\";\n }\n else if ($hostname == \"localhost.com\" || $hostname == \"trelpancake\")\n {\n # my laptop\n $host_info['hostname'] = \"laptop\";\n $host_info['ownername'] = \"trel\";\n $host_info['dotlocation'] = \"/opt/local/bin/dot\";\n $host_info['appdir'] = \"/Users/trel/Sites/MPACT\";\n $host_info['webdir'] = \"http://localhost.com/~trel/MPACT\";\n $host_info['dotcachedir'] = \"dotgraphs\";\n $host_info['dotfiletype'] = \"png\";\n $host_info['dotfontface'] = \"cour\";\n }\n else\n {\n # unknown host\n #exit;\n }\n\n return $host_info;\n}\n\n# -------------------------------------------------------------------------------\nfunction delete_associated_dotgraphs($passed_person)\n{\n $host_info = get_environment_info();\n $group = array($passed_person);\n $ancestors = find_ancestors_for_group($group);\n $descendents = find_descendents_for_group($group);\n $entire_family_tree = array_unique($ancestors + $descendents);\n foreach ($entire_family_tree as $one)\n {\n # set the filenames\n $dotfilename = $host_info['appdir'].\"/\".$host_info['dotcachedir'].\"/$one.dot\";\n $imagefilename = $host_info['appdir'].\"/\".$host_info['dotcachedir'].\"/$one.\".$host_info['dotfiletype'];\n $imagemapfilename = $host_info['appdir'].\"/\".$host_info['dotcachedir'].\"/$one.map\";\n # delete each if they exist\n if (file_exists($dotfilename))\n {\n `rm $dotfilename`;\n }\n if (file_exists($imagefilename))\n {\n `rm $imagefilename`;\n }\n if (file_exists($imagemapfilename))\n {\n `rm $imagemapfilename`;\n }\n # mark as 'dirty' so cronjob can recreate images\n mark_record_as_dirty($one);\n }\n}\n\n# -------------------------------------------------------------------------------\nfunction mark_record_as_dirty($passed_person)\n{\n global $dbh;\n # mark database record for this person as dirty\n # a cronjob will pick these up and regenerate their dotgraphs\n # gets around permission issues on the server if necessary\n $query = \"UPDATE people SET regenerate_dotgraph = '1' WHERE id = '\".$passed_person.\"'\";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n}\n\n# -------------------------------------------------------------------------------\nfunction narray_slice($array, $offset, $length) {\n # http://us3.php.net/manual/en/function.array-slice.php#73882\n\n //Check if this version already supports it\n if (str_replace('.', '', PHP_VERSION) >= 502)\n return array_slice($array, $offset, $length, true);\n\n foreach ($array as $key => $value) {\n\n if ($a >= $offset && $a - $offset <= $length)\n $output_array[$key] = $value;\n $a++;\n\n }\n return $output_array;\n}\n\n# -------------------------------------------------------------------------------\nfunction generate_dotfile($passed_person){\n $a = find_person($passed_person);\n if ($a == null)\n {\n return 0;\n }\n else\n {\n $dotfilecontents = \"\";\n $dotfilecontents .= \"digraph familytree\\n\";\n $dotfilecontents .= \"{\\n\";\n $dotfilecontents .= \"rankdir=\\\"LR\\\"\\n\";\n $dotfilecontents .= \"node [fontname = Times, fontsize=10, shape = rect, height=.15]\\n\";\n # ancestors\n $upgroup = array();\n $upgroup[] = $passed_person;\n $ancestors = find_ancestors_for_group($upgroup);\n foreach ($ancestors as $one)\n {\n $person = find_person($one);\n $dotfilecontents .= \"$one [label = \\\"\".$person['fullname'].\"\\\" URL=\\\"mpact.php?op=show_tree&id=\".$one.\"\\\"];\\n\";\n $advisors = find_advisors_for_person($one);\n foreach ($advisors as $adv)\n {\n $dotfilecontents .= \"$adv -> $one;\\n\";\n }\n }\n # descendents\n $downgroup = array();\n $downgroup[] = $passed_person;\n $descendents = find_descendents_for_group($downgroup);\n foreach ($descendents as $one)\n {\n $person = find_person($one);\n $dotfilecontents .= \"$one [label = \\\"\".$person['fullname'].\"\\\" URL=\\\"mpact.php?op=show_tree&id=\".$one.\"\\\"\";\n if ($one == $passed_person){\n $dotfilecontents .= \" color=\\\"red\\\" style=\\\"filled\\\" fillcolor=\\\"grey\\\"\";\n }\n $dotfilecontents .= \"];\\n\";\n $advisees = find_advisorships_under_person($one);\n foreach ($advisees as $adv)\n {\n $dotfilecontents .= \"$one -> $adv;\\n\";\n }\n }\n $dotfilecontents .= \"}\\n\";\n\n return $dotfilecontents;\n }\n}\n\n# -------------------------------------------------------------------------------\nfunction draw_tree_dotgraph($passed_person)\n{\n $person = $passed_person;\n $host_info = get_environment_info();\n if (isset($host_info['appdir']))\n {\n $webfilename = generate_dotgraph($person);\n if ($webfilename == \"marked_as_dirty\"){\n echo \"generating graph, please reload\";\n }\n else{\n echo \"\\\"Directed
            \";\n }\n }\n else\n {\n echo \"graphics libraries are not configured\";\n }\n}\n\n# -------------------------------------------------------------------------------\nfunction generate_dotgraph($passed_person, $forcenew=\"no\")\n{\n $person = $passed_person;\n $host_info = get_environment_info();\n# print_r($host_info);\n $appcache = $host_info['appdir'].\"/\".$host_info['dotcachedir'];\n $webcache = $host_info['webdir'].\"/\".$host_info['dotcachedir'];\n $appfilename = \"$appcache/$person.\".$host_info['dotfiletype'];\n# echo \"appfilename = $appfilename
            \\n\";\n $dotfilename = \"$appcache/$person.dot\";\n# echo \"dotfilename = $dotfilename
            \\n\";\n $webfilename = \"$webcache/$person.\".$host_info['dotfiletype'];\n# echo \"webfilename = $webfilename
            \\n\";\n $appimagemap = \"$appcache/$person.map\";\n# echo \"appimagemap = $appimagemap
            \\n\";\n\n if (!file_exists($appfilename)) {\n # assumption is that the cachedir exists... (run setupmpact.sh)\n # generate dotfile\n if (!file_exists($dotfilename) or $forcenew == \"force\") {\n# print \" - creating dotfile...\\n\";\n $dotfilecontents = generate_dotfile($person);\n $fh = fopen($dotfilename, 'w');\n fwrite($fh, $dotfilecontents);\n fclose($fh);\n exec(\"chmod 666 $dotfilename\");\n }\n # generate graph\n $getandgenerategraph = \"/bin/cat $dotfilename | \".$host_info['dotlocation'].\" -Nfontname=\".$host_info['dotfontface'].\" -Gcharset=latin1 -Tcmapx -o$appimagemap -T\".$host_info['dotfiletype'].\" -o$appfilename 2>&1\";\n# echo \"getandgenerategraph = $getandgenerategraph
            \";\n exec($getandgenerategraph);\n exec(\"chmod 666 $appimagemap\");\n exec(\"chmod 666 $appfilename\");\n if (!file_exists($appfilename)) {\n # mark as dirty if it didn't work\n mark_record_as_dirty($person);\n return \"marked_as_dirty\";\n }\n }\n else\n {\n# echo \"SHOWING CACHED COPY
            \";\n }\n\n return $webfilename;\n}\n\n# -------------------------------------------------------------------------------\nfunction draw_graph($passed_person)\n{\n if (!$passed_person){action_box(\"No ID given.\");}\n\n $person = $passed_person;\n $host_info = get_environment_info();\n if (isset($host_info['appdir']))\n {\n $appcache = $host_info['appdir'].\"/\".$host_info['dotcachedir'];\n $webcache = $host_info['webdir'].\"/\".$host_info['dotcachedir'];\n $appfilename = \"$appcache/$person.\".$host_info['dotfiletype'];\n #echo \"appfilename = $appfilename
            \";\n $webfilename = \"$webcache/$person.\".$host_info['dotfiletype'];\n #echo \"webfilename = $webfilename
            \";\n $appimagemap = \"$appcache/$person.map\";\n #echo \"appimagemap = $appimagemap
            \";\n\n\n echo \"\";\n echo file_get_contents($appimagemap);\n }\n else\n {\n echo \"graphics libraries are not configured\";\n }\n}\n\n# -------------------------------------------------------------------------------\nfunction draw_tree($passed_person)\n{\n global $dbh;\n GLOBAL $statuscodes;\n GLOBAL $inspectioncodes;\n\n // shows a person\n\n if (!$passed_person){action_box(\"No ID given.\");}\n else\n {\n $personcount = 0;\n $thisperson = array();\n $dissertation = array();\n\n // get person's preferred name\n\n $query = \"SELECT\n n.firstname, n.middlename,\n n.lastname, n.suffix, p.degree\n FROM\n names n, people p\n WHERE\n p.preferred_name_id = n.id AND\n p.id = '\".$passed_person.\"'\n \";\n $result = mysqli_query($dbh, $query) or die(mysqli_error($dbh));\n\n while ( $line = mysqli_fetch_array($result)) {\n $thisperson['firstname'] = $line['firstname'];\n $thisperson['middlename'] = $line['middlename'];\n $thisperson['lastname'] = $line['lastname'];\n $thisperson['suffix'] = $line['suffix'];\n $thisperson['degree'] = $line['degree'];\n $personcount++;\n }\n\n $schoolinfo = find_persons_school($passed_person);\n $thisperson['dissertation_id'] = $schoolinfo['dissertation_id'];\n $thisperson['completedyear'] = $schoolinfo['completedyear'];\n $thisperson['country'] = $schoolinfo['country'];\n $thisperson['school'] = $schoolinfo['school'];\n $thisperson['schoolid'] = $schoolinfo['schoolid'];\n\n if ($thisperson['dissertation_id'] == \"\")\n {\n $thisperson['status'] = \"\";\n $thisperson['notes'] = \"\";\n $thisperson['title'] = \"N/A\";\n $thisperson['abstract'] = \"N/A\";\n $thisperson['abstract_html'] = \"N/A\";\n }\n else\n {\n $dissertation = find_dissertation($thisperson['dissertation_id']);\n $thisperson['status'] = $dissertation['status'];\n $thisperson['notes'] = $dissertation['notes'];\n $thisperson['discipline_id'] = $dissertation['discipline_id'];\n $thisperson['title'] = $dissertation['title'];\n $thisperson['abstract'] = $dissertation['abstract'];\n $thisperson['abstract_html'] = encode_linebreaks($dissertation['abstract']);\n if ($thisperson['title'] == \"\") { $thisperson['title'] = \"N/A\";}\n if ($thisperson['abstract'] == \"\")\n {\n $thisperson['abstract'] = \"N/A\";\n $thisperson['abstract_html'] = \"N/A\";\n }\n }\n\n $thisperson['advisors'] = find_advisors_for_person($passed_person);\n $thisperson['cmembers'] = find_committee_for_person($passed_person);\n $thisperson['advisorships'] = find_advisorships_under_person($passed_person);\n $thisperson['committeeships'] = find_committeeships_under_person($passed_person);\n\n\n if ($personcount < 1)\n {\n action_box(\"Person \".$passed_person.\" Not Found\");\n }\n else\n {\n\n echo \"
            \\n\";\n\n # Name / Aliases\n $count = 0;\n $printme = \"\";\n $fullname = $thisperson['firstname'].\" \".$thisperson['middlename'].\" \".$thisperson['lastname'].\" \".$thisperson['suffix'];\n $printme .= \"

            Dissertation Information for $fullname

            \";\n $printme .= \"

            \";\n if (is_admin())\n {\n if (isset($thisperson['completedyear']))\n {\n $printme .= \" (Edit)\";\n }\n else\n {\n $printme .= \" (Create Dissertation for $fullname)\";\n }\n $printme .= \"
            \\n\";\n }\n $printme .= \"

            \";\n $printme .= \"

            \";\n $printme .= \"NAME: \";\n if (is_admin())\n {\n $printme .= \"(Add)\";\n }\n $printme .= \"
            \";\n $printme .= \" - \";\n $printme .= get_person_link($passed_person);\n if (is_admin())\n {\n $printme .= \" (Edit)\";\n }\n $printme .= \"
            \\n\";\n\n $aliases = 0;\n foreach (find_aliases($passed_person) as $one)\n {\n $printme .= \" - (Alias) \";\n $printme .= $one['firstname'].\" \";\n $printme .= $one['middlename'].\" \";\n $printme .= $one['lastname'].\" \";\n $printme .= $one['suffix'].\" \";\n if (is_admin())\n {\n $printme .= \"(Set as Primary)\";\n $printme .= \" (Delete)\";\n }\n $printme .= \"
            \";\n $aliases++;\n }\n $printme .= \"

            \";\n echo $printme;\n\n # Degree\n $printme = \"

            \\n\";\n $printme .= \"DEGREE:
            \\n\";\n $printme .= \" - \".$thisperson['degree'];\n if (is_admin())\n {\n $printme .= \" (Edit)\";\n }\n $printme .= \"

            \";\n echo $printme;\n\n # Discipline\n $printme = \"

            \\n\";\n $printme .= \"DISCIPLINE:
            \\n\";\n if (isset($thisperson['discipline_id']))\n {\n $discipline = find_discipline($thisperson['discipline_id']);\n $printme .= \" - \".$discipline['title'].\"\";\n if (is_admin())\n {\n $printme .= \" (Edit)\";\n }\n }\n else\n {\n $printme .= \" - None\";\n if (is_admin())\n {\n $printme .= \" (Create Dissertation for $fullname)\";\n }\n }\n $printme .= \"

            \";\n echo $printme;\n\n # School\n $printme = \"

            \\n\";\n $printme .= \"SCHOOL:
            \\n\";\n if (isset($thisperson['completedyear']))\n {\n $printme .= \" - \".$thisperson['school'].\" (\".$thisperson['country'].\") (\".$thisperson['completedyear'].\")\";\n if (is_admin())\n {\n $printme .= \" (Edit)\";\n }\n }\n else\n {\n $printme .= \" - None\";\n if (is_admin())\n {\n $printme .= \" (Create Dissertation for $fullname)\";\n }\n }\n $printme .= \"

            \\n\";\n echo $printme;\n\n\n # Advisors\n $count = 0;\n $printme = \"\";\n $printme .= \"

            \";\n $printme .= \"ADVISORS: \";\n if (is_admin() && isset($thisperson['completedyear']))\n {\n $printme .= \" (Add)\";\n }\n $printme .= \"
            \";\n if (isset($thisperson['advisors'])){\n foreach ($thisperson['advisors'] as $one)\n {\n $printme .= \" - \";\n $printme .= get_person_link($one);\n if (is_admin())\n {\n $printme .= \" (Remove)\";\n }\n $printme .= \"
            \";\n $count++;\n }\n }\n if ($count < 1){$printme .= \" - None\";}\n $printme .= \"

            \";\n echo $printme;\n\n # Committee Members\n $count = 0;\n $printme = \"\";\n $printme .= \"

            \";\n $printme .= \"COMMITTEE MEMBERS: \";\n if (is_admin() && isset($thisperson['completedyear']))\n {\n $printme .= \" (Add)\";\n }\n $printme .= \"
            \";\n if (isset($thisperson['cmembers'])){\n foreach ($thisperson['cmembers'] as $one)\n {\n $printme .= \" - \";\n $printme .= get_person_link($one);\n if (is_admin())\n {\n $printme .= \" (Remove)\";\n }\n $printme .= \"
            \";\n $count++;\n }\n }\n if ($count < 1){$printme .= \" - None\";}\n $printme .= \"

            \\n\\n\";\n\n # Admin Notes\n if (is_admin())\n {\n if ($thisperson['notes'] != \"\")\n {\n $printme .= \"

            \";\n $printme .= \"\\n\";\n $printme .= \"\\n\";\n $printme .= \"
            \\n\";\n $printme .= \"Admin Notes: \".$thisperson['notes'].\"
            \\n\";\n $printme .= \"
            \\n\";\n $printme .= \"

            \\n\\n\";\n }\n }\n\n $glossaryterms = find_glossaryterms();\n # Status and Inspection\n $printme .= \"

            \";\n $printme .= \"MPACT Status: \".$statuscodes[$thisperson['status']].\"
            \\n\";\n $printme .= \"

            \\n\\n\";\n\n # Title and Abstract\n $printme .= \"

            \";\n $printme .= \"Title: \".$thisperson['title'].\"
            \";\n $printme .= \"

            \\n\";\n $printme .= \"

            \";\n $printme .= \"Abstract: \".$thisperson['abstract_html'].\"
            \";\n $printme .= \"

            \\n\\n\";\n\n # print it all out...\n echo $printme;\n\n # URLS\n\n if (is_admin())\n {\n $urls = find_urls_by_person($passed_person);\n echo \"

            \\n\";\n echo \"REFERENCE URLS\";\n echo \" (Add)\";\n echo \"
            \\n\";\n if (count($urls) > 0)\n {\n echo \"\\n\";\n }\n else\n {\n echo \" - None\\n\";\n }\n foreach ($urls as $one)\n {\n echo \"\\n\";\n echo \"\\n\";\n echo \"\\n\";\n }\n if (count($urls) > 0)\n {\n echo \"
            Updated: \".$one['updated_at'].\"\";\n echo \" (Edit)\";\n echo \" (Delete)\";\n echo \"
            \".$one['url'].\"
            \".$one['description'].\"
            \\n\";\n }\n echo \"

            \\n\";\n }\n\n # EDIT HISTORY\n\n if (is_admin())\n {\n $entries = get_dissertation_history($thisperson['dissertation_id']);\n if (count($entries) > 0)\n {\n echo \"

            \\n\";\n echo \"EDIT HISTORY (Show/Hide)\\n\";\n echo \"\";\n echo \"\\n\";\n }\n\n foreach ($entries as $one)\n {\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\\n\";\n }\n if (count($entries) > 0)\n {\n echo \"
            \".$one['logged_at'].\"\".$one['user'].\"\".$one['message'].\"
            \\n\";\n echo \"

            \\n\";\n }\n }\n\n\n\n echo \"
            \\n\";\n\n # MPACT Scores\n $printme = \"\";\n $printme .= \"

            MPACT Scores for $fullname

            \";\n $printme .= \"

            \";\n $mpact = mpact_scores($passed_person);\n $printme .= $mpact['output'];\n $printme .= \"

            \\n\";\n if (is_admin())\n {\n $printme .= \"

            (Recalculate)

            \";\n }\n echo $printme;\n\n # Draw FamilyTree Graph for this person\n echo \"

            Advisors and Advisees Graph

            \\n\";\n echo \"

            \";\n draw_tree_dotgraph($passed_person);\n echo \"

            \";\n\n echo \"
            \\n\";\n\n\n # Students\n echo \"

            Students under $fullname

            \\n\\n\";\n\n # Advisees\n $count = 0;\n $printme = \"\";\n $printme .= \"

            \";\n $printme .= \"ADVISEES: \";\n if (is_admin())\n {\n $printme .= \" (Add)\";\n }\n $printme .= \"
            \";\n if (isset($thisperson['advisorships'])){\n foreach ($thisperson['advisorships'] as $one)\n {\n $printme .= \" - \";\n $printme .= get_person_link($one);\n $schoolinfo = find_persons_school($one);\n if (isset($schoolinfo['completedyear']))\n {\n $printme .= \" - \".$schoolinfo['school'].\" (\".$schoolinfo['completedyear'].\")\";\n }\n if (is_admin())\n {\n $printme .= \" (Remove)\";\n }\n $printme .= \"
            \";\n $count++;\n }\n }\n if ($count < 1){$printme .= \" - None\";}\n $printme .= \"

            \\n\";\n echo $printme;\n\n # Committeeships\n $ccount = 0;\n $printme = \"\";\n $printme .= \"

            \";\n $printme .= \"COMMITTEESHIPS: \";\n if (is_admin())\n {\n $printme .= \" (Add)\";\n }\n $printme .= \"
            \";\n if (isset($thisperson['committeeships'])){\n foreach ($thisperson['committeeships'] as $one)\n {\n $printme .= \" - \";\n $printme .= get_person_link($one);\n $schoolinfo = find_persons_school($one);\n if (isset($schoolinfo['completedyear']))\n {\n $printme .= \" - \".$schoolinfo['school'].\" (\".$schoolinfo['completedyear'].\")\";\n }\n if (is_admin())\n {\n $printme .= \" (Remove)\";\n }\n $printme .= \"
            \";\n $count++;\n }\n }\n if ($count < 1){$printme .= \" - None\";}\n $printme .= \"

            \";\n echo $printme;\n\n }\n\n }\n\n\n}\n\n\n?>\n"}} +{"repo": "trac-hacks/trac-dashboard", "pr_number": 2, "title": "Unpack one-element tuple correctly", "state": "closed", "merged_at": "2016-08-27T20:14:18Z", "additions": 2, "deletions": 2, "files_changed": ["dashboard/dashboard.py"], "files_before": {"dashboard/dashboard.py": "from trac.core import *\nfrom pkg_resources import resource_filename\nfrom trac.config import Option, IntOption, ListOption, BoolOption\nfrom trac.web.api import IRequestHandler, Href\nfrom trac.util.translation import _\nfrom trac.web.chrome import add_stylesheet, add_script, INavigationContributor, ITemplateProvider\nfrom trac.web.chrome import Chrome\nfrom trac.util.datefmt import utc, to_timestamp\nfrom genshi.template import TemplateLoader\nfrom genshi.filters.transform import Transformer\nfrom trac.web.api import ITemplateStreamFilter\nfrom trac.perm import IPermissionRequestor\nfrom trac.util import escape, Markup\n\nimport time\nfrom datetime import datetime, timedelta\n\n\n\n\nclass DashBoard(Component):\n implements(IRequestHandler, ITemplateProvider, IPermissionRequestor, INavigationContributor)\n \n permission = Option('dashboard', 'permission', '')\n default_milestone = Option('dashboard', 'default_milestone', '')\n\n def __init__(self):\n self.db = self.env.get_db_cnx()\n self.username = None\n self.backDate = 30\n self.ticket_closed = ['checkedin', 'closed']\n\n self.ticket_closed_sql = \"','\".join(self.ticket_closed)\n\n self.milestone = self.default_milestone\n \n if self.permission:\n self.perm = self.permission\n else:\n self.perm = 'DASHBOARD_VIEW'\n\n self.env.log.debug(\"Using Permission: %s\" % self.permission)\n\n \n # INavigationContributor methods\n def get_active_navigation_item(self, req):\n return 'dashboard'\n\n def get_navigation_items(self, req):\n if self.perm in req.perm or 'TRAC_ADMIN' in req.perm:\n yield 'mainnav', 'dashboard', Markup('Dashboard' % (\n self.env.href.dashboard() ) )\n\n\n\n def get_permission_actions(self):\n yield self.perm\n\n \n # IRequestHandler methods\n def match_request(self, req):\n serve = False\n self.env.log.debug(\"Match Request\")\n\n\n uri = req.path_info.lstrip('/').split('/')\n if uri[0] == 'dashboard':\n serve = True\n\n self.env.log.debug(\"Handle Request: %s\" % serve)\n self.baseURL = req.href('dashboard', '/')\n self.baseQueryURL = req.href('query', '/')\n self.username = req.authname\n if 'milestone' in req.args:\n self.milestone = req.args.get('milestone')\n else:\n self.milestone = self.default_milestone\n\n if self.milestone == '':\n cursor = self.db.cursor()\n sql = \"select name from milestone where (completed = 0) limit 0, 1\"\n cursor.execute(sql)\n for name in cursor:\n self.milestone = name\n\n if 'dev' in req.args:\n self.username = req.args.get('dev')\n else:\n self.username = req.authname\n\n return serve\n\n if not self.perm in req.perm:\n self.env.log.debug(\"NO Permission to view\")\n return False\n\n return serve\n \n def get_updated_tickets(self):\n cursor = self.db.cursor()\n sql = \"select id, component, summary, status from ticket where (owner = '%s') and (changetime >= %s) and (status not in ('%s', 'new')) order by changetime desc\" % (self.username, self.stamp, self.ticket_closed_sql)\n cursor.execute(sql)\n out = []\n idx = 0\n for id, component, summary, status in cursor:\n data = {\n '__idx__': idx,\n 'id': id,\n 'component': component,\n 'summary': summary,\n 'status': status\n }\n idx = idx + 1\n out.append(data)\n return out\n\n def get_new_tickets(self):\n cursor = self.db.cursor()\n sql = \"select id, status, component, summary, changetime, priority from ticket where (owner = '%s') and (status in ('new', 'assigned')) and (type = 'defect') order by changetime desc\" % self.username\n cursor.execute(sql)\n out = []\n idx = 0\n for id, status, component, summary, changetime, priority in cursor:\n data = {\n '__idx__': idx,\n 'id': id,\n 'status': status,\n 'component': component,\n 'summary': summary,\n 'priority': priority,\n 'changetime': datetime.fromtimestamp(changetime, utc)\n }\n idx = idx + 1\n out.append(data)\n return out\n\n def get_closed_tickets(self):\n cursor = self.db.cursor()\n sql = \"select id, component, summary, changetime, status from ticket where (owner = '%s') and (status in ('%s')) and (changetime >= %s) order by component, status, changetime desc\" % (self.username, self.ticket_closed_sql, self.stamp)\n cursor.execute(sql)\n out = []\n idx = 0\n for id, component, summary, changetime, status in cursor:\n data = {\n '__idx__': idx,\n 'id': id,\n 'component': component,\n 'summary': summary,\n 'status': status,\n 'changetime': datetime.fromtimestamp(changetime, utc)\n }\n idx = idx + 1\n out.append(data)\n return out\n\n def get_milestone_tickets(self):\n cursor = self.db.cursor()\n sql = \"select id, component, summary, status, priority from ticket where (owner = '%s') and (status not in ('%s', 'new')) and (type in ('defect', 'enhancement')) and (milestone = '%s') order by component, priority\" % (self.username, self.ticket_closed_sql, self.milestone)\n cursor.execute(sql)\n out = []\n idx = 0\n for id, component, summary, status, priority in cursor:\n data = {\n '__idx__': idx,\n 'id': id,\n 'component': component,\n 'summary': summary,\n 'status': status,\n 'priority': priority\n }\n idx = idx + 1\n out.append(data)\n return out\n\n def get_todo_tickets(self):\n cursor = self.db.cursor()\n sql = \"select id, component, summary, status from ticket where (owner = '%s') and (status not in ('%s')) and (type = 'task') order by changetime desc\" % (self.username, self.ticket_closed_sql)\n cursor.execute(sql)\n out = []\n idx = 0\n for id, component, summary, status in cursor:\n data = {\n '__idx__': idx,\n 'id': id,\n 'component': component,\n 'summary': summary,\n 'status': status\n }\n idx = idx + 1\n out.append(data)\n return out\n\n def get_ticket_counts(self):\n cursor = self.db.cursor()\n sql = \"select count(*) as total, type, status from ticket where (owner = '%s') and (status not in ('%s')) group by type, status order by total desc\" % (self.username, self.ticket_closed_sql)\n cursor.execute(sql)\n out = []\n idx = 0\n for total, type, status in cursor:\n data = {\n '__idx__': idx,\n 'total': total,\n 'status': status,\n 'type': type\n }\n idx = idx + 1\n out.append(data)\n\n return out\n\n def get_action_counts(self):\n cursor = self.db.cursor()\n #sql = \"select count(*) as total, concat(oldvalue, ' => ', newvalue) as status from ticket_change where (author = '%s') and (time > %s) and (field = 'status') group by status order by total desc\" % (self.username, self.stamp)\n sql = \"select count(*) as total, (%s) as status from ticket_change where (author = '%s') and (time > %s) and (field = 'status') group by status order by total desc\" % (self.db.concat('oldvalue', \"' => '\", 'newvalue'), self.username, self.stamp)\n cursor.execute(sql)\n \n out = []\n idx = 0\n for total, status in cursor:\n data = {\n '__idx__': idx,\n 'total': total,\n 'status': status\n }\n idx = idx + 1\n out.append(data)\n\n return out\n\n\n def get_milestone_data(self):\n cursor = self.db.cursor()\n out = {\n 'total': 0,\n 'closed': 0,\n 'closed_percent': 0,\n 'new': 0,\n 'new_percent': 0,\n 'inprogress': 0,\n 'inprogress_percent': 0,\n 'name': self.milestone\n }\n #sql = \"select count(*) as total, ticket.status from ticket, ticket_custom where (ticket.milestone = '%s') and (ticket.owner = '%s') and (ticket.id = ticket_custom.ticket) and (ticket_custom.name = 'location') and (ticket_custom.value = 'Library Code')\" % (self.milestone, self.username)\n sql = \"select count(*) as total, status from ticket where (milestone = '%s') and (owner = '%s') and (type = 'defect') group by status\" % (self.milestone, self.username)\n cursor.execute(sql)\n\n for total, status in cursor:\n out['total'] = out['total'] + total\n\n if status in self.ticket_closed:\n out['closed'] = out['closed'] + total\n elif status == 'new':\n out['new'] = out['new'] + total\n else:\n out['inprogress'] = out['inprogress'] + total\n\n if out['closed'] > 0:\n out['closed_percent'] = int(round((float(out['closed']) / out['total']), 3) * 100)\n\n if out['new'] > 0:\n out['new_percent'] = int(round((float(out['new']) / out['total']), 1) * 100)\n\n if out['inprogress'] > 0:\n out['inprogress_percent'] = int(round((float(out['inprogress']) / out['total']), 3) * 100)\n\n\n return out\n\n def get_milestones(self):\n cursor = self.db.cursor()\n sql = \"select name from milestone where (name not in ('%s')) and (completed = 0)\" % self.milestone\n cursor.execute(sql)\n data = []\n for name in cursor:\n data.append(name)\n\n return data\n\n def get_users(self):\n devs = self.env.get_known_users()\n odevs = []\n for username,name,email in devs:\n if username != self.username:\n data = {\n 'username': username,\n 'name': name or username\n }\n odevs.append(data)\n return odevs\n\n\n def process_request(self, req):\n data = {}\n self.stamp = time.time() - (60 * 60 * 24 * self.backDate)\n today = datetime.now(req.tz)\n\n\n data['backDate'] = self.backDate\n data['stamp'] = self.stamp\n data['username'] = self.username\n data['milestone'] = self.milestone\n\n #Updated Tickets \n data['updated_tickets'] = self.get_updated_tickets()\n data['has_updated_tickets'] = len(data['updated_tickets'])\n\n #New Tickets\n data['new_tickets'] = self.get_new_tickets()\n data['has_new_tickets'] = len(data['new_tickets'])\n\n #Closed Tickets\n data['closed_tickets'] = self.get_closed_tickets()\n data['has_closed_tickets'] = len(data['closed_tickets'])\n\n #Ticket Counts\n data['ticket_counts'] = self.get_ticket_counts()\n data['has_ticket_counts'] = len(data['ticket_counts'])\n\n #Action Counts\n data['action_counts'] = self.get_action_counts()\n data['has_action_counts'] = len(data['action_counts'])\n\n #TODO Lists\n data['todo_tickets'] = self.get_todo_tickets()\n data['has_todo_tickets'] = len(data['todo_tickets'])\n\n #Milestones\n data['milestone_data'] = self.get_milestone_data()\n data['has_milestones'] = len(data['milestone_data'])\n\n #Milestone Tickets\n data['milestone_tickets'] = self.get_milestone_tickets()\n data['has_milestone_tickets'] = len(data['milestone_tickets'])\n\n #Milestones\n data['milestones'] = self.get_milestones()\n\n #Users\n data['users'] = self.get_users()\n\n\n add_script(req, \"dashboard/dashboard.js\")\n add_stylesheet(req, \"dashboard/dashboard.css\")\n return 'dashboard.html', data, None\n\n\n def get_htdocs_dirs(self):\n \"\"\"Return the absolute path of a directory containing additional\n static resources (such as images, style sheets, etc).\n \"\"\"\n return [('dashboard', resource_filename(__name__, 'htdocs'))]\n \n def get_templates_dirs(self):\n \"\"\"Return the absolute path of the directory containing the provided\n genshi templates.\n \"\"\"\n rtn = [resource_filename(__name__, 'templates')]\n return rtn\n"}, "files_after": {"dashboard/dashboard.py": "from trac.core import *\nfrom pkg_resources import resource_filename\nfrom trac.config import Option, IntOption, ListOption, BoolOption\nfrom trac.web.api import IRequestHandler, Href\nfrom trac.util.translation import _\nfrom trac.web.chrome import add_stylesheet, add_script, INavigationContributor, ITemplateProvider\nfrom trac.web.chrome import Chrome\nfrom trac.util.datefmt import utc, to_timestamp\nfrom genshi.template import TemplateLoader\nfrom genshi.filters.transform import Transformer\nfrom trac.web.api import ITemplateStreamFilter\nfrom trac.perm import IPermissionRequestor\nfrom trac.util import escape, Markup\n\nimport time\nfrom datetime import datetime, timedelta\n\n\n\n\nclass DashBoard(Component):\n implements(IRequestHandler, ITemplateProvider, IPermissionRequestor, INavigationContributor)\n \n permission = Option('dashboard', 'permission', '')\n default_milestone = Option('dashboard', 'default_milestone', '')\n\n def __init__(self):\n self.db = self.env.get_db_cnx()\n self.username = None\n self.backDate = 30\n self.ticket_closed = ['checkedin', 'closed']\n\n self.ticket_closed_sql = \"','\".join(self.ticket_closed)\n\n self.milestone = self.default_milestone\n \n if self.permission:\n self.perm = self.permission\n else:\n self.perm = 'DASHBOARD_VIEW'\n\n self.env.log.debug(\"Using Permission: %s\" % self.permission)\n\n \n # INavigationContributor methods\n def get_active_navigation_item(self, req):\n return 'dashboard'\n\n def get_navigation_items(self, req):\n if self.perm in req.perm or 'TRAC_ADMIN' in req.perm:\n yield 'mainnav', 'dashboard', Markup('Dashboard' % (\n self.env.href.dashboard() ) )\n\n\n\n def get_permission_actions(self):\n yield self.perm\n\n \n # IRequestHandler methods\n def match_request(self, req):\n serve = False\n self.env.log.debug(\"Match Request\")\n\n\n uri = req.path_info.lstrip('/').split('/')\n if uri[0] == 'dashboard':\n serve = True\n\n self.env.log.debug(\"Handle Request: %s\" % serve)\n self.baseURL = req.href('dashboard', '/')\n self.baseQueryURL = req.href('query', '/')\n self.username = req.authname\n if 'milestone' in req.args:\n self.milestone = req.args.get('milestone')\n else:\n self.milestone = self.default_milestone\n\n if self.milestone == '':\n cursor = self.db.cursor()\n sql = \"select name from milestone where (completed = 0) limit 0, 1\"\n cursor.execute(sql)\n for name, in cursor:\n self.milestone = name\n\n if 'dev' in req.args:\n self.username = req.args.get('dev')\n else:\n self.username = req.authname\n\n return serve\n\n if not self.perm in req.perm:\n self.env.log.debug(\"NO Permission to view\")\n return False\n\n return serve\n \n def get_updated_tickets(self):\n cursor = self.db.cursor()\n sql = \"select id, component, summary, status from ticket where (owner = '%s') and (changetime >= %s) and (status not in ('%s', 'new')) order by changetime desc\" % (self.username, self.stamp, self.ticket_closed_sql)\n cursor.execute(sql)\n out = []\n idx = 0\n for id, component, summary, status in cursor:\n data = {\n '__idx__': idx,\n 'id': id,\n 'component': component,\n 'summary': summary,\n 'status': status\n }\n idx = idx + 1\n out.append(data)\n return out\n\n def get_new_tickets(self):\n cursor = self.db.cursor()\n sql = \"select id, status, component, summary, changetime, priority from ticket where (owner = '%s') and (status in ('new', 'assigned')) and (type = 'defect') order by changetime desc\" % self.username\n cursor.execute(sql)\n out = []\n idx = 0\n for id, status, component, summary, changetime, priority in cursor:\n data = {\n '__idx__': idx,\n 'id': id,\n 'status': status,\n 'component': component,\n 'summary': summary,\n 'priority': priority,\n 'changetime': datetime.fromtimestamp(changetime, utc)\n }\n idx = idx + 1\n out.append(data)\n return out\n\n def get_closed_tickets(self):\n cursor = self.db.cursor()\n sql = \"select id, component, summary, changetime, status from ticket where (owner = '%s') and (status in ('%s')) and (changetime >= %s) order by component, status, changetime desc\" % (self.username, self.ticket_closed_sql, self.stamp)\n cursor.execute(sql)\n out = []\n idx = 0\n for id, component, summary, changetime, status in cursor:\n data = {\n '__idx__': idx,\n 'id': id,\n 'component': component,\n 'summary': summary,\n 'status': status,\n 'changetime': datetime.fromtimestamp(changetime, utc)\n }\n idx = idx + 1\n out.append(data)\n return out\n\n def get_milestone_tickets(self):\n cursor = self.db.cursor()\n sql = \"select id, component, summary, status, priority from ticket where (owner = '%s') and (status not in ('%s', 'new')) and (type in ('defect', 'enhancement')) and (milestone = '%s') order by component, priority\" % (self.username, self.ticket_closed_sql, self.milestone)\n cursor.execute(sql)\n out = []\n idx = 0\n for id, component, summary, status, priority in cursor:\n data = {\n '__idx__': idx,\n 'id': id,\n 'component': component,\n 'summary': summary,\n 'status': status,\n 'priority': priority\n }\n idx = idx + 1\n out.append(data)\n return out\n\n def get_todo_tickets(self):\n cursor = self.db.cursor()\n sql = \"select id, component, summary, status from ticket where (owner = '%s') and (status not in ('%s')) and (type = 'task') order by changetime desc\" % (self.username, self.ticket_closed_sql)\n cursor.execute(sql)\n out = []\n idx = 0\n for id, component, summary, status in cursor:\n data = {\n '__idx__': idx,\n 'id': id,\n 'component': component,\n 'summary': summary,\n 'status': status\n }\n idx = idx + 1\n out.append(data)\n return out\n\n def get_ticket_counts(self):\n cursor = self.db.cursor()\n sql = \"select count(*) as total, type, status from ticket where (owner = '%s') and (status not in ('%s')) group by type, status order by total desc\" % (self.username, self.ticket_closed_sql)\n cursor.execute(sql)\n out = []\n idx = 0\n for total, type, status in cursor:\n data = {\n '__idx__': idx,\n 'total': total,\n 'status': status,\n 'type': type\n }\n idx = idx + 1\n out.append(data)\n\n return out\n\n def get_action_counts(self):\n cursor = self.db.cursor()\n #sql = \"select count(*) as total, concat(oldvalue, ' => ', newvalue) as status from ticket_change where (author = '%s') and (time > %s) and (field = 'status') group by status order by total desc\" % (self.username, self.stamp)\n sql = \"select count(*) as total, (%s) as status from ticket_change where (author = '%s') and (time > %s) and (field = 'status') group by status order by total desc\" % (self.db.concat('oldvalue', \"' => '\", 'newvalue'), self.username, self.stamp)\n cursor.execute(sql)\n \n out = []\n idx = 0\n for total, status in cursor:\n data = {\n '__idx__': idx,\n 'total': total,\n 'status': status\n }\n idx = idx + 1\n out.append(data)\n\n return out\n\n\n def get_milestone_data(self):\n cursor = self.db.cursor()\n out = {\n 'total': 0,\n 'closed': 0,\n 'closed_percent': 0,\n 'new': 0,\n 'new_percent': 0,\n 'inprogress': 0,\n 'inprogress_percent': 0,\n 'name': self.milestone\n }\n #sql = \"select count(*) as total, ticket.status from ticket, ticket_custom where (ticket.milestone = '%s') and (ticket.owner = '%s') and (ticket.id = ticket_custom.ticket) and (ticket_custom.name = 'location') and (ticket_custom.value = 'Library Code')\" % (self.milestone, self.username)\n sql = \"select count(*) as total, status from ticket where (milestone = '%s') and (owner = '%s') and (type = 'defect') group by status\" % (self.milestone, self.username)\n cursor.execute(sql)\n\n for total, status in cursor:\n out['total'] = out['total'] + total\n\n if status in self.ticket_closed:\n out['closed'] = out['closed'] + total\n elif status == 'new':\n out['new'] = out['new'] + total\n else:\n out['inprogress'] = out['inprogress'] + total\n\n if out['closed'] > 0:\n out['closed_percent'] = int(round((float(out['closed']) / out['total']), 3) * 100)\n\n if out['new'] > 0:\n out['new_percent'] = int(round((float(out['new']) / out['total']), 1) * 100)\n\n if out['inprogress'] > 0:\n out['inprogress_percent'] = int(round((float(out['inprogress']) / out['total']), 3) * 100)\n\n\n return out\n\n def get_milestones(self):\n cursor = self.db.cursor()\n sql = \"select name from milestone where (name not in ('%s')) and (completed = 0)\" % self.milestone\n cursor.execute(sql)\n data = []\n for name, in cursor:\n data.append(name)\n\n return data\n\n def get_users(self):\n devs = self.env.get_known_users()\n odevs = []\n for username,name,email in devs:\n if username != self.username:\n data = {\n 'username': username,\n 'name': name or username\n }\n odevs.append(data)\n return odevs\n\n\n def process_request(self, req):\n data = {}\n self.stamp = time.time() - (60 * 60 * 24 * self.backDate)\n today = datetime.now(req.tz)\n\n\n data['backDate'] = self.backDate\n data['stamp'] = self.stamp\n data['username'] = self.username\n data['milestone'] = self.milestone\n\n #Updated Tickets \n data['updated_tickets'] = self.get_updated_tickets()\n data['has_updated_tickets'] = len(data['updated_tickets'])\n\n #New Tickets\n data['new_tickets'] = self.get_new_tickets()\n data['has_new_tickets'] = len(data['new_tickets'])\n\n #Closed Tickets\n data['closed_tickets'] = self.get_closed_tickets()\n data['has_closed_tickets'] = len(data['closed_tickets'])\n\n #Ticket Counts\n data['ticket_counts'] = self.get_ticket_counts()\n data['has_ticket_counts'] = len(data['ticket_counts'])\n\n #Action Counts\n data['action_counts'] = self.get_action_counts()\n data['has_action_counts'] = len(data['action_counts'])\n\n #TODO Lists\n data['todo_tickets'] = self.get_todo_tickets()\n data['has_todo_tickets'] = len(data['todo_tickets'])\n\n #Milestones\n data['milestone_data'] = self.get_milestone_data()\n data['has_milestones'] = len(data['milestone_data'])\n\n #Milestone Tickets\n data['milestone_tickets'] = self.get_milestone_tickets()\n data['has_milestone_tickets'] = len(data['milestone_tickets'])\n\n #Milestones\n data['milestones'] = self.get_milestones()\n\n #Users\n data['users'] = self.get_users()\n\n\n add_script(req, \"dashboard/dashboard.js\")\n add_stylesheet(req, \"dashboard/dashboard.css\")\n return 'dashboard.html', data, None\n\n\n def get_htdocs_dirs(self):\n \"\"\"Return the absolute path of a directory containing additional\n static resources (such as images, style sheets, etc).\n \"\"\"\n return [('dashboard', resource_filename(__name__, 'htdocs'))]\n \n def get_templates_dirs(self):\n \"\"\"Return the absolute path of the directory containing the provided\n genshi templates.\n \"\"\"\n rtn = [resource_filename(__name__, 'templates')]\n return rtn\n"}} +{"repo": "lowendbox/lowendscript", "pr_number": 12, "title": "Added functionality for Drupal installation, made readme file, and fixed some bugs.", "state": "open", "merged_at": null, "additions": 524, "deletions": 24, "files_changed": ["setup-debian.sh"], "files_before": {"setup-debian.sh": "#!/bin/bash\n\nfunction check_install {\n if [ -z \"`which \"$1\" 2>/dev/null`\" ]\n then\n executable=$1\n shift\n while [ -n \"$1\" ]\n do\n DEBIAN_FRONTEND=noninteractive apt-get -q -y install \"$1\"\n print_info \"$1 installed for $executable\"\n shift\n done\n else\n print_warn \"$2 already installed\"\n fi\n}\n\nfunction check_remove {\n if [ -n \"`which \"$1\" 2>/dev/null`\" ]\n then\n DEBIAN_FRONTEND=noninteractive apt-get -q -y remove --purge \"$2\"\n print_info \"$2 removed\"\n else\n print_warn \"$2 is not installed\"\n fi\n}\n\nfunction check_sanity {\n # Do some sanity checking.\n if [ $(/usr/bin/id -u) != \"0\" ]\n then\n die 'Must be run by root user'\n fi\n\n if [ ! -f /etc/debian_version ]\n then\n die \"Distribution is not supported\"\n fi\n}\n\nfunction die {\n echo \"ERROR: $1\" > /dev/null 1>&2\n exit 1\n}\n\nfunction get_domain_name() {\n # Getting rid of the lowest part.\n domain=${1%.*}\n lowest=`expr \"$domain\" : '.*\\.\\([a-z][a-z]*\\)'`\n case \"$lowest\" in\n com|net|org|gov|edu|co)\n domain=${domain%.*}\n ;;\n esac\n lowest=`expr \"$domain\" : '.*\\.\\([a-z][a-z]*\\)'`\n [ -z \"$lowest\" ] && echo \"$domain\" || echo \"$lowest\"\n}\n\nfunction get_password() {\n # Check whether our local salt is present.\n SALT=/var/lib/radom_salt\n if [ ! -f \"$SALT\" ]\n then\n head -c 512 /dev/urandom > \"$SALT\"\n chmod 400 \"$SALT\"\n fi\n password=`(cat \"$SALT\"; echo $1) | md5sum | base64`\n echo ${password:0:13}\n}\n\nfunction install_dash {\n check_install dash dash\n rm -f /bin/sh\n ln -s dash /bin/sh\n}\n\nfunction install_dropbear {\n check_install dropbear dropbear\n check_install /usr/sbin/xinetd xinetd\n\n # Disable SSH\n touch /etc/ssh/sshd_not_to_be_run\n invoke-rc.d ssh stop\n\n # Enable dropbear to start. We are going to use xinetd as it is just\n # easier to configure and might be used for other things.\n cat > /etc/xinetd.d/dropbear < /etc/mysql/conf.d/lowendbox.cnf < ~/.my.cnf < /etc/nginx/conf.d/lowendbox.conf < /etc/init.d/php-cgi <&2\n exit 1\n ;;\nesac\nexit 0\nEND\n chmod 755 /etc/init.d/php-cgi\n mkdir -p /var/run/www\n chown www-data:www-data /var/run/www\n\n cat > /etc/nginx/fastcgi_php < /etc/syslog.conf < /etc/logrotate.d/inetutils-syslogd </dev/null\n endscript\n}\nEND\n\n invoke-rc.d inetutils-syslogd start\n}\n\nfunction install_wordpress {\n check_install wget wget\n if [ -z \"$1\" ]\n then\n die \"Usage: `basename $0` wordpress \"\n fi\n\n # Downloading the WordPress' latest and greatest distribution.\n mkdir /tmp/wordpress.$$\n wget -O - http://wordpress.org/latest.tar.gz | \\\n tar zxf - -C /tmp/wordpress.$$\n mv /tmp/wordpress.$$/wordpress \"/var/www/$1\"\n rm -rf /tmp/wordpress.$$\n chown root:root -R \"/var/www/$1\"\n\n # Setting up the MySQL database\n dbname=`echo $1 | tr . _`\n userid=`get_domain_name $1`\n # MySQL userid cannot be more than 15 characters long\n userid=\"${userid:0:15}\"\n passwd=`get_password \"$userid@mysql\"`\n cp \"/var/www/$1/wp-config-sample.php\" \"/var/www/$1/wp-config.php\"\n sed -i \"s/database_name_here/$dbname/; s/username_here/$userid/; s/password_here/$passwd/\" \\\n \"/var/www/$1/wp-config.php\"\n mysqladmin create \"$dbname\"\n echo \"GRANT ALL PRIVILEGES ON \\`$dbname\\`.* TO \\`$userid\\`@localhost IDENTIFIED BY '$passwd';\" | \\\n mysql\n\n # Setting up Nginx mapping\n cat > \"/etc/nginx/sites-enabled/$1.conf\" <&2\n exit 1\nfi\n\nfunction check_install {\n if [ -z \"`which \"$1\" 2>/dev/null`\" ]\n then\n executable=$1\n shift\n while [ -n \"$1\" ]\n do\n DEBIAN_FRONTEND=noninteractive apt-get -q -y install \"$1\"\n print_info \"$1 installed for $executable\"\n shift\n done\n else\n print_warn \"$2 already installed\"\n fi\n}\n\nfunction check_remove {\n if [ -n \"`which \"$1\" 2>/dev/null`\" ]\n then\n DEBIAN_FRONTEND=noninteractive apt-get -q -y remove --purge \"$2\"\n print_info \"$2 removed\"\n else\n print_warn \"$2 is not installed\"\n fi\n}\n\nfunction check_sanity {\n # Do some sanity checking.\n if [ $(/usr/bin/id -u) != \"0\" ]\n then\n die 'Must be run by root user'\n fi\n\n if [ ! -f /etc/debian_version ]\n then\n die \"Distribution is not supported\"\n fi\n}\n\nfunction die {\n echo \"ERROR: $1\" > /dev/null 1>&2\n exit 1\n}\n\nfunction get_domain_name() {\n # Getting rid of the lowest part.\n domain=${1%.*}\n lowest=`expr \"$domain\" : '.*\\.\\([a-z][a-z]*\\)'`\n case \"$lowest\" in\n com|net|org|gov|edu|co)\n domain=${domain%.*}\n ;;\n esac\n lowest=`expr \"$domain\" : '.*\\.\\([a-z][a-z]*\\)'`\n [ -z \"$lowest\" ] && echo \"$domain\" || echo \"$lowest\"\n}\n\nfunction get_password() {\n # Check whether our local salt is present.\n SALT=/var/lib/radom_salt\n if [ ! -f \"$SALT\" ]\n then\n head -c 512 /dev/urandom > \"$SALT\"\n chmod 400 \"$SALT\"\n fi\n password=`(cat \"$SALT\"; echo $1) | md5sum | base64`\n echo ${password:0:13}\n}\n\nfunction install_dash {\n check_install dash dash\n rm -f /bin/sh\n ln -s dash /bin/sh\n}\n\nfunction install_htop {\n check_install htop htop\n}\n\nfunction install_smart {\n\tcheck_install smartmontools smartmontools\n}\n\nfunction install_locate {\n check_install locate locate\n}\n\nfunction fix_locale {\n dpkg-reconfigure locales\n}\n\nfunction var_www {\n mkdir -p /var/www/\n}\n\nfunction install_dropbear {\n check_install dropbear dropbear\n check_install /usr/sbin/xinetd xinetd\n\n # Disable SSH\n touch /etc/ssh/sshd_not_to_be_run\n invoke-rc.d ssh stop\n\n # Enable dropbear to start. We are going to use xinetd as it is just\n # easier to configure and might be used for other things.\n cat > /etc/xinetd.d/dropbear < /etc/mysql/conf.d/lowendbox.cnf < ~/.my.cnf < /etc/nginx/conf.d/lowendbox.conf < /etc/init.d/php-cgi <&2\n exit 1\n ;;\nesac\nexit 0\nEND\n chmod 755 /etc/init.d/php-cgi\n mkdir -p /var/lib/www\n chown www-data:www-data /var/lib/www\n\n cat > /etc/nginx/fastcgi_php < /etc/syslog.conf < /etc/logrotate.d/inetutils-syslogd </dev/null\n endscript\n}\nEND\n\n invoke-rc.d inetutils-syslogd start\n}\n\nfunction install_wordpress {\n# Needs fixing, soon!!!\n check_install wget wget\n if [ -z \"$1\" ]\n then\n die \"Usage: `basename $0` wordpress \"\n fi\n\n # Downloading the WordPress' latest and greatest distribution.\n mkdir /tmp/wordpress.$$\n wget -O - http://wordpress.org/latest.tar.gz | \\\n tar zxf - -C /tmp/wordpress.$$\n\tmkdir -p /var/www/$1\n mv /tmp/wordpress.$$/wordpress/* \"/var/www/$1\"\n rm -rf /tmp/wordpress.$$\n chown root:root -R \"/var/www/$1\"\n\n # Setting up the MySQL database\n dbname=`echo $1 | tr . _`\n\techo Database Name = 'echo $1 | tr . _'\n userid=`get_domain_name $1`\n # MySQL userid cannot be more than 15 characters long\n userid=\"${userid:0:15}\"\n passwd=`get_password \"$userid@mysql\"`\n cp \"/var/www/$1/wp-config-sample.php\" \"/var/www/$1/wp-config.php\"\n sed -i \"s/database_name_here/$dbname/; s/username_here/$userid/; s/password_here/$passwd/\" \\\n \"/var/www/$1/wp-config.php\"\n mysqladmin create \"$dbname\"\n echo \"GRANT ALL PRIVILEGES ON \\`$dbname\\`.* TO \\`$userid\\`@localhost IDENTIFIED BY '$passwd';\" | \\\n mysql\n\n # Setting up Nginx mapping\n cat > \"/etc/nginx/sites-enabled/$1.conf\" < \"/usr/share/nginx/www/$1/index.html\" < \"/etc/nginx/sites-enabled/$1.conf\" <\"\n fi\n\t\n\t#Download PHP5-gd package\n\tapt-get -q -y install php5-gd\n /etc/init.d/php-cgi restart\n\t\n # Downloading the Drupal' latest and greatest distribution.\n mkdir /tmp/drupal.$$\n wget -O - http://ftp.drupal.org/files/projects/drupal-6.30.tar.gz | \\\n tar zxf - -C /tmp/drupal.$$/\n mkdir -p /var/www/$1\n cp -Rf /tmp/drupal.$$/drupal*/* \"/var/www/$1\"\n rm -rf /tmp/drupal*\n chown root:root -R \"/var/www/$1\"\n\n # Setting up the MySQL database\n dbname=`echo $1 | tr . _`\n\t\n\t# MySQL dbname cannot be more than 15 characters long\n dbname=\"${dbname:0:15}\"\n \n\tuserid=`get_domain_name $1`\n \n\t# MySQL userid cannot be more than 15 characters long\n userid=\"${userid:0:15}\"\n passwd=`get_password \"$userid@mysql\"`\n cp \"/var/www/$1/sites/default/default.settings.php\" \"/var/www/$1/sites/default/settings.php\"\n\tchmod 777 /var/www/$1/sites/default/settings.php\n\tmkdir /var/www/$1/sites/default/files\n\tchmod -R 777 /var/www/$1/sites/default/files\n mysqladmin create \"$dbname\"\n echo \"GRANT ALL PRIVILEGES ON \\`$dbname\\`.* TO \\`$userid\\`@localhost IDENTIFIED BY '$passwd';\" | \\\n mysql\n\n\t#Copy DB Name, User, and Pass to settings.php and set to read only.\n\tsed -i \"91 s/username/$userid/; 91 s/password/$passwd/; 91 s/databasename/$dbname/\" \"/var/www/$1/sites/default/settings.php\"\n\tchmod 644 /var/www/$1/sites/default/settings.php\n \n\t# Setting up Nginx mapping\n cat > \"/etc/nginx/sites-enabled/$1.conf\" <\"\n fi\n\t\n\t#Download PHP5-gd package\n\tapt-get -q -y install php5-gd\n /etc/init.d/php-cgi restart\n\t\n # Downloading the Drupal' latest and greatest distribution.\n mkdir /tmp/drupal.$$\n wget -O - http://ftp.drupal.org/files/projects/drupal-7.26.tar.gz | \\\n tar zxf - -C /tmp/drupal.$$/\n mkdir -p /var/www/$1\n cp -Rf /tmp/drupal.$$/drupal*/* \"/var/www/$1\"\n rm -rf /tmp/drupal*\n chown root:root -R \"/var/www/$1\"\n\n # Setting up the MySQL database\n dbname=`echo $1 | tr . _`\n\t\n\t# MySQL dbname cannot be more than 15 characters long\n dbname=\"${dbname:0:15}\"\n\t\n userid=`get_domain_name $1`\n\t\n # MySQL userid cannot be more than 15 characters long\n userid=\"${userid:0:15}\"\n passwd=`get_password \"$userid@mysql\"`\n\t\n\t# Copy default.settings.php to settings.php and set write permissions.\n cp \"/var/www/$1/sites/default/default.settings.php\" \"/var/www/$1/sites/default/settings.php\"\n\tchmod 777 /var/www/$1/sites/default/settings.php\n\tmkdir /var/www/$1/sites/default/files\n\tchmod -R 777 /var/www/$1/sites/default/files\n \n\t# Create MySQL database\n\tmysqladmin create \"$dbname\"\n echo \"GRANT ALL PRIVILEGES ON \\`$dbname\\`.* TO \\`$userid\\`@localhost IDENTIFIED BY '$passwd';\" | \\\n mysql\n\t\t\n #Copy DB Name, User, and Pass to settings.php and set to read only.\n echo \"\\$databases['default']['default'] = array(\" >> /var/www/$1/sites/default/settings.php\n echo \"'driver' => 'mysql',\" >> /var/www/$1/sites/default/settings.php\n echo \"'database' => '$dbname',\" >> /var/www/$1/sites/default/settings.php\n echo \"'username' => '$userid',\" >> /var/www/$1/sites/default/settings.php\n echo \"'password' => '$passwd',\" >> /var/www/$1/sites/default/settings.php\n echo \"'host' => 'localhost');\" >> /var/www/$1/sites/default/settings.php\n chmod 644 /var/www/$1/sites/default/settings.php\n\t\n\t#Echo DB Name\n\techo -e $COL_BLUE\"*** COPY FOR SAFE KEEPING ***\"\n\tCOL_BLUE=\"\\x1b[34;01m\"\n COL_RESET=\"\\x1b[39;49;00m\"\n echo -e $COL_BLUE\"Database Name: \"$COL_RESET\"$dbname\"\n\t\n #Echo DB User value\n\techo -e $COL_BLUE\"Database User: \"$COL_RESET\"${userid:0:15}\"\n\t\n\t#Echo DB Password\n\techo -e $COL_BLUE\"Database Password: \"$COL_RESET\"$passwd\"\n\t\n\t#Echo Install URL\n\techo -e $COL_BLUE\"Visit to finalize installation: \"$COL_RESET\"http://$1/install.php\"\n\t\n\n\n # Setting up Nginx mapping\n cat > \"/etc/nginx/sites-enabled/$1.conf\" <args = $args;\n\t\t\n\t\tif (!$this->args[\"username\"]){\n\t\t\tthrow new exception(\"No username was given.\");\n\t\t}\n\t\t\n\t\tif (!$this->args[\"password\"]){\n\t\t\tthrow new exception(\"No password was given.\");\n\t\t}\n\t\t\n\t\trequire_once \"knj/http.php\";\n\t\t$this->http = new knj_httpbrowser();\n\t\t$this->http->connect(\"betaling.wannafind.dk\", 443);\n\t\t\n\t\t$html = $this->http->getaddr(\"index.php\");\n\t\t\n\t\t$html = $this->http->post(\"pg.loginauth.php\", array(\n\t\t\t\"username\" => $this->args[\"username\"],\n\t\t\t\"password\" => $this->args[\"password\"]\n\t\t));\n\t\t\n\t\tif (strpos($html, \"Brugernavn eller password, blev ikke godkendt.\") !== false){\n\t\t\tthrow new exception(\"Could not log in.\");\n\t\t}\n\t}\n\t\n\tfunction http(){\n\t\treturn $this->http;\n\t}\n\t\n\tfunction listPayments($args = array()){\n\t\tif ($args[\"awaiting\"]){\n\t\t\t$html = $this->http->getaddr(\"pg.frontend/pg.transactions.php\");\n\t\t}else{\n\t\t\t$sargs = array(\n\t\t\t\t\"searchtype\" => \"\",\n\t\t\t\t\"fromday\" => \"01\",\n\t\t\t\t\"frommonth\" => \"01\",\n\t\t\t\t\"fromyear\" => date(\"Y\"),\n\t\t\t\t\"today\" => \"31\",\n\t\t\t\t\"tomonth\" => \"12\",\n\t\t\t\t\"toyear\" => date(\"Y\"),\n\t\t\t\t\"transacknum\" => \"\"\n\t\t\t);\n\t\t\t\n\t\t\tif ($args[\"order_id\"]){\n\t\t\t\t$sargs[\"orderid\"] = $args[\"order_id\"];\n\t\t\t}\n\t\t\t\n\t\t\t$html = $this->http->post(\"pg.frontend/pg.search.php?search=doit\", $sargs);\n\t\t}\n\t\t\n\t\tif (!preg_match_all(\"/([0-9]+)<\\/a><\\/td>\\s*(.+)<\\/td>\\s*(.+)<\\/td>\\s*(.+)<\\/td>\\s*.*<\\/td>\\s*(.*)<\\/td>\\s*(.*)<\\/td>/U\", $html, $matches)){\n\t\t\treturn array(); //no payments were found - return empty array.\n\t\t\t//echo $html . \"\\n\\n\";\n\t\t\tthrow new exception(\"Could not parse payments.\");\n\t\t}\n\t\t\n\t\t$payments = array();\n\t\tforeach($matches[0] AS $key => $value){\n\t\t\t$id = $matches[1][$key];\n\t\t\t\n\t\t\t$amount = str_replace(\" DKK\", \"\", $matches[6][$key]);\n\t\t\t$amount = strtr($amount, array(\n\t\t\t\t\".\" => \"\",\n\t\t\t\t\",\" => \".\"\n\t\t\t));\n\t\t\t\n\t\t\t$card_type = $matches[7][$key];\n\t\t\tif (strpos($card_type, \"dk.png\") !== false){\n\t\t\t\t$card_type = \"dk\";\n\t\t\t}elseif(strpos($card_type, \"visa-elec.png\") !== false){\n\t\t\t\t$card_type = \"visa_electron\";\n\t\t\t}elseif(strpos($card_type, \"mc.png\") !== false){\n\t\t\t\t$card_type = \"mastercard\";\n\t\t\t}elseif(strpos($card_type, \"visa.png\") !== false){\n\t\t\t\t$card_type = \"visa\";\n\t\t\t}else{\n\t\t\t\tthrow new exception(\"Unknown card-type image: \" . $card_type);\n\t\t\t}\n\t\t\t\n\t\t\t$date = strtr($matches[5][$key], array(\n\t\t\t\t\"januar\" => 1,\n\t\t\t\t\"februar\" => 2,\n\t\t\t\t\"marts\" => 3,\n\t\t\t\t\"april\" => 4,\n\t\t\t\t\"maj\" => 5,\n\t\t\t\t\"juni\" => 6,\n\t\t\t\t\"juli\" => 7,\n\t\t\t\t\"august\" => 8,\n\t\t\t\t\"september\" => 9,\n\t\t\t\t\"oktober\" => 10,\n\t\t\t\t\"november\" => 11,\n\t\t\t\t\"december\" => 12\n\t\t\t));\n\t\t\t\n\t\t\tif (preg_match(\"/(\\d+) (\\d+) (\\d+) (\\d+):(\\d+):(\\d+)/\", $date, $match)){\n\t\t\t\t$unixt = mktime($match[4], $match[5], $match[6], $match[2], $match[1], $match[3]);\n\t\t\t}elseif(preg_match(\"/(\\d+) ([a-z]{3}) (\\d{4}) (\\d{2}):(\\d{2}):(\\d{2})/\", $date, $match)){\n\t\t\t\t$month = $match[2];\n\t\t\t\tif ($month == \"jan\"){\n\t\t\t\t\t$month_no = 1;\n\t\t\t\t}elseif($month == \"feb\"){\n\t\t\t\t\t$month_no = 2;\n\t\t\t\t}elseif($month == \"mar\"){\n\t\t\t\t\t$month_no = 3;\n\t\t\t\t}elseif($month == \"apr\"){\n\t\t\t\t\t$month_no = 4;\n\t\t\t\t}elseif($month == \"maj\"){\n\t\t\t\t\t$month_no = 5;\n\t\t\t\t}elseif($month == \"jun\"){\n\t\t\t\t\t$month_no = 6;\n\t\t\t\t}elseif($month == \"jul\"){\n\t\t\t\t\t$month_no = 7;\n\t\t\t\t}elseif($month == \"aug\"){\n\t\t\t\t\t$month_no = 8;\n\t\t\t\t}elseif($month == \"sep\"){\n\t\t\t\t\t$month_no = 9;\n\t\t\t\t}elseif($month == \"okt\"){\n\t\t\t\t\t$month_no = 10;\n\t\t\t\t}elseif($month == \"nov\"){\n\t\t\t\t\t$month_no = 11;\n\t\t\t\t}elseif($month == \"dec\"){\n\t\t\t\t\t$month_no = 12;\n\t\t\t\t}else{\n\t\t\t\t\tthrow new exception(\"Unknown month string: \" . $month);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t$unixt = mktime($match[4], $match[5], $match[6], $month_no, $match[1], $match[3]);\n\t\t\t}else{\n\t\t\t\tthrow new exception(\"Could not parse date: \" . $date);\n\t\t\t}\n\t\t\t\n\t\t\t$state = $matches[8][$key];\n\t\t\tif ($state == \"Gennemf\u00f8rt\"){\n\t\t\t\t$state = \"done\";\n\t\t\t}elseif(strpos($state, \"Gennemf\u00f8r\") !== false){\n\t\t\t\t$state = \"waiting\";\n\t\t\t}elseif($state == \"Annulleret\"){\n\t\t\t\t$state = \"canceled\";\n\t\t\t}elseif($state == \"Refunderet\"){\n\t\t\t\t$state = \"returned\";\n\t\t\t}else{\n\t\t\t\tthrow new exception(\"Unknown state: \" . $state);\n\t\t\t}\n\t\t\t\n\t\t\tif ($this->payments[$id]){\n\t\t\t\t$payment = $this->payments[$id];\n\t\t\t\t$payment->set(\"state\", $state);\n\t\t\t}else{\n\t\t\t\t$payment = new wfpayment_payment($this, array(\n\t\t\t\t\t\"id\" => $id,\n\t\t\t\t\t\"order_id\" => substr($matches[4][$key], 4),\n\t\t\t\t\t\"customer_id\" => $matches[3][$key],\n\t\t\t\t\t\"customer_string\" => $matches[4][$key],\n\t\t\t\t\t\"date\" => $unixt,\n\t\t\t\t\t\"amount\" => $amount,\n\t\t\t\t\t\"card_type\" => $card_type,\n\t\t\t\t\t\"state\" => $state\n\t\t\t\t));\n\t\t\t}\n\t\t\t\n\t\t\t$payments[] = $payment;\n\t\t}\n\t\t\n\t\treturn $payments;\n\t}\n}\n\nclass wfpayment_payment{\n\tfunction __construct($wfpayment, $args){\n\t\t$this->wfpayment = $wfpayment;\n\t\t$this->http = $this->wfpayment->http();\n\t\t$this->args = $args;\n\t}\n\t\n\tfunction set($key, $value){\n\t\t$this->args[$key] = $value;\n\t}\n\t\n\tfunction get($key){\n\t\tif (!array_key_exists($key, $this->args)){\n\t\t\tthrow new exception(\"No such key: \" . $key);\n\t\t}\n\t\t\n\t\treturn $this->args[$key];\n\t}\n\t\n\tfunction args(){\n\t\treturn $this->args;\n\t}\n\t\n\tfunction accept(){\n\t\tif ($this->state() == \"done\"){\n\t\t\tthrow new exception(\"This payment is already accepted.\");\n\t\t}\n\t\t\n\t\t$html = $this->http->getaddr(\"pg.frontend/pg.transactions.php?capture=singlecapture&transid=\" . $this->get(\"id\") . \"&page=1&orderby=&direction=\");\n\t\t\n\t\tif ($this->state() != \"done\"){\n\t\t\tthrow new exception(\"Could not accept the payment. State: \" . $this->state());\n\t\t}\n\t}\n\t\n\tfunction cancel(){\n\t\tif ($this->state() != \"waiting\"){\n\t\t\tthrow new exception(\"This is not waiting and cannot be canceled.\");\n\t\t}\n\t\t\n\t\t$html = $this->http->getaddr(\"pg.frontend/pg.transactionview.php?action=cancel&id=\" . $this->get(\"id\") . \"&page=1\");\n\t\t\n\t\tif ($this->state() != \"canceled\"){\n\t\t\tthrow new exception(\"Could not cancel the payment.\");\n\t\t}\n\t}\n\t\n\tfunction state(){\n\t\t$payments = $this->wfpayment->listPayments(array(\"order_id\" => $this->get(\"order_id\")));\n\t\tif (!$payments or !$payments[0]){\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\treturn $payments[0]->get(\"state\");\n\t}\n}", "strings.php": " $value){\n\t\t\t\t$array[] = $value;\n\t\t\t\t$string = str_replace($matches[0][$key], \"\", $string);\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (strlen($string) > 0){\n\t\t\tforeach(preg_split(\"/\\s/\", $string) AS $value){\n\t\t\t\tif (strlen(trim($value)) > 0){\n\t\t\t\t\t$array[] = $value;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn $array;\n\t}\n\t\n\tstatic function parseImageHTML($content){\n\t\tif (preg_match_all(\"//U\", $content, $matches)){\n\t\t\tforeach($matches[0] AS $key => $value){\n\t\t\t\t$img_html = $value;\n\t\t\t\t\n\t\t\t\tif (preg_match(\"/src=\\\"([\\s\\S]+)\\\"/U\", $img_html, $match_src)){\n\t\t\t\t\t$src = $match_src[1];\n\t\t\t\t\tif (substr($src, 0, 1) == \"/\"){\n\t\t\t\t\t\t$src = substr($src, 1);\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\t$replace_with = \"image.php?picture=\" . $src;\n\t\t\t\t\t\n\t\t\t\t\tif (preg_match(\"/width: ([0-9]+)(px|)/\", $img_html, $match_width)){\n\t\t\t\t\t\t$size[\"width\"] = $match_width[1];\n\t\t\t\t\t\t$replace_with .= \"&width=\" . $match_width[1];\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tif (preg_match(\"/height: ([0-9]+)(px|)/\", $img_html, $match_height)){\n\t\t\t\t\t\t$size[\"height\"] = $match_height[1];\n\t\t\t\t\t\t$replace_with .= \"&height=\" . $match_width[1];\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tif (preg_match_all(\"/(width|height)=\\\"([0-9]+)(px|)\\\"/\", $img_html, $match_sizes)){\n\t\t\t\t\t\t$size = array();\n\t\t\t\t\t\tforeach($match_sizes[1] AS $key => $sizetype){\n\t\t\t\t\t\t\tif (!$size[$sizetype]){\n\t\t\t\t\t\t\t\t$size[$sizetype] = $match_sizes[2][$key];\n\t\t\t\t\t\t\t\t$replace_with .= \"&\" . $sizetype . \"=\" . $match_sizes[2][$key];\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tif ($size){\n\t\t\t\t\t\t$img_html = str_replace($src, $replace_with, $img_html);\n\t\t\t\t\t\t$content = str_replace($value, $img_html, $content);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn $content;\n\t}\n\t\n\tstatic function UnixSafe($string){\n\t\t$string = str_replace(\"\\\\\", \"\\\\\\\\\", $string);\n\t\t$string = str_replace(\" \", \"\\\\ \", $string);\n\t\t$string = str_replace(\"\\$\", \"\\\\\\$\", $string);\n\t\t$string = str_replace(\"(\", \"\\\\(\", $string);\n\t\t$string = str_replace(\")\", \"\\\\)\", $string);\n\t\t$string = str_replace(\";\", \"\\\\;\", $string);\n\t\t$string = str_replace(\",\", \"\\\\,\", $string);\n\t\t$string = str_replace(\"'\", \"\\\\'\", $string);\n\t\t$string = str_replace(\">\", \"\\\\>\", $string);\n\t\t$string = str_replace(\"<\", \"\\\\<\", $string);\n\t\t$string = str_replace(\"\\\"\", \"\\\\\\\"\", $string);\n\t\t$string = str_replace(\"&\", \"\\\\&\", $string);\n\t\t\n\t\t//Replace the end & - if any.\n\t\t//$string = preg_replace(\"/&\\s*$/\", \"\\\\&\", $string);\n\t\t\n\t\treturn $string;\n\t}\n\t\n\tstatic function RegexSafe($string){\n\t\treturn strtr($string, array(\n\t\t\t\"/\" => \"\\\\/\",\n\t\t\t\".\" => \"\\\\.\",\n\t\t\t\"(\" => \"\\\\(\",\n\t\t\t\")\" => \"\\\\)\",\n\t\t\t\"[\" => \"\\\\[\",\n\t\t\t\"]\" => \"\\\\]\",\n\t\t\t\"^\" => \"\\\\^\",\n\t\t\t\"\\$\" => \"\\\\\\$\",\n\t\t\t\"+\" => \"\\\\+\"\n\t\t));\n\t}\n\t\n\tstatic function HeaderSafe($string){\n\t\treturn strtr($string, array(\n\t\t\t\"\\r\" => \"\",\n\t\t\t\"\\n\" => \" \"\n\t\t));\n\t}\n\t\n\tstatic function csvsafe($string){\n\t\t$string = htmlspecialchars($string);\n\t\t$string = str_replace(\"\\\"\", \"\", $string);\n\t\t$string = str_replace(\""\", \"\", $string);\n\t\t$string = str_replace(\"&\", \"&\", $string);\n\t\t$string = str_replace(\"\\r\", \"\", $string);\n\t\t$string = str_replace(\"\\n\", \"\", $string);\n\t\t$string = str_replace(\"<\", \"<\", $string);\n\t\t$string = str_replace(\">\", \">\", $string);\n\t\t\n\t\treturn $string;\n\t}\n\t\n\tstatic function htmlspecialchars_textarea($text){\n\t\treturn preg_replace(\"/<\\/textarea>/i\", \"</textarea>\", $text);\n\t}\n\t\n\tstatic function jsparse($string, $paras = array()){\n\t\t$string = strtr($string, array(\n\t\t\t\"'\" => \"\\\\'\",\n\t\t\t\"\\\"\" => \""\",\n\t\t\t\"\\r\" => \"\",\n\t\t\t\"\\n\" => \"\\\\n\"\n\t\t));\n\t\t\n\t\tif ($paras[\"parse_quotes\"]){\n\t\t\t$string = str_replace(\"\\\"\", \"\\\\\\\"\", $string);\n\t\t}\n\t\t\n\t\treturn $string;\n\t}\n\t\n\tstatic function tf_str($value, $yesstr, $nostr){\n\t\tif ($value){\n\t\t\treturn $yesstr;\n\t\t}\n\t\t\n\t\treturn $nostr;\n\t}\n\t\n\tstatic function shorten($text, $maxlength = nil){\n\t\tif (!$maxlength or strlen($text) <= $maxlength){\n\t\t\treturn $text;\n\t\t}\n\t\t\n\t\treturn trim(substr($text, 0, $maxlength)) . \"...\";\n\t}\n\t\n\tstatic function is_email($str){\n\t\tif (preg_match(\"/^(.+)@(.+)\\.(.+)/\", $str)){\n\t\t\treturn true;\n\t\t}\n\t\t\n\t\treturn false;\n\t}\n}\n\n/**\n\t* Parses the quotes of a string.\n\t* \n\t* FIXME: DONT USE THIS FUNCTION! It will be removed soon... Look in the SQL-functions instead.\n*/\nfunction parse_quotes($string){\n\t$string = str_replace(\"'\", \"\\\\'\", $string);\n\t\n\tif (substr($string, -1, 1) == \"\\\\\" && substr($string, -2, 2) !== \"\\\\\\\\\"){\n\t\t$string = substr($string, 0, -1) . \"\\\\\\\\\";\n\t}\n\t\n\treturn $string;\n}\n\n/** Parse a string so it fits into the command-line of Linux. */\nfunction knj_string_unix_safe($string){\n\treturn knj_strings::UnixSafe($string);\n}\n\n/** Parse a string so it will be a valid filename. */\nfunction knj_string_filename($string, $os = null){\n\tif (!$os){\n\t\trequire_once(\"knj/os.php\");\n\t\t$os = knj_os::getOS();\n\t\t$os = $os[\"os\"];\n\t}\n\t\n\tif ($os == \"windows\"){\n\t\t//parse windows-filename here.\n\t}elseif($os == \"linux\"){\n\t\t$string = strtr($string, array(\n\t\t\t\"\u00e5\" => \"aa\",\n\t\t\t\"\u00f8\" => \"oe\",\n\t\t\t\"\u00e6\" => \"ae\",\n\t\t\tutf8_decode(\"\u00e5\") => \"aa\",\n\t\t\tutf8_decode(\"\u00e6\") => \"ae\",\n\t\t\tutf8_decode(\"\u00f8\") => \"oe\",\n\t\t\t\"|\" => \"\",\n\t\t\t\"&\" => \"\",\n\t\t\t\"/\" => \"\",\n\t\t\t\"\\\\\" => \"\"\n\t\t));\n\t}else{\n\t\tthrow new Exception(\"Unsupported OS.\");\n\t}\n\t\n\treturn $string;\n}\n\n/** Parse a string to it is safe in a regex-command. */\nfunction knj_string_regex($string){\n\treturn knj_strings::RegexSafe($string);\n}", "epay.php": "args = $args;\n\t\t\n\t\tif (!$this->args[\"username\"]){\n\t\t\tthrow new exception(\"No username was given.\");\n\t\t}\n\t\t\n\t\tif (!$this->args[\"password\"]){\n\t\t\tthrow new exception(\"No password was given.\");\n\t\t}\n\t\t\n\t\t$this->soap_client = new SoapClient(\"https://ssl.ditonlinebetalingssystem.dk/remote/payment.asmx?WSDL\", array(\n\t\t\t\"verify_peer\" => false,\n\t\t\t\"allow_self_signed\" => true\n\t\t));\n\t}\n\t\n\tfunction transactions($args = array()){\n\t\t$res = $this->soap_client->__soapCall(\"gettransactionlist\", array(\"parameters\" => array_merge($args, array(\n\t\t\t\"merchantnumber\" => $this->args[\"merchant_no\"]\n\t\t))));\n\t\t$ret = array();\n\t\t\n\t\tif (is_array($res->transactionInformationAry->TransactionInformationType)){\n\t\t\tforeach($res->transactionInformationAry->TransactionInformationType as $trans_obj){\n\t\t\t\t$ret[] = new epay_payment(array(\n\t\t\t\t\t\"epay\" => $this,\n\t\t\t\t\t\"obj\" => $trans_obj,\n\t\t\t\t\t\"soap_client\" => $this->soap_client\n\t\t\t\t));\n\t\t\t}\n\t\t}elseif($res->transactionInformationAry->TransactionInformationType){\n\t\t\t$ret[] = new epay_payment(array(\n\t\t\t\t\"epay\" => $this,\n\t\t\t\t\"obj\" => $res->transactionInformationAry->TransactionInformationType,\n\t\t\t\t\"soap_client\" => $this->soap_client\n\t\t\t));\n\t\t}\n\t\t\n\t\treturn $ret;\n\t}\n\t\n\tfunction transaction($args = array()){\n\t\t$res = $this->soap_client->__soapCall(\"gettransaction\", array(\"parameters\" => array_merge($args, array(\n\t\t\t\"merchantnumber\" => $this->args[\"merchant_no\"],\n\t\t\t\"epayresponse\" => true\n\t\t))));\n\t\t\n\t\treturn new epay_payment(array(\n\t\t\t\"epay\" => $this,\n\t\t\t\"obj\" => $res->transactionInformation,\n\t\t\t\"soap_client\" => $this->soap_client\n\t\t));\n\t}\n}\n\nclass epay_payment{\n\tfunction __construct($args){\n\t\t$this->args = $args;\n\t\t$this->soap_client = $args[\"soap_client\"];\n\t\t\n\t\t$this->data = array(\n\t\t\t\"amount\" => floatval($args[\"obj\"]->authamount),\n\t\t\t\"orderid\" => intval($args[\"obj\"]->orderid),\n\t\t\t\"status\" => $args[\"obj\"]->status,\n\t\t\t\"transactionid\" => $args[\"obj\"]->transactionid\n\t\t);\n\t}\n\t\n\tfunction get($key){\n\t\tif ($key == \"id\"){\n\t\t\t$key = \"transactionid\";\n\t\t}\n\t\t\n\t\tif (!array_key_exists($key, $this->data)){\n\t\t\tthrow new exception(\"No such key: \" . $key);\n\t\t}\n\t\t\n\t\treturn $this->data[$key];\n\t}\n\t\n\tfunction args(){\n\t\treturn $this->args;\n\t}\n\t\n\tfunction accept(){\n\t\tif ($this->data[\"status\"] == \"PAYMENT_CAPTURED\"){\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\t$res = $this->soap_client->__soapCall(\"capture\", array(\"parameters\" => array(\n\t\t\t\"merchantnumber\" => $this->args[\"epay\"]->args[\"merchant_no\"],\n\t\t\t\"transactionid\" => $this->data[\"transactionid\"],\n\t\t\t\"amount\" => $this->data[\"amount\"],\n\t\t\t\"epayresponse\" => true,\n\t\t\t\"pbsResponse\" => true\n\t\t)));\n\t\t\n\t\tif (!$res->captureResult){\n\t\t\tthrow new exception(\"Could not accept payment.\\n\\n\" . print_r($res, true));\n\t\t}\n\t}\n\t\n\tfunction delete(){\n\t\t$res = $this->soap_client->__soapCall(\"delete\", array(\"parameters\" => array(\n\t\t\t\"merchantnumber\" => $this->args[\"epay\"]->args[\"merchant_no\"],\n\t\t\t\"transactionid\" => $this->data[\"transactionid\"],\n\t\t\t\"epayresponse\" => true\n\t\t)));\n\t\t\n\t\tif (!$res->deleteResult){\n\t\t\tthrow new exception(\"Could not delete payment.\\n\\n\" . print_r($res, true));\n\t\t}\n\t}\n\t\n\tfunction state(){\n\t\tthrow new exception(\"stub!\");\n\t}\n}"}, "files_after": {"wfpayment.php": "args = $args;\n\t\t\n\t\tif (!$this->args[\"username\"]){\n\t\t\tthrow new exception(\"No username was given.\");\n\t\t}\n\t\t\n\t\tif (!$this->args[\"password\"]){\n\t\t\tthrow new exception(\"No password was given.\");\n\t\t}\n\t\t\n\t\trequire_once \"knj/http.php\";\n\t\t$this->http = new knj_httpbrowser();\n\t\t$this->http->connect(\"betaling.wannafind.dk\", 443);\n\t\t\n\t\t$html = $this->http->getaddr(\"index.php\");\n\t\t\n\t\t$html = $this->http->post(\"pg.loginauth.php\", array(\n\t\t\t\"username\" => $this->args[\"username\"],\n\t\t\t\"password\" => $this->args[\"password\"]\n\t\t));\n\t\t\n\t\tif (strpos($html, \"Brugernavn eller password, blev ikke godkendt.\") !== false){\n\t\t\tthrow new exception(\"Could not log in.\");\n\t\t}\n\t}\n\t\n\tfunction http(){\n\t\treturn $this->http;\n\t}\n\t\n\tfunction listPayments($args = array()){\n\t\tif ($args[\"awaiting\"]){\n\t\t\t$html = $this->http->getaddr(\"pg.frontend/pg.transactions.php\");\n\t\t}else{\n\t\t\t$sargs = array(\n\t\t\t\t\"searchtype\" => \"\",\n\t\t\t\t\"fromday\" => \"01\",\n\t\t\t\t\"frommonth\" => \"01\",\n\t\t\t\t\"fromyear\" => date(\"Y\"),\n\t\t\t\t\"today\" => \"31\",\n\t\t\t\t\"tomonth\" => \"12\",\n\t\t\t\t\"toyear\" => date(\"Y\"),\n\t\t\t\t\"transacknum\" => \"\"\n\t\t\t);\n\t\t\t\n\t\t\tif ($args[\"order_id\"]){\n\t\t\t\t$sargs[\"orderid\"] = $args[\"order_id\"];\n\t\t\t}\n\t\t\t\n\t\t\t$html = $this->http->post(\"pg.frontend/pg.search.php?search=doit\", $sargs);\n\t\t}\n\t\t\n\t\tif (!preg_match_all(\"/]+)>\\s*([\\s\\S]+)<\\/tr>/U\", $html, $matches_tr)){\n\t\t\treturn array();\n\t\t}\n\t\t\n\t\tif (count($matches_tr[2]) == 1 or strlen(trim($matches_tr[2][0])) <= 0){\n\t\t\treturn array();\n\t\t}\n\t\t\n\t\t$payments = array();\n\t\tforeach($matches_tr[0] AS $key => $value){\n\t\t\tif (!preg_match_all(\"/]+)>(.*)<\\/td>/U\", $value, $matches_td)){\n\t\t\t\tthrow new exception(\"Could not match TDs.\");\n\t\t\t}\n\t\t\t\n\t\t\tif (!preg_match(\"/id=(\\d+)/\", $matches_td[2][0], $match_id)){\n\t\t\t\tthrow new exception(\"Could not match ID.\");\n\t\t\t}\n\t\t\t\n\t\t\t$id = $match_id[1];\n\t\t\t\n\t\t\t$amount = str_replace(\" DKK\", \"\", $matches_td[2][3]);\n\t\t\t$amount = strtr($amount, array(\n\t\t\t\t\".\" => \"\",\n\t\t\t\t\",\" => \".\"\n\t\t\t));\n\t\t\t\n\t\t\t$card_type = $matches_td[2][6];\n\t\t\t\n\t\t\tif (strpos($card_type, \"dk.png\") !== false){\n\t\t\t\t$card_type = \"dk\";\n\t\t\t}elseif(strpos($card_type, \"visa-elec.png\") !== false){\n\t\t\t\t$card_type = \"visa_electron\";\n\t\t\t}elseif(strpos($card_type, \"mc.png\") !== false){\n\t\t\t\t$card_type = \"mastercard\";\n\t\t\t}elseif(strpos($card_type, \"visa.png\") !== false){\n\t\t\t\t$card_type = \"visa\";\n\t\t\t}else{\n\t\t\t\tthrow new exception(\"Unknown card-type image: \" . $card_type);\n\t\t\t}\n\t\t\t\n\t\t\t$date = strtr($matches_td[2][2], array(\n\t\t\t\t\"januar\" => 1,\n\t\t\t\t\"februar\" => 2,\n\t\t\t\t\"marts\" => 3,\n\t\t\t\t\"april\" => 4,\n\t\t\t\t\"maj\" => 5,\n\t\t\t\t\"juni\" => 6,\n\t\t\t\t\"juli\" => 7,\n\t\t\t\t\"august\" => 8,\n\t\t\t\t\"september\" => 9,\n\t\t\t\t\"oktober\" => 10,\n\t\t\t\t\"november\" => 11,\n\t\t\t\t\"december\" => 12\n\t\t\t));\n\t\t\t\n\t\t\tif (preg_match(\"/(\\d+) (\\d+) (\\d+) (\\d+):(\\d+):(\\d+)/\", $date, $match)){\n\t\t\t\t$unixt = mktime($match[4], $match[5], $match[6], $match[2], $match[1], $match[3]);\n\t\t\t}elseif(preg_match(\"/(\\d+) ([a-z]{3}) (\\d{4}) (\\d{2}):(\\d{2}):(\\d{2})/\", $date, $match)){\n\t\t\t\t$month = $match[2];\n\t\t\t\tif ($month == \"jan\"){\n\t\t\t\t\t$month_no = 1;\n\t\t\t\t}elseif($month == \"feb\"){\n\t\t\t\t\t$month_no = 2;\n\t\t\t\t}elseif($month == \"mar\"){\n\t\t\t\t\t$month_no = 3;\n\t\t\t\t}elseif($month == \"apr\"){\n\t\t\t\t\t$month_no = 4;\n\t\t\t\t}elseif($month == \"maj\"){\n\t\t\t\t\t$month_no = 5;\n\t\t\t\t}elseif($month == \"jun\"){\n\t\t\t\t\t$month_no = 6;\n\t\t\t\t}elseif($month == \"jul\"){\n\t\t\t\t\t$month_no = 7;\n\t\t\t\t}elseif($month == \"aug\"){\n\t\t\t\t\t$month_no = 8;\n\t\t\t\t}elseif($month == \"sep\"){\n\t\t\t\t\t$month_no = 9;\n\t\t\t\t}elseif($month == \"okt\"){\n\t\t\t\t\t$month_no = 10;\n\t\t\t\t}elseif($month == \"nov\"){\n\t\t\t\t\t$month_no = 11;\n\t\t\t\t}elseif($month == \"dec\"){\n\t\t\t\t\t$month_no = 12;\n\t\t\t\t}else{\n\t\t\t\t\tthrow new exception(\"Unknown month string: \" . $month);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t$unixt = mktime($match[4], $match[5], $match[6], $month_no, $match[1], $match[3]);\n\t\t\t}else{\n\t\t\t\tthrow new exception(\"Could not parse date: \" . $date);\n\t\t\t}\n\t\t\t\n\t\t\t$state = $matches_td[2][7];\n\t\t\tif (strpos($state, \"Gennemf\u00f8rt\") !== false){\n\t\t\t\t$state = \"done\";\n\t\t\t}elseif(strpos($state, \"Gennemf\u00f8r\") !== false){\n\t\t\t\t$state = \"waiting\";\n\t\t\t}elseif(strpos($state, \"Annulleret\") !== false){\n\t\t\t\t$state = \"canceled\";\n\t\t\t}elseif(strpos($state, \"Refunderet\") !== false){\n\t\t\t\t$state = \"returned\";\n\t\t\t}else{\n\t\t\t\tthrow new exception(\"Unknown state: \" . $state);\n\t\t\t}\n\t\t\t\n\t\t\tif ($this->payments[$id]){\n\t\t\t\t$payment = $this->payments[$id];\n\t\t\t\t$payment->set(\"state\", $state);\n\t\t\t}else{\n\t\t\t\t$payment = new wfpayment_payment($this, array(\n\t\t\t\t\t\"id\" => $id,\n\t\t\t\t\t\"order_id\" => substr($matches_td[2][1], 4),\n\t\t\t\t\t\"customer_id\" => $matches_td[2][1],\n\t\t\t\t\t\"customer_string\" => $matches_td[2][1],\n\t\t\t\t\t\"date\" => $unixt,\n\t\t\t\t\t\"amount\" => $amount,\n\t\t\t\t\t\"card_type\" => $card_type,\n\t\t\t\t\t\"state\" => $state\n\t\t\t\t));\n\t\t\t}\n\t\t\t\n\t\t\t$payments[] = $payment;\n\t\t}\n\t\t\n\t\treturn $payments;\n\t}\n}\n\nclass wfpayment_payment{\n\tfunction __construct($wfpayment, $args){\n\t\t$this->wfpayment = $wfpayment;\n\t\t$this->http = $this->wfpayment->http();\n\t\t$this->args = $args;\n\t}\n\t\n\tfunction set($key, $value){\n\t\t$this->args[$key] = $value;\n\t}\n\t\n\tfunction get($key){\n\t\tif (!array_key_exists($key, $this->args)){\n\t\t\tthrow new exception(\"No such key: \" . $key);\n\t\t}\n\t\t\n\t\treturn $this->args[$key];\n\t}\n\t\n\tfunction args(){\n\t\treturn $this->args;\n\t}\n\t\n\tfunction accept(){\n\t\tif ($this->state() == \"done\"){\n\t\t\tthrow new exception(\"This payment is already accepted.\");\n\t\t}\n\t\t\n\t\t$html = $this->http->getaddr(\"pg.frontend/pg.transactions.php?capture=singlecapture&transid=\" . $this->get(\"id\") . \"&page=1&orderby=&direction=\");\n\t\t\n\t\tif ($this->state() != \"done\"){\n\t\t\tthrow new exception(\"Could not accept the payment. State: \" . $this->state());\n\t\t}\n\t}\n\t\n\tfunction cancel(){\n\t\tif ($this->state() != \"waiting\"){\n\t\t\tthrow new exception(\"This is not waiting and cannot be canceled.\");\n\t\t}\n\t\t\n\t\t$html = $this->http->getaddr(\"pg.frontend/pg.transactionview.php?action=cancel&id=\" . $this->get(\"id\") . \"&page=1\");\n\t\t\n\t\tif ($this->state() != \"canceled\"){\n\t\t\tthrow new exception(\"Could not cancel the payment.\");\n\t\t}\n\t}\n\t\n\tfunction state(){\n\t\t$payments = $this->wfpayment->listPayments(array(\"order_id\" => $this->get(\"order_id\")));\n\t\tif (!$payments or !$payments[0]){\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\treturn $payments[0]->get(\"state\");\n\t}\n}", "strings.php": " $value){\n\t\t\t\t$string[$key] = knj_strings::utf8force($value);\n\t\t\t}\n\t\t\t\n\t\t\treturn $string;\n\t\t}else{\n\t\t\t$values = array();\n\t\t\t$special = array(\"\u00f8\", \"\u00e6\", \"\u00e5\", \"\u00d8\", \"\u00c6\", \"\u00c5\");\n\t\t\tforeach($special AS $value){\n\t\t\t\t$values[utf8_decode($value)] = $value;\n\t\t\t}\n\t\t\t\n\t\t\t$string = str_replace(\"\u00c3\u00a6\", \"\u00e6\", $string);\n\t\t\t\n\t\t\treturn strtr($string, $values);\n\t\t}\n\t}\n\t\n\t/** Parses a string into an array of strings, which should all be searched for. */\n\tstatic function searchstring($string){\n\t\t$array = array();\n\t\t\n\t\tif (preg_match_all(\"/\\\"(.*)\\\"/U\", $string, $matches)){\n\t\t\tforeach($matches[1] AS $key => $value){\n\t\t\t\t$array[] = $value;\n\t\t\t\t$string = str_replace($matches[0][$key], \"\", $string);\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (strlen($string) > 0){\n\t\t\tforeach(preg_split(\"/\\s/\", $string) AS $value){\n\t\t\t\tif (strlen(trim($value)) > 0){\n\t\t\t\t\t$array[] = $value;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn $array;\n\t}\n\t\n\tstatic function parseImageHTML($content){\n\t\tif (preg_match_all(\"//U\", $content, $matches)){\n\t\t\tforeach($matches[0] AS $key => $value){\n\t\t\t\t$img_html = $value;\n\t\t\t\t\n\t\t\t\tif (preg_match(\"/src=\\\"([\\s\\S]+)\\\"/U\", $img_html, $match_src)){\n\t\t\t\t\t$src = $match_src[1];\n\t\t\t\t\tif (substr($src, 0, 1) == \"/\"){\n\t\t\t\t\t\t$src = substr($src, 1);\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\t$replace_with = \"image.php?picture=\" . $src;\n\t\t\t\t\t\n\t\t\t\t\tif (preg_match(\"/width: ([0-9]+)(px|)/\", $img_html, $match_width)){\n\t\t\t\t\t\t$size[\"width\"] = $match_width[1];\n\t\t\t\t\t\t$replace_with .= \"&width=\" . $match_width[1];\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tif (preg_match(\"/height: ([0-9]+)(px|)/\", $img_html, $match_height)){\n\t\t\t\t\t\t$size[\"height\"] = $match_height[1];\n\t\t\t\t\t\t$replace_with .= \"&height=\" . $match_width[1];\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tif (preg_match_all(\"/(width|height)=\\\"([0-9]+)(px|)\\\"/\", $img_html, $match_sizes)){\n\t\t\t\t\t\t$size = array();\n\t\t\t\t\t\tforeach($match_sizes[1] AS $key => $sizetype){\n\t\t\t\t\t\t\tif (!$size[$sizetype]){\n\t\t\t\t\t\t\t\t$size[$sizetype] = $match_sizes[2][$key];\n\t\t\t\t\t\t\t\t$replace_with .= \"&\" . $sizetype . \"=\" . $match_sizes[2][$key];\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tif ($size){\n\t\t\t\t\t\t$img_html = str_replace($src, $replace_with, $img_html);\n\t\t\t\t\t\t$content = str_replace($value, $img_html, $content);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn $content;\n\t}\n\t\n\tstatic function UnixSafe($string){\n\t\t$string = str_replace(\"\\\\\", \"\\\\\\\\\", $string);\n\t\t$string = str_replace(\" \", \"\\\\ \", $string);\n\t\t$string = str_replace(\"\\$\", \"\\\\\\$\", $string);\n\t\t$string = str_replace(\"(\", \"\\\\(\", $string);\n\t\t$string = str_replace(\")\", \"\\\\)\", $string);\n\t\t$string = str_replace(\";\", \"\\\\;\", $string);\n\t\t$string = str_replace(\",\", \"\\\\,\", $string);\n\t\t$string = str_replace(\"'\", \"\\\\'\", $string);\n\t\t$string = str_replace(\">\", \"\\\\>\", $string);\n\t\t$string = str_replace(\"<\", \"\\\\<\", $string);\n\t\t$string = str_replace(\"\\\"\", \"\\\\\\\"\", $string);\n\t\t$string = str_replace(\"&\", \"\\\\&\", $string);\n\t\t\n\t\t//Replace the end & - if any.\n\t\t//$string = preg_replace(\"/&\\s*$/\", \"\\\\&\", $string);\n\t\t\n\t\treturn $string;\n\t}\n\t\n\tstatic function RegexSafe($string){\n\t\treturn strtr($string, array(\n\t\t\t\"/\" => \"\\\\/\",\n\t\t\t\".\" => \"\\\\.\",\n\t\t\t\"(\" => \"\\\\(\",\n\t\t\t\")\" => \"\\\\)\",\n\t\t\t\"[\" => \"\\\\[\",\n\t\t\t\"]\" => \"\\\\]\",\n\t\t\t\"^\" => \"\\\\^\",\n\t\t\t\"\\$\" => \"\\\\\\$\",\n\t\t\t\"+\" => \"\\\\+\"\n\t\t));\n\t}\n\t\n\tstatic function HeaderSafe($string){\n\t\treturn strtr($string, array(\n\t\t\t\"\\r\" => \"\",\n\t\t\t\"\\n\" => \" \"\n\t\t));\n\t}\n\t\n\tstatic function csvsafe($string){\n\t\t$string = htmlspecialchars($string);\n\t\t$string = str_replace(\"\\\"\", \"\", $string);\n\t\t$string = str_replace(\""\", \"\", $string);\n\t\t$string = str_replace(\"&\", \"&\", $string);\n\t\t$string = str_replace(\"\\r\", \"\", $string);\n\t\t$string = str_replace(\"\\n\", \"\", $string);\n\t\t$string = str_replace(\"<\", \"<\", $string);\n\t\t$string = str_replace(\">\", \">\", $string);\n\t\t\n\t\treturn $string;\n\t}\n\t\n\tstatic function htmlspecialchars_textarea($text){\n\t\treturn preg_replace(\"/<\\/textarea>/i\", \"</textarea>\", $text);\n\t}\n\t\n\tstatic function jsparse($string, $paras = array()){\n\t\t$string = strtr($string, array(\n\t\t\t\"'\" => \"\\\\'\",\n\t\t\t\"\\\"\" => \""\",\n\t\t\t\"\\r\" => \"\",\n\t\t\t\"\\n\" => \"\\\\n\"\n\t\t));\n\t\t\n\t\tif ($paras[\"parse_quotes\"]){\n\t\t\t$string = str_replace(\"\\\"\", \"\\\\\\\"\", $string);\n\t\t}\n\t\t\n\t\treturn $string;\n\t}\n\t\n\tstatic function tf_str($value, $yesstr, $nostr){\n\t\tif ($value){\n\t\t\treturn $yesstr;\n\t\t}\n\t\t\n\t\treturn $nostr;\n\t}\n\t\n\tstatic function shorten($text, $maxlength = nil){\n\t\tif (!$maxlength or strlen($text) <= $maxlength){\n\t\t\treturn $text;\n\t\t}\n\t\t\n\t\treturn trim(substr($text, 0, $maxlength)) . \"...\";\n\t}\n\t\n\tstatic function is_email($str){\n\t\tif (preg_match(\"/^(.+)@(.+)\\.(.+)/\", $str)){\n\t\t\treturn true;\n\t\t}\n\t\t\n\t\treturn false;\n\t}\n}\n\n/**\n\t* Parses the quotes of a string.\n\t* \n\t* FIXME: DONT USE THIS FUNCTION! It will be removed soon... Look in the SQL-functions instead.\n*/\nfunction parse_quotes($string){\n\t$string = str_replace(\"'\", \"\\\\'\", $string);\n\t\n\tif (substr($string, -1, 1) == \"\\\\\" && substr($string, -2, 2) !== \"\\\\\\\\\"){\n\t\t$string = substr($string, 0, -1) . \"\\\\\\\\\";\n\t}\n\t\n\treturn $string;\n}\n\n/** Parse a string so it fits into the command-line of Linux. */\nfunction knj_string_unix_safe($string){\n\treturn knj_strings::UnixSafe($string);\n}\n\n/** Parse a string so it will be a valid filename. */\nfunction knj_string_filename($string, $os = null){\n\tif (!$os){\n\t\trequire_once(\"knj/os.php\");\n\t\t$os = knj_os::getOS();\n\t\t$os = $os[\"os\"];\n\t}\n\t\n\tif ($os == \"windows\"){\n\t\t//parse windows-filename here.\n\t}elseif($os == \"linux\"){\n\t\t$string = strtr($string, array(\n\t\t\t\"\u00e5\" => \"aa\",\n\t\t\t\"\u00f8\" => \"oe\",\n\t\t\t\"\u00e6\" => \"ae\",\n\t\t\tutf8_decode(\"\u00e5\") => \"aa\",\n\t\t\tutf8_decode(\"\u00e6\") => \"ae\",\n\t\t\tutf8_decode(\"\u00f8\") => \"oe\",\n\t\t\t\"|\" => \"\",\n\t\t\t\"&\" => \"\",\n\t\t\t\"/\" => \"\",\n\t\t\t\"\\\\\" => \"\"\n\t\t));\n\t}else{\n\t\tthrow new Exception(\"Unsupported OS.\");\n\t}\n\t\n\treturn $string;\n}\n\n/** Parse a string to it is safe in a regex-command. */\nfunction knj_string_regex($string){\n\treturn knj_strings::RegexSafe($string);\n}", "epay.php": "args = $args;\n\t\t\n\t\tif (!$this->args[\"username\"]){\n\t\t\tthrow new exception(\"No username was given.\");\n\t\t}\n\t\t\n\t\tif (!$this->args[\"password\"]){\n\t\t\tthrow new exception(\"No password was given.\");\n\t\t}\n\t\t\n\t\t$this->soap_client = new SoapClient(\"https://ssl.ditonlinebetalingssystem.dk/remote/payment.asmx?WSDL\", array(\n\t\t\t\"verify_peer\" => false,\n\t\t\t\"allow_self_signed\" => true\n\t\t));\n\t}\n\t\n\tfunction transactions($args = array()){\n\t\t$res = $this->soap_client->__soapCall(\"gettransactionlist\", array(\"parameters\" => array_merge($args, array(\n\t\t\t\"merchantnumber\" => $this->args[\"merchant_no\"]\n\t\t))));\n\t\t$ret = array();\n\t\t\n\t\tif (is_array($res->transactionInformationAry->TransactionInformationType)){\n\t\t\tforeach($res->transactionInformationAry->TransactionInformationType as $trans_obj){\n\t\t\t\t$ret[] = new epay_payment(array(\n\t\t\t\t\t\"epay\" => $this,\n\t\t\t\t\t\"obj\" => $trans_obj,\n\t\t\t\t\t\"soap_client\" => $this->soap_client\n\t\t\t\t));\n\t\t\t}\n\t\t}elseif($res->transactionInformationAry->TransactionInformationType){\n\t\t\t$ret[] = new epay_payment(array(\n\t\t\t\t\"epay\" => $this,\n\t\t\t\t\"obj\" => $res->transactionInformationAry->TransactionInformationType,\n\t\t\t\t\"soap_client\" => $this->soap_client\n\t\t\t));\n\t\t}\n\t\t\n\t\treturn $ret;\n\t}\n\t\n\tfunction transaction($args = array()){\n\t\t$res = $this->soap_client->__soapCall(\"gettransaction\", array(\"parameters\" => array_merge($args, array(\n\t\t\t\"merchantnumber\" => $this->args[\"merchant_no\"],\n\t\t\t\"epayresponse\" => true\n\t\t))));\n\t\t\n\t\treturn new epay_payment(array(\n\t\t\t\"epay\" => $this,\n\t\t\t\"obj\" => $res->transactionInformation,\n\t\t\t\"soap_client\" => $this->soap_client\n\t\t));\n\t}\n}\n\nclass epay_payment{\n\tfunction __construct($args){\n\t\t$this->args = $args;\n\t\t$this->soap_client = $args[\"soap_client\"];\n\t\t\n\t\tif ($args[\"obj\"]->capturedamount){\n\t\t\t$amount = floatval($args[\"obj\"]->capturedamount);\n\t\t}else{\n\t\t\t$amount = floatval($args[\"obj\"]->authamount);\n\t\t}\n\t\t\n\t\t$this->data = array(\n\t\t\t\"amount\" => $amount,\n\t\t\t\"orderid\" => intval($args[\"obj\"]->orderid),\n\t\t\t\"status\" => $args[\"obj\"]->status,\n\t\t\t\"transactionid\" => $args[\"obj\"]->transactionid\n\t\t);\n\t}\n\t\n\tfunction get($key){\n\t\tif ($key == \"id\"){\n\t\t\t$key = \"transactionid\";\n\t\t}\n\t\t\n\t\tif (!array_key_exists($key, $this->data)){\n\t\t\tthrow new exception(\"No such key: \" . $key);\n\t\t}\n\t\t\n\t\treturn $this->data[$key];\n\t}\n\t\n\tfunction args(){\n\t\treturn $this->args;\n\t}\n\t\n\tfunction accept(){\n\t\tif ($this->data[\"status\"] == \"PAYMENT_CAPTURED\"){\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\t$res = $this->soap_client->__soapCall(\"capture\", array(\"parameters\" => array(\n\t\t\t\"merchantnumber\" => $this->args[\"epay\"]->args[\"merchant_no\"],\n\t\t\t\"transactionid\" => $this->data[\"transactionid\"],\n\t\t\t\"amount\" => $this->data[\"amount\"],\n\t\t\t\"epayresponse\" => true,\n\t\t\t\"pbsResponse\" => true\n\t\t)));\n\t\t\n\t\tif (!$res->captureResult){\n\t\t\tthrow new exception(\"Could not accept payment.\\n\\n\" . print_r($res, true));\n\t\t}\n\t}\n\t\n\tfunction delete(){\n\t\t$res = $this->soap_client->__soapCall(\"delete\", array(\"parameters\" => array(\n\t\t\t\"merchantnumber\" => $this->args[\"epay\"]->args[\"merchant_no\"],\n\t\t\t\"transactionid\" => $this->data[\"transactionid\"],\n\t\t\t\"epayresponse\" => true\n\t\t)));\n\t\t\n\t\tif (!$res->deleteResult){\n\t\t\tthrow new exception(\"Could not delete payment.\\n\\n\" . print_r($res, true));\n\t\t}\n\t}\n\t\n\tfunction state(){\n\t\tthrow new exception(\"stub!\");\n\t}\n}"}} +{"repo": "collective/collective.setuphandlertools", "pr_number": 1, "title": "Depend on Products.CMFPlone instead of Plone to not fetch unnecessary\u2026", "state": "closed", "merged_at": "2018-02-08T13:11:26Z", "additions": 8, "deletions": 1, "files_changed": ["setup.py"], "files_before": {"setup.py": "from setuptools import setup, find_packages\nimport os\n\nversion = '1.0b4'\n\nsetup(name='collective.setuphandlertools',\n version=version,\n description=\"Tools for setting up a Plone site.\",\n long_description=open(\"README.txt\").read() + \"\\n\\n\" +\n open(os.path.join(\"docs\", \"HISTORY.txt\")).read(),\n # Get more strings from http://pypi.python.org/pypi?:action=list_classifiers\n classifiers=[\n \"Framework :: Plone\",\n \"Programming Language :: Python\",\n ],\n keywords='plone zope setup',\n author='Johannes Raggam',\n author_email='raggam-nl@adm.at',\n url='http://github.com/collective/collective.setuphandlertools',\n license='GPL',\n packages=find_packages(exclude=['ez_setup']),\n namespace_packages=['collective'],\n include_package_data=True,\n zip_safe=False,\n install_requires=[\n 'setuptools',\n # -*- Extra requirements: -*-\n 'Plone',\n 'Products.ATContentTypes',\n 'Products.CMFCore',\n 'Products.PortalTransforms',\n ],\n )\n"}, "files_after": {"setup.py": "from setuptools import setup, find_packages\nimport os\n\nversion = '1.0b4'\n\nsetup(name='collective.setuphandlertools',\n version=version,\n description=\"Tools for setting up a Plone site.\",\n long_description=open(\"README.txt\").read() + \"\\n\\n\" +\n open(os.path.join(\"docs\", \"HISTORY.txt\")).read(),\n # Get more strings from http://pypi.python.org/pypi?:action=list_classifiers\n classifiers=[\n \"Framework :: Plone\",\n \"Programming Language :: Python\",\n ],\n keywords='plone zope setup',\n author='Johannes Raggam',\n author_email='raggam-nl@adm.at',\n url='http://github.com/collective/collective.setuphandlertools',\n license='GPL',\n packages=find_packages(exclude=['ez_setup']),\n namespace_packages=['collective'],\n include_package_data=True,\n zip_safe=False,\n install_requires=[\n 'setuptools',\n # -*- Extra requirements: -*-\n 'Products.CMFPlone',\n 'Products.ATContentTypes',\n 'Products.CMFCore',\n 'Products.PortalTransforms',\n ],\n )\n"}} +{"repo": "balinterdi/balinterdi.github.com", "pr_number": 13, "title": "Sales web changes", "state": "closed", "merged_at": "2016-03-07T13:05:36Z", "additions": 13, "deletions": 1, "files_changed": ["source/_layouts/rarwe_book.html"], "files_before": {"source/_layouts/rarwe_book.html": "\n\n\n\n \n \n \n \n\n \n \n \n \n \n \n\n \n \n\n Cut your learning curve and build ambitious apps with Ember.js.\n\n \n \n \n \n \n \n \n \n \n\n \n \n \n \n \n\n\n\n
            \n\n \n
            \n
            \n\n \n\n
            \n
            \n
            \n \"Rock\n
            \n
            \n
            \n
            \n

            Build ambitious apps with confidence

            \n

            Ember.js is a kick-ass framework for building\n web applications. It's the only tool you need\n (on the client-side) to craft your idea into a working\n wonder. However, its strong opinions and heavy reliance of\n \u201cconvention over configuration\u201d can give developers who\n are new to the framework a hard time figuring out how\n Ember wants them to do things.

            \n\n

            This book helps to overcome that initial\n frustration, and help you grok Ember a lot\n faster, by pinpointing the core concepts and\n explaining them in detail. Once you understand them you\n are on your way to taming and mastering Ember.js.\n So don't fear the learning curve.

            \n\n
            \n
            \n
            \n

            This is a really great book. I think it will be very helpful to many people. I\u2019m definitely going to recommend it to beginners.

            \n
            \n
            \n
            \n \"Taras\n
            \n
            \n — Taras Mankowski\n EmberSherpa\n
            \n
            \n
            \n
            \n

            The book guides you through the steps of building a real application so that you can see how the concepts are applied in practice. You'll learn about the building blocks of Ember one by one, in a way that crushes the steep learning curve. Knowledge is dripped in slowly, chapter by chapter, to prevent you from drowning in a sea of novel information. By improving an existing and working application, you will learn more quickly and new knowledge will sink in deeper.

            \n

            Already convinced? Skip to the packages.

            \n
            \n\n
            \n
            \n
            \n
            \n \n\n \n
            \n
            \n
            \n
            \n
            \n \"Sample\n
            \n
            \n
            \n
            \n

            Want to read a sample chapter first?

            \n \n
            \n\n
            \n \n \n
            \n \n \n
            \n
            \n

            There was an error submitting your subscription. Please try again.

            \n
            \n
            \n
            \n \n \n
            \n
            \n \n \n
            \n \n We won't send you spam. Unsubscribe at any time.\n
            \n
            \n
            \n
            \n\n
            \n
            \n
            \n
            \n \n \n \n\n \n
            \n
            \n
            \n
            \n \n
            \n
            \n

            Once upon a time...

            \n
            \n
            \n
            \n\n
            \n

            \n It all started in September 2013. Having just returned from the first European\n Ember.js conference, my enthusiasm went through the roof. I wanted to spread the\n word, for people to realize how beautiful Ember is, for them to know\n that Ember.js is not that hard to learn. It's just a matter of having the core\n concepts internalized.\n

            \n

            \n So without proper equipment (and after a few episodes, with a ~$80 mic) I started producing screencasts, a series in\n which a simple application is developed step-by-step. I sent the first few to my\n subscribers and kept producing them. And people seemed to have liked them.\n

            \n\n
            \n
            \n
            \n
            \n
            \n

            Great episode! Pace and depth was perfect. Thanks for such a great webcast series!

            \n
            \n
            \n
            \n \"Curtis\n
            \n
            \n — Curtis Wallen\n
            \n
            \n
            \n
            \n\n
            \n
            \n
            \n

            I really appreciate the effort you want to put up. Just wanted to thank you for this and let you know that your video series rock!

            \n
            \n
            \n
            \n \"Antonio\n
            \n
            \n — Antonio Antillon\n
            \n
            \n
            \n
            \n
            \n
            \n\n

            \n Once the screencast series was finished, I switched to blog posts and lengthier\n articles, and in 2014 I committed to posting something of\n value each week. Then, after a long labor of (mostly) love,\n I published the 1st edition of the book in Feburary\n 2015, that used the then stable Ember version, 1.10.\n

            \n

            \n I was not done, though. As Ember made progress in a\n neck breaking pace, I kept the book up-to-date with the\n actual stable version of the framework, and adding material\n that covered the new features.\n

            \n
            \n
            \n
            \n
            \n \n\n \n
            \n
            \n
            \n
            \n \n
            \n
            \n

            Buy once, get all updates for free

            \n
            \n
            \n
            \n\n
            \n

            The first edition of this book followed Ember's journey to\n its 2.0 release. As Ember gracefully shedded old syntaxes, the\n book's content was updated not to use those syntaxes, either.\n When a new feature appeared, I added a section about it, trying\n to find a practical example for it in the application.

            \n\n

            Since Ember follows a 6-week release cycle, that meant\n frequent book updates, precisely 8 \"minor book releases\" in a\n little less than 7 months. These updates came free for all of my\n customers, no matter which package they chose. I aim to follow a\n similar path and update policy with Ember 2.x. The framework\n makes progress really fast but I'll keep in sync with the latest\n stable version of Ember and keep the content fresh. And\n free until at least the next major version.

            \n
            \n
            \n\n
            \n
            \n
            \n
            \n
            \n

            I really like it! It is super difficult to find the right balance between pacing and detail\nand put it all together in an understandable form but you pulled it off.

            \n
            \n
            \n
            \n \"Cory\n
            \n
            \n — Cory Forsyth\n 201 Created\n
            \n
            \n
            \n
            \n\n
            \n
            \n
            \n

            Just wanted to say thanks for the ongoing updates of the book. Even after finishing the book, it\u2019s becoming a great reference for the changes Ember is going through (even more so than the official docs).

            \n
            \n
            \n
            \n \"Gabriel\n
            \n
            \n — Gabriel Rotbart\n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n \n\n \n
            \n
            \n
            \n
            \n
            \n
            \n

            Table of Contents

            \n
            \n
            \n
            \n
            \n\n
            \n
            \n
            \n \n
            \n
              \n
            • Preface\n\n
                \n
              • My love affair with Ember.js
              • \n
              • Acknowledgements
              • \n
            • \n
            • Introduction to Ember.js\n\n
                \n
              • Why Ember.js
              • \n
              • Backstage - Dial M for Model
              • \n
              • About this book
              • \n
              • Is this book for you?
              • \n
              • Ambitious goal for an ambitious framework
              • \n
              • The application we are going to build
              • \n
              • Errata
              • \n
            • \n
            • Ember CLI\n\n
                \n
              • Setting up Ember CLI
              • \n
              • Creating our application
              • \n
            • \n
            • Templates and data bindings\n\n
                \n
              • The first template
              • \n
              • Showing a list of songs in the application template
              • \n
              • Backstage - Handlebar's fail-softness
              • \n
              • Backstage - ES2015 modules
              • \n
              • Backstage - Class and instance properties
              • \n
              • Adding libraries to the build
              • \n
              • Importing needed assets manually
              • \n
              • Using an Ember add-on
              • \n
              • Auto-updating templates
              • \n
            • \n
            • Routing\n\n
                \n
              • What do we want to achieve?
              • \n
              • New styles
              • \n
              • Routes set up data
              • \n
              • Backstage - A word about generated test files
              • \n
              • Moving around with link-to
              • \n
              • Using the model property
              • \n
              • Showing a list of bands
              • \n
              • Showing a list of songs
              • \n
            • \n
            • Nested routes\n\n
                \n
              • Defining the nested routes
              • \n
              • Full route names
              • \n
              • Backstage - Resource routes
              • \n
              • Stepping through a router transition
              • \n
              • Backstage - Computed properties
              • \n
              • Nested templates
              • \n
              • {{outlet}} is the default template for routes
              • \n
            • \n
            • Actions\n\n
                \n
              • Extracting model classes
              • \n
              • The class-level mutable attribute property
              • \n
              • Capturing the event
              • \n
              • Turning event into intent
              • \n
            • \n
            • Components\n\n
                \n
              • The idea behind components
              • \n
              • Component specification
              • \n
              • Defining the component's properties
              • \n
              • Using the component
              • \n
              • Displaying the rating with stars
              • \n
              • Backstage - The default component template
              • \n
              • Backstage - On the utility of explicit dependency definitions
              • \n
              • Speaking to the outside world through actions
              • \n
              • Closure actions
              • \n
            • \n
            • Controllers\n\n
                \n
              • Preventing the creation of bands without a name
              • \n
              • Smooth UI flows
              • \n
              • Going to the band page after it is created
              • \n
              • Nudging the user to create the first song
              • \n
              • Showing the text field when the call to action has been acted on
              • \n
              • Creating new bands and songs by pressing return
              • \n
              • Backstage - Where to handle actions?
              • \n
            • \n
            • Advanced routing\n\n
                \n
              • Route hooks
              • \n
              • Route actions
              • \n
              • Redirection
              • \n
              • Redirecting before the model is known
              • \n
              • Redirecting after the model is known
              • \n
              • Backstage - Skipping model resolution
              • \n
              • Leaving routes and arriving at them
              • \n
              • Setting descriptive page titles
              • \n
              • Warning about losing data
              • \n
            • \n
            • Talking to a backend - with Ember Data\n\n
                \n
              • The concept behind Ember Data
              • \n
              • The API
              • \n
              • Model classes
              • \n
              • Transforming the app to use Ember Data
              • \n
              • Loading bands
              • \n
              • Fetching a single band
              • \n
              • Loading songs for a band
              • \n
              • Creating a band
              • \n
              • Updating a band's description
              • \n
              • Updating song ratings
              • \n
              • Backstage - Promises
              • \n
            • \n
            • Testing\n\n
                \n
              • Clarifying the vocabulary
              • \n
              • Acceptance tests
              • \n
              • To mock or not to mock?
              • \n
              • Unit tests
              • \n
              • Integration tests
              • \n
              • Adding an acceptance test
              • \n
              • Analyzing an Ember acceptance test
              • \n
              • Making the first test pass
              • \n
              • Safeguarding critical user scenarios
              • \n
              • Creating a band
              • \n
              • Creating a song
              • \n
              • Backstage \u2013 Fake synchronous tests
              • \n
              • Writing your own test helpers
              • \n
              • Registering a synchronous helper
              • \n
              • Registering an async helper
              • \n
              • Refactoring stubs
              • \n
              • Integration tests in Ember
              • \n
              • Unit tests in Ember
              • \n
            • \n
            • Sorting and searching with query parameters\n\n
                \n
              • Query parameters
              • \n
              • Query parameters in Ember
              • \n
              • Sorting the list of songs
              • \n
              • Sorting an array of items
              • \n
              • Backstage - Computed property macros
              • \n
              • Changing the sorting criteria
              • \n
              • Filtering songs by a search term
              • \n
              • Adding a dash of query parameters
              • \n
              • Using links instead of buttons
              • \n
              • Taking a look at what we made
              • \n
            • \n
            • Loading and error routes\n\n
                \n
              • Loading routes
              • \n
              • Backstage - Rendering the loading template is an overridable default
              • \n
              • Error routes
              • \n
            • \n
            • Helpers\n\n
                \n
              • About helpers
              • \n
              • Capitalizing each word of a name
              • \n
              • Using it in templates, or elsewhere
              • \n
              • Use dashed names for helpers
              • \n
            • \n
            • Animations\n\n
                \n
              • Setting up liquid-fire
              • \n
              • liquid-fire architecture
              • \n
              • Transition map
              • \n
              • Transition functions
              • \n
              • Template helpers
              • \n
              • Putting it all together
              • \n
              • Debugging transitions
              • \n
              • Animate moving between routes
              • \n
              • Adding a custom animation
              • \n
              • Animate a value change
              • \n
            • \n
            • Making an Ember addon\n\n
                \n
              • What is an Ember addon?
              • \n
              • Developing the addon
              • \n
              • Integrating our addon into our app
              • \n
              • Adding a block form
              • \n
              • Customizing the star-rating component's look and behavior
              • \n
              • Publishing the addon
              • \n
              • Using a published addon from the app
              • \n
            • \n
            • ES2015 - Writing modern JavaScript\n\n
                \n
              • Modernizing the app
              • \n
              • Modules
              • \n
              • Template strings
              • \n
              • Short-hand method definitions
              • \n
              • Replacing var (let & const)
              • \n
              • Arrow functions
              • \n
              • Destructuring
              • \n
              • Other useful ES2015 features
              • \n
              • Backstage - ember-watson
              • \n
              • Computed property macros
              • \n
            • \n
            • Deployment\n\n
                \n
              • FrontPage
              • \n
              • Heroku
              • \n
              • ember-cli-deploy
              • \n
            • \n
            • Afterword\n\n
                \n
              • Your journey with Ember.js
              • \n
            • \n
            \n\n
            \n\n
            \n
            \n
            \n
            \n
            \n
            \n
            \n \n\n \n
            \n
            \n
            \n
            \n \"Balint\n
            \n\n
            \n

            About me

            \n

            Hello there, I'm Balint Erdi.

            \n

            \n I have a long history of building web applications and have mostly been a back-end\n guy.\n

            \n

            \n On a grey, chilly February day in 2013 that I\u2019ll never forget (maybe it was\n January?) I got acquainted with Ember.js. Ember.js made that day bright and the\n ones that came after that. After learning the ropes I shifted gears and have been\n proselytizing for Ember since last summer.\n

            \n

            \n I gave a beginner\u2019s workshop at Eurucamp, and held presentations at Arrrrcamp, The Geek Gathering and EmberFest. I started an Ember.js mailing list, made an introductory\n screencast series and have been sending Ember content to my dear subscribers on a\n weekly basis. I have also written guest articles for Safari Books Online, Firebase\n and Toptal.\n

            \n

            \n I guess you could say I\u2019m pretty passionate about Ember.\n

            \n

            \n Oh, and I love rock & roll, obviously.\n

            \n
            \n
            \n
            \n
            \n \n\n \n
            \n
            \n
            \n
            \n \n
            \n
            \n

            Bonus: Exclusive hack.hands() deal

            \n
            \n
            \n
            \n
            \n

            \n hack.hands()\n is your SOS button for live programming support, available 24/7. hack.hands() instantly connects developers with a network of expert programmers at the click of a button. Never get stuck, learn more and keep coding!\n If you buy any package, you will receive $25 to spend on their platform that you can use to get your Ember project unstuck.\n

            \n
            \n
            \n\n
            \n
            \n
            \n
            \n
            \n

            Even though I have worked with Ember for the past 6 months, the book helped clarify a lot of things, especially new features and their deprecated counterparts. Such a great book, and looking forward to the second one!

            \n
            \n
            \n
            \n \"David\n
            \n
            \n — David Tang\n
            \n
            \n
            \n
            \n\n
            \n
            \n
            \n

            There is almost nowhere to go to get a good grounding in Ember. In months of searching this is the best resource that exists... so much so I'm going to try to get a few copies sorted out for my team at work. Thanks Balint!

            \n
            \n
            \n
            \n \"\n
            \n
            \n — Andy Davison\n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n \n\n \n
            \n
            \n
            \n
            \n
            \n

            Stairway to Heaven Package

            \n
            \n
            \n
            \n\n
            \n
            \n

            \n The path to Ember.js bliss, this package contains all you need to take your Ember.js skills to the next level. It contains:

            \n \"Stairway\n

            \n
            \n
            \n
            \n\n
            \n
            \n
            \n
            \n
            \n

            This was a truly great series of screencasts. Very, very well done. Simple enough while not being simplistic.

            \n
            \n
            \n
            \n \"Claude\n
            \n
            \n — Claude Pr\u00e9court\n
            \n
            \n
            \n
            \n\n
            \n
            \n
            \n

            Nice work with these Ember tutorials. You're doing a really nice thing for the community.

            \n
            \n
            \n
            \n \"Steven\n
            \n
            \n — Steven Kane\n
            \n
            \n
            \n
            \n
            \n
            \n
            \n \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n \"The\n
            \n

            The book

            \n 18 chapters\n

            This is what you absolutely need to get up & running with Ember.js. Comes in pdf, mobi and epub formats for your reading pleasure.

            \n
            \n
            \n\n
            \n
            \n
            \n \"Code\"\n
            \n

            Access to the code

            \n All of the source code\n

            in the application so that you can check how the app looks & works at each step. Or tweak it to your liking.

            \n
            \n
            \n\n
            \n
            \n
            \n \"Screencast\"\n
            \n

            Screencasts

            \n 4 screencasts\n

            They run around 10 minutes each and cover the following,\n advanced topics: Pods in Ember CLI, Animations,\n Authentication & Authorization, and ES2015 &\n computed macros.

            \n
            \n
            \n\n
            \n
            \n
            \n \"Rock\n
            \n

            Rock & More

            \n Includes\n

            $25 credit on the hack.hands() platform

            \n

            60-day refund guarantee

            \n
            \n
            \n
            \n
            \n\n
            \n \n
            \n\n
            \n
            \n\n \n
            \n
            \n
            \n
            \n
            \n

            Light my Fire Package

            \n
            \n
            \n
            \n\n
            \n
            \n

            \n Take out the screencasts and you have this smaller package that will still ignite your Ember rocket. It contains:\n \"Light\n

            \n
            \n
            \n
            \n
            \n\n
            \n
            \n
            \n
            \n
            \n
            \n
            \n \"The\n
            \n

            The book

            \n 18 chapters\n

            This is what you absolutely need to get up & running with Ember.js. Comes in pdf, mobi and epub formats for your reading pleasure.

            \n
            \n
            \n\n
            \n
            \n
            \n \"Code\"\n
            \n

            Access to the code

            \n All of the source code\n

            in the application so that you can check how the app looks & works at each step. Or tweak it to your liking.

            \n
            \n
            \n\n
            \n
            \n
            \n \"Rock\n
            \n

            Rock & More

            \n Includes\n

            $25 credit on the hack.hands() platform

            \n

            60-day refund guarantee

            \n
            \n
            \n
            \n
            \n\n
            \n \n
            \n
            \n
            \n \n\n \n
            \n
            \n
            \n
            \n
            \n

            Smoke on the Water Package

            \n
            \n
            \n
            \n\n
            \n
            \n

            \n Basic but still solid, as the name suggests. This package inclues the book and the hack.hands() deal. It contains:\n

            \n \"Smoke\n

            \n
            \n
            \n
            \n
            \n\n
            \n
            \n
            \n
            \n
            \n
            \n
            \n \"The\n
            \n

            The book

            \n 18 chapters\n

            This is what you absolutely need to get up & running with Ember.js. Comes in pdf, mobi and epub formats for your reading pleasure.

            \n
            \n
            \n\n
            \n
            \n
            \n \"Rock\n
            \n

            Rock & More

            \n Includes\n

            $25 credit on the hack.hands() platform

            \n

            60-day refund guarantee

            \n
            \n
            \n\n
            \n
            \n\n
            \n \n
            \n\n
            \n
            \n
            \n
            \n
            \n

            I\u2019m REALLY enjoying the book and find it to be very thorough and informative. You\u2019ve done a great job of answering questions I had about various concepts that were not detailed clearly elsewhere.

            \n
            \n
            \n
            \n \"Bill\n
            \n
            \n — Bill White\n Data Visualizations at www.bildwhite.com\n
            \n
            \n
            \n
            \n\n
            \n
            \n
            \n

            It\u2019s been an invaluable resource in learning Ember and one I would recommend to any developer wanting to get started with the framework.

            \n
            \n
            \n
            \n \"Jonathan\n
            \n
            \n — Jonathan Rowley\n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n \n\n \n
            \n
            \n
            \n
            \n \n
            \n
            \n

            Hmm, I\u2019m not sure...

            \n
            \n
            \n
            \n\n
            \n
              \n
            • \n

              Is the book ready for Ember 2?

              \n

              \n Yes, it is! The app in the book runs Ember (and Ember Data)\n 2 and does not use any deprecated stuff.\n

              \n
            • \n\n
            • \n

              Is this book for me?

              \n

              \n The book starts from the very basics (installing\n ember-cli, writing your first template, etc.) so if you\n completely get Ember, this book is probably not for you. If\n you are just starting out (or about to) or want to\n understand fundamental concepts in Ember, the book is\n definitely for you.\n

              \n
            • \n\n
            • \n

              What if I don't like the book?

              \n

              \n I offer a 60-day moneyback guarantee. No strings attached,\n just send your purchase receipt (or email address) to\n rarwe-book@balinterdi.com or answer to the welcome email\n that you received when you purchased.\n

              \n
            • \n\n
            • \n

              Everything is changing so fast; won't the content be outdated by next week?

              \n

              \n As Ember.js moves towards 3.0, I will keep updating the\n content of the book so that it stays void of deprecation\n warnings and does not promote practices that are no longer\n considered idiomatic. For the 1st edition of the book,\n I released an update once about every four weeks,\n more often than Ember stable versions came out.\n Expect the same for the this book edition.\n

              \n
            • \n\n
            • \n

              I heard Ember is so hard. Will this book help me understand it?

              \n

              \n I think there are a handful of key concepts in Ember.js\n that you need to understand to master it (probably the main\n one among these is routing). Once you understand these,\n Ember is not that hard. The intention of the book is\n to introduce concepts by way of building an actual\n application, so you see them applied in practice right away.\n That also helps the learning process. I also encourage you\n to work through the book as you read it, since that makes\n things sink in even deeper. You have access to the code\n repository if you have purchased the middle- or\n high-tier package. If I failed to explain Ember for you, please\n send me your purchase receipt to rarwe-book@balinterdi.com\n within 60 days of purchase and I\u2019ll issue a refund.\n

              \n
            • \n\n
            • \n

              Is the book DRM protected?

              \n

              \n No, it\u2019s not. If you would like to share it with\n colleagues (or a class), please contact me at rarwe-book@balinterdi.com.

              \n
            • \n\n
            • \n

              What if I buy the book-only package and later realize I want to switch to a higher package?

              \n

              No problem! Just send me your purchase receipt to rarwe-book@balinterdi.com, and I will upgrade you for the difference between the package prices.

              \n
            • \n
            \n
            \n
            \n
            \n
            \n \n\n \n
            \n
            \n
            \n
            \n
            \n \"60-day\n
            \n\n \n
            \n
            \n

            Choose a Package

            \n
            \n
            \n
            \n
            \n\n
            \n
            \n
              \n
            • \n

              Smoke on the Water

              \n
              \n
              \n $39\n
              \n
              \n
                \n
              • The book with 18 chapters
              • \n
              • Free book updates until 3.0
              • \n
              • $25 credit for hack.hands()
              • \n
              • 60-days money back guarantee
              • \n
              • Rock & Roll!
              • \n
              • \n
              • \n
              \n
              \n Buy Now\n
              \n
            • \n
            • \n

              Light my Fire

              \n
              \n
              \n $59\n
              \n
              \n
                \n
              • The book with 18 chapters
              • \n
              • Free book updates until 3.0
              • \n
              • Access to the code
              • \n
              • $25 credit for hack.hands()
              • \n
              • 60-days money back guarantee
              • \n
              • Rock & Roll!
              • \n
              • \n
              \n
              \n Buy Now\n
              \n
            • \n
            • \n

              Stairway to Heaven

              \n
              \n
              \n $89\n
              \n
              \n
                \n
              • The book with 18 chapters
              • \n
              • Free book updates until 3.0
              • \n
              • Access to the code
              • \n
              • 4 Screencasts
              • \n
              • $25 credit for hack.hands()
              • \n
              • 60-days money back guarantee
              • \n
              • Rock & Roll!
              • \n
              \n
              \n Buy Now\n
              \n
            • \n
            \n
            \n
            \n
            \n
            \n \n\n \n
            \n
            \n
            \n
            \n\n
            \n
            \n

            This book is a fabulous, approachable, foray into Emberjs that makes the learning curve much less scary. I just wish it had been available sooner for students in my previous classes.

            \n
            \n
            \n
            \n \"Matt\n
            \n
            \n — Matt Hale\n Assistant Professor at the University of Nebraska\n
            \n
            \n
            \n
            \n\n
            \n
            \n
            \n

            I\u2019ve gone through the first four chapters and I am already loving it.

            \n
            \n
            \n
            \n \"Sergio\n
            \n
            \n — Sergio Arbeo\n EmberMadrid\n
            \n
            \n
            \n
            \n
            \n
            \n
            \n \n\n \n \n \n\n \n\n \n \n \n \n\n \n \n\n\n\n"}, "files_after": {"source/_layouts/rarwe_book.html": "\n\n\n\n \n \n \n \n\n \n \n \n \n \n \n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n\n Cut your learning curve and build ambitious apps with Ember.js.\n\n \n \n \n \n \n \n \n \n \n\n \n \n \n \n \n\n\n\n
            \n\n \n
            \n
            \n\n
            \n
            \n

            The most up-to-date book to learn Ember.js

            \n
            \n Trusted by:\n \"Toptal\"\n \"Firebase\"\n \"Airpair\"\n \"Nathan\n
            \n
            \n
            \n\n
            \n
            \n
            \n \"Rock\n
            \n
            \n
            \n
            \n

            Build ambitious apps with confidence

            \n

            Ember.js is a kick-ass framework for building\n web applications. It's the only tool you need\n (on the client-side) to craft your idea into a working\n wonder. However, its strong opinions and heavy reliance of\n \u201cconvention over configuration\u201d can give developers who\n are new to the framework a hard time figuring out how\n Ember wants them to do things.

            \n\n

            This book helps to overcome that initial\n frustration, and help you grok Ember a lot\n faster, by pinpointing the core concepts and\n explaining them in detail. Once you understand them you\n are on your way to taming and mastering Ember.js.\n So don't fear the learning curve.

            \n\n
            \n
            \n
            \n

            This is a really great book. I think it will be very helpful to many people. I\u2019m definitely going to recommend it to beginners.

            \n
            \n
            \n
            \n \"Taras\n
            \n
            \n — Taras Mankowski\n EmberSherpa\n
            \n
            \n
            \n
            \n

            The book guides you through the steps of building a real application so that you can see how the concepts are applied in practice. You'll learn about the building blocks of Ember one by one, in a way that crushes the steep learning curve. Knowledge is dripped in slowly, chapter by chapter, to prevent you from drowning in a sea of novel information. By improving an existing and working application, you will learn more quickly and new knowledge will sink in deeper.

            \n

            Already convinced? Skip to the packages.

            \n
            \n\n
            \n
            \n
            \n
            \n \n\n \n
            \n
            \n
            \n
            \n
            \n \"Sample\n
            \n
            \n
            \n
            \n

            Want to read a sample chapter first?

            \n \n
            \n\n
            \n \n \n
            \n \n \n
            \n
            \n

            There was an error submitting your subscription. Please try again.

            \n
            \n
            \n
            \n \n \n
            \n
            \n \n \n
            \n \n We won't send you spam. Unsubscribe at any time.\n
            \n
            \n
            \n
            \n\n
            \n
            \n
            \n
            \n \n \n \n\n \n
            \n
            \n
            \n
            \n \n
            \n
            \n

            Once upon a time...

            \n
            \n
            \n
            \n\n
            \n

            \n It all started in September 2013. Having just returned from the first European\n Ember.js conference, my enthusiasm went through the roof. I wanted to spread the\n word, for people to realize how beautiful Ember is, for them to know\n that Ember.js is not that hard to learn. It's just a matter of having the core\n concepts internalized.\n

            \n

            \n So without proper equipment (and after a few episodes, with a ~$80 mic) I started producing screencasts, a series in\n which a simple application is developed step-by-step. I sent the first few to my\n subscribers and kept producing them. And people seemed to have liked them.\n

            \n\n
            \n
            \n
            \n
            \n
            \n

            Great episode! Pace and depth was perfect. Thanks for such a great webcast series!

            \n
            \n
            \n
            \n \"Curtis\n
            \n
            \n — Curtis Wallen\n
            \n
            \n
            \n
            \n\n
            \n
            \n
            \n

            I really appreciate the effort you want to put up. Just wanted to thank you for this and let you know that your video series rock!

            \n
            \n
            \n
            \n \"Antonio\n
            \n
            \n — Antonio Antillon\n
            \n
            \n
            \n
            \n
            \n
            \n\n

            \n Once the screencast series was finished, I switched to blog posts and lengthier\n articles, and in 2014 I committed to posting something of\n value each week. Then, after a long labor of (mostly) love,\n I published the 1st edition of the book in Feburary\n 2015, that used the then stable Ember version, 1.10.\n

            \n

            \n I was not done, though. As Ember made progress in a\n neck breaking pace, I kept the book up-to-date with the\n actual stable version of the framework, and adding material\n that covered the new features.\n

            \n
            \n
            \n
            \n
            \n \n\n \n
            \n
            \n
            \n
            \n \n
            \n
            \n

            Buy once, get all updates for free

            \n
            \n
            \n
            \n\n
            \n

            The first edition of this book followed Ember's journey to\n its 2.0 release. As Ember gracefully shedded old syntaxes, the\n book's content was updated not to use those syntaxes, either.\n When a new feature appeared, I added a section about it, trying\n to find a practical example for it in the application.

            \n\n

            Since Ember follows a 6-week release cycle, that meant\n frequent book updates, precisely 8 \"minor book releases\" in a\n little less than 7 months. These updates came free for all of my\n customers, no matter which package they chose. I aim to follow a\n similar path and update policy with Ember 2.x. The framework\n makes progress really fast but I'll keep in sync with the latest\n stable version of Ember and keep the content fresh. And\n free until at least the next major version.

            \n
            \n
            \n\n
            \n
            \n
            \n
            \n
            \n

            I really like it! It is super difficult to find the right balance between pacing and detail\nand put it all together in an understandable form but you pulled it off.

            \n
            \n
            \n
            \n \"Cory\n
            \n
            \n — Cory Forsyth\n 201 Created\n
            \n
            \n
            \n
            \n\n
            \n
            \n
            \n

            Just wanted to say thanks for the ongoing updates of the book. Even after finishing the book, it\u2019s becoming a great reference for the changes Ember is going through (even more so than the official docs).

            \n
            \n
            \n
            \n \"Gabriel\n
            \n
            \n — Gabriel Rotbart\n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n \n\n \n
            \n
            \n
            \n
            \n
            \n
            \n

            Table of Contents

            \n
            \n
            \n
            \n
            \n\n
            \n
            \n
            \n \n
            \n
              \n
            • Preface\n\n
                \n
              • My love affair with Ember.js
              • \n
              • Acknowledgements
              • \n
            • \n
            • Introduction to Ember.js\n\n
                \n
              • Why Ember.js
              • \n
              • Backstage - Dial M for Model
              • \n
              • About this book
              • \n
              • Is this book for you?
              • \n
              • Ambitious goal for an ambitious framework
              • \n
              • The application we are going to build
              • \n
              • Errata
              • \n
            • \n
            • Ember CLI\n\n
                \n
              • Setting up Ember CLI
              • \n
              • Creating our application
              • \n
            • \n
            • Templates and data bindings\n\n
                \n
              • The first template
              • \n
              • Showing a list of songs in the application template
              • \n
              • Backstage - Handlebar's fail-softness
              • \n
              • Backstage - ES2015 modules
              • \n
              • Backstage - Class and instance properties
              • \n
              • Adding libraries to the build
              • \n
              • Importing needed assets manually
              • \n
              • Using an Ember add-on
              • \n
              • Auto-updating templates
              • \n
            • \n
            • Routing\n\n
                \n
              • What do we want to achieve?
              • \n
              • New styles
              • \n
              • Routes set up data
              • \n
              • Backstage - A word about generated test files
              • \n
              • Moving around with link-to
              • \n
              • Using the model property
              • \n
              • Showing a list of bands
              • \n
              • Showing a list of songs
              • \n
            • \n
            • Nested routes\n\n
                \n
              • Defining the nested routes
              • \n
              • Full route names
              • \n
              • Backstage - Resource routes
              • \n
              • Stepping through a router transition
              • \n
              • Backstage - Computed properties
              • \n
              • Nested templates
              • \n
              • {{outlet}} is the default template for routes
              • \n
            • \n
            • Actions\n\n
                \n
              • Extracting model classes
              • \n
              • The class-level mutable attribute property
              • \n
              • Capturing the event
              • \n
              • Turning event into intent
              • \n
            • \n
            • Components\n\n
                \n
              • The idea behind components
              • \n
              • Component specification
              • \n
              • Defining the component's properties
              • \n
              • Using the component
              • \n
              • Displaying the rating with stars
              • \n
              • Backstage - The default component template
              • \n
              • Backstage - On the utility of explicit dependency definitions
              • \n
              • Speaking to the outside world through actions
              • \n
              • Closure actions
              • \n
            • \n
            • Controllers\n\n
                \n
              • Preventing the creation of bands without a name
              • \n
              • Smooth UI flows
              • \n
              • Going to the band page after it is created
              • \n
              • Nudging the user to create the first song
              • \n
              • Showing the text field when the call to action has been acted on
              • \n
              • Creating new bands and songs by pressing return
              • \n
              • Backstage - Where to handle actions?
              • \n
            • \n
            • Advanced routing\n\n
                \n
              • Route hooks
              • \n
              • Route actions
              • \n
              • Redirection
              • \n
              • Redirecting before the model is known
              • \n
              • Redirecting after the model is known
              • \n
              • Backstage - Skipping model resolution
              • \n
              • Leaving routes and arriving at them
              • \n
              • Setting descriptive page titles
              • \n
              • Warning about losing data
              • \n
            • \n
            • Talking to a backend - with Ember Data\n\n
                \n
              • The concept behind Ember Data
              • \n
              • The API
              • \n
              • Model classes
              • \n
              • Transforming the app to use Ember Data
              • \n
              • Loading bands
              • \n
              • Fetching a single band
              • \n
              • Loading songs for a band
              • \n
              • Creating a band
              • \n
              • Updating a band's description
              • \n
              • Updating song ratings
              • \n
              • Backstage - Promises
              • \n
            • \n
            • Testing\n\n
                \n
              • Clarifying the vocabulary
              • \n
              • Acceptance tests
              • \n
              • To mock or not to mock?
              • \n
              • Unit tests
              • \n
              • Integration tests
              • \n
              • Adding an acceptance test
              • \n
              • Analyzing an Ember acceptance test
              • \n
              • Making the first test pass
              • \n
              • Safeguarding critical user scenarios
              • \n
              • Creating a band
              • \n
              • Creating a song
              • \n
              • Backstage \u2013 Fake synchronous tests
              • \n
              • Writing your own test helpers
              • \n
              • Registering a synchronous helper
              • \n
              • Registering an async helper
              • \n
              • Refactoring stubs
              • \n
              • Integration tests in Ember
              • \n
              • Unit tests in Ember
              • \n
            • \n
            • Sorting and searching with query parameters\n\n
                \n
              • Query parameters
              • \n
              • Query parameters in Ember
              • \n
              • Sorting the list of songs
              • \n
              • Sorting an array of items
              • \n
              • Backstage - Computed property macros
              • \n
              • Changing the sorting criteria
              • \n
              • Filtering songs by a search term
              • \n
              • Adding a dash of query parameters
              • \n
              • Using links instead of buttons
              • \n
              • Taking a look at what we made
              • \n
            • \n
            • Loading and error routes\n\n
                \n
              • Loading routes
              • \n
              • Backstage - Rendering the loading template is an overridable default
              • \n
              • Error routes
              • \n
            • \n
            • Helpers\n\n
                \n
              • About helpers
              • \n
              • Capitalizing each word of a name
              • \n
              • Using it in templates, or elsewhere
              • \n
              • Use dashed names for helpers
              • \n
            • \n
            • Animations\n\n
                \n
              • Setting up liquid-fire
              • \n
              • liquid-fire architecture
              • \n
              • Transition map
              • \n
              • Transition functions
              • \n
              • Template helpers
              • \n
              • Putting it all together
              • \n
              • Debugging transitions
              • \n
              • Animate moving between routes
              • \n
              • Adding a custom animation
              • \n
              • Animate a value change
              • \n
            • \n
            • Making an Ember addon\n\n
                \n
              • What is an Ember addon?
              • \n
              • Developing the addon
              • \n
              • Integrating our addon into our app
              • \n
              • Adding a block form
              • \n
              • Customizing the star-rating component's look and behavior
              • \n
              • Publishing the addon
              • \n
              • Using a published addon from the app
              • \n
            • \n
            • ES2015 - Writing modern JavaScript\n\n
                \n
              • Modernizing the app
              • \n
              • Modules
              • \n
              • Template strings
              • \n
              • Short-hand method definitions
              • \n
              • Replacing var (let & const)
              • \n
              • Arrow functions
              • \n
              • Destructuring
              • \n
              • Other useful ES2015 features
              • \n
              • Backstage - ember-watson
              • \n
              • Computed property macros
              • \n
            • \n
            • Deployment\n\n
                \n
              • FrontPage
              • \n
              • Heroku
              • \n
              • ember-cli-deploy
              • \n
            • \n
            • Afterword\n\n
                \n
              • Your journey with Ember.js
              • \n
            • \n
            \n\n
            \n\n
            \n
            \n
            \n
            \n
            \n
            \n
            \n \n\n \n
            \n
            \n
            \n
            \n \"Balint\n
            \n\n
            \n

            About me

            \n

            Hello there, I'm Balint Erdi.

            \n

            \n I have a long history of building web applications and have mostly been a back-end\n guy.\n

            \n

            \n On a grey, chilly February day in 2013 that I\u2019ll never forget (maybe it was\n January?) I got acquainted with Ember.js. Ember.js made that day bright and the\n ones that came after that. After learning the ropes I shifted gears and have been\n proselytizing for Ember since last summer.\n

            \n

            \n I gave a beginner\u2019s workshop at Eurucamp, and held presentations at Arrrrcamp, The Geek Gathering and EmberFest. I started an Ember.js mailing list, made an introductory\n screencast series and have been sending Ember content to my dear subscribers on a\n weekly basis. I have also written guest articles for Safari Books Online, Firebase\n and Toptal.\n

            \n

            \n I guess you could say I\u2019m pretty passionate about Ember.\n

            \n

            \n Oh, and I love rock & roll, obviously.\n

            \n
            \n
            \n
            \n
            \n \n\n \n
            \n
            \n
            \n
            \n \n
            \n
            \n

            Bonus: Exclusive hack.hands() deal

            \n
            \n
            \n
            \n
            \n

            \n hack.hands()\n is your SOS button for live programming support, available 24/7. hack.hands() instantly connects developers with a network of expert programmers at the click of a button. Never get stuck, learn more and keep coding!\n If you buy any package, you will receive $25 to spend on their platform that you can use to get your Ember project unstuck.\n

            \n
            \n
            \n\n
            \n
            \n
            \n
            \n
            \n

            Even though I have worked with Ember for the past 6 months, the book helped clarify a lot of things, especially new features and their deprecated counterparts. Such a great book, and looking forward to the second one!

            \n
            \n
            \n
            \n \"David\n
            \n
            \n — David Tang\n
            \n
            \n
            \n
            \n\n
            \n
            \n
            \n

            There is almost nowhere to go to get a good grounding in Ember. In months of searching this is the best resource that exists... so much so I'm going to try to get a few copies sorted out for my team at work. Thanks Balint!

            \n
            \n
            \n
            \n \"\n
            \n
            \n — Andy Davison\n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n \n\n \n
            \n
            \n
            \n
            \n
            \n

            Stairway to Heaven Package

            \n
            \n
            \n
            \n\n
            \n
            \n

            \n The path to Ember.js bliss, this package contains all you need to take your Ember.js skills to the next level. It contains:

            \n \"Stairway\n

            \n
            \n
            \n
            \n\n
            \n
            \n
            \n
            \n
            \n

            This was a truly great series of screencasts. Very, very well done. Simple enough while not being simplistic.

            \n
            \n
            \n
            \n \"Claude\n
            \n
            \n — Claude Pr\u00e9court\n
            \n
            \n
            \n
            \n\n
            \n
            \n
            \n

            Nice work with these Ember tutorials. You're doing a really nice thing for the community.

            \n
            \n
            \n
            \n \"Steven\n
            \n
            \n — Steven Kane\n
            \n
            \n
            \n
            \n
            \n
            \n
            \n \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n \"The\n
            \n

            The book

            \n 18 chapters\n

            This is what you absolutely need to get up & running with Ember.js. Comes in pdf, mobi and epub formats for your reading pleasure.

            \n
            \n
            \n\n
            \n
            \n
            \n \"Code\"\n
            \n

            Access to the code

            \n All of the source code\n

            in the application so that you can check how the app looks & works at each step. Or tweak it to your liking.

            \n
            \n
            \n\n
            \n
            \n
            \n \"Screencast\"\n
            \n

            Screencasts

            \n 4 screencasts\n

            They run around 10 minutes each and cover the following,\n advanced topics: Pods in Ember CLI, Animations,\n Authentication & Authorization, and ES2015 &\n computed macros.

            \n
            \n
            \n\n
            \n
            \n
            \n \"Rock\n
            \n

            Rock & More

            \n Includes\n

            $25 credit on the hack.hands() platform

            \n

            60-day refund guarantee

            \n
            \n
            \n
            \n
            \n\n
            \n \n
            \n\n
            \n
            \n\n \n
            \n
            \n
            \n
            \n
            \n

            Light my Fire Package

            \n
            \n
            \n
            \n\n
            \n
            \n

            \n Take out the screencasts and you have this smaller package that will still ignite your Ember rocket. It contains:\n \"Light\n

            \n
            \n
            \n
            \n
            \n\n
            \n
            \n
            \n
            \n
            \n
            \n
            \n \"The\n
            \n

            The book

            \n 18 chapters\n

            This is what you absolutely need to get up & running with Ember.js. Comes in pdf, mobi and epub formats for your reading pleasure.

            \n
            \n
            \n\n
            \n
            \n
            \n \"Code\"\n
            \n

            Access to the code

            \n All of the source code\n

            in the application so that you can check how the app looks & works at each step. Or tweak it to your liking.

            \n
            \n
            \n\n
            \n
            \n
            \n \"Rock\n
            \n

            Rock & More

            \n Includes\n

            $25 credit on the hack.hands() platform

            \n

            60-day refund guarantee

            \n
            \n
            \n
            \n
            \n\n
            \n \n
            \n
            \n
            \n \n\n \n
            \n
            \n
            \n
            \n
            \n

            Smoke on the Water Package

            \n
            \n
            \n
            \n\n
            \n
            \n

            \n Basic but still solid, as the name suggests. This package inclues the book and the hack.hands() deal. It contains:\n

            \n \"Smoke\n

            \n
            \n
            \n
            \n
            \n\n
            \n
            \n
            \n
            \n
            \n
            \n
            \n \"The\n
            \n

            The book

            \n 18 chapters\n

            This is what you absolutely need to get up & running with Ember.js. Comes in pdf, mobi and epub formats for your reading pleasure.

            \n
            \n
            \n\n
            \n
            \n
            \n \"Rock\n
            \n

            Rock & More

            \n Includes\n

            $25 credit on the hack.hands() platform

            \n

            60-day refund guarantee

            \n
            \n
            \n\n
            \n
            \n\n
            \n \n
            \n\n
            \n
            \n
            \n
            \n
            \n

            I\u2019m REALLY enjoying the book and find it to be very thorough and informative. You\u2019ve done a great job of answering questions I had about various concepts that were not detailed clearly elsewhere.

            \n
            \n
            \n
            \n \"Bill\n
            \n
            \n — Bill White\n Data Visualizations at www.bildwhite.com\n
            \n
            \n
            \n
            \n\n
            \n
            \n
            \n

            It\u2019s been an invaluable resource in learning Ember and one I would recommend to any developer wanting to get started with the framework.

            \n
            \n
            \n
            \n \"Jonathan\n
            \n
            \n — Jonathan Rowley\n
            \n
            \n
            \n
            \n
            \n
            \n
            \n
            \n \n\n \n
            \n
            \n
            \n
            \n \n
            \n
            \n

            Hmm, I\u2019m not sure...

            \n
            \n
            \n
            \n\n
            \n
              \n
            • \n

              Is the book ready for Ember 2?

              \n

              \n Yes, it is! The app in the book runs Ember (and Ember Data)\n 2 and does not use any deprecated stuff.\n

              \n
            • \n\n
            • \n

              Is this book for me?

              \n

              \n The book starts from the very basics (installing\n ember-cli, writing your first template, etc.) so if you\n completely get Ember, this book is probably not for you. If\n you are just starting out (or about to) or want to\n understand fundamental concepts in Ember, the book is\n definitely for you.\n

              \n
            • \n\n
            • \n

              What if I don't like the book?

              \n

              \n I offer a 60-day moneyback guarantee. No strings attached,\n just send your purchase receipt (or email address) to\n rarwe-book@balinterdi.com or answer to the welcome email\n that you received when you purchased.\n

              \n
            • \n\n
            • \n

              Everything is changing so fast; won't the content be outdated by next week?

              \n

              \n As Ember.js moves towards 3.0, I will keep updating the\n content of the book so that it stays void of deprecation\n warnings and does not promote practices that are no longer\n considered idiomatic. For the 1st edition of the book,\n I released an update once about every four weeks,\n more often than Ember stable versions came out.\n Expect the same for the this book edition.\n

              \n
            • \n\n
            • \n

              I heard Ember is so hard. Will this book help me understand it?

              \n

              \n I think there are a handful of key concepts in Ember.js\n that you need to understand to master it (probably the main\n one among these is routing). Once you understand these,\n Ember is not that hard. The intention of the book is\n to introduce concepts by way of building an actual\n application, so you see them applied in practice right away.\n That also helps the learning process. I also encourage you\n to work through the book as you read it, since that makes\n things sink in even deeper. You have access to the code\n repository if you have purchased the middle- or\n high-tier package. If I failed to explain Ember for you, please\n send me your purchase receipt to rarwe-book@balinterdi.com\n within 60 days of purchase and I\u2019ll issue a refund.\n

              \n
            • \n\n
            • \n

              Is the book DRM protected?

              \n

              \n No, it\u2019s not. If you would like to share it with\n colleagues (or a class), please contact me at rarwe-book@balinterdi.com.

              \n
            • \n\n
            • \n

              What if I buy the book-only package and later realize I want to switch to a higher package?

              \n

              No problem! Just send me your purchase receipt to rarwe-book@balinterdi.com, and I will upgrade you for the difference between the package prices.

              \n
            • \n
            \n
            \n
            \n
            \n
            \n \n\n \n
            \n
            \n
            \n
            \n
            \n \"60-day\n
            \n\n \n
            \n
            \n

            Choose a Package

            \n
            \n
            \n
            \n
            \n\n
            \n
            \n
              \n
            • \n

              Smoke on the Water

              \n
              \n
              \n $39\n
              \n
              \n
                \n
              • The book with 18 chapters
              • \n
              • Free book updates until 3.0
              • \n
              • $25 credit for hack.hands()
              • \n
              • 60-days money back guarantee
              • \n
              • Rock & Roll!
              • \n
              • \n
              • \n
              \n
              \n Buy Now\n
              \n
            • \n
            • \n

              Light my Fire

              \n
              \n
              \n $59\n
              \n
              \n
                \n
              • The book with 18 chapters
              • \n
              • Free book updates until 3.0
              • \n
              • Access to the code
              • \n
              • $25 credit for hack.hands()
              • \n
              • 60-days money back guarantee
              • \n
              • Rock & Roll!
              • \n
              • \n
              \n
              \n Buy Now\n
              \n
            • \n
            • \n

              Stairway to Heaven

              \n
              \n
              \n $89\n
              \n
              \n
                \n
              • The book with 18 chapters
              • \n
              • Free book updates until 3.0
              • \n
              • Access to the code
              • \n
              • 4 Screencasts
              • \n
              • $25 credit for hack.hands()
              • \n
              • 60-days money back guarantee
              • \n
              • Rock & Roll!
              • \n
              \n
              \n Buy Now\n
              \n
            • \n
            \n
            \n
            \n
            \n
            \n \n\n \n
            \n
            \n
            \n
            \n\n
            \n
            \n

            This book is a fabulous, approachable, foray into Emberjs that makes the learning curve much less scary. I just wish it had been available sooner for students in my previous classes.

            \n
            \n
            \n
            \n \"Matt\n
            \n
            \n — Matt Hale\n Assistant Professor at the University of Nebraska\n
            \n
            \n
            \n
            \n\n
            \n
            \n
            \n

            I\u2019ve gone through the first four chapters and I am already loving it.

            \n
            \n
            \n
            \n \"Sergio\n
            \n
            \n — Sergio Arbeo\n EmberMadrid\n
            \n
            \n
            \n
            \n
            \n
            \n
            \n \n\n \n \n \n\n \n\n \n \n \n \n\n \n \n\n\n\n"}} +{"repo": "sebastianbergmann/phpcpd", "pr_number": 206, "title": "Fixing regressed bug-fix for Issue#147", "state": "closed", "merged_at": null, "additions": 1, "deletions": 1, "files_changed": ["src/CLI/Application.php"], "files_before": {"src/CLI/Application.php": "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\nnamespace SebastianBergmann\\PHPCPD;\n\nuse const PHP_EOL;\nuse function count;\nuse function printf;\nuse SebastianBergmann\\FileIterator\\Facade;\nuse SebastianBergmann\\PHPCPD\\Detector\\Detector;\nuse SebastianBergmann\\PHPCPD\\Detector\\Strategy\\AbstractStrategy;\nuse SebastianBergmann\\PHPCPD\\Detector\\Strategy\\DefaultStrategy;\nuse SebastianBergmann\\PHPCPD\\Detector\\Strategy\\StrategyConfiguration;\nuse SebastianBergmann\\PHPCPD\\Detector\\Strategy\\SuffixTreeStrategy;\nuse SebastianBergmann\\PHPCPD\\Log\\PMD;\nuse SebastianBergmann\\PHPCPD\\Log\\Text;\nuse SebastianBergmann\\Timer\\ResourceUsageFormatter;\nuse SebastianBergmann\\Timer\\Timer;\nuse SebastianBergmann\\Version;\n\nfinal class Application\n{\n private const VERSION = '7.0';\n\n public function run(array $argv): int\n {\n $this->printVersion();\n\n try {\n $arguments = (new ArgumentsBuilder)->build($argv);\n } catch (Exception $e) {\n print PHP_EOL . $e->getMessage() . PHP_EOL;\n\n return 1;\n }\n\n if ($arguments->version()) {\n return 0;\n }\n\n print PHP_EOL;\n\n if ($arguments->help()) {\n $this->help();\n\n return 0;\n }\n\n $files = (new Facade)->getFilesAsArray(\n $arguments->directories(),\n $arguments->suffixes(),\n '',\n $arguments->exclude()\n );\n\n if (empty($files)) {\n print 'No files found to scan' . PHP_EOL;\n\n return 1;\n }\n\n $config = new StrategyConfiguration($arguments);\n\n try {\n $strategy = $this->pickStrategy($arguments->algorithm(), $config);\n } catch (InvalidStrategyException $e) {\n print $e->getMessage() . PHP_EOL;\n\n return 1;\n }\n\n $timer = new Timer;\n $timer->start();\n\n $clones = (new Detector($strategy))->copyPasteDetection($files);\n\n (new Text)->printResult($clones, $arguments->verbose());\n\n if ($arguments->pmdCpdXmlLogfile()) {\n (new PMD($arguments->pmdCpdXmlLogfile()))->processClones($clones);\n }\n\n print (new ResourceUsageFormatter)->resourceUsage($timer->stop()) . PHP_EOL;\n\n return count($clones) > 0 ? 1 : 0;\n }\n\n private function printVersion(): void\n {\n printf(\n 'phpcpd %s by Sebastian Bergmann.' . PHP_EOL,\n (new Version(self::VERSION, dirname(__DIR__)))->getVersion()\n );\n }\n\n /**\n * @throws InvalidStrategyException\n */\n private function pickStrategy(?string $algorithm, StrategyConfiguration $config): AbstractStrategy\n {\n return match ($algorithm) {\n null, 'rabin-karp' => new DefaultStrategy($config),\n 'suffixtree' => new SuffixTreeStrategy($config),\n default => throw new InvalidStrategyException('Unsupported algorithm: ' . $algorithm),\n };\n }\n\n private function help(): void\n {\n print <<<'EOT'\nUsage:\n phpcpd [options] \n\nOptions for selecting files:\n\n --suffix Include files with names ending in in the analysis\n (default: .php; can be given multiple times)\n --exclude Exclude files with in their path from the analysis\n (can be given multiple times)\n\nOptions for analysing files:\n\n --fuzzy Fuzz variable names\n --min-lines Minimum number of identical lines (default: 5)\n --min-tokens Minimum number of identical tokens (default: 70)\n --algorithm Select which algorithm to use ('rabin-karp' (default) or 'suffixtree')\n --edit-distance Distance in number of edits between two clones (only for suffixtree; default: 5)\n --head-equality Minimum equality at start of clone (only for suffixtree; default 10)\n\nOptions for report generation:\n\n --log-pmd Write log in PMD-CPD XML format to \n\nEOT;\n }\n}\n"}, "files_after": {"src/CLI/Application.php": "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\nnamespace SebastianBergmann\\PHPCPD;\n\nuse const PHP_EOL;\nuse function count;\nuse function printf;\nuse SebastianBergmann\\FileIterator\\Facade;\nuse SebastianBergmann\\PHPCPD\\Detector\\Detector;\nuse SebastianBergmann\\PHPCPD\\Detector\\Strategy\\AbstractStrategy;\nuse SebastianBergmann\\PHPCPD\\Detector\\Strategy\\DefaultStrategy;\nuse SebastianBergmann\\PHPCPD\\Detector\\Strategy\\StrategyConfiguration;\nuse SebastianBergmann\\PHPCPD\\Detector\\Strategy\\SuffixTreeStrategy;\nuse SebastianBergmann\\PHPCPD\\Log\\PMD;\nuse SebastianBergmann\\PHPCPD\\Log\\Text;\nuse SebastianBergmann\\Timer\\ResourceUsageFormatter;\nuse SebastianBergmann\\Timer\\Timer;\nuse SebastianBergmann\\Version;\n\nfinal class Application\n{\n private const VERSION = '7.0';\n\n public function run(array $argv): int\n {\n $this->printVersion();\n\n try {\n $arguments = (new ArgumentsBuilder)->build($argv);\n } catch (Exception $e) {\n print PHP_EOL . $e->getMessage() . PHP_EOL;\n\n return 1;\n }\n\n if ($arguments->version()) {\n return 0;\n }\n\n print PHP_EOL;\n\n if ($arguments->help()) {\n $this->help();\n\n return 0;\n }\n\n $files = (new Facade)->getFilesAsArray(\n $arguments->directories(),\n $arguments->suffixes(),\n '',\n $arguments->exclude()\n );\n\n if (empty($files)) {\n print 'No files found to scan' . PHP_EOL;\n\n return 0;\n }\n\n $config = new StrategyConfiguration($arguments);\n\n try {\n $strategy = $this->pickStrategy($arguments->algorithm(), $config);\n } catch (InvalidStrategyException $e) {\n print $e->getMessage() . PHP_EOL;\n\n return 1;\n }\n\n $timer = new Timer;\n $timer->start();\n\n $clones = (new Detector($strategy))->copyPasteDetection($files);\n\n (new Text)->printResult($clones, $arguments->verbose());\n\n if ($arguments->pmdCpdXmlLogfile()) {\n (new PMD($arguments->pmdCpdXmlLogfile()))->processClones($clones);\n }\n\n print (new ResourceUsageFormatter)->resourceUsage($timer->stop()) . PHP_EOL;\n\n return count($clones) > 0 ? 1 : 0;\n }\n\n private function printVersion(): void\n {\n printf(\n 'phpcpd %s by Sebastian Bergmann.' . PHP_EOL,\n (new Version(self::VERSION, dirname(__DIR__)))->getVersion()\n );\n }\n\n /**\n * @throws InvalidStrategyException\n */\n private function pickStrategy(?string $algorithm, StrategyConfiguration $config): AbstractStrategy\n {\n return match ($algorithm) {\n null, 'rabin-karp' => new DefaultStrategy($config),\n 'suffixtree' => new SuffixTreeStrategy($config),\n default => throw new InvalidStrategyException('Unsupported algorithm: ' . $algorithm),\n };\n }\n\n private function help(): void\n {\n print <<<'EOT'\nUsage:\n phpcpd [options] \n\nOptions for selecting files:\n\n --suffix Include files with names ending in in the analysis\n (default: .php; can be given multiple times)\n --exclude Exclude files with in their path from the analysis\n (can be given multiple times)\n\nOptions for analysing files:\n\n --fuzzy Fuzz variable names\n --min-lines Minimum number of identical lines (default: 5)\n --min-tokens Minimum number of identical tokens (default: 70)\n --algorithm Select which algorithm to use ('rabin-karp' (default) or 'suffixtree')\n --edit-distance Distance in number of edits between two clones (only for suffixtree; default: 5)\n --head-equality Minimum equality at start of clone (only for suffixtree; default 10)\n\nOptions for report generation:\n\n --log-pmd Write log in PMD-CPD XML format to \n\nEOT;\n }\n}\n"}} +{"repo": "jezdez/limechat-whisper", "pr_number": 1, "title": "fix display of #channame or www.link.com", "state": "closed", "merged_at": "2012-08-03T20:35:28Z", "additions": 1, "deletions": 1, "files_changed": ["Whisper.css"], "files_before": {"Whisper.css": "html.normal {\n color: #4b4b4b;\n background-color: white;\n font: 12px/1.3em 'Lucida Grande' sans-serif;\n margin: 0;\n padding: 0;\n}\n\nbody.normal .sender[type=myself]:hover:before {\n content: \"\u2022 \";\n color: #bebebe;\n}\n\nbody.normal a img {\n border: 0;\n}\n\nbody.normal img {\n display: block;\n padding-top: 5px;\n padding-bottom: 5px;\n padding-left: 8px;\n max-width: 95%;\n}\n\nbody.normal a:link, a:visited, a:hover, a:active {\n color: #184586;\n}\n\nbody.normal .text span {\n display: block;\n}\n\nbody.normal .line {\n padding: 0;\n margin: 0;\n background-color: #eee;\n line-height: 130%;\n}\n\nbody.normal .event {\n padding: 0.2em;\n margin: 0;\n color: #363636;\n background: #e5edf7;\n}\n\nbody.normal .event + .event {\n border-top: #fff 1px solid;\n}\n\nbody.normal .text span.message {\n border-bottom: #efefef 1px solid;\n}\n\nbody.normal .text + .event {\n margin-top: -1px;\n}\n\nbody.normal .sender {\n padding: 0.4em 0;\n float: left;\n text-align: right;\n font-weight: bold;\n width: 130px;\n overflow: hidden;\n}\n\nbody.normal .line .message {\n margin: 0 0 0 134px;\n padding: 0.4em;\n color: #303030;\n border-left: 1px solid #dcdcdc;\n background-color: #fff;\n}\n\nbody.normal .event .message {\n margin: 0;\n padding: 0.4em;\n border: 0;\n color: #a6b9c0;\n background: none;\n font: bold 11px \"Helvetica Neue\", Arial, Helvetica, sans-serif;\n}\n\nbody.normal .line .time {\n float: right;\n margin-right: 6px;\n margin-top: 5px;\n margin-left: 4px;\n color: #999;\n font: bold 11px \"Helvetica Neue\", Arial, Helvetica, sans-serif;\n}\n\nbody.normal .line .place {\n display: block;\n color: #999;\n margin: 0;\n font-size: 12px;\n}\n\nbody.normal .event .time {\n margin: 1px 3px;\n float: right;\n text-align: right;\n font-size: 11px;\n color: #a6b9c0;\n}\n\nbody.normal .line[highlight=true] span.message {\n background-color: #ffc;\n}\n\nbody.normal .member {\n text-decoration: none !important;\n color: inherit !important;\n}\n\nbody.normal .member:hover {\n text-decoration: underline;\n}\n\nbody.normal {\n \n}\n\nbody.console {\n \n}\n\nbody[type=channel] {\n \n}\n\nbody[type=talk] {\n \n}\n\nbody[type=console] {\n \n}\n\nbody.normal hr {\n margin: 0;\n padding: 2px;\n border: none;\n background-color: #d33b54;\n height: 2px;\n text-align: center;\n}\n\na {\n \n}\n\n/* lines */\n\n.line[alternate=even] {\n \n}\n\n.line[alternate=odd] {\n \n}\n\n.line[type=action] .sender:before {\n content: \"\";\n}\n\nbody.normal .line[type=action] .sender {\n font-style: italic;\n}\n\nbody.normal .line[type=action] .message {\n background: #eee;\n border-left: none;\n margin: 0 0 0 130px;\n}\n\nbody.normal .url {\n word-break: break-all;\n}\n\nbody.normal .address {\n text-decoration: underline;\n word-break: break-all;\n}\n\nbody.normal .highlight {\n color: #d33b54;\n font-weight: bold;\n}\n\n/* nickname for text messages */\n\nbody.normal .sender[type=myself] {\n color: #333;\n}\n\nbody.normal .sender[type=normal] {\n color: #333;\n}\n\nbody.normal .sender[type=normal][colornumber='0'] {\n \n}\n\nbody.normal .sender[type=normal][colornumber='1'] {\n \n}\n\nbody.normal .sender[type=normal][colornumber='2'] {\n \n}\n\nbody.normal .sender[type=normal][colornumber='3'] {\n \n}\n\nbody.normal .sender[type=normal][colornumber='4'] {\n \n}\n\nbody.normal .sender[type=normal][colornumber='5'] {\n \n}\n\nbody.normal .sender[type=normal][colornumber='6'] {\n \n}\n\nbody.normal .sender[type=normal][colornumber='7'] {\n \n}\n\nbody.normal .sender[type=normal][colornumber='8'] {\n \n}\n\nbody.normal .sender[type=normal][colornumber='9'] {\n \n}\n\nbody.normal .sender[type=normal][colornumber='10'] {\n \n}\n\nbody.normal .sender[type=normal][colornumber='11'] {\n \n}\n\nbody.normal .sender[type=normal][colornumber='12'] {\n \n}\n\nbody.normal .sender[type=normal][colornumber='13'] {\n \n}\n\nbody.normal .sender[type=normal][colornumber='14'] {\n \n}\n\nbody.normal .sender[type=normal][colornumber='15'] {\n \n}\n\n/* message body */\n\nbody.normal .message[type=system] {\n color: #303030;\n}\n\nbody.normal .message[type=error] {\n color: #d14025;\n font-weight: bold;\n}\n\nbody.normal .message[type=reply] {\n color: #a6b9c0;\n}\n\nbody.normal .message[type=error_reply] {\n color: #d33b54;\n}\n\nbody.normal .message[type=dcc_send_send] {\n color: #a6b9c0;\n}\n\nbody.normal .message[type=dcc_send_receive] {\n color: #153b7c;\n}\n\nbody.normal .message[type=privmsg] {\n \n}\n\nbody.normal .message[type=notice] {\n color: #888;\n}\n\nbody.normal .message[type=action] {\n color: #303030;\n font-style: italic;\n font-weight: bold;\n}\n\nbody.normal .message[type=join] {\n color: #a6b9c0;\n}\n\nbody.normal .message[type=part] {\n color: #a6b9c0;\n}\n\nbody.normal .message[type=kick] {\n color: #303030;\n}\n\nbody.normal .message[type=quit] {\n color: #a6b9c0;\n}\n\nbody.normal .message[type=kill] {\n color: #a6b9c0;\n}\n\nbody.normal .message[type=nick] {\n color: #a6b9c0;\n}\n\nbody.normal .message[type=mode] {\n color: #a6b9c0;\n}\n\nbody.normal .message[type=topic] {\n color: #a6b9c0;\n}\n\nbody.normal .message[type=invite] {\n color: #a6b9c0;\n}\n\nbody.normal .message[type=wallops] {\n color: #a6b9c0;\n}\n\nbody.normal .message[type=debug_send] {\n color: #aaa;\n}\n\nbody.normal .message[type=debug_receive] {\n color: #444;\n}"}, "files_after": {"Whisper.css": "html.normal {\n color: #4b4b4b;\n background-color: white;\n font: 12px/1.3em 'Lucida Grande' sans-serif;\n margin: 0;\n padding: 0;\n}\n\nbody.normal .sender[type=myself]:hover:before {\n content: \"\u2022 \";\n color: #bebebe;\n}\n\nbody.normal a img {\n border: 0;\n}\n\nbody.normal img {\n display: block;\n padding-top: 5px;\n padding-bottom: 5px;\n padding-left: 8px;\n max-width: 95%;\n}\n\nbody.normal a:link, a:visited, a:hover, a:active {\n color: #184586;\n}\n\nbody.normal .text > span {\n display: block;\n}\n\nbody.normal .line {\n padding: 0;\n margin: 0;\n background-color: #eee;\n line-height: 130%;\n}\n\nbody.normal .event {\n padding: 0.2em;\n margin: 0;\n color: #363636;\n background: #e5edf7;\n}\n\nbody.normal .event + .event {\n border-top: #fff 1px solid;\n}\n\nbody.normal .text span.message {\n border-bottom: #efefef 1px solid;\n}\n\nbody.normal .text + .event {\n margin-top: -1px;\n}\n\nbody.normal .sender {\n padding: 0.4em 0;\n float: left;\n text-align: right;\n font-weight: bold;\n width: 130px;\n overflow: hidden;\n}\n\nbody.normal .line .message {\n margin: 0 0 0 134px;\n padding: 0.4em;\n color: #303030;\n border-left: 1px solid #dcdcdc;\n background-color: #fff;\n}\n\nbody.normal .event .message {\n margin: 0;\n padding: 0.4em;\n border: 0;\n color: #a6b9c0;\n background: none;\n font: bold 11px \"Helvetica Neue\", Arial, Helvetica, sans-serif;\n}\n\nbody.normal .line .time {\n float: right;\n margin-right: 6px;\n margin-top: 5px;\n margin-left: 4px;\n color: #999;\n font: bold 11px \"Helvetica Neue\", Arial, Helvetica, sans-serif;\n}\n\nbody.normal .line .place {\n display: block;\n color: #999;\n margin: 0;\n font-size: 12px;\n}\n\nbody.normal .event .time {\n margin: 1px 3px;\n float: right;\n text-align: right;\n font-size: 11px;\n color: #a6b9c0;\n}\n\nbody.normal .line[highlight=true] span.message {\n background-color: #ffc;\n}\n\nbody.normal .member {\n text-decoration: none !important;\n color: inherit !important;\n}\n\nbody.normal .member:hover {\n text-decoration: underline;\n}\n\nbody.normal {\n \n}\n\nbody.console {\n \n}\n\nbody[type=channel] {\n \n}\n\nbody[type=talk] {\n \n}\n\nbody[type=console] {\n \n}\n\nbody.normal hr {\n margin: 0;\n padding: 2px;\n border: none;\n background-color: #d33b54;\n height: 2px;\n text-align: center;\n}\n\na {\n \n}\n\n/* lines */\n\n.line[alternate=even] {\n \n}\n\n.line[alternate=odd] {\n \n}\n\n.line[type=action] .sender:before {\n content: \"\";\n}\n\nbody.normal .line[type=action] .sender {\n font-style: italic;\n}\n\nbody.normal .line[type=action] .message {\n background: #eee;\n border-left: none;\n margin: 0 0 0 130px;\n}\n\nbody.normal .url {\n word-break: break-all;\n}\n\nbody.normal .address {\n text-decoration: underline;\n word-break: break-all;\n}\n\nbody.normal .highlight {\n color: #d33b54;\n font-weight: bold;\n}\n\n/* nickname for text messages */\n\nbody.normal .sender[type=myself] {\n color: #333;\n}\n\nbody.normal .sender[type=normal] {\n color: #333;\n}\n\nbody.normal .sender[type=normal][colornumber='0'] {\n \n}\n\nbody.normal .sender[type=normal][colornumber='1'] {\n \n}\n\nbody.normal .sender[type=normal][colornumber='2'] {\n \n}\n\nbody.normal .sender[type=normal][colornumber='3'] {\n \n}\n\nbody.normal .sender[type=normal][colornumber='4'] {\n \n}\n\nbody.normal .sender[type=normal][colornumber='5'] {\n \n}\n\nbody.normal .sender[type=normal][colornumber='6'] {\n \n}\n\nbody.normal .sender[type=normal][colornumber='7'] {\n \n}\n\nbody.normal .sender[type=normal][colornumber='8'] {\n \n}\n\nbody.normal .sender[type=normal][colornumber='9'] {\n \n}\n\nbody.normal .sender[type=normal][colornumber='10'] {\n \n}\n\nbody.normal .sender[type=normal][colornumber='11'] {\n \n}\n\nbody.normal .sender[type=normal][colornumber='12'] {\n \n}\n\nbody.normal .sender[type=normal][colornumber='13'] {\n \n}\n\nbody.normal .sender[type=normal][colornumber='14'] {\n \n}\n\nbody.normal .sender[type=normal][colornumber='15'] {\n \n}\n\n/* message body */\n\nbody.normal .message[type=system] {\n color: #303030;\n}\n\nbody.normal .message[type=error] {\n color: #d14025;\n font-weight: bold;\n}\n\nbody.normal .message[type=reply] {\n color: #a6b9c0;\n}\n\nbody.normal .message[type=error_reply] {\n color: #d33b54;\n}\n\nbody.normal .message[type=dcc_send_send] {\n color: #a6b9c0;\n}\n\nbody.normal .message[type=dcc_send_receive] {\n color: #153b7c;\n}\n\nbody.normal .message[type=privmsg] {\n \n}\n\nbody.normal .message[type=notice] {\n color: #888;\n}\n\nbody.normal .message[type=action] {\n color: #303030;\n font-style: italic;\n font-weight: bold;\n}\n\nbody.normal .message[type=join] {\n color: #a6b9c0;\n}\n\nbody.normal .message[type=part] {\n color: #a6b9c0;\n}\n\nbody.normal .message[type=kick] {\n color: #303030;\n}\n\nbody.normal .message[type=quit] {\n color: #a6b9c0;\n}\n\nbody.normal .message[type=kill] {\n color: #a6b9c0;\n}\n\nbody.normal .message[type=nick] {\n color: #a6b9c0;\n}\n\nbody.normal .message[type=mode] {\n color: #a6b9c0;\n}\n\nbody.normal .message[type=topic] {\n color: #a6b9c0;\n}\n\nbody.normal .message[type=invite] {\n color: #a6b9c0;\n}\n\nbody.normal .message[type=wallops] {\n color: #a6b9c0;\n}\n\nbody.normal .message[type=debug_send] {\n color: #aaa;\n}\n\nbody.normal .message[type=debug_receive] {\n color: #444;\n}"}} +{"repo": "paveltyk/technical-test", "pr_number": 1, "title": "improve CLI", "state": "closed", "merged_at": "2010-09-30T09:53:36Z", "additions": 7, "deletions": 1, "files_changed": ["lib/editor.rb"], "files_before": {"lib/editor.rb": "require 'image'\nrequire 'readline'\n\nclass Editor\n def initialize(output)\n @output = output\n end\n def start\n @output.puts 'Welcome to Image Editor!'\n listen\n end\n\n def listen\n loop do\n cmd = Readline::readline '> ', true\n execute(cmd)\n end\n end\n\n def execute(cmd)\n case cmd\n when /^i (\\d+)+ (\\d+)+$/i\n @image = Image.new($1.to_i, $2.to_i)\n when /^c/i\n @image.clear\n when /^l (\\d+) (\\d+) ([a-z])$/i\n @image.colorize($1.to_i, $2.to_i,$3)\n when /^v (\\d+) (\\d+) (\\d+) ([a-z])$/i\n @image.draw_vertical_segment($1.to_i, $2.to_i, $3.to_i, $4)\n when /^h (\\d+) (\\d+) (\\d+) ([a-z])$/i\n @image.draw_horizontal_segment($1.to_i, $2.to_i, $3.to_i, $4)\n when /^f (\\d+) (\\d+) ([a-z])$/i\n @image.fill($1.to_i, $2.to_i, $3)\n when /^s$/i\n @output.puts @image.to_s\n when /^x$/i\n exit\n else\n puts 'Unknown command'\n end\n end\n \nend"}, "files_after": {"lib/editor.rb": "require 'image'\nrequire 'readline'\n\n# trap SIGINT and restore the state of the terminal\nstty_save = `stty -g`.chomp\ntrap('INT') { system('stty', stty_save); exit }\n\nclass Editor\n def initialize(output)\n @output = output\n end\n def start\n @output.puts 'Welcome to Image Editor!'\n listen\n end\n\n def listen\n loop do\n cmd = Readline::readline '> ', true\n # exit if user press CTRL-D\n exit if cmd.nil?\n execute(cmd)\n end\n end\n\n def execute(cmd)\n case cmd\n when /^i (\\d+)+ (\\d+)+$/i\n @image = Image.new($1.to_i, $2.to_i)\n when /^c/i\n @image.clear\n when /^l (\\d+) (\\d+) ([a-z])$/i\n @image.colorize($1.to_i, $2.to_i,$3)\n when /^v (\\d+) (\\d+) (\\d+) ([a-z])$/i\n @image.draw_vertical_segment($1.to_i, $2.to_i, $3.to_i, $4)\n when /^h (\\d+) (\\d+) (\\d+) ([a-z])$/i\n @image.draw_horizontal_segment($1.to_i, $2.to_i, $3.to_i, $4)\n when /^f (\\d+) (\\d+) ([a-z])$/i\n @image.fill($1.to_i, $2.to_i, $3)\n when /^s$/i\n @output.puts @image.to_s\n when /^x$/i\n exit\n else\n puts 'Unknown command'\n end\n end\n \nend\n"}} +{"repo": "nhowell/subdomain-fu", "pr_number": 1, "title": "Path url_for to work on on Rails 4.2", "state": "closed", "merged_at": null, "additions": 14, "deletions": 2, "files_changed": ["lib/subdomain_fu/url_rewriter.rb"], "files_before": {"lib/subdomain_fu/url_rewriter.rb": "require 'action_dispatch/routing/route_set'\n\nmodule ActionDispatch\n module Routing\n class RouteSet #:nodoc:\n def url_for_with_subdomains(options, path_segments=nil)\n if SubdomainFu.needs_rewrite?(options[:subdomain], (options[:host] || @request.host_with_port)) || options[:only_path] == false\n options[:only_path] = false if SubdomainFu.override_only_path?\n options[:host] = SubdomainFu.rewrite_host_for_subdomains(options.delete(:subdomain), options[:host] || @request.host_with_port)\n # puts \"options[:host]: #{options[:host].inspect}\"\n else\n options.delete(:subdomain)\n end\n url_for_without_subdomains(options)\n end\n alias_method_chain :url_for, :subdomains\n end\n end\nend\n"}, "files_after": {"lib/subdomain_fu/url_rewriter.rb": "require 'action_dispatch/routing/route_set'\n\nmodule ActionDispatch\n module Routing\n class RouteSet #:nodoc:\n # Known Issue: Monkey-patching `url_for` is error-prone.\n # For example, in rails 4.2, the method signature changed from\n #\n # def url_for(options)\n #\n # to\n #\n # def url_for(options, route_name = nil, url_strategy = UNKNOWN)\n #\n # Is there an alternative design using composition or class\n # inheritance?\n\n def url_for_with_subdomains(options, *args)\n if SubdomainFu.needs_rewrite?(options[:subdomain], (options[:host] || @request.host_with_port)) || options[:only_path] == false\n options[:only_path] = false if SubdomainFu.override_only_path?\n options[:host] = SubdomainFu.rewrite_host_for_subdomains(options.delete(:subdomain), options[:host] || @request.host_with_port)\n # puts \"options[:host]: #{options[:host].inspect}\"\n else\n options.delete(:subdomain)\n end\n url_for_without_subdomains(options, *args)\n end\n alias_method_chain :url_for, :subdomains\n end\n end\nend\n"}} +{"repo": "jcsalterego/nagios-rb", "pr_number": 1, "title": "unbreak adding further options", "state": "closed", "merged_at": "2012-02-16T16:25:17Z", "additions": 1, "deletions": 1, "files_changed": ["lib/nagios/config.rb"], "files_before": {"lib/nagios/config.rb": "require 'optparse'\n\nmodule Nagios\n class Config\n\n attr_accessor :options\n\n def initialize\n @settings = {}\n @options = OptionParser.new do |options|\n options.on(\"-wWARNING\",\n \"--warning=WARNING\",\n \"Warning Threshold\") do |x|\n @settings[:warning] = int_if_possible(x)\n end\n options.on(\"-cCRITICAL\",\n \"--critical=CRITICAL\",\n \"Critical Threshold\") do |x|\n @settings[:critical] = int_if_possible(x)\n end\n end\n end\n\n def [](setting)\n @settings[setting]\n end\n\n def []=(field, value)\n @settings[field] = vaule\n end\n\n def parse!\n @options.parse!\n end\n\n private\n def int_if_possible(x)\n (x.to_i > 0 || x == '0') ? x.to_i : x\n end\n end\nend\n"}, "files_after": {"lib/nagios/config.rb": "require 'optparse'\n\nmodule Nagios\n class Config\n\n attr_accessor :options\n\n def initialize\n @settings = {}\n @options = OptionParser.new do |options|\n options.on(\"-wWARNING\",\n \"--warning=WARNING\",\n \"Warning Threshold\") do |x|\n @settings[:warning] = int_if_possible(x)\n end\n options.on(\"-cCRITICAL\",\n \"--critical=CRITICAL\",\n \"Critical Threshold\") do |x|\n @settings[:critical] = int_if_possible(x)\n end\n end\n end\n\n def [](setting)\n @settings[setting]\n end\n\n def []=(field, value)\n @settings[field] = value\n end\n\n def parse!\n @options.parse!\n end\n\n private\n def int_if_possible(x)\n (x.to_i > 0 || x == '0') ? x.to_i : x\n end\n end\nend\n"}} +{"repo": "aconbere/evented", "pr_number": 1, "title": "Correct the URL for the github repo.", "state": "open", "merged_at": null, "additions": 1, "deletions": 1, "files_changed": ["lib/evented.js"], "files_before": {"lib/evented.js": "/*\n * YO check out the repository for updates\n * http://github.com/aconbere/event-emitter\n *\n */\nvar Evented = function () {\n this.listeners = {};\n this.listenersOnce = {};\n};\n\nEvented.prototype.withListeners = function (ev, callback) {\n if (!this.listeners[ev]) {\n this.listeners[ev] = [];\n }\n\n if (!this.listenersOnce[ev]) {\n this.listenersOnce[ev] = [];\n }\n\n if (callback) {\n callback(this.listeners[ev], this.listenersOnce[ev]);\n }\n};\n\nEvented.prototype.trigger = function (ev, data) {\n data = data || [];\n\n var that = this;\n this.withListeners(ev, function (listeners, listenersOnce) {\n for (var i = 0; i < listeners.length; i++) {\n listeners[i].apply(null, data);\n }\n\n for (var i = 0; i < listenersOnce.length; i++) {\n listenersOnce[i].apply(null, data);\n }\n // reset any of the once listeners for this event\n that.listenersOnce[ev] = [];\n });\n};\n\n\nEvented.prototype.bind = function (ev, callback) {\n this.withListeners(ev, function (listeners, _listenersOnce) {\n listeners.push(callback);\n });\n};\n\nEvented.prototype.bindOnce = function (ev, callback) {\n this.withListeners(ev, function (_listeners, listenersOnce) {\n listenersOnce.push(callback);\n });\n};\n\nEvented.prototype.unbindAll = function () {\n this.listeners = {};\n};\n\nif (typeof window === \"undefined\") {\n exports.Evented = Evented;\n}\n"}, "files_after": {"lib/evented.js": "/*\n * YO check out the repository for updates\n * http://github.com/aconbere/evented\n *\n */\nvar Evented = function () {\n this.listeners = {};\n this.listenersOnce = {};\n};\n\nEvented.prototype.withListeners = function (ev, callback) {\n if (!this.listeners[ev]) {\n this.listeners[ev] = [];\n }\n\n if (!this.listenersOnce[ev]) {\n this.listenersOnce[ev] = [];\n }\n\n if (callback) {\n callback(this.listeners[ev], this.listenersOnce[ev]);\n }\n};\n\nEvented.prototype.trigger = function (ev, data) {\n data = data || [];\n\n var that = this;\n this.withListeners(ev, function (listeners, listenersOnce) {\n for (var i = 0; i < listeners.length; i++) {\n listeners[i].apply(null, data);\n }\n\n for (var i = 0; i < listenersOnce.length; i++) {\n listenersOnce[i].apply(null, data);\n }\n // reset any of the once listeners for this event\n that.listenersOnce[ev] = [];\n });\n};\n\n\nEvented.prototype.bind = function (ev, callback) {\n this.withListeners(ev, function (listeners, _listenersOnce) {\n listeners.push(callback);\n });\n};\n\nEvented.prototype.bindOnce = function (ev, callback) {\n this.withListeners(ev, function (_listeners, listenersOnce) {\n listenersOnce.push(callback);\n });\n};\n\nEvented.prototype.unbindAll = function () {\n this.listeners = {};\n};\n\nif (typeof window === \"undefined\") {\n exports.Evented = Evented;\n}\n"}} +{"repo": "jtauber/web-graphics", "pr_number": 1, "title": "Fixed 'open' to write binary data in Windows too", "state": "closed", "merged_at": "2013-08-23T12:31:06Z", "additions": 1, "deletions": 1, "files_changed": ["web_graphics.py"], "files_before": {"web_graphics.py": "import zlib\nimport struct\nimport array\nimport random\nimport colorsys\n\n\ndef output_chunk(out, chunk_type, data):\n out.write(struct.pack(\"!I\", len(data)))\n out.write(chunk_type)\n out.write(data)\n checksum = zlib.crc32(data, zlib.crc32(chunk_type))\n out.write(struct.pack(\"!i\", checksum))\n\n\ndef get_data(width, height, rgb_func):\n fw = float(width)\n fh = float(height)\n compressor = zlib.compressobj()\n data = array.array(\"B\")\n for y in range(height):\n data.append(0)\n fy = float(y)\n for x in range(width):\n fx = float(x)\n data.extend([min(255, max(0, int(v * 255))) for v in rgb_func(fx / fw, fy / fh)])\n compressed = compressor.compress(data.tostring())\n flushed = compressor.flush()\n return compressed + flushed\n\n\ndef write_png(filename, width, height, rgb_func):\n out = open(filename, \"w\")\n out.write(struct.pack(\"8B\", 137, 80, 78, 71, 13, 10, 26, 10))\n output_chunk(out, \"IHDR\", struct.pack(\"!2I5B\", width, height, 8, 2, 0, 0, 0))\n output_chunk(out, \"IDAT\", get_data(width, height, rgb_func))\n output_chunk(out, \"IEND\", \"\")\n out.close()\n\n\ndef linear_gradient(start_value, stop_value, start_offset=0.0, stop_offset=1.0):\n return lambda offset: (start_value + ((offset - start_offset) / (stop_offset - start_offset) * (stop_value - start_value))) / 255.0\n\n\ndef LINEAR_Y(x, y):\n return y\n\n\ndef LINEAR_X(x, y):\n return x\n\n\ndef RADIAL(center_x, center_y):\n return lambda x, y: (x - center_x) ** 2 + (y - center_y) ** 2\n\n\ndef NO_NOISE(r, g, b):\n return r, g, b\n\n\ndef GAUSSIAN(sigma):\n def add_noise(r, g, b):\n d = random.gauss(0, sigma)\n return r + d, g + d, b + d\n return add_noise\n\n\ndef HSV(h, s, v):\n r, g, b = colorsys.hsv_to_rgb(h, s, v)\n return 255 * r, 255 * g, 255 * b\n\n\ndef hexstring_to_rgb(s):\n r = int(s[1:3], 16)\n g = int(s[3:5], 16)\n b = int(s[5:7], 16)\n return r, g, b\n\n\ndef gradient(value_func, noise_func, DATA):\n def gradient_function(x, y):\n initial_offset = 0.0\n v = value_func(x, y)\n for offset, start, end in DATA:\n if isinstance(start, str) and start.startswith(\"#\"):\n start = hexstring_to_rgb(start)\n if isinstance(end, str) and end.startswith(\"#\"):\n end = hexstring_to_rgb(end)\n if v < offset:\n r = linear_gradient(start[0], end[0], initial_offset, offset)(v)\n g = linear_gradient(start[1], end[1], initial_offset, offset)(v)\n b = linear_gradient(start[2], end[2], initial_offset, offset)(v)\n return noise_func(r, g, b)\n initial_offset = offset\n return noise_func(end[0] / 255.0, end[1] / 255.0, end[2] / 255.0)\n return gradient_function\n"}, "files_after": {"web_graphics.py": "import zlib\nimport struct\nimport array\nimport random\nimport colorsys\n\n\ndef output_chunk(out, chunk_type, data):\n out.write(struct.pack(\"!I\", len(data)))\n out.write(chunk_type)\n out.write(data)\n checksum = zlib.crc32(data, zlib.crc32(chunk_type))\n out.write(struct.pack(\"!i\", checksum))\n\n\ndef get_data(width, height, rgb_func):\n fw = float(width)\n fh = float(height)\n compressor = zlib.compressobj()\n data = array.array(\"B\")\n for y in range(height):\n data.append(0)\n fy = float(y)\n for x in range(width):\n fx = float(x)\n data.extend([min(255, max(0, int(v * 255))) for v in rgb_func(fx / fw, fy / fh)])\n compressed = compressor.compress(data.tostring())\n flushed = compressor.flush()\n return compressed + flushed\n\n\ndef write_png(filename, width, height, rgb_func):\n out = open(filename, \"wb\")\n out.write(struct.pack(\"8B\", 137, 80, 78, 71, 13, 10, 26, 10))\n output_chunk(out, \"IHDR\", struct.pack(\"!2I5B\", width, height, 8, 2, 0, 0, 0))\n output_chunk(out, \"IDAT\", get_data(width, height, rgb_func))\n output_chunk(out, \"IEND\", \"\")\n out.close()\n\n\ndef linear_gradient(start_value, stop_value, start_offset=0.0, stop_offset=1.0):\n return lambda offset: (start_value + ((offset - start_offset) / (stop_offset - start_offset) * (stop_value - start_value))) / 255.0\n\n\ndef LINEAR_Y(x, y):\n return y\n\n\ndef LINEAR_X(x, y):\n return x\n\n\ndef RADIAL(center_x, center_y):\n return lambda x, y: (x - center_x) ** 2 + (y - center_y) ** 2\n\n\ndef NO_NOISE(r, g, b):\n return r, g, b\n\n\ndef GAUSSIAN(sigma):\n def add_noise(r, g, b):\n d = random.gauss(0, sigma)\n return r + d, g + d, b + d\n return add_noise\n\n\ndef HSV(h, s, v):\n r, g, b = colorsys.hsv_to_rgb(h, s, v)\n return 255 * r, 255 * g, 255 * b\n\n\ndef hexstring_to_rgb(s):\n r = int(s[1:3], 16)\n g = int(s[3:5], 16)\n b = int(s[5:7], 16)\n return r, g, b\n\n\ndef gradient(value_func, noise_func, DATA):\n def gradient_function(x, y):\n initial_offset = 0.0\n v = value_func(x, y)\n for offset, start, end in DATA:\n if isinstance(start, str) and start.startswith(\"#\"):\n start = hexstring_to_rgb(start)\n if isinstance(end, str) and end.startswith(\"#\"):\n end = hexstring_to_rgb(end)\n if v < offset:\n r = linear_gradient(start[0], end[0], initial_offset, offset)(v)\n g = linear_gradient(start[1], end[1], initial_offset, offset)(v)\n b = linear_gradient(start[2], end[2], initial_offset, offset)(v)\n return noise_func(r, g, b)\n initial_offset = offset\n return noise_func(end[0] / 255.0, end[1] / 255.0, end[2] / 255.0)\n return gradient_function\n"}} +{"repo": "chnm/thatcamp-registrations", "pr_number": 28, "title": "Simplifies user creation.", "state": "closed", "merged_at": "2012-02-09T21:10:49Z", "additions": 5, "deletions": 18, "files_changed": ["thatcamp-registrations-functions.php"], "files_before": {"thatcamp-registrations-functions.php": "prefix . \"thatcamp_registrations\";\n \n $_POST = stripslashes_deep($_POST); \n \n // The user_id is set to the posted user ID, or null.\n $user_id = isset($_POST['user_id']) ? $_POST['user_id'] : null;\n \n $applicant_info = array();\n \n // Array of applicant info fields. May set up an option in plugin so admins can modify this list.\n $applicant_fields = array(\n 'first_name',\n 'last_name',\n 'user_email',\n 'user_url',\n 'description',\n 'previous_thatcamps',\n 'user_title',\n 'user_organization',\n 'user_twitter',\n 'tshirt_size',\n 'dietary_preferences'\n );\n \n foreach ( $applicant_fields as $field) {\n $applicant_info[$field] = isset($_POST[$field]) ? $_POST[$field] : null;\n }\n \n $date = isset($_POST['date']) ? $_POST['date'] : null;\n $applicationText = isset($_POST['application_text']) ? $_POST['application_text'] : null;\n\n // Let's serialize the applicant_info before putting it in the database.\n $applicant_info = maybe_serialize($applicant_info);\n $applicant_email = isset($_POST['user_email']) ? $_POST['user_email'] : null;\n \n if ( $registration = thatcamp_registrations_get_registration_by_user_id($user_id) \n || $registration = thatcamp_registrations_get_registration_by_applicant_email($applicant_email) ) {\n return 'You have already submitted an application.';\n } else {\n $wpdb->insert(\n $table,\n array(\n 'applicant_info' => $applicant_info,\n 'applicant_email' => $applicant_email,\n 'application_text' => $applicationText,\n 'status' => $status,\n 'date' => $date,\n 'user_id' => $user_id\n )\n );\n thatcamp_registrations_send_applicant_email($applicant_email);\n }\n}\n\n/**\n * Returns registration records based on type\n * \n * @param array The parameters on which to retrieve registrations\n **/\nfunction thatcamp_registrations_get_registrations($params = array()) {\n global $wpdb;\n $registrations_table = $wpdb->prefix . \"thatcamp_registrations\";\n \n $sql = \"SELECT * FROM \" . $registrations_table;\n \n if( isset($params['id']) && $id = $params['id']) {\n $sql .= \" WHERE id=\".$params['id'];\n if( isset($params['status']) && $status = $params['status']) {\n $sql .= \" AND status = CONVERT( _utf8 '$status' USING latin1 )\";\n }\n } elseif ( isset($params['status']) && $status = $params['status']) {\n $sql .= \" WHERE status = CONVERT( _utf8 '$status' USING latin1 )\";\n }\n \n // echo $sql; exit;\n $results = $wpdb->get_results($sql, OBJECT);\n return $results;\n}\n\n/**\n * Processes an array of registrations based on ID. Used mainly in the admin.\n * \n * @param array The IDs of the registration records.\n * @param string The status for the registration records.\n **/\nfunction thatcamp_registrations_process_registrations($ids = array(), $status) {\n global $wpdb;\n $table = $wpdb->prefix . \"thatcamp_registrations\";\n \n $idArray = array();\n foreach ($ids as $id) {\n $idArray['id'] = $id;\n }\n \n if ($status && !empty($idArray)) { \n $wpdb->update(\n $table,\n array('status' => $status),\n $idArray\n );\n if ($status == 'approved' && thatcamp_registrations_create_user_accounts()) {\n foreach ($ids as $id) {\n thatcamp_registrations_process_user($id);\n }\n }\n }\n \n return;\n}\n\n/**\n * Process a single registration based on ID. Uses mainly in the admin.\n * \n * @param int The ID of the registration record.\n * @param string The status for the registration record.\n **/\nfunction thatcamp_registrations_process_registration($id, $status) {\n if (isset($id) && isset($status)) {\n thatcamp_registrations_process_registrations(array($id), $status);\n }\n return;\n}\n\n/**\n * Processes a WP user when adding/updating a registration record. Only \n * should be used if we're creating users with approved registrations.\n *\n * @param integer|null The User ID\n * @param array The array of user information.\n * @param $registrationId\n * @return integer The User ID\n **/\nfunction thatcamp_registrations_process_user($registrationId = null, $role = 'author') {\n global $wpdb;\n \n /**\n * If the Registration ID is set, it means we already have a registration \n * record! Booyah. We'll use the user_id and application_info columns from \n * that record to process the user.\n */\n \n if ($registration = thatcamp_registrations_get_registration_by_id($registrationId)) { \n \n $userInfo = maybe_unserialize($registration->applicant_info);\n $userId = $registration->user_id ? $registration->user_id : email_exists($registration->applicant_email);\n \n // If we have a valid a User ID, we're dealing with an existing user.\n if ($userId) {\n add_existing_user_to_blog(array('user_id' => $userId, 'role' => $role));\n wp_new_user_notification($userId);\n }\n // We're probably dealing with a new user. Let's create one and associate it to our blog.\n else { \n $randomPassword = wp_generate_password( 12, false );\n $userEmail = $registration->applicant_email;\n $uarray = split( '@', $userEmail );\n $userName = sanitize_user( $uarray[0] );\n $userId = wp_create_user( $userName, $randomPassword, $userEmail );\n add_user_to_blog($wpdb->blogid, $userId, $role);\n thatcamp_registrations_update_user_data($userId, $userInfo);\n wp_new_user_notification($userId, $randomPassword);\n }\n }\n \n return $userId;\n}\n\n/**\n * Updates the user data. \n * Note: this needs to be altered so that user_url goes in the wp_users table and not the wp_usermeta table. --AF Sample: wp_update_user( array ('ID' => $user_id, 'user_url' => 'http://www.site.com' ) ) ; and http://wordpress.org/support/topic/wordpress-33-update_user_meta-and-wp_userswp_usermeta-issue?replies=8 \n **/\nfunction thatcamp_registrations_update_user_data($userId, $params)\n{\n\n if ( isset( $userId ) && $userData = get_userdata($userId) ) {\n foreach ($params as $key => $value) {\n update_user_meta( $userId, $key, $value );\n }\n } \n}\n\n/**\n * Gets registration record by ID.\n *\n **/\nfunction thatcamp_registrations_get_registration_by_id($id)\n{\n global $wpdb;\n $registrations_table = $wpdb->prefix . \"thatcamp_registrations\";\n $sql = \"SELECT * from \" . $registrations_table . \" WHERE id = \" .$id;\n return $wpdb->get_row($sql, OBJECT);\n}\n\n/**\n * Gets registration record by applicant_email.\n *\n **/\nfunction thatcamp_registrations_get_registration_by_applicant_email($applicant_email)\n{\n global $wpdb;\n $registrations_table = $wpdb->prefix . \"thatcamp_registrations\";\n $sql = \"SELECT * from \" . $registrations_table . \" WHERE applicant_email = '\" .$applicant_email .\"'\";\n return $wpdb->get_row($sql, OBJECT);\n}\n\n/**\n * Gets registration record by user_id.\n *\n * @param int $user_id The User ID.\n * @return object Registration record.\n **/\nfunction thatcamp_registrations_get_registration_by_user_id($user_id)\n{\n global $wpdb;\n $registrations_table = $wpdb->prefix . \"thatcamp_registrations\";\n $sql = \"SELECT * from \" . $registrations_table . \" WHERE user_id = \" .$user_id;\n return $wpdb->get_row($sql, OBJECT);\n}\n\n/**\n * Deletes a registration record by ID.\n *\n **/\nfunction thatcamp_registrations_delete_registration($id)\n{\n global $wpdb;\n $registrations_table = $wpdb->prefix . \"thatcamp_registrations\";\n if($id) {\n $wpdb->query(\"DELETE FROM \" . $registrations_table . \" WHERE id = '\" . $id . \"'\");\n }\n}\n\n/**\n * Creates a user from a registration record.\n *\n * @param integer $registrationId \n **/\nfunction thatcamp_registrations_create_user($registrationId)\n{\n if ($applicant = thatcamp_registrations_get_registration_applicant($registrationId)) {\n \n // if ( !is_int($applicant) ) {\n return $applicant;\n // }\n }\n}\n\n/**\n * Returns the value for thatcamp_registrations_options\n *\n * @uses get_option()\n * @return array The array of options\n **/\nfunction thatcamp_registrations_options() \n{\n return get_option('thatcamp_registrations_options');\n}\n\n/**\n * Returns the value for a single THATCamp Registrations option.\n *\n * @uses thatcamp_registrations_options()\n * @param string The name of the option\n * @return string\n **/\nfunction thatcamp_registrations_option($optionName) \n{\n if (isset($optionName)) {\n $options = thatcamp_registrations_options();\n return $options[$optionName];\n }\n return false;\n}\n\nfunction thatcamp_registrations_get_applicant_info($registration) \n{\n global $wpdb;\n \n if ($registration) {\n $registrations_table = $wpdb->prefix . \"thatcamp_registrations\";\n $sql = \"SELECT * from \" . $registrations_table . \" WHERE id = \" .$registration->id;\n $record = $wpdb->get_row($sql, OBJECT);\n if (($record->user_id == 0 || $record->user_id == null) && !empty($record->applicant_info)) {\n return (object) maybe_unserialize($record->applicant_info);\n } else {\n return get_userdata($record->user_id);\n }\n }\n}\n\n/**\n * Send a notification email to a THATCamp Registrations applicant\n *\n * @param string The applicant email address.\n * @param string The status of the application. Options are 'pending',\n * 'approved', and 'rejected. Default is pending.\n */\nfunction thatcamp_registrations_send_applicant_email($to, $status = \"pending\")\n{\n if (is_email($to)) {\n switch ($status) {\n case 'approved':\n $subject = __('Application Approved', 'thatcamp-registrations');\n $message = thatcamp_registrations_option('accepted_application_email');\n break;\n \n case 'rejected':\n $subject = __('Application Rejected', 'thatcamp-registrations');\n $message = thatcamp_registrations_option('rejected_application_email');\n break;\n case 'pending':\n default:\n $subject = __('Application Pending', 'thatcamp-registrations');\n $message = thatcamp_registrations_option('pending_application_email');\n break;\n }\n \n $subject = $subject . ': '.get_bloginfo('name');\n wp_mail($to, $subject, $message);\n \n return __('Email successfully sent!');\n }\n return false;\n}\n\n/**\n * Checks the option to create user accounts upon application approval.\n *\n * @return boolean\n **/\nfunction thatcamp_registrations_create_user_accounts() \n{\n return (bool) thatcamp_registrations_option('create_user_accounts');\n}\n\n/**\n * Checks to see if user authentication is required.\n *\n * @return boolean\n **/\nfunction thatcamp_registrations_user_required() \n{\n return (bool) thatcamp_registrations_option('require_login');\n}\n\n/**\n * Checks if registration is open.\n *\n * @return boolean\n */\nfunction thatcamp_registrations_registration_is_open()\n{\n return (bool) thatcamp_registrations_option('open_registration');\n}\n\n/**\n * Generates a random string for a token\n **/\nfunction thatcamp_registrations_generate_token()\n{\n return sha1(microtime() . mt_rand(1, 100000));\n}\n"}, "files_after": {"thatcamp-registrations-functions.php": "prefix . \"thatcamp_registrations\";\n \n $_POST = stripslashes_deep($_POST); \n \n // The user_id is set to the posted user ID, or null.\n $user_id = isset($_POST['user_id']) ? $_POST['user_id'] : null;\n \n $applicant_info = array();\n \n // Array of applicant info fields. May set up an option in plugin so admins can modify this list.\n $applicant_fields = array(\n 'first_name',\n 'last_name',\n 'user_email',\n 'user_url',\n 'description',\n 'previous_thatcamps',\n 'user_title',\n 'user_organization',\n 'user_twitter',\n 'tshirt_size',\n 'dietary_preferences'\n );\n \n foreach ( $applicant_fields as $field) {\n $applicant_info[$field] = isset($_POST[$field]) ? $_POST[$field] : null;\n }\n \n $date = isset($_POST['date']) ? $_POST['date'] : null;\n $applicationText = isset($_POST['application_text']) ? $_POST['application_text'] : null;\n\n // Let's serialize the applicant_info before putting it in the database.\n $applicant_info = maybe_serialize($applicant_info);\n $applicant_email = isset($_POST['user_email']) ? $_POST['user_email'] : null;\n \n if ( $registration = thatcamp_registrations_get_registration_by_user_id($user_id) \n || $registration = thatcamp_registrations_get_registration_by_applicant_email($applicant_email) ) {\n return 'You have already submitted an application.';\n } else {\n $wpdb->insert(\n $table,\n array(\n 'applicant_info' => $applicant_info,\n 'applicant_email' => $applicant_email,\n 'application_text' => $applicationText,\n 'status' => $status,\n 'date' => $date,\n 'user_id' => $user_id\n )\n );\n thatcamp_registrations_send_applicant_email($applicant_email);\n }\n}\n\n/**\n * Returns registration records based on type\n * \n * @param array The parameters on which to retrieve registrations\n **/\nfunction thatcamp_registrations_get_registrations($params = array()) {\n global $wpdb;\n $registrations_table = $wpdb->prefix . \"thatcamp_registrations\";\n \n $sql = \"SELECT * FROM \" . $registrations_table;\n \n if( isset($params['id']) && $id = $params['id']) {\n $sql .= \" WHERE id=\".$params['id'];\n if( isset($params['status']) && $status = $params['status']) {\n $sql .= \" AND status = CONVERT( _utf8 '$status' USING latin1 )\";\n }\n } elseif ( isset($params['status']) && $status = $params['status']) {\n $sql .= \" WHERE status = CONVERT( _utf8 '$status' USING latin1 )\";\n }\n \n // echo $sql; exit;\n $results = $wpdb->get_results($sql, OBJECT);\n return $results;\n}\n\n/**\n * Processes an array of registrations based on ID. Used mainly in the admin.\n * \n * @param array The IDs of the registration records.\n * @param string The status for the registration records.\n **/\nfunction thatcamp_registrations_process_registrations($ids = array(), $status) {\n global $wpdb;\n $table = $wpdb->prefix . \"thatcamp_registrations\";\n \n $idArray = array();\n foreach ($ids as $id) {\n $idArray['id'] = $id;\n }\n \n if ($status && !empty($idArray)) { \n $wpdb->update(\n $table,\n array('status' => $status),\n $idArray\n );\n if ($status == 'approved' && thatcamp_registrations_create_user_accounts()) {\n foreach ($ids as $id) {\n thatcamp_registrations_process_user($id);\n }\n }\n }\n \n return;\n}\n\n/**\n * Process a single registration based on ID. Uses mainly in the admin.\n * \n * @param int The ID of the registration record.\n * @param string The status for the registration record.\n **/\nfunction thatcamp_registrations_process_registration($id, $status) {\n if (isset($id) && isset($status)) {\n thatcamp_registrations_process_registrations(array($id), $status);\n }\n return;\n}\n\n/**\n * Processes a WP user when adding/updating a registration record. Only \n * should be used if we're creating users with approved registrations.\n *\n * @param integer|null The User ID\n * @param array The array of user information.\n * @param $registrationId\n * @return integer The User ID\n **/\nfunction thatcamp_registrations_process_user($registrationId = null, $role = 'author') {\n global $wpdb;\n \n /**\n * If the Registration ID is set, it means we already have a registration \n * record! Booyah. We'll use the user_id and application_info columns from \n * that record to process the user.\n */\n \n if ($registration = thatcamp_registrations_get_registration_by_id($registrationId)) { \n \n $userInfo = maybe_unserialize($registration->applicant_info);\n $userId = $registration->user_id ? $registration->user_id : email_exists($registration->applicant_email);\n \n // If we have a valid a User ID, we're dealing with an existing user.\n if ($userId) {\n add_existing_user_to_blog(array('user_id' => $userId, 'role' => $role));\n wp_new_user_notification($userId);\n }\n // We're probably dealing with a new user. Let's create one and associate it to our blog.\n else { \n $userEmail = $registration->applicant_email;\n $uarray = split( '@', $userEmail );\n $userName = sanitize_user( $uarray[0] );\n $userInfo['user_login'] = $userName;\n $userInfo['user_email'] = $userEmail;\n\n $userId = wp_insert_user( $userInfo );\n add_user_to_blog($wpdb->blogid, $userId, $role);\n wp_new_user_notification($userId);\n }\n }\n \n return $userId;\n}\n\n/**\n * Gets registration record by ID.\n *\n **/\nfunction thatcamp_registrations_get_registration_by_id($id)\n{\n global $wpdb;\n $registrations_table = $wpdb->prefix . \"thatcamp_registrations\";\n $sql = \"SELECT * from \" . $registrations_table . \" WHERE id = \" .$id;\n return $wpdb->get_row($sql, OBJECT);\n}\n\n/**\n * Gets registration record by applicant_email.\n *\n **/\nfunction thatcamp_registrations_get_registration_by_applicant_email($applicant_email)\n{\n global $wpdb;\n $registrations_table = $wpdb->prefix . \"thatcamp_registrations\";\n $sql = \"SELECT * from \" . $registrations_table . \" WHERE applicant_email = '\" .$applicant_email .\"'\";\n return $wpdb->get_row($sql, OBJECT);\n}\n\n/**\n * Gets registration record by user_id.\n *\n * @param int $user_id The User ID.\n * @return object Registration record.\n **/\nfunction thatcamp_registrations_get_registration_by_user_id($user_id)\n{\n global $wpdb;\n $registrations_table = $wpdb->prefix . \"thatcamp_registrations\";\n $sql = \"SELECT * from \" . $registrations_table . \" WHERE user_id = \" .$user_id;\n return $wpdb->get_row($sql, OBJECT);\n}\n\n/**\n * Deletes a registration record by ID.\n *\n **/\nfunction thatcamp_registrations_delete_registration($id)\n{\n global $wpdb;\n $registrations_table = $wpdb->prefix . \"thatcamp_registrations\";\n if($id) {\n $wpdb->query(\"DELETE FROM \" . $registrations_table . \" WHERE id = '\" . $id . \"'\");\n }\n}\n\n/**\n * Creates a user from a registration record.\n *\n * @param integer $registrationId \n **/\nfunction thatcamp_registrations_create_user($registrationId)\n{\n if ($applicant = thatcamp_registrations_get_registration_applicant($registrationId)) {\n \n // if ( !is_int($applicant) ) {\n return $applicant;\n // }\n }\n}\n\n/**\n * Returns the value for thatcamp_registrations_options\n *\n * @uses get_option()\n * @return array The array of options\n **/\nfunction thatcamp_registrations_options() \n{\n return get_option('thatcamp_registrations_options');\n}\n\n/**\n * Returns the value for a single THATCamp Registrations option.\n *\n * @uses thatcamp_registrations_options()\n * @param string The name of the option\n * @return string\n **/\nfunction thatcamp_registrations_option($optionName) \n{\n if (isset($optionName)) {\n $options = thatcamp_registrations_options();\n return $options[$optionName];\n }\n return false;\n}\n\nfunction thatcamp_registrations_get_applicant_info($registration) \n{\n global $wpdb;\n \n if ($registration) {\n $registrations_table = $wpdb->prefix . \"thatcamp_registrations\";\n $sql = \"SELECT * from \" . $registrations_table . \" WHERE id = \" .$registration->id;\n $record = $wpdb->get_row($sql, OBJECT);\n if (($record->user_id == 0 || $record->user_id == null) && !empty($record->applicant_info)) {\n return (object) maybe_unserialize($record->applicant_info);\n } else {\n return get_userdata($record->user_id);\n }\n }\n}\n\n/**\n * Send a notification email to a THATCamp Registrations applicant\n *\n * @param string The applicant email address.\n * @param string The status of the application. Options are 'pending',\n * 'approved', and 'rejected. Default is pending.\n */\nfunction thatcamp_registrations_send_applicant_email($to, $status = \"pending\")\n{\n if (is_email($to)) {\n switch ($status) {\n case 'approved':\n $subject = __('Application Approved', 'thatcamp-registrations');\n $message = thatcamp_registrations_option('accepted_application_email');\n break;\n \n case 'rejected':\n $subject = __('Application Rejected', 'thatcamp-registrations');\n $message = thatcamp_registrations_option('rejected_application_email');\n break;\n case 'pending':\n default:\n $subject = __('Application Pending', 'thatcamp-registrations');\n $message = thatcamp_registrations_option('pending_application_email');\n break;\n }\n \n $subject = $subject . ': '.get_bloginfo('name');\n wp_mail($to, $subject, $message);\n \n return __('Email successfully sent!');\n }\n return false;\n}\n\n/**\n * Checks the option to create user accounts upon application approval.\n *\n * @return boolean\n **/\nfunction thatcamp_registrations_create_user_accounts() \n{\n return (bool) thatcamp_registrations_option('create_user_accounts');\n}\n\n/**\n * Checks to see if user authentication is required.\n *\n * @return boolean\n **/\nfunction thatcamp_registrations_user_required() \n{\n return (bool) thatcamp_registrations_option('require_login');\n}\n\n/**\n * Checks if registration is open.\n *\n * @return boolean\n */\nfunction thatcamp_registrations_registration_is_open()\n{\n return (bool) thatcamp_registrations_option('open_registration');\n}\n\n/**\n * Generates a random string for a token\n **/\nfunction thatcamp_registrations_generate_token()\n{\n return sha1(microtime() . mt_rand(1, 100000));\n}\n"}} +{"repo": "roman/warden_oauth", "pr_number": 4, "title": "Added a way to modify the oauth_callback url", "state": "open", "merged_at": null, "additions": 465, "deletions": 4, "files_changed": ["lib/warden_oauth.rb", "lib/warden_oauth/strategy.rb", "lib/warden_oauth2/base.rb", "lib/warden_oauth2/config.rb", "lib/warden_oauth2/config_extension.rb", "lib/warden_oauth2/errors.rb", "lib/warden_oauth2/strategy.rb", "lib/warden_oauth2/strategy_builder.rb", "lib/warden_oauth2/utils.rb"], "files_before": {"lib/warden_oauth/strategy.rb": "module Warden\n module OAuth\n\n #\n # Holds all the main logic of the OAuth authentication, all the generated\n # OAuth classes will extend from this class\n #\n class Strategy < Warden::Strategies::Base\n extend StrategyBuilder\n\n ######################\n ### Strategy Logic ###\n ######################\n\n\n def self.access_token_user_finders\n (@_user_token_finders ||= {})\n end\n\n #\n # An OAuth strategy will be valid to execute if:\n # * A 'warden_oauth_provider' parameter is given, with the name of the OAuth service\n # * A 'oauth_token' is being receive on the request (response from an OAuth provider)\n #\n def valid?\n (params.include?('warden_oauth_provider') && params['warden_oauth_provider'] == config.provider_name.to_s) ||\n params.include?('oauth_token') \n end\n\n\n #\n # Manages the OAuth authentication process, there can be 3 outcomes from this Strategy:\n # 1. The OAuth credentials are invalid and the FailureApp is called\n # 2. The OAuth credentials are valid, but there is no user associated to them. In this case\n # the FailureApp is called, but the env['warden.options'][:oauth][:access_token] will be \n # available.\n # 3. The OAuth credentials are valid, and the user is authenticated successfuly\n #\n # @note\n # If you want to signup users with the twitter credentials, you can manage the creation of a new \n # user in the FailureApp with the given access_token\n #\n def authenticate!\n if params.include?('warden_oauth_provider')\n store_request_token_on_session\n redirect!(request_token.authorize_url)\n throw(:warden)\n elsif params.include?('oauth_token')\n load_request_token_from_session\n if missing_stored_token?\n fail!(\"There is no OAuth authentication in progress\")\n elsif !stored_token_match_recieved_token?\n fail!(\"Received OAuth token didn't match stored OAuth token\")\n else\n user = find_user_by_access_token(access_token)\n if user.nil?\n fail!(\"User with access token not found\")\n throw_error_with_oauth_info\n else\n success!(user)\n end\n end\n end\n\n end\n\n def fail!(msg) #:nodoc:\n self.errors.add(service_param_name.to_sym, msg)\n super\n end\n \n ###################\n ### OAuth Logic ###\n ###################\n\n def consumer\n @consumer ||= ::OAuth::Consumer.new(config.consumer_key, config.consumer_secret, config.options)\n end\n\n def request_token\n host_with_port = Warden::OAuth::Utils.host_with_port(request)\n @request_token ||= consumer.get_request_token(:oauth_callback => host_with_port)\n end\n\n def access_token\n @access_token ||= request_token.get_access_token(:oauth_verifier => params['oauth_verifier'])\n end\n\n protected\n\n def find_user_by_access_token(access_token)\n raise RuntimeError.new(<<-ERROR_MESSAGE) unless self.respond_to?(:_find_user_by_access_token)\n \nYou need to define a finder by access_token for this strategy.\nWrite on the warden initializer the following code:\nWarden::OAuth.access_token_user_finder(:#{config.provider_name}) do |access_token|\n # Logic to get your user from an access_token\nend\n\nERROR_MESSAGE\n self._find_user_by_access_token(access_token)\n end\n\n def throw_error_with_oauth_info\n throw(:warden, :oauth => { \n self.config.provider_name => {\n :provider => config.provider_name,\n :access_token => access_token,\n :consumer_key => config.consumer_key,\n :consumer_secret => config.consumer_secret\n }\n })\n end\n\n def store_request_token_on_session\n session[:request_token] = request_token.token\n session[:request_secret] = request_token.secret\n end\n\n def load_request_token_from_session\n token = session.delete(:request_token)\n secret = session.delete(:request_secret)\n @request_token = ::OAuth::RequestToken.new(consumer, token, secret)\n end\n\n def missing_stored_token? \n !request_token\n end\n\n def stored_token_match_recieved_token?\n request_token.token == params['oauth_token']\n end\n\n def service_param_name\n '%s_oauth' % config.provider_name\n end\n\n def config\n self.class::CONFIG\n end\n\n end\n\n end\nend\n", "lib/warden_oauth.rb": "require \"rack\"\nrequire \"warden\"\nrequire \"oauth\"\n\nmodule Warden\n module OAuth\n\n base_path = File.dirname(__FILE__) + \"/warden_oauth\"\n \n require base_path + \"/base\"\n require base_path + \"/errors\"\n autoload :Utils, base_path + '/utils'\n autoload :StrategyBuilder, base_path + '/strategy_builder'\n autoload :Strategy, base_path + '/strategy'\n autoload :Config, base_path + \"/config\"\n require base_path + \"/config_extension\"\n \n\n end\nend\n"}, "files_after": {"lib/warden_oauth/strategy.rb": "module Warden\n module OAuth\n\n #\n # Holds all the main logic of the OAuth authentication, all the generated\n # OAuth classes will extend from this class\n #\n class Strategy < Warden::Strategies::Base\n extend StrategyBuilder\n\n ######################\n ### Strategy Logic ###\n ######################\n\n\n def self.access_token_user_finders\n (@_user_token_finders ||= {})\n end\n\n #\n # An OAuth strategy will be valid to execute if:\n # * A 'warden_oauth_provider' parameter is given, with the name of the OAuth service\n # * A 'oauth_token' is being receive on the request (response from an OAuth provider)\n #\n def valid?\n (params.include?('warden_oauth_provider') && params['warden_oauth_provider'] == config.provider_name.to_s) ||\n params.include?('oauth_token') \n end\n\n\n #\n # Manages the OAuth authentication process, there can be 3 outcomes from this Strategy:\n # 1. The OAuth credentials are invalid and the FailureApp is called\n # 2. The OAuth credentials are valid, but there is no user associated to them. In this case\n # the FailureApp is called, but the env['warden.options'][:oauth][:access_token] will be \n # available.\n # 3. The OAuth credentials are valid, and the user is authenticated successfuly\n #\n # @note\n # If you want to signup users with the twitter credentials, you can manage the creation of a new \n # user in the FailureApp with the given access_token\n #\n def authenticate!\n if params.include?('warden_oauth_provider')\n store_request_token_on_session\n redirect!(request_token.authorize_url(config.options))\n throw(:warden)\n elsif params.include?('oauth_token')\n load_request_token_from_session\n if missing_stored_token?\n fail!(\"There is no OAuth authentication in progress\")\n elsif !stored_token_match_recieved_token?\n fail!(\"Received OAuth token didn't match stored OAuth token\")\n else\n user = find_user_by_access_token(access_token)\n if user.nil?\n fail!(\"User with access token not found\")\n throw_error_with_oauth_info\n else\n success!(user)\n end\n end\n end\n\n end\n\n def fail!(msg) #:nodoc:\n self.errors.add(service_param_name.to_sym, msg)\n super\n end\n \n ###################\n ### OAuth Logic ###\n ###################\n\n def consumer\n @consumer ||= ::OAuth::Consumer.new(config.consumer_key, config.consumer_secret, config.options)\n end\n\n def request_token\n @request_token ||= consumer.get_request_token(:oauth_callback => config.options[:oauth_callback])\n end\n\n def access_token\n @access_token ||= request_token.get_access_token(:oauth_verifier => params['oauth_verifier'])\n end\n\n protected\n\n def find_user_by_access_token(access_token)\n raise RuntimeError.new(<<-ERROR_MESSAGE) unless self.respond_to?(:_find_user_by_access_token)\n \nYou need to define a finder by access_token for this strategy.\nWrite on the warden initializer the following code:\nWarden::OAuth.access_token_user_finder(:#{config.provider_name}) do |access_token|\n # Logic to get your user from an access_token\nend\n\nERROR_MESSAGE\n self._find_user_by_access_token(access_token)\n end\n\n def throw_error_with_oauth_info\n throw(:warden, :oauth => { \n self.config.provider_name => {\n :provider => config.provider_name,\n :access_token => access_token,\n :consumer_key => config.consumer_key,\n :consumer_secret => config.consumer_secret\n }\n })\n end\n\n def store_request_token_on_session\n session[:request_token] = request_token.token\n session[:request_secret] = request_token.secret\n end\n\n def load_request_token_from_session\n token = session.delete(:request_token)\n secret = session.delete(:request_secret)\n @request_token = ::OAuth::RequestToken.new(consumer, token, secret)\n end\n\n def missing_stored_token? \n !request_token\n end\n\n def stored_token_match_recieved_token?\n request_token.token == params['oauth_token']\n end\n\n def service_param_name\n '%s_oauth' % config.provider_name\n end\n\n def config\n self.class::CONFIG\n end\n\n end\n\n end\nend\n", "lib/warden_oauth.rb": "require \"rack\"\nrequire \"warden\"\nrequire \"oauth\"\n\nmodule Warden\n module OAuth\n\n base_path = File.dirname(__FILE__) + \"/warden_oauth\"\n \n require base_path + \"/base\"\n require base_path + \"/errors\"\n autoload :Utils, base_path + '/utils'\n autoload :StrategyBuilder, base_path + '/strategy_builder'\n autoload :Strategy, base_path + '/strategy'\n autoload :Config, base_path + \"/config\"\n require base_path + \"/config_extension\"\n \n\n end\nend\n\nrequire \"oauth2\"\n\nmodule Warden\n module OAuth2\n\n base_path = File.dirname(__FILE__) + \"/warden_oauth2\"\n \n require base_path + \"/base\"\n require base_path + \"/errors\"\n autoload :Utils, base_path + '/utils'\n autoload :StrategyBuilder, base_path + '/strategy_builder'\n autoload :Strategy, base_path + '/strategy'\n autoload :Config, base_path + \"/config\"\n require base_path + \"/config_extension\"\n \n\n end\nend\n\n"}} +{"repo": "railsfactory-shiv/rupees", "pr_number": 2, "title": "Spacing fix", "state": "closed", "merged_at": null, "additions": 43, "deletions": 38, "files_changed": ["lib/rupees.rb"], "files_before": {"lib/rupees.rb": "module NumberToRupees\n WORDS = {0=>\"zero\", 1=>\"One\", 2=>\"Two\", 3=>\"Three\", 4=>\"Four\", 5=>\"Five\", 6=>\"six\", 7=>\"seven\", 8=>\"Eight\", 9=>\"Nine\",10=>\"Ten\",11=>\"Eleven\",12=>\"Twelve\",13=>\"Thirteen\",14=>\"Fourteen\",15=>\"Fifteen\",16=>\"Sixteen\",17=>\"Seventeen\",18=>\"Eighteen\",19=>\"Nineteen\",20=>\"Twenty\",30=>\"Thirty\",40=>\"Fourty\",50=>\"Fifty\",60=>\"Sixty\",70=>\"Seventy\",80=>\"Eighty\",90=>\"Ninty\"}\n SUFIXES = {0=>\"hundred & \", 1=>\" Crore, \", 2=>\" Lakh, \", 3=>\" Thousand, \", 4=>\" Hundred, \"} # 5=>''\n module Fixnum\n def self.included(recipient)\n recipient.extend(ClassMethods)\n recipient.class_eval do\n include InstanceMethods\n end\n end\n \n module ClassMethods\n end\n \n module InstanceMethods\n def rupees\n result = self >= 0 ? \"\" : \"(-) \"\n\t num = self.abs\n \n # I would prefer One Rupee, insead of One Rupees\n return \"One Rupee.\" if num==1\n\t \n if num > 99\n num.to_s.rjust(11,'0').insert(-4,'0').scan(/../).each_with_index{|x,i| result += self.def_calc(x,i) }\n \t else\t \n result = spell_two_digits(num)\n end\n\t result.sub(/,\\s$/,'')+ \" Rupees.\"\n end\n\n protected\n def def_calc(x,i)\n str=self.proc_unit(x)\n\t return '' if str.length==0\n return \"#{str}#{SUFIXES[i]}\"\n end\n\n def proc_unit(x)\n return \"\" unless x.to_i > 0\n return spell_two_digits(x.to_i)\n end\n\t \n\t def spell_two_digits(x)\n return WORDS[x] if WORDS[x]\n r,f = x.divmod(10)\n return \"#{WORDS[r*10]}#{WORDS[f]}\"\n\t end\n end\n end \nend \nFixnum.send :include, NumberToRupees::Fixnum\n"}, "files_after": {"lib/rupees.rb": "module NumberToRupees\n WORDS = { 0 => 'zero', 1 => 'One', 2 => 'Two', 3 => 'Three', 4 => 'Four', 5 => 'Five', 6 => 'six', 7 => 'seven', 8 => 'Eight', 9 => 'Nine',\n 10 => 'Ten', 11 => 'Eleven', 12 => 'Twelve', 13 => 'Thirteen', 14 => 'Fourteen', 15 => 'Fifteen', 16 => 'Sixteen', 17 => 'Seventeen', 18 => 'Eighteen', 19 => 'Nineteen', 20 => 'Twenty', 30 => 'Thirty', 40 => 'Fourty', 50 => 'Fifty', 60 => 'Sixty', 70 => 'Seventy', 80 => 'Eighty', 90 => 'Ninty' }\n SUFIXES = { 0 => 'hundred & ', 1 => ' Crore, ', 2 => ' Lakh, ', 3 => ' Thousand, ', 4 => ' Hundred, ' } # 5=>''\n module Integer\n def self.included(recipient)\n recipient.extend(ClassMethods)\n recipient.class_eval do\n include InstanceMethods\n end\n end\n\n module ClassMethods\n end\n\n module InstanceMethods\n def rupees\n result = self >= 0 ? '' : '(-) '\n num = abs\n\n # I would prefer One Rupee, insead of One Rupees\n return 'One Rupee.' if num == 1\n\n if num > 99\n num.to_s.rjust(11, '0').insert(-4, '0').scan(/../).each_with_index { |x, i| result += def_calc(x, i) }\n else\n result = spell_two_digits(num)\n end\n result.sub(/,\\s$/, '')\n end\n\n protected\n\n def def_calc(x, i)\n str = proc_unit(x)\n return '' if str.length == 0\n\n \"#{str}#{SUFIXES[i]}\"\n end\n\n def proc_unit(x)\n return '' unless x.to_i > 0\n\n spell_two_digits(x.to_i)\n end\n\n def spell_two_digits(x)\n return WORDS[x] if WORDS[x]\n\n r, f = x.divmod(10)\n f.zero? ? \"#{WORDS[r*10]}\" : \"#{WORDS[r*10]} #{WORDS[f]}\"\n end\n end\n end\nend\nInteger.include NumberToRupees::Integer\n"}} +{"repo": "mediavrog/cfe", "pr_number": 1, "title": "update to mootools 1.3", "state": "closed", "merged_at": null, "additions": 83, "deletions": 68, "files_changed": ["cfe/addons/cfe.addon.dependencies.js", "cfe/addons/cfe.addon.toolTips.js", "cfe/base/cfe.base.js", "cfe/modules/button/cfe.module.button.js", "cfe/modules/check/cfe.module.checkbox.js", "cfe/modules/check/cfe.module.radio.js", "cfe/modules/file/cfe.module.file.js", "cfe/modules/select/cfe.module.select.js", "cfe/modules/select/cfe.module.select.multiple.js", "cfe/replace/cfe.replace.js", "demo.html"], "files_before": {"cfe/modules/file/cfe.module.file.js": "/**\n * @module File\n */\n\n/**\n * replaces file upload fields\n *\n *

            is not resetted onReset

            \n * \n *
            Tested in:
            \n *
              \n *
            • Safari 4 - implicitly labelled triggers when deletin a file; reset doesnt trigger
            • \n *
            • Firefox 3.6.
            • \n *
            • Google Chrome 6 - implicitly labelled triggers twice, when using alias button & triggers when deletin a file.
            • \n *
            • Opera 10.62.
            • \n *
            • IE 7 - gaga.
            • \n *
            • IE 8 - implicitly labelled triggers when deletin a file.
            • \n *
            \n *\n * @class File\n * @namespace cfe.modules\n *\n * @extends cfe.module.Button\n */\n\ncfe.module.File = new Class({\n \n Extends: cfe.module.Button,\n \n instance: 0,\n\n /**\n * CSS Selector to fetch \"original\" HTMLElements for replacement with this module\n * @property selector\n * @type string\n */\n selector: \"input[type=file]\",\n\t\n options: {\n /**\n * enables the use of fileicons through a bit of markup and css\n * @config fileIcons\n * @type boolean\n * @default true\n */\n fileIcons: true,\n /**\n * show only the filename, not the whole path\n * @config trimFilePath\n * @type boolean\n * @default true\n */\n trimFilePath: true,\n\n innerLabel: \"Choose File\"\n },\n\n hideOriginalElement: false,\n\n toElement: function()\n {\n return this.wrapa\n },\n\n /**\n * retreive the filepath\n *\n * @method getFilePath\n * @return {HTMLElement}\n */\n getFilePath: function()\n {\n return this.v;\n },\n\n afterInitialize: function()\n {\n this.a = this.button;\n \n if(this.hideOriginalElement) this.o.hideInPlace();\n\n if(this.o.id) this.wrapa.addClass(cfe.prefix+this.type+this.o.id.capitalize());\n\n // various additions\n if(!this.o.implicitLabel && !Browser.Engine.webkit) this.wrapa.addEvent(\"click\", this.clicked.bindWithEvent(this));\n\n if(this.isDisabled()) this.disable();\n\n if(!this.options.slidingDoors) this.wrapa.addClass(cfe.prefix+this.type)\n\n if(this.options.buttonStyle) this.a.addClass(cfe.prefix+\"Button\")\n\n this.a.removeClass(cfe.prefix+this.type)\n },\n\n build: function()\n {\n this.parent();\n this.innerlabel.set(\"text\", $pick(this.options.innerLabel, \"\"));\n\n // make original element follow mouse\n // setup wrapper\n this.wrapa = new Element(\"span\",{\n \"class\": cfe.prefix+this.type,\n styles:\n {\n overflow: \"hidden\",\n position: \"relative\"\n }\n }).cloneEvents(this.a)\n \n this.wrapa.inject(this.a, \"after\").adopt(this.a, this.o);\n\n // add positioning styles and events to \"hidden\" file input\n this.o.addEvents({\n \"mouseout\": this.update.bind(this),\n \"change\": this.update.bind(this),\n onDisable: this.disable.bind(this),\n onEnable: this.enable.bind(this)\n }).setStyles({\n opacity: \"0\",\n visibility: \"visible\",\n height: \"100%\",\n width: \"auto\",\n position: \"absolute\",\n top: 0,\n right: 0,\n margin: 0\n });\n\n this.wrapa.addEvent(\"mousemove\", this.follow.bindWithEvent(this));\n\n this.button = this.a;\n this.a = this.wrapa;\n \n // add filepath\n this.v = new Element(\"span\").addClass(cfe.prefix+this.type+\"Path hidden\");\n\t\t\n this.path = new Element(\"span\").addClass(\"filePath\");\n\n if(this.options.fileIcons)\n {\n this.path.addClass(\"fileIcon\");\n }\n\n this.cross = $( new cfe.module.Button({delegateClick: false}).addEvent(\"click\", this.deleteCurrentFile.bind(this)) ).addClass(\"delete\");\n\n this.v.adopt(this.path, this.cross).inject(this.wrapa, \"after\");\n\n this.update();\n },\n\n /**\n * Method to programmatically create an \"original\" HTMLElement\n *\n * @method createOriginal\n * @return {HTMLElement} an input field of type \"file\"\n */\n createOriginal: function()\n {\n return new Element(\"input\",{\n type: \"file\"\n });\n },\n\t\n follow: function(ev)\n {\n this.o.setStyle(\"left\",(ev.client.x-this.a.getLeft()-(this.o.getWidth()-30)));\n\t\t\n /* special treatment for internet explorer as the fileinput will not be cut off by overflow:hidden */\n if(Browser.Engine.trident){\n if(ev.client.x < this.a.getLeft() || ev.client.x > this.a.getLeft()+this.a.getWidth())\n this.o.setStyle(\"left\", -9999);\n }\n },\n\t\n update: function()\n {\n // only do stuff if original element is not disabled\n if( !$chk(this.o.disabled) )\n {\n if( this.o.value != \"\" )\n {\n this.o.disable().blur();\n\n this.oldValue = this.o.getProperty(\"value\");\n if(this.options.trimFilePath) this.oldValue = this.oldValue.trimFilePath();\n this.path.set(\"html\", this.oldValue);\n\n if(this.options.fileIcons)\n {\n var ind = this.oldValue.lastIndexOf(\".\");\n this.path.setProperty(\"class\",\"filePath fileIcon \" + this.oldValue.substring(++ind).toLowerCase());\n }\n this.v.removeClass(\"hidden\");\n }\n else\n {\n this.o.enable().focus();\n\n this.path.set(\"html\", \"\");\n this.v.addClass(\"hidden\");\n }\n\n this.parent();\n }\n },\n\t\n deleteCurrentFile: function()\n {\n // we dont clone the old file input here, since the attribute \"value\" would be cloned, too\n // and we cannot modify the value of an file input field without user interaction\n this.o = this.createOriginal().addClass(this.o.getProperty(\"class\")).setProperties({\n name: this.o.getProperty(\"name\"),\n id: this.o.getProperty(\"id\"),\n style: this.o.getProperty(\"style\"),\n title: this.o.getProperty(\"title\")\n }).cloneEvents(this.o).replaces(this.o);\n\t\t\n this.update();\n }\n});\n\n// add trimFilePath to Native String for convenience\nString.implement({\n trimFilePath: function()\n {\n var ind = false;\n if(!(ind = this.lastIndexOf(\"\\\\\")))\n if(!(ind = this.lastIndexOf(\"\\/\")))\n ind = 0;\n\n return this.substring(++ind);\n }\n});", "cfe/base/cfe.base.js": "/**\n * The core of custom form elements. Includes cfe.Generic and some slight addons to the native Element object. \n *\n * @module Core\n * @namespace cfe\n */\n\nvar cfe = {\n version: \"0.9.9\",\n prefix: \"cfe\",\n module: {},\n addon: {}\n};\n\n/**\n * extend Elements with some Helper functions\n * @class Helpers\n * @namespace Element\n */\nElement.Helpers = new Class({\n\n /**\n * cross-browser method for disabling the text selection by setting css attributes\n * \n * @method disableTextSelection\n */\n disableTextSelection: function(){\n if(Browser.Engine.trident || Browser.Engine.presto){\n this.setProperty(\"unselectable\",\"on\");\n }\n else if(Browser.Engine.gecko){\n this.setStyle(\"MozUserSelect\",\"none\");\n }\n else if(Browser.Engine.webkit){\n this.setStyle(\"KhtmlUserSelect\",\"none\");\n }\n\n return this;\n },\n\n /**\n * disables a HTMLElement if its a form element by setting the disabled attribute to true\n *\n * @method disable\n * @return boolean true, if element could be disabled\n */\n disable: function()\n {\n if($type(this) === \"element\" && [\"button\", \"input\", \"option\", \"optgroup\", \"select\", \"textarea\"].contains( this.get(\"tag\") ) )\n {\n this.setProperty(\"disabled\", true);\n this.fireEvent(\"onDisable\");\n }\n\n return this;\n },\n\n /**\n * enables a HTMLElement if its a form element by setting the disabled attribute to false\n *\n * @method enable\n * @return {boolean} true, if element could be enabled\n */\n enable: function()\n {\n if($type(this) === \"element\" && [\"button\", \"input\", \"option\", \"optgroup\", \"select\", \"textarea\"].contains( this.get(\"tag\") ) )\n {\n this.setProperty(\"disabled\", false);\n this.fireEvent(\"onEnable\");\n }\n\n return this;\n },\n\n /**\n * enables or disabled a HTMLElement if its a form element depending on it's current state\n *\n * @method toggleDisabled\n * @return {boolean} true, if element could be toggled\n */\n toggleDisabled: function()\n {\n if($type(this) === \"element\" && [\"button\", \"input\", \"option\", \"optgroup\", \"select\", \"textarea\"].contains( this.get(\"tag\") ) )\n {\n this.setProperty(\"disabled\", !this.getProperty(\"disabled\") );\n this.fireEvent(this.getProperty(\"disabled\")?\"onDisable\":\"onEnable\");\n }\n return this;\n },\n\n /**\n * returns the label-element which belongs to this element\n *\n * @method getLabel\n * @return HTMLElement or NULL\n */\n getLabel: function()\n {\n var label = null;\n\n // get label by id/for-combo\n if(this.id) label = $$(\"label[for=\"+this.id+\"]\")[0];\n \n // no label was found for id/for, let's see if it's implicitly labelled\n if(!label)\n {\n label = this.getParent('label');\n\n if(label) this.implicitLabel = true;\n }\n\n return label;\n },\n\n /**\n * generates the markup used by sliding doors css technique to use with this element\n *\n * @method setSlidingDoors\n *\n * @param count\n * @param type\n * @param prefix\n * \n * @return HTMLElement or NULL the wrapped HTMLElement\n */\n setSlidingDoors: function(count, type, prefix, suffixes)\n {\n var slide = null;\n var wrapped = this;\n prefix = $pick(prefix, \"sd\");\n\n suffixes = $pick(suffixes, []);\n\n for(var i = count; i > 0; --i)\n {\n wrapped.addClass( prefix+\"Slide\"+( (i == 1 && count == i) ? \"\" : (suffixes[i] || i) ));\n slide = new Element(type);\n try{\n wrapped = slide.wraps(wrapped);\n }catch(e){\n wrapped = slide.grab(wrapped);\n }\n }\n\n wrapped = null;\n\n return slide;\n },\n\n /**\n * hide an element but keep it's vertical position and leave it tab- & screenreader-able :)\n *\n * @method hideInPlace\n *\n * @return HTMLElement\n */\n hideInPlace: function()\n {\n return this.setStyles({\n position: \"absolute\",\n left: -99999,\n width: 1,\n height: 1\n });\n }\n});\n\nElement.implement(new Element.Helpers);", "cfe/modules/check/cfe.module.radio.js": "/**\n * @module Checkable\n */\n\n/**\n *

            replaces radiobuttons

            \n *\n *
            Tested in:
            \n *
              \n *
            • Safari 4.
            • \n *
            • Firefox 3.6.
            • \n *
            • Google Chrome 6.
            • \n *
            • Opera 10.62.
            • \n *
            • IE 7.
            • \n *\n *
            • IE 8\n *
                \n *
              • labels dont work for normal labelled elements
              • \n *
              \n *
            • \n *\n *
            \n *\n * @class Radiobutton\n * @namespace cfe.module\n *\n * @extends cfe.modules.Checkbox\n */\ncfe.module.Radiobutton = new Class({\n\n Extends: cfe.module.Checkbox,\n\n instance: 0,\n\n /**\n * CSS Selector to fetch \"original\" HTMLElements for replacement with this module\n * @property selector\n * @type string\n */\n selector: \"input[type=radio]\",\n\n /**\n * Method to programmatically create an \"original\" HTMLElement\n *\n * @method createOriginal\n * @return {HTMLElement} an input field of type \"radio\"\n */\n createOriginal: function()\n {\n return new Element(\"input\",{\n \"type\": \"radio\",\n \"checked\": this.options.checked\n });\n },\n\n /**\n * @method initializeAdv\n * @protected\n */\n afterInitialize: function()\n {\n this.parent();\n \n if( !(Browser.Engine.trident || Browser.Engine.gecko) ) this.o.addEvent(\"click\", this.update.bind(this));\n\n // on check, disable all other radiobuttons in this group\n this.addEvent(\"check\", function(){\n $$(\"input[name='\"+this.o.get(\"name\")+\"']\").each(function(el)\n {\n if(el != this.o && el.retrieve(\"cfe\")) el.retrieve(\"cfe\").uncheck();\n }.bind(this));\n })\n }\n});", "cfe/replace/cfe.replace.js": "/**\n * replacement class for automated replacment of scoped form elements\n *\n * @module replace\n * @namespace cfe\n *\n */\n\ncfe.Replace = new Class(\n{\n Implements: [new Options, new Events],\n\n options:{\n scope: false,\n\t\t\n onInit: $empty,\n onInitSingle: $empty,\n onBeforeInitSingle: $empty,\n onSetModuleOption: $empty,\n onRegisterModule: $empty,\n onUnregisterModule: $empty,\n onComplete: $empty\n },\n\t\t\n modules: {},\n moduleOptions: {},\n moduleOptionsAll: {},\n\t\n initialize: function()\n {\n this.registerAllModules.bind(this)();\n },\n\t\n /**\n * @method registerAllModules\n\t * registeres all loaded modules onInitialize\n\t */\n registerAllModules: function(){\n\t\t\n //console.log(\"Register all modules\");\n\t\t\n $each(cfe.module, function(modObj, modType){\n //console.log(\"Registering type \"+modType);\n if(modType != \"Generic\")\n this.registerModule(modType);\n\t\t\t\t\n }.bind(this));\n },\n\t\n /* call to register module */\n registerModule: function(mod){\n\t\t\n //console.log(\"Call to registerModule with arg:\"+mod);\n modObj = cfe.module[mod];\n\t\t\n this.fireEvent(\"onRegisterModule\", [mod,modObj]);\n this.modules[mod] = modObj;\n this.moduleOptions[mod] = {};\n\n return true;\n },\n\t\n registerModules: function(mods)\n {\n $each(mods,function(mod){\n this.registerModule(mod);\n },this);\n },\n\t\n unregisterModule: function(mod)\n {\n modObj = cfe.module[mod];\n\t\t\n this.fireEvent(\"onUnregisterModule\", [mod,modObj]);\n\n delete this.modules[mod];\n },\n\t\n unregisterModules: function(mods)\n {\n $each(mods,function(mod){\n this.unregisterModule(mod);\n },this);\n },\n /**\n\t * sets a single option for a specified module\n\t * if no module was given, it sets the options for all modules\n\t *\n * @method setModuleOption\n *\n\t * @param {String} \tmod \tName of the module\n\t * @param {String} \topt \tName of the option\n\t * @param {Mixed} \tval\t\tThe options value\n\t */\n setModuleOption: function(mod,opt,val){\n\t\t\n modObj = cfe.module[mod];\n\t\t\n this.fireEvent(\"onSetModuleOption\", [mod,modObj,opt,val]);\n\t\t\n if(!modObj){\n this.moduleOptionsAll[opt] = val;\n }\n else{\n this.moduleOptions[mod][opt] = val;\n }\n },\n\n setModuleOptions: function(mod,opt){\n\t\t\n $each(opt, function(optionValue, optionName){\n this.setModuleOption(mod,optionName,optionValue);\n }.bind(this));\n\t\t\n },\n\n engage: function(options){\n\n this.setOptions(this.options, options);\n\n if($type(this.options.scope) != \"element\"){\n this.options.scope = $(document.body);\n }\n\n this.fireEvent(\"onInit\");\n\t\t\n $each(this.modules,function(module,moduleName,i){\n\t\t\t\n var selector = module.prototype.selector;\n\t\t\t\n this.options.scope.getElements(selector).each(function(el,i){\n\n if(el.retrieve(\"cfe\") != null){\n\n var basicOptions = {\n replaces: el\n };\n\n this.fireEvent(\"onBeforeInitSingle\", [el,i,basicOptions]);\n\n var single = new module($merge(basicOptions,$merge(this.moduleOptions[moduleName],this.moduleOptionsAll)));\n\t\t\t\t\n this.fireEvent(\"onInitSingle\", single);\n }else{\n this.fireEvent(\"onSkippedInitSingle\", [el,i,basicOptions]); \n }\n\t\t\t\t\n },this);\n },this);\n\t\t\n this.fireEvent(\"onComplete\");\n }\n});", "cfe/modules/check/cfe.module.checkbox.js": "/**\n * @module Checkable\n */\n\n/**\n *

            replaces checkboxes

            \n * \n *
            Tested in:
            \n *
              \n *
            • Safari 4.
            • \n *
            • Firefox 3.6.
            • \n *
            • Google Chrome 6.
            • \n *
            • Opera 10.62.
            • \n *
            • IE 7.
            • \n *
            • IE 8.
            • \n *
            \n *\n * @class Checkbox\n * @namespace cfe.module\n * \n * @extends cfe.module.Button\n */\ncfe.module.Checkbox = new Class({\n \n Extends: cfe.module.Button,\n \n instance: 0,\n\n /**\n * CSS Selector to fetch \"original\" HTMLElements for replacement with this module\n * @property selector\n * @type string\n */\n selector: \"input[type=checkbox]\",\n\n options:{\n /**\n * @inherit\n */\n slidingDoors: false\n /**\n * Fired when the original element gets checked\n * @event onCheck\n */\n //onCheck: Class.empty,\n /**\n * Fired when the original element's checked state is set to false\n * @event onUnCheck\n */\n //onUncheck: Class.empty\n },\n\n afterInitialize: function()\n {\n this.parent();\n\n // important for resetting dynamically created cfe\n this.o.defaultChecked = this.o.checked;\n\n if( Browser.Engine.presto || Browser.Engine.trident )\n {\n //console.log(\"fix for element update (IE and Opera)\")\n this.o.addEvent(\"click\", this.update.bind(this) );\n }\n\n\n if(Browser.Engine.trident && this.o.implicitLabel)\n {\n //console.log(\"fix for implicit labels (IE) element[\"+this.o.id+\"]\")\n this.l.removeEvents(\"click\")\n this.a.removeEvents(\"click\").addEvent(\"click\", function(e){\n e.stop();\n this.clicked.bind(this)();\n }.bind(this))\n }\n\n this.update();\n },\n\n /**\n * Method to programmatically create an \"original\" HTMLElement\n *\n * @method createOriginal\n * @return {HTMLElement} an input field of type \"checkbox\"\n * @protected\n */\n createOriginal: function()\n {\n return new Element(\"input\",{\n type: \"checkbox\",\n checked: this.options.checked\n });\n },\n\n clicked: function(e)\n {\n if(Browser.Engine.trident && e) e.stop();\n\n this.parent()\n },\n\n /**\n * public method to check a checkbox programatically\n *\n * @method check\n * @public\n */\n check: function()\n {\n this.a.addClass(\"A\");\n this.fireEvent(\"onCheck\");\n },\n\n /**\n * public method to uncheck a checkbox programatically\n *\n * @method uncheck\n * @public\n */\n uncheck: function()\n {\n this.a.removeClass(\"A\");\n this.fireEvent(\"onUncheck\");\n },\n\n update: function()\n {\n this.o.checked ? this.check() : this.uncheck();\n this.parent();\n }\n});", "cfe/addons/cfe.addon.toolTips.js": "/**\n * @module Addon\n */\n\n/**\n * pretty simple integration of auto-generated tooltips (from title-attribute)\n * depends on mootools Tips\n *\n * @class Tips\n * @namespace cfe.addon\n *\n */\ncfe.addon.Tips = new Class({\n\t\n options: $merge(this.parent, {\n enableTips: true,\n ttStyle: \"label\",\n ttClass: cfe.prefix+\"Tip\"\n }),\n\t\n initToolTips: function(){\n\t\t\n if(!window.Tips || !this.options.enableTips){\n if(this.options.debug){\n this.throwMsg.bind(this)(\"CustomFormElements: initialization of toolTips failed.\\nReason: Mootools Plugin 'Tips' not available.\");\n }\n \n return false;\n }\n\t\n switch(this.options.ttStyle){\n default:case 'label': this.toolTipsLabel.bind(this)();break;\n }\n\n return true;\n },\n\t\n toolTipsLabel: function(){\n\t\t\n var labels = this.options.scope.getElements('label');\n \t\t\n labels.each(function(lbl,i){\n\n forEl = lbl.getProperty(\"for\");\n\t\t\t\n if(!forEl){\n var cl = lbl.getProperty(\"class\");\n\t\t\t\t\n if( $defined(cl) ){\n var forEl = cl.match(/for_[a-zA-Z0-9\\-]+/);\n\n if(forEl){\n forEl = forEl.toString();\n el = $( forEl.replace(/for_/,\"\") );\n } \n }\n\t\t\t\t\n if(!el){\n el = lbl.getElement(\"input\");\n }\n }else{\n el = $(forEl);\n }\n\n if(el){\n if($chk(qmTitle = el.getProperty(\"title\"))){\n\t\t\t\t\t\n el.setProperty(\"title\",\"\").setProperty(\"hint\", qmTitle)\n\t\t\t\t\t\n var qm = new Element(\"span\",{\n \"class\": this.options.ttClass,\n \"title\": qmTitle\n });\n \n // check if implicit label span is present\n var impLabel = lbl.getFirst(\"span[class=label]\");\n \n qm.injectInside($chk(impLabel)?impLabel:lbl);\n }\n }\n },this);\n\t\t\n new Tips($$('.'+this.options.ttClass+'[title]'));\n }\n});\n\ncfe.Replace.implement(new cfe.addon.Tips);\ncfe.Replace.prototype.addEvent(\"onComplete\", function(){\n this.initToolTips();\n});", "cfe/addons/cfe.addon.dependencies.js": "/**\n * @module Addon\n */\n\n/**\n * adds dependencies to checkboxes\n *\n * @class Dependencies\n * @namespace cfe.addon\n *\n */\ncfe.addon.Dependencies = new Class({\n\t\n /**\n\t * adds dependencies for an element \n\t * @param {Object} el\n\t * @param {Array} dep\n\t */\n addDependencies: function(el, deps){\n $each(deps,function(dep){\n this.addDependency(el,dep);\n }.bind(this));\n },\n\t\n /**\n\t * adds dependency for an element \n\t * @param {Object} el\n\t * @param {Object} dep\n\t */\n addDependency: function(el, dep){\n\t\t\n // create an array if needed\n if($type( el.retrieve('deps') ) !== \"array\"){\n el.store('deps', []);\n }\n\t\t\n // deps may be objects or strings > if a string was given, try to interpret it as id and fetch element by $()\n if($type(dep) === \"string\" || $type(dep) === \"element\"){\n el.retrieve('deps').push( $(dep) );\n return true;\n }\n\t\t\n return false;\n },\n\t\n getDependencies: function(el)\n {\n return el.retrieve('deps');\n },\n\t\n /**\n\t * this is called when a new item of a cfemodule gets initialized\n\t * it checks, whether there are dependencies for this element and adds them to its options\n\t * \n\t * @param {Object} el\n\t */\n attachDependencies: function(el,i,baseOptions)\n {\n var deps = this.getDependencies(el);\n\t\t\n if($type(deps) === \"array\"){\n baseOptions.deps = deps;\n return true;\n }\n\t\n return false;\n }\n\t\t\n});\ncfe.Replace.implement(new cfe.addon.Dependencies);\ncfe.Replace.prototype.addEvent(\"onBeforeInitSingle\", cfe.Replace.prototype.attachDependencies);\n\ncfe.addon.Dependencies.Helper = new Class({\n resolveDependencies: function()\n {\n var deps = this.o.retrieve('deps');\n\t\t\n if(deps){\n $each(deps, function(dep,i){\n dep.checked = true;\n dep.fireEvent(\"change\");\n }.bind(this));\n }\n }\n});\n\n// support for checkboxes\ncfe.module.Checkbox.implement(new cfe.addon.Dependencies.Helper);\ncfe.module.Checkbox.prototype.addEvent(\"onCheck\", function(){\n this.resolveDependencies();\n});", "cfe/modules/button/cfe.module.button.js": "/**\n * @module Button\n */\n\n/**\n * gets extended by modules to start off with standard, button-like behaviours.\n *\n * when focused and pressed, form gets submitted\n *\n * @class Button\n * @namespace cfe.module\n *\n */\ncfe.module.Button = new Class(\n{\n Implements: [new Options, new Events],\n\n selector: \"button\",\n\n instance: 0,\n\n /**\n * basic options for all cfes and always available\n * @property options\n */\n options: {\n /**\n * if > 0, it will create markup for css sliding doors tech
            \n * the number defines the amount of wrappers to create around this element
            \n * 2: standard sliding doors (x- or y-Axis)
            \n * 4: sliding doors in all directions (x/y-Axis)\n *\n * @config slidingDoors\n * @type int\n * @default 4\n */\n slidingDoors: 2,\n\n /**\n * if this element shall replace an existing html form element, pass it here\n * @config replaces\n * @type HTMLElement\n */\n replaces: null,\n\n /**\n * determines if a click on the decorator should be delegated to the original element\n * @config delegateClick\n * @type Boolean\n */\n delegateClick: true,\n\n /**\n * may pass any element as a label (toggling, hovering,..) for this cfe\n * @config label\n * @type HTMLElement\n */\n label: null,\n\n /**\n * if this cfe is created programatically, it's possible to set the name attribute of the generated input element\n * @config name\n * @type string\n */\n name: \"\",\n\n /**\n * setting this to true will create a disabled element\n * @config disabled\n * @type boolean\n */\n disabled: false,\n\n buttonStyle: true\n\n /**\n * Fired when the mouse is moved over the \"decorator\" element\n * @event onMouseOver\n */\n //onMouseOver: Class.empty,\n\n /**\n * Fired when the mouse is moved away from the \"decorator\" element\n * @event onMouseOut\n */\n //onMouseOut: Class.empty,\n\n /**\n * Fired when the \"original\" element gets focus (e.g. by tabbing)\n * @event onFocus\n */\n //onFocus: Class.empty,\n\n /**\n * Fired when the \"original\" element loses focus\n * @event onBlur\n */\n //onBlur: Class.empty,\n\n /**\n * Fired when \"decorator\" is clicked by mouse\n * @event onClick\n */\n //onClick: Class.empty,\n\n /**\n * Fired when pressing down with the mouse button on the \"decorator\"\n * Fired when pressing the space key while \"original\" has focus\n * @event onPress\n */\n //onPress: Class.empty,\n\n /**\n * Fired when \"decorator\" was pressed and the mouse button is released\n * Fired when \"original\" was pressed by space key and this key is released\n * @event onRelease\n */\n //onRelease: Class.empty,\n\n /**\n * Fired when \"original\"'s value changes\n * @event onUpdate\n */\n //onUpdate: Class.empty,\n\n /**\n * Fired when \"original\" gets disabled by HTMLElement.enable()\n * @event onEnable\n */\n //onEnable: Class.empty,\n\n /**\n * Fired when \"original\" gets disabled by HTMLElement.disable()\n * @event onDisable\n */\n //onDisable: Class.empty,\n\n /**\n * Fired when decorator is completely loaded and is ready to use\n * @event onLoad\n */\n //onLoad: Class.empty\n\n\n },\n\n hideOriginalElement: true,\n\n /**\n * constructor
            \n * building algorithm for cfe (template method)
            \n *
              \n *
            1. setOptions: set Options
            2. \n *
            3. buildWrapper: setup the \"decorator\"
            4. \n *
            5. setupOriginal: procede the \"original\" element (add Events...)
            6. \n *
            7. addLabel: add and procede the label
            8. \n *
            9. initializeAdv: last chance for subclasses to do initialization
            10. \n *
            11. build: various specific dom handling and \"decorator\" building
            12. \n *\n * @method initialize\n * @constructor\n *\n * @param {Object} options\n **/\n initialize: function(opt)\n {\n // sets instance id\n this.instance = this.constructor.prototype.instance++;\n\n this.setOptions(opt);\n\n this.type = $pick(this.options.type, $H(cfe.module).keyOf(this.constructor));\n\n this.buildWrapper();\n\n // prepares original html element for use with cfe and injects decorator into dom\n this.setupOriginal();\n\n // add a label, if present\n this.addLabel( $pick(this.o.getLabel(), this.setupLabel(this.options.label) ) );\n\n this.build();\n\n // add events to wrapping element\n this.setupWrapperEvents();\n\n // specific initialization\n this.afterInitialize();\n\n this.fireEvent(\"load\")\n },\n\n /**\n * retreive the \"decorator\"\n * mootools supports the use of $(myCfe) if toElement is defined\n *\n * @method toElement\n * @return {HTMLElement}\n */\n toElement: function()\n {\n return this.a;\n },\n\n /**\n * retreive the label\n *\n * @method getLabel\n * @return {HTMLElement}\n */\n getLabel: function()\n {\n return this.l;\n },\n\n /**\n * template method STEP 1\n */\n buildWrapper: function(){\n this.a = new Element(\"span\");\n },\n\n /**\n * handles the creation of the underlying original form element
              \n * stores a reference to the cfe object in the original form element\n * template method STEP 2\n *\n * @method setupOriginal\n * @protected\n */\n setupOriginal: function()\n {\n // get original element\n if( $defined(this.options.replaces) )\n {\n this.o = this.options.replaces;\n this.a.inject(this.o, 'before');\n }\n else // standalone\n {\n this.o = this.createOriginal();\n\n if(this.options.id) this.o.setProperty(\"id\", this.options.id);\n\n if(this.options.disabled) this.o.disable();\n\n if(this.options.name)\n {\n this.o.setProperty(\"name\", this.options.name);\n\n if( !$chk(this.o.id) ) this.o.setProperty(\"id\", this.options.name+this.instance);\n }\n\n if(this.options.value) this.o.setProperty(\"value\", this.options.value);\n\n this.a.adopt(this.o);\n }\n\n this.o.addEvents({\n focus: this.setFocus.bind(this),\n blur: this.removeFocus.bind(this),\n change: this.update.bind(this),\n keydown: function(e){\n if(e.key == \"space\") this.press();\n }.bind(this),\n keyup: function(e){\n if(e.key == \"space\") this.release();\n }.bind(this),\n onDisable: function(){\n this.a.fireEvent(\"disable\");\n }.bind(this),\n onEnable: function(){\n this.a.fireEvent(\"enable\");\n }.bind(this)\n });\n\n // store a reference to this cfe \"in\" the original form element\n this.o.store(\"cfe\", this);\n },\n\n /*\n * adds a label element to this cfe\n * template method STEP 3\n *\n * @method addLabel\n * @protected\n *\n * @param {HTMLElement} the label element to set as label for this cfe\n */\n addLabel: function(label)\n {\n if( !$defined(label) ) return;\n\n this.l = label;\n\n // remove for property\n if(!this.dontRemoveForFromLabel) this.l.removeProperty(\"for\");\n\n // add adequate className, add stdEvents\n this.l.addClass(cfe.prefix+this.type+\"L\");\n\n if(this.o.id || this.o.name) this.l.addClass(\"for_\"+ (this.o.id || (this.o.name+this.o.value).replace(\"]\",\"-\").replace(\"[\",\"\") ));\n\n // add stdevents\n this.l.addEvents({\n mouseover: this.hover.bind(this),\n mouseout: this.unhover.bind(this),\n mousedown: this.press.bind(this),\n mouseup: this.release.bind(this),\n click: this.clicked.bindWithEvent(this)\n });\n\n this.addEvents({\n press: function()\n {\n this.l.addClass(\"P\");\n },\n release: function()\n {\n this.l.removeClass(\"P\");\n },\n mouseOver: function()\n {\n this.l.addClass(\"H\");\n },\n mouseOut: function()\n {\n this.l.removeClass(\"H\");\n this.l.removeClass(\"P\");\n },\n focus: function()\n {\n this.l.addClass(\"F\");\n },\n blur: function()\n {\n this.l.removeClass(\"F\");\n //this.l.removeClass(\"P\");\n },\n enable: function()\n {\n this.l.removeClass(\"D\");\n },\n disable: function()\n {\n this.l.addClass(\"D\");\n }\n });\n },\n\n /**\n * part of the main template method for building the \"decorator\"
              \n * must be extended by subclasses\n *\n * template method STEP 4\n *\n * @method build\n * @protected\n */\n build: function(){\n\n this.innerlabel = this.setupInnerLabel();\n this.a.adopt(this.innerlabel);\n\n if( $chk(this.options.slidingDoors) )\n {\n this.a = this.a.setSlidingDoors(this.options.slidingDoors-1, \"span\", cfe.prefix).addClass(cfe.prefix+this.type);\n }\n },\n\n\n /**\n * adds events and mousepointer style to the \"decorator\"\n * usually gets called by buildWrapper\n *\n * template method STEP 5\n *\n * @method setupWrapperEvents\n * @protected\n */\n setupWrapperEvents: function()\n {\n if(!this.o.implicitLabel)\n {\n this.a.addEvents({\n mouseover: this.hover.bind(this),\n mouseout: this.unhover.bind(this),\n mousedown: this.press.bind(this),\n mouseup: this.release.bind(this)\n });\n }\n\n this.a.addEvents({\n disable: this.disable.bind(this),\n enable: this.enable.bind(this)\n })\n \n },\n\n /**\n * part of the main template method for building the \"decorator\"
              \n * gets called immediately before the build-method
              \n * may be extended by subclasses\n *\n * template method STEP 6\n *\n * @method initializeAdv\n * @protected\n */\n afterInitialize: function()\n {\n if(this.hideOriginalElement) this.o.hideInPlace();\n\n if(this.o.id) this.a.addClass(cfe.prefix+this.type+this.o.id.capitalize());\n\n // various additions\n if(!this.o.implicitLabel) this.a.addEvent(\"click\", this.clicked.bindWithEvent(this));\n\n if(this.isDisabled()) this.a.fireEvent(\"disable\");\n\n if(!this.options.slidingDoors) this.a.addClass(cfe.prefix+this.type)\n\n if(this.options.buttonStyle) this.a.addClass(cfe.prefix+\"Button\")\n },\n\n setupInnerLabel: function(){\n return new Element(\"span\").addClass(\"label\").disableTextSelection();\n },\n\n\n /**\n * getter for retrieving the disabled state of the \"original\" element\n *\n * @method isDisabled\n * @return boolean\n */\n isDisabled: function()\n {\n return this.o.getProperty(\"disabled\")\n },\n\n /**\n * programatically creates an \"original\" element
              \n * each subclass has to implement this\n *\n * @method createOriginal\n * @return {HTMLElement}\n */\n createOriginal: function()\n {\n return new Element(\"button\")\n },\n\n /*\n * creates a label element and fills it with the contents (may be html) given by option \"label\"\n *\n * @method setupLabel\n * @protected\n *\n * @return {HTMLElement or NULL} if option \"label\" is not set\n */\n setupLabel: function()\n {\n if( $defined(this.options.label) ) return new Element(\"label\").set(\"html\", this.options.label).setProperty(\"for\", this.o.id);\n\n return null;\n },\n\n /**\n * wrapper method for event onPress
              \n * may be extended by subclasses\n *\n * @method press\n * @protected\n */\n press: function()\n {\n if(this.isDisabled()) return\n\n this.a.addClass(\"P\");\n this.fireEvent(\"onPress\");\n\n //console.log(this.type + \"pressed\");\n },\n\n /**\n * wrapper method for event onRelease
              \n * may be extended by subclasses\n *\n * @method release\n * @protected\n */\n release: function()\n {\n if(this.isDisabled()) return\n\n this.a.removeClass(\"P\");\n this.fireEvent(\"onRelease\");\n \n //console.log(this.type + \"released\");\n\n },\n\n /**\n * wrapper method for event onMouseOver
              \n * may be extended by subclasses\n *\n * @method onMouseOver\n * @protected\n */\n hover: function()\n {\n if(this.isDisabled()) return\n\n this.a.addClass(\"H\");\n this.fireEvent(\"onMouseOver\");\n\n //console.log(this.type + \"hovered\");\n },\n\n /**\n * wrapper method for event onMouseOut
              \n * may be extended by subclasses\n *\n * @method unhover\n * @protected\n */\n unhover: function()\n {\n if(this.isDisabled()) return\n\n this.a.removeClass(\"H\");\n this.fireEvent(\"onMouseOut\");\n this.release();\n\n //console.log(this.type + \"unhovered\");\n },\n\n /**\n * wrapper method for event onFocus
              \n * may be extended by subclasses\n *\n * @method setFocus\n * @protected\n */\n setFocus: function()\n {\n this.a.addClass(\"F\");\n this.fireEvent(\"onFocus\");\n\n //console.log(this.type + \"focused\");\n },\n\n /**\n * wrapper method for event onBlur
              \n * may be extended by subclasses\n *\n * @method removeFocus\n * @protected\n */\n removeFocus: function()\n {\n //console.log(\"o blurred\");\n this.a.removeClass(\"F\");\n // if cfe gets blurred, also clear press state\n //this.a.removeClass(\"P\");\n this.fireEvent(\"onBlur\");\n\n //console.log(this.type + \"blurred\");\n\n },\n\n /**\n * wrapper method for event onClick
              \n * delegates the click to the \"original\" element
              \n * may be extended by subclasses\n *\n * @method clicked\n * @protected\n */\n clicked: function(e)\n {\n //causes problems in other browsers than ie - gonna took into this later; its the best approach to stop the event from bubbling right here though imho\n //e.stop();\n\n if(this.isDisabled()) return\n\n if( $chk(this.o.click) && $chk(this.options.delegateClick) ) this.o.click();\n this.o.focus();\n\n this.fireEvent(\"onClick\");\n\n //console.log(this.type + \" clicked\");\n },\n\n /**\n * wrapper method for event onUpdate
              \n * may be extended by subclasses\n *\n * @method update\n * @protected\n */\n update: function()\n {\n this.fireEvent(\"onUpdate\");\n\n //console.log(\"o was updated\");\n },\n\n /**\n * wrapper method for event onEnable
              \n * may be extended by subclasses\n *\n * @method enable\n * @protected\n */\n enable: function()\n {\n this.a.removeClass(\"D\");\n this.fireEvent(\"onEnable\");\n\n //console.log(this.type+\"-\"+this.instance+\" now enabled\");\n },\n\n /**\n * wrapper method for event onDisable
              \n * may be extended by subclasses\n *\n * @method disable\n * @protected\n */\n disable: function()\n {\n this.a.addClass(\"D\");\n this.fireEvent(\"onDisable\");\n\n //console.log(this.type+\"-\"+this.instance+\" now disabled\");\n }\n});", "cfe/modules/select/cfe.module.select.js": "/**\n * @module Scrollable\n */\n\n/**\n * SCROLLING functionality for select boxes;\n * TODO: refactor to standalone module\n * \n * creates handles and sets up a slider object\n *\n * @class Scrollable\n * @namespace cfe.helper\n *\n * \n */\ncfe.helper = cfe.helper || {}\n\ncfe.helper.Scrollable = {\n\n options: {\n size: 4,\n scrolling: true\n },\n \n setupScrolling: function()\n {\n // slider config\n this.scrollerWrapper = new Element(\"span\",{\n \"class\": cfe.prefix+\"ScrollerWrapper\",\n \"styles\":{\n height: this.container.getHeight()\n }\n }).inject(this.container, \"after\");\n\n var scrollTimer, scrollTimeout;\n var scrollStepHeight = this.allOptions[0].getHeight();\n\n function scroll(by){\n clearInterval(scrollTimer);\n clearTimeout(scrollTimeout);\n\n slider.set(slider.step+by);\n\n scrollTimeout = (function(){\n scrollTimer = (function(){\n slider.set(slider.step+by);\n }.bind(this)).periodical(50)\n }.bind(this)).delay(200)\n }\n\n function clearScroll(){\n clearInterval(scrollTimer);\n clearTimeout(scrollTimeout);\n }\n\n this.scrollerTop = $(new cfe.module.Button({\n delegateClick: false\n }).addEvent(\"release\", clearScroll).addEvent(\"press\", scroll.pass(-1))).addClass(\"scrollTop\");\n\n this.scrollerBottom = $(new cfe.module.Button({\n delegateClick: false\n }).addEvent(\"release\", clearScroll).addEvent(\"press\", scroll.pass(1))).addClass(\"scrollBottom\")\n\n this.scrollerKnob = new Element(\"span\").addClass(\"scrollKnob\");\n this.scrollerBack = new Element(\"span\").addClass(\"scrollRail\");\n\n this.scrollerBack.adopt(this.scrollerKnob);\n this.scrollerWrapper.adopt(this.scrollerBack, this.scrollerTop, this.scrollerBottom);\n\n var slider = new Slider(this.scrollerBack, this.scrollerKnob, {\n steps: this.allOptions.length-this.options.size,\n mode: \"vertical\" ,\n onChange: function(step){\n this.container.scrollTo(false,step*scrollStepHeight);\n }.bind(this)\n }).set(this.selectedIndex);\n\n this.scrollerKnob.setStyle(\"position\", \"absolute\");\n\n // scrolling\n function wheelListener(ev)\n {\n ev.stop();\n slider.set(slider.step-ev.wheel);\n }\n\n this.boundWheelListener = wheelListener.bindWithEvent(this)\n\n this.addEvent(\"containerShow\", function(){\n $(document.body).addEvent(\"mousewheel\", this.boundWheelListener)\n\n slider.set(this.o.selectedIndex);\n this.container.scrollTo(false,this.o.selectedIndex*scrollStepHeight);\n })\n\n this.addEvent(\"containerHide\", function(){\n $(document.body).removeEvent(\"mousewheel\", this.boundWheelListener);\n })\n\n this.o.addEvent(\"change\", function(){\n slider.set(this.o.selectedIndex)\n }.bind(this))\n }\n}\n\n/**\n * @module Selectable\n */\n\n/**\n * replaces select fields\n *\n *

              disabled should also disable scrolling

              \n * \n *
              Tested in:
              \n *
                \n *
              • Safari 4.
              • \n *
              • Firefox 3.6.
              • \n *
              • Google Chrome 6.
              • \n *
              • Opera 10.62 - key autocompletion closes box.
              • \n *
              • IE 7.
              • \n *
              • IE 8.
              • \n *
              \n *\n * @class Select\n * @namespace cfe.module\n *\n * @extends cfe.module.Button\n *\n */\ncfe.module.Select = new Class({\n\t\n Extends: cfe.module.Button,\n Implements: cfe.helper.Scrollable,\n \n Binds: \"clickedOutsideListener\",\n\n instance: 0,\n\n /**\n * CSS Selector to fetch \"original\" HTMLElements for replacement with this module\n * @property selector\n * @type string\n */\n selector: \"select:not(select[multiple])\",\n\t\n selectedIndex: 0,\n\n setupOriginal: function()\n {\n this.parent();\n \n this.o.addEvents({\n \"keyup\": this.keyup.bind(this),\n \"keydown\": this.keydown.bind(this)\n });\n },\n\n afterInitialize: function()\n {\n this.parent();\n\n // set width to widest option if no width is given to select via css\n if(this.cssWidth == \"auto\") this.a.setStyle(\"width\", this.container.getWidth())\n\n // inject labelArrow as IE 7 doesn't support :after css selector\n if(Browser.Engine.trident5) new Element(\"span\").addClass(\"labelArrow\").inject(this.innerlabel, \"after\")\n\n // select default option\n if(this.selectedIndex != -1) this.selectOption(this.selectedIndex, true);\n\n if(this.options.scrolling)\n {\n this.container.setStyle(\"height\", this.allOptions[0].getHeight()*this.options.size);\n this.setupScrolling();\n }\n\n this.hideContainer();\n },\n\n /**\n * Method to programmatically create an \"original\" HTMLElement\n *\n * @method createOriginal\n * @return {HTMLElement} a select input\n */\n createOriginal: function()\n {\n var ori = new Element(\"select\");\n\n if( $chk(this.options.options) )\n {\n for(var key in this.options.options)\n {\n ori.adopt( new Element(\"option\", {\n value: key,\n selected: this.options.options[key].selected?\"selected\":\"\"\n }).set(\"html\", this.options.options[key].label ) );\n }\n }\n return ori;\n },\n\n build: function()\n {\n this.origOptions = this.o.getChildren();\n\n this.selectedIndex = this.o.selectedIndex || this.selectedIndex;\n\n // integrity check\n if(this.options.size > this.origOptions.length || this.options.scrolling != true) this.options.size = this.origOptions.length;\n \n this.parent();\n\n this.a.setStyles({\"position\": \"relative\", \"z-index\": 100000 - this.instance});\n\n // build container which shows on click\n this.buildContainer();\n\n this.cssWidth = this.a.getStyle(\"width\");\n },\n\n buildContainer: function()\n {\n this.container = new Element(\"span\",{\n \"class\": cfe.prefix+this.type+\"Container\",\n \"styles\":{\n \"overflow\":\"hidden\"\n }\n });\n \n this.containerWrapper = this.container.setSlidingDoors(4, \"span\", cfe.prefix).addClass(cfe.prefix+this.type+\"ContainerWrapper\").setStyles({\n position: \"absolute\",\n \"z-index\": this.instance + 1\n }).inject(this.a);\n\n // insert option elements\n this.allOptions = [];\n this.origOptions.each(function(el,i)\n {\n this.allOptions.push(this.buildOption(el, i))\n }.bind(this));\n\n this.container.adopt(this.allOptions);\n\n },\n\n buildOption: function(el, i)\n {\n return new Element(\"span\",{\n \"class\": cfe.prefix+\"Option \"+cfe.prefix+\"Option\"+i+(el.get('class')?\" \"+el.get('class'):\"\"),\n \"events\":{\n \"mouseover\": this.highlightOption.pass([i,true],this)/*,\n \"mouseout\": this.highlightOption.pass([i,true],this)*/\n }\n }).set('html', el.innerHTML.replace(/\\s/g, \" \")).disableTextSelection().store(\"index\", i);\n },\n\n selectOption: function(index)\n {\n index = index.limit(0,this.origOptions.length-1);\n\n this.highlightOption(index);\n\n this.selectedIndex = index;\n\n this.innerlabel.set('html', (this.allOptions[index]).innerHTML);\n\n this.fireEvent(\"onSelectOption\", index);\n },\n\n highlightOption: function(index)\n {\n index = index.limit(0,this.origOptions.length-1);\n\n if(this.highlighted) this.highlighted.removeClass(\"H\");\n\n this.highlighted = this.allOptions[index].addClass(\"H\");\n\n this.highlightedIndex = index;\n\n this.fireEvent(\"onHighlightOption\", index);\n },\n\n updateOption: function(by)\n {\n // fix for IE 7\n if(this.containerWrapper.retrieve(\"hidden\") != true && !Browser.Engine.trident5) this.o.selectedIndex = (this.highlightedIndex+by).limit(0,this.origOptions.length-1);\n this.o.fireEvent(\"change\");\n },\n\n hideContainer: function()\n {\n $(document.body).removeEvent(\"click\", this.clickedOutsideListener);\n \n this.containerWrapper.setStyle(\"display\",\"none\").removeClass(\"F\").store(\"hidden\", true);\n\n this.fireEvent(\"onContainerHide\", this.selectedIndex);\n },\n\n showContainer: function()\n {\n $(document.body).addEvent(\"click\", this.clickedOutsideListener);\n\n this.containerWrapper.setStyle(\"display\", \"block\").addClass(\"F\").store(\"hidden\", false);\n\n this.highlightOption(this.o.selectedIndex);\n\n this.fireEvent(\"onContainerShow\", this.selectedIndex);\n },\n\n clicked: function(ev)\n {\n if(!this.isDisabled())\n {\n if( $defined(ev.target) )\n {\n var oTarget = $(ev.target);\n\n if( oTarget.getParent() == this.container )\n {\n this.selectOption(oTarget.retrieve(\"index\"), true);\n this.hideContainer();\n this.parent();\n this.o.selectedIndex = oTarget.retrieve(\"index\");\n this.o.fireEvent(\"change\");\n return;\n }\n else if(this.options.scrolling && oTarget.getParent(\".\"+this.scrollerWrapper.getProperty(\"class\")) == this.scrollerWrapper)\n {\n //console.log(\"no toggle\");\n return;\n }\n }\n\n this.toggle();\n this.parent();\n }\n },\n\n toggle: function()\n {\n this.containerWrapper.retrieve(\"hidden\") == true ? this.showContainer() : this.hideContainer();\n },\n\t\n keyup: function(ev)\n {\n // toggle on alt+arrow\n if(ev.alt && (ev.key == \"up\" || ev.key == \"down\") )\n {\n this.toggle();\n return;\n }\n\n switch(ev.key){\n case \"enter\":\n case \"space\":\n this.toggle();\n break;\n\n case \"up\":\n this.updateOption(-1);\n break;\n\n case \"down\":\n this.updateOption(1);\n break;\n\n case \"esc\":\n this.hideContainer();\n break;\n \n default:\n this.o.fireEvent(\"change\");\n break;\n }\n },\n\n keydown: function(ev)\n {\n if(ev.key == \"tab\")\n {\n this.hideContainer();\n }\n },\n\n clickedOutsideListener: function(ev)\n {\n if ($(ev.target).getParent(\".\"+cfe.prefix+this.type) != this.a && !( (Browser.Engine.trident || (Browser.Engine.presto && Browser.Engine.version > 950)) && ev.target == this.o) && ( !$chk(this.l) || (this.l && $(ev.target) != this.l) ) ) this.hideContainer();\n },\n\n update: function()\n {\n this.parent();\n this.selectOption(this.o.selectedIndex);\n }\n});", "demo.html": "\n\n \n \n \n\n \n \n \n \n\n \n \n

              CFE Barebone Example

              \n

              for mootools 1.2

              \n

              \n Visit homepage\n

              \n\n
              \n\n\n
              Checkboxes (input[checkbox])\n \n\n
              \n\n
              Checkboxes with implicit labelling\n

              NOTE: 3rd Checkbox has dependencies: 1st and 2nd get automatically checked if not already

              \n
                \n
              • \n
              • \n\n
              • \n
              • \n\n
              • \n\n
              \n
              \n\n\n
              Radiobuttons (input[radio])\n
                \n
              • \n \n
              • \n\n
              • \n \n
              • \n\n
              • \n
              • \n\n
              • \n
              • \n\n\n
              • \n
              • \n\n
              • \n
              • \n
              \n
              \n\n\n
              Textinput&-area(input[text,password],textarea)- w/ slidingDoors\n
                \n
              • \n \n
              • \n\n
              • \n \n
              • \n\n
              • \n \n
              • \n\n
              • \n \n
              • \n\n
              • trigger textfield 4 disabled/enabled\n
              • \n\n
              • \n \n
              • \n\n
              • \n \n
              • \n\n
              • \n \n
              • \n\n
              • \n \n
              • \n\n
              • trigger textarea 2 disabled/enabled\n
              • \n\n
              • \n \n
              • \n
              \n
              \n\n\n\n
              Textinput&-area with implicit labelling\n
                \n
              • \n
              • \n\n
              • \n
              • \n\n
              • \n
              • \n\n
              • \n\n
              • \n\n
              • \n
              • \n
              \n
              \n\n\n\n \n\n
              Selectfield (select) with and without multiple option and preselected\n
                \n\n
              • \n \n
              • \n\n
              • \n\n \n
              • \n\n
              • \n \n
              • \n\n
              • trigger select 3 disabled/enabled\n
              • \n\n
              • \n \n
              • \n\n
              • \n \n
              • \n\n
              • trigger multiple select 2 disabled/enabled\n
              • \n
              \n
              \n\n\n\n
              file upload (input[file]) -- without and with implicit labelling\n
                \n
              • \n \n
              • \n\n
              • \n
              • \n\n
              • \n \n
              • \n
              \n
              \n\n\n
              \n Check POST Data or Reset Data via Buttons (input[submit], input[reset], input[image])\n\n
                \n
              • \n \n
              • \n\n
              • \n \n
              • \n\n
              • \n \n
              • \n\n
              • \n \n
              • \n\n
              • \n \n
              • \n
              \n\n
              \n\n
              Advanced example: Search field\n
                \n
              • \n \n \" name=\"inputSearchSubmit\" />\n
              • \n
              \n
              \n
              \n\n \n \n \n \n \n \n \n \n\n", "cfe/modules/select/cfe.module.select.multiple.js": "/**\n * @module Selectable\n */\n\n/**\n * replaces select fields with attribute multiple set\n *\n * bug:\n * mouseWheel support needed\n * \n * @class SelectMultiple\n * @namespace cfe.module\n *\n * @extends cfe.module.Select\n */\ncfe.module.SelectMultiple = new Class({\n\t\n Extends: cfe.module.Select,\n instance: 0,\n\n /**\n * CSS Selector to fetch \"original\" HTMLElements for replacement with this module\n * @property selector\n * @type string\n */\n selector: \"select[multiple]\",\n\n options: {\n buttonStyle: false\n },\n\n afterInitialize: function()\n {\n this.containerWrapper.addClass(cfe.prefix+\"SelectContainerWrapper\").setStyles({\n \"position\": \"relative\",\n \"z-index\": \"auto\"\n });\n this.container.addClass(cfe.prefix+\"SelectContainer\");\n\n this.o.addEvents({\n onDisable: function(){\n this.containerWrapper.getElements(\"input, button\").each(function(el){\n el.disable();\n });\n }.bind(this),\n onEnable: function(){\n this.containerWrapper.getElements(\"input, button\").each(function(el){\n el.enable();\n });\n }.bind(this)\n });\n \n this.parent();\n },\n\n setupWrapperEvents: function()\n {\n this.a = this.containerWrapper;\n this.parent();\n },\n\n buildOption: function(el, index)\n {\n var oOpt = new cfe.module.Checkbox({\n label: el.innerHTML,\n checked: $chk(el.selected),\n disabled: this.isDisabled()\n });\n oOpt.index = index;\n\n oOpt.addEvents({\n \"check\": function(index){\n this.origOptions[index].selected = true;\n this.o.fireEvent(\"change\")\n }.pass(index, this),\n \"uncheck\": function(index){\n this.origOptions[index].selected = false;\n this.o.fireEvent(\"change\")\n }.pass(index, this)\n });\n\n $(oOpt).addClass(cfe.prefix+\"Option \"+cfe.prefix+\"Option\"+index+(el.get('class')?\" \".el.get('class'):\"\")).disableTextSelection();\n oOpt.getLabel().removeEvents().inject( $(oOpt) );\n\n return $(oOpt);\n },\n\n selectOption: function(index)\n {\n index = index.limit(0,this.origOptions.length-1);\n\n this.highlightOption(index);\n },\n\n clicked: function()\n {\n if(!this.isDisabled())\n {\n this.o.focus();\n this.fireEvent(\"onClick\");\n }\n },\n\n update: function()\n {\n this.fireEvent(\"onUpdate\");\n },\n\n toggle: function(){},\n keydown: function(){},\n hideContainer: function(){},\n showContainer: function(){}\n});"}, "files_after": {"cfe/modules/file/cfe.module.file.js": "/**\n * @module File\n */\n\n/**\n * replaces file upload fields\n *\n *

              is not resetted onReset

              \n * \n *
              Tested in:
              \n *
                \n *
              • Safari 4 - implicitly labelled triggers when deletin a file; reset doesnt trigger
              • \n *
              • Firefox 3.6.
              • \n *
              • Google Chrome 6 - implicitly labelled triggers twice, when using alias button & triggers when deletin a file.
              • \n *
              • Opera 10.62.
              • \n *
              • IE 7 - gaga.
              • \n *
              • IE 8 - implicitly labelled triggers when deletin a file.
              • \n *
              \n *\n * @class File\n * @namespace cfe.modules\n *\n * @extends cfe.module.Button\n */\n\ncfe.module.File = new Class({\n \n Extends: cfe.module.Button,\n \n instance: 0,\n\n /**\n * CSS Selector to fetch \"original\" HTMLElements for replacement with this module\n * @property selector\n * @type string\n */\n selector: \"input[type=file]\",\n\t\n options: {\n /**\n * enables the use of fileicons through a bit of markup and css\n * @config fileIcons\n * @type boolean\n * @default true\n */\n fileIcons: true,\n /**\n * show only the filename, not the whole path\n * @config trimFilePath\n * @type boolean\n * @default true\n */\n trimFilePath: true,\n\n innerLabel: \"Choose File\"\n },\n\n hideOriginalElement: false,\n\n toElement: function()\n {\n return this.wrapa\n },\n\n /**\n * retreive the filepath\n *\n * @method getFilePath\n * @return {HTMLElement}\n */\n getFilePath: function()\n {\n return this.v;\n },\n\n afterInitialize: function()\n {\n this.a = this.button;\n \n if(this.hideOriginalElement) this.o.hideInPlace();\n\n if(this.o.id) this.wrapa.addClass(cfe.prefix+this.type+this.o.id.capitalize());\n\n // various additions\n if(!this.o.implicitLabel && !Browser.safari && !Browser.chrome) this.wrapa.addEvent(\"click\", this.clicked.pass([e],this));\n\n if(this.isDisabled()) this.disable();\n\n if(!this.options.slidingDoors) this.wrapa.addClass(cfe.prefix+this.type)\n\n if(this.options.buttonStyle) this.a.addClass(cfe.prefix+\"Button\")\n\n this.a.removeClass(cfe.prefix+this.type)\n },\n\n build: function()\n {\n this.parent();\n this.innerlabel.set(\"text\", Array.pick(this.options.innerLabel, \"\"));\n\n // make original element follow mouse\n // setup wrapper\n this.wrapa = new Element(\"span\",{\n \"class\": cfe.prefix+this.type,\n styles:\n {\n overflow: \"hidden\",\n position: \"relative\"\n }\n }).cloneEvents(this.a)\n \n this.wrapa.inject(this.a, \"after\").adopt(this.a, this.o);\n\n // add positioning styles and events to \"hidden\" file input\n this.o.addEvents({\n \"mouseout\": this.update.bind(this),\n \"change\": this.update.bind(this),\n onDisable: this.disable.bind(this),\n onEnable: this.enable.bind(this)\n }).setStyles({\n opacity: \"0\",\n visibility: \"visible\",\n height: \"100%\",\n width: \"auto\",\n position: \"absolute\",\n top: 0,\n right: 0,\n margin: 0\n });\n\n this.wrapa.addEvent(\"mousemove\", this.follow.pass([e],this));\n\n this.button = this.a;\n this.a = this.wrapa;\n \n // add filepath\n this.v = new Element(\"span\").addClass(cfe.prefix+this.type+\"Path hidden\");\n\t\t\n this.path = new Element(\"span\").addClass(\"filePath\");\n\n if(this.options.fileIcons)\n {\n this.path.addClass(\"fileIcon\");\n }\n\n this.cross = $( new cfe.module.Button({delegateClick: false}).addEvent(\"click\", this.deleteCurrentFile.bind(this)) ).addClass(\"delete\");\n\n this.v.adopt(this.path, this.cross).inject(this.wrapa, \"after\");\n\n this.update();\n },\n\n /**\n * Method to programmatically create an \"original\" HTMLElement\n *\n * @method createOriginal\n * @return {HTMLElement} an input field of type \"file\"\n */\n createOriginal: function()\n {\n return new Element(\"input\",{\n type: \"file\"\n });\n },\n\t\n follow: function(ev)\n {\n this.o.setStyle(\"left\",(ev.client.x-this.a.getLeft()-(this.o.getWidth()-30)));\n\t\t\n /* special treatment for internet explorer as the fileinput will not be cut off by overflow:hidden */\n if(Browser.ie){\n if(ev.client.x < this.a.getLeft() || ev.client.x > this.a.getLeft()+this.a.getWidth())\n this.o.setStyle(\"left\", -9999);\n }\n },\n\t\n update: function()\n {\n // only do stuff if original element is not disabled\n if( this.o.disabled == null )\n {\n if( this.o.value != \"\" )\n {\n this.o.disable().blur();\n\n this.oldValue = this.o.getProperty(\"value\");\n if(this.options.trimFilePath) this.oldValue = this.oldValue.trimFilePath();\n this.path.set(\"html\", this.oldValue);\n\n if(this.options.fileIcons)\n {\n var ind = this.oldValue.lastIndexOf(\".\");\n this.path.setProperty(\"class\",\"filePath fileIcon \" + this.oldValue.substring(++ind).toLowerCase());\n }\n this.v.removeClass(\"hidden\");\n }\n else\n {\n this.o.enable().focus();\n\n this.path.set(\"html\", \"\");\n this.v.addClass(\"hidden\");\n }\n\n this.parent();\n }\n },\n\t\n deleteCurrentFile: function()\n {\n // we dont clone the old file input here, since the attribute \"value\" would be cloned, too\n // and we cannot modify the value of an file input field without user interaction\n this.o = this.createOriginal().addClass(this.o.getProperty(\"class\")).setProperties({\n name: this.o.getProperty(\"name\"),\n id: this.o.getProperty(\"id\"),\n style: this.o.getProperty(\"style\"),\n title: this.o.getProperty(\"title\")\n }).cloneEvents(this.o).replaces(this.o);\n\t\t\n this.update();\n }\n});\n\n// add trimFilePath to Native String for convenience\nString.implement({\n trimFilePath: function()\n {\n var ind = false;\n if(!(ind = this.lastIndexOf(\"\\\\\")))\n if(!(ind = this.lastIndexOf(\"\\/\")))\n ind = 0;\n\n return this.substring(++ind);\n }\n});", "cfe/base/cfe.base.js": "/**\n * The core of custom form elements. Includes cfe.Generic and some slight addons to the native Element object. \n *\n * @module Core\n * @namespace cfe\n */\n\nvar cfe = {\n version: \"0.9.9\",\n prefix: \"cfe\",\n module: {},\n addon: {}\n};\n\n/**\n * extend Elements with some Helper functions\n * @class Helpers\n * @namespace Element\n */\nElement.Helpers = new Class({\n\n /**\n * cross-browser method for disabling the text selection by setting css attributes\n * \n * @method disableTextSelection\n */\n disableTextSelection: function(){\n if(Browser.ie || Browser.opera){\n this.setProperty(\"unselectable\",\"on\");\n }\n else if(Browser.firefox){\n this.setStyle(\"MozUserSelect\",\"none\");\n }\n else if(Browser.safari || Browser.chrome){\n this.setStyle(\"KhtmlUserSelect\",\"none\");\n }\n\n return this;\n },\n\n /**\n * disables a HTMLElement if its a form element by setting the disabled attribute to true\n *\n * @method disable\n * @return boolean true, if element could be disabled\n */\n disable: function()\n {\n if(typeOf(this) === \"element\" && [\"button\", \"input\", \"option\", \"optgroup\", \"select\", \"textarea\"].contains( this.get(\"tag\") ) )\n {\n this.setProperty(\"disabled\", true);\n this.fireEvent(\"onDisable\");\n }\n\n return this;\n },\n\n /**\n * enables a HTMLElement if its a form element by setting the disabled attribute to false\n *\n * @method enable\n * @return {boolean} true, if element could be enabled\n */\n enable: function()\n {\n if(typeOf(this) === \"element\" && [\"button\", \"input\", \"option\", \"optgroup\", \"select\", \"textarea\"].contains( this.get(\"tag\") ) )\n {\n this.setProperty(\"disabled\", false);\n this.fireEvent(\"onEnable\");\n }\n\n return this;\n },\n\n /**\n * enables or disabled a HTMLElement if its a form element depending on it's current state\n *\n * @method toggleDisabled\n * @return {boolean} true, if element could be toggled\n */\n toggleDisabled: function()\n {\n if(typeOf(this) === \"element\" && [\"button\", \"input\", \"option\", \"optgroup\", \"select\", \"textarea\"].contains( this.get(\"tag\") ) )\n {\n this.setProperty(\"disabled\", !this.getProperty(\"disabled\") );\n this.fireEvent(this.getProperty(\"disabled\")?\"onDisable\":\"onEnable\");\n }\n return this;\n },\n\n /**\n * returns the label-element which belongs to this element\n *\n * @method getLabel\n * @return HTMLElement or NULL\n */\n getLabel: function()\n {\n var label = null;\n\n // get label by id/for-combo\n if(this.id) label = $$(\"label[for=\"+this.id+\"]\")[0];\n \n // no label was found for id/for, let's see if it's implicitly labelled\n if(!label)\n {\n label = this.getParent('label');\n\n if(label) this.implicitLabel = true;\n }\n\n return label;\n },\n\n /**\n * generates the markup used by sliding doors css technique to use with this element\n *\n * @method setSlidingDoors\n *\n * @param count\n * @param type\n * @param prefix\n * \n * @return HTMLElement or NULL the wrapped HTMLElement\n */\n setSlidingDoors: function(count, type, prefix, suffixes)\n {\n var slide = null;\n var wrapped = this;\n prefix = Array.pick(prefix, \"sd\");\n\n suffixes = Array.pick(suffixes, []);\n\n for(var i = count; i > 0; --i)\n {\n wrapped.addClass( prefix+\"Slide\"+( (i == 1 && count == i) ? \"\" : (suffixes[i] || i) ));\n slide = new Element(type);\n try{\n wrapped = slide.wraps(wrapped);\n }catch(e){\n wrapped = slide.grab(wrapped);\n }\n }\n\n wrapped = null;\n\n return slide;\n },\n\n /**\n * hide an element but keep it's vertical position and leave it tab- & screenreader-able :)\n *\n * @method hideInPlace\n *\n * @return HTMLElement\n */\n hideInPlace: function()\n {\n return this.setStyles({\n position: \"absolute\",\n left: -99999,\n width: 1,\n height: 1\n });\n }\n});\n\nElement.implement(new Element.Helpers);", "cfe/modules/check/cfe.module.radio.js": "/**\n * @module Checkable\n */\n\n/**\n *

              replaces radiobuttons

              \n *\n *
              Tested in:
              \n *
                \n *
              • Safari 4.
              • \n *
              • Firefox 3.6.
              • \n *
              • Google Chrome 6.
              • \n *
              • Opera 10.62.
              • \n *
              • IE 7.
              • \n *\n *
              • IE 8\n *
                  \n *
                • labels dont work for normal labelled elements
                • \n *
                \n *
              • \n *\n *
              \n *\n * @class Radiobutton\n * @namespace cfe.module\n *\n * @extends cfe.modules.Checkbox\n */\ncfe.module.Radiobutton = new Class({\n\n Extends: cfe.module.Checkbox,\n\n instance: 0,\n\n /**\n * CSS Selector to fetch \"original\" HTMLElements for replacement with this module\n * @property selector\n * @type string\n */\n selector: \"input[type=radio]\",\n\n /**\n * Method to programmatically create an \"original\" HTMLElement\n *\n * @method createOriginal\n * @return {HTMLElement} an input field of type \"radio\"\n */\n createOriginal: function()\n {\n return new Element(\"input\",{\n \"type\": \"radio\",\n \"checked\": this.options.checked\n });\n },\n\n /**\n * @method initializeAdv\n * @protected\n */\n afterInitialize: function()\n {\n this.parent();\n \n if( !(Browser.ie || Browser.firefox) ) this.o.addEvent(\"click\", this.update.bind(this));\n\n // on check, disable all other radiobuttons in this group\n this.addEvent(\"check\", function(){\n $$(\"input[name='\"+this.o.get(\"name\")+\"']\").each(function(el)\n {\n if(el != this.o && el.retrieve(\"cfe\")) el.retrieve(\"cfe\").uncheck();\n }.bind(this));\n })\n }\n});", "cfe/replace/cfe.replace.js": "/**\n * replacement class for automated replacment of scoped form elements\n *\n * @module replace\n * @namespace cfe\n *\n */\n\ncfe.Replace = new Class(\n{\n Implements: [new Options, new Events],\n\n options:{\n scope: false,\n\t\t\n onInit: function(){},\n onInitSingle: function(){},\n onBeforeInitSingle: function(){},\n onSetModuleOption: function(){},\n onRegisterModule: function(){},\n onUnregisterModule: function(){},\n onComplete: function(){}\n },\n\t\t\n modules: {},\n moduleOptions: {},\n moduleOptionsAll: {},\n\t\n initialize: function()\n {\n this.registerAllModules.bind(this)();\n },\n\t\n /**\n * @method registerAllModules\n\t * registeres all loaded modules onInitialize\n\t */\n registerAllModules: function(){\n\t\t\n //console.log(\"Register all modules\");\n\t\t\n Object.each(cfe.module, function(modObj, modType){\n //console.log(\"Registering type \"+modType);\n if(modType != \"Generic\")\n this.registerModule(modType);\n\t\t\t\t\n },this);\n },\n\t\n /* call to register module */\n registerModule: function(mod){\n\t\t\n //console.log(\"Call to registerModule with arg:\"+mod);\n modObj = cfe.module[mod];\n\t\t\n this.fireEvent(\"onRegisterModule\", [mod,modObj]);\n this.modules[mod] = modObj;\n this.moduleOptions[mod] = {};\n\n return true;\n },\n\t\n registerModules: function(mods)\n {\n Object.each(mods,function(mod){\n this.registerModule(mod);\n },this);\n },\n\t\n unregisterModule: function(mod)\n {\n modObj = cfe.module[mod];\n\t\t\n this.fireEvent(\"onUnregisterModule\", [mod,modObj]);\n\n delete this.modules[mod];\n },\n\t\n unregisterModules: function(mods)\n {\n Object.each(mods,function(mod){\n this.unregisterModule(mod);\n },this);\n },\n /**\n\t * sets a single option for a specified module\n\t * if no module was given, it sets the options for all modules\n\t *\n * @method setModuleOption\n *\n\t * @param {String} \tmod \tName of the module\n\t * @param {String} \topt \tName of the option\n\t * @param {Mixed} \tval\t\tThe options value\n\t */\n setModuleOption: function(mod,opt,val){\n\t\t\n modObj = cfe.module[mod];\n\t\t\n this.fireEvent(\"onSetModuleOption\", [mod,modObj,opt,val]);\n\t\t\n if(!modObj){\n this.moduleOptionsAll[opt] = val;\n }\n else{\n this.moduleOptions[mod][opt] = val;\n }\n },\n\n setModuleOptions: function(mod,opt){\n\t\t\n Object.each(opt, function(optionValue, optionName){\n this.setModuleOption(mod,optionName,optionValue);\n },this);\n\t\t\n },\n\n engage: function(options){\n\n this.setOptions(this.options, options);\n\n if(typeOf(this.options.scope) != \"element\"){\n this.options.scope = $(document.body);\n }\n\n this.fireEvent(\"onInit\");\n\t\t\n Object.each(this.modules,function(module,moduleName,i){\n\t\t\t\n var selector = module.prototype.selector;\n\t\t\t\n this.options.scope.getElements(selector).each(function(el,i){\n\n if(el.retrieve(\"cfe\") != null){\n\n var basicOptions = {\n replaces: el\n };\n\n this.fireEvent(\"onBeforeInitSingle\", [el,i,basicOptions]);\n\n var single = new module(Object.merge({},basicOptions,Object.merge({},this.moduleOptions[moduleName],this.moduleOptionsAll)));\n\t\t\t\t\n this.fireEvent(\"onInitSingle\", single);\n }else{\n this.fireEvent(\"onSkippedInitSingle\", [el,i,basicOptions]); \n }\n\t\t\t\t\n },this);\n },this);\n\t\t\n this.fireEvent(\"onComplete\");\n }\n});", "cfe/modules/check/cfe.module.checkbox.js": "/**\n * @module Checkable\n */\n\n/**\n *

              replaces checkboxes

              \n * \n *
              Tested in:
              \n *
                \n *
              • Safari 4.
              • \n *
              • Firefox 3.6.
              • \n *
              • Google Chrome 6.
              • \n *
              • Opera 10.62.
              • \n *
              • IE 7.
              • \n *
              • IE 8.
              • \n *
              \n *\n * @class Checkbox\n * @namespace cfe.module\n * \n * @extends cfe.module.Button\n */\ncfe.module.Checkbox = new Class({\n \n Extends: cfe.module.Button,\n \n instance: 0,\n\n /**\n * CSS Selector to fetch \"original\" HTMLElements for replacement with this module\n * @property selector\n * @type string\n */\n selector: \"input[type=checkbox]\",\n\n options:{\n /**\n * @inherit\n */\n slidingDoors: false\n /**\n * Fired when the original element gets checked\n * @event onCheck\n */\n //onCheck: Class.empty,\n /**\n * Fired when the original element's checked state is set to false\n * @event onUnCheck\n */\n //onUncheck: Class.empty\n },\n\n afterInitialize: function()\n {\n this.parent();\n\n // important for resetting dynamically created cfe\n this.o.defaultChecked = this.o.checked;\n\n if( Browser.ie || Browser.opera )\n {\n //console.log(\"fix for element update (IE and Opera)\")\n this.o.addEvent(\"click\", this.update.bind(this) );\n }\n\n\n if(Browser.ie && this.o.implicitLabel)\n {\n //console.log(\"fix for implicit labels (IE) element[\"+this.o.id+\"]\")\n this.l.removeEvents(\"click\")\n this.a.removeEvents(\"click\").addEvent(\"click\", function(e){\n e.stop();\n this.clicked.bind(this)();\n }.bind(this))\n }\n\n this.update();\n },\n\n /**\n * Method to programmatically create an \"original\" HTMLElement\n *\n * @method createOriginal\n * @return {HTMLElement} an input field of type \"checkbox\"\n * @protected\n */\n createOriginal: function()\n {\n return new Element(\"input\",{\n type: \"checkbox\",\n checked: this.options.checked\n });\n },\n\n clicked: function(e)\n {\n if(Browser.ie && e) e.stop();\n\n this.parent()\n },\n\n /**\n * public method to check a checkbox programatically\n *\n * @method check\n * @public\n */\n check: function()\n {\n this.a.addClass(\"A\");\n this.fireEvent(\"onCheck\");\n },\n\n /**\n * public method to uncheck a checkbox programatically\n *\n * @method uncheck\n * @public\n */\n uncheck: function()\n {\n this.a.removeClass(\"A\");\n this.fireEvent(\"onUncheck\");\n },\n\n update: function()\n {\n this.o.checked ? this.check() : this.uncheck();\n this.parent();\n }\n});", "cfe/addons/cfe.addon.toolTips.js": "/**\n * @module Addon\n */\n\n/**\n * pretty simple integration of auto-generated tooltips (from title-attribute)\n * depends on mootools Tips\n *\n * @class Tips\n * @namespace cfe.addon\n *\n */\ncfe.addon.Tips = new Class({\n\t\n options: Object.merge({},this.parent, {\n enableTips: true,\n ttStyle: \"label\",\n ttClass: cfe.prefix+\"Tip\"\n }),\n\t\n initToolTips: function(){\n\t\t\n if(!window.Tips || !this.options.enableTips){\n if(this.options.debug){\n this.throwMsg.bind(this)(\"CustomFormElements: initialization of toolTips failed.\\nReason: Mootools Plugin 'Tips' not available.\");\n }\n \n return false;\n }\n\t\n switch(this.options.ttStyle){\n default:case 'label': this.toolTipsLabel.bind(this)();break;\n }\n\n return true;\n },\n\t\n toolTipsLabel: function(){\n\t\t\n var labels = this.options.scope.getElements('label');\n \t\t\n labels.each(function(lbl,i){\n\n forEl = lbl.getProperty(\"for\");\n\t\t\t\n if(!forEl){\n var cl = lbl.getProperty(\"class\");\n\t\t\t\t\n if( cl != null ){\n var forEl = cl.match(/for_[a-zA-Z0-9\\-]+/);\n\n if(forEl){\n forEl = forEl.toString();\n el = $( forEl.replace(/for_/,\"\") );\n } \n }\n\t\t\t\t\n if(!el){\n el = lbl.getElement(\"input\");\n }\n }else{\n el = $(forEl);\n }\n\n if(el){\n if((qmTitle = el.getProperty(\"title\")) != null){\n\t\t\t\t\t\n el.setProperty(\"title\",\"\").setProperty(\"hint\", qmTitle)\n\t\t\t\t\t\n var qm = new Element(\"span\",{\n \"class\": this.options.ttClass,\n \"title\": qmTitle\n });\n \n // check if implicit label span is present\n var impLabel = lbl.getFirst(\"span[class=label]\");\n \n qm.inject((impLabel != null)?impLabel:lbl,'inside');\n }\n }\n },this);\n\t\t\n new Tips($$('.'+this.options.ttClass+'[title]'));\n }\n});\n\ncfe.Replace.implement(new cfe.addon.Tips);\ncfe.Replace.prototype.addEvent(\"onComplete\", function(){\n this.initToolTips();\n});", "cfe/addons/cfe.addon.dependencies.js": "/**\n * @module Addon\n */\n\n/**\n * adds dependencies to checkboxes\n *\n * @class Dependencies\n * @namespace cfe.addon\n *\n */\ncfe.addon.Dependencies = new Class({\n\t\n /**\n\t * adds dependencies for an element \n\t * @param {Object} el\n\t * @param {Array} dep\n\t */\n addDependencies: function(el, deps){\n Array.each(deps,function(dep){\n this.addDependency(el,dep);\n },this);\n },\n\t\n /**\n\t * adds dependency for an element \n\t * @param {Object} el\n\t * @param {Object} dep\n\t */\n addDependency: function(el, dep){\n\t\t\n // create an array if needed\n if(typeOf( el.retrieve('deps') ) !== \"array\"){\n el.store('deps', []);\n }\n\t\t\n // deps may be objects or strings > if a string was given, try to interpret it as id and fetch element by $()\n if(typeOf(dep) === \"string\" || typeOf(dep) === \"element\"){\n el.retrieve('deps').push( $(dep) );\n return true;\n }\n\t\t\n return false;\n },\n\t\n getDependencies: function(el)\n {\n return el.retrieve('deps');\n },\n\t\n /**\n\t * this is called when a new item of a cfemodule gets initialized\n\t * it checks, whether there are dependencies for this element and adds them to its options\n\t * \n\t * @param {Object} el\n\t */\n attachDependencies: function(el,i,baseOptions)\n {\n var deps = this.getDependencies(el);\n\t\t\n if(typeOf(deps) === \"array\"){\n baseOptions.deps = deps;\n return true;\n }\n\t\n return false;\n }\n\t\t\n});\ncfe.Replace.implement(new cfe.addon.Dependencies);\ncfe.Replace.prototype.addEvent(\"onBeforeInitSingle\", cfe.Replace.prototype.attachDependencies);\n\ncfe.addon.Dependencies.Helper = new Class({\n resolveDependencies: function()\n {\n var deps = this.o.retrieve('deps');\n\t\t\n if(deps){\n Array.each(deps, function(dep,i){\n dep.checked = true;\n dep.fireEvent(\"change\");\n },this);\n }\n }\n});\n\n// support for checkboxes\ncfe.module.Checkbox.implement(new cfe.addon.Dependencies.Helper);\ncfe.module.Checkbox.prototype.addEvent(\"onCheck\", function(){\n this.resolveDependencies();\n});", "cfe/modules/button/cfe.module.button.js": "/**\n * @module Button\n */\n\n/**\n * gets extended by modules to start off with standard, button-like behaviours.\n *\n * when focused and pressed, form gets submitted\n *\n * @class Button\n * @namespace cfe.module\n *\n */\ncfe.module.Button = new Class(\n{\n Implements: [new Options, new Events],\n\n selector: \"button\",\n\n instance: 0,\n\n /**\n * basic options for all cfes and always available\n * @property options\n */\n options: {\n /**\n * if > 0, it will create markup for css sliding doors tech
              \n * the number defines the amount of wrappers to create around this element
              \n * 2: standard sliding doors (x- or y-Axis)
              \n * 4: sliding doors in all directions (x/y-Axis)\n *\n * @config slidingDoors\n * @type int\n * @default 4\n */\n slidingDoors: 2,\n\n /**\n * if this element shall replace an existing html form element, pass it here\n * @config replaces\n * @type HTMLElement\n */\n replaces: null,\n\n /**\n * determines if a click on the decorator should be delegated to the original element\n * @config delegateClick\n * @type Boolean\n */\n delegateClick: true,\n\n /**\n * may pass any element as a label (toggling, hovering,..) for this cfe\n * @config label\n * @type HTMLElement\n */\n label: null,\n\n /**\n * if this cfe is created programatically, it's possible to set the name attribute of the generated input element\n * @config name\n * @type string\n */\n name: \"\",\n\n /**\n * setting this to true will create a disabled element\n * @config disabled\n * @type boolean\n */\n disabled: false,\n\n buttonStyle: true\n\n /**\n * Fired when the mouse is moved over the \"decorator\" element\n * @event onMouseOver\n */\n //onMouseOver: Class.empty,\n\n /**\n * Fired when the mouse is moved away from the \"decorator\" element\n * @event onMouseOut\n */\n //onMouseOut: Class.empty,\n\n /**\n * Fired when the \"original\" element gets focus (e.g. by tabbing)\n * @event onFocus\n */\n //onFocus: Class.empty,\n\n /**\n * Fired when the \"original\" element loses focus\n * @event onBlur\n */\n //onBlur: Class.empty,\n\n /**\n * Fired when \"decorator\" is clicked by mouse\n * @event onClick\n */\n //onClick: Class.empty,\n\n /**\n * Fired when pressing down with the mouse button on the \"decorator\"\n * Fired when pressing the space key while \"original\" has focus\n * @event onPress\n */\n //onPress: Class.empty,\n\n /**\n * Fired when \"decorator\" was pressed and the mouse button is released\n * Fired when \"original\" was pressed by space key and this key is released\n * @event onRelease\n */\n //onRelease: Class.empty,\n\n /**\n * Fired when \"original\"'s value changes\n * @event onUpdate\n */\n //onUpdate: Class.empty,\n\n /**\n * Fired when \"original\" gets disabled by HTMLElement.enable()\n * @event onEnable\n */\n //onEnable: Class.empty,\n\n /**\n * Fired when \"original\" gets disabled by HTMLElement.disable()\n * @event onDisable\n */\n //onDisable: Class.empty,\n\n /**\n * Fired when decorator is completely loaded and is ready to use\n * @event onLoad\n */\n //onLoad: Class.empty\n\n\n },\n\n hideOriginalElement: true,\n\n /**\n * constructor
              \n * building algorithm for cfe (template method)
              \n *
                \n *
              1. setOptions: set Options
              2. \n *
              3. buildWrapper: setup the \"decorator\"
              4. \n *
              5. setupOriginal: procede the \"original\" element (add Events...)
              6. \n *
              7. addLabel: add and procede the label
              8. \n *
              9. initializeAdv: last chance for subclasses to do initialization
              10. \n *
              11. build: various specific dom handling and \"decorator\" building
              12. \n *\n * @method initialize\n * @constructor\n *\n * @param {Object} options\n **/\n initialize: function(opt)\n {\n // sets instance id\n this.instance = this.constructor.prototype.instance++;\n\n this.setOptions(opt);\n\n this.type = Array.pick(this.options.type, cfe.module.keyOf(this.constructor));\n\n this.buildWrapper();\n\n // prepares original html element for use with cfe and injects decorator into dom\n this.setupOriginal();\n\n // add a label, if present\n this.addLabel( Array.pick(this.o.getLabel(), this.setupLabel(this.options.label) ) );\n\n this.build();\n\n // add events to wrapping element\n this.setupWrapperEvents();\n\n // specific initialization\n this.afterInitialize();\n\n this.fireEvent(\"load\")\n },\n\n /**\n * retreive the \"decorator\"\n * mootools supports the use of $(myCfe) if toElement is defined\n *\n * @method toElement\n * @return {HTMLElement}\n */\n toElement: function()\n {\n return this.a;\n },\n\n /**\n * retreive the label\n *\n * @method getLabel\n * @return {HTMLElement}\n */\n getLabel: function()\n {\n return this.l;\n },\n\n /**\n * template method STEP 1\n */\n buildWrapper: function(){\n this.a = new Element(\"span\");\n },\n\n /**\n * handles the creation of the underlying original form element
                \n * stores a reference to the cfe object in the original form element\n * template method STEP 2\n *\n * @method setupOriginal\n * @protected\n */\n setupOriginal: function()\n {\n // get original element\n if( this.options.replaces != null )\n {\n this.o = this.options.replaces;\n this.a.inject(this.o, 'before');\n }\n else // standalone\n {\n this.o = this.createOriginal();\n\n if(this.options.id) this.o.setProperty(\"id\", this.options.id);\n\n if(this.options.disabled) this.o.disable();\n\n if(this.options.name)\n {\n this.o.setProperty(\"name\", this.options.name);\n\n if( this.o.id == null ) this.o.setProperty(\"id\", this.options.name+this.instance);\n }\n\n if(this.options.value) this.o.setProperty(\"value\", this.options.value);\n\n this.a.adopt(this.o);\n }\n\n this.o.addEvents({\n focus: this.setFocus.bind(this),\n blur: this.removeFocus.bind(this),\n change: this.update.bind(this),\n keydown: function(e){\n if(e.key == \"space\") this.press();\n }.bind(this),\n keyup: function(e){\n if(e.key == \"space\") this.release();\n }.bind(this),\n onDisable: function(){\n this.a.fireEvent(\"disable\");\n }.bind(this),\n onEnable: function(){\n this.a.fireEvent(\"enable\");\n }.bind(this)\n });\n\n // store a reference to this cfe \"in\" the original form element\n this.o.store(\"cfe\", this);\n },\n\n /*\n * adds a label element to this cfe\n * template method STEP 3\n *\n * @method addLabel\n * @protected\n *\n * @param {HTMLElement} the label element to set as label for this cfe\n */\n addLabel: function(label)\n {\n if( label == null ) return;\n\n this.l = label;\n\n // remove for property\n if(!this.dontRemoveForFromLabel) this.l.removeProperty(\"for\");\n\n // add adequate className, add stdEvents\n this.l.addClass(cfe.prefix+this.type+\"L\");\n\n if(this.o.id || this.o.name) this.l.addClass(\"for_\"+ (this.o.id || (this.o.name+this.o.value).replace(\"]\",\"-\").replace(\"[\",\"\") ));\n\n // add stdevents\n this.l.addEvents({\n mouseover: this.hover.bind(this),\n mouseout: this.unhover.bind(this),\n mousedown: this.press.bind(this),\n mouseup: this.release.bind(this),\n click: this.clicked.bind(this,[e])\n });\n\n this.addEvents({\n press: function()\n {\n this.l.addClass(\"P\");\n },\n release: function()\n {\n this.l.removeClass(\"P\");\n },\n mouseOver: function()\n {\n this.l.addClass(\"H\");\n },\n mouseOut: function()\n {\n this.l.removeClass(\"H\");\n this.l.removeClass(\"P\");\n },\n focus: function()\n {\n this.l.addClass(\"F\");\n },\n blur: function()\n {\n this.l.removeClass(\"F\");\n //this.l.removeClass(\"P\");\n },\n enable: function()\n {\n this.l.removeClass(\"D\");\n },\n disable: function()\n {\n this.l.addClass(\"D\");\n }\n });\n },\n\n /**\n * part of the main template method for building the \"decorator\"
                \n * must be extended by subclasses\n *\n * template method STEP 4\n *\n * @method build\n * @protected\n */\n build: function(){\n\n this.innerlabel = this.setupInnerLabel();\n this.a.adopt(this.innerlabel);\n\n if( this.options.slidingDoors != null )\n {\n this.a = this.a.setSlidingDoors(this.options.slidingDoors-1, \"span\", cfe.prefix).addClass(cfe.prefix+this.type);\n }\n },\n\n\n /**\n * adds events and mousepointer style to the \"decorator\"\n * usually gets called by buildWrapper\n *\n * template method STEP 5\n *\n * @method setupWrapperEvents\n * @protected\n */\n setupWrapperEvents: function()\n {\n if(!this.o.implicitLabel)\n {\n this.a.addEvents({\n mouseover: this.hover.bind(this),\n mouseout: this.unhover.bind(this),\n mousedown: this.press.bind(this),\n mouseup: this.release.bind(this)\n });\n }\n\n this.a.addEvents({\n disable: this.disable.bind(this),\n enable: this.enable.bind(this)\n })\n \n },\n\n /**\n * part of the main template method for building the \"decorator\"
                \n * gets called immediately before the build-method
                \n * may be extended by subclasses\n *\n * template method STEP 6\n *\n * @method initializeAdv\n * @protected\n */\n afterInitialize: function()\n {\n if(this.hideOriginalElement) this.o.hideInPlace();\n\n if(this.o.id) this.a.addClass(cfe.prefix+this.type+this.o.id.capitalize());\n\n // various additions\n if(!this.o.implicitLabel) this.a.addEvent(\"click\", this.clicked.pass([e],this));\n\n if(this.isDisabled()) this.a.fireEvent(\"disable\");\n\n if(!this.options.slidingDoors) this.a.addClass(cfe.prefix+this.type)\n\n if(this.options.buttonStyle) this.a.addClass(cfe.prefix+\"Button\")\n },\n\n setupInnerLabel: function(){\n return new Element(\"span\").addClass(\"label\").disableTextSelection();\n },\n\n\n /**\n * getter for retrieving the disabled state of the \"original\" element\n *\n * @method isDisabled\n * @return boolean\n */\n isDisabled: function()\n {\n return this.o.getProperty(\"disabled\")\n },\n\n /**\n * programatically creates an \"original\" element
                \n * each subclass has to implement this\n *\n * @method createOriginal\n * @return {HTMLElement}\n */\n createOriginal: function()\n {\n return new Element(\"button\")\n },\n\n /*\n * creates a label element and fills it with the contents (may be html) given by option \"label\"\n *\n * @method setupLabel\n * @protected\n *\n * @return {HTMLElement or NULL} if option \"label\" is not set\n */\n setupLabel: function()\n {\n if( this.options.label != null ) return new Element(\"label\").set(\"html\", this.options.label).setProperty(\"for\", this.o.id);\n\n return null;\n },\n\n /**\n * wrapper method for event onPress
                \n * may be extended by subclasses\n *\n * @method press\n * @protected\n */\n press: function()\n {\n if(this.isDisabled()) return\n\n this.a.addClass(\"P\");\n this.fireEvent(\"onPress\");\n\n //console.log(this.type + \"pressed\");\n },\n\n /**\n * wrapper method for event onRelease
                \n * may be extended by subclasses\n *\n * @method release\n * @protected\n */\n release: function()\n {\n if(this.isDisabled()) return\n\n this.a.removeClass(\"P\");\n this.fireEvent(\"onRelease\");\n \n //console.log(this.type + \"released\");\n\n },\n\n /**\n * wrapper method for event onMouseOver
                \n * may be extended by subclasses\n *\n * @method onMouseOver\n * @protected\n */\n hover: function()\n {\n if(this.isDisabled()) return\n\n this.a.addClass(\"H\");\n this.fireEvent(\"onMouseOver\");\n\n //console.log(this.type + \"hovered\");\n },\n\n /**\n * wrapper method for event onMouseOut
                \n * may be extended by subclasses\n *\n * @method unhover\n * @protected\n */\n unhover: function()\n {\n if(this.isDisabled()) return\n\n this.a.removeClass(\"H\");\n this.fireEvent(\"onMouseOut\");\n this.release();\n\n //console.log(this.type + \"unhovered\");\n },\n\n /**\n * wrapper method for event onFocus
                \n * may be extended by subclasses\n *\n * @method setFocus\n * @protected\n */\n setFocus: function()\n {\n this.a.addClass(\"F\");\n this.fireEvent(\"onFocus\");\n\n //console.log(this.type + \"focused\");\n },\n\n /**\n * wrapper method for event onBlur
                \n * may be extended by subclasses\n *\n * @method removeFocus\n * @protected\n */\n removeFocus: function()\n {\n //console.log(\"o blurred\");\n this.a.removeClass(\"F\");\n // if cfe gets blurred, also clear press state\n //this.a.removeClass(\"P\");\n this.fireEvent(\"onBlur\");\n\n //console.log(this.type + \"blurred\");\n\n },\n\n /**\n * wrapper method for event onClick
                \n * delegates the click to the \"original\" element
                \n * may be extended by subclasses\n *\n * @method clicked\n * @protected\n */\n clicked: function(e)\n {\n //causes problems in other browsers than ie - gonna took into this later; its the best approach to stop the event from bubbling right here though imho\n //e.stop();\n\n if(this.isDisabled()) return\n\n if( $chk(this.o.click) && this.options.delegateClick != null ) this.o.click();\n this.o.focus();\n\n this.fireEvent(\"onClick\");\n\n //console.log(this.type + \" clicked\");\n },\n\n /**\n * wrapper method for event onUpdate
                \n * may be extended by subclasses\n *\n * @method update\n * @protected\n */\n update: function()\n {\n this.fireEvent(\"onUpdate\");\n\n //console.log(\"o was updated\");\n },\n\n /**\n * wrapper method for event onEnable
                \n * may be extended by subclasses\n *\n * @method enable\n * @protected\n */\n enable: function()\n {\n this.a.removeClass(\"D\");\n this.fireEvent(\"onEnable\");\n\n //console.log(this.type+\"-\"+this.instance+\" now enabled\");\n },\n\n /**\n * wrapper method for event onDisable
                \n * may be extended by subclasses\n *\n * @method disable\n * @protected\n */\n disable: function()\n {\n this.a.addClass(\"D\");\n this.fireEvent(\"onDisable\");\n\n //console.log(this.type+\"-\"+this.instance+\" now disabled\");\n }\n});", "cfe/modules/select/cfe.module.select.js": "/**\n * @module Scrollable\n */\n\n/**\n * SCROLLING functionality for select boxes;\n * TODO: refactor to standalone module\n * \n * creates handles and sets up a slider object\n *\n * @class Scrollable\n * @namespace cfe.helper\n *\n * \n */\ncfe.helper = cfe.helper || {}\n\ncfe.helper.Scrollable = {\n\n options: {\n size: 4,\n scrolling: true\n },\n \n setupScrolling: function()\n {\n // slider config\n this.scrollerWrapper = new Element(\"span\",{\n \"class\": cfe.prefix+\"ScrollerWrapper\",\n \"styles\":{\n height: this.container.getHeight()\n }\n }).inject(this.container, \"after\");\n\n var scrollTimer, scrollTimeout;\n var scrollStepHeight = this.allOptions[0].getHeight();\n\n function scroll(by){\n clearInterval(scrollTimer);\n clearTimeout(scrollTimeout);\n\n slider.set(slider.step+by);\n\n scrollTimeout = (function(){\n scrollTimer = (function(){\n slider.set(slider.step+by);\n }.bind(this)).periodical(50)\n }.bind(this)).delay(200)\n }\n\n function clearScroll(){\n clearInterval(scrollTimer);\n clearTimeout(scrollTimeout);\n }\n\n this.scrollerTop = $(new cfe.module.Button({\n delegateClick: false\n }).addEvent(\"release\", clearScroll).addEvent(\"press\", scroll.pass(-1))).addClass(\"scrollTop\");\n\n this.scrollerBottom = $(new cfe.module.Button({\n delegateClick: false\n }).addEvent(\"release\", clearScroll).addEvent(\"press\", scroll.pass(1))).addClass(\"scrollBottom\")\n\n this.scrollerKnob = new Element(\"span\").addClass(\"scrollKnob\");\n this.scrollerBack = new Element(\"span\").addClass(\"scrollRail\");\n\n this.scrollerBack.adopt(this.scrollerKnob);\n this.scrollerWrapper.adopt(this.scrollerBack, this.scrollerTop, this.scrollerBottom);\n\n var slider = new Slider(this.scrollerBack, this.scrollerKnob, {\n steps: this.allOptions.length-this.options.size,\n mode: \"vertical\" ,\n onChange: function(step){\n this.container.scrollTo(false,step*scrollStepHeight);\n }.bind(this)\n }).set(this.selectedIndex);\n\n this.scrollerKnob.setStyle(\"position\", \"absolute\");\n\n // scrolling\n function wheelListener(ev)\n {\n ev.stop();\n slider.set(slider.step-ev.wheel);\n }\n\n this.boundWheelListener = wheelListener.pass([e],this)\n\n this.addEvent(\"containerShow\", function(){\n $(document.body).addEvent(\"mousewheel\", this.boundWheelListener)\n\n slider.set(this.o.selectedIndex);\n this.container.scrollTo(false,this.o.selectedIndex*scrollStepHeight);\n })\n\n this.addEvent(\"containerHide\", function(){\n $(document.body).removeEvent(\"mousewheel\", this.boundWheelListener);\n })\n\n this.o.addEvent(\"change\", function(){\n slider.set(this.o.selectedIndex)\n }.bind(this))\n }\n}\n\n/**\n * @module Selectable\n */\n\n/**\n * replaces select fields\n *\n *

                disabled should also disable scrolling

                \n * \n *
                Tested in:
                \n *
                  \n *
                • Safari 4.
                • \n *
                • Firefox 3.6.
                • \n *
                • Google Chrome 6.
                • \n *
                • Opera 10.62 - key autocompletion closes box.
                • \n *
                • IE 7.
                • \n *
                • IE 8.
                • \n *
                \n *\n * @class Select\n * @namespace cfe.module\n *\n * @extends cfe.module.Button\n *\n */\ncfe.module.Select = new Class({\n\t\n Extends: cfe.module.Button,\n Implements: cfe.helper.Scrollable,\n \n Binds: \"clickedOutsideListener\",\n\n instance: 0,\n\n /**\n * CSS Selector to fetch \"original\" HTMLElements for replacement with this module\n * @property selector\n * @type string\n */\n selector: \"select:not(select[multiple])\",\n\t\n selectedIndex: 0,\n\n setupOriginal: function()\n {\n this.parent();\n \n this.o.addEvents({\n \"keyup\": this.keyup.bind(this),\n \"keydown\": this.keydown.bind(this)\n });\n },\n\n afterInitialize: function()\n {\n this.parent();\n\n // set width to widest option if no width is given to select via css\n if(this.cssWidth == \"auto\") this.a.setStyle(\"width\", this.container.getWidth())\n\n // inject labelArrow as IE 7 doesn't support :after css selector\n if(Browser.ie) new Element(\"span\").addClass(\"labelArrow\").inject(this.innerlabel, \"after\")\n\n // select default option\n if(this.selectedIndex != -1) this.selectOption(this.selectedIndex, true);\n\n if(this.options.scrolling)\n {\n this.container.setStyle(\"height\", this.allOptions[0].getHeight()*this.options.size);\n this.setupScrolling();\n }\n\n this.hideContainer();\n },\n\n /**\n * Method to programmatically create an \"original\" HTMLElement\n *\n * @method createOriginal\n * @return {HTMLElement} a select input\n */\n createOriginal: function()\n {\n var ori = new Element(\"select\");\n\n if( this.options.options != null )\n {\n for(var key in this.options.options)\n {\n ori.adopt( new Element(\"option\", {\n value: key,\n selected: this.options.options[key].selected?\"selected\":\"\"\n }).set(\"html\", this.options.options[key].label ) );\n }\n }\n return ori;\n },\n\n build: function()\n {\n this.origOptions = this.o.getChildren();\n\n this.selectedIndex = this.o.selectedIndex || this.selectedIndex;\n\n // integrity check\n if(this.options.size > this.origOptions.length || this.options.scrolling != true) this.options.size = this.origOptions.length;\n \n this.parent();\n\n this.a.setStyles({\"position\": \"relative\", \"z-index\": 100000 - this.instance});\n\n // build container which shows on click\n this.buildContainer();\n\n this.cssWidth = this.a.getStyle(\"width\");\n },\n\n buildContainer: function()\n {\n this.container = new Element(\"span\",{\n \"class\": cfe.prefix+this.type+\"Container\",\n \"styles\":{\n \"overflow\":\"hidden\"\n }\n });\n \n this.containerWrapper = this.container.setSlidingDoors(4, \"span\", cfe.prefix).addClass(cfe.prefix+this.type+\"ContainerWrapper\").setStyles({\n position: \"absolute\",\n \"z-index\": this.instance + 1\n }).inject(this.a);\n\n // insert option elements\n this.allOptions = [];\n this.origOptions.each(function(el,i)\n {\n this.allOptions.push(this.buildOption(el, i))\n }.bind(this));\n\n this.container.adopt(this.allOptions);\n\n },\n\n buildOption: function(el, i)\n {\n return new Element(\"span\",{\n \"class\": cfe.prefix+\"Option \"+cfe.prefix+\"Option\"+i+(el.get('class')?\" \"+el.get('class'):\"\"),\n \"events\":{\n \"mouseover\": this.highlightOption.pass([i,true],this)/*,\n \"mouseout\": this.highlightOption.pass([i,true],this)*/\n }\n }).set('html', el.innerHTML.replace(/\\s/g, \" \")).disableTextSelection().store(\"index\", i);\n },\n\n selectOption: function(index)\n {\n index = index.limit(0,this.origOptions.length-1);\n\n this.highlightOption(index);\n\n this.selectedIndex = index;\n\n this.innerlabel.set('html', (this.allOptions[index]).innerHTML);\n\n this.fireEvent(\"onSelectOption\", index);\n },\n\n highlightOption: function(index)\n {\n index = index.limit(0,this.origOptions.length-1);\n\n if(this.highlighted) this.highlighted.removeClass(\"H\");\n\n this.highlighted = this.allOptions[index].addClass(\"H\");\n\n this.highlightedIndex = index;\n\n this.fireEvent(\"onHighlightOption\", index);\n },\n\n updateOption: function(by)\n {\n // fix for IE 7\n if(this.containerWrapper.retrieve(\"hidden\") != true && !Browser.ie) this.o.selectedIndex = (this.highlightedIndex+by).limit(0,this.origOptions.length-1);\n this.o.fireEvent(\"change\");\n },\n\n hideContainer: function()\n {\n $(document.body).removeEvent(\"click\", this.clickedOutsideListener);\n \n this.containerWrapper.setStyle(\"display\",\"none\").removeClass(\"F\").store(\"hidden\", true);\n\n this.fireEvent(\"onContainerHide\", this.selectedIndex);\n },\n\n showContainer: function()\n {\n $(document.body).addEvent(\"click\", this.clickedOutsideListener);\n\n this.containerWrapper.setStyle(\"display\", \"block\").addClass(\"F\").store(\"hidden\", false);\n\n this.highlightOption(this.o.selectedIndex);\n\n this.fireEvent(\"onContainerShow\", this.selectedIndex);\n },\n\n clicked: function(ev)\n {\n if(!this.isDisabled())\n {\n if( ev.target != null )\n {\n var oTarget = $(ev.target);\n\n if( oTarget.getParent() == this.container )\n {\n this.selectOption(oTarget.retrieve(\"index\"), true);\n this.hideContainer();\n this.parent();\n this.o.selectedIndex = oTarget.retrieve(\"index\");\n this.o.fireEvent(\"change\");\n return;\n }\n else if(this.options.scrolling && oTarget.getParent(\".\"+this.scrollerWrapper.getProperty(\"class\")) == this.scrollerWrapper)\n {\n //console.log(\"no toggle\");\n return;\n }\n }\n\n this.toggle();\n this.parent();\n }\n },\n\n toggle: function()\n {\n this.containerWrapper.retrieve(\"hidden\") == true ? this.showContainer() : this.hideContainer();\n },\n\t\n keyup: function(ev)\n {\n // toggle on alt+arrow\n if(ev.alt && (ev.key == \"up\" || ev.key == \"down\") )\n {\n this.toggle();\n return;\n }\n\n switch(ev.key){\n case \"enter\":\n case \"space\":\n this.toggle();\n break;\n\n case \"up\":\n this.updateOption(-1);\n break;\n\n case \"down\":\n this.updateOption(1);\n break;\n\n case \"esc\":\n this.hideContainer();\n break;\n \n default:\n this.o.fireEvent(\"change\");\n break;\n }\n },\n\n keydown: function(ev)\n {\n if(ev.key == \"tab\")\n {\n this.hideContainer();\n }\n },\n\n clickedOutsideListener: function(ev)\n {\n if ($(ev.target).getParent(\".\"+cfe.prefix+this.type) != this.a && !( (Browser.ie || Browser.opera) && ev.target == this.o) && ( this.l == null || (this.l && $(ev.target) != this.l) ) ) this.hideContainer();\n },\n\n update: function()\n {\n this.parent();\n this.selectOption(this.o.selectedIndex);\n }\n});", "demo.html": "\n\n \n \n \n\n \n \n \n \n\n \n \n

                CFE Barebone Example

                \n

                for mootools 1.2

                \n

                \n Visit homepage\n

                \n\n
                \n\n\n
                Checkboxes (input[checkbox])\n \n\n
                \n\n
                Checkboxes with implicit labelling\n

                NOTE: 3rd Checkbox has dependencies: 1st and 2nd get automatically checked if not already

                \n
                  \n
                • \n
                • \n\n
                • \n
                • \n\n
                • \n\n
                \n
                \n\n\n
                Radiobuttons (input[radio])\n
                  \n
                • \n \n
                • \n\n
                • \n \n
                • \n\n
                • \n
                • \n\n
                • \n
                • \n\n\n
                • \n
                • \n\n
                • \n
                • \n
                \n
                \n\n\n
                Textinput&-area(input[text,password],textarea)- w/ slidingDoors\n
                  \n
                • \n \n
                • \n\n
                • \n \n
                • \n\n
                • \n \n
                • \n\n
                • \n \n
                • \n\n
                • trigger textfield 4 disabled/enabled\n
                • \n\n
                • \n \n
                • \n\n
                • \n \n
                • \n\n
                • \n \n
                • \n\n
                • \n \n
                • \n\n
                • trigger textarea 2 disabled/enabled\n
                • \n\n
                • \n \n
                • \n
                \n
                \n\n\n\n
                Textinput&-area with implicit labelling\n
                  \n
                • \n
                • \n\n
                • \n
                • \n\n
                • \n
                • \n\n
                • \n\n
                • \n\n
                • \n
                • \n
                \n
                \n\n\n\n \n\n
                Selectfield (select) with and without multiple option and preselected\n
                  \n\n
                • \n \n
                • \n\n
                • \n\n \n
                • \n\n
                • \n \n
                • \n\n
                • trigger select 3 disabled/enabled\n
                • \n\n
                • \n \n
                • \n\n
                • \n \n
                • \n\n
                • trigger multiple select 2 disabled/enabled\n
                • \n
                \n
                \n\n\n\n
                file upload (input[file]) -- without and with implicit labelling\n
                  \n
                • \n \n
                • \n\n
                • \n
                • \n\n
                • \n \n
                • \n
                \n
                \n\n\n
                \n Check POST Data or Reset Data via Buttons (input[submit], input[reset], input[image])\n\n
                  \n
                • \n \n
                • \n\n
                • \n \n
                • \n\n
                • \n \n
                • \n\n
                • \n \n
                • \n\n
                • \n \n
                • \n
                \n\n
                \n\n
                Advanced example: Search field\n
                  \n
                • \n \n \" name=\"inputSearchSubmit\" />\n
                • \n
                \n
                \n
                \n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n\n", "cfe/modules/select/cfe.module.select.multiple.js": "/**\n * @module Selectable\n */\n\n/**\n * replaces select fields with attribute multiple set\n *\n * bug:\n * mouseWheel support needed\n * \n * @class SelectMultiple\n * @namespace cfe.module\n *\n * @extends cfe.module.Select\n */\ncfe.module.SelectMultiple = new Class({\n\t\n Extends: cfe.module.Select,\n instance: 0,\n\n /**\n * CSS Selector to fetch \"original\" HTMLElements for replacement with this module\n * @property selector\n * @type string\n */\n selector: \"select[multiple]\",\n\n options: {\n buttonStyle: false\n },\n\n afterInitialize: function()\n {\n this.containerWrapper.addClass(cfe.prefix+\"SelectContainerWrapper\").setStyles({\n \"position\": \"relative\",\n \"z-index\": \"auto\"\n });\n this.container.addClass(cfe.prefix+\"SelectContainer\");\n\n this.o.addEvents({\n onDisable: function(){\n this.containerWrapper.getElements(\"input, button\").each(function(el){\n el.disable();\n });\n }.bind(this),\n onEnable: function(){\n this.containerWrapper.getElements(\"input, button\").each(function(el){\n el.enable();\n });\n }.bind(this)\n });\n \n this.parent();\n },\n\n setupWrapperEvents: function()\n {\n this.a = this.containerWrapper;\n this.parent();\n },\n\n buildOption: function(el, index)\n {\n var oOpt = new cfe.module.Checkbox({\n label: el.innerHTML,\n checked: (el.selected != null),\n disabled: this.isDisabled()\n });\n oOpt.index = index;\n\n oOpt.addEvents({\n \"check\": function(index){\n this.origOptions[index].selected = true;\n this.o.fireEvent(\"change\")\n }.pass(index, this),\n \"uncheck\": function(index){\n this.origOptions[index].selected = false;\n this.o.fireEvent(\"change\")\n }.pass(index, this)\n });\n\n $(oOpt).addClass(cfe.prefix+\"Option \"+cfe.prefix+\"Option\"+index+(el.get('class')?\" \".el.get('class'):\"\")).disableTextSelection();\n oOpt.getLabel().removeEvents().inject( $(oOpt) );\n\n return $(oOpt);\n },\n\n selectOption: function(index)\n {\n index = index.limit(0,this.origOptions.length-1);\n\n this.highlightOption(index);\n },\n\n clicked: function()\n {\n if(!this.isDisabled())\n {\n this.o.focus();\n this.fireEvent(\"onClick\");\n }\n },\n\n update: function()\n {\n this.fireEvent(\"onUpdate\");\n },\n\n toggle: function(){},\n keydown: function(){},\n hideContainer: function(){},\n showContainer: function(){}\n});"}}