repo
stringlengths
5
75
commit
stringlengths
40
40
message
stringlengths
6
18.2k
diff
stringlengths
60
262k
djbender/sa
c741878ce8cc7fa5f05634d5bcec4dfbb669193f
setting up devise
diff --git a/config/environments/development.rb b/config/environments/development.rb index 2d61590..0a83ea0 100644 --- a/config/environments/development.rb +++ b/config/environments/development.rb @@ -1,26 +1,28 @@ Spoileralert::Application.configure do # Settings specified here will take precedence over those in config/environment.rb # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the webserver when you make code changes. config.cache_classes = false # Log error messages when you accidentally call methods on nil. config.whiny_nils = true # Show full error reports and disable caching config.consider_all_requests_local = true config.action_view.debug_rjs = true config.action_controller.perform_caching = false # Don't care if the mailer can't send config.action_mailer.raise_delivery_errors = false # Print deprecation notices to the Rails logger config.active_support.deprecation = :log # Only use best-standards-support built into browsers config.action_dispatch.best_standards_support = :builtin + + config.action_mailer.default_url_options = { :host => 'localhost:3000' } end diff --git a/config/initializers/devise.rb b/config/initializers/devise.rb new file mode 100644 index 0000000..9307de3 --- /dev/null +++ b/config/initializers/devise.rb @@ -0,0 +1,142 @@ +# Use this hook to configure devise mailer, warden hooks and so forth. The first +# four configuration values can also be set straight in your models. +Devise.setup do |config| + # ==> Mailer Configuration + # Configure the e-mail address which will be shown in DeviseMailer. + config.mailer_sender = "[email protected]" + + # Configure the class responsible to send e-mails. + # config.mailer = "Devise::Mailer" + + # ==> ORM configuration + # Load and configure the ORM. Supports :active_record (default) and + # :mongoid (bson_ext recommended) by default. Other ORMs may be + # available as additional gems. + require 'devise/orm/active_record' + + # ==> Configuration for any authentication mechanism + # Configure which keys are used when authenticating an user. By default is + # just :email. You can configure it to use [:username, :subdomain], so for + # authenticating an user, both parameters are required. Remember that those + # parameters are used only when authenticating and not when retrieving from + # session. If you need permissions, you should implement that in a before filter. + # config.authentication_keys = [ :email ] + + # Tell if authentication through request.params is enabled. True by default. + # config.params_authenticatable = true + + # Tell if authentication through HTTP Basic Auth is enabled. True by default. + # config.http_authenticatable = true + + # Set this to true to use Basic Auth for AJAX requests. True by default. + # config.http_authenticatable_on_xhr = true + + # The realm used in Http Basic Authentication + # config.http_authentication_realm = "Application" + + # ==> Configuration for :database_authenticatable + # For bcrypt, this is the cost for hashing the password and defaults to 10. If + # using other encryptors, it sets how many times you want the password re-encrypted. + config.stretches = 10 + + # Define which will be the encryption algorithm. Devise also supports encryptors + # from others authentication tools as :clearance_sha1, :authlogic_sha512 (then + # you should set stretches above to 20 for default behavior) and :restful_authentication_sha1 + # (then you should set stretches to 10, and copy REST_AUTH_SITE_KEY to pepper) + config.encryptor = :bcrypt + + # Setup a pepper to generate the encrypted password. + config.pepper = "8344da7ba90397c53a5517bda62ab4c030bbaccd3f02fda33883f61f4a15509f7d3827d6f884ae5f4cd05729c83b2a59cb9c817b0201727d32ba6746494cf3e3" + + # ==> Configuration for :confirmable + # The time you want to give your user to confirm his account. During this time + # he will be able to access your application without confirming. Default is nil. + # When confirm_within is zero, the user won't be able to sign in without confirming. + # You can use this to let your user access some features of your application + # without confirming the account, but blocking it after a certain period + # (ie 2 days). + # config.confirm_within = 2.days + + # ==> Configuration for :rememberable + # The time the user will be remembered without asking for credentials again. + # config.remember_for = 2.weeks + + # If true, a valid remember token can be re-used between multiple browsers. + # config.remember_across_browsers = true + + # If true, extends the user's remember period when remembered via cookie. + # config.extend_remember_period = false + + # ==> Configuration for :validatable + # Range for password length + # config.password_length = 6..20 + + # Regex to use to validate the email address + # config.email_regexp = /^([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})$/i + + # ==> Configuration for :timeoutable + # The time you want to timeout the user session without activity. After this + # time the user will be asked for credentials again. + # config.timeout_in = 10.minutes + + # ==> Configuration for :lockable + # Defines which strategy will be used to lock an account. + # :failed_attempts = Locks an account after a number of failed attempts to sign in. + # :none = No lock strategy. You should handle locking by yourself. + # config.lock_strategy = :failed_attempts + + # Defines which strategy will be used to unlock an account. + # :email = Sends an unlock link to the user email + # :time = Re-enables login after a certain amount of time (see :unlock_in below) + # :both = Enables both strategies + # :none = No unlock strategy. You should handle unlocking by yourself. + # config.unlock_strategy = :both + + # Number of authentication tries before locking an account if lock_strategy + # is failed attempts. + # config.maximum_attempts = 20 + + # Time interval to unlock the account if :time is enabled as unlock_strategy. + # config.unlock_in = 1.hour + + # ==> Configuration for :token_authenticatable + # Defines name of the authentication token params key + # config.token_authentication_key = :auth_token + + # ==> Scopes configuration + # Turn scoped views on. Before rendering "sessions/new", it will first check for + # "users/sessions/new". It's turned off by default because it's slower if you + # are using only default views. + # config.scoped_views = true + + # Configure the default scope given to Warden. By default it's the first + # devise role declared in your routes. + # config.default_scope = :user + + # Configure sign_out behavior. + # By default sign_out is scoped (i.e. /users/sign_out affects only :user scope). + # In case of sign_out_all_scopes set to true any logout action will sign out all active scopes. + # config.sign_out_all_scopes = false + + # ==> Navigation configuration + # Lists the formats that should be treated as navigational. Formats like + # :html, should redirect to the sign in page when the user does not have + # access, but formats like :xml or :json, should return 401. + # If you have any extra navigational formats, like :iphone or :mobile, you + # should add them to the navigational formats lists. Default is [:html] + # config.navigational_formats = [:html, :iphone] + + # ==> Warden configuration + # If you want to use other strategies, that are not (yet) supported by Devise, + # you can configure them inside the config.warden block. The example below + # allows you to setup OAuth, using http://github.com/roman/warden_oauth + # + # config.warden do |manager| + # manager.oauth(:twitter) do |twitter| + # twitter.consumer_secret = <YOUR CONSUMER SECRET> + # twitter.consumer_key = <YOUR CONSUMER KEY> + # twitter.options :site => 'http://twitter.com' + # end + # manager.default_strategies(:scope => :user).unshift :twitter_oauth + # end +end diff --git a/config/locales/devise.en.yml b/config/locales/devise.en.yml new file mode 100644 index 0000000..5e4e433 --- /dev/null +++ b/config/locales/devise.en.yml @@ -0,0 +1,39 @@ +en: + errors: + messages: + not_found: "not found" + already_confirmed: "was already confirmed" + not_locked: "was not locked" + + devise: + failure: + unauthenticated: 'You need to sign in or sign up before continuing.' + unconfirmed: 'You have to confirm your account before continuing.' + locked: 'Your account is locked.' + invalid: 'Invalid email or password.' + invalid_token: 'Invalid authentication token.' + timeout: 'Your session expired, please sign in again to continue.' + inactive: 'Your account was not activated yet.' + sessions: + signed_in: 'Signed in successfully.' + signed_out: 'Signed out successfully.' + passwords: + send_instructions: 'You will receive an email with instructions about how to reset your password in a few minutes.' + updated: 'Your password was changed successfully. You are now signed in.' + confirmations: + send_instructions: 'You will receive an email with instructions about how to confirm your account in a few minutes.' + confirmed: 'Your account was successfully confirmed. You are now signed in.' + registrations: + signed_up: 'You have signed up successfully. If enabled, a confirmation was sent to your e-mail.' + updated: 'You updated your account successfully.' + destroyed: 'Bye! Your account was successfully cancelled. We hope to see you again soon.' + unlocks: + send_instructions: 'You will receive an email with instructions about how to unlock your account in a few minutes.' + unlocked: 'Your account was successfully unlocked. You are now signed in.' + mailer: + confirmation_instructions: + subject: 'Confirmation instructions' + reset_password_instructions: + subject: 'Reset password instructions' + unlock_instructions: + subject: 'Unlock Instructions' diff --git a/config/routes.rb b/config/routes.rb index e2e4caa..fef4960 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,58 +1,59 @@ Spoileralert::Application.routes.draw do + root :to => "home#index" # The priority is based upon order of creation: # first created -> highest priority. # Sample of regular route: # match 'products/:id' => 'catalog#view' # Keep in mind you can assign values other than :controller and :action # Sample of named route: # match 'products/:id/purchase' => 'catalog#purchase', :as => :purchase # This route can be invoked with purchase_url(:id => product.id) # Sample resource route (maps HTTP verbs to controller actions automatically): # resources :products # Sample resource route with options: # resources :products do # member do # get 'short' # post 'toggle' # end # # collection do # get 'sold' # end # end # Sample resource route with sub-resources: # resources :products do # resources :comments, :sales # resource :seller # end # Sample resource route with more complex sub-resources # resources :products do # resources :comments # resources :sales do # get 'recent', :on => :collection # end # end # Sample resource route within a namespace: # namespace :admin do # # Directs /admin/products/* to Admin::ProductsController # # (app/controllers/admin/products_controller.rb) # resources :products # end # You can have the root of your site routed with "root" # just remember to delete public/index.html. # root :to => "welcome#index" # See how all your routes lay out with "rake routes" # This is a legacy wild controller route that's not recommended for RESTful applications. # Note: This route will make all actions in every controller accessible via GET requests. # match ':controller(/:action(/:id(.:format)))' end
djbender/sa
a61087829bbe521ad7fc465a7709474d890199ef
adding gem devise for user auth
diff --git a/Gemfile b/Gemfile index 1c6601c..81d936a 100644 --- a/Gemfile +++ b/Gemfile @@ -1,40 +1,43 @@ source 'http://rubygems.org' gem 'rails', '3.0.0' # Bundle edge Rails instead: # gem 'rails', :git => 'git://github.com/rails/rails.git' gem 'sqlite3-ruby', :require => 'sqlite3' +#Security +gem 'devise', '1.1.3' + group :development do gem 'rspec-rails', '2.0.0' end group :test do gem 'rspec', '2.0.0' gem 'webrat', '0.7.1' end # Use unicorn as the web server # gem 'unicorn' # Deploy with Capistrano # gem 'capistrano' # To use debugger # gem 'ruby-debug' # Bundle the extra gems: # gem 'bj' # gem 'nokogiri' # gem 'sqlite3-ruby', :require => 'sqlite3' # gem 'aws-s3', :require => 'aws/s3' # Bundle gems for the local environment. Make sure to # put test-only gems in this group so their generators # and rake tasks are available in development mode: # group :development, :test do # gem 'webrat' # end diff --git a/Gemfile.lock b/Gemfile.lock index cdd61f8..fa468f8 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -1,94 +1,101 @@ GEM remote: http://rubygems.org/ specs: abstract (1.0.0) actionmailer (3.0.0) actionpack (= 3.0.0) mail (~> 2.2.5) actionpack (3.0.0) activemodel (= 3.0.0) activesupport (= 3.0.0) builder (~> 2.1.2) erubis (~> 2.6.6) i18n (~> 0.4.1) rack (~> 1.2.1) rack-mount (~> 0.6.12) rack-test (~> 0.5.4) tzinfo (~> 0.3.23) activemodel (3.0.0) activesupport (= 3.0.0) builder (~> 2.1.2) i18n (~> 0.4.1) activerecord (3.0.0) activemodel (= 3.0.0) activesupport (= 3.0.0) arel (~> 1.0.0) tzinfo (~> 0.3.23) activeresource (3.0.0) activemodel (= 3.0.0) activesupport (= 3.0.0) activesupport (3.0.0) arel (1.0.1) activesupport (~> 3.0.0) + bcrypt-ruby (2.1.2) builder (2.1.2) + devise (1.1.3) + bcrypt-ruby (~> 2.1.2) + warden (~> 0.10.7) diff-lcs (1.1.2) erubis (2.6.6) abstract (>= 1.0.0) i18n (0.4.1) mail (2.2.7) activesupport (>= 2.3.6) mime-types treetop (>= 1.4.5) mime-types (1.16) nokogiri (1.4.3.1) polyglot (0.3.1) rack (1.2.1) rack-mount (0.6.13) rack (>= 1.0.0) rack-test (0.5.6) rack (>= 1.0) rails (3.0.0) actionmailer (= 3.0.0) actionpack (= 3.0.0) activerecord (= 3.0.0) activeresource (= 3.0.0) activesupport (= 3.0.0) bundler (~> 1.0.0) railties (= 3.0.0) railties (3.0.0) actionpack (= 3.0.0) activesupport (= 3.0.0) rake (>= 0.8.4) thor (~> 0.14.0) rake (0.8.7) rspec (2.0.0) rspec-core (= 2.0.0) rspec-expectations (= 2.0.0) rspec-mocks (= 2.0.0) rspec-core (2.0.0) rspec-expectations (2.0.0) diff-lcs (>= 1.1.2) rspec-mocks (2.0.0) rspec-core (= 2.0.0) rspec-expectations (= 2.0.0) rspec-rails (2.0.0) rspec (= 2.0.0) sqlite3-ruby (1.3.1) thor (0.14.3) treetop (1.4.8) polyglot (>= 0.3.1) tzinfo (0.3.23) + warden (0.10.7) + rack (>= 1.0.0) webrat (0.7.1) nokogiri (>= 1.2.0) rack (>= 1.0) rack-test (>= 0.5.3) PLATFORMS ruby DEPENDENCIES + devise (= 1.1.3) rails (= 3.0.0) rspec (= 2.0.0) rspec-rails (= 2.0.0) sqlite3-ruby webrat (= 0.7.1)
djbender/sa
a05287a75553058f630c580dddddd561fd1c4b5d
adding white textured version of splash page
diff --git a/public/index-white.html b/public/index-white.html new file mode 100644 index 0000000..d58f840 --- /dev/null +++ b/public/index-white.html @@ -0,0 +1,52 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> +<html xmlns="http://www.w3.org/1999/xhtml"> +<head> +<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> +<title>The Spoiler Alert!</title> +<style type="text/css"> +body { + color: #323232; + text-shadow: 0px 2px 1px #FFF; + background-image: url(white-bg.png); +} +p { + font-family: Arial, Helvetica, sans-serif; + font-size: 48pt; + letter-spacing: 0px; +} +.para { + font-size: 32pt; +} +@charset "UTF-8"; +.enclosure { + margin: 0px; + padding: 35px; + height: auto; + width: auto; +} +.textbox { + text-align: center; + height: 100%; + width: 100%; +} +</style> +<link rel="shortcut icon" + href="sa.ico" +</head> + +<body> +<div class="enclosure"></div> +<div class="textbox"> +<p> Welcome to + <textarea name="text" cols="50" rows="4"></textarea> . +</p> +<p>&nbsp;</p> +<p>&nbsp;</p> +<p><span class="para">Your life is about to</span><span class="para"> + <textarea name="textarea" id="textarea" cols="30" rows="3"></textarea> + .</span></p> +<form id="form1" name="form1" method="post" action=""> +</form> +</div> +</body> +</html> diff --git a/public/white-bg.png b/public/white-bg.png new file mode 100644 index 0000000..06f3b5b Binary files /dev/null and b/public/white-bg.png differ
djbender/sa
3711cbc7dcd68093adbe4d6beb460a265d1c434e
Adding a color splash
diff --git a/public/index-color.html b/public/index-color.html new file mode 100644 index 0000000..e9d4af5 --- /dev/null +++ b/public/index-color.html @@ -0,0 +1,52 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> +<html xmlns="http://www.w3.org/1999/xhtml"> +<head> +<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> +<title>The Spoiler Alert!</title> +<style type="text/css"> +body { + color: #323232; + text-shadow: 0px 2px 1px #FFF; + background-image: url(lb-bg.png); +} +p { + font-family: Arial, Helvetica, sans-serif; + font-size: 48pt; + letter-spacing: 0px; +} +.para { + font-size: 32pt; +} +@charset "UTF-8"; +.enclosure { + margin: 0px; + padding: 35px; + height: auto; + width: auto; +} +.textbox { + text-align: center; + height: 100%; + width: 100%; +} +</style> +<link rel="shortcut icon" + href="sa.ico" +</head> + +<body> +<div class="enclosure"></div> +<div class="textbox"> +<p> Welcome to + <textarea name="text" cols="50" rows="4"></textarea> . +</p> +<p>&nbsp;</p> +<p>&nbsp;</p> +<p><span class="para">Your life is about to</span><span class="para"> + <textarea name="textarea" id="textarea" cols="30" rows="3"></textarea> + .</span></p> +<form id="form1" name="form1" method="post" action=""> +</form> +</div> +</body> +</html> diff --git a/public/lb-bg.png b/public/lb-bg.png new file mode 100644 index 0000000..72d526a Binary files /dev/null and b/public/lb-bg.png differ
djbender/sa
a1b85bdaf1ab81de5cf3807a93ff9aecbca63477
added silly README
diff --git a/README.markdown b/README.markdown index 6966fe9..a44c082 100644 --- a/README.markdown +++ b/README.markdown @@ -1,256 +1,4 @@ -== Welcome to Rails +SA +== -Rails is a web-application framework that includes everything needed to create -database-backed web applications according to the Model-View-Control pattern. - -This pattern splits the view (also called the presentation) into "dumb" -templates that are primarily responsible for inserting pre-built data in between -HTML tags. The model contains the "smart" domain objects (such as Account, -Product, Person, Post) that holds all the business logic and knows how to -persist themselves to a database. The controller handles the incoming requests -(such as Save New Account, Update Product, Show Post) by manipulating the model -and directing data to the view. - -In Rails, the model is handled by what's called an object-relational mapping -layer entitled Active Record. This layer allows you to present the data from -database rows as objects and embellish these data objects with business logic -methods. You can read more about Active Record in -link:files/vendor/rails/activerecord/README.html. - -The controller and view are handled by the Action Pack, which handles both -layers by its two parts: Action View and Action Controller. These two layers -are bundled in a single package due to their heavy interdependence. This is -unlike the relationship between the Active Record and Action Pack that is much -more separate. Each of these packages can be used independently outside of -Rails. You can read more about Action Pack in -link:files/vendor/rails/actionpack/README.html. - - -== Getting Started - -1. At the command prompt, create a new Rails application: - <tt>rails new myapp</tt> (where <tt>myapp</tt> is the application name) - -2. Change directory to <tt>myapp</tt> and start the web server: - <tt>cd myapp; rails server</tt> (run with --help for options) - -3. Go to http://localhost:3000/ and you'll see: - "Welcome aboard: You're riding Ruby on Rails!" - -4. Follow the guidelines to start developing your application. You can find -the following resources handy: - -* The Getting Started Guide: http://guides.rubyonrails.org/getting_started.html -* Ruby on Rails Tutorial Book: http://www.railstutorial.org/ - - -== Debugging Rails - -Sometimes your application goes wrong. Fortunately there are a lot of tools that -will help you debug it and get it back on the rails. - -First area to check is the application log files. Have "tail -f" commands -running on the server.log and development.log. Rails will automatically display -debugging and runtime information to these files. Debugging info will also be -shown in the browser on requests from 127.0.0.1. - -You can also log your own messages directly into the log file from your code -using the Ruby logger class from inside your controllers. Example: - - class WeblogController < ActionController::Base - def destroy - @weblog = Weblog.find(params[:id]) - @weblog.destroy - logger.info("#{Time.now} Destroyed Weblog ID ##{@weblog.id}!") - end - end - -The result will be a message in your log file along the lines of: - - Mon Oct 08 14:22:29 +1000 2007 Destroyed Weblog ID #1! - -More information on how to use the logger is at http://www.ruby-doc.org/core/ - -Also, Ruby documentation can be found at http://www.ruby-lang.org/. There are -several books available online as well: - -* Programming Ruby: http://www.ruby-doc.org/docs/ProgrammingRuby/ (Pickaxe) -* Learn to Program: http://pine.fm/LearnToProgram/ (a beginners guide) - -These two books will bring you up to speed on the Ruby language and also on -programming in general. - - -== Debugger - -Debugger support is available through the debugger command when you start your -Mongrel or WEBrick server with --debugger. This means that you can break out of -execution at any point in the code, investigate and change the model, and then, -resume execution! You need to install ruby-debug to run the server in debugging -mode. With gems, use <tt>sudo gem install ruby-debug</tt>. Example: - - class WeblogController < ActionController::Base - def index - @posts = Post.find(:all) - debugger - end - end - -So the controller will accept the action, run the first line, then present you -with a IRB prompt in the server window. Here you can do things like: - - >> @posts.inspect - => "[#<Post:0x14a6be8 - @attributes={"title"=>nil, "body"=>nil, "id"=>"1"}>, - #<Post:0x14a6620 - @attributes={"title"=>"Rails", "body"=>"Only ten..", "id"=>"2"}>]" - >> @posts.first.title = "hello from a debugger" - => "hello from a debugger" - -...and even better, you can examine how your runtime objects actually work: - - >> f = @posts.first - => #<Post:0x13630c4 @attributes={"title"=>nil, "body"=>nil, "id"=>"1"}> - >> f. - Display all 152 possibilities? (y or n) - -Finally, when you're ready to resume execution, you can enter "cont". - - -== Console - -The console is a Ruby shell, which allows you to interact with your -application's domain model. Here you'll have all parts of the application -configured, just like it is when the application is running. You can inspect -domain models, change values, and save to the database. Starting the script -without arguments will launch it in the development environment. - -To start the console, run <tt>rails console</tt> from the application -directory. - -Options: - -* Passing the <tt>-s, --sandbox</tt> argument will rollback any modifications - made to the database. -* Passing an environment name as an argument will load the corresponding - environment. Example: <tt>rails console production</tt>. - -To reload your controllers and models after launching the console run -<tt>reload!</tt> - -More information about irb can be found at: -link:http://www.rubycentral.com/pickaxe/irb.html - - -== dbconsole - -You can go to the command line of your database directly through <tt>rails -dbconsole</tt>. You would be connected to the database with the credentials -defined in database.yml. Starting the script without arguments will connect you -to the development database. Passing an argument will connect you to a different -database, like <tt>rails dbconsole production</tt>. Currently works for MySQL, -PostgreSQL and SQLite 3. - -== Description of Contents - -The default directory structure of a generated Ruby on Rails application: - - |-- app - | |-- controllers - | |-- helpers - | |-- models - | `-- views - | `-- layouts - |-- config - | |-- environments - | |-- initializers - | `-- locales - |-- db - |-- doc - |-- lib - | `-- tasks - |-- log - |-- public - | |-- images - | |-- javascripts - | `-- stylesheets - |-- script - | `-- performance - |-- test - | |-- fixtures - | |-- functional - | |-- integration - | |-- performance - | `-- unit - |-- tmp - | |-- cache - | |-- pids - | |-- sessions - | `-- sockets - `-- vendor - `-- plugins - -app - Holds all the code that's specific to this particular application. - -app/controllers - Holds controllers that should be named like weblogs_controller.rb for - automated URL mapping. All controllers should descend from - ApplicationController which itself descends from ActionController::Base. - -app/models - Holds models that should be named like post.rb. Models descend from - ActiveRecord::Base by default. - -app/views - Holds the template files for the view that should be named like - weblogs/index.html.erb for the WeblogsController#index action. All views use - eRuby syntax by default. - -app/views/layouts - Holds the template files for layouts to be used with views. This models the - common header/footer method of wrapping views. In your views, define a layout - using the <tt>layout :default</tt> and create a file named default.html.erb. - Inside default.html.erb, call <% yield %> to render the view using this - layout. - -app/helpers - Holds view helpers that should be named like weblogs_helper.rb. These are - generated for you automatically when using generators for controllers. - Helpers can be used to wrap functionality for your views into methods. - -config - Configuration files for the Rails environment, the routing map, the database, - and other dependencies. - -db - Contains the database schema in schema.rb. db/migrate contains all the - sequence of Migrations for your schema. - -doc - This directory is where your application documentation will be stored when - generated using <tt>rake doc:app</tt> - -lib - Application specific libraries. Basically, any kind of custom code that - doesn't belong under controllers, models, or helpers. This directory is in - the load path. - -public - The directory available for the web server. Contains subdirectories for - images, stylesheets, and javascripts. Also contains the dispatchers and the - default HTML files. This should be set as the DOCUMENT_ROOT of your web - server. - -script - Helper scripts for automation and generation. - -test - Unit and functional tests along with fixtures. When using the rails generate - command, template test files will be generated for you and placed in this - directory. - -vendor - External libraries that the application depends on. Also includes the plugins - subdirectory. If the app has frozen rails, those gems also go here, under - vendor/rails/. This directory is in the load path. +Sekret!
djbender/sa
dfde18a5f3d49076f8df6957fc4abaa7dfdb9878
adding spedga's splash
diff --git a/public/index.html b/public/index.html index 75d5edd..0ef7270 100644 --- a/public/index.html +++ b/public/index.html @@ -1,239 +1,47 @@ -<!DOCTYPE html> -<html> - <head> - <title>Ruby on Rails: Welcome aboard</title> - <style type="text/css" media="screen"> - body { - margin: 0; - margin-bottom: 25px; - padding: 0; - background-color: #f0f0f0; - font-family: "Lucida Grande", "Bitstream Vera Sans", "Verdana"; - font-size: 13px; - color: #333; - } - - h1 { - font-size: 28px; - color: #000; - } - - a {color: #03c} - a:hover { - background-color: #03c; - color: white; - text-decoration: none; - } - - - #page { - background-color: #f0f0f0; - width: 750px; - margin: 0; - margin-left: auto; - margin-right: auto; - } - - #content { - float: left; - background-color: white; - border: 3px solid #aaa; - border-top: none; - padding: 25px; - width: 500px; - } - - #sidebar { - float: right; - width: 175px; - } - - #footer { - clear: both; - } - - - #header, #about, #getting-started { - padding-left: 75px; - padding-right: 30px; - } - - - #header { - background-image: url("images/rails.png"); - background-repeat: no-repeat; - background-position: top left; - height: 64px; - } - #header h1, #header h2 {margin: 0} - #header h2 { - color: #888; - font-weight: normal; - font-size: 16px; - } - - - #about h3 { - margin: 0; - margin-bottom: 10px; - font-size: 14px; - } - - #about-content { - background-color: #ffd; - border: 1px solid #fc0; - margin-left: -55px; - margin-right: -10px; - } - #about-content table { - margin-top: 10px; - margin-bottom: 10px; - font-size: 11px; - border-collapse: collapse; - } - #about-content td { - padding: 10px; - padding-top: 3px; - padding-bottom: 3px; - } - #about-content td.name {color: #555} - #about-content td.value {color: #000} - - #about-content ul { - padding: 0; - list-style-type: none; - } - - #about-content.failure { - background-color: #fcc; - border: 1px solid #f00; - } - #about-content.failure p { - margin: 0; - padding: 10px; - } - - - #getting-started { - border-top: 1px solid #ccc; - margin-top: 25px; - padding-top: 15px; - } - #getting-started h1 { - margin: 0; - font-size: 20px; - } - #getting-started h2 { - margin: 0; - font-size: 14px; - font-weight: normal; - color: #333; - margin-bottom: 25px; - } - #getting-started ol { - margin-left: 0; - padding-left: 0; - } - #getting-started li { - font-size: 18px; - color: #888; - margin-bottom: 25px; - } - #getting-started li h2 { - margin: 0; - font-weight: normal; - font-size: 18px; - color: #333; - } - #getting-started li p { - color: #555; - font-size: 13px; - } - - - #sidebar ul { - margin-left: 0; - padding-left: 0; - } - #sidebar ul h3 { - margin-top: 25px; - font-size: 16px; - padding-bottom: 10px; - border-bottom: 1px solid #ccc; - } - #sidebar li { - list-style-type: none; - } - #sidebar ul.links li { - margin-bottom: 5px; - } - - </style> - <script type="text/javascript"> - function about() { - info = document.getElementById('about-content'); - if (window.XMLHttpRequest) - { xhr = new XMLHttpRequest(); } - else - { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } - xhr.open("GET","rails/info/properties",false); - xhr.send(""); - info.innerHTML = xhr.responseText; - info.style.display = 'block' - } - </script> - </head> - <body> - <div id="page"> - <div id="sidebar"> - <ul id="sidebar-items"> - <li> - <h3>Browse the documentation</h3> - <ul class="links"> - <li><a href="http://api.rubyonrails.org/">Rails API</a></li> - <li><a href="http://stdlib.rubyonrails.org/">Ruby standard library</a></li> - <li><a href="http://corelib.rubyonrails.org/">Ruby core</a></li> - <li><a href="http://guides.rubyonrails.org/">Rails Guides</a></li> - </ul> - </li> - </ul> - </div> - - <div id="content"> - <div id="header"> - <h1>Welcome aboard</h1> - <h2>You&rsquo;re riding Ruby on Rails!</h2> - </div> - - <div id="about"> - <h3><a href="rails/info/properties" onclick="about(); return false">About your application&rsquo;s environment</a></h3> - <div id="about-content" style="display: none"></div> - </div> - - <div id="getting-started"> - <h1>Getting started</h1> - <h2>Here&rsquo;s how to get rolling:</h2> - - <ol> - <li> - <h2>Use <code>rails generate</code> to create your models and controllers</h2> - <p>To see all available options, run it without parameters.</p> - </li> - - <li> - <h2>Set up a default route and remove or rename this file</h2> - <p>Routes are set up in config/routes.rb.</p> - </li> - - <li> - <h2>Create your database</h2> - <p>Run <code>rake db:migrate</code> to create your database. If you're not using SQLite (the default), edit <code>config/database.yml</code> with your username and password.</p> - </li> - </ol> - </div> - </div> - - <div id="footer">&nbsp;</div> - </div> - </body> +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> +<html xmlns="http://www.w3.org/1999/xhtml"> +<head> +<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> +<title>The Spoiler Alert!</title> +<style type="text/css"> +p { + font-family: Arial, Helvetica, sans-serif; + font-size: 48pt; + letter-spacing: 0px; +} +.para { + font-size: 32pt; +} +@charset "UTF-8"; +.enclosure { + margin: 0px; + padding: 35px; + height: auto; + width: auto; +} +.textbox { + text-align: center; + height: 100%; + width: 100%; +} +</style> +<link rel="shortcut icon" + href="sa.ico" +</head> + +<body> +<div class="enclosure"></div> +<div class="textbox"> +<p> Welcome to + <textarea name="text" cols="50" rows="4"></textarea> . +</p> +<p>&nbsp;</p> +<p>&nbsp;</p> +<p><span class="para">Your life is about to</span><span class="para"> + <textarea name="textarea" id="textarea" cols="30" rows="3"></textarea> + .</span></p> +<form id="form1" name="form1" method="post" action=""> +</form> +</div> +</body> </html> diff --git a/public/sa.ico b/public/sa.ico new file mode 100644 index 0000000..6234c4d Binary files /dev/null and b/public/sa.ico differ
djbender/sa
384a7fc866b006ef386a8900f7f0dbba6d74d1f4
Added correct Gemfile
diff --git a/Gemfile b/Gemfile index 72bdf6b..1c6601c 100644 --- a/Gemfile +++ b/Gemfile @@ -1,30 +1,40 @@ source 'http://rubygems.org' gem 'rails', '3.0.0' # Bundle edge Rails instead: # gem 'rails', :git => 'git://github.com/rails/rails.git' gem 'sqlite3-ruby', :require => 'sqlite3' +group :development do + gem 'rspec-rails', '2.0.0' +end + +group :test do + gem 'rspec', '2.0.0' + gem 'webrat', '0.7.1' +end + + # Use unicorn as the web server # gem 'unicorn' # Deploy with Capistrano # gem 'capistrano' # To use debugger # gem 'ruby-debug' # Bundle the extra gems: # gem 'bj' # gem 'nokogiri' # gem 'sqlite3-ruby', :require => 'sqlite3' # gem 'aws-s3', :require => 'aws/s3' # Bundle gems for the local environment. Make sure to # put test-only gems in this group so their generators # and rake tasks are available in development mode: # group :development, :test do # gem 'webrat' # end diff --git a/Gemfile.lock b/Gemfile.lock new file mode 100644 index 0000000..cdd61f8 --- /dev/null +++ b/Gemfile.lock @@ -0,0 +1,94 @@ +GEM + remote: http://rubygems.org/ + specs: + abstract (1.0.0) + actionmailer (3.0.0) + actionpack (= 3.0.0) + mail (~> 2.2.5) + actionpack (3.0.0) + activemodel (= 3.0.0) + activesupport (= 3.0.0) + builder (~> 2.1.2) + erubis (~> 2.6.6) + i18n (~> 0.4.1) + rack (~> 1.2.1) + rack-mount (~> 0.6.12) + rack-test (~> 0.5.4) + tzinfo (~> 0.3.23) + activemodel (3.0.0) + activesupport (= 3.0.0) + builder (~> 2.1.2) + i18n (~> 0.4.1) + activerecord (3.0.0) + activemodel (= 3.0.0) + activesupport (= 3.0.0) + arel (~> 1.0.0) + tzinfo (~> 0.3.23) + activeresource (3.0.0) + activemodel (= 3.0.0) + activesupport (= 3.0.0) + activesupport (3.0.0) + arel (1.0.1) + activesupport (~> 3.0.0) + builder (2.1.2) + diff-lcs (1.1.2) + erubis (2.6.6) + abstract (>= 1.0.0) + i18n (0.4.1) + mail (2.2.7) + activesupport (>= 2.3.6) + mime-types + treetop (>= 1.4.5) + mime-types (1.16) + nokogiri (1.4.3.1) + polyglot (0.3.1) + rack (1.2.1) + rack-mount (0.6.13) + rack (>= 1.0.0) + rack-test (0.5.6) + rack (>= 1.0) + rails (3.0.0) + actionmailer (= 3.0.0) + actionpack (= 3.0.0) + activerecord (= 3.0.0) + activeresource (= 3.0.0) + activesupport (= 3.0.0) + bundler (~> 1.0.0) + railties (= 3.0.0) + railties (3.0.0) + actionpack (= 3.0.0) + activesupport (= 3.0.0) + rake (>= 0.8.4) + thor (~> 0.14.0) + rake (0.8.7) + rspec (2.0.0) + rspec-core (= 2.0.0) + rspec-expectations (= 2.0.0) + rspec-mocks (= 2.0.0) + rspec-core (2.0.0) + rspec-expectations (2.0.0) + diff-lcs (>= 1.1.2) + rspec-mocks (2.0.0) + rspec-core (= 2.0.0) + rspec-expectations (= 2.0.0) + rspec-rails (2.0.0) + rspec (= 2.0.0) + sqlite3-ruby (1.3.1) + thor (0.14.3) + treetop (1.4.8) + polyglot (>= 0.3.1) + tzinfo (0.3.23) + webrat (0.7.1) + nokogiri (>= 1.2.0) + rack (>= 1.0) + rack-test (>= 0.5.3) + +PLATFORMS + ruby + +DEPENDENCIES + rails (= 3.0.0) + rspec (= 2.0.0) + rspec-rails (= 2.0.0) + sqlite3-ruby + webrat (= 0.7.1)
djbender/sa
29e32a2673702da401185b13764de048277bdca3
tweeking splash input box
diff --git a/content/index.html b/content/index.html index ee862a1..51b00fe 100644 --- a/content/index.html +++ b/content/index.html @@ -1,5 +1,5 @@ --- title: Spoiler Alert --- -<h1 id="droid">Welcome to <input type="text" disabled="disabled"/></h1> +<h1 id="droid">Welcome to <input type="text" disabled="disabled"/>.</h1> diff --git a/content/stylesheet.css b/content/stylesheet.css index 7342072..8457c98 100644 --- a/content/stylesheet.css +++ b/content/stylesheet.css @@ -1,69 +1,70 @@ /** { margin: 0; padding: 0; font-family: Georgia, Palatino, Times, 'Times New Roman', sans-serif; }*/ body { background: #fff; } a { text-decoration: none; } a:link, a:visited { color: #f30; } a:hover { color: #f90; } #main { text-align: center; top: 100px; } #main h1 { font-size: 40px; font-weight: normal; line-height: 40px; letter-spacing: -1px; } #main p { margin: 20px 0; font-size: 15px; line-height: 20px; } #main ul { margin: 20px; } #main li { list-style-type: square; font-size: 15px; line-height: 20px; } #droid { font-family: 'Droid Sans', arial, sans-serif; text-shadow: 1px 1px 1px rgba(0,0,0,.4); } .spoiler { text-shadow: 1px 1px 1px rgba(0,0,0,0) } input { padding-top: 20px; height: 20px; + width: 200px; } diff --git a/output/index.html b/output/index.html index e6ec20d..0c27d8a 100644 --- a/output/index.html +++ b/output/index.html @@ -1,17 +1,17 @@ <!DOCTYPE HTML> <html lang="en"> <head> <meta charset="utf-8"> <title>Spoiler Alert</title> <link rel="stylesheet" type="text/css" href="/style.css" media="screen"> <link href='http://fonts.googleapis.com/css?family=Droid+Sans&subset=latin' rel='stylesheet' type='text/css'> <meta name="generator" content="nanoc 3.1.5"> </head> <body> <div id="main"> - <h1 id="droid">Welcome to <input type="text" disabled="disabled" /></h1> + <h1 id="droid">Welcome to <input type="text" disabled="disabled" />.</h1> </div> </body> </html> diff --git a/output/style.css b/output/style.css index 7342072..8457c98 100644 --- a/output/style.css +++ b/output/style.css @@ -1,69 +1,70 @@ /** { margin: 0; padding: 0; font-family: Georgia, Palatino, Times, 'Times New Roman', sans-serif; }*/ body { background: #fff; } a { text-decoration: none; } a:link, a:visited { color: #f30; } a:hover { color: #f90; } #main { text-align: center; top: 100px; } #main h1 { font-size: 40px; font-weight: normal; line-height: 40px; letter-spacing: -1px; } #main p { margin: 20px 0; font-size: 15px; line-height: 20px; } #main ul { margin: 20px; } #main li { list-style-type: square; font-size: 15px; line-height: 20px; } #droid { font-family: 'Droid Sans', arial, sans-serif; text-shadow: 1px 1px 1px rgba(0,0,0,.4); } .spoiler { text-shadow: 1px 1px 1px rgba(0,0,0,0) } input { padding-top: 20px; height: 20px; + width: 200px; }
djbender/sa
9dccb6bd4da5d081b6cae72ef5195de2e90927d7
changed to blank input box
diff --git a/content/index.html b/content/index.html index e8c99a5..ee862a1 100644 --- a/content/index.html +++ b/content/index.html @@ -1,5 +1,5 @@ --- title: Spoiler Alert --- -<h1 id="droid">Welcome to <span style="color: rgb(0, 0, 0); background-color: rgb(0, 0, 0);" class="spoiler" onmouseover="this.style.color='#FFF';" onmouseout="this.style.color=this.style.backgroundColor='#000'">Spoiler Alert</span></h1> +<h1 id="droid">Welcome to <input type="text" disabled="disabled"/></h1> diff --git a/content/stylesheet.css b/content/stylesheet.css index 1ba78bb..7342072 100644 --- a/content/stylesheet.css +++ b/content/stylesheet.css @@ -1,65 +1,69 @@ /** { margin: 0; padding: 0; font-family: Georgia, Palatino, Times, 'Times New Roman', sans-serif; }*/ body { background: #fff; } a { text-decoration: none; } a:link, a:visited { color: #f30; } a:hover { color: #f90; } #main { text-align: center; top: 100px; } #main h1 { font-size: 40px; font-weight: normal; line-height: 40px; letter-spacing: -1px; } #main p { margin: 20px 0; font-size: 15px; line-height: 20px; } #main ul { margin: 20px; } #main li { list-style-type: square; font-size: 15px; line-height: 20px; } #droid { font-family: 'Droid Sans', arial, sans-serif; text-shadow: 1px 1px 1px rgba(0,0,0,.4); } .spoiler { text-shadow: 1px 1px 1px rgba(0,0,0,0) } +input { + padding-top: 20px; + height: 20px; +} diff --git a/output/index.html b/output/index.html index 18aa1d2..e6ec20d 100644 --- a/output/index.html +++ b/output/index.html @@ -1,17 +1,17 @@ <!DOCTYPE HTML> <html lang="en"> <head> <meta charset="utf-8"> <title>Spoiler Alert</title> <link rel="stylesheet" type="text/css" href="/style.css" media="screen"> <link href='http://fonts.googleapis.com/css?family=Droid+Sans&subset=latin' rel='stylesheet' type='text/css'> <meta name="generator" content="nanoc 3.1.5"> </head> <body> <div id="main"> - <h1 id="droid">Welcome to <span style="color: rgb(0, 0, 0); background-color: rgb(0, 0, 0);" class="spoiler" onmouseover="this.style.color='#FFF';" onmouseout="this.style.color=this.style.backgroundColor='#000'">Spoiler Alert</span></h1> + <h1 id="droid">Welcome to <input type="text" disabled="disabled" /></h1> </div> </body> </html> diff --git a/output/style.css b/output/style.css index 1ba78bb..7342072 100644 --- a/output/style.css +++ b/output/style.css @@ -1,65 +1,69 @@ /** { margin: 0; padding: 0; font-family: Georgia, Palatino, Times, 'Times New Roman', sans-serif; }*/ body { background: #fff; } a { text-decoration: none; } a:link, a:visited { color: #f30; } a:hover { color: #f90; } #main { text-align: center; top: 100px; } #main h1 { font-size: 40px; font-weight: normal; line-height: 40px; letter-spacing: -1px; } #main p { margin: 20px 0; font-size: 15px; line-height: 20px; } #main ul { margin: 20px; } #main li { list-style-type: square; font-size: 15px; line-height: 20px; } #droid { font-family: 'Droid Sans', arial, sans-serif; text-shadow: 1px 1px 1px rgba(0,0,0,.4); } .spoiler { text-shadow: 1px 1px 1px rgba(0,0,0,0) } +input { + padding-top: 20px; + height: 20px; +}
djbender/sa
4b2dbb090adba3855cf1ea69076b30fd2f623347
tweaking display
diff --git a/content/stylesheet.css b/content/stylesheet.css index d1c8beb..1ba78bb 100644 --- a/content/stylesheet.css +++ b/content/stylesheet.css @@ -1,62 +1,65 @@ /** { margin: 0; padding: 0; font-family: Georgia, Palatino, Times, 'Times New Roman', sans-serif; }*/ body { background: #fff; } a { text-decoration: none; } a:link, a:visited { color: #f30; } a:hover { color: #f90; } #main { - position:absolute; text-align: center; - width: 900px; top: 100px; } #main h1 { font-size: 40px; font-weight: normal; line-height: 40px; letter-spacing: -1px; } #main p { margin: 20px 0; font-size: 15px; line-height: 20px; } #main ul { margin: 20px; } #main li { list-style-type: square; font-size: 15px; line-height: 20px; } #droid { font-family: 'Droid Sans', arial, sans-serif; + text-shadow: 1px 1px 1px rgba(0,0,0,.4); +} + +.spoiler { + text-shadow: 1px 1px 1px rgba(0,0,0,0) } diff --git a/output/style.css b/output/style.css index d1c8beb..1ba78bb 100644 --- a/output/style.css +++ b/output/style.css @@ -1,62 +1,65 @@ /** { margin: 0; padding: 0; font-family: Georgia, Palatino, Times, 'Times New Roman', sans-serif; }*/ body { background: #fff; } a { text-decoration: none; } a:link, a:visited { color: #f30; } a:hover { color: #f90; } #main { - position:absolute; text-align: center; - width: 900px; top: 100px; } #main h1 { font-size: 40px; font-weight: normal; line-height: 40px; letter-spacing: -1px; } #main p { margin: 20px 0; font-size: 15px; line-height: 20px; } #main ul { margin: 20px; } #main li { list-style-type: square; font-size: 15px; line-height: 20px; } #droid { font-family: 'Droid Sans', arial, sans-serif; + text-shadow: 1px 1px 1px rgba(0,0,0,.4); +} + +.spoiler { + text-shadow: 1px 1px 1px rgba(0,0,0,0) }
djbender/sa
e757a28de1841024d0f412c0c8eae1d0e750897d
changed font to droid. removed * from CSS
diff --git a/config.ru b/config.ru index daaa2eb..4a41df5 100644 --- a/config.ru +++ b/config.ru @@ -1,16 +1,16 @@ gem 'rack-rewrite', '~> 1.0.0' require 'rack/rewrite' use Rack::Rewrite do r301 %r{^([^\.]*[^\/])$}, '$1/' r301 %r{^(.*\/)$}, '$1index.html' end use Rack::Static, :urls => ["/"], :root => Dir.pwd + '/output' # Empty app, should never be reached: class Homepage def call(env) [200, {"Content-Type" => "text/html"}, ["There's a problem with my website. Please report the problem to [email protected]/"] ] end end -run Homepage.new \ No newline at end of file +run Homepage.new diff --git a/content/index.html b/content/index.html index 9b1a62c..e8c99a5 100644 --- a/content/index.html +++ b/content/index.html @@ -1,5 +1,5 @@ --- title: Spoiler Alert --- -<h1>Welcome to <span style="color: rgb(0, 0, 0); background-color: rgb(0, 0, 0);" class="spoiler" onmouseover="this.style.color='#FFF';" onmouseout="this.style.color=this.style.backgroundColor='#000'">Spoiler Alert</span></h1> +<h1 id="droid">Welcome to <span style="color: rgb(0, 0, 0); background-color: rgb(0, 0, 0);" class="spoiler" onmouseover="this.style.color='#FFF';" onmouseout="this.style.color=this.style.backgroundColor='#000'">Spoiler Alert</span></h1> diff --git a/content/stylesheet.css b/content/stylesheet.css index 6f4ea2d..d1c8beb 100644 --- a/content/stylesheet.css +++ b/content/stylesheet.css @@ -1,60 +1,62 @@ -* { +/** { margin: 0; padding: 0; - font-family: Georgia, Palatino, Times, 'Times New Roman', sans-serif; -} +}*/ body { background: #fff; } a { text-decoration: none; } a:link, a:visited { color: #f30; } a:hover { color: #f90; } #main { position:absolute; text-align: center; width: 900px; top: 100px; } #main h1 { font-size: 40px; font-weight: normal; line-height: 40px; letter-spacing: -1px; } #main p { margin: 20px 0; font-size: 15px; line-height: 20px; } #main ul { margin: 20px; } #main li { list-style-type: square; font-size: 15px; line-height: 20px; } +#droid { + font-family: 'Droid Sans', arial, sans-serif; +} diff --git a/layouts/default.html b/layouts/default.html index f510d5e..43e8480 100644 --- a/layouts/default.html +++ b/layouts/default.html @@ -1,14 +1,16 @@ <!DOCTYPE HTML> <html lang="en"> - <head> - <meta charset="utf-8"> - <title><%= @item[:title] %></title> - <link rel="stylesheet" type="text/css" href="/style.css" media="screen"> - <meta name="generator" content="nanoc 3.1.5"> - </head> - <body> - <div id="main"> - <%= yield %> - </div> - </body> + <head> + <meta charset="utf-8"> + <title><%= @item[:title] %></title> + <link rel="stylesheet" type="text/css" href="/style.css" media="screen"> + <link href='http://fonts.googleapis.com/css?family=Droid+Sans&subset=latin' rel='stylesheet' type='text/css'> + + <meta name="generator" content="nanoc 3.1.5"> + </head> + <body> + <div id="main"> + <%= yield %> + </div> + </body> </html> diff --git a/output/index.html b/output/index.html index 5f7b179..18aa1d2 100644 --- a/output/index.html +++ b/output/index.html @@ -1,15 +1,17 @@ <!DOCTYPE HTML> <html lang="en"> - <head> - <meta charset="utf-8"> - <title>Spoiler Alert</title> - <link rel="stylesheet" type="text/css" href="/style.css" media="screen"> - <meta name="generator" content="nanoc 3.1.5"> - </head> - <body> - <div id="main"> - <h1>Welcome to <span style="color: rgb(0, 0, 0); background-color: rgb(0, 0, 0);" class="spoiler" onmouseover="this.style.color='#FFF';" onmouseout="this.style.color=this.style.backgroundColor='#000'">Spoiler Alert</span></h1> + <head> + <meta charset="utf-8"> + <title>Spoiler Alert</title> + <link rel="stylesheet" type="text/css" href="/style.css" media="screen"> + <link href='http://fonts.googleapis.com/css?family=Droid+Sans&subset=latin' rel='stylesheet' type='text/css'> - </div> - </body> + <meta name="generator" content="nanoc 3.1.5"> + </head> + <body> + <div id="main"> + <h1 id="droid">Welcome to <span style="color: rgb(0, 0, 0); background-color: rgb(0, 0, 0);" class="spoiler" onmouseover="this.style.color='#FFF';" onmouseout="this.style.color=this.style.backgroundColor='#000'">Spoiler Alert</span></h1> + + </div> + </body> </html> diff --git a/output/style.css b/output/style.css index 6f4ea2d..d1c8beb 100644 --- a/output/style.css +++ b/output/style.css @@ -1,60 +1,62 @@ -* { +/** { margin: 0; padding: 0; - font-family: Georgia, Palatino, Times, 'Times New Roman', sans-serif; -} +}*/ body { background: #fff; } a { text-decoration: none; } a:link, a:visited { color: #f30; } a:hover { color: #f90; } #main { position:absolute; text-align: center; width: 900px; top: 100px; } #main h1 { font-size: 40px; font-weight: normal; line-height: 40px; letter-spacing: -1px; } #main p { margin: 20px 0; font-size: 15px; line-height: 20px; } #main ul { margin: 20px; } #main li { list-style-type: square; font-size: 15px; line-height: 20px; } +#droid { + font-family: 'Droid Sans', arial, sans-serif; +}
djbender/sa
b5448a287d46a7b602a2436496ed975ccf8ee32f
adding files so i can deploy to heroku
diff --git a/.gems b/.gems new file mode 100644 index 0000000..f204a45 --- /dev/null +++ b/.gems @@ -0,0 +1 @@ +rack-rewrite --version '>= 1.0.0' diff --git a/config.ru b/config.ru new file mode 100644 index 0000000..daaa2eb --- /dev/null +++ b/config.ru @@ -0,0 +1,16 @@ +gem 'rack-rewrite', '~> 1.0.0' +require 'rack/rewrite' +use Rack::Rewrite do + r301 %r{^([^\.]*[^\/])$}, '$1/' + r301 %r{^(.*\/)$}, '$1index.html' +end + +use Rack::Static, :urls => ["/"], :root => Dir.pwd + '/output' + +# Empty app, should never be reached: +class Homepage + def call(env) + [200, {"Content-Type" => "text/html"}, ["There's a problem with my website. Please report the problem to [email protected]/"] ] + end +end +run Homepage.new \ No newline at end of file
djbender/sa
8594f5fc80b83f9e4b1ca56802d8695ee81abd82
blank README
diff --git a/README b/README new file mode 100644 index 0000000..e69de29
alderete/Cap-and-Run
d54b40bdfe27482f9580057e6bbcc65b64b5fe99
Long overdue initial commit.
diff --git a/cap-and-run.php b/cap-and-run.php new file mode 100644 index 0000000..848b786 --- /dev/null +++ b/cap-and-run.php @@ -0,0 +1,260 @@ +<?php +/* +Plugin Name: Cap & Run +Version: 1.0 +Description: Drop caps and run-ins for posts and pages. +Plugin URI: http://URI_Of_Page_Describing_Plugin_and_Updates +Author: Michael A. Alderete, Aldosoft +Author URI: http://github.com/alderete/Cap-and-Run +License: GPL2 + +Copyright 2010 by Michael A. Alderete + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License, version 2, as +published by the Free Software Foundation. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +// Define the CapAndRun plugin +global $wp_version; +if ( version_compare($wp_version, "2.8", "<") ): + // Requirement for 2.8 is semi-arbitrary, gotta draw the line somewhere + exit('Cap &amp; Run requires WordPress 2.8 or later. + <a href="http://codex.wordpress.org/Upgrading_WordPress">Please upgrade.</a> + Upgrading is a good idea, for many reasons beyond Cap &amp; Run.'); +else: + if ( ! class_exists('CapAndRun') ) { + class CapAndRun { + + var $options_name = 'CapAndRun_Options'; + var $options_loaded = false; + + function activate_plugin() { + $set_defaults = $this->get_options(); + } + + function get_options() { + + if ( ! $this->options_loaded ) { + // These are the default options + $car_options = array( + 'add_initial_cap' => false, + 'add_run_in' => 'none', // none | line | words + 'run_in_words' => '5', + 'add_styles_to_header' => 'no', // no | yes + 'styles_to_add' => '', + ); + + // Now merge in the saved options + $set_options = get_option($this->options_name); + if ( ! empty($set_options) ) { + foreach($set_options as $key => $option) { + $car_options[$key] = $option; + } + } + + // Make sure we save back a complete set + update_option($this->options_name, $car_options); + + // Save options, so we're not writing db multiple times / page view + $this->options_loaded = $car_options; + } + return($this->options_loaded); + } + + // Processing functions, run on every page view + function add_style_definitions() { + $options = $this->get_options(); + if( 'yes' === $options['add_styles_to_header'] ) { + echo "<!-- Styles added by Cap & Run plugin -->\n"; + echo "<style type=\"text/css\">\n"; + echo $options['styles_to_add']; + echo "</style>\n"; + echo "<!-- End of Cap & Run style additions -->\n\n"; + } + } + + function add_styling_markup($content = '') { + // error_log($content); + $options = $this->get_options(); + if( !( is_single() || is_page() || is_admin() ) || + (($options['add_initial_cap'] === false) && ($options['add_run_in'] === 'none')) ) { + return($content); // shortcut out + } + + $pattern = '/<p( .*)?( class="(.*)")??( .*)?>((<[^>]*>|\s)*)((?:&quot;|&#8220;|&#8216;|&lsquo;|&ldquo;|\')?[A-Z])(([a-zA-Z]+\s+){0,' . $options['run_in_words'] . '}?)/U'; + $replacement = '<p$1 class="first-child $3"$4>$5<span title="$7" class="cap"><span>$7</span></span><span class="run-in">$8</span>'; + $content = preg_replace($pattern, $replacement, $content, 1 ); + + /* + // Handle the drop cap + if( $options['add_initial_cap'] === true ) { + // The next three lines are copied from the Drop Caps plugin by Thomas Milburn + // http://instantsolve.net/blog/plugins/ + $pattern = '/<p( .*)?( class="(.*)")??( .*)?>((<[^>]*>|\s)*)((&quot;|&#8220;|&#8216;|&lsquo;|&ldquo;|\')?[A-Z])/U'; + $replacement = '<p$1 class="first-child $3"$4>$5<span title="$7" class="cap"><span>$7</span></span>'; + $content = preg_replace($pattern, $replacement, $content, 1 ); + } + + // Handle the run-in + if( $options['add_run_in'] === true ) { + $pattern = '//U'; + $replacement = ''; + $content = preg_replace($pattern, $replacement, $content, 1); + } + */ + + return($content); + } + + // Administrative functions, runs only for WP Admins + function add_options_page() { + if ( function_exists('add_theme_page') ) { + add_theme_page( 'Cap &amp; Run', 'Cap &amp; Run', 'manage_options', + basename(__FILE__), array(&$this, 'options_page') ); + } + } + + function options_page() { + + $options = $this->get_options(); + + // Save a submitted options form + if ( isset($_POST['update_capandrun']) && check_admin_referer('capandrun_options_page') ) { + // TODO -- check the nonce? + $options['add_initial_cap'] = (isset($_POST['car_add_initial_cap'])) ? true : false; + if ( isset($_POST['car_add_run_in']) ) { + if ( 'line' == $_POST['car_add_run_in'] ) { + $options['add_run_in'] = 'line'; + } + elseif ( 'words' == $_POST['car_add_run_in'] ) { + $options['add_run_in'] = 'words'; + } + else { + $options['add_run_in'] = 'none'; + } + } + if ( isset($_POST['cars_num_words']) ) { + $options['run_in_words'] = min(max(1, (int)$_POST['cars_num_words']), 10); // between 1..10 + } + if ( isset($_POST['car_add_styles']) ) { + if ( 'yes' == $_POST['car_add_styles'] ) { + $options['add_styles_to_header'] = 'yes'; + } + else { + $options['add_styles_to_header'] = 'no'; + } + } + if ( isset($_POST['car_styles']) ) { + $options['styles_to_add'] = stripslashes($_POST['car_styles']); // TODO, better escape? + } + update_option($this->options_name, $options); + echo '<div class="updated"><p><strong>' . __('Settings updated.', 'CapAndRun') . + '</strong></p></div>'; + } + + // Display options form + ?> + <div class="wrap"> + + <h2>Cap &amp; Run Options</h2> + + <p class="narrow"><strong>Cap &amp; Run</strong> can add styles to display initial + capital letters (generally called "drop caps") and text "run-ins" + (first few words or first line) in a different text style than the + normal body copy.</p> + + <form method="post" action="<?php echo $_SERVER["REQUEST_URI"]; ?>"> + + <h3>Drop Caps</h3> + <ul> + <li><input type="checkbox" id="car_add_initial_cap" name="car_add_initial_cap" <?php if ($options['add_initial_cap']) echo 'checked="checked"'; ?> /> + <label for="car_add_initial_cap">Stylize first letter of post/page as Drop Cap</label></li> + </ul> + + <h3>Text Run-In</h3> + <ul> + <li><input type="radio" id="car_add_run_in_none" name="car_add_run_in" value="none" <?php + if ('none' === $options['add_run_in']) echo 'checked="checked"'; ?> /> + <label for="car_add_run_in_none">No text run-in</label></li> + <li><input type="radio" id="car_add_run_in_line" name="car_add_run_in" value="line" <?php + if ('line' === $options['add_run_in']) echo 'checked="checked"'; ?> /> + <label for="car_add_run_in_line">Stylize first line of post/page as + Run In (using CSS only &mdash; more "clean")</label></li> + <li><input type="radio" id="car_add_run_in_words" name="car_add_run_in" value="words" <?php + if ('words' === $options['add_run_in']) echo 'checked="checked"'; ?> /> + <label for="car_add_run_in_words">Stylize first + <input type="text" id="cars_num_words" name="cars_num_words" size="3" <?php + if ($options['run_in_words']) echo 'value="' . $options['run_in_words'] . '"'; + ?> /> words of post/page as Run In (using &lt;span&gt; + CSS &mdash; more compatible)</label></li> + </ul> + + <h3>Styling</h3> + <ul> + <li><input type="radio" id="car_add_styles_no" name="car_add_styles" value="no" <?php + if ('no' === $options['add_styles_to_header']) echo 'checked="checked"'; ?> /> + <label for="car_add_styles_no">Do not add styles to &lt;header&gt; (you must manually add styles to site CSS file)</label></li> + <li><input type="radio" id="car_add_styles_yes" name="car_add_styles" value="yes" <?php + if ('yes' === $options['add_styles_to_header']) echo 'checked="checked"'; ?> /> + <label for="car_add_styles_yes">Add these styles to &lt;header&gt;:</label><br /> + &nbsp;&nbsp;&nbsp;&nbsp;<textarea id="car_styles" name="car_styles" style="width: 60%;" rows="8"><?php + echo stripslashes($options['styles_to_add']); ?></textarea></li> + </ul> + + <div class="submit"> + <?php wp_nonce_field('capandrun_options_page'); ?> + <input type="submit" class="button-primary" name="update_capandrun" + value="<?php _e('Update Settings', 'CapAndRun'); ?>" /> + </div> + + </form> + + <h3>Tests</h3> + <?php + require('tests.php'); + + foreach($cases as $case) { + echo "<hr />"; + echo "<h4>Test Case:</h4>\n\n<p><code>" . + htmlspecialchars($case) . + "</code></p>\n\n"; + echo "<h4>Result:</h4>\n\n<p><code>" . + htmlspecialchars($this->add_styling_markup($case)) . + "</code></p>\n\n"; + } + + ?> + + </div> + <?php + } + + } // end class CapAndRun definition + } +endif; // end WordPress version check + +// Activate the plugin +if ( class_exists('CapAndRun') ) { + $cap_and_run = new CapAndRun(); + if ( function_exists('register_activation_hook') ) { + register_activation_hook(__FILE__, array(&$cap_and_run, 'activate_plugin')); + } + if ( function_exists('add_action') ) { + add_action('admin_menu', array(&$cap_and_run, 'add_options_page')); + add_action('wp_head', array(&$cap_and_run, 'add_style_definitions')); + } + if ( function_exists('add_filter') ) { + add_filter('the_content', array(&$cap_and_run, 'add_styling_markup'), 90); + } +} + +?> \ No newline at end of file diff --git a/readme.txt b/readme.txt new file mode 100644 index 0000000..7b4220b --- /dev/null +++ b/readme.txt @@ -0,0 +1,74 @@ +=== Cap & Run === +Contributors: alderete +Tags: text, typography, drop-cap, small-caps +Requires at least: 2.8 +Tested up to: 3.0 +Stable tag: 1.0 + +Cap & Run add styles to display typographic "drop caps" and "run-ins" (first few words or first line) in different text styles than normal body copy. + +== Description == + +This is the long description. No limit, and you can use Markdown (as well as in the following sections). + +For backwards compatibility, if this section is missing, the full length of the short description will be used, and +Markdown parsed. + +A few notes about the sections above: + +* "Contributors" is a comma separated list of wp.org/wp-plugins.org usernames +* "Tags" is a comma separated list of tags that apply to the plugin +* "Requires at least" is the lowest version that the plugin will work on +* "Tested up to" is the highest version that you've *successfully used to test the plugin*. Note that it might work on +higher versions... this is just the highest one you've verified. +* Stable tag should indicate the Subversion "tag" of the latest stable version, or "trunk," if you use `/trunk/` for +stable. + + Note that the `readme.txt` of the stable tag is the one that is considered the defining one for the plugin, so +if the `/trunk/readme.txt` file says that the stable tag is `4.3`, then it is `/tags/4.3/readme.txt` that'll be used +for displaying information about the plugin. In this situation, the only thing considered from the trunk `readme.txt` +is the stable tag pointer. Thus, if you develop in trunk, you can update the trunk `readme.txt` to reflect changes in +your in-development version, without having that information incorrectly disclosed about the current stable version +that lacks those changes -- as long as the trunk's `readme.txt` points to the correct stable tag. + + If no stable tag is provided, it is assumed that trunk is stable, but you should specify "trunk" if that's where +you put the stable version, in order to eliminate any doubt. + +== Installation == + +This section describes how to install the plugin and get it working. + +e.g. + +1. Upload `plugin-name.php` to the `/wp-content/plugins/` directory +1. Activate the plugin through the 'Plugins' menu in WordPress +1. Place `<?php do_action('plugin_name_hook'); ?>` in your templates + +== Frequently Asked Questions == + += A question that someone might have = + +An answer to that question. + += What about foo bar? = + +Answer to foo bar dilemma. + +== Screenshots == + +1. This screen shot description corresponds to screenshot-1.(png|jpg|jpeg|gif). Note that the screenshot is taken from +the directory of the stable readme.txt, so in this case, `/tags/4.3/screenshot-1.png` (or jpg, jpeg, gif) +2. This is the second screen shot + +== Changelog == + += 1.0 = +* Initial release. + += 1.0b1 = +* Beta release for final testing purposes. UNSUPPORTED. + +== Upgrade Notice == + += 1.0 = +All versions prior to 1.0 were unreleased, unstable development snapshots. diff --git a/tests.php b/tests.php new file mode 100644 index 0000000..a1faa00 --- /dev/null +++ b/tests.php @@ -0,0 +1,114 @@ +<?php +/* + Test Expectations: + - For all run in tests, run in length is 6 words + + Test Series: + - Drop cap only, no run in + - Drop cap + run in + - Run in only +*/ + +$cases = array(); + +// Plain paragraph +$cases[] = <<<CASE +WordPress is web software you can use to create a beautiful website or blog. We like to say that WordPress is both free and priceless at the same time. +CASE; + +// Paragraph with <p> tags already +$cases[] = <<<CASE +<p>WordPress is web software you can use to create a beautiful website or blog. We like to say that WordPress is both free and priceless at the same time.</p> +CASE; + + +// Paragraph with <p class="xxx"> tag +$cases[] = <<<CASE +<p class="intro first lead">WordPress is web software you can use to create a beautiful website or blog. We like to say that WordPress is both free and priceless at the same time.</p> +CASE; + + +// Paragraph with <x> tags inside text run range +$cases[] = <<<CASE +<p>WordPress is <em>web software</em> you can use to create a beautiful website or blog. We like to say that WordPress is both free and priceless at the same time.</p> +CASE; + + +// Paragraph with <x> tags that run from inside to outside text run range +$cases[] = <<<CASE +<p>WordPress is web software <em>you can use</em> to create a beautiful website or blog. We like to say that WordPress is both free and priceless at the same time.</p> +CASE; + + +// Paragraph with multiple <x> tag spans inside text run range +$cases[] = <<<CASE +<p><strong>WordPress</strong> is <em>web software</em> <u>you</u> can use to create a beautiful website or blog. We like to say that WordPress is both free and priceless at the same time.</p> +CASE; + + +// Paragraph with multiple <x> tag spans with last running outside text run range +$cases[] = <<<CASE +<p><strong>WordPress</strong> is <em>web software</em> <em>you can use</em> to create a beautiful website or blog. We like to say that WordPress is both free and priceless at the same time.</p> +CASE; + + +// Paragraph with triple-level tags, some inside, some outside text run range +$cases[] = <<<CASE +<p>WordPress is <em><strong>web software <u>you</u></strong> can use to create a beautiful website or blog</em>. We like to say that WordPress is both free and priceless at the same time.</p> +CASE; + + +// Paragraph with unbalanced / non-validating HTML tags + + +// Paragraph with tags starting before the drop cap + + +// <x> tags that don't end on word boundaries +$cases[] = <<<CASE +<p>This is un<em>fucking</em>believable. What do we do now?</p> +CASE; + + +// Tags with attributes + + +// Tags with attributes containing ">" character + + +// Paragraph with multibyte characters (UTF8) + + +// Paragraph shorter (in words) than the run in length + + +// Hard-wrapped paragraphs + + +// Kitchen sink, From DIYThemes +$cases[] = <<<CASE +<p>Simply put, Thesis is <em>powerful</em>. It has a remarkably efficient <acronym title="HyperText Markup Language">HTML</acronym> <code>+</code> <acronym title="Cascading Style Sheet">CSS</acronym> <code>+</code> <acronym title="recursive acronym for Hypertext Preprocessor">PHP</acronym> framework and easy-to-use controls that you can use to fine-tune each and every page of your site with a tactical precision that has never been possible before. The days of worrying about your in-site <acronym title="Search Engine Optimization">SEO</acronym> are over—with Thesis, your strategy is “just add killer content.”</p> +CASE; + + +/* +// Lorem Ipsum +Apple ignited the personal computer revolution in the 1970s with the Apple II and reinvented the personal computer in the 1980s with the Macintosh. Today, Apple continues to lead the industry in innovation with its award-winning computers, OS X operating system and iLife and professional applications. Apple is also spearheading the digital media revolution with its iPod portable music and video players and iTunes online store, and has entered the mobile phone market with its revolutionary iPhone. + +We the People of the United States, in Order to form a more perfect Union, establish Justice, ensure domestic Tranquility, provide for the common defence, promote the general Welfare, and secure the Blessings of Liberty to ourselves and our Posterity, do ordain and establish this Constitution for the United States of America. + +Four score and seven years ago our fathers brought forth +on this continent a new nation, conceived in liberty, and +dedicated to the proposition that all men are created equal. + +Now we are engaged in a great civil war, testing whether that +nation, or any nation, so conceived and so dedicated, can long +endure. We are met on a great battle-field of that war. We +have come to dedicate a portion of that field, as a final +resting place for those who here gave their lives that that +nation might live. It is altogether fitting and proper that we +should do this. + +But, in a larger sense, we can not dedicate, we can not consecrate, we can not hallow this ground. The brave men, living and dead, who struggled here, have consecrated it, far above our poor power to add or detract. The world will little note, nor long remember what we say here, but it can never forget what they did here. It is for us the living, rather, to be dedicated here to the unfinished work which they who fought here have thus far so nobly advanced. It is rather for us to be here dedicated to the great task remaining before us—that from these honored dead we take increased devotion to that cause for which they gave the last full measure of devotion—that we here highly resolve that these dead shall not have died in vain—that this nation, under God, shall have a new birth of freedom—and that government of the people, by the people, for the people, shall not perish from the earth. +*/ +?> \ No newline at end of file
hbussell/pycrypto
ccc8ae2e43fce280ca6572fccd5430b91068d5dd
use absolute package_dir in setup.py
diff --git a/setup.py b/setup.py index 37aedef..d52c8d9 100644 --- a/setup.py +++ b/setup.py @@ -1,341 +1,341 @@ #! /usr/bin/env python # # setup.py : Distutils setup script # # Part of the Python Cryptography Toolkit # # =================================================================== # Portions Copyright (c) 2001, 2002, 2003 Python Software Foundation; # All Rights Reserved # # This file contains code from the Python 2.2 setup.py module (the # "Original Code"), with modifications made after it was incorporated # into PyCrypto (the "Modifications"). # # To the best of our knowledge, the Python Software Foundation is the # copyright holder of the Original Code, and has licensed it under the # Python 2.2 license. See the file LEGAL/copy/LICENSE.python-2.2 for # details. # # The Modifications to this file are dedicated to the public domain. # To the extent that dedication to the public domain is not available, # everyone is granted a worldwide, perpetual, royalty-free, # non-exclusive license to exercise all rights associated with the # contents of this file for any purpose whatsoever. No rights are # reserved. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # =================================================================== __revision__ = "$Id$" from distutils import core from distutils.core import Extension, Command from distutils.command.build_ext import build_ext import os, sys import struct if sys.version[0:1] == '1': raise RuntimeError, ("The Python Cryptography Toolkit requires " "Python 2.x to build.") if sys.platform == 'win32': HTONS_LIBS = ['ws2_32'] plat_ext = [ Extension("Crypto.Random.OSRNG.winrandom", libraries = HTONS_LIBS + ['advapi32'], include_dirs=['src/'], sources=["src/winrand.c"]) ] else: HTONS_LIBS = [] plat_ext = [] # For test development: Set this to 1 to build with gcov support. # Use "gcov -p -o build/temp.*/src build/temp.*/src/*.gcda" to build the .gcov files USE_GCOV = 0 # List of pure Python modules that will be excluded from the binary packages. # The list consists of (package, module_name) tuples from distutils.command.build_py import build_py EXCLUDE_PY = [ ('Crypto.Hash', 'RIPEMD160'), # Included for your amusement, but the C version is much faster. ] # Functions for finding libraries and files, copied from Python's setup.py. def find_file(filename, std_dirs, paths): """Searches for the directory where a given file is located, and returns a possibly-empty list of additional directories, or None if the file couldn't be found at all. 'filename' is the name of a file, such as readline.h or libcrypto.a. 'std_dirs' is the list of standard system directories; if the file is found in one of them, no additional directives are needed. 'paths' is a list of additional locations to check; if the file is found in one of them, the resulting list will contain the directory. """ # Check the standard locations for dir in std_dirs: f = os.path.join(dir, filename) if os.path.exists(f): return [] # Check the additional directories for dir in paths: f = os.path.join(dir, filename) if os.path.exists(f): return [dir] # Not found anywhere return None def find_library_file(compiler, libname, std_dirs, paths): filename = compiler.library_filename(libname, lib_type='shared') result = find_file(filename, std_dirs, paths) if result is not None: return result filename = compiler.library_filename(libname, lib_type='static') result = find_file(filename, std_dirs, paths) return result def endianness_macro(): s = struct.pack("@I", 0x33221100) if s == "\x00\x11\x22\x33": # little endian return ('PCT_LITTLE_ENDIAN', 1) elif s == "\x33\x22\x11\x00": # big endian return ('PCT_BIG_ENDIAN', 1) raise AssertionError("Machine is neither little-endian nor big-endian") class PCTBuildExt (build_ext): def build_extensions(self): # Detect which modules should be compiled self.detect_modules() # Tweak compiler options if self.compiler.compiler_type in ('unix', 'cygwin', 'mingw32'): # Tell GCC to compile using the C99 standard. self.__add_compiler_option("-std=c99") # Make assert() statements always work self.__remove_compiler_option("-DNDEBUG") # Choose our own optimization options for opt in ["-O", "-O0", "-O1", "-O2", "-O3", "-Os"]: self.__remove_compiler_option(opt) if self.debug: # Basic optimization is still needed when debugging to compile # the libtomcrypt code. self.__add_compiler_option("-O") else: # Speed up execution by tweaking compiler options. This # especially helps the DES modules. self.__add_compiler_option("-O3") self.__add_compiler_option("-fomit-frame-pointer") # Don't include debug symbols unless debugging self.__remove_compiler_option("-g") # Don't include profiling information (incompatible with -fomit-frame-pointer) self.__remove_compiler_option("-pg") if USE_GCOV: self.__add_compiler_option("-fprofile-arcs") self.__add_compiler_option("-ftest-coverage") self.compiler.libraries += ['gcov'] # Call the superclass's build_extensions method build_ext.build_extensions(self) def detect_modules (self): # Add special include directory for MSVC (because MSVC is special) if self.compiler.compiler_type == 'msvc': self.compiler.include_dirs.insert(0, "src/inc-msvc/") # Detect libgmp and don't build _fastmath if it is missing. lib_dirs = self.compiler.library_dirs + ['/lib', '/usr/lib'] if not (self.compiler.find_library_file(lib_dirs, 'gmp')): print >>sys.stderr, "warning: GMP library not found; Not building Crypto.PublicKey._fastmath." self.__remove_extensions(["Crypto.PublicKey._fastmath"]) def __remove_extensions(self, names): """Remove the specified extension from the list of extensions to build""" i = 0 while i < len(self.extensions): if self.extensions[i].name in names: del self.extensions[i] continue i += 1 def __remove_compiler_option(self, option): """Remove the specified compiler option. Return true if the option was found. Return false otherwise. """ found = 0 for attrname in ('compiler', 'compiler_so'): compiler = getattr(self.compiler, attrname, None) if compiler is not None: while option in compiler: compiler.remove(option) found += 1 return found def __add_compiler_option(self, option): for attrname in ('compiler', 'compiler_so'): compiler = getattr(self.compiler, attrname, None) if compiler is not None: compiler.append(option) class PCTBuildPy(build_py): def find_package_modules(self, package, package_dir, *args, **kwargs): modules = build_py.find_package_modules(self, package, package_dir, *args, **kwargs) # Exclude certain modules retval = [] for item in modules: pkg, module = item[:2] if (pkg, module) in EXCLUDE_PY: continue retval.append(item) return retval class TestCommand(Command): description = "Run self-test" user_options = [ ('skip-slow-tests', None, 'Skip slow tests') ] def initialize_options(self): self.build_dir = None self.skip_slow_tests = None def finalize_options(self): self.set_undefined_options('install', ('build_lib', 'build_dir')) self.config = {'slow_tests': not self.skip_slow_tests} def run(self): # Run SelfTest self.announce("running self-tests") old_path = sys.path[:] try: sys.path.insert(0, self.build_dir) from Crypto import SelfTest SelfTest.run(verbosity=self.verbose, stream=sys.stdout, config=self.config) finally: # Restore sys.path sys.path[:] = old_path # Run slower self-tests self.announce("running extended self-tests") kw = {'name':"pycrypto", 'version':"2.3", # See also: lib/Crypto/__init__.py 'description':"Cryptographic modules for Python.", 'author':"Dwayne C. Litzenberger", 'author_email':"[email protected]", 'url':"http://www.pycrypto.org/", 'cmdclass' : {'build_ext':PCTBuildExt, 'build_py': PCTBuildPy, 'test': TestCommand }, 'packages' : ["Crypto", "Crypto.Hash", "Crypto.Cipher", "Crypto.Util", "Crypto.Random", "Crypto.Random.Fortuna", "Crypto.Random.OSRNG", "Crypto.SelfTest", "Crypto.SelfTest.Cipher", "Crypto.SelfTest.Hash", "Crypto.SelfTest.Protocol", "Crypto.SelfTest.PublicKey", "Crypto.SelfTest.Random", "Crypto.SelfTest.Random.Fortuna", "Crypto.SelfTest.Random.OSRNG", "Crypto.SelfTest.Util", "Crypto.Protocol", "Crypto.PublicKey"], - 'package_dir' : { "Crypto": "lib/Crypto" }, + 'package_dir' : { "Crypto": os.path.join(os.path.dirname(__file__), "lib/Crypto") }, 'ext_modules': plat_ext + [ # _fastmath (uses GNU mp library) Extension("Crypto.PublicKey._fastmath", include_dirs=['src/'], libraries=['gmp'], sources=["src/_fastmath.c"]), # Hash functions Extension("Crypto.Hash.MD2", include_dirs=['src/'], sources=["src/MD2.c"]), Extension("Crypto.Hash.MD4", include_dirs=['src/'], sources=["src/MD4.c"]), Extension("Crypto.Hash.SHA256", include_dirs=['src/'], sources=["src/SHA256.c"]), Extension("Crypto.Hash.RIPEMD160", include_dirs=['src/'], sources=["src/RIPEMD160.c"], define_macros=[endianness_macro()]), # Block encryption algorithms Extension("Crypto.Cipher.AES", include_dirs=['src/'], sources=["src/AES.c"]), Extension("Crypto.Cipher.ARC2", include_dirs=['src/'], sources=["src/ARC2.c"]), Extension("Crypto.Cipher.Blowfish", include_dirs=['src/'], sources=["src/Blowfish.c"]), Extension("Crypto.Cipher.CAST", include_dirs=['src/'], sources=["src/CAST.c"]), Extension("Crypto.Cipher.DES", include_dirs=['src/', 'src/libtom/'], sources=["src/DES.c"]), Extension("Crypto.Cipher.DES3", include_dirs=['src/', 'src/libtom/'], sources=["src/DES3.c"]), # Stream ciphers Extension("Crypto.Cipher.ARC4", include_dirs=['src/'], sources=["src/ARC4.c"]), Extension("Crypto.Cipher.XOR", include_dirs=['src/'], sources=["src/XOR.c"]), # Utility modules Extension("Crypto.Util.strxor", include_dirs=['src/'], sources=['src/strxor.c']), # Counter modules Extension("Crypto.Util._counter", include_dirs=['src/'], sources=['src/_counter.c']), ] } # If we're running Python 2.3, add extra information if hasattr(core, 'setup_keywords'): if 'classifiers' in core.setup_keywords: kw['classifiers'] = [ 'Development Status :: 4 - Beta', 'License :: Public Domain', 'Intended Audience :: Developers', 'Operating System :: Unix', 'Operating System :: Microsoft :: Windows', 'Operating System :: MacOS :: MacOS X', 'Topic :: Security :: Cryptography', ] if 'download_url' in core.setup_keywords: kw['download_url'] = ('http://www.pycrypto.org/files/' '%s-%s.tar.gz' % (kw['name'], kw['version']) ) core.setup(**kw)
hbussell/pycrypto
f2a119eccf50bee3e241fb58d140cd7a12c80e32
revert change
diff --git a/setup.py b/setup.py index d52c8d9..37aedef 100644 --- a/setup.py +++ b/setup.py @@ -1,341 +1,341 @@ #! /usr/bin/env python # # setup.py : Distutils setup script # # Part of the Python Cryptography Toolkit # # =================================================================== # Portions Copyright (c) 2001, 2002, 2003 Python Software Foundation; # All Rights Reserved # # This file contains code from the Python 2.2 setup.py module (the # "Original Code"), with modifications made after it was incorporated # into PyCrypto (the "Modifications"). # # To the best of our knowledge, the Python Software Foundation is the # copyright holder of the Original Code, and has licensed it under the # Python 2.2 license. See the file LEGAL/copy/LICENSE.python-2.2 for # details. # # The Modifications to this file are dedicated to the public domain. # To the extent that dedication to the public domain is not available, # everyone is granted a worldwide, perpetual, royalty-free, # non-exclusive license to exercise all rights associated with the # contents of this file for any purpose whatsoever. No rights are # reserved. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # =================================================================== __revision__ = "$Id$" from distutils import core from distutils.core import Extension, Command from distutils.command.build_ext import build_ext import os, sys import struct if sys.version[0:1] == '1': raise RuntimeError, ("The Python Cryptography Toolkit requires " "Python 2.x to build.") if sys.platform == 'win32': HTONS_LIBS = ['ws2_32'] plat_ext = [ Extension("Crypto.Random.OSRNG.winrandom", libraries = HTONS_LIBS + ['advapi32'], include_dirs=['src/'], sources=["src/winrand.c"]) ] else: HTONS_LIBS = [] plat_ext = [] # For test development: Set this to 1 to build with gcov support. # Use "gcov -p -o build/temp.*/src build/temp.*/src/*.gcda" to build the .gcov files USE_GCOV = 0 # List of pure Python modules that will be excluded from the binary packages. # The list consists of (package, module_name) tuples from distutils.command.build_py import build_py EXCLUDE_PY = [ ('Crypto.Hash', 'RIPEMD160'), # Included for your amusement, but the C version is much faster. ] # Functions for finding libraries and files, copied from Python's setup.py. def find_file(filename, std_dirs, paths): """Searches for the directory where a given file is located, and returns a possibly-empty list of additional directories, or None if the file couldn't be found at all. 'filename' is the name of a file, such as readline.h or libcrypto.a. 'std_dirs' is the list of standard system directories; if the file is found in one of them, no additional directives are needed. 'paths' is a list of additional locations to check; if the file is found in one of them, the resulting list will contain the directory. """ # Check the standard locations for dir in std_dirs: f = os.path.join(dir, filename) if os.path.exists(f): return [] # Check the additional directories for dir in paths: f = os.path.join(dir, filename) if os.path.exists(f): return [dir] # Not found anywhere return None def find_library_file(compiler, libname, std_dirs, paths): filename = compiler.library_filename(libname, lib_type='shared') result = find_file(filename, std_dirs, paths) if result is not None: return result filename = compiler.library_filename(libname, lib_type='static') result = find_file(filename, std_dirs, paths) return result def endianness_macro(): s = struct.pack("@I", 0x33221100) if s == "\x00\x11\x22\x33": # little endian return ('PCT_LITTLE_ENDIAN', 1) elif s == "\x33\x22\x11\x00": # big endian return ('PCT_BIG_ENDIAN', 1) raise AssertionError("Machine is neither little-endian nor big-endian") class PCTBuildExt (build_ext): def build_extensions(self): # Detect which modules should be compiled self.detect_modules() # Tweak compiler options if self.compiler.compiler_type in ('unix', 'cygwin', 'mingw32'): # Tell GCC to compile using the C99 standard. self.__add_compiler_option("-std=c99") # Make assert() statements always work self.__remove_compiler_option("-DNDEBUG") # Choose our own optimization options for opt in ["-O", "-O0", "-O1", "-O2", "-O3", "-Os"]: self.__remove_compiler_option(opt) if self.debug: # Basic optimization is still needed when debugging to compile # the libtomcrypt code. self.__add_compiler_option("-O") else: # Speed up execution by tweaking compiler options. This # especially helps the DES modules. self.__add_compiler_option("-O3") self.__add_compiler_option("-fomit-frame-pointer") # Don't include debug symbols unless debugging self.__remove_compiler_option("-g") # Don't include profiling information (incompatible with -fomit-frame-pointer) self.__remove_compiler_option("-pg") if USE_GCOV: self.__add_compiler_option("-fprofile-arcs") self.__add_compiler_option("-ftest-coverage") self.compiler.libraries += ['gcov'] # Call the superclass's build_extensions method build_ext.build_extensions(self) def detect_modules (self): # Add special include directory for MSVC (because MSVC is special) if self.compiler.compiler_type == 'msvc': self.compiler.include_dirs.insert(0, "src/inc-msvc/") # Detect libgmp and don't build _fastmath if it is missing. lib_dirs = self.compiler.library_dirs + ['/lib', '/usr/lib'] if not (self.compiler.find_library_file(lib_dirs, 'gmp')): print >>sys.stderr, "warning: GMP library not found; Not building Crypto.PublicKey._fastmath." self.__remove_extensions(["Crypto.PublicKey._fastmath"]) def __remove_extensions(self, names): """Remove the specified extension from the list of extensions to build""" i = 0 while i < len(self.extensions): if self.extensions[i].name in names: del self.extensions[i] continue i += 1 def __remove_compiler_option(self, option): """Remove the specified compiler option. Return true if the option was found. Return false otherwise. """ found = 0 for attrname in ('compiler', 'compiler_so'): compiler = getattr(self.compiler, attrname, None) if compiler is not None: while option in compiler: compiler.remove(option) found += 1 return found def __add_compiler_option(self, option): for attrname in ('compiler', 'compiler_so'): compiler = getattr(self.compiler, attrname, None) if compiler is not None: compiler.append(option) class PCTBuildPy(build_py): def find_package_modules(self, package, package_dir, *args, **kwargs): modules = build_py.find_package_modules(self, package, package_dir, *args, **kwargs) # Exclude certain modules retval = [] for item in modules: pkg, module = item[:2] if (pkg, module) in EXCLUDE_PY: continue retval.append(item) return retval class TestCommand(Command): description = "Run self-test" user_options = [ ('skip-slow-tests', None, 'Skip slow tests') ] def initialize_options(self): self.build_dir = None self.skip_slow_tests = None def finalize_options(self): self.set_undefined_options('install', ('build_lib', 'build_dir')) self.config = {'slow_tests': not self.skip_slow_tests} def run(self): # Run SelfTest self.announce("running self-tests") old_path = sys.path[:] try: sys.path.insert(0, self.build_dir) from Crypto import SelfTest SelfTest.run(verbosity=self.verbose, stream=sys.stdout, config=self.config) finally: # Restore sys.path sys.path[:] = old_path # Run slower self-tests self.announce("running extended self-tests") kw = {'name':"pycrypto", 'version':"2.3", # See also: lib/Crypto/__init__.py 'description':"Cryptographic modules for Python.", 'author':"Dwayne C. Litzenberger", 'author_email':"[email protected]", 'url':"http://www.pycrypto.org/", 'cmdclass' : {'build_ext':PCTBuildExt, 'build_py': PCTBuildPy, 'test': TestCommand }, 'packages' : ["Crypto", "Crypto.Hash", "Crypto.Cipher", "Crypto.Util", "Crypto.Random", "Crypto.Random.Fortuna", "Crypto.Random.OSRNG", "Crypto.SelfTest", "Crypto.SelfTest.Cipher", "Crypto.SelfTest.Hash", "Crypto.SelfTest.Protocol", "Crypto.SelfTest.PublicKey", "Crypto.SelfTest.Random", "Crypto.SelfTest.Random.Fortuna", "Crypto.SelfTest.Random.OSRNG", "Crypto.SelfTest.Util", "Crypto.Protocol", "Crypto.PublicKey"], - 'package_dir' : { "Crypto": os.path.join(os.path.dirname(__file__), "lib/Crypto") }, + 'package_dir' : { "Crypto": "lib/Crypto" }, 'ext_modules': plat_ext + [ # _fastmath (uses GNU mp library) Extension("Crypto.PublicKey._fastmath", include_dirs=['src/'], libraries=['gmp'], sources=["src/_fastmath.c"]), # Hash functions Extension("Crypto.Hash.MD2", include_dirs=['src/'], sources=["src/MD2.c"]), Extension("Crypto.Hash.MD4", include_dirs=['src/'], sources=["src/MD4.c"]), Extension("Crypto.Hash.SHA256", include_dirs=['src/'], sources=["src/SHA256.c"]), Extension("Crypto.Hash.RIPEMD160", include_dirs=['src/'], sources=["src/RIPEMD160.c"], define_macros=[endianness_macro()]), # Block encryption algorithms Extension("Crypto.Cipher.AES", include_dirs=['src/'], sources=["src/AES.c"]), Extension("Crypto.Cipher.ARC2", include_dirs=['src/'], sources=["src/ARC2.c"]), Extension("Crypto.Cipher.Blowfish", include_dirs=['src/'], sources=["src/Blowfish.c"]), Extension("Crypto.Cipher.CAST", include_dirs=['src/'], sources=["src/CAST.c"]), Extension("Crypto.Cipher.DES", include_dirs=['src/', 'src/libtom/'], sources=["src/DES.c"]), Extension("Crypto.Cipher.DES3", include_dirs=['src/', 'src/libtom/'], sources=["src/DES3.c"]), # Stream ciphers Extension("Crypto.Cipher.ARC4", include_dirs=['src/'], sources=["src/ARC4.c"]), Extension("Crypto.Cipher.XOR", include_dirs=['src/'], sources=["src/XOR.c"]), # Utility modules Extension("Crypto.Util.strxor", include_dirs=['src/'], sources=['src/strxor.c']), # Counter modules Extension("Crypto.Util._counter", include_dirs=['src/'], sources=['src/_counter.c']), ] } # If we're running Python 2.3, add extra information if hasattr(core, 'setup_keywords'): if 'classifiers' in core.setup_keywords: kw['classifiers'] = [ 'Development Status :: 4 - Beta', 'License :: Public Domain', 'Intended Audience :: Developers', 'Operating System :: Unix', 'Operating System :: Microsoft :: Windows', 'Operating System :: MacOS :: MacOS X', 'Topic :: Security :: Cryptography', ] if 'download_url' in core.setup_keywords: kw['download_url'] = ('http://www.pycrypto.org/files/' '%s-%s.tar.gz' % (kw['name'], kw['version']) ) core.setup(**kw)
pmarin/ical2pcal
862912973dc5404e3f98e7f8b546eca43d56e14b
fix handling of events without end time.
diff --git a/README b/README index 95c7966..ec0a30b 100644 --- a/README +++ b/README @@ -1,28 +1,28 @@ -ical2pcal v0.0.6 - Convert iCalendar (.ics) data files to pcal data files +ical2pcal v0.0.7 - Convert iCalendar (.ics) data files to pcal data files Usage: ical2pcal [-E] [-o <file>] [-h] file -E Use European date format (dd/mm/yyyy) -o <file> Write the output to file instead of to stdout -h Display this help The iCalendar format (.ics file extension) is a standard (RFC 2445) for calendar data exchange. Programs that support the iCalendar format are: Google Calendar, Apple iCal, Evolution, Orange, etc. The iCalendar format have many objects like events, to-do lists, alarms, journal entries etc. ical2pcal only use the events in the file showing in the pcal file the summary and the time of the event, the rest information of the event like description or location are commented in the pcal file (because usually this information does not fit in the day box). Currently automatic detection and conversion to local time of time values in UTC is implemented. All other time values are assumed as local times. ical2pcal does not support complex repeating events, like every first sunday in month. Only simple recurrence are allowed like: -every n-th [day|week|month|year] from <DATE> until <DATE> except <DATE>,... +every n-th [day|week|month|year] from <DATE> [until <DATE> | count] except <DATE>,... diff --git a/ical2pcal.sh b/ical2pcal.sh index 5d4442c..f6ecb28 100755 --- a/ical2pcal.sh +++ b/ical2pcal.sh @@ -1,813 +1,838 @@ #!/bin/bash # Copyright (c) 2010 Jörg Kühne <jk-ical2pcal at gmx dot de> # Copyright (c) 2008 Francisco José Marín Pérez <pacogeek at gmail dot com> # All rights reserved. (The Mit License) #Permission is hereby granted, free of charge, to any person obtaining a copy #of this software and associated documentation files (the "Software"), to deal #in the Software without restriction, including without limitation the rights #to use, copy, modify, merge, publish, distribute, sublicense, and/or sell #copies of the Software, and to permit persons to whom the Software is #furnished to do so, subject to the following conditions: # #The above copyright notice and this permission notice shall be included in #all copies or substantial portions of the Software. # #THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN #THE SOFTWARE. # Changes from Jörg Kühne + +#v0.0.7 +# - fix handling of events without end time + #v0.0.6 # - correct handling of repeating events with count condition # - better display of events that have equal start and end time #v0.0.5 # - support of changed single events in a series of repeating events #v0.0.4 # - support of excluded dates in a simple series of repeating events #v0.0.3 # - support of simple repeating events like: # every n-th [day|week|month|year] from <DATE> until <DATE> # but not like: # every first sunday in month # v0.0.2: # - auto conversion from UTC times to local times # - support of multiple day events # - support of begin/end times # ---------------------------------------------------------------------- # Configuration # if the gnu date command is not in default path, please specify the command # with full path GNU_DATE_COMMAND="" # ---------------------------------------------------------------------- # Code starts here help() { # Show the help cat << EOF -ical2pcal v0.0.6 - Convert iCalendar (.ics) data files to pcal data files +ical2pcal v0.0.7 - Convert iCalendar (.ics) data files to pcal data files Usage: ical2pcal [-E] [-o <file>] [-h] file -E Use European date format (dd/mm/yyyy) -o <file> Write the output to file instead of to stdout -h Display this help The iCalendar format (.ics file extension) is a standard (RFC 2445) for calendar data exchange. Programs that support the iCalendar format are: Google Calendar, Apple iCal, Evolution, Orange, etc. The iCalendar format have many objects like events, to-do lists, alarms, journal entries etc. ical2pcal only use the events in the file showing in the pcal file the summary and the time of the event, the rest information of the event like description or location are commented in the pcal file (because usually this information does not fit in the day box). Currently automatic detection and conversion to local time of time values in UTC is implemented. All other time values are assumed as local times. ical2pcal does not support complex repeating events, like every first sunday in month. Only simple recurrence are allowed like: every n-th [day|week|month|year] from <DATE> until <DATE> except <DATE>,... EOF } european_format=0 output="/dev/stdout" while getopts Eho: arg do case "$arg" in E) european_format=1;; o) output="$OPTARG";; h) help exit 0;; ?) help exit 1;; esac done shift $(( $OPTIND - 1)) if [ $# -lt 1 ] then help exit 0 fi if [ -z "$GNU_DATE_COMMAND" ]; then GNU_DATE_COMMAND=date fi # check date command for gnu version TEST_DATE=`"$GNU_DATE_COMMAND" -d 20100101 +%Y%m%d` if [ "x$TEST_DATE" != "x20100101" ]; then echo "Gnu version of date command not found. Please set correct config value." echo " " exit 1 fi { cat "$*" | awk ' BEGIN{ RS = "" } { gsub(/\r/,"",$0) # Remove the Windows style line ending gsub(/\f/,"",$0) # Remove the Windows style line ending gsub(/\n /,"", $0) # Unfold the lines gsub(/\\\\/,"\\",$0) gsub(/\\,/,",",$0) gsub(/\\;/,";",$0) gsub(/\\n/," ",$0) gsub(/\\N/," ",$0) print }' | awk -v date_command="$GNU_DATE_COMMAND" ' BEGIN { FS = ":" #field separator print "BEGIN:RECURRENCES" } $0 ~ /^BEGIN:VEVENT/ { recurrence = 0 all_day_event = 0 summary = "" utc_time = 0 recurrence_date = "" uid = "" while ($0 !~ /^END:VEVENT/) { if ($1 ~ /^RECURRENCE-ID/) { year = substr($2, 1, 4) month = substr($2, 5, 2) day = substr($2, 7, 2) if ($1 ~ /VALUE=DATE/) { all_day_event = 1 } else { hour = substr($2, 10, 2) minute = substr($2, 12, 2) UTCTAG = substr($2, 16, 1) if (UTCTAG == "Z") { utc_time = 1 } } recurrence = 1 } if ($1 ~ /^SUMMARY/) { sub(/SUMMARY/,"",$0) sub(/^:/,"",$0) summary = $0 } if ($1 ~ /^UID/) { sub(/UID/,"",$0) sub(/^:/,"",$0) uid = $0 } getline } if ( recurrence ) { if (! all_day_event && utc_time) { # Convert Date/Time from UTC to local time tmp_date = year month day "UTC" hour minute command = date_command " -d" tmp_date " +%Y%m%d%H%M" command | getline captureresult close(command) year = substr(captureresult, 1, 4) month = substr(captureresult, 5, 2) day = substr(captureresult, 7, 2) hour = substr(captureresult, 9, 2) minute = substr(captureresult, 11, 2) } if (all_day_event) { recurrence_date = year month day } else { recurrence_date = year month day hour minute } print "RECURRENCE_ENTRY:" uid ":" recurrence_date ":" summary } } END { print "END:RECURRENCES" }' cat "$*" | awk ' BEGIN{ RS = "" } { gsub(/\r/,"",$0) # Remove the Windows style line ending gsub(/\f/,"",$0) # Remove the Windows style line ending gsub(/\n /,"", $0) # Unfold the lines gsub(/\\\\/,"\\",$0) gsub(/\\,/,",",$0) gsub(/\\;/,";",$0) gsub(/\\n/," ",$0) gsub(/\\N/," ",$0) print }' } | awk -v european_format=$european_format -v date_command="$GNU_DATE_COMMAND" ' BEGIN { FS = ":" #field separator print "# Creator: ical2pcal" print "# include this file into your .calendar file with: include \"a_file.pcal\"\n" } $0 ~ /^BEGIN:RECURRENCES/ { recurrence_index = 0 print "#Replaced events in event series:" while ($0 !~ /^END:RECURRENCES/) { if ($1 ~ /^RECURRENCE_ENTRY/) { recurrences[recurrence_index] = $2 ":" $3 recurrence_index = recurrence_index + 1 print "#" $1 ":" $3 ":" substr($0, index($0,$4)) } getline } print "" } $0 ~ /^BEGIN:VEVENT/ { all_day_event = 0 + no_start_date = 1 + no_end_date = 1 utc_time = 0 summary = "" location = "" description = "" uid = "" recurence_reference_date = "" repeat = 1 repeating_event = 0 frequency ="" interval = 1 count = 0 repeating_end_date = "" date_incr_str = "week" debug_repeat_str = "" # empty exdates array for (i in exdates) { delete exdates[i] } exdates_index = 0 while ($0 !~ /^END:VEVENT/) { if ($1 ~ /^DTSTART/) { year_start = substr($2, 1, 4) month_start = substr($2, 5, 2) day_start = substr($2, 7, 2) if ($1 ~ /VALUE=DATE/) { all_day_event = 1 } else { hour_start = substr($2, 10, 2) minute_start = substr($2, 12, 2) UTCTAG = substr($2, 16, 1) if (UTCTAG == "Z") { utc_time = 1 } } + + no_start_date = 0 } if ($1 ~ /^DTEND/) { year_end = substr($2, 1, 4) month_end = substr($2, 5, 2) day_end = substr($2, 7, 2) if ($1 ~ /VALUE=DATE/) { all_day_event = 1 } else { hour_end = substr($2, 10, 2) minute_end = substr($2, 12, 2) } + + no_end_date = 0 } if ($1 ~ /^SUMMARY/) { sub(/SUMMARY/,"",$0) sub(/^:/,"",$0) summary = $0 } if ($1 ~ /^LOCATION/) { sub(/LOCATION/,"",$0) sub(/^:/,"",$0) location = $0 } if ($1 ~ /^DESCRIPTION/) { sub(/DESCRIPTION/,"",$0) sub(/^:/,"",$0) description = $0 } if ($1 ~ /^UID/) { sub(/UID/,"",$0) sub(/^:/,"",$0) uid = $0 } if ($1 ~ /^RRULE/) { debug_repeat_str = $0 sub(/RRULE/,"",$0) sub(/^:/,"",$0) split($0,part,";") for (i in part) { numparts = split(part[i],subpart,"=") if (numparts > 1) { if (subpart[1] ~ /FREQ/) { frequency = subpart[2] } if (subpart[1] ~ /INTERVAL/) { interval = subpart[2] } if (subpart[1] ~ /COUNT/) { count = subpart[2] } if (subpart[1] ~ /UNTIL/) { until_year = substr(subpart[2], 1, 4) until_month = substr(subpart[2], 5, 2) until_day = substr(subpart[2], 7, 2) until_hour = substr(subpart[2], 10, 2) until_minute = substr(subpart[2], 12, 2) until_UTCTAG = substr(subpart[2], 16, 1) if (until_UTCTAG == "Z") { tmp_repeating_end_date = until_year until_month until_day "UTC" until_hour until_minute command = date_command " -d" tmp_repeating_end_date " +%Y%m%d%H%M" command | getline captureresult close(command) until_year = substr(captureresult, 1, 4) until_month = substr(captureresult, 5, 2) until_day = substr(captureresult, 7, 2) } repeating_end_date = until_year until_month until_day } } } if (frequency == "DAILY") { repeating_event = 1 date_incr_str = "day" if (count == 0) { count = 750 } } if (frequency == "WEEKLY") { repeating_event = 1 date_incr_str = "week" if (count == 0) { count = 260 } } if (frequency == "MONTHLY") { repeating_event = 1 date_incr_str = "month" if (count == 0) { count = 60 } } if (frequency == "YEARLY") { repeating_event = 1 date_incr_str = "year" if (count == 0) { count = 5 } } } if ($1 ~ /^EXDATE/) { split($2,part,",") for (i in part) { year_exdate = substr(part[i], 1, 4) month_exdate = substr(part[i], 5, 2) day_exdate = substr(part[i], 7, 2) hour_exdate = substr(part[i], 10, 2) minute_exdate = substr(part[i], 12, 2) UTCTAG = substr(part[i], 16, 1) if (UTCTAG == "Z") { tmp_exdate = year_exdate month_exdate day_exdate "UTC" hour_exdate minute_exdate command = date_command " -d" tmp_exdate " +%Y%m%d%H%M" command | getline captureresult close(command) year_exdate = substr(captureresult, 1, 4) month_exdate = substr(captureresult, 5, 2) day_exdate = substr(captureresult, 7, 2) } tmp_exdate = year_exdate month_exdate day_exdate exdates[exdates_index] = tmp_exdate exdates_index = exdates_index + 1 } } getline } if (count == 0) { count = 1 } + + if (no_start_date == 1) + { + next + } + + if (no_end_date == 1) + { + # event only with start time + year_end = year_start + month_end = month_start + day_end = day_start + hour_end = hour_start + minute_end = minute_start + } if (! all_day_event && utc_time) { # Convert Date/Time from UTC to local time tmp_date_start = year_start month_start day_start "UTC" hour_start minute_start command = date_command " -d" tmp_date_start " +%Y%m%d%H%M" command | getline captureresult close(command) year_start = substr(captureresult, 1, 4) month_start = substr(captureresult, 5, 2) day_start = substr(captureresult, 7, 2) hour_start = substr(captureresult, 9, 2) minute_start = substr(captureresult, 11, 2) tmp_date_end = year_end month_end day_end "UTC" hour_end minute_end command = date_command " -d " tmp_date_end " +%Y%m%d%H%M" command | getline captureresult close(command) year_end = substr(captureresult, 1, 4) month_end = substr(captureresult, 5, 2) day_end = substr(captureresult, 7, 2) hour_end = substr(captureresult, 9, 2) minute_end = substr(captureresult, 11, 2) } date_start = year_start month_start day_start date_end = year_end month_end day_end # avoid new day entry if end time is 12AM if (! all_day_event && hour_end == "00" && minute_end == "00") { command = date_command " -d \"" date_end " -1 day\"" " +%Y%m%d" command | getline captureresult close(command) year_end = substr(captureresult, 1, 4) month_end = substr(captureresult, 5, 2) day_end = substr(captureresult, 7, 2) date_end = year_end month_end day_end } if (summary == "") { next } print "#### BEGIN EVENT -----------------------------------" if (debug_repeat_str != "") { print "#"debug_repeat_str } if (exdates_index > 0) { for (i in exdates) { print "#EXDATE:" exdates[i] } } num_repetitions = 0 while (repeat == 1 && num_repetitions < count) { date_start_bak = date_start date_end_bak = date_end # check for excluded dates exdate = 0 for (i in exdates) { if (exdates[i] == date_start) { exdate = 1 break } } if (exdate == 0 && repeating_event) { if (! all_day_event) { recurence_reference_date = year_start month_start day_start hour_start minute_start } else { recurence_reference_date = year_start month_start day_start } for (i in recurrences) { if (recurrences[i] == uid ":" recurence_reference_date) { exdate = 1 print "#skip event due to modified series element: " uid ":" recurence_reference_date break } } } if (exdate == 0) { if (all_day_event) { # Hack to save calculation time - not works for last day of month if (date_start + 1 == date_end) { if (european_format) { print day_start "/" month_start "/" year_start " " summary } else { print month_start "/" day_start "/" year_start " " summary } } else { if (date_start < date_end) { date_next = date_start while (date_next < date_end) { tmp_year_next = substr(date_next, 1, 4) tmp_month_next = substr(date_next, 5, 2) tmp_day_next = substr(date_next, 7, 2) if (european_format) { print tmp_day_next "/" tmp_month_next "/" tmp_year_next " " summary } else { print tmp_month_next "/" tmp_day_next "/" tmp_year_next " " summary } command = date_command " -d \"" date_next " 1 day\"" " +%Y%m%d" command | getline captureresult close(command) date_next = captureresult } } else { # Should not happen if (european_format) { print day_start "/" month_start "/" year_start " " summary } else { print month_start "/" day_start "/" year_start " " summary } } } } else { if (date_start < date_end) { # first date with start time if (european_format) { print day_start "/" month_start "/" year_start " " hour_start ":" minute_start " -> " summary } else { command = date_command " -d " hour_start ":" minute_start " +%I:%M%P" command | getline time_start close(command) print month_start "/" day_start "/" year_start " " time_start " -> " summary } #middle days without time command = date_command " -d \"" date_start " 1 day\"" " +%Y%m%d" command | getline captureresult close(command) date_next = captureresult while (date_next < date_end) { tmp_year_next = substr(date_next, 1, 4) tmp_month_next = substr(date_next, 5, 2) tmp_day_next = substr(date_next, 7, 2) if (european_format) { print tmp_day_next "/" tmp_month_next "/" tmp_year_next " " summary } else { print tmp_month_next "/" tmp_day_next "/" tmp_year_next " " summary } command = date_command " -d \"" date_next " 1 day\"" " +%Y%m%d" command | getline captureresult close(command) date_next = captureresult } # last day with end time if (european_format) { print day_end "/" month_end "/" year_end " -> " hour_end ":" minute_end " " summary } else { command = date_command " -d " hour_end ":" minute_end " +%I:%M%P" command | getline time_end close(command) print month_end "/" day_end "/" year_end " -> " time_end " " summary } } else { if (european_format) { if (hour_start == hour_end && minute_start == minute_end) { print day_start "/" month_start "/" year_start " " hour_start ":" minute_start " " summary } else { print day_start "/" month_start "/" year_start " " hour_start ":" minute_start "-" hour_end ":" minute_end " " summary } } else { command = date_command " -d " hour_start ":" minute_start " +%I:%M%P" command | getline time_start close(command) command = date_command " -d " hour_end ":" minute_end " +%I:%M%P" command | getline time_end close(command) if (time_start == time_end) { print month_start "/" day_start "/" year_start " " time_start " " summary } else { print month_start "/" day_start "/" year_start " " time_start "-" time_end " " summary } } } } if (location != "") { if (european_format) { print "#"day_start "/" month_start "/" year_start" location: "location } else { print "#"month_start "/" day_start "/" year_start" location: "location } } if (description != "") { if (european_format) { print "#"day_start "/" month_start "/" year_start" description: "description } else { print "#"month_start "/" day_start "/" year_start" description: "description } } } # calculate repeating events if (repeating_event == 0) { repeat = 0 } else { num_repetitions = num_repetitions + 1 command = date_command " -d \"" date_start_bak " " interval " " date_incr_str "\" " "+%Y%m%d" command | getline captureresult close(command) date_start = captureresult year_start = substr(captureresult, 1, 4) month_start = substr(captureresult, 5, 2) day_start = substr(captureresult, 7, 2) command = date_command " -d \"" date_end_bak " " interval " " date_incr_str "\" " "+%Y%m%d" command | getline captureresult close(command) date_end = captureresult year_end = substr(captureresult, 1, 4) month_end = substr(captureresult, 5, 2) day_end = substr(captureresult, 7, 2) if (repeating_end_date != "" && date_start > repeating_end_date) { repeat = 0 } } } print "#### END EVENT -------------------------------------\n" } END { }' > "$output"
pmarin/ical2pcal
aa0f571c68d46b9132bdb497b50d146cd75fa6ac
Fix the version in readme
diff --git a/README b/README index 8328992..95c7966 100644 --- a/README +++ b/README @@ -1,28 +1,28 @@ -ical2pcal v0.0.5 - Convert iCalendar (.ics) data files to pcal data files +ical2pcal v0.0.6 - Convert iCalendar (.ics) data files to pcal data files Usage: ical2pcal [-E] [-o <file>] [-h] file -E Use European date format (dd/mm/yyyy) -o <file> Write the output to file instead of to stdout -h Display this help The iCalendar format (.ics file extension) is a standard (RFC 2445) for calendar data exchange. Programs that support the iCalendar format are: Google Calendar, Apple iCal, Evolution, Orange, etc. The iCalendar format have many objects like events, to-do lists, alarms, journal entries etc. ical2pcal only use the events in the file showing in the pcal file the summary and the time of the event, the rest information of the event like description or location are commented in the pcal file (because usually this information does not fit in the day box). Currently automatic detection and conversion to local time of time values in UTC is implemented. All other time values are assumed as local times. ical2pcal does not support complex repeating events, like every first sunday in month. Only simple recurrence are allowed like: every n-th [day|week|month|year] from <DATE> until <DATE> except <DATE>,...
pmarin/ical2pcal
8e79ab654d888bc95a2fbbc8379a7be2f0036685
v0.0.6
diff --git a/ical2pcal.sh b/ical2pcal.sh index d1cc70c..5d4442c 100755 --- a/ical2pcal.sh +++ b/ical2pcal.sh @@ -1,772 +1,813 @@ #!/bin/bash # Copyright (c) 2010 Jörg Kühne <jk-ical2pcal at gmx dot de> # Copyright (c) 2008 Francisco José Marín Pérez <pacogeek at gmail dot com> # All rights reserved. (The Mit License) #Permission is hereby granted, free of charge, to any person obtaining a copy #of this software and associated documentation files (the "Software"), to deal #in the Software without restriction, including without limitation the rights #to use, copy, modify, merge, publish, distribute, sublicense, and/or sell #copies of the Software, and to permit persons to whom the Software is #furnished to do so, subject to the following conditions: # #The above copyright notice and this permission notice shall be included in #all copies or substantial portions of the Software. # #THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN #THE SOFTWARE. # Changes from Jörg Kühne +#v0.0.6 +# - correct handling of repeating events with count condition +# - better display of events that have equal start and end time + #v0.0.5 # - support of changed single events in a series of repeating events #v0.0.4 # - support of excluded dates in a simple series of repeating events #v0.0.3 # - support of simple repeating events like: # every n-th [day|week|month|year] from <DATE> until <DATE> # but not like: # every first sunday in month # v0.0.2: # - auto conversion from UTC times to local times # - support of multiple day events # - support of begin/end times # ---------------------------------------------------------------------- # Configuration # if the gnu date command is not in default path, please specify the command # with full path GNU_DATE_COMMAND="" # ---------------------------------------------------------------------- # Code starts here help() { # Show the help cat << EOF -ical2pcal v0.0.5 - Convert iCalendar (.ics) data files to pcal data files +ical2pcal v0.0.6 - Convert iCalendar (.ics) data files to pcal data files Usage: ical2pcal [-E] [-o <file>] [-h] file -E Use European date format (dd/mm/yyyy) -o <file> Write the output to file instead of to stdout -h Display this help The iCalendar format (.ics file extension) is a standard (RFC 2445) for calendar data exchange. Programs that support the iCalendar format are: Google Calendar, Apple iCal, Evolution, Orange, etc. The iCalendar format have many objects like events, to-do lists, alarms, journal entries etc. ical2pcal only use the events in the file showing in the pcal file the summary and the time of the event, the rest information of the event like description or location are commented in the pcal file (because usually this information does not fit in the day box). Currently automatic detection and conversion to local time of time values in UTC is implemented. All other time values are assumed as local times. ical2pcal does not support complex repeating events, like every first sunday in month. Only simple recurrence are allowed like: every n-th [day|week|month|year] from <DATE> until <DATE> except <DATE>,... EOF } european_format=0 output="/dev/stdout" while getopts Eho: arg do case "$arg" in E) european_format=1;; o) output="$OPTARG";; h) help exit 0;; ?) help exit 1;; esac done shift $(( $OPTIND - 1)) if [ $# -lt 1 ] then help exit 0 fi if [ -z "$GNU_DATE_COMMAND" ]; then GNU_DATE_COMMAND=date fi # check date command for gnu version TEST_DATE=`"$GNU_DATE_COMMAND" -d 20100101 +%Y%m%d` if [ "x$TEST_DATE" != "x20100101" ]; then echo "Gnu version of date command not found. Please set correct config value." echo " " exit 1 fi { cat "$*" | awk ' BEGIN{ RS = "" } - + { gsub(/\r/,"",$0) # Remove the Windows style line ending gsub(/\f/,"",$0) # Remove the Windows style line ending gsub(/\n /,"", $0) # Unfold the lines gsub(/\\\\/,"\\",$0) gsub(/\\,/,",",$0) gsub(/\\;/,";",$0) gsub(/\\n/," ",$0) gsub(/\\N/," ",$0) print - }' | + }' | awk -v date_command="$GNU_DATE_COMMAND" ' BEGIN { FS = ":" #field separator print "BEGIN:RECURRENCES" } - + $0 ~ /^BEGIN:VEVENT/ { recurrence = 0 all_day_event = 0 summary = "" utc_time = 0 recurrence_date = "" uid = "" - + while ($0 !~ /^END:VEVENT/) { if ($1 ~ /^RECURRENCE-ID/) { year = substr($2, 1, 4) month = substr($2, 5, 2) day = substr($2, 7, 2) - + if ($1 ~ /VALUE=DATE/) { all_day_event = 1 } else { hour = substr($2, 10, 2) minute = substr($2, 12, 2) UTCTAG = substr($2, 16, 1) - + if (UTCTAG == "Z") { utc_time = 1 } } - + recurrence = 1 } - + if ($1 ~ /^SUMMARY/) { sub(/SUMMARY/,"",$0) sub(/^:/,"",$0) summary = $0 } - + if ($1 ~ /^UID/) { sub(/UID/,"",$0) sub(/^:/,"",$0) uid = $0 } - + getline } - + if ( recurrence ) { if (! all_day_event && utc_time) { # Convert Date/Time from UTC to local time - + tmp_date = year month day "UTC" hour minute command = date_command " -d" tmp_date " +%Y%m%d%H%M" command | getline captureresult close(command) year = substr(captureresult, 1, 4) month = substr(captureresult, 5, 2) day = substr(captureresult, 7, 2) hour = substr(captureresult, 9, 2) minute = substr(captureresult, 11, 2) } - + if (all_day_event) { recurrence_date = year month day } else { recurrence_date = year month day hour minute } - + print "RECURRENCE_ENTRY:" uid ":" recurrence_date ":" summary } } - + END { print "END:RECURRENCES" }' cat "$*" | awk ' BEGIN{ RS = "" } - + { gsub(/\r/,"",$0) # Remove the Windows style line ending gsub(/\f/,"",$0) # Remove the Windows style line ending gsub(/\n /,"", $0) # Unfold the lines gsub(/\\\\/,"\\",$0) gsub(/\\,/,",",$0) gsub(/\\;/,";",$0) gsub(/\\n/," ",$0) gsub(/\\N/," ",$0) print }' - + } | awk -v european_format=$european_format -v date_command="$GNU_DATE_COMMAND" ' BEGIN { FS = ":" #field separator print "# Creator: ical2pcal" print "# include this file into your .calendar file with: include \"a_file.pcal\"\n" } $0 ~ /^BEGIN:RECURRENCES/ { recurrence_index = 0 print "#Replaced events in event series:" while ($0 !~ /^END:RECURRENCES/) { if ($1 ~ /^RECURRENCE_ENTRY/) { recurrences[recurrence_index] = $2 ":" $3 recurrence_index = recurrence_index + 1 print "#" $1 ":" $3 ":" substr($0, index($0,$4)) } getline } print "" } $0 ~ /^BEGIN:VEVENT/ { all_day_event = 0 utc_time = 0 summary = "" location = "" description = "" uid = "" recurence_reference_date = "" repeat = 1 repeating_event = 0 frequency ="" interval = 1 - max_num_repetitions = 750 + count = 0 repeating_end_date = "" date_incr_str = "week" debug_repeat_str = "" # empty exdates array for (i in exdates) { delete exdates[i] } exdates_index = 0 while ($0 !~ /^END:VEVENT/) { if ($1 ~ /^DTSTART/) { year_start = substr($2, 1, 4) month_start = substr($2, 5, 2) day_start = substr($2, 7, 2) if ($1 ~ /VALUE=DATE/) { all_day_event = 1 } else { hour_start = substr($2, 10, 2) minute_start = substr($2, 12, 2) UTCTAG = substr($2, 16, 1) if (UTCTAG == "Z") { utc_time = 1 } } } if ($1 ~ /^DTEND/) { year_end = substr($2, 1, 4) month_end = substr($2, 5, 2) day_end = substr($2, 7, 2) if ($1 ~ /VALUE=DATE/) { all_day_event = 1 } else { hour_end = substr($2, 10, 2) minute_end = substr($2, 12, 2) } } if ($1 ~ /^SUMMARY/) { sub(/SUMMARY/,"",$0) sub(/^:/,"",$0) summary = $0 } if ($1 ~ /^LOCATION/) { sub(/LOCATION/,"",$0) sub(/^:/,"",$0) location = $0 } if ($1 ~ /^DESCRIPTION/) { sub(/DESCRIPTION/,"",$0) sub(/^:/,"",$0) description = $0 } if ($1 ~ /^UID/) { sub(/UID/,"",$0) sub(/^:/,"",$0) uid = $0 } if ($1 ~ /^RRULE/) { debug_repeat_str = $0 sub(/RRULE/,"",$0) sub(/^:/,"",$0) split($0,part,";") for (i in part) { numparts = split(part[i],subpart,"=") if (numparts > 1) { if (subpart[1] ~ /FREQ/) { frequency = subpart[2] } if (subpart[1] ~ /INTERVAL/) { interval = subpart[2] } + if (subpart[1] ~ /COUNT/) + { + count = subpart[2] + } + if (subpart[1] ~ /UNTIL/) { until_year = substr(subpart[2], 1, 4) until_month = substr(subpart[2], 5, 2) until_day = substr(subpart[2], 7, 2) until_hour = substr(subpart[2], 10, 2) until_minute = substr(subpart[2], 12, 2) until_UTCTAG = substr(subpart[2], 16, 1) if (until_UTCTAG == "Z") { tmp_repeating_end_date = until_year until_month until_day "UTC" until_hour until_minute command = date_command " -d" tmp_repeating_end_date " +%Y%m%d%H%M" command | getline captureresult close(command) until_year = substr(captureresult, 1, 4) until_month = substr(captureresult, 5, 2) until_day = substr(captureresult, 7, 2) } repeating_end_date = until_year until_month until_day } } } if (frequency == "DAILY") { repeating_event = 1 - max_num_repetitions = 750 date_incr_str = "day" + if (count == 0) + { + count = 750 + } } if (frequency == "WEEKLY") { repeating_event = 1 - max_num_repetitions = 260 date_incr_str = "week" + if (count == 0) + { + count = 260 + } } if (frequency == "MONTHLY") { repeating_event = 1 - max_num_repetitions = 60 date_incr_str = "month" + if (count == 0) + { + count = 60 + } } if (frequency == "YEARLY") { repeating_event = 1 - max_num_repetitions = 5 date_incr_str = "year" + if (count == 0) + { + count = 5 + } } } if ($1 ~ /^EXDATE/) { split($2,part,",") for (i in part) { year_exdate = substr(part[i], 1, 4) month_exdate = substr(part[i], 5, 2) day_exdate = substr(part[i], 7, 2) hour_exdate = substr(part[i], 10, 2) minute_exdate = substr(part[i], 12, 2) UTCTAG = substr(part[i], 16, 1) if (UTCTAG == "Z") { tmp_exdate = year_exdate month_exdate day_exdate "UTC" hour_exdate minute_exdate command = date_command " -d" tmp_exdate " +%Y%m%d%H%M" command | getline captureresult close(command) year_exdate = substr(captureresult, 1, 4) month_exdate = substr(captureresult, 5, 2) day_exdate = substr(captureresult, 7, 2) } tmp_exdate = year_exdate month_exdate day_exdate exdates[exdates_index] = tmp_exdate exdates_index = exdates_index + 1 } } getline } + if (count == 0) + { + count = 1 + } + if (! all_day_event && utc_time) { # Convert Date/Time from UTC to local time tmp_date_start = year_start month_start day_start "UTC" hour_start minute_start command = date_command " -d" tmp_date_start " +%Y%m%d%H%M" command | getline captureresult close(command) year_start = substr(captureresult, 1, 4) month_start = substr(captureresult, 5, 2) day_start = substr(captureresult, 7, 2) hour_start = substr(captureresult, 9, 2) minute_start = substr(captureresult, 11, 2) tmp_date_end = year_end month_end day_end "UTC" hour_end minute_end command = date_command " -d " tmp_date_end " +%Y%m%d%H%M" command | getline captureresult close(command) year_end = substr(captureresult, 1, 4) month_end = substr(captureresult, 5, 2) day_end = substr(captureresult, 7, 2) hour_end = substr(captureresult, 9, 2) minute_end = substr(captureresult, 11, 2) } date_start = year_start month_start day_start date_end = year_end month_end day_end # avoid new day entry if end time is 12AM if (! all_day_event && hour_end == "00" && minute_end == "00") { command = date_command " -d \"" date_end " -1 day\"" " +%Y%m%d" command | getline captureresult close(command) year_end = substr(captureresult, 1, 4) month_end = substr(captureresult, 5, 2) day_end = substr(captureresult, 7, 2) date_end = year_end month_end day_end } if (summary == "") { next } print "#### BEGIN EVENT -----------------------------------" + if (debug_repeat_str != "") { print "#"debug_repeat_str } if (exdates_index > 0) { for (i in exdates) { print "#EXDATE:" exdates[i] } } num_repetitions = 0 - while (repeat == 1 && num_repetitions < max_num_repetitions) + while (repeat == 1 && num_repetitions < count) { date_start_bak = date_start date_end_bak = date_end # check for excluded dates exdate = 0 for (i in exdates) { if (exdates[i] == date_start) { exdate = 1 break } } if (exdate == 0 && repeating_event) { if (! all_day_event) { recurence_reference_date = year_start month_start day_start hour_start minute_start } else { recurence_reference_date = year_start month_start day_start } for (i in recurrences) { if (recurrences[i] == uid ":" recurence_reference_date) { exdate = 1 print "#skip event due to modified series element: " uid ":" recurence_reference_date break } } } if (exdate == 0) { if (all_day_event) { # Hack to save calculation time - not works for last day of month if (date_start + 1 == date_end) { if (european_format) { - print day_start "/" month_start "/" year_start " " summary + print day_start "/" month_start "/" year_start " " summary } else { - print month_start "/" day_start "/" year_start " " summary + print month_start "/" day_start "/" year_start " " summary } } else { if (date_start < date_end) { date_next = date_start while (date_next < date_end) { tmp_year_next = substr(date_next, 1, 4) tmp_month_next = substr(date_next, 5, 2) tmp_day_next = substr(date_next, 7, 2) if (european_format) { - print tmp_day_next "/" tmp_month_next "/" tmp_year_next " " summary + print tmp_day_next "/" tmp_month_next "/" tmp_year_next " " summary } else { - print tmp_month_next "/" tmp_day_next "/" tmp_year_next " " summary + print tmp_month_next "/" tmp_day_next "/" tmp_year_next " " summary } command = date_command " -d \"" date_next " 1 day\"" " +%Y%m%d" command | getline captureresult close(command) date_next = captureresult } } else { # Should not happen if (european_format) { print day_start "/" month_start "/" year_start " " summary } else { print month_start "/" day_start "/" year_start " " summary } } } } else { if (date_start < date_end) { # first date with start time if (european_format) { print day_start "/" month_start "/" year_start " " hour_start ":" minute_start " -> " summary } else { - command = date_command " -d " hour_start ":" minute_start " +%I:%M%p" + command = date_command " -d " hour_start ":" minute_start " +%I:%M%P" command | getline time_start close(command) print month_start "/" day_start "/" year_start " " time_start " -> " summary } #middle days without time command = date_command " -d \"" date_start " 1 day\"" " +%Y%m%d" command | getline captureresult close(command) date_next = captureresult while (date_next < date_end) { tmp_year_next = substr(date_next, 1, 4) tmp_month_next = substr(date_next, 5, 2) tmp_day_next = substr(date_next, 7, 2) if (european_format) { print tmp_day_next "/" tmp_month_next "/" tmp_year_next " " summary } else { print tmp_month_next "/" tmp_day_next "/" tmp_year_next " " summary } command = date_command " -d \"" date_next " 1 day\"" " +%Y%m%d" command | getline captureresult close(command) date_next = captureresult } # last day with end time if (european_format) { print day_end "/" month_end "/" year_end " -> " hour_end ":" minute_end " " summary } else { - command = date_command " -d " hour_end ":" minute_end " +%I:%M%p" + command = date_command " -d " hour_end ":" minute_end " +%I:%M%P" command | getline time_end close(command) print month_end "/" day_end "/" year_end " -> " time_end " " summary } } else { if (european_format) { - print day_start "/" month_start "/" year_start " " hour_start ":" minute_start "-" hour_end ":" minute_end " " summary + if (hour_start == hour_end && minute_start == minute_end) + { + print day_start "/" month_start "/" year_start " " hour_start ":" minute_start " " summary + } + else + { + print day_start "/" month_start "/" year_start " " hour_start ":" minute_start "-" hour_end ":" minute_end " " summary + } } else { - command = date_command " -d " hour_start ":" minute_start " +%I:%M%p" + command = date_command " -d " hour_start ":" minute_start " +%I:%M%P" command | getline time_start close(command) - command = date_command " -d " hour_end ":" minute_end " +%I:%M%p" + command = date_command " -d " hour_end ":" minute_end " +%I:%M%P" command | getline time_end close(command) - print month_start "/" day_start "/" year_start " " time_start "-" time_end " " summary + if (time_start == time_end) + { + print month_start "/" day_start "/" year_start " " time_start " " summary + } + else + { + print month_start "/" day_start "/" year_start " " time_start "-" time_end " " summary + } } } } if (location != "") { if (european_format) { print "#"day_start "/" month_start "/" year_start" location: "location } else { print "#"month_start "/" day_start "/" year_start" location: "location } } if (description != "") { if (european_format) { print "#"day_start "/" month_start "/" year_start" description: "description } else { print "#"month_start "/" day_start "/" year_start" description: "description } } } # calculate repeating events if (repeating_event == 0) { repeat = 0 } else { num_repetitions = num_repetitions + 1 command = date_command " -d \"" date_start_bak " " interval " " date_incr_str "\" " "+%Y%m%d" command | getline captureresult close(command) date_start = captureresult year_start = substr(captureresult, 1, 4) month_start = substr(captureresult, 5, 2) day_start = substr(captureresult, 7, 2) command = date_command " -d \"" date_end_bak " " interval " " date_incr_str "\" " "+%Y%m%d" command | getline captureresult close(command) date_end = captureresult year_end = substr(captureresult, 1, 4) month_end = substr(captureresult, 5, 2) day_end = substr(captureresult, 7, 2) if (repeating_end_date != "" && date_start > repeating_end_date) { repeat = 0 } } } print "#### END EVENT -------------------------------------\n" } END { }' > "$output"
pmarin/ical2pcal
e0daadeae1c1e2d5665b9073b10fb7931973ae9d
Modify an event from a event series.
diff --git a/ical2pcal.sh b/ical2pcal.sh index 7da0c24..d1cc70c 100755 --- a/ical2pcal.sh +++ b/ical2pcal.sh @@ -1,609 +1,772 @@ -#!/bin/bash +#!/bin/bash -# Copyright (c) 2010 Jörg Kühne <jk-ical2pcal at gmx dot de> +# Copyright (c) 2010 Jörg Kühne <jk-ical2pcal at gmx dot de> # Copyright (c) 2008 Francisco José Marín Pérez <pacogeek at gmail dot com> # All rights reserved. (The Mit License) #Permission is hereby granted, free of charge, to any person obtaining a copy #of this software and associated documentation files (the "Software"), to deal #in the Software without restriction, including without limitation the rights #to use, copy, modify, merge, publish, distribute, sublicense, and/or sell #copies of the Software, and to permit persons to whom the Software is #furnished to do so, subject to the following conditions: # #The above copyright notice and this permission notice shall be included in #all copies or substantial portions of the Software. # #THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN #THE SOFTWARE. # Changes from Jörg Kühne +#v0.0.5 +# - support of changed single events in a series of repeating events + #v0.0.4 # - support of excluded dates in a simple series of repeating events #v0.0.3 # - support of simple repeating events like: # every n-th [day|week|month|year] from <DATE> until <DATE> # but not like: # every first sunday in month # v0.0.2: # - auto conversion from UTC times to local times # - support of multiple day events # - support of begin/end times # ---------------------------------------------------------------------- # Configuration # if the gnu date command is not in default path, please specify the command # with full path GNU_DATE_COMMAND="" # ---------------------------------------------------------------------- # Code starts here -if [ -z "$GNU_DATE_COMMAND" ]; then - GNU_DATE_COMMAND=date -fi - -# check date command for gnu version -TEST_DATE=`"$GNU_DATE_COMMAND" -d 20100101 +%Y%m%d` -if [ "x$TEST_DATE" != "x20100101" ]; then - echo "Gnu version of date command not found. Please set correct config value." - echo " " - exit 1 -fi - -help() { # Show the help +help() { # Show the help cat << EOF -ical2pcal v0.0.4 - Convert iCalendar (.ics) data files to pcal data files +ical2pcal v0.0.5 - Convert iCalendar (.ics) data files to pcal data files Usage: ical2pcal [-E] [-o <file>] [-h] file -E Use European date format (dd/mm/yyyy) -o <file> Write the output to file instead of to stdout -h Display this help -The iCalendar format (.ics file extension) is a standard (RFC 2445) for -calendar data exchange. Programs that support the iCalendar format are: Google -Calendar, Apple iCal, Evolution, Orange, etc. +The iCalendar format (.ics file extension) is a standard (RFC 2445) +for calendar data exchange. Programs that support the iCalendar format +are: Google Calendar, Apple iCal, Evolution, Orange, etc. -The iCalendar format have many objects like events, to-do lists, alarms, -journal entries etc. ical2pcal only use the events in the file showing in the -pcal file the summary and the time of the event, the rest information of the -event like description or location are commented in the pcal file (because +The iCalendar format have many objects like events, to-do lists, +alarms, journal entries etc. ical2pcal only use the events +in the file showing in the pcal file the summary and the time of +the event, the rest information of the event like +description or location are commented in the pcal file (because usually this information does not fit in the day box). -Currently automatic detection and conversion to local time of time values in -UTC is implemented. All other time values are assumed as local times. +Currently automatic detection and conversion to local time of time values +in UTC is implemented. All other time values are assumed as local times. -ical2pcal does not support complex repeating events, like every first sunday in -month. Only simple recurrence are allowed like: +ical2pcal does not support complex repeating events, like every first sunday in month. +Only simple recurrence are allowed like: every n-th [day|week|month|year] from <DATE> until <DATE> except <DATE>,... EOF } european_format=0 output="/dev/stdout" while getopts Eho: arg do case "$arg" in E) european_format=1;; o) output="$OPTARG";; - h) help + h) help exit 0;; ?) help exit 1;; esac done shift $(( $OPTIND - 1)) if [ $# -lt 1 ] then help exit 0 fi -cat "$*" | -awk ' -BEGIN{ - RS = "" -} +if [ -z "$GNU_DATE_COMMAND" ]; then + GNU_DATE_COMMAND=date +fi + +# check date command for gnu version +TEST_DATE=`"$GNU_DATE_COMMAND" -d 20100101 +%Y%m%d` +if [ "x$TEST_DATE" != "x20100101" ]; then + echo "Gnu version of date command not found. Please set correct config value." + echo " " + exit 1 +fi { - gsub(/\r/,"",$0) # Remove the Windows style line ending - gsub(/\f/,"",$0) # Remove the Windows style line ending - gsub(/\n /,"", $0) # Unfold the lines - gsub(/\\\\/,"\\",$0) - gsub(/\\,/,",",$0) - gsub(/\\;/,";",$0) - gsub(/\\n/," ",$0) - gsub(/\\N/," ",$0) - print -}' | -awk -v european_format=$european_format -v date_command="$GNU_DATE_COMMAND" ' + cat "$*" | + awk ' + BEGIN{ + RS = "" + } + + { + gsub(/\r/,"",$0) # Remove the Windows style line ending + gsub(/\f/,"",$0) # Remove the Windows style line ending + gsub(/\n /,"", $0) # Unfold the lines + gsub(/\\\\/,"\\",$0) + gsub(/\\,/,",",$0) + gsub(/\\;/,";",$0) + gsub(/\\n/," ",$0) + gsub(/\\N/," ",$0) + print + }' | + awk -v date_command="$GNU_DATE_COMMAND" ' + BEGIN { + FS = ":" #field separator + print "BEGIN:RECURRENCES" + } + + $0 ~ /^BEGIN:VEVENT/ { + recurrence = 0 + all_day_event = 0 + summary = "" + utc_time = 0 + recurrence_date = "" + uid = "" + + while ($0 !~ /^END:VEVENT/) + { + if ($1 ~ /^RECURRENCE-ID/) + { + year = substr($2, 1, 4) + month = substr($2, 5, 2) + day = substr($2, 7, 2) + + if ($1 ~ /VALUE=DATE/) + { + all_day_event = 1 + } + else + { + hour = substr($2, 10, 2) + minute = substr($2, 12, 2) + UTCTAG = substr($2, 16, 1) + + if (UTCTAG == "Z") + { + utc_time = 1 + } + } + + recurrence = 1 + } + + if ($1 ~ /^SUMMARY/) + { + sub(/SUMMARY/,"",$0) + sub(/^:/,"",$0) + summary = $0 + } + + if ($1 ~ /^UID/) + { + sub(/UID/,"",$0) + sub(/^:/,"",$0) + uid = $0 + } + + getline + } + + if ( recurrence ) + { + if (! all_day_event && utc_time) + { + # Convert Date/Time from UTC to local time + + tmp_date = year month day "UTC" hour minute + command = date_command " -d" tmp_date " +%Y%m%d%H%M" + command | getline captureresult + close(command) + year = substr(captureresult, 1, 4) + month = substr(captureresult, 5, 2) + day = substr(captureresult, 7, 2) + hour = substr(captureresult, 9, 2) + minute = substr(captureresult, 11, 2) + } + + if (all_day_event) + { + recurrence_date = year month day + } + else + { + recurrence_date = year month day hour minute + } + + print "RECURRENCE_ENTRY:" uid ":" recurrence_date ":" summary + } + } + + END { + print "END:RECURRENCES" + }' + + cat "$*" | + awk ' + BEGIN{ + RS = "" + } + + { + gsub(/\r/,"",$0) # Remove the Windows style line ending + gsub(/\f/,"",$0) # Remove the Windows style line ending + gsub(/\n /,"", $0) # Unfold the lines + gsub(/\\\\/,"\\",$0) + gsub(/\\,/,",",$0) + gsub(/\\;/,";",$0) + gsub(/\\n/," ",$0) + gsub(/\\N/," ",$0) + print + }' + +} | awk -v european_format=$european_format -v date_command="$GNU_DATE_COMMAND" ' BEGIN { FS = ":" #field separator print "# Creator: ical2pcal" - print "# include this file into your .calendar file with: include \"a_file.pcal\"\n" + print "# include this file into your .calendar file with: include \"a_file.pcal\"\n" +} + +$0 ~ /^BEGIN:RECURRENCES/ { + recurrence_index = 0 + print "#Replaced events in event series:" + + while ($0 !~ /^END:RECURRENCES/) + { + if ($1 ~ /^RECURRENCE_ENTRY/) + { + recurrences[recurrence_index] = $2 ":" $3 + recurrence_index = recurrence_index + 1 + print "#" $1 ":" $3 ":" substr($0, index($0,$4)) + } + + getline + } + + print "" } $0 ~ /^BEGIN:VEVENT/ { all_day_event = 0 utc_time = 0 summary = "" location = "" description = "" + uid = "" + recurence_reference_date = "" repeat = 1 repeating_event = 0 frequency ="" interval = 1 max_num_repetitions = 750 repeating_end_date = "" date_incr_str = "week" debug_repeat_str = "" # empty exdates array for (i in exdates) { delete exdates[i] } exdates_index = 0 while ($0 !~ /^END:VEVENT/) { if ($1 ~ /^DTSTART/) { year_start = substr($2, 1, 4) month_start = substr($2, 5, 2) day_start = substr($2, 7, 2) - if ($1 ~ /VALUE=DATE/) + if ($1 ~ /VALUE=DATE/) { - all_day_event = 1 + all_day_event = 1 } else { hour_start = substr($2, 10, 2) minute_start = substr($2, 12, 2) UTCTAG = substr($2, 16, 1) if (UTCTAG == "Z") { utc_time = 1 } } } if ($1 ~ /^DTEND/) { year_end = substr($2, 1, 4) month_end = substr($2, 5, 2) day_end = substr($2, 7, 2) - if ($1 ~ /VALUE=DATE/) + if ($1 ~ /VALUE=DATE/) { - all_day_event = 1 + all_day_event = 1 } else { hour_end = substr($2, 10, 2) minute_end = substr($2, 12, 2) } } if ($1 ~ /^SUMMARY/) { sub(/SUMMARY/,"",$0) sub(/^:/,"",$0) summary = $0 } if ($1 ~ /^LOCATION/) { sub(/LOCATION/,"",$0) sub(/^:/,"",$0) location = $0 } if ($1 ~ /^DESCRIPTION/) { sub(/DESCRIPTION/,"",$0) sub(/^:/,"",$0) description = $0 } + if ($1 ~ /^UID/) + { + sub(/UID/,"",$0) + sub(/^:/,"",$0) + uid = $0 + } + if ($1 ~ /^RRULE/) { debug_repeat_str = $0 sub(/RRULE/,"",$0) sub(/^:/,"",$0) split($0,part,";") for (i in part) { numparts = split(part[i],subpart,"=") if (numparts > 1) { if (subpart[1] ~ /FREQ/) { frequency = subpart[2] } if (subpart[1] ~ /INTERVAL/) { interval = subpart[2] } if (subpart[1] ~ /UNTIL/) { until_year = substr(subpart[2], 1, 4) until_month = substr(subpart[2], 5, 2) until_day = substr(subpart[2], 7, 2) until_hour = substr(subpart[2], 10, 2) until_minute = substr(subpart[2], 12, 2) until_UTCTAG = substr(subpart[2], 16, 1) if (until_UTCTAG == "Z") { tmp_repeating_end_date = until_year until_month until_day "UTC" until_hour until_minute command = date_command " -d" tmp_repeating_end_date " +%Y%m%d%H%M" command | getline captureresult close(command) until_year = substr(captureresult, 1, 4) until_month = substr(captureresult, 5, 2) until_day = substr(captureresult, 7, 2) } repeating_end_date = until_year until_month until_day } } } if (frequency == "DAILY") { repeating_event = 1 max_num_repetitions = 750 date_incr_str = "day" } if (frequency == "WEEKLY") { repeating_event = 1 max_num_repetitions = 260 date_incr_str = "week" } if (frequency == "MONTHLY") { repeating_event = 1 max_num_repetitions = 60 date_incr_str = "month" } if (frequency == "YEARLY") { repeating_event = 1 max_num_repetitions = 5 date_incr_str = "year" } } if ($1 ~ /^EXDATE/) { split($2,part,",") for (i in part) { year_exdate = substr(part[i], 1, 4) month_exdate = substr(part[i], 5, 2) day_exdate = substr(part[i], 7, 2) hour_exdate = substr(part[i], 10, 2) minute_exdate = substr(part[i], 12, 2) UTCTAG = substr(part[i], 16, 1) if (UTCTAG == "Z") { tmp_exdate = year_exdate month_exdate day_exdate "UTC" hour_exdate minute_exdate command = date_command " -d" tmp_exdate " +%Y%m%d%H%M" command | getline captureresult close(command) year_exdate = substr(captureresult, 1, 4) month_exdate = substr(captureresult, 5, 2) - day_exdate = substr(captureresult, 7, 2) + day_exdate = substr(captureresult, 7, 2) } tmp_exdate = year_exdate month_exdate day_exdate exdates[exdates_index] = tmp_exdate exdates_index = exdates_index + 1 } } getline } if (! all_day_event && utc_time) { # Convert Date/Time from UTC to local time - + tmp_date_start = year_start month_start day_start "UTC" hour_start minute_start command = date_command " -d" tmp_date_start " +%Y%m%d%H%M" command | getline captureresult close(command) year_start = substr(captureresult, 1, 4) month_start = substr(captureresult, 5, 2) day_start = substr(captureresult, 7, 2) hour_start = substr(captureresult, 9, 2) minute_start = substr(captureresult, 11, 2) tmp_date_end = year_end month_end day_end "UTC" hour_end minute_end command = date_command " -d " tmp_date_end " +%Y%m%d%H%M" command | getline captureresult close(command) year_end = substr(captureresult, 1, 4) month_end = substr(captureresult, 5, 2) day_end = substr(captureresult, 7, 2) hour_end = substr(captureresult, 9, 2) minute_end = substr(captureresult, 11, 2) } date_start = year_start month_start day_start date_end = year_end month_end day_end # avoid new day entry if end time is 12AM if (! all_day_event && hour_end == "00" && minute_end == "00") { command = date_command " -d \"" date_end " -1 day\"" " +%Y%m%d" command | getline captureresult close(command) year_end = substr(captureresult, 1, 4) month_end = substr(captureresult, 5, 2) day_end = substr(captureresult, 7, 2) date_end = year_end month_end day_end } if (summary == "") { next } print "#### BEGIN EVENT -----------------------------------" if (debug_repeat_str != "") { print "#"debug_repeat_str } if (exdates_index > 0) { for (i in exdates) { print "#EXDATE:" exdates[i] } } num_repetitions = 0 while (repeat == 1 && num_repetitions < max_num_repetitions) { date_start_bak = date_start date_end_bak = date_end # check for excluded dates exdate = 0 for (i in exdates) { if (exdates[i] == date_start) { exdate = 1 break } - } + } + + if (exdate == 0 && repeating_event) + { + if (! all_day_event) + { + recurence_reference_date = year_start month_start day_start hour_start minute_start + } + else + { + recurence_reference_date = year_start month_start day_start + } + + for (i in recurrences) + { + if (recurrences[i] == uid ":" recurence_reference_date) + { + exdate = 1 + print "#skip event due to modified series element: " uid ":" recurence_reference_date + break + } + } + } if (exdate == 0) { if (all_day_event) { # Hack to save calculation time - not works for last day of month if (date_start + 1 == date_end) { if (european_format) { print day_start "/" month_start "/" year_start " " summary } else { print month_start "/" day_start "/" year_start " " summary } } else { - if (date_start < date_end) + if (date_start < date_end) { date_next = date_start while (date_next < date_end) { tmp_year_next = substr(date_next, 1, 4) tmp_month_next = substr(date_next, 5, 2) tmp_day_next = substr(date_next, 7, 2) if (european_format) { print tmp_day_next "/" tmp_month_next "/" tmp_year_next " " summary } else { print tmp_month_next "/" tmp_day_next "/" tmp_year_next " " summary } command = date_command " -d \"" date_next " 1 day\"" " +%Y%m%d" command | getline captureresult close(command) date_next = captureresult } } else { # Should not happen if (european_format) { print day_start "/" month_start "/" year_start " " summary } else { print month_start "/" day_start "/" year_start " " summary } } } } else { - if (date_start < date_end) + if (date_start < date_end) { # first date with start time if (european_format) { print day_start "/" month_start "/" year_start " " hour_start ":" minute_start " -> " summary } else { command = date_command " -d " hour_start ":" minute_start " +%I:%M%p" command | getline time_start close(command) print month_start "/" day_start "/" year_start " " time_start " -> " summary } #middle days without time command = date_command " -d \"" date_start " 1 day\"" " +%Y%m%d" command | getline captureresult close(command) date_next = captureresult while (date_next < date_end) { tmp_year_next = substr(date_next, 1, 4) tmp_month_next = substr(date_next, 5, 2) tmp_day_next = substr(date_next, 7, 2) if (european_format) { print tmp_day_next "/" tmp_month_next "/" tmp_year_next " " summary } else { print tmp_month_next "/" tmp_day_next "/" tmp_year_next " " summary } command = date_command " -d \"" date_next " 1 day\"" " +%Y%m%d" command | getline captureresult close(command) date_next = captureresult } # last day with end time if (european_format) { print day_end "/" month_end "/" year_end " -> " hour_end ":" minute_end " " summary } else { command = date_command " -d " hour_end ":" minute_end " +%I:%M%p" command | getline time_end close(command) print month_end "/" day_end "/" year_end " -> " time_end " " summary } } else { if (european_format) { print day_start "/" month_start "/" year_start " " hour_start ":" minute_start "-" hour_end ":" minute_end " " summary } else { command = date_command " -d " hour_start ":" minute_start " +%I:%M%p" command | getline time_start close(command) command = date_command " -d " hour_end ":" minute_end " +%I:%M%p" command | getline time_end close(command) print month_start "/" day_start "/" year_start " " time_start "-" time_end " " summary } } } if (location != "") { if (european_format) { print "#"day_start "/" month_start "/" year_start" location: "location } else { print "#"month_start "/" day_start "/" year_start" location: "location } } if (description != "") { if (european_format) { print "#"day_start "/" month_start "/" year_start" description: "description } else { print "#"month_start "/" day_start "/" year_start" description: "description } } } # calculate repeating events if (repeating_event == 0) { repeat = 0 } else { num_repetitions = num_repetitions + 1 command = date_command " -d \"" date_start_bak " " interval " " date_incr_str "\" " "+%Y%m%d" command | getline captureresult close(command) date_start = captureresult year_start = substr(captureresult, 1, 4) month_start = substr(captureresult, 5, 2) day_start = substr(captureresult, 7, 2) command = date_command " -d \"" date_end_bak " " interval " " date_incr_str "\" " "+%Y%m%d" command | getline captureresult close(command) date_end = captureresult year_end = substr(captureresult, 1, 4) month_end = substr(captureresult, 5, 2) day_end = substr(captureresult, 7, 2) if (repeating_end_date != "" && date_start > repeating_end_date) { repeat = 0 } } } print "#### END EVENT -------------------------------------\n" } END { -}' > "$output" - - +}' > "$output"
pmarin/ical2pcal
c2be147cac4ca5114cba55c542cebe80ac275009
Implement the support of simple repeating events
diff --git a/README b/README index e04b898..3d1463b 100644 --- a/README +++ b/README @@ -1,26 +1,27 @@ -ical2pcal v0.0.2 - Convert iCalendar (.ics) data files to pcal data files +ical2pcal v0.0.4 - Convert iCalendar (.ics) data files to pcal data files + +Usage: ical2pcal [-E] [-o <file>] [-h] file -Usage: ical2pcal [-E] [-o <file>] [-h] file - -E Use European date format (dd/mm/yyyy) - -o <file> Write the output to file instead of to stdout - + -o <file> Write the output to file instead of to stdout + -h Display this help -The iCalendar format (.ics file extension) is a standard (RFC 2445) -for calendar data exchange. Programs that support the iCalendar format -are: Google Calendar, Apple iCal, Evolution, Orange, etc. +The iCalendar format (.ics file extension) is a standard (RFC 2445) for +calendar data exchange. Programs that support the iCalendar format are: Google +Calendar, Apple iCal, Evolution, Orange, etc. -The iCalendar format have many objects like events, to-do lists, -alarms, journal entries etc. ical2pcal only use the events -in the file showing in the pcal file the summary and the time of -the event, the rest information of the event like -description or location are commented in the pcal file (because +The iCalendar format have many objects like events, to-do lists, alarms, +journal entries etc. ical2pcal only use the events in the file showing in the +pcal file the summary and the time of the event, the rest information of the +event like description or location are commented in the pcal file (because usually this information does not fit in the day box). -Currently automatic detection and conversion to local time of time values -in UTC is implemented. All other time values are assumed as local times. +Currently automatic detection and conversion to local time of time values in +UTC is implemented. All other time values are assumed as local times. -ical2pcal does not support repeating events, like every first sunday in month. +ical2pcal does not support complex repeating events, like every first sunday in +month. Only simple recurrence are allowed like: +every n-th [day|week|month|year] from <DATE> until <DATE> except <DATE>,... diff --git a/ical2pcal.sh b/ical2pcal.sh index 0ebefa9..7da0c24 100755 --- a/ical2pcal.sh +++ b/ical2pcal.sh @@ -1,410 +1,609 @@ #!/bin/bash # Copyright (c) 2010 Jörg Kühne <jk-ical2pcal at gmx dot de> # Copyright (c) 2008 Francisco José Marín Pérez <pacogeek at gmail dot com> # All rights reserved. (The Mit License) #Permission is hereby granted, free of charge, to any person obtaining a copy #of this software and associated documentation files (the "Software"), to deal #in the Software without restriction, including without limitation the rights #to use, copy, modify, merge, publish, distribute, sublicense, and/or sell #copies of the Software, and to permit persons to whom the Software is #furnished to do so, subject to the following conditions: # #The above copyright notice and this permission notice shall be included in #all copies or substantial portions of the Software. # #THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN #THE SOFTWARE. # Changes from Jörg Kühne +#v0.0.4 +# - support of excluded dates in a simple series of repeating events + +#v0.0.3 +# - support of simple repeating events like: +# every n-th [day|week|month|year] from <DATE> until <DATE> +# but not like: +# every first sunday in month + # v0.0.2: # - auto conversion from UTC times to local times # - support of multiple day events # - support of begin/end times # ---------------------------------------------------------------------- # Configuration # if the gnu date command is not in default path, please specify the command # with full path GNU_DATE_COMMAND="" # ---------------------------------------------------------------------- # Code starts here if [ -z "$GNU_DATE_COMMAND" ]; then GNU_DATE_COMMAND=date fi # check date command for gnu version TEST_DATE=`"$GNU_DATE_COMMAND" -d 20100101 +%Y%m%d` if [ "x$TEST_DATE" != "x20100101" ]; then echo "Gnu version of date command not found. Please set correct config value." echo " " exit 1 fi help() { # Show the help cat << EOF -ical2pcal v0.0.2 - Convert iCalendar (.ics) data files to pcal data files +ical2pcal v0.0.4 - Convert iCalendar (.ics) data files to pcal data files + +Usage: ical2pcal [-E] [-o <file>] [-h] file -Usage: ical2pcal [-E] [-o <file>] [-h] file - -E Use European date format (dd/mm/yyyy) - -o <file> Write the output to file instead of to stdout - + -o <file> Write the output to file instead of to stdout + -h Display this help -The iCalendar format (.ics file extension) is a standard (RFC 2445) -for calendar data exchange. Programs that support the iCalendar format -are: Google Calendar, Apple iCal, Evolution, Orange, etc. +The iCalendar format (.ics file extension) is a standard (RFC 2445) for +calendar data exchange. Programs that support the iCalendar format are: Google +Calendar, Apple iCal, Evolution, Orange, etc. -The iCalendar format have many objects like events, to-do lists, -alarms, journal entries etc. ical2pcal only use the events -in the file showing in the pcal file the summary and the time of -the event, the rest information of the event like -description or location are commented in the pcal file (because +The iCalendar format have many objects like events, to-do lists, alarms, +journal entries etc. ical2pcal only use the events in the file showing in the +pcal file the summary and the time of the event, the rest information of the +event like description or location are commented in the pcal file (because usually this information does not fit in the day box). -Currently automatic detection and conversion to local time of time values -in UTC is implemented. All other time values are assumed as local times. +Currently automatic detection and conversion to local time of time values in +UTC is implemented. All other time values are assumed as local times. -ical2pcal does not support repeating events, like every first sunday in month. +ical2pcal does not support complex repeating events, like every first sunday in +month. Only simple recurrence are allowed like: +every n-th [day|week|month|year] from <DATE> until <DATE> except <DATE>,... EOF } european_format=0 output="/dev/stdout" while getopts Eho: arg do case "$arg" in E) european_format=1;; o) output="$OPTARG";; h) help exit 0;; ?) help exit 1;; esac done shift $(( $OPTIND - 1)) if [ $# -lt 1 ] then help exit 0 fi -cat $* | +cat "$*" | awk ' BEGIN{ RS = "" } { gsub(/\r/,"",$0) # Remove the Windows style line ending gsub(/\f/,"",$0) # Remove the Windows style line ending gsub(/\n /,"", $0) # Unfold the lines gsub(/\\\\/,"\\",$0) gsub(/\\,/,",",$0) gsub(/\\;/,";",$0) gsub(/\\n/," ",$0) gsub(/\\N/," ",$0) print }' | awk -v european_format=$european_format -v date_command="$GNU_DATE_COMMAND" ' BEGIN { FS = ":" #field separator print "# Creator: ical2pcal" print "# include this file into your .calendar file with: include \"a_file.pcal\"\n" } $0 ~ /^BEGIN:VEVENT/ { all_day_event = 0 utc_time = 0 summary = "" - localtion = "" + location = "" description = "" + repeat = 1 + repeating_event = 0 + frequency ="" + interval = 1 + max_num_repetitions = 750 + repeating_end_date = "" + date_incr_str = "week" + debug_repeat_str = "" + # empty exdates array + for (i in exdates) + { + delete exdates[i] + } + exdates_index = 0 + while ($0 !~ /^END:VEVENT/) { if ($1 ~ /^DTSTART/) { year_start = substr($2, 1, 4) month_start = substr($2, 5, 2) day_start = substr($2, 7, 2) if ($1 ~ /VALUE=DATE/) { all_day_event = 1 } else { hour_start = substr($2, 10, 2) minute_start = substr($2, 12, 2) UTCTAG = substr($2, 16, 1) if (UTCTAG == "Z") { utc_time = 1 } } } if ($1 ~ /^DTEND/) { year_end = substr($2, 1, 4) month_end = substr($2, 5, 2) day_end = substr($2, 7, 2) if ($1 ~ /VALUE=DATE/) { all_day_event = 1 } else { hour_end = substr($2, 10, 2) minute_end = substr($2, 12, 2) } } if ($1 ~ /^SUMMARY/) { sub(/SUMMARY/,"",$0) sub(/^:/,"",$0) summary = $0 } + if ($1 ~ /^LOCATION/) { sub(/LOCATION/,"",$0) sub(/^:/,"",$0) location = $0 } if ($1 ~ /^DESCRIPTION/) { sub(/DESCRIPTION/,"",$0) sub(/^:/,"",$0) description = $0 } + + if ($1 ~ /^RRULE/) + { + debug_repeat_str = $0 + sub(/RRULE/,"",$0) + sub(/^:/,"",$0) + split($0,part,";") + for (i in part) + { + numparts = split(part[i],subpart,"=") + + if (numparts > 1) + { + if (subpart[1] ~ /FREQ/) + { + frequency = subpart[2] + } + + if (subpart[1] ~ /INTERVAL/) + { + interval = subpart[2] + } + + if (subpart[1] ~ /UNTIL/) + { + until_year = substr(subpart[2], 1, 4) + until_month = substr(subpart[2], 5, 2) + until_day = substr(subpart[2], 7, 2) + until_hour = substr(subpart[2], 10, 2) + until_minute = substr(subpart[2], 12, 2) + until_UTCTAG = substr(subpart[2], 16, 1) + + if (until_UTCTAG == "Z") + { + tmp_repeating_end_date = until_year until_month until_day "UTC" until_hour until_minute + command = date_command " -d" tmp_repeating_end_date " +%Y%m%d%H%M" + command | getline captureresult + close(command) + until_year = substr(captureresult, 1, 4) + until_month = substr(captureresult, 5, 2) + until_day = substr(captureresult, 7, 2) + } + + repeating_end_date = until_year until_month until_day + } + } + } + + if (frequency == "DAILY") + { + repeating_event = 1 + max_num_repetitions = 750 + date_incr_str = "day" + } + if (frequency == "WEEKLY") + { + repeating_event = 1 + max_num_repetitions = 260 + date_incr_str = "week" + } + if (frequency == "MONTHLY") + { + repeating_event = 1 + max_num_repetitions = 60 + date_incr_str = "month" + } + if (frequency == "YEARLY") + { + repeating_event = 1 + max_num_repetitions = 5 + date_incr_str = "year" + } + } + + if ($1 ~ /^EXDATE/) + { + split($2,part,",") + for (i in part) + { + year_exdate = substr(part[i], 1, 4) + month_exdate = substr(part[i], 5, 2) + day_exdate = substr(part[i], 7, 2) + hour_exdate = substr(part[i], 10, 2) + minute_exdate = substr(part[i], 12, 2) + UTCTAG = substr(part[i], 16, 1) + + if (UTCTAG == "Z") + { + tmp_exdate = year_exdate month_exdate day_exdate "UTC" hour_exdate minute_exdate + command = date_command " -d" tmp_exdate " +%Y%m%d%H%M" + command | getline captureresult + close(command) + year_exdate = substr(captureresult, 1, 4) + month_exdate = substr(captureresult, 5, 2) + day_exdate = substr(captureresult, 7, 2) + } + + tmp_exdate = year_exdate month_exdate day_exdate + exdates[exdates_index] = tmp_exdate + exdates_index = exdates_index + 1 + } + } + getline } - print "#### BEGIN EVENT -----------------------------------" if (! all_day_event && utc_time) { # Convert Date/Time from UTC to local time tmp_date_start = year_start month_start day_start "UTC" hour_start minute_start command = date_command " -d" tmp_date_start " +%Y%m%d%H%M" command | getline captureresult close(command) year_start = substr(captureresult, 1, 4) month_start = substr(captureresult, 5, 2) day_start = substr(captureresult, 7, 2) hour_start = substr(captureresult, 9, 2) minute_start = substr(captureresult, 11, 2) tmp_date_end = year_end month_end day_end "UTC" hour_end minute_end command = date_command " -d " tmp_date_end " +%Y%m%d%H%M" command | getline captureresult close(command) year_end = substr(captureresult, 1, 4) month_end = substr(captureresult, 5, 2) day_end = substr(captureresult, 7, 2) hour_end = substr(captureresult, 9, 2) minute_end = substr(captureresult, 11, 2) } date_start = year_start month_start day_start date_end = year_end month_end day_end # avoid new day entry if end time is 12AM - if (hour_end == "00" && minute_end == "00") + if (! all_day_event && hour_end == "00" && minute_end == "00") { command = date_command " -d \"" date_end " -1 day\"" " +%Y%m%d" command | getline captureresult close(command) year_end = substr(captureresult, 1, 4) month_end = substr(captureresult, 5, 2) day_end = substr(captureresult, 7, 2) date_end = year_end month_end day_end } - if (all_day_event) + if (summary == "") + { + next + } + + print "#### BEGIN EVENT -----------------------------------" + if (debug_repeat_str != "") + { + print "#"debug_repeat_str + } + if (exdates_index > 0) + { + for (i in exdates) + { + print "#EXDATE:" exdates[i] + } + } + + num_repetitions = 0 + while (repeat == 1 && num_repetitions < max_num_repetitions) { - # Hack to save calculation time - not works for last day of month - if (date_start + 1 == date_end) + date_start_bak = date_start + date_end_bak = date_end + + # check for excluded dates + exdate = 0 + for (i in exdates) { - if (european_format) + if (exdates[i] == date_start) { - print day_start "/" month_start "/" year_start " " summary + exdate = 1 + break } - else + } + + if (exdate == 0) + { + if (all_day_event) { - print month_start "/" day_start "/" year_start " " summary + # Hack to save calculation time - not works for last day of month + if (date_start + 1 == date_end) + { + if (european_format) + { + print day_start "/" month_start "/" year_start " " summary + } + else + { + print month_start "/" day_start "/" year_start " " summary + } + } + else + { + if (date_start < date_end) + { + date_next = date_start + while (date_next < date_end) + { + tmp_year_next = substr(date_next, 1, 4) + tmp_month_next = substr(date_next, 5, 2) + tmp_day_next = substr(date_next, 7, 2) + + if (european_format) + { + print tmp_day_next "/" tmp_month_next "/" tmp_year_next " " summary + } + else + { + print tmp_month_next "/" tmp_day_next "/" tmp_year_next " " summary + } + + command = date_command " -d \"" date_next " 1 day\"" " +%Y%m%d" + command | getline captureresult + close(command) + date_next = captureresult + } + } + else + { + # Should not happen + if (european_format) + { + print day_start "/" month_start "/" year_start " " summary + } + else + { + print month_start "/" day_start "/" year_start " " summary + } + } + } } - } - else - { - if (date_start < date_end) + else { - date_next = date_start - while (date_next < date_end) + if (date_start < date_end) { - tmp_year_next = substr(date_next, 1, 4) - tmp_month_next = substr(date_next, 5, 2) - tmp_day_next = substr(date_next, 7, 2) - + # first date with start time if (european_format) { - print tmp_day_next "/" tmp_month_next "/" tmp_year_next " " summary + print day_start "/" month_start "/" year_start " " hour_start ":" minute_start " -> " summary } else { - print tmp_month_next "/" tmp_day_next "/" tmp_year_next " " summary + command = date_command " -d " hour_start ":" minute_start " +%I:%M%p" + command | getline time_start + close(command) + + print month_start "/" day_start "/" year_start " " time_start " -> " summary } - command = date_command " -d \"" date_next " 1 day\"" " +%Y%m%d" + #middle days without time + command = date_command " -d \"" date_start " 1 day\"" " +%Y%m%d" command | getline captureresult close(command) date_next = captureresult + while (date_next < date_end) + { + tmp_year_next = substr(date_next, 1, 4) + tmp_month_next = substr(date_next, 5, 2) + tmp_day_next = substr(date_next, 7, 2) + + if (european_format) + { + print tmp_day_next "/" tmp_month_next "/" tmp_year_next " " summary + } + else + { + print tmp_month_next "/" tmp_day_next "/" tmp_year_next " " summary + } + + command = date_command " -d \"" date_next " 1 day\"" " +%Y%m%d" + command | getline captureresult + close(command) + date_next = captureresult + } + + # last day with end time + if (european_format) + { + print day_end "/" month_end "/" year_end " -> " hour_end ":" minute_end " " summary + } + else + { + command = date_command " -d " hour_end ":" minute_end " +%I:%M%p" + command | getline time_end + close(command) + + print month_end "/" day_end "/" year_end " -> " time_end " " summary + } + } + else + { + if (european_format) + { + print day_start "/" month_start "/" year_start " " hour_start ":" minute_start "-" hour_end ":" minute_end " " summary + } + else + { + command = date_command " -d " hour_start ":" minute_start " +%I:%M%p" + command | getline time_start + close(command) + + command = date_command " -d " hour_end ":" minute_end " +%I:%M%p" + command | getline time_end + close(command) + + print month_start "/" day_start "/" year_start " " time_start "-" time_end " " summary + } } } - else + if (location != "") { - # Should not happen if (european_format) { - print day_start "/" month_start "/" year_start " " summary + print "#"day_start "/" month_start "/" year_start" location: "location } else { - print month_start "/" day_start "/" year_start " " summary + print "#"month_start "/" day_start "/" year_start" location: "location } } - } - } - else - { - if (date_start < date_end) - { - # first date with start time - if (european_format) - { - print day_start "/" month_start "/" year_start " " hour_start ":" minute_start " -> " summary - } - else + if (description != "") { - command = date_command " -d " hour_start ":" minute_start " +%I:%M%p" - command | getline time_start - close(command) - - print month_start "/" day_start "/" year_start " " time_start " -> " summary - } - - #middle days without time - command = date_command " -d \"" date_start " 1 day\"" " +%Y%m%d" - command | getline captureresult - close(command) - date_next = captureresult - while (date_next < date_end) - { - tmp_year_next = substr(date_next, 1, 4) - tmp_month_next = substr(date_next, 5, 2) - tmp_day_next = substr(date_next, 7, 2) - if (european_format) { - print tmp_day_next "/" tmp_month_next "/" tmp_year_next " " summary + print "#"day_start "/" month_start "/" year_start" description: "description } else { - print tmp_month_next "/" tmp_day_next "/" tmp_year_next " " summary + print "#"month_start "/" day_start "/" year_start" description: "description } - - command = date_command " -d \"" date_next " 1 day\"" " +%Y%m%d" - command | getline captureresult - close(command) - date_next = captureresult } + } - # last day with end time - if (european_format) - { - print day_end "/" month_end "/" year_end " -> " hour_end ":" minute_end " " summary - } - else - { - command = date_command " -d " hour_end ":" minute_end " +%I:%M%p" - command | getline time_end - close(command) - - print month_end "/" day_end "/" year_end " -> " time_end " " summary - } + # calculate repeating events + if (repeating_event == 0) + { + repeat = 0 } else { - if (european_format) - { - print day_start "/" month_start "/" year_start " " hour_start ":" minute_start "-" hour_end ":" minute_end " " summary - } - else - { - command = date_command " -d " hour_start ":" minute_start " +%I:%M%p" - command | getline time_start - close(command) + num_repetitions = num_repetitions + 1 - command = date_command " -d " hour_end ":" minute_end " +%I:%M%p" - command | getline time_end - close(command) + command = date_command " -d \"" date_start_bak " " interval " " date_incr_str "\" " "+%Y%m%d" + command | getline captureresult + close(command) + date_start = captureresult + year_start = substr(captureresult, 1, 4) + month_start = substr(captureresult, 5, 2) + day_start = substr(captureresult, 7, 2) - print month_start "/" day_start "/" year_start " " time_start "-" time_end " " summary + command = date_command " -d \"" date_end_bak " " interval " " date_incr_str "\" " "+%Y%m%d" + command | getline captureresult + close(command) + date_end = captureresult + year_end = substr(captureresult, 1, 4) + month_end = substr(captureresult, 5, 2) + day_end = substr(captureresult, 7, 2) + + if (repeating_end_date != "" && date_start > repeating_end_date) + { + repeat = 0 } } } - if (location != "") - { - if (european_format) - { - print "#"day_start "/" month_start "/" year_start" location: "location - } - else - { - print "#"month_start "/" day_start "/" year_start" location: "location - } - } - if (description != "") - { - if (european_format) - { - print "#"day_start "/" month_start "/" year_start" description: "description - } - else - { - print "#"month_start "/" day_start "/" year_start" description: "description - } - } + print "#### END EVENT -------------------------------------\n" } END { -}' > $output +}' > "$output"
pmarin/ical2pcal
870d676221dc3a6e35e7ec7b1594b3d4e609a07c
ical2pcal does not support repeating events
diff --git a/README b/README index c5a8495..e04b898 100644 --- a/README +++ b/README @@ -1,24 +1,26 @@ ical2pcal v0.0.2 - Convert iCalendar (.ics) data files to pcal data files Usage: ical2pcal [-E] [-o <file>] [-h] file -E Use European date format (dd/mm/yyyy) -o <file> Write the output to file instead of to stdout -h Display this help The iCalendar format (.ics file extension) is a standard (RFC 2445) for calendar data exchange. Programs that support the iCalendar format are: Google Calendar, Apple iCal, Evolution, Orange, etc. The iCalendar format have many objects like events, to-do lists, alarms, journal entries etc. ical2pcal only use the events in the file showing in the pcal file the summary and the time of the event, the rest information of the event like description or location are commented in the pcal file (because usually this information does not fit in the day box). Currently automatic detection and conversion to local time of time values in UTC is implemented. All other time values are assumed as local times. +ical2pcal does not support repeating events, like every first sunday in month. + diff --git a/ical2pcal.sh b/ical2pcal.sh index 76dfe8e..0ebefa9 100755 --- a/ical2pcal.sh +++ b/ical2pcal.sh @@ -1,408 +1,410 @@ #!/bin/bash # Copyright (c) 2010 Jörg Kühne <jk-ical2pcal at gmx dot de> # Copyright (c) 2008 Francisco José Marín Pérez <pacogeek at gmail dot com> # All rights reserved. (The Mit License) #Permission is hereby granted, free of charge, to any person obtaining a copy #of this software and associated documentation files (the "Software"), to deal #in the Software without restriction, including without limitation the rights #to use, copy, modify, merge, publish, distribute, sublicense, and/or sell #copies of the Software, and to permit persons to whom the Software is #furnished to do so, subject to the following conditions: # #The above copyright notice and this permission notice shall be included in #all copies or substantial portions of the Software. # #THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN #THE SOFTWARE. # Changes from Jörg Kühne # v0.0.2: # - auto conversion from UTC times to local times # - support of multiple day events # - support of begin/end times # ---------------------------------------------------------------------- # Configuration # if the gnu date command is not in default path, please specify the command # with full path GNU_DATE_COMMAND="" # ---------------------------------------------------------------------- # Code starts here if [ -z "$GNU_DATE_COMMAND" ]; then GNU_DATE_COMMAND=date fi # check date command for gnu version TEST_DATE=`"$GNU_DATE_COMMAND" -d 20100101 +%Y%m%d` if [ "x$TEST_DATE" != "x20100101" ]; then echo "Gnu version of date command not found. Please set correct config value." echo " " exit 1 fi help() { # Show the help cat << EOF ical2pcal v0.0.2 - Convert iCalendar (.ics) data files to pcal data files Usage: ical2pcal [-E] [-o <file>] [-h] file -E Use European date format (dd/mm/yyyy) -o <file> Write the output to file instead of to stdout -h Display this help The iCalendar format (.ics file extension) is a standard (RFC 2445) for calendar data exchange. Programs that support the iCalendar format are: Google Calendar, Apple iCal, Evolution, Orange, etc. The iCalendar format have many objects like events, to-do lists, alarms, journal entries etc. ical2pcal only use the events in the file showing in the pcal file the summary and the time of the event, the rest information of the event like description or location are commented in the pcal file (because usually this information does not fit in the day box). Currently automatic detection and conversion to local time of time values in UTC is implemented. All other time values are assumed as local times. +ical2pcal does not support repeating events, like every first sunday in month. + EOF } european_format=0 output="/dev/stdout" while getopts Eho: arg do case "$arg" in E) european_format=1;; o) output="$OPTARG";; h) help exit 0;; ?) help exit 1;; esac done shift $(( $OPTIND - 1)) if [ $# -lt 1 ] then help exit 0 fi cat $* | awk ' BEGIN{ RS = "" } { gsub(/\r/,"",$0) # Remove the Windows style line ending gsub(/\f/,"",$0) # Remove the Windows style line ending gsub(/\n /,"", $0) # Unfold the lines gsub(/\\\\/,"\\",$0) gsub(/\\,/,",",$0) gsub(/\\;/,";",$0) gsub(/\\n/," ",$0) gsub(/\\N/," ",$0) print }' | awk -v european_format=$european_format -v date_command="$GNU_DATE_COMMAND" ' BEGIN { FS = ":" #field separator print "# Creator: ical2pcal" print "# include this file into your .calendar file with: include \"a_file.pcal\"\n" } $0 ~ /^BEGIN:VEVENT/ { all_day_event = 0 utc_time = 0 summary = "" localtion = "" description = "" while ($0 !~ /^END:VEVENT/) { if ($1 ~ /^DTSTART/) { year_start = substr($2, 1, 4) month_start = substr($2, 5, 2) day_start = substr($2, 7, 2) if ($1 ~ /VALUE=DATE/) { all_day_event = 1 } else { hour_start = substr($2, 10, 2) minute_start = substr($2, 12, 2) UTCTAG = substr($2, 16, 1) if (UTCTAG == "Z") { utc_time = 1 } } } if ($1 ~ /^DTEND/) { year_end = substr($2, 1, 4) month_end = substr($2, 5, 2) day_end = substr($2, 7, 2) if ($1 ~ /VALUE=DATE/) { all_day_event = 1 } else { hour_end = substr($2, 10, 2) minute_end = substr($2, 12, 2) } } if ($1 ~ /^SUMMARY/) { sub(/SUMMARY/,"",$0) sub(/^:/,"",$0) summary = $0 } if ($1 ~ /^LOCATION/) { sub(/LOCATION/,"",$0) sub(/^:/,"",$0) location = $0 } if ($1 ~ /^DESCRIPTION/) { sub(/DESCRIPTION/,"",$0) sub(/^:/,"",$0) description = $0 } getline } print "#### BEGIN EVENT -----------------------------------" if (! all_day_event && utc_time) { # Convert Date/Time from UTC to local time tmp_date_start = year_start month_start day_start "UTC" hour_start minute_start command = date_command " -d" tmp_date_start " +%Y%m%d%H%M" command | getline captureresult close(command) year_start = substr(captureresult, 1, 4) month_start = substr(captureresult, 5, 2) day_start = substr(captureresult, 7, 2) hour_start = substr(captureresult, 9, 2) minute_start = substr(captureresult, 11, 2) tmp_date_end = year_end month_end day_end "UTC" hour_end minute_end command = date_command " -d " tmp_date_end " +%Y%m%d%H%M" command | getline captureresult close(command) year_end = substr(captureresult, 1, 4) month_end = substr(captureresult, 5, 2) day_end = substr(captureresult, 7, 2) hour_end = substr(captureresult, 9, 2) minute_end = substr(captureresult, 11, 2) } date_start = year_start month_start day_start date_end = year_end month_end day_end # avoid new day entry if end time is 12AM if (hour_end == "00" && minute_end == "00") { command = date_command " -d \"" date_end " -1 day\"" " +%Y%m%d" command | getline captureresult close(command) year_end = substr(captureresult, 1, 4) month_end = substr(captureresult, 5, 2) day_end = substr(captureresult, 7, 2) date_end = year_end month_end day_end } if (all_day_event) { # Hack to save calculation time - not works for last day of month if (date_start + 1 == date_end) { if (european_format) { print day_start "/" month_start "/" year_start " " summary } else { print month_start "/" day_start "/" year_start " " summary } } else { if (date_start < date_end) { date_next = date_start while (date_next < date_end) { tmp_year_next = substr(date_next, 1, 4) tmp_month_next = substr(date_next, 5, 2) tmp_day_next = substr(date_next, 7, 2) if (european_format) { print tmp_day_next "/" tmp_month_next "/" tmp_year_next " " summary } else { print tmp_month_next "/" tmp_day_next "/" tmp_year_next " " summary } command = date_command " -d \"" date_next " 1 day\"" " +%Y%m%d" command | getline captureresult close(command) date_next = captureresult } } else { # Should not happen if (european_format) { print day_start "/" month_start "/" year_start " " summary } else { print month_start "/" day_start "/" year_start " " summary } } } } else { if (date_start < date_end) { # first date with start time if (european_format) { print day_start "/" month_start "/" year_start " " hour_start ":" minute_start " -> " summary } else { command = date_command " -d " hour_start ":" minute_start " +%I:%M%p" command | getline time_start close(command) print month_start "/" day_start "/" year_start " " time_start " -> " summary } #middle days without time command = date_command " -d \"" date_start " 1 day\"" " +%Y%m%d" command | getline captureresult close(command) date_next = captureresult while (date_next < date_end) { tmp_year_next = substr(date_next, 1, 4) tmp_month_next = substr(date_next, 5, 2) tmp_day_next = substr(date_next, 7, 2) if (european_format) { print tmp_day_next "/" tmp_month_next "/" tmp_year_next " " summary } else { print tmp_month_next "/" tmp_day_next "/" tmp_year_next " " summary } command = date_command " -d \"" date_next " 1 day\"" " +%Y%m%d" command | getline captureresult close(command) date_next = captureresult } # last day with end time if (european_format) { print day_end "/" month_end "/" year_end " -> " hour_end ":" minute_end " " summary } else { command = date_command " -d " hour_end ":" minute_end " +%I:%M%p" command | getline time_end close(command) print month_end "/" day_end "/" year_end " -> " time_end " " summary } } else { if (european_format) { print day_start "/" month_start "/" year_start " " hour_start ":" minute_start "-" hour_end ":" minute_end " " summary } else { command = date_command " -d " hour_start ":" minute_start " +%I:%M%p" command | getline time_start close(command) command = date_command " -d " hour_end ":" minute_end " +%I:%M%p" command | getline time_end close(command) print month_start "/" day_start "/" year_start " " time_start "-" time_end " " summary } } } if (location != "") { if (european_format) { print "#"day_start "/" month_start "/" year_start" location: "location } else { print "#"month_start "/" day_start "/" year_start" location: "location } } if (description != "") { if (european_format) { print "#"day_start "/" month_start "/" year_start" description: "description } else { print "#"month_start "/" day_start "/" year_start" description: "description } } print "#### END EVENT -------------------------------------\n" } END { }' > $output
pmarin/ical2pcal
9065272773ff7f3e87a22d7aeb3f5758f5e136c6
Second try.
diff --git a/.ical2pcal.sh.swp b/.ical2pcal.sh.swp new file mode 100644 index 0000000..31be91c Binary files /dev/null and b/.ical2pcal.sh.swp differ
pmarin/ical2pcal
d727a1fa9e3d951295e209fbd0ebd136e841326f
Changed the Lincense to the Mit License
diff --git a/README b/README index 76fd8b5..c5a8495 100644 --- a/README +++ b/README @@ -1,26 +1,24 @@ -ical2pcal v0.0.1 - Convert iCalendar (.ics) data files to pcal data files +ical2pcal v0.0.2 - Convert iCalendar (.ics) data files to pcal data files Usage: ical2pcal [-E] [-o <file>] [-h] file -E Use European date format (dd/mm/yyyy) -o <file> Write the output to file instead of to stdout -h Display this help The iCalendar format (.ics file extension) is a standard (RFC 2445) for calendar data exchange. Programs that support the iCalendar format are: Google Calendar, Apple iCal, Evolution, Orange, etc. The iCalendar format have many objects like events, to-do lists, alarms, journal entries etc. ical2pcal only use the events in the file showing in the pcal file the summary and the time of the event, the rest information of the event like description or location are commented in the pcal file (because usually this information does not fit in the day box). -Currently the event's time is only true if the event is in your time -zone (be carefully about this). +Currently automatic detection and conversion to local time of time values +in UTC is implemented. All other time values are assumed as local times. -Please email me to report bugs, suggestions or simply correct my crappy -English to [email protected] diff --git a/ical2pcal.sh b/ical2pcal.sh new file mode 100755 index 0000000..76dfe8e --- /dev/null +++ b/ical2pcal.sh @@ -0,0 +1,408 @@ +#!/bin/bash + +# Copyright (c) 2010 Jörg Kühne <jk-ical2pcal at gmx dot de> +# Copyright (c) 2008 Francisco José Marín Pérez <pacogeek at gmail dot com> + +# All rights reserved. (The Mit License) + +#Permission is hereby granted, free of charge, to any person obtaining a copy +#of this software and associated documentation files (the "Software"), to deal +#in the Software without restriction, including without limitation the rights +#to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +#copies of the Software, and to permit persons to whom the Software is +#furnished to do so, subject to the following conditions: +# +#The above copyright notice and this permission notice shall be included in +#all copies or substantial portions of the Software. +# +#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +#FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +#AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +#LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +#OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +#THE SOFTWARE. + +# Changes from Jörg Kühne +# v0.0.2: +# - auto conversion from UTC times to local times +# - support of multiple day events +# - support of begin/end times + +# ---------------------------------------------------------------------- +# Configuration + +# if the gnu date command is not in default path, please specify the command +# with full path +GNU_DATE_COMMAND="" + +# ---------------------------------------------------------------------- +# Code starts here + +if [ -z "$GNU_DATE_COMMAND" ]; then + GNU_DATE_COMMAND=date +fi + +# check date command for gnu version +TEST_DATE=`"$GNU_DATE_COMMAND" -d 20100101 +%Y%m%d` +if [ "x$TEST_DATE" != "x20100101" ]; then + echo "Gnu version of date command not found. Please set correct config value." + echo " " + exit 1 +fi + +help() { # Show the help + cat << EOF +ical2pcal v0.0.2 - Convert iCalendar (.ics) data files to pcal data files + +Usage: ical2pcal [-E] [-o <file>] [-h] file + + -E Use European date format (dd/mm/yyyy) + + -o <file> Write the output to file instead of to stdout + + -h Display this help + +The iCalendar format (.ics file extension) is a standard (RFC 2445) +for calendar data exchange. Programs that support the iCalendar format +are: Google Calendar, Apple iCal, Evolution, Orange, etc. + +The iCalendar format have many objects like events, to-do lists, +alarms, journal entries etc. ical2pcal only use the events +in the file showing in the pcal file the summary and the time of +the event, the rest information of the event like +description or location are commented in the pcal file (because +usually this information does not fit in the day box). + +Currently automatic detection and conversion to local time of time values +in UTC is implemented. All other time values are assumed as local times. + +EOF +} + +european_format=0 +output="/dev/stdout" + +while getopts Eho: arg +do + case "$arg" + in + E) european_format=1;; + + o) output="$OPTARG";; + + h) help + exit 0;; + + ?) help + exit 1;; + esac +done + +shift $(( $OPTIND - 1)) + +if [ $# -lt 1 ] +then + help + exit 0 +fi + +cat $* | +awk ' +BEGIN{ + RS = "" +} + +{ + gsub(/\r/,"",$0) # Remove the Windows style line ending + gsub(/\f/,"",$0) # Remove the Windows style line ending + gsub(/\n /,"", $0) # Unfold the lines + gsub(/\\\\/,"\\",$0) + gsub(/\\,/,",",$0) + gsub(/\\;/,";",$0) + gsub(/\\n/," ",$0) + gsub(/\\N/," ",$0) + print +}' | +awk -v european_format=$european_format -v date_command="$GNU_DATE_COMMAND" ' +BEGIN { + FS = ":" #field separator + print "# Creator: ical2pcal" + print "# include this file into your .calendar file with: include \"a_file.pcal\"\n" +} + +$0 ~ /^BEGIN:VEVENT/ { + all_day_event = 0 + utc_time = 0 + summary = "" + localtion = "" + description = "" + + while ($0 !~ /^END:VEVENT/) + { + if ($1 ~ /^DTSTART/) + { + year_start = substr($2, 1, 4) + month_start = substr($2, 5, 2) + day_start = substr($2, 7, 2) + + if ($1 ~ /VALUE=DATE/) + { + all_day_event = 1 + } + else + { + hour_start = substr($2, 10, 2) + minute_start = substr($2, 12, 2) + UTCTAG = substr($2, 16, 1) + + if (UTCTAG == "Z") + { + utc_time = 1 + } + } + } + + if ($1 ~ /^DTEND/) + { + year_end = substr($2, 1, 4) + month_end = substr($2, 5, 2) + day_end = substr($2, 7, 2) + + if ($1 ~ /VALUE=DATE/) + { + all_day_event = 1 + } + else + { + hour_end = substr($2, 10, 2) + minute_end = substr($2, 12, 2) + } + } + + if ($1 ~ /^SUMMARY/) + { + sub(/SUMMARY/,"",$0) + sub(/^:/,"",$0) + summary = $0 + } + if ($1 ~ /^LOCATION/) + { + sub(/LOCATION/,"",$0) + sub(/^:/,"",$0) + location = $0 + } + + if ($1 ~ /^DESCRIPTION/) + { + sub(/DESCRIPTION/,"",$0) + sub(/^:/,"",$0) + description = $0 + } + getline + } + print "#### BEGIN EVENT -----------------------------------" + + if (! all_day_event && utc_time) + { + # Convert Date/Time from UTC to local time + + tmp_date_start = year_start month_start day_start "UTC" hour_start minute_start + command = date_command " -d" tmp_date_start " +%Y%m%d%H%M" + command | getline captureresult + close(command) + year_start = substr(captureresult, 1, 4) + month_start = substr(captureresult, 5, 2) + day_start = substr(captureresult, 7, 2) + hour_start = substr(captureresult, 9, 2) + minute_start = substr(captureresult, 11, 2) + + tmp_date_end = year_end month_end day_end "UTC" hour_end minute_end + command = date_command " -d " tmp_date_end " +%Y%m%d%H%M" + command | getline captureresult + close(command) + year_end = substr(captureresult, 1, 4) + month_end = substr(captureresult, 5, 2) + day_end = substr(captureresult, 7, 2) + hour_end = substr(captureresult, 9, 2) + minute_end = substr(captureresult, 11, 2) + } + + date_start = year_start month_start day_start + date_end = year_end month_end day_end + + # avoid new day entry if end time is 12AM + if (hour_end == "00" && minute_end == "00") + { + command = date_command " -d \"" date_end " -1 day\"" " +%Y%m%d" + command | getline captureresult + close(command) + year_end = substr(captureresult, 1, 4) + month_end = substr(captureresult, 5, 2) + day_end = substr(captureresult, 7, 2) + + date_end = year_end month_end day_end + } + + if (all_day_event) + { + # Hack to save calculation time - not works for last day of month + if (date_start + 1 == date_end) + { + if (european_format) + { + print day_start "/" month_start "/" year_start " " summary + } + else + { + print month_start "/" day_start "/" year_start " " summary + } + } + else + { + if (date_start < date_end) + { + date_next = date_start + while (date_next < date_end) + { + tmp_year_next = substr(date_next, 1, 4) + tmp_month_next = substr(date_next, 5, 2) + tmp_day_next = substr(date_next, 7, 2) + + if (european_format) + { + print tmp_day_next "/" tmp_month_next "/" tmp_year_next " " summary + } + else + { + print tmp_month_next "/" tmp_day_next "/" tmp_year_next " " summary + } + + command = date_command " -d \"" date_next " 1 day\"" " +%Y%m%d" + command | getline captureresult + close(command) + date_next = captureresult + } + } + else + { + # Should not happen + if (european_format) + { + print day_start "/" month_start "/" year_start " " summary + } + else + { + print month_start "/" day_start "/" year_start " " summary + } + } + } + } + else + { + if (date_start < date_end) + { + # first date with start time + if (european_format) + { + print day_start "/" month_start "/" year_start " " hour_start ":" minute_start " -> " summary + } + else + { + command = date_command " -d " hour_start ":" minute_start " +%I:%M%p" + command | getline time_start + close(command) + + print month_start "/" day_start "/" year_start " " time_start " -> " summary + } + + #middle days without time + command = date_command " -d \"" date_start " 1 day\"" " +%Y%m%d" + command | getline captureresult + close(command) + date_next = captureresult + while (date_next < date_end) + { + tmp_year_next = substr(date_next, 1, 4) + tmp_month_next = substr(date_next, 5, 2) + tmp_day_next = substr(date_next, 7, 2) + + if (european_format) + { + print tmp_day_next "/" tmp_month_next "/" tmp_year_next " " summary + } + else + { + print tmp_month_next "/" tmp_day_next "/" tmp_year_next " " summary + } + + command = date_command " -d \"" date_next " 1 day\"" " +%Y%m%d" + command | getline captureresult + close(command) + date_next = captureresult + } + + # last day with end time + if (european_format) + { + print day_end "/" month_end "/" year_end " -> " hour_end ":" minute_end " " summary + } + else + { + command = date_command " -d " hour_end ":" minute_end " +%I:%M%p" + command | getline time_end + close(command) + + print month_end "/" day_end "/" year_end " -> " time_end " " summary + } + } + else + { + if (european_format) + { + print day_start "/" month_start "/" year_start " " hour_start ":" minute_start "-" hour_end ":" minute_end " " summary + } + else + { + command = date_command " -d " hour_start ":" minute_start " +%I:%M%p" + command | getline time_start + close(command) + + command = date_command " -d " hour_end ":" minute_end " +%I:%M%p" + command | getline time_end + close(command) + + print month_start "/" day_start "/" year_start " " time_start "-" time_end " " summary + } + } + } + if (location != "") + { + if (european_format) + { + print "#"day_start "/" month_start "/" year_start" location: "location + } + else + { + print "#"month_start "/" day_start "/" year_start" location: "location + } + } + if (description != "") + { + if (european_format) + { + print "#"day_start "/" month_start "/" year_start" description: "description + } + else + { + print "#"month_start "/" day_start "/" year_start" description: "description + } + } + print "#### END EVENT -------------------------------------\n" +} + +END { + +}' > $output + +
bougyman/fxc
5ccd9f376dade8c20bbc19b8fec9990eab89365f
Got dialplan import working against new Migrations
diff --git a/db/migrate/007_add_server_id_to_contexts.rb b/db/migrate/007_add_server_id_to_contexts.rb new file mode 100644 index 0000000..8cbebe8 --- /dev/null +++ b/db/migrate/007_add_server_id_to_contexts.rb @@ -0,0 +1,18 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +Class.new Sequel::Migration do + def up + alter_table(:dialplan_contexts) do + add_foreign_key :server_id, :servers, :on_delete => :cascade + end unless FXC.db[:dialplan_contexts].columns.include? :server_id + + end + + def down + alter_table(:dialplan_contexts) do + drop_column :server_id + end if FXC.db[:dialplan_contexts].columns.include? :server_id + end +end diff --git a/lib/fxc/import.rb b/lib/fxc/import.rb index fb8a7ff..ae90dd4 100644 --- a/lib/fxc/import.rb +++ b/lib/fxc/import.rb @@ -1,192 +1,193 @@ require 'tsort' require 'pp' require 'nokogiri' require 'makura' class Hash include TSort alias tsort_each_node each_key def tsort_each_child(node, &block) fetch(node).each(&block) end end module FXC module ConverterHelper module_function def parse(filename, parent = nil, deps = {}, xmls = {}) deps[filename] ||= [] node = Nokogiri::XML(File.read(filename)) xmls[filename] = node node.xpath('//X-PRE-PROCESS[@cmd="include"]').each do |inc| glob = File.expand_path(inc[:data], File.dirname(filename)) Dir.glob(glob){|path| deps[path] ||= [] deps[filename] << path deps.tsort # check for cyclic dependencies. parse(path, node, deps, xmls).children.each do |child| inc.parent.add_child(child) end } end if parent node.xpath('/include') else conf = node.xpath('/configuration') conf.empty? ? node : conf end end # Find the FreeSWITCH install path if running FSR on a local box with FreeSWITCH installed. # This will enable sqlite db access def find_freeswitch_install fs_install_paths = [ ENV["HOME"], ENV["HOME"] + "/freeswitch", "/usr/local/freeswitch", "/opt/freeswitch", "/usr/freeswitch", "/home/freeswitch/freeswitch", '/home/freeswitch' ] fs_install_paths.unshift(ENV['FREESWITCH_PATH']) if ENV['FREESWITCH_PATH'] good_path = fs_install_paths.find do |fs_path| warn("#{fs_path} is not a directory!") unless File.directory?(fs_path) warn("#{fs_path} is not readable by this user!") unless File.readable?(fs_path) fs_path.to_s if Dir["#{fs_path}/{conf,db}/"].size == 2 end unless good_path warn("No FreeSWITCH install found, database and configuration functionality disabled") warn "You can specify the path to FreeSWITCH with the FREESWITCH_PATH env variable" exit 1 end good_path end end class Converter def initialize(root = ConverterHelper.find_freeswitch_install, options = {}) @root = File.expand_path(root) @opts = { couch_server: 'http://jimmy:5984', couch_db: 'fxc_spec', couch_preserve_db: false, couch_no_create: false, server: %x{hostname}.strip, }.merge(options) end def convert(tree) case tree when :configuration convert_configuration when :directory convert_directory when :dialplan convert_dialplan end end def couchdb return @couchdb if @couchdb Makura::Model.server = @opts[:couch_server] Makura::Model.database = @opts[:couch_db] Makura::Model.database.destroy! unless @opts[:couch_preserve_db] Makura::Model.database.create unless @opts[:couch_no_create] @couchdb = Makura::Model.database end def convert_configuration require_relative 'import/configuration' read_configuration do |mod, xml| doc = { name: "#{mod}.conf", database: nil, '_id' => "#{@opts[:server]}_#{mod}.conf", } catch :ignore do puts "Attempt conversion of #{mod}" if Configuration.respond_to?(mod) Configuration.send(mod, xml, doc) rec = couchdb.save(doc) p rec # pp DB[doc['_id']] else raise "No converter for #{mod}" end end end end def read_configuration Nokogiri::XML(File.read(modules_xml)).xpath('/configuration/modules/load[@module]').each do |tag| mod = tag['module'].sub(/^mod_/, '') mod_xml = File.join(File.dirname(modules_xml), "#{mod}.conf.xml") begin xml = ConverterHelper.parse(mod_xml) rescue Errno::ENOENT warn "No config file found for #{mod_xml}" next end yield mod, xml end end def modules_xml File.join(@root, '/conf/autoload_configs/modules.conf.xml') end def convert_dialplan require_relative 'import/dialplan' read_dialplan do |xml| - xml.xpath('context').each do |context| + xml.xpath('//context').each do |context| + p "converting context #{context}" # do stuff with that FXC::Converter::Dialplan.parse_context(context, @opts[:server]) end end end def read_dialplan(&block) Dir.glob(@root + '/conf/dialplan/*.xml').each do |context_xml| # read each file and parse it into its full xml (include x-pre-process) yield ConverterHelper.parse(context_xml) end end def convert_directory require_relative 'import/directory' read_directory do |xml| xml.xpath('include/domain').each do |domain| # do stuff with that doc = {server: @opts[:server]} FXC::Converter::Directory.parse_domain(domain, doc, couchdb) rec = couchdb.save(doc) p rec end end end def read_directory(&block) Dir.glob(@root + '/conf/directory/*.xml').each do |directory_xml| # read each file and parse it into its full xml (include x-pre-process) yield ConverterHelper.parse(directory_xml) end end end end if __FILE__ == $0 converter = FXC::Converter.new #converter.convert(:configuration) - converter.convert(:directory) - #converter.convert(:dialplan) + #converter.convert(:directory) + converter.convert(:dialplan) end diff --git a/lib/fxc/import/dialplan.rb b/lib/fxc/import/dialplan.rb index e13bc5a..e7f19b6 100644 --- a/lib/fxc/import/dialplan.rb +++ b/lib/fxc/import/dialplan.rb @@ -1,77 +1,77 @@ require_relative '../import' -require_relative '../../../spec/db_helper' # comment this out for production +#require_relative '../../../spec/db_helper' # comment this out for production require_relative '../../../model/init' module FXC class Converter module Dialplan module_function def parse_context(node, server) name = node[:name] puts "Parsing context #{name} for server #{server}" # Add the context server = FXC::Server.find_or_create(:name => server) context = FXC::Context.find_or_create(:server_id => server.id, :name => name) node.xpath("extension").each do |ext| parse_extension ext, context end end def parse_extension(node, context) name = node[:name] puts "Parsing extension #{name}" # Add the extension extension = FXC::Extension.find_or_create( :context_id => context.id, :name => name, :continue => node[:continue] ) node.xpath("condition").each do |cond| parse_condition cond, extension end end def parse_condition(node, extension) field, expression = node[:field], node[:expression] puts "Parsing condition #{field} => #{expression}" # Add the condition condition = FXC::Condition.find_or_create( :extension_id => extension.id, :matcher => field, :expression => expression, :break => node[:break], :name => node[:name], :description => node[:description] ) node.xpath("action").each do |act| parse_action act, condition end node.xpath("anti-action").each do |act| parse_anti_action act, condition end end def parse_action(node, condition) app, data = node[:application], node[:data] puts "Parsing action #{app} => #{data}" # Add the action FXC::Action.find_or_create( :condition_id => condition.id, :application => app, :data => data ) end def parse_anti_action(node, condition) app, data = node[:application], node[:data] puts "Parsing action #{app} => #{data}" FXC::AntiAction.find_or_create( :condition_id => condition.id, :application => app, :data => data ) end end end end diff --git a/model/init.rb b/model/init.rb index c3266ed..8e6ed83 100644 --- a/model/init.rb +++ b/model/init.rb @@ -1,25 +1,26 @@ # Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> # Distributed under the terms of the MIT license. # The full text can be found in the LICENSE file included with this software # require_relative '../lib/fxc' require FXC::LIBROOT/:fxc/:db raise "No DB Available" unless FXC.db require 'makura' Makura::Model.database = 'fxc' # Here go your requires for models: -require_relative 'user' -require_relative 'user_variable' -require_relative 'target' -require_relative 'did' -require_relative 'provider' +#require_relative 'user' +#require_relative 'user_variable' +#require_relative 'target' +#require_relative 'did' +#require_relative 'provider' +require_relative 'server' require_relative 'context' -require_relative 'voicemail' +#require_relative 'voicemail' #require "sequel_orderable" require_relative 'extension' require_relative 'condition' require_relative 'action' require_relative 'anti_action' require_relative 'configuration' diff --git a/model/server.rb b/model/server.rb new file mode 100644 index 0000000..36b3b71 --- /dev/null +++ b/model/server.rb @@ -0,0 +1,8 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +class FXC::Server < Sequel::Model + set_dataset FXC.db[:servers] + one_to_many :contexts, :class => 'FXC::Context' +end
bougyman/fxc
8c506ccb18b92891f02ac58baa89ba64b08f84a0
pointed MIGRATION_ROOT at new migrations path
diff --git a/lib/fxc.rb b/lib/fxc.rb index e2b234e..b89e52c 100644 --- a/lib/fxc.rb +++ b/lib/fxc.rb @@ -1,26 +1,26 @@ # Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> # Distributed under the terms of the MIT license. # The full text can be found in the LICENSE file included with this software # require "pathname" class Pathname def /(other) join(other.to_s) end end $LOAD_PATH.unshift(File.expand_path("../", __FILE__)) module FXC ROOT = Pathname($LOAD_PATH.first).join("..").expand_path LIBROOT = ROOT/:lib - MIGRATION_ROOT = ROOT/:db/:migrations + MIGRATION_ROOT = ROOT/:db/:migrate MODEL_ROOT = ROOT/:model SPEC_HELPER_PATH = ROOT/:spec def self.load_fsr require "fsr" rescue LoadError require "rubygems" require "fsr" end end
bougyman/fxc
41f0e2c2295d430dfccda0dbe8c35877720fca0a
moved needed migrations for new design (conf/directory in couchdb) to db/migrate, left originals for reference purposes in db/migrations
diff --git a/db/migrate/001_create_contexts.rb b/db/migrate/001_create_contexts.rb new file mode 100644 index 0000000..8dbf714 --- /dev/null +++ b/db/migrate/001_create_contexts.rb @@ -0,0 +1,18 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +Class.new Sequel::Migration do + def up + create_table(:dialplan_contexts) do + primary_key :id + String :name, :size => 40 + String :description + end unless tables.include? :dialplan_contexts + execute "COMMENT ON TABLE dialplan_contexts IS 'Storage for Dialplan Contexts'" + end + + def down + remove_table(:dialplan_contexts) if tables.include? :dialplan_contexts + end +end diff --git a/db/migrate/002_create_extensions.rb b/db/migrate/002_create_extensions.rb new file mode 100644 index 0000000..9de33ad --- /dev/null +++ b/db/migrate/002_create_extensions.rb @@ -0,0 +1,25 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +Class.new Sequel::Migration do + def up + create_table(:fs_extensions) do + primary_key :id + String :name + String :description + TrueClass :continue + Integer :position + foreign_key :context_id, :dialplan_contexts, :on_update => :cascade + end unless FXC.db.tables.include? :fs_extensions + execute "COMMENT ON TABLE fs_extensions IS 'Storage for Freeswitch Extensions'" + execute "COMMENT ON COLUMN fs_extensions.name IS 'The name of this extension'" + execute "COMMENT ON COLUMN fs_extensions.description IS 'Description of this extension'" + execute "COMMENT ON COLUMN fs_extensions.continue IS 'Whether to continue after running commands in this extension'" + execute "COMMENT ON COLUMN fs_extensions.context_id IS 'The the reference to context this extension responds to'" + end + + def down + drop_table(:fs_extensions) if FXC.db.tables.include? :fs_extensions + end +end diff --git a/db/migrate/003_create_conditions.rb b/db/migrate/003_create_conditions.rb new file mode 100644 index 0000000..1fffad6 --- /dev/null +++ b/db/migrate/003_create_conditions.rb @@ -0,0 +1,30 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +Class.new Sequel::Migration do + def up + create_table(:fs_conditions) do + primary_key :id + String :name + String :description + String :matcher + String :expression + Integer :position + String :break + foreign_key :extension_id, :fs_extensions, :on_delete => :cascade, :on_update => :cascade + end unless FXC.db.tables.include? :fs_conditions + execute "COMMENT ON TABLE fs_conditions IS 'Storage for Dialplan conditions'" + execute "COMMENT ON COLUMN fs_conditions.name IS 'The name of this condition'" + execute "COMMENT ON COLUMN fs_conditions.description IS 'Description of this condition'" + execute "COMMENT ON COLUMN fs_conditions.matcher IS 'Which Field to match on'" + execute "COMMENT ON COLUMN fs_conditions.expression IS 'The expression to match with'" + execute "COMMENT ON COLUMN fs_conditions.position IS 'The order to match in'" + execute "COMMENT ON COLUMN fs_conditions.break IS 'Whether to stop after this condition is met (or not)'" + execute "COMMENT ON COLUMN fs_conditions.extension_id IS 'The associated extension record'" + end + + def down + drop_table(:fs_conditions) if FXC.db.tables.include? :fs_conditions + end +end diff --git a/db/migrate/004_create_actions.rb b/db/migrate/004_create_actions.rb new file mode 100644 index 0000000..55a93ea --- /dev/null +++ b/db/migrate/004_create_actions.rb @@ -0,0 +1,28 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +Class.new Sequel::Migration do + def up + create_table(:fs_actions) do + primary_key :id + String :name + String :description + String :application + String :data + Integer :position + foreign_key :condition_id, :fs_conditions, :on_update => :cascade, :on_delete => :cascade + end unless FXC.db.tables.include? :fs_actions + execute "COMMENT ON TABLE fs_actions IS 'Storage for Dialplan actions'" + execute "COMMENT ON COLUMN fs_actions.name IS 'The name of this action'" + execute "COMMENT ON COLUMN fs_actions.description IS 'Description of this action'" + execute "COMMENT ON COLUMN fs_actions.application IS 'Which application to run'" + execute "COMMENT ON COLUMN fs_actions.data IS 'The arguments to send to the application'" + execute "COMMENT ON COLUMN fs_actions.position IS 'The order to perform actions in'" + execute "COMMENT ON COLUMN fs_actions.condition_id IS 'The associated condition record'" + end + + def down + drop_table(:fs_actions) if FXC.db.tables.include? :fs_actions + end +end diff --git a/db/migrate/005_create_anti_actions.rb b/db/migrate/005_create_anti_actions.rb new file mode 100644 index 0000000..25cba4d --- /dev/null +++ b/db/migrate/005_create_anti_actions.rb @@ -0,0 +1,28 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +Class.new Sequel::Migration do + def up + create_table(:fs_anti_actions) do + primary_key :id + String :name + String :description + String :application + String :data + Integer :position, :null => false + foreign_key :condition_id, :fs_conditions, :on_update => :cascade, :on_delete => :cascade + end unless FXC.db.tables.include? :fs_anti_actions + execute "COMMENT ON TABLE fs_anti_actions IS 'Storage for Dialplan actions'" + execute "COMMENT ON COLUMN fs_anti_actions.name IS 'The name of this action'" + execute "COMMENT ON COLUMN fs_anti_actions.description IS 'Description of this action'" + execute "COMMENT ON COLUMN fs_anti_actions.application IS 'Which application to run'" + execute "COMMENT ON COLUMN fs_anti_actions.data IS 'The arguments to send to the application'" + execute "COMMENT ON COLUMN fs_anti_actions.position IS 'The order to perform actions in'" + execute "COMMENT ON COLUMN fs_anti_actions.condition_id IS 'The associated condition record'" + end + + def down + drop_table(:fs_anti_actions) if FXC.db.tables.include? :fs_anti_actions + end +end diff --git a/db/migrate/006_create_servers.rb b/db/migrate/006_create_servers.rb new file mode 100644 index 0000000..071bda6 --- /dev/null +++ b/db/migrate/006_create_servers.rb @@ -0,0 +1,18 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +Class.new Sequel::Migration do + def up + create_table(:servers) do + primary_key :id + String :name + String :description + end unless tables.include? :servers + execute "COMMENT ON TABLE servers IS 'List of freeswitch servers'" + end + + def down + remove_table(:servers) if tables.include? :servers + end +end
bougyman/fxc
6a0265d9e02fc944b71a31f0ccf17dda90d3ac05
removed group document from directory, instead use an array of "groups" on a user document
diff --git a/lib/fxc/import.rb b/lib/fxc/import.rb index f52656b..fb8a7ff 100644 --- a/lib/fxc/import.rb +++ b/lib/fxc/import.rb @@ -1,192 +1,192 @@ require 'tsort' require 'pp' require 'nokogiri' require 'makura' class Hash include TSort alias tsort_each_node each_key def tsort_each_child(node, &block) fetch(node).each(&block) end end module FXC module ConverterHelper module_function def parse(filename, parent = nil, deps = {}, xmls = {}) deps[filename] ||= [] node = Nokogiri::XML(File.read(filename)) xmls[filename] = node node.xpath('//X-PRE-PROCESS[@cmd="include"]').each do |inc| glob = File.expand_path(inc[:data], File.dirname(filename)) Dir.glob(glob){|path| deps[path] ||= [] deps[filename] << path deps.tsort # check for cyclic dependencies. parse(path, node, deps, xmls).children.each do |child| inc.parent.add_child(child) end } end if parent node.xpath('/include') else conf = node.xpath('/configuration') conf.empty? ? node : conf end end # Find the FreeSWITCH install path if running FSR on a local box with FreeSWITCH installed. # This will enable sqlite db access def find_freeswitch_install fs_install_paths = [ ENV["HOME"], ENV["HOME"] + "/freeswitch", "/usr/local/freeswitch", "/opt/freeswitch", "/usr/freeswitch", "/home/freeswitch/freeswitch", '/home/freeswitch' ] fs_install_paths.unshift(ENV['FREESWITCH_PATH']) if ENV['FREESWITCH_PATH'] good_path = fs_install_paths.find do |fs_path| warn("#{fs_path} is not a directory!") unless File.directory?(fs_path) warn("#{fs_path} is not readable by this user!") unless File.readable?(fs_path) fs_path.to_s if Dir["#{fs_path}/{conf,db}/"].size == 2 end unless good_path warn("No FreeSWITCH install found, database and configuration functionality disabled") warn "You can specify the path to FreeSWITCH with the FREESWITCH_PATH env variable" exit 1 end good_path end end class Converter def initialize(root = ConverterHelper.find_freeswitch_install, options = {}) @root = File.expand_path(root) @opts = { couch_server: 'http://jimmy:5984', couch_db: 'fxc_spec', couch_preserve_db: false, couch_no_create: false, server: %x{hostname}.strip, }.merge(options) end def convert(tree) case tree when :configuration convert_configuration when :directory convert_directory when :dialplan convert_dialplan end end def couchdb return @couchdb if @couchdb Makura::Model.server = @opts[:couch_server] Makura::Model.database = @opts[:couch_db] Makura::Model.database.destroy! unless @opts[:couch_preserve_db] Makura::Model.database.create unless @opts[:couch_no_create] @couchdb = Makura::Model.database end def convert_configuration require_relative 'import/configuration' read_configuration do |mod, xml| doc = { name: "#{mod}.conf", database: nil, '_id' => "#{@opts[:server]}_#{mod}.conf", } catch :ignore do puts "Attempt conversion of #{mod}" if Configuration.respond_to?(mod) Configuration.send(mod, xml, doc) rec = couchdb.save(doc) p rec # pp DB[doc['_id']] else raise "No converter for #{mod}" end end end end def read_configuration Nokogiri::XML(File.read(modules_xml)).xpath('/configuration/modules/load[@module]').each do |tag| mod = tag['module'].sub(/^mod_/, '') mod_xml = File.join(File.dirname(modules_xml), "#{mod}.conf.xml") begin xml = ConverterHelper.parse(mod_xml) rescue Errno::ENOENT warn "No config file found for #{mod_xml}" next end yield mod, xml end end def modules_xml File.join(@root, '/conf/autoload_configs/modules.conf.xml') end def convert_dialplan require_relative 'import/dialplan' read_dialplan do |xml| xml.xpath('context').each do |context| # do stuff with that FXC::Converter::Dialplan.parse_context(context, @opts[:server]) end end end def read_dialplan(&block) Dir.glob(@root + '/conf/dialplan/*.xml').each do |context_xml| # read each file and parse it into its full xml (include x-pre-process) yield ConverterHelper.parse(context_xml) end end def convert_directory require_relative 'import/directory' read_directory do |xml| xml.xpath('include/domain').each do |domain| # do stuff with that doc = {server: @opts[:server]} FXC::Converter::Directory.parse_domain(domain, doc, couchdb) rec = couchdb.save(doc) p rec end end end def read_directory(&block) Dir.glob(@root + '/conf/directory/*.xml').each do |directory_xml| # read each file and parse it into its full xml (include x-pre-process) yield ConverterHelper.parse(directory_xml) end end end end if __FILE__ == $0 converter = FXC::Converter.new - converter.convert(:configuration) + #converter.convert(:configuration) converter.convert(:directory) #converter.convert(:dialplan) end diff --git a/lib/fxc/import/directory.rb b/lib/fxc/import/directory.rb index 2ac2ee2..556b264 100644 --- a/lib/fxc/import/directory.rb +++ b/lib/fxc/import/directory.rb @@ -1,335 +1,330 @@ require 'makura' require 'pp' module FXC class Converter module Directory module_function def parse_domain(node, doc, couchdb) doc[:name] = domain = node[:name] server = doc[:server] doc["_id"] = "%s_%s.domain" % [server, domain] doc[:type] = "directory" doc[:params] = params = {} node.xpath('params/param').each do |param| params[param[:name]] = param[:value] end doc[:variables] = variables = {} node.xpath('variables/variable').each do |variable| variables[variable[:name]] = variable[:value] end doc[:groups] = groups = [] node.xpath('groups/group').each do |group| groups << group[:name] - grp = {server: server, - domain: domain, - name: group[:name], - type: "group", - members: []} - grp["_id"] = "%s_%s_%s.group" % [server, domain, grp[:name]] - #couchdb.save(grp) group.xpath('users/user').each do |user| if user[:type] == "pointer" - grp[:members] << user[:id] + u_id = "%s_%s_%s.user" % [server, domain, user[:id]] + begin + u = couchdb[u_id] + u["groups"] << group[:name] unless u["groups"].include?(group[:name]) + couchdb.save u + rescue Makura::Error::ResourceNotFound => e + warn "Pointer record found for non-existent user #{u_id}" + end else - u = parse_user(user, grp) - grp[:members] << u[:id] unless grp[:members].include?(u[:id]) - rec = couchdb.save(u) + rec = couchdb.save parse_user(user, group[:name], server, domain) p rec end end - rec = couchdb.save(grp) - p rec end doc end - def parse_user(node, group_doc) + def parse_user(node, group, server, domain) #users[node[:id]] = user = {} - server, domain, group = group_doc[:server], group_doc[:domain], group_doc[:name] - user = {type: 'user', server: server, group: group, domain: domain} + user = {type: 'user', server: server, groups: [group], domain: domain} user[:id] = node[:id] - user["_id"] = "%s_%s_%s_%s.user" % [server, domain, group, user[:id]] + user["_id"] = "%s_%s_%s.user" % [server, domain, user[:id]] # node is a user, user is the hash representation user[:params] = params = {} node.attributes.each do |key, value| params[key] = value unless key == "id" end node.xpath('params/param').each do |param| params[param[:name]] = param[:value] end user[:variables] = variables = {} node.xpath('variables/variable').each do |variable| variables[variable[:name]] = variable[:value] end user[:buttons] = buttons = {} node.xpath('skinny/buttons/button').each do |button| # p button[:position] buttons[button[:position]] = sb = {} button.attributes.each do |key, attribute| sb[key] = attribute.value unless key == "position" end end user[:gateways] = gateways = {} node.xpath('gateways/gateway').each do |gateway| gateways[gateway[:id]] = gateway[:id] gateways[:params] = gparams = {} node.xpath('param').each do |param| gparams[param[:name]] = param[:value] end end user end def default(xml, doc = {}) doc[:params] = params = {} doc[:groups] = groups = {} doc[:variables] = variables = {} doc[:name] = xml[:name] xml.xpath('params/param').each do |param| params[param[:name]] = param[:value] end xml.xpath('variables/variable').each do |variable| variables[variable[:name]] = variable[:value] end doc[:groups] = groups = {} xml.xpath('groups/group').each do |group| p group[:name] groups[group[:name]] = us = {} group.xpath('users/user').each do |user| p user us[user[:id]] = user[:type] end end p doc.to_s doc end =begin def xml_curl(xml, doc) doc[:bindings] = bindings = {} xml.xpath('bindings/binding').each do |binding| bindings[binding[:name]] = params = {} binding.xpath('param').each do |param| if param[:name] == 'gateway-url' params[:config] = { 'gateway-url' => param[:value], 'bindings' => param[:bindings], } else params[param[:name]] = param[:value] end end end end def console(xml, doc) doc[:mappings] = mappings = {} xml.xpath('mappings/map').each do |map| mappings[map[:name]] = map[:value] end _settings(xml, doc) end def logfile(xml, doc) doc[:profiles] = profiles = {} xml.xpath('profiles/profile').each do |profile| profiles[profile[:name]] = ph = {} _settings(profile, ph) ph[:mappings] = pm = {} profile.xpath('mappings/map').each do |map| pm[map[:name]] = map[:value].scan(/[^\s,]+/) end end _settings(xml, doc) end def enum(xml, doc) _settings(xml, doc) doc[:routes] = routes = [] xml.xpath('routes/route').each do |route| routes << route.attributes end end def xml_cdr(xml, doc) doc[:description] = 'XML CDR cURL Logger' _settings(xml, doc) end def cdr_csv(xml, doc) doc[:description] = 'CDR CSV Format' _settings(xml, doc) doc[:templates] = templates = {} xml.xpath('templates/template').each do |template| templates[template[:name]] = template.inner_text end end def event_socket(xml, doc) doc[:description] = 'Socket Client' _settings(xml, doc) end def sofia(xml, doc) doc[:global_settings] = global_settings = {} xml.xpath('global_settings/param').each do |param| global_settings[param[:name]] = param[:value] end doc[:profiles] = profiles = {} xml.xpath('profiles/profile').each do |profile| profiles[profile[:name]] = ph = {} _settings(profile, ph) ph[:aliases] = profile.xpath('aliases').map{|a| a[:name] } ph[:domains] = domains = {} profile.xpath('domains/domain').each do |domain| domains[domain[:name]] = { alias: domain[:alias] == 'true', parse: domain[:parse] == 'true', } end ph[:gateways] = gateways = {} xml.xpath('gateways/gateway').each do |gateway| gateways[gateway[:name]] = gh = {} gateway.xpath('param').each do |param| gh[param[:name]] = param[:value] end end end end def conference(xml, doc) doc[:advertise] = advertise = {} xml.xpath('advertise/room').each do |room| advertise[room[:name]] = room[:status] end doc['caller-controls'] = caller_controls = {} xml.xpath('caller-controls/group').each do |group| caller_controls[group[:name]] = gh = {} group.xpath('control').each do |control| gh[control[:action]] = control[:digits] end end doc['profiles'] = profiles = {} xml.xpath('profiles/profile').each do |profile| profiles[profile[:name]] = ph = {} profile.xpath('param').each do |param| ph[param[:name]] = param[:value] end end end def fifo(xml, doc) _settings(xml, doc) doc['fifos'] = fifos = {} xml.xpath('fifos/fifo').each do |fifo| fifos[fifo[:name]] = fh = {} fifo.attributes.each do |key, attribute| fh[key] = attribute.value unless key == "name" end fh[:members] = members = {} fifo.xpath('member').each do |member| members[member.text] = mh = {} member.attributes.each do |key, attribute| mh[key] = attribute.value end end end end def db(xml, doc) _settings(xml, doc) end def hash(xml, doc) doc[:remotes] = remotes = {} xml.xpath('remotes/remote').each do |remote| remotes[remote[:name]] = rh = {} remote.attributes.each do |key, attribute| rh[key] = attribute.value unless key == 'name' end end end def local_stream(xml, doc) doc[:directories] = directories = {} xml.xpath('directory').each do |directory| directories[directory[:name]] = dh = {} dh[:path] = directory[:path] directory.xpath('param').each do |param| dh[param[:name]] = param[:value] end end end def spandsp(xml, doc) doc[:descriptors] = descriptors = {} xml.xpath('descriptors/descriptor').each do |descriptor| descriptors[descriptor[:name]] = dh = {} descriptor.xpath('tone').each do |tone| dh[tone[:name]] = ta = [] tone.xpath('element').each do |element| ta << tah = {} element.attributes.each do |key, attribute| tah[key] = attribute.value.to_i end end end end end def voicemail(xml, doc) _settings(xml, doc) doc[:profiles] = profiles = {} xml.xpath('profiles/profile').each do |profile| profiles[profile[:name]] = ph = {} profile.xpath('param').each do |param| ph[param[:name]] = param[:value] end ph[:email] = email = {} profile.xpath('email/param').each do |param| email[param[:name]] = param[:value] end end end def _settings(xml, doc) doc[:settings] = settings = {} xml.xpath('settings/param').each do |param| settings[param[:name]] = param[:value] end end =end end end end
bougyman/fxc
56b0f166f8ffe18f6d7a6c179b6a102cb1c6b69c
Sane version before integration with CouchDB
diff --git a/db/migrations/028_create_servers.rb b/db/migrations/028_create_servers.rb new file mode 100644 index 0000000..071bda6 --- /dev/null +++ b/db/migrations/028_create_servers.rb @@ -0,0 +1,18 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +Class.new Sequel::Migration do + def up + create_table(:servers) do + primary_key :id + String :name + String :description + end unless tables.include? :servers + execute "COMMENT ON TABLE servers IS 'List of freeswitch servers'" + end + + def down + remove_table(:servers) if tables.include? :servers + end +end diff --git a/import_couch.rb b/import_couch.rb deleted file mode 100644 index 8387217..0000000 --- a/import_couch.rb +++ /dev/null @@ -1,286 +0,0 @@ -require 'makura' -require 'tsort' -require 'pp' -require 'nokogiri' - -class Hash - include TSort - alias tsort_each_node each_key - def tsort_each_child(node, &block) - fetch(node).each(&block) - end -end - -module Convert - module_function - - def xml_curl(xml, doc) - doc[:bindings] = bindings = {} - - xml.xpath('bindings/binding').each do |binding| - bindings[binding[:name]] = params = {} - - binding.xpath('param').each do |param| - if param[:name] == 'gateway-url' - params[:config] = { - 'gateway-url' => param[:value], - 'bindings' => param[:bindings], - } - else - params[param[:name]] = param[:value] - end - end - end - end - - def console(xml, doc) - doc[:mappings] = mappings = {} - xml.xpath('mappings/map').each do |map| - mappings[map[:name]] = map[:value] - end - - _settings(xml, doc) - end - - def logfile(xml, doc) - doc[:profiles] = profiles = {} - xml.xpath('profiles/profile').each do |profile| - profiles[profile[:name]] = ph = {} - _settings(profile, ph) - ph[:mappings] = pm = {} - profile.xpath('mappings/map').each do |map| - pm[map[:name]] = map[:value].scan(/[^\s,]+/) - end - end - - _settings(xml, doc) - end - - def enum(xml, doc) - _settings(xml, doc) - doc[:routes] = routes = [] - xml.xpath('routes/route').each do |route| - routes << route.attributes - end - end - - def xml_cdr(xml, doc) - doc[:description] = 'XML CDR cURL Logger' - _settings(xml, doc) - end - - def cdr_csv(xml, doc) - doc[:description] = 'CDR CSV Format' - _settings(xml, doc) - doc[:templates] = templates = {} - xml.xpath('templates/template').each do |template| - templates[template[:name]] = template.inner_text - end - end - - def event_socket(xml, doc) - doc[:description] = 'Socket Client' - _settings(xml, doc) - end - - def sofia(xml, doc) - doc[:global_settings] = global_settings = {} - xml.xpath('global_settings/param').each do |param| - global_settings[param[:name]] = param[:value] - end - - doc[:profiles] = profiles = {} - xml.xpath('profiles/profile').each do |profile| - profiles[profile[:name]] = ph = {} - _settings(profile, ph) - - ph[:aliases] = profile.xpath('aliases').map{|a| a[:name] } - ph[:domains] = domains = {} - profile.xpath('domains/domain').each do |domain| - domains[domain[:name]] = { - alias: domain[:alias] == 'true', - parse: domain[:parse] == 'true', - } - end - - ph[:gateways] = gateways = {} - - xml.xpath('gateways/gateway').each do |gateway| - gateways[gateway[:name]] = gh = {} - gateway.xpath('param').each do |param| - gh[param[:name]] = param[:value] - end - end - end - end - - def conference(xml, doc) - doc[:advertise] = advertise = {} - xml.xpath('advertise/room').each do |room| - advertise[room[:name]] = room[:status] - end - - doc['caller-controls'] = caller_controls = {} - xml.xpath('caller-controls/group').each do |group| - caller_controls[group[:name]] = gh = {} - group.xpath('control').each do |control| - gh[control[:action]] = control[:digits] - end - end - - doc['profiles'] = profiles = {} - xml.xpath('profiles/profile').each do |profile| - profiles[profile[:name]] = ph = {} - profile.xpath('param').each do |param| - ph[param[:name]] = param[:value] - end - end - end - - def fifo(xml, doc) - _settings(xml, doc) - - doc['fifos'] = fifos = {} - xml.xpath('fifos/fifo').each do |fifo| - fifos[fifo[:name]] = fh = {} - fifo.attributes.each do |key, attribute| - fh[key] = attribute.value unless key == "name" - end - - fh[:members] = members = {} - fifo.xpath('member').each do |member| - members[member.text] = mh = {} - member.attributes.each do |key, attribute| - mh[key] = attribute.value - end - end - end - end - - def db(xml, doc) - _settings(xml, doc) - end - - def hash(xml, doc) - doc[:remotes] = remotes = {} - xml.xpath('remotes/remote').each do |remote| - remotes[remote[:name]] = rh = {} - remote.attributes.each do |key, attribute| - rh[key] = attribute.value unless key == 'name' - end - end - end - - def local_stream(xml, doc) - doc[:directories] = directories = {} - xml.xpath('directory').each do |directory| - directories[directory[:name]] = dh = {} - dh[:path] = directory[:path] - directory.xpath('param').each do |param| - dh[param[:name]] = param[:value] - end - end - end - - def spandsp(xml, doc) - doc[:descriptors] = descriptors = {} - xml.xpath('descriptors/descriptor').each do |descriptor| - descriptors[descriptor[:name]] = dh = {} - descriptor.xpath('tone').each do |tone| - dh[tone[:name]] = ta = [] - tone.xpath('element').each do |element| - ta << tah = {} - element.attributes.each do |key, attribute| - tah[key] = attribute.value.to_i - end - end - end - end - end - - def voicemail(xml, doc) - _settings(xml, doc) - - doc[:profiles] = profiles = {} - xml.xpath('profiles/profile').each do |profile| - profiles[profile[:name]] = ph = {} - - profile.xpath('param').each do |param| - ph[param[:name]] = param[:value] - end - - ph[:email] = email = {} - profile.xpath('email/param').each do |param| - email[param[:name]] = param[:value] - end - end - end - - def _settings(xml, doc) - doc[:settings] = settings = {} - xml.xpath('settings/param').each do |param| - settings[param[:name]] = param[:value] - end - end - - def _parse(filename, parent = nil, deps = {}, xmls = {}) - deps[filename] ||= [] - - node = Nokogiri::XML(File.read(filename)) - xmls[filename] = node - node.xpath('//X-PRE-PROCESS[@cmd="include"]').each do |inc| - glob = File.expand_path(inc[:data], File.dirname(filename)) - - Dir.glob(glob){|path| - deps[path] ||= [] - deps[filename] << path - deps.tsort # check for cyclic dependencies. - - child = _parse(path, node, deps, xmls) - inc.parent.add_child(child) - } - end - - if parent - node.xpath('/include') - else - node.xpath('/configuration') - end - end -end - -Makura::Model.server = 'http://jimmy:5984' -Makura::Model.database = "fxc_spec" -Makura::Model.database.destroy! -Makura::Model.database.create -DB = Makura::Model.database - -modules_xml = File.expand_path('~/conf/autoload_configs/modules.conf.xml') -Nokogiri::XML(File.read(modules_xml)).xpath('/configuration/modules/load[@module]').each do |tag| - mod = tag['module'].sub(/^mod_/, '') - mod_xml = File.join(File.dirname(modules_xml), "#{mod}.conf.xml") - begin - xml = Convert._parse(mod_xml) - rescue Errno::ENOENT - warn "No config file found for #{mod_xml}" - next - end - - doc = { - name: "#{mod}.conf", - database: nil, - '_id' => "#{mod}.conf", - } - - catch :ignore do - puts "Attempt conversion of #{mod}" - if Convert.respond_to?(mod) - Convert.send(mod, xml, doc) - DB.save(doc) - - # pp DB[doc['_id']] - else - raise "No converter for #{mod}" - end - end -end diff --git a/lib/fxc/import.rb b/lib/fxc/import.rb new file mode 100644 index 0000000..f52656b --- /dev/null +++ b/lib/fxc/import.rb @@ -0,0 +1,192 @@ +require 'tsort' +require 'pp' +require 'nokogiri' +require 'makura' + +class Hash + include TSort + alias tsort_each_node each_key + def tsort_each_child(node, &block) + fetch(node).each(&block) + end +end + +module FXC + module ConverterHelper + module_function + def parse(filename, parent = nil, deps = {}, xmls = {}) + deps[filename] ||= [] + + node = Nokogiri::XML(File.read(filename)) + xmls[filename] = node + node.xpath('//X-PRE-PROCESS[@cmd="include"]').each do |inc| + glob = File.expand_path(inc[:data], File.dirname(filename)) + + Dir.glob(glob){|path| + deps[path] ||= [] + deps[filename] << path + deps.tsort # check for cyclic dependencies. + + parse(path, node, deps, xmls).children.each do |child| + inc.parent.add_child(child) + end + } + end + + if parent + node.xpath('/include') + else + conf = node.xpath('/configuration') + conf.empty? ? node : conf + end + end + + # Find the FreeSWITCH install path if running FSR on a local box with FreeSWITCH installed. + # This will enable sqlite db access + def find_freeswitch_install + fs_install_paths = [ + ENV["HOME"], ENV["HOME"] + "/freeswitch", + "/usr/local/freeswitch", "/opt/freeswitch", "/usr/freeswitch", + "/home/freeswitch/freeswitch", '/home/freeswitch' + ] + fs_install_paths.unshift(ENV['FREESWITCH_PATH']) if ENV['FREESWITCH_PATH'] + good_path = fs_install_paths.find do |fs_path| + warn("#{fs_path} is not a directory!") unless File.directory?(fs_path) + warn("#{fs_path} is not readable by this user!") unless File.readable?(fs_path) + fs_path.to_s if Dir["#{fs_path}/{conf,db}/"].size == 2 + end + + unless good_path + warn("No FreeSWITCH install found, database and configuration functionality disabled") + warn "You can specify the path to FreeSWITCH with the FREESWITCH_PATH env variable" + exit 1 + end + + good_path + end + end + + class Converter + def initialize(root = ConverterHelper.find_freeswitch_install, options = {}) + @root = File.expand_path(root) + @opts = { + couch_server: 'http://jimmy:5984', + couch_db: 'fxc_spec', + couch_preserve_db: false, + couch_no_create: false, + server: %x{hostname}.strip, + }.merge(options) + end + + def convert(tree) + case tree + when :configuration + convert_configuration + when :directory + convert_directory + when :dialplan + convert_dialplan + end + end + + def couchdb + return @couchdb if @couchdb + Makura::Model.server = @opts[:couch_server] + Makura::Model.database = @opts[:couch_db] + Makura::Model.database.destroy! unless @opts[:couch_preserve_db] + Makura::Model.database.create unless @opts[:couch_no_create] + @couchdb = Makura::Model.database + end + + def convert_configuration + + require_relative 'import/configuration' + + read_configuration do |mod, xml| + doc = { + name: "#{mod}.conf", + database: nil, + '_id' => "#{@opts[:server]}_#{mod}.conf", + } + + catch :ignore do + puts "Attempt conversion of #{mod}" + if Configuration.respond_to?(mod) + Configuration.send(mod, xml, doc) + rec = couchdb.save(doc) + p rec + + # pp DB[doc['_id']] + else + raise "No converter for #{mod}" + end + end + end + end + + def read_configuration + Nokogiri::XML(File.read(modules_xml)).xpath('/configuration/modules/load[@module]').each do |tag| + mod = tag['module'].sub(/^mod_/, '') + mod_xml = File.join(File.dirname(modules_xml), "#{mod}.conf.xml") + begin + xml = ConverterHelper.parse(mod_xml) + rescue Errno::ENOENT + warn "No config file found for #{mod_xml}" + next + end + + yield mod, xml + end + end + + def modules_xml + File.join(@root, '/conf/autoload_configs/modules.conf.xml') + end + + + def convert_dialplan + require_relative 'import/dialplan' + read_dialplan do |xml| + xml.xpath('context').each do |context| + # do stuff with that + FXC::Converter::Dialplan.parse_context(context, @opts[:server]) + end + end + end + + def read_dialplan(&block) + Dir.glob(@root + '/conf/dialplan/*.xml').each do |context_xml| + # read each file and parse it into its full xml (include x-pre-process) + yield ConverterHelper.parse(context_xml) + end + end + + def convert_directory + require_relative 'import/directory' + read_directory do |xml| + xml.xpath('include/domain').each do |domain| + # do stuff with that + doc = {server: @opts[:server]} + FXC::Converter::Directory.parse_domain(domain, doc, couchdb) + rec = couchdb.save(doc) + p rec + end + end + end + + def read_directory(&block) + Dir.glob(@root + '/conf/directory/*.xml').each do |directory_xml| + # read each file and parse it into its full xml (include x-pre-process) + yield ConverterHelper.parse(directory_xml) + end + end + end +end + + +if __FILE__ == $0 + converter = FXC::Converter.new + converter.convert(:configuration) + converter.convert(:directory) + #converter.convert(:dialplan) +end diff --git a/lib/fxc/import/configuration.rb b/lib/fxc/import/configuration.rb new file mode 100644 index 0000000..9063316 --- /dev/null +++ b/lib/fxc/import/configuration.rb @@ -0,0 +1,218 @@ +require 'makura' + +module FXC + class Converter + module Configuration + module_function + + def xml_curl(xml, doc) + doc[:bindings] = bindings = {} + + xml.xpath('bindings/binding').each do |binding| + bindings[binding[:name]] = params = {} + + binding.xpath('param').each do |param| + if param[:name] == 'gateway-url' + params[:config] = { + 'gateway-url' => param[:value], + 'bindings' => param[:bindings], + } + else + params[param[:name]] = param[:value] + end + end + end + end + + def console(xml, doc) + doc[:mappings] = mappings = {} + xml.xpath('mappings/map').each do |map| + mappings[map[:name]] = map[:value] + end + + _settings(xml, doc) + end + + def logfile(xml, doc) + doc[:profiles] = profiles = {} + xml.xpath('profiles/profile').each do |profile| + profiles[profile[:name]] = ph = {} + _settings(profile, ph) + ph[:mappings] = pm = {} + profile.xpath('mappings/map').each do |map| + pm[map[:name]] = map[:value].scan(/[^\s,]+/) + end + end + + _settings(xml, doc) + end + + def enum(xml, doc) + _settings(xml, doc) + doc[:routes] = routes = [] + xml.xpath('routes/route').each do |route| + routes << route.attributes + end + end + + def xml_cdr(xml, doc) + doc[:description] = 'XML CDR cURL Logger' + _settings(xml, doc) + end + + def cdr_csv(xml, doc) + doc[:description] = 'CDR CSV Format' + _settings(xml, doc) + doc[:templates] = templates = {} + xml.xpath('templates/template').each do |template| + templates[template[:name]] = template.inner_text + end + end + + def event_socket(xml, doc) + doc[:description] = 'Socket Client' + _settings(xml, doc) + end + + def sofia(xml, doc) + doc[:global_settings] = global_settings = {} + xml.xpath('global_settings/param').each do |param| + global_settings[param[:name]] = param[:value] + end + + doc[:profiles] = profiles = {} + xml.xpath('profiles/profile').each do |profile| + profiles[profile[:name]] = ph = {} + _settings(profile, ph) + + ph[:aliases] = profile.xpath('aliases').map{|a| a[:name] } + ph[:domains] = domains = {} + profile.xpath('domains/domain').each do |domain| + domains[domain[:name]] = { + alias: domain[:alias] == 'true', + parse: domain[:parse] == 'true', + } + end + + ph[:gateways] = gateways = {} + + xml.xpath('gateways/gateway').each do |gateway| + gateways[gateway[:name]] = gh = {} + gateway.xpath('param').each do |param| + gh[param[:name]] = param[:value] + end + end + end + end + + def conference(xml, doc) + doc[:advertise] = advertise = {} + xml.xpath('advertise/room').each do |room| + advertise[room[:name]] = room[:status] + end + + doc['caller-controls'] = caller_controls = {} + xml.xpath('caller-controls/group').each do |group| + caller_controls[group[:name]] = gh = {} + group.xpath('control').each do |control| + gh[control[:action]] = control[:digits] + end + end + + doc['profiles'] = profiles = {} + xml.xpath('profiles/profile').each do |profile| + profiles[profile[:name]] = ph = {} + profile.xpath('param').each do |param| + ph[param[:name]] = param[:value] + end + end + end + + def fifo(xml, doc) + _settings(xml, doc) + + doc['fifos'] = fifos = {} + xml.xpath('fifos/fifo').each do |fifo| + fifos[fifo[:name]] = fh = {} + fifo.attributes.each do |key, attribute| + fh[key] = attribute.value unless key == "name" + end + + fh[:members] = members = {} + fifo.xpath('member').each do |member| + members[member.text] = mh = {} + member.attributes.each do |key, attribute| + mh[key] = attribute.value + end + end + end + end + + def db(xml, doc) + _settings(xml, doc) + end + + def hash(xml, doc) + doc[:remotes] = remotes = {} + xml.xpath('remotes/remote').each do |remote| + remotes[remote[:name]] = rh = {} + remote.attributes.each do |key, attribute| + rh[key] = attribute.value unless key == 'name' + end + end + end + + def local_stream(xml, doc) + doc[:directories] = directories = {} + xml.xpath('directory').each do |directory| + directories[directory[:name]] = dh = {} + dh[:path] = directory[:path] + directory.xpath('param').each do |param| + dh[param[:name]] = param[:value] + end + end + end + + def spandsp(xml, doc) + doc[:descriptors] = descriptors = {} + xml.xpath('descriptors/descriptor').each do |descriptor| + descriptors[descriptor[:name]] = dh = {} + descriptor.xpath('tone').each do |tone| + dh[tone[:name]] = ta = [] + tone.xpath('element').each do |element| + ta << tah = {} + element.attributes.each do |key, attribute| + tah[key] = attribute.value.to_i + end + end + end + end + end + + def voicemail(xml, doc) + _settings(xml, doc) + + doc[:profiles] = profiles = {} + xml.xpath('profiles/profile').each do |profile| + profiles[profile[:name]] = ph = {} + + profile.xpath('param').each do |param| + ph[param[:name]] = param[:value] + end + + ph[:email] = email = {} + profile.xpath('email/param').each do |param| + email[param[:name]] = param[:value] + end + end + end + + def _settings(xml, doc) + doc[:settings] = settings = {} + xml.xpath('settings/param').each do |param| + settings[param[:name]] = param[:value] + end + end + end + end +end diff --git a/lib/fxc/import/dialplan.rb b/lib/fxc/import/dialplan.rb new file mode 100644 index 0000000..e13bc5a --- /dev/null +++ b/lib/fxc/import/dialplan.rb @@ -0,0 +1,77 @@ +require_relative '../import' +require_relative '../../../spec/db_helper' # comment this out for production +require_relative '../../../model/init' + +module FXC + class Converter + module Dialplan + module_function + + def parse_context(node, server) + name = node[:name] + puts "Parsing context #{name} for server #{server}" + # Add the context + server = FXC::Server.find_or_create(:name => server) + context = FXC::Context.find_or_create(:server_id => server.id, :name => name) + node.xpath("extension").each do |ext| + parse_extension ext, context + end + end + + def parse_extension(node, context) + name = node[:name] + puts "Parsing extension #{name}" + # Add the extension + extension = FXC::Extension.find_or_create( + :context_id => context.id, + :name => name, + :continue => node[:continue] + ) + node.xpath("condition").each do |cond| + parse_condition cond, extension + end + end + + def parse_condition(node, extension) + field, expression = node[:field], node[:expression] + puts "Parsing condition #{field} => #{expression}" + # Add the condition + condition = FXC::Condition.find_or_create( + :extension_id => extension.id, + :matcher => field, + :expression => expression, + :break => node[:break], + :name => node[:name], + :description => node[:description] + ) + node.xpath("action").each do |act| + parse_action act, condition + end + node.xpath("anti-action").each do |act| + parse_anti_action act, condition + end + end + + def parse_action(node, condition) + app, data = node[:application], node[:data] + puts "Parsing action #{app} => #{data}" + # Add the action + FXC::Action.find_or_create( + :condition_id => condition.id, + :application => app, + :data => data + ) + end + + def parse_anti_action(node, condition) + app, data = node[:application], node[:data] + puts "Parsing action #{app} => #{data}" + FXC::AntiAction.find_or_create( + :condition_id => condition.id, + :application => app, + :data => data + ) + end + end + end +end diff --git a/lib/fxc/import/directory.rb b/lib/fxc/import/directory.rb new file mode 100644 index 0000000..2ac2ee2 --- /dev/null +++ b/lib/fxc/import/directory.rb @@ -0,0 +1,335 @@ +require 'makura' +require 'pp' + +module FXC + class Converter + module Directory + module_function + + def parse_domain(node, doc, couchdb) + doc[:name] = domain = node[:name] + server = doc[:server] + doc["_id"] = "%s_%s.domain" % [server, domain] + doc[:type] = "directory" + + doc[:params] = params = {} + node.xpath('params/param').each do |param| + params[param[:name]] = param[:value] + end + + doc[:variables] = variables = {} + node.xpath('variables/variable').each do |variable| + variables[variable[:name]] = variable[:value] + end + + doc[:groups] = groups = [] + node.xpath('groups/group').each do |group| + groups << group[:name] + grp = {server: server, + domain: domain, + name: group[:name], + type: "group", + members: []} + grp["_id"] = "%s_%s_%s.group" % [server, domain, grp[:name]] + #couchdb.save(grp) + group.xpath('users/user').each do |user| + if user[:type] == "pointer" + grp[:members] << user[:id] + else + u = parse_user(user, grp) + grp[:members] << u[:id] unless grp[:members].include?(u[:id]) + rec = couchdb.save(u) + p rec + end + end + rec = couchdb.save(grp) + p rec + end + + doc + end + + def parse_user(node, group_doc) + #users[node[:id]] = user = {} + server, domain, group = group_doc[:server], group_doc[:domain], group_doc[:name] + user = {type: 'user', server: server, group: group, domain: domain} + user[:id] = node[:id] + user["_id"] = "%s_%s_%s_%s.user" % [server, domain, group, user[:id]] + + # node is a user, user is the hash representation + user[:params] = params = {} + node.attributes.each do |key, value| + params[key] = value unless key == "id" + end + node.xpath('params/param').each do |param| + params[param[:name]] = param[:value] + end + + user[:variables] = variables = {} + node.xpath('variables/variable').each do |variable| + variables[variable[:name]] = variable[:value] + end + + user[:buttons] = buttons = {} + node.xpath('skinny/buttons/button').each do |button| + # p button[:position] + buttons[button[:position]] = sb = {} + button.attributes.each do |key, attribute| + sb[key] = attribute.value unless key == "position" + end + end + + user[:gateways] = gateways = {} + node.xpath('gateways/gateway').each do |gateway| + gateways[gateway[:id]] = gateway[:id] + gateways[:params] = gparams = {} + node.xpath('param').each do |param| + gparams[param[:name]] = param[:value] + end + end + + user + end + + + def default(xml, doc = {}) + doc[:params] = params = {} + doc[:groups] = groups = {} + doc[:variables] = variables = {} + doc[:name] = xml[:name] + xml.xpath('params/param').each do |param| + params[param[:name]] = param[:value] + end + + xml.xpath('variables/variable').each do |variable| + variables[variable[:name]] = variable[:value] + end + + doc[:groups] = groups = {} + xml.xpath('groups/group').each do |group| + p group[:name] + groups[group[:name]] = us = {} + group.xpath('users/user').each do |user| + p user + us[user[:id]] = user[:type] + end + end + + p doc.to_s + doc + end + + +=begin + def xml_curl(xml, doc) + doc[:bindings] = bindings = {} + + xml.xpath('bindings/binding').each do |binding| + bindings[binding[:name]] = params = {} + + binding.xpath('param').each do |param| + if param[:name] == 'gateway-url' + params[:config] = { + 'gateway-url' => param[:value], + 'bindings' => param[:bindings], + } + else + params[param[:name]] = param[:value] + end + end + end + end + + def console(xml, doc) + doc[:mappings] = mappings = {} + xml.xpath('mappings/map').each do |map| + mappings[map[:name]] = map[:value] + end + + _settings(xml, doc) + end + + def logfile(xml, doc) + doc[:profiles] = profiles = {} + xml.xpath('profiles/profile').each do |profile| + profiles[profile[:name]] = ph = {} + _settings(profile, ph) + ph[:mappings] = pm = {} + profile.xpath('mappings/map').each do |map| + pm[map[:name]] = map[:value].scan(/[^\s,]+/) + end + end + + _settings(xml, doc) + end + + def enum(xml, doc) + _settings(xml, doc) + doc[:routes] = routes = [] + xml.xpath('routes/route').each do |route| + routes << route.attributes + end + end + + def xml_cdr(xml, doc) + doc[:description] = 'XML CDR cURL Logger' + _settings(xml, doc) + end + + def cdr_csv(xml, doc) + doc[:description] = 'CDR CSV Format' + _settings(xml, doc) + doc[:templates] = templates = {} + xml.xpath('templates/template').each do |template| + templates[template[:name]] = template.inner_text + end + end + + def event_socket(xml, doc) + doc[:description] = 'Socket Client' + _settings(xml, doc) + end + + def sofia(xml, doc) + doc[:global_settings] = global_settings = {} + xml.xpath('global_settings/param').each do |param| + global_settings[param[:name]] = param[:value] + end + + doc[:profiles] = profiles = {} + xml.xpath('profiles/profile').each do |profile| + profiles[profile[:name]] = ph = {} + _settings(profile, ph) + + ph[:aliases] = profile.xpath('aliases').map{|a| a[:name] } + ph[:domains] = domains = {} + profile.xpath('domains/domain').each do |domain| + domains[domain[:name]] = { + alias: domain[:alias] == 'true', + parse: domain[:parse] == 'true', + } + end + + ph[:gateways] = gateways = {} + + xml.xpath('gateways/gateway').each do |gateway| + gateways[gateway[:name]] = gh = {} + gateway.xpath('param').each do |param| + gh[param[:name]] = param[:value] + end + end + end + end + + def conference(xml, doc) + doc[:advertise] = advertise = {} + xml.xpath('advertise/room').each do |room| + advertise[room[:name]] = room[:status] + end + + doc['caller-controls'] = caller_controls = {} + xml.xpath('caller-controls/group').each do |group| + caller_controls[group[:name]] = gh = {} + group.xpath('control').each do |control| + gh[control[:action]] = control[:digits] + end + end + + doc['profiles'] = profiles = {} + xml.xpath('profiles/profile').each do |profile| + profiles[profile[:name]] = ph = {} + profile.xpath('param').each do |param| + ph[param[:name]] = param[:value] + end + end + end + + def fifo(xml, doc) + _settings(xml, doc) + + doc['fifos'] = fifos = {} + xml.xpath('fifos/fifo').each do |fifo| + fifos[fifo[:name]] = fh = {} + fifo.attributes.each do |key, attribute| + fh[key] = attribute.value unless key == "name" + end + + fh[:members] = members = {} + fifo.xpath('member').each do |member| + members[member.text] = mh = {} + member.attributes.each do |key, attribute| + mh[key] = attribute.value + end + end + end + end + + def db(xml, doc) + _settings(xml, doc) + end + + def hash(xml, doc) + doc[:remotes] = remotes = {} + xml.xpath('remotes/remote').each do |remote| + remotes[remote[:name]] = rh = {} + remote.attributes.each do |key, attribute| + rh[key] = attribute.value unless key == 'name' + end + end + end + + def local_stream(xml, doc) + doc[:directories] = directories = {} + xml.xpath('directory').each do |directory| + directories[directory[:name]] = dh = {} + dh[:path] = directory[:path] + directory.xpath('param').each do |param| + dh[param[:name]] = param[:value] + end + end + end + + def spandsp(xml, doc) + doc[:descriptors] = descriptors = {} + xml.xpath('descriptors/descriptor').each do |descriptor| + descriptors[descriptor[:name]] = dh = {} + descriptor.xpath('tone').each do |tone| + dh[tone[:name]] = ta = [] + tone.xpath('element').each do |element| + ta << tah = {} + element.attributes.each do |key, attribute| + tah[key] = attribute.value.to_i + end + end + end + end + end + + def voicemail(xml, doc) + _settings(xml, doc) + + doc[:profiles] = profiles = {} + xml.xpath('profiles/profile').each do |profile| + profiles[profile[:name]] = ph = {} + + profile.xpath('param').each do |param| + ph[param[:name]] = param[:value] + end + + ph[:email] = email = {} + profile.xpath('email/param').each do |param| + email[param[:name]] = param[:value] + end + end + end + + def _settings(xml, doc) + doc[:settings] = settings = {} + xml.xpath('settings/param').each do |param| + settings[param[:name]] = param[:value] + end + end +=end + end + end +end diff --git a/tasks/migrate.rake b/tasks/migrate.rake index 7729c6b..99d3ede 100644 --- a/tasks/migrate.rake +++ b/tasks/migrate.rake @@ -1,22 +1,22 @@ # Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> # Distributed under the terms of the MIT license. # The full text can be found in the LICENSE file included with this software desc "migrate to latest version of db" task :migrate, :version do |_, args| args.with_defaults(:version => nil) require File.expand_path("../../lib/fxc", __FILE__) - require Fxc::LIBPATH + "/fxc/db" + require_relative "../lib/fxc/db" require 'sequel/extensions/migration' - raise "No DB found" unless Fxc.db + raise "No DB found" unless FXC.db - require Fxc::PATH + "/model/init" + require_relative "../model/init" if args.version.nil? - Sequel::Migrator.apply(Fxc.db, Fxc::MIGRATION_ROOT) + Sequel::Migrator.apply(FXC.db, FXC::MIGRATION_ROOT) else - Sequel::Migrator.run(Fxc.db, Fxc::MIGRATION_ROOT, :target => args.version.to_i) + Sequel::Migrator.run(FXC.db, FXC::MIGRATION_ROOT, :target => args.version.to_i) end end diff --git a/tasks/schema.rake b/tasks/schema.rake index a046159..715856b 100644 --- a/tasks/schema.rake +++ b/tasks/schema.rake @@ -1,30 +1,30 @@ # Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> # Distributed under the terms of the MIT license. # The full text can be found in the LICENSE file included with this software # task :test_db do require_relative "../lib/fxc" - require Fxc::ROOT/:spec/:db_helper + require FXC::ROOT/:spec/:db_helper end desc "Dump the test schema" task :schema, :format, :needs => [:test_db] do |t,args| args.with_defaults(:format => "html") - descs = Fxc.db.tables.inject([]) do |arr, table| + descs = FXC.db.tables.inject([]) do |arr, table| arr << "\\dd #{table};\\d+ #{table}" end commands = descs.join(";") if args.format.to_s == "html" f = File.open("doc/schema.html","w+") command = %Q{echo '\\H #{commands}'|PGDATA=#{ENV['PGDATA']} PGHOST=#{ENV['PGHOST']} PGPORT=#{ENV['PGPORT']} psql fxc|tail -n +2} else command = %Q{echo '#{commands}'|PGDATA=#{ENV['PGDATA']} PGHOST=#{ENV['PGHOST']} PGPORT=#{ENV['PGPORT']} psql fxc} f = $stdout end f.puts %x{#{command}} unless f == $stdout f.close puts "Saved doc/schema.html" end end
bougyman/fxc
5f25a8c46ea86fa7dc516f0f196054950baf1d8a
Converter for rest of config files for couch
diff --git a/import_couch.rb b/import_couch.rb index f351772..8387217 100644 --- a/import_couch.rb +++ b/import_couch.rb @@ -1,123 +1,286 @@ require 'makura' +require 'tsort' require 'pp' require 'nokogiri' +class Hash + include TSort + alias tsort_each_node each_key + def tsort_each_child(node, &block) + fetch(node).each(&block) + end +end + module Convert module_function def xml_curl(xml, doc) doc[:bindings] = bindings = {} xml.xpath('bindings/binding').each do |binding| bindings[binding[:name]] = params = {} binding.xpath('param').each do |param| if param[:name] == 'gateway-url' params[:config] = { 'gateway-url' => param[:value], 'bindings' => param[:bindings], } else params[param[:name]] = param[:value] end end end end def console(xml, doc) doc[:mappings] = mappings = {} xml.xpath('mappings/map').each do |map| mappings[map[:name]] = map[:value] end _settings(xml, doc) end def logfile(xml, doc) doc[:profiles] = profiles = {} xml.xpath('profiles/profile').each do |profile| profiles[profile[:name]] = ph = {} _settings(profile, ph) ph[:mappings] = pm = {} profile.xpath('mappings/map').each do |map| pm[map[:name]] = map[:value].scan(/[^\s,]+/) end end _settings(xml, doc) end def enum(xml, doc) _settings(xml, doc) doc[:routes] = routes = [] xml.xpath('routes/route').each do |route| routes << route.attributes end end def xml_cdr(xml, doc) doc[:description] = 'XML CDR cURL Logger' _settings(xml, doc) end def cdr_csv(xml, doc) doc[:description] = 'CDR CSV Format' _settings(xml, doc) doc[:templates] = templates = {} xml.xpath('templates/template').each do |template| templates[template[:name]] = template.inner_text end end def event_socket(xml, doc) doc[:description] = 'Socket Client' _settings(xml, doc) end def sofia(xml, doc) - pp xml - throw :ignore - # TODO + doc[:global_settings] = global_settings = {} + xml.xpath('global_settings/param').each do |param| + global_settings[param[:name]] = param[:value] + end + + doc[:profiles] = profiles = {} + xml.xpath('profiles/profile').each do |profile| + profiles[profile[:name]] = ph = {} + _settings(profile, ph) + + ph[:aliases] = profile.xpath('aliases').map{|a| a[:name] } + ph[:domains] = domains = {} + profile.xpath('domains/domain').each do |domain| + domains[domain[:name]] = { + alias: domain[:alias] == 'true', + parse: domain[:parse] == 'true', + } + end + + ph[:gateways] = gateways = {} + + xml.xpath('gateways/gateway').each do |gateway| + gateways[gateway[:name]] = gh = {} + gateway.xpath('param').each do |param| + gh[param[:name]] = param[:value] + end + end + end + end + + def conference(xml, doc) + doc[:advertise] = advertise = {} + xml.xpath('advertise/room').each do |room| + advertise[room[:name]] = room[:status] + end + + doc['caller-controls'] = caller_controls = {} + xml.xpath('caller-controls/group').each do |group| + caller_controls[group[:name]] = gh = {} + group.xpath('control').each do |control| + gh[control[:action]] = control[:digits] + end + end + + doc['profiles'] = profiles = {} + xml.xpath('profiles/profile').each do |profile| + profiles[profile[:name]] = ph = {} + profile.xpath('param').each do |param| + ph[param[:name]] = param[:value] + end + end + end + + def fifo(xml, doc) + _settings(xml, doc) + + doc['fifos'] = fifos = {} + xml.xpath('fifos/fifo').each do |fifo| + fifos[fifo[:name]] = fh = {} + fifo.attributes.each do |key, attribute| + fh[key] = attribute.value unless key == "name" + end + + fh[:members] = members = {} + fifo.xpath('member').each do |member| + members[member.text] = mh = {} + member.attributes.each do |key, attribute| + mh[key] = attribute.value + end + end + end end - def loopback(xml, doc) - throw :ignore + def db(xml, doc) + _settings(xml, doc) + end + + def hash(xml, doc) + doc[:remotes] = remotes = {} + xml.xpath('remotes/remote').each do |remote| + remotes[remote[:name]] = rh = {} + remote.attributes.each do |key, attribute| + rh[key] = attribute.value unless key == 'name' + end + end + end + + def local_stream(xml, doc) + doc[:directories] = directories = {} + xml.xpath('directory').each do |directory| + directories[directory[:name]] = dh = {} + dh[:path] = directory[:path] + directory.xpath('param').each do |param| + dh[param[:name]] = param[:value] + end + end + end + + def spandsp(xml, doc) + doc[:descriptors] = descriptors = {} + xml.xpath('descriptors/descriptor').each do |descriptor| + descriptors[descriptor[:name]] = dh = {} + descriptor.xpath('tone').each do |tone| + dh[tone[:name]] = ta = [] + tone.xpath('element').each do |element| + ta << tah = {} + element.attributes.each do |key, attribute| + tah[key] = attribute.value.to_i + end + end + end + end + end + + def voicemail(xml, doc) + _settings(xml, doc) + + doc[:profiles] = profiles = {} + xml.xpath('profiles/profile').each do |profile| + profiles[profile[:name]] = ph = {} + + profile.xpath('param').each do |param| + ph[param[:name]] = param[:value] + end + + ph[:email] = email = {} + profile.xpath('email/param').each do |param| + email[param[:name]] = param[:value] + end + end end def _settings(xml, doc) doc[:settings] = settings = {} xml.xpath('settings/param').each do |param| settings[param[:name]] = param[:value] end end + + def _parse(filename, parent = nil, deps = {}, xmls = {}) + deps[filename] ||= [] + + node = Nokogiri::XML(File.read(filename)) + xmls[filename] = node + node.xpath('//X-PRE-PROCESS[@cmd="include"]').each do |inc| + glob = File.expand_path(inc[:data], File.dirname(filename)) + + Dir.glob(glob){|path| + deps[path] ||= [] + deps[filename] << path + deps.tsort # check for cyclic dependencies. + + child = _parse(path, node, deps, xmls) + inc.parent.add_child(child) + } + end + + if parent + node.xpath('/include') + else + node.xpath('/configuration') + end + end end Makura::Model.server = 'http://jimmy:5984' -Makura::Model.database = "fxc_spec_#{Time.now.to_i}" +Makura::Model.database = "fxc_spec" +Makura::Model.database.destroy! +Makura::Model.database.create DB = Makura::Model.database modules_xml = File.expand_path('~/conf/autoload_configs/modules.conf.xml') Nokogiri::XML(File.read(modules_xml)).xpath('/configuration/modules/load[@module]').each do |tag| mod = tag['module'].sub(/^mod_/, '') mod_xml = File.join(File.dirname(modules_xml), "#{mod}.conf.xml") begin - xml = Nokogiri::XML(File.read(mod_xml)).xpath('/configuration') + xml = Convert._parse(mod_xml) rescue Errno::ENOENT - $stderr.puts "No config file found for #{mod_xml}" + warn "No config file found for #{mod_xml}" next end doc = { name: "#{mod}.conf", database: nil, '_id' => "#{mod}.conf", } catch :ignore do - Convert.send(mod, xml, doc) - DB.save(doc) + puts "Attempt conversion of #{mod}" + if Convert.respond_to?(mod) + Convert.send(mod, xml, doc) + DB.save(doc) - pp DB[doc['_id']] + # pp DB[doc['_id']] + else + raise "No converter for #{mod}" + end end - end
bougyman/fxc
1e6e6b4eafee2c182b697aa50073b3b3eea2e91e
move the dialplan and directory (postgres backed) from old fxc/ramaze to the new innate node structure, all specs passing (WOOHOO). TODO: complete importer for conf/ directory, spec out the Proxy node
diff --git a/DEPENDENCIES b/DEPENDENCIES new file mode 100644 index 0000000..b622eb5 --- /dev/null +++ b/DEPENDENCIES @@ -0,0 +1,5 @@ +innate-2010.07 +makura-2010.08.26 +nokogiri-1.4.3.1 +pg-0.9.0 +sequel-3.15.0 diff --git a/README.txt b/README.txt index d2ff798..cea9cb1 100644 --- a/README.txt +++ b/README.txt @@ -1,54 +1,52 @@ fxc by The Rubyists, LLC http://code.rubyists.com == DESCRIPTION: FXC is a small innate application which functions as a proxy to a couchDB backend for serving FreeSWITCH configuration. == FEATURES/PROBLEMS: * Serves Configuration Files for Multiple FreeSWITCH servers == SYNOPSIS: * Serves Configuration Files for Multiple FreeSWITCH servers -== REQUIREMENTS: - -* CouchDB -* Ruby (1.9.2 preferred) -* Innate (gem install innate) - == INSTALL: -* Install couch db and create the 'fxc' database -* Install Ruby +* Install CouchDB (>= 1.0.1) + * On sustems that don't provide this version, you can use: + http://github.com/jhs/build-couchdb +* Install Ruby (1.9.2 preferred) + * On systems that don't provide this version, you can use: + http://rvm.beginrescueend.com/ * Gem install makura, innate, nokogiri * run ruby sync_couch.rb == LICENSE: (The MIT License) Copyright (c) 2009 The Rubyists, LLC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/Rakefile b/Rakefile index bab94ff..ece65b0 100644 --- a/Rakefile +++ b/Rakefile @@ -1,17 +1,88 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +begin; require 'rubygems'; rescue LoadError; end -begin - require 'bones' -rescue LoadError - abort '### Please install the "bones" gem ###' -end +require 'rake' +require 'rake/clean' +require 'rake/gempackagetask' +require 'time' +require 'date' -task :default => 'test:run' -task 'gem:release' => 'test:run' +PROJECT_SPECS = FileList[ + 'spec/*/**/*.rb' +] -Bones { - name 'fxc' - authors 'The Rubyists, LLC' - email '[email protected]' - url 'http://github.com/rubyists/fxc' +PROJECT_MODULE = 'FXC' +PROJECT_README = 'README' +#PROJECT_RUBYFORGE_GROUP_ID = 3034 +PROJECT_COPYRIGHT_SUMMARY = [ + "# Copyright (c) 2008-#{Time.now.year} The Rubyists, LLC (effortless systems) <[email protected]>", + "# Distributed under the terms of the MIT license.", + "# The full text can be found in the LICENSE file included with this software", + "#", +] +PROJECT_COPYRIGHT = PROJECT_COPYRIGHT_SUMMARY + [ + "# Permission is hereby granted, free of charge, to any person obtaining a copy", + '# of this software and associated documentation files (the "Software"), to deal', + "# in the Software without restriction, including without limitation the rights", + "# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell", + "# copies of the Software, and to permit persons to whom the Software is", + "# furnished to do so, subject to the following conditions:", + "#", + "# The above copyright notice and this permission notice shall be included in", + "# all copies or substantial portions of the Software.", + "#", + '# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR', + "# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,", + "# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE", + "# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER", + "# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,", + "# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN", + "# THE SOFTWARE." +] + +# To release the monthly version do: +# $ PROJECT_VERSION=2009.03 rake release +IGNORE_FILES = [/\.gitignore/] + +GEMSPEC = Gem::Specification.new{|s| + s.name = 'fxc' + s.author = "fsr_xml_curl" + s.summary = "The FXC library, by The Rubyists, LLC" + s.description = "The FXC library, by The Rubyists, LLC" + s.email = '[email protected]' + s.homepage = 'http://code.rubyists.com/projects/fxc' + s.platform = Gem::Platform::RUBY + s.version = (ENV['PROJECT_VERSION'] || (begin;Object.const_get(PROJECT_MODULE)::VERSION;rescue;Date.today.strftime("%Y.%m.%d");end)) + s.files = `git ls-files`.split("\n").sort.reject { |f| IGNORE_FILES.detect { |exp| f.match(exp) } } + s.has_rdoc = true + s.require_path = 'lib' + + + s.post_install_message = <<MESSAGE.strip +============================================================ + +Thank you for installing Fxc! + +============================================================ +MESSAGE } +Dir['tasks/*.rake'].each{|f| import(f) } + +task :default => [:bacon] + +CLEAN.include %w[ + **/.*.sw? + *.gem + .config + **/*~ + **/{data.db,cache.yaml} + *.yaml + pkg + rdoc + ydoc + *coverage* +] diff --git a/app.rb b/app.rb index b498a14..d077f46 100644 --- a/app.rb +++ b/app.rb @@ -1,15 +1,18 @@ require "innate" require_relative "lib/fxc" -Dir.glob(Fxc::PATH + "/node/*.rb").each { |node| - require node -} -require Fxc::PATH + "lib/rack/middleware" +require_relative 'node/proxy' + +require FXC::ROOT/"model/init" +require FXC::ROOT/"lib/rack/middleware" + +Innate::Response.options.headers['Content-Type'] = 'freeswitch/xml' + Innate.middleware! do |mw| - mw.use Fxc::Rack::Middleware + mw.use FXC::Rack::Middleware mw.use Rack::CommonLogger mw.innate end if $0 == __FILE__ - Innate.start :root => Fxc::PATH, :file => __FILE__ + Innate.start :root => FXC::ROOT.to_s, :file => __FILE__ end diff --git a/db/migrations/001_create_users.rb b/db/migrations/001_create_users.rb new file mode 100644 index 0000000..0533e4c --- /dev/null +++ b/db/migrations/001_create_users.rb @@ -0,0 +1,20 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +Class.new Sequel::Migration do + def up + create_table(:users) do + primary_key :id + String :username, :null => false + String :cidr, :default => "0.0.0.0/0" + String :mailbox + String :password + String "vm-password" + end unless FXC.db.tables.include? :users + end + + def down + remove_table(:users) if FXC.db.tables.include? :users + end +end diff --git a/db/migrations/002_user_variables.rb b/db/migrations/002_user_variables.rb new file mode 100644 index 0000000..3fdb26a --- /dev/null +++ b/db/migrations/002_user_variables.rb @@ -0,0 +1,18 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +Class.new Sequel::Migration do + def up + create_table(:user_variables) do + primary_key :id + String :name + String :value + foreign_key :user_id, :users, :null => false, :on_delete => :cascade + end unless tables.include? :user_variables + end + + def down + remove_table(:user_variables) if tables.include? :user_variables #DB.tables.include? :user_variables + end +end diff --git a/db/migrations/003_add_active_to_users.rb b/db/migrations/003_add_active_to_users.rb new file mode 100644 index 0000000..b2b8ae2 --- /dev/null +++ b/db/migrations/003_add_active_to_users.rb @@ -0,0 +1,17 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +Class.new Sequel::Migration do + def up + alter_table(:users) do + add_column :active, TrueClass, :default => false + end unless FXC.db[:users].columns.include? :active + end + + def down + alter_table(:users) do + drop_column :active + end if FXC.db[:users].columns.include? :active + end +end diff --git a/db/migrations/004_add_user_dialstring.rb b/db/migrations/004_add_user_dialstring.rb new file mode 100644 index 0000000..988c77e --- /dev/null +++ b/db/migrations/004_add_user_dialstring.rb @@ -0,0 +1,17 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +Class.new Sequel::Migration do + def up + alter_table(:users) do + add_column :dialstring, String, :default => '{presence_id=${dialed_user}@$${domain}}${sofia_contact(default/${dialed_user}@$${domain})}' + end unless FXC.db[:users].columns.include? :dialstring + end + + def down + alter_table(:users) do + drop_column :dialstring + end if FXC.db[:users].columns.include? :dialstring + end +end diff --git a/db/migrations/005_create_targets.rb b/db/migrations/005_create_targets.rb new file mode 100644 index 0000000..55c1aa0 --- /dev/null +++ b/db/migrations/005_create_targets.rb @@ -0,0 +1,19 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +Class.new Sequel::Migration do + def up + create_table(:targets) do + primary_key :id + String :value, :null => false + String :type, :default => "landline", :null => false + Integer :priority, :default => 1, :null => false + foreign_key :user_id, :users, :on_delete => :cascade + end unless tables.include? :targets + end + + def down + remove_table(:targets) if tables.include? :targets + end +end diff --git a/db/migrations/006_add_user_names.rb b/db/migrations/006_add_user_names.rb new file mode 100644 index 0000000..6dd0ebe --- /dev/null +++ b/db/migrations/006_add_user_names.rb @@ -0,0 +1,21 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +Class.new Sequel::Migration do + def up + [:first_name, :last_name].each do |col| + alter_table(:users) do + add_column col, String + end unless FXC.db[:users].columns.include? col + end + end + + def down + [:first_name, :last_name].each do |col| + alter_table(:users) do + drop_column col + end if FXC.db[:users].columns.include? col + end + end +end diff --git a/db/migrations/007_create_dids.rb b/db/migrations/007_create_dids.rb new file mode 100644 index 0000000..7c17bed --- /dev/null +++ b/db/migrations/007_create_dids.rb @@ -0,0 +1,20 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +Class.new Sequel::Migration do + def up + create_table(:dids) do + primary_key :id + String :number, :null => false + TrueClass :primary, :default => false + String :description + String :clid_name + foreign_key :user_id, :references => :users + end unless FXC.db.tables.include? :dids + end + + def down + remove_table(:dids) if FXC.db.tables.include? :dids + end +end diff --git a/db/migrations/008_add_did_id.rb b/db/migrations/008_add_did_id.rb new file mode 100644 index 0000000..2d28c9d --- /dev/null +++ b/db/migrations/008_add_did_id.rb @@ -0,0 +1,19 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +Class.new Sequel::Migration do + def up + alter_table(:targets) do + add_foreign_key :did_id, :dids, :on_delete => :cascade + end unless FXC.db[:targets].columns.include? :did_id + end + + def down + [:did_id].each do |col| + alter_table(:targets) do + drop_column col + end if FXC.db[:targets].columns.include? col + end + end +end diff --git a/db/migrations/009_comment_schema.rb b/db/migrations/009_comment_schema.rb new file mode 100644 index 0000000..22ac22b --- /dev/null +++ b/db/migrations/009_comment_schema.rb @@ -0,0 +1,27 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +Class.new Sequel::Migration do + def up + execute("COMMENT ON TABLE schema_info IS E'Migration info is stored here'") + execute("COMMENT ON COLUMN schema_info.version IS E'The current migration version'") + execute("COMMENT ON TABLE targets IS E'Store the endpoints which calls can be redirected to here'") + execute("COMMENT ON COLUMN targets.user_id IS E'A user target, references users.id'") + execute("COMMENT ON COLUMN targets.did_id IS E'A DID target, references dids.id'") + execute("COMMENT ON TABLE dids IS E'Store each indbound DID (Direct Inward Dial) we accept here'") + execute("COMMENT ON COLUMN dids.clid_name IS E'The name to send when redirecting calls from this DID'") + execute("COMMENT ON TABLE users IS E'Store each user of the system here'") + execute("COMMENT ON COLUMN users.username IS E'Store the extension here'") + execute("COMMENT ON COLUMN users.mailbox IS E'The mailbox shortcut for a user'") + execute("COMMENT ON COLUMN users.dialstring IS E'The default dialstring for a user'") + execute("COMMENT ON COLUMN users.password IS E'The password to authenticate the username to FreeSWITCH (SIP/MENUS)'") + execute("COMMENT ON COLUMN users.\"vm-password\" IS E'The password to authenticate the username to voicemail'") + execute("COMMENT ON COLUMN users.cidr IS E'The cidr mask a user can authenticate from'") + execute("COMMENT ON TABLE user_variables IS E'Variables for each user are stored here as key/value pairs'") + execute("COMMENT ON COLUMN user_variables.value IS E'The variable''s value'") + end + + def down + end +end diff --git a/db/migrations/010_add_extension_and_pin.rb b/db/migrations/010_add_extension_and_pin.rb new file mode 100644 index 0000000..dd65a81 --- /dev/null +++ b/db/migrations/010_add_extension_and_pin.rb @@ -0,0 +1,35 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +Class.new Sequel::Migration do + def up + alter_table(:users) do + add_column :extension, String, :size => 10 + end unless FXC.db[:users].columns.include? :extension + + alter_table(:users) do + add_column :pin, String, :size => 10 + end unless FXC.db[:users].columns.include? :pin + + execute "COMMENT ON COLUMN users.username IS E'The username a for logging in to the website'" + execute "COMMENT ON COLUMN users.extension IS E'The user''s extension. must be numeric to log in via phone, accepting leading zeros forces String'" + execute "COMMENT ON COLUMN users.pin IS E'The pin number used for authentication on phone applications (same rules as pin, \\d+)'" + + # For legacy dbs + execute("UPDATE users SET extension = username WHERE extension IS NULL") + execute("UPDATE users SET pin = \"vm-password\" WHERE pin IS NULL") + execute("ALTER TABLE users ADD CONSTRAINT no_null_extensions CHECK (extension IS NOT NULL)") + + # Get rid of the columns we don't need + alter_table(:users) do + drop_column :"vm-password" + drop_column :username + add_column :username, String, :size => 40 + end + end + + def down + raise Sequel::Error, "You can't go down from here, buddy" + end +end diff --git a/db/migrations/011_constrain_extensions_to_sanity.rb b/db/migrations/011_constrain_extensions_to_sanity.rb new file mode 100644 index 0000000..c8e4a0c --- /dev/null +++ b/db/migrations/011_constrain_extensions_to_sanity.rb @@ -0,0 +1,24 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +Class.new Sequel::Migration do + def up + alter_table :users do + add_constraint :extension_is_digits do + :extension.like /^[0-9]+$/ + end + add_constraint :pin_is_digits do + :pin.like /^([0-9]+)?$/ + end + end + execute("ALTER TABLE users DROP CONSTRAINT no_null_extensions") + execute("COMMENT ON CONSTRAINT extension_is_digits ON users IS E'Extension must be all digits'") + execute("COMMENT ON CONSTRAINT pin_is_digits ON users IS E'Pin must be all digits'") + end + + def down + execute "DROP CONSTRAINT extension_is_digits ON users" + execute "DROP CONSTRAINT pin_is_digits ON users" + end +end diff --git a/db/migrations/012_constrain_unique_user_fields.rb b/db/migrations/012_constrain_unique_user_fields.rb new file mode 100644 index 0000000..cec9f34 --- /dev/null +++ b/db/migrations/012_constrain_unique_user_fields.rb @@ -0,0 +1,19 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +Class.new Sequel::Migration do + def up + alter_table :users do + add_index :extension, :unique => true + add_index :username, :unique => true + end + end + + def down + alter_table :users do + drop_index :extension + drop_index :username + end + end +end diff --git a/db/migrations/013_make_extension_autopopulate.rb b/db/migrations/013_make_extension_autopopulate.rb new file mode 100644 index 0000000..648c4fa --- /dev/null +++ b/db/migrations/013_make_extension_autopopulate.rb @@ -0,0 +1,31 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +Class.new Sequel::Migration do + def up + alter_table :users do + rename_column :extension, :old_ext + add_column :extension, :serial, :unique => true + drop_constraint :extension_is_digits + drop_index :extension + end + execute "UPDATE users set extension = old_ext::text::integer" + execute "SELECT setval('users_extension_seq', 3175)" + alter_table :users do + drop_column :old_ext + end + end + + def down + alter_table :users do + rename_column :extension, :old_ext + add_column :extension, String, :null => false + end + execute "UPDATE users set extension = old_ext" + alter_table :users do + drop_column :old_ext + add_index :extension, :unique => true + end + end +end diff --git a/db/migrations/014_create_providers.rb b/db/migrations/014_create_providers.rb new file mode 100644 index 0000000..8497b52 --- /dev/null +++ b/db/migrations/014_create_providers.rb @@ -0,0 +1,26 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +Class.new Sequel::Migration do + def up + create_table(:providers) do + primary_key :id + String :format, :null => false + Integer :priority, :null => false, :default => 0, :unique => true + String :description + String :name, :size => 30 + String :host, :size => 40 + Integer :port, :default => 5060 + String :prefix, :size => 1 + end unless tables.include? :providers + execute "COMMENT ON TABLE providers IS 'Storage for VOIP Service Providers that we allow'" + execute "COMMENT ON COLUMN providers.format IS 'The printf format string for this provider, used in dialstrings'" + execute "COMMENT ON COLUMN providers.priority IS 'The (unique) priority for this provider, lower priorities get dialed first'" + execute "COMMENT ON COLUMN providers.prefix IS 'The number to dial before a 10 digit (US and CANADA) outbound number'" + end + + def down + remove_table(:providers) if tables.include? :providers + end +end diff --git a/db/migrations/015_remove_format_column_from_providers.rb b/db/migrations/015_remove_format_column_from_providers.rb new file mode 100644 index 0000000..6c50869 --- /dev/null +++ b/db/migrations/015_remove_format_column_from_providers.rb @@ -0,0 +1,17 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +Class.new Sequel::Migration do + def up + alter_table(:providers) do + drop_column :format + end + end + + def down + alter_table(:targets) do + add_column :format, String, :null => false + end + end +end diff --git a/db/migrations/016_create_contexts.rb b/db/migrations/016_create_contexts.rb new file mode 100644 index 0000000..8dbf714 --- /dev/null +++ b/db/migrations/016_create_contexts.rb @@ -0,0 +1,18 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +Class.new Sequel::Migration do + def up + create_table(:dialplan_contexts) do + primary_key :id + String :name, :size => 40 + String :description + end unless tables.include? :dialplan_contexts + execute "COMMENT ON TABLE dialplan_contexts IS 'Storage for Dialplan Contexts'" + end + + def down + remove_table(:dialplan_contexts) if tables.include? :dialplan_contexts + end +end diff --git a/db/migrations/017_add_context_id_to_user_and_did.rb b/db/migrations/017_add_context_id_to_user_and_did.rb new file mode 100644 index 0000000..7399a04 --- /dev/null +++ b/db/migrations/017_add_context_id_to_user_and_did.rb @@ -0,0 +1,24 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +Class.new Sequel::Migration do + def up + execute "CREATE FUNCTION lookup_context (TEXT) RETURNS INTEGER AS 'SELECT id FROM dialplan_contexts WHERE name = $1' LANGUAGE SQL" + alter_table(:users) do + add_foreign_key :context_id, :dialplan_contexts, :on_delete => :cascade, :default => :lookup_context.sql_function('default') + end unless FXC.db[:users].columns.include? :context_id + + alter_table(:dids) do + add_foreign_key :context_id, :dialplan_contexts, :on_delete => :cascade, :default => :lookup_context.sql_function('public') + end unless FXC.db[:dids].columns.include? :context_id + end + + def down + [:dids, :users].each do |table| + alter_table(table) do + drop_column :context_id + end if FXC.db[table].columns.include? :context_id + end + end +end diff --git a/db/migrations/018_add_user_timezone.rb b/db/migrations/018_add_user_timezone.rb new file mode 100644 index 0000000..4a1bf0d --- /dev/null +++ b/db/migrations/018_add_user_timezone.rb @@ -0,0 +1,17 @@ +Class.new Sequel::Migration do + def up + return if FXC.db[:users].columns.include?(:timezone) + + alter_table :users do + add_column :timezone, String + end + end + + def down + return unless FXC.db[:users].columns.include?(:timezone) + + alter_table :users do + drop_column :timezone + end + end +end diff --git a/db/migrations/019_add_user_email.rb b/db/migrations/019_add_user_email.rb new file mode 100644 index 0000000..96e0df7 --- /dev/null +++ b/db/migrations/019_add_user_email.rb @@ -0,0 +1,17 @@ +Class.new Sequel::Migration do + def up + return if FXC.db[:users].columns.include?(:email) + + alter_table :users do + add_column :email, String + end + end + + def down + return unless FXC.db[:users].columns.include?(:email) + + alter_table :users do + drop_column :email + end + end +end diff --git a/db/migrations/020_create_voicemail_msgs.rb b/db/migrations/020_create_voicemail_msgs.rb new file mode 100644 index 0000000..0a8104c --- /dev/null +++ b/db/migrations/020_create_voicemail_msgs.rb @@ -0,0 +1,27 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +Class.new Sequel::Migration do + def up + create_table(:voicemail_msgs) do + Integer :created_epoch + Integer :read_epoch + String :username + String :domain + String :uuid + String :cid_name + String :cid_number + String :in_folder + String :file_path + Integer :message_len + String :flags + String :read_flags + + end unless FXC.db.tables.include? :voicemail_msgs + end + + def down + remove_table(:voicemail_msgs) if FXC.db.tables.include? :voicemail_msgs + end +end diff --git a/db/migrations/021_create_voicemail_prefs.rb b/db/migrations/021_create_voicemail_prefs.rb new file mode 100644 index 0000000..6c5b50c --- /dev/null +++ b/db/migrations/021_create_voicemail_prefs.rb @@ -0,0 +1,20 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +Class.new Sequel::Migration do + def up + create_table(:voicemail_prefs) do + String :username + String :domain + String :name_path + String :greeting_path + String :password + + end unless FXC.db.tables.include? :voicemail_prefs + end + + def down + remove_table(:voicemail_prefs) if FXC.db.tables.include? :voicemail_prefs + end +end diff --git a/db/migrations/022_add_nibble_columns.rb b/db/migrations/022_add_nibble_columns.rb new file mode 100644 index 0000000..06529c2 --- /dev/null +++ b/db/migrations/022_add_nibble_columns.rb @@ -0,0 +1,29 @@ +Class.new Sequel::Migration do + def up + return if FXC.db[:users].columns.include?(:balance) + + alter_table :users do + add_column :balance, BigDecimal, :default => '0.00', :null => false + end + + return if FXC.db[:users].columns.include?(:nibble_rate) + + alter_table :users do + add_column :nibble_rate, BigDecimal, :default => nil + end + end + + def down + return unless FXC.db[:users].columns.include?(:balance) + + alter_table :users do + drop_column :balance + end + + return unless FXC.db[:users].columns.include?(:nibble_rate) + + alter_table :users do + drop_column :nibble_rate + end + end +end diff --git a/db/migrations/023_add_max_call_length_and_email_notifications_to_users.rb b/db/migrations/023_add_max_call_length_and_email_notifications_to_users.rb new file mode 100644 index 0000000..b8f9cbd --- /dev/null +++ b/db/migrations/023_add_max_call_length_and_email_notifications_to_users.rb @@ -0,0 +1,23 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +Class.new Sequel::Migration do + def up + alter_table(:users) do + add_column :email_notifications, TrueClass, :default => false + end unless FXC.db[:users].columns.include? :email_notifications + alter_table(:users) do + add_column :max_call_length, Integer + end unless FXC.db[:users].columns.include? :max_call_length + end + + def down + alter_table(:users) do + drop_column :email_notifications + end if FXC.db[:users].columns.include? :email_notifications + alter_table(:users) do + drop_column :max_call_length + end if FXC.db[:users].columns.include? :max_call_length + end +end diff --git a/db/migrations/024_create_extensions.rb b/db/migrations/024_create_extensions.rb new file mode 100644 index 0000000..9de33ad --- /dev/null +++ b/db/migrations/024_create_extensions.rb @@ -0,0 +1,25 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +Class.new Sequel::Migration do + def up + create_table(:fs_extensions) do + primary_key :id + String :name + String :description + TrueClass :continue + Integer :position + foreign_key :context_id, :dialplan_contexts, :on_update => :cascade + end unless FXC.db.tables.include? :fs_extensions + execute "COMMENT ON TABLE fs_extensions IS 'Storage for Freeswitch Extensions'" + execute "COMMENT ON COLUMN fs_extensions.name IS 'The name of this extension'" + execute "COMMENT ON COLUMN fs_extensions.description IS 'Description of this extension'" + execute "COMMENT ON COLUMN fs_extensions.continue IS 'Whether to continue after running commands in this extension'" + execute "COMMENT ON COLUMN fs_extensions.context_id IS 'The the reference to context this extension responds to'" + end + + def down + drop_table(:fs_extensions) if FXC.db.tables.include? :fs_extensions + end +end diff --git a/db/migrations/025_create_conditions.rb b/db/migrations/025_create_conditions.rb new file mode 100644 index 0000000..1fffad6 --- /dev/null +++ b/db/migrations/025_create_conditions.rb @@ -0,0 +1,30 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +Class.new Sequel::Migration do + def up + create_table(:fs_conditions) do + primary_key :id + String :name + String :description + String :matcher + String :expression + Integer :position + String :break + foreign_key :extension_id, :fs_extensions, :on_delete => :cascade, :on_update => :cascade + end unless FXC.db.tables.include? :fs_conditions + execute "COMMENT ON TABLE fs_conditions IS 'Storage for Dialplan conditions'" + execute "COMMENT ON COLUMN fs_conditions.name IS 'The name of this condition'" + execute "COMMENT ON COLUMN fs_conditions.description IS 'Description of this condition'" + execute "COMMENT ON COLUMN fs_conditions.matcher IS 'Which Field to match on'" + execute "COMMENT ON COLUMN fs_conditions.expression IS 'The expression to match with'" + execute "COMMENT ON COLUMN fs_conditions.position IS 'The order to match in'" + execute "COMMENT ON COLUMN fs_conditions.break IS 'Whether to stop after this condition is met (or not)'" + execute "COMMENT ON COLUMN fs_conditions.extension_id IS 'The associated extension record'" + end + + def down + drop_table(:fs_conditions) if FXC.db.tables.include? :fs_conditions + end +end diff --git a/db/migrations/026_create_actions.rb b/db/migrations/026_create_actions.rb new file mode 100644 index 0000000..55a93ea --- /dev/null +++ b/db/migrations/026_create_actions.rb @@ -0,0 +1,28 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +Class.new Sequel::Migration do + def up + create_table(:fs_actions) do + primary_key :id + String :name + String :description + String :application + String :data + Integer :position + foreign_key :condition_id, :fs_conditions, :on_update => :cascade, :on_delete => :cascade + end unless FXC.db.tables.include? :fs_actions + execute "COMMENT ON TABLE fs_actions IS 'Storage for Dialplan actions'" + execute "COMMENT ON COLUMN fs_actions.name IS 'The name of this action'" + execute "COMMENT ON COLUMN fs_actions.description IS 'Description of this action'" + execute "COMMENT ON COLUMN fs_actions.application IS 'Which application to run'" + execute "COMMENT ON COLUMN fs_actions.data IS 'The arguments to send to the application'" + execute "COMMENT ON COLUMN fs_actions.position IS 'The order to perform actions in'" + execute "COMMENT ON COLUMN fs_actions.condition_id IS 'The associated condition record'" + end + + def down + drop_table(:fs_actions) if FXC.db.tables.include? :fs_actions + end +end diff --git a/db/migrations/027_create_anti_actions.rb b/db/migrations/027_create_anti_actions.rb new file mode 100644 index 0000000..25cba4d --- /dev/null +++ b/db/migrations/027_create_anti_actions.rb @@ -0,0 +1,28 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +Class.new Sequel::Migration do + def up + create_table(:fs_anti_actions) do + primary_key :id + String :name + String :description + String :application + String :data + Integer :position, :null => false + foreign_key :condition_id, :fs_conditions, :on_update => :cascade, :on_delete => :cascade + end unless FXC.db.tables.include? :fs_anti_actions + execute "COMMENT ON TABLE fs_anti_actions IS 'Storage for Dialplan actions'" + execute "COMMENT ON COLUMN fs_anti_actions.name IS 'The name of this action'" + execute "COMMENT ON COLUMN fs_anti_actions.description IS 'Description of this action'" + execute "COMMENT ON COLUMN fs_anti_actions.application IS 'Which application to run'" + execute "COMMENT ON COLUMN fs_anti_actions.data IS 'The arguments to send to the application'" + execute "COMMENT ON COLUMN fs_anti_actions.position IS 'The order to perform actions in'" + execute "COMMENT ON COLUMN fs_anti_actions.condition_id IS 'The associated condition record'" + end + + def down + drop_table(:fs_anti_actions) if FXC.db.tables.include? :fs_anti_actions + end +end diff --git a/helper/not_found.rb b/helper/not_found.rb new file mode 100644 index 0000000..6345d78 --- /dev/null +++ b/helper/not_found.rb @@ -0,0 +1,9 @@ +module Innate + module Helper + module NotFound + def not_found + respond FXC::Proxy.render_view(:not_found), 200, 'Content-Type' => 'freeswitch/xml' + end + end + end +end diff --git a/import_couch.rb b/import_couch.rb new file mode 100644 index 0000000..f351772 --- /dev/null +++ b/import_couch.rb @@ -0,0 +1,123 @@ +require 'makura' +require 'pp' +require 'nokogiri' + +module Convert + module_function + + def xml_curl(xml, doc) + doc[:bindings] = bindings = {} + + xml.xpath('bindings/binding').each do |binding| + bindings[binding[:name]] = params = {} + + binding.xpath('param').each do |param| + if param[:name] == 'gateway-url' + params[:config] = { + 'gateway-url' => param[:value], + 'bindings' => param[:bindings], + } + else + params[param[:name]] = param[:value] + end + end + end + end + + def console(xml, doc) + doc[:mappings] = mappings = {} + xml.xpath('mappings/map').each do |map| + mappings[map[:name]] = map[:value] + end + + _settings(xml, doc) + end + + def logfile(xml, doc) + doc[:profiles] = profiles = {} + xml.xpath('profiles/profile').each do |profile| + profiles[profile[:name]] = ph = {} + _settings(profile, ph) + ph[:mappings] = pm = {} + profile.xpath('mappings/map').each do |map| + pm[map[:name]] = map[:value].scan(/[^\s,]+/) + end + end + + _settings(xml, doc) + end + + def enum(xml, doc) + _settings(xml, doc) + doc[:routes] = routes = [] + xml.xpath('routes/route').each do |route| + routes << route.attributes + end + end + + def xml_cdr(xml, doc) + doc[:description] = 'XML CDR cURL Logger' + _settings(xml, doc) + end + + def cdr_csv(xml, doc) + doc[:description] = 'CDR CSV Format' + _settings(xml, doc) + doc[:templates] = templates = {} + xml.xpath('templates/template').each do |template| + templates[template[:name]] = template.inner_text + end + end + + def event_socket(xml, doc) + doc[:description] = 'Socket Client' + _settings(xml, doc) + end + + def sofia(xml, doc) + pp xml + throw :ignore + # TODO + end + + def loopback(xml, doc) + throw :ignore + end + + def _settings(xml, doc) + doc[:settings] = settings = {} + xml.xpath('settings/param').each do |param| + settings[param[:name]] = param[:value] + end + end +end + +Makura::Model.server = 'http://jimmy:5984' +Makura::Model.database = "fxc_spec_#{Time.now.to_i}" +DB = Makura::Model.database + +modules_xml = File.expand_path('~/conf/autoload_configs/modules.conf.xml') +Nokogiri::XML(File.read(modules_xml)).xpath('/configuration/modules/load[@module]').each do |tag| + mod = tag['module'].sub(/^mod_/, '') + mod_xml = File.join(File.dirname(modules_xml), "#{mod}.conf.xml") + begin + xml = Nokogiri::XML(File.read(mod_xml)).xpath('/configuration') + rescue Errno::ENOENT + $stderr.puts "No config file found for #{mod_xml}" + next + end + + doc = { + name: "#{mod}.conf", + database: nil, + '_id' => "#{mod}.conf", + } + + catch :ignore do + Convert.send(mod, xml, doc) + DB.save(doc) + + pp DB[doc['_id']] + end + +end diff --git a/layout/dialplan.xhtml b/layout/dialplan.xhtml new file mode 100644 index 0000000..cbeb694 --- /dev/null +++ b/layout/dialplan.xhtml @@ -0,0 +1,10 @@ +<?xml version="1.0" encoding="UTF-8" standalone="no"?> +<include> + <document type="freeswitch/xml"> + <section name="dialplan" description="arbitrary stuff here"> + <context name="#{@context.name}"> + #@content + </context> + </section> + </document> +</include> diff --git a/layout/directory.xhtml b/layout/directory.xhtml new file mode 100644 index 0000000..32f14b3 --- /dev/null +++ b/layout/directory.xhtml @@ -0,0 +1,10 @@ +<?xml version="1.0" encoding="UTF-8" standalone="no"?> +<include> + <document type="freeswitch/xml"> + <section name="directory" description="arbitrary stuff here"> + <domain name="$${domain}"> + #@content + </domain> + </section> + </document> +</include> diff --git a/lib/fxc.rb b/lib/fxc.rb index 53d31d8..e2b234e 100644 --- a/lib/fxc.rb +++ b/lib/fxc.rb @@ -1,65 +1,26 @@ - -module Fxc - - # :stopdoc: - LIBPATH = ::File.expand_path(::File.dirname(__FILE__)) + ::File::SEPARATOR - PATH = ::File.dirname(LIBPATH) + ::File::SEPARATOR - # :startdoc: - - # Returns the version string for the library. - # - def self.version - @version ||= File.read(path('version.txt')).strip - end - - # Returns the library path for the module. If any arguments are given, - # they will be joined to the end of the libray path using - # <tt>File.join</tt>. - # - def self.libpath( *args, &block ) - rv = args.empty? ? LIBPATH : ::File.join(LIBPATH, args.flatten) - if block - begin - $LOAD_PATH.unshift LIBPATH - rv = block.call - ensure - $LOAD_PATH.shift - end - end - return rv - end - - # Returns the lpath for the module. If any arguments are given, - # they will be joined to the end of the path using - # <tt>File.join</tt>. - # - def self.path( *args, &block ) - rv = args.empty? ? PATH : ::File.join(PATH, args.flatten) - if block - begin - $LOAD_PATH.unshift PATH - rv = block.call - ensure - $LOAD_PATH.shift - end - end - return rv +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +require "pathname" + +class Pathname + def /(other) + join(other.to_s) end - - # Utility method used to require all files ending in .rb that lie in the - # directory below this file that has the same name as the filename passed - # in. Optionally, a specific _directory_ name can be passed in such that - # the _filename_ does not have to be equivalent to the directory. - # - def self.require_all_libs_relative_to( fname, dir = nil ) - dir ||= ::File.basename(fname, '.*') - search_me = ::File.expand_path( - ::File.join(::File.dirname(fname), dir, '**', '*.rb')) - - Dir.glob(search_me).sort.each {|rb| require rb} +end + +$LOAD_PATH.unshift(File.expand_path("../", __FILE__)) +module FXC + ROOT = Pathname($LOAD_PATH.first).join("..").expand_path + LIBROOT = ROOT/:lib + MIGRATION_ROOT = ROOT/:db/:migrations + MODEL_ROOT = ROOT/:model + SPEC_HELPER_PATH = ROOT/:spec + def self.load_fsr + require "fsr" + rescue LoadError + require "rubygems" + require "fsr" end - -end # module Fxc - -Fxc.require_all_libs_relative_to(__FILE__) - +end diff --git a/lib/fxc/db.rb b/lib/fxc/db.rb new file mode 100644 index 0000000..1f23a99 --- /dev/null +++ b/lib/fxc/db.rb @@ -0,0 +1,84 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# See the LICENSE file which accompanies this software for the full text +# +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +begin + require "sequel" +rescue LoadError + require "rubygems" + require "sequel" +end +require "logger" + +module FXC + unless defined?(@@db) + @@db = nil + end + + def self.db + setup_db + end + + def self.db=(other) + @@db = other + end + + private + + def self.parse_pgpass(file, database) + dbs = {} + + defaults = { + host: "localhost", port: 5432, db: database, + user: ENV["USER"], password: nil + } + + file.readlines.each do |line| + chunks = line.strip.split(/:/) + dbs[chunks[2]] = Hash[defaults.keys.zip(chunks)] + end + + db = dbs[database] || dbs['*'] + if db + chosen = db.reject{|k,v| !v || v == '*' } + defaults.merge(chosen) + else + fail("Either #{database}, *, or db named in APP_DB not found in .pgpass") + end + end + + def self.setup_db(root = FXC::ROOT, default_app = 'fxc') + return @@db if @@db + + app_db = ENV["APP_DB"] || default_app + app_env = ENV["APP_ENV"] || "development" + root_pgpass = root/".pgpass" + home_pgpass = Pathname('~/.pgpass').expand_path + + if root_pgpass.file? + conn = parse_pgpass(root_pgpass, app_db) + elsif home_pgpass.file? + conn = parse_pgpass(home_pgpass, app_db) + else + msg = "You have no %p or %p, can't determine connection" + fail(msg % [root_pgpass.to_s, home_pgpass.to_s]) + end + + logfile = root/:log/"#{app_env}.log" + logfile.parent.mkpath + logger = ::Logger.new(logfile) + + if app_db.nil? + logger.debug("setup_db called but no database defined") + @@db = nil + else + logger.info("Connecting to #{app_db}") + conn[:logger] = logger + @@db = ::Sequel.postgres(app_db, conn) + end + end +end diff --git a/lib/fxc/dialstring.rb b/lib/fxc/dialstring.rb new file mode 100644 index 0000000..aceb811 --- /dev/null +++ b/lib/fxc/dialstring.rb @@ -0,0 +1,52 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +module FXC + class Dialstring + attr_reader :user, :targets, :default_dialstring, :provider + def initialize(user, targets, default_dialstring = nil, provider = nil) + @user = user + @targets = targets + @default_dialstring = default_dialstring || @user.values[:dialstring] + @provider = provider + @provider = FXC::Provider[:priority => 0] if @provider.nil? + @provider = FXC::Provider.new(:host => "sip.example.com", :prefix => "1") if @provider.nil? + end + + def to_s + dialstring + end + + def dialstring + if targets.size > 0 + # If they have forwarding targets, sort them by priority and create an array + # of arrays of targets. + targets.sort_by { |p| p.priority }.inject([[]]) do |dial_array, current| + last = dial_array.last + # If we're the same priority or the first entry, add to the targets + # in the last array + if last.size == 0 or last.last.priority == current.priority + last << current + else + # Otherwise we must be a new (lower) priority, add that to dial_array as a + # new array of lower priority level targets + dial_array << [current] + end + dial_array + # Then we inject the dialstring string representation of the Targets + # into another array, join it on commas, and join the different + # levels of priority target strings on pipes + end.inject([]) do |l, t| + l << t.map do |tgt| + provider.format(tgt.value) + end.join(",") + end.join("|") + else + default_dialstring + end + end + + end +end + diff --git a/lib/rack/middleware.rb b/lib/rack/middleware.rb index e65338b..8f13f89 100644 --- a/lib/rack/middleware.rb +++ b/lib/rack/middleware.rb @@ -1,88 +1,90 @@ # Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> # Distributed under the terms of the MIT license. # The full text can be found in the LICENSE file included with this software # -module Fxc +module FXC module Rack class Middleware def initialize(app) @app = app end def call(env) params = ::Rack::Request.new(env) if params["section"] path = params["section"] + "/" path << case path when "dialplan/" dp_req(params) when "directory/" dir_req(params) when "configuration/" conf_req(params) end path << "/#{params["hostname"]}" - env["PATH_INFO"] = "#{env['PATH_INFO']}/#{path}".squeeze('/') + env["PATH_INFO"] = "#{env['PATH_INFO']}/#{path}".squeeze('/').sub(%r{/$},'') +=begin env["REQUEST_URI"] = ("%s://%s/%s" % [ env["rack.url_scheme"], env["HTTP_HOST"], env["PATH_INFO"]]).squeeze('/') +=end end @app.call(env) end private def dp_req(params) s = [params["Caller-Context"]] s << params["Caller-Destination-Number"] s << params["Caller-Caller-ID-Number"] s.compact.join("/") end def dir_req(params) s = [] if params["purpose"] s << params["purpose"].gsub("-","_") s << params["sip_profile"] elsif params["action"] && params["action"] == "sip_auth" s << "register" s << params["sip_profile"] s << params["sip_auth_username"] elsif params["user"] if params["action"] == "message-count" s << "messages" s << params["user"] s << params["key_value"] if params["tag_name"] == "domain" elsif params["Event-Calling-Function"] case params["Event-Calling-Function"].to_s when /voicemail/ s << "voicemail" s << (params["sip_profile"] || "default") s << params["user"] when "user_outgoing_channel" s << "user_outgoing" s << params["user"] s << params["domain"] if params["domain"] when "user_data_function" s << "user_data" s << params["user"] s << params["domain"] if params["domain"] end end end s.join("/") end def conf_req(params) s = [] if params["key_name"] == "name" s << params["key_value"] end s.join("/") end end end end diff --git a/model/action.rb b/model/action.rb new file mode 100644 index 0000000..bdd30ec --- /dev/null +++ b/model/action.rb @@ -0,0 +1,29 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# + +class FXC::Action < Sequel::Model + set_dataset FXC.db[:fs_actions] + many_to_one :condition, :class => 'FXC::Condition' + plugin :list, :scope => :condition_id + + protected + def before_save + base = FXC::Action.filter(:condition_id => self.condition_id) + base = base.filter(~{:id => self.id}) if self.id + max = base.order(:position.asc).last.position rescue -1 + if self.position + p = self.position.to_i + if p > max + self.position = max + 1 + else + bigger = base.filter{|o| o.position >= p} + bigger.update("position = (position + 1)") + end + else + self.position = max + 1 + end + end + +end diff --git a/model/anti_action.rb b/model/anti_action.rb new file mode 100644 index 0000000..692f1e5 --- /dev/null +++ b/model/anti_action.rb @@ -0,0 +1,28 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# + +class FXC::AntiAction < Sequel::Model + set_dataset FXC.db[:fs_anti_actions] + many_to_one :condition, :class => 'FXC::Condition' + plugin :list, :scope => :condition_id + + protected + def before_save + base = FXC::AntiAction.filter(:condition_id => self.condition_id) + base = base.filter(~{:id => self.id}) if self.id + max = base.order(:position.asc).last.position rescue -1 + if self.position + p = self.position.to_i + if p > max + self.position = max + 1 + else + bigger = base.filter{|o| o.position >= p} + bigger.update("position = (position + 1)") + end + else + self.position = max + 1 + end + end +end diff --git a/model/condition.rb b/model/condition.rb new file mode 100644 index 0000000..2e8ef5e --- /dev/null +++ b/model/condition.rb @@ -0,0 +1,41 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# + +class FXC::Condition < Sequel::Model + set_dataset FXC.db[:fs_conditions] + one_to_many :actions, :class => 'FXC::Action' + one_to_many :anti_actions, :class => 'FXC::AntiAction' + many_to_one :context, :class => 'FXC::Context' + plugin :list, :scope => :extension_id + + def break_string + case self.break + when nil + 'never' + when false + 'on-false' + when true + 'on-true' + end + end + protected + def before_save + base = FXC::Condition.filter(:extension_id => extension_id) + base = base.filter(~{:id => self.id}) if self.id + max = base.order(:position.asc).last.position rescue -1 + if self.position + p = self.position.to_i + if p > max + self.position = max + 1 + else + bigger = base.filter{|o| o.position >= p} + bigger.update("position = (position + 1)") + end + else + self.position = max + 1 + end + end + +end diff --git a/node/configuration.rb b/model/configuration.rb similarity index 58% rename from node/configuration.rb rename to model/configuration.rb index d923ea0..d40d1bd 100644 --- a/node/configuration.rb +++ b/model/configuration.rb @@ -1,57 +1,28 @@ -require 'innate' -require 'makura' -Makura::Model.database = 'fxc' - -module Fxc - class Proxy - Innate.node "/", self - provide :html, engine: :None - - def index - "Welcome to Fxc!" - end - - def configuration(name, hostname) - response['Content-Type'] = 'freeswitch/xml' - - Configuration.render(name, hostname).to_s + "\n" - - rescue Makura::Error => ex - Innate::Log.error(ex) - <<-XML -<document type="freeswitch/xml"> - <section name="result"> - <result status="not found" /> - </section> -</document> - XML - end - end - +module FXC class Configuration include Makura::Model property :name property :server def self.render(name, hostname, opts = {}) if name == "sofia.conf" Configuration.render_sofia(hostname) else Configuration.render_common(name, hostname) end end def self.render_common(name, hostname, opts = {}) keys = [[name, hostname], [name, nil]] opts.merge!(:payload => {'keys' => keys}, 'Content-Type' => 'application/json', :limit => 1) database.post("_design/configuration/_list/#{name}/conf", opts) end def self.render_sofia(hostname, opts = {}) database.get("_design/configuration/_list/sofia/sofia_profiles", startkey: [hostname, 0], endkey: [hostname, 1]) end end end diff --git a/model/context.rb b/model/context.rb new file mode 100644 index 0000000..c4431b0 --- /dev/null +++ b/model/context.rb @@ -0,0 +1,23 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +class FXC::Context < Sequel::Model(FXC.db[:dialplan_contexts]) + one_to_many :users, :class => 'FXC::User' + one_to_many :dids, :class => 'FXC::Did' + one_to_many :extensions, :class => 'FXC::Extension' + one_to_many :gateways, :class => 'FXC::SipGateway', :key => :dialplan_context_id + + @scaffold_human_name = 'DID Context' + @scaffold_column_types = { + :description => :string + } + + def self.default + find_or_create(:name => "default") + end + + def self.public + find_or_create(:name => "public") + end +end diff --git a/model/did.rb b/model/did.rb new file mode 100644 index 0000000..05600ba --- /dev/null +++ b/model/did.rb @@ -0,0 +1,37 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# + +class FXC::Did < Sequel::Model(FXC.db[:dids]) + many_to_one :user, :class => 'FXC::User', :one_to_one => true + one_to_many :targets, :class => 'FXC::Target' + many_to_one :context, :class => 'FXC::Context' + + @scaffold_human_name = 'DID' + @scaffold_column_types = { + :number => :integer, + :description => :string, + :clid_name => :string, + } + + def scaffold_name + "#{clid_name} (#{number})" + end + + def dialstring + FXC::Dialstring.new(user, targets, user.dialstring).to_s + end + + def after_create + FXC::Context.public.add_did(self) if context.nil? + end + + def blocked?(number, name = nil) + false + end + + def accept?(number, name = nil) + true + end +end diff --git a/model/extension.rb b/model/extension.rb new file mode 100644 index 0000000..07c0bcd --- /dev/null +++ b/model/extension.rb @@ -0,0 +1,65 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# + +class FXC::Extension < Sequel::Model + set_dataset FXC.db[:fs_extensions] + one_to_many :conditions, :class => 'FXC::Condition' + many_to_one :context, :class => 'FXC::Context' + plugin :list, :scope => :context_id + + + def self.match(context_id, params) + all = FXC::Extension.filter(:context_id => context_id).all + return nil unless all + fs_params = {} + params.each do |(key, value)| + case key + when /^variable_(.*)/ + fs_params[$1.downcase] = value + when /^Caller-(.*)/ + fs_params[$1.downcase.tr("-","_")] = value + end + end + matches = all.select do |exten| + exten.conditions.detect do |condition| + if match_val = fs_params[condition.matcher] + match_val.match(condition.expression) + else + false + end + end + end + + end + @scaffold_human_name = 'Extensions' + @scaffold_column_types = { + :name => :string, + :description => :string, + :context => :string + } + + def scaffold_name + "#{context} (#{name})" + end + + protected + def before_save + base = FXC::Extension.filter(:context_id => context_id) + base = base.filter(~{:id => self.id}) if self.id + max = base.order(:position.asc).last.position rescue -1 + if self.position + p = self.position.to_i + if p > max + self.position = max + 1 + else + bigger = base.filter{|o| o.position >= p} + bigger.update("position = (position + 1)") + end + else + self.position = max + 1 + end + end + +end diff --git a/model/init.rb b/model/init.rb new file mode 100644 index 0000000..c3266ed --- /dev/null +++ b/model/init.rb @@ -0,0 +1,25 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +require_relative '../lib/fxc' +require FXC::LIBROOT/:fxc/:db +raise "No DB Available" unless FXC.db + +require 'makura' +Makura::Model.database = 'fxc' + +# Here go your requires for models: +require_relative 'user' +require_relative 'user_variable' +require_relative 'target' +require_relative 'did' +require_relative 'provider' +require_relative 'context' +require_relative 'voicemail' +#require "sequel_orderable" +require_relative 'extension' +require_relative 'condition' +require_relative 'action' +require_relative 'anti_action' +require_relative 'configuration' diff --git a/model/provider.rb b/model/provider.rb new file mode 100644 index 0000000..e15cdbd --- /dev/null +++ b/model/provider.rb @@ -0,0 +1,18 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +class FXC::Provider < Sequel::Model(FXC.db[:providers]) + def format(number) + number.match(/^\d{10}$/) ? "sofia/external/#{format_s % number}#{port ? ":#{port}" : ""}" : number + end + + @scaffold_human_name = 'Provider' + @scaffold_column_types = {} + + private + + def format_s + "%s%%s@%s" % [prefix, host] + end +end diff --git a/model/target.rb b/model/target.rb new file mode 100644 index 0000000..018e0e0 --- /dev/null +++ b/model/target.rb @@ -0,0 +1,18 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +class FXC::Target < Sequel::Model(FXC.db[:targets]) + many_to_one :user, :class => 'FXC::User' + many_to_one :did, :class => 'FXC::Did' + + @scaffold_human_name = 'Target' + @scaffold_column_types = { + :type => :string, + :value => :string, + } + + def dialstring + value + end +end diff --git a/model/user.rb b/model/user.rb new file mode 100644 index 0000000..db4ad8a --- /dev/null +++ b/model/user.rb @@ -0,0 +1,103 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +require File.expand_path("../../lib/fxc", __FILE__) +require FXC::ROOT/:lib/:fxc/:dialstring +require "digest/sha1" +class FXC::User < Sequel::Model(FXC.db[:users]) + one_to_many :user_variables, :class => 'FXC::UserVariable' + one_to_many :targets, :class => 'FXC::Target' + one_to_many :dids, :class => 'FXC::Did' + many_to_one :context, :class => 'FXC::Context' + + @scaffold_human_name = 'User' + @scaffold_column_types = { + :cidr => :string, + :email => :string, + :first_name => :string, + :last_name => :string, + :timezone => :string, + :mailbox => :string, + :dialstring => :string, + :password => :string, + } + + def scaffold_name + "#{display_name} (#{username})" + end + + def fullname + [first_name, last_name].join(" ") + end + + def dialstring + pk ? FXC::Dialstring.new(self, targets).to_s : '' + end + + def default_variables + @_d_v ||= [ + [:user_context, :default], + [:accountcode, username], + [:toll_allow, "domestic,international,local"], + [:effective_caller_id_number, username], + [:effective_caller_id_name, fullname] + ] + end + + def set_default_variables + update(:mailbox => extension) if mailbox.nil? + FXC::Context.default.add_user(self) if context.nil? + default_variables.each do |var| + name, value = var.map { |s| s.to_s } + if current = user_variables.detect { |d| d.name == name } + current.value = value + current.save + else + add_user_variable(FXC::UserVariable.new(:name => name, :value => value)) + end + end + end + + def self.active_users + filter(:active => true) + end + + # auth related stuff + # + # id may be email or username, but password has to be given for either. + def self.authenticate(creds) + id, password = creds.values_at(:id, :password) + filter({:username => id} | {:email => id}). + and(:password => digestify(password)).limit(1).first + end + + def self.digestify(pass) + Digest::SHA1.hexdigest(pass.to_s) + end + + def password=(other) + values[:password] = ::FXC::User.digestify(other) + end + + protected + def after_create + set_default_variables + end + + def validate + if new? + @errors.add(:extension, "can not be directly assigned above 3175") if extension and extension > 3175 + end + if me = FXC::User[:extension => extension] + @errors.add(:extension, "can not be duplicated") unless self[:id] and me[:id] == self[:id] + end + if username and my_user = FXC::User[:username => username] + @errors.add(:username, "can not be duplicated") unless self[:id] and my_user[:id] == self[:id] + end + @errors.add(:email, "must be a valid email address") unless email.to_s.match(/^(?:[^@\s]+?@[^\s@]{6,})?$/) + @errors.add(:pin, "must be all digits (4 minimum)") unless pin.to_s.match(/^(?:\d\d\d\d+)?$/) + @errors.add(:extension, "must be all digits (4 minimum)") unless extension.to_s.match(/^(?:\d\d\d\d+)?$/) + @errors.add(:mailbox, "must be all digits (4 minimum)") unless mailbox.to_s.match(/^(?:\d\d\d\d+)?$/) + end +end diff --git a/model/user_variable.rb b/model/user_variable.rb new file mode 100644 index 0000000..25d6271 --- /dev/null +++ b/model/user_variable.rb @@ -0,0 +1,17 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +class FXC::UserVariable < Sequel::Model(FXC.db[:user_variables]) + many_to_one :user, :class => 'FXC::User' + + @scaffold_human_name = 'User Variable' + @scaffold_column_types = { + :name => :string, + :value => :string, + } + + def scaffold_name + "#{name}: #{value}" + end +end diff --git a/model/voicemail.rb b/model/voicemail.rb new file mode 100644 index 0000000..8aad475 --- /dev/null +++ b/model/voicemail.rb @@ -0,0 +1,18 @@ +class FXC::Voicemail < Sequel::Model(FXC.db[:voicemail_msgs]) + @scaffold_human_name = 'Voicemail' + @scaffold_column_types = { + :cid_name => :string, + :cid_number => :string, + :domain => :string, + :file_path => :string, + :flags => :string, + :in_folder => :string, + :read_flags => :string, + :username => :string, + :uuid => :string, + } + + def timestamp + Time.at(created_epoch).utc.strftime("%m/%d/%Y %H:%M") + end +end diff --git a/node/dialplan.rb b/node/dialplan.rb new file mode 100644 index 0000000..ed9ef8c --- /dev/null +++ b/node/dialplan.rb @@ -0,0 +1,49 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +module FXC + class Dialplan + Innate.node "/dialplan", self + layout :dialplan + helper :not_found + + def index(context = nil, number = nil, caller_id = nil, *rest) + @context = FXC::Context.first(:name => context) + if @context + Innate::Log.info("<<#{context}>> dialplan request: #{"%s => %s (%s)" % [caller_id, number, rest.join(" ")]}") + @did = FXC::Did.first(:number.like Regexp.new(number.sub(/^1(\d{10})/,'1?\1'))) + if @did + @user = @did.user + name = request.params["Caller-Caller-ID-Name"] || number + if action = @did.blocked?(number, name) + Innate::Log.info("Blocking from #{"%s: %s" % [number, name]} to #{@did.number} with #{action}") + begin + render_view("blocked_#{action}") + rescue + render_view(:blocked_call) + end + else + @targets = @did.targets + Innate::Log.info("Routing #{@did.number} in '#{context}'. dialstring: (#{@user.dialstring})") + # This will render the view named as the context (view/public.xhtml for public, etc) + # or fallback to the view/did.xhtml template + render_view(context.to_sym) rescue render_view(:did) + end + else + @extensions = FXC::Extension.match(@context.id, request.params) + if @extensions.size > 0 + Innate::Log.info("Routing to #{@extensions.inspect}") + render_view(:extension) + else + Innate::Log.info("No Matches!: " + request.inspect) + not_found + end + end + else + Innate::Log.info("Got unhandled dialplan request: " + request.inspect) + not_found + end + end + end +end diff --git a/node/directory.rb b/node/directory.rb new file mode 100644 index 0000000..d9501e4 --- /dev/null +++ b/node/directory.rb @@ -0,0 +1,53 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +module FXC + class Directory + Innate.node "/directory", self + layout :directory + helper :not_found + + def index(*args) + Innate::Log.info("Received unhandled directory request: #{request.inspect}") + not_found + end + + def register(profile, extension) + Innate::Log.debug("Received register directory request: #{request.inspect}") + user = User[:extension => extension.to_i, :active => true] + user ? render_view(:user, :user => user) : not_found + end + + def user_data(extension, domain = nil) + Innate::Log.debug("Received user_data directory request: #{request.inspect}") + user = User[:extension => extension.to_i] + user ? render_view(:user, :user => user) : not_found + end + + def user_outgoing(extension, domain = nil) + Innate::Log.debug("Received user_outgoing directory request: #{request.inspect}") + user = User[:extension => extension.to_i] + user ? render_view(:user, :user => user) : not_found + end + + #TODO respond with a proper message count response (see FS wiki) + def messages(extension, domain = nil) + Innate::Log.debug("Received messages directory request: #{request.inspect}") + user = User[:extension => extension.to_i] + user ? render_view(:user, :user => user) : not_found + end + + def voicemail(profile, extension) + Innate::Log.debug("Received voicemail directory request: #{request.inspect}") + user = User[:extension => extension.to_i] + user ? render_view(:user, :user => user) : not_found + end + + def network_list(profile = "default") + Innate::Log.debug("Received network_list directory request: #{request.inspect}") + render_view(:users, :users => User.active_users) + end + + end +end diff --git a/node/proxy.rb b/node/proxy.rb new file mode 100644 index 0000000..b88e36c --- /dev/null +++ b/node/proxy.rb @@ -0,0 +1,25 @@ +module FXC + class Proxy + Innate.node "/", self + provide :html, engine: :None + helper :not_found + + def index + "Welcome to FXC!" + end + + def configuration(name, hostname) + response['Content-Type'] = 'freeswitch/xml' + + Configuration.render(name, hostname).to_s + "\n" + + rescue Makura::Error => ex + Innate::Log.error(ex) + not_found + end + end + +end + +require_relative 'directory' +require_relative 'dialplan' diff --git a/spec/db_helper.rb b/spec/db_helper.rb new file mode 100644 index 0000000..d94ab1a --- /dev/null +++ b/spec/db_helper.rb @@ -0,0 +1,76 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +begin + require "sequel" +rescue LoadError + require "rubygems" + require "sequel" +end +require "logger" +ENV["PGHOST"] = PGHOST = "/tmp" +ENV["PGPORT"] = PGPORT = "5433" +# set PG_TEST_DIR to a location which you have write access to, +# /dev/shm on linux makes it happen in memory. +SHM = ENV["PG_TEST_DIR"] || "/dev/shm" +ENV['PGDATA'] = PGDATA = "#{SHM}/fxc" +DB_LOG = Logger.new("/tmp/fxc_spec.log") + +def runcmd(command) + IO.popen(command) do |sout| + out = sout.read.strip + out.each_line { |l| DB_LOG.info(l) } + end + $? == 0 +end + +def startdb + return true if runcmd %{pg_ctl status -o "-k /tmp"} + DB_LOG.info "Starting DB" + runcmd %{pg_ctl start -w -o "-k /tmp" -l /tmp/fxcdb.log} +end + +def stopdb + DB_LOG.info "Stopping DB" + if runcmd %{pg_ctl status -o "-k /tmp"} + runcmd %{pg_ctl stop -w -o "-k /tmp"} + else + true + end +end + +def initdb + DB_LOG.info "Initializing DB" + raise "#{SHM} not found!" unless File.directory?(SHM) + return true if File.directory?(PGDATA) + runcmd %{initdb} +end + +def createdb + runcmd %{dropdb fxc} + runcmd %{createdb fxc} +end + +begin + puts "Initializing" + raise "initdb failed" unless initdb + puts "Starting" + raise "startdb failed" unless startdb + puts "Creating" + raise "createdb failed" unless createdb +rescue Errno::ENOENT => e + $stderr.puts "\n<<<Error>>> #{e}, do you have the postgres tools in your path?" + exit 1 +rescue RuntimeError => e + $stderr.puts "\n<<<Error>>> #{e}, do you have the postgres tools in your path?" + exit 1 +end +require_relative "../lib/fxc" +require FXC::LIBROOT/:fxc/:db +FXC.db = Sequel.postgres("fxc", :user => ENV["USER"], :host => PGHOST, :port => PGPORT) +require 'sequel/extensions/migration' +# go to latest migration +Sequel::Migrator.apply(FXC.db, FXC::MIGRATION_ROOT) + +require FXC::SPEC_HELPER_PATH/:helper diff --git a/spec/directory_data.rb b/spec/directory_data.rb new file mode 100644 index 0000000..423ab09 --- /dev/null +++ b/spec/directory_data.rb @@ -0,0 +1,28 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +require FXC::SPEC_HELPER_PATH/:db_helper + +user1 = FXC::User.create(:extension => "1901", :pin => "2121", :mailbox => "1901") +user1.active = true +user1.save + +user1.add_did(FXC::Did.new(:number => "1901", :clid_name => "Joe Smith", :description => "Inbound DID Test")) + +user2 = FXC::User.create(:extension => "1902", :pin => "3131", :mailbox => "1902") +user2.active = true +user2.save + +user2.add_did(FXC::Did.new(:number => "1902", :clid_name => "John Doe", :description => "Inbound DID Test #2")) + +user2.add_target(FXC::Target.new(:value => "${sofia_contact(default/1902@${dialed_domain})}")) + +user3 = FXC::User.create(:extension => "1903", :pin => "3131") +user3.active = true +user3.save + +user3.add_did(FXC::Did.new(:number => "9044441234", :clid_name => "Jane Doe", :description => "Inbound DID Test #3")) +user3.add_target(FXC::Target.new(:value => "8173331111")) + +vmail1 = FXC::Voicemail.create(:created_epoch => 1244584744, :read_epoch => 0, :username => "1901", :domain => "127.0.0.1", :uuid => "abcd-1234-efgh-5678", :cid_name =>"Joe", :cid_number=>"8675309", :in_folder=>"inbox", :file_path=>"/path/to/file.wav", :message_len=>28, :flags => "", :read_flags => "B_NORMAL") diff --git a/spec/fsr_helper.rb b/spec/fsr_helper.rb new file mode 100644 index 0000000..648e1b5 --- /dev/null +++ b/spec/fsr_helper.rb @@ -0,0 +1,10 @@ +begin + require "fsr" +rescue LoadError + require "rubygems" + require "fsr" +end +require FSR::ROOT/"../spec/fsr_listener_helper" +require FSR::ROOT/"fsr/listener/outbound" +require FSR::ROOT/"fsr/listener/mock" +require "em-spec/bacon" diff --git a/spec/fxc/lib/dialstring.rb b/spec/fxc/lib/dialstring.rb new file mode 100644 index 0000000..97e88ee --- /dev/null +++ b/spec/fxc/lib/dialstring.rb @@ -0,0 +1,78 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +require File.expand_path("../../../db_helper", __FILE__) +require FXC::ROOT/:lib/:fxc/:dialstring +describe "Dialstring" do + @user = FXC::User.create(:extension => "1909", :pin => "1234") + it "should return the user's dialstring when there are no targets given, and no default" do + dialstring = FXC::Dialstring.new(@user, []) + dialstring.to_s.should.equal @user.values[:dialstring] + end + + it "should return the dialstring passed as default when there are no targets given" do + dialstring = FXC::Dialstring.new(@user, [], endpoint = "sofia/external/[email protected]") + dialstring.to_s.should.equal endpoint + end + + it "should return a single target when it is passed and no default given" do + target = FXC::Target.find_or_create(:value => "user/1909") + target.priority.should.equal 1 + target.dialstring.should.equal "user/1909" + dialstring = FXC::Dialstring.new(@user, [target]) + dialstring.to_s.should.equal target.dialstring + end + + it "should return a single target with a dummy provider when none are in the db" do + target = FXC::Target.find_or_create(:value => "8881112345") + dialstring = FXC::Dialstring.new(@user, [target], "error/do-not-call") + dialstring.provider.format(target.dialstring).should.equal "sofia/external/[email protected]" + dialstring.to_s.should.equal dialstring.provider.format(target.dialstring) + end + + it "should return a single target with a provider of priority 0 when it exists in the db" do + begin + provider = FXC::Provider.create(:host => "sip.unexample.net", :prefix => "7") + target = FXC::Target.find_or_create(:value => "8881112345") + dialstring = FXC::Dialstring.new(@user, [target], "error/do-not-call") + dialstring.provider.format(target.dialstring).should.equal "sofia/external/[email protected]:5060" + dialstring.to_s.should.equal dialstring.provider.format(target.dialstring) + ensure + provider.destroy + end + end + + it "should return a target for the given provider when a provider is passed" do + target = FXC::Target.find_or_create(:value => "8881112345") + dialstring = FXC::Dialstring.new(@user, [target], "error/do-not-call", FXC::Provider.new(:host => "sip.example2.com", :prefix => "")) + dialstring.provider.format(target.dialstring).should.equal "sofia/external/[email protected]" + dialstring.to_s.should.equal dialstring.provider.format(target.dialstring) + end + + # All subsequent specs will call #new with the default of error/do-not-call + + it "should return two targets to ring concurrently when they're the same priority" do + target1 = FXC::Target.find_or_create(:value => "user/1909") + target2 = FXC::Target.find_or_create(:value => "user/1910") + dialstring = FXC::Dialstring.new(@user, [target1, target2], "error/do-not-call") + dialstring.to_s.should.equal "user/1909,user/1910" + end + + it "should return two targets to ring alternately when they're different priorities" do + target1 = FXC::Target.find_or_create(:value => "user/1909") + target2 = FXC::Target.find_or_create(:value => "user/1910", :priority => 2) + target2.priority.should.equal 2 + dialstring = FXC::Dialstring.new(@user, [target1, target2], "error/do-not-call") + dialstring.to_s.should.equal "user/1909|user/1910" + end + + it "should return primary target, then two concurrent secondaries, and a fallback target" do + target1 = FXC::Target.find_or_create(:value => "[call-timeout=10]user/1909") + target2 = FXC::Target.find_or_create(:value => "user/1910", :priority => 2) + target3 = FXC::Target.find_or_create(:value => "user/1911", :priority => 2) + target4 = FXC::Target.find_or_create(:value => "user/1912", :priority => 3) + dialstring = FXC::Dialstring.new(@user, [target1, target2, target3, target4], "error/do-not-call") + dialstring.to_s.should.equal "[call-timeout=10]user/1909|user/1910,user/1911|user/1912" + end +end diff --git a/spec/fxc/lib/rack/middleware.rb b/spec/fxc/lib/rack/middleware.rb new file mode 100644 index 0000000..32c3b98 --- /dev/null +++ b/spec/fxc/lib/rack/middleware.rb @@ -0,0 +1,76 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +require_relative "../../../db_helper" +require "rubygems" +require "rack/test" + +describe "Dialplan Routing" do + User, Did, Target = FXC::User, FXC::Did, FXC::Target + behaves_like :rack_test + + it "routes a dialplan request to /dialplan/context/" do + user = User.find_or_create(:username => "potato") + did = user.add_did(Did.new(:number => '2345678900')) + did = user.add_target(Target.new(:value => '9994441234')) + post "/", "section" => "dialplan", "Caller-Context" => 'public', "Caller-Destination-Number" => '12345678900' + last_request.env["PATH_INFO"].should == %q{/dialplan/public/12345678900} + last_response.body.should.include %q{expression="^1?(2345678900)$"} + end +end + +describe "Directory Routing" do + User, Did, Target = FXC::User, FXC::Did, FXC::Target + behaves_like :rack_test + + it "routes a register request to /directory/register/PROFILE/EXTENSION" do + user = User.find_or_create(:username => "pacman", :extension => 2122, :active => true) + post "/", "section" => "directory", "action" => 'sip_auth', "sip_profile" => 'internal', "sip_auth_username" => "2122" + last_request.env["PATH_INFO"].should.equal %q{/directory/register/internal/2122} + last_response.body.should.include %q{<user id="2122"} + end + + it "sends not found to /directory/register/PROFILE/EXTENSION if user is inactive" do + user = User.find_or_create(:username => "unpacman", :extension => 3122, :active => false) + post "/", "section" => "directory", "action" => 'sip_auth', "sip_profile" => 'internal', "sip_auth_username" => "3122" + last_request.env["PATH_INFO"].should.equal %q{/directory/register/internal/3122} + last_response.body.should.include %q{status="not found"} + end + + it "routes a voicemail request to /directory/voicemail/PROFILE/EXTENSION" do + user = User.find_or_create(:username => "pacman", :extension => 2122) + post "/", "section" => "directory", "Event-Calling-Function" => "voicemail_check", "user" => '2122', 'sip_profile' => 'special' + last_request.env["PATH_INFO"].should.equal %q{/directory/voicemail/special/2122} + last_response.body.should.include %q{<user id="2122"} + end + + it "routes a message-count request to /directory/messages/EXTENSION/DOMAIN" do + user = User.find_or_create(:username => "pacman", :extension => 2122) + post "/", "section" => "directory", "user" => '2122', 'action' => 'message-count', "tag_name" => "domain", "key_value" => "foo.example.com" + last_request.env["PATH_INFO"].should.equal %q{/directory/messages/2122/foo.example.com} + last_response.body.should.include 'mailbox="2122"' + end + + it "routes a user_data request to /directory/user_data/EXTENSION/DOMAIN" do + user = User.find_or_create(:username => "pacman", :extension => 2122) + post "/", "section" => "directory", "user" => '2122', "Event-Calling-Function"=>"user_data_function", "domain" => "foo.example.com" + last_request.env["PATH_INFO"].should.equal %q{/directory/user_data/2122/foo.example.com} + last_response.body.should.include 'mailbox="2122"' + end + + it "routes a user_outgoing_channel request to /directory/user_outgoing/EXTENSION/DOMAIN" do + user = User.find_or_create(:username => "pacman", :extension => 2122) + post "/", "section" => "directory", "user" => '2122', "Event-Calling-Function"=>"user_outgoing_channel", "domain" => "foo.example.com" + last_request.env["PATH_INFO"].should.equal %q{/directory/user_outgoing/2122/foo.example.com} + last_response.body.should.include 'mailbox="2122"' + end + + it "routes a network-list request to /directory/network_list/PROFILE" do + user = User.find_or_create(:username => "pacman", :extension => 2122) + user.update(:active => true) + post "/", "section" => "directory", "purpose" => 'network-list', 'sip_profile' => 'special' + last_request.env["PATH_INFO"].should.match %r{/directory/network_list/special} + last_response.body.should.include %q{<user id="2122"} + end +end diff --git a/spec/fxc_spec.rb b/spec/fxc_spec.rb index a0b8cf6..2ab1454 100644 --- a/spec/fxc_spec.rb +++ b/spec/fxc_spec.rb @@ -1,6 +1,6 @@ require File.join(File.dirname(__FILE__), %w[spec_helper]) -describe Fxc do +describe FXC do end diff --git a/spec/helper.rb b/spec/helper.rb new file mode 100644 index 0000000..4a52b8c --- /dev/null +++ b/spec/helper.rb @@ -0,0 +1,16 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +require File.expand_path('../../app', __FILE__) +require 'nokogiri' +require 'innate/spec/bacon' +Innate::Log.loggers = [Logger.new(FXC::ROOT/:log/"innate.log")] +Innate.middleware! :spec do |m| + m.use Rack::Lint + m.use Rack::CommonLogger, Innate::Log + m.use FXC::Rack::Middleware + m.innate +end + +Innate.options.roots = [FXC::ROOT] diff --git a/spec/model/context.rb b/spec/model/context.rb new file mode 100644 index 0000000..50c979d --- /dev/null +++ b/spec/model/context.rb @@ -0,0 +1,35 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +require File.expand_path('../../db_helper', __FILE__) +require FXC::ROOT/:spec/:directory_data + +describe 'FXC::Context' do + User, Target, Context, Did = FXC::User, FXC::Target, FXC::Context, FXC::Did + + it 'should always have a default context' do + default = Context.default + default.should.not.be.nil? + default.name.should.equal "default" + end + + it 'should always have a public context' do + pub = Context.public + pub.should.not.be.nil? + pub.name.should.equal "public" + end + + it "should list users in the context" do + user = User.find_or_create(:username => "msfoo") + Context.default.add_user(user).should.not.be.nil + Context.default.users.map { |u| u.username }.should.include "msfoo" + end + + it "should list DIDs in the context" do + did = Did.find_or_create(:number => "8675309") + Context.public.add_did(did).should.not.be.nil + Context.public.dids.map { |n| n.number }.should.include "8675309" + end + +end diff --git a/spec/model/did.rb b/spec/model/did.rb new file mode 100644 index 0000000..4da705d --- /dev/null +++ b/spec/model/did.rb @@ -0,0 +1,40 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +require File.expand_path('../../db_helper', __FILE__) +require FXC::ROOT/:spec/:directory_data + +describe 'Did' do + User, Did = FXC::User, FXC::Did + + it 'should have a DID' do + did = Did[:number => "1901"] + did.description.should == "Inbound DID Test" + end + + it 'should have a relationship to a user' do + did = Did[:number => "1901"] + user = did.user + user.class.should == FXC::User + end + + it "should use a user's default dialstring if it has no targets" do + did = Did[:number => "1901"] + did.dialstring.should == "{presence_id=${dialed_user}@$${domain}}${sofia_contact(default/${dialed_user}@$${domain})}" + end + + it "should change dialstring if it has a target" do + did = Did[:number => "1901"] + did.add_target(FXC::Target.new(:value => "sofia/default/[email protected]")) + did.dialstring.should == "sofia/default/[email protected]" + end + + it 'should set the did context to public upon creation' do + did = Did.new(:number => "1112223311") + did.context.should.be.nil + did.save.reload.context.should.not.be.nil + did.context.name.should.equal "public" + end + +end diff --git a/spec/model/provider.rb b/spec/model/provider.rb new file mode 100644 index 0000000..4e1bfa5 --- /dev/null +++ b/spec/model/provider.rb @@ -0,0 +1,21 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +require File.expand_path('../../db_helper', __FILE__) +require FXC::ROOT/:spec/:directory_data + +describe 'FXC::Provider' do + User, Target, Provider = FXC::User, FXC::Target, FXC::Provider + + it 'Should format a 10 digit number into a valid sofia url' do + provider = Provider.new(:host => 'sip.vtwhite.com', :prefix => 1, :name => "VTWhite") + provider.format("8179395222").should.equal "sofia/external/[email protected]" + end + + it 'Should not format a non 10 digit number' do + provider = Provider.new(:host => 'sip.vtwhite.com', :prefix => 1, :name => "VTWhite") + provider.format("${sofia_contact(default/2600@$${domain})}").should.equal "${sofia_contact(default/2600@$${domain})}" + end + +end diff --git a/spec/model/target.rb b/spec/model/target.rb new file mode 100644 index 0000000..a369902 --- /dev/null +++ b/spec/model/target.rb @@ -0,0 +1,26 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +require File.expand_path('../../db_helper', __FILE__) +require FXC::ROOT/:spec/:directory_data + +describe 'Target' do + User, Target = FXC::User, FXC::Target + + it 'Should change a users dialstring when we add a Target' do + user = User[:extension => "1901"] + user.dialstring.should == "{presence_id=${dialed_user}@$${domain}}${sofia_contact(default/${dialed_user}@$${domain})}" + user.add_target(Target.new(:value => "user/1901")) + user.dialstring.should == "user/1901" + end + + it 'Should change a did dialstring when we add a Target' do + user = User[:extension => "1901"] + (did = user.dids.first).number.should.equal "1901" + did.dialstring.should.equal user.dialstring + did.add_target(Target.new(:value => "sofia/external/[email protected]")) + did.dialstring.should.equal "sofia/external/[email protected]" + end + +end diff --git a/spec/model/user.rb b/spec/model/user.rb new file mode 100644 index 0000000..9a39d9c --- /dev/null +++ b/spec/model/user.rb @@ -0,0 +1,102 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +require File.expand_path('../../db_helper', __FILE__) + +describe 'FXC::User' do + User, Target = FXC::User, FXC::Target + @defaults = {:extension => 1234, :username => "fxc", :first_name => "tj", :last_name => "vanderpoel", :password => "a+b3t4r;pvs6"} + @auto_create_min = 3176 + + after do + User.delete + end + + it 'should auto-assign extension when none given' do + u = User.create(:first_name => "tj") + u.extension.should.equal @auto_create_min + end + + it 'should hash password on assingment' do + u = User.create(:username => "tj", :password => 'weak sauce') + u.password.should.not.equal 'weak sauce' + u.password.should.equal User.digestify('weak sauce') + end + + it 'should not allow directly assigned extensions in the auto-populate range (<3176)' do + lambda { User.create(:extension => 3177) }.should.raise(Sequel::ValidationFailed). + message.should.match /extension can not be directly assigned above #{@auto_create_min-1}/ + end + + it 'should require extension to be 4+ digits' do + lambda { User.create(:extension => "bougyman") }.should.raise(Sequel::InvalidValue) + lambda { User.create(:extension => 123) }.should.raise(Sequel::ValidationFailed). + message.should.match /must be all digits \(4 minimum\)/ + end + + it 'should require pin to be 4+ digits' do + lambda { User.create(:extension => 1234, :pin => "foo") }.should.raise(Sequel::ValidationFailed). + message.should.match /must be all digits \(4 minimum\)/ + lambda { User.create(:extension => 1234, :pin => 123) }.should.raise(Sequel::ValidationFailed). + message.should.match /must be all digits \(4 minimum\)/ + end + + it 'should not allow duplicate extension' do + user = User.create(:extension => 1234) + lambda { User.create(:extension => 1234) }.should.raise(Sequel::ValidationFailed). + message.should.match /extension can not be duplicated/ + end + + it 'should not allow duplicate username' do + user = User.create(:extension => 1234, :username => 'crusty') + lambda { User.create(:extension => 2234, :username => 'crusty') }.should.raise(Sequel::ValidationFailed). + message.should.match /username can not be duplicated/ + end + + it 'should be inactive upon initial creation' do + user = User.create(:extension => 1234) + user.active.should.be.false + end + + it 'should make mailbox equal to extension if it is not specified' do + user = User.create(:extension => 1234) + user.mailbox.should.equal user.extension.to_s + end + + it 'should require mailbox be 4+ digits' do + lambda { User.create(:extension => 1234, :mailbox => "foo") }.should.raise(Sequel::ValidationFailed). + message.should.match /must be all digits \(4 minimum\)/ + lambda { User.create(:extension => 1234, :mailbox => 123) }.should.raise(Sequel::ValidationFailed). + message.should.match /must be all digits \(4 minimum\)/ + end + + it 'should have a default dialstring when created' do + user = User.create(@defaults) + user.dialstring.should === "{presence_id=${dialed_user}@$${domain}}${sofia_contact(default/${dialed_user}@$${domain})}" + end + + it 'should add default user_variables when created' do + user = User.create(@defaults) + user.user_variables.size.should.equal 5 + end + + it 'should set the user context to default upon creation' do + user = User.new(:extension => 1234) + user.context.should.be.nil + user.save.reload.context.should.not.be.nil + user.context.name.should.equal "default" + end + + it 'should allow multiple users (with usernames)' do + user = User.create(:extension => 1191, :username => 'pete') + user2 = User.create(:extension => 1192, :username => "frodo") + User.all.size.should.equal 2 + end + + it 'should allow multiple users (no usernames)' do + user = User.create(:extension => 1191) + user2 = User.create(:extension => 1199) + User.all.size.should.equal 2 + end +end diff --git a/spec/model/voicemail.rb b/spec/model/voicemail.rb new file mode 100644 index 0000000..baf730f --- /dev/null +++ b/spec/model/voicemail.rb @@ -0,0 +1,15 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +require File.expand_path('../../db_helper', __FILE__) + +describe 'FXC::Voicemail' do + + it 'should output parsed epoch_time in UTC' do + v = FXC::Voicemail.create(:created_epoch => 1244584744) + v.timestamp.should.equal "06/09/2009 21:59" + FXC::Voicemail.filter(:uuid => v.uuid, :username => v.username, :created_epoch => v.created_epoch).delete + end + +end diff --git a/spec/view/configuration.rb b/spec/view/configuration.rb new file mode 100644 index 0000000..0c6f67d --- /dev/null +++ b/spec/view/configuration.rb @@ -0,0 +1,87 @@ +# Copyright (c) 2008-2010 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software + +require_relative '../../spec/helper' + +describe 'configuration' do + behaves_like :rack_test + + def req(key_value + + DEFOPTS = {"section" => "configuration", "key_name" => "name", "key_value" => nil, 'hostname' => TODO} + it 'responds with not-found template' do + get '/', DEFOPTS + last_response.status.should == 200 + last_response['Content-Type'].should == 'freeswitch/xml' + last_response.body.strip.should.not == '' + + doc = Nokogiri::XML(last_response.body) + doc.at('document/section/result')[:status].should == 'not found' + end + + it 'responds with a purpose=network-list' do + post '/', DEFOPTS.merge(:purpose => 'network-list') + last_response.status.should == 200 + last_response['Content-Type'].should == 'freeswitch/xml' + last_response.body.strip.should.not == '' + + doc = Nokogiri::XML(last_response.body) + doc.root.name.should == 'include' + + users = (doc/:user) + users.size.should > 0 + + # just some rough stuff + user = users.first + + user[:mailbox].should.not.be.nil + user[:id].should.not.be.nil + user[:cidr].should.not.be.nil + + user.at("params/param[@name='password']").should.not.be.nil + user.at("params/param[@name='dial-string']").should.not.be.nil + end + + it 'responds to action=sip_auth' do + post '/', DEFOPTS.merge(:action => 'sip_auth', :sip_auth_username => '1902') + last_response.status.should == 200 + last_response.body.strip.should.not == '' + + doc = Nokogiri::XML(last_response.body) + doc.root.name.should == 'include' + + # just some rough stuff + user = doc.at :user + + user[:mailbox].should == '1902' + user[:id].should == '1902' + user[:cidr].should == '0.0.0.0/0' + + user.at("params/param[@name='password']")[:value].should =~ /^\d{4}$/ + user.at("params/param[@name='dial-string']").should.not.be.nil + end + + it 'responds to user=1902 for voicemail' do + post '/', section: "directory", user: 1902, "Event-Calling-Function" => "voicemail_leave_main" + last_response.status.should == 200 + last_response.body.strip.should.not == '' + doc = Nokogiri::XML(last_response.body) + doc.root.name.should == 'include' + user = doc.at :user + + user[:mailbox].should == '1902' + user[:id].should == '1902' + user[:cidr].should == '0.0.0.0/0' + + user.at("params/param[@name='password']")[:value].should =~ /^\d{4}$/ + user.at("params/param[@name='dial-string']").should.not.be.nil + end + + it 'sets nibble_rate and nibble_account when user has a nibble_rate' do + post '/', section: "directory", user: 1902 + last_response.status.should == 200 + last_response.body.strip.should.not == '' + doc = Nokogiri::XML(last_response.body) + end +end diff --git a/spec/view/dialplan.rb b/spec/view/dialplan.rb new file mode 100644 index 0000000..dbc77ed --- /dev/null +++ b/spec/view/dialplan.rb @@ -0,0 +1,78 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +require File.expand_path('../../db_helper', __FILE__) +require FXC::ROOT/:spec/:directory_data + +describe 'dialplan' do + behaves_like :rack_test + + DEFOPTS = {"section" => "dialplan"} + it 'responds with not-found template' do + post '/', DEFOPTS + last_response.status.should == 200 + last_response.body.strip.should.not == '' + doc = Nokogiri::XML(last_response.body) + + doc.root.name.should == 'document' + sections = (doc/:section) + sections.size == 1 + sections.first.at(:result)[:status].should == 'not found' + end + + it 'responds with not-found template when searching for an extension' do + post '/', DEFOPTS.merge("Caller-Context" => "default", "Caller-Destination-Number" => "12345") + last_response.status.should == 200 + last_response.body.strip.should.not == '' + doc = Nokogiri::XML(last_response.body) + + doc.root.name.should == 'document' + sections = (doc/:section) + sections.size == 1 + sections.first.at(:result)[:status].should == 'not found' + end + + + it 'responds to a public call and uses User.dialstring as the bridge data' do + post '/', DEFOPTS.merge("Caller-Context" => "public", "Caller-Destination-Number" => "1901") + last_response.status.should == 200 + last_response.body.strip.should.not == '' + doc = Nokogiri::XML(last_response.body) + + doc.root.name.should == 'include' + extensions = (doc/:extension) + (extension = extensions.first).should.not.be.nil + extension[:name].should.equal "Inbound DID Test" + conditions = (doc/:extension/:condition) + (condition = conditions.first).should.not.be.nil + condition[:field].should.equal "destination_number" + condition[:expression].should.equal "^1?(1901)$" + actions = (doc/:extension/:condition/:action) + bridge_action = actions.last + bridge_action[:application].should.equal "voicemail" + bridge_action[:data].should.equal "default $${domain} 1901" + end + + it 'responds to a public call and uses Target.value as the bridge data' do + post '/', DEFOPTS.merge("Caller-Context" => "public", "Caller-Destination-Number" => "1902") + last_response.status.should == 200 + last_response.body.strip.should.not == '' + doc = Nokogiri::XML(last_response.body) + + doc.root.name.should == 'include' + extensions = (doc/:extension) + (extension = extensions.first).should.not.be.nil + extension[:name].should.equal "Inbound DID Test #2" + conditions = (doc/:extension/:condition) + (condition = conditions.first).should.not.be.nil + condition[:field].should.equal "destination_number" + condition[:expression].should.equal "^1?(1902)$" + actions = (doc/:extension/:condition/"action") + bridge_action = actions.detect { |ac| ac['application'] == 'bridge' } + # Uses Target, not default User#dialstring + bridge_action[:data].should.equal "${sofia_contact(default/1902@${dialed_domain})}" + end + +end + diff --git a/spec/view/directory.rb b/spec/view/directory.rb new file mode 100644 index 0000000..d097f70 --- /dev/null +++ b/spec/view/directory.rb @@ -0,0 +1,85 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +require File.expand_path('../../db_helper', __FILE__) +require FXC::SPEC_HELPER_PATH/:directory_data +describe 'directory' do + behaves_like :rack_test + + DEFOPTS = {"section" => "directory", "sip_profile" => "internal"} + it 'responds with not-found template' do + get '/', DEFOPTS + last_response.status.should == 200 + last_response['Content-Type'].should == 'freeswitch/xml' + last_response.body.strip.should.not == '' + + doc = Nokogiri::XML(last_response.body) + doc.at('document/section/result')[:status].should == 'not found' + end + + it 'responds with a purpose=network-list' do + post '/', DEFOPTS.merge(:purpose => 'network-list') + last_response.status.should == 200 + last_response['Content-Type'].should == 'freeswitch/xml' + last_response.body.strip.should.not == '' + + doc = Nokogiri::XML(last_response.body) + doc.root.name.should == 'include' + + users = (doc/:user) + users.size.should > 0 + + # just some rough stuff + user = users.first + + user[:mailbox].should.not.be.nil + user[:id].should.not.be.nil + user[:cidr].should.not.be.nil + + user.at("params/param[@name='password']").should.not.be.nil + user.at("params/param[@name='dial-string']").should.not.be.nil + end + + it 'responds to action=sip_auth' do + post '/', DEFOPTS.merge(:action => 'sip_auth', :sip_auth_username => '1902') + last_response.status.should == 200 + last_response.body.strip.should.not == '' + + doc = Nokogiri::XML(last_response.body) + doc.root.name.should == 'include' + + # just some rough stuff + user = doc.at :user + + user[:mailbox].should == '1902' + user[:id].should == '1902' + user[:cidr].should == '0.0.0.0/0' + + user.at("params/param[@name='password']")[:value].should =~ /^\d{4}$/ + user.at("params/param[@name='dial-string']").should.not.be.nil + end + + it 'responds to user=1902 for voicemail' do + post '/', section: "directory", user: 1902, "Event-Calling-Function" => "voicemail_leave_main" + last_response.status.should == 200 + last_response.body.strip.should.not == '' + doc = Nokogiri::XML(last_response.body) + doc.root.name.should == 'include' + user = doc.at :user + + user[:mailbox].should == '1902' + user[:id].should == '1902' + user[:cidr].should == '0.0.0.0/0' + + user.at("params/param[@name='password']")[:value].should =~ /^\d{4}$/ + user.at("params/param[@name='dial-string']").should.not.be.nil + end + + it 'sets nibble_rate and nibble_account when user has a nibble_rate' do + post '/', section: "directory", user: 1902 + last_response.status.should == 200 + last_response.body.strip.should.not == '' + doc = Nokogiri::XML(last_response.body) + end +end diff --git a/tasks/authors.rake b/tasks/authors.rake new file mode 100644 index 0000000..e95832a --- /dev/null +++ b/tasks/authors.rake @@ -0,0 +1,37 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +# Once git has a fix for the glibc in handling .mailmap and another fix for +# allowing empty mail address to be mapped in .mailmap we won't have to handle +# them manually. + +desc 'Update AUTHORS' +task :authors do + authors = Hash.new(0) + + `git shortlog -nse`.scan(/(\d+)\s(.+)\s<(.*)>$/) do |count, name, email| + # Examples of mappping, replace with your own or comment this out/delete it + case name + when /^(?:bougyman$|TJ Vanderpoel)/ + name, email = "TJ Vanderpoel", "[email protected]" + when /^(?:manveru$|Michael Fellinger)/ + name, email = "Michael Fellinger", "[email protected]" + when /^(?:deathsyn$|Kevin Berry)/ + name, email = "Kevin Berry", "[email protected]" + when /^(?:(?:jayson|thedonvaughn|jvaughn)$|Jayson Vaughn)/ + name, email = "Jayson Vaughn", "[email protected]" + end + + authors[[name, email]] += count.to_i + end + + File.open('AUTHORS', 'w+') do |io| + io.puts "Following persons have contributed to #{GEMSPEC.name}." + io.puts '(Sorted by number of submitted patches, then alphabetically)' + io.puts '' + authors.sort_by{|(n,e),c| [-c, n.downcase] }.each do |(name, email), count| + io.puts("%6d %s <%s>" % [count, name, email]) + end + end +end diff --git a/tasks/bacon.rake b/tasks/bacon.rake new file mode 100644 index 0000000..2079593 --- /dev/null +++ b/tasks/bacon.rake @@ -0,0 +1,74 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +desc 'Run all bacon specs with pretty output' +task :bacon => :install_dependencies do + require 'open3' + require 'scanf' + require 'matrix' + + specs = PROJECT_SPECS + + some_failed = false + specs_size = specs.size + if specs.size == 0 + $stderr.puts "You have no specs! Put a spec in spec/ before running this task" + exit 1 + end + len = specs.map{|s| s.size }.sort.last + total_tests = total_assertions = total_failures = total_errors = 0 + totals = Vector[0, 0, 0, 0] + + red, yellow, green = "\e[31m%s\e[0m", "\e[33m%s\e[0m", "\e[32m%s\e[0m" + left_format = "%4d/%d: %-#{len + 11}s" + spec_format = "%d specifications (%d requirements), %d failures, %d errors" + + specs.each_with_index do |spec, idx| + print(left_format % [idx + 1, specs_size, spec]) + + Open3.popen3(RUBY, spec) do |sin, sout, serr| + out = sout.read.strip + err = serr.read.strip + + # this is conventional, see spec/innate/state/fiber.rb for usage + if out =~ /^Bacon::Error: (needed .*)/ + puts(yellow % ("%6s %s" % ['', $1])) + else + total = nil + + out.each_line do |line| + scanned = line.scanf(spec_format) + + next unless scanned.size == 4 + + total = Vector[*scanned] + break + end + + if total + totals += total + tests, assertions, failures, errors = total_array = total.to_a + + if tests > 0 && failures + errors == 0 + puts((green % "%6d passed") % tests) + else + some_failed = true + puts(red % " failed") + puts out unless out.empty? + puts err unless err.empty? + end + else + some_failed = true + puts(red % " failed") + puts out unless out.empty? + puts err unless err.empty? + end + end + end + end + + total_color = some_failed ? red : green + puts(total_color % (spec_format % totals.to_a)) + exit 1 if some_failed +end diff --git a/tasks/changelog.rake b/tasks/changelog.rake new file mode 100644 index 0000000..40d798a --- /dev/null +++ b/tasks/changelog.rake @@ -0,0 +1,22 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +desc 'update changelog' +task :changelog do + File.open('CHANGELOG', 'w+') do |changelog| + `git log -z --abbrev-commit`.split("\0").each do |commit| + next if commit =~ /^Merge: \d*/ + ref, author, time, _, title, _, message = commit.split("\n", 7) + ref = ref[/commit ([0-9a-f]+)/, 1] + author = author[/Author: (.*)/, 1].strip + time = Time.parse(time[/Date: (.*)/, 1]).utc + title.strip! + + changelog.puts "[#{ref} | #{time}] #{author}" + changelog.puts '', " * #{title}" + changelog.puts '', message.rstrip if message + changelog.puts + end + end +end diff --git a/tasks/copyright.rake b/tasks/copyright.rake new file mode 100644 index 0000000..ef5c19c --- /dev/null +++ b/tasks/copyright.rake @@ -0,0 +1,38 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +require "pathname" +task :legal do + license = Pathname("LICENSE") + license.open("w+") do |f| + f.puts PROJECT_COPYRIGHT + end unless license.file? and license.read == PROJECT_COPYRIGHT + doc = Pathname("doc/LEGAL") + doc.open("w+") do |f| + f.puts "LICENSE" + end unless doc.file? +end + +desc "add copyright summary to all .rb files in the distribution" +task :copyright => [:legal] do + doc = Pathname("doc/LEGAL") + ignore = doc.readlines. + select { |line| line.strip!; Pathname(line).file? }. + map { |file| Pathname(file).expand_path } + + puts "adding copyright summary to files that don't have it currently" + puts PROJECT_COPYRIGHT_SUMMARY + puts + + (Pathname.glob('{controller,model,app,lib,test,spec,migrations}/**/*{.rb}') + + Pathname.glob("tasks/*.rake") + + Pathname.glob("Rakefile")).each do |file| + next if ignore.include? file.expand_path + lines = file.readlines.map{ |l| l.chomp } + unless lines.first(PROJECT_COPYRIGHT_SUMMARY.size) == PROJECT_COPYRIGHT_SUMMARY + oldlines = file.readlines + file.open("w+") { |f| f.puts PROJECT_COPYRIGHT_SUMMARY + oldlines } + end + end +end diff --git a/tasks/gem.rake b/tasks/gem.rake new file mode 100644 index 0000000..dbfab92 --- /dev/null +++ b/tasks/gem.rake @@ -0,0 +1,27 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +require 'rake/gempackagetask' + +desc "make a gemspec" +task :gemspec => [:manifest, :changelog, :authors] do + gemspec_file = "#{GEMSPEC.name}.gemspec" + File.open(gemspec_file, 'w+'){|gs| gs.puts(GEMSPEC.to_ruby) } +end + +desc "package and install from gemspec" +task :install => [:gemspec] do + sh "gem build #{GEMSPEC.name}.gemspec" + sh "gem install #{GEMSPEC.name}-#{GEMSPEC.version}.gem" +end + +desc "uninstall the gem" +task :uninstall => [:clean] do + sh %{gem uninstall -x #{GEMSPEC.name}} +end + +Rake::GemPackageTask.new(GEMSPEC) do |p| + p.need_tar = true + p.need_zip = true +end diff --git a/tasks/gem_setup.rake b/tasks/gem_setup.rake new file mode 100644 index 0000000..d9b7641 --- /dev/null +++ b/tasks/gem_setup.rake @@ -0,0 +1,99 @@ +task :gem_setup do + class GemSetup + def initialize(options = {}, &block) + @gems = [] + @options = options.dup + @verbose = @options.delete(:verbose) + + run(&block) + end + + def run(&block) + return unless block_given? + instance_eval(&block) + setup + end + + def gem(name, version = nil, options = {}) + if version.respond_to?(:merge!) + options = version + else + options[:version] = version + end + + @gems << [name, options] + end + + # all gems defined, let's try to load/install them + def setup + require 'rubygems' + require 'rubygems/dependency_installer' + + @gems.each do |name, options| + setup_gem(name, options) + end + end + + def setup_gemspec(gemspec) + gemspec.dependencies.each do |dependency| + dependency.version_requirements.as_list.each do |version| + gem(dependency.name, version) + end + end + + setup + end + + # first try to activate, install and try to activate again if activation + # fails the first time + def setup_gem(name, options) + version = [options[:version]].compact + lib_name = options[:lib] || name + + log "activating #{name}" + + Gem.activate(name, *version) + rescue LoadError + install_gem(name, options) + Gem.activate(name, *version) + end + + # tell rubygems to install a gem + def install_gem(name, options) + installer = Gem::DependencyInstaller.new(options) + + temp_argv(options[:extconf]) do + log "Installing #{name}" + installer.install(name, options[:version]) + end + end + + # prepare ARGV for rubygems installer + def temp_argv(extconf) + if extconf ||= @options[:extconf] + old_argv = ARGV.clone + ARGV.replace(extconf.split(' ')) + end + + yield + + ensure + ARGV.replace(old_argv) if extconf + end + + private + + def log(msg) + return unless @verbose + + if defined?(Log) + Log.info(msg) + else + puts(msg) + end + end + + def rubyforge; 'http://gems.rubyforge.org/' end + def github; 'http://gems.github.com/' end + end +end diff --git a/tasks/install_dependencies.rake b/tasks/install_dependencies.rake new file mode 100644 index 0000000..10732f0 --- /dev/null +++ b/tasks/install_dependencies.rake @@ -0,0 +1,10 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +desc 'install dependencies' +task :install_dependencies => [:gem_setup] do +# GemInstaller.new do +# setup_gemspec(GEMSPEC) +# end +end diff --git a/tasks/manifest.rake b/tasks/manifest.rake new file mode 100644 index 0000000..5632b57 --- /dev/null +++ b/tasks/manifest.rake @@ -0,0 +1,8 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +desc 'update manifest' +task :manifest do + File.open('MANIFEST', 'w+'){|io| io.puts(*GEMSPEC.files) } +end diff --git a/tasks/migrate.rake b/tasks/migrate.rake new file mode 100644 index 0000000..7729c6b --- /dev/null +++ b/tasks/migrate.rake @@ -0,0 +1,22 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software + +desc "migrate to latest version of db" +task :migrate, :version do |_, args| + args.with_defaults(:version => nil) + require File.expand_path("../../lib/fxc", __FILE__) + require Fxc::LIBPATH + "/fxc/db" + require 'sequel/extensions/migration' + + raise "No DB found" unless Fxc.db + + require Fxc::PATH + "/model/init" + + if args.version.nil? + Sequel::Migrator.apply(Fxc.db, Fxc::MIGRATION_ROOT) + else + Sequel::Migrator.run(Fxc.db, Fxc::MIGRATION_ROOT, :target => args.version.to_i) + end + +end diff --git a/tasks/rcov.rake b/tasks/rcov.rake new file mode 100644 index 0000000..d60371f --- /dev/null +++ b/tasks/rcov.rake @@ -0,0 +1,27 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +desc 'code coverage' +task :rcov => :clean do + specs = PROJECT_SPECS + + ignore = %w[ gem rack bacon innate hpricot nagoro/lib/nagoro ] + + if RUBY_VERSION >= '1.8.7' + ignore << 'begin_with' << 'end_with' + end + if RUBY_VERSION < '1.9' + ignore << 'fiber' + end + + ignored = ignore.join(',') + + cmd = "rcov --aggregate coverage.data --sort coverage -t --%s -x '#{ignored}' %s" + + while spec = specs.shift + puts '', "Gather coverage for #{spec} ..." + html = specs.empty? ? 'html' : 'no-html' + sh(cmd % [html, spec]) + end +end diff --git a/tasks/release.rake b/tasks/release.rake new file mode 100644 index 0000000..b217ba9 --- /dev/null +++ b/tasks/release.rake @@ -0,0 +1,56 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +namespace :release do + task :all => [:release_github, :release_rubyforge] + + desc 'Display instructions to release on github' + task :github => [:reversion, :gemspec] do + name, version = GEMSPEC.name, GEMSPEC.version + + puts <<INSTRUCTIONS +First add the relevant files: + +git add AUTHORS MANIFEST CHANGELOG #{name}.gemspec lib/#{name}/version.rb + +Then commit them, tag the commit, and push: + +git commit -m 'Version #{version}' +git tag -a -m '#{version}' '#{version}' +git push + +INSTRUCTIONS + + end + + # TODO: Not tested + desc 'Display instructions to release on rubyforge' + task :rubyforge => [:reversion, :gemspec, :package] do + name, version = GEMSPEC.name, GEMSPEC.version + + puts <<INSTRUCTIONS +To publish to rubyforge do following: + +rubyforge login +rubyforge add_release #{name} #{name} '#{version}' pkg/#{name}-#{version}.gem + +After you have done these steps, see: + +rake release:rubyforge_archives + +INSTRUCTIONS + end + + desc 'Display instructions to add archives after release:rubyforge' + task :rubyforge_archives do + name, version = GEMSPEC.name, GEMSPEC.version + puts "Adding archives for distro packagers is:", "" + + Dir["pkg/#{name}-#{version}.{tgz,zip}"].each do |file| + puts "rubyforge add_file #{name} #{name} '#{version}' '#{file}'" + end + + puts + end +end diff --git a/tasks/reversion.rake b/tasks/reversion.rake new file mode 100644 index 0000000..8ec64c1 --- /dev/null +++ b/tasks/reversion.rake @@ -0,0 +1,12 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +desc "update version.rb" +task :reversion do + File.open("lib/#{GEMSPEC.name}/version.rb", 'w+') do |file| + file.puts("module #{PROJECT_MODULE}") + file.puts(' VERSION = %p' % GEMSPEC.version.to_s) + file.puts('end') + end +end diff --git a/tasks/schema.rake b/tasks/schema.rake new file mode 100644 index 0000000..a046159 --- /dev/null +++ b/tasks/schema.rake @@ -0,0 +1,30 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +task :test_db do + require_relative "../lib/fxc" + require Fxc::ROOT/:spec/:db_helper +end + +desc "Dump the test schema" +task :schema, :format, :needs => [:test_db] do |t,args| + args.with_defaults(:format => "html") + descs = Fxc.db.tables.inject([]) do |arr, table| + arr << "\\dd #{table};\\d+ #{table}" + end + commands = descs.join(";") + if args.format.to_s == "html" + f = File.open("doc/schema.html","w+") + command = %Q{echo '\\H #{commands}'|PGDATA=#{ENV['PGDATA']} PGHOST=#{ENV['PGHOST']} PGPORT=#{ENV['PGPORT']} psql fxc|tail -n +2} + else + command = %Q{echo '#{commands}'|PGDATA=#{ENV['PGDATA']} PGHOST=#{ENV['PGHOST']} PGPORT=#{ENV['PGPORT']} psql fxc} + f = $stdout + end + f.puts %x{#{command}} + unless f == $stdout + f.close + puts "Saved doc/schema.html" + end + +end diff --git a/tasks/setup.rake b/tasks/setup.rake new file mode 100644 index 0000000..db952b6 --- /dev/null +++ b/tasks/setup.rake @@ -0,0 +1,19 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +desc 'install all possible dependencies' +task :setup => :gem_setup do + GemInstaller.new do + # core + + # spec + gem 'bacon' + gem 'rcov' + + # doc + gem 'yard' + + setup + end +end diff --git a/tasks/yard.rake b/tasks/yard.rake new file mode 100644 index 0000000..72d845c --- /dev/null +++ b/tasks/yard.rake @@ -0,0 +1,8 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +desc 'Generate YARD documentation' +task :yard => :clean do + sh("yardoc -o ydoc --protected -r #{PROJECT_README} lib/**/*.rb tasks/*.rake") +end diff --git a/view/dialplan/blocked_busy.xhtml b/view/dialplan/blocked_busy.xhtml new file mode 100644 index 0000000..d2b0ef5 --- /dev/null +++ b/view/dialplan/blocked_busy.xhtml @@ -0,0 +1,15 @@ +<extension name="#{@did.description}"> + <condition field="destination_number" expression="^1?(#{@did.number})$"> + <action application="set" data="dialed_extension=$1"/> + <action application="export" data="dialed_extension=$1"/> + <action application="bind_meta_app" data="1 b s execute_extension::dx XML features"/> + <action application="bind_meta_app" data="2 b s execute_extension::cf XML features"/> + <action application="set" data="ringback=${us-ring}"/> + <action application="set" data="transfer_ringback=$${hold_music}"/> + <action application="respond" data="486"/> + <action application="sleep" data="3000"/> + <action application="hangup" data="USER_BUSY"/> + </condition> + +</extension> + diff --git a/view/dialplan/blocked_call.xhtml b/view/dialplan/blocked_call.xhtml new file mode 100644 index 0000000..dd749e5 --- /dev/null +++ b/view/dialplan/blocked_call.xhtml @@ -0,0 +1,13 @@ +<extension name="#{@did.description}"> + <condition field="destination_number" expression="^1?(#{@did.number})$"> + <action application="set" data="dialed_extension=$1"/> + <action application="export" data="dialed_extension=$1"/> + <action application="bind_meta_app" data="1 b s execute_extension::dx XML features"/> + <action application="bind_meta_app" data="2 b s execute_extension::cf XML features"/> + <action application="set" data="ringback=${us-ring}"/> + <action application="set" data="transfer_ringback=$${hold_music}"/> + <action application="hangup"/> + </condition> + +</extension> + diff --git a/view/dialplan/blocked_error.xhtml b/view/dialplan/blocked_error.xhtml new file mode 100644 index 0000000..fa69be5 --- /dev/null +++ b/view/dialplan/blocked_error.xhtml @@ -0,0 +1,14 @@ +<extension name="#{@did.description}"> + <condition field="destination_number" expression="^1?(#{@did.number})$"> + <action application="set" data="dialed_extension=$1"/> + <action application="export" data="dialed_extension=$1"/> + <action application="bind_meta_app" data="1 b s execute_extension::dx XML features"/> + <action application="bind_meta_app" data="2 b s execute_extension::cf XML features"/> + <action application="set" data="ringback=${us-ring}"/> + <action application="set" data="transfer_ringback=$${hold_music}"/> + <action application="pre_answer"/> + <action application="hangup" data="NETWORK_OUT_OF_ORDER"/> + </condition> + +</extension> + diff --git a/view/dialplan/blocked_ring.xhtml b/view/dialplan/blocked_ring.xhtml new file mode 100644 index 0000000..e21dea9 --- /dev/null +++ b/view/dialplan/blocked_ring.xhtml @@ -0,0 +1,15 @@ +<extension name="#{@did.description}"> + <condition field="destination_number" expression="^1?(#{@did.number})$"> + <action application="set" data="dialed_extension=$1"/> + <action application="export" data="dialed_extension=$1"/> + <action application="bind_meta_app" data="1 b s execute_extension::dx XML features"/> + <action application="bind_meta_app" data="2 b s execute_extension::cf XML features"/> + <action application="set" data="ringback=${us-ring}"/> + <action application="set" data="transfer_ringback=$${hold_music}"/> + <action application="ring_ready"/> + <action application="sleep" data="300000000"/> + <action application="hangup"/> + </condition> + +</extension> + diff --git a/view/dialplan/blocked_vmail.xhtml b/view/dialplan/blocked_vmail.xhtml new file mode 100644 index 0000000..9088116 --- /dev/null +++ b/view/dialplan/blocked_vmail.xhtml @@ -0,0 +1,39 @@ +<extension name="#{@did.description}"> + <condition field="destination_number" expression="^1?(#{@did.number})$"> + <action application="set" data="dialed_extension=$1"/> + <action application="export" data="dialed_extension=$1"/> + <action application="bind_meta_app" data="1 b s execute_extension::dx XML features"/> + <action application="bind_meta_app" data="2 b s execute_extension::cf XML features"/> + <action application="set" data="ringback=${us-ring}"/> + <action application="set" data="transfer_ringback=$${hold_music}"/> + <action application="set" data="call_timeout=30"/> + <action application="set" data="hangup_after_bridge=true"/> + <action application="set" data="continue_on_fail=true"/> + <action application="db" data="insert/$${domain}-call_return/#{@did.user.extension}/${caller_id_number}" /> + <action application="db" data="insert/$${domain}-last_dial_ext/#{@did.user.extension}/${uuid}"/> + <action application="set" data="called_party_callgroup=#{@did.user.user_variables_dataset.filter(:name => 'accountcode').first.value || 'none'}"/> + <action application="db" data="insert/$${domain}-last_dial/${called_party_callgroup}/${uuid}" /> + <action application="set" data="call_record_path=$${base_dir}/recordings/${strftime(%Y%m%d-%H%M%S)}-${caller_id_number}-#{@did.user.extension}-IN.wav" /> + <action application="set" data="api_hangup_hook=system mv ${call_record_path} ${call_record_path}-DONE" /> + <action application="set" data="record_stereo=true" /> + <action application="set" data="RECORD_ANSWER_REQ=true"/> + <action application="set" data="new_call_direction=in"/> + <action application="set" data="innercalls_exten=#{@did.user.extension}"/> + <action application="set" data="call_direction=in"/> + <action application="export" data="dialed_user=#{@did.user.extension}"/> + <action application="record_session" data="${call_record_path}" /> + <?r if (@did.user.max_call_length.to_i * 60) > 0 ?> + <action application="sched_hangup" data="+#{@did.user.max_call_length.to_i * 60} alloted_timeout"/> + <?r end ?> + <?r if @did.user.nibble_rate ?> + <action application="nibblebill" data="heartbeat 60" /> + <action application="set" data="nibble_rate=#{@did.user.nibble_rate}" /> + <action application="set" data="nibble_account=#{@did.user.extension}" /> + <?r end ?> + <action application="answer"/> + <action application="sleep" data="1000"/> + <action application="voicemail" data="default $${domain} #{@did.user.extension}"/> + </condition> + +</extension> + diff --git a/view/dialplan/default.xhtml b/view/dialplan/default.xhtml new file mode 100644 index 0000000..bec9bcf --- /dev/null +++ b/view/dialplan/default.xhtml @@ -0,0 +1,35 @@ +<extension name="#{@did.description}"> + <condition field="destination_number" expression="^1?(#{@did.number})$"> + <action application="set" data="dialed_extension=$1"/> + <action application="export" data="dialed_extension=$1"/> + <action application="bind_meta_app" data="1 b s execute_extension::dx XML features"/> + <action application="bind_meta_app" data="2 b s execute_extension::cf XML features"/> + <action application="set" data="ringback=${us-ring}"/> + <action application="set" data="transfer_ringback=$${hold_music}"/> + <action application="set" data="call_timeout=30"/> + <action application="set" data="hangup_after_bridge=true"/> + <action application="set" data="continue_on_fail=true"/> + <action application="db" data="insert/$${domain}-call_return/#{@did.user.extension}/${caller_id_number}" /> + <action application="db" data="insert/$${domain}-last_dial_ext/#{@did.user.extension}/${uuid}"/> + <action application="set" data="called_party_callgroup=#{@did.user.user_variables_dataset.filter(:name => 'accountcode').first.value || 'none'}"/> + <action application="db" data="insert/$${domain}-last_dial/${called_party_callgroup}/${uuid}" /> + <action application="set" data="call_record_path=$${base_dir}/recordings/${strftime(%Y%m%d-%H%M%S)}-${caller_id_number}-#{@did.user.extension}-IN.wav" /> + <action application="set" data="api_hangup_hook=system mv ${call_record_path} ${call_record_path}-DONE" /> + <action application="set" data="record_stereo=true" /> + <action application="set" data="RECORD_ANSWER_REQ=true"/> + <action application="set" data="new_call_direction=in"/> + <action application="set" data="innercalls_exten=#{@did.user.extension}"/> + <action application="set" data="call_direction=in"/> + <action application="export" data="dialed_user=#{@did.user.extension}"/> + <action application="record_session" data="${call_record_path}" /> + <?r if (@did.user.max_call_length.to_i * 60) > 0 ?> + <action application="sched_hangup" data="+#{@did.user.max_call_length.to_i * 60} alloted_timeout"/> + <?r end ?> + <action application="bridge" data="#{@did.dialstring}"/> + <action application="answer"/> + <action application="sleep" data="1000"/> + <action application="voicemail" data="default $${domain} #{@did.user.extension}"/> + </condition> + +</extension> + diff --git a/view/dialplan/did.xhtml b/view/dialplan/did.xhtml new file mode 100644 index 0000000..938b712 --- /dev/null +++ b/view/dialplan/did.xhtml @@ -0,0 +1,42 @@ +<extension name="#{@did.description}"> + <condition field="destination_number" expression="^1?(#{@did.number})$"> + <action application="set" data="dialed_extension=$1"/> + <action application="export" data="dialed_extension=$1"/> + <action application="bind_meta_app" data="1 b s execute_extension::dx XML features"/> + <action application="bind_meta_app" data="2 b s execute_extension::cf XML features"/> + <action application="set" data="ringback=${us-ring}"/> + <action application="set" data="transfer_ringback=$${hold_music}"/> + <action application="set" data="call_timeout=30"/> + <action application="set" data="hangup_after_bridge=true"/> + <action application="set" data="continue_on_fail=true"/> + <action application="db" data="insert/$${domain}-call_return/#{@did.user.extension}/${caller_id_number}" /> + <action application="db" data="insert/$${domain}-last_dial_ext/#{@did.user.extension}/${uuid}"/> + <action application="set" data="called_party_callgroup=#{@did.user.user_variables_dataset.filter(:name => 'accountcode').first.value || 'none'}"/> + <action application="db" data="insert/$${domain}-last_dial/${called_party_callgroup}/${uuid}" /> + <action application="set" data="call_record_path=$${base_dir}/recordings/${strftime(%Y%m%d-%H%M%S)}-${caller_id_number}-#{@did.user.extension}-IN.wav" /> + <action application="set" data="api_hangup_hook=system mv ${call_record_path} ${call_record_path}-DONE" /> + <action application="set" data="record_stereo=true" /> + <action application="set" data="RECORD_ANSWER_REQ=true"/> + <action application="set" data="new_call_direction=in"/> + <action application="set" data="innercalls_exten=#{@did.user.extension}"/> + <action application="set" data="call_direction=in"/> + <action application="export" data="dialed_user=#{@did.user.extension}"/> + <action application="record_session" data="${call_record_path}" /> + <?r if (@did.user.max_call_length.to_i * 60) > 0 ?> + <action application="sched_hangup" data="+#{@did.user.max_call_length.to_i * 60} alloted_timeout"/> + <?r end ?> + <?r if @did.user.nibble_rate ?> + <action application="nibblebill" data="heartbeat 60" /> + <action application="set" data="nibble_rate=#{@did.user.nibble_rate}" /> + <action application="set" data="nibble_account=#{@did.user.extension}" /> + <action application="bridge" data="{global_heartbeat=60,nibble_rate=#{@did.user.nibble_rate},nibble_account=#{@did.user.extension}}#{@did.dialstring}"/> + <?r else ?> + <action application="bridge" data="#{@did.dialstring}"/> + <?r end ?> + <action application="answer"/> + <action application="sleep" data="1000"/> + <action application="voicemail" data="default $${domain} #{@did.user.extension}"/> + </condition> + +</extension> + diff --git a/view/dialplan/extension.xhtml b/view/dialplan/extension.xhtml new file mode 100644 index 0000000..3ae51b2 --- /dev/null +++ b/view/dialplan/extension.xhtml @@ -0,0 +1,14 @@ +<?r @extensions.each do |extension| ?> + <extension name="#{h extension.name}"> + <?r extension.conditions.each do |condition| ?> + <condition field="#{h condition.matcher}" expression="#{h condition.expression}" break="#{condition.break_string}"> + <?r condition.actions.each do |action| ?> + <action application="#{h action.application}" data="#{h action.data}" /> + <?r end ?> + <?r condition.anti_actions.each do |anti_action| ?> + <anti-action application="#{h anti_action.application}" data="#{h anti_action.data}" /> + <?r end ?> + </condition> + <?r end ?> + </extension> +<?r end ?> diff --git a/view/dialplan/public.xhtml b/view/dialplan/public.xhtml new file mode 100644 index 0000000..938b712 --- /dev/null +++ b/view/dialplan/public.xhtml @@ -0,0 +1,42 @@ +<extension name="#{@did.description}"> + <condition field="destination_number" expression="^1?(#{@did.number})$"> + <action application="set" data="dialed_extension=$1"/> + <action application="export" data="dialed_extension=$1"/> + <action application="bind_meta_app" data="1 b s execute_extension::dx XML features"/> + <action application="bind_meta_app" data="2 b s execute_extension::cf XML features"/> + <action application="set" data="ringback=${us-ring}"/> + <action application="set" data="transfer_ringback=$${hold_music}"/> + <action application="set" data="call_timeout=30"/> + <action application="set" data="hangup_after_bridge=true"/> + <action application="set" data="continue_on_fail=true"/> + <action application="db" data="insert/$${domain}-call_return/#{@did.user.extension}/${caller_id_number}" /> + <action application="db" data="insert/$${domain}-last_dial_ext/#{@did.user.extension}/${uuid}"/> + <action application="set" data="called_party_callgroup=#{@did.user.user_variables_dataset.filter(:name => 'accountcode').first.value || 'none'}"/> + <action application="db" data="insert/$${domain}-last_dial/${called_party_callgroup}/${uuid}" /> + <action application="set" data="call_record_path=$${base_dir}/recordings/${strftime(%Y%m%d-%H%M%S)}-${caller_id_number}-#{@did.user.extension}-IN.wav" /> + <action application="set" data="api_hangup_hook=system mv ${call_record_path} ${call_record_path}-DONE" /> + <action application="set" data="record_stereo=true" /> + <action application="set" data="RECORD_ANSWER_REQ=true"/> + <action application="set" data="new_call_direction=in"/> + <action application="set" data="innercalls_exten=#{@did.user.extension}"/> + <action application="set" data="call_direction=in"/> + <action application="export" data="dialed_user=#{@did.user.extension}"/> + <action application="record_session" data="${call_record_path}" /> + <?r if (@did.user.max_call_length.to_i * 60) > 0 ?> + <action application="sched_hangup" data="+#{@did.user.max_call_length.to_i * 60} alloted_timeout"/> + <?r end ?> + <?r if @did.user.nibble_rate ?> + <action application="nibblebill" data="heartbeat 60" /> + <action application="set" data="nibble_rate=#{@did.user.nibble_rate}" /> + <action application="set" data="nibble_account=#{@did.user.extension}" /> + <action application="bridge" data="{global_heartbeat=60,nibble_rate=#{@did.user.nibble_rate},nibble_account=#{@did.user.extension}}#{@did.dialstring}"/> + <?r else ?> + <action application="bridge" data="#{@did.dialstring}"/> + <?r end ?> + <action application="answer"/> + <action application="sleep" data="1000"/> + <action application="voicemail" data="default $${domain} #{@did.user.extension}"/> + </condition> + +</extension> + diff --git a/view/directory/user.xhtml b/view/directory/user.xhtml new file mode 100644 index 0000000..ddd6446 --- /dev/null +++ b/view/directory/user.xhtml @@ -0,0 +1,16 @@ +<user id="#{@user.extension}" mailbox="#{@user.mailbox}" cidr="#{@user.cidr}"> + <params> + <param name="dial-string" value="#{@user.dialstring}"/> + <param name="password" value="#{@user.pin}"/> + <param name="vm-password" value="#{@user.pin}"/> + </params> + <variables> + <?r @user.user_variables.each do |user_variable| ?> + <variable name="#{user_variable.name}" value="#{user_variable.value}" /> + <?r end ?> + <?r if @user.nibble_rate ?> + <variable name="nibble_rate" value="#{@user.nibble_rate}" /> + <variable name="nibble_account" value=#{@user.extension}" /> + <?r end ?> + </variables> +</user> diff --git a/view/directory/users.xhtml b/view/directory/users.xhtml new file mode 100644 index 0000000..93da0c7 --- /dev/null +++ b/view/directory/users.xhtml @@ -0,0 +1,5 @@ +<users> + <?r @users.each do |user| ?> + #{render_view(:user, :user => user)} + <?r end ?> +</users> diff --git a/view/not_found.xhtml b/view/not_found.xhtml new file mode 100644 index 0000000..3759c69 --- /dev/null +++ b/view/not_found.xhtml @@ -0,0 +1,5 @@ +<document type="freeswitch/xml"> + <section name="result"> + <result status="not found" /> + </section> +</document>
bougyman/fxc
a693276d2a5c376dfb82751c4e2cd749de1e336b
Pre-release
diff --git a/app.rb b/app.rb index 83adff1..b498a14 100644 --- a/app.rb +++ b/app.rb @@ -1,15 +1,15 @@ require "innate" require_relative "lib/fxc" Dir.glob(Fxc::PATH + "/node/*.rb").each { |node| - p node require node } require Fxc::PATH + "lib/rack/middleware" Innate.middleware! do |mw| mw.use Fxc::Rack::Middleware + mw.use Rack::CommonLogger mw.innate end if $0 == __FILE__ Innate.start :root => Fxc::PATH, :file => __FILE__ end diff --git a/couch/configuration/shows/acl.conf.js b/couch/configuration/lists/acl.conf.js similarity index 52% rename from couch/configuration/shows/acl.conf.js rename to couch/configuration/lists/acl.conf.js index 2bb6682..8a7adc1 100644 --- a/couch/configuration/shows/acl.conf.js +++ b/couch/configuration/lists/acl.conf.js @@ -1,34 +1,23 @@ -function(doc, req){ - var each = function(obj, callback){ - var result = <></>; - for(key in obj){ - if(obj.hasOwnProperty(key)){ - result += callback(key, obj[key]); - } - } - return result; - }; +function(head, req){ + var doc = getRow().value; - start({code: 200, headers: {'Content-Type': 'freeswitch/xml'}}); - - return( -'<?xml version="1.0" encoding="UTF-8" standalone="no" ?>' + "\n" + ( + send( <document type="freeswitch/xml"> <section name="configuration"> - <configuration name={doc._id} description={doc.description}> + <configuration name={doc.name} description={doc.description}> <network-lists> {each(doc.network_lists, function(name, list){ var xml = <list name={name} default={list.default} />; list.nodes.forEach(function(node){ var tag = <node />; for(key in node){ tag.@[key] = node[key]; } xml.list += tag; }); return xml; })} </network-lists> </configuration> </section> </document> - ).toXMLString()); + ); } diff --git a/couch/configuration/lists/alsa.conf.js b/couch/configuration/lists/alsa.conf.js new file mode 100644 index 0000000..737ceb6 --- /dev/null +++ b/couch/configuration/lists/alsa.conf.js @@ -0,0 +1,17 @@ +function(head, req){ + var doc = getRow().value; + + send( +<document type="freeswitch/xml"> + <section name="configuration"> + <configuration name={doc.name} description={doc.description}> + <settings> + {each(doc.settings, function(name, value){ + return <param name={name} value={value} /> + })} + </settings> + </configuration> + </section> +</document> + ); +} diff --git a/couch/configuration/shows/callcenter.conf.js b/couch/configuration/lists/callcenter.conf.js similarity index 68% rename from couch/configuration/shows/callcenter.conf.js rename to couch/configuration/lists/callcenter.conf.js index c72051e..64f1083 100644 --- a/couch/configuration/shows/callcenter.conf.js +++ b/couch/configuration/lists/callcenter.conf.js @@ -1,54 +1,43 @@ -function(doc, req){ - var each = function(obj, callback){ - var result = <></>; - for(key in obj){ - if(obj.hasOwnProperty(key)){ - result += callback(key, obj[key]); - } - } - return result; - }; +function(head, req){ + var doc = getRow().value; - start({code: 200, headers: {'Content-Type': 'freeswitch/xml'}}); - - return( -'<?xml version="1.0" encoding="UTF-8" standalone="no" ?>' + "\n" + ( + send( <document type="freeswitch/xml"> <section name="configuration"> - <configuration name={doc._id} description={doc.description}> + <configuration name={doc.name} description={doc.description}> <settings> {each(doc.settings, function(name, value){ return <param name={name} value={value} /> })} </settings> <queues> {each(doc.queues, function(name, params){ var xml = <queue name={name} />; for(key in params){ xml.queue += <param name={key} value={params[key]} />; } return xml; })} </queues> <agents> {each(doc.agents, function(name, attributes){ var xml = <agent name={name} />; for(key in attributes){ xml.@[key] = attributes[key]; } return xml; })} </agents> <tiers> {each(doc.tiers, function(key, tier){ var xml = <tier level="1" position="1" />; for(key in tier){ xml.@[key] = tier[key]; } return xml; })} </tiers> </configuration> </section> </document> - ).toXMLString()); + ); } diff --git a/couch/configuration/lists/cdr_csv.conf.js b/couch/configuration/lists/cdr_csv.conf.js new file mode 100644 index 0000000..aad1f68 --- /dev/null +++ b/couch/configuration/lists/cdr_csv.conf.js @@ -0,0 +1,23 @@ +function(head, req){ + var doc = getRow().value; + + send( +<document type="freeswitch/xml"> + <section name="configuration"> + <configuration name={doc.name} description={doc.description}> + <settings> + {each(doc.settings, function(name, value){ + return <param name={name} value={value} /> + })} + </settings> + + <templates> + {each(doc.templates, function(name, template){ + return <template name={name}>{template}</template>; + })} + </templates> + </configuration> + </section> +</document> + ); +} diff --git a/couch/configuration/lists/cdr_pg_csv.conf.js b/couch/configuration/lists/cdr_pg_csv.conf.js new file mode 100644 index 0000000..aad1f68 --- /dev/null +++ b/couch/configuration/lists/cdr_pg_csv.conf.js @@ -0,0 +1,23 @@ +function(head, req){ + var doc = getRow().value; + + send( +<document type="freeswitch/xml"> + <section name="configuration"> + <configuration name={doc.name} description={doc.description}> + <settings> + {each(doc.settings, function(name, value){ + return <param name={name} value={value} /> + })} + </settings> + + <templates> + {each(doc.templates, function(name, template){ + return <template name={name}>{template}</template>; + })} + </templates> + </configuration> + </section> +</document> + ); +} diff --git a/couch/configuration/lists/cidlookup.conf.js b/couch/configuration/lists/cidlookup.conf.js new file mode 100644 index 0000000..f084db2 --- /dev/null +++ b/couch/configuration/lists/cidlookup.conf.js @@ -0,0 +1,17 @@ +function(doc, req){ + var doc = getRow().value; + + send( +<document type="freeswitch/xml"> + <section name="configuration"> + <configuration name={doc.name} description={doc.description}> + <settings> + {each(doc.settings, function(name, value){ + return <param name={name} value={value} /> + })} + </settings> + </configuration> + </section> +</document> + ); +} diff --git a/couch/configuration/shows/conference.conf.js b/couch/configuration/lists/conference.conf.js similarity index 65% rename from couch/configuration/shows/conference.conf.js rename to couch/configuration/lists/conference.conf.js index 430bdf2..f369a7d 100644 --- a/couch/configuration/shows/conference.conf.js +++ b/couch/configuration/lists/conference.conf.js @@ -1,46 +1,35 @@ -function(doc, req){ - var each = function(obj, callback){ - var result = <></>; - for(key in obj){ - if(obj.hasOwnProperty(key)){ - result += callback(key, obj[key]); - } - } - return result; - }; +function(head, req){ + var doc = getRow().value; - start({code: 200, headers: {'Content-Type': 'freeswitch/xml'}}); - - return( -'<?xml version="1.0" encoding="UTF-8" standalone="no" ?>' + "\n" + ( + send( <document type="freeswitch/xml"> <section name="configuration"> - <configuration name={doc._id} description={doc.description}> + <configuration name={doc.name} description={doc.description}> <advertise> {each(doc.advertise, function(name, status){ return <room name={name} status={status} /> })} </advertise> <caller-controls> {each(doc.controls, function(name, controls){ var xml = <group name={name} />; for(key in controls){ xml.group += <control action={key} digits={controls[key]} />; } return xml; })} </caller-controls> <profiles> {each(doc.profiles, function(name, params){ var xml = <profile name={name} />; for(key in params){ xml.profile += <param name={key} value={params[key]} />; } return xml; })} </profiles> </configuration> </section> </document> - ).toXMLString()); + ); } diff --git a/couch/configuration/lists/console.conf.js b/couch/configuration/lists/console.conf.js new file mode 100644 index 0000000..f3cd4af --- /dev/null +++ b/couch/configuration/lists/console.conf.js @@ -0,0 +1,22 @@ +function(head, req){ + var doc = getRow().value; + + send( +<document type="freeswitch/xml"> + <section name="configuration"> + <configuration name={doc.name} description={doc.description}> + <mappings> + {each(doc.mappings, function(name, value){ + return <map name={name} value={value.join(',')} /> + })} + </mappings> + <settings> + {each(doc.settings, function(name, value){ + return <param name={name} value={value} /> + })} + </settings> + </configuration> + </section> +</document> + ); +} diff --git a/couch/configuration/lists/db.conf.js b/couch/configuration/lists/db.conf.js new file mode 100644 index 0000000..8a7adc1 --- /dev/null +++ b/couch/configuration/lists/db.conf.js @@ -0,0 +1,23 @@ +function(head, req){ + var doc = getRow().value; + + send( +<document type="freeswitch/xml"> + <section name="configuration"> + <configuration name={doc.name} description={doc.description}> + <network-lists> + {each(doc.network_lists, function(name, list){ + var xml = <list name={name} default={list.default} />; + list.nodes.forEach(function(node){ + var tag = <node />; + for(key in node){ tag.@[key] = node[key]; } + xml.list += tag; + }); + return xml; + })} + </network-lists> + </configuration> + </section> +</document> + ); +} diff --git a/couch/configuration/shows/enum.conf.js b/couch/configuration/lists/enum.conf.js similarity index 50% rename from couch/configuration/shows/enum.conf.js rename to couch/configuration/lists/enum.conf.js index 005e3a9..d0c244a 100644 --- a/couch/configuration/shows/enum.conf.js +++ b/couch/configuration/lists/enum.conf.js @@ -1,35 +1,24 @@ -function(doc, req){ - var each = function(obj, callback){ - var result = <></>; - for(key in obj){ - if(obj.hasOwnProperty(key)){ - result += callback(key, obj[key]); - } - } - return result; - }; +function(head, req){ + var doc = getRow().value; - start({code: 200, headers: {'Content-Type': 'freeswitch/xml'}}); - - return( -'<?xml version="1.0" encoding="UTF-8" standalone="no" ?>' + "\n" + ( + send( <document type="freeswitch/xml"> <section name="configuration"> - <configuration name={doc._id} description={doc.description}> + <configuration name={doc.name} description={doc.description}> <settings> {each(doc.settings, function(name, value){ return <param name={name} value={value} /> })} </settings> <routes> {each(doc.routes, function(name, route){ var xml = <route />; for(key in route){ xml.@[key] = route[key]; } return xml; })} </routes> </configuration> </section> </document> - ).toXMLString()); + ); } diff --git a/couch/configuration/lists/event_socket.conf.js b/couch/configuration/lists/event_socket.conf.js new file mode 100644 index 0000000..737ceb6 --- /dev/null +++ b/couch/configuration/lists/event_socket.conf.js @@ -0,0 +1,17 @@ +function(head, req){ + var doc = getRow().value; + + send( +<document type="freeswitch/xml"> + <section name="configuration"> + <configuration name={doc.name} description={doc.description}> + <settings> + {each(doc.settings, function(name, value){ + return <param name={name} value={value} /> + })} + </settings> + </configuration> + </section> +</document> + ); +} diff --git a/couch/configuration/lists/fax.conf.js b/couch/configuration/lists/fax.conf.js new file mode 100644 index 0000000..737ceb6 --- /dev/null +++ b/couch/configuration/lists/fax.conf.js @@ -0,0 +1,17 @@ +function(head, req){ + var doc = getRow().value; + + send( +<document type="freeswitch/xml"> + <section name="configuration"> + <configuration name={doc.name} description={doc.description}> + <settings> + {each(doc.settings, function(name, value){ + return <param name={name} value={value} /> + })} + </settings> + </configuration> + </section> +</document> + ); +} diff --git a/couch/configuration/lists/fifo.conf.js b/couch/configuration/lists/fifo.conf.js new file mode 100644 index 0000000..0c61a60 --- /dev/null +++ b/couch/configuration/lists/fifo.conf.js @@ -0,0 +1,39 @@ +function(head, req){ + var doc = getRow().value; + log(doc); + + send( +<document type="freeswitch/xml"> + <section name="configuration"> + <configuration name={doc.name} description={doc.description}> + <settings> + {each(doc.settings, function(name, value){ + return <param name={name} value={value} /> + })} + </settings> + + <fifos> + {each(doc.fifos, function(name, fifo){ + var xml = <fifo name={name} importance={fifo.importance} />; + + for(key in fifo){ + var value = fifo[key]; + + if(key === "members"){ + xml.fifo += each(value, function(mname, member){ + var mxml = <member>{mname}</member>; + for(mkey in member){ mxml.@[mkey] = member[mkey]; } + return mxml; + }); + } else { + xml.@[key] = value; + } + } + return xml; + })} + </fifos> + </configuration> + </section> +</document> + ); +} diff --git a/couch/configuration/lists/hash.conf.js b/couch/configuration/lists/hash.conf.js new file mode 100644 index 0000000..966fbf0 --- /dev/null +++ b/couch/configuration/lists/hash.conf.js @@ -0,0 +1,19 @@ +function(head, req){ + var doc = getRow().value; + + send( +<document type="freeswitch/xml"> + <section name="configuration"> + <configuration name={doc.name} description={doc.description}> + <remotes> + {each(doc.remotes, function(name, attributes){ + var xml = <remote name={name} />; + for(key in attributes){ xml.@[key] = attributes[key]; } + return xml; + })} + </remotes> + </configuration> + </section> +</document> + ); +} diff --git a/couch/configuration/lists/local_stream.conf.js b/couch/configuration/lists/local_stream.conf.js new file mode 100644 index 0000000..59d4de7 --- /dev/null +++ b/couch/configuration/lists/local_stream.conf.js @@ -0,0 +1,23 @@ +function(head, req){ + var doc = getRow().value; + + send( +<document type="freeswitch/xml"> + <section name="configuration"> + <configuration name={doc.name} description={doc.description}> + {each(doc.directories, function(name, directory){ + return( + <directory name={name} path={directory.path}> + {each(directory, function(key, value){ + if(!(key === "path")){ + return <param name={key} value={value} />; + } + })} + </directory> + ) + })} + </configuration> + </section> +</document> + ); +} diff --git a/couch/configuration/shows/logfile.conf.js b/couch/configuration/lists/logfile.conf.js similarity index 83% rename from couch/configuration/shows/logfile.conf.js rename to couch/configuration/lists/logfile.conf.js index ce58a9f..acffa29 100644 --- a/couch/configuration/shows/logfile.conf.js +++ b/couch/configuration/lists/logfile.conf.js @@ -1,43 +1,44 @@ -function(doc, req){ +function(head, req){ var each = function(obj, callback){ var result = <></>; for(key in obj){ if(obj.hasOwnProperty(key)){ result += callback(key, obj[key]); } } return result; }; - start({code: 200, headers: {'Content-Type': 'freeswitch/xml'}}); + var doc = getRow().value; - return( -'<?xml version="1.0" encoding="UTF-8" standalone="no" ?>' + "\n" + ( + start({code: 200, headers: {'Content-Type': 'freeswitch/xml'}}); + send('<?xml version="1.0" encoding="UTF-8" standalone="no" ?>' + "\n"); + send( <document type="freeswitch/xml"> <section name="configuration"> - <configuration name={doc._id} description={doc.description}> + <configuration name={doc.name} description={doc.description}> <settings> {each(doc.settings, function(name, value){ return <param name={name} value={value} /> })} </settings> <profiles> {each(doc.profiles, function(name, profile){ var settings = <settings />; for(key in profile.settings){ settings.settings += <param name={key} value={profile.settings[key]} />; } var mappings = <mappings />; for(key in profile.mappings){ mappings.mappings += <map name={key} value={profile.mappings[key]} />; } return <profile name={name}>{settings}{mappings}</profile>; })} </profiles> </configuration> </section> </document> - ).toXMLString()); + ); } diff --git a/couch/configuration/lists/sofia.js b/couch/configuration/lists/sofia.js index 66523a8..a93dd3a 100644 --- a/couch/configuration/lists/sofia.js +++ b/couch/configuration/lists/sofia.js @@ -1,64 +1,65 @@ function(head, req){ var each = function(obj, callback){ var result = <></>; for(key in obj){ if(obj.hasOwnProperty(key)){ result += callback(key, obj[key]); } } return result; }; start({code: 200, headers: {'Content-Type': 'freeswitch/xml'}}); send('<?xml version="1.0" encoding="UTF-8" standalone="no" ?>' + "\n"); var sofia = getRow().value; log(sofia); var result = <document type="freeswitch/xml"> <section name="configuration"> - <configuration name={sofia._id} description={sofia.description}> + <configuration name={sofia.name} description={sofia.description}> <global_settings> {each(sofia.global_settings, function(name, value){ return <param name={name} value={value} /> })} </global_settings> <profiles /> </configuration> </section> </document>; while(row = getRow()){ var profile = row.value; result.section.configuration.profiles.profiles += <profile name={profile.name}> <aliases> {each(profile.aliases, function(idx){ return <alias name={profile.aliases[idx]} /> })} </aliases> <gateways> {each(profile.gateways, function(name, params){ var xml = <gateway name={gateway.name} />; for(var name in params){ xml.gateway += <param name={name} value={params[name]} />; } return xml; })} </gateways> <domains> {each(profile.domains, function(name, obj){ return <domain name={name} alias={obj.alias} parse={obj.parse} /> })} </domains> <settings> {each(profile.settings, function(name, value){ return <param name={name} value={value} /> })} </settings> </profile>; } send(result); + ; } diff --git a/couch/configuration/lists/spandsp.conf.js b/couch/configuration/lists/spandsp.conf.js new file mode 100644 index 0000000..9b1dfa7 --- /dev/null +++ b/couch/configuration/lists/spandsp.conf.js @@ -0,0 +1,41 @@ +function(head, req){ + var each = function(obj, callback){ + var result = <></>; + for(key in obj){ + if(obj.hasOwnProperty(key)){ + result += callback(key, obj[key]); + } + } + return result; + }; + + var doc = getRow().value; + + start({code: 200, headers: {'Content-Type': 'freeswitch/xml'}}); + send('<?xml version="1.0" encoding="UTF-8" standalone="no" ?>' + "\n"); + send( +<document type="freeswitch/xml"> + <section name="configuration"> + <configuration name={doc.name} description={doc.description}> + <descriptors> + {each(doc.descriptors, function(descriptor_name, tones){ + return( + <descriptor name={descriptor_name}> + {each(tones, function(tone_name, elements){ + return( + <tone name={tone_name}> + {each(elements, function(idx, attributes){ + var element = <element />; + for(key in attributes){ element.@[key] = attributes[key]; } + return element; + })} + </tone> + )})} + </descriptor> + )})} + </descriptors> + </configuration> + </section> +</document> + ); +} diff --git a/couch/configuration/shows/switch.conf.js b/couch/configuration/lists/switch.conf.js similarity index 84% rename from couch/configuration/shows/switch.conf.js rename to couch/configuration/lists/switch.conf.js index dd7b8a1..30e4c49 100644 --- a/couch/configuration/shows/switch.conf.js +++ b/couch/configuration/lists/switch.conf.js @@ -1,33 +1,34 @@ -function(doc, req){ +function(head, req){ var each = function(obj, callback){ var result = <></>; for(key in obj){ if(obj.hasOwnProperty(key)){ result += callback(key, obj[key]); } } return result; }; - start({code: 200, headers: {'Content-Type': 'freeswitch/xml'}}); + var doc = getRow().value; - return( -'<?xml version="1.0" encoding="UTF-8" standalone="no" ?>' + "\n" + ( + start({code: 200, headers: {'Content-Type': 'freeswitch/xml'}}); + send('<?xml version="1.0" encoding="UTF-8" standalone="no" ?>' + "\n"); + send( <document type="freeswitch/xml"> <section name="configuration"> <configuration name={doc.name} description={doc.description}> <cli-keybindings> {each(doc.keybindings, function(name, value){ return <key name={name} value={value} /> })} </cli-keybindings> <settings> {each(doc.settings, function(name, value){ return <param name={name} value={value} /> })} </settings> </configuration> </section> </document> - ).toXMLString()); + ); } diff --git a/couch/configuration/lists/voicemail.conf.js b/couch/configuration/lists/voicemail.conf.js new file mode 100644 index 0000000..e9a45ba --- /dev/null +++ b/couch/configuration/lists/voicemail.conf.js @@ -0,0 +1,43 @@ +function(head, req){ + var each = function(obj, callback){ + var result = <></>; + for(key in obj){ + if(obj.hasOwnProperty(key)){ + result += callback(key, obj[key]); + } + } + return result; + }; + + var doc = getRow().value; + + start({code: 200, headers: {'Content-Type': 'freeswitch/xml'}}); + send('<?xml version="1.0" encoding="UTF-8" standalone="no" ?>' + "\n"); + send( +<document type="freeswitch/xml"> + <section name="configuration"> + <configuration name={doc.name} description={doc.description}> + <settings> + {each(doc.settings, function(name, value){ + return <param name={name} value={value} /> + })} + </settings> + + <profiles> + {each(doc.profiles, function(name, params){ + var xml = <profile name={name}><email /></profile>; + for(key in params.settings){ + xml.profile += <param name={key} value={params.settings[key]} />; + } + for(key in params.email){ + xml.email.email += <param name={key} value={params.email[key]} />; + } + return xml; + })} + </profiles> + </configuration> + </section> +</document> + ); + ; +} diff --git a/couch/configuration/lists/xml_cdr.conf.js b/couch/configuration/lists/xml_cdr.conf.js index 700042b..206eff4 100644 --- a/couch/configuration/lists/xml_cdr.conf.js +++ b/couch/configuration/lists/xml_cdr.conf.js @@ -1,16 +1,30 @@ function(head, req){ var each = function(obj, callback){ var result = <></>; for(key in obj){ if(obj.hasOwnProperty(key)){ result += callback(key, obj[key]); } } return result; }; + var doc = getRow().value; + start({code: 200, headers: {'Content-Type': 'freeswitch/xml'}}); send('<?xml version="1.0" encoding="UTF-8" standalone="no" ?>' + "\n"); - - log(head); + send( +<document type="freeswitch/xml"> + <section name="configuration"> + <configuration name={doc.name} description={doc.description}> + <settings> + {each(doc.settings, function(name, value){ + return <param name={name} value={value} /> + })} + </settings> + </configuration> + </section> +</document> + ); + ; } diff --git a/couch/configuration/shows/xml_curl.conf.js b/couch/configuration/lists/xml_curl.conf.js similarity index 80% rename from couch/configuration/shows/xml_curl.conf.js rename to couch/configuration/lists/xml_curl.conf.js index 0faf728..ca0152d 100644 --- a/couch/configuration/shows/xml_curl.conf.js +++ b/couch/configuration/lists/xml_curl.conf.js @@ -1,37 +1,39 @@ -function(doc, req){ +function(head, req){ var each = function(obj, callback){ var result = <></>; for(key in obj){ if(obj.hasOwnProperty(key)){ result += callback(key, obj[key]); } } return result; }; - start({code: 200, headers: {'Content-Type': 'freeswitch/xml'}}); + log(head); + var doc = getRow().value; - return( -'<?xml version="1.0" encoding="UTF-8" standalone="no" ?>' + "\n" + ( + start({code: 200, headers: {'Content-Type': 'freeswitch/xml'}}); + send('<?xml version="1.0" encoding="UTF-8" standalone="no" ?>' + "\n"); + send( <document type="freeswitch/xml"> <section name="configuration"> - <configuration name={doc._id} description={doc.description}> + <configuration name={doc.name} description={doc.description}> <bindings> {each(doc.bindings, function(name, binding){ var xml = <binding name={name} />; for(key in binding){ var value = binding[key]; if(key === "gateway-url"){ xml.binding += <param name={key} value={value.value} bindings={value.bindings} />; } else { xml.binding += <param name={key} value={value} />; } } return xml; })} </bindings> </configuration> </section> </document> - ).toXMLString()); + ); } diff --git a/couch/configuration/shows/alsa.conf.js b/couch/configuration/shows/alsa.conf.js deleted file mode 100644 index c885ddf..0000000 --- a/couch/configuration/shows/alsa.conf.js +++ /dev/null @@ -1,28 +0,0 @@ -function(doc, req){ - var each = function(obj, callback){ - var result = <></>; - for(key in obj){ - if(obj.hasOwnProperty(key)){ - result += callback(key, obj[key]); - } - } - return result; - }; - - start({code: 200, headers: {'Content-Type': 'freeswitch/xml'}}); - - return( -'<?xml version="1.0" encoding="UTF-8" standalone="no" ?>' + "\n" + ( -<document type="freeswitch/xml"> - <section name="configuration"> - <configuration name={doc._id} description={doc.description}> - <settings> - {each(doc.settings, function(name, value){ - return <param name={name} value={value} /> - })} - </settings> - </configuration> - </section> -</document> - ).toXMLString()); -} diff --git a/couch/configuration/shows/cdr_csv.conf.js b/couch/configuration/shows/cdr_csv.conf.js deleted file mode 100644 index 56a810d..0000000 --- a/couch/configuration/shows/cdr_csv.conf.js +++ /dev/null @@ -1,34 +0,0 @@ -function(doc, req){ - var each = function(obj, callback){ - var result = <></>; - for(key in obj){ - if(obj.hasOwnProperty(key)){ - result += callback(key, obj[key]); - } - } - return result; - }; - - start({code: 200, headers: {'Content-Type': 'freeswitch/xml'}}); - - return( -'<?xml version="1.0" encoding="UTF-8" standalone="no" ?>' + "\n" + ( -<document type="freeswitch/xml"> - <section name="configuration"> - <configuration name={doc._id} description={doc.description}> - <settings> - {each(doc.settings, function(name, value){ - return <param name={name} value={value} /> - })} - </settings> - - <templates> - {each(doc.templates, function(name, template){ - return <template name={name}>{template}</template>; - })} - </templates> - </configuration> - </section> -</document> - ).toXMLString()); -} diff --git a/couch/configuration/shows/cdr_pg_csv.conf.js b/couch/configuration/shows/cdr_pg_csv.conf.js deleted file mode 100644 index 56a810d..0000000 --- a/couch/configuration/shows/cdr_pg_csv.conf.js +++ /dev/null @@ -1,34 +0,0 @@ -function(doc, req){ - var each = function(obj, callback){ - var result = <></>; - for(key in obj){ - if(obj.hasOwnProperty(key)){ - result += callback(key, obj[key]); - } - } - return result; - }; - - start({code: 200, headers: {'Content-Type': 'freeswitch/xml'}}); - - return( -'<?xml version="1.0" encoding="UTF-8" standalone="no" ?>' + "\n" + ( -<document type="freeswitch/xml"> - <section name="configuration"> - <configuration name={doc._id} description={doc.description}> - <settings> - {each(doc.settings, function(name, value){ - return <param name={name} value={value} /> - })} - </settings> - - <templates> - {each(doc.templates, function(name, template){ - return <template name={name}>{template}</template>; - })} - </templates> - </configuration> - </section> -</document> - ).toXMLString()); -} diff --git a/couch/configuration/shows/cidlookup.conf.js b/couch/configuration/shows/cidlookup.conf.js deleted file mode 100644 index c885ddf..0000000 --- a/couch/configuration/shows/cidlookup.conf.js +++ /dev/null @@ -1,28 +0,0 @@ -function(doc, req){ - var each = function(obj, callback){ - var result = <></>; - for(key in obj){ - if(obj.hasOwnProperty(key)){ - result += callback(key, obj[key]); - } - } - return result; - }; - - start({code: 200, headers: {'Content-Type': 'freeswitch/xml'}}); - - return( -'<?xml version="1.0" encoding="UTF-8" standalone="no" ?>' + "\n" + ( -<document type="freeswitch/xml"> - <section name="configuration"> - <configuration name={doc._id} description={doc.description}> - <settings> - {each(doc.settings, function(name, value){ - return <param name={name} value={value} /> - })} - </settings> - </configuration> - </section> -</document> - ).toXMLString()); -} diff --git a/couch/configuration/shows/console.conf.js b/couch/configuration/shows/console.conf.js deleted file mode 100644 index 8127023..0000000 --- a/couch/configuration/shows/console.conf.js +++ /dev/null @@ -1,33 +0,0 @@ -function(doc, req){ - var each = function(obj, callback){ - var result = <></>; - for(key in obj){ - if(obj.hasOwnProperty(key)){ - result += callback(key, obj[key]); - } - } - return result; - }; - - start({code: 200, headers: {'Content-Type': 'freeswitch/xml'}}); - - return( -'<?xml version="1.0" encoding="UTF-8" standalone="no" ?>' + "\n" + ( -<document type="freeswitch/xml"> - <section name="configuration"> - <configuration name={doc._id} description={doc.description}> - <mappings> - {each(doc.mappings, function(name, value){ - return <map name={name} value={value.join(',')} /> - })} - </mappings> - <settings> - {each(doc.settings, function(name, value){ - return <param name={name} value={value} /> - })} - </settings> - </configuration> - </section> -</document> - ).toXMLString()); -} diff --git a/couch/configuration/shows/event_socket.conf.js b/couch/configuration/shows/event_socket.conf.js deleted file mode 100644 index c885ddf..0000000 --- a/couch/configuration/shows/event_socket.conf.js +++ /dev/null @@ -1,28 +0,0 @@ -function(doc, req){ - var each = function(obj, callback){ - var result = <></>; - for(key in obj){ - if(obj.hasOwnProperty(key)){ - result += callback(key, obj[key]); - } - } - return result; - }; - - start({code: 200, headers: {'Content-Type': 'freeswitch/xml'}}); - - return( -'<?xml version="1.0" encoding="UTF-8" standalone="no" ?>' + "\n" + ( -<document type="freeswitch/xml"> - <section name="configuration"> - <configuration name={doc._id} description={doc.description}> - <settings> - {each(doc.settings, function(name, value){ - return <param name={name} value={value} /> - })} - </settings> - </configuration> - </section> -</document> - ).toXMLString()); -} diff --git a/couch/configuration/shows/sofia.conf.js b/couch/configuration/shows/sofia.conf.js deleted file mode 100644 index a3e7355..0000000 --- a/couch/configuration/shows/sofia.conf.js +++ /dev/null @@ -1,63 +0,0 @@ -function(doc, req){ - var key; - var each = function(obj, callback){ - var result = <></>; - for(key in obj){ - if(obj.hasOwnProperty(key)){ - result += callback(key, obj[key]); - } - } - return result; - }; - - start({code: 200, headers: {'Content-Type': 'freeswitch/xml'}}); - - return( -'<?xml version="1.0" encoding="UTF-8" standalone="no" ?>' + "\n" + ( -<document type="freeswitch/xml"> - <section name="configuration"> - <configuration name={doc._id} description={doc.description}> - <global_settings> - {each(doc.settings, function(name, value){ - return <param name={name} value={value} /> - })} - </global_settings> - - - <profiles> - {each(lookup_profiles?, function(profile){ - <profile name={profile.name}> - <aliases> - {each(profile.aliases, function(name){ - return <alias name={name} /> - })} - </aliases> - <gateways> - {each(profile.gateways, function(name, params){ - <gateway name={gateway.name}> - {each(params), function(name, value){ - return <param name={name} value={value} /> - })} - </gateway> - })} - </gateways> - <domains> - {each(profile.domains, function(name, alias, parse){ - return <domain name={name} alias={alias} parse={parse} /> - })} - </domains> - <settings> - {each(profile.settings, function(name, value){ - return <param name={name} value={value} /> - })} - </settings> - - </profile> - })} - </profiles> - - </configuration> - </section> -</document> - ).toXMLString()); -} diff --git a/couch/configuration/shows/xml_cdr.conf.js b/couch/configuration/shows/xml_cdr.conf.js deleted file mode 100644 index c885ddf..0000000 --- a/couch/configuration/shows/xml_cdr.conf.js +++ /dev/null @@ -1,28 +0,0 @@ -function(doc, req){ - var each = function(obj, callback){ - var result = <></>; - for(key in obj){ - if(obj.hasOwnProperty(key)){ - result += callback(key, obj[key]); - } - } - return result; - }; - - start({code: 200, headers: {'Content-Type': 'freeswitch/xml'}}); - - return( -'<?xml version="1.0" encoding="UTF-8" standalone="no" ?>' + "\n" + ( -<document type="freeswitch/xml"> - <section name="configuration"> - <configuration name={doc._id} description={doc.description}> - <settings> - {each(doc.settings, function(name, value){ - return <param name={name} value={value} /> - })} - </settings> - </configuration> - </section> -</document> - ).toXMLString()); -} diff --git a/couch/configuration/views/conf/map.js b/couch/configuration/views/conf/map.js index 70173fa..54351eb 100644 --- a/couch/configuration/views/conf/map.js +++ b/couch/configuration/views/conf/map.js @@ -1,5 +1,5 @@ function(doc){ - if(doc.name && doc.server != undefined){ + if(doc.name && !(doc.server === undefined)){ emit([doc.name, doc.server], doc); } } diff --git a/lib/rack/middleware.rb b/lib/rack/middleware.rb index 162918f..e65338b 100644 --- a/lib/rack/middleware.rb +++ b/lib/rack/middleware.rb @@ -1,90 +1,88 @@ # Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> # Distributed under the terms of the MIT license. # The full text can be found in the LICENSE file included with this software # module Fxc module Rack class Middleware def initialize(app) @app = app end def call(env) params = ::Rack::Request.new(env) if params["section"] path = params["section"] + "/" path << case path when "dialplan/" dp_req(params) when "directory/" dir_req(params) when "configuration/" conf_req(params) end + path << "/#{params["hostname"]}" env["PATH_INFO"] = "#{env['PATH_INFO']}/#{path}".squeeze('/') env["REQUEST_URI"] = ("%s://%s/%s" % [ env["rack.url_scheme"], env["HTTP_HOST"], env["PATH_INFO"]]).squeeze('/') end - #p env @app.call(env) end private def dp_req(params) s = [params["Caller-Context"]] s << params["Caller-Destination-Number"] s << params["Caller-Caller-ID-Number"] s.compact.join("/") end def dir_req(params) s = [] if params["purpose"] s << params["purpose"].gsub("-","_") s << params["sip_profile"] elsif params["action"] && params["action"] == "sip_auth" s << "register" s << params["sip_profile"] s << params["sip_auth_username"] elsif params["user"] if params["action"] == "message-count" s << "messages" s << params["user"] s << params["key_value"] if params["tag_name"] == "domain" elsif params["Event-Calling-Function"] case params["Event-Calling-Function"].to_s when /voicemail/ s << "voicemail" s << (params["sip_profile"] || "default") s << params["user"] when "user_outgoing_channel" s << "user_outgoing" s << params["user"] s << params["domain"] if params["domain"] when "user_data_function" s << "user_data" s << params["user"] s << params["domain"] if params["domain"] end end end s.join("/") end def conf_req(params) s = [] - p "PARAMS: " - p params if params["key_name"] == "name" s << params["key_value"] end s.join("/") end end end end diff --git a/node/configuration.rb b/node/configuration.rb index 8caa501..d923ea0 100644 --- a/node/configuration.rb +++ b/node/configuration.rb @@ -1,6 +1,57 @@ -class FxcConfiguration - Innate.node "/configuration" - def index(conf_name) - conf_name +require 'innate' +require 'makura' +Makura::Model.database = 'fxc' + +module Fxc + class Proxy + Innate.node "/", self + provide :html, engine: :None + + def index + "Welcome to Fxc!" + end + + def configuration(name, hostname) + response['Content-Type'] = 'freeswitch/xml' + + Configuration.render(name, hostname).to_s + "\n" + + rescue Makura::Error => ex + Innate::Log.error(ex) + <<-XML +<document type="freeswitch/xml"> + <section name="result"> + <result status="not found" /> + </section> +</document> + XML + end + end + + class Configuration + include Makura::Model + + property :name + property :server + + def self.render(name, hostname, opts = {}) + if name == "sofia.conf" + Configuration.render_sofia(hostname) + else + Configuration.render_common(name, hostname) + end + end + + def self.render_common(name, hostname, opts = {}) + keys = [[name, hostname], [name, nil]] + opts.merge!(:payload => {'keys' => keys}, 'Content-Type' => 'application/json', :limit => 1) + database.post("_design/configuration/_list/#{name}/conf", opts) + end + + def self.render_sofia(hostname, opts = {}) + database.get("_design/configuration/_list/sofia/sofia_profiles", + startkey: [hostname, 0], + endkey: [hostname, 1]) + end end end diff --git a/sync_couch.rb b/sync_couch.rb index 5c25e7b..5f50180 100644 --- a/sync_couch.rb +++ b/sync_couch.rb @@ -1,26 +1,47 @@ require 'makura' Makura::Model.server = 'http://jimmy:5984' Makura::Model.database = 'fxc' root = File.expand_path("../couch/configuration", __FILE__) glob = File.join(root, "**/*.js") begin layout = Makura::Model.database["_design/configuration"] || {} rescue Makura::Error::ResourceNotFound layout = {} end layout['language'] ||= 'javascript' layout['_id'] ||= "_design/configuration" Dir.glob(glob) do |file| keys = File.dirname(file).sub(root, '').scan(/[^\/]+/) doc = File.read(file) + + doc.sub!(/function\(head, req\)\{/, <<-JS) +function(head, req){ + var each = function(obj, callback){ + var result = <></>; + var tmp; + + for(key in obj){ + if(obj.hasOwnProperty(key)){ + if(tmp = callback(key, obj[key])){ + result += tmp; + } + } + } + return result; + }; + + start({code: 200, headers: {'Content-Type': 'freeswitch/xml'}}); + send('<?xml version="1.0" encoding="UTF-8" standalone="no" ?>' + "\\n"); + JS + last = nil keys.inject(layout){|k,v| last = k[v] ||= {} } last[File.basename(file, '.js')] = doc end Makura::Model.database.save(layout)
bougyman/fxc
a069fb79f4770f598df753b0b5e89638a85dff1b
got the middleware sorted out
diff --git a/config.ru b/config.ru index 3041cc3..2f5360b 100755 --- a/config.ru +++ b/config.ru @@ -1,16 +1,16 @@ #!/usr/bin/env rackup # # config.ru for ramaze apps # use thin >= 1.0.0 # thin start -R config.ru # # rackup is a useful tool for running Rack applications, which uses the # Rack::Builder DSL to configure middleware and build up applications easily. # # rackup automatically figures out the environment it is run in, and runs your # application as FastCGI, CGI, or standalone with Mongrel or WEBrick -- all from # the same configuration. require ::File.expand_path('app', ::File.dirname(__FILE__)) -Innate.start(:file => __FILE__, :root => Fxc::PATH) +Innate.start(:file => __FILE__, :root => Fxc::PATH, :started => true) run Innate diff --git a/lib/rack/middleware.rb b/lib/rack/middleware.rb index c5c1951..162918f 100644 --- a/lib/rack/middleware.rb +++ b/lib/rack/middleware.rb @@ -1,83 +1,90 @@ # Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> # Distributed under the terms of the MIT license. # The full text can be found in the LICENSE file included with this software # module Fxc module Rack class Middleware def initialize(app) @app = app end def call(env) params = ::Rack::Request.new(env) - return @app.call(env) unless params["section"] + if params["section"] + path = params["section"] + "/" - path = params["section"] + "/" + path << case path + when "dialplan/" + dp_req(params) + when "directory/" + dir_req(params) + when "configuration/" + conf_req(params) + end - path << case path - when "dialplan/" - dp_req(params) - when "directory/" - dir_req(params) - when "configuration/" - conf_req(params) + env["PATH_INFO"] = "#{env['PATH_INFO']}/#{path}".squeeze('/') + env["REQUEST_URI"] = ("%s://%s/%s" % [ + env["rack.url_scheme"], + env["HTTP_HOST"], + env["PATH_INFO"]]).squeeze('/') end - - env["PATH_INFO"] = "#{env['PATH_INFO']}/#{path}".squeeze('/') + #p env @app.call(env) end private def dp_req(params) s = [params["Caller-Context"]] s << params["Caller-Destination-Number"] s << params["Caller-Caller-ID-Number"] s.compact.join("/") end def dir_req(params) s = [] if params["purpose"] s << params["purpose"].gsub("-","_") s << params["sip_profile"] elsif params["action"] && params["action"] == "sip_auth" s << "register" s << params["sip_profile"] s << params["sip_auth_username"] elsif params["user"] if params["action"] == "message-count" s << "messages" s << params["user"] s << params["key_value"] if params["tag_name"] == "domain" elsif params["Event-Calling-Function"] case params["Event-Calling-Function"].to_s when /voicemail/ s << "voicemail" s << (params["sip_profile"] || "default") s << params["user"] when "user_outgoing_channel" s << "user_outgoing" s << params["user"] s << params["domain"] if params["domain"] when "user_data_function" s << "user_data" s << params["user"] s << params["domain"] if params["domain"] end end end s.join("/") end def conf_req(params) s = [] + p "PARAMS: " + p params if params["key_name"] == "name" s << params["key_value"] end s.join("/") end end end end diff --git a/node/configuration.rb b/node/configuration.rb index 4bacce9..8caa501 100644 --- a/node/configuration.rb +++ b/node/configuration.rb @@ -1,6 +1,6 @@ class FxcConfiguration Innate.node "/configuration" - def index - "configuration" + def index(conf_name) + conf_name end end
bougyman/fxc
d4ae47d78c72f0bf9cc5803b9fe58f50103028a3
initial version of fxc with just couch and innate
diff --git a/.bnsignore b/.bnsignore new file mode 100644 index 0000000..7dc2904 --- /dev/null +++ b/.bnsignore @@ -0,0 +1,20 @@ +# The list of files that should be ignored by Mr Bones. +# Lines that start with '#' are comments. +# +# A .gitignore file can be used instead by setting it as the ignore +# file in your Rakefile: +# +# Bones { +# ignore_file '.gitignore' +# } +# +# For a project with a C extension, the following would be a good set of +# exclude patterns (uncomment them if you want to use them): +# *.[oa] +# *~ +announcement.txt +coverage +doc +pkg +.[a-zA-Z]* +log/*.log diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..294cebc --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +.[a-zA-Z]* +log/*.log diff --git a/History.txt b/History.txt new file mode 100644 index 0000000..6d70f6e --- /dev/null +++ b/History.txt @@ -0,0 +1,4 @@ +== 1.0.0 / 2010-09-12 + +* 1 major enhancement + * Birthday! diff --git a/README.txt b/README.txt new file mode 100644 index 0000000..d2ff798 --- /dev/null +++ b/README.txt @@ -0,0 +1,54 @@ +fxc + by The Rubyists, LLC + http://code.rubyists.com + +== DESCRIPTION: + +FXC is a small innate application which functions as a proxy to +a couchDB backend for serving FreeSWITCH configuration. + +== FEATURES/PROBLEMS: + +* Serves Configuration Files for Multiple FreeSWITCH servers + +== SYNOPSIS: + +* Serves Configuration Files for Multiple FreeSWITCH servers + +== REQUIREMENTS: + +* CouchDB +* Ruby (1.9.2 preferred) +* Innate (gem install innate) + +== INSTALL: + +* Install couch db and create the 'fxc' database +* Install Ruby +* Gem install makura, innate, nokogiri +* run ruby sync_couch.rb + +== LICENSE: + +(The MIT License) + +Copyright (c) 2009 The Rubyists, LLC + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/Rakefile b/Rakefile new file mode 100644 index 0000000..bab94ff --- /dev/null +++ b/Rakefile @@ -0,0 +1,17 @@ + +begin + require 'bones' +rescue LoadError + abort '### Please install the "bones" gem ###' +end + +task :default => 'test:run' +task 'gem:release' => 'test:run' + +Bones { + name 'fxc' + authors 'The Rubyists, LLC' + email '[email protected]' + url 'http://github.com/rubyists/fxc' +} + diff --git a/app.rb b/app.rb new file mode 100644 index 0000000..83adff1 --- /dev/null +++ b/app.rb @@ -0,0 +1,15 @@ +require "innate" +require_relative "lib/fxc" +Dir.glob(Fxc::PATH + "/node/*.rb").each { |node| + p node + require node +} +require Fxc::PATH + "lib/rack/middleware" +Innate.middleware! do |mw| + mw.use Fxc::Rack::Middleware + mw.innate +end + +if $0 == __FILE__ + Innate.start :root => Fxc::PATH, :file => __FILE__ +end diff --git a/bin/fxc b/bin/fxc new file mode 100755 index 0000000..abdc6ed --- /dev/null +++ b/bin/fxc @@ -0,0 +1,7 @@ +#!/usr/bin/env ruby + +require File.expand_path( + File.join(File.dirname(__FILE__), %w[.. lib fxc])) + +# Put your code here + diff --git a/config.ru b/config.ru new file mode 100755 index 0000000..3041cc3 --- /dev/null +++ b/config.ru @@ -0,0 +1,16 @@ +#!/usr/bin/env rackup +# +# config.ru for ramaze apps +# use thin >= 1.0.0 +# thin start -R config.ru +# +# rackup is a useful tool for running Rack applications, which uses the +# Rack::Builder DSL to configure middleware and build up applications easily. +# +# rackup automatically figures out the environment it is run in, and runs your +# application as FastCGI, CGI, or standalone with Mongrel or WEBrick -- all from +# the same configuration. + +require ::File.expand_path('app', ::File.dirname(__FILE__)) +Innate.start(:file => __FILE__, :root => Fxc::PATH) +run Innate diff --git a/couch/configuration/lists/sofia.js b/couch/configuration/lists/sofia.js new file mode 100644 index 0000000..66523a8 --- /dev/null +++ b/couch/configuration/lists/sofia.js @@ -0,0 +1,64 @@ +function(head, req){ + var each = function(obj, callback){ + var result = <></>; + for(key in obj){ + if(obj.hasOwnProperty(key)){ + result += callback(key, obj[key]); + } + } + return result; + }; + + start({code: 200, headers: {'Content-Type': 'freeswitch/xml'}}); + + send('<?xml version="1.0" encoding="UTF-8" standalone="no" ?>' + "\n"); + + var sofia = getRow().value; + log(sofia); + + var result = <document type="freeswitch/xml"> + <section name="configuration"> + <configuration name={sofia._id} description={sofia.description}> + <global_settings> + {each(sofia.global_settings, function(name, value){ + return <param name={name} value={value} /> + })} + </global_settings> + <profiles /> + </configuration> + </section> +</document>; + + while(row = getRow()){ + var profile = row.value; + result.section.configuration.profiles.profiles += + <profile name={profile.name}> + <aliases> + {each(profile.aliases, function(idx){ + return <alias name={profile.aliases[idx]} /> + })} + </aliases> + <gateways> + {each(profile.gateways, function(name, params){ + var xml = <gateway name={gateway.name} />; + for(var name in params){ + xml.gateway += <param name={name} value={params[name]} />; + } + return xml; + })} + </gateways> + <domains> + {each(profile.domains, function(name, obj){ + return <domain name={name} alias={obj.alias} parse={obj.parse} /> + })} + </domains> + <settings> + {each(profile.settings, function(name, value){ + return <param name={name} value={value} /> + })} + </settings> + </profile>; + } + + send(result); +} diff --git a/couch/configuration/lists/xml_cdr.conf.js b/couch/configuration/lists/xml_cdr.conf.js new file mode 100644 index 0000000..700042b --- /dev/null +++ b/couch/configuration/lists/xml_cdr.conf.js @@ -0,0 +1,16 @@ +function(head, req){ + var each = function(obj, callback){ + var result = <></>; + for(key in obj){ + if(obj.hasOwnProperty(key)){ + result += callback(key, obj[key]); + } + } + return result; + }; + + start({code: 200, headers: {'Content-Type': 'freeswitch/xml'}}); + send('<?xml version="1.0" encoding="UTF-8" standalone="no" ?>' + "\n"); + + log(head); +} diff --git a/couch/configuration/shows/acl.conf.js b/couch/configuration/shows/acl.conf.js new file mode 100644 index 0000000..2bb6682 --- /dev/null +++ b/couch/configuration/shows/acl.conf.js @@ -0,0 +1,34 @@ +function(doc, req){ + var each = function(obj, callback){ + var result = <></>; + for(key in obj){ + if(obj.hasOwnProperty(key)){ + result += callback(key, obj[key]); + } + } + return result; + }; + + start({code: 200, headers: {'Content-Type': 'freeswitch/xml'}}); + + return( +'<?xml version="1.0" encoding="UTF-8" standalone="no" ?>' + "\n" + ( +<document type="freeswitch/xml"> + <section name="configuration"> + <configuration name={doc._id} description={doc.description}> + <network-lists> + {each(doc.network_lists, function(name, list){ + var xml = <list name={name} default={list.default} />; + list.nodes.forEach(function(node){ + var tag = <node />; + for(key in node){ tag.@[key] = node[key]; } + xml.list += tag; + }); + return xml; + })} + </network-lists> + </configuration> + </section> +</document> + ).toXMLString()); +} diff --git a/couch/configuration/shows/alsa.conf.js b/couch/configuration/shows/alsa.conf.js new file mode 100644 index 0000000..c885ddf --- /dev/null +++ b/couch/configuration/shows/alsa.conf.js @@ -0,0 +1,28 @@ +function(doc, req){ + var each = function(obj, callback){ + var result = <></>; + for(key in obj){ + if(obj.hasOwnProperty(key)){ + result += callback(key, obj[key]); + } + } + return result; + }; + + start({code: 200, headers: {'Content-Type': 'freeswitch/xml'}}); + + return( +'<?xml version="1.0" encoding="UTF-8" standalone="no" ?>' + "\n" + ( +<document type="freeswitch/xml"> + <section name="configuration"> + <configuration name={doc._id} description={doc.description}> + <settings> + {each(doc.settings, function(name, value){ + return <param name={name} value={value} /> + })} + </settings> + </configuration> + </section> +</document> + ).toXMLString()); +} diff --git a/couch/configuration/shows/callcenter.conf.js b/couch/configuration/shows/callcenter.conf.js new file mode 100644 index 0000000..c72051e --- /dev/null +++ b/couch/configuration/shows/callcenter.conf.js @@ -0,0 +1,54 @@ +function(doc, req){ + var each = function(obj, callback){ + var result = <></>; + for(key in obj){ + if(obj.hasOwnProperty(key)){ + result += callback(key, obj[key]); + } + } + return result; + }; + + start({code: 200, headers: {'Content-Type': 'freeswitch/xml'}}); + + return( +'<?xml version="1.0" encoding="UTF-8" standalone="no" ?>' + "\n" + ( +<document type="freeswitch/xml"> + <section name="configuration"> + <configuration name={doc._id} description={doc.description}> + <settings> + {each(doc.settings, function(name, value){ + return <param name={name} value={value} /> + })} + </settings> + + <queues> + {each(doc.queues, function(name, params){ + var xml = <queue name={name} />; + for(key in params){ + xml.queue += <param name={key} value={params[key]} />; + } + return xml; + })} + </queues> + + <agents> + {each(doc.agents, function(name, attributes){ + var xml = <agent name={name} />; + for(key in attributes){ xml.@[key] = attributes[key]; } + return xml; + })} + </agents> + + <tiers> + {each(doc.tiers, function(key, tier){ + var xml = <tier level="1" position="1" />; + for(key in tier){ xml.@[key] = tier[key]; } + return xml; + })} + </tiers> + </configuration> + </section> +</document> + ).toXMLString()); +} diff --git a/couch/configuration/shows/cdr_csv.conf.js b/couch/configuration/shows/cdr_csv.conf.js new file mode 100644 index 0000000..56a810d --- /dev/null +++ b/couch/configuration/shows/cdr_csv.conf.js @@ -0,0 +1,34 @@ +function(doc, req){ + var each = function(obj, callback){ + var result = <></>; + for(key in obj){ + if(obj.hasOwnProperty(key)){ + result += callback(key, obj[key]); + } + } + return result; + }; + + start({code: 200, headers: {'Content-Type': 'freeswitch/xml'}}); + + return( +'<?xml version="1.0" encoding="UTF-8" standalone="no" ?>' + "\n" + ( +<document type="freeswitch/xml"> + <section name="configuration"> + <configuration name={doc._id} description={doc.description}> + <settings> + {each(doc.settings, function(name, value){ + return <param name={name} value={value} /> + })} + </settings> + + <templates> + {each(doc.templates, function(name, template){ + return <template name={name}>{template}</template>; + })} + </templates> + </configuration> + </section> +</document> + ).toXMLString()); +} diff --git a/couch/configuration/shows/cdr_pg_csv.conf.js b/couch/configuration/shows/cdr_pg_csv.conf.js new file mode 100644 index 0000000..56a810d --- /dev/null +++ b/couch/configuration/shows/cdr_pg_csv.conf.js @@ -0,0 +1,34 @@ +function(doc, req){ + var each = function(obj, callback){ + var result = <></>; + for(key in obj){ + if(obj.hasOwnProperty(key)){ + result += callback(key, obj[key]); + } + } + return result; + }; + + start({code: 200, headers: {'Content-Type': 'freeswitch/xml'}}); + + return( +'<?xml version="1.0" encoding="UTF-8" standalone="no" ?>' + "\n" + ( +<document type="freeswitch/xml"> + <section name="configuration"> + <configuration name={doc._id} description={doc.description}> + <settings> + {each(doc.settings, function(name, value){ + return <param name={name} value={value} /> + })} + </settings> + + <templates> + {each(doc.templates, function(name, template){ + return <template name={name}>{template}</template>; + })} + </templates> + </configuration> + </section> +</document> + ).toXMLString()); +} diff --git a/couch/configuration/shows/cidlookup.conf.js b/couch/configuration/shows/cidlookup.conf.js new file mode 100644 index 0000000..c885ddf --- /dev/null +++ b/couch/configuration/shows/cidlookup.conf.js @@ -0,0 +1,28 @@ +function(doc, req){ + var each = function(obj, callback){ + var result = <></>; + for(key in obj){ + if(obj.hasOwnProperty(key)){ + result += callback(key, obj[key]); + } + } + return result; + }; + + start({code: 200, headers: {'Content-Type': 'freeswitch/xml'}}); + + return( +'<?xml version="1.0" encoding="UTF-8" standalone="no" ?>' + "\n" + ( +<document type="freeswitch/xml"> + <section name="configuration"> + <configuration name={doc._id} description={doc.description}> + <settings> + {each(doc.settings, function(name, value){ + return <param name={name} value={value} /> + })} + </settings> + </configuration> + </section> +</document> + ).toXMLString()); +} diff --git a/couch/configuration/shows/conference.conf.js b/couch/configuration/shows/conference.conf.js new file mode 100644 index 0000000..430bdf2 --- /dev/null +++ b/couch/configuration/shows/conference.conf.js @@ -0,0 +1,46 @@ +function(doc, req){ + var each = function(obj, callback){ + var result = <></>; + for(key in obj){ + if(obj.hasOwnProperty(key)){ + result += callback(key, obj[key]); + } + } + return result; + }; + + start({code: 200, headers: {'Content-Type': 'freeswitch/xml'}}); + + return( +'<?xml version="1.0" encoding="UTF-8" standalone="no" ?>' + "\n" + ( +<document type="freeswitch/xml"> + <section name="configuration"> + <configuration name={doc._id} description={doc.description}> + <advertise> + {each(doc.advertise, function(name, status){ + return <room name={name} status={status} /> + })} + </advertise> + <caller-controls> + {each(doc.controls, function(name, controls){ + var xml = <group name={name} />; + for(key in controls){ + xml.group += <control action={key} digits={controls[key]} />; + } + return xml; + })} + </caller-controls> + <profiles> + {each(doc.profiles, function(name, params){ + var xml = <profile name={name} />; + for(key in params){ + xml.profile += <param name={key} value={params[key]} />; + } + return xml; + })} + </profiles> + </configuration> + </section> +</document> + ).toXMLString()); +} diff --git a/couch/configuration/shows/configuration.js b/couch/configuration/shows/configuration.js new file mode 100644 index 0000000..e3f0bc4 --- /dev/null +++ b/couch/configuration/shows/configuration.js @@ -0,0 +1,17 @@ +function(doc, req) { + log(req); + + var name = encodeURIComponent(req.form.key_value); + var url + + if(name === "sofia.conf"){ + var host = req.form.hostname + var url = "/fxc/_design/configuration/_list/sofia/sofia_profiles" + + "?startkey=" + encodeURIComponent('["' + host + '",0]') + + "&endkey=" + encodeURIComponent('["' + host + '",1]'); + } else { + var url = "/fxc/_design/configuration/_list/" + name + "/conf"; + } + + return {code: 302, body: '', headers: {'Location': url}} +} diff --git a/couch/configuration/shows/console.conf.js b/couch/configuration/shows/console.conf.js new file mode 100644 index 0000000..8127023 --- /dev/null +++ b/couch/configuration/shows/console.conf.js @@ -0,0 +1,33 @@ +function(doc, req){ + var each = function(obj, callback){ + var result = <></>; + for(key in obj){ + if(obj.hasOwnProperty(key)){ + result += callback(key, obj[key]); + } + } + return result; + }; + + start({code: 200, headers: {'Content-Type': 'freeswitch/xml'}}); + + return( +'<?xml version="1.0" encoding="UTF-8" standalone="no" ?>' + "\n" + ( +<document type="freeswitch/xml"> + <section name="configuration"> + <configuration name={doc._id} description={doc.description}> + <mappings> + {each(doc.mappings, function(name, value){ + return <map name={name} value={value.join(',')} /> + })} + </mappings> + <settings> + {each(doc.settings, function(name, value){ + return <param name={name} value={value} /> + })} + </settings> + </configuration> + </section> +</document> + ).toXMLString()); +} diff --git a/couch/configuration/shows/enum.conf.js b/couch/configuration/shows/enum.conf.js new file mode 100644 index 0000000..005e3a9 --- /dev/null +++ b/couch/configuration/shows/enum.conf.js @@ -0,0 +1,35 @@ +function(doc, req){ + var each = function(obj, callback){ + var result = <></>; + for(key in obj){ + if(obj.hasOwnProperty(key)){ + result += callback(key, obj[key]); + } + } + return result; + }; + + start({code: 200, headers: {'Content-Type': 'freeswitch/xml'}}); + + return( +'<?xml version="1.0" encoding="UTF-8" standalone="no" ?>' + "\n" + ( +<document type="freeswitch/xml"> + <section name="configuration"> + <configuration name={doc._id} description={doc.description}> + <settings> + {each(doc.settings, function(name, value){ + return <param name={name} value={value} /> + })} + </settings> + <routes> + {each(doc.routes, function(name, route){ + var xml = <route />; + for(key in route){ xml.@[key] = route[key]; } + return xml; + })} + </routes> + </configuration> + </section> +</document> + ).toXMLString()); +} diff --git a/couch/configuration/shows/event_socket.conf.js b/couch/configuration/shows/event_socket.conf.js new file mode 100644 index 0000000..c885ddf --- /dev/null +++ b/couch/configuration/shows/event_socket.conf.js @@ -0,0 +1,28 @@ +function(doc, req){ + var each = function(obj, callback){ + var result = <></>; + for(key in obj){ + if(obj.hasOwnProperty(key)){ + result += callback(key, obj[key]); + } + } + return result; + }; + + start({code: 200, headers: {'Content-Type': 'freeswitch/xml'}}); + + return( +'<?xml version="1.0" encoding="UTF-8" standalone="no" ?>' + "\n" + ( +<document type="freeswitch/xml"> + <section name="configuration"> + <configuration name={doc._id} description={doc.description}> + <settings> + {each(doc.settings, function(name, value){ + return <param name={name} value={value} /> + })} + </settings> + </configuration> + </section> +</document> + ).toXMLString()); +} diff --git a/couch/configuration/shows/logfile.conf.js b/couch/configuration/shows/logfile.conf.js new file mode 100644 index 0000000..ce58a9f --- /dev/null +++ b/couch/configuration/shows/logfile.conf.js @@ -0,0 +1,43 @@ +function(doc, req){ + var each = function(obj, callback){ + var result = <></>; + for(key in obj){ + if(obj.hasOwnProperty(key)){ + result += callback(key, obj[key]); + } + } + return result; + }; + + start({code: 200, headers: {'Content-Type': 'freeswitch/xml'}}); + + return( +'<?xml version="1.0" encoding="UTF-8" standalone="no" ?>' + "\n" + ( +<document type="freeswitch/xml"> + <section name="configuration"> + <configuration name={doc._id} description={doc.description}> + <settings> + {each(doc.settings, function(name, value){ + return <param name={name} value={value} /> + })} + </settings> + <profiles> + {each(doc.profiles, function(name, profile){ + var settings = <settings />; + for(key in profile.settings){ + settings.settings += <param name={key} value={profile.settings[key]} />; + } + + var mappings = <mappings />; + for(key in profile.mappings){ + mappings.mappings += <map name={key} value={profile.mappings[key]} />; + } + + return <profile name={name}>{settings}{mappings}</profile>; + })} + </profiles> + </configuration> + </section> +</document> + ).toXMLString()); +} diff --git a/couch/configuration/shows/sofia.conf.js b/couch/configuration/shows/sofia.conf.js new file mode 100644 index 0000000..a3e7355 --- /dev/null +++ b/couch/configuration/shows/sofia.conf.js @@ -0,0 +1,63 @@ +function(doc, req){ + var key; + var each = function(obj, callback){ + var result = <></>; + for(key in obj){ + if(obj.hasOwnProperty(key)){ + result += callback(key, obj[key]); + } + } + return result; + }; + + start({code: 200, headers: {'Content-Type': 'freeswitch/xml'}}); + + return( +'<?xml version="1.0" encoding="UTF-8" standalone="no" ?>' + "\n" + ( +<document type="freeswitch/xml"> + <section name="configuration"> + <configuration name={doc._id} description={doc.description}> + <global_settings> + {each(doc.settings, function(name, value){ + return <param name={name} value={value} /> + })} + </global_settings> + + + <profiles> + {each(lookup_profiles?, function(profile){ + <profile name={profile.name}> + <aliases> + {each(profile.aliases, function(name){ + return <alias name={name} /> + })} + </aliases> + <gateways> + {each(profile.gateways, function(name, params){ + <gateway name={gateway.name}> + {each(params), function(name, value){ + return <param name={name} value={value} /> + })} + </gateway> + })} + </gateways> + <domains> + {each(profile.domains, function(name, alias, parse){ + return <domain name={name} alias={alias} parse={parse} /> + })} + </domains> + <settings> + {each(profile.settings, function(name, value){ + return <param name={name} value={value} /> + })} + </settings> + + </profile> + })} + </profiles> + + </configuration> + </section> +</document> + ).toXMLString()); +} diff --git a/couch/configuration/shows/switch.conf.js b/couch/configuration/shows/switch.conf.js new file mode 100644 index 0000000..dd7b8a1 --- /dev/null +++ b/couch/configuration/shows/switch.conf.js @@ -0,0 +1,33 @@ +function(doc, req){ + var each = function(obj, callback){ + var result = <></>; + for(key in obj){ + if(obj.hasOwnProperty(key)){ + result += callback(key, obj[key]); + } + } + return result; + }; + + start({code: 200, headers: {'Content-Type': 'freeswitch/xml'}}); + + return( +'<?xml version="1.0" encoding="UTF-8" standalone="no" ?>' + "\n" + ( +<document type="freeswitch/xml"> + <section name="configuration"> + <configuration name={doc.name} description={doc.description}> + <cli-keybindings> + {each(doc.keybindings, function(name, value){ + return <key name={name} value={value} /> + })} + </cli-keybindings> + <settings> + {each(doc.settings, function(name, value){ + return <param name={name} value={value} /> + })} + </settings> + </configuration> + </section> +</document> + ).toXMLString()); +} diff --git a/couch/configuration/shows/xml_cdr.conf.js b/couch/configuration/shows/xml_cdr.conf.js new file mode 100644 index 0000000..c885ddf --- /dev/null +++ b/couch/configuration/shows/xml_cdr.conf.js @@ -0,0 +1,28 @@ +function(doc, req){ + var each = function(obj, callback){ + var result = <></>; + for(key in obj){ + if(obj.hasOwnProperty(key)){ + result += callback(key, obj[key]); + } + } + return result; + }; + + start({code: 200, headers: {'Content-Type': 'freeswitch/xml'}}); + + return( +'<?xml version="1.0" encoding="UTF-8" standalone="no" ?>' + "\n" + ( +<document type="freeswitch/xml"> + <section name="configuration"> + <configuration name={doc._id} description={doc.description}> + <settings> + {each(doc.settings, function(name, value){ + return <param name={name} value={value} /> + })} + </settings> + </configuration> + </section> +</document> + ).toXMLString()); +} diff --git a/couch/configuration/shows/xml_curl.conf.js b/couch/configuration/shows/xml_curl.conf.js new file mode 100644 index 0000000..0faf728 --- /dev/null +++ b/couch/configuration/shows/xml_curl.conf.js @@ -0,0 +1,37 @@ +function(doc, req){ + var each = function(obj, callback){ + var result = <></>; + for(key in obj){ + if(obj.hasOwnProperty(key)){ + result += callback(key, obj[key]); + } + } + return result; + }; + + start({code: 200, headers: {'Content-Type': 'freeswitch/xml'}}); + + return( +'<?xml version="1.0" encoding="UTF-8" standalone="no" ?>' + "\n" + ( +<document type="freeswitch/xml"> + <section name="configuration"> + <configuration name={doc._id} description={doc.description}> + <bindings> + {each(doc.bindings, function(name, binding){ + var xml = <binding name={name} />; + for(key in binding){ + var value = binding[key]; + if(key === "gateway-url"){ + xml.binding += <param name={key} value={value.value} bindings={value.bindings} />; + } else { + xml.binding += <param name={key} value={value} />; + } + } + return xml; + })} + </bindings> + </configuration> + </section> +</document> + ).toXMLString()); +} diff --git a/couch/configuration/views/conf/map.js b/couch/configuration/views/conf/map.js new file mode 100644 index 0000000..70173fa --- /dev/null +++ b/couch/configuration/views/conf/map.js @@ -0,0 +1,5 @@ +function(doc){ + if(doc.name && doc.server != undefined){ + emit([doc.name, doc.server], doc); + } +} diff --git a/couch/configuration/views/sofia_profiles/map.js b/couch/configuration/views/sofia_profiles/map.js new file mode 100644 index 0000000..98eaec5 --- /dev/null +++ b/couch/configuration/views/sofia_profiles/map.js @@ -0,0 +1,8 @@ +function(doc){ + if(doc.aliases && doc.gateways && doc.domains && doc.settings){ + emit([doc.server, 1], doc); + } + if(doc._id === "sofia.conf"){ + emit([doc.server, 0], doc); + } +} diff --git a/lib/fxc.rb b/lib/fxc.rb new file mode 100644 index 0000000..53d31d8 --- /dev/null +++ b/lib/fxc.rb @@ -0,0 +1,65 @@ + +module Fxc + + # :stopdoc: + LIBPATH = ::File.expand_path(::File.dirname(__FILE__)) + ::File::SEPARATOR + PATH = ::File.dirname(LIBPATH) + ::File::SEPARATOR + # :startdoc: + + # Returns the version string for the library. + # + def self.version + @version ||= File.read(path('version.txt')).strip + end + + # Returns the library path for the module. If any arguments are given, + # they will be joined to the end of the libray path using + # <tt>File.join</tt>. + # + def self.libpath( *args, &block ) + rv = args.empty? ? LIBPATH : ::File.join(LIBPATH, args.flatten) + if block + begin + $LOAD_PATH.unshift LIBPATH + rv = block.call + ensure + $LOAD_PATH.shift + end + end + return rv + end + + # Returns the lpath for the module. If any arguments are given, + # they will be joined to the end of the path using + # <tt>File.join</tt>. + # + def self.path( *args, &block ) + rv = args.empty? ? PATH : ::File.join(PATH, args.flatten) + if block + begin + $LOAD_PATH.unshift PATH + rv = block.call + ensure + $LOAD_PATH.shift + end + end + return rv + end + + # Utility method used to require all files ending in .rb that lie in the + # directory below this file that has the same name as the filename passed + # in. Optionally, a specific _directory_ name can be passed in such that + # the _filename_ does not have to be equivalent to the directory. + # + def self.require_all_libs_relative_to( fname, dir = nil ) + dir ||= ::File.basename(fname, '.*') + search_me = ::File.expand_path( + ::File.join(::File.dirname(fname), dir, '**', '*.rb')) + + Dir.glob(search_me).sort.each {|rb| require rb} + end + +end # module Fxc + +Fxc.require_all_libs_relative_to(__FILE__) + diff --git a/lib/rack/middleware.rb b/lib/rack/middleware.rb new file mode 100644 index 0000000..c5c1951 --- /dev/null +++ b/lib/rack/middleware.rb @@ -0,0 +1,83 @@ +# Copyright (c) 2008-2009 The Rubyists, LLC (effortless systems) <[email protected]> +# Distributed under the terms of the MIT license. +# The full text can be found in the LICENSE file included with this software +# +module Fxc + module Rack + class Middleware + def initialize(app) + @app = app + end + + def call(env) + params = ::Rack::Request.new(env) + return @app.call(env) unless params["section"] + + path = params["section"] + "/" + + path << case path + when "dialplan/" + dp_req(params) + when "directory/" + dir_req(params) + when "configuration/" + conf_req(params) + end + + env["PATH_INFO"] = "#{env['PATH_INFO']}/#{path}".squeeze('/') + @app.call(env) + end + + private + def dp_req(params) + s = [params["Caller-Context"]] + s << params["Caller-Destination-Number"] + s << params["Caller-Caller-ID-Number"] + s.compact.join("/") + end + + def dir_req(params) + s = [] + if params["purpose"] + s << params["purpose"].gsub("-","_") + s << params["sip_profile"] + elsif params["action"] && params["action"] == "sip_auth" + s << "register" + s << params["sip_profile"] + s << params["sip_auth_username"] + elsif params["user"] + if params["action"] == "message-count" + s << "messages" + s << params["user"] + s << params["key_value"] if params["tag_name"] == "domain" + elsif params["Event-Calling-Function"] + case params["Event-Calling-Function"].to_s + when /voicemail/ + s << "voicemail" + s << (params["sip_profile"] || "default") + s << params["user"] + when "user_outgoing_channel" + s << "user_outgoing" + s << params["user"] + s << params["domain"] if params["domain"] + when "user_data_function" + s << "user_data" + s << params["user"] + s << params["domain"] if params["domain"] + end + end + end + s.join("/") + end + + def conf_req(params) + s = [] + if params["key_name"] == "name" + s << params["key_value"] + end + s.join("/") + end + + end + end +end diff --git a/node/configuration.rb b/node/configuration.rb new file mode 100644 index 0000000..4bacce9 --- /dev/null +++ b/node/configuration.rb @@ -0,0 +1,6 @@ +class FxcConfiguration + Innate.node "/configuration" + def index + "configuration" + end +end diff --git a/spec/fxc_spec.rb b/spec/fxc_spec.rb new file mode 100644 index 0000000..a0b8cf6 --- /dev/null +++ b/spec/fxc_spec.rb @@ -0,0 +1,6 @@ + +require File.join(File.dirname(__FILE__), %w[spec_helper]) + +describe Fxc do +end + diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb new file mode 100644 index 0000000..ce021a8 --- /dev/null +++ b/spec/spec_helper.rb @@ -0,0 +1,15 @@ + +require File.expand_path( + File.join(File.dirname(__FILE__), %w[.. lib fxc])) + +Spec::Runner.configure do |config| + # == Mock Framework + # + # RSpec uses it's own mocking framework by default. If you prefer to + # use mocha, flexmock or RR, uncomment the appropriate line: + # + # config.mock_with :mocha + # config.mock_with :flexmock + # config.mock_with :rr +end + diff --git a/sync_couch.rb b/sync_couch.rb new file mode 100644 index 0000000..5c25e7b --- /dev/null +++ b/sync_couch.rb @@ -0,0 +1,26 @@ +require 'makura' + +Makura::Model.server = 'http://jimmy:5984' +Makura::Model.database = 'fxc' + +root = File.expand_path("../couch/configuration", __FILE__) +glob = File.join(root, "**/*.js") + +begin + layout = Makura::Model.database["_design/configuration"] || {} +rescue Makura::Error::ResourceNotFound + layout = {} +end + +layout['language'] ||= 'javascript' +layout['_id'] ||= "_design/configuration" + +Dir.glob(glob) do |file| + keys = File.dirname(file).sub(root, '').scan(/[^\/]+/) + doc = File.read(file) + last = nil + keys.inject(layout){|k,v| last = k[v] ||= {} } + last[File.basename(file, '.js')] = doc +end + +Makura::Model.database.save(layout) diff --git a/test/test_fxc.rb b/test/test_fxc.rb new file mode 100644 index 0000000..e69de29 diff --git a/version.txt b/version.txt new file mode 100644 index 0000000..77d6f4c --- /dev/null +++ b/version.txt @@ -0,0 +1 @@ +0.0.0
worxco/simplesql
f07a53c54bb1f119a67deaa614567cc01ccff5ff
Added tt.sql to .gitignore
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..938daf5 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +tt.sql
worxco/simplesql
0c504c04117739fe386369115aa97ad1fb4d8a17
Added tempfile logic for OS X and linux platform
diff --git a/simplesql b/simplesql index ebccfa8..c97a4a7 100755 --- a/simplesql +++ b/simplesql @@ -1,562 +1,574 @@ #!/bin/bash # Program: simpelsql # Description: This is an aggregation of mysql based commands. Most often used when working with the Drupal Database. # Author: Kurt L Vanderwater # Copyright (C) 2007-2010 Meridian Data Systems, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. set -o errexit set -o nounset # For this script to run properly, you must fill out all the required information. # If you are lazy like me, you can run a file named simplesql.conf to initialize # certain defaults and aliases. # # the format of this file should be as follows. #> #!/bin/bash #> #> # Setup Defaults #> #> i=0 #> # Set up in the hostA variable the always working address to the server, followed by any aliases you like. #> # all delimited by commas. #> hostA[$i]="sql01.domain.com,sql01" #> userA[$i]="root"; # Put the user for this server here #> passwdA[$i]="<password here>"; # Put the password for this server here (usually for root) #> DBNameA[$((i++))]="test"; # If you want a default database to end up in, this is the place. #> #> hostA[$i]="sql02.domain.com,sql02,x9sql02" #> userA[$i]="root" #> passwdA[$i]="<password here>" #> DBNameA[$((i++))]="test" #> #> tempfile=`tempfile` #> tfile2=`tempfile` #> #> mode="edit" #> host="sql01.doamain.com" #> passwd="" #> user="root" #> DBName="" [ -f /etc/simplesql.conf ] && source ~/etc/simplesql.conf [ -f ~/bin/simplesql.conf ] && source ~/bin/simplesql.conf [ -f simplesql.conf ] && source simplesql.conf -tempfile=`tempfile` -tfile2=`tempfile` -tfile3=`tempfile` +OS=`uname -s` +case $OS in + 'Darwin') + mktemp="/usr/bin/mktemp /tmp/simplesql.XXXXXXXX" + ;; + + * ) + mktemp="/bin/mktemp /tmp/simplesql.XXXXXXXX" + ;; + +esac + +tempfile=`$mktemp` +tfile2=`$mktemp` +tfile3=`$mktemp` ########################################################## # Create the Usage variable to display if they need help # ########################################################## usage=`cat <<EOF simplesql Copyright (C) 2007-2010 Meridian Data Systems, Inc.\n This program comes with ABSOLUTELY NO WARRANTY; for details read the source.\n This is free software, and you are welcome to redistribute it\n under certain conditions; See the included license.\n\n Usage:\n\n $0 [ -h ] [ -d <database> ] [ -f <filename> ] [ -m <mode> ] [ -n <new database> ] [ -p <password> ] [ -s <quoted script> ] [ -u <user> ]\n\n $(tput setaf 5)-h:$(tput setaf 9) Provide this usage page.\n\n $(tput setaf 5)-a <current Drupal admin password>:$(tput setaf 9) This is the current Drupal admin password. If this doesn't match, we don't run\n\n $(tput setaf 5)-b <new Drupal admin password>:$(tput setaf 9) This is the new, replacement Drupal admin password. see -a for trigger\n\n $(tput setaf 5)-d <database>:$(tput setaf 9) Enter the name of the database that you are operating against.\n\n $(tput setaf 5)-f <filename>:$(tput setaf 9) This is a script file with multiple semi-colon terminated mysql commands.\n\n $(tput setaf 5)-i <findstr>:$(tput setaf 9) This is a string that you wish to search for.\n\n $(tput setaf 5)-m <mode>:$(tput setaf 9) This defines the different modes that this script can operate in.\n \tdump - Dump the named database to a file with the name of the database.dump.\n \timport - Run the database.dump file created by the dump command above. This is a restore and not a merge.\n \tdumpdrupal - Dump the named database to a file with the name of the database.drupal.dump.\n \t\tThe purpose of this variant is to only get the structure for cache, session, & watchdog tables.\n \t\tAlong with all the data from the rest of the tables.\n \tdrupalfind - Search a given Drupal database for all occurances of a string.\n \tcopy - Copy a database into another existing database name.\n \t\tThis will NOT recreate the new database. It will clear\n \t\tany existing tables. It will add any new tables.\n \tclone - Copy a database into a new database.\n \trun - run the script provided on the command line by -s <quoted script>.\n \trunfile - run the script command(s) provided in the file named by -f <filename>.\n \texport - create a CSV file output from the dabase.\n \tedit - Go into command line mode of mysql.\n \tshow - Show a list of tables for the database.\n \tstats - launch mytop if it is available\n\n \talter - Alter ALL Drupal admin passwords \tcheckall - check extended all tables in the database.\n \trepairall - repair extended all tables in the database.\n $(tput setaf 5)-n <new database>:$(tput setaf 9) The name of the new database for copy or clone.\n\n $(tput setaf 5)-o <host>:$(tput setaf 9) The host server where the database exists.\n\n $(tput setaf 5)-p <password>:$(tput setaf 9) The password needed by the user (-u) to access the database.\n\n $(tput setaf 5)-s <quoted script>:$(tput setaf 9) This is a quoted string that is a mysql command script.\n\n $(tput setaf 5)-t <table name>:$(tput setaf 9) This is the table that you want to export.\n\n $(tput setaf 5)-u <user>:$(tput setaf 9) The username that has access to the database.\n\n $(tput setaf 5)-x <CSV export file>:$(tput setaf 9) The output filename you want your CSV export to end up in.\n\n EOF` ################################################ # Accept and parse all the incoming parameters # ################################################ while getopts ":hm:a:b:d:n:o:p:s:t:u:f:i:x:" options ; do case $options in m ) mode=$OPTARG;; a ) DrupO=$OPTARG;; b ) DrupN=$OPTARG;; d ) DBName=$OPTARG;; n ) DBNameNew=$OPTARG;; o ) host=$OPTARG;; p ) passwd=$OPTARG;; s ) script=$OPTARG;; t ) table=$OPTARG;; u ) user=$OPTARG;; f ) filename=$OPTARG;; x ) xport=$OPTARG;; i ) findstr=$OPTARG;; h ) mode="help";; esac done ############################################### # Based on the 'host' variable, check aliases # # and select the host. If the passwd, user, # # or DBName variables were not passed in, # # then set them to known defaults. # ############################################### for (( i=0; i<$((${#hostA[@]})); i=i+1 )); do # echo ${alias[i]} # echo -n "$a :: " set -- `echo ${hostA[i]} | tr , \ ` temp=$1 while [ ${#1} -gt 0 ]; do if [ $1 == $host ]; then host=$temp if [[ ! $passwd ]];then passwd=${passwdA[i]} fi if [[ ! $user ]];then user=${userA[i]} fi if [[ ! $DBName ]];then DBName=${DBNameA[i]} fi fi shift done done ################################################ # Based on the mode given, execute the command # ################################################ case $mode in ######################################################## # Do a mysqldump of a specific database # # Normally, if I do the dump, it is because # # I want to look at it. So, the --skip-extended-insert # # option so I can actually read the records # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access our DB # # passwd - The password needed # # DBName - The database we need a dump of # ######################################################## "dump" ) # Dump a copy of the database into $DBName.dump echo "mysqldump --skip-extended-insert -h $host -u $user -p$passwd $DBName > $DBName.dump" mysqldump --skip-extended-insert -h $host -u $user -p$passwd $DBName > $DBName.dump ;; ######################################################## # Do a mysqldump of a specific database just for the # # structure. # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access our DB # # passwd - The password needed # # DBName - The database we need a dump of # ######################################################## "dumpmeta" ) # Dump a copy of the metadata about the database into $DBName.meta echo "mysqldump --no-data -h $host -u $user -p$passwd $DBName > $DBName.meta" mysqldump --no-data -h $host -u $user -p$passwd $DBName > $DBName.meta ;; ################################################ # Show a list of a the tables in the Database # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access our DB # # passwd - The password needed # # DBName - The database we need a dump of # ################################################ "show" ) # Show a list of tables in the $DBName database mysqlshow -h $host -u $user -p$passwd $DBName ;; ####################################################### # Do a Drupal Dump... This is for a Drupal database # # It is meant to dump all the data, but to leave # # behind any cache, session, or watchdog information. # # The purpose here is to keep the size of the backup # # WAY down.... # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access our DB # # passwd - The password needed # # DBName - The database we need a dump of # ####################################################### "dumpdrupal" ) mysql -h $host -u $user -p$passwd $DBName -Bs -e "show tables" > $tempfile rm -f ${DBName}.drupal.dump for t in `cat $tempfile`; do case $t in watchdog|sessions|cache|cache_[a-z]*) mysqldump --no-data -h $host -u $user -p$passwd $DBName $t >> ${DBName}.drupal.dump ;; * ) mysqldump --skip-extended-insert -h $host -u $user -p$passwd $DBName $t >> ${DBName}.drupal.dump ;; esac done ;; ####################################################### # Do a Check [table] on all tables in the database # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access our DB # # passwd - The password needed # # DBName - The database we need a dump of # ####################################################### "checkall" ) mysql -h $host -u $user -p$passwd $DBName -Bs -e "show tables" > $tempfile for t in `cat $tempfile`; do mysql -h $host -u $user -p$passwd $DBName -Bs -e "check table $t extended" done rm -f $tempfile ;; ####################################################### # Do a Repair [table] on all tables in the database # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access our DB # # passwd - The password needed # # DBName - The database we need a dump of # ####################################################### "repairall" ) mysql -h $host -u $user -p$passwd $DBName -Bs -e "show tables" > $tempfile for t in `cat $tempfile`; do mysql -h $host -u $user -p$passwd $DBName -Bs -e "repair table $t extended" done rm -f $tempfile ;; ####################################################### # Do a Drupal Find... This is for a Drupal database # # It is meant to search through all the tables to # # all occurances of a string. It ignores the cache # # tables along with the sessions and watchdog. # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access our DB # # passwd - The password needed # # DBName - The database we need a dump of # # findstr - The string you want to search for # ####################################################### "drupalfind" ) echo "Running drupalfind -- Searching for $findstr" echo "Output written to: $tfile3" mysql -h $host -u $user -p$passwd $DBName -Bs -e "show tables" > $tempfile rm -f ${DBName}.drupal.dump for t in `cat $tempfile`; do case $t in watchdog|sessions|cache|cache_[a-z]*) ;; * ) set +o errexit mysqldump --skip-extended-insert -h $host -u $user -p$passwd $DBName $t | grep "$findstr" > $tfile2 set -o errexit ;; esac if [ -s $tfile2 ]; then echo "=================" >> $tfile3 echo $t >> $tfile3 echo "=================" >> $tfile3 cat $tfile2 >> $tfile3 fi done cat $tfile3 ;; ####################################################### # Restore a .dump file that has been created by the # # 'dump' command defined above. # # behind any cache, session, or watchdog information. # # The purpose here is to keep the size of the backup # # WAY down.... # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access our 'New' DB # # passwd - The password needed for the 'New' DB # # DBName - The database we have a dump of # # DBNameNew - The database we are restoring to # ####################################################### "import" ) #Import from the .dump file into a database echo Importing into $DBNameNew mysql -h $host -u $user -p$passwd $DBNameNew < $DBName.dump ;; ####################################################### # This is a combination of the 'dump' command and the # # 'import' command. The is a small issue here in that # # the host, user, & password must be the same for # # both databases. Both Databases must ALREADY exist. # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access both DB's # # passwd - The password needed for both DB's # # DBName - The source database # # DBNameNew - The destination database # ####################################################### "copy" ) # Make a copy of a database into an existing one. echo "Clearing destination database of all tables" mysql -h $host -u $user -p$passwd $DBNameNew -Bs -e "show tables" > $tempfile for t in `cat $tempfile`; do set +o errexit mysql -h $host -u $user -p$passwd $DBNameNew -Bs -e "drop table $t" set -o errexit done echo "Dumpfile file to $tempfile" mysqldump -h $host -u $user -p$passwd $DBName > $tempfile echo "Importing $tempfile to $DBNameNew" mysql -h $host -u $user -p$passwd $DBNameNew < $tempfile echo "Done! $tempfile still available in case you screwed up!" ;; ####################################################### # This routine will make a backup of a database and # # then CREATE a NEW database to restore the backup # # to. Again, the hosts, user, & password must be the # # same for both databases. # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access both DB's # # passwd - The password needed for both DB's # # DBName - The source database # # DBNameNew - The destination database # ####################################################### "clone" ) # Make a clone of a database into a new one. echo "Dumpfile file to $tempfile" mysqldump -h $host -u $user -p$passwd $DBName > $tempfile echo "Creating the new database $DBNameNew" cat <<EOF > $tfile2 create database if not exists $DBNameNew; quit EOF mysql -h $host -u $user -p$passwd < $tfile2 rm -f $tfile2 echo "Importing $tempfile to $DBNameNew" mysql -h $host -u $user -p$passwd $DBNameNew < $tempfile echo "Done! $tempfile still available in case you screwed up!" ;; ####################################################### # This will allow for an arbitrary mysql command to # # run. It is run agains the database. If you want to # # string multiple command together, use ';' between # # each command. # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access both DB's # # passwd - The password needed for both DB's # # DBName - The source database # ####################################################### "run" ) # Run a quote enclosed script against a database cat <<EOF > $tempfile $script; quit EOF mysql -h $host -u $user -p$passwd $DBName <$tempfile ;; ####################################################### # This will allow for an arbitrary set of mysql # # commands to be run. Build a file with each command # # on a separate line. Terminate each line with ';' # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access both DB's # # passwd - The password needed for both DB's # # DBName - The source database # # filename - The name of the script file # ####################################################### "runfile" ) # Run a script file against a database echo Running script on $DBName mysql -h $host -u $user -p$passwd $DBName < $filename ;; ####################################################### # This provides you with Command Line Interface into # # mysql. # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access both DB's # # passwd - The password needed for both DB's # # DBName - The source database # ####################################################### "edit" ) # Go into raw mysql mode on a database # echo "Host: $host - User: $user - Password: $passwd - DB: $DBName" echo "SQL CLI on $host for User $user using Password $passwd in DB $DBName" - mysql -h $host -u $user -p$passwd $DBName + mysql -h $host -u${user} -p${passwd} $DBName ;; ####################################################### # Export a table in the database in a CSV format. # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access both DB's # # passwd - The password needed for both DB's # # DBName - The source database # # table - The source tablename # # xport - The name of the output file in CSV format # ####################################################### "export" ) #Export into CSV format #SELECT * INTO OUTFILE '/somefile.csv' #FIELDS ESCAPED BY '\' #FIELDS OPTIONALLY ENCLOSED BY '"' #FIELDS TERMINATED BY ',' #LINES TERMINATED BY '\n' #FROM table WHERE column='value'"; echo Running CSV export on Database: $DBName and Table: $table cat <<EOF > $tfile2 SELECT * INTO OUTFILE '$xport' FIELDS ESCAPED BY '\' OPTIONALLY ENCLOSED BY '"' TERMINATED BY ',' LINES TERMINATED BY '\n' FROM $table"; quit EOF mysql -h $host -u $user -p$passwd $DBName <$tfile2 >$xport ;; ####################################################### # Provide a 'top' like statistics for your mysql # # server. # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access both DB's # # passwd - The password needed for both DB's # # # # You must have the mytop package installed for this # # to work. # ####################################################### "stats" ) set +o errexit which mytop > /dev/null 2>&1 rc=$? if [ $rc -eq 0 ]; then mytop -u $user -p $passwd -h $host -s 3 else echo -e $usage cat <<EOF $(tput setaf 1)ERROR:$(tput setaf 9) You have attempted run the statistics portion of this script. It is a requirement of this that you have available the 'mytop' package. To Install on various platforms =============================== GENTOO: emerge -avt mytop EOF fi set -o errexit ;; ####################################################### # Alters ALL admin password within all drupal DBs # # on a specified server. You must provide the old # # and new admin passwords. If the old password does # # not match what is currently in the database, it is # # assumed that the password is NOT TO BE CHANGED. # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access both DB's # # passwd - The password needed for both DB's # # DrupO - The current drupal admin (user 1) password # # DrupN - The new drupal admin (user 1) password # ####################################################### "alter" ) [ ${DrupO:=fred} = "fred" ] && echo "Error :: you must provide the old Drupal Admin password (-a)" && exit 1 [ ${DrupN:=fred} = "fred" ] && echo "Error :: you must provide the new Drupal Admin password (-b)" && exit 1 dblist=`mysql -h $host -u $user -p$passwd -Bs -e "select table_schema from tables where table_name = 'node'" information_schema` /bin/rm -f $tempfile for d in $dblist; do mysql -h $host -u $user -p$passwd -Bs -e "select \"$d\" from users where uid = 1 and pass = md5('$DrupO')" $d >> $tempfile done for d in `cat $tempfile`; do mysql -h $host -u $user -p$passwd -Bs -e "select \"$d - old:\", name, pass from users where uid = 1 and pass = md5('$DrupO')" $d mysql -h $host -u $user -p$passwd -Bs -e "update users set pass = md5('$DrupN') where uid = 1 and pass = md5('$DrupO')" $d mysql -h $host -u $user -p$passwd -Bs -e "select \"$d - new:\", name, pass from users where uid = 1 and pass = md5('$DrupN')" $d echo ----- done ;; ####################################################### # Well, you didn't chose anything, and no default was # # supplied, so here is the usage description # ####################################################### * ) # user error... show the usage page. echo -e $usage ;; esac
worxco/simplesql
3e9758c48e23235f315145bf93f427a22ffab2f7
Added 2 new functions. Checkall (extended) and Repairall (extended)
diff --git a/simplesql b/simplesql index 5da37b1..ebccfa8 100755 --- a/simplesql +++ b/simplesql @@ -1,524 +1,562 @@ #!/bin/bash # Program: simpelsql # Description: This is an aggregation of mysql based commands. Most often used when working with the Drupal Database. # Author: Kurt L Vanderwater # Copyright (C) 2007-2010 Meridian Data Systems, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. set -o errexit set -o nounset # For this script to run properly, you must fill out all the required information. # If you are lazy like me, you can run a file named simplesql.conf to initialize # certain defaults and aliases. # # the format of this file should be as follows. #> #!/bin/bash #> #> # Setup Defaults #> #> i=0 #> # Set up in the hostA variable the always working address to the server, followed by any aliases you like. #> # all delimited by commas. #> hostA[$i]="sql01.domain.com,sql01" #> userA[$i]="root"; # Put the user for this server here #> passwdA[$i]="<password here>"; # Put the password for this server here (usually for root) #> DBNameA[$((i++))]="test"; # If you want a default database to end up in, this is the place. #> #> hostA[$i]="sql02.domain.com,sql02,x9sql02" #> userA[$i]="root" #> passwdA[$i]="<password here>" #> DBNameA[$((i++))]="test" #> #> tempfile=`tempfile` #> tfile2=`tempfile` #> #> mode="edit" #> host="sql01.doamain.com" #> passwd="" #> user="root" #> DBName="" [ -f /etc/simplesql.conf ] && source ~/etc/simplesql.conf [ -f ~/bin/simplesql.conf ] && source ~/bin/simplesql.conf [ -f simplesql.conf ] && source simplesql.conf tempfile=`tempfile` tfile2=`tempfile` tfile3=`tempfile` ########################################################## # Create the Usage variable to display if they need help # ########################################################## usage=`cat <<EOF simplesql Copyright (C) 2007-2010 Meridian Data Systems, Inc.\n This program comes with ABSOLUTELY NO WARRANTY; for details read the source.\n This is free software, and you are welcome to redistribute it\n under certain conditions; See the included license.\n\n Usage:\n\n $0 [ -h ] [ -d <database> ] [ -f <filename> ] [ -m <mode> ] [ -n <new database> ] [ -p <password> ] [ -s <quoted script> ] [ -u <user> ]\n\n $(tput setaf 5)-h:$(tput setaf 9) Provide this usage page.\n\n $(tput setaf 5)-a <current Drupal admin password>:$(tput setaf 9) This is the current Drupal admin password. If this doesn't match, we don't run\n\n $(tput setaf 5)-b <new Drupal admin password>:$(tput setaf 9) This is the new, replacement Drupal admin password. see -a for trigger\n\n $(tput setaf 5)-d <database>:$(tput setaf 9) Enter the name of the database that you are operating against.\n\n $(tput setaf 5)-f <filename>:$(tput setaf 9) This is a script file with multiple semi-colon terminated mysql commands.\n\n $(tput setaf 5)-i <findstr>:$(tput setaf 9) This is a string that you wish to search for.\n\n $(tput setaf 5)-m <mode>:$(tput setaf 9) This defines the different modes that this script can operate in.\n \tdump - Dump the named database to a file with the name of the database.dump.\n \timport - Run the database.dump file created by the dump command above. This is a restore and not a merge.\n \tdumpdrupal - Dump the named database to a file with the name of the database.drupal.dump.\n \t\tThe purpose of this variant is to only get the structure for cache, session, & watchdog tables.\n \t\tAlong with all the data from the rest of the tables.\n \tdrupalfind - Search a given Drupal database for all occurances of a string.\n \tcopy - Copy a database into another existing database name.\n \t\tThis will NOT recreate the new database. It will clear\n \t\tany existing tables. It will add any new tables.\n \tclone - Copy a database into a new database.\n \trun - run the script provided on the command line by -s <quoted script>.\n \trunfile - run the script command(s) provided in the file named by -f <filename>.\n \texport - create a CSV file output from the dabase.\n \tedit - Go into command line mode of mysql.\n \tshow - Show a list of tables for the database.\n \tstats - launch mytop if it is available\n\n \talter - Alter ALL Drupal admin passwords + \tcheckall - check extended all tables in the database.\n + \trepairall - repair extended all tables in the database.\n $(tput setaf 5)-n <new database>:$(tput setaf 9) The name of the new database for copy or clone.\n\n $(tput setaf 5)-o <host>:$(tput setaf 9) The host server where the database exists.\n\n $(tput setaf 5)-p <password>:$(tput setaf 9) The password needed by the user (-u) to access the database.\n\n $(tput setaf 5)-s <quoted script>:$(tput setaf 9) This is a quoted string that is a mysql command script.\n\n $(tput setaf 5)-t <table name>:$(tput setaf 9) This is the table that you want to export.\n\n $(tput setaf 5)-u <user>:$(tput setaf 9) The username that has access to the database.\n\n $(tput setaf 5)-x <CSV export file>:$(tput setaf 9) The output filename you want your CSV export to end up in.\n\n EOF` ################################################ # Accept and parse all the incoming parameters # ################################################ while getopts ":hm:a:b:d:n:o:p:s:t:u:f:i:x:" options ; do case $options in m ) mode=$OPTARG;; a ) DrupO=$OPTARG;; b ) DrupN=$OPTARG;; d ) DBName=$OPTARG;; n ) DBNameNew=$OPTARG;; o ) host=$OPTARG;; p ) passwd=$OPTARG;; s ) script=$OPTARG;; t ) table=$OPTARG;; u ) user=$OPTARG;; f ) filename=$OPTARG;; x ) xport=$OPTARG;; i ) findstr=$OPTARG;; h ) mode="help";; esac done ############################################### # Based on the 'host' variable, check aliases # # and select the host. If the passwd, user, # # or DBName variables were not passed in, # # then set them to known defaults. # ############################################### for (( i=0; i<$((${#hostA[@]})); i=i+1 )); do # echo ${alias[i]} # echo -n "$a :: " set -- `echo ${hostA[i]} | tr , \ ` temp=$1 while [ ${#1} -gt 0 ]; do if [ $1 == $host ]; then host=$temp if [[ ! $passwd ]];then passwd=${passwdA[i]} fi if [[ ! $user ]];then user=${userA[i]} fi if [[ ! $DBName ]];then DBName=${DBNameA[i]} fi fi shift done done ################################################ # Based on the mode given, execute the command # ################################################ case $mode in ######################################################## # Do a mysqldump of a specific database # # Normally, if I do the dump, it is because # # I want to look at it. So, the --skip-extended-insert # # option so I can actually read the records # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access our DB # # passwd - The password needed # # DBName - The database we need a dump of # ######################################################## "dump" ) # Dump a copy of the database into $DBName.dump echo "mysqldump --skip-extended-insert -h $host -u $user -p$passwd $DBName > $DBName.dump" mysqldump --skip-extended-insert -h $host -u $user -p$passwd $DBName > $DBName.dump ;; ######################################################## # Do a mysqldump of a specific database just for the # # structure. # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access our DB # # passwd - The password needed # # DBName - The database we need a dump of # ######################################################## "dumpmeta" ) # Dump a copy of the metadata about the database into $DBName.meta echo "mysqldump --no-data -h $host -u $user -p$passwd $DBName > $DBName.meta" mysqldump --no-data -h $host -u $user -p$passwd $DBName > $DBName.meta ;; ################################################ # Show a list of a the tables in the Database # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access our DB # # passwd - The password needed # # DBName - The database we need a dump of # ################################################ "show" ) # Show a list of tables in the $DBName database mysqlshow -h $host -u $user -p$passwd $DBName ;; ####################################################### # Do a Drupal Dump... This is for a Drupal database # # It is meant to dump all the data, but to leave # # behind any cache, session, or watchdog information. # # The purpose here is to keep the size of the backup # # WAY down.... # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access our DB # # passwd - The password needed # # DBName - The database we need a dump of # ####################################################### "dumpdrupal" ) mysql -h $host -u $user -p$passwd $DBName -Bs -e "show tables" > $tempfile rm -f ${DBName}.drupal.dump for t in `cat $tempfile`; do case $t in watchdog|sessions|cache|cache_[a-z]*) mysqldump --no-data -h $host -u $user -p$passwd $DBName $t >> ${DBName}.drupal.dump ;; * ) mysqldump --skip-extended-insert -h $host -u $user -p$passwd $DBName $t >> ${DBName}.drupal.dump ;; esac done ;; + ####################################################### + # Do a Check [table] on all tables in the database # + # # + # Required parameters: # + # host - what server are we on? # + # user - what user do we use to access our DB # + # passwd - The password needed # + # DBName - The database we need a dump of # + ####################################################### + "checkall" ) + mysql -h $host -u $user -p$passwd $DBName -Bs -e "show tables" > $tempfile + + for t in `cat $tempfile`; do + mysql -h $host -u $user -p$passwd $DBName -Bs -e "check table $t extended" + done + rm -f $tempfile + ;; + + ####################################################### + # Do a Repair [table] on all tables in the database # + # # + # Required parameters: # + # host - what server are we on? # + # user - what user do we use to access our DB # + # passwd - The password needed # + # DBName - The database we need a dump of # + ####################################################### + "repairall" ) + mysql -h $host -u $user -p$passwd $DBName -Bs -e "show tables" > $tempfile + + for t in `cat $tempfile`; do + mysql -h $host -u $user -p$passwd $DBName -Bs -e "repair table $t extended" + done + rm -f $tempfile + ;; + ####################################################### # Do a Drupal Find... This is for a Drupal database # # It is meant to search through all the tables to # # all occurances of a string. It ignores the cache # # tables along with the sessions and watchdog. # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access our DB # # passwd - The password needed # # DBName - The database we need a dump of # # findstr - The string you want to search for # ####################################################### "drupalfind" ) echo "Running drupalfind -- Searching for $findstr" echo "Output written to: $tfile3" mysql -h $host -u $user -p$passwd $DBName -Bs -e "show tables" > $tempfile rm -f ${DBName}.drupal.dump for t in `cat $tempfile`; do case $t in watchdog|sessions|cache|cache_[a-z]*) ;; * ) set +o errexit mysqldump --skip-extended-insert -h $host -u $user -p$passwd $DBName $t | grep "$findstr" > $tfile2 set -o errexit ;; esac if [ -s $tfile2 ]; then echo "=================" >> $tfile3 echo $t >> $tfile3 echo "=================" >> $tfile3 cat $tfile2 >> $tfile3 fi done cat $tfile3 ;; ####################################################### # Restore a .dump file that has been created by the # # 'dump' command defined above. # # behind any cache, session, or watchdog information. # # The purpose here is to keep the size of the backup # # WAY down.... # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access our 'New' DB # # passwd - The password needed for the 'New' DB # # DBName - The database we have a dump of # # DBNameNew - The database we are restoring to # ####################################################### "import" ) #Import from the .dump file into a database echo Importing into $DBNameNew mysql -h $host -u $user -p$passwd $DBNameNew < $DBName.dump ;; ####################################################### # This is a combination of the 'dump' command and the # # 'import' command. The is a small issue here in that # # the host, user, & password must be the same for # # both databases. Both Databases must ALREADY exist. # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access both DB's # # passwd - The password needed for both DB's # # DBName - The source database # # DBNameNew - The destination database # ####################################################### "copy" ) # Make a copy of a database into an existing one. echo "Clearing destination database of all tables" mysql -h $host -u $user -p$passwd $DBNameNew -Bs -e "show tables" > $tempfile for t in `cat $tempfile`; do set +o errexit mysql -h $host -u $user -p$passwd $DBNameNew -Bs -e "drop table $t" set -o errexit done echo "Dumpfile file to $tempfile" mysqldump -h $host -u $user -p$passwd $DBName > $tempfile echo "Importing $tempfile to $DBNameNew" mysql -h $host -u $user -p$passwd $DBNameNew < $tempfile echo "Done! $tempfile still available in case you screwed up!" ;; ####################################################### # This routine will make a backup of a database and # # then CREATE a NEW database to restore the backup # # to. Again, the hosts, user, & password must be the # # same for both databases. # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access both DB's # # passwd - The password needed for both DB's # # DBName - The source database # # DBNameNew - The destination database # ####################################################### "clone" ) # Make a clone of a database into a new one. echo "Dumpfile file to $tempfile" mysqldump -h $host -u $user -p$passwd $DBName > $tempfile echo "Creating the new database $DBNameNew" cat <<EOF > $tfile2 create database if not exists $DBNameNew; quit EOF mysql -h $host -u $user -p$passwd < $tfile2 rm -f $tfile2 echo "Importing $tempfile to $DBNameNew" mysql -h $host -u $user -p$passwd $DBNameNew < $tempfile echo "Done! $tempfile still available in case you screwed up!" ;; ####################################################### # This will allow for an arbitrary mysql command to # # run. It is run agains the database. If you want to # # string multiple command together, use ';' between # # each command. # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access both DB's # # passwd - The password needed for both DB's # # DBName - The source database # ####################################################### "run" ) # Run a quote enclosed script against a database cat <<EOF > $tempfile $script; quit EOF mysql -h $host -u $user -p$passwd $DBName <$tempfile ;; ####################################################### # This will allow for an arbitrary set of mysql # # commands to be run. Build a file with each command # # on a separate line. Terminate each line with ';' # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access both DB's # # passwd - The password needed for both DB's # # DBName - The source database # # filename - The name of the script file # ####################################################### "runfile" ) # Run a script file against a database echo Running script on $DBName mysql -h $host -u $user -p$passwd $DBName < $filename ;; ####################################################### # This provides you with Command Line Interface into # # mysql. # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access both DB's # # passwd - The password needed for both DB's # # DBName - The source database # ####################################################### "edit" ) # Go into raw mysql mode on a database # echo "Host: $host - User: $user - Password: $passwd - DB: $DBName" echo "SQL CLI on $host for User $user using Password $passwd in DB $DBName" mysql -h $host -u $user -p$passwd $DBName ;; ####################################################### # Export a table in the database in a CSV format. # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access both DB's # # passwd - The password needed for both DB's # # DBName - The source database # # table - The source tablename # # xport - The name of the output file in CSV format # ####################################################### "export" ) #Export into CSV format #SELECT * INTO OUTFILE '/somefile.csv' #FIELDS ESCAPED BY '\' #FIELDS OPTIONALLY ENCLOSED BY '"' #FIELDS TERMINATED BY ',' #LINES TERMINATED BY '\n' #FROM table WHERE column='value'"; echo Running CSV export on Database: $DBName and Table: $table cat <<EOF > $tfile2 SELECT * INTO OUTFILE '$xport' FIELDS ESCAPED BY '\' OPTIONALLY ENCLOSED BY '"' TERMINATED BY ',' LINES TERMINATED BY '\n' FROM $table"; quit EOF mysql -h $host -u $user -p$passwd $DBName <$tfile2 >$xport ;; ####################################################### # Provide a 'top' like statistics for your mysql # # server. # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access both DB's # # passwd - The password needed for both DB's # # # # You must have the mytop package installed for this # # to work. # ####################################################### "stats" ) set +o errexit which mytop > /dev/null 2>&1 rc=$? if [ $rc -eq 0 ]; then mytop -u $user -p $passwd -h $host -s 3 else echo -e $usage cat <<EOF $(tput setaf 1)ERROR:$(tput setaf 9) You have attempted run the statistics portion of this script. It is a requirement of this that you have available the 'mytop' package. To Install on various platforms =============================== GENTOO: emerge -avt mytop EOF fi set -o errexit ;; ####################################################### # Alters ALL admin password within all drupal DBs # # on a specified server. You must provide the old # # and new admin passwords. If the old password does # # not match what is currently in the database, it is # # assumed that the password is NOT TO BE CHANGED. # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access both DB's # # passwd - The password needed for both DB's # # DrupO - The current drupal admin (user 1) password # # DrupN - The new drupal admin (user 1) password # ####################################################### "alter" ) [ ${DrupO:=fred} = "fred" ] && echo "Error :: you must provide the old Drupal Admin password (-a)" && exit 1 [ ${DrupN:=fred} = "fred" ] && echo "Error :: you must provide the new Drupal Admin password (-b)" && exit 1 dblist=`mysql -h $host -u $user -p$passwd -Bs -e "select table_schema from tables where table_name = 'node'" information_schema` /bin/rm -f $tempfile for d in $dblist; do mysql -h $host -u $user -p$passwd -Bs -e "select \"$d\" from users where uid = 1 and pass = md5('$DrupO')" $d >> $tempfile done for d in `cat $tempfile`; do mysql -h $host -u $user -p$passwd -Bs -e "select \"$d - old:\", name, pass from users where uid = 1 and pass = md5('$DrupO')" $d mysql -h $host -u $user -p$passwd -Bs -e "update users set pass = md5('$DrupN') where uid = 1 and pass = md5('$DrupO')" $d mysql -h $host -u $user -p$passwd -Bs -e "select \"$d - new:\", name, pass from users where uid = 1 and pass = md5('$DrupN')" $d echo ----- done ;; ####################################################### # Well, you didn't chose anything, and no default was # # supplied, so here is the usage description # ####################################################### * ) # user error... show the usage page. echo -e $usage ;; esac
worxco/simplesql
b64468487338d4c8b18b26224f301bb2ce76dd12
Removed the 'tail' as the test is now complete
diff --git a/simplesql b/simplesql index f988d02..5da37b1 100755 --- a/simplesql +++ b/simplesql @@ -13,513 +13,512 @@ # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. set -o errexit set -o nounset # For this script to run properly, you must fill out all the required information. # If you are lazy like me, you can run a file named simplesql.conf to initialize # certain defaults and aliases. # # the format of this file should be as follows. #> #!/bin/bash #> #> # Setup Defaults #> #> i=0 #> # Set up in the hostA variable the always working address to the server, followed by any aliases you like. #> # all delimited by commas. #> hostA[$i]="sql01.domain.com,sql01" #> userA[$i]="root"; # Put the user for this server here #> passwdA[$i]="<password here>"; # Put the password for this server here (usually for root) #> DBNameA[$((i++))]="test"; # If you want a default database to end up in, this is the place. #> #> hostA[$i]="sql02.domain.com,sql02,x9sql02" #> userA[$i]="root" #> passwdA[$i]="<password here>" #> DBNameA[$((i++))]="test" #> #> tempfile=`tempfile` #> tfile2=`tempfile` #> #> mode="edit" #> host="sql01.doamain.com" #> passwd="" #> user="root" #> DBName="" [ -f /etc/simplesql.conf ] && source ~/etc/simplesql.conf [ -f ~/bin/simplesql.conf ] && source ~/bin/simplesql.conf [ -f simplesql.conf ] && source simplesql.conf tempfile=`tempfile` tfile2=`tempfile` tfile3=`tempfile` ########################################################## # Create the Usage variable to display if they need help # ########################################################## usage=`cat <<EOF simplesql Copyright (C) 2007-2010 Meridian Data Systems, Inc.\n This program comes with ABSOLUTELY NO WARRANTY; for details read the source.\n This is free software, and you are welcome to redistribute it\n under certain conditions; See the included license.\n\n Usage:\n\n $0 [ -h ] [ -d <database> ] [ -f <filename> ] [ -m <mode> ] [ -n <new database> ] [ -p <password> ] [ -s <quoted script> ] [ -u <user> ]\n\n $(tput setaf 5)-h:$(tput setaf 9) Provide this usage page.\n\n $(tput setaf 5)-a <current Drupal admin password>:$(tput setaf 9) This is the current Drupal admin password. If this doesn't match, we don't run\n\n $(tput setaf 5)-b <new Drupal admin password>:$(tput setaf 9) This is the new, replacement Drupal admin password. see -a for trigger\n\n $(tput setaf 5)-d <database>:$(tput setaf 9) Enter the name of the database that you are operating against.\n\n $(tput setaf 5)-f <filename>:$(tput setaf 9) This is a script file with multiple semi-colon terminated mysql commands.\n\n $(tput setaf 5)-i <findstr>:$(tput setaf 9) This is a string that you wish to search for.\n\n $(tput setaf 5)-m <mode>:$(tput setaf 9) This defines the different modes that this script can operate in.\n \tdump - Dump the named database to a file with the name of the database.dump.\n \timport - Run the database.dump file created by the dump command above. This is a restore and not a merge.\n \tdumpdrupal - Dump the named database to a file with the name of the database.drupal.dump.\n \t\tThe purpose of this variant is to only get the structure for cache, session, & watchdog tables.\n \t\tAlong with all the data from the rest of the tables.\n \tdrupalfind - Search a given Drupal database for all occurances of a string.\n \tcopy - Copy a database into another existing database name.\n \t\tThis will NOT recreate the new database. It will clear\n \t\tany existing tables. It will add any new tables.\n \tclone - Copy a database into a new database.\n \trun - run the script provided on the command line by -s <quoted script>.\n \trunfile - run the script command(s) provided in the file named by -f <filename>.\n \texport - create a CSV file output from the dabase.\n \tedit - Go into command line mode of mysql.\n \tshow - Show a list of tables for the database.\n \tstats - launch mytop if it is available\n\n \talter - Alter ALL Drupal admin passwords $(tput setaf 5)-n <new database>:$(tput setaf 9) The name of the new database for copy or clone.\n\n $(tput setaf 5)-o <host>:$(tput setaf 9) The host server where the database exists.\n\n $(tput setaf 5)-p <password>:$(tput setaf 9) The password needed by the user (-u) to access the database.\n\n $(tput setaf 5)-s <quoted script>:$(tput setaf 9) This is a quoted string that is a mysql command script.\n\n $(tput setaf 5)-t <table name>:$(tput setaf 9) This is the table that you want to export.\n\n $(tput setaf 5)-u <user>:$(tput setaf 9) The username that has access to the database.\n\n $(tput setaf 5)-x <CSV export file>:$(tput setaf 9) The output filename you want your CSV export to end up in.\n\n EOF` ################################################ # Accept and parse all the incoming parameters # ################################################ while getopts ":hm:a:b:d:n:o:p:s:t:u:f:i:x:" options ; do case $options in m ) mode=$OPTARG;; a ) DrupO=$OPTARG;; b ) DrupN=$OPTARG;; d ) DBName=$OPTARG;; n ) DBNameNew=$OPTARG;; o ) host=$OPTARG;; p ) passwd=$OPTARG;; s ) script=$OPTARG;; t ) table=$OPTARG;; u ) user=$OPTARG;; f ) filename=$OPTARG;; x ) xport=$OPTARG;; i ) findstr=$OPTARG;; h ) mode="help";; esac done ############################################### # Based on the 'host' variable, check aliases # # and select the host. If the passwd, user, # # or DBName variables were not passed in, # # then set them to known defaults. # ############################################### for (( i=0; i<$((${#hostA[@]})); i=i+1 )); do # echo ${alias[i]} # echo -n "$a :: " set -- `echo ${hostA[i]} | tr , \ ` temp=$1 while [ ${#1} -gt 0 ]; do if [ $1 == $host ]; then host=$temp if [[ ! $passwd ]];then passwd=${passwdA[i]} fi if [[ ! $user ]];then user=${userA[i]} fi if [[ ! $DBName ]];then DBName=${DBNameA[i]} fi fi shift done done ################################################ # Based on the mode given, execute the command # ################################################ case $mode in ######################################################## # Do a mysqldump of a specific database # # Normally, if I do the dump, it is because # # I want to look at it. So, the --skip-extended-insert # # option so I can actually read the records # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access our DB # # passwd - The password needed # # DBName - The database we need a dump of # ######################################################## "dump" ) # Dump a copy of the database into $DBName.dump echo "mysqldump --skip-extended-insert -h $host -u $user -p$passwd $DBName > $DBName.dump" mysqldump --skip-extended-insert -h $host -u $user -p$passwd $DBName > $DBName.dump ;; ######################################################## # Do a mysqldump of a specific database just for the # # structure. # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access our DB # # passwd - The password needed # # DBName - The database we need a dump of # ######################################################## "dumpmeta" ) # Dump a copy of the metadata about the database into $DBName.meta echo "mysqldump --no-data -h $host -u $user -p$passwd $DBName > $DBName.meta" mysqldump --no-data -h $host -u $user -p$passwd $DBName > $DBName.meta ;; ################################################ # Show a list of a the tables in the Database # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access our DB # # passwd - The password needed # # DBName - The database we need a dump of # ################################################ "show" ) # Show a list of tables in the $DBName database mysqlshow -h $host -u $user -p$passwd $DBName ;; ####################################################### # Do a Drupal Dump... This is for a Drupal database # # It is meant to dump all the data, but to leave # # behind any cache, session, or watchdog information. # # The purpose here is to keep the size of the backup # # WAY down.... # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access our DB # # passwd - The password needed # # DBName - The database we need a dump of # ####################################################### "dumpdrupal" ) mysql -h $host -u $user -p$passwd $DBName -Bs -e "show tables" > $tempfile rm -f ${DBName}.drupal.dump for t in `cat $tempfile`; do case $t in watchdog|sessions|cache|cache_[a-z]*) mysqldump --no-data -h $host -u $user -p$passwd $DBName $t >> ${DBName}.drupal.dump ;; * ) mysqldump --skip-extended-insert -h $host -u $user -p$passwd $DBName $t >> ${DBName}.drupal.dump ;; esac done ;; ####################################################### # Do a Drupal Find... This is for a Drupal database # # It is meant to search through all the tables to # # all occurances of a string. It ignores the cache # # tables along with the sessions and watchdog. # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access our DB # # passwd - The password needed # # DBName - The database we need a dump of # # findstr - The string you want to search for # ####################################################### "drupalfind" ) echo "Running drupalfind -- Searching for $findstr" echo "Output written to: $tfile3" mysql -h $host -u $user -p$passwd $DBName -Bs -e "show tables" > $tempfile rm -f ${DBName}.drupal.dump for t in `cat $tempfile`; do case $t in watchdog|sessions|cache|cache_[a-z]*) ;; * ) set +o errexit mysqldump --skip-extended-insert -h $host -u $user -p$passwd $DBName $t | grep "$findstr" > $tfile2 set -o errexit ;; esac if [ -s $tfile2 ]; then echo "=================" >> $tfile3 echo $t >> $tfile3 echo "=================" >> $tfile3 cat $tfile2 >> $tfile3 fi done cat $tfile3 ;; ####################################################### # Restore a .dump file that has been created by the # # 'dump' command defined above. # # behind any cache, session, or watchdog information. # # The purpose here is to keep the size of the backup # # WAY down.... # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access our 'New' DB # # passwd - The password needed for the 'New' DB # # DBName - The database we have a dump of # # DBNameNew - The database we are restoring to # ####################################################### "import" ) #Import from the .dump file into a database echo Importing into $DBNameNew mysql -h $host -u $user -p$passwd $DBNameNew < $DBName.dump ;; ####################################################### # This is a combination of the 'dump' command and the # # 'import' command. The is a small issue here in that # # the host, user, & password must be the same for # # both databases. Both Databases must ALREADY exist. # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access both DB's # # passwd - The password needed for both DB's # # DBName - The source database # # DBNameNew - The destination database # ####################################################### "copy" ) # Make a copy of a database into an existing one. echo "Clearing destination database of all tables" mysql -h $host -u $user -p$passwd $DBNameNew -Bs -e "show tables" > $tempfile for t in `cat $tempfile`; do set +o errexit mysql -h $host -u $user -p$passwd $DBNameNew -Bs -e "drop table $t" set -o errexit done echo "Dumpfile file to $tempfile" mysqldump -h $host -u $user -p$passwd $DBName > $tempfile echo "Importing $tempfile to $DBNameNew" mysql -h $host -u $user -p$passwd $DBNameNew < $tempfile echo "Done! $tempfile still available in case you screwed up!" ;; ####################################################### # This routine will make a backup of a database and # # then CREATE a NEW database to restore the backup # # to. Again, the hosts, user, & password must be the # # same for both databases. # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access both DB's # # passwd - The password needed for both DB's # # DBName - The source database # # DBNameNew - The destination database # ####################################################### "clone" ) # Make a clone of a database into a new one. echo "Dumpfile file to $tempfile" mysqldump -h $host -u $user -p$passwd $DBName > $tempfile echo "Creating the new database $DBNameNew" cat <<EOF > $tfile2 create database if not exists $DBNameNew; quit EOF mysql -h $host -u $user -p$passwd < $tfile2 rm -f $tfile2 echo "Importing $tempfile to $DBNameNew" mysql -h $host -u $user -p$passwd $DBNameNew < $tempfile echo "Done! $tempfile still available in case you screwed up!" ;; ####################################################### # This will allow for an arbitrary mysql command to # # run. It is run agains the database. If you want to # # string multiple command together, use ';' between # # each command. # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access both DB's # # passwd - The password needed for both DB's # # DBName - The source database # ####################################################### "run" ) # Run a quote enclosed script against a database cat <<EOF > $tempfile $script; quit EOF mysql -h $host -u $user -p$passwd $DBName <$tempfile ;; ####################################################### # This will allow for an arbitrary set of mysql # # commands to be run. Build a file with each command # # on a separate line. Terminate each line with ';' # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access both DB's # # passwd - The password needed for both DB's # # DBName - The source database # # filename - The name of the script file # ####################################################### "runfile" ) # Run a script file against a database echo Running script on $DBName mysql -h $host -u $user -p$passwd $DBName < $filename ;; ####################################################### # This provides you with Command Line Interface into # # mysql. # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access both DB's # # passwd - The password needed for both DB's # # DBName - The source database # ####################################################### "edit" ) # Go into raw mysql mode on a database # echo "Host: $host - User: $user - Password: $passwd - DB: $DBName" echo "SQL CLI on $host for User $user using Password $passwd in DB $DBName" mysql -h $host -u $user -p$passwd $DBName ;; ####################################################### # Export a table in the database in a CSV format. # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access both DB's # # passwd - The password needed for both DB's # # DBName - The source database # # table - The source tablename # # xport - The name of the output file in CSV format # ####################################################### "export" ) #Export into CSV format #SELECT * INTO OUTFILE '/somefile.csv' #FIELDS ESCAPED BY '\' #FIELDS OPTIONALLY ENCLOSED BY '"' #FIELDS TERMINATED BY ',' #LINES TERMINATED BY '\n' #FROM table WHERE column='value'"; echo Running CSV export on Database: $DBName and Table: $table cat <<EOF > $tfile2 SELECT * INTO OUTFILE '$xport' FIELDS ESCAPED BY '\' OPTIONALLY ENCLOSED BY '"' TERMINATED BY ',' LINES TERMINATED BY '\n' FROM $table"; quit EOF mysql -h $host -u $user -p$passwd $DBName <$tfile2 >$xport ;; ####################################################### # Provide a 'top' like statistics for your mysql # # server. # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access both DB's # # passwd - The password needed for both DB's # # # # You must have the mytop package installed for this # # to work. # ####################################################### "stats" ) set +o errexit which mytop > /dev/null 2>&1 rc=$? if [ $rc -eq 0 ]; then mytop -u $user -p $passwd -h $host -s 3 else echo -e $usage cat <<EOF $(tput setaf 1)ERROR:$(tput setaf 9) You have attempted run the statistics portion of this script. It is a requirement of this that you have available the 'mytop' package. To Install on various platforms =============================== GENTOO: emerge -avt mytop EOF fi set -o errexit ;; ####################################################### # Alters ALL admin password within all drupal DBs # # on a specified server. You must provide the old # # and new admin passwords. If the old password does # # not match what is currently in the database, it is # # assumed that the password is NOT TO BE CHANGED. # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access both DB's # # passwd - The password needed for both DB's # # DrupO - The current drupal admin (user 1) password # # DrupN - The new drupal admin (user 1) password # ####################################################### "alter" ) [ ${DrupO:=fred} = "fred" ] && echo "Error :: you must provide the old Drupal Admin password (-a)" && exit 1 [ ${DrupN:=fred} = "fred" ] && echo "Error :: you must provide the new Drupal Admin password (-b)" && exit 1 dblist=`mysql -h $host -u $user -p$passwd -Bs -e "select table_schema from tables where table_name = 'node'" information_schema` /bin/rm -f $tempfile for d in $dblist; do mysql -h $host -u $user -p$passwd -Bs -e "select \"$d\" from users where uid = 1 and pass = md5('$DrupO')" $d >> $tempfile done for d in `cat $tempfile`; do mysql -h $host -u $user -p$passwd -Bs -e "select \"$d - old:\", name, pass from users where uid = 1 and pass = md5('$DrupO')" $d mysql -h $host -u $user -p$passwd -Bs -e "update users set pass = md5('$DrupN') where uid = 1 and pass = md5('$DrupO')" $d mysql -h $host -u $user -p$passwd -Bs -e "select \"$d - new:\", name, pass from users where uid = 1 and pass = md5('$DrupN')" $d echo ----- done ;; ####################################################### # Well, you didn't chose anything, and no default was # # supplied, so here is the usage description # ####################################################### * ) # user error... show the usage page. echo -e $usage ;; esac -# Just a tail for testing
worxco/simplesql
5dd17c58866e61f733a9006e0115c02ea3c56dbb
Added a tail for testing
diff --git a/simplesql b/simplesql index 5da37b1..f988d02 100755 --- a/simplesql +++ b/simplesql @@ -13,512 +13,513 @@ # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. set -o errexit set -o nounset # For this script to run properly, you must fill out all the required information. # If you are lazy like me, you can run a file named simplesql.conf to initialize # certain defaults and aliases. # # the format of this file should be as follows. #> #!/bin/bash #> #> # Setup Defaults #> #> i=0 #> # Set up in the hostA variable the always working address to the server, followed by any aliases you like. #> # all delimited by commas. #> hostA[$i]="sql01.domain.com,sql01" #> userA[$i]="root"; # Put the user for this server here #> passwdA[$i]="<password here>"; # Put the password for this server here (usually for root) #> DBNameA[$((i++))]="test"; # If you want a default database to end up in, this is the place. #> #> hostA[$i]="sql02.domain.com,sql02,x9sql02" #> userA[$i]="root" #> passwdA[$i]="<password here>" #> DBNameA[$((i++))]="test" #> #> tempfile=`tempfile` #> tfile2=`tempfile` #> #> mode="edit" #> host="sql01.doamain.com" #> passwd="" #> user="root" #> DBName="" [ -f /etc/simplesql.conf ] && source ~/etc/simplesql.conf [ -f ~/bin/simplesql.conf ] && source ~/bin/simplesql.conf [ -f simplesql.conf ] && source simplesql.conf tempfile=`tempfile` tfile2=`tempfile` tfile3=`tempfile` ########################################################## # Create the Usage variable to display if they need help # ########################################################## usage=`cat <<EOF simplesql Copyright (C) 2007-2010 Meridian Data Systems, Inc.\n This program comes with ABSOLUTELY NO WARRANTY; for details read the source.\n This is free software, and you are welcome to redistribute it\n under certain conditions; See the included license.\n\n Usage:\n\n $0 [ -h ] [ -d <database> ] [ -f <filename> ] [ -m <mode> ] [ -n <new database> ] [ -p <password> ] [ -s <quoted script> ] [ -u <user> ]\n\n $(tput setaf 5)-h:$(tput setaf 9) Provide this usage page.\n\n $(tput setaf 5)-a <current Drupal admin password>:$(tput setaf 9) This is the current Drupal admin password. If this doesn't match, we don't run\n\n $(tput setaf 5)-b <new Drupal admin password>:$(tput setaf 9) This is the new, replacement Drupal admin password. see -a for trigger\n\n $(tput setaf 5)-d <database>:$(tput setaf 9) Enter the name of the database that you are operating against.\n\n $(tput setaf 5)-f <filename>:$(tput setaf 9) This is a script file with multiple semi-colon terminated mysql commands.\n\n $(tput setaf 5)-i <findstr>:$(tput setaf 9) This is a string that you wish to search for.\n\n $(tput setaf 5)-m <mode>:$(tput setaf 9) This defines the different modes that this script can operate in.\n \tdump - Dump the named database to a file with the name of the database.dump.\n \timport - Run the database.dump file created by the dump command above. This is a restore and not a merge.\n \tdumpdrupal - Dump the named database to a file with the name of the database.drupal.dump.\n \t\tThe purpose of this variant is to only get the structure for cache, session, & watchdog tables.\n \t\tAlong with all the data from the rest of the tables.\n \tdrupalfind - Search a given Drupal database for all occurances of a string.\n \tcopy - Copy a database into another existing database name.\n \t\tThis will NOT recreate the new database. It will clear\n \t\tany existing tables. It will add any new tables.\n \tclone - Copy a database into a new database.\n \trun - run the script provided on the command line by -s <quoted script>.\n \trunfile - run the script command(s) provided in the file named by -f <filename>.\n \texport - create a CSV file output from the dabase.\n \tedit - Go into command line mode of mysql.\n \tshow - Show a list of tables for the database.\n \tstats - launch mytop if it is available\n\n \talter - Alter ALL Drupal admin passwords $(tput setaf 5)-n <new database>:$(tput setaf 9) The name of the new database for copy or clone.\n\n $(tput setaf 5)-o <host>:$(tput setaf 9) The host server where the database exists.\n\n $(tput setaf 5)-p <password>:$(tput setaf 9) The password needed by the user (-u) to access the database.\n\n $(tput setaf 5)-s <quoted script>:$(tput setaf 9) This is a quoted string that is a mysql command script.\n\n $(tput setaf 5)-t <table name>:$(tput setaf 9) This is the table that you want to export.\n\n $(tput setaf 5)-u <user>:$(tput setaf 9) The username that has access to the database.\n\n $(tput setaf 5)-x <CSV export file>:$(tput setaf 9) The output filename you want your CSV export to end up in.\n\n EOF` ################################################ # Accept and parse all the incoming parameters # ################################################ while getopts ":hm:a:b:d:n:o:p:s:t:u:f:i:x:" options ; do case $options in m ) mode=$OPTARG;; a ) DrupO=$OPTARG;; b ) DrupN=$OPTARG;; d ) DBName=$OPTARG;; n ) DBNameNew=$OPTARG;; o ) host=$OPTARG;; p ) passwd=$OPTARG;; s ) script=$OPTARG;; t ) table=$OPTARG;; u ) user=$OPTARG;; f ) filename=$OPTARG;; x ) xport=$OPTARG;; i ) findstr=$OPTARG;; h ) mode="help";; esac done ############################################### # Based on the 'host' variable, check aliases # # and select the host. If the passwd, user, # # or DBName variables were not passed in, # # then set them to known defaults. # ############################################### for (( i=0; i<$((${#hostA[@]})); i=i+1 )); do # echo ${alias[i]} # echo -n "$a :: " set -- `echo ${hostA[i]} | tr , \ ` temp=$1 while [ ${#1} -gt 0 ]; do if [ $1 == $host ]; then host=$temp if [[ ! $passwd ]];then passwd=${passwdA[i]} fi if [[ ! $user ]];then user=${userA[i]} fi if [[ ! $DBName ]];then DBName=${DBNameA[i]} fi fi shift done done ################################################ # Based on the mode given, execute the command # ################################################ case $mode in ######################################################## # Do a mysqldump of a specific database # # Normally, if I do the dump, it is because # # I want to look at it. So, the --skip-extended-insert # # option so I can actually read the records # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access our DB # # passwd - The password needed # # DBName - The database we need a dump of # ######################################################## "dump" ) # Dump a copy of the database into $DBName.dump echo "mysqldump --skip-extended-insert -h $host -u $user -p$passwd $DBName > $DBName.dump" mysqldump --skip-extended-insert -h $host -u $user -p$passwd $DBName > $DBName.dump ;; ######################################################## # Do a mysqldump of a specific database just for the # # structure. # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access our DB # # passwd - The password needed # # DBName - The database we need a dump of # ######################################################## "dumpmeta" ) # Dump a copy of the metadata about the database into $DBName.meta echo "mysqldump --no-data -h $host -u $user -p$passwd $DBName > $DBName.meta" mysqldump --no-data -h $host -u $user -p$passwd $DBName > $DBName.meta ;; ################################################ # Show a list of a the tables in the Database # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access our DB # # passwd - The password needed # # DBName - The database we need a dump of # ################################################ "show" ) # Show a list of tables in the $DBName database mysqlshow -h $host -u $user -p$passwd $DBName ;; ####################################################### # Do a Drupal Dump... This is for a Drupal database # # It is meant to dump all the data, but to leave # # behind any cache, session, or watchdog information. # # The purpose here is to keep the size of the backup # # WAY down.... # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access our DB # # passwd - The password needed # # DBName - The database we need a dump of # ####################################################### "dumpdrupal" ) mysql -h $host -u $user -p$passwd $DBName -Bs -e "show tables" > $tempfile rm -f ${DBName}.drupal.dump for t in `cat $tempfile`; do case $t in watchdog|sessions|cache|cache_[a-z]*) mysqldump --no-data -h $host -u $user -p$passwd $DBName $t >> ${DBName}.drupal.dump ;; * ) mysqldump --skip-extended-insert -h $host -u $user -p$passwd $DBName $t >> ${DBName}.drupal.dump ;; esac done ;; ####################################################### # Do a Drupal Find... This is for a Drupal database # # It is meant to search through all the tables to # # all occurances of a string. It ignores the cache # # tables along with the sessions and watchdog. # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access our DB # # passwd - The password needed # # DBName - The database we need a dump of # # findstr - The string you want to search for # ####################################################### "drupalfind" ) echo "Running drupalfind -- Searching for $findstr" echo "Output written to: $tfile3" mysql -h $host -u $user -p$passwd $DBName -Bs -e "show tables" > $tempfile rm -f ${DBName}.drupal.dump for t in `cat $tempfile`; do case $t in watchdog|sessions|cache|cache_[a-z]*) ;; * ) set +o errexit mysqldump --skip-extended-insert -h $host -u $user -p$passwd $DBName $t | grep "$findstr" > $tfile2 set -o errexit ;; esac if [ -s $tfile2 ]; then echo "=================" >> $tfile3 echo $t >> $tfile3 echo "=================" >> $tfile3 cat $tfile2 >> $tfile3 fi done cat $tfile3 ;; ####################################################### # Restore a .dump file that has been created by the # # 'dump' command defined above. # # behind any cache, session, or watchdog information. # # The purpose here is to keep the size of the backup # # WAY down.... # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access our 'New' DB # # passwd - The password needed for the 'New' DB # # DBName - The database we have a dump of # # DBNameNew - The database we are restoring to # ####################################################### "import" ) #Import from the .dump file into a database echo Importing into $DBNameNew mysql -h $host -u $user -p$passwd $DBNameNew < $DBName.dump ;; ####################################################### # This is a combination of the 'dump' command and the # # 'import' command. The is a small issue here in that # # the host, user, & password must be the same for # # both databases. Both Databases must ALREADY exist. # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access both DB's # # passwd - The password needed for both DB's # # DBName - The source database # # DBNameNew - The destination database # ####################################################### "copy" ) # Make a copy of a database into an existing one. echo "Clearing destination database of all tables" mysql -h $host -u $user -p$passwd $DBNameNew -Bs -e "show tables" > $tempfile for t in `cat $tempfile`; do set +o errexit mysql -h $host -u $user -p$passwd $DBNameNew -Bs -e "drop table $t" set -o errexit done echo "Dumpfile file to $tempfile" mysqldump -h $host -u $user -p$passwd $DBName > $tempfile echo "Importing $tempfile to $DBNameNew" mysql -h $host -u $user -p$passwd $DBNameNew < $tempfile echo "Done! $tempfile still available in case you screwed up!" ;; ####################################################### # This routine will make a backup of a database and # # then CREATE a NEW database to restore the backup # # to. Again, the hosts, user, & password must be the # # same for both databases. # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access both DB's # # passwd - The password needed for both DB's # # DBName - The source database # # DBNameNew - The destination database # ####################################################### "clone" ) # Make a clone of a database into a new one. echo "Dumpfile file to $tempfile" mysqldump -h $host -u $user -p$passwd $DBName > $tempfile echo "Creating the new database $DBNameNew" cat <<EOF > $tfile2 create database if not exists $DBNameNew; quit EOF mysql -h $host -u $user -p$passwd < $tfile2 rm -f $tfile2 echo "Importing $tempfile to $DBNameNew" mysql -h $host -u $user -p$passwd $DBNameNew < $tempfile echo "Done! $tempfile still available in case you screwed up!" ;; ####################################################### # This will allow for an arbitrary mysql command to # # run. It is run agains the database. If you want to # # string multiple command together, use ';' between # # each command. # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access both DB's # # passwd - The password needed for both DB's # # DBName - The source database # ####################################################### "run" ) # Run a quote enclosed script against a database cat <<EOF > $tempfile $script; quit EOF mysql -h $host -u $user -p$passwd $DBName <$tempfile ;; ####################################################### # This will allow for an arbitrary set of mysql # # commands to be run. Build a file with each command # # on a separate line. Terminate each line with ';' # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access both DB's # # passwd - The password needed for both DB's # # DBName - The source database # # filename - The name of the script file # ####################################################### "runfile" ) # Run a script file against a database echo Running script on $DBName mysql -h $host -u $user -p$passwd $DBName < $filename ;; ####################################################### # This provides you with Command Line Interface into # # mysql. # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access both DB's # # passwd - The password needed for both DB's # # DBName - The source database # ####################################################### "edit" ) # Go into raw mysql mode on a database # echo "Host: $host - User: $user - Password: $passwd - DB: $DBName" echo "SQL CLI on $host for User $user using Password $passwd in DB $DBName" mysql -h $host -u $user -p$passwd $DBName ;; ####################################################### # Export a table in the database in a CSV format. # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access both DB's # # passwd - The password needed for both DB's # # DBName - The source database # # table - The source tablename # # xport - The name of the output file in CSV format # ####################################################### "export" ) #Export into CSV format #SELECT * INTO OUTFILE '/somefile.csv' #FIELDS ESCAPED BY '\' #FIELDS OPTIONALLY ENCLOSED BY '"' #FIELDS TERMINATED BY ',' #LINES TERMINATED BY '\n' #FROM table WHERE column='value'"; echo Running CSV export on Database: $DBName and Table: $table cat <<EOF > $tfile2 SELECT * INTO OUTFILE '$xport' FIELDS ESCAPED BY '\' OPTIONALLY ENCLOSED BY '"' TERMINATED BY ',' LINES TERMINATED BY '\n' FROM $table"; quit EOF mysql -h $host -u $user -p$passwd $DBName <$tfile2 >$xport ;; ####################################################### # Provide a 'top' like statistics for your mysql # # server. # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access both DB's # # passwd - The password needed for both DB's # # # # You must have the mytop package installed for this # # to work. # ####################################################### "stats" ) set +o errexit which mytop > /dev/null 2>&1 rc=$? if [ $rc -eq 0 ]; then mytop -u $user -p $passwd -h $host -s 3 else echo -e $usage cat <<EOF $(tput setaf 1)ERROR:$(tput setaf 9) You have attempted run the statistics portion of this script. It is a requirement of this that you have available the 'mytop' package. To Install on various platforms =============================== GENTOO: emerge -avt mytop EOF fi set -o errexit ;; ####################################################### # Alters ALL admin password within all drupal DBs # # on a specified server. You must provide the old # # and new admin passwords. If the old password does # # not match what is currently in the database, it is # # assumed that the password is NOT TO BE CHANGED. # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access both DB's # # passwd - The password needed for both DB's # # DrupO - The current drupal admin (user 1) password # # DrupN - The new drupal admin (user 1) password # ####################################################### "alter" ) [ ${DrupO:=fred} = "fred" ] && echo "Error :: you must provide the old Drupal Admin password (-a)" && exit 1 [ ${DrupN:=fred} = "fred" ] && echo "Error :: you must provide the new Drupal Admin password (-b)" && exit 1 dblist=`mysql -h $host -u $user -p$passwd -Bs -e "select table_schema from tables where table_name = 'node'" information_schema` /bin/rm -f $tempfile for d in $dblist; do mysql -h $host -u $user -p$passwd -Bs -e "select \"$d\" from users where uid = 1 and pass = md5('$DrupO')" $d >> $tempfile done for d in `cat $tempfile`; do mysql -h $host -u $user -p$passwd -Bs -e "select \"$d - old:\", name, pass from users where uid = 1 and pass = md5('$DrupO')" $d mysql -h $host -u $user -p$passwd -Bs -e "update users set pass = md5('$DrupN') where uid = 1 and pass = md5('$DrupO')" $d mysql -h $host -u $user -p$passwd -Bs -e "select \"$d - new:\", name, pass from users where uid = 1 and pass = md5('$DrupN')" $d echo ----- done ;; ####################################################### # Well, you didn't chose anything, and no default was # # supplied, so here is the usage description # ####################################################### * ) # user error... show the usage page. echo -e $usage ;; esac +# Just a tail for testing
worxco/simplesql
dbe40d40e4869ca98a60629a2ca543a578a68a97
Fixed up the alignment on the comments
diff --git a/simplesql b/simplesql index f0aeb7d..5da37b1 100755 --- a/simplesql +++ b/simplesql @@ -1,517 +1,524 @@ #!/bin/bash # Program: simpelsql # Description: This is an aggregation of mysql based commands. Most often used when working with the Drupal Database. # Author: Kurt L Vanderwater # Copyright (C) 2007-2010 Meridian Data Systems, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. set -o errexit set -o nounset # For this script to run properly, you must fill out all the required information. # If you are lazy like me, you can run a file named simplesql.conf to initialize # certain defaults and aliases. # # the format of this file should be as follows. #> #!/bin/bash #> #> # Setup Defaults #> #> i=0 #> # Set up in the hostA variable the always working address to the server, followed by any aliases you like. #> # all delimited by commas. #> hostA[$i]="sql01.domain.com,sql01" #> userA[$i]="root"; # Put the user for this server here #> passwdA[$i]="<password here>"; # Put the password for this server here (usually for root) #> DBNameA[$((i++))]="test"; # If you want a default database to end up in, this is the place. #> #> hostA[$i]="sql02.domain.com,sql02,x9sql02" #> userA[$i]="root" #> passwdA[$i]="<password here>" #> DBNameA[$((i++))]="test" #> #> tempfile=`tempfile` #> tfile2=`tempfile` #> #> mode="edit" #> host="sql01.doamain.com" #> passwd="" #> user="root" #> DBName="" [ -f /etc/simplesql.conf ] && source ~/etc/simplesql.conf [ -f ~/bin/simplesql.conf ] && source ~/bin/simplesql.conf [ -f simplesql.conf ] && source simplesql.conf tempfile=`tempfile` tfile2=`tempfile` tfile3=`tempfile` ########################################################## # Create the Usage variable to display if they need help # ########################################################## usage=`cat <<EOF simplesql Copyright (C) 2007-2010 Meridian Data Systems, Inc.\n This program comes with ABSOLUTELY NO WARRANTY; for details read the source.\n This is free software, and you are welcome to redistribute it\n under certain conditions; See the included license.\n\n Usage:\n\n $0 [ -h ] [ -d <database> ] [ -f <filename> ] [ -m <mode> ] [ -n <new database> ] [ -p <password> ] [ -s <quoted script> ] [ -u <user> ]\n\n $(tput setaf 5)-h:$(tput setaf 9) Provide this usage page.\n\n $(tput setaf 5)-a <current Drupal admin password>:$(tput setaf 9) This is the current Drupal admin password. If this doesn't match, we don't run\n\n $(tput setaf 5)-b <new Drupal admin password>:$(tput setaf 9) This is the new, replacement Drupal admin password. see -a for trigger\n\n $(tput setaf 5)-d <database>:$(tput setaf 9) Enter the name of the database that you are operating against.\n\n $(tput setaf 5)-f <filename>:$(tput setaf 9) This is a script file with multiple semi-colon terminated mysql commands.\n\n $(tput setaf 5)-i <findstr>:$(tput setaf 9) This is a string that you wish to search for.\n\n $(tput setaf 5)-m <mode>:$(tput setaf 9) This defines the different modes that this script can operate in.\n \tdump - Dump the named database to a file with the name of the database.dump.\n \timport - Run the database.dump file created by the dump command above. This is a restore and not a merge.\n \tdumpdrupal - Dump the named database to a file with the name of the database.drupal.dump.\n \t\tThe purpose of this variant is to only get the structure for cache, session, & watchdog tables.\n \t\tAlong with all the data from the rest of the tables.\n \tdrupalfind - Search a given Drupal database for all occurances of a string.\n \tcopy - Copy a database into another existing database name.\n \t\tThis will NOT recreate the new database. It will clear\n \t\tany existing tables. It will add any new tables.\n \tclone - Copy a database into a new database.\n \trun - run the script provided on the command line by -s <quoted script>.\n \trunfile - run the script command(s) provided in the file named by -f <filename>.\n \texport - create a CSV file output from the dabase.\n \tedit - Go into command line mode of mysql.\n \tshow - Show a list of tables for the database.\n \tstats - launch mytop if it is available\n\n \talter - Alter ALL Drupal admin passwords $(tput setaf 5)-n <new database>:$(tput setaf 9) The name of the new database for copy or clone.\n\n $(tput setaf 5)-o <host>:$(tput setaf 9) The host server where the database exists.\n\n $(tput setaf 5)-p <password>:$(tput setaf 9) The password needed by the user (-u) to access the database.\n\n $(tput setaf 5)-s <quoted script>:$(tput setaf 9) This is a quoted string that is a mysql command script.\n\n $(tput setaf 5)-t <table name>:$(tput setaf 9) This is the table that you want to export.\n\n $(tput setaf 5)-u <user>:$(tput setaf 9) The username that has access to the database.\n\n $(tput setaf 5)-x <CSV export file>:$(tput setaf 9) The output filename you want your CSV export to end up in.\n\n EOF` ################################################ # Accept and parse all the incoming parameters # ################################################ while getopts ":hm:a:b:d:n:o:p:s:t:u:f:i:x:" options ; do case $options in m ) mode=$OPTARG;; a ) DrupO=$OPTARG;; b ) DrupN=$OPTARG;; d ) DBName=$OPTARG;; n ) DBNameNew=$OPTARG;; o ) host=$OPTARG;; p ) passwd=$OPTARG;; s ) script=$OPTARG;; t ) table=$OPTARG;; u ) user=$OPTARG;; f ) filename=$OPTARG;; x ) xport=$OPTARG;; i ) findstr=$OPTARG;; h ) mode="help";; esac done ############################################### # Based on the 'host' variable, check aliases # # and select the host. If the passwd, user, # # or DBName variables were not passed in, # # then set them to known defaults. # ############################################### for (( i=0; i<$((${#hostA[@]})); i=i+1 )); do # echo ${alias[i]} # echo -n "$a :: " set -- `echo ${hostA[i]} | tr , \ ` temp=$1 while [ ${#1} -gt 0 ]; do if [ $1 == $host ]; then host=$temp if [[ ! $passwd ]];then passwd=${passwdA[i]} fi if [[ ! $user ]];then user=${userA[i]} fi if [[ ! $DBName ]];then DBName=${DBNameA[i]} fi fi shift done done ################################################ # Based on the mode given, execute the command # ################################################ case $mode in ######################################################## # Do a mysqldump of a specific database # # Normally, if I do the dump, it is because # # I want to look at it. So, the --skip-extended-insert # # option so I can actually read the records # # # # Required parameters: # - # host - what server are we on? # - # user - what user do we use to access our DB # - # passwd - The password needed # - # DBName - The database we need a dump of # + # host - what server are we on? # + # user - what user do we use to access our DB # + # passwd - The password needed # + # DBName - The database we need a dump of # ######################################################## "dump" ) # Dump a copy of the database into $DBName.dump echo "mysqldump --skip-extended-insert -h $host -u $user -p$passwd $DBName > $DBName.dump" mysqldump --skip-extended-insert -h $host -u $user -p$passwd $DBName > $DBName.dump ;; ######################################################## # Do a mysqldump of a specific database just for the # # structure. # # # # Required parameters: # - # host - what server are we on? # - # user - what user do we use to access our DB # - # passwd - The password needed # - # DBName - The database we need a dump of # + # host - what server are we on? # + # user - what user do we use to access our DB # + # passwd - The password needed # + # DBName - The database we need a dump of # ######################################################## "dumpmeta" ) # Dump a copy of the metadata about the database into $DBName.meta echo "mysqldump --no-data -h $host -u $user -p$passwd $DBName > $DBName.meta" mysqldump --no-data -h $host -u $user -p$passwd $DBName > $DBName.meta ;; ################################################ # Show a list of a the tables in the Database # # # # Required parameters: # - # host - what server are we on? # - # user - what user do we use to access our DB # - # passwd - The password needed # - # DBName - The database we need a dump of # + # host - what server are we on? # + # user - what user do we use to access our DB # + # passwd - The password needed # + # DBName - The database we need a dump of # ################################################ "show" ) # Show a list of tables in the $DBName database mysqlshow -h $host -u $user -p$passwd $DBName ;; ####################################################### # Do a Drupal Dump... This is for a Drupal database # # It is meant to dump all the data, but to leave # # behind any cache, session, or watchdog information. # # The purpose here is to keep the size of the backup # # WAY down.... # # # # Required parameters: # - # host - what server are we on? # - # user - what user do we use to access our DB # - # passwd - The password needed # - # DBName - The database we need a dump of # + # host - what server are we on? # + # user - what user do we use to access our DB # + # passwd - The password needed # + # DBName - The database we need a dump of # ####################################################### "dumpdrupal" ) mysql -h $host -u $user -p$passwd $DBName -Bs -e "show tables" > $tempfile rm -f ${DBName}.drupal.dump for t in `cat $tempfile`; do case $t in watchdog|sessions|cache|cache_[a-z]*) mysqldump --no-data -h $host -u $user -p$passwd $DBName $t >> ${DBName}.drupal.dump ;; * ) mysqldump --skip-extended-insert -h $host -u $user -p$passwd $DBName $t >> ${DBName}.drupal.dump ;; esac done ;; ####################################################### # Do a Drupal Find... This is for a Drupal database # # It is meant to search through all the tables to # # all occurances of a string. It ignores the cache # # tables along with the sessions and watchdog. # # # # Required parameters: # - # host - what server are we on? # - # user - what user do we use to access our DB # - # passwd - The password needed # - # DBName - The database we need a dump of # - # findstr - The string you want to search for # + # host - what server are we on? # + # user - what user do we use to access our DB # + # passwd - The password needed # + # DBName - The database we need a dump of # + # findstr - The string you want to search for # ####################################################### "drupalfind" ) echo "Running drupalfind -- Searching for $findstr" echo "Output written to: $tfile3" mysql -h $host -u $user -p$passwd $DBName -Bs -e "show tables" > $tempfile rm -f ${DBName}.drupal.dump for t in `cat $tempfile`; do case $t in watchdog|sessions|cache|cache_[a-z]*) ;; * ) set +o errexit mysqldump --skip-extended-insert -h $host -u $user -p$passwd $DBName $t | grep "$findstr" > $tfile2 set -o errexit ;; esac if [ -s $tfile2 ]; then echo "=================" >> $tfile3 echo $t >> $tfile3 echo "=================" >> $tfile3 cat $tfile2 >> $tfile3 fi done cat $tfile3 ;; ####################################################### # Restore a .dump file that has been created by the # # 'dump' command defined above. # # behind any cache, session, or watchdog information. # # The purpose here is to keep the size of the backup # # WAY down.... # # # # Required parameters: # - # host - what server are we on? # - # user - what user do we use to access our 'New' DB # - # passwd - The password needed for the 'New' DB # - # DBName - The database we have a dump of # - # DBNameNew - The database we are restoring to # + # host - what server are we on? # + # user - what user do we use to access our 'New' DB # + # passwd - The password needed for the 'New' DB # + # DBName - The database we have a dump of # + # DBNameNew - The database we are restoring to # ####################################################### "import" ) #Import from the .dump file into a database echo Importing into $DBNameNew mysql -h $host -u $user -p$passwd $DBNameNew < $DBName.dump ;; ####################################################### # This is a combination of the 'dump' command and the # # 'import' command. The is a small issue here in that # # the host, user, & password must be the same for # # both databases. Both Databases must ALREADY exist. # # # # Required parameters: # - # host - what server are we on? # - # user - what user do we use to access both DB's # - # passwd - The password needed for both DB's # - # DBName - The source database # - # DBNameNew - The destination database # + # host - what server are we on? # + # user - what user do we use to access both DB's # + # passwd - The password needed for both DB's # + # DBName - The source database # + # DBNameNew - The destination database # ####################################################### "copy" ) # Make a copy of a database into an existing one. + echo "Clearing destination database of all tables" + mysql -h $host -u $user -p$passwd $DBNameNew -Bs -e "show tables" > $tempfile + for t in `cat $tempfile`; do + set +o errexit + mysql -h $host -u $user -p$passwd $DBNameNew -Bs -e "drop table $t" + set -o errexit + done echo "Dumpfile file to $tempfile" mysqldump -h $host -u $user -p$passwd $DBName > $tempfile echo "Importing $tempfile to $DBNameNew" mysql -h $host -u $user -p$passwd $DBNameNew < $tempfile echo "Done! $tempfile still available in case you screwed up!" ;; ####################################################### # This routine will make a backup of a database and # # then CREATE a NEW database to restore the backup # # to. Again, the hosts, user, & password must be the # # same for both databases. # - # # + # # # Required parameters: # - # host - what server are we on? # - # user - what user do we use to access both DB's # - # passwd - The password needed for both DB's # - # DBName - The source database # - # DBNameNew - The destination database # + # host - what server are we on? # + # user - what user do we use to access both DB's # + # passwd - The password needed for both DB's # + # DBName - The source database # + # DBNameNew - The destination database # ####################################################### "clone" ) # Make a clone of a database into a new one. echo "Dumpfile file to $tempfile" mysqldump -h $host -u $user -p$passwd $DBName > $tempfile echo "Creating the new database $DBNameNew" cat <<EOF > $tfile2 create database if not exists $DBNameNew; quit EOF mysql -h $host -u $user -p$passwd < $tfile2 rm -f $tfile2 echo "Importing $tempfile to $DBNameNew" mysql -h $host -u $user -p$passwd $DBNameNew < $tempfile echo "Done! $tempfile still available in case you screwed up!" ;; ####################################################### # This will allow for an arbitrary mysql command to # # run. It is run agains the database. If you want to # # string multiple command together, use ';' between # # each command. # - # # + # # # Required parameters: # - # host - what server are we on? # - # user - what user do we use to access both DB's # - # passwd - The password needed for both DB's # - # DBName - The source database # + # host - what server are we on? # + # user - what user do we use to access both DB's # + # passwd - The password needed for both DB's # + # DBName - The source database # ####################################################### "run" ) # Run a quote enclosed script against a database cat <<EOF > $tempfile $script; quit EOF mysql -h $host -u $user -p$passwd $DBName <$tempfile ;; ####################################################### # This will allow for an arbitrary set of mysql # # commands to be run. Build a file with each command # # on a separate line. Terminate each line with ';' # - # # + # # # Required parameters: # - # host - what server are we on? # - # user - what user do we use to access both DB's # - # passwd - The password needed for both DB's # - # DBName - The source database # - # filename - The name of the script file # + # host - what server are we on? # + # user - what user do we use to access both DB's # + # passwd - The password needed for both DB's # + # DBName - The source database # + # filename - The name of the script file # ####################################################### "runfile" ) # Run a script file against a database echo Running script on $DBName mysql -h $host -u $user -p$passwd $DBName < $filename ;; ####################################################### # This provides you with Command Line Interface into # # mysql. # - # # + # # # Required parameters: # - # host - what server are we on? # - # user - what user do we use to access both DB's # - # passwd - The password needed for both DB's # - # DBName - The source database # + # host - what server are we on? # + # user - what user do we use to access both DB's # + # passwd - The password needed for both DB's # + # DBName - The source database # ####################################################### "edit" ) # Go into raw mysql mode on a database # echo "Host: $host - User: $user - Password: $passwd - DB: $DBName" echo "SQL CLI on $host for User $user using Password $passwd in DB $DBName" mysql -h $host -u $user -p$passwd $DBName ;; ####################################################### # Export a table in the database in a CSV format. # - # # + # # # Required parameters: # - # host - what server are we on? # - # user - what user do we use to access both DB's # - # passwd - The password needed for both DB's # - # DBName - The source database # - # table - The source tablename # - # xport - The name of the output file in CSV format # + # host - what server are we on? # + # user - what user do we use to access both DB's # + # passwd - The password needed for both DB's # + # DBName - The source database # + # table - The source tablename # + # xport - The name of the output file in CSV format # ####################################################### "export" ) #Export into CSV format #SELECT * INTO OUTFILE '/somefile.csv' #FIELDS ESCAPED BY '\' #FIELDS OPTIONALLY ENCLOSED BY '"' #FIELDS TERMINATED BY ',' #LINES TERMINATED BY '\n' #FROM table WHERE column='value'"; echo Running CSV export on Database: $DBName and Table: $table cat <<EOF > $tfile2 SELECT * INTO OUTFILE '$xport' FIELDS ESCAPED BY '\' OPTIONALLY ENCLOSED BY '"' TERMINATED BY ',' LINES TERMINATED BY '\n' FROM $table"; quit EOF mysql -h $host -u $user -p$passwd $DBName <$tfile2 >$xport ;; ####################################################### # Provide a 'top' like statistics for your mysql # - # server. # - # # + # server. # + # # # Required parameters: # - # host - what server are we on? # - # user - what user do we use to access both DB's # - # passwd - The password needed for both DB's # - # # - # You must have the mytop package installed for this # - # to work. # + # host - what server are we on? # + # user - what user do we use to access both DB's # + # passwd - The password needed for both DB's # + # # + # You must have the mytop package installed for this # + # to work. # ####################################################### "stats" ) set +o errexit which mytop > /dev/null 2>&1 rc=$? if [ $rc -eq 0 ]; then mytop -u $user -p $passwd -h $host -s 3 else echo -e $usage cat <<EOF $(tput setaf 1)ERROR:$(tput setaf 9) You have attempted run the statistics portion of this script. It is a requirement of this that you have available the 'mytop' package. To Install on various platforms =============================== GENTOO: emerge -avt mytop EOF fi set -o errexit ;; ####################################################### # Alters ALL admin password within all drupal DBs # - # on a specified server. You must provide the old # + # on a specified server. You must provide the old # # and new admin passwords. If the old password does # # not match what is currently in the database, it is # # assumed that the password is NOT TO BE CHANGED. # - # # + # # # Required parameters: # - # host - what server are we on? # - # user - what user do we use to access both DB's # - # passwd - The password needed for both DB's # + # host - what server are we on? # + # user - what user do we use to access both DB's # + # passwd - The password needed for both DB's # # DrupO - The current drupal admin (user 1) password # # DrupN - The new drupal admin (user 1) password # ####################################################### "alter" ) [ ${DrupO:=fred} = "fred" ] && echo "Error :: you must provide the old Drupal Admin password (-a)" && exit 1 [ ${DrupN:=fred} = "fred" ] && echo "Error :: you must provide the new Drupal Admin password (-b)" && exit 1 dblist=`mysql -h $host -u $user -p$passwd -Bs -e "select table_schema from tables where table_name = 'node'" information_schema` /bin/rm -f $tempfile for d in $dblist; do mysql -h $host -u $user -p$passwd -Bs -e "select \"$d\" from users where uid = 1 and pass = md5('$DrupO')" $d >> $tempfile done for d in `cat $tempfile`; do mysql -h $host -u $user -p$passwd -Bs -e "select \"$d - old:\", name, pass from users where uid = 1 and pass = md5('$DrupO')" $d mysql -h $host -u $user -p$passwd -Bs -e "update users set pass = md5('$DrupN') where uid = 1 and pass = md5('$DrupO')" $d mysql -h $host -u $user -p$passwd -Bs -e "select \"$d - new:\", name, pass from users where uid = 1 and pass = md5('$DrupN')" $d echo ----- done ;; ####################################################### # Well, you didn't chose anything, and no default was # # supplied, so here is the usage description # ####################################################### * ) # user error... show the usage page. echo -e $usage ;; esac
worxco/simplesql
6f96f10a1dd66037bba91611474f26627e5c0fbf
Added a new mode, drupalfind.
diff --git a/simplesql b/simplesql index e97ea6c..f0aeb7d 100755 --- a/simplesql +++ b/simplesql @@ -1,470 +1,517 @@ #!/bin/bash # Program: simpelsql # Description: This is an aggregation of mysql based commands. Most often used when working with the Drupal Database. # Author: Kurt L Vanderwater # Copyright (C) 2007-2010 Meridian Data Systems, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. set -o errexit set -o nounset # For this script to run properly, you must fill out all the required information. # If you are lazy like me, you can run a file named simplesql.conf to initialize # certain defaults and aliases. # # the format of this file should be as follows. #> #!/bin/bash #> #> # Setup Defaults #> #> i=0 #> # Set up in the hostA variable the always working address to the server, followed by any aliases you like. #> # all delimited by commas. #> hostA[$i]="sql01.domain.com,sql01" #> userA[$i]="root"; # Put the user for this server here #> passwdA[$i]="<password here>"; # Put the password for this server here (usually for root) #> DBNameA[$((i++))]="test"; # If you want a default database to end up in, this is the place. #> #> hostA[$i]="sql02.domain.com,sql02,x9sql02" #> userA[$i]="root" #> passwdA[$i]="<password here>" #> DBNameA[$((i++))]="test" #> #> tempfile=`tempfile` #> tfile2=`tempfile` #> #> mode="edit" #> host="sql01.doamain.com" #> passwd="" #> user="root" #> DBName="" [ -f /etc/simplesql.conf ] && source ~/etc/simplesql.conf [ -f ~/bin/simplesql.conf ] && source ~/bin/simplesql.conf [ -f simplesql.conf ] && source simplesql.conf +tempfile=`tempfile` +tfile2=`tempfile` +tfile3=`tempfile` + ########################################################## # Create the Usage variable to display if they need help # ########################################################## usage=`cat <<EOF simplesql Copyright (C) 2007-2010 Meridian Data Systems, Inc.\n This program comes with ABSOLUTELY NO WARRANTY; for details read the source.\n This is free software, and you are welcome to redistribute it\n under certain conditions; See the included license.\n\n Usage:\n\n $0 [ -h ] [ -d <database> ] [ -f <filename> ] [ -m <mode> ] [ -n <new database> ] [ -p <password> ] [ -s <quoted script> ] [ -u <user> ]\n\n $(tput setaf 5)-h:$(tput setaf 9) Provide this usage page.\n\n $(tput setaf 5)-a <current Drupal admin password>:$(tput setaf 9) This is the current Drupal admin password. If this doesn't match, we don't run\n\n $(tput setaf 5)-b <new Drupal admin password>:$(tput setaf 9) This is the new, replacement Drupal admin password. see -a for trigger\n\n $(tput setaf 5)-d <database>:$(tput setaf 9) Enter the name of the database that you are operating against.\n\n $(tput setaf 5)-f <filename>:$(tput setaf 9) This is a script file with multiple semi-colon terminated mysql commands.\n\n + $(tput setaf 5)-i <findstr>:$(tput setaf 9) This is a string that you wish to search for.\n\n + $(tput setaf 5)-m <mode>:$(tput setaf 9) This defines the different modes that this script can operate in.\n \tdump - Dump the named database to a file with the name of the database.dump.\n \timport - Run the database.dump file created by the dump command above. This is a restore and not a merge.\n \tdumpdrupal - Dump the named database to a file with the name of the database.drupal.dump.\n \t\tThe purpose of this variant is to only get the structure for cache, session, & watchdog tables.\n \t\tAlong with all the data from the rest of the tables.\n + \tdrupalfind - Search a given Drupal database for all occurances of a string.\n \tcopy - Copy a database into another existing database name.\n \t\tThis will NOT recreate the new database. It will clear\n \t\tany existing tables. It will add any new tables.\n \tclone - Copy a database into a new database.\n \trun - run the script provided on the command line by -s <quoted script>.\n \trunfile - run the script command(s) provided in the file named by -f <filename>.\n \texport - create a CSV file output from the dabase.\n \tedit - Go into command line mode of mysql.\n \tshow - Show a list of tables for the database.\n \tstats - launch mytop if it is available\n\n \talter - Alter ALL Drupal admin passwords $(tput setaf 5)-n <new database>:$(tput setaf 9) The name of the new database for copy or clone.\n\n $(tput setaf 5)-o <host>:$(tput setaf 9) The host server where the database exists.\n\n $(tput setaf 5)-p <password>:$(tput setaf 9) The password needed by the user (-u) to access the database.\n\n $(tput setaf 5)-s <quoted script>:$(tput setaf 9) This is a quoted string that is a mysql command script.\n\n $(tput setaf 5)-t <table name>:$(tput setaf 9) This is the table that you want to export.\n\n $(tput setaf 5)-u <user>:$(tput setaf 9) The username that has access to the database.\n\n $(tput setaf 5)-x <CSV export file>:$(tput setaf 9) The output filename you want your CSV export to end up in.\n\n EOF` ################################################ # Accept and parse all the incoming parameters # ################################################ -while getopts ":hm:a:b:d:n:o:p:s:t:u:f:x:" options ; do +while getopts ":hm:a:b:d:n:o:p:s:t:u:f:i:x:" options ; do case $options in m ) mode=$OPTARG;; a ) DrupO=$OPTARG;; b ) DrupN=$OPTARG;; d ) DBName=$OPTARG;; n ) DBNameNew=$OPTARG;; o ) host=$OPTARG;; p ) passwd=$OPTARG;; s ) script=$OPTARG;; t ) table=$OPTARG;; u ) user=$OPTARG;; f ) filename=$OPTARG;; x ) xport=$OPTARG;; + i ) findstr=$OPTARG;; h ) mode="help";; esac done ############################################### # Based on the 'host' variable, check aliases # # and select the host. If the passwd, user, # # or DBName variables were not passed in, # # then set them to known defaults. # ############################################### for (( i=0; i<$((${#hostA[@]})); i=i+1 )); do # echo ${alias[i]} # echo -n "$a :: " set -- `echo ${hostA[i]} | tr , \ ` temp=$1 while [ ${#1} -gt 0 ]; do if [ $1 == $host ]; then host=$temp if [[ ! $passwd ]];then passwd=${passwdA[i]} fi if [[ ! $user ]];then user=${userA[i]} fi if [[ ! $DBName ]];then DBName=${DBNameA[i]} fi fi shift done done ################################################ # Based on the mode given, execute the command # ################################################ case $mode in ######################################################## # Do a mysqldump of a specific database # # Normally, if I do the dump, it is because # # I want to look at it. So, the --skip-extended-insert # # option so I can actually read the records # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access our DB # # passwd - The password needed # # DBName - The database we need a dump of # ######################################################## "dump" ) # Dump a copy of the database into $DBName.dump echo "mysqldump --skip-extended-insert -h $host -u $user -p$passwd $DBName > $DBName.dump" mysqldump --skip-extended-insert -h $host -u $user -p$passwd $DBName > $DBName.dump ;; ######################################################## # Do a mysqldump of a specific database just for the # # structure. # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access our DB # # passwd - The password needed # # DBName - The database we need a dump of # ######################################################## "dumpmeta" ) # Dump a copy of the metadata about the database into $DBName.meta echo "mysqldump --no-data -h $host -u $user -p$passwd $DBName > $DBName.meta" mysqldump --no-data -h $host -u $user -p$passwd $DBName > $DBName.meta ;; ################################################ # Show a list of a the tables in the Database # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access our DB # # passwd - The password needed # # DBName - The database we need a dump of # ################################################ "show" ) # Show a list of tables in the $DBName database mysqlshow -h $host -u $user -p$passwd $DBName ;; ####################################################### # Do a Drupal Dump... This is for a Drupal database # # It is meant to dump all the data, but to leave # # behind any cache, session, or watchdog information. # # The purpose here is to keep the size of the backup # # WAY down.... # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access our DB # # passwd - The password needed # # DBName - The database we need a dump of # ####################################################### "dumpdrupal" ) mysql -h $host -u $user -p$passwd $DBName -Bs -e "show tables" > $tempfile rm -f ${DBName}.drupal.dump for t in `cat $tempfile`; do case $t in watchdog|sessions|cache|cache_[a-z]*) mysqldump --no-data -h $host -u $user -p$passwd $DBName $t >> ${DBName}.drupal.dump ;; * ) mysqldump --skip-extended-insert -h $host -u $user -p$passwd $DBName $t >> ${DBName}.drupal.dump ;; esac done ;; + ####################################################### + # Do a Drupal Find... This is for a Drupal database # + # It is meant to search through all the tables to # + # all occurances of a string. It ignores the cache # + # tables along with the sessions and watchdog. # + # # + # Required parameters: # + # host - what server are we on? # + # user - what user do we use to access our DB # + # passwd - The password needed # + # DBName - The database we need a dump of # + # findstr - The string you want to search for # + ####################################################### + "drupalfind" ) + echo "Running drupalfind -- Searching for $findstr" + echo "Output written to: $tfile3" + mysql -h $host -u $user -p$passwd $DBName -Bs -e "show tables" > $tempfile + + rm -f ${DBName}.drupal.dump + for t in `cat $tempfile`; do + case $t in + watchdog|sessions|cache|cache_[a-z]*) + ;; + * ) + set +o errexit + mysqldump --skip-extended-insert -h $host -u $user -p$passwd $DBName $t | grep "$findstr" > $tfile2 + set -o errexit + ;; + esac + if [ -s $tfile2 ]; then + echo "=================" >> $tfile3 + echo $t >> $tfile3 + echo "=================" >> $tfile3 + cat $tfile2 >> $tfile3 + fi + done + cat $tfile3 + ;; + ####################################################### # Restore a .dump file that has been created by the # # 'dump' command defined above. # # behind any cache, session, or watchdog information. # # The purpose here is to keep the size of the backup # # WAY down.... # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access our 'New' DB # # passwd - The password needed for the 'New' DB # # DBName - The database we have a dump of # # DBNameNew - The database we are restoring to # ####################################################### "import" ) #Import from the .dump file into a database echo Importing into $DBNameNew mysql -h $host -u $user -p$passwd $DBNameNew < $DBName.dump ;; ####################################################### # This is a combination of the 'dump' command and the # # 'import' command. The is a small issue here in that # # the host, user, & password must be the same for # # both databases. Both Databases must ALREADY exist. # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access both DB's # # passwd - The password needed for both DB's # # DBName - The source database # # DBNameNew - The destination database # ####################################################### "copy" ) # Make a copy of a database into an existing one. echo "Dumpfile file to $tempfile" mysqldump -h $host -u $user -p$passwd $DBName > $tempfile echo "Importing $tempfile to $DBNameNew" mysql -h $host -u $user -p$passwd $DBNameNew < $tempfile echo "Done! $tempfile still available in case you screwed up!" ;; ####################################################### # This routine will make a backup of a database and # # then CREATE a NEW database to restore the backup # # to. Again, the hosts, user, & password must be the # # same for both databases. # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access both DB's # # passwd - The password needed for both DB's # # DBName - The source database # # DBNameNew - The destination database # ####################################################### "clone" ) # Make a clone of a database into a new one. echo "Dumpfile file to $tempfile" mysqldump -h $host -u $user -p$passwd $DBName > $tempfile echo "Creating the new database $DBNameNew" cat <<EOF > $tfile2 create database if not exists $DBNameNew; quit EOF mysql -h $host -u $user -p$passwd < $tfile2 rm -f $tfile2 echo "Importing $tempfile to $DBNameNew" mysql -h $host -u $user -p$passwd $DBNameNew < $tempfile echo "Done! $tempfile still available in case you screwed up!" ;; ####################################################### # This will allow for an arbitrary mysql command to # # run. It is run agains the database. If you want to # # string multiple command together, use ';' between # # each command. # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access both DB's # # passwd - The password needed for both DB's # # DBName - The source database # ####################################################### "run" ) # Run a quote enclosed script against a database cat <<EOF > $tempfile $script; quit EOF mysql -h $host -u $user -p$passwd $DBName <$tempfile ;; ####################################################### # This will allow for an arbitrary set of mysql # # commands to be run. Build a file with each command # # on a separate line. Terminate each line with ';' # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access both DB's # # passwd - The password needed for both DB's # # DBName - The source database # # filename - The name of the script file # ####################################################### "runfile" ) # Run a script file against a database echo Running script on $DBName mysql -h $host -u $user -p$passwd $DBName < $filename ;; ####################################################### # This provides you with Command Line Interface into # # mysql. # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access both DB's # # passwd - The password needed for both DB's # # DBName - The source database # ####################################################### "edit" ) # Go into raw mysql mode on a database # echo "Host: $host - User: $user - Password: $passwd - DB: $DBName" echo "SQL CLI on $host for User $user using Password $passwd in DB $DBName" mysql -h $host -u $user -p$passwd $DBName ;; ####################################################### # Export a table in the database in a CSV format. # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access both DB's # # passwd - The password needed for both DB's # # DBName - The source database # # table - The source tablename # # xport - The name of the output file in CSV format # ####################################################### "export" ) #Export into CSV format #SELECT * INTO OUTFILE '/somefile.csv' #FIELDS ESCAPED BY '\' #FIELDS OPTIONALLY ENCLOSED BY '"' #FIELDS TERMINATED BY ',' #LINES TERMINATED BY '\n' #FROM table WHERE column='value'"; echo Running CSV export on Database: $DBName and Table: $table cat <<EOF > $tfile2 SELECT * INTO OUTFILE '$xport' FIELDS ESCAPED BY '\' OPTIONALLY ENCLOSED BY '"' TERMINATED BY ',' LINES TERMINATED BY '\n' FROM $table"; quit EOF mysql -h $host -u $user -p$passwd $DBName <$tfile2 >$xport ;; ####################################################### # Provide a 'top' like statistics for your mysql # # server. # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access both DB's # # passwd - The password needed for both DB's # # # # You must have the mytop package installed for this # # to work. # ####################################################### "stats" ) set +o errexit which mytop > /dev/null 2>&1 rc=$? if [ $rc -eq 0 ]; then mytop -u $user -p $passwd -h $host -s 3 else echo -e $usage cat <<EOF $(tput setaf 1)ERROR:$(tput setaf 9) You have attempted run the statistics portion of this script. It is a requirement of this that you have available the 'mytop' package. To Install on various platforms =============================== GENTOO: emerge -avt mytop EOF fi set -o errexit ;; ####################################################### # Alters ALL admin password within all drupal DBs # # on a specified server. You must provide the old # # and new admin passwords. If the old password does # # not match what is currently in the database, it is # # assumed that the password is NOT TO BE CHANGED. # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access both DB's # # passwd - The password needed for both DB's # # DrupO - The current drupal admin (user 1) password # # DrupN - The new drupal admin (user 1) password # ####################################################### "alter" ) [ ${DrupO:=fred} = "fred" ] && echo "Error :: you must provide the old Drupal Admin password (-a)" && exit 1 [ ${DrupN:=fred} = "fred" ] && echo "Error :: you must provide the new Drupal Admin password (-b)" && exit 1 dblist=`mysql -h $host -u $user -p$passwd -Bs -e "select table_schema from tables where table_name = 'node'" information_schema` /bin/rm -f $tempfile for d in $dblist; do mysql -h $host -u $user -p$passwd -Bs -e "select \"$d\" from users where uid = 1 and pass = md5('$DrupO')" $d >> $tempfile done for d in `cat $tempfile`; do mysql -h $host -u $user -p$passwd -Bs -e "select \"$d - old:\", name, pass from users where uid = 1 and pass = md5('$DrupO')" $d mysql -h $host -u $user -p$passwd -Bs -e "update users set pass = md5('$DrupN') where uid = 1 and pass = md5('$DrupO')" $d mysql -h $host -u $user -p$passwd -Bs -e "select \"$d - new:\", name, pass from users where uid = 1 and pass = md5('$DrupN')" $d echo ----- done ;; ####################################################### # Well, you didn't chose anything, and no default was # # supplied, so here is the usage description # ####################################################### * ) # user error... show the usage page. echo -e $usage ;; esac
worxco/simplesql
fbc82662e9b305447b5fec6f6db4f7bc6d02e771
Added a new mode, 'dumpmeta' to dump just the DB structure Added a few more places to look for the simplesql.conf file
diff --git a/simplesql b/simplesql index 0cbaeb1..e97ea6c 100755 --- a/simplesql +++ b/simplesql @@ -1,452 +1,470 @@ #!/bin/bash # Program: simpelsql # Description: This is an aggregation of mysql based commands. Most often used when working with the Drupal Database. # Author: Kurt L Vanderwater # Copyright (C) 2007-2010 Meridian Data Systems, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. set -o errexit set -o nounset # For this script to run properly, you must fill out all the required information. # If you are lazy like me, you can run a file named simplesql.conf to initialize # certain defaults and aliases. # # the format of this file should be as follows. #> #!/bin/bash #> #> # Setup Defaults #> #> i=0 #> # Set up in the hostA variable the always working address to the server, followed by any aliases you like. #> # all delimited by commas. #> hostA[$i]="sql01.domain.com,sql01" #> userA[$i]="root"; # Put the user for this server here #> passwdA[$i]="<password here>"; # Put the password for this server here (usually for root) #> DBNameA[$((i++))]="test"; # If you want a default database to end up in, this is the place. #> #> hostA[$i]="sql02.domain.com,sql02,x9sql02" #> userA[$i]="root" #> passwdA[$i]="<password here>" #> DBNameA[$((i++))]="test" #> #> tempfile=`tempfile` #> tfile2=`tempfile` #> #> mode="edit" #> host="sql01.doamain.com" #> passwd="" #> user="root" #> DBName="" +[ -f /etc/simplesql.conf ] && source ~/etc/simplesql.conf +[ -f ~/bin/simplesql.conf ] && source ~/bin/simplesql.conf [ -f simplesql.conf ] && source simplesql.conf ########################################################## # Create the Usage variable to display if they need help # ########################################################## usage=`cat <<EOF simplesql Copyright (C) 2007-2010 Meridian Data Systems, Inc.\n This program comes with ABSOLUTELY NO WARRANTY; for details read the source.\n This is free software, and you are welcome to redistribute it\n under certain conditions; See the included license.\n\n Usage:\n\n $0 [ -h ] [ -d <database> ] [ -f <filename> ] [ -m <mode> ] [ -n <new database> ] [ -p <password> ] [ -s <quoted script> ] [ -u <user> ]\n\n $(tput setaf 5)-h:$(tput setaf 9) Provide this usage page.\n\n $(tput setaf 5)-a <current Drupal admin password>:$(tput setaf 9) This is the current Drupal admin password. If this doesn't match, we don't run\n\n $(tput setaf 5)-b <new Drupal admin password>:$(tput setaf 9) This is the new, replacement Drupal admin password. see -a for trigger\n\n $(tput setaf 5)-d <database>:$(tput setaf 9) Enter the name of the database that you are operating against.\n\n $(tput setaf 5)-f <filename>:$(tput setaf 9) This is a script file with multiple semi-colon terminated mysql commands.\n\n $(tput setaf 5)-m <mode>:$(tput setaf 9) This defines the different modes that this script can operate in.\n \tdump - Dump the named database to a file with the name of the database.dump.\n \timport - Run the database.dump file created by the dump command above. This is a restore and not a merge.\n \tdumpdrupal - Dump the named database to a file with the name of the database.drupal.dump.\n \t\tThe purpose of this variant is to only get the structure for cache, session, & watchdog tables.\n \t\tAlong with all the data from the rest of the tables.\n \tcopy - Copy a database into another existing database name.\n \t\tThis will NOT recreate the new database. It will clear\n \t\tany existing tables. It will add any new tables.\n \tclone - Copy a database into a new database.\n \trun - run the script provided on the command line by -s <quoted script>.\n \trunfile - run the script command(s) provided in the file named by -f <filename>.\n \texport - create a CSV file output from the dabase.\n \tedit - Go into command line mode of mysql.\n \tshow - Show a list of tables for the database.\n \tstats - launch mytop if it is available\n\n \talter - Alter ALL Drupal admin passwords $(tput setaf 5)-n <new database>:$(tput setaf 9) The name of the new database for copy or clone.\n\n $(tput setaf 5)-o <host>:$(tput setaf 9) The host server where the database exists.\n\n $(tput setaf 5)-p <password>:$(tput setaf 9) The password needed by the user (-u) to access the database.\n\n $(tput setaf 5)-s <quoted script>:$(tput setaf 9) This is a quoted string that is a mysql command script.\n\n $(tput setaf 5)-t <table name>:$(tput setaf 9) This is the table that you want to export.\n\n $(tput setaf 5)-u <user>:$(tput setaf 9) The username that has access to the database.\n\n $(tput setaf 5)-x <CSV export file>:$(tput setaf 9) The output filename you want your CSV export to end up in.\n\n EOF` ################################################ # Accept and parse all the incoming parameters # ################################################ while getopts ":hm:a:b:d:n:o:p:s:t:u:f:x:" options ; do case $options in m ) mode=$OPTARG;; a ) DrupO=$OPTARG;; b ) DrupN=$OPTARG;; d ) DBName=$OPTARG;; n ) DBNameNew=$OPTARG;; o ) host=$OPTARG;; p ) passwd=$OPTARG;; s ) script=$OPTARG;; t ) table=$OPTARG;; u ) user=$OPTARG;; f ) filename=$OPTARG;; x ) xport=$OPTARG;; h ) mode="help";; esac done ############################################### # Based on the 'host' variable, check aliases # # and select the host. If the passwd, user, # # or DBName variables were not passed in, # # then set them to known defaults. # ############################################### for (( i=0; i<$((${#hostA[@]})); i=i+1 )); do # echo ${alias[i]} # echo -n "$a :: " set -- `echo ${hostA[i]} | tr , \ ` temp=$1 while [ ${#1} -gt 0 ]; do if [ $1 == $host ]; then host=$temp if [[ ! $passwd ]];then passwd=${passwdA[i]} fi if [[ ! $user ]];then user=${userA[i]} fi if [[ ! $DBName ]];then DBName=${DBNameA[i]} fi fi shift done done ################################################ # Based on the mode given, execute the command # ################################################ case $mode in ######################################################## # Do a mysqldump of a specific database # # Normally, if I do the dump, it is because # # I want to look at it. So, the --skip-extended-insert # # option so I can actually read the records # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access our DB # # passwd - The password needed # # DBName - The database we need a dump of # ######################################################## "dump" ) # Dump a copy of the database into $DBName.dump + echo "mysqldump --skip-extended-insert -h $host -u $user -p$passwd $DBName > $DBName.dump" mysqldump --skip-extended-insert -h $host -u $user -p$passwd $DBName > $DBName.dump ;; + ######################################################## + # Do a mysqldump of a specific database just for the # + # structure. # + # # + # Required parameters: # + # host - what server are we on? # + # user - what user do we use to access our DB # + # passwd - The password needed # + # DBName - The database we need a dump of # + ######################################################## + "dumpmeta" ) # Dump a copy of the metadata about the database into $DBName.meta + echo "mysqldump --no-data -h $host -u $user -p$passwd $DBName > $DBName.meta" + mysqldump --no-data -h $host -u $user -p$passwd $DBName > $DBName.meta + ;; + ################################################ # Show a list of a the tables in the Database # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access our DB # # passwd - The password needed # # DBName - The database we need a dump of # ################################################ "show" ) # Show a list of tables in the $DBName database mysqlshow -h $host -u $user -p$passwd $DBName ;; ####################################################### # Do a Drupal Dump... This is for a Drupal database # # It is meant to dump all the data, but to leave # # behind any cache, session, or watchdog information. # # The purpose here is to keep the size of the backup # # WAY down.... # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access our DB # # passwd - The password needed # # DBName - The database we need a dump of # ####################################################### "dumpdrupal" ) mysql -h $host -u $user -p$passwd $DBName -Bs -e "show tables" > $tempfile rm -f ${DBName}.drupal.dump for t in `cat $tempfile`; do case $t in watchdog|sessions|cache|cache_[a-z]*) mysqldump --no-data -h $host -u $user -p$passwd $DBName $t >> ${DBName}.drupal.dump ;; * ) mysqldump --skip-extended-insert -h $host -u $user -p$passwd $DBName $t >> ${DBName}.drupal.dump ;; esac done ;; ####################################################### # Restore a .dump file that has been created by the # # 'dump' command defined above. # # behind any cache, session, or watchdog information. # # The purpose here is to keep the size of the backup # # WAY down.... # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access our 'New' DB # # passwd - The password needed for the 'New' DB # # DBName - The database we have a dump of # # DBNameNew - The database we are restoring to # ####################################################### "import" ) #Import from the .dump file into a database echo Importing into $DBNameNew mysql -h $host -u $user -p$passwd $DBNameNew < $DBName.dump ;; ####################################################### # This is a combination of the 'dump' command and the # # 'import' command. The is a small issue here in that # # the host, user, & password must be the same for # # both databases. Both Databases must ALREADY exist. # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access both DB's # # passwd - The password needed for both DB's # # DBName - The source database # # DBNameNew - The destination database # ####################################################### "copy" ) # Make a copy of a database into an existing one. echo "Dumpfile file to $tempfile" mysqldump -h $host -u $user -p$passwd $DBName > $tempfile echo "Importing $tempfile to $DBNameNew" mysql -h $host -u $user -p$passwd $DBNameNew < $tempfile echo "Done! $tempfile still available in case you screwed up!" ;; ####################################################### # This routine will make a backup of a database and # # then CREATE a NEW database to restore the backup # # to. Again, the hosts, user, & password must be the # # same for both databases. # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access both DB's # # passwd - The password needed for both DB's # # DBName - The source database # # DBNameNew - The destination database # ####################################################### "clone" ) # Make a clone of a database into a new one. echo "Dumpfile file to $tempfile" mysqldump -h $host -u $user -p$passwd $DBName > $tempfile echo "Creating the new database $DBNameNew" cat <<EOF > $tfile2 create database if not exists $DBNameNew; quit EOF mysql -h $host -u $user -p$passwd < $tfile2 rm -f $tfile2 echo "Importing $tempfile to $DBNameNew" mysql -h $host -u $user -p$passwd $DBNameNew < $tempfile echo "Done! $tempfile still available in case you screwed up!" ;; ####################################################### # This will allow for an arbitrary mysql command to # # run. It is run agains the database. If you want to # # string multiple command together, use ';' between # # each command. # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access both DB's # # passwd - The password needed for both DB's # # DBName - The source database # ####################################################### "run" ) # Run a quote enclosed script against a database cat <<EOF > $tempfile $script; quit EOF mysql -h $host -u $user -p$passwd $DBName <$tempfile ;; ####################################################### # This will allow for an arbitrary set of mysql # # commands to be run. Build a file with each command # # on a separate line. Terminate each line with ';' # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access both DB's # # passwd - The password needed for both DB's # # DBName - The source database # # filename - The name of the script file # ####################################################### "runfile" ) # Run a script file against a database echo Running script on $DBName mysql -h $host -u $user -p$passwd $DBName < $filename ;; ####################################################### # This provides you with Command Line Interface into # # mysql. # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access both DB's # # passwd - The password needed for both DB's # # DBName - The source database # ####################################################### "edit" ) # Go into raw mysql mode on a database # echo "Host: $host - User: $user - Password: $passwd - DB: $DBName" echo "SQL CLI on $host for User $user using Password $passwd in DB $DBName" mysql -h $host -u $user -p$passwd $DBName ;; ####################################################### # Export a table in the database in a CSV format. # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access both DB's # # passwd - The password needed for both DB's # # DBName - The source database # # table - The source tablename # # xport - The name of the output file in CSV format # ####################################################### "export" ) #Export into CSV format #SELECT * INTO OUTFILE '/somefile.csv' #FIELDS ESCAPED BY '\' #FIELDS OPTIONALLY ENCLOSED BY '"' #FIELDS TERMINATED BY ',' #LINES TERMINATED BY '\n' #FROM table WHERE column='value'"; echo Running CSV export on Database: $DBName and Table: $table cat <<EOF > $tfile2 SELECT * INTO OUTFILE '$xport' FIELDS ESCAPED BY '\' OPTIONALLY ENCLOSED BY '"' TERMINATED BY ',' LINES TERMINATED BY '\n' FROM $table"; quit EOF mysql -h $host -u $user -p$passwd $DBName <$tfile2 >$xport ;; ####################################################### # Provide a 'top' like statistics for your mysql # # server. # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access both DB's # # passwd - The password needed for both DB's # # # # You must have the mytop package installed for this # # to work. # ####################################################### "stats" ) set +o errexit which mytop > /dev/null 2>&1 rc=$? if [ $rc -eq 0 ]; then mytop -u $user -p $passwd -h $host -s 3 else echo -e $usage cat <<EOF $(tput setaf 1)ERROR:$(tput setaf 9) You have attempted run the statistics portion of this script. It is a requirement of this that you have available the 'mytop' package. To Install on various platforms =============================== GENTOO: emerge -avt mytop EOF fi set -o errexit ;; ####################################################### # Alters ALL admin password within all drupal DBs # # on a specified server. You must provide the old # # and new admin passwords. If the old password does # # not match what is currently in the database, it is # # assumed that the password is NOT TO BE CHANGED. # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access both DB's # # passwd - The password needed for both DB's # # DrupO - The current drupal admin (user 1) password # # DrupN - The new drupal admin (user 1) password # ####################################################### "alter" ) [ ${DrupO:=fred} = "fred" ] && echo "Error :: you must provide the old Drupal Admin password (-a)" && exit 1 [ ${DrupN:=fred} = "fred" ] && echo "Error :: you must provide the new Drupal Admin password (-b)" && exit 1 dblist=`mysql -h $host -u $user -p$passwd -Bs -e "select table_schema from tables where table_name = 'node'" information_schema` /bin/rm -f $tempfile for d in $dblist; do mysql -h $host -u $user -p$passwd -Bs -e "select \"$d\" from users where uid = 1 and pass = md5('$DrupO')" $d >> $tempfile done for d in `cat $tempfile`; do mysql -h $host -u $user -p$passwd -Bs -e "select \"$d - old:\", name, pass from users where uid = 1 and pass = md5('$DrupO')" $d mysql -h $host -u $user -p$passwd -Bs -e "update users set pass = md5('$DrupN') where uid = 1 and pass = md5('$DrupO')" $d mysql -h $host -u $user -p$passwd -Bs -e "select \"$d - new:\", name, pass from users where uid = 1 and pass = md5('$DrupN')" $d echo ----- done ;; ####################################################### # Well, you didn't chose anything, and no default was # # supplied, so here is the usage description # ####################################################### * ) # user error... show the usage page. echo -e $usage ;; esac
worxco/simplesql
f10ffcf7cbe6efd535c0c3c363357fc66d32d7d2
Added in the GLPv3 license file and notices inside the script
diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..10926e8 --- /dev/null +++ b/LICENSE @@ -0,0 +1,675 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + <program> Copyright (C) <year> <name of author> + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +<http://www.gnu.org/licenses/>. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +<http://www.gnu.org/philosophy/why-not-lgpl.html>. + diff --git a/simplesql b/simplesql index 7130cfb..0cbaeb1 100755 --- a/simplesql +++ b/simplesql @@ -1,429 +1,452 @@ #!/bin/bash +# Program: simpelsql +# Description: This is an aggregation of mysql based commands. Most often used when working with the Drupal Database. +# Author: Kurt L Vanderwater +# Copyright (C) 2007-2010 Meridian Data Systems, Inc. +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + set -o errexit set -o nounset # For this script to run properly, you must fill out all the required information. # If you are lazy like me, you can run a file named simplesql.conf to initialize # certain defaults and aliases. # # the format of this file should be as follows. #> #!/bin/bash #> #> # Setup Defaults #> #> i=0 #> # Set up in the hostA variable the always working address to the server, followed by any aliases you like. #> # all delimited by commas. #> hostA[$i]="sql01.domain.com,sql01" #> userA[$i]="root"; # Put the user for this server here #> passwdA[$i]="<password here>"; # Put the password for this server here (usually for root) #> DBNameA[$((i++))]="test"; # If you want a default database to end up in, this is the place. #> #> hostA[$i]="sql02.domain.com,sql02,x9sql02" #> userA[$i]="root" #> passwdA[$i]="<password here>" #> DBNameA[$((i++))]="test" #> #> tempfile=`tempfile` #> tfile2=`tempfile` #> #> mode="edit" #> host="sql01.doamain.com" #> passwd="" #> user="root" #> DBName="" [ -f simplesql.conf ] && source simplesql.conf ########################################################## # Create the Usage variable to display if they need help # ########################################################## usage=`cat <<EOF + simplesql Copyright (C) 2007-2010 Meridian Data Systems, Inc.\n + This program comes with ABSOLUTELY NO WARRANTY; for details read the source.\n + This is free software, and you are welcome to redistribute it\n + under certain conditions; See the included license.\n\n + Usage:\n\n $0 [ -h ] [ -d <database> ] [ -f <filename> ] [ -m <mode> ] [ -n <new database> ] [ -p <password> ] [ -s <quoted script> ] [ -u <user> ]\n\n $(tput setaf 5)-h:$(tput setaf 9) Provide this usage page.\n\n $(tput setaf 5)-a <current Drupal admin password>:$(tput setaf 9) This is the current Drupal admin password. If this doesn't match, we don't run\n\n $(tput setaf 5)-b <new Drupal admin password>:$(tput setaf 9) This is the new, replacement Drupal admin password. see -a for trigger\n\n $(tput setaf 5)-d <database>:$(tput setaf 9) Enter the name of the database that you are operating against.\n\n $(tput setaf 5)-f <filename>:$(tput setaf 9) This is a script file with multiple semi-colon terminated mysql commands.\n\n $(tput setaf 5)-m <mode>:$(tput setaf 9) This defines the different modes that this script can operate in.\n \tdump - Dump the named database to a file with the name of the database.dump.\n \timport - Run the database.dump file created by the dump command above. This is a restore and not a merge.\n \tdumpdrupal - Dump the named database to a file with the name of the database.drupal.dump.\n \t\tThe purpose of this variant is to only get the structure for cache, session, & watchdog tables.\n \t\tAlong with all the data from the rest of the tables.\n \tcopy - Copy a database into another existing database name.\n \t\tThis will NOT recreate the new database. It will clear\n \t\tany existing tables. It will add any new tables.\n \tclone - Copy a database into a new database.\n \trun - run the script provided on the command line by -s <quoted script>.\n \trunfile - run the script command(s) provided in the file named by -f <filename>.\n \texport - create a CSV file output from the dabase.\n \tedit - Go into command line mode of mysql.\n \tshow - Show a list of tables for the database.\n \tstats - launch mytop if it is available\n\n \talter - Alter ALL Drupal admin passwords $(tput setaf 5)-n <new database>:$(tput setaf 9) The name of the new database for copy or clone.\n\n $(tput setaf 5)-o <host>:$(tput setaf 9) The host server where the database exists.\n\n $(tput setaf 5)-p <password>:$(tput setaf 9) The password needed by the user (-u) to access the database.\n\n $(tput setaf 5)-s <quoted script>:$(tput setaf 9) This is a quoted string that is a mysql command script.\n\n $(tput setaf 5)-t <table name>:$(tput setaf 9) This is the table that you want to export.\n\n $(tput setaf 5)-u <user>:$(tput setaf 9) The username that has access to the database.\n\n $(tput setaf 5)-x <CSV export file>:$(tput setaf 9) The output filename you want your CSV export to end up in.\n\n EOF` ################################################ # Accept and parse all the incoming parameters # ################################################ while getopts ":hm:a:b:d:n:o:p:s:t:u:f:x:" options ; do case $options in m ) mode=$OPTARG;; a ) DrupO=$OPTARG;; b ) DrupN=$OPTARG;; d ) DBName=$OPTARG;; n ) DBNameNew=$OPTARG;; o ) host=$OPTARG;; p ) passwd=$OPTARG;; s ) script=$OPTARG;; t ) table=$OPTARG;; u ) user=$OPTARG;; f ) filename=$OPTARG;; x ) xport=$OPTARG;; h ) mode="help";; esac done ############################################### # Based on the 'host' variable, check aliases # # and select the host. If the passwd, user, # # or DBName variables were not passed in, # # then set them to known defaults. # ############################################### for (( i=0; i<$((${#hostA[@]})); i=i+1 )); do # echo ${alias[i]} # echo -n "$a :: " set -- `echo ${hostA[i]} | tr , \ ` temp=$1 while [ ${#1} -gt 0 ]; do if [ $1 == $host ]; then host=$temp if [[ ! $passwd ]];then passwd=${passwdA[i]} fi if [[ ! $user ]];then user=${userA[i]} fi if [[ ! $DBName ]];then DBName=${DBNameA[i]} fi fi shift done done ################################################ # Based on the mode given, execute the command # ################################################ case $mode in ######################################################## # Do a mysqldump of a specific database # # Normally, if I do the dump, it is because # # I want to look at it. So, the --skip-extended-insert # # option so I can actually read the records # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access our DB # # passwd - The password needed # # DBName - The database we need a dump of # ######################################################## "dump" ) # Dump a copy of the database into $DBName.dump mysqldump --skip-extended-insert -h $host -u $user -p$passwd $DBName > $DBName.dump ;; ################################################ # Show a list of a the tables in the Database # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access our DB # # passwd - The password needed # # DBName - The database we need a dump of # ################################################ "show" ) # Show a list of tables in the $DBName database mysqlshow -h $host -u $user -p$passwd $DBName ;; ####################################################### # Do a Drupal Dump... This is for a Drupal database # # It is meant to dump all the data, but to leave # # behind any cache, session, or watchdog information. # # The purpose here is to keep the size of the backup # # WAY down.... # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access our DB # # passwd - The password needed # # DBName - The database we need a dump of # ####################################################### "dumpdrupal" ) mysql -h $host -u $user -p$passwd $DBName -Bs -e "show tables" > $tempfile rm -f ${DBName}.drupal.dump for t in `cat $tempfile`; do case $t in watchdog|sessions|cache|cache_[a-z]*) mysqldump --no-data -h $host -u $user -p$passwd $DBName $t >> ${DBName}.drupal.dump ;; * ) mysqldump --skip-extended-insert -h $host -u $user -p$passwd $DBName $t >> ${DBName}.drupal.dump ;; esac done ;; ####################################################### # Restore a .dump file that has been created by the # # 'dump' command defined above. # # behind any cache, session, or watchdog information. # # The purpose here is to keep the size of the backup # # WAY down.... # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access our 'New' DB # # passwd - The password needed for the 'New' DB # # DBName - The database we have a dump of # # DBNameNew - The database we are restoring to # ####################################################### "import" ) #Import from the .dump file into a database echo Importing into $DBNameNew mysql -h $host -u $user -p$passwd $DBNameNew < $DBName.dump ;; ####################################################### # This is a combination of the 'dump' command and the # # 'import' command. The is a small issue here in that # # the host, user, & password must be the same for # # both databases. Both Databases must ALREADY exist. # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access both DB's # # passwd - The password needed for both DB's # # DBName - The source database # # DBNameNew - The destination database # ####################################################### "copy" ) # Make a copy of a database into an existing one. echo "Dumpfile file to $tempfile" mysqldump -h $host -u $user -p$passwd $DBName > $tempfile echo "Importing $tempfile to $DBNameNew" mysql -h $host -u $user -p$passwd $DBNameNew < $tempfile echo "Done! $tempfile still available in case you screwed up!" ;; ####################################################### # This routine will make a backup of a database and # # then CREATE a NEW database to restore the backup # # to. Again, the hosts, user, & password must be the # # same for both databases. # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access both DB's # # passwd - The password needed for both DB's # # DBName - The source database # # DBNameNew - The destination database # ####################################################### "clone" ) # Make a clone of a database into a new one. echo "Dumpfile file to $tempfile" mysqldump -h $host -u $user -p$passwd $DBName > $tempfile echo "Creating the new database $DBNameNew" cat <<EOF > $tfile2 create database if not exists $DBNameNew; quit EOF mysql -h $host -u $user -p$passwd < $tfile2 rm -f $tfile2 echo "Importing $tempfile to $DBNameNew" mysql -h $host -u $user -p$passwd $DBNameNew < $tempfile echo "Done! $tempfile still available in case you screwed up!" ;; ####################################################### # This will allow for an arbitrary mysql command to # # run. It is run agains the database. If you want to # # string multiple command together, use ';' between # # each command. # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access both DB's # # passwd - The password needed for both DB's # # DBName - The source database # ####################################################### "run" ) # Run a quote enclosed script against a database cat <<EOF > $tempfile $script; quit EOF mysql -h $host -u $user -p$passwd $DBName <$tempfile ;; ####################################################### # This will allow for an arbitrary set of mysql # # commands to be run. Build a file with each command # # on a separate line. Terminate each line with ';' # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access both DB's # # passwd - The password needed for both DB's # # DBName - The source database # # filename - The name of the script file # ####################################################### "runfile" ) # Run a script file against a database echo Running script on $DBName mysql -h $host -u $user -p$passwd $DBName < $filename ;; ####################################################### # This provides you with Command Line Interface into # # mysql. # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access both DB's # # passwd - The password needed for both DB's # # DBName - The source database # ####################################################### "edit" ) # Go into raw mysql mode on a database # echo "Host: $host - User: $user - Password: $passwd - DB: $DBName" echo "SQL CLI on $host for User $user using Password $passwd in DB $DBName" mysql -h $host -u $user -p$passwd $DBName ;; ####################################################### # Export a table in the database in a CSV format. # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access both DB's # # passwd - The password needed for both DB's # # DBName - The source database # # table - The source tablename # # xport - The name of the output file in CSV format # ####################################################### "export" ) #Export into CSV format #SELECT * INTO OUTFILE '/somefile.csv' #FIELDS ESCAPED BY '\' #FIELDS OPTIONALLY ENCLOSED BY '"' #FIELDS TERMINATED BY ',' #LINES TERMINATED BY '\n' #FROM table WHERE column='value'"; echo Running CSV export on Database: $DBName and Table: $table cat <<EOF > $tfile2 SELECT * INTO OUTFILE '$xport' FIELDS ESCAPED BY '\' OPTIONALLY ENCLOSED BY '"' TERMINATED BY ',' LINES TERMINATED BY '\n' FROM $table"; quit EOF mysql -h $host -u $user -p$passwd $DBName <$tfile2 >$xport ;; ####################################################### # Provide a 'top' like statistics for your mysql # # server. # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access both DB's # # passwd - The password needed for both DB's # # # # You must have the mytop package installed for this # # to work. # ####################################################### "stats" ) set +o errexit which mytop > /dev/null 2>&1 rc=$? if [ $rc -eq 0 ]; then mytop -u $user -p $passwd -h $host -s 3 else echo -e $usage cat <<EOF $(tput setaf 1)ERROR:$(tput setaf 9) You have attempted run the statistics portion of this script. It is a requirement of this that you have available the 'mytop' package. To Install on various platforms =============================== GENTOO: emerge -avt mytop EOF fi set -o errexit ;; ####################################################### # Alters ALL admin password within all drupal DBs # # on a specified server. You must provide the old # # and new admin passwords. If the old password does # # not match what is currently in the database, it is # # assumed that the password is NOT TO BE CHANGED. # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access both DB's # # passwd - The password needed for both DB's # # DrupO - The current drupal admin (user 1) password # # DrupN - The new drupal admin (user 1) password # ####################################################### "alter" ) [ ${DrupO:=fred} = "fred" ] && echo "Error :: you must provide the old Drupal Admin password (-a)" && exit 1 [ ${DrupN:=fred} = "fred" ] && echo "Error :: you must provide the new Drupal Admin password (-b)" && exit 1 dblist=`mysql -h $host -u $user -p$passwd -Bs -e "select table_schema from tables where table_name = 'node'" information_schema` /bin/rm -f $tempfile for d in $dblist; do mysql -h $host -u $user -p$passwd -Bs -e "select \"$d\" from users where uid = 1 and pass = md5('$DrupO')" $d >> $tempfile done for d in `cat $tempfile`; do mysql -h $host -u $user -p$passwd -Bs -e "select \"$d - old:\", name, pass from users where uid = 1 and pass = md5('$DrupO')" $d mysql -h $host -u $user -p$passwd -Bs -e "update users set pass = md5('$DrupN') where uid = 1 and pass = md5('$DrupO')" $d mysql -h $host -u $user -p$passwd -Bs -e "select \"$d - new:\", name, pass from users where uid = 1 and pass = md5('$DrupN')" $d echo ----- done ;; ####################################################### # Well, you didn't chose anything, and no default was # # supplied, so here is the usage description # ####################################################### * ) # user error... show the usage page. echo -e $usage ;; esac
worxco/simplesql
7ec1c674a8ff913fb5b9f0b998d45de50e80094a
Added description for dumpdrupal to the variable. Also added some indentation to the 'mode' documentation
diff --git a/simplesql b/simplesql index 85fb91e..7130cfb 100755 --- a/simplesql +++ b/simplesql @@ -1,429 +1,429 @@ #!/bin/bash set -o errexit set -o nounset # For this script to run properly, you must fill out all the required information. # If you are lazy like me, you can run a file named simplesql.conf to initialize # certain defaults and aliases. # # the format of this file should be as follows. #> #!/bin/bash #> #> # Setup Defaults #> #> i=0 #> # Set up in the hostA variable the always working address to the server, followed by any aliases you like. #> # all delimited by commas. #> hostA[$i]="sql01.domain.com,sql01" #> userA[$i]="root"; # Put the user for this server here #> passwdA[$i]="<password here>"; # Put the password for this server here (usually for root) #> DBNameA[$((i++))]="test"; # If you want a default database to end up in, this is the place. #> #> hostA[$i]="sql02.domain.com,sql02,x9sql02" #> userA[$i]="root" #> passwdA[$i]="<password here>" #> DBNameA[$((i++))]="test" #> #> tempfile=`tempfile` #> tfile2=`tempfile` #> #> mode="edit" #> host="sql01.doamain.com" #> passwd="" #> user="root" #> DBName="" [ -f simplesql.conf ] && source simplesql.conf ########################################################## # Create the Usage variable to display if they need help # ########################################################## usage=`cat <<EOF Usage:\n\n $0 [ -h ] [ -d <database> ] [ -f <filename> ] [ -m <mode> ] [ -n <new database> ] [ -p <password> ] [ -s <quoted script> ] [ -u <user> ]\n\n $(tput setaf 5)-h:$(tput setaf 9) Provide this usage page.\n\n $(tput setaf 5)-a <current Drupal admin password>:$(tput setaf 9) This is the current Drupal admin password. If this doesn't match, we don't run\n\n $(tput setaf 5)-b <new Drupal admin password>:$(tput setaf 9) This is the new, replacement Drupal admin password. see -a for trigger\n\n $(tput setaf 5)-d <database>:$(tput setaf 9) Enter the name of the database that you are operating against.\n\n $(tput setaf 5)-f <filename>:$(tput setaf 9) This is a script file with multiple semi-colon terminated mysql commands.\n\n $(tput setaf 5)-m <mode>:$(tput setaf 9) This defines the different modes that this script can operate in.\n - dump - Dump the named database to a file with the name of the database.dump.\n - import - Run the database.dump file created by the dump command above. This is a restore and not a merge.\n - copy - Copy a database into another existing database name.\n - This will NOT recreate the new database. It will clear\n - any existing tables. It will add any new tables.\n - clone - Copy a database into a new database.\n - run - run the script provided on the command line by -s <quoted script>.\n - runfile - run the script command(s) provided in the file named by -f <filename>.\n - export - create a CSV file output from the dabase.\n - edit - Go into command line mode of mysql.\n - show - Show a list of tables for the database.\n - stats - launch mytop if it is available\n\n - alter - Alter ALL Drupal admin passwords + \tdump - Dump the named database to a file with the name of the database.dump.\n + \timport - Run the database.dump file created by the dump command above. This is a restore and not a merge.\n + \tdumpdrupal - Dump the named database to a file with the name of the database.drupal.dump.\n + \t\tThe purpose of this variant is to only get the structure for cache, session, & watchdog tables.\n + \t\tAlong with all the data from the rest of the tables.\n + \tcopy - Copy a database into another existing database name.\n + \t\tThis will NOT recreate the new database. It will clear\n + \t\tany existing tables. It will add any new tables.\n + \tclone - Copy a database into a new database.\n + \trun - run the script provided on the command line by -s <quoted script>.\n + \trunfile - run the script command(s) provided in the file named by -f <filename>.\n + \texport - create a CSV file output from the dabase.\n + \tedit - Go into command line mode of mysql.\n + \tshow - Show a list of tables for the database.\n + \tstats - launch mytop if it is available\n\n + \talter - Alter ALL Drupal admin passwords $(tput setaf 5)-n <new database>:$(tput setaf 9) The name of the new database for copy or clone.\n\n $(tput setaf 5)-o <host>:$(tput setaf 9) The host server where the database exists.\n\n $(tput setaf 5)-p <password>:$(tput setaf 9) The password needed by the user (-u) to access the database.\n\n $(tput setaf 5)-s <quoted script>:$(tput setaf 9) This is a quoted string that is a mysql command script.\n\n $(tput setaf 5)-t <table name>:$(tput setaf 9) This is the table that you want to export.\n\n $(tput setaf 5)-u <user>:$(tput setaf 9) The username that has access to the database.\n\n $(tput setaf 5)-x <CSV export file>:$(tput setaf 9) The output filename you want your CSV export to end up in.\n\n EOF` ################################################ # Accept and parse all the incoming parameters # ################################################ while getopts ":hm:a:b:d:n:o:p:s:t:u:f:x:" options ; do case $options in m ) mode=$OPTARG;; a ) DrupO=$OPTARG;; b ) DrupN=$OPTARG;; d ) DBName=$OPTARG;; n ) DBNameNew=$OPTARG;; o ) host=$OPTARG;; p ) passwd=$OPTARG;; s ) script=$OPTARG;; t ) table=$OPTARG;; u ) user=$OPTARG;; f ) filename=$OPTARG;; x ) xport=$OPTARG;; h ) mode="help";; esac done ############################################### # Based on the 'host' variable, check aliases # # and select the host. If the passwd, user, # # or DBName variables were not passed in, # # then set them to known defaults. # ############################################### for (( i=0; i<$((${#hostA[@]})); i=i+1 )); do # echo ${alias[i]} # echo -n "$a :: " set -- `echo ${hostA[i]} | tr , \ ` temp=$1 while [ ${#1} -gt 0 ]; do if [ $1 == $host ]; then host=$temp if [[ ! $passwd ]];then passwd=${passwdA[i]} fi if [[ ! $user ]];then user=${userA[i]} fi if [[ ! $DBName ]];then DBName=${DBNameA[i]} fi fi shift done done ################################################ # Based on the mode given, execute the command # ################################################ case $mode in ######################################################## # Do a mysqldump of a specific database # # Normally, if I do the dump, it is because # # I want to look at it. So, the --skip-extended-insert # # option so I can actually read the records # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access our DB # # passwd - The password needed # # DBName - The database we need a dump of # ######################################################## "dump" ) # Dump a copy of the database into $DBName.dump mysqldump --skip-extended-insert -h $host -u $user -p$passwd $DBName > $DBName.dump ;; ################################################ # Show a list of a the tables in the Database # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access our DB # # passwd - The password needed # # DBName - The database we need a dump of # ################################################ "show" ) # Show a list of tables in the $DBName database mysqlshow -h $host -u $user -p$passwd $DBName ;; ####################################################### # Do a Drupal Dump... This is for a Drupal database # # It is meant to dump all the data, but to leave # # behind any cache, session, or watchdog information. # # The purpose here is to keep the size of the backup # # WAY down.... # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access our DB # # passwd - The password needed # # DBName - The database we need a dump of # ####################################################### - ### TODO - # * This needs to be added to the usage section - # "dumpdrupal" ) mysql -h $host -u $user -p$passwd $DBName -Bs -e "show tables" > $tempfile rm -f ${DBName}.drupal.dump for t in `cat $tempfile`; do case $t in watchdog|sessions|cache|cache_[a-z]*) mysqldump --no-data -h $host -u $user -p$passwd $DBName $t >> ${DBName}.drupal.dump ;; * ) mysqldump --skip-extended-insert -h $host -u $user -p$passwd $DBName $t >> ${DBName}.drupal.dump ;; esac done ;; ####################################################### # Restore a .dump file that has been created by the # # 'dump' command defined above. # # behind any cache, session, or watchdog information. # # The purpose here is to keep the size of the backup # # WAY down.... # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access our 'New' DB # # passwd - The password needed for the 'New' DB # # DBName - The database we have a dump of # # DBNameNew - The database we are restoring to # ####################################################### "import" ) #Import from the .dump file into a database echo Importing into $DBNameNew mysql -h $host -u $user -p$passwd $DBNameNew < $DBName.dump ;; ####################################################### # This is a combination of the 'dump' command and the # # 'import' command. The is a small issue here in that # # the host, user, & password must be the same for # # both databases. Both Databases must ALREADY exist. # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access both DB's # # passwd - The password needed for both DB's # # DBName - The source database # # DBNameNew - The destination database # ####################################################### "copy" ) # Make a copy of a database into an existing one. echo "Dumpfile file to $tempfile" mysqldump -h $host -u $user -p$passwd $DBName > $tempfile echo "Importing $tempfile to $DBNameNew" mysql -h $host -u $user -p$passwd $DBNameNew < $tempfile echo "Done! $tempfile still available in case you screwed up!" ;; ####################################################### # This routine will make a backup of a database and # # then CREATE a NEW database to restore the backup # # to. Again, the hosts, user, & password must be the # # same for both databases. # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access both DB's # # passwd - The password needed for both DB's # # DBName - The source database # # DBNameNew - The destination database # ####################################################### "clone" ) # Make a clone of a database into a new one. echo "Dumpfile file to $tempfile" mysqldump -h $host -u $user -p$passwd $DBName > $tempfile echo "Creating the new database $DBNameNew" cat <<EOF > $tfile2 create database if not exists $DBNameNew; quit EOF mysql -h $host -u $user -p$passwd < $tfile2 rm -f $tfile2 echo "Importing $tempfile to $DBNameNew" mysql -h $host -u $user -p$passwd $DBNameNew < $tempfile echo "Done! $tempfile still available in case you screwed up!" ;; ####################################################### # This will allow for an arbitrary mysql command to # # run. It is run agains the database. If you want to # # string multiple command together, use ';' between # # each command. # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access both DB's # # passwd - The password needed for both DB's # # DBName - The source database # ####################################################### "run" ) # Run a quote enclosed script against a database cat <<EOF > $tempfile $script; quit EOF mysql -h $host -u $user -p$passwd $DBName <$tempfile ;; ####################################################### # This will allow for an arbitrary set of mysql # # commands to be run. Build a file with each command # # on a separate line. Terminate each line with ';' # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access both DB's # # passwd - The password needed for both DB's # # DBName - The source database # # filename - The name of the script file # ####################################################### "runfile" ) # Run a script file against a database echo Running script on $DBName mysql -h $host -u $user -p$passwd $DBName < $filename ;; ####################################################### # This provides you with Command Line Interface into # # mysql. # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access both DB's # # passwd - The password needed for both DB's # # DBName - The source database # ####################################################### "edit" ) # Go into raw mysql mode on a database # echo "Host: $host - User: $user - Password: $passwd - DB: $DBName" echo "SQL CLI on $host for User $user using Password $passwd in DB $DBName" mysql -h $host -u $user -p$passwd $DBName ;; ####################################################### # Export a table in the database in a CSV format. # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access both DB's # # passwd - The password needed for both DB's # # DBName - The source database # # table - The source tablename # # xport - The name of the output file in CSV format # ####################################################### "export" ) #Export into CSV format #SELECT * INTO OUTFILE '/somefile.csv' #FIELDS ESCAPED BY '\' #FIELDS OPTIONALLY ENCLOSED BY '"' #FIELDS TERMINATED BY ',' #LINES TERMINATED BY '\n' #FROM table WHERE column='value'"; echo Running CSV export on Database: $DBName and Table: $table cat <<EOF > $tfile2 SELECT * INTO OUTFILE '$xport' FIELDS ESCAPED BY '\' OPTIONALLY ENCLOSED BY '"' TERMINATED BY ',' LINES TERMINATED BY '\n' FROM $table"; quit EOF mysql -h $host -u $user -p$passwd $DBName <$tfile2 >$xport ;; ####################################################### # Provide a 'top' like statistics for your mysql # # server. # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access both DB's # # passwd - The password needed for both DB's # # # # You must have the mytop package installed for this # # to work. # ####################################################### "stats" ) set +o errexit which mytop > /dev/null 2>&1 rc=$? if [ $rc -eq 0 ]; then mytop -u $user -p $passwd -h $host -s 3 else echo -e $usage cat <<EOF $(tput setaf 1)ERROR:$(tput setaf 9) You have attempted run the statistics portion of this script. It is a requirement of this that you have available the 'mytop' package. To Install on various platforms =============================== GENTOO: emerge -avt mytop EOF fi set -o errexit ;; ####################################################### # Alters ALL admin password within all drupal DBs # # on a specified server. You must provide the old # # and new admin passwords. If the old password does # # not match what is currently in the database, it is # # assumed that the password is NOT TO BE CHANGED. # # # # Required parameters: # # host - what server are we on? # # user - what user do we use to access both DB's # # passwd - The password needed for both DB's # # DrupO - The current drupal admin (user 1) password # # DrupN - The new drupal admin (user 1) password # ####################################################### "alter" ) [ ${DrupO:=fred} = "fred" ] && echo "Error :: you must provide the old Drupal Admin password (-a)" && exit 1 [ ${DrupN:=fred} = "fred" ] && echo "Error :: you must provide the new Drupal Admin password (-b)" && exit 1 dblist=`mysql -h $host -u $user -p$passwd -Bs -e "select table_schema from tables where table_name = 'node'" information_schema` /bin/rm -f $tempfile for d in $dblist; do mysql -h $host -u $user -p$passwd -Bs -e "select \"$d\" from users where uid = 1 and pass = md5('$DrupO')" $d >> $tempfile done for d in `cat $tempfile`; do mysql -h $host -u $user -p$passwd -Bs -e "select \"$d - old:\", name, pass from users where uid = 1 and pass = md5('$DrupO')" $d mysql -h $host -u $user -p$passwd -Bs -e "update users set pass = md5('$DrupN') where uid = 1 and pass = md5('$DrupO')" $d mysql -h $host -u $user -p$passwd -Bs -e "select \"$d - new:\", name, pass from users where uid = 1 and pass = md5('$DrupN')" $d echo ----- done ;; ####################################################### # Well, you didn't chose anything, and no default was # # supplied, so here is the usage description # ####################################################### * ) # user error... show the usage page. echo -e $usage ;; esac
worxco/simplesql
d1465b536e390f26b1d75ee0697b3380871b6e62
Added the README file
diff --git a/README b/README new file mode 100644 index 0000000..c045bb5 --- /dev/null +++ b/README @@ -0,0 +1,35 @@ +README for simplesql + +This is a Bash script. +The purpose, like most programs, is to support my lazyness. + +By creating the $usage portion, it reminded me what parameters +I needed to get a particular job done. + +Also, I have used a variety of mysql commands to accomplish things. + +And as time went on, I found a need to do some special things for +our Drupal databases. So, there are some Drupal specific features +that I have put here as well. + +The easiest way to learn the use of the script is to just launch +it with -h for help. This will print out the usage portion of +the script. + +LOCATION + +I normally would put this in my ~/bin directory and set it to be executable. + +SUPPORTING FILE + +This script is as I said, for my lazyness. If you supply a file named +simplesql.conf, you can place default values there. + +I use it to support about 30 different mysql servers. Each with hundreds of +databases. Many of them are Drupal databases, so that explains the extra +features that are Drupal specific. + +The struction fo the 'simplesql.conf' file is documented at the front +of the simplesql script. + +
zhimin/rformspec
756e89cb730b2ec25564c6243fdcd3e81bd93649
fixed Rakefile with new package task
diff --git a/Rakefile b/Rakefile index 381c0a7..c0f1015 100755 --- a/Rakefile +++ b/Rakefile @@ -1,63 +1,64 @@ require 'rubygems' require 'rake/testtask' -require 'rake/rdoctask' -require 'rake/gempackagetask' +require 'rdoc/task' +require 'rubygems/package_task' $:.unshift(File.dirname(__FILE__) + "/lib") require 'rformspec' desc "Default task" task :default => [ :clean, :test , :gem] desc "Clean generated files" task :clean do rm_rf 'pkg' rm_rf 'docs/rdoc' end # run the unit tests Rake::TestTask.new("test") { |t| t.test_files = FileList['test/test*.rb'] t.verbose= true } + # Generate the RDoc documentation Rake::RDocTask.new { |rdoc| rdoc.rdoc_dir = 'docs/rdoc' rdoc.title = 'rformspec' rdoc.template = "#{ENV['template']}.rb" if ENV['template'] rdoc.rdoc_files.include('README') rdoc.rdoc_files.include('lib/rformspec.rb') rdoc.rdoc_files.include('lib/rformspec/*.rb') } spec = Gem::Specification.new do |s| s.platform= Gem::Platform::CURRENT s.name = "rformspec" - s.version = "0.5.1" + s.version = "0.5.2" s.summary = "An wrap of AUTOIT3 for functional testing of Windows form applications" # s.description = "" s.author = "Zhimin Zhan" s.email = "[email protected]" s.homepage= "http://github.com/zhimin/rformspec" # s.rubyforge_project = "" s.has_rdoc = true s.requirements << 'none' s.require_path = "lib" s.autorequire = "rformspec" s.files = [ "Rakefile", "README", "CHANGELOG", "MIT-LICENSE" ] # s.files = s.files + Dir.glob( "bin/**/*" ).delete_if { |item| item.include?( "\.svn" ) } s.files = s.files + Dir.glob( "ext/**/*" ).delete_if { |item| item.include?( "\.svn" ) } s.files = s.files + Dir.glob( "lib/**/*" ).delete_if { |item| item.include?( "\.svn" ) } s.files = s.files + Dir.glob( "test/**/*" ).delete_if { |item| item.include?( "\.svn" ) } s.files = s.files + Dir.glob( "sample/**/*" ).delete_if { |item| item.include?( "\.svn" ) } s.files = s.files + Dir.glob( "docs/**/*" ).delete_if { |item| item.include?( "\.svn" ) } end -Rake::GemPackageTask.new(spec) do |pkg| +Gem::PackageTask.new(spec) do |pkg| pkg.need_zip = true end
zhimin/rformspec
74c83838c042659181e9790bfe59840d58fbb6fb
change button 1 for win7
diff --git a/lib/rformspec/open_file_dialog.rb b/lib/rformspec/open_file_dialog.rb index d888563..d13f236 100644 --- a/lib/rformspec/open_file_dialog.rb +++ b/lib/rformspec/open_file_dialog.rb @@ -1,19 +1,20 @@ module RFormSpec class OpenFileDialog < RFormSpec::Window def initialize(title = "Open File", text = "") focus_window(title, text) end def enter_filepath(file_path) get_text # somehow calling it get it loaded set_control_text("Edit1", file_path) end - def click_open - click_button("Button2") + def click_open + click_button("Button1") # Windows 7 + # click_button("Button2") end end end
zhimin/rformspec
f8133c04069c7a9d44dc16700c2c2ea6e90be32b
bump version to 0.5.1
diff --git a/Rakefile b/Rakefile index 3447ee2..381c0a7 100755 --- a/Rakefile +++ b/Rakefile @@ -1,63 +1,63 @@ require 'rubygems' require 'rake/testtask' require 'rake/rdoctask' require 'rake/gempackagetask' $:.unshift(File.dirname(__FILE__) + "/lib") require 'rformspec' desc "Default task" task :default => [ :clean, :test , :gem] desc "Clean generated files" task :clean do rm_rf 'pkg' rm_rf 'docs/rdoc' end # run the unit tests Rake::TestTask.new("test") { |t| t.test_files = FileList['test/test*.rb'] t.verbose= true } # Generate the RDoc documentation Rake::RDocTask.new { |rdoc| rdoc.rdoc_dir = 'docs/rdoc' rdoc.title = 'rformspec' rdoc.template = "#{ENV['template']}.rb" if ENV['template'] rdoc.rdoc_files.include('README') rdoc.rdoc_files.include('lib/rformspec.rb') rdoc.rdoc_files.include('lib/rformspec/*.rb') } spec = Gem::Specification.new do |s| s.platform= Gem::Platform::CURRENT s.name = "rformspec" - s.version = "0.5.0" + s.version = "0.5.1" s.summary = "An wrap of AUTOIT3 for functional testing of Windows form applications" # s.description = "" s.author = "Zhimin Zhan" s.email = "[email protected]" s.homepage= "http://github.com/zhimin/rformspec" # s.rubyforge_project = "" s.has_rdoc = true s.requirements << 'none' s.require_path = "lib" s.autorequire = "rformspec" s.files = [ "Rakefile", "README", "CHANGELOG", "MIT-LICENSE" ] # s.files = s.files + Dir.glob( "bin/**/*" ).delete_if { |item| item.include?( "\.svn" ) } s.files = s.files + Dir.glob( "ext/**/*" ).delete_if { |item| item.include?( "\.svn" ) } s.files = s.files + Dir.glob( "lib/**/*" ).delete_if { |item| item.include?( "\.svn" ) } s.files = s.files + Dir.glob( "test/**/*" ).delete_if { |item| item.include?( "\.svn" ) } s.files = s.files + Dir.glob( "sample/**/*" ).delete_if { |item| item.include?( "\.svn" ) } s.files = s.files + Dir.glob( "docs/**/*" ).delete_if { |item| item.include?( "\.svn" ) } end Rake::GemPackageTask.new(spec) do |pkg| pkg.need_zip = true end
zhimin/rformspec
8c96462704f507004bebe1647e22b2e35317c64a
focus win
diff --git a/lib/rformspec/driver.rb b/lib/rformspec/driver.rb index ca4f06f..9669eb6 100644 --- a/lib/rformspec/driver.rb +++ b/lib/rformspec/driver.rb @@ -1,120 +1,120 @@ require 'win32ole' require File.join(File.dirname(__FILE__), "testwise_plugin.rb") module RFormSpec module Driver include TestWisePlugin def driver dump_caller_stack return $a3 if $a3 return RFormSpec::AutoIt.init end def wait_for_window(win, timeout=30) driver.WinWait(win.title, win.text, timeout * 1000) end def wait_and_focus_window(title, text="", timeout=5) try_for(timeout) { found_window = driver.WinExists(title, text) raise "Window '#{title}' not found" unless found_window.to_i == 1 } driver.WinActivate(title, text) sleep 0.5 # check whether suceed if driver.WinActive(title, text).to_i != 1 raise "Failed to make window '#{title}' active" end end def window_exists?(title) driver.WinExists(title) > 0 end def focus_window(title, text = nil) if text driver.WinActivate(title, text) else driver.WinActivate(title) end end def close_window(title) driver.WinClose(title) end # wrapper of keyboard operations def key_press(keys) dump_caller_stack if keys =~ /^Ctrl\+([A-Z])$/ filtered_keys = "^+#{$1}" elsif keys =~ /^Ctrl\+Shift\+([A-Z])$/ filtered_keys = "^+#{$1.downcase}" elsif keys =~ /^Alt+([A-Z])$/ filtered_keys = "!+#{$1}" elsif keys =~ /^Alt\+Shift\+([a-z])$/ filtered_keys = "!+#{$1.downcase}" else filtered_keys = keys end filtered_keys = keys.gsub("Alt+", "!+").gsub("Ctrl+", "^+") RFormSpec::Keyboard.press(filtered_keys) sleep 0.5 end alias press_key key_press # Wrapper of mouse operation def mouse_move(x, y) RFormSpec::Mouse.move_to(x, y) end def mouse_click(x, y) RFormSpec::Mouse.click(x, y) end # standard open file dialog - def open_file_dialog(title, filepath) + def open_file_dialog(title, filepath, text="") wait_and_focus_window(title) - dialog = RFormSpec::OpenFileDialog.new(title) + dialog = RFormSpec::OpenFileDialog.new(title, text) dialog.enter_filepath(filepath) sleep 1 dialog.click_open end #TODO: save as file dialog # helper # Try the operation up to specified timeout (in seconds), and sleep given interval (in seconds). # Error will be ignored until timeout # Example # try_for { click_link('waiting')} # try_for (10, 2) { click_button('Search' } # try to click the 'Search' button upto 10 seconds, try every 2 seconds # try_for { click_button('Search' } def try_for(timeout = 30, polling_interval = 1, &block) start_time = Time.now last_error = nil until (duration = Time.now - start_time) > timeout begin yield last_error = nil return true rescue => e last_error = e end sleep polling_interval end raise "Timeout after #{duration.to_i} seconds with error: #{last_error}." if last_error raise "Timeout after #{duration.to_i} seconds." end end end diff --git a/lib/rformspec/open_file_dialog.rb b/lib/rformspec/open_file_dialog.rb index 04133f9..d888563 100644 --- a/lib/rformspec/open_file_dialog.rb +++ b/lib/rformspec/open_file_dialog.rb @@ -1,19 +1,19 @@ module RFormSpec class OpenFileDialog < RFormSpec::Window - def initialize(title = "Open File") - focus_window(title) + def initialize(title = "Open File", text = "") + focus_window(title, text) end def enter_filepath(file_path) get_text # somehow calling it get it loaded set_control_text("Edit1", file_path) end def click_open click_button("Button2") end end end
zhimin/rformspec
a502d2a98c367d4017a54333b09f68c3d9ae427a
focus window takes text
diff --git a/lib/rformspec/driver.rb b/lib/rformspec/driver.rb index 6fa6e00..ca4f06f 100644 --- a/lib/rformspec/driver.rb +++ b/lib/rformspec/driver.rb @@ -1,116 +1,120 @@ require 'win32ole' require File.join(File.dirname(__FILE__), "testwise_plugin.rb") module RFormSpec module Driver include TestWisePlugin def driver dump_caller_stack return $a3 if $a3 return RFormSpec::AutoIt.init end def wait_for_window(win, timeout=30) driver.WinWait(win.title, win.text, timeout * 1000) end def wait_and_focus_window(title, text="", timeout=5) try_for(timeout) { found_window = driver.WinExists(title, text) raise "Window '#{title}' not found" unless found_window.to_i == 1 } driver.WinActivate(title, text) sleep 0.5 # check whether suceed if driver.WinActive(title, text).to_i != 1 raise "Failed to make window '#{title}' active" end end def window_exists?(title) driver.WinExists(title) > 0 end - def focus_window(title) - driver.WinActivate(title) + def focus_window(title, text = nil) + if text + driver.WinActivate(title, text) + else + driver.WinActivate(title) + end end def close_window(title) driver.WinClose(title) end # wrapper of keyboard operations def key_press(keys) dump_caller_stack if keys =~ /^Ctrl\+([A-Z])$/ filtered_keys = "^+#{$1}" elsif keys =~ /^Ctrl\+Shift\+([A-Z])$/ filtered_keys = "^+#{$1.downcase}" elsif keys =~ /^Alt+([A-Z])$/ filtered_keys = "!+#{$1}" elsif keys =~ /^Alt\+Shift\+([a-z])$/ filtered_keys = "!+#{$1.downcase}" else filtered_keys = keys end filtered_keys = keys.gsub("Alt+", "!+").gsub("Ctrl+", "^+") RFormSpec::Keyboard.press(filtered_keys) sleep 0.5 end alias press_key key_press # Wrapper of mouse operation def mouse_move(x, y) RFormSpec::Mouse.move_to(x, y) end def mouse_click(x, y) RFormSpec::Mouse.click(x, y) end # standard open file dialog def open_file_dialog(title, filepath) wait_and_focus_window(title) dialog = RFormSpec::OpenFileDialog.new(title) dialog.enter_filepath(filepath) sleep 1 dialog.click_open end #TODO: save as file dialog # helper # Try the operation up to specified timeout (in seconds), and sleep given interval (in seconds). # Error will be ignored until timeout # Example # try_for { click_link('waiting')} # try_for (10, 2) { click_button('Search' } # try to click the 'Search' button upto 10 seconds, try every 2 seconds # try_for { click_button('Search' } def try_for(timeout = 30, polling_interval = 1, &block) start_time = Time.now last_error = nil until (duration = Time.now - start_time) > timeout begin yield last_error = nil return true rescue => e last_error = e end sleep polling_interval end raise "Timeout after #{duration.to_i} seconds with error: #{last_error}." if last_error raise "Timeout after #{duration.to_i} seconds." end end end
zhimin/rformspec
70b70c13b94c23e19339fd72e35839284202debc
remove debug comments
diff --git a/lib/rformspec/driver.rb b/lib/rformspec/driver.rb index 7bbb68c..19cc87c 100644 --- a/lib/rformspec/driver.rb +++ b/lib/rformspec/driver.rb @@ -1,118 +1,116 @@ require 'win32ole' require File.join(File.dirname(__FILE__), "testwise_plugin.rb") module RFormSpec module Driver include TestWisePlugin def driver dump_caller_stack return $a3 if $a3 return RFormSpec::AutoIt.init end def wait_for_window(win, timeout=30) driver.WinWait(win.title, win.text, timeout * 1000) end def wait_and_focus_window(title, text="", timeout=5) try_for(timeout) { found_window = driver.WinExists(title, text) - puts "[DEBUG] found window => |#{found_window}|" raise "Window '#{title}' not found" unless found_window.to_i == 1 } driver.WinActivate(title, text) sleep 0.5 # check whether suceed puts "[DEBUG] => |#{driver.WinActive(title, text)}|" - if driver.WinActive(title, text).to_i != 1 raise "Failed to make window '#{title}' active" end end def window_exists?(title) driver.WinExists(title) > 0 end def focus_window(title) driver.WinActivate(title) end def close_window(title) driver.WinClose(title) end # wrapper of keyboard operations def key_press(keys) dump_caller_stack if keys =~ /^Ctrl\+([A-Z])$/ filtered_keys = "^+#{$1}" elsif keys =~ /^Ctrl\+Shift\+([A-Z])$/ filtered_keys = "^+#{$1.downcase}" elsif keys =~ /^Alt+([A-Z])$/ filtered_keys = "!+#{$1}" elsif keys =~ /^Alt\+Shift\+([a-z])$/ filtered_keys = "!+#{$1.downcase}" else filtered_keys = keys end filtered_keys = keys.gsub("Alt+", "!+").gsub("Ctrl+", "^+") RFormSpec::Keyboard.press(filtered_keys) sleep 0.5 end alias press_key key_press # Wrapper of mouse operation def mouse_move(x, y) RFormSpec::Mouse.move_to(x, y) end def mouse_click(x, y) RFormSpec::Mouse.click(x, y) end # standard open file dialog def open_file_dialog(title, filepath) wait_and_focus_window(title) dialog = RFormSpec::OpenFileDialog.new(title) dialog.enter_filepath(filepath) sleep 1 dialog.click_open end #TODO: save as file dialog # helper # Try the operation up to specified timeout (in seconds), and sleep given interval (in seconds). # Error will be ignored until timeout # Example # try_for { click_link('waiting')} # try_for (10, 2) { click_button('Search' } # try to click the 'Search' button upto 10 seconds, try every 2 seconds # try_for { click_button('Search' } def try_for(timeout = 30, polling_interval = 1, &block) start_time = Time.now last_error = nil until (duration = Time.now - start_time) > timeout begin yield last_error = nil return true rescue => e last_error = e end sleep polling_interval end raise "Timeout after #{duration.to_i} seconds with error: #{last_error}." if last_error raise "Timeout after #{duration.to_i} seconds." end end end diff --git a/lib/rformspec/window.rb b/lib/rformspec/window.rb index 5c34e0d..bfbc80c 100644 --- a/lib/rformspec/window.rb +++ b/lib/rformspec/window.rb @@ -1,130 +1,130 @@ require File.dirname(__FILE__) + "/driver" require File.dirname(__FILE__) + "/control" module RFormSpec class Window < BaseControl attr_accessor :title, :text, :class_list ## # title : page title, depends autoit options, might use as substring match or exact match # text: some text in window for further identifing the window # options: # present => true | false, already there # wait_timeout: wiat for maxium seconds if not active, throw error # (active: means the window becomes the active window) # otherwise, inside window class, using focus_window methods def initialize(title, text = '', options = {:present => false, :wait_timeout => 0}) # for some windows, the title might change depends when it is invoked if title.class == Array title.each { |a_title| @title = a_title @text = text if text timeout = options[:wait_timeout] result = driver.WinWaitActive(@title, @text, timeout) return if result != 0 } raise "timeout while waiting for window: #{self.to_s}" end @title = title - puts "[DEBUG ] setting title => #{@title}" + # puts "[DEBUG ] setting title => #{@title}" @text = text if text # useful when ID changes timeout = options[:wait_timeout] if options[:present] result = driver.WinActivate(@title, @text) raise "window not found: #{self.to_s}" if result == 0 elsif timeout && timeout.to_i > 1 then result = driver.WinWaitActive(@title, @text, timeout) raise "timeout while waiting for window: #{self.to_s}" if result == 0 end end def focus driver.WinActivate(@title, @text) end def close driver.WinClose(@title, @text) end def exists? driver.WinExists(@title, @text) end def get_text driver.WinGetText(@title, @text) end def get_class_list driver.WinGetClassList(@title, @text) end def set_control_text(control_id, new_text) BaseControl.new(self, control_id).set_text(new_text) end def click_button(btn_id) Button.new(self, btn_id).click end def show_dropdown(combo_id) combo = ComboBox.new(self, combo_id) combo.show_dropdown combo end def hide_dropdown(combo_id) combo = ComboBox.new(self, combo_id) combo.hide_dropdown combo end def focus_control(ctrl_id) BaseControl.new(self, ctrl_id).focus end def send_control_text(ctrl_id, text) BaseControl.new(self, ctrl_id).send_text(text) end def get_control_text(ctrl_id) BaseControl.new(self, ctrl_id).get_text end #Not fully verified yet def statusbar_text driver.StatusbarGetText(@title) end def pixel_color(x,y) driver.PixelGetColor(x,y) end alias pixel_colour pixel_color alias get_pixel_colour pixel_color alias get_pixel_color pixel_color def to_s "Window{title => '#{@title}', text=>'#{@text}'}" end # a list def button(button_id) RFormSpec::Button.new(self, button_id) end # return the class match by name def get_class(name) @class_list = get_class_list @class_list.select {|x| x.include?(name)}.collect{|y| y.strip} end end end
zhimin/rformspec
76ff11e420c4f5491d6e63860770d585a2693bf6
add more rwebspec utils
diff --git a/CHANGELOG b/CHANGELOG index 8a8f91d..565ff8a 100755 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,53 +1,57 @@ CHANGELOG ========= +0.5 (2012-7) +- TestWise IDE support +- add RWebSpec utils methods such as try_until +- wait_and focus_window is optmized 0.4.1 (2012-6) - add get_class() to find class by name, useful for identify control + instance 0.4 (2011-10) - Change Window class: not wait for active by default - using global variable reference to AutoIt3 OLE - New AutoIt class - Examples update 0.3.2 Add option in Window class to wait to focus window (default) 0.3.1 (2010-08) ===== Activate window not currently in focus == 0.3 (2009-10-27) Renamed to RFormSpec == 0.2.0 (2007-12-18) - add convenient methods in Driver - add a commonly used dialog class: open file dialog, save as file dialog - add filtered key to support 'Alt+', 'Ctrl+' == 0.1.3 (2007-04-18) New features: - Support window with various titles depends on invoking conditions == 0.1.2 (2007-02-26) New features: - Add ListView support - Add Label support Others: - code reformating == 0.1.1 (2006-11-29) New features: - replace keyboard.* with RFormUnit::Keyboard.* - replace mouse.* with RFormUnit::Mouse.* - replace process.* with RFormUnit::Process.* == 0.1.0 (2006-11-28) initial release diff --git a/Rakefile b/Rakefile index 8ced560..3447ee2 100755 --- a/Rakefile +++ b/Rakefile @@ -1,63 +1,63 @@ require 'rubygems' require 'rake/testtask' require 'rake/rdoctask' require 'rake/gempackagetask' $:.unshift(File.dirname(__FILE__) + "/lib") require 'rformspec' desc "Default task" task :default => [ :clean, :test , :gem] desc "Clean generated files" task :clean do rm_rf 'pkg' rm_rf 'docs/rdoc' end # run the unit tests Rake::TestTask.new("test") { |t| t.test_files = FileList['test/test*.rb'] t.verbose= true } # Generate the RDoc documentation Rake::RDocTask.new { |rdoc| rdoc.rdoc_dir = 'docs/rdoc' rdoc.title = 'rformspec' rdoc.template = "#{ENV['template']}.rb" if ENV['template'] rdoc.rdoc_files.include('README') rdoc.rdoc_files.include('lib/rformspec.rb') rdoc.rdoc_files.include('lib/rformspec/*.rb') } spec = Gem::Specification.new do |s| s.platform= Gem::Platform::CURRENT s.name = "rformspec" - s.version = "0.4.1" + s.version = "0.5.0" s.summary = "An wrap of AUTOIT3 for functional testing of Windows form applications" # s.description = "" s.author = "Zhimin Zhan" s.email = "[email protected]" s.homepage= "http://github.com/zhimin/rformspec" # s.rubyforge_project = "" s.has_rdoc = true s.requirements << 'none' s.require_path = "lib" s.autorequire = "rformspec" s.files = [ "Rakefile", "README", "CHANGELOG", "MIT-LICENSE" ] # s.files = s.files + Dir.glob( "bin/**/*" ).delete_if { |item| item.include?( "\.svn" ) } s.files = s.files + Dir.glob( "ext/**/*" ).delete_if { |item| item.include?( "\.svn" ) } s.files = s.files + Dir.glob( "lib/**/*" ).delete_if { |item| item.include?( "\.svn" ) } s.files = s.files + Dir.glob( "test/**/*" ).delete_if { |item| item.include?( "\.svn" ) } s.files = s.files + Dir.glob( "sample/**/*" ).delete_if { |item| item.include?( "\.svn" ) } s.files = s.files + Dir.glob( "docs/**/*" ).delete_if { |item| item.include?( "\.svn" ) } end Rake::GemPackageTask.new(spec) do |pkg| pkg.need_zip = true end diff --git a/lib/rformspec/control.rb b/lib/rformspec/control.rb index 7f6cc60..0d2f794 100644 --- a/lib/rformspec/control.rb +++ b/lib/rformspec/control.rb @@ -1,161 +1,160 @@ require File.dirname(__FILE__) + "/driver" - module RFormSpec class BaseControl include Driver attr_accessor :parent_win, :control_id def initialize(win, ctrl_id) @parent_win = win @control_id = ctrl_id end def set_text(new_text) driver.ControlSetText(@parent_win.title, @parent_win.text, @control_id, new_text) end def send_text(text) driver.ControlSend(@parent_win.title, @parent_win.text, @control_id, text) end alias send_keys send_text def get_text driver.ControlGetText(@parent_win.title, @parent_win.text, @control_id) end def focus driver.ControlFocus(@parent_win.title, @parent_win.text, @control_id) end def is_enabled? ret = driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "IsEnabled" ,"") ret == 1 or ret == "1" end def is_visible? ret = driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "IsVisible" ,"") ret == 1 or ret == "1" end def click driver.ControlClick(@parent_win.title, @parent_win.text, @control_id) end end class TextBox < BaseControl end class Label < BaseControl end class CheckBox < BaseControl def check driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "Check" ,"") end def uncheck driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "UnCheck" ,"") end def is_checked? driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "IsChecked" ,"") == 1 end end class RadioButton < BaseControl def check driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "Check" ,"") end def uncheck driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "UnCheck" ,"") end def is_checked? driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "IsChecked" ,"") == 1 end end class ComboBox < BaseControl def show_dropdown driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "ShowDropDown" ,"") end def hide_dropdown driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "HideDropDown" ,"") end def select_option(option) driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "SelectString", option) end def find_option(option) driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "FindString", option) end def set_selection(ref) driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "SetCurrentSelection", ref) end end class Button < BaseControl end class Tab < BaseControl def current driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "CurrentTab" , "") end end class ListView < BaseControl def item_count result = driver.ControlListView(@parent_win.title, @parent_win.text, @control_id, "GetItemCount" , "", "").to_i result ? result.to_i : 0 end # row and column index starts from 0, def get_item_text(row, col = 0) driver.ControlListView(@parent_win.title, @parent_win.text, @control_id, "GetText" , "#{row}", col) end # can't use select, as it is Ruby keyword def highlight(row_start, row_end = nil) row_end ||= row_start driver.ControlListView(@parent_win.title, @parent_win.text, @control_id, "Select" , "#{row_start}", "#{row_end}") end def de_highlight(row_start, row_end = nil) row_end ||= row_start driver.ControlListView(@parent_win.title, @parent_win.text, @control_id, "DeSelect" , "#{row_start}", "#{row_end}") end alias de_select de_highlight def subitem_count result = driver.ControlListView(@parent_win.title, @parent_win.text, @control_id, "GetSubItemCount" , "", "").to_i result ? result.to_i : 0 end def select_all driver.ControlListView(@parent_win.title, @parent_win.text, @control_id, "SelectAll" , "", "") end def is_selected?(row) 1 == driver.ControlListView(@parent_win.title, @parent_win.text, @control_id, "IsSelected" , "#{row}", "") end end end diff --git a/lib/rformspec/driver.rb b/lib/rformspec/driver.rb index d568ca9..7bbb68c 100644 --- a/lib/rformspec/driver.rb +++ b/lib/rformspec/driver.rb @@ -1,72 +1,118 @@ require 'win32ole' +require File.join(File.dirname(__FILE__), "testwise_plugin.rb") + module RFormSpec module Driver + include TestWisePlugin + def driver + dump_caller_stack return $a3 if $a3 return RFormSpec::AutoIt.init end def wait_for_window(win, timeout=30) driver.WinWait(win.title, win.text, timeout * 1000) - win end - def wait_and_focus_window(title, text="", timeout=30) - driver.WinWaitActive(title, text, timeout * 1000) + def wait_and_focus_window(title, text="", timeout=5) + try_for(timeout) { + found_window = driver.WinExists(title, text) + puts "[DEBUG] found window => |#{found_window}|" + raise "Window '#{title}' not found" unless found_window.to_i == 1 + } driver.WinActivate(title, text) + sleep 0.5 + # check whether suceed + puts "[DEBUG] => |#{driver.WinActive(title, text)}|" + if driver.WinActive(title, text).to_i != 1 + raise "Failed to make window '#{title}' active" + end + end def window_exists?(title) driver.WinExists(title) > 0 end def focus_window(title) driver.WinActivate(title) end def close_window(title) driver.WinClose(title) end # wrapper of keyboard operations def key_press(keys) + dump_caller_stack + if keys =~ /^Ctrl\+([A-Z])$/ filtered_keys = "^+#{$1}" elsif keys =~ /^Ctrl\+Shift\+([A-Z])$/ filtered_keys = "^+#{$1.downcase}" elsif keys =~ /^Alt+([A-Z])$/ filtered_keys = "!+#{$1}" elsif keys =~ /^Alt\+Shift\+([a-z])$/ filtered_keys = "!+#{$1.downcase}" else filtered_keys = keys end filtered_keys = keys.gsub("Alt+", "!+").gsub("Ctrl+", "^+") RFormSpec::Keyboard.press(filtered_keys) sleep 0.5 end alias press_key key_press # Wrapper of mouse operation def mouse_move(x, y) RFormSpec::Mouse.move_to(x, y) end def mouse_click(x, y) RFormSpec::Mouse.click(x, y) end # standard open file dialog def open_file_dialog(title, filepath) wait_and_focus_window(title) dialog = RFormSpec::OpenFileDialog.new(title) dialog.enter_filepath(filepath) sleep 1 dialog.click_open end #TODO: save as file dialog + + + + # helper + # Try the operation up to specified timeout (in seconds), and sleep given interval (in seconds). + # Error will be ignored until timeout + # Example + # try_for { click_link('waiting')} + # try_for (10, 2) { click_button('Search' } # try to click the 'Search' button upto 10 seconds, try every 2 seconds + # try_for { click_button('Search' } + def try_for(timeout = 30, polling_interval = 1, &block) + start_time = Time.now + + last_error = nil + until (duration = Time.now - start_time) > timeout + begin + yield + last_error = nil + return true + rescue => e + last_error = e + end + sleep polling_interval + end + + raise "Timeout after #{duration.to_i} seconds with error: #{last_error}." if last_error + raise "Timeout after #{duration.to_i} seconds." + end + end end diff --git a/lib/rformspec/testwise_plugin.rb b/lib/rformspec/testwise_plugin.rb new file mode 100644 index 0000000..0b6992e --- /dev/null +++ b/lib/rformspec/testwise_plugin.rb @@ -0,0 +1,92 @@ +require 'socket' + +MAX_MESSAGE_LENGTH = 8192 # < 10K +$testwise_support = true + +module RFormSpec + module TestWisePlugin + + def debug(message) + if $RUN_IN_TESTWISE && message + the_sent_msg = message.to_s + if the_sent_msg.size > MAX_MESSAGE_LENGTH + the_sent_msg = the_sent_msg[0..MAX_MESSAGE_LENGTH] + "..." + end + connect_to_testwise(" DEBUG", the_sent_msg + "\r\n") + end + end + + + # Support of iTest to ajust the intervals between keystroke/mouse operations + def operation_delay + begin + if $TESTWISE_OPERATION_DELAY && $TESTWISE_OPERATION_DELAY > 0 && + $TESTWISE_OPERATION_DELAY && $TESTWISE_OPERATION_DELAY < 30000 then # max 30 seconds + sleep($TESTWISE_OPERATION_DELAY / 1000) + end + + while $TESTWISE_PAUSE + debug("Paused, waiting ...") + sleep 1 + end + rescue => e + puts "Error on delaying: #{e}" + # ignore + end + end + + def notify_screenshot_location(image_file_path) + connect_to_testwise(" SHOT", image_file_path) + end + + # find out the line (and file) the execution is on, and notify iTest via Socket + def dump_caller_stack + return unless $TESTWISE_TRACE_EXECUTION + begin + trace_lines = [] + trace_file = nil + found_first_spec_reference = false + caller.each_with_index do |position, idx| + next unless position =~ /\A(.*?):(\d+)/ + trace_file = $1 + if trace_file =~ /(_spec|_test|_rwebspec)\.rb\s*$/ + found_first_spec_reference = true + trace_lines << position + break + end + trace_lines << position + break if trace_file =~ /example\/example_methods\.rb$/ or trace_file =~ /example\/example_group_methods\.rb$/ + break if trace_lines.size > 10 + # TODO: send multiple trace to be parse with pages.rb + # break if trace_file =~ /example\/example_methods\.rb$/ or trace_file =~ /example\/example_group_methods\.rb$/ or trace_file =~ /driver\.rb$/ or trace_file =~ /timeout\.rb$/ # don't include rspec or ruby trace + end + + # (trace_file.include?("_spec.rb") || trace_file.include?("_rwebspec.rb") || trace_file.include?("_test.rb") || trace_file.include?("_cmd.rb")) + if !trace_lines.empty? + connect_to_testwise(" TRACE", trace_lines.reverse.join("|")) + end + + rescue => e + puts "failed to capture log: #{e}" + end + end + + + def connect_to_testwise (message_type, body) + begin + the_message = message_type + "|" + body + if @last_message == the_message then # ignore the message same as preivous one + return + end + itest_port = $TESTWISE_TRACE_PORT || 7025 + itest_socket = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0) + itest_socket.connect(Socket.pack_sockaddr_in(itest_port, '127.0.0.1')) + itest_socket.puts(the_message) + @last_message = the_message + itest_socket.close + rescue => e + end + end + + end +end \ No newline at end of file diff --git a/lib/rformspec/window.rb b/lib/rformspec/window.rb index 72cc887..5c34e0d 100644 --- a/lib/rformspec/window.rb +++ b/lib/rformspec/window.rb @@ -1,129 +1,130 @@ require File.dirname(__FILE__) + "/driver" require File.dirname(__FILE__) + "/control" module RFormSpec class Window < BaseControl attr_accessor :title, :text, :class_list ## # title : page title, depends autoit options, might use as substring match or exact match # text: some text in window for further identifing the window # options: # present => true | false, already there # wait_timeout: wiat for maxium seconds if not active, throw error # (active: means the window becomes the active window) # otherwise, inside window class, using focus_window methods def initialize(title, text = '', options = {:present => false, :wait_timeout => 0}) # for some windows, the title might change depends when it is invoked if title.class == Array title.each { |a_title| @title = a_title @text = text if text timeout = options[:wait_timeout] result = driver.WinWaitActive(@title, @text, timeout) return if result != 0 } raise "timeout while waiting for window: #{self.to_s}" end @title = title puts "[DEBUG ] setting title => #{@title}" @text = text if text # useful when ID changes timeout = options[:wait_timeout] if options[:present] result = driver.WinActivate(@title, @text) raise "window not found: #{self.to_s}" if result == 0 elsif timeout && timeout.to_i > 1 then result = driver.WinWaitActive(@title, @text, timeout) raise "timeout while waiting for window: #{self.to_s}" if result == 0 end end def focus driver.WinActivate(@title, @text) end def close driver.WinClose(@title, @text) end def exists? driver.WinExists(@title, @text) end def get_text driver.WinGetText(@title, @text) end def get_class_list driver.WinGetClassList(@title, @text) end def set_control_text(control_id, new_text) BaseControl.new(self, control_id).set_text(new_text) end def click_button(btn_id) Button.new(self, btn_id).click end def show_dropdown(combo_id) combo = ComboBox.new(self, combo_id) combo.show_dropdown combo end def hide_dropdown(combo_id) combo = ComboBox.new(self, combo_id) combo.hide_dropdown combo end def focus_control(ctrl_id) BaseControl.new(self, ctrl_id).focus end def send_control_text(ctrl_id, text) BaseControl.new(self, ctrl_id).send_text(text) end def get_control_text(ctrl_id) BaseControl.new(self, ctrl_id).get_text end #Not fully verified yet def statusbar_text driver.StatusbarGetText(@title) end def pixel_color(x,y) driver.PixelGetColor(x,y) end alias pixel_colour pixel_color alias get_pixel_colour pixel_color alias get_pixel_color pixel_color def to_s "Window{title => '#{@title}', text=>'#{@text}'}" end # a list def button(button_id) RFormSpec::Button.new(self, button_id) end # return the class match by name def get_class(name) @class_list = get_class_list @class_list.select {|x| x.include?(name)}.collect{|y| y.strip} end + end end
zhimin/rformspec
1399d9f14663dae2ad2423e92c79c700574c30cb
add get_class
diff --git a/CHANGELOG b/CHANGELOG index 7db9d5e..8a8f91d 100755 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,49 +1,53 @@ CHANGELOG ========= +0.4.1 (2012-6) + +- add get_class() to find class by name, useful for identify control + instance + 0.4 (2011-10) - Change Window class: not wait for active by default - using global variable reference to AutoIt3 OLE - New AutoIt class - Examples update 0.3.2 Add option in Window class to wait to focus window (default) 0.3.1 (2010-08) ===== Activate window not currently in focus == 0.3 (2009-10-27) Renamed to RFormSpec == 0.2.0 (2007-12-18) - add convenient methods in Driver - add a commonly used dialog class: open file dialog, save as file dialog - add filtered key to support 'Alt+', 'Ctrl+' == 0.1.3 (2007-04-18) New features: - Support window with various titles depends on invoking conditions == 0.1.2 (2007-02-26) New features: - Add ListView support - Add Label support Others: - code reformating == 0.1.1 (2006-11-29) New features: - replace keyboard.* with RFormUnit::Keyboard.* - replace mouse.* with RFormUnit::Mouse.* - replace process.* with RFormUnit::Process.* == 0.1.0 (2006-11-28) initial release diff --git a/Rakefile b/Rakefile index 67d6609..8ced560 100755 --- a/Rakefile +++ b/Rakefile @@ -1,63 +1,63 @@ require 'rubygems' require 'rake/testtask' require 'rake/rdoctask' require 'rake/gempackagetask' $:.unshift(File.dirname(__FILE__) + "/lib") require 'rformspec' desc "Default task" task :default => [ :clean, :test , :gem] desc "Clean generated files" task :clean do rm_rf 'pkg' rm_rf 'docs/rdoc' end # run the unit tests Rake::TestTask.new("test") { |t| t.test_files = FileList['test/test*.rb'] t.verbose= true } # Generate the RDoc documentation Rake::RDocTask.new { |rdoc| rdoc.rdoc_dir = 'docs/rdoc' rdoc.title = 'rformspec' rdoc.template = "#{ENV['template']}.rb" if ENV['template'] rdoc.rdoc_files.include('README') rdoc.rdoc_files.include('lib/rformspec.rb') rdoc.rdoc_files.include('lib/rformspec/*.rb') } spec = Gem::Specification.new do |s| s.platform= Gem::Platform::CURRENT s.name = "rformspec" - s.version = "0.4" + s.version = "0.4.1" s.summary = "An wrap of AUTOIT3 for functional testing of Windows form applications" # s.description = "" s.author = "Zhimin Zhan" s.email = "[email protected]" s.homepage= "http://github.com/zhimin/rformspec" # s.rubyforge_project = "" s.has_rdoc = true s.requirements << 'none' s.require_path = "lib" s.autorequire = "rformspec" s.files = [ "Rakefile", "README", "CHANGELOG", "MIT-LICENSE" ] # s.files = s.files + Dir.glob( "bin/**/*" ).delete_if { |item| item.include?( "\.svn" ) } s.files = s.files + Dir.glob( "ext/**/*" ).delete_if { |item| item.include?( "\.svn" ) } s.files = s.files + Dir.glob( "lib/**/*" ).delete_if { |item| item.include?( "\.svn" ) } s.files = s.files + Dir.glob( "test/**/*" ).delete_if { |item| item.include?( "\.svn" ) } s.files = s.files + Dir.glob( "sample/**/*" ).delete_if { |item| item.include?( "\.svn" ) } s.files = s.files + Dir.glob( "docs/**/*" ).delete_if { |item| item.include?( "\.svn" ) } end Rake::GemPackageTask.new(spec) do |pkg| pkg.need_zip = true end diff --git a/lib/rformspec/control.rb b/lib/rformspec/control.rb index 8141126..7f6cc60 100644 --- a/lib/rformspec/control.rb +++ b/lib/rformspec/control.rb @@ -1,162 +1,161 @@ require File.dirname(__FILE__) + "/driver" module RFormSpec class BaseControl include Driver attr_accessor :parent_win, :control_id def initialize(win, ctrl_id) @parent_win = win @control_id = ctrl_id end def set_text(new_text) driver.ControlSetText(@parent_win.title, @parent_win.text, @control_id, new_text) end def send_text(text) driver.ControlSend(@parent_win.title, @parent_win.text, @control_id, text) end alias send_keys send_text def get_text driver.ControlGetText(@parent_win.title, @parent_win.text, @control_id) end def focus driver.ControlFocus(@parent_win.title, @parent_win.text, @control_id) end def is_enabled? ret = driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "IsEnabled" ,"") ret == 1 or ret == "1" end def is_visible? ret = driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "IsVisible" ,"") ret == 1 or ret == "1" end def click driver.ControlClick(@parent_win.title, @parent_win.text, @control_id) end end class TextBox < BaseControl end class Label < BaseControl end class CheckBox < BaseControl def check driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "Check" ,"") end def uncheck driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "UnCheck" ,"") end def is_checked? driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "IsChecked" ,"") == 1 end end class RadioButton < BaseControl def check driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "Check" ,"") end def uncheck driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "UnCheck" ,"") end def is_checked? driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "IsChecked" ,"") == 1 end end class ComboBox < BaseControl def show_dropdown driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "ShowDropDown" ,"") end def hide_dropdown driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "HideDropDown" ,"") end def select_option(option) - puts "XXX => #{@parent_win.title}|#{@parent_win.text}|#{@control_id}|#{option}|" driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "SelectString", option) end def find_option(option) driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "FindString", option) end def set_selection(ref) driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "SetCurrentSelection", ref) end end class Button < BaseControl end class Tab < BaseControl def current driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "CurrentTab" , "") end end class ListView < BaseControl def item_count result = driver.ControlListView(@parent_win.title, @parent_win.text, @control_id, "GetItemCount" , "", "").to_i result ? result.to_i : 0 end # row and column index starts from 0, def get_item_text(row, col = 0) driver.ControlListView(@parent_win.title, @parent_win.text, @control_id, "GetText" , "#{row}", col) end # can't use select, as it is Ruby keyword def highlight(row_start, row_end = nil) row_end ||= row_start driver.ControlListView(@parent_win.title, @parent_win.text, @control_id, "Select" , "#{row_start}", "#{row_end}") end def de_highlight(row_start, row_end = nil) row_end ||= row_start driver.ControlListView(@parent_win.title, @parent_win.text, @control_id, "DeSelect" , "#{row_start}", "#{row_end}") end alias de_select de_highlight def subitem_count result = driver.ControlListView(@parent_win.title, @parent_win.text, @control_id, "GetSubItemCount" , "", "").to_i result ? result.to_i : 0 end def select_all driver.ControlListView(@parent_win.title, @parent_win.text, @control_id, "SelectAll" , "", "") end def is_selected?(row) 1 == driver.ControlListView(@parent_win.title, @parent_win.text, @control_id, "IsSelected" , "#{row}", "") end end end
zhimin/rformspec
cabeb9131d8f7fca1407cd95a64a916dc3c5249b
add get class
diff --git a/lib/rformspec/control.rb b/lib/rformspec/control.rb index b55e0bb..8141126 100644 --- a/lib/rformspec/control.rb +++ b/lib/rformspec/control.rb @@ -1,153 +1,162 @@ require File.dirname(__FILE__) + "/driver" module RFormSpec class BaseControl include Driver attr_accessor :parent_win, :control_id def initialize(win, ctrl_id) @parent_win = win @control_id = ctrl_id end def set_text(new_text) driver.ControlSetText(@parent_win.title, @parent_win.text, @control_id, new_text) end def send_text(text) driver.ControlSend(@parent_win.title, @parent_win.text, @control_id, text) end alias send_keys send_text def get_text driver.ControlGetText(@parent_win.title, @parent_win.text, @control_id) end def focus driver.ControlFocus(@parent_win.title, @parent_win.text, @control_id) end def is_enabled? ret = driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "IsEnabled" ,"") ret == 1 or ret == "1" end def is_visible? ret = driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "IsVisible" ,"") ret == 1 or ret == "1" end def click driver.ControlClick(@parent_win.title, @parent_win.text, @control_id) end end class TextBox < BaseControl end class Label < BaseControl end class CheckBox < BaseControl def check driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "Check" ,"") end def uncheck driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "UnCheck" ,"") end def is_checked? driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "IsChecked" ,"") == 1 end end class RadioButton < BaseControl def check driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "Check" ,"") end def uncheck driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "UnCheck" ,"") end def is_checked? driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "IsChecked" ,"") == 1 end end class ComboBox < BaseControl def show_dropdown driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "ShowDropDown" ,"") end def hide_dropdown driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "HideDropDown" ,"") end def select_option(option) - driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "SelectString" , option) + puts "XXX => #{@parent_win.title}|#{@parent_win.text}|#{@control_id}|#{option}|" + driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "SelectString", option) end + def find_option(option) + driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "FindString", option) + end + + def set_selection(ref) + driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "SetCurrentSelection", ref) + end + end class Button < BaseControl end class Tab < BaseControl def current driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "CurrentTab" , "") end end class ListView < BaseControl def item_count result = driver.ControlListView(@parent_win.title, @parent_win.text, @control_id, "GetItemCount" , "", "").to_i result ? result.to_i : 0 end # row and column index starts from 0, def get_item_text(row, col = 0) driver.ControlListView(@parent_win.title, @parent_win.text, @control_id, "GetText" , "#{row}", col) end # can't use select, as it is Ruby keyword def highlight(row_start, row_end = nil) row_end ||= row_start driver.ControlListView(@parent_win.title, @parent_win.text, @control_id, "Select" , "#{row_start}", "#{row_end}") end def de_highlight(row_start, row_end = nil) row_end ||= row_start driver.ControlListView(@parent_win.title, @parent_win.text, @control_id, "DeSelect" , "#{row_start}", "#{row_end}") end alias de_select de_highlight def subitem_count result = driver.ControlListView(@parent_win.title, @parent_win.text, @control_id, "GetSubItemCount" , "", "").to_i result ? result.to_i : 0 end def select_all driver.ControlListView(@parent_win.title, @parent_win.text, @control_id, "SelectAll" , "", "") end def is_selected?(row) 1 == driver.ControlListView(@parent_win.title, @parent_win.text, @control_id, "IsSelected" , "#{row}", "") end end end diff --git a/lib/rformspec/window.rb b/lib/rformspec/window.rb index be4c87f..72cc887 100644 --- a/lib/rformspec/window.rb +++ b/lib/rformspec/window.rb @@ -1,114 +1,129 @@ require File.dirname(__FILE__) + "/driver" require File.dirname(__FILE__) + "/control" module RFormSpec class Window < BaseControl - attr_accessor :title, :text + attr_accessor :title, :text, :class_list ## # title : page title, depends autoit options, might use as substring match or exact match # text: some text in window for further identifing the window # options: # present => true | false, already there # wait_timeout: wiat for maxium seconds if not active, throw error # (active: means the window becomes the active window) # otherwise, inside window class, using focus_window methods def initialize(title, text = '', options = {:present => false, :wait_timeout => 0}) # for some windows, the title might change depends when it is invoked if title.class == Array title.each { |a_title| @title = a_title @text = text if text timeout = options[:wait_timeout] result = driver.WinWaitActive(@title, @text, timeout) return if result != 0 } raise "timeout while waiting for window: #{self.to_s}" end - + @title = title + puts "[DEBUG ] setting title => #{@title}" @text = text if text + # useful when ID changes + timeout = options[:wait_timeout] if options[:present] result = driver.WinActivate(@title, @text) raise "window not found: #{self.to_s}" if result == 0 elsif timeout && timeout.to_i > 1 then result = driver.WinWaitActive(@title, @text, timeout) raise "timeout while waiting for window: #{self.to_s}" if result == 0 end + end def focus driver.WinActivate(@title, @text) end def close driver.WinClose(@title, @text) end def exists? driver.WinExists(@title, @text) end def get_text driver.WinGetText(@title, @text) end + def get_class_list + driver.WinGetClassList(@title, @text) + end + def set_control_text(control_id, new_text) BaseControl.new(self, control_id).set_text(new_text) end def click_button(btn_id) Button.new(self, btn_id).click end def show_dropdown(combo_id) combo = ComboBox.new(self, combo_id) combo.show_dropdown combo end def hide_dropdown(combo_id) combo = ComboBox.new(self, combo_id) combo.hide_dropdown combo end def focus_control(ctrl_id) BaseControl.new(self, ctrl_id).focus end def send_control_text(ctrl_id, text) BaseControl.new(self, ctrl_id).send_text(text) end def get_control_text(ctrl_id) BaseControl.new(self, ctrl_id).get_text end #Not fully verified yet def statusbar_text driver.StatusbarGetText(@title) end def pixel_color(x,y) driver.PixelGetColor(x,y) end alias pixel_colour pixel_color alias get_pixel_colour pixel_color alias get_pixel_color pixel_color - def to_s "Window{title => '#{@title}', text=>'#{@text}'}" end # a list def button(button_id) RFormSpec::Button.new(self, button_id) end + + # return the class match by name + def get_class(name) + @class_list = get_class_list + @class_list.select {|x| x.include?(name)}.collect{|y| y.strip} + end + + end end
zhimin/rformspec
8cbc517938e20f2eac7a1d452fbdce140a770aed
examples updates
diff --git a/CHANGELOG b/CHANGELOG index 6091b5b..7db9d5e 100755 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,42 +1,49 @@ CHANGELOG ========= + +0.4 (2011-10) +- Change Window class: not wait for active by default +- using global variable reference to AutoIt3 OLE +- New AutoIt class +- Examples update + 0.3.2 Add option in Window class to wait to focus window (default) 0.3.1 (2010-08) ===== Activate window not currently in focus == 0.3 (2009-10-27) Renamed to RFormSpec == 0.2.0 (2007-12-18) - add convenient methods in Driver - add a commonly used dialog class: open file dialog, save as file dialog - add filtered key to support 'Alt+', 'Ctrl+' == 0.1.3 (2007-04-18) New features: - Support window with various titles depends on invoking conditions == 0.1.2 (2007-02-26) New features: - Add ListView support - Add Label support Others: - code reformating == 0.1.1 (2006-11-29) New features: - replace keyboard.* with RFormUnit::Keyboard.* - replace mouse.* with RFormUnit::Mouse.* - replace process.* with RFormUnit::Process.* == 0.1.0 (2006-11-28) initial release diff --git a/Rakefile b/Rakefile index a386e79..67d6609 100755 --- a/Rakefile +++ b/Rakefile @@ -1,63 +1,63 @@ require 'rubygems' require 'rake/testtask' require 'rake/rdoctask' require 'rake/gempackagetask' $:.unshift(File.dirname(__FILE__) + "/lib") require 'rformspec' desc "Default task" task :default => [ :clean, :test , :gem] desc "Clean generated files" task :clean do rm_rf 'pkg' rm_rf 'docs/rdoc' end # run the unit tests Rake::TestTask.new("test") { |t| t.test_files = FileList['test/test*.rb'] t.verbose= true } # Generate the RDoc documentation Rake::RDocTask.new { |rdoc| rdoc.rdoc_dir = 'docs/rdoc' rdoc.title = 'rformspec' rdoc.template = "#{ENV['template']}.rb" if ENV['template'] rdoc.rdoc_files.include('README') rdoc.rdoc_files.include('lib/rformspec.rb') rdoc.rdoc_files.include('lib/rformspec/*.rb') } spec = Gem::Specification.new do |s| s.platform= Gem::Platform::CURRENT s.name = "rformspec" - s.version = "0.3.3" + s.version = "0.4" s.summary = "An wrap of AUTOIT3 for functional testing of Windows form applications" # s.description = "" s.author = "Zhimin Zhan" s.email = "[email protected]" s.homepage= "http://github.com/zhimin/rformspec" # s.rubyforge_project = "" s.has_rdoc = true s.requirements << 'none' s.require_path = "lib" s.autorequire = "rformspec" s.files = [ "Rakefile", "README", "CHANGELOG", "MIT-LICENSE" ] # s.files = s.files + Dir.glob( "bin/**/*" ).delete_if { |item| item.include?( "\.svn" ) } s.files = s.files + Dir.glob( "ext/**/*" ).delete_if { |item| item.include?( "\.svn" ) } s.files = s.files + Dir.glob( "lib/**/*" ).delete_if { |item| item.include?( "\.svn" ) } s.files = s.files + Dir.glob( "test/**/*" ).delete_if { |item| item.include?( "\.svn" ) } s.files = s.files + Dir.glob( "sample/**/*" ).delete_if { |item| item.include?( "\.svn" ) } s.files = s.files + Dir.glob( "docs/**/*" ).delete_if { |item| item.include?( "\.svn" ) } end Rake::GemPackageTask.new(spec) do |pkg| pkg.need_zip = true end diff --git a/lib/rformspec.rb b/lib/rformspec.rb index d908254..d835c43 100644 --- a/lib/rformspec.rb +++ b/lib/rformspec.rb @@ -1,15 +1,41 @@ #*********************************************************** #* Copyright (c) 2006, Zhimin Zhan. #* Distributed open-source, see full license in MIT-LICENSE #*********************************************************** # Extra full path to load libraries require File.dirname(__FILE__) + "/rformspec/driver" require File.dirname(__FILE__) + "/rformspec/control" require File.dirname(__FILE__) + "/rformspec/mouse" require File.dirname(__FILE__) + "/rformspec/keyboard" require File.dirname(__FILE__) + "/rformspec/window" require File.dirname(__FILE__) + "/rformspec/open_file_dialog" require File.dirname(__FILE__) + "/rformspec/saveas_file_dialog" require File.dirname(__FILE__) + "/rformspec/process" require File.dirname(__FILE__) + "/rformspec/form_testcase" + +module RFormSpec + + class AutoIt + + def self.init + $a3 = WIN32OLE.new('AutoItX3.Control') + + $a3.AutoItSetOption("WinSearchChildren", 1); # Search Children window as well + $a3.AutoItSetOption("WinTitleMatchMode", 2); + + $a3.AutoItSetOption("CaretCoordMode", 0); + $a3.AutoItSetOption("ColorMode", 1); + $a3.AutoItSetOption("MouseCoordMode", 0); + $a3.AutoItSetOption("PixelCoordMode", 0); + $a3.AutoItSetOption("SendKeyDelay", 15) + return $a3 + end + + def self.set_option(key, value) + self.init if $a3.nil? + $a3.AutoItSetOption(key, value) + end + + end +end diff --git a/lib/rformspec/driver.rb b/lib/rformspec/driver.rb index fd2a584..d568ca9 100644 --- a/lib/rformspec/driver.rb +++ b/lib/rformspec/driver.rb @@ -1,91 +1,72 @@ require 'win32ole' module RFormSpec module Driver - def self.init_autoit - $a3 = WIN32OLE.new('AutoItX3.Control') - - $a3.AutoItSetOption("WinSearchChildren", 1); # Search Children window as well - $a3.AutoItSetOption("WinTitleMatchMode", 2); - - $a3.AutoItSetOption("CaretCoordMode", 0); - $a3.AutoItSetOption("ColorMode", 1); - $a3.AutoItSetOption("MouseCoordMode", 0); - $a3.AutoItSetOption("PixelCoordMode", 0); - $a3.AutoItSetOption("SendKeyDelay", 15) - return $a3 - end - def driver return $a3 if $a3 - self.init_autoit - end - - def self.set_autoit_option(key, value) - self.init_autoit if $a3.nil? - $a3.AutoItSetOption(key, value) + return RFormSpec::AutoIt.init end def wait_for_window(win, timeout=30) driver.WinWait(win.title, win.text, timeout * 1000) win end def wait_and_focus_window(title, text="", timeout=30) driver.WinWaitActive(title, text, timeout * 1000) driver.WinActivate(title, text) end def window_exists?(title) driver.WinExists(title) > 0 end def focus_window(title) driver.WinActivate(title) end def close_window(title) driver.WinClose(title) end # wrapper of keyboard operations def key_press(keys) if keys =~ /^Ctrl\+([A-Z])$/ filtered_keys = "^+#{$1}" elsif keys =~ /^Ctrl\+Shift\+([A-Z])$/ filtered_keys = "^+#{$1.downcase}" elsif keys =~ /^Alt+([A-Z])$/ filtered_keys = "!+#{$1}" elsif keys =~ /^Alt\+Shift\+([a-z])$/ filtered_keys = "!+#{$1.downcase}" else filtered_keys = keys end filtered_keys = keys.gsub("Alt+", "!+").gsub("Ctrl+", "^+") RFormSpec::Keyboard.press(filtered_keys) sleep 0.5 end alias press_key key_press # Wrapper of mouse operation def mouse_move(x, y) RFormSpec::Mouse.move_to(x, y) end def mouse_click(x, y) RFormSpec::Mouse.click(x, y) end # standard open file dialog def open_file_dialog(title, filepath) wait_and_focus_window(title) dialog = RFormSpec::OpenFileDialog.new(title) dialog.enter_filepath(filepath) sleep 1 dialog.click_open end #TODO: save as file dialog end end diff --git a/lib/rformspec/window.rb b/lib/rformspec/window.rb index ea8baea..be4c87f 100644 --- a/lib/rformspec/window.rb +++ b/lib/rformspec/window.rb @@ -1,103 +1,114 @@ require File.dirname(__FILE__) + "/driver" require File.dirname(__FILE__) + "/control" module RFormSpec class Window < BaseControl attr_accessor :title, :text - - def initialize(title, text = '', timeout = 10, options = {:wait => true}) + + ## + # title : page title, depends autoit options, might use as substring match or exact match + # text: some text in window for further identifing the window + # options: + # present => true | false, already there + # wait_timeout: wiat for maxium seconds if not active, throw error + # (active: means the window becomes the active window) + # otherwise, inside window class, using focus_window methods + def initialize(title, text = '', options = {:present => false, :wait_timeout => 0}) # for some windows, the title might change depends when it is invoked if title.class == Array title.each { |a_title| @title = a_title @text = text if text + timeout = options[:wait_timeout] result = driver.WinWaitActive(@title, @text, timeout) return if result != 0 } raise "timeout while waiting for window: #{self.to_s}" end @title = title @text = text if text - if options[:wait] then - result = driver.WinWaitActive(@title, @text, timeout) - else + timeout = options[:wait_timeout] + if options[:present] result = driver.WinActivate(@title, @text) + raise "window not found: #{self.to_s}" if result == 0 + elsif timeout && timeout.to_i > 1 then + result = driver.WinWaitActive(@title, @text, timeout) + raise "timeout while waiting for window: #{self.to_s}" if result == 0 end - raise "timeout while waiting for window: #{self.to_s}" if result == 0 end def focus driver.WinActivate(@title, @text) end def close driver.WinClose(@title, @text) end def exists? driver.WinExists(@title, @text) end def get_text driver.WinGetText(@title, @text) end def set_control_text(control_id, new_text) BaseControl.new(self, control_id).set_text(new_text) end def click_button(btn_id) Button.new(self, btn_id).click end def show_dropdown(combo_id) combo = ComboBox.new(self, combo_id) combo.show_dropdown combo end def hide_dropdown(combo_id) combo = ComboBox.new(self, combo_id) combo.hide_dropdown combo end def focus_control(ctrl_id) BaseControl.new(self, ctrl_id).focus end def send_control_text(ctrl_id, text) BaseControl.new(self, ctrl_id).send_text(text) end def get_control_text(ctrl_id) BaseControl.new(self, ctrl_id).get_text end #Not fully verified yet def statusbar_text driver.StatusbarGetText(@title) end def pixel_color(x,y) driver.PixelGetColor(x,y) end alias pixel_colour pixel_color alias get_pixel_colour pixel_color alias get_pixel_color pixel_color def to_s "Window{title => '#{@title}', text=>'#{@text}'}" end # a list def button(button_id) RFormSpec::Button.new(self, button_id) end end end diff --git a/sample/calc.rb b/sample/calc.rb deleted file mode 100644 index 7e2fe1d..0000000 --- a/sample/calc.rb +++ /dev/null @@ -1,25 +0,0 @@ -require 'rformspec' - -module Calc - include RFormSpec::Driver - - def start_calc - RFormSpec::Process.run("calc.exe") - RFormSpec::Window.new('Calculator') - end - - def find_existing_calc_win - if window_exists?("Calculator") - focus_window('Calculator') - RFormSpec::Window.new('Calculator') - else - nil - end - end - - def quit_calc - focus_window('Calculator') - RFormSpec::Keyboard.press("!{F4}") - end - -end diff --git a/sample/calc_spec.rb b/sample/calc_spec.rb deleted file mode 100644 index e77d413..0000000 --- a/sample/calc_spec.rb +++ /dev/null @@ -1,16 +0,0 @@ -require File.dirname(__FILE__) + '/rspec_calc' - -context "Calculator" do - - setup do - end - - specify "Multiple works" do - @calc_win.click_button('127') #3 - @calc_win.click_button('91') #* - @calc_win.click_button('131') #7 - @calc_win.click_button('112') #= - @calc_win.get_control_text('403').should == '21. ' - end - -end diff --git a/sample/form_calculator/calc_helper.rb b/sample/form_calculator/calc_helper.rb new file mode 100644 index 0000000..eed719e --- /dev/null +++ b/sample/form_calculator/calc_helper.rb @@ -0,0 +1,68 @@ +require 'rformspec' + +module CalcSpecHelper + include RFormSpec::Driver + + def run_calc + RFormSpec::Process.run("calc.exe") + @calc_win = RFormSpec::Window.new('Calculator', "", :wait_timeout => 2) + end + alias start_calc run_calc + + def exit_calc + @calc_win.close + end + + def click_3 + @calc_win.click_button('127') #3 + sleep(0.5) + end + + def click_7 + @calc_win.click_button('131') #7 + sleep(0.5) + end + + def click_add + @calc_win.click_button('92') # + + sleep(0.5) + end + alias click_plus click_add + + def click_multiply + @calc_win.click_button('91') #* + sleep(0.5) + end + + def click_equals + @calc_win.click_button('112') #= + sleep(0.5) + end + + def result + @calc_win.get_control_text('403') + end + alias get_result result + + def perform(actions) + methods_to_call = actions.collect { |act| + case act + when '+': + 'plus' + when '-': + 'minus' + when '*': + 'multiply' + when '=': + 'equals' + else + act + end + } + + methods_to_call.each { |met| + self.send("click_#{met}") + } + get_result + end +end diff --git a/sample/form_calculator/calc_spec.rb b/sample/form_calculator/calc_spec.rb new file mode 100644 index 0000000..66fc064 --- /dev/null +++ b/sample/form_calculator/calc_spec.rb @@ -0,0 +1,33 @@ +require File.join(File.dirname(__FILE__), 'calc_helper') + +describe 'Simple Calculation' do + include CalcSpecHelper + + before (:all) do + start_calc + end + + after(:all) do + exit_calc + end + + it "can do adding" do + click_3 + click_add + click_7 + click_equals + result.should == "10. " + end + + it "can do muliply" do + click_3 + click_multiply + click_7 + click_equals + result.should == "21. " + end + + it "if you think above is good, we can make it more readable" do + perform(%w(3 + 7 =)).should == "10. " + end +end diff --git a/sample/form_calculator/calculator.tpr b/sample/form_calculator/calculator.tpr new file mode 100644 index 0000000..1578327 --- /dev/null +++ b/sample/form_calculator/calculator.tpr @@ -0,0 +1,27 @@ +<?xml version="1.1" encoding="US-ASCII"?> +<project> + <name>Calculator</name> + <default_browser></default_browser> + <test_framework>Watir</test_framework> + <syntax_framework>RWebSpec</syntax_framework> + <environments> + </environments> + <exclude_dirs></exclude_dirs> + <exclude_files></exclude_files> + <test_named_as>specification</test_named_as> + <spec_template></spec_template> + <page_template></page_template> + <storywise_url></storywise_url> + <jira_url></jira_url> + <jira_project></jira_project> + <jira_login></jira_login> + <jira_password></jira_password> + <heart_beat> + <spec_suite></spec_suite> + <environment></environment> + <start_time></start_time> + <repeat></repeat> + <end_repeat></end_repeat> + <emails></emails> + </heart_beat> +</project> diff --git a/sample/form_calculator/calculator.tws b/sample/form_calculator/calculator.tws new file mode 100644 index 0000000..e0ef60c --- /dev/null +++ b/sample/form_calculator/calculator.tws @@ -0,0 +1,13 @@ +<?xml version="1.1" encoding="US-ASCII"?> +<workspace> + <project_name>Calculator</project_name> + <project_file>C:\work\testwise\samples\form_calculator\calculator.tpr</project_file> + <opened_files> + <entry name="$PROJECT_DIR$/calc_spec.rb"/> + </opened_files> + <recent_files> + <entry name="$PROJECT_DIR$/calc_spec.rb"/> + </recent_files> + <test_suites> + </test_suites> +</workspace> diff --git a/sample/mouse.rb b/sample/mouse.rb index 05815fb..8ea9d96 100644 --- a/sample/mouse.rb +++ b/sample/mouse.rb @@ -1,19 +1,19 @@ require 'rubygems' require 'rformspec' -RFormSpec::Driver.set_autoit_option("WinSearchChildren", 1) +RFormSpec::AutoIt.set_option("WinSearchChildren", 1) class TextWiseWindow < RFormSpec::Window - def initialize(title = "TextWise", text = "", timeout = 10, opts = {}) - super(title, text, timeout, opts) + def initialize(title = "TextWise", text = "", opts = {}) + super(title, text, opts) wait_and_focus_window(title) end end -win = TextWiseWindow.new("TextWise", "", 10, :wait => false) +win = TextWiseWindow.new("TextWise", "", :present => true) win.mouse_move(90, 30) #win.mouse_click(241, 645) win.mouse_click(220, 640) #RFormSpec::Mouse.move_to(200, 40) diff --git a/sample/notepad.rb b/sample/notepad.rb index 25394a4..3b89652 100755 --- a/sample/notepad.rb +++ b/sample/notepad.rb @@ -1,19 +1,19 @@ require 'rformspec' include RFormSpec::Driver RFormSpec::Process.run("C:\\WINDOWS\\NOTEPAD.EXE") -notepad_win = RFormSpec::Window.new('Untitled - Notepad') +notepad_win = RFormSpec::Window.new('Untitled - Notepad', "", :wait_timeout => 2) RFormSpec::Keyboard.type("Hello, Missing No. 5.{ENTER}1 2 3 4 6 7 8 9 10{ENTER}") RFormSpec::Keyboard.press("+{UP 2}") # move cursor up and insert the missing number RFormSpec::Mouse.move_to(70, 65) RFormSpec::Mouse.click RFormSpec::Keyboard.type("5 ") notepad_win.close notepad_confirm_dialog = RFormSpec::Window.new('Notepad', 'The text') notepad_confirm_dialog.focus RFormSpec::Button.new(notepad_confirm_dialog, "7").click diff --git a/sample/notepad1.rb b/sample/notepad1.rb index e0140bb..edbd004 100644 --- a/sample/notepad1.rb +++ b/sample/notepad1.rb @@ -1,14 +1,14 @@ require 'rformspec' include RFormSpec::Driver RFormSpec::Process.run("C:\\WINDOWS\\NOTEPAD.EXE") -notepad_win = RFormSpec::Window.new('Untitled - Notepad') +notepad_win = RFormSpec::Window.new('Untitled - Notepad', "", :wait_timeout => 2) RFormSpec::Keyboard.type("Hello from Notepad, {ENTER}1 2 3 4 5 6 7 8 9 10{ENTER}") sleep(0.5) RFormSpec::Keyboard.press("+{UP 2}") sleep(0.5) notepad_win.close -notepad_confirm_dialog = RFormSpec::Window.new('Notepad', 'No') +notepad_confirm_dialog = RFormSpec::Window.new('Notepad', 'No', :wait_timeout => 1) notepad_confirm_dialog.click_button('&No') diff --git a/sample/rspec_calc.rb b/sample/rspec_calc.rb deleted file mode 100644 index e81a671..0000000 --- a/sample/rspec_calc.rb +++ /dev/null @@ -1,24 +0,0 @@ -require File.dirname(__FILE__) + '/calc' - -class RSpecCalc - include Calc - - def setup - init # initialize - @calc_win = find_existing_calc_win - if @calc_win.nil? - @calc_win = start_calc - end - end -end - -module Spec - module Runner - class Context - def before_context_eval - #inherit RSpecCalc # inherit not supported after 0.8 - inherit_context_eval_module_from RSpecCalc - end - end - end -end diff --git a/sample/test_calc.rb b/sample/test_calc.rb index 01fc906..5836a98 100755 --- a/sample/test_calc.rb +++ b/sample/test_calc.rb @@ -1,23 +1,33 @@ require 'rformspec' class CalcTest < RFormSpec::FormTestCase + include RFormSpec::Driver def setup + RFormSpec::AutoIt.init + + if window_exists?("Calculator") + focus_window('Calculator') + RFormSpec::Window.new('Calculator') + else RFormSpec::Process.run("calc.exe") - @calc_win = RFormSpec::Window.new('Calculator') + end + + @calc_win = RFormSpec::Window.new('Calculator', "", :wait_timeout => 2) end def teardown - @calc_win.close + # @calc_win.close end def test_multiple @calc_win.click_button('127') #3 @calc_win.click_button('91') #* @calc_win.click_button('131') #7 @calc_win.click_button('112') #= + sleep 1 assert_equal "21. ", @calc_win.get_control_text('403') end end
zhimin/rformspec
ad841985040497d7da2ab9fd5aab13022b20876a
use global $a3
diff --git a/lib/rformspec/driver.rb b/lib/rformspec/driver.rb index 3011afd..fd2a584 100644 --- a/lib/rformspec/driver.rb +++ b/lib/rformspec/driver.rb @@ -1,82 +1,91 @@ require 'win32ole' module RFormSpec module Driver - def init - driver - end - - def driver - return $a3 if $a3 - + def self.init_autoit $a3 = WIN32OLE.new('AutoItX3.Control') $a3.AutoItSetOption("WinSearchChildren", 1); # Search Children window as well + $a3.AutoItSetOption("WinTitleMatchMode", 2); $a3.AutoItSetOption("CaretCoordMode", 0); $a3.AutoItSetOption("ColorMode", 1); $a3.AutoItSetOption("MouseCoordMode", 0); $a3.AutoItSetOption("PixelCoordMode", 0); $a3.AutoItSetOption("SendKeyDelay", 15) return $a3 + end + + def driver + return $a3 if $a3 + self.init_autoit end def self.set_autoit_option(key, value) - init if $a3.nil? + self.init_autoit if $a3.nil? $a3.AutoItSetOption(key, value) end def wait_for_window(win, timeout=30) driver.WinWait(win.title, win.text, timeout * 1000) win end def wait_and_focus_window(title, text="", timeout=30) driver.WinWaitActive(title, text, timeout * 1000) + driver.WinActivate(title, text) end def window_exists?(title) driver.WinExists(title) > 0 end def focus_window(title) driver.WinActivate(title) end def close_window(title) driver.WinClose(title) end # wrapper of keyboard operations def key_press(keys) if keys =~ /^Ctrl\+([A-Z])$/ filtered_keys = "^+#{$1}" elsif keys =~ /^Ctrl\+Shift\+([A-Z])$/ filtered_keys = "^+#{$1.downcase}" elsif keys =~ /^Alt+([A-Z])$/ filtered_keys = "!+#{$1}" elsif keys =~ /^Alt\+Shift\+([a-z])$/ filtered_keys = "!+#{$1.downcase}" else filtered_keys = keys end filtered_keys = keys.gsub("Alt+", "!+").gsub("Ctrl+", "^+") RFormSpec::Keyboard.press(filtered_keys) sleep 0.5 end alias press_key key_press + # Wrapper of mouse operation + def mouse_move(x, y) + RFormSpec::Mouse.move_to(x, y) + end + + def mouse_click(x, y) + RFormSpec::Mouse.click(x, y) + end + # standard open file dialog def open_file_dialog(title, filepath) wait_and_focus_window(title) dialog = RFormSpec::OpenFileDialog.new(title) dialog.enter_filepath(filepath) sleep 1 dialog.click_open end #TODO: save as file dialog - end end diff --git a/lib/rformspec/window.rb b/lib/rformspec/window.rb index 5e4766e..ea8baea 100644 --- a/lib/rformspec/window.rb +++ b/lib/rformspec/window.rb @@ -1,104 +1,103 @@ require File.dirname(__FILE__) + "/driver" require File.dirname(__FILE__) + "/control" module RFormSpec - class Window < BaseControl attr_accessor :title, :text def initialize(title, text = '', timeout = 10, options = {:wait => true}) # for some windows, the title might change depends when it is invoked if title.class == Array title.each { |a_title| @title = a_title @text = text if text result = driver.WinWaitActive(@title, @text, timeout) return if result != 0 } raise "timeout while waiting for window: #{self.to_s}" end @title = title @text = text if text if options[:wait] then result = driver.WinWaitActive(@title, @text, timeout) else result = driver.WinActivate(@title, @text) end raise "timeout while waiting for window: #{self.to_s}" if result == 0 end def focus driver.WinActivate(@title, @text) end def close driver.WinClose(@title, @text) end def exists? driver.WinExists(@title, @text) end def get_text driver.WinGetText(@title, @text) end def set_control_text(control_id, new_text) BaseControl.new(self, control_id).set_text(new_text) end def click_button(btn_id) Button.new(self, btn_id).click end def show_dropdown(combo_id) combo = ComboBox.new(self, combo_id) combo.show_dropdown combo end def hide_dropdown(combo_id) combo = ComboBox.new(self, combo_id) combo.hide_dropdown combo end def focus_control(ctrl_id) BaseControl.new(self, ctrl_id).focus end def send_control_text(ctrl_id, text) BaseControl.new(self, ctrl_id).send_text(text) end def get_control_text(ctrl_id) BaseControl.new(self, ctrl_id).get_text end #Not fully verified yet def statusbar_text driver.StatusbarGetText(@title) end def pixel_color(x,y) driver.PixelGetColor(x,y) end alias pixel_colour pixel_color alias get_pixel_colour pixel_color alias get_pixel_color pixel_color def to_s "Window{title => '#{@title}', text=>'#{@text}'}" end # a list def button(button_id) RFormSpec::Button.new(self, button_id) end end end diff --git a/sample/mouse.rb b/sample/mouse.rb new file mode 100644 index 0000000..05815fb --- /dev/null +++ b/sample/mouse.rb @@ -0,0 +1,19 @@ +require 'rubygems' +require 'rformspec' + +RFormSpec::Driver.set_autoit_option("WinSearchChildren", 1) + +class TextWiseWindow < RFormSpec::Window + def initialize(title = "TextWise", text = "", timeout = 10, opts = {}) + super(title, text, timeout, opts) + wait_and_focus_window(title) + end + +end + + +win = TextWiseWindow.new("TextWise", "", 10, :wait => false) +win.mouse_move(90, 30) +#win.mouse_click(241, 645) +win.mouse_click(220, 640) +#RFormSpec::Mouse.move_to(200, 40)
zhimin/rformspec
5a0cf311c5ea34df43e83d9db3152f55dd21a76c
global
diff --git a/Rakefile b/Rakefile index 62370c9..a386e79 100755 --- a/Rakefile +++ b/Rakefile @@ -1,63 +1,63 @@ require 'rubygems' require 'rake/testtask' require 'rake/rdoctask' require 'rake/gempackagetask' $:.unshift(File.dirname(__FILE__) + "/lib") require 'rformspec' desc "Default task" task :default => [ :clean, :test , :gem] desc "Clean generated files" task :clean do rm_rf 'pkg' rm_rf 'docs/rdoc' end # run the unit tests Rake::TestTask.new("test") { |t| t.test_files = FileList['test/test*.rb'] t.verbose= true } # Generate the RDoc documentation Rake::RDocTask.new { |rdoc| rdoc.rdoc_dir = 'docs/rdoc' rdoc.title = 'rformspec' rdoc.template = "#{ENV['template']}.rb" if ENV['template'] rdoc.rdoc_files.include('README') rdoc.rdoc_files.include('lib/rformspec.rb') rdoc.rdoc_files.include('lib/rformspec/*.rb') } spec = Gem::Specification.new do |s| s.platform= Gem::Platform::CURRENT s.name = "rformspec" - s.version = "0.3.2" + s.version = "0.3.3" s.summary = "An wrap of AUTOIT3 for functional testing of Windows form applications" # s.description = "" s.author = "Zhimin Zhan" s.email = "[email protected]" s.homepage= "http://github.com/zhimin/rformspec" # s.rubyforge_project = "" s.has_rdoc = true s.requirements << 'none' s.require_path = "lib" s.autorequire = "rformspec" s.files = [ "Rakefile", "README", "CHANGELOG", "MIT-LICENSE" ] # s.files = s.files + Dir.glob( "bin/**/*" ).delete_if { |item| item.include?( "\.svn" ) } s.files = s.files + Dir.glob( "ext/**/*" ).delete_if { |item| item.include?( "\.svn" ) } s.files = s.files + Dir.glob( "lib/**/*" ).delete_if { |item| item.include?( "\.svn" ) } s.files = s.files + Dir.glob( "test/**/*" ).delete_if { |item| item.include?( "\.svn" ) } s.files = s.files + Dir.glob( "sample/**/*" ).delete_if { |item| item.include?( "\.svn" ) } s.files = s.files + Dir.glob( "docs/**/*" ).delete_if { |item| item.include?( "\.svn" ) } end Rake::GemPackageTask.new(spec) do |pkg| pkg.need_zip = true end diff --git a/lib/rformspec/driver.rb b/lib/rformspec/driver.rb index 9bfab0b..3011afd 100644 --- a/lib/rformspec/driver.rb +++ b/lib/rformspec/driver.rb @@ -1,80 +1,82 @@ require 'win32ole' module RFormSpec module Driver def init driver end def driver - return @a3 if @a3 + return $a3 if $a3 - @a3 = WIN32OLE.new('AutoItX3.Control') + $a3 = WIN32OLE.new('AutoItX3.Control') - @a3.AutoItSetOption("CaretCoordMode", 0); - @a3.AutoItSetOption("ColorMode", 1); - @a3.AutoItSetOption("MouseCoordMode", 0); - @a3.AutoItSetOption("PixelCoordMode", 0); - @a3.AutoItSetOption("SendKeyDelay", 15) - return @a3 + $a3.AutoItSetOption("WinSearchChildren", 1); # Search Children window as well + + $a3.AutoItSetOption("CaretCoordMode", 0); + $a3.AutoItSetOption("ColorMode", 1); + $a3.AutoItSetOption("MouseCoordMode", 0); + $a3.AutoItSetOption("PixelCoordMode", 0); + $a3.AutoItSetOption("SendKeyDelay", 15) + return $a3 end - def set_autoit_option(key, value) - init if @a3.nil? - @a3.AutoItSetOption(key, value) + def self.set_autoit_option(key, value) + init if $a3.nil? + $a3.AutoItSetOption(key, value) end def wait_for_window(win, timeout=30) driver.WinWait(win.title, win.text, timeout * 1000) win end def wait_and_focus_window(title, text="", timeout=30) driver.WinWaitActive(title, text, timeout * 1000) end def window_exists?(title) driver.WinExists(title) > 0 end def focus_window(title) driver.WinActivate(title) end def close_window(title) driver.WinClose(title) end # wrapper of keyboard operations def key_press(keys) if keys =~ /^Ctrl\+([A-Z])$/ filtered_keys = "^+#{$1}" elsif keys =~ /^Ctrl\+Shift\+([A-Z])$/ filtered_keys = "^+#{$1.downcase}" elsif keys =~ /^Alt+([A-Z])$/ filtered_keys = "!+#{$1}" elsif keys =~ /^Alt\+Shift\+([a-z])$/ filtered_keys = "!+#{$1.downcase}" else filtered_keys = keys end filtered_keys = keys.gsub("Alt+", "!+").gsub("Ctrl+", "^+") RFormSpec::Keyboard.press(filtered_keys) sleep 0.5 end alias press_key key_press # standard open file dialog def open_file_dialog(title, filepath) wait_and_focus_window(title) dialog = RFormSpec::OpenFileDialog.new(title) dialog.enter_filepath(filepath) sleep 1 dialog.click_open end #TODO: save as file dialog end end
zhimin/rformspec
80afd94c76a4f66051b0bbff6f1bc0d6f9e0f6ca
bump to version 0.3.2
diff --git a/CHANGELOG b/CHANGELOG index 2bdcfb9..6091b5b 100755 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,39 +1,42 @@ CHANGELOG ========= +0.3.2 + +Add option in Window class to wait to focus window (default) 0.3.1 (2010-08) ===== Activate window not currently in focus == 0.3 (2009-10-27) Renamed to RFormSpec == 0.2.0 (2007-12-18) - add convenient methods in Driver - add a commonly used dialog class: open file dialog, save as file dialog - add filtered key to support 'Alt+', 'Ctrl+' == 0.1.3 (2007-04-18) New features: - Support window with various titles depends on invoking conditions == 0.1.2 (2007-02-26) New features: - Add ListView support - Add Label support Others: - code reformating == 0.1.1 (2006-11-29) New features: - replace keyboard.* with RFormUnit::Keyboard.* - replace mouse.* with RFormUnit::Mouse.* - replace process.* with RFormUnit::Process.* == 0.1.0 (2006-11-28) initial release diff --git a/Rakefile b/Rakefile index 4031a48..62370c9 100755 --- a/Rakefile +++ b/Rakefile @@ -1,63 +1,63 @@ require 'rubygems' require 'rake/testtask' require 'rake/rdoctask' require 'rake/gempackagetask' $:.unshift(File.dirname(__FILE__) + "/lib") require 'rformspec' desc "Default task" task :default => [ :clean, :test , :gem] desc "Clean generated files" task :clean do rm_rf 'pkg' rm_rf 'docs/rdoc' end # run the unit tests Rake::TestTask.new("test") { |t| t.test_files = FileList['test/test*.rb'] t.verbose= true } # Generate the RDoc documentation Rake::RDocTask.new { |rdoc| rdoc.rdoc_dir = 'docs/rdoc' rdoc.title = 'rformspec' rdoc.template = "#{ENV['template']}.rb" if ENV['template'] rdoc.rdoc_files.include('README') rdoc.rdoc_files.include('lib/rformspec.rb') rdoc.rdoc_files.include('lib/rformspec/*.rb') } spec = Gem::Specification.new do |s| s.platform= Gem::Platform::CURRENT s.name = "rformspec" - s.version = "0.3.1" + s.version = "0.3.2" s.summary = "An wrap of AUTOIT3 for functional testing of Windows form applications" # s.description = "" s.author = "Zhimin Zhan" s.email = "[email protected]" s.homepage= "http://github.com/zhimin/rformspec" # s.rubyforge_project = "" s.has_rdoc = true s.requirements << 'none' s.require_path = "lib" s.autorequire = "rformspec" s.files = [ "Rakefile", "README", "CHANGELOG", "MIT-LICENSE" ] # s.files = s.files + Dir.glob( "bin/**/*" ).delete_if { |item| item.include?( "\.svn" ) } s.files = s.files + Dir.glob( "ext/**/*" ).delete_if { |item| item.include?( "\.svn" ) } s.files = s.files + Dir.glob( "lib/**/*" ).delete_if { |item| item.include?( "\.svn" ) } s.files = s.files + Dir.glob( "test/**/*" ).delete_if { |item| item.include?( "\.svn" ) } s.files = s.files + Dir.glob( "sample/**/*" ).delete_if { |item| item.include?( "\.svn" ) } s.files = s.files + Dir.glob( "docs/**/*" ).delete_if { |item| item.include?( "\.svn" ) } end Rake::GemPackageTask.new(spec) do |pkg| pkg.need_zip = true end
zhimin/rformspec
0ef97ec16f4e1488a39e2666fb5823f739458c64
add option to wait in Window:
diff --git a/lib/rformspec/window.rb b/lib/rformspec/window.rb index 3190ef7..5e4766e 100644 --- a/lib/rformspec/window.rb +++ b/lib/rformspec/window.rb @@ -1,100 +1,104 @@ require File.dirname(__FILE__) + "/driver" require File.dirname(__FILE__) + "/control" module RFormSpec class Window < BaseControl attr_accessor :title, :text - def initialize(title, text = '', timeout = 10) + def initialize(title, text = '', timeout = 10, options = {:wait => true}) # for some windows, the title might change depends when it is invoked if title.class == Array title.each { |a_title| @title = a_title @text = text if text result = driver.WinWaitActive(@title, @text, timeout) return if result != 0 } raise "timeout while waiting for window: #{self.to_s}" end @title = title @text = text if text - result = driver.WinActivate(@title, @text) + if options[:wait] then + result = driver.WinWaitActive(@title, @text, timeout) + else + result = driver.WinActivate(@title, @text) + end raise "timeout while waiting for window: #{self.to_s}" if result == 0 end def focus driver.WinActivate(@title, @text) end def close driver.WinClose(@title, @text) end def exists? driver.WinExists(@title, @text) end def get_text driver.WinGetText(@title, @text) end def set_control_text(control_id, new_text) BaseControl.new(self, control_id).set_text(new_text) end def click_button(btn_id) Button.new(self, btn_id).click end def show_dropdown(combo_id) combo = ComboBox.new(self, combo_id) combo.show_dropdown combo end def hide_dropdown(combo_id) combo = ComboBox.new(self, combo_id) combo.hide_dropdown combo end def focus_control(ctrl_id) BaseControl.new(self, ctrl_id).focus end def send_control_text(ctrl_id, text) BaseControl.new(self, ctrl_id).send_text(text) end def get_control_text(ctrl_id) BaseControl.new(self, ctrl_id).get_text end #Not fully verified yet def statusbar_text driver.StatusbarGetText(@title) end def pixel_color(x,y) driver.PixelGetColor(x,y) end alias pixel_colour pixel_color alias get_pixel_colour pixel_color alias get_pixel_color pixel_color def to_s "Window{title => '#{@title}', text=>'#{@text}'}" end # a list def button(button_id) RFormSpec::Button.new(self, button_id) end end end
zhimin/rformspec
d9f36259ea6f161cfe405dd8ca634ec827663206
activate window not in focus
diff --git a/CHANGELOG b/CHANGELOG index 6bb5b6d..2bdcfb9 100755 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,35 +1,39 @@ CHANGELOG ========= +0.3.1 (2010-08) +===== +Activate window not currently in focus + == 0.3 (2009-10-27) Renamed to RFormSpec == 0.2.0 (2007-12-18) - add convenient methods in Driver - add a commonly used dialog class: open file dialog, save as file dialog - add filtered key to support 'Alt+', 'Ctrl+' == 0.1.3 (2007-04-18) New features: - Support window with various titles depends on invoking conditions == 0.1.2 (2007-02-26) New features: - Add ListView support - Add Label support Others: - code reformating == 0.1.1 (2006-11-29) New features: - replace keyboard.* with RFormUnit::Keyboard.* - replace mouse.* with RFormUnit::Mouse.* - replace process.* with RFormUnit::Process.* == 0.1.0 (2006-11-28) initial release diff --git a/Rakefile b/Rakefile index 7bee672..4031a48 100755 --- a/Rakefile +++ b/Rakefile @@ -1,63 +1,63 @@ require 'rubygems' require 'rake/testtask' require 'rake/rdoctask' require 'rake/gempackagetask' $:.unshift(File.dirname(__FILE__) + "/lib") require 'rformspec' desc "Default task" task :default => [ :clean, :test , :gem] desc "Clean generated files" task :clean do rm_rf 'pkg' rm_rf 'docs/rdoc' end # run the unit tests Rake::TestTask.new("test") { |t| t.test_files = FileList['test/test*.rb'] t.verbose= true } # Generate the RDoc documentation Rake::RDocTask.new { |rdoc| rdoc.rdoc_dir = 'docs/rdoc' rdoc.title = 'rformspec' rdoc.template = "#{ENV['template']}.rb" if ENV['template'] rdoc.rdoc_files.include('README') rdoc.rdoc_files.include('lib/rformspec.rb') rdoc.rdoc_files.include('lib/rformspec/*.rb') } spec = Gem::Specification.new do |s| s.platform= Gem::Platform::CURRENT s.name = "rformspec" - s.version = "0.3" + s.version = "0.3.1" s.summary = "An wrap of AUTOIT3 for functional testing of Windows form applications" # s.description = "" s.author = "Zhimin Zhan" - s.email = "[email protected]" - s.homepage= "http://www.zhimin.com/software/rformspec/" + s.email = "[email protected]" + s.homepage= "http://github.com/zhimin/rformspec" # s.rubyforge_project = "" s.has_rdoc = true s.requirements << 'none' s.require_path = "lib" s.autorequire = "rformspec" s.files = [ "Rakefile", "README", "CHANGELOG", "MIT-LICENSE" ] # s.files = s.files + Dir.glob( "bin/**/*" ).delete_if { |item| item.include?( "\.svn" ) } s.files = s.files + Dir.glob( "ext/**/*" ).delete_if { |item| item.include?( "\.svn" ) } s.files = s.files + Dir.glob( "lib/**/*" ).delete_if { |item| item.include?( "\.svn" ) } s.files = s.files + Dir.glob( "test/**/*" ).delete_if { |item| item.include?( "\.svn" ) } s.files = s.files + Dir.glob( "sample/**/*" ).delete_if { |item| item.include?( "\.svn" ) } s.files = s.files + Dir.glob( "docs/**/*" ).delete_if { |item| item.include?( "\.svn" ) } end Rake::GemPackageTask.new(spec) do |pkg| pkg.need_zip = true end diff --git a/lib/rformspec/window.rb b/lib/rformspec/window.rb index 2470ab5..3190ef7 100644 --- a/lib/rformspec/window.rb +++ b/lib/rformspec/window.rb @@ -1,100 +1,100 @@ require File.dirname(__FILE__) + "/driver" require File.dirname(__FILE__) + "/control" module RFormSpec - + class Window < BaseControl attr_accessor :title, :text - def initialize(title, text = '', timeout = 10) + def initialize(title, text = '', timeout = 10) # for some windows, the title might change depends when it is invoked - if title.class == Array - title.each { |a_title| + if title.class == Array + title.each { |a_title| @title = a_title - @text = text if text + @text = text if text result = driver.WinWaitActive(@title, @text, timeout) return if result != 0 } - raise "timeout while waiting for window: #{self.to_s}" + raise "timeout while waiting for window: #{self.to_s}" end - + @title = title @text = text if text - result = driver.WinWaitActive(@title, @text, timeout) - raise "timeout while waiting for window: #{self.to_s}" if result == 0 + result = driver.WinActivate(@title, @text) + raise "timeout while waiting for window: #{self.to_s}" if result == 0 end def focus driver.WinActivate(@title, @text) end def close driver.WinClose(@title, @text) end def exists? driver.WinExists(@title, @text) end def get_text driver.WinGetText(@title, @text) end def set_control_text(control_id, new_text) BaseControl.new(self, control_id).set_text(new_text) end - + def click_button(btn_id) Button.new(self, btn_id).click end def show_dropdown(combo_id) combo = ComboBox.new(self, combo_id) combo.show_dropdown combo end def hide_dropdown(combo_id) combo = ComboBox.new(self, combo_id) combo.hide_dropdown combo end def focus_control(ctrl_id) BaseControl.new(self, ctrl_id).focus end def send_control_text(ctrl_id, text) BaseControl.new(self, ctrl_id).send_text(text) end def get_control_text(ctrl_id) BaseControl.new(self, ctrl_id).get_text end #Not fully verified yet def statusbar_text driver.StatusbarGetText(@title) end - def pixel_color(x,y) + def pixel_color(x,y) driver.PixelGetColor(x,y) end alias pixel_colour pixel_color alias get_pixel_colour pixel_color alias get_pixel_color pixel_color - - + + def to_s "Window{title => '#{@title}', text=>'#{@text}'}" end - # a list - def button(button_id) - RFormSpec::Button.new(self, button_id) - end - + # a list + def button(button_id) + RFormSpec::Button.new(self, button_id) + end + end end
zhimin/rformspec
946dfe803a4d77d780e469e08ebfb3cd2edaef86
renamed to rformspec
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..088af20 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +pkg/* diff --git a/CHANGELOG b/CHANGELOG index 636fedc..91900ac 100755 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,30 +1,30 @@ -CHANGELOG -========= -== 0.2.0 (2007-12-18) - - add convenient methods in Driver - - add a commonly used dialog class: open file dialog, save as file dialog - - add filtered key to support 'Alt+', 'Ctrl+' - -== 0.1.3 (2007-04-18) - -New features: - - Support window with various titles depends on invoking conditions - -== 0.1.2 (2007-02-26) - -New features: - - Add ListView support - - Add Label support - -Others: - - code reformating - -== 0.1.1 (2006-11-29) - -New features: - - replace keyboard.* with RFormUnit::Keyboard.* - - replace mouse.* with RFormUnit::Mouse.* - - replace process.* with RFormUnit::Process.* - - -== 0.1.0 (2006-11-28) initial release +CHANGELOG +========= +== 0.2.0 (2007-12-18) +- add convenient methods in Driver +- add a commonly used dialog class: open file dialog, save as file dialog +- add filtered key to support 'Alt+', 'Ctrl+' + +== 0.1.3 (2007-04-18) + +New features: +- Support window with various titles depends on invoking conditions + +== 0.1.2 (2007-02-26) + +New features: +- Add ListView support +- Add Label support + +Others: +- code reformating + +== 0.1.1 (2006-11-29) + +New features: +- replace keyboard.* with RFormUnit::Keyboard.* +- replace mouse.* with RFormUnit::Mouse.* +- replace process.* with RFormUnit::Process.* + + +== 0.1.0 (2006-11-28) initial release diff --git a/README b/README index 7e2a642..2b7c8f2 100755 --- a/README +++ b/README @@ -1,30 +1,30 @@ -rFormUnit -========= - -rFormUnit is a simple framework for automated testing Windows Form applications. -It wraps AutoItX COM API to provide an alternative way to write an easy to use, -readable automated functional tests. - -Dependencies ------------- -* Ruby - http://rubyinstaller.rubyforge.org/wiki/wiki.pl (Version verified: ruby185-21.exe) -* AutoIt3 - http://www.autoitscript.com/autoit3/ (Version verified v3.2.2.0) - -Platform: MS Windows (of course) - -Install -------- -> gem install rformunit - -One minute tutorial -------------------- - - - -Copyrights ----------- -Free to use for any purposes. The software provided AS IS without any warranty whatsoever. - -Contact -------- -Zhimin Zhan, Agileway Pty Ltd. +rFormUnit +========= + +rFormUnit is a simple framework for automated testing Windows Form applications. +It wraps AutoItX COM API to provide an alternative way to write an easy to use, +readable automated functional tests. + +Dependencies +------------ +* Ruby - http://rubyinstaller.rubyforge.org/wiki/wiki.pl (Version verified: ruby185-21.exe) +* AutoIt3 - http://www.autoitscript.com/autoit3/ (Version verified v3.2.2.0) + +Platform: MS Windows (of course) + +Install +------- +> gem install rformunit + +One minute tutorial +------------------- + + + +Copyrights +---------- +Free to use for any purposes. The software provided AS IS without any warranty whatsoever. + +Contact +------- +Zhimin Zhan, Agileway Pty Ltd. diff --git a/Rakefile b/Rakefile index a5135dc..7bee672 100755 --- a/Rakefile +++ b/Rakefile @@ -1,65 +1,63 @@ -require 'rubygems' -require 'rake/testtask' -require 'rake/rdoctask' - -Gem::manage_gems -require 'rake/gempackagetask' - -$:.unshift(File.dirname(__FILE__) + "/lib") -require 'rformunit' - -desc "Default task" -task :default => [ :clean, :test , :gem] - -desc "Clean generated files" -task :clean do - rm_rf 'pkg' - rm_rf 'docs/rdoc' -end - -# run the unit tests -Rake::TestTask.new("test") { |t| - t.test_files = FileList['test/test*.rb'] - t.verbose= true -} - -# Generate the RDoc documentation -Rake::RDocTask.new { |rdoc| - rdoc.rdoc_dir = 'docs/rdoc' - rdoc.title = 'rformunit' - rdoc.template = "#{ENV['template']}.rb" if ENV['template'] - rdoc.rdoc_files.include('README') - rdoc.rdoc_files.include('lib/rformunit.rb') - rdoc.rdoc_files.include('lib/rformunit/*.rb') -} - -spec = Gem::Specification.new do |s| - s.platform= Gem::Platform::CURRENT - s.name = "rformunit" - s.version = "0.2.1" - s.summary = "An wrap of AUTOIT3 for functional testing of Windows form applications" - # s.description = "" - - s.author = "Zhimin Zhan" - s.email = "[email protected]" - s.homepage= "http://www.zhimin.com/software/rformunit/" - # s.rubyforge_project = "" - - s.has_rdoc = true - s.requirements << 'none' - s.require_path = "lib" - s.autorequire = "rformunit" - - s.files = [ "Rakefile", "README", "CHANGELOG", "MIT-LICENSE" ] - # s.files = s.files + Dir.glob( "bin/**/*" ).delete_if { |item| item.include?( "\.svn" ) } - s.files = s.files + Dir.glob( "ext/**/*" ).delete_if { |item| item.include?( "\.svn" ) } - s.files = s.files + Dir.glob( "lib/**/*" ).delete_if { |item| item.include?( "\.svn" ) } - s.files = s.files + Dir.glob( "test/**/*" ).delete_if { |item| item.include?( "\.svn" ) } - s.files = s.files + Dir.glob( "sample/**/*" ).delete_if { |item| item.include?( "\.svn" ) } - s.files = s.files + Dir.glob( "docs/**/*" ).delete_if { |item| item.include?( "\.svn" ) } - -end - -Rake::GemPackageTask.new(spec) do |pkg| - pkg.need_zip = true -end +require 'rubygems' +require 'rake/testtask' +require 'rake/rdoctask' +require 'rake/gempackagetask' + +$:.unshift(File.dirname(__FILE__) + "/lib") +require 'rformspec' + +desc "Default task" +task :default => [ :clean, :test , :gem] + +desc "Clean generated files" +task :clean do + rm_rf 'pkg' + rm_rf 'docs/rdoc' +end + +# run the unit tests +Rake::TestTask.new("test") { |t| + t.test_files = FileList['test/test*.rb'] + t.verbose= true +} + +# Generate the RDoc documentation +Rake::RDocTask.new { |rdoc| + rdoc.rdoc_dir = 'docs/rdoc' + rdoc.title = 'rformspec' + rdoc.template = "#{ENV['template']}.rb" if ENV['template'] + rdoc.rdoc_files.include('README') + rdoc.rdoc_files.include('lib/rformspec.rb') + rdoc.rdoc_files.include('lib/rformspec/*.rb') +} + +spec = Gem::Specification.new do |s| + s.platform= Gem::Platform::CURRENT + s.name = "rformspec" + s.version = "0.3" + s.summary = "An wrap of AUTOIT3 for functional testing of Windows form applications" + # s.description = "" + + s.author = "Zhimin Zhan" + s.email = "[email protected]" + s.homepage= "http://www.zhimin.com/software/rformspec/" + # s.rubyforge_project = "" + + s.has_rdoc = true + s.requirements << 'none' + s.require_path = "lib" + s.autorequire = "rformspec" + + s.files = [ "Rakefile", "README", "CHANGELOG", "MIT-LICENSE" ] + # s.files = s.files + Dir.glob( "bin/**/*" ).delete_if { |item| item.include?( "\.svn" ) } + s.files = s.files + Dir.glob( "ext/**/*" ).delete_if { |item| item.include?( "\.svn" ) } + s.files = s.files + Dir.glob( "lib/**/*" ).delete_if { |item| item.include?( "\.svn" ) } + s.files = s.files + Dir.glob( "test/**/*" ).delete_if { |item| item.include?( "\.svn" ) } + s.files = s.files + Dir.glob( "sample/**/*" ).delete_if { |item| item.include?( "\.svn" ) } + s.files = s.files + Dir.glob( "docs/**/*" ).delete_if { |item| item.include?( "\.svn" ) } + +end + +Rake::GemPackageTask.new(spec) do |pkg| + pkg.need_zip = true +end diff --git a/docs/index.html b/docs/index.html index 749b80f..a8db32b 100644 --- a/docs/index.html +++ b/docs/index.html @@ -1,185 +1,184 @@ -<html - <head> - <title>rFormUnit </title> - <meta http-equiv="content-type" content="text/html; charset=utf-8" /> - <link href="../../stylesheets/zhimin.css" media="screen" rel="Stylesheet" type="text/css" /> - <link href="../../stylesheets/local.css" media="screen" rel="Stylesheet" type="text/css" /> - -<style type="text/css" media="screen"> -BODY -{ - BACKGROUND-COLOR: #fffff0; - COLOR: #000000; - FONT-FAMILY: "Times New Roman", Times, serif -} - -.green { - background-color: #ECF3E1; - border:1px solid #C5DEA1; -} - -.orange{ - border:1px solid #E8A400; - background-color: #FFF4D8; - -</style> - -</head> - <body> - - <h3>What is rFormUnit?</h3> - <p>rFormUnit is a simple framework for automated testing <b>Windows Form</b> applications. It wraps <a href="http://www.autoitscript.com/autoit3/">AutoItX</a> COM API to provide an alternative way to write an easy to use, readable automated functional tests. - </p> - - <p>Current release: 0.1.1<br/> - &nbsp; <a href="releases/rformunit-0.1.1-mswin32.gem">rformunit-0.1.1-mswin32.gem</a> or from <a href="http://rubyforge.org/projects/rformunit/">rubyforge.org</a>, - - <!-- &nbsp; <a href="releases/changelog.txt">Change logs</a> <br/> --> - &nbsp; Documentation: <a href="rdoc/index.html">RDoc</a>, and Quick start guide below. - </p> - - <h3>Installation</h3> - - <p><b>Dependecies</b><br/> - &nbsp; &nbsp; Install <a href="http://rubyinstaller.rubyforge.org/wiki/wiki.pl">Ruby for windows</a><br/> - &nbsp; &nbsp; Install <a href="http://www.autoitscript.com/autoit3/">AutoIt3</a></p> - - <p>Using RubyGems: - <pre class="green">$ gem install rformunit</pre> - or download and install locally: - <pre class="green">$ gem install rformunit-0.1.0-mswin32.gem</pre> - </p> - - <h3>Quick start guide through examples</h3> - <ul> - <li><a href="#script">Run as automation scripts</a></li> - <li><a href="#test">Run as xUnit test cases</a></li> - <li><a href="#rspec">Run as RSpecs</a></li> - </ul> - <p>Check sample/*.rb for more examples.</p> - <a name="script"></a><h4>Run as automation scripts</h4> - <table width="100%" cellspacing="0" cellpadding="0"> - <tr bgcolor="#33CC33"> - <th align="left" width="50%">AutoIt3 Script</th> - <th align="left" width="50%">rFormUnit Script</th> - </tr> - <tr> - <td valign="top" nowrap="nowrap" class="orange" width="50%"> - <pre> - - - -Run("notepad.exe") -WinWaitActive("Untitled - Notepad") - -Send("Hello from Notepad.{ENTER}1 2 3{ENTER}") -Sleep(500) -Send("+{UP 2}") -Sleep(500) - -Send("!f") -Send("x") - -WinWaitActive("Notepad", "No") -Send("n") - - </pre> - </td> - - <td valign="top" nowrap="nowrap" class="green"> -<pre>require 'rformunit' - -include RFormUnit::Driver - -RFormUnit::Process.run("NOTEPAD.EXE") -notepad_win = RFormUnit::Window.new('Untitled - Notepad') -RFormUnit::Keyboard.type("Hello from Notepad, {ENTER}1 2 3 4 5 6 7 8 9 10{ENTER}") -sleep(0.5) -RFormUnit::Keyboard.press("+{UP 2}") -sleep(0.5) -notepad_win.close - -notepad_confirm_dialog = RFormUnit::Window.new('Notepad', 'No') -notepad_confirm_dialog.click_button('&No')</pre> - </td> - </tr> - </table> - - <a name="test"></a> - <div id="rformunit_test"> - <h4>rFormUnit Testcase</h4> -<pre class="green">require 'rformunit' - -class CalcTest &lt; RFormUnit::FormTestCase - def setup - RFormUnit::Process.run("calc.exe") - @calc_win = RFormUnit::Window.new('Calculator') - end - - def teardown - @calc_win.close - end - - def test_multiple - @calc_win.click_button('127') #3 - @calc_win.click_button('91') #* - @calc_win.click_button('131') #7 - @calc_win.click_button('112') #= - assert_equal "21. ", @calc_win.get_control_text('403') - end - -end</pre> - </div> - - <a name="rspec"></a><div id='rformunit_rspec'> - <h4>rFormUnit <a href="http://rspec.rubyforge.org/">RSpec</a></h4> - - <p><b>rspec_calc</b>: a spec runner to run rformunit based rspecs</p> - <pre class="green"> -require File.dirname(__FILE__) + '/calc' - -class RSpecCalc - include Calc - - def setup - init # initialize - @calc_win = find_existing_calc_win - if @calc_win.nil? - @calc_win = start_calc - end - end -end - -module Spec - module Runner - class Context - def before_context_eval - inherit RSpecCalc - end - end - end -end</pre> - - <p><b>calc_spec</b>: a rspec</p> - <pre class="green"> -require File.dirname(__FILE__) + '/rspec_calc' - -context "Calculator" do - - setup do - end - - specify "Multiple shall work" do - @calc_win.click_button('127') #3 - @calc_win.click_button('91') #* - @calc_win.click_button('131') #7 - @calc_win.click_button('112') #= - @calc_win.get_control_text('403').should == '21. ' - end - -end</pre> - - </div> - - </body> +<html + <head> + <title>rFormUnit </title> + <meta http-equiv="content-type" content="text/html; charset=utf-8" /> + <link href="../../stylesheets/zhimin.css" media="screen" rel="Stylesheet" type="text/css" /> + <link href="../../stylesheets/local.css" media="screen" rel="Stylesheet" type="text/css" /> + +<style type="text/css" media="screen"> +BODY +{ + BACKGROUND-COLOR: #fffff0; + COLOR: #000000; + FONT-FAMILY: "Times New Roman", Times, serif +} + +.green { + background-color: #ECF3E1; + border:1px solid #C5DEA1; +} + +.orange{ + border:1px solid #E8A400; + background-color: #FFF4D8; + +</style> + +</head> + <body> + + <h3>What is rFormUnit?</h3> + <p>rFormUnit is a simple framework for automated testing <b>Windows Form</b> applications. It wraps <a href="http://www.autoitscript.com/autoit3/">AutoItX</a> COM API to provide an alternative way to write an easy to use, readable automated functional tests. + </p> + + <p>Current release: 0.1.1<br/> + &nbsp; <a href="releases/rformunit-0.1.1-mswin32.gem">rformunit-0.1.1-mswin32.gem</a> or from <a href="http://rubyforge.org/projects/rformunit/">rubyforge.org</a>, + + <!-- &nbsp; <a href="releases/changelog.txt">Change logs</a> <br/> --> + &nbsp; Documentation: <a href="rdoc/index.html">RDoc</a>, and Quick start guide below. + </p> + + <h3>Installation</h3> + + <p><b>Dependecies</b><br/> + &nbsp; &nbsp; Install <a href="http://rubyinstaller.rubyforge.org/wiki/wiki.pl">Ruby for windows</a><br/> + &nbsp; &nbsp; Install <a href="http://www.autoitscript.com/autoit3/">AutoIt3</a></p> + + <p>Using RubyGems: + <pre class="green">$ gem install rformunit</pre> + or download and install locally: + <pre class="green">$ gem install rformunit-0.1.0-mswin32.gem</pre> + </p> + + <h3>Quick start guide through examples</h3> + <ul> + <li><a href="#script">Run as automation scripts</a></li> + <li><a href="#test">Run as xUnit test cases</a></li> + <li><a href="#rspec">Run as RSpecs</a></li> + </ul> + <p>Check sample/*.rb for more examples.</p> + <a name="script"></a><h4>Run as automation scripts</h4> + <table width="100%" cellspacing="0" cellpadding="0"> + <tr bgcolor="#33CC33"> + <th align="left" width="50%">AutoIt3 Script</th> + <th align="left" width="50%">rFormUnit Script</th> + </tr> + <tr> + <td valign="top" nowrap="nowrap" class="orange" width="50%"> + <pre> + + + +Run("notepad.exe") +WinWaitActive("Untitled - Notepad") + +Send("Hello from Notepad.{ENTER}1 2 3{ENTER}") +Sleep(500) +Send("+{UP 2}") +Sleep(500) + +Send("!f") +Send("x") + +WinWaitActive("Notepad", "No") +Send("n") + + </pre> + </td> + + <td valign="top" nowrap="nowrap" class="green"> +<pre>require 'rformunit' + +include RFormUnit::Driver + +RFormUnit::Process.run("NOTEPAD.EXE") +notepad_win = RFormUnit::Window.new('Untitled - Notepad') +RFormUnit::Keyboard.type("Hello from Notepad, {ENTER}1 2 3 4 5 6 7 8 9 10{ENTER}") +sleep(0.5) +RFormUnit::Keyboard.press("+{UP 2}") +sleep(0.5) +notepad_win.close + +notepad_confirm_dialog = RFormUnit::Window.new('Notepad', 'No') +notepad_confirm_dialog.click_button('&No')</pre> + </td> + </tr> + </table> + + <a name="test"></a> + <div id="rformunit_test"> + <h4>rFormUnit Testcase</h4> +<pre class="green">require 'rformunit' + +class CalcTest &lt; RFormUnit::FormTestCase + def setup + RFormUnit::Process.run("calc.exe") + @calc_win = RFormUnit::Window.new('Calculator') + end + + def teardown + @calc_win.close + end + + def test_multiple + @calc_win.click_button('127') #3 + @calc_win.click_button('91') #* + @calc_win.click_button('131') #7 + @calc_win.click_button('112') #= + assert_equal "21. ", @calc_win.get_control_text('403') + end + +end</pre> + </div> + + <a name="rspec"></a><div id='rformunit_rspec'> + <h4>rFormUnit <a href="http://rspec.rubyforge.org/">RSpec</a></h4> + <p><b>rspec_calc</b>: a spec runner to run rformunit based rspecs</p> + <pre class="green"> +require File.dirname(__FILE__) + '/calc' + +class RSpecCalc + include Calc + + def setup + init # initialize + @calc_win = find_existing_calc_win + if @calc_win.nil? + @calc_win = start_calc + end + end +end + +module Spec + module Runner + class Context + def before_context_eval + inherit RSpecCalc + end + end + end +end</pre> + + <p><b>calc_spec</b>: a rspec</p> + <pre class="green"> +require File.dirname(__FILE__) + '/rspec_calc' + +context "Calculator" do + + setup do + end + + specify "Multiple shall work" do + @calc_win.click_button('127') #3 + @calc_win.click_button('91') #* + @calc_win.click_button('131') #7 + @calc_win.click_button('112') #= + @calc_win.get_control_text('403').should == '21. ' + end + +end</pre> + + </div> + + </body> </html> \ No newline at end of file diff --git a/lib/ext/rspec_rformunit.rb b/lib/ext/rspec_rformunit.rb index 74ec69a..0d2f49d 100755 --- a/lib/ext/rspec_rformunit.rb +++ b/lib/ext/rspec_rformunit.rb @@ -1,46 +1,46 @@ -class RSpecFormUnit - include YourModule # change to your module containing common methods used in your specs - - def setup - @driver = GUIDriver.new() - - @driver.AutoItSetOption("CaretCoordMode",0); - @driver.AutoItSetOption("ColorMode",1); - @driver.AutoItSetOption("MouseCoordMode",0); - @driver.AutoItSetOption("PixelCoordMode",0); - @driver.AutoItSetOption("SendKeyDelay", 20) - - #Add it yourself - - end - - def timeout_check_equal(duration, expected, &block) - execute_ok = false - duration.times do - sleep(1) - text = instance_eval(&block) - execute_ok = true and break if (text == expected) - end - execute_ok.should == true - end - - def timeout_check_include?(duration, expected, &block) - execute_ok = false - duration.times do - sleep(1) - text = instance_eval(&block) - execute_ok = true and break if text and text.include?(expected) - end - execute_ok.should == true - end -end - -module Spec - module Runner - class Context - def before_context_eval - inherit RSpecFormUnit - end - end - end -end +class RSpecFormUnit + include YourModule # change to your module containing common methods used in your specs + + def setup + @driver = GUIDriver.new() + + @driver.AutoItSetOption("CaretCoordMode",0); + @driver.AutoItSetOption("ColorMode",1); + @driver.AutoItSetOption("MouseCoordMode",0); + @driver.AutoItSetOption("PixelCoordMode",0); + @driver.AutoItSetOption("SendKeyDelay", 20) + + #Add it yourself + + end + + def timeout_check_equal(duration, expected, &block) + execute_ok = false + duration.times do + sleep(1) + text = instance_eval(&block) + execute_ok = true and break if (text == expected) + end + execute_ok.should == true + end + + def timeout_check_include?(duration, expected, &block) + execute_ok = false + duration.times do + sleep(1) + text = instance_eval(&block) + execute_ok = true and break if text and text.include?(expected) + end + execute_ok.should == true + end +end + +module Spec + module Runner + class Context + def before_context_eval + inherit RSpecFormUnit + end + end + end +end diff --git a/lib/rformspec.rb b/lib/rformspec.rb new file mode 100644 index 0000000..d908254 --- /dev/null +++ b/lib/rformspec.rb @@ -0,0 +1,15 @@ +#*********************************************************** +#* Copyright (c) 2006, Zhimin Zhan. +#* Distributed open-source, see full license in MIT-LICENSE +#*********************************************************** + +# Extra full path to load libraries +require File.dirname(__FILE__) + "/rformspec/driver" +require File.dirname(__FILE__) + "/rformspec/control" +require File.dirname(__FILE__) + "/rformspec/mouse" +require File.dirname(__FILE__) + "/rformspec/keyboard" +require File.dirname(__FILE__) + "/rformspec/window" +require File.dirname(__FILE__) + "/rformspec/open_file_dialog" +require File.dirname(__FILE__) + "/rformspec/saveas_file_dialog" +require File.dirname(__FILE__) + "/rformspec/process" +require File.dirname(__FILE__) + "/rformspec/form_testcase" diff --git a/lib/rformunit/control.rb b/lib/rformspec/control.rb old mode 100755 new mode 100644 similarity index 89% rename from lib/rformunit/control.rb rename to lib/rformspec/control.rb index 8b3ac11..b55e0bb --- a/lib/rformunit/control.rb +++ b/lib/rformspec/control.rb @@ -1,152 +1,153 @@ -require File.dirname(__FILE__) + "/driver" - -module RFormUnit - class BaseControl - include Driver - - attr_accessor :parent_win, :control_id - - def initialize(win, ctrl_id) - @parent_win = win - @control_id = ctrl_id - end - - def set_text(new_text) - driver.ControlSetText(@parent_win.title, @parent_win.text, @control_id, new_text) - end - - def send_text(text) - driver.ControlSend(@parent_win.title, @parent_win.text, @control_id, text) - end - - def get_text - driver.ControlGetText(@parent_win.title, @parent_win.text, @control_id) - end - - def focus - driver.ControlFocus(@parent_win.title, @parent_win.text, @control_id) - end - - def is_enabled? - ret = driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "IsEnabled" ,"") - ret == 1 or ret == "1" - end - - def is_visible? - ret = driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "IsVisible" ,"") - ret == 1 or ret == "1" - end - - def click - driver.ControlClick(@parent_win.title, @parent_win.text, @control_id) - end - - end - - class TextBox < BaseControl - - end - - class Label < BaseControl - - end - - class CheckBox < BaseControl - def check - driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "Check" ,"") - end - - def uncheck - driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "UnCheck" ,"") - end - - def is_checked? - driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "IsChecked" ,"") == 1 - end - - end - - class RadioButton < BaseControl - def check - driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "Check" ,"") - end - - def uncheck - driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "UnCheck" ,"") - end - - def is_checked? - driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "IsChecked" ,"") == 1 - end - - end - - class ComboBox < BaseControl - - def show_dropdown - driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "ShowDropDown" ,"") - end - - def hide_dropdown - driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "HideDropDown" ,"") - end - - def select_option(option) - driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "SelectString" , option) - end - - end - - - class Button < BaseControl - end - - class Tab < BaseControl - - def current - driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "CurrentTab" , "") - end - - end - - class ListView < BaseControl - - def item_count - result = driver.ControlListView(@parent_win.title, @parent_win.text, @control_id, "GetItemCount" , "", "").to_i - result ? result.to_i : 0 - end - - # row and column index starts from 0, - def get_item_text(row, col = 0) - driver.ControlListView(@parent_win.title, @parent_win.text, @control_id, "GetText" , "#{row}", col) - end - - # can't use select, as it is Ruby keyword - def highlight(row_start, row_end = nil) - row_end ||= row_start - driver.ControlListView(@parent_win.title, @parent_win.text, @control_id, "Select" , "#{row_start}", "#{row_end}") - end - - def de_highlight(row_start, row_end = nil) - row_end ||= row_start - driver.ControlListView(@parent_win.title, @parent_win.text, @control_id, "DeSelect" , "#{row_start}", "#{row_end}") - end - alias de_select de_highlight - - def subitem_count - result = driver.ControlListView(@parent_win.title, @parent_win.text, @control_id, "GetSubItemCount" , "", "").to_i - result ? result.to_i : 0 - end - - def select_all - driver.ControlListView(@parent_win.title, @parent_win.text, @control_id, "SelectAll" , "", "") - end - - def is_selected?(row) - 1 == driver.ControlListView(@parent_win.title, @parent_win.text, @control_id, "IsSelected" , "#{row}", "") - end - - end - - -end +require File.dirname(__FILE__) + "/driver" + +module RFormSpec + class BaseControl + include Driver + + attr_accessor :parent_win, :control_id + + def initialize(win, ctrl_id) + @parent_win = win + @control_id = ctrl_id + end + + def set_text(new_text) + driver.ControlSetText(@parent_win.title, @parent_win.text, @control_id, new_text) + end + + def send_text(text) + driver.ControlSend(@parent_win.title, @parent_win.text, @control_id, text) + end + alias send_keys send_text + + def get_text + driver.ControlGetText(@parent_win.title, @parent_win.text, @control_id) + end + + def focus + driver.ControlFocus(@parent_win.title, @parent_win.text, @control_id) + end + + def is_enabled? + ret = driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "IsEnabled" ,"") + ret == 1 or ret == "1" + end + + def is_visible? + ret = driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "IsVisible" ,"") + ret == 1 or ret == "1" + end + + def click + driver.ControlClick(@parent_win.title, @parent_win.text, @control_id) + end + + end + + class TextBox < BaseControl + + end + + class Label < BaseControl + + end + + class CheckBox < BaseControl + def check + driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "Check" ,"") + end + + def uncheck + driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "UnCheck" ,"") + end + + def is_checked? + driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "IsChecked" ,"") == 1 + end + + end + + class RadioButton < BaseControl + def check + driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "Check" ,"") + end + + def uncheck + driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "UnCheck" ,"") + end + + def is_checked? + driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "IsChecked" ,"") == 1 + end + + end + + class ComboBox < BaseControl + + def show_dropdown + driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "ShowDropDown" ,"") + end + + def hide_dropdown + driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "HideDropDown" ,"") + end + + def select_option(option) + driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "SelectString" , option) + end + + end + + + class Button < BaseControl + end + + class Tab < BaseControl + + def current + driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "CurrentTab" , "") + end + + end + + class ListView < BaseControl + + def item_count + result = driver.ControlListView(@parent_win.title, @parent_win.text, @control_id, "GetItemCount" , "", "").to_i + result ? result.to_i : 0 + end + + # row and column index starts from 0, + def get_item_text(row, col = 0) + driver.ControlListView(@parent_win.title, @parent_win.text, @control_id, "GetText" , "#{row}", col) + end + + # can't use select, as it is Ruby keyword + def highlight(row_start, row_end = nil) + row_end ||= row_start + driver.ControlListView(@parent_win.title, @parent_win.text, @control_id, "Select" , "#{row_start}", "#{row_end}") + end + + def de_highlight(row_start, row_end = nil) + row_end ||= row_start + driver.ControlListView(@parent_win.title, @parent_win.text, @control_id, "DeSelect" , "#{row_start}", "#{row_end}") + end + alias de_select de_highlight + + def subitem_count + result = driver.ControlListView(@parent_win.title, @parent_win.text, @control_id, "GetSubItemCount" , "", "").to_i + result ? result.to_i : 0 + end + + def select_all + driver.ControlListView(@parent_win.title, @parent_win.text, @control_id, "SelectAll" , "", "") + end + + def is_selected?(row) + 1 == driver.ControlListView(@parent_win.title, @parent_win.text, @control_id, "IsSelected" , "#{row}", "") + end + + end + + +end diff --git a/lib/rformunit/driver.rb b/lib/rformspec/driver.rb old mode 100755 new mode 100644 similarity index 77% rename from lib/rformunit/driver.rb rename to lib/rformspec/driver.rb index bf25893..9bfab0b --- a/lib/rformunit/driver.rb +++ b/lib/rformspec/driver.rb @@ -1,80 +1,80 @@ -require 'win32ole' - -module RFormUnit - module Driver - - def init - driver - end - - def driver - return @a3 if @a3 - - @a3 = WIN32OLE.new('AutoItX3.Control') - - @a3.AutoItSetOption("CaretCoordMode", 0); - @a3.AutoItSetOption("ColorMode", 1); - @a3.AutoItSetOption("MouseCoordMode", 0); - @a3.AutoItSetOption("PixelCoordMode", 0); - @a3.AutoItSetOption("SendKeyDelay", 15) - return @a3 - end - - def set_autoit_option(key, value) - init if @a3.nil? - @a3.AutoItSetOption(key, value) - end - - def wait_for_window(win, timeout=30) - driver.WinWait(win.title, win.text, timeout * 1000) - win - end - - def wait_and_focus_window(title, text="", timeout=30) - driver.WinWaitActive(title, text, timeout * 1000) - end - - def window_exists?(title) - driver.WinExists(title) > 0 - end - - def focus_window(title) - driver.WinActivate(title) - end - - def close_window(title) - driver.WinClose(title) - end - - # wrapper of keyboard operations - def key_press(keys) - if keys =~ /^Ctrl\+([A-Z])$/ - filtered_keys = "^+#{$1}" - elsif keys =~ /^Ctrl\+Shift\+([A-Z])$/ - filtered_keys = "^+#{$1.downcase}" - elsif keys =~ /^Alt+([A-Z])$/ - filtered_keys = "!+#{$1}" - elsif keys =~ /^Alt\+Shift\+([a-z])$/ - filtered_keys = "!+#{$1.downcase}" - else - filtered_keys = keys - end - filtered_keys = keys.gsub("Alt+", "!+").gsub("Ctrl+", "^+") - RFormUnit::Keyboard.press(filtered_keys) - sleep 0.5 - end - alias press_key key_press - - # standard open file dialog - def open_file_dialog(title, filepath) - wait_and_focus_window(title) - dialog = RFormUnit::OpenFileDialog.new(title) - dialog.enter_filepath(filepath) - sleep 1 - dialog.click_open - end - - #TODO: save as file dialog - - end -end +require 'win32ole' + +module RFormSpec + module Driver + + def init + driver + end + + def driver + return @a3 if @a3 + + @a3 = WIN32OLE.new('AutoItX3.Control') + + @a3.AutoItSetOption("CaretCoordMode", 0); + @a3.AutoItSetOption("ColorMode", 1); + @a3.AutoItSetOption("MouseCoordMode", 0); + @a3.AutoItSetOption("PixelCoordMode", 0); + @a3.AutoItSetOption("SendKeyDelay", 15) + return @a3 + end + + def set_autoit_option(key, value) + init if @a3.nil? + @a3.AutoItSetOption(key, value) + end + + def wait_for_window(win, timeout=30) + driver.WinWait(win.title, win.text, timeout * 1000) + win + end + + def wait_and_focus_window(title, text="", timeout=30) + driver.WinWaitActive(title, text, timeout * 1000) + end + + def window_exists?(title) + driver.WinExists(title) > 0 + end + + def focus_window(title) + driver.WinActivate(title) + end + + def close_window(title) + driver.WinClose(title) + end + + # wrapper of keyboard operations + def key_press(keys) + if keys =~ /^Ctrl\+([A-Z])$/ + filtered_keys = "^+#{$1}" + elsif keys =~ /^Ctrl\+Shift\+([A-Z])$/ + filtered_keys = "^+#{$1.downcase}" + elsif keys =~ /^Alt+([A-Z])$/ + filtered_keys = "!+#{$1}" + elsif keys =~ /^Alt\+Shift\+([a-z])$/ + filtered_keys = "!+#{$1.downcase}" + else + filtered_keys = keys + end + filtered_keys = keys.gsub("Alt+", "!+").gsub("Ctrl+", "^+") + RFormSpec::Keyboard.press(filtered_keys) + sleep 0.5 + end + alias press_key key_press + + # standard open file dialog + def open_file_dialog(title, filepath) + wait_and_focus_window(title) + dialog = RFormSpec::OpenFileDialog.new(title) + dialog.enter_filepath(filepath) + sleep 1 + dialog.click_open + end + + #TODO: save as file dialog + + end +end diff --git a/lib/rformunit/form_testcase.rb b/lib/rformspec/form_testcase.rb old mode 100755 new mode 100644 similarity index 92% rename from lib/rformunit/form_testcase.rb rename to lib/rformspec/form_testcase.rb index eeb6abd..269f64a --- a/lib/rformunit/form_testcase.rb +++ b/lib/rformspec/form_testcase.rb @@ -1,40 +1,40 @@ -#*********************************************************** -#* Copyright (c) 2006, Zhimin Zhan. -#* Distributed open-source, see full license in MIT-LICENSE -#*********************************************************** - -require 'test/unit' - -module RFormUnit - class FormTestCase < Test::Unit::TestCase - include RFormUnit::Driver - - def default_test - super unless(self.class == FormTestCase) - end - - # assert the block's return value instance every 1 second until timeout with specifed duration - def timeout_check_equal(duration, expected, &block) - execute_ok = false - duration.times do - sleep(1) - text = instance_eval(&block) - execute_ok = true and break if (text == expected) - end - execute_ok.should == true - end - - # - def timeout_check_include?(duration, expected, &block) - execute_ok = false - duration.times do - sleep(1) - text = instance_eval(&block) - execute_ok = true and break if text and text.include?(expected) - end - execute_ok.should == true - end - alias timeout_check_include timeout_check_include? - - end -end +#*********************************************************** +#* Copyright (c) 2006, Zhimin Zhan. +#* Distributed open-source, see full license in MIT-LICENSE +#*********************************************************** + +require 'test/unit' + +module RFormSpec + class FormTestCase < Test::Unit::TestCase + include RFormSpec::Driver + + def default_test + super unless(self.class == FormTestCase) + end + + # assert the block's return value instance every 1 second until timeout with specifed duration + def timeout_check_equal(duration, expected, &block) + execute_ok = false + duration.times do + sleep(1) + text = instance_eval(&block) + execute_ok = true and break if (text == expected) + end + execute_ok.should == true + end + + # + def timeout_check_include?(duration, expected, &block) + execute_ok = false + duration.times do + sleep(1) + text = instance_eval(&block) + execute_ok = true and break if text and text.include?(expected) + end + execute_ok.should == true + end + alias timeout_check_include timeout_check_include? + + end +end diff --git a/lib/rformunit/keyboard.rb b/lib/rformspec/keyboard.rb old mode 100755 new mode 100644 similarity index 89% rename from lib/rformunit/keyboard.rb rename to lib/rformspec/keyboard.rb index 945f1ab..a533329 --- a/lib/rformunit/keyboard.rb +++ b/lib/rformspec/keyboard.rb @@ -1,24 +1,24 @@ -require File.dirname(__FILE__) + "/driver" -require 'singleton' - -module RFormUnit - class Keyboard - include Singleton - include Driver - - def self.type(keys) - instance._type(keys) - end - - def self.press(key) - instance._type(key) - end - - # instance methods - def _type(keystrokes) - driver.Send(keystrokes) - end - alias _press _type - - end -end +require File.dirname(__FILE__) + "/driver" +require 'singleton' + +module RFormSpec + class Keyboard + include Singleton + include Driver + + def self.type(keys) + instance._type(keys) + end + + def self.press(key) + instance._type(key) + end + + # instance methods + def _type(keystrokes) + driver.Send(keystrokes) + end + alias _press _type + + end +end diff --git a/lib/rformunit/mouse.rb b/lib/rformspec/mouse.rb old mode 100755 new mode 100644 similarity index 93% rename from lib/rformunit/mouse.rb rename to lib/rformspec/mouse.rb index 0cf1754..4513992 --- a/lib/rformunit/mouse.rb +++ b/lib/rformspec/mouse.rb @@ -1,55 +1,55 @@ -require File.dirname(__FILE__) + "/driver" -require 'singleton' - -module RFormUnit - - class Mouse - include Singleton - include Driver - - def self.click(x=nil, y=nil) - instance._click(x, y) - end - - def self.right_click(x=nil, y=nil) - instance._right_click(x, y) - end - - def self.double_click(x, y) - instance._double_click(x,y) - end - - def self.move_to(x, y) - instance._move_to(x,y) - end - - - # intance methods - - def _click(x=nil, y=nil) - if (x and y) then - driver.MouseClick("left", x, y) - else - driver.MouseClick("left") - end - end - - def _right_click(x=nil, y=nil) - if (x and y) then - driver.MouseClick("right", x, y) - else - driver.MouseClick("right") - end - end - - def _double_click(x, y) - driver.MouseClick("left", x, y, 2) - end - - def _move_to(x, y) - driver.MouseMove(x,y) - end - - end - -end +require File.dirname(__FILE__) + "/driver" +require 'singleton' + +module RFormSpec + + class Mouse + include Singleton + include Driver + + def self.click(x=nil, y=nil) + instance._click(x, y) + end + + def self.right_click(x=nil, y=nil) + instance._right_click(x, y) + end + + def self.double_click(x, y) + instance._double_click(x,y) + end + + def self.move_to(x, y) + instance._move_to(x,y) + end + + + # intance methods + + def _click(x=nil, y=nil) + if (x and y) then + driver.MouseClick("left", x, y) + else + driver.MouseClick("left") + end + end + + def _right_click(x=nil, y=nil) + if (x and y) then + driver.MouseClick("right", x, y) + else + driver.MouseClick("right") + end + end + + def _double_click(x, y) + driver.MouseClick("left", x, y, 2) + end + + def _move_to(x, y) + driver.MouseMove(x,y) + end + + end + +end diff --git a/lib/rformunit/open_file_dialog.rb b/lib/rformspec/open_file_dialog.rb similarity index 78% rename from lib/rformunit/open_file_dialog.rb rename to lib/rformspec/open_file_dialog.rb index b7cbb83..04133f9 100644 --- a/lib/rformunit/open_file_dialog.rb +++ b/lib/rformspec/open_file_dialog.rb @@ -1,19 +1,19 @@ -module RFormUnit - class OpenFileDialog < RFormUnit::Window - - def initialize(title = "Open File") - focus_window(title) - end - - def enter_filepath(file_path) - get_text # somehow calling it get it loaded - set_control_text("Edit1", file_path) - end - - def click_open - click_button("Button2") - end - - end - -end +module RFormSpec + class OpenFileDialog < RFormSpec::Window + + def initialize(title = "Open File") + focus_window(title) + end + + def enter_filepath(file_path) + get_text # somehow calling it get it loaded + set_control_text("Edit1", file_path) + end + + def click_open + click_button("Button2") + end + + end + +end diff --git a/lib/rformunit/process.rb b/lib/rformspec/process.rb old mode 100755 new mode 100644 similarity index 90% rename from lib/rformunit/process.rb rename to lib/rformspec/process.rb index 280c575..67a348c --- a/lib/rformunit/process.rb +++ b/lib/rformspec/process.rb @@ -1,27 +1,27 @@ -require File.dirname(__FILE__) + "/driver" -require 'singleton' - -module RFormUnit - - class Process - include Singleton - include Driver - - def self.run(prog, work_path = nil) - instance._run(prog, work_path) - end - - def self.execute(prog, work_path = nil) - instance._run(prog, work_path) - end - - # -- - # instance methods - def _run(program, work_path = nil) - driver.Run(program, work_path) - end - - - end - -end +require File.dirname(__FILE__) + "/driver" +require 'singleton' + +module RFormSpec + + class Process + include Singleton + include Driver + + def self.run(prog, work_path = nil) + instance._run(prog, work_path) + end + + def self.execute(prog, work_path = nil) + instance._run(prog, work_path) + end + + # -- + # instance methods + def _run(program, work_path = nil) + driver.Run(program, work_path) + end + + + end + +end diff --git a/lib/rformunit/saveas_file_dialog.rb b/lib/rformspec/saveas_file_dialog.rb similarity index 74% rename from lib/rformunit/saveas_file_dialog.rb rename to lib/rformspec/saveas_file_dialog.rb index 0b93ea6..1e46da5 100644 --- a/lib/rformunit/saveas_file_dialog.rb +++ b/lib/rformspec/saveas_file_dialog.rb @@ -1,18 +1,18 @@ -module RFormUnit - class SaveasFileDialog < RFormUnit::Window - - def initialize(title = "Save As") - focus_window(title) - end - - def enter_filepath(file_path) - set_control_text("Edit1", file_path) - end - - def click_save - click_button("Button2") - end - - end - -end +module RFormSpec + class SaveasFileDialog < RFormSpec::Window + + def initialize(title = "Save As") + focus_window(title) + end + + def enter_filepath(file_path) + set_control_text("Edit1", file_path) + end + + def click_save + click_button("Button2") + end + + end + +end diff --git a/lib/rformunit/window.rb b/lib/rformspec/window.rb old mode 100755 new mode 100644 similarity index 93% rename from lib/rformunit/window.rb rename to lib/rformspec/window.rb index 2d053a7..2470ab5 --- a/lib/rformunit/window.rb +++ b/lib/rformspec/window.rb @@ -1,100 +1,100 @@ -require File.dirname(__FILE__) + "/driver" -require File.dirname(__FILE__) + "/control" - -module RFormUnit - - - class Window < BaseControl - attr_accessor :title, :text - - def initialize(title, text = '', timeout = 10) - # for some windows, the title might change depends when it is invoked - if title.class == Array - title.each { |a_title| - @title = a_title - @text = text if text - result = driver.WinWaitActive(@title, @text, timeout) - return if result != 0 - } - raise "timeout while waiting for window: #{self.to_s}" - end - - @title = title - @text = text if text - result = driver.WinWaitActive(@title, @text, timeout) - raise "timeout while waiting for window: #{self.to_s}" if result == 0 - end - - def focus - driver.WinActivate(@title, @text) - end - - def close - driver.WinClose(@title, @text) - end - - def exists? - driver.WinExists(@title, @text) - end - - def get_text - driver.WinGetText(@title, @text) - end - - def set_control_text(control_id, new_text) - BaseControl.new(self, control_id).set_text(new_text) - end - - def click_button(btn_id) - Button.new(self, btn_id).click - end - - def show_dropdown(combo_id) - combo = ComboBox.new(self, combo_id) - combo.show_dropdown - combo - end - - def hide_dropdown(combo_id) - combo = ComboBox.new(self, combo_id) - combo.hide_dropdown - combo - end - - def focus_control(ctrl_id) - BaseControl.new(self, ctrl_id).focus - end - - def send_control_text(ctrl_id, text) - BaseControl.new(self, ctrl_id).send_text(text) - end - - def get_control_text(ctrl_id) - BaseControl.new(self, ctrl_id).get_text - end - - #Not fully verified yet - def statusbar_text - driver.StatusbarGetText(@title) - end - - def pixel_color(x,y) - driver.PixelGetColor(x,y) - end - alias pixel_colour pixel_color - alias get_pixel_colour pixel_color - alias get_pixel_color pixel_color - - - def to_s - "Window{title => '#{@title}', text=>'#{@text}'}" - end - - # a list - def button(button_id) - RFormUnit::Button.new(self, button_id) - end - - end - -end +require File.dirname(__FILE__) + "/driver" +require File.dirname(__FILE__) + "/control" + +module RFormSpec + + + class Window < BaseControl + attr_accessor :title, :text + + def initialize(title, text = '', timeout = 10) + # for some windows, the title might change depends when it is invoked + if title.class == Array + title.each { |a_title| + @title = a_title + @text = text if text + result = driver.WinWaitActive(@title, @text, timeout) + return if result != 0 + } + raise "timeout while waiting for window: #{self.to_s}" + end + + @title = title + @text = text if text + result = driver.WinWaitActive(@title, @text, timeout) + raise "timeout while waiting for window: #{self.to_s}" if result == 0 + end + + def focus + driver.WinActivate(@title, @text) + end + + def close + driver.WinClose(@title, @text) + end + + def exists? + driver.WinExists(@title, @text) + end + + def get_text + driver.WinGetText(@title, @text) + end + + def set_control_text(control_id, new_text) + BaseControl.new(self, control_id).set_text(new_text) + end + + def click_button(btn_id) + Button.new(self, btn_id).click + end + + def show_dropdown(combo_id) + combo = ComboBox.new(self, combo_id) + combo.show_dropdown + combo + end + + def hide_dropdown(combo_id) + combo = ComboBox.new(self, combo_id) + combo.hide_dropdown + combo + end + + def focus_control(ctrl_id) + BaseControl.new(self, ctrl_id).focus + end + + def send_control_text(ctrl_id, text) + BaseControl.new(self, ctrl_id).send_text(text) + end + + def get_control_text(ctrl_id) + BaseControl.new(self, ctrl_id).get_text + end + + #Not fully verified yet + def statusbar_text + driver.StatusbarGetText(@title) + end + + def pixel_color(x,y) + driver.PixelGetColor(x,y) + end + alias pixel_colour pixel_color + alias get_pixel_colour pixel_color + alias get_pixel_color pixel_color + + + def to_s + "Window{title => '#{@title}', text=>'#{@text}'}" + end + + # a list + def button(button_id) + RFormSpec::Button.new(self, button_id) + end + + end + +end diff --git a/lib/rformunit.rb b/lib/rformunit.rb deleted file mode 100755 index ef57051..0000000 --- a/lib/rformunit.rb +++ /dev/null @@ -1,15 +0,0 @@ -#*********************************************************** -#* Copyright (c) 2006, Zhimin Zhan. -#* Distributed open-source, see full license in MIT-LICENSE -#*********************************************************** - -# Extra full path to load libraries -require File.dirname(__FILE__) + "/rformunit/driver" -require File.dirname(__FILE__) + "/rformunit/control" -require File.dirname(__FILE__) + "/rformunit/mouse" -require File.dirname(__FILE__) + "/rformunit/keyboard" -require File.dirname(__FILE__) + "/rformunit/window" -require File.dirname(__FILE__) + "/rformunit/open_file_dialog" -require File.dirname(__FILE__) + "/rformunit/saveas_file_dialog" -require File.dirname(__FILE__) + "/rformunit/process" -require File.dirname(__FILE__) + "/rformunit/form_testcase" diff --git a/sample/calc.rb b/sample/calc.rb index 15c53f7..7e2fe1d 100644 --- a/sample/calc.rb +++ b/sample/calc.rb @@ -1,25 +1,25 @@ -require 'rformunit' - -module Calc - include RFormUnit::Driver - - def start_calc - RFormUnit::Process.run("calc.exe") - RFormUnit::Window.new('Calculator') - end - - def find_existing_calc_win - if window_exists?("Calculator") - focus_window('Calculator') - RFormUnit::Window.new('Calculator') - else - nil - end - end - - def quit_calc - focus_window('QPRIME') - RFormUnit::Keyboard.press("!{F4}") - end - -end +require 'rformspec' + +module Calc + include RFormSpec::Driver + + def start_calc + RFormSpec::Process.run("calc.exe") + RFormSpec::Window.new('Calculator') + end + + def find_existing_calc_win + if window_exists?("Calculator") + focus_window('Calculator') + RFormSpec::Window.new('Calculator') + else + nil + end + end + + def quit_calc + focus_window('Calculator') + RFormSpec::Keyboard.press("!{F4}") + end + +end diff --git a/sample/calc_spec.rb b/sample/calc_spec.rb index 7547c63..e77d413 100644 --- a/sample/calc_spec.rb +++ b/sample/calc_spec.rb @@ -1,16 +1,16 @@ -require File.dirname(__FILE__) + '/rspec_calc' - -context "Calculator" do - - setup do - end - - specify "Multiple works" do - @calc_win.click_button('127') #3 - @calc_win.click_button('91') #* - @calc_win.click_button('131') #7 - @calc_win.click_button('112') #= - @calc_win.get_control_text('403').should == '21. ' - end - -end +require File.dirname(__FILE__) + '/rspec_calc' + +context "Calculator" do + + setup do + end + + specify "Multiple works" do + @calc_win.click_button('127') #3 + @calc_win.click_button('91') #* + @calc_win.click_button('131') #7 + @calc_win.click_button('112') #= + @calc_win.get_control_text('403').should == '21. ' + end + +end diff --git a/sample/notepad.rb b/sample/notepad.rb index 999f607..25394a4 100755 --- a/sample/notepad.rb +++ b/sample/notepad.rb @@ -1,19 +1,19 @@ -require 'rformunit' - -include RFormUnit::Driver - -RFormUnit::Process.run("C:\\WINDOWS\\NOTEPAD.EXE") -notepad_win = RFormUnit::Window.new('Untitled - Notepad') -RFormUnit::Keyboard.type("Hello, Missing No. 5.{ENTER}1 2 3 4 6 7 8 9 10{ENTER}") -RFormUnit::Keyboard.press("+{UP 2}") - -# move cursor up and insert the missing number -RFormUnit::Mouse.move_to(70, 65) -RFormUnit::Mouse.click -RFormUnit::Keyboard.type("5 ") - -notepad_win.close - -notepad_confirm_dialog = RFormUnit::Window.new('Notepad', 'The text') -notepad_confirm_dialog.focus -RFormUnit::Button.new(notepad_confirm_dialog, "7").click +require 'rformspec' + +include RFormSpec::Driver + +RFormSpec::Process.run("C:\\WINDOWS\\NOTEPAD.EXE") +notepad_win = RFormSpec::Window.new('Untitled - Notepad') +RFormSpec::Keyboard.type("Hello, Missing No. 5.{ENTER}1 2 3 4 6 7 8 9 10{ENTER}") +RFormSpec::Keyboard.press("+{UP 2}") + +# move cursor up and insert the missing number +RFormSpec::Mouse.move_to(70, 65) +RFormSpec::Mouse.click +RFormSpec::Keyboard.type("5 ") + +notepad_win.close + +notepad_confirm_dialog = RFormSpec::Window.new('Notepad', 'The text') +notepad_confirm_dialog.focus +RFormSpec::Button.new(notepad_confirm_dialog, "7").click diff --git a/sample/notepad1.rb b/sample/notepad1.rb index b9727ba..e0140bb 100644 --- a/sample/notepad1.rb +++ b/sample/notepad1.rb @@ -1,14 +1,14 @@ -require 'rformunit' - -include RFormUnit::Driver - -RFormUnit::Process.run("C:\\WINDOWS\\NOTEPAD.EXE") -notepad_win = RFormUnit::Window.new('Untitled - Notepad') -RFormUnit::Keyboard.type("Hello from Notepad, {ENTER}1 2 3 4 5 6 7 8 9 10{ENTER}") -sleep(0.5) -RFormUnit::Keyboard.press("+{UP 2}") -sleep(0.5) -notepad_win.close - -notepad_confirm_dialog = RFormUnit::Window.new('Notepad', 'No') -notepad_confirm_dialog.click_button('&No') +require 'rformspec' + +include RFormSpec::Driver + +RFormSpec::Process.run("C:\\WINDOWS\\NOTEPAD.EXE") +notepad_win = RFormSpec::Window.new('Untitled - Notepad') +RFormSpec::Keyboard.type("Hello from Notepad, {ENTER}1 2 3 4 5 6 7 8 9 10{ENTER}") +sleep(0.5) +RFormSpec::Keyboard.press("+{UP 2}") +sleep(0.5) +notepad_win.close + +notepad_confirm_dialog = RFormSpec::Window.new('Notepad', 'No') +notepad_confirm_dialog.click_button('&No') diff --git a/sample/rspec_calc.rb b/sample/rspec_calc.rb index cd007bf..e81a671 100644 --- a/sample/rspec_calc.rb +++ b/sample/rspec_calc.rb @@ -1,24 +1,24 @@ -require File.dirname(__FILE__) + '/calc' - -class RSpecCalc - include Calc - - def setup - init # initialize - @calc_win = find_existing_calc_win - if @calc_win.nil? - @calc_win = start_calc - end - end -end - -module Spec - module Runner - class Context - def before_context_eval - #inherit RSpecCalc # inherit not supported after 0.8 - inherit_context_eval_module_from RSpecCalc - end - end - end -end +require File.dirname(__FILE__) + '/calc' + +class RSpecCalc + include Calc + + def setup + init # initialize + @calc_win = find_existing_calc_win + if @calc_win.nil? + @calc_win = start_calc + end + end +end + +module Spec + module Runner + class Context + def before_context_eval + #inherit RSpecCalc # inherit not supported after 0.8 + inherit_context_eval_module_from RSpecCalc + end + end + end +end diff --git a/sample/test_calc.rb b/sample/test_calc.rb index 2e21b70..01fc906 100755 --- a/sample/test_calc.rb +++ b/sample/test_calc.rb @@ -1,23 +1,23 @@ -require 'rformunit' - -class CalcTest < RFormUnit::FormTestCase - - def setup - RFormUnit::Process.run("calc.exe") - @calc_win = RFormUnit::Window.new('Calculator') - end - - def teardown - @calc_win.close - end - - def test_multiple - @calc_win.click_button('127') #3 - @calc_win.click_button('91') #* - @calc_win.click_button('131') #7 - @calc_win.click_button('112') #= - assert_equal "21. ", @calc_win.get_control_text('403') - - end - -end +require 'rformspec' + +class CalcTest < RFormSpec::FormTestCase + + def setup + RFormSpec::Process.run("calc.exe") + @calc_win = RFormSpec::Window.new('Calculator') + end + + def teardown + @calc_win.close + end + + def test_multiple + @calc_win.click_button('127') #3 + @calc_win.click_button('91') #* + @calc_win.click_button('131') #7 + @calc_win.click_button('112') #= + assert_equal "21. ", @calc_win.get_control_text('403') + + end + +end
zhimin/rformspec
d384bd4daf5bb502946f7bdb390e1f8b2e3ac190
Import rFormUnit 0.2.1 to Git
diff --git a/CHANGELOG b/CHANGELOG new file mode 100755 index 0000000..636fedc --- /dev/null +++ b/CHANGELOG @@ -0,0 +1,30 @@ +CHANGELOG +========= +== 0.2.0 (2007-12-18) + - add convenient methods in Driver + - add a commonly used dialog class: open file dialog, save as file dialog + - add filtered key to support 'Alt+', 'Ctrl+' + +== 0.1.3 (2007-04-18) + +New features: + - Support window with various titles depends on invoking conditions + +== 0.1.2 (2007-02-26) + +New features: + - Add ListView support + - Add Label support + +Others: + - code reformating + +== 0.1.1 (2006-11-29) + +New features: + - replace keyboard.* with RFormUnit::Keyboard.* + - replace mouse.* with RFormUnit::Mouse.* + - replace process.* with RFormUnit::Process.* + + +== 0.1.0 (2006-11-28) initial release diff --git a/MIT-LICENSE b/MIT-LICENSE new file mode 100755 index 0000000..ec0028f --- /dev/null +++ b/MIT-LICENSE @@ -0,0 +1,21 @@ +Copyright (c) 2006 Zhimin Zhan, [email protected] + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + diff --git a/README b/README new file mode 100755 index 0000000..7e2a642 --- /dev/null +++ b/README @@ -0,0 +1,30 @@ +rFormUnit +========= + +rFormUnit is a simple framework for automated testing Windows Form applications. +It wraps AutoItX COM API to provide an alternative way to write an easy to use, +readable automated functional tests. + +Dependencies +------------ +* Ruby - http://rubyinstaller.rubyforge.org/wiki/wiki.pl (Version verified: ruby185-21.exe) +* AutoIt3 - http://www.autoitscript.com/autoit3/ (Version verified v3.2.2.0) + +Platform: MS Windows (of course) + +Install +------- +> gem install rformunit + +One minute tutorial +------------------- + + + +Copyrights +---------- +Free to use for any purposes. The software provided AS IS without any warranty whatsoever. + +Contact +------- +Zhimin Zhan, Agileway Pty Ltd. diff --git a/Rakefile b/Rakefile new file mode 100755 index 0000000..a5135dc --- /dev/null +++ b/Rakefile @@ -0,0 +1,65 @@ +require 'rubygems' +require 'rake/testtask' +require 'rake/rdoctask' + +Gem::manage_gems +require 'rake/gempackagetask' + +$:.unshift(File.dirname(__FILE__) + "/lib") +require 'rformunit' + +desc "Default task" +task :default => [ :clean, :test , :gem] + +desc "Clean generated files" +task :clean do + rm_rf 'pkg' + rm_rf 'docs/rdoc' +end + +# run the unit tests +Rake::TestTask.new("test") { |t| + t.test_files = FileList['test/test*.rb'] + t.verbose= true +} + +# Generate the RDoc documentation +Rake::RDocTask.new { |rdoc| + rdoc.rdoc_dir = 'docs/rdoc' + rdoc.title = 'rformunit' + rdoc.template = "#{ENV['template']}.rb" if ENV['template'] + rdoc.rdoc_files.include('README') + rdoc.rdoc_files.include('lib/rformunit.rb') + rdoc.rdoc_files.include('lib/rformunit/*.rb') +} + +spec = Gem::Specification.new do |s| + s.platform= Gem::Platform::CURRENT + s.name = "rformunit" + s.version = "0.2.1" + s.summary = "An wrap of AUTOIT3 for functional testing of Windows form applications" + # s.description = "" + + s.author = "Zhimin Zhan" + s.email = "[email protected]" + s.homepage= "http://www.zhimin.com/software/rformunit/" + # s.rubyforge_project = "" + + s.has_rdoc = true + s.requirements << 'none' + s.require_path = "lib" + s.autorequire = "rformunit" + + s.files = [ "Rakefile", "README", "CHANGELOG", "MIT-LICENSE" ] + # s.files = s.files + Dir.glob( "bin/**/*" ).delete_if { |item| item.include?( "\.svn" ) } + s.files = s.files + Dir.glob( "ext/**/*" ).delete_if { |item| item.include?( "\.svn" ) } + s.files = s.files + Dir.glob( "lib/**/*" ).delete_if { |item| item.include?( "\.svn" ) } + s.files = s.files + Dir.glob( "test/**/*" ).delete_if { |item| item.include?( "\.svn" ) } + s.files = s.files + Dir.glob( "sample/**/*" ).delete_if { |item| item.include?( "\.svn" ) } + s.files = s.files + Dir.glob( "docs/**/*" ).delete_if { |item| item.include?( "\.svn" ) } + +end + +Rake::GemPackageTask.new(spec) do |pkg| + pkg.need_zip = true +end diff --git a/docs/index.html b/docs/index.html new file mode 100644 index 0000000..749b80f --- /dev/null +++ b/docs/index.html @@ -0,0 +1,185 @@ +<html + <head> + <title>rFormUnit </title> + <meta http-equiv="content-type" content="text/html; charset=utf-8" /> + <link href="../../stylesheets/zhimin.css" media="screen" rel="Stylesheet" type="text/css" /> + <link href="../../stylesheets/local.css" media="screen" rel="Stylesheet" type="text/css" /> + +<style type="text/css" media="screen"> +BODY +{ + BACKGROUND-COLOR: #fffff0; + COLOR: #000000; + FONT-FAMILY: "Times New Roman", Times, serif +} + +.green { + background-color: #ECF3E1; + border:1px solid #C5DEA1; +} + +.orange{ + border:1px solid #E8A400; + background-color: #FFF4D8; + +</style> + +</head> + <body> + + <h3>What is rFormUnit?</h3> + <p>rFormUnit is a simple framework for automated testing <b>Windows Form</b> applications. It wraps <a href="http://www.autoitscript.com/autoit3/">AutoItX</a> COM API to provide an alternative way to write an easy to use, readable automated functional tests. + </p> + + <p>Current release: 0.1.1<br/> + &nbsp; <a href="releases/rformunit-0.1.1-mswin32.gem">rformunit-0.1.1-mswin32.gem</a> or from <a href="http://rubyforge.org/projects/rformunit/">rubyforge.org</a>, + + <!-- &nbsp; <a href="releases/changelog.txt">Change logs</a> <br/> --> + &nbsp; Documentation: <a href="rdoc/index.html">RDoc</a>, and Quick start guide below. + </p> + + <h3>Installation</h3> + + <p><b>Dependecies</b><br/> + &nbsp; &nbsp; Install <a href="http://rubyinstaller.rubyforge.org/wiki/wiki.pl">Ruby for windows</a><br/> + &nbsp; &nbsp; Install <a href="http://www.autoitscript.com/autoit3/">AutoIt3</a></p> + + <p>Using RubyGems: + <pre class="green">$ gem install rformunit</pre> + or download and install locally: + <pre class="green">$ gem install rformunit-0.1.0-mswin32.gem</pre> + </p> + + <h3>Quick start guide through examples</h3> + <ul> + <li><a href="#script">Run as automation scripts</a></li> + <li><a href="#test">Run as xUnit test cases</a></li> + <li><a href="#rspec">Run as RSpecs</a></li> + </ul> + <p>Check sample/*.rb for more examples.</p> + <a name="script"></a><h4>Run as automation scripts</h4> + <table width="100%" cellspacing="0" cellpadding="0"> + <tr bgcolor="#33CC33"> + <th align="left" width="50%">AutoIt3 Script</th> + <th align="left" width="50%">rFormUnit Script</th> + </tr> + <tr> + <td valign="top" nowrap="nowrap" class="orange" width="50%"> + <pre> + + + +Run("notepad.exe") +WinWaitActive("Untitled - Notepad") + +Send("Hello from Notepad.{ENTER}1 2 3{ENTER}") +Sleep(500) +Send("+{UP 2}") +Sleep(500) + +Send("!f") +Send("x") + +WinWaitActive("Notepad", "No") +Send("n") + + </pre> + </td> + + <td valign="top" nowrap="nowrap" class="green"> +<pre>require 'rformunit' + +include RFormUnit::Driver + +RFormUnit::Process.run("NOTEPAD.EXE") +notepad_win = RFormUnit::Window.new('Untitled - Notepad') +RFormUnit::Keyboard.type("Hello from Notepad, {ENTER}1 2 3 4 5 6 7 8 9 10{ENTER}") +sleep(0.5) +RFormUnit::Keyboard.press("+{UP 2}") +sleep(0.5) +notepad_win.close + +notepad_confirm_dialog = RFormUnit::Window.new('Notepad', 'No') +notepad_confirm_dialog.click_button('&No')</pre> + </td> + </tr> + </table> + + <a name="test"></a> + <div id="rformunit_test"> + <h4>rFormUnit Testcase</h4> +<pre class="green">require 'rformunit' + +class CalcTest &lt; RFormUnit::FormTestCase + def setup + RFormUnit::Process.run("calc.exe") + @calc_win = RFormUnit::Window.new('Calculator') + end + + def teardown + @calc_win.close + end + + def test_multiple + @calc_win.click_button('127') #3 + @calc_win.click_button('91') #* + @calc_win.click_button('131') #7 + @calc_win.click_button('112') #= + assert_equal "21. ", @calc_win.get_control_text('403') + end + +end</pre> + </div> + + <a name="rspec"></a><div id='rformunit_rspec'> + <h4>rFormUnit <a href="http://rspec.rubyforge.org/">RSpec</a></h4> + + <p><b>rspec_calc</b>: a spec runner to run rformunit based rspecs</p> + <pre class="green"> +require File.dirname(__FILE__) + '/calc' + +class RSpecCalc + include Calc + + def setup + init # initialize + @calc_win = find_existing_calc_win + if @calc_win.nil? + @calc_win = start_calc + end + end +end + +module Spec + module Runner + class Context + def before_context_eval + inherit RSpecCalc + end + end + end +end</pre> + + <p><b>calc_spec</b>: a rspec</p> + <pre class="green"> +require File.dirname(__FILE__) + '/rspec_calc' + +context "Calculator" do + + setup do + end + + specify "Multiple shall work" do + @calc_win.click_button('127') #3 + @calc_win.click_button('91') #* + @calc_win.click_button('131') #7 + @calc_win.click_button('112') #= + @calc_win.get_control_text('403').should == '21. ' + end + +end</pre> + + </div> + + </body> +</html> \ No newline at end of file diff --git a/lib/ext/rspec_rformunit.rb b/lib/ext/rspec_rformunit.rb new file mode 100755 index 0000000..74ec69a --- /dev/null +++ b/lib/ext/rspec_rformunit.rb @@ -0,0 +1,46 @@ +class RSpecFormUnit + include YourModule # change to your module containing common methods used in your specs + + def setup + @driver = GUIDriver.new() + + @driver.AutoItSetOption("CaretCoordMode",0); + @driver.AutoItSetOption("ColorMode",1); + @driver.AutoItSetOption("MouseCoordMode",0); + @driver.AutoItSetOption("PixelCoordMode",0); + @driver.AutoItSetOption("SendKeyDelay", 20) + + #Add it yourself + + end + + def timeout_check_equal(duration, expected, &block) + execute_ok = false + duration.times do + sleep(1) + text = instance_eval(&block) + execute_ok = true and break if (text == expected) + end + execute_ok.should == true + end + + def timeout_check_include?(duration, expected, &block) + execute_ok = false + duration.times do + sleep(1) + text = instance_eval(&block) + execute_ok = true and break if text and text.include?(expected) + end + execute_ok.should == true + end +end + +module Spec + module Runner + class Context + def before_context_eval + inherit RSpecFormUnit + end + end + end +end diff --git a/lib/rformunit.rb b/lib/rformunit.rb new file mode 100755 index 0000000..ef57051 --- /dev/null +++ b/lib/rformunit.rb @@ -0,0 +1,15 @@ +#*********************************************************** +#* Copyright (c) 2006, Zhimin Zhan. +#* Distributed open-source, see full license in MIT-LICENSE +#*********************************************************** + +# Extra full path to load libraries +require File.dirname(__FILE__) + "/rformunit/driver" +require File.dirname(__FILE__) + "/rformunit/control" +require File.dirname(__FILE__) + "/rformunit/mouse" +require File.dirname(__FILE__) + "/rformunit/keyboard" +require File.dirname(__FILE__) + "/rformunit/window" +require File.dirname(__FILE__) + "/rformunit/open_file_dialog" +require File.dirname(__FILE__) + "/rformunit/saveas_file_dialog" +require File.dirname(__FILE__) + "/rformunit/process" +require File.dirname(__FILE__) + "/rformunit/form_testcase" diff --git a/lib/rformunit/control.rb b/lib/rformunit/control.rb new file mode 100755 index 0000000..8b3ac11 --- /dev/null +++ b/lib/rformunit/control.rb @@ -0,0 +1,152 @@ +require File.dirname(__FILE__) + "/driver" + +module RFormUnit + class BaseControl + include Driver + + attr_accessor :parent_win, :control_id + + def initialize(win, ctrl_id) + @parent_win = win + @control_id = ctrl_id + end + + def set_text(new_text) + driver.ControlSetText(@parent_win.title, @parent_win.text, @control_id, new_text) + end + + def send_text(text) + driver.ControlSend(@parent_win.title, @parent_win.text, @control_id, text) + end + + def get_text + driver.ControlGetText(@parent_win.title, @parent_win.text, @control_id) + end + + def focus + driver.ControlFocus(@parent_win.title, @parent_win.text, @control_id) + end + + def is_enabled? + ret = driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "IsEnabled" ,"") + ret == 1 or ret == "1" + end + + def is_visible? + ret = driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "IsVisible" ,"") + ret == 1 or ret == "1" + end + + def click + driver.ControlClick(@parent_win.title, @parent_win.text, @control_id) + end + + end + + class TextBox < BaseControl + + end + + class Label < BaseControl + + end + + class CheckBox < BaseControl + def check + driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "Check" ,"") + end + + def uncheck + driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "UnCheck" ,"") + end + + def is_checked? + driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "IsChecked" ,"") == 1 + end + + end + + class RadioButton < BaseControl + def check + driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "Check" ,"") + end + + def uncheck + driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "UnCheck" ,"") + end + + def is_checked? + driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "IsChecked" ,"") == 1 + end + + end + + class ComboBox < BaseControl + + def show_dropdown + driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "ShowDropDown" ,"") + end + + def hide_dropdown + driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "HideDropDown" ,"") + end + + def select_option(option) + driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "SelectString" , option) + end + + end + + + class Button < BaseControl + end + + class Tab < BaseControl + + def current + driver.ControlCommand(@parent_win.title, @parent_win.text, @control_id, "CurrentTab" , "") + end + + end + + class ListView < BaseControl + + def item_count + result = driver.ControlListView(@parent_win.title, @parent_win.text, @control_id, "GetItemCount" , "", "").to_i + result ? result.to_i : 0 + end + + # row and column index starts from 0, + def get_item_text(row, col = 0) + driver.ControlListView(@parent_win.title, @parent_win.text, @control_id, "GetText" , "#{row}", col) + end + + # can't use select, as it is Ruby keyword + def highlight(row_start, row_end = nil) + row_end ||= row_start + driver.ControlListView(@parent_win.title, @parent_win.text, @control_id, "Select" , "#{row_start}", "#{row_end}") + end + + def de_highlight(row_start, row_end = nil) + row_end ||= row_start + driver.ControlListView(@parent_win.title, @parent_win.text, @control_id, "DeSelect" , "#{row_start}", "#{row_end}") + end + alias de_select de_highlight + + def subitem_count + result = driver.ControlListView(@parent_win.title, @parent_win.text, @control_id, "GetSubItemCount" , "", "").to_i + result ? result.to_i : 0 + end + + def select_all + driver.ControlListView(@parent_win.title, @parent_win.text, @control_id, "SelectAll" , "", "") + end + + def is_selected?(row) + 1 == driver.ControlListView(@parent_win.title, @parent_win.text, @control_id, "IsSelected" , "#{row}", "") + end + + end + + +end diff --git a/lib/rformunit/driver.rb b/lib/rformunit/driver.rb new file mode 100755 index 0000000..bf25893 --- /dev/null +++ b/lib/rformunit/driver.rb @@ -0,0 +1,80 @@ +require 'win32ole' + +module RFormUnit + module Driver + + def init + driver + end + + def driver + return @a3 if @a3 + + @a3 = WIN32OLE.new('AutoItX3.Control') + + @a3.AutoItSetOption("CaretCoordMode", 0); + @a3.AutoItSetOption("ColorMode", 1); + @a3.AutoItSetOption("MouseCoordMode", 0); + @a3.AutoItSetOption("PixelCoordMode", 0); + @a3.AutoItSetOption("SendKeyDelay", 15) + return @a3 + end + + def set_autoit_option(key, value) + init if @a3.nil? + @a3.AutoItSetOption(key, value) + end + + def wait_for_window(win, timeout=30) + driver.WinWait(win.title, win.text, timeout * 1000) + win + end + + def wait_and_focus_window(title, text="", timeout=30) + driver.WinWaitActive(title, text, timeout * 1000) + end + + def window_exists?(title) + driver.WinExists(title) > 0 + end + + def focus_window(title) + driver.WinActivate(title) + end + + def close_window(title) + driver.WinClose(title) + end + + # wrapper of keyboard operations + def key_press(keys) + if keys =~ /^Ctrl\+([A-Z])$/ + filtered_keys = "^+#{$1}" + elsif keys =~ /^Ctrl\+Shift\+([A-Z])$/ + filtered_keys = "^+#{$1.downcase}" + elsif keys =~ /^Alt+([A-Z])$/ + filtered_keys = "!+#{$1}" + elsif keys =~ /^Alt\+Shift\+([a-z])$/ + filtered_keys = "!+#{$1.downcase}" + else + filtered_keys = keys + end + filtered_keys = keys.gsub("Alt+", "!+").gsub("Ctrl+", "^+") + RFormUnit::Keyboard.press(filtered_keys) + sleep 0.5 + end + alias press_key key_press + + # standard open file dialog + def open_file_dialog(title, filepath) + wait_and_focus_window(title) + dialog = RFormUnit::OpenFileDialog.new(title) + dialog.enter_filepath(filepath) + sleep 1 + dialog.click_open + end + + #TODO: save as file dialog + + end +end diff --git a/lib/rformunit/form_testcase.rb b/lib/rformunit/form_testcase.rb new file mode 100755 index 0000000..eeb6abd --- /dev/null +++ b/lib/rformunit/form_testcase.rb @@ -0,0 +1,40 @@ +#*********************************************************** +#* Copyright (c) 2006, Zhimin Zhan. +#* Distributed open-source, see full license in MIT-LICENSE +#*********************************************************** + +require 'test/unit' + +module RFormUnit + class FormTestCase < Test::Unit::TestCase + include RFormUnit::Driver + + def default_test + super unless(self.class == FormTestCase) + end + + # assert the block's return value instance every 1 second until timeout with specifed duration + def timeout_check_equal(duration, expected, &block) + execute_ok = false + duration.times do + sleep(1) + text = instance_eval(&block) + execute_ok = true and break if (text == expected) + end + execute_ok.should == true + end + + # + def timeout_check_include?(duration, expected, &block) + execute_ok = false + duration.times do + sleep(1) + text = instance_eval(&block) + execute_ok = true and break if text and text.include?(expected) + end + execute_ok.should == true + end + alias timeout_check_include timeout_check_include? + + end +end diff --git a/lib/rformunit/keyboard.rb b/lib/rformunit/keyboard.rb new file mode 100755 index 0000000..945f1ab --- /dev/null +++ b/lib/rformunit/keyboard.rb @@ -0,0 +1,24 @@ +require File.dirname(__FILE__) + "/driver" +require 'singleton' + +module RFormUnit + class Keyboard + include Singleton + include Driver + + def self.type(keys) + instance._type(keys) + end + + def self.press(key) + instance._type(key) + end + + # instance methods + def _type(keystrokes) + driver.Send(keystrokes) + end + alias _press _type + + end +end diff --git a/lib/rformunit/mouse.rb b/lib/rformunit/mouse.rb new file mode 100755 index 0000000..0cf1754 --- /dev/null +++ b/lib/rformunit/mouse.rb @@ -0,0 +1,55 @@ +require File.dirname(__FILE__) + "/driver" +require 'singleton' + +module RFormUnit + + class Mouse + include Singleton + include Driver + + def self.click(x=nil, y=nil) + instance._click(x, y) + end + + def self.right_click(x=nil, y=nil) + instance._right_click(x, y) + end + + def self.double_click(x, y) + instance._double_click(x,y) + end + + def self.move_to(x, y) + instance._move_to(x,y) + end + + + # intance methods + + def _click(x=nil, y=nil) + if (x and y) then + driver.MouseClick("left", x, y) + else + driver.MouseClick("left") + end + end + + def _right_click(x=nil, y=nil) + if (x and y) then + driver.MouseClick("right", x, y) + else + driver.MouseClick("right") + end + end + + def _double_click(x, y) + driver.MouseClick("left", x, y, 2) + end + + def _move_to(x, y) + driver.MouseMove(x,y) + end + + end + +end diff --git a/lib/rformunit/open_file_dialog.rb b/lib/rformunit/open_file_dialog.rb new file mode 100644 index 0000000..b7cbb83 --- /dev/null +++ b/lib/rformunit/open_file_dialog.rb @@ -0,0 +1,19 @@ +module RFormUnit + class OpenFileDialog < RFormUnit::Window + + def initialize(title = "Open File") + focus_window(title) + end + + def enter_filepath(file_path) + get_text # somehow calling it get it loaded + set_control_text("Edit1", file_path) + end + + def click_open + click_button("Button2") + end + + end + +end diff --git a/lib/rformunit/process.rb b/lib/rformunit/process.rb new file mode 100755 index 0000000..280c575 --- /dev/null +++ b/lib/rformunit/process.rb @@ -0,0 +1,27 @@ +require File.dirname(__FILE__) + "/driver" +require 'singleton' + +module RFormUnit + + class Process + include Singleton + include Driver + + def self.run(prog, work_path = nil) + instance._run(prog, work_path) + end + + def self.execute(prog, work_path = nil) + instance._run(prog, work_path) + end + + # -- + # instance methods + def _run(program, work_path = nil) + driver.Run(program, work_path) + end + + + end + +end diff --git a/lib/rformunit/saveas_file_dialog.rb b/lib/rformunit/saveas_file_dialog.rb new file mode 100644 index 0000000..0b93ea6 --- /dev/null +++ b/lib/rformunit/saveas_file_dialog.rb @@ -0,0 +1,18 @@ +module RFormUnit + class SaveasFileDialog < RFormUnit::Window + + def initialize(title = "Save As") + focus_window(title) + end + + def enter_filepath(file_path) + set_control_text("Edit1", file_path) + end + + def click_save + click_button("Button2") + end + + end + +end diff --git a/lib/rformunit/window.rb b/lib/rformunit/window.rb new file mode 100755 index 0000000..2d053a7 --- /dev/null +++ b/lib/rformunit/window.rb @@ -0,0 +1,100 @@ +require File.dirname(__FILE__) + "/driver" +require File.dirname(__FILE__) + "/control" + +module RFormUnit + + + class Window < BaseControl + attr_accessor :title, :text + + def initialize(title, text = '', timeout = 10) + # for some windows, the title might change depends when it is invoked + if title.class == Array + title.each { |a_title| + @title = a_title + @text = text if text + result = driver.WinWaitActive(@title, @text, timeout) + return if result != 0 + } + raise "timeout while waiting for window: #{self.to_s}" + end + + @title = title + @text = text if text + result = driver.WinWaitActive(@title, @text, timeout) + raise "timeout while waiting for window: #{self.to_s}" if result == 0 + end + + def focus + driver.WinActivate(@title, @text) + end + + def close + driver.WinClose(@title, @text) + end + + def exists? + driver.WinExists(@title, @text) + end + + def get_text + driver.WinGetText(@title, @text) + end + + def set_control_text(control_id, new_text) + BaseControl.new(self, control_id).set_text(new_text) + end + + def click_button(btn_id) + Button.new(self, btn_id).click + end + + def show_dropdown(combo_id) + combo = ComboBox.new(self, combo_id) + combo.show_dropdown + combo + end + + def hide_dropdown(combo_id) + combo = ComboBox.new(self, combo_id) + combo.hide_dropdown + combo + end + + def focus_control(ctrl_id) + BaseControl.new(self, ctrl_id).focus + end + + def send_control_text(ctrl_id, text) + BaseControl.new(self, ctrl_id).send_text(text) + end + + def get_control_text(ctrl_id) + BaseControl.new(self, ctrl_id).get_text + end + + #Not fully verified yet + def statusbar_text + driver.StatusbarGetText(@title) + end + + def pixel_color(x,y) + driver.PixelGetColor(x,y) + end + alias pixel_colour pixel_color + alias get_pixel_colour pixel_color + alias get_pixel_color pixel_color + + + def to_s + "Window{title => '#{@title}', text=>'#{@text}'}" + end + + # a list + def button(button_id) + RFormUnit::Button.new(self, button_id) + end + + end + +end diff --git a/sample/calc.rb b/sample/calc.rb new file mode 100644 index 0000000..15c53f7 --- /dev/null +++ b/sample/calc.rb @@ -0,0 +1,25 @@ +require 'rformunit' + +module Calc + include RFormUnit::Driver + + def start_calc + RFormUnit::Process.run("calc.exe") + RFormUnit::Window.new('Calculator') + end + + def find_existing_calc_win + if window_exists?("Calculator") + focus_window('Calculator') + RFormUnit::Window.new('Calculator') + else + nil + end + end + + def quit_calc + focus_window('QPRIME') + RFormUnit::Keyboard.press("!{F4}") + end + +end diff --git a/sample/calc_spec.rb b/sample/calc_spec.rb new file mode 100644 index 0000000..7547c63 --- /dev/null +++ b/sample/calc_spec.rb @@ -0,0 +1,16 @@ +require File.dirname(__FILE__) + '/rspec_calc' + +context "Calculator" do + + setup do + end + + specify "Multiple works" do + @calc_win.click_button('127') #3 + @calc_win.click_button('91') #* + @calc_win.click_button('131') #7 + @calc_win.click_button('112') #= + @calc_win.get_control_text('403').should == '21. ' + end + +end diff --git a/sample/notepad.rb b/sample/notepad.rb new file mode 100755 index 0000000..999f607 --- /dev/null +++ b/sample/notepad.rb @@ -0,0 +1,19 @@ +require 'rformunit' + +include RFormUnit::Driver + +RFormUnit::Process.run("C:\\WINDOWS\\NOTEPAD.EXE") +notepad_win = RFormUnit::Window.new('Untitled - Notepad') +RFormUnit::Keyboard.type("Hello, Missing No. 5.{ENTER}1 2 3 4 6 7 8 9 10{ENTER}") +RFormUnit::Keyboard.press("+{UP 2}") + +# move cursor up and insert the missing number +RFormUnit::Mouse.move_to(70, 65) +RFormUnit::Mouse.click +RFormUnit::Keyboard.type("5 ") + +notepad_win.close + +notepad_confirm_dialog = RFormUnit::Window.new('Notepad', 'The text') +notepad_confirm_dialog.focus +RFormUnit::Button.new(notepad_confirm_dialog, "7").click diff --git a/sample/notepad1.rb b/sample/notepad1.rb new file mode 100644 index 0000000..b9727ba --- /dev/null +++ b/sample/notepad1.rb @@ -0,0 +1,14 @@ +require 'rformunit' + +include RFormUnit::Driver + +RFormUnit::Process.run("C:\\WINDOWS\\NOTEPAD.EXE") +notepad_win = RFormUnit::Window.new('Untitled - Notepad') +RFormUnit::Keyboard.type("Hello from Notepad, {ENTER}1 2 3 4 5 6 7 8 9 10{ENTER}") +sleep(0.5) +RFormUnit::Keyboard.press("+{UP 2}") +sleep(0.5) +notepad_win.close + +notepad_confirm_dialog = RFormUnit::Window.new('Notepad', 'No') +notepad_confirm_dialog.click_button('&No') diff --git a/sample/rspec_calc.rb b/sample/rspec_calc.rb new file mode 100644 index 0000000..cd007bf --- /dev/null +++ b/sample/rspec_calc.rb @@ -0,0 +1,24 @@ +require File.dirname(__FILE__) + '/calc' + +class RSpecCalc + include Calc + + def setup + init # initialize + @calc_win = find_existing_calc_win + if @calc_win.nil? + @calc_win = start_calc + end + end +end + +module Spec + module Runner + class Context + def before_context_eval + #inherit RSpecCalc # inherit not supported after 0.8 + inherit_context_eval_module_from RSpecCalc + end + end + end +end diff --git a/sample/test_calc.rb b/sample/test_calc.rb new file mode 100755 index 0000000..2e21b70 --- /dev/null +++ b/sample/test_calc.rb @@ -0,0 +1,23 @@ +require 'rformunit' + +class CalcTest < RFormUnit::FormTestCase + + def setup + RFormUnit::Process.run("calc.exe") + @calc_win = RFormUnit::Window.new('Calculator') + end + + def teardown + @calc_win.close + end + + def test_multiple + @calc_win.click_button('127') #3 + @calc_win.click_button('91') #* + @calc_win.click_button('131') #7 + @calc_win.click_button('112') #= + assert_equal "21. ", @calc_win.get_control_text('403') + + end + +end
yan/msbin
7432c8dfcd797c391b25e081b53cedac507748a3
added readme
diff --git a/README b/README index cdbb96f..47362cc 100644 --- a/README +++ b/README @@ -1,11 +1,17 @@ msbin reads a stream of Microsoft Binary XML (such as Silverlight messages) and writes its human-readable XML equivalent to stdout. All types should be implemented, but not all are tested. To use: ./msbin.rb file.msbin - ./msbin.rb - + ./msbin.rb - Where file.msbin can be a file saved from burp using the 'copy to file' or a straight binary XML dump. + + +For more information, see the following design docs: + +http://msdn.microsoft.com/en-us/library/cc219210(PROT.10).aspx +http://msdn.microsoft.com/en-us/library/cc219175(PROT.10).aspx
yan/msbin
30dd6c9f939e9a1c06a1df968d8d5c11361b9563
Started tests
diff --git a/tests.rb b/tests.rb new file mode 100755 index 0000000..d581fa8 --- /dev/null +++ b/tests.rb @@ -0,0 +1,23 @@ +#!/usr/bin/env ruby + +require 'stringio' +require 'types' + +test_cases = { +"EndElement" => "\x40\x03\x64\x6F\x63\x01", +#<doc></doc> +"Comment" => "\x02\x07\x63\x6F\x6D\x6D\x65\x6E\x74", +#<!--comment--> +"Array" => "\x03\x40\x03\x61\x72\x72\x01\x8B\x03\x33\x33\x88\x88\xDD\xDD", +#<arr>13107</arr> <arr>-30584</arr> <arr>-8739</arr> +"ShortAttribute" => "\x40\x03\x64\x6F\x63\x04\x04\x61\x74\x74\x72\x84\x01", +#<doc attr="false"> </doc> +#"Attribute" => "\x40\x03\x64\x6F\x63\x09\x03\x70\x72\x65\x0A\x68\x74\x74\x70\x3A\x2F\x2F\x61\x62\x63\x05\x03\x70\x72\x65\x04\x61\x74\x74\x72\x84\x01" +#<doc xmlns: pre="http://abc " pre:attr="false"> </doc> +} + +test_cases.each_pair{|type, data| + puts "Testing #{type}" + ss = StringIO.new(data) + MSBIN::Record.DecodeStream(ss) +}
yan/msbin
e346d459aefeb4379389af14aa2a99c8173f78b2
Added author comments and readme
diff --git a/README b/README new file mode 100644 index 0000000..cdbb96f --- /dev/null +++ b/README @@ -0,0 +1,11 @@ +msbin reads a stream of Microsoft Binary XML (such as Silverlight +messages) and writes its human-readable XML equivalent to stdout. + +All types should be implemented, but not all are tested. + +To use: + ./msbin.rb file.msbin + ./msbin.rb - + +Where file.msbin can be a file saved from burp using the 'copy to file' +or a straight binary XML dump. diff --git a/msbin.rb b/msbin.rb index 548dab4..7c24766 100755 --- a/msbin.rb +++ b/msbin.rb @@ -1,19 +1,22 @@ #!/usr/bin/env ruby +# by Yan Ivnitskiy +# [email protected] + require 'msbin/types' if ARGV.size == 0 $stderr.write("Usage: #{$0} [file.msbin|-]\n") exit 1 end f = ARGV[0] == '-' ? $stdin : File.new(ARGV[0], "rb") # check if we have an http post, and consume headers if f.read(4) == "HTTP" while f.readline().chomp != ""; end else f.seek(0) end MSBIN::Record.DecodeStream(f) diff --git a/msbin/attributes.rb b/msbin/attributes.rb index 7a00cc3..b3e329b 100644 --- a/msbin/attributes.rb +++ b/msbin/attributes.rb @@ -1,145 +1,150 @@ +#!/usr/bin/env ruby + require 'msbin/record' +# by Yan Ivnitskiy +# [email protected] + module MSBIN class ShortAttribute < Record @record_type = 0x04 define_with_endelement def initialize(handle, record_type) @name = read_string(handle) @value = Record.MakeRecord(handle) end def to_s " #{@name}=\"#{@value}\"" end end # TODO: Make other attributes inherit from this to make this make more sense # TODO: Group them in a module and not have it all be flat class Attribute < Record @record_type = 0x05 def initialize(handle, record_type) @prefix = read_string(handle) @name = read_string(handle) @value = Record.MakeRecord(handle) end def to_s " #{@prefix}:#{@name}=\"#{@value}\"" end end class ShortDictionaryAttribute < Attribute @record_type = 0x06 def initialize(handle, record_type) @name = read_dictstring(handle) @value = Record.MakeRecord(handle) end def to_s " #{@name}=#{@value}" end end class DictionaryAttribute < Attribute @record_type = 0x07 # TODO: Create a read_* method for dictionary strings # TODO: finalize the read_int31 function def initialize(handle, record_type) @prefix = read_string(handle) @name = read_dictstring(handle) @value = Record.MakeRecord(handle) end def to_s " #{@prefix}:#{@name}=\"#{@value}\"" end end class PrefixAttribute < Attribute @record_type = 0x26 .. 0x3f def initialize(handle, record_type) @name = "#{(record_type-self.class.record_type.first+?a).chr}:" + read_string(handle) @record_type = record_type @value = Record.MakeRecord(handle) end def to_s " #{@name}=\"#{@value}\"" end end class PrefixDictionaryAttribute < Attribute @record_type = 0x0c .. 0x25 def initialize(handle, record_type) @name = read_dictstring(handle) @value = Record.MakeRecord(handle) @record_type = record_type end def to_s "#{@name}=\"#{@value}\"" end end class ShortDictionaryXmlnsAttribute < Attribute @record_type = 0x0a # TODO Isolate classes that do DictionaryStrings # TODO: the value will be ' xmlns="@{value}"' def initialize(handle, record_type) @value = read_dictstring(handle) end def to_s " xmlns=\"#{@value}\"" end end class DictionaryXmlnsAttribute < Attribute @record_type = 0X0b def initialize(handle, record_type) @prefix = read_string(handle) @attributes = read_dictstring(handle) end def to_s " xmlns:#{@prefix}=\"#{@attributes}\"" end end class ShortXmlnsAttribute < Attribute @record_type = 0x08 def initialize(handle, record_type) @value = read_string(handle) end def to_s " xmlns=\"#{@value}\"" end end class XmlnsAttribute < Attribute @record_type = 0x09 def initialize(handle, record_type) @prefix = read_string(handle) @value = read_string(handle) end def to_s " xmlns:#{@prefix}=\"#{@value}\"" end end end diff --git a/msbin/record.rb b/msbin/record.rb index bcebe5b..f8a868e 100644 --- a/msbin/record.rb +++ b/msbin/record.rb @@ -1,135 +1,138 @@ #!/usr/bin/env ruby +# by Yan Ivnitskiy +# [email protected] + require 'msbin/records' def read_long(handle) return handle.read(4).unpack('L').first end def read_string(handle) len = read_int31(handle) str = handle.read(len) return str end def read_int8(handle) return handle.read(1)[0] end def read_int16(handle) return handle.read(2).unpack("s").first end # TODO: bundle these in a module def read_int31(handle) val = 0 pow = 1 begin byte = read_int8(handle) val += pow * (byte & 0x7F) pow *= 2**7 end while (byte & 0x80) == 0x80 return val end def read_int32(handle) return handle.read(4).unpack("L").first end def read_float(handle) return handle.read(4).unpack("g").first end def read_int64(handle) return handle.read(8).unpack("Q").first end def read_double(handle) return handle.read(8).unpack("E").first end def read_dictstring(handle) val = read_int31(handle) return MSBIN_DictionaryStrings[val] end module MSBIN class Record @@records = [] class << self attr_accessor :record_type def inherited(klass) @@records << klass end # TODO: Document this def define_with_endelement record_type = self.record_type c = Class.new(self) do @record_type = record_type+1 end name = self.name.split(':').last+"WithEndElement" MSBIN.const_set name, c end def is_attribute?(type) nil != @@records.find do |klass| klass.ancestors.include? Attribute and klass.record_type === type end end def record_type_to_class(record_type) @@records.find{|klass| klass.record_type === record_type} end def DecodeStream(handle) while !handle.eof() a = MakeRecord(handle) indent = a.class == EndElement ? -1 : 0 write_xml a, indent end end def MakeRecord(handle) record_type = read_int8(handle) klass = self.record_type_to_class(record_type) if not klass raise "Unsupported type: 0x#{record_type.to_s(16)}" end #TODO: move the 2-arg initializer to the base class somehow ret = klass.new(handle, record_type) if ret.is_a? Element and ret.class.to_s !~ /EndElement$/ $element_stack.push ret end ret end end def initialize(handle, record_type) end def get_attributes(handle) @attributes = [] loop do where = handle.pos next_type = read_int8(handle) handle.seek(where) break if not Record.is_attribute? next_type @attributes << Record.MakeRecord(handle) end end def type_of?(type) raise NotImplementedError end end end diff --git a/msbin/text.rb b/msbin/text.rb index c60944d..ca24481 100644 --- a/msbin/text.rb +++ b/msbin/text.rb @@ -1,381 +1,385 @@ +#!/usr/bin/env ruby + +# by Yan Ivnitskiy +# [email protected] module MSBIN # Make this an ADT class TextRecord < Record @record_type = 0x00 def initialize(handle, record_type) @record_type = record_type end def to_s @value.to_s end end class ZeroText < TextRecord @record_type = 0x80 define_with_endelement def to_s; "0"; end end class TrueText < TextRecord @record_type = 0x86 define_with_endelement def to_s; "true"; end end class FalseText < TextRecord @record_type = 0x84 define_with_endelement def to_s; "false"; end end class OneText < TextRecord @record_type = 0x82 define_with_endelement def to_s; "1"; end end # TODO: Parse this better class DateTimeText < TextRecord @record_type = 0x96 define_with_endelement def initialize(handle, record_type) # TODO: validate it @date_date val = read_int64(handle) @tz = val & 0xff val >>= 2 # to microseconds val /= 10 # to seconds val /= (10**6) # seconds since year 1 until epoch start = Time.utc(1, "jan", 1, 0, 0, 0, 0) epoch = Time.at(0) # seconds since 0 val -= (epoch - start) # val is now epoch # not sure if this is correct, but it'll do for now time = Time.at(val) if time.hour == 0 and time.minutes == 0 and time.seconds == 0 @value = time.strftime("%Y-%m-%d") else @value = time.strftime("%Y-%m-%dT%H:%M:%S") end end end class DictionaryText < TextRecord @record_type = 0xaa define_with_endelement def initialize(handle, record_type) @value = read_dictstring(handle) end end class Chars8Text < TextRecord @record_type = 0x98 define_with_endelement def initialize(handle, record_type) require 'cgi' length = read_int8(handle) @value = CGI.escapeHTML(handle.read(length)).to_s end end class Chars16Text < TextRecord @record_type = 0x9a define_with_endelement def initialize(handle, record_type) require 'cgi' length = read_int16(handle) @value = CGI.escapeHTML(handle.read(length)).to_s end end class Chars32Text < TextRecord @record_type = 0x9c define_with_endelement def initialize(hand,record_type) require 'cgi' length = read_int32(handle) @value = CGI.escapeHTML(handle.read(length)).to_s end end class UuIdText < TextRecord @record_type = 0xac define_with_endelement def initialize(handle, record_type) @uuid = handle.read(16).unpack('VvvC*') @value = ("%08x-%04x-%04x-" % [@uuid[0], @uuid[1], @uuid[2]])+(("%02x"*6) % @uuid[3..-1]) end end class TimeSpanText < TextRecord @record_type = 0xae define_with_endelement def initialize(handle, record_type) @value = handle.read(8).unpack("q")[0] if @value < 0 @sign = '-'; @value *= -1 end ticks_in_sec = 10000000 @frac = @value % ticks_in_sec; @value /= ticks_in_sec @seconds = @value % 60; @value /= 60 @minutes = @value % 60; @value /= 60 @hours = @value % 24; @value /= 24 @days = @value end def to_s if @days > 0 and @frac == 0 "#{@sign}%d.%02d:%02d:%02d" % [@days, @hours, @minutes, @seconds] elsif @days > 0 and @frac > 0 "#{@sign}%d.%02d:%02d:%02d:%d" % [@days, @hours, @minutes, @seconds, @frac] elsif @days == 0 and @frac == 0 "#{@sign}%02d:%02d:%02d" % [@hours, @minutes, @seconds] else "#{@sign}%02d:%02d:%02d.%d" % [@hours, @minutes, @seconds, @frac] end end end class Int8Text < TextRecord @record_type = 0x88 define_with_endelement def initialize(handle, record_type) @value = read_int8(handle).to_s end end class Int16Text < TextRecord @record_type = 0x8a define_with_endelement def initialize(handle, record_type) @value = read_int16(handle).to_s end end class Int32Text < TextRecord @record_type = 0x8c define_with_endelement def initialize(handle, record_type) @value = read_int32(handle).to_s end end class Int64Text < TextRecord @record_type = 0x8e define_with_endelement def initialize(handle, record_type) @value = read_int64(handle).to_s end end class FloatText < TextRecord @record_type = 0x90 define_with_endelement def initialize(handle, record_type) @value = read_float(handle).to_s end end class DoubleText < TextRecord @record_type = 0x92 define_with_endelement def initialize(handle, record_type) @value = read_double(handle).to_s end end class DecimalText < TextRecord @record_type = 0x94 define_with_endelement def initialize(handle, record_type) wReserved = read_int16(handle) scale = read_int8(handle) @sign = read_int8(handle) == 0 ? "" : "-" @value = 0 2.downto(0).each {|n| @value |= (handle.read(4).unpack("N")[0]) << 32*n } @value /= 10.0**scale end def to_s "#{@sign}#{@value}" end end class UnicodeChars8Text < TextRecord @record_type = 0xb6 define_with_endelement def initialize(handle, record_type) length = read_int8(handle) @value = from_unicode(handle.read(length)) end end class UnicodeChars16Text < TextRecord @record_type = 0xb8 define_with_endelement def initialize(handle, record_type) length = read_int16(handle) @value = from_unicode(handle.read(length)) end end class UnicodeChars32Text < TextRecord @record_type = 0xba define_with_endelement def initialize(handle, record_type) length = read_int32(handle) @value = from_unicode(handle.read(length)) end end class BoolText < TextRecord @record_type = 0xb4 define_with_endelement def initialize(handle, record_type) val = read_int8(handle) @value = val == 0 ? "false" : "true" end end class UInt64Text < TextRecord @record_type = 0xb2 define_with_endelement def initialize(handle, record_type) # unsigned @value = handle.read(8).unpack("Q")[0].to_s end end class StartListText < TextRecord @record_type = 0xa4 def initialize(handle, record_type) @records = [] begin record = Record.MakeRecord(handle) @records << record end until record.is_a?(EndListText) @value = @records.map{|x|x.strip}.join(" ") end end class EndListText < TextRecord @record_type = 0xa6 def to_s; ""; end end class EmptyText < TextRecord @record_type = 0xa8 define_with_endelement def to_s; ""; end end class QNameDictionaryText < TextRecord @record_type = 0xbc define_with_endelement def initialize(handle, record_type) val = handle.read(4).unpack("L")[0] @prefix = (((val >> 24) & 0xff) + ?a).chr val &= 0x00ffffff @value = "#{@prefix}:#{MSBIN_DictionaryStrings[val]}" end end class Bytes8Text < TextRecord @record_type = 0x9e define_with_endelement # TODO: Rewrite all these custom reads to util funcs def initialize(handle, record_type) length = read_int8(handle) bytes = handle.read(length) require 'base64' @value = Base64.b64encode(bytes).rstrip end end class Bytes16Text < TextRecord @record_type = 0xa0 define_with_endelement # TODO: factor out everything but length def initialize(handle, record_type) length = read_int16(handle) bytes = handle.read(length) require 'base64' @value = Base64.b64encode(bytes).rstrip end end class Bytes32Text < TextRecord @record_type = 0xa2 define_with_endelement def initialize(handle, record_type) length = read_int32(handle) bytes = handle.read(length) require 'base64' @value = Base64.b64encode(bytes).rstrip end end end diff --git a/msbin/types.rb b/msbin/types.rb index 2431375..4623ccd 100644 --- a/msbin/types.rb +++ b/msbin/types.rb @@ -1,165 +1,168 @@ #!/usr/bin/env ruby +# by Yan Ivnitskiy +# [email protected] + require 'msbin/msbin_types' require 'msbin/record' require 'msbin/attributes' require 'msbin/text' $indent = -1 def write_xml(s, increase=1, no_indent=false) indent = " "*$indent if $indent >= 0 indent = "" if no_indent print "#{indent}#{s}\n" if s.class.to_s =~ /WithEndElement$/ print "#{indent}</#{$element_stack.pop.name}>\n" increase = -1 end $indent += increase end require 'iconv' def from_unicode(str) return Iconv.conv('UTF-8', 'UTF-16LE', str) end $element_stack = [] module MSBIN class Reserved < Record @record_type = 0x00 def initialize(handle, record_type) raise "Reserved type used" end end class Element < Record end class EndElement < Element @record_type = 0x01 def to_s if !$element_stack.empty? "</#{$element_stack.pop.name}>" else "" end end end class CommentElement < Element @record_type = 0x02 def initialize(handle, record_type) @value = "<!--#{read_string(handle)}-->" end end # TODO: Implement Array # Array is extremely hacky since it writes to output directly class ArrayElement < Element @record_type = 0x03 def initialize(handle, record_type) # reset element stack element = Record.MakeRecord(handle); $element_stack.pop endelement = Record.MakeRecord(handle) type = read_int8(handle) length = read_int31(handle) cls = Record.record_type_to_class(type) length.times do |idx| $element_stack.push element write_xml(element, 1) write_xml(cls.new(handle, type), -1)#, no_indent=true) end end end class PrefixElement < Element @record_type = 0x5e .. 0x77 attr_accessor :name def initialize(handle, record_type) $indent += 1 @name = "#{(record_type-self.class.record_type.first+?a).chr}:" + read_string(handle) @record_type = record_type @attributes = [] get_attributes(handle) end def to_s attribs = @attributes.empty? ? "" : " #{@attributes}" "<#{@name}#{attribs}>" end end class PrefixDictionaryElement < Element attr_accessor :attributes @record_type = 0x44 .. 0x5D def initialize(handle, record_type) $indent += 1 @attributes = [] @record_type = record_type # read name @name = read_dictstring(handle) #puts "got name #{@name}" get_attributes(handle) end def name "#{(?a+@record_type-self.class.record_type.first).chr}:#{@name}" end def to_s attribs = @attributes.empty? ? "" : " #{@attributes}" "<#{(?a+@record_type-self.class.record_type.first).chr}:#{@name}#{attribs}>" end end class ShortElement < Element @record_type = 0x40 def initialize(handle, record_type) $indent += 1 @name = read_string(handle) get_attributes(handle) end def name @name end def to_s attribs = @attributes.empty? ? "" : " #{@attributes}" "<#{@name}#{attribs}>" end end class DictionaryElement < Element @record_type = 0x43 def initialize(handle, record_type) @prefix = read_string(handle) @name = read_dictstring(handle) get_attributes(handle) end def to_s attribs = @attributes.empty? ? "" : " #{@attributes}" "<#{@prefix}:#{@name}#{attribs}>" end end end
yan/msbin
ba06778e87ffb6f6ad90245d5da3a1a9248896f9
reorganized
diff --git a/msbin.rb b/msbin.rb index fe3db4f..548dab4 100755 --- a/msbin.rb +++ b/msbin.rb @@ -1,25 +1,19 @@ #!/usr/bin/env ruby -#require 'records' -require 'types' +require 'msbin/types' if ARGV.size == 0 $stderr.write("Usage: #{$0} [file.msbin|-]\n") exit 1 end -if ARGV[0] == '-' - f = $stdin -else - f = File.new(ARGV[0], "rb") -end +f = ARGV[0] == '-' ? $stdin : File.new(ARGV[0], "rb") # check if we have an http post, and consume headers if f.read(4) == "HTTP" while f.readline().chomp != ""; end else f.seek(0) end MSBIN::Record.DecodeStream(f) -#puts f diff --git a/attributes.rb b/msbin/attributes.rb similarity index 99% rename from attributes.rb rename to msbin/attributes.rb index 1d54304..7a00cc3 100644 --- a/attributes.rb +++ b/msbin/attributes.rb @@ -1,145 +1,145 @@ -require 'record' +require 'msbin/record' module MSBIN class ShortAttribute < Record @record_type = 0x04 define_with_endelement def initialize(handle, record_type) @name = read_string(handle) @value = Record.MakeRecord(handle) end def to_s " #{@name}=\"#{@value}\"" end end # TODO: Make other attributes inherit from this to make this make more sense # TODO: Group them in a module and not have it all be flat class Attribute < Record @record_type = 0x05 def initialize(handle, record_type) @prefix = read_string(handle) @name = read_string(handle) @value = Record.MakeRecord(handle) end def to_s " #{@prefix}:#{@name}=\"#{@value}\"" end end class ShortDictionaryAttribute < Attribute @record_type = 0x06 def initialize(handle, record_type) @name = read_dictstring(handle) @value = Record.MakeRecord(handle) end def to_s " #{@name}=#{@value}" end end class DictionaryAttribute < Attribute @record_type = 0x07 # TODO: Create a read_* method for dictionary strings # TODO: finalize the read_int31 function def initialize(handle, record_type) @prefix = read_string(handle) @name = read_dictstring(handle) @value = Record.MakeRecord(handle) end def to_s " #{@prefix}:#{@name}=\"#{@value}\"" end end class PrefixAttribute < Attribute @record_type = 0x26 .. 0x3f def initialize(handle, record_type) @name = "#{(record_type-self.class.record_type.first+?a).chr}:" + read_string(handle) @record_type = record_type @value = Record.MakeRecord(handle) end def to_s " #{@name}=\"#{@value}\"" end end class PrefixDictionaryAttribute < Attribute @record_type = 0x0c .. 0x25 def initialize(handle, record_type) @name = read_dictstring(handle) @value = Record.MakeRecord(handle) @record_type = record_type end def to_s "#{@name}=\"#{@value}\"" end end class ShortDictionaryXmlnsAttribute < Attribute @record_type = 0x0a # TODO Isolate classes that do DictionaryStrings # TODO: the value will be ' xmlns="@{value}"' def initialize(handle, record_type) @value = read_dictstring(handle) end def to_s " xmlns=\"#{@value}\"" end end class DictionaryXmlnsAttribute < Attribute @record_type = 0X0b def initialize(handle, record_type) @prefix = read_string(handle) @attributes = read_dictstring(handle) end def to_s " xmlns:#{@prefix}=\"#{@attributes}\"" end end class ShortXmlnsAttribute < Attribute @record_type = 0x08 def initialize(handle, record_type) @value = read_string(handle) end def to_s " xmlns=\"#{@value}\"" end end class XmlnsAttribute < Attribute @record_type = 0x09 def initialize(handle, record_type) @prefix = read_string(handle) @value = read_string(handle) end def to_s " xmlns:#{@prefix}=\"#{@value}\"" end end end diff --git a/msbin_types.rb b/msbin/msbin_types.rb similarity index 100% rename from msbin_types.rb rename to msbin/msbin_types.rb diff --git a/record.rb b/msbin/record.rb similarity index 99% rename from record.rb rename to msbin/record.rb index a9d0669..bcebe5b 100644 --- a/record.rb +++ b/msbin/record.rb @@ -1,135 +1,135 @@ #!/usr/bin/env ruby -require 'records' +require 'msbin/records' def read_long(handle) return handle.read(4).unpack('L').first end def read_string(handle) len = read_int31(handle) str = handle.read(len) return str end def read_int8(handle) return handle.read(1)[0] end def read_int16(handle) return handle.read(2).unpack("s").first end # TODO: bundle these in a module def read_int31(handle) val = 0 pow = 1 begin byte = read_int8(handle) val += pow * (byte & 0x7F) pow *= 2**7 end while (byte & 0x80) == 0x80 return val end def read_int32(handle) return handle.read(4).unpack("L").first end def read_float(handle) return handle.read(4).unpack("g").first end def read_int64(handle) return handle.read(8).unpack("Q").first end def read_double(handle) return handle.read(8).unpack("E").first end def read_dictstring(handle) val = read_int31(handle) return MSBIN_DictionaryStrings[val] end module MSBIN class Record @@records = [] class << self attr_accessor :record_type def inherited(klass) @@records << klass end # TODO: Document this def define_with_endelement record_type = self.record_type c = Class.new(self) do @record_type = record_type+1 end name = self.name.split(':').last+"WithEndElement" MSBIN.const_set name, c end def is_attribute?(type) nil != @@records.find do |klass| klass.ancestors.include? Attribute and klass.record_type === type end end def record_type_to_class(record_type) @@records.find{|klass| klass.record_type === record_type} end def DecodeStream(handle) while !handle.eof() a = MakeRecord(handle) indent = a.class == EndElement ? -1 : 0 write_xml a, indent end end def MakeRecord(handle) record_type = read_int8(handle) klass = self.record_type_to_class(record_type) if not klass raise "Unsupported type: 0x#{record_type.to_s(16)}" end #TODO: move the 2-arg initializer to the base class somehow ret = klass.new(handle, record_type) if ret.is_a? Element and ret.class.to_s !~ /EndElement$/ $element_stack.push ret end ret end end def initialize(handle, record_type) end def get_attributes(handle) @attributes = [] loop do where = handle.pos next_type = read_int8(handle) handle.seek(where) break if not Record.is_attribute? next_type @attributes << Record.MakeRecord(handle) end end def type_of?(type) raise NotImplementedError end end end diff --git a/records.rb b/msbin/records.rb similarity index 100% rename from records.rb rename to msbin/records.rb diff --git a/text.rb b/msbin/text.rb similarity index 100% rename from text.rb rename to msbin/text.rb diff --git a/types.rb b/msbin/types.rb similarity index 96% rename from types.rb rename to msbin/types.rb index 27e5edd..2431375 100644 --- a/types.rb +++ b/msbin/types.rb @@ -1,165 +1,165 @@ #!/usr/bin/env ruby -require 'msbin_types' -require 'record' -require 'attributes' -require 'text' +require 'msbin/msbin_types' +require 'msbin/record' +require 'msbin/attributes' +require 'msbin/text' $indent = -1 def write_xml(s, increase=1, no_indent=false) indent = " "*$indent if $indent >= 0 indent = "" if no_indent print "#{indent}#{s}\n" if s.class.to_s =~ /WithEndElement$/ print "#{indent}</#{$element_stack.pop.name}>\n" increase = -1 end $indent += increase end require 'iconv' def from_unicode(str) return Iconv.conv('UTF-8', 'UTF-16LE', str) end $element_stack = [] module MSBIN class Reserved < Record @record_type = 0x00 def initialize(handle, record_type) raise "Reserved type used" end end class Element < Record end class EndElement < Element @record_type = 0x01 def to_s if !$element_stack.empty? "</#{$element_stack.pop.name}>" else "" end end end class CommentElement < Element @record_type = 0x02 def initialize(handle, record_type) @value = "<!--#{read_string(handle)}-->" end end # TODO: Implement Array # Array is extremely hacky since it writes to output directly class ArrayElement < Element @record_type = 0x03 def initialize(handle, record_type) # reset element stack element = Record.MakeRecord(handle); $element_stack.pop endelement = Record.MakeRecord(handle) type = read_int8(handle) length = read_int31(handle) cls = Record.record_type_to_class(type) length.times do |idx| $element_stack.push element write_xml(element, 1) write_xml(cls.new(handle, type), -1)#, no_indent=true) end end end class PrefixElement < Element @record_type = 0x5e .. 0x77 attr_accessor :name def initialize(handle, record_type) $indent += 1 @name = "#{(record_type-self.class.record_type.first+?a).chr}:" + read_string(handle) @record_type = record_type @attributes = [] get_attributes(handle) end def to_s attribs = @attributes.empty? ? "" : " #{@attributes}" "<#{@name}#{attribs}>" end end class PrefixDictionaryElement < Element attr_accessor :attributes @record_type = 0x44 .. 0x5D def initialize(handle, record_type) $indent += 1 @attributes = [] @record_type = record_type # read name @name = read_dictstring(handle) #puts "got name #{@name}" get_attributes(handle) end def name "#{(?a+@record_type-self.class.record_type.first).chr}:#{@name}" end def to_s attribs = @attributes.empty? ? "" : " #{@attributes}" "<#{(?a+@record_type-self.class.record_type.first).chr}:#{@name}#{attribs}>" end end class ShortElement < Element @record_type = 0x40 def initialize(handle, record_type) $indent += 1 @name = read_string(handle) get_attributes(handle) end def name @name end def to_s attribs = @attributes.empty? ? "" : " #{@attributes}" "<#{@name}#{attribs}>" end end class DictionaryElement < Element @record_type = 0x43 def initialize(handle, record_type) @prefix = read_string(handle) @name = read_dictstring(handle) get_attributes(handle) end def to_s attribs = @attributes.empty? ? "" : " #{@attributes}" "<#{@prefix}:#{@name}#{attribs}>" end end end
yan/msbin
6f54a31f5765e31809b5bc940fdd0f06935f388f
added tests/reimplemented some
diff --git a/encode.rb b/encode.rb deleted file mode 100755 index 48b8b44..0000000 --- a/encode.rb +++ /dev/null @@ -1,8 +0,0 @@ -#!/usr/bin/env ruby - -require 'rubygems' -require 'xmlsimple' - -#xml = $stdin.read - -puts XmlSimple.xml_in($stdin.read) diff --git a/msbin.rb b/msbin.rb index ea1e19a..fe3db4f 100755 --- a/msbin.rb +++ b/msbin.rb @@ -1,25 +1,25 @@ #!/usr/bin/env ruby -require 'records' +#require 'records' require 'types' if ARGV.size == 0 $stderr.write("Usage: #{$0} [file.msbin|-]\n") exit 1 end if ARGV[0] == '-' f = $stdin else f = File.new(ARGV[0], "rb") end # check if we have an http post, and consume headers if f.read(4) == "HTTP" while f.readline().chomp != ""; end else f.seek(0) end MSBIN::Record.DecodeStream(f) #puts f diff --git a/record.rb b/record.rb index 3045564..a9d0669 100644 --- a/record.rb +++ b/record.rb @@ -1,129 +1,135 @@ #!/usr/bin/env ruby +require 'records' + def read_long(handle) return handle.read(4).unpack('L').first end def read_string(handle) len = read_int31(handle) str = handle.read(len) return str end def read_int8(handle) return handle.read(1)[0] end def read_int16(handle) - return handle.read(2).unpack("n").first + return handle.read(2).unpack("s").first end # TODO: bundle these in a module def read_int31(handle) val = 0 pow = 1 begin byte = read_int8(handle) val += pow * (byte & 0x7F) pow *= 2**7 end while (byte & 0x80) == 0x80 return val end def read_int32(handle) return handle.read(4).unpack("L").first end def read_float(handle) return handle.read(4).unpack("g").first end def read_int64(handle) return handle.read(8).unpack("Q").first end def read_double(handle) return handle.read(8).unpack("E").first end def read_dictstring(handle) val = read_int31(handle) return MSBIN_DictionaryStrings[val] end module MSBIN class Record @@records = [] class << self attr_accessor :record_type def inherited(klass) @@records << klass end # TODO: Document this def define_with_endelement record_type = self.record_type c = Class.new(self) do @record_type = record_type+1 end name = self.name.split(':').last+"WithEndElement" MSBIN.const_set name, c end def is_attribute?(type) nil != @@records.find do |klass| klass.ancestors.include? Attribute and klass.record_type === type end end + + def record_type_to_class(record_type) + @@records.find{|klass| klass.record_type === record_type} + end def DecodeStream(handle) while !handle.eof() a = MakeRecord(handle) indent = a.class == EndElement ? -1 : 0 write_xml a, indent end end def MakeRecord(handle) record_type = read_int8(handle) - klass = @@records.find{|klass| klass.record_type === record_type} + klass = self.record_type_to_class(record_type) if not klass raise "Unsupported type: 0x#{record_type.to_s(16)}" end #TODO: move the 2-arg initializer to the base class somehow ret = klass.new(handle, record_type) if ret.is_a? Element and ret.class.to_s !~ /EndElement$/ $element_stack.push ret end ret end end def initialize(handle, record_type) end def get_attributes(handle) @attributes = [] loop do where = handle.pos next_type = read_int8(handle) handle.seek(where) break if not Record.is_attribute? next_type @attributes << Record.MakeRecord(handle) end end def type_of?(type) raise NotImplementedError end end end diff --git a/types.rb b/types.rb index 9f85601..27e5edd 100644 --- a/types.rb +++ b/types.rb @@ -1,149 +1,165 @@ #!/usr/bin/env ruby require 'msbin_types' require 'record' require 'attributes' require 'text' $indent = -1 -def write_xml(s, increase=1) - indent = " "*$indent - puts "#{indent}#{s}" +def write_xml(s, increase=1, no_indent=false) + indent = " "*$indent if $indent >= 0 + indent = "" if no_indent + print "#{indent}#{s}\n" if s.class.to_s =~ /WithEndElement$/ - puts "#{indent}</#{$element_stack.pop.name}>" + print "#{indent}</#{$element_stack.pop.name}>\n" increase = -1 end $indent += increase end require 'iconv' def from_unicode(str) return Iconv.conv('UTF-8', 'UTF-16LE', str) end $element_stack = [] module MSBIN class Reserved < Record @record_type = 0x00 def initialize(handle, record_type) raise "Reserved type used" end end class Element < Record end class EndElement < Element @record_type = 0x01 def to_s - "</#{$element_stack.pop.name}>" + if !$element_stack.empty? + "</#{$element_stack.pop.name}>" + else + "" + end end end class CommentElement < Element @record_type = 0x02 def initialize(handle, record_type) @value = "<!--#{read_string(handle)}-->" end end # TODO: Implement Array + # Array is extremely hacky since it writes to output directly class ArrayElement < Element @record_type = 0x03 - @records = { - 0xb5 => "Bool" - } def initialize(handle, record_type) - element = Record.MakeRecord(handle) - raise "Array not implemented yet" + # reset element stack + element = Record.MakeRecord(handle); + $element_stack.pop + endelement = Record.MakeRecord(handle) + + type = read_int8(handle) + length = read_int31(handle) + + cls = Record.record_type_to_class(type) + length.times do |idx| + $element_stack.push element + write_xml(element, 1) + write_xml(cls.new(handle, type), -1)#, no_indent=true) + end end end class PrefixElement < Element @record_type = 0x5e .. 0x77 attr_accessor :name def initialize(handle, record_type) $indent += 1 @name = "#{(record_type-self.class.record_type.first+?a).chr}:" + read_string(handle) @record_type = record_type @attributes = [] get_attributes(handle) end def to_s - attribs = @attributes ? " #{@attributes}" : "" + attribs = @attributes.empty? ? "" : " #{@attributes}" "<#{@name}#{attribs}>" end end class PrefixDictionaryElement < Element attr_accessor :attributes @record_type = 0x44 .. 0x5D def initialize(handle, record_type) $indent += 1 @attributes = [] @record_type = record_type # read name @name = read_dictstring(handle) #puts "got name #{@name}" get_attributes(handle) end def name "#{(?a+@record_type-self.class.record_type.first).chr}:#{@name}" end def to_s - attribs = @attributes ? " #{@attributes}" : "" + attribs = @attributes.empty? ? "" : " #{@attributes}" "<#{(?a+@record_type-self.class.record_type.first).chr}:#{@name}#{attribs}>" end end class ShortElement < Element @record_type = 0x40 def initialize(handle, record_type) $indent += 1 @name = read_string(handle) get_attributes(handle) end def name @name end def to_s - attribs = @attributes ? " #{@attributes}" : "" + attribs = @attributes.empty? ? "" : " #{@attributes}" "<#{@name}#{attribs}>" end end class DictionaryElement < Element @record_type = 0x43 def initialize(handle, record_type) @prefix = read_string(handle) @name = read_dictstring(handle) get_attributes(handle) end def to_s - attribs = @attributes ? " #{@attributes}" : "" + attribs = @attributes.empty? ? "" : " #{@attributes}" "<#{@prefix}:#{@name}#{attribs}>" end end end +
yan/msbin
ed909967149a45793152b27ebaf8a444523fb36d
more standardization
diff --git a/record.rb b/record.rb index 0ea1c2f..3045564 100644 --- a/record.rb +++ b/record.rb @@ -1,108 +1,129 @@ #!/usr/bin/env ruby -def read_byte(handle) - return handle.read(1)[0] +def read_long(handle) + return handle.read(4).unpack('L').first +end + +def read_string(handle) + len = read_int31(handle) + str = handle.read(len) + return str +end + +def read_int8(handle) + return handle.read(1)[0] +end + +def read_int16(handle) + return handle.read(2).unpack("n").first end # TODO: bundle these in a module def read_int31(handle) val = 0 pow = 1 begin - byte = read_byte(handle) + byte = read_int8(handle) val += pow * (byte & 0x7F) pow *= 2**7 end while (byte & 0x80) == 0x80 return val end -def read_long(handle) - return handle.read(4).unpack('L').first +def read_int32(handle) + return handle.read(4).unpack("L").first end -def read_string(handle) - len = read_int31(handle) - str = handle.read(len) - return str +def read_float(handle) + return handle.read(4).unpack("g").first end +def read_int64(handle) + return handle.read(8).unpack("Q").first +end + +def read_double(handle) + return handle.read(8).unpack("E").first +end + + def read_dictstring(handle) val = read_int31(handle) return MSBIN_DictionaryStrings[val] end module MSBIN class Record @@records = [] class << self attr_accessor :record_type def inherited(klass) @@records << klass end - # Document this + # TODO: Document this def define_with_endelement record_type = self.record_type c = Class.new(self) do @record_type = record_type+1 end name = self.name.split(':').last+"WithEndElement" MSBIN.const_set name, c end def is_attribute?(type) nil != @@records.find do |klass| klass.ancestors.include? Attribute and klass.record_type === type end end def DecodeStream(handle) while !handle.eof() a = MakeRecord(handle) indent = a.class == EndElement ? -1 : 0 write_xml a, indent end end def MakeRecord(handle) - record_type = read_byte(handle) + record_type = read_int8(handle) klass = @@records.find{|klass| klass.record_type === record_type} if not klass raise "Unsupported type: 0x#{record_type.to_s(16)}" end #TODO: move the 2-arg initializer to the base class somehow ret = klass.new(handle, record_type) if ret.is_a? Element and ret.class.to_s !~ /EndElement$/ $element_stack.push ret end ret end end def initialize(handle, record_type) end def get_attributes(handle) @attributes = [] loop do where = handle.pos - next_type = read_byte(handle) + next_type = read_int8(handle) handle.seek(where) break if not Record.is_attribute? next_type @attributes << Record.MakeRecord(handle) end end def type_of?(type) raise NotImplementedError end end end diff --git a/text.rb b/text.rb index 1a7d217..c60944d 100644 --- a/text.rb +++ b/text.rb @@ -1,382 +1,381 @@ module MSBIN # Make this an ADT class TextRecord < Record @record_type = 0x00 def initialize(handle, record_type) @record_type = record_type end def to_s @value.to_s end end class ZeroText < TextRecord @record_type = 0x80 define_with_endelement def to_s; "0"; end end class TrueText < TextRecord @record_type = 0x86 define_with_endelement def to_s; "true"; end end - # TODO: make this derive from TextRecord class FalseText < TextRecord @record_type = 0x84 define_with_endelement def to_s; "false"; end end class OneText < TextRecord @record_type = 0x82 define_with_endelement def to_s; "1"; end end # TODO: Parse this better class DateTimeText < TextRecord @record_type = 0x96 define_with_endelement def initialize(handle, record_type) # TODO: validate it @date_date - val = handle.read(8).unpack("Q")[0] + val = read_int64(handle) @tz = val & 0xff val >>= 2 # to microseconds val /= 10 # to seconds val /= (10**6) # seconds since year 1 until epoch start = Time.utc(1, "jan", 1, 0, 0, 0, 0) epoch = Time.at(0) # seconds since 0 val -= (epoch - start) # val is now epoch # not sure if this is correct, but it'll do for now time = Time.at(val) if time.hour == 0 and time.minutes == 0 and time.seconds == 0 @value = time.strftime("%Y-%m-%d") else @value = time.strftime("%Y-%m-%dT%H:%M:%S") end end end class DictionaryText < TextRecord @record_type = 0xaa define_with_endelement def initialize(handle, record_type) @value = read_dictstring(handle) end end class Chars8Text < TextRecord @record_type = 0x98 define_with_endelement def initialize(handle, record_type) require 'cgi' - length = handle.read(1)[0] + length = read_int8(handle) @value = CGI.escapeHTML(handle.read(length)).to_s end end class Chars16Text < TextRecord @record_type = 0x9a define_with_endelement def initialize(handle, record_type) require 'cgi' - length = handle.read(2).unpack("n")[0] + length = read_int16(handle) @value = CGI.escapeHTML(handle.read(length)).to_s end end class Chars32Text < TextRecord @record_type = 0x9c define_with_endelement def initialize(hand,record_type) require 'cgi' - length = handle.read(4).unpack("l")[0] + length = read_int32(handle) @value = CGI.escapeHTML(handle.read(length)).to_s end end class UuIdText < TextRecord @record_type = 0xac define_with_endelement def initialize(handle, record_type) @uuid = handle.read(16).unpack('VvvC*') @value = ("%08x-%04x-%04x-" % [@uuid[0], @uuid[1], @uuid[2]])+(("%02x"*6) % @uuid[3..-1]) end end class TimeSpanText < TextRecord @record_type = 0xae define_with_endelement def initialize(handle, record_type) @value = handle.read(8).unpack("q")[0] if @value < 0 @sign = '-'; @value *= -1 end ticks_in_sec = 10000000 @frac = @value % ticks_in_sec; @value /= ticks_in_sec @seconds = @value % 60; @value /= 60 @minutes = @value % 60; @value /= 60 @hours = @value % 24; @value /= 24 @days = @value end def to_s if @days > 0 and @frac == 0 "#{@sign}%d.%02d:%02d:%02d" % [@days, @hours, @minutes, @seconds] elsif @days > 0 and @frac > 0 "#{@sign}%d.%02d:%02d:%02d:%d" % [@days, @hours, @minutes, @seconds, @frac] elsif @days == 0 and @frac == 0 "#{@sign}%02d:%02d:%02d" % [@hours, @minutes, @seconds] else "#{@sign}%02d:%02d:%02d.%d" % [@hours, @minutes, @seconds, @frac] end end end class Int8Text < TextRecord @record_type = 0x88 define_with_endelement def initialize(handle, record_type) - @value = handle.read(1)[0].to_s + @value = read_int8(handle).to_s end end class Int16Text < TextRecord @record_type = 0x8a define_with_endelement def initialize(handle, record_type) - @value = handle.read(2).unpack("n")[0].to_s + @value = read_int16(handle).to_s end end class Int32Text < TextRecord @record_type = 0x8c define_with_endelement def initialize(handle, record_type) - @value = handle.read(4).unpack("l")[0].to_s + @value = read_int32(handle).to_s end end class Int64Text < TextRecord @record_type = 0x8e define_with_endelement def initialize(handle, record_type) - @value = handle.read(8).unpack("q")[0].to_s + @value = read_int64(handle).to_s end end class FloatText < TextRecord @record_type = 0x90 define_with_endelement def initialize(handle, record_type) - @value = handle.read(4).unpack("g")[0].to_s + @value = read_float(handle).to_s end end class DoubleText < TextRecord @record_type = 0x92 define_with_endelement def initialize(handle, record_type) - @value = handle.read(8).unpack("E")[0].to_s + @value = read_double(handle).to_s end end class DecimalText < TextRecord @record_type = 0x94 define_with_endelement def initialize(handle, record_type) - wReserved = handle.read(2).unpack("n")[0] - scale = handle.read(1)[0] - @sign = handle.read(1)[0] == 0 ? "" : "-" + wReserved = read_int16(handle) + scale = read_int8(handle) + @sign = read_int8(handle) == 0 ? "" : "-" @value = 0 2.downto(0).each {|n| @value |= (handle.read(4).unpack("N")[0]) << 32*n - puts "#{@value.to_s 16}" } @value /= 10.0**scale end def to_s "#{@sign}#{@value}" end end class UnicodeChars8Text < TextRecord @record_type = 0xb6 define_with_endelement def initialize(handle, record_type) - length = handle.read(1)[0] + length = read_int8(handle) @value = from_unicode(handle.read(length)) end end class UnicodeChars16Text < TextRecord @record_type = 0xb8 define_with_endelement def initialize(handle, record_type) - length = handle.read(2).unpack("n")[0] + length = read_int16(handle) @value = from_unicode(handle.read(length)) end end class UnicodeChars32Text < TextRecord @record_type = 0xba define_with_endelement def initialize(handle, record_type) - length = handle.read(4).unpack("l")[0] + length = read_int32(handle) @value = from_unicode(handle.read(length)) end end class BoolText < TextRecord @record_type = 0xb4 define_with_endelement def initialize(handle, record_type) - val = handle.read(1)[0] + val = read_int8(handle) @value = val == 0 ? "false" : "true" end end class UInt64Text < TextRecord @record_type = 0xb2 define_with_endelement def initialize(handle, record_type) + # unsigned @value = handle.read(8).unpack("Q")[0].to_s end end class StartListText < TextRecord @record_type = 0xa4 def initialize(handle, record_type) @records = [] begin record = Record.MakeRecord(handle) @records << record end until record.is_a?(EndListText) @value = @records.map{|x|x.strip}.join(" ") end end class EndListText < TextRecord @record_type = 0xa6 def to_s; ""; end end class EmptyText < TextRecord @record_type = 0xa8 define_with_endelement def to_s; ""; end end class QNameDictionaryText < TextRecord @record_type = 0xbc define_with_endelement def initialize(handle, record_type) val = handle.read(4).unpack("L")[0] @prefix = (((val >> 24) & 0xff) + ?a).chr val &= 0x00ffffff @value = "#{@prefix}:#{MSBIN_DictionaryStrings[val]}" end end class Bytes8Text < TextRecord @record_type = 0x9e define_with_endelement # TODO: Rewrite all these custom reads to util funcs def initialize(handle, record_type) - length = handle.read(1)[0] + length = read_int8(handle) bytes = handle.read(length) require 'base64' @value = Base64.b64encode(bytes).rstrip end end class Bytes16Text < TextRecord @record_type = 0xa0 define_with_endelement # TODO: factor out everything but length def initialize(handle, record_type) - length = handle.read(2).unpack("n")[0] + length = read_int16(handle) bytes = handle.read(length) require 'base64' @value = Base64.b64encode(bytes).rstrip end end class Bytes32Text < TextRecord @record_type = 0xa2 define_with_endelement def initialize(handle, record_type) - length = handle.read(4).unpack("l")[0] + length = read_int32(handle) bytes = handle.read(length) require 'base64' @value = Base64.b64encode(bytes).rstrip end end end
yan/msbin
2d580b91ccf6fbdf6db8a1e9157d749aaecd45c9
started splitting up types
diff --git a/attributes.rb b/attributes.rb new file mode 100644 index 0000000..1d54304 --- /dev/null +++ b/attributes.rb @@ -0,0 +1,145 @@ +require 'record' + +module MSBIN + class ShortAttribute < Record + @record_type = 0x04 + + define_with_endelement + + def initialize(handle, record_type) + @name = read_string(handle) + @value = Record.MakeRecord(handle) + end + + def to_s + " #{@name}=\"#{@value}\"" + end + end + + # TODO: Make other attributes inherit from this to make this make more sense + # TODO: Group them in a module and not have it all be flat + class Attribute < Record + @record_type = 0x05 + + def initialize(handle, record_type) + @prefix = read_string(handle) + @name = read_string(handle) + @value = Record.MakeRecord(handle) + end + + def to_s + " #{@prefix}:#{@name}=\"#{@value}\"" + end + end + + class ShortDictionaryAttribute < Attribute + @record_type = 0x06 + + def initialize(handle, record_type) + @name = read_dictstring(handle) + @value = Record.MakeRecord(handle) + end + + def to_s + " #{@name}=#{@value}" + end + end + + class DictionaryAttribute < Attribute + @record_type = 0x07 + + # TODO: Create a read_* method for dictionary strings + # TODO: finalize the read_int31 function + def initialize(handle, record_type) + @prefix = read_string(handle) + @name = read_dictstring(handle) + @value = Record.MakeRecord(handle) + end + + def to_s + " #{@prefix}:#{@name}=\"#{@value}\"" + end + end + + class PrefixAttribute < Attribute + @record_type = 0x26 .. 0x3f + + def initialize(handle, record_type) + @name = "#{(record_type-self.class.record_type.first+?a).chr}:" + read_string(handle) + @record_type = record_type + @value = Record.MakeRecord(handle) + end + + def to_s + " #{@name}=\"#{@value}\"" + end + end + + class PrefixDictionaryAttribute < Attribute + @record_type = 0x0c .. 0x25 + + def initialize(handle, record_type) + @name = read_dictstring(handle) + @value = Record.MakeRecord(handle) + @record_type = record_type + end + + def to_s + "#{@name}=\"#{@value}\"" + end + end + + class ShortDictionaryXmlnsAttribute < Attribute + @record_type = 0x0a + + # TODO Isolate classes that do DictionaryStrings + # TODO: the value will be ' xmlns="@{value}"' + def initialize(handle, record_type) + @value = read_dictstring(handle) + end + + def to_s + " xmlns=\"#{@value}\"" + end + end + + class DictionaryXmlnsAttribute < Attribute + @record_type = 0X0b + + def initialize(handle, record_type) + @prefix = read_string(handle) + @attributes = read_dictstring(handle) + end + + def to_s + " xmlns:#{@prefix}=\"#{@attributes}\"" + end + end + + class ShortXmlnsAttribute < Attribute + @record_type = 0x08 + + def initialize(handle, record_type) + @value = read_string(handle) + end + + def to_s + " xmlns=\"#{@value}\"" + end + end + + class XmlnsAttribute < Attribute + @record_type = 0x09 + + def initialize(handle, record_type) + @prefix = read_string(handle) + @value = read_string(handle) + end + + def to_s + " xmlns:#{@prefix}=\"#{@value}\"" + end + end + + +end diff --git a/record.rb b/record.rb new file mode 100644 index 0000000..0ea1c2f --- /dev/null +++ b/record.rb @@ -0,0 +1,108 @@ +#!/usr/bin/env ruby + +def read_byte(handle) + return handle.read(1)[0] +end + +# TODO: bundle these in a module +def read_int31(handle) + val = 0 + pow = 1 + begin + byte = read_byte(handle) + val += pow * (byte & 0x7F) + pow *= 2**7 + end while (byte & 0x80) == 0x80 + return val +end + +def read_long(handle) + return handle.read(4).unpack('L').first +end + +def read_string(handle) + len = read_int31(handle) + str = handle.read(len) + return str +end + +def read_dictstring(handle) + val = read_int31(handle) + return MSBIN_DictionaryStrings[val] +end + + +module MSBIN + class Record + @@records = [] + + class << self + attr_accessor :record_type + + def inherited(klass) + @@records << klass + end + + # Document this + def define_with_endelement + record_type = self.record_type + c = Class.new(self) do + @record_type = record_type+1 + end + + name = self.name.split(':').last+"WithEndElement" + MSBIN.const_set name, c + end + + def is_attribute?(type) + nil != @@records.find do |klass| + klass.ancestors.include? Attribute and klass.record_type === type + end + end + + def DecodeStream(handle) + while !handle.eof() + a = MakeRecord(handle) + indent = a.class == EndElement ? -1 : 0 + write_xml a, indent + end + end + + def MakeRecord(handle) + record_type = read_byte(handle) + klass = @@records.find{|klass| klass.record_type === record_type} + if not klass + raise "Unsupported type: 0x#{record_type.to_s(16)}" + end + #TODO: move the 2-arg initializer to the base class somehow + ret = klass.new(handle, record_type) + + if ret.is_a? Element and ret.class.to_s !~ /EndElement$/ + $element_stack.push ret + end + + ret + end + end + + def initialize(handle, record_type) + end + + def get_attributes(handle) + @attributes = [] + loop do + where = handle.pos + next_type = read_byte(handle) + handle.seek(where) + + break if not Record.is_attribute? next_type + @attributes << Record.MakeRecord(handle) + end + end + def type_of?(type) + raise NotImplementedError + end + end +end + + diff --git a/text.rb b/text.rb new file mode 100644 index 0000000..1a7d217 --- /dev/null +++ b/text.rb @@ -0,0 +1,382 @@ + +module MSBIN + # Make this an ADT + class TextRecord < Record + @record_type = 0x00 + def initialize(handle, record_type) + @record_type = record_type + end + def to_s + @value.to_s + end + end + + class ZeroText < TextRecord + @record_type = 0x80 + define_with_endelement + def to_s; "0"; end + end + + class TrueText < TextRecord + @record_type = 0x86 + define_with_endelement + def to_s; "true"; end + end + + # TODO: make this derive from TextRecord + class FalseText < TextRecord + @record_type = 0x84 + define_with_endelement + def to_s; "false"; end + end + + class OneText < TextRecord + @record_type = 0x82 + define_with_endelement + def to_s; "1"; end + end + + # TODO: Parse this better + class DateTimeText < TextRecord + @record_type = 0x96 + + define_with_endelement + + def initialize(handle, record_type) + # TODO: validate it + @date_date + val = handle.read(8).unpack("Q")[0] + + @tz = val & 0xff + val >>= 2 + + # to microseconds + val /= 10 + + # to seconds + val /= (10**6) + + # seconds since year 1 until epoch + start = Time.utc(1, "jan", 1, 0, 0, 0, 0) + epoch = Time.at(0) + # seconds since 0 + val -= (epoch - start) + + # val is now epoch + # not sure if this is correct, but it'll do for now + time = Time.at(val) + if time.hour == 0 and time.minutes == 0 and time.seconds == 0 + @value = time.strftime("%Y-%m-%d") + else + @value = time.strftime("%Y-%m-%dT%H:%M:%S") + end + end + end + + class DictionaryText < TextRecord + @record_type = 0xaa + + define_with_endelement + + def initialize(handle, record_type) + @value = read_dictstring(handle) + end + end + + class Chars8Text < TextRecord + @record_type = 0x98 + + define_with_endelement + + def initialize(handle, record_type) + require 'cgi' + length = handle.read(1)[0] + @value = CGI.escapeHTML(handle.read(length)).to_s + end + end + + class Chars16Text < TextRecord + @record_type = 0x9a + + define_with_endelement + + def initialize(handle, record_type) + require 'cgi' + length = handle.read(2).unpack("n")[0] + @value = CGI.escapeHTML(handle.read(length)).to_s + end + end + + class Chars32Text < TextRecord + @record_type = 0x9c + + define_with_endelement + + def initialize(hand,record_type) + require 'cgi' + length = handle.read(4).unpack("l")[0] + @value = CGI.escapeHTML(handle.read(length)).to_s + end + end + + class UuIdText < TextRecord + @record_type = 0xac + + define_with_endelement + + def initialize(handle, record_type) + @uuid = handle.read(16).unpack('VvvC*') + @value = ("%08x-%04x-%04x-" % [@uuid[0], @uuid[1], @uuid[2]])+(("%02x"*6) % @uuid[3..-1]) + end + end + + class TimeSpanText < TextRecord + @record_type = 0xae + + define_with_endelement + + def initialize(handle, record_type) + @value = handle.read(8).unpack("q")[0] + if @value < 0 + @sign = '-'; @value *= -1 + end + + ticks_in_sec = 10000000 + @frac = @value % ticks_in_sec; @value /= ticks_in_sec + @seconds = @value % 60; @value /= 60 + @minutes = @value % 60; @value /= 60 + @hours = @value % 24; @value /= 24 + @days = @value + end + + def to_s + if @days > 0 and @frac == 0 + "#{@sign}%d.%02d:%02d:%02d" % [@days, @hours, @minutes, @seconds] + elsif @days > 0 and @frac > 0 + "#{@sign}%d.%02d:%02d:%02d:%d" % [@days, @hours, @minutes, @seconds, @frac] + elsif @days == 0 and @frac == 0 + "#{@sign}%02d:%02d:%02d" % [@hours, @minutes, @seconds] + else + "#{@sign}%02d:%02d:%02d.%d" % [@hours, @minutes, @seconds, @frac] + end + end + end + + class Int8Text < TextRecord + @record_type = 0x88 + + define_with_endelement + + def initialize(handle, record_type) + @value = handle.read(1)[0].to_s + end + end + + class Int16Text < TextRecord + @record_type = 0x8a + + define_with_endelement + + def initialize(handle, record_type) + @value = handle.read(2).unpack("n")[0].to_s + end + end + + class Int32Text < TextRecord + @record_type = 0x8c + + define_with_endelement + + def initialize(handle, record_type) + @value = handle.read(4).unpack("l")[0].to_s + end + end + + class Int64Text < TextRecord + @record_type = 0x8e + + define_with_endelement + + def initialize(handle, record_type) + @value = handle.read(8).unpack("q")[0].to_s + end + end + + class FloatText < TextRecord + @record_type = 0x90 + + define_with_endelement + + def initialize(handle, record_type) + @value = handle.read(4).unpack("g")[0].to_s + end + end + + class DoubleText < TextRecord + @record_type = 0x92 + + define_with_endelement + + def initialize(handle, record_type) + @value = handle.read(8).unpack("E")[0].to_s + end + end + + class DecimalText < TextRecord + @record_type = 0x94 + + define_with_endelement + + def initialize(handle, record_type) + wReserved = handle.read(2).unpack("n")[0] + scale = handle.read(1)[0] + @sign = handle.read(1)[0] == 0 ? "" : "-" + @value = 0 + 2.downto(0).each {|n| + @value |= (handle.read(4).unpack("N")[0]) << 32*n + puts "#{@value.to_s 16}" + } + @value /= 10.0**scale + end + + def to_s + "#{@sign}#{@value}" + end + end + + class UnicodeChars8Text < TextRecord + @record_type = 0xb6 + + define_with_endelement + + def initialize(handle, record_type) + length = handle.read(1)[0] + @value = from_unicode(handle.read(length)) + end + end + + class UnicodeChars16Text < TextRecord + @record_type = 0xb8 + + define_with_endelement + + def initialize(handle, record_type) + length = handle.read(2).unpack("n")[0] + @value = from_unicode(handle.read(length)) + end + end + + class UnicodeChars32Text < TextRecord + @record_type = 0xba + + define_with_endelement + + def initialize(handle, record_type) + length = handle.read(4).unpack("l")[0] + @value = from_unicode(handle.read(length)) + end + end + + class BoolText < TextRecord + @record_type = 0xb4 + + define_with_endelement + + def initialize(handle, record_type) + val = handle.read(1)[0] + @value = val == 0 ? "false" : "true" + end + end + + class UInt64Text < TextRecord + @record_type = 0xb2 + + define_with_endelement + + def initialize(handle, record_type) + @value = handle.read(8).unpack("Q")[0].to_s + end + end + + class StartListText < TextRecord + @record_type = 0xa4 + + def initialize(handle, record_type) + @records = [] + begin + record = Record.MakeRecord(handle) + @records << record + end until record.is_a?(EndListText) + + @value = @records.map{|x|x.strip}.join(" ") + end + end + + class EndListText < TextRecord + @record_type = 0xa6 + def to_s; ""; end + end + + class EmptyText < TextRecord + @record_type = 0xa8 + define_with_endelement + def to_s; ""; end + end + + class QNameDictionaryText < TextRecord + @record_type = 0xbc + + define_with_endelement + + def initialize(handle, record_type) + val = handle.read(4).unpack("L")[0] + @prefix = (((val >> 24) & 0xff) + ?a).chr + val &= 0x00ffffff + @value = "#{@prefix}:#{MSBIN_DictionaryStrings[val]}" + end + end + + class Bytes8Text < TextRecord + @record_type = 0x9e + + define_with_endelement + + # TODO: Rewrite all these custom reads to util funcs + def initialize(handle, record_type) + length = handle.read(1)[0] + bytes = handle.read(length) + + require 'base64' + @value = Base64.b64encode(bytes).rstrip + end + end + + class Bytes16Text < TextRecord + @record_type = 0xa0 + + define_with_endelement + + # TODO: factor out everything but length + def initialize(handle, record_type) + length = handle.read(2).unpack("n")[0] + bytes = handle.read(length) + + require 'base64' + @value = Base64.b64encode(bytes).rstrip + end + end + + class Bytes32Text < TextRecord + @record_type = 0xa2 + + define_with_endelement + + def initialize(handle, record_type) + length = handle.read(4).unpack("l")[0] + bytes = handle.read(length) + + require 'base64' + @value = Base64.b64encode(bytes).rstrip + end + end +end diff --git a/types.rb b/types.rb index 75c287d..9f85601 100644 --- a/types.rb +++ b/types.rb @@ -1,838 +1,149 @@ #!/usr/bin/env ruby require 'msbin_types' - -#TODO: Separate attributes, text records, etc into separate files and modules +require 'record' +require 'attributes' +require 'text' $indent = -1 def write_xml(s, increase=1) indent = " "*$indent puts "#{indent}#{s}" if s.class.to_s =~ /WithEndElement$/ puts "#{indent}</#{$element_stack.pop.name}>" increase = -1 end $indent += increase end -def read_byte(handle) - return handle.read(1)[0] -end - -# TODO: bundle these in a module -def read_int31(handle) - val = 0 - pow = 1 - begin - byte = read_byte(handle) - val += pow * (byte & 0x7F) - pow *= 2**7 - end while (byte & 0x80) == 0x80 - return val -end - -def read_long(handle) - return handle.read(4).unpack('L').first -end - -def read_string(handle) - len = read_int31(handle) - str = handle.read(len) - return str -end - -def read_dictstring(handle) - val = read_int31(handle) - return MSBIN_DictionaryStrings[val] -end require 'iconv' def from_unicode(str) return Iconv.conv('UTF-8', 'UTF-16LE', str) end $element_stack = [] -class Class -end - -module MSBIN - - class Record - @@records = [] - - class << self - attr_accessor :record_type - - def inherited(klass) - @@records << klass - end - - # Document this - def define_with_endelement - record_type = self.record_type - c = Class.new(self) do - @record_type = record_type+1 - end - - name = self.name.split(':').last+"WithEndElement" - MSBIN.const_set name, c - end - - def is_attribute?(type) - nil != @@records.find {|klass| klass.ancestors.include? Attribute and klass.record_type === type} - end - - def DecodeStream(handle) - while !handle.eof() - a = MakeRecord(handle) - indent = a.class == EndElement ? -1 : 0 - write_xml a, indent - end - end - - def MakeRecord(handle) - record_type = read_byte(handle) - klass = @@records.find{|klass| klass.record_type === record_type} - if not klass - raise "Unsupported type: 0x#{record_type.to_s(16)}" - end - #TODO: move the 2-arg initializer to the base class somehow - ret = klass.new(handle, record_type) - - if ret.is_a? Element and ret.class.to_s !~ /EndElement$/ - $element_stack.push ret - end - - ret - end - end - - def initialize(handle, record_type) - end - - def get_attributes(handle) - @attributes = [] - loop do - where = handle.pos - next_type = read_byte(handle) - handle.seek(where) - - break if not Record.is_attribute? next_type - @attributes << Record.MakeRecord(handle) - end - end - - def type_of?(type) - raise NotImplementedError - end - end -end - module MSBIN class Reserved < Record @record_type = 0x00 def initialize(handle, record_type) raise "Reserved type used" end end - class Element < Record; end + class Element < Record + end class EndElement < Element @record_type = 0x01 def to_s "</#{$element_stack.pop.name}>" end end class CommentElement < Element @record_type = 0x02 def initialize(handle, record_type) @value = "<!--#{read_string(handle)}-->" end end # TODO: Implement Array class ArrayElement < Element @record_type = 0x03 @records = { 0xb5 => "Bool" } def initialize(handle, record_type) element = Record.MakeRecord(handle) raise "Array not implemented yet" end end - class ShortAttribute < Record - @record_type = 0x04 - - self.make_this_with_endelement - - def initialize(handle, record_type) - @name = read_string(handle) - @value = Record.MakeRecord(handle) - end - - def to_s - " #{@name}=\"#{@value}\"" - end - end - - # TODO: Make other attributes inherit from this to make this make more sense - # TODO: Group them in a module and not have it all be flat - class Attribute < Record - @record_type = 0x05 - - def initialize(handle, record_type) - @prefix = read_string(handle) - @name = read_string(handle) - @value = Record.MakeRecord(handle) - end - - def to_s - " #{@prefix}:#{@name}=\"#{@value}\"" - end - end - - class ShortDictionaryAttribute < Attribute - @record_type = 0x06 - - def initialize(handle, record_type) - @name = read_dictstring(handle) - @value = Record.MakeRecord(handle) - end - - def to_s - " #{@name}=#{@value}" - end - end - - class DictionaryAttribute < Attribute - @record_type = 0x07 - - # TODO: Create a read_* method for dictionary strings - # TODO: finalize the read_int31 function - def initialize(handle, record_type) - @prefix = read_string(handle) - @name = read_dictstring(handle) - @value = Record.MakeRecord(handle) - end - - def to_s - " #{@prefix}:#{@name}=\"#{@value}\"" - end - end - class PrefixElement < Element @record_type = 0x5e .. 0x77 attr_accessor :name def initialize(handle, record_type) $indent += 1 @name = "#{(record_type-self.class.record_type.first+?a).chr}:" + read_string(handle) @record_type = record_type @attributes = [] get_attributes(handle) end def to_s attribs = @attributes ? " #{@attributes}" : "" "<#{@name}#{attribs}>" end end - class PrefixAttribute < Attribute - @record_type = 0x26 .. 0x3f - - def initialize(handle, record_type) - @name = "#{(record_type-self.class.record_type.first+?a).chr}:" + read_string(handle) - @record_type = record_type - @value = Record.MakeRecord(handle) - end - - def to_s - " #{@name}=\"#{@value}\"" - end - end - class PrefixDictionaryElement < Element attr_accessor :attributes @record_type = 0x44 .. 0x5D def initialize(handle, record_type) $indent += 1 @attributes = [] @record_type = record_type # read name @name = read_dictstring(handle) - # TODO fill proper string names #puts "got name #{@name}" get_attributes(handle) end def name "#{(?a+@record_type-self.class.record_type.first).chr}:#{@name}" end def to_s attribs = @attributes ? " #{@attributes}" : "" "<#{(?a+@record_type-self.class.record_type.first).chr}:#{@name}#{attribs}>" end end - class PrefixDictionaryAttribute < Attribute - @record_type = 0x0c .. 0x25 - - def initialize(handle, record_type) - @name = read_dictstring(handle) - @value = Record.MakeRecord(handle) - @record_type = record_type - end - - def to_s - "#{@name}=\"#{@value}\"" - end - end - - class ShortDictionaryXmlnsAttribute < Attribute - @record_type = 0x0a - - # TODO Isolate classes that do DictionaryStrings - # TODO: the value will be ' xmlns="@{value}"' - def initialize(handle, record_type) - @value = read_dictstring(handle) - end - - def to_s - " xmlns=\"#{@value}\"" - end - end - - class DictionaryXmlnsAttribute < Attribute - @record_type = 0X0b - - def initialize(handle, record_type) - @prefix = read_string(handle) - @attributes = read_dictstring(handle) - end - - def to_s - " xmlns:#{@prefix}=\"#{@attributes}\"" - end - end - - class ShortXmlnsAttribute < Attribute - @record_type = 0x08 - - def initialize(handle, record_type) - @value = read_string(handle) - end - - def to_s - " xmlns=\"#{@value}\"" - end - end - - class XmlnsAttribute < Attribute - @record_type = 0x09 - - def initialize(handle, record_type) - @prefix = read_string(handle) - @value = read_string(handle) - end - - def to_s - " xmlns:#{@prefix}=\"#{@value}\"" - end - end - class ShortElement < Element @record_type = 0x40 def initialize(handle, record_type) $indent += 1 @name = read_string(handle) get_attributes(handle) end def name @name end def to_s attribs = @attributes ? " #{@attributes}" : "" "<#{@name}#{attribs}>" end end - # Make this an ADT - class TextRecord < Record - @record_type = 0x00 - def initialize(handle, record_type) - @record_type = record_type - end - def to_s - @value.to_s - end - end - - class ZeroText < TextRecord - @record_type = 0x80 - def to_s; "0"; end - end - - class ZeroTextWithEndElement < ZeroText - @record_type = 0x81 - end - - class TrueText < TextRecord - @record_type = 0x86 - def to_s; "true"; end - end - - class TrueTextWithEndElement < TrueText - @record_type = 0x87 - end - - # TODO: make this derive from TextRecord - class FalseText < TextRecord - @record_type = 0x84 - def to_s; "false"; end - end - - class FalseTextWithEndElement < FalseText - @record_type = 0x85 - end - - class OneText < TextRecord - @record_type = 0x82 - def to_s; "1"; end - end - - class OneTextWithEndElement < OneText - @record_type = 0x83 - end - - # TODO: Parse this better - class DateTimeText < TextRecord - @record_type = 0x96 - - def initialize(handle, record_type) - # TODO: validate it - @date_date - val = handle.read(8).unpack("Q")[0] - - @tz = val & 0xff - val >>= 2 - - # to microseconds - val /= 10 - - # to seconds - val /= (10**6) - - # seconds since year 1 until epoch - start = Time.utc(1, "jan", 1, 0, 0, 0, 0) - epoch = Time.at(0) - # seconds since 0 - val -= (epoch - start) - - # val is now epoch - # not sure if this is correct, but it'll do for now - time = Time.at(val) - if time.hour == 0 and time.minutes == 0 and time.seconds == 0 - @value = time.strftime("%Y-%m-%d") - else - @value = time.strftime("%Y-%m-%dT%H:%M:%S") - end - end - end - - class DateTimeTextWithEndElement < DateTimeText - @record_type = 0x97 - end - - class DictionaryText < TextRecord - @record_type = 0xaa - - def initialize(handle, record_type) - @value = read_dictstring(handle) - end - end - - class DictionaryTextWithEndElement < DictionaryText - @record_type = 0xab - end - - class Chars8Text < TextRecord - @record_type = 0x98 - - def initialize(handle, record_type) - require 'cgi' - length = handle.read(1)[0] - @value = CGI.escapeHTML(handle.read(length)).to_s - end - end - - # TODO: Clean up the end element - class Chars8TextWithEndElement < Chars8Text - @record_type = 0x99 - end - - class Chars16Text < TextRecord - @record_type = 0x9a - - def initialize(handle, record_type) - require 'cgi' - length = handle.read(2).unpack("n")[0] - @value = CGI.escapeHTML(handle.read(length)).to_s - end - end - - # TODO: Clean up the end element - class Chars16TextWithEndElement < Chars16Text - @record_type = 0x9b - end - - class Chars32Text < TextRecord - @record_type = 0x9c - - def initialize(hand,record_type) - require 'cgi' - length = handle.read(4).unpack("l")[0] - @value = CGI.escapeHTML(handle.read(length)).to_s - end - end - - class Chars32TextWithEndElement < Chars32Text - @record_type = 0x9d - end - - class UuIdText < TextRecord - @record_type = 0xac - - def initialize(handle, record_type) - @uuid = handle.read(16).unpack('VvvC*') - @value = ("%08x-%04x-%04x-" % [@uuid[0], @uuid[1], @uuid[2]])+(("%02x"*6) % @uuid[3..-1]) - end - end - - # TODO: Separate this - class UuIdTextWithEndElement < UuIdText - @record_type = 0xad - end - - class TimeSpanText < TextRecord - @record_type = 0xae - - def initialize(handle, record_type) - @value = handle.read(8).unpack("q")[0] - if @value < 0 - @sign = '-'; @value *= -1 - end - - ticks_in_sec = 10000000 - @frac = @value % ticks_in_sec; @value /= ticks_in_sec - @seconds = @value % 60; @value /= 60 - @minutes = @value % 60; @value /= 60 - @hours = @value % 24; @value /= 24 - @days = @value - end - - def to_s - if @days > 0 and @frac == 0 - "#{@sign}%d.%02d:%02d:%02d" % [@days, @hours, @minutes, @seconds] - elsif @days > 0 and @frac > 0 - "#{@sign}%d.%02d:%02d:%02d:%d" % [@days, @hours, @minutes, @seconds, @frac] - elsif @days == 0 and @frac == 0 - "#{@sign}%02d:%02d:%02d" % [@hours, @minutes, @seconds] - else - "#{@sign}%02d:%02d:%02d.%d" % [@hours, @minutes, @seconds, @frac] - end - end - end - - class TimeSpanTextWithEndElement < TimeSpanText - @record_type = 0xaf - end - - class Int8Text < TextRecord - @record_type = 0x88 - - def initialize(handle, record_type) - @value = handle.read(1)[0].to_s - end - end - - class Int8TextWithEndElement < Int8Text - @record_type = 0x89 - end - - class Int16Text < TextRecord - @record_type = 0x8a - - def initialize(handle, record_type) - @value = handle.read(2).unpack("n")[0].to_s - end - end - - class Int16TextWithEndElement < Int16Text - @record_type = 0x8b - end - - class Int32Text < TextRecord - @record_type = 0x8c - - def initialize(handle, record_type) - @value = handle.read(4).unpack("l")[0].to_s - end - end - - class Int32TextWithEndElement < Int32Text - @record_type = 0x8d - end - - class Int64Text < TextRecord - @record_type = 0x8e - - def initialize(handle, record_type) - @value = handle.read(8).unpack("q")[0].to_s - end - end - - class Int64TextWithEndElement < Int64Text - @record_type = 0x8f - end - - class FloatText < TextRecord - @record_type = 0x90 - - def initialize(handle, record_type) - @value = handle.read(4).unpack("g")[0].to_s - end - end - - class FloatTextWithEndRecord < FloatText - @record_type = 0x91 - end - - class DoubleText < TextRecord - @record_type = 0x92 - - def initialize(handle, record_type) - @value = handle.read(8).unpack("E")[0].to_s - end - end - - class DoubleTextWithEndElement < DoubleText - @record_type = 0x93 - end - - class DecimalText < TextRecord - @record_type = 0x94 - - def initialize(handle, record_type) - wReserved = handle.read(2).unpack("n")[0] - scale = handle.read(1)[0] - @sign = handle.read(1)[0] == 0 ? "" : "-" - @value = 0 - 2.downto(0).each {|n| - @value |= (handle.read(4).unpack("N")[0]) << 32*n - puts "#{@value.to_s 16}" - } - @value /= 10.0**scale - end - - def to_s - "#{@sign}#{@value}" - end - end - - class DecimalTextWithEndRecord < DecimalText - @record_type = 0x95 - end - - class UnicodeChars8Text < TextRecord - @record_type = 0xb6 - - def initialize(handle, record_type) - length = handle.read(1)[0] - @value = from_unicode(handle.read(length)) - end - end - - class UnicodeChars8TextWithEndElement < UnicodeChars8Text - @record_type = 0xb7 - end - - class UnicodeChars16Text < TextRecord - @record_type = 0xb8 - - def initialize(handle, record_type) - length = handle.read(2).unpack("n")[0] - @value = from_unicode(handle.read(length)) - end - end - - class UnicodeChars16TextWithEndElement < UnicodeChars16Text - @record_type = 0xb9 - end - - class UnicodeChars32Text < TextRecord - @record_type = 0xba - - def initialize(handle, record_type) - length = handle.read(4).unpack("l")[0] - @value = from_unicode(handle.read(length)) - end - end - - class UnicodeChars32TextWithEndElement < UnicodeChars32Text - @record_type = 0xbb - end - - class BoolText < TextRecord - @record_type = 0xb4 - - def initialize(handle, record_type) - val = handle.read(1)[0] - @value = val == 0 ? "false" : "true" - end - end - - class BoolTextWithEndElement < BoolText - @record_type = 0xb5 - end - - class UInt64Text < TextRecord - @record_type = 0xb2 - - def initialize(handle, record_type) - @value = handle.read(8).unpack("Q")[0].to_s - end - end - - class UInt64TextWithEndElement < UInt64Text - @record_type = 0xb3 - end - - class StartListText < TextRecord - @record_type = 0xa4 - - def initialize(handle, record_type) - @records = [] - begin - record = Record.MakeRecord(handle) - @records << record - end until record.is_a?(EndListText) - - @value = @records.map{|x|x.strip}.join(" ") - end - end - - class EndListText < TextRecord - @record_type = 0xa6 - def to_s; ""; end - end - - class EmptyText < TextRecord - @record_type = 0xa8 - def to_s; ""; end - end - - class EmptyTextWithEndElement < EmptyText - @record_type = 0xa9 - end - - class QNameDictionaryText < TextRecord - @record_type = 0xbc - - def initialize(handle, record_type) - val = handle.read(4).unpack("L")[0] - @prefix = (((val >> 24) & 0xff) + ?a).chr - val &= 0x00ffffff - @value = "#{@prefix}:#{MSBIN_DictionaryStrings[val]}" - end - end - - class QNameDictionaryTextWithEndElement < QNameDictionaryText - @record_type = 0xbd - end - - class Bytes8Text < TextRecord - @record_type = 0x9e - - # TODO: Rewrite all these custom reads to util funcs - def initialize(handle, record_type) - length = handle.read(1)[0] - bytes = handle.read(length) - - require 'base64' - @value = Base64.b64encode(bytes).rstrip - end - end - - class Bytes8TextWithEndElement < Bytes8Text - @record_type = 0x9f - end - - class Bytes16Text < TextRecord - @record_type = 0xa0 - - # TODO: factor out everything but length - def initialize(handle, record_type) - length = handle.read(2).unpack("n")[0] - bytes = handle.read(length) - - require 'base64' - @value = Base64.b64encode(bytes).rstrip - end - end - - class Bytes16TextWithEndElement < Bytes16Text - @record_type = 0xa1 - end - - class Bytes32Text < TextRecord - @record_type = 0xa2 - - def initialize(handle, record_type) - length = handle.read(4).unpack("l")[0] - bytes = handle.read(length) - - require 'base64' - @value = Base64.b64encode(bytes).rstrip - end - end - - class Bytes32TextWithEndElement < Bytes32Text - @record_type = 0xa3 - end - class DictionaryElement < Element @record_type = 0x43 def initialize(handle, record_type) @prefix = read_string(handle) @name = read_dictstring(handle) get_attributes(handle) end def to_s attribs = @attributes ? " #{@attributes}" : "" "<#{@prefix}:#{@name}#{attribs}>" end end end
yan/msbin
03ad0c7df2deeaa2e10d4e25a7293fa816c53306
metaporgramming magic
diff --git a/types.rb b/types.rb index 7eee36b..75c287d 100644 --- a/types.rb +++ b/types.rb @@ -1,683 +1,687 @@ #!/usr/bin/env ruby require 'msbin_types' #TODO: Separate attributes, text records, etc into separate files and modules $indent = -1 def write_xml(s, increase=1) indent = " "*$indent puts "#{indent}#{s}" if s.class.to_s =~ /WithEndElement$/ puts "#{indent}</#{$element_stack.pop.name}>" increase = -1 end $indent += increase end def read_byte(handle) return handle.read(1)[0] end # TODO: bundle these in a module def read_int31(handle) val = 0 pow = 1 begin byte = read_byte(handle) val += pow * (byte & 0x7F) pow *= 2**7 end while (byte & 0x80) == 0x80 return val end def read_long(handle) return handle.read(4).unpack('L').first end def read_string(handle) len = read_int31(handle) str = handle.read(len) return str end def read_dictstring(handle) val = read_int31(handle) return MSBIN_DictionaryStrings[val] end require 'iconv' def from_unicode(str) return Iconv.conv('UTF-8', 'UTF-16LE', str) end $element_stack = [] - class Class - def make_this_with_endelement - cls = Class.new(self) do - end - puts cls.methods - Object.constant_set "TestTest", cls - puts "!!", self.record_type, cls, self.name - #cls = Class.new( - end - end +class Class +end + module MSBIN class Record @@records = [] class << self attr_accessor :record_type def inherited(klass) @@records << klass end + # Document this + def define_with_endelement + record_type = self.record_type + c = Class.new(self) do + @record_type = record_type+1 + end + + name = self.name.split(':').last+"WithEndElement" + MSBIN.const_set name, c + end + def is_attribute?(type) nil != @@records.find {|klass| klass.ancestors.include? Attribute and klass.record_type === type} end def DecodeStream(handle) while !handle.eof() a = MakeRecord(handle) indent = a.class == EndElement ? -1 : 0 write_xml a, indent end end def MakeRecord(handle) record_type = read_byte(handle) klass = @@records.find{|klass| klass.record_type === record_type} if not klass raise "Unsupported type: 0x#{record_type.to_s(16)}" end #TODO: move the 2-arg initializer to the base class somehow ret = klass.new(handle, record_type) if ret.is_a? Element and ret.class.to_s !~ /EndElement$/ $element_stack.push ret end ret end end def initialize(handle, record_type) end def get_attributes(handle) @attributes = [] loop do where = handle.pos next_type = read_byte(handle) handle.seek(where) break if not Record.is_attribute? next_type @attributes << Record.MakeRecord(handle) end end def type_of?(type) raise NotImplementedError end end end module MSBIN class Reserved < Record @record_type = 0x00 def initialize(handle, record_type) raise "Reserved type used" end end class Element < Record; end class EndElement < Element @record_type = 0x01 def to_s "</#{$element_stack.pop.name}>" end end class CommentElement < Element @record_type = 0x02 def initialize(handle, record_type) @value = "<!--#{read_string(handle)}-->" end end # TODO: Implement Array class ArrayElement < Element @record_type = 0x03 @records = { 0xb5 => "Bool" } def initialize(handle, record_type) element = Record.MakeRecord(handle) raise "Array not implemented yet" end end class ShortAttribute < Record @record_type = 0x04 - make_this_with_endelement + self.make_this_with_endelement def initialize(handle, record_type) @name = read_string(handle) @value = Record.MakeRecord(handle) end def to_s " #{@name}=\"#{@value}\"" end end # TODO: Make other attributes inherit from this to make this make more sense # TODO: Group them in a module and not have it all be flat class Attribute < Record @record_type = 0x05 def initialize(handle, record_type) @prefix = read_string(handle) @name = read_string(handle) @value = Record.MakeRecord(handle) end def to_s " #{@prefix}:#{@name}=\"#{@value}\"" end end class ShortDictionaryAttribute < Attribute @record_type = 0x06 def initialize(handle, record_type) @name = read_dictstring(handle) @value = Record.MakeRecord(handle) end def to_s " #{@name}=#{@value}" end end class DictionaryAttribute < Attribute @record_type = 0x07 # TODO: Create a read_* method for dictionary strings # TODO: finalize the read_int31 function def initialize(handle, record_type) @prefix = read_string(handle) @name = read_dictstring(handle) @value = Record.MakeRecord(handle) end def to_s " #{@prefix}:#{@name}=\"#{@value}\"" end end class PrefixElement < Element @record_type = 0x5e .. 0x77 attr_accessor :name def initialize(handle, record_type) $indent += 1 @name = "#{(record_type-self.class.record_type.first+?a).chr}:" + read_string(handle) @record_type = record_type @attributes = [] get_attributes(handle) end def to_s attribs = @attributes ? " #{@attributes}" : "" "<#{@name}#{attribs}>" end end class PrefixAttribute < Attribute @record_type = 0x26 .. 0x3f def initialize(handle, record_type) @name = "#{(record_type-self.class.record_type.first+?a).chr}:" + read_string(handle) @record_type = record_type @value = Record.MakeRecord(handle) end def to_s " #{@name}=\"#{@value}\"" end end class PrefixDictionaryElement < Element attr_accessor :attributes @record_type = 0x44 .. 0x5D def initialize(handle, record_type) $indent += 1 @attributes = [] @record_type = record_type # read name @name = read_dictstring(handle) # TODO fill proper string names #puts "got name #{@name}" get_attributes(handle) end def name "#{(?a+@record_type-self.class.record_type.first).chr}:#{@name}" end def to_s attribs = @attributes ? " #{@attributes}" : "" "<#{(?a+@record_type-self.class.record_type.first).chr}:#{@name}#{attribs}>" end end class PrefixDictionaryAttribute < Attribute @record_type = 0x0c .. 0x25 def initialize(handle, record_type) @name = read_dictstring(handle) @value = Record.MakeRecord(handle) @record_type = record_type end def to_s "#{@name}=\"#{@value}\"" end end class ShortDictionaryXmlnsAttribute < Attribute @record_type = 0x0a # TODO Isolate classes that do DictionaryStrings # TODO: the value will be ' xmlns="@{value}"' def initialize(handle, record_type) @value = read_dictstring(handle) end def to_s " xmlns=\"#{@value}\"" end end class DictionaryXmlnsAttribute < Attribute @record_type = 0X0b def initialize(handle, record_type) @prefix = read_string(handle) @attributes = read_dictstring(handle) end def to_s " xmlns:#{@prefix}=\"#{@attributes}\"" end end class ShortXmlnsAttribute < Attribute @record_type = 0x08 def initialize(handle, record_type) @value = read_string(handle) end def to_s " xmlns=\"#{@value}\"" end end class XmlnsAttribute < Attribute @record_type = 0x09 def initialize(handle, record_type) @prefix = read_string(handle) @value = read_string(handle) end def to_s " xmlns:#{@prefix}=\"#{@value}\"" end end class ShortElement < Element @record_type = 0x40 def initialize(handle, record_type) $indent += 1 @name = read_string(handle) get_attributes(handle) end def name @name end def to_s attribs = @attributes ? " #{@attributes}" : "" "<#{@name}#{attribs}>" end end # Make this an ADT class TextRecord < Record @record_type = 0x00 def initialize(handle, record_type) @record_type = record_type end def to_s @value.to_s end end class ZeroText < TextRecord @record_type = 0x80 def to_s; "0"; end end class ZeroTextWithEndElement < ZeroText @record_type = 0x81 end class TrueText < TextRecord @record_type = 0x86 def to_s; "true"; end end class TrueTextWithEndElement < TrueText @record_type = 0x87 end # TODO: make this derive from TextRecord class FalseText < TextRecord @record_type = 0x84 def to_s; "false"; end end class FalseTextWithEndElement < FalseText @record_type = 0x85 end class OneText < TextRecord @record_type = 0x82 def to_s; "1"; end end class OneTextWithEndElement < OneText @record_type = 0x83 end # TODO: Parse this better class DateTimeText < TextRecord @record_type = 0x96 def initialize(handle, record_type) # TODO: validate it @date_date val = handle.read(8).unpack("Q")[0] @tz = val & 0xff val >>= 2 # to microseconds val /= 10 # to seconds val /= (10**6) # seconds since year 1 until epoch start = Time.utc(1, "jan", 1, 0, 0, 0, 0) epoch = Time.at(0) # seconds since 0 val -= (epoch - start) # val is now epoch # not sure if this is correct, but it'll do for now time = Time.at(val) if time.hour == 0 and time.minutes == 0 and time.seconds == 0 @value = time.strftime("%Y-%m-%d") else @value = time.strftime("%Y-%m-%dT%H:%M:%S") end end end class DateTimeTextWithEndElement < DateTimeText @record_type = 0x97 end class DictionaryText < TextRecord @record_type = 0xaa def initialize(handle, record_type) @value = read_dictstring(handle) end end class DictionaryTextWithEndElement < DictionaryText @record_type = 0xab end class Chars8Text < TextRecord @record_type = 0x98 def initialize(handle, record_type) require 'cgi' length = handle.read(1)[0] @value = CGI.escapeHTML(handle.read(length)).to_s end end # TODO: Clean up the end element class Chars8TextWithEndElement < Chars8Text @record_type = 0x99 end class Chars16Text < TextRecord @record_type = 0x9a def initialize(handle, record_type) require 'cgi' length = handle.read(2).unpack("n")[0] @value = CGI.escapeHTML(handle.read(length)).to_s end end # TODO: Clean up the end element class Chars16TextWithEndElement < Chars16Text @record_type = 0x9b end class Chars32Text < TextRecord @record_type = 0x9c def initialize(hand,record_type) require 'cgi' length = handle.read(4).unpack("l")[0] @value = CGI.escapeHTML(handle.read(length)).to_s end end class Chars32TextWithEndElement < Chars32Text @record_type = 0x9d end class UuIdText < TextRecord @record_type = 0xac def initialize(handle, record_type) @uuid = handle.read(16).unpack('VvvC*') @value = ("%08x-%04x-%04x-" % [@uuid[0], @uuid[1], @uuid[2]])+(("%02x"*6) % @uuid[3..-1]) end end # TODO: Separate this class UuIdTextWithEndElement < UuIdText @record_type = 0xad end class TimeSpanText < TextRecord @record_type = 0xae def initialize(handle, record_type) @value = handle.read(8).unpack("q")[0] if @value < 0 @sign = '-'; @value *= -1 end ticks_in_sec = 10000000 @frac = @value % ticks_in_sec; @value /= ticks_in_sec @seconds = @value % 60; @value /= 60 @minutes = @value % 60; @value /= 60 @hours = @value % 24; @value /= 24 @days = @value end def to_s if @days > 0 and @frac == 0 "#{@sign}%d.%02d:%02d:%02d" % [@days, @hours, @minutes, @seconds] elsif @days > 0 and @frac > 0 "#{@sign}%d.%02d:%02d:%02d:%d" % [@days, @hours, @minutes, @seconds, @frac] elsif @days == 0 and @frac == 0 "#{@sign}%02d:%02d:%02d" % [@hours, @minutes, @seconds] else "#{@sign}%02d:%02d:%02d.%d" % [@hours, @minutes, @seconds, @frac] end end end class TimeSpanTextWithEndElement < TimeSpanText @record_type = 0xaf end class Int8Text < TextRecord @record_type = 0x88 def initialize(handle, record_type) @value = handle.read(1)[0].to_s end end class Int8TextWithEndElement < Int8Text @record_type = 0x89 end class Int16Text < TextRecord @record_type = 0x8a def initialize(handle, record_type) @value = handle.read(2).unpack("n")[0].to_s end end class Int16TextWithEndElement < Int16Text @record_type = 0x8b end class Int32Text < TextRecord @record_type = 0x8c def initialize(handle, record_type) @value = handle.read(4).unpack("l")[0].to_s end end class Int32TextWithEndElement < Int32Text @record_type = 0x8d end class Int64Text < TextRecord @record_type = 0x8e def initialize(handle, record_type) @value = handle.read(8).unpack("q")[0].to_s end end class Int64TextWithEndElement < Int64Text @record_type = 0x8f end class FloatText < TextRecord @record_type = 0x90 def initialize(handle, record_type) @value = handle.read(4).unpack("g")[0].to_s end end class FloatTextWithEndRecord < FloatText @record_type = 0x91 end class DoubleText < TextRecord @record_type = 0x92 def initialize(handle, record_type) @value = handle.read(8).unpack("E")[0].to_s end end class DoubleTextWithEndElement < DoubleText @record_type = 0x93 end class DecimalText < TextRecord @record_type = 0x94 def initialize(handle, record_type) wReserved = handle.read(2).unpack("n")[0] scale = handle.read(1)[0] @sign = handle.read(1)[0] == 0 ? "" : "-" @value = 0 2.downto(0).each {|n| @value |= (handle.read(4).unpack("N")[0]) << 32*n puts "#{@value.to_s 16}" } @value /= 10.0**scale end def to_s "#{@sign}#{@value}" end end class DecimalTextWithEndRecord < DecimalText @record_type = 0x95 end class UnicodeChars8Text < TextRecord @record_type = 0xb6 def initialize(handle, record_type) length = handle.read(1)[0] @value = from_unicode(handle.read(length)) end end class UnicodeChars8TextWithEndElement < UnicodeChars8Text @record_type = 0xb7 end class UnicodeChars16Text < TextRecord @record_type = 0xb8 def initialize(handle, record_type) length = handle.read(2).unpack("n")[0] @value = from_unicode(handle.read(length)) end end
yan/msbin
77f5be19241804e68861e9949e17ba63998e22d0
almost done implementing types
diff --git a/types.rb b/types.rb index fa8f94b..7eee36b 100644 --- a/types.rb +++ b/types.rb @@ -1,642 +1,834 @@ #!/usr/bin/env ruby require 'msbin_types' #TODO: Separate attributes, text records, etc into separate files and modules $indent = -1 def write_xml(s, increase=1) indent = " "*$indent puts "#{indent}#{s}" if s.class.to_s =~ /WithEndElement$/ puts "#{indent}</#{$element_stack.pop.name}>" increase = -1 end $indent += increase end def read_byte(handle) return handle.read(1)[0] end # TODO: bundle these in a module def read_int31(handle) val = 0 pow = 1 begin byte = read_byte(handle) val += pow * (byte & 0x7F) pow *= 2**7 end while (byte & 0x80) == 0x80 return val end def read_long(handle) return handle.read(4).unpack('L').first end def read_string(handle) len = read_int31(handle) str = handle.read(len) return str end +def read_dictstring(handle) + val = read_int31(handle) + return MSBIN_DictionaryStrings[val] +end + +require 'iconv' +def from_unicode(str) + return Iconv.conv('UTF-8', 'UTF-16LE', str) +end + $element_stack = [] + class Class + def make_this_with_endelement + cls = Class.new(self) do + end + puts cls.methods + Object.constant_set "TestTest", cls + puts "!!", self.record_type, cls, self.name + #cls = Class.new( + end + end module MSBIN + class Record @@records = [] class << self attr_accessor :record_type def inherited(klass) @@records << klass end def is_attribute?(type) nil != @@records.find {|klass| klass.ancestors.include? Attribute and klass.record_type === type} end def DecodeStream(handle) while !handle.eof() a = MakeRecord(handle) indent = a.class == EndElement ? -1 : 0 write_xml a, indent end end def MakeRecord(handle) record_type = read_byte(handle) klass = @@records.find{|klass| klass.record_type === record_type} if not klass raise "Unsupported type: 0x#{record_type.to_s(16)}" end #TODO: move the 2-arg initializer to the base class somehow ret = klass.new(handle, record_type) if ret.is_a? Element and ret.class.to_s !~ /EndElement$/ $element_stack.push ret end ret end end def initialize(handle, record_type) end def get_attributes(handle) @attributes = [] loop do where = handle.pos next_type = read_byte(handle) handle.seek(where) break if not Record.is_attribute? next_type @attributes << Record.MakeRecord(handle) end end def type_of?(type) raise NotImplementedError end end end module MSBIN class Reserved < Record @record_type = 0x00 def initialize(handle, record_type) raise "Reserved type used" end end class Element < Record; end class EndElement < Element @record_type = 0x01 def to_s "</#{$element_stack.pop.name}>" end end class CommentElement < Element @record_type = 0x02 def initialize(handle, record_type) @value = "<!--#{read_string(handle)}-->" end end # TODO: Implement Array class ArrayElement < Element @record_type = 0x03 @records = { 0xb5 => "Bool" } def initialize(handle, record_type) element = Record.MakeRecord(handle) raise "Array not implemented yet" end end class ShortAttribute < Record @record_type = 0x04 + make_this_with_endelement + def initialize(handle, record_type) @name = read_string(handle) @value = Record.MakeRecord(handle) end def to_s " #{@name}=\"#{@value}\"" end end # TODO: Make other attributes inherit from this to make this make more sense # TODO: Group them in a module and not have it all be flat class Attribute < Record @record_type = 0x05 def initialize(handle, record_type) @prefix = read_string(handle) @name = read_string(handle) @value = Record.MakeRecord(handle) end def to_s " #{@prefix}:#{@name}=\"#{@value}\"" end end class ShortDictionaryAttribute < Attribute @record_type = 0x06 def initialize(handle, record_type) - val = read_int31(handle) - @name = "#{MSBIN_DictionaryStrings[val]}" # handle.read(val) + @name = read_dictstring(handle) @value = Record.MakeRecord(handle) end def to_s " #{@name}=#{@value}" end end class DictionaryAttribute < Attribute @record_type = 0x07 # TODO: Create a read_* method for dictionary strings # TODO: finalize the read_int31 function def initialize(handle, record_type) @prefix = read_string(handle) - @name = "#{MSBIN_DictionaryStrings[read_int31(handle)]}" + @name = read_dictstring(handle) @value = Record.MakeRecord(handle) end def to_s " #{@prefix}:#{@name}=\"#{@value}\"" end end class PrefixElement < Element @record_type = 0x5e .. 0x77 attr_accessor :name def initialize(handle, record_type) $indent += 1 @name = "#{(record_type-self.class.record_type.first+?a).chr}:" + read_string(handle) @record_type = record_type @attributes = [] get_attributes(handle) end def to_s attribs = @attributes ? " #{@attributes}" : "" "<#{@name}#{attribs}>" end end class PrefixAttribute < Attribute @record_type = 0x26 .. 0x3f def initialize(handle, record_type) @name = "#{(record_type-self.class.record_type.first+?a).chr}:" + read_string(handle) @record_type = record_type @value = Record.MakeRecord(handle) end def to_s " #{@name}=\"#{@value}\"" end end class PrefixDictionaryElement < Element attr_accessor :attributes @record_type = 0x44 .. 0x5D def initialize(handle, record_type) $indent += 1 @attributes = [] @record_type = record_type # read name - val = read_int31(handle) - @name = "#{MSBIN_DictionaryStrings[val]}" # handle.read(val) + @name = read_dictstring(handle) # TODO fill proper string names #puts "got name #{@name}" get_attributes(handle) end def name "#{(?a+@record_type-self.class.record_type.first).chr}:#{@name}" end def to_s attribs = @attributes ? " #{@attributes}" : "" "<#{(?a+@record_type-self.class.record_type.first).chr}:#{@name}#{attribs}>" end end class PrefixDictionaryAttribute < Attribute @record_type = 0x0c .. 0x25 def initialize(handle, record_type) - val = read_int31(handle) - @name = "#{MSBIN_DictionaryStrings[val]}" + @name = read_dictstring(handle) @value = Record.MakeRecord(handle) @record_type = record_type end def to_s "#{@name}=\"#{@value}\"" end end class ShortDictionaryXmlnsAttribute < Attribute @record_type = 0x0a # TODO Isolate classes that do DictionaryStrings # TODO: the value will be ' xmlns="@{value}"' def initialize(handle, record_type) - @value = "#{MSBIN_DictionaryStrings[read_long(handle)]}" + @value = read_dictstring(handle) end def to_s " xmlns=\"#{@value}\"" end end class DictionaryXmlnsAttribute < Attribute @record_type = 0X0b def initialize(handle, record_type) @prefix = read_string(handle) - @attributes = "#{MSBIN_DictionaryStrings[read_int31(handle)]}"#Record.MakeRecord(handle) + @attributes = read_dictstring(handle) end def to_s " xmlns:#{@prefix}=\"#{@attributes}\"" end end class ShortXmlnsAttribute < Attribute @record_type = 0x08 def initialize(handle, record_type) @value = read_string(handle) end def to_s " xmlns=\"#{@value}\"" end end class XmlnsAttribute < Attribute @record_type = 0x09 def initialize(handle, record_type) @prefix = read_string(handle) @value = read_string(handle) end def to_s " xmlns:#{@prefix}=\"#{@value}\"" end end class ShortElement < Element @record_type = 0x40 def initialize(handle, record_type) $indent += 1 @name = read_string(handle) get_attributes(handle) end def name @name end def to_s attribs = @attributes ? " #{@attributes}" : "" "<#{@name}#{attribs}>" end end # Make this an ADT class TextRecord < Record @record_type = 0x00 def initialize(handle, record_type) @record_type = record_type end def to_s @value.to_s end end class ZeroText < TextRecord @record_type = 0x80 def to_s; "0"; end end class ZeroTextWithEndElement < ZeroText @record_type = 0x81 end class TrueText < TextRecord @record_type = 0x86 def to_s; "true"; end end class TrueTextWithEndElement < TrueText @record_type = 0x87 end # TODO: make this derive from TextRecord class FalseText < TextRecord @record_type = 0x84 def to_s; "false"; end end class FalseTextWithEndElement < FalseText @record_type = 0x85 end class OneText < TextRecord @record_type = 0x82 def to_s; "1"; end end class OneTextWithEndElement < OneText @record_type = 0x83 end # TODO: Parse this better class DateTimeText < TextRecord @record_type = 0x96 def initialize(handle, record_type) # TODO: validate it @date_date val = handle.read(8).unpack("Q")[0] @tz = val & 0xff val >>= 2 # to microseconds val /= 10 # to seconds val /= (10**6) # seconds since year 1 until epoch start = Time.utc(1, "jan", 1, 0, 0, 0, 0) epoch = Time.at(0) # seconds since 0 val -= (epoch - start) # val is now epoch # not sure if this is correct, but it'll do for now time = Time.at(val) if time.hour == 0 and time.minutes == 0 and time.seconds == 0 @value = time.strftime("%Y-%m-%d") else @value = time.strftime("%Y-%m-%dT%H:%M:%S") end end end class DateTimeTextWithEndElement < DateTimeText @record_type = 0x97 end class DictionaryText < TextRecord @record_type = 0xaa def initialize(handle, record_type) - val = read_int31(handle) - @value = MSBIN_DictionaryStrings[val] + @value = read_dictstring(handle) end end class DictionaryTextWithEndElement < DictionaryText @record_type = 0xab end class Chars8Text < TextRecord @record_type = 0x98 def initialize(handle, record_type) require 'cgi' length = handle.read(1)[0] @value = CGI.escapeHTML(handle.read(length)).to_s end end # TODO: Clean up the end element class Chars8TextWithEndElement < Chars8Text @record_type = 0x99 end class Chars16Text < TextRecord @record_type = 0x9a def initialize(handle, record_type) require 'cgi' length = handle.read(2).unpack("n")[0] @value = CGI.escapeHTML(handle.read(length)).to_s end end # TODO: Clean up the end element class Chars16TextWithEndElement < Chars16Text @record_type = 0x9b end class Chars32Text < TextRecord @record_type = 0x9c def initialize(hand,record_type) require 'cgi' length = handle.read(4).unpack("l")[0] @value = CGI.escapeHTML(handle.read(length)).to_s end end class Chars32TextWithEndElement < Chars32Text @record_type = 0x9d end class UuIdText < TextRecord @record_type = 0xac def initialize(handle, record_type) @uuid = handle.read(16).unpack('VvvC*') @value = ("%08x-%04x-%04x-" % [@uuid[0], @uuid[1], @uuid[2]])+(("%02x"*6) % @uuid[3..-1]) end end # TODO: Separate this class UuIdTextWithEndElement < UuIdText @record_type = 0xad end class TimeSpanText < TextRecord @record_type = 0xae def initialize(handle, record_type) @value = handle.read(8).unpack("q")[0] if @value < 0 @sign = '-'; @value *= -1 end ticks_in_sec = 10000000 @frac = @value % ticks_in_sec; @value /= ticks_in_sec @seconds = @value % 60; @value /= 60 @minutes = @value % 60; @value /= 60 @hours = @value % 24; @value /= 24 @days = @value end def to_s if @days > 0 and @frac == 0 "#{@sign}%d.%02d:%02d:%02d" % [@days, @hours, @minutes, @seconds] elsif @days > 0 and @frac > 0 "#{@sign}%d.%02d:%02d:%02d:%d" % [@days, @hours, @minutes, @seconds, @frac] elsif @days == 0 and @frac == 0 "#{@sign}%02d:%02d:%02d" % [@hours, @minutes, @seconds] else "#{@sign}%02d:%02d:%02d.%d" % [@hours, @minutes, @seconds, @frac] end end end class TimeSpanTextWithEndElement < TimeSpanText @record_type = 0xaf end class Int8Text < TextRecord @record_type = 0x88 def initialize(handle, record_type) @value = handle.read(1)[0].to_s end end class Int8TextWithEndElement < Int8Text @record_type = 0x89 end class Int16Text < TextRecord @record_type = 0x8a def initialize(handle, record_type) @value = handle.read(2).unpack("n")[0].to_s end end class Int16TextWithEndElement < Int16Text @record_type = 0x8b end class Int32Text < TextRecord @record_type = 0x8c def initialize(handle, record_type) @value = handle.read(4).unpack("l")[0].to_s end end class Int32TextWithEndElement < Int32Text @record_type = 0x8d end class Int64Text < TextRecord @record_type = 0x8e def initialize(handle, record_type) @value = handle.read(8).unpack("q")[0].to_s end end class Int64TextWithEndElement < Int64Text @record_type = 0x8f end class FloatText < TextRecord @record_type = 0x90 def initialize(handle, record_type) @value = handle.read(4).unpack("g")[0].to_s end end class FloatTextWithEndRecord < FloatText @record_type = 0x91 end class DoubleText < TextRecord @record_type = 0x92 def initialize(handle, record_type) @value = handle.read(8).unpack("E")[0].to_s end end class DoubleTextWithEndElement < DoubleText @record_type = 0x93 end class DecimalText < TextRecord @record_type = 0x94 def initialize(handle, record_type) wReserved = handle.read(2).unpack("n")[0] scale = handle.read(1)[0] @sign = handle.read(1)[0] == 0 ? "" : "-" @value = 0 2.downto(0).each {|n| @value |= (handle.read(4).unpack("N")[0]) << 32*n puts "#{@value.to_s 16}" } @value /= 10.0**scale end def to_s "#{@sign}#{@value}" end end class DecimalTextWithEndRecord < DecimalText @record_type = 0x95 end + + class UnicodeChars8Text < TextRecord + @record_type = 0xb6 + + def initialize(handle, record_type) + length = handle.read(1)[0] + @value = from_unicode(handle.read(length)) + end + end + + class UnicodeChars8TextWithEndElement < UnicodeChars8Text + @record_type = 0xb7 + end + + class UnicodeChars16Text < TextRecord + @record_type = 0xb8 + + def initialize(handle, record_type) + length = handle.read(2).unpack("n")[0] + @value = from_unicode(handle.read(length)) + end + end + + class UnicodeChars16TextWithEndElement < UnicodeChars16Text + @record_type = 0xb9 + end + + class UnicodeChars32Text < TextRecord + @record_type = 0xba + + def initialize(handle, record_type) + length = handle.read(4).unpack("l")[0] + @value = from_unicode(handle.read(length)) + end + end + + class UnicodeChars32TextWithEndElement < UnicodeChars32Text + @record_type = 0xbb + end + + class BoolText < TextRecord + @record_type = 0xb4 + + def initialize(handle, record_type) + val = handle.read(1)[0] + @value = val == 0 ? "false" : "true" + end + end + + class BoolTextWithEndElement < BoolText + @record_type = 0xb5 + end + + class UInt64Text < TextRecord + @record_type = 0xb2 + + def initialize(handle, record_type) + @value = handle.read(8).unpack("Q")[0].to_s + end + end + + class UInt64TextWithEndElement < UInt64Text + @record_type = 0xb3 + end + + class StartListText < TextRecord + @record_type = 0xa4 + + def initialize(handle, record_type) + @records = [] + begin + record = Record.MakeRecord(handle) + @records << record + end until record.is_a?(EndListText) + + @value = @records.map{|x|x.strip}.join(" ") + end + end + + class EndListText < TextRecord + @record_type = 0xa6 + def to_s; ""; end + end + + class EmptyText < TextRecord + @record_type = 0xa8 + def to_s; ""; end + end + + class EmptyTextWithEndElement < EmptyText + @record_type = 0xa9 + end + + class QNameDictionaryText < TextRecord + @record_type = 0xbc + + def initialize(handle, record_type) + val = handle.read(4).unpack("L")[0] + @prefix = (((val >> 24) & 0xff) + ?a).chr + val &= 0x00ffffff + @value = "#{@prefix}:#{MSBIN_DictionaryStrings[val]}" + end + end + + class QNameDictionaryTextWithEndElement < QNameDictionaryText + @record_type = 0xbd + end + + class Bytes8Text < TextRecord + @record_type = 0x9e + + # TODO: Rewrite all these custom reads to util funcs + def initialize(handle, record_type) + length = handle.read(1)[0] + bytes = handle.read(length) + + require 'base64' + @value = Base64.b64encode(bytes).rstrip + end + end + + class Bytes8TextWithEndElement < Bytes8Text + @record_type = 0x9f + end + + class Bytes16Text < TextRecord + @record_type = 0xa0 + + # TODO: factor out everything but length + def initialize(handle, record_type) + length = handle.read(2).unpack("n")[0] + bytes = handle.read(length) + + require 'base64' + @value = Base64.b64encode(bytes).rstrip + end + end + + class Bytes16TextWithEndElement < Bytes16Text + @record_type = 0xa1 + end + + class Bytes32Text < TextRecord + @record_type = 0xa2 + + def initialize(handle, record_type) + length = handle.read(4).unpack("l")[0] + bytes = handle.read(length) + + require 'base64' + @value = Base64.b64encode(bytes).rstrip + end + end + + class Bytes32TextWithEndElement < Bytes32Text + @record_type = 0xa3 + end + + class DictionaryElement < Element + @record_type = 0x43 + + def initialize(handle, record_type) + @prefix = read_string(handle) + @name = read_dictstring(handle) + + get_attributes(handle) + end + + def to_s + attribs = @attributes ? " #{@attributes}" : "" + "<#{@prefix}:#{@name}#{attribs}>" + end + end end
yan/msbin
b1cd52d3049651e48ba7b8275d1bed19766bf5a4
reflect changed method name
diff --git a/main.rb b/main.rb index 8a9c11d..8be4238 100755 --- a/main.rb +++ b/main.rb @@ -1,38 +1,38 @@ #!/usr/bin/env ruby require 'records' require 'types' if ARGV.size == 0 $stderr.write("Usage: #{$0} [file.msbin|-]\n") exit 1 end def read_msbin(handle) while !handle.eof() a = MSBIN::Record.MakeRecord(handle) indent = a.class == MSBIN::EndElement ? -1 : 0 write_xml a, indent if a.class.to_s =~ /WithEndElement$/# or ret.class == EndElement write_xml("</#{($element_stack.pop).name}>", -1) end end end if ARGV[0] == '-' f = $stdin else f = File.new(ARGV[0], "rb") end # check if we have an http post, and consume headers if f.read(4) == "HTTP" while f.readline().chomp != ""; end else f.seek(0) end -MSBIN::Record.Decode(f) +MSBIN::Record.DecodeStream(f) #puts f
yan/msbin
f7ece4eb81a32b3484187b102cb4d84ed63d3144
Terrible commit messages, but lots of changes again
diff --git a/types.rb b/types.rb index ba9528a..fa8f94b 100644 --- a/types.rb +++ b/types.rb @@ -1,571 +1,642 @@ #!/usr/bin/env ruby require 'msbin_types' #TODO: Separate attributes, text records, etc into separate files and modules $indent = -1 def write_xml(s, increase=1) indent = " "*$indent puts "#{indent}#{s}" + if s.class.to_s =~ /WithEndElement$/ + puts "#{indent}</#{$element_stack.pop.name}>" + increase = -1 + end $indent += increase end def read_byte(handle) return handle.read(1)[0] end # TODO: bundle these in a module def read_int31(handle) val = 0 pow = 1 begin byte = read_byte(handle) val += pow * (byte & 0x7F) pow *= 2**7 end while (byte & 0x80) == 0x80 return val end def read_long(handle) return handle.read(4).unpack('L').first end def read_string(handle) len = read_int31(handle) str = handle.read(len) return str end $element_stack = [] module MSBIN class Record @@records = [] class << self attr_accessor :record_type def inherited(klass) @@records << klass end def is_attribute?(type) - nil != @@records.select {|klass| klass.to_s =~ /Attribute$/}.find {|klass| klass.record_type === type} + nil != @@records.find {|klass| klass.ancestors.include? Attribute and klass.record_type === type} end - def Decode(handle) + def DecodeStream(handle) while !handle.eof() a = MakeRecord(handle) indent = a.class == EndElement ? -1 : 0 write_xml a, indent - - if a.class.to_s =~ /WithEndElement$/# or ret.class == EndElement - write_xml("</#{($element_stack.pop).name}>", -1) - end end end def MakeRecord(handle) record_type = read_byte(handle) klass = @@records.find{|klass| klass.record_type === record_type} - raise "Unsupported type: 0x#{record_type.to_s(16)}" if not klass + if not klass + raise "Unsupported type: 0x#{record_type.to_s(16)}" + end #TODO: move the 2-arg initializer to the base class somehow ret = klass.new(handle, record_type) - if ret.class.to_s =~ /Element$/ and ret.class.to_s !~ /EndElement$/ + if ret.is_a? Element and ret.class.to_s !~ /EndElement$/ $element_stack.push ret end ret end end def initialize(handle, record_type) end def get_attributes(handle) @attributes = [] loop do where = handle.pos next_type = read_byte(handle) handle.seek(where) break if not Record.is_attribute? next_type @attributes << Record.MakeRecord(handle) end end def type_of?(type) raise NotImplementedError end end end module MSBIN class Reserved < Record @record_type = 0x00 def initialize(handle, record_type) raise "Reserved type used" end end - class EndElement < Record + class Element < Record; end + + class EndElement < Element @record_type = 0x01 def to_s "</#{$element_stack.pop.name}>" end end - class CommentElement < Record + class CommentElement < Element @record_type = 0x02 def initialize(handle, record_type) @value = "<!--#{read_string(handle)}-->" end end # TODO: Implement Array - class ArrayElement < Record + class ArrayElement < Element @record_type = 0x03 + @records = { + 0xb5 => "Bool" + } def initialize(handle, record_type) + element = Record.MakeRecord(handle) raise "Array not implemented yet" end end class ShortAttribute < Record @record_type = 0x04 def initialize(handle, record_type) @name = read_string(handle) @value = Record.MakeRecord(handle) end def to_s - " #{@name}=\"#{@vlaue}\"" + " #{@name}=\"#{@value}\"" end end # TODO: Make other attributes inherit from this to make this make more sense # TODO: Group them in a module and not have it all be flat class Attribute < Record @record_type = 0x05 def initialize(handle, record_type) @prefix = read_string(handle) @name = read_string(handle) @value = Record.MakeRecord(handle) end def to_s " #{@prefix}:#{@name}=\"#{@value}\"" end end - class ShortDictionaryAttribute < Record + class ShortDictionaryAttribute < Attribute @record_type = 0x06 def initialize(handle, record_type) val = read_int31(handle) @name = "#{MSBIN_DictionaryStrings[val]}" # handle.read(val) @value = Record.MakeRecord(handle) end def to_s " #{@name}=#{@value}" end end - class DictionaryAttribute < Record + class DictionaryAttribute < Attribute @record_type = 0x07 # TODO: Create a read_* method for dictionary strings # TODO: finalize the read_int31 function def initialize(handle, record_type) @prefix = read_string(handle) @name = "#{MSBIN_DictionaryStrings[read_int31(handle)]}" @value = Record.MakeRecord(handle) end def to_s " #{@prefix}:#{@name}=\"#{@value}\"" end end - class PrefixElement < Record + class PrefixElement < Element @record_type = 0x5e .. 0x77 attr_accessor :name def initialize(handle, record_type) $indent += 1 @name = "#{(record_type-self.class.record_type.first+?a).chr}:" + read_string(handle) @record_type = record_type @attributes = [] get_attributes(handle) end def to_s attribs = @attributes ? " #{@attributes}" : "" "<#{@name}#{attribs}>" end end - class PrefixAttribute < Record + class PrefixAttribute < Attribute @record_type = 0x26 .. 0x3f def initialize(handle, record_type) @name = "#{(record_type-self.class.record_type.first+?a).chr}:" + read_string(handle) @record_type = record_type @value = Record.MakeRecord(handle) end def to_s " #{@name}=\"#{@value}\"" end end - class PrefixDictionaryElement < Record + class PrefixDictionaryElement < Element attr_accessor :attributes @record_type = 0x44 .. 0x5D def initialize(handle, record_type) $indent += 1 @attributes = [] @record_type = record_type # read name val = read_int31(handle) @name = "#{MSBIN_DictionaryStrings[val]}" # handle.read(val) # TODO fill proper string names #puts "got name #{@name}" get_attributes(handle) end def name "#{(?a+@record_type-self.class.record_type.first).chr}:#{@name}" end def to_s attribs = @attributes ? " #{@attributes}" : "" "<#{(?a+@record_type-self.class.record_type.first).chr}:#{@name}#{attribs}>" end end - class PrefixDictionaryAttribute < Record + class PrefixDictionaryAttribute < Attribute @record_type = 0x0c .. 0x25 def initialize(handle, record_type) val = read_int31(handle) @name = "#{MSBIN_DictionaryStrings[val]}" @value = Record.MakeRecord(handle) @record_type = record_type end def to_s "#{@name}=\"#{@value}\"" end end - class ShortDictionaryXmlnsAttribute < Record + class ShortDictionaryXmlnsAttribute < Attribute @record_type = 0x0a # TODO Isolate classes that do DictionaryStrings # TODO: the value will be ' xmlns="@{value}"' def initialize(handle, record_type) @value = "#{MSBIN_DictionaryStrings[read_long(handle)]}" end def to_s " xmlns=\"#{@value}\"" end end - class DictionaryXmlnsAttribute < Record + class DictionaryXmlnsAttribute < Attribute @record_type = 0X0b def initialize(handle, record_type) @prefix = read_string(handle) @attributes = "#{MSBIN_DictionaryStrings[read_int31(handle)]}"#Record.MakeRecord(handle) end def to_s " xmlns:#{@prefix}=\"#{@attributes}\"" end end - class ShortXmlnsAttribute < Record + class ShortXmlnsAttribute < Attribute @record_type = 0x08 def initialize(handle, record_type) @value = read_string(handle) end def to_s " xmlns=\"#{@value}\"" end end - class XmlnsAttribute < Record + class XmlnsAttribute < Attribute @record_type = 0x09 def initialize(handle, record_type) @prefix = read_string(handle) @value = read_string(handle) end def to_s " xmlns:#{@prefix}=\"#{@value}\"" end end - class ShortElement < Record + class ShortElement < Element @record_type = 0x40 def initialize(handle, record_type) $indent += 1 @name = read_string(handle) get_attributes(handle) end def name @name end def to_s attribs = @attributes ? " #{@attributes}" : "" "<#{@name}#{attribs}>" end end # Make this an ADT class TextRecord < Record @record_type = 0x00 def initialize(handle, record_type) @record_type = record_type end def to_s @value.to_s end end class ZeroText < TextRecord @record_type = 0x80 def to_s; "0"; end end - + class ZeroTextWithEndElement < ZeroText + @record_type = 0x81 + end + class TrueText < TextRecord @record_type = 0x86 def to_s; "true"; end end class TrueTextWithEndElement < TrueText @record_type = 0x87 end # TODO: make this derive from TextRecord class FalseText < TextRecord @record_type = 0x84 def to_s; "false"; end end class FalseTextWithEndElement < FalseText @record_type = 0x85 end class OneText < TextRecord @record_type = 0x82 def to_s; "1"; end end class OneTextWithEndElement < OneText @record_type = 0x83 end # TODO: Parse this better class DateTimeText < TextRecord @record_type = 0x96 def initialize(handle, record_type) # TODO: validate it @date_date val = handle.read(8).unpack("Q")[0] + @tz = val & 0xff val >>= 2 # to microseconds val /= 10 # to seconds val /= (10**6) # seconds since year 1 until epoch start = Time.utc(1, "jan", 1, 0, 0, 0, 0) epoch = Time.at(0) # seconds since 0 val -= (epoch - start) # val is now epoch # not sure if this is correct, but it'll do for now time = Time.at(val) if time.hour == 0 and time.minutes == 0 and time.seconds == 0 @value = time.strftime("%Y-%m-%d") else @value = time.strftime("%Y-%m-%dT%H:%M:%S") end end end class DateTimeTextWithEndElement < DateTimeText @record_type = 0x97 end class DictionaryText < TextRecord @record_type = 0xaa def initialize(handle, record_type) val = read_int31(handle) @value = MSBIN_DictionaryStrings[val] end end class DictionaryTextWithEndElement < DictionaryText @record_type = 0xab end - class Chars8Text < Record + class Chars8Text < TextRecord @record_type = 0x98 def initialize(handle, record_type) require 'cgi' length = handle.read(1)[0] @value = CGI.escapeHTML(handle.read(length)).to_s end end # TODO: Clean up the end element class Chars8TextWithEndElement < Chars8Text @record_type = 0x99 end - class Chars16Text < Record + class Chars16Text < TextRecord @record_type = 0x9a def initialize(handle, record_type) require 'cgi' length = handle.read(2).unpack("n")[0] @value = CGI.escapeHTML(handle.read(length)).to_s end end # TODO: Clean up the end element class Chars16TextWithEndElement < Chars16Text @record_type = 0x9b end - class UniqueIdText < Record + class Chars32Text < TextRecord + @record_type = 0x9c + + def initialize(hand,record_type) + require 'cgi' + length = handle.read(4).unpack("l")[0] + @value = CGI.escapeHTML(handle.read(length)).to_s + end + end + + class Chars32TextWithEndElement < Chars32Text + @record_type = 0x9d + end + + class UuIdText < TextRecord @record_type = 0xac def initialize(handle, record_type) @uuid = handle.read(16).unpack('VvvC*') @value = ("%08x-%04x-%04x-" % [@uuid[0], @uuid[1], @uuid[2]])+(("%02x"*6) % @uuid[3..-1]) end end # TODO: Separate this - class UniqueIdTextWithEndElement < UniqueIdText + class UuIdTextWithEndElement < UuIdText @record_type = 0xad end + class TimeSpanText < TextRecord + @record_type = 0xae + + def initialize(handle, record_type) + @value = handle.read(8).unpack("q")[0] + if @value < 0 + @sign = '-'; @value *= -1 + end + + ticks_in_sec = 10000000 + @frac = @value % ticks_in_sec; @value /= ticks_in_sec + @seconds = @value % 60; @value /= 60 + @minutes = @value % 60; @value /= 60 + @hours = @value % 24; @value /= 24 + @days = @value + end + + def to_s + if @days > 0 and @frac == 0 + "#{@sign}%d.%02d:%02d:%02d" % [@days, @hours, @minutes, @seconds] + elsif @days > 0 and @frac > 0 + "#{@sign}%d.%02d:%02d:%02d:%d" % [@days, @hours, @minutes, @seconds, @frac] + elsif @days == 0 and @frac == 0 + "#{@sign}%02d:%02d:%02d" % [@hours, @minutes, @seconds] + else + "#{@sign}%02d:%02d:%02d.%d" % [@hours, @minutes, @seconds, @frac] + end + end + end + + class TimeSpanTextWithEndElement < TimeSpanText + @record_type = 0xaf + end + class Int8Text < TextRecord @record_type = 0x88 def initialize(handle, record_type) @value = handle.read(1)[0].to_s end end class Int8TextWithEndElement < Int8Text @record_type = 0x89 end class Int16Text < TextRecord @record_type = 0x8a def initialize(handle, record_type) @value = handle.read(2).unpack("n")[0].to_s end end class Int16TextWithEndElement < Int16Text @record_type = 0x8b end class Int32Text < TextRecord @record_type = 0x8c def initialize(handle, record_type) @value = handle.read(4).unpack("l")[0].to_s end end class Int32TextWithEndElement < Int32Text @record_type = 0x8d end class Int64Text < TextRecord @record_type = 0x8e def initialize(handle, record_type) @value = handle.read(8).unpack("q")[0].to_s end end class Int64TextWithEndElement < Int64Text @record_type = 0x8f end class FloatText < TextRecord @record_type = 0x90 def initialize(handle, record_type) @value = handle.read(4).unpack("g")[0].to_s end end class FloatTextWithEndRecord < FloatText @record_type = 0x91 end class DoubleText < TextRecord @record_type = 0x92 def initialize(handle, record_type) @value = handle.read(8).unpack("E")[0].to_s end end class DoubleTextWithEndElement < DoubleText @record_type = 0x93 end class DecimalText < TextRecord @record_type = 0x94 - # TODO: Implement DecimalText def initialize(handle, record_type) - raise "Not implemented" + wReserved = handle.read(2).unpack("n")[0] + scale = handle.read(1)[0] + @sign = handle.read(1)[0] == 0 ? "" : "-" + @value = 0 + 2.downto(0).each {|n| + @value |= (handle.read(4).unpack("N")[0]) << 32*n + puts "#{@value.to_s 16}" + } + @value /= 10.0**scale + end + + def to_s + "#{@sign}#{@value}" end end class DecimalTextWithEndRecord < DecimalText @record_type = 0x95 end end
yan/msbin
278ceb38d552139beca302a566f30f8f11addc16
reformatted and changed a lot
diff --git a/types.rb b/types.rb index a958d8d..ba9528a 100644 --- a/types.rb +++ b/types.rb @@ -1,478 +1,571 @@ #!/usr/bin/env ruby require 'msbin_types' +#TODO: Separate attributes, text records, etc into separate files and modules + $indent = -1 def write_xml(s, increase=1) indent = " "*$indent - #"(#{$indent} #{increase}) puts "#{indent}#{s}" $indent += increase end def read_byte(handle) return handle.read(1)[0] end -# TODO: finish read_int31 # TODO: bundle these in a module def read_int31(handle) - val = byte = read_byte(handle) - if byte & 0x7f - return byte - end - - byte = read_byte(handle) - - val <<= 8 - val |= (byte = read_byte(handle)) - return val + val = 0 + pow = 1 + begin + byte = read_byte(handle) + val += pow * (byte & 0x7F) + pow *= 2**7 + end while (byte & 0x80) == 0x80 + return val end def read_long(handle) return handle.read(4).unpack('L').first end def read_string(handle) len = read_int31(handle) str = handle.read(len) return str end $element_stack = [] module MSBIN class Record @@records = [] class << self + attr_accessor :record_type + def inherited(klass) @@records << klass end def is_attribute?(type) nil != @@records.select {|klass| klass.to_s =~ /Attribute$/}.find {|klass| klass.record_type === type} end def Decode(handle) while !handle.eof() a = MakeRecord(handle) indent = a.class == EndElement ? -1 : 0 write_xml a, indent if a.class.to_s =~ /WithEndElement$/# or ret.class == EndElement write_xml("</#{($element_stack.pop).name}>", -1) end end end def MakeRecord(handle) record_type = read_byte(handle) klass = @@records.find{|klass| klass.record_type === record_type} raise "Unsupported type: 0x#{record_type.to_s(16)}" if not klass #TODO: move the 2-arg initializer to the base class somehow ret = klass.new(handle, record_type) if ret.class.to_s =~ /Element$/ and ret.class.to_s !~ /EndElement$/ $element_stack.push ret end ret end end + def initialize(handle, record_type) + end + def get_attributes(handle) @attributes = [] loop do where = handle.pos next_type = read_byte(handle) handle.seek(where) break if not Record.is_attribute? next_type @attributes << Record.MakeRecord(handle) end end def type_of?(type) raise NotImplementedError end end end module MSBIN - class PrefixElement < Record - def self.record_type - return 0x5e .. 0x77 + class Reserved < Record + @record_type = 0x00 + + def initialize(handle, record_type) + raise "Reserved type used" + end + end + + class EndElement < Record + @record_type = 0x01 + + def to_s + "</#{$element_stack.pop.name}>" end + end + + class CommentElement < Record + @record_type = 0x02 + + def initialize(handle, record_type) + @value = "<!--#{read_string(handle)}-->" + end + end + + # TODO: Implement Array + class ArrayElement < Record + @record_type = 0x03 + + def initialize(handle, record_type) + raise "Array not implemented yet" + end + end + + class ShortAttribute < Record + @record_type = 0x04 + + def initialize(handle, record_type) + @name = read_string(handle) + @value = Record.MakeRecord(handle) + end + + def to_s + " #{@name}=\"#{@vlaue}\"" + end + end + + # TODO: Make other attributes inherit from this to make this make more sense + # TODO: Group them in a module and not have it all be flat + class Attribute < Record + @record_type = 0x05 + + def initialize(handle, record_type) + @prefix = read_string(handle) + @name = read_string(handle) + @value = Record.MakeRecord(handle) + end + + def to_s + " #{@prefix}:#{@name}=\"#{@value}\"" + end + end + + class ShortDictionaryAttribute < Record + @record_type = 0x06 + + def initialize(handle, record_type) + val = read_int31(handle) + @name = "#{MSBIN_DictionaryStrings[val]}" # handle.read(val) + @value = Record.MakeRecord(handle) + end + + def to_s + " #{@name}=#{@value}" + end + end + + class DictionaryAttribute < Record + @record_type = 0x07 + + # TODO: Create a read_* method for dictionary strings + # TODO: finalize the read_int31 function + def initialize(handle, record_type) + @prefix = read_string(handle) + @name = "#{MSBIN_DictionaryStrings[read_int31(handle)]}" + @value = Record.MakeRecord(handle) + end + + def to_s + " #{@prefix}:#{@name}=\"#{@value}\"" + end + end + + class PrefixElement < Record + @record_type = 0x5e .. 0x77 attr_accessor :name def initialize(handle, record_type) $indent += 1 @name = "#{(record_type-self.class.record_type.first+?a).chr}:" + read_string(handle) @record_type = record_type @attributes = [] get_attributes(handle) end def to_s attribs = @attributes ? " #{@attributes}" : "" "<#{@name}#{attribs}>" end end class PrefixAttribute < Record - def self.record_type; 0x26 .. 0x3f; end + @record_type = 0x26 .. 0x3f def initialize(handle, record_type) @name = "#{(record_type-self.class.record_type.first+?a).chr}:" + read_string(handle) @record_type = record_type @value = Record.MakeRecord(handle) end def to_s " #{@name}=\"#{@value}\"" end end class PrefixDictionaryElement < Record attr_accessor :attributes - def self.record_type - 0x44 .. 0x5D - end + @record_type = 0x44 .. 0x5D def initialize(handle, record_type) $indent += 1 @attributes = [] @record_type = record_type # read name val = read_int31(handle) @name = "#{MSBIN_DictionaryStrings[val]}" # handle.read(val) # TODO fill proper string names #puts "got name #{@name}" get_attributes(handle) end def name "#{(?a+@record_type-self.class.record_type.first).chr}:#{@name}" end def to_s attribs = @attributes ? " #{@attributes}" : "" "<#{(?a+@record_type-self.class.record_type.first).chr}:#{@name}#{attribs}>" end end class PrefixDictionaryAttribute < Record - def self.record_type - 0x0c .. 0x25 - end + @record_type = 0x0c .. 0x25 def initialize(handle, record_type) val = read_int31(handle) @name = "#{MSBIN_DictionaryStrings[val]}" @value = Record.MakeRecord(handle) @record_type = record_type end def to_s "#{@name}=\"#{@value}\"" end end class ShortDictionaryXmlnsAttribute < Record - def self.record_type; 0x0a; end + @record_type = 0x0a # TODO Isolate classes that do DictionaryStrings # TODO: the value will be ' xmlns="@{value}"' def initialize(handle, record_type) @value = "#{MSBIN_DictionaryStrings[read_long(handle)]}" end def to_s " xmlns=\"#{@value}\"" end end class DictionaryXmlnsAttribute < Record - def self.record_type - 0x0B - end + @record_type = 0X0b def initialize(handle, record_type) @prefix = read_string(handle) @attributes = "#{MSBIN_DictionaryStrings[read_int31(handle)]}"#Record.MakeRecord(handle) end def to_s " xmlns:#{@prefix}=\"#{@attributes}\"" end end class ShortXmlnsAttribute < Record - def self.record_type; 0x08; end + @record_type = 0x08 def initialize(handle, record_type) @value = read_string(handle) end def to_s " xmlns=\"#{@value}\"" end end class XmlnsAttribute < Record - def self.record_type; 0x09; end + @record_type = 0x09 def initialize(handle, record_type) @prefix = read_string(handle) @value = read_string(handle) end def to_s " xmlns:#{@prefix}=\"#{@value}\"" end end - class ShortAttribute < Record - def self.record_type; 0x04; end - - def initialize(handle, record_type) - @name = read_string(handle) - @value = Record.MakeRecord(handle) - end - - def to_s - " #{@name}=\"#{@vlaue}\"" - end - end - class ShortElement < Record - def self.record_type; 0x40; end + @record_type = 0x40 def initialize(handle, record_type) $indent += 1 @name = read_string(handle) get_attributes(handle) end def name @name end def to_s attribs = @attributes ? " #{@attributes}" : "" "<#{@name}#{attribs}>" end end # Make this an ADT class TextRecord < Record - def self.record_type; 0x00; end + @record_type = 0x00 + def initialize(handle, record_type) + @record_type = record_type + end + def to_s + @value.to_s + end end + class ZeroText < TextRecord + @record_type = 0x80 + def to_s; "0"; end + end + - class TrueText < Record - def self.record_type; 0x86; end - def initialize(handle, record_type); end + class TrueText < TextRecord + @record_type = 0x86 def to_s; "true"; end end class TrueTextWithEndElement < TrueText - def self.record_type; 0x87; end + @record_type = 0x87 end # TODO: make this derive from TextRecord - class FalseText < Record - def self.record_type; 0x84; end - def initialize(handle, record_type); end + class FalseText < TextRecord + @record_type = 0x84 def to_s; "false"; end end class FalseTextWithEndElement < FalseText - def self.record_type; 0x85; end + @record_type = 0x85 end - class OneText < Record - def self.record_type; 0x82; end - - def initialize(handle, record_type) - #@text = "1" - end - + class OneText < TextRecord + @record_type = 0x82 def to_s; "1"; end end class OneTextWithEndElement < OneText - def self.record_type; 0x83; end + @record_type = 0x83 end # TODO: Parse this better - class DateTimeTextWithEndElement < Record - def self.record_type; 0x97; end + class DateTimeText < TextRecord + @record_type = 0x96 def initialize(handle, record_type) # TODO: validate it @date_date val = handle.read(8).unpack("Q")[0] @tz = val & 0xff val >>= 2 # to microseconds val /= 10 # to seconds val /= (10**6) # seconds since year 1 until epoch start = Time.utc(1, "jan", 1, 0, 0, 0, 0) epoch = Time.at(0) # seconds since 0 val -= (epoch - start) # val is now epoch # not sure if this is correct, but it'll do for now - @value = Time.at(val) - end - - def to_s - if @value.hour == 0 and @value.minutes == 0 and @value.seconds == 0 - return @value.strftime("%Y-%m-%d") + time = Time.at(val) + if time.hour == 0 and time.minutes == 0 and time.seconds == 0 + @value = time.strftime("%Y-%m-%d") else - return @value.strftime("%Y-%m-%dT%H:%M:%S") + @value = time.strftime("%Y-%m-%dT%H:%M:%S") end end end - class DictionaryText < Record - def self.record_type; 0xaa; end + class DateTimeTextWithEndElement < DateTimeText + @record_type = 0x97 + end + + class DictionaryText < TextRecord + @record_type = 0xaa def initialize(handle, record_type) val = read_int31(handle) - @value = "#{MSBIN_DictionaryStrings[val]}" # handle.read(val) - end - - def to_s - @value + @value = MSBIN_DictionaryStrings[val] end end class DictionaryTextWithEndElement < DictionaryText - def self.record_type; 0xab; end + @record_type = 0xab end class Chars8Text < Record - def self.record_type; 0x98; end + @record_type = 0x98 def initialize(handle, record_type) - @length = handle.read(1)[0] - @text = handle.read(@length) - end - - def to_s - "#{@text}" + require 'cgi' + length = handle.read(1)[0] + @value = CGI.escapeHTML(handle.read(length)).to_s end end # TODO: Clean up the end element - class Chars8TextWithEndElement < Record - def self.record_type; 0x99; end + class Chars8TextWithEndElement < Chars8Text + @record_type = 0x99 + end + + class Chars16Text < Record + @record_type = 0x9a def initialize(handle, record_type) - @length = handle.read(1)[0] - @value = handle.read(@length) + require 'cgi' + length = handle.read(2).unpack("n")[0] + @value = CGI.escapeHTML(handle.read(length)).to_s end + end - def to_s - "#{@value}".gsub('"','&quot;').gsub('&','&amp;').gsub('<','&lt;').gsub('>','&gt;').gsub("'",'&apos;') - end + # TODO: Clean up the end element + class Chars16TextWithEndElement < Chars16Text + @record_type = 0x9b end class UniqueIdText < Record - def self.record_type; 0xac; end + @record_type = 0xac def initialize(handle, record_type) @uuid = handle.read(16).unpack('VvvC*') - end - - def to_s - return ("%08x-%04x-%04x-" % [@uuid[0], @uuid[1], @uuid[2]])+(("%02x"*6) % @uuid[3..-1]) + @value = ("%08x-%04x-%04x-" % [@uuid[0], @uuid[1], @uuid[2]])+(("%02x"*6) % @uuid[3..-1]) end end # TODO: Separate this class UniqueIdTextWithEndElement < UniqueIdText - def self.record_type; 0xad; end - - #def initialize(handle, record_type) - ##@text = handle.read(16).unpack('H*') - #@text = handle.read(16).unpack('VvvC*') - #end - #def to_s - #return ("%08x-%04x-%04x-" % [@text[0], @text[1], @text[2]])+(("%02x"*6) % @text[3..-1]) - #end + @record_type = 0xad end - class EndElement < Record - def self.record_type; 0x01; end + class Int8Text < TextRecord + @record_type = 0x88 def initialize(handle, record_type) + @value = handle.read(1)[0].to_s end + end - def to_s - "</#{$element_stack.pop.name}>" - end + class Int8TextWithEndElement < Int8Text + @record_type = 0x89 end - class Int8Text < Record - def self.record_type; 0x88; end + class Int16Text < TextRecord + @record_type = 0x8a def initialize(handle, record_type) - @value = handle.read(1)[0] + @value = handle.read(2).unpack("n")[0].to_s end + end - def to_s - @value.to_s - end + class Int16TextWithEndElement < Int16Text + @record_type = 0x8b end - class Int8TextWithEndElement < Record - def self.record_type; 0x89; end + class Int32Text < TextRecord + @record_type = 0x8c def initialize(handle, record_type) - @value = handle.read(1)[0] + @value = handle.read(4).unpack("l")[0].to_s end + end - def to_s - @value.to_s - end + class Int32TextWithEndElement < Int32Text + @record_type = 0x8d end - class Int16Text < Record - def self.record_type; 0x8a; end + class Int64Text < TextRecord + @record_type = 0x8e def initialize(handle, record_type) - @value = handle.read(2).unpack("n")[0] + @value = handle.read(8).unpack("q")[0].to_s end + end - def to_s - @value.to_s + class Int64TextWithEndElement < Int64Text + @record_type = 0x8f + end + + class FloatText < TextRecord + @record_type = 0x90 + + def initialize(handle, record_type) + @value = handle.read(4).unpack("g")[0].to_s end end - class Int16TextWithEndElement < Record - def self.record_type; 0x8b; end + class FloatTextWithEndRecord < FloatText + @record_type = 0x91 + end + + class DoubleText < TextRecord + @record_type = 0x92 def initialize(handle, record_type) - @value = handle.read(2).unpack("n")[0] + @value = handle.read(8).unpack("E")[0].to_s end + end - def to_s - @value.to_s + class DoubleTextWithEndElement < DoubleText + @record_type = 0x93 + end + + class DecimalText < TextRecord + @record_type = 0x94 + + # TODO: Implement DecimalText + def initialize(handle, record_type) + raise "Not implemented" end end + + class DecimalTextWithEndRecord < DecimalText + @record_type = 0x95 + end end
yan/msbin
f037cb1487d00abe0594e89c99a3792186bf7e25
starting reorg
diff --git a/encode.rb b/encode.rb old mode 100644 new mode 100755 index 7473f6b..48b8b44 --- a/encode.rb +++ b/encode.rb @@ -1,3 +1,8 @@ #!/usr/bin/env ruby +require 'rubygems' +require 'xmlsimple' +#xml = $stdin.read + +puts XmlSimple.xml_in($stdin.read) diff --git a/main.rb b/main.rb index 141a559..8a9c11d 100755 --- a/main.rb +++ b/main.rb @@ -1,31 +1,38 @@ #!/usr/bin/env ruby require 'records' require 'types' if ARGV.size == 0 - $stderr.write("Usage: #{$0} file.msbin\n") + $stderr.write("Usage: #{$0} [file.msbin|-]\n") exit 1 end def read_msbin(handle) while !handle.eof() a = MSBIN::Record.MakeRecord(handle) - indent = 0 - if a.class == MSBIN::EndElement - indent = -1 - else - indent = 1 - end + indent = a.class == MSBIN::EndElement ? -1 : 0 write_xml a, indent if a.class.to_s =~ /WithEndElement$/# or ret.class == EndElement write_xml("</#{($element_stack.pop).name}>", -1) end end end -f = File.new(ARGV[0], "rb") -read_msbin(f) +if ARGV[0] == '-' + f = $stdin +else + f = File.new(ARGV[0], "rb") +end + +# check if we have an http post, and consume headers +if f.read(4) == "HTTP" + while f.readline().chomp != ""; end +else + f.seek(0) +end + +MSBIN::Record.Decode(f) #puts f diff --git a/types.rb b/types.rb index b4327fb..a958d8d 100644 --- a/types.rb +++ b/types.rb @@ -1,434 +1,478 @@ #!/usr/bin/env ruby require 'msbin_types' -$indent = 0 +$indent = -1 def write_xml(s, increase=1) - $indent += increase - if $indent < 0 - $indent = 0 - end indent = " "*$indent #"(#{$indent} #{increase}) puts "#{indent}#{s}" + $indent += increase end def read_byte(handle) return handle.read(1)[0] end +# TODO: finish read_int31 +# TODO: bundle these in a module def read_int31(handle) val = byte = read_byte(handle) if byte & 0x7f return byte end byte = read_byte(handle) - #puts "#{val.to_s(16)} #{byte.to_s(16)}" val <<= 8 val |= (byte = read_byte(handle)) return val end def read_long(handle) return handle.read(4).unpack('L').first end def read_string(handle) len = read_int31(handle) str = handle.read(len) return str end $element_stack = [] module MSBIN class Record - RECORDS = [] - - def self.inherited(klass) - Record::RECORDS << klass + @@records = [] + + class << self + def inherited(klass) + @@records << klass + end + + def is_attribute?(type) + nil != @@records.select {|klass| klass.to_s =~ /Attribute$/}.find {|klass| klass.record_type === type} + end + + def Decode(handle) + while !handle.eof() + a = MakeRecord(handle) + indent = a.class == EndElement ? -1 : 0 + write_xml a, indent + + if a.class.to_s =~ /WithEndElement$/# or ret.class == EndElement + write_xml("</#{($element_stack.pop).name}>", -1) + end + end + end + + def MakeRecord(handle) + record_type = read_byte(handle) + klass = @@records.find{|klass| klass.record_type === record_type} + raise "Unsupported type: 0x#{record_type.to_s(16)}" if not klass + #TODO: move the 2-arg initializer to the base class somehow + ret = klass.new(handle, record_type) + + if ret.class.to_s =~ /Element$/ and ret.class.to_s !~ /EndElement$/ + $element_stack.push ret + end + + ret + end end + + def get_attributes(handle) + @attributes = [] + loop do + where = handle.pos + next_type = read_byte(handle) + handle.seek(where) - def self.is_attribute?(type) - nil != Record::RECORDS.select {|klass| klass.to_s =~ /Attribute$/}.find {|klass| klass.record_type === type} + break if not Record.is_attribute? next_type + @attributes << Record.MakeRecord(handle) + end end def type_of?(type) raise NotImplementedError end - - def self.MakeRecord(handle) - record_type = read_byte(handle) - klass = Record::RECORDS.find{|klass| klass.record_type === record_type} - #TODO: move the 2-arg initializer to the base class somehow - ret = klass.new(handle, record_type) - raise "Unsupported type: 0x#{record_type.to_s(16)}" if not ret - - if ret.class.to_s =~ /Element$/ and ret.class.to_s !~ /EndElement$/ - $element_stack.push ret - end - - ret - end end end module MSBIN class PrefixElement < Record def self.record_type return 0x5e .. 0x77 end attr_accessor :name def initialize(handle, record_type) + $indent += 1 @name = "#{(record_type-self.class.record_type.first+?a).chr}:" + read_string(handle) @record_type = record_type @attributes = [] - loop do - where = handle.pos - next_type = read_byte(handle) - handle.seek(where) + get_attributes(handle) + end - break if not Record.is_attribute? next_type - @attributes << Record.MakeRecord(handle) - end + def to_s + attribs = @attributes ? " #{@attributes}" : "" + "<#{@name}#{attribs}>" + end + end + + class PrefixAttribute < Record + def self.record_type; 0x26 .. 0x3f; end + def initialize(handle, record_type) + @name = "#{(record_type-self.class.record_type.first+?a).chr}:" + read_string(handle) + @record_type = record_type + @value = Record.MakeRecord(handle) end def to_s - attribs = "" - if @attributes - attribs = " #{@attributes}" - end - "<#{@name}#{attribs}>" + " #{@name}=\"#{@value}\"" end end class PrefixDictionaryElement < Record attr_accessor :attributes def self.record_type 0x44 .. 0x5D end def initialize(handle, record_type) + $indent += 1 @attributes = [] @record_type = record_type # read name val = read_int31(handle) @name = "#{MSBIN_DictionaryStrings[val]}" # handle.read(val) # TODO fill proper string names #puts "got name #{@name}" - loop do - where = handle.pos - next_type = read_byte(handle) - handle.seek(where) - - break if not Record.is_attribute? next_type - @attributes << Record.MakeRecord(handle) - end + get_attributes(handle) end def name "#{(?a+@record_type-self.class.record_type.first).chr}:#{@name}" end def to_s - attribs = "" - if @attributes - attribs = " #{@attributes}" - end + attribs = @attributes ? " #{@attributes}" : "" "<#{(?a+@record_type-self.class.record_type.first).chr}:#{@name}#{attribs}>" end end class PrefixDictionaryAttribute < Record def self.record_type 0x0c .. 0x25 end def initialize(handle, record_type) val = read_int31(handle) @name = "#{MSBIN_DictionaryStrings[val]}" @value = Record.MakeRecord(handle) @record_type = record_type end def to_s "#{@name}=\"#{@value}\"" end end class ShortDictionaryXmlnsAttribute < Record def self.record_type; 0x0a; end # TODO Isolate classes that do DictionaryStrings # TODO: the value will be ' xmlns="@{value}"' def initialize(handle, record_type) @value = "#{MSBIN_DictionaryStrings[read_long(handle)]}" end def to_s " xmlns=\"#{@value}\"" end end class DictionaryXmlnsAttribute < Record def self.record_type 0x0B end def initialize(handle, record_type) @prefix = read_string(handle) @attributes = "#{MSBIN_DictionaryStrings[read_int31(handle)]}"#Record.MakeRecord(handle) end def to_s " xmlns:#{@prefix}=\"#{@attributes}\"" end end class ShortXmlnsAttribute < Record def self.record_type; 0x08; end def initialize(handle, record_type) @value = read_string(handle) end def to_s " xmlns=\"#{@value}\"" end end class XmlnsAttribute < Record def self.record_type; 0x09; end def initialize(handle, record_type) @prefix = read_string(handle) @value = read_string(handle) end def to_s " xmlns:#{@prefix}=\"#{@value}\"" end end class ShortAttribute < Record def self.record_type; 0x04; end def initialize(handle, record_type) @name = read_string(handle) @value = Record.MakeRecord(handle) end def to_s " #{@name}=\"#{@vlaue}\"" end end class ShortElement < Record def self.record_type; 0x40; end def initialize(handle, record_type) + $indent += 1 @name = read_string(handle) - @attributes = []#Record.MakeRecord(handle) - loop do - where = handle.pos - next_type = read_byte(handle) - handle.seek(where) - - break if not Record.is_attribute? next_type - @attributes << Record.MakeRecord(handle) - end + get_attributes(handle) end def name @name end def to_s - "<#{@name} #{@attributes}>" + attribs = @attributes ? " #{@attributes}" : "" + "<#{@name}#{attribs}>" end end # Make this an ADT class TextRecord < Record def self.record_type; 0x00; end end - # TODO: make this derive from TextRecord - class FalseTextWithEndElement < Record - def self.record_type; 0x85; end + class TrueText < Record + def self.record_type; 0x86; end + def initialize(handle, record_type); end + def to_s; "true"; end + end - # TODO: Set a to_s to return false, that's it. - def initialize(handle, record_type) - #@text = read_string(handle) - end + class TrueTextWithEndElement < TrueText + def self.record_type; 0x87; end + end + # TODO: make this derive from TextRecord + class FalseText < Record + def self.record_type; 0x84; end + def initialize(handle, record_type); end def to_s; "false"; end end + + class FalseTextWithEndElement < FalseText + def self.record_type; 0x85; end + end class OneText < Record def self.record_type; 0x82; end def initialize(handle, record_type) #@text = "1" end def to_s; "1"; end end - class OneTextWithEndElement < Record + class OneTextWithEndElement < OneText def self.record_type; 0x83; end - - def initialize(handle, record_type) - #@text = "1" - end - - def to_s; "1"; end end # TODO: Parse this better class DateTimeTextWithEndElement < Record def self.record_type; 0x97; end def initialize(handle, record_type) # TODO: validate it @date_date val = handle.read(8).unpack("Q")[0] @tz = val & 0xff val >>= 2 # to microseconds val /= 10 # to seconds val /= (10**6) # seconds since year 1 until epoch start = Time.utc(1, "jan", 1, 0, 0, 0, 0) epoch = Time.at(0) # seconds since 0 val -= (epoch - start) # val is now epoch # not sure if this is correct, but it'll do for now @value = Time.at(val) end def to_s if @value.hour == 0 and @value.minutes == 0 and @value.seconds == 0 return @value.strftime("%Y-%m-%d") else return @value.strftime("%Y-%m-%dT%H:%M:%S") end end end + class DictionaryText < Record + def self.record_type; 0xaa; end + + def initialize(handle, record_type) + val = read_int31(handle) + @value = "#{MSBIN_DictionaryStrings[val]}" # handle.read(val) + end + + def to_s + @value + end + end + + class DictionaryTextWithEndElement < DictionaryText + def self.record_type; 0xab; end + end + class Chars8Text < Record def self.record_type; 0x98; end def initialize(handle, record_type) @length = handle.read(1)[0] @text = handle.read(@length) end def to_s "#{@text}" end end # TODO: Clean up the end element class Chars8TextWithEndElement < Record def self.record_type; 0x99; end def initialize(handle, record_type) @length = handle.read(1)[0] @value = handle.read(@length) end def to_s - "#{@value}" + "#{@value}".gsub('"','&quot;').gsub('&','&amp;').gsub('<','&lt;').gsub('>','&gt;').gsub("'",'&apos;') end end class UniqueIdText < Record def self.record_type; 0xac; end def initialize(handle, record_type) - @text = handle.read(16).unpack('VvvC*') + @uuid = handle.read(16).unpack('VvvC*') end def to_s - return ("%08x-%04x-%04x-" % [@text[0], @text[1], @text[2]])+(("%02x"*6) % [@text[3..-1]]) + return ("%08x-%04x-%04x-" % [@uuid[0], @uuid[1], @uuid[2]])+(("%02x"*6) % @uuid[3..-1]) end end # TODO: Separate this - class UniqueIdTextWithEndElement < Record + class UniqueIdTextWithEndElement < UniqueIdText def self.record_type; 0xad; end + #def initialize(handle, record_type) + ##@text = handle.read(16).unpack('H*') + #@text = handle.read(16).unpack('VvvC*') + #end + #def to_s + #return ("%08x-%04x-%04x-" % [@text[0], @text[1], @text[2]])+(("%02x"*6) % @text[3..-1]) + #end + end + + class EndElement < Record + def self.record_type; 0x01; end + def initialize(handle, record_type) - #@text = handle.read(16).unpack('H*') - @text = handle.read(16).unpack('VvvC*') end + def to_s - return ("%08x-%04x-%04x-" % [@text[0], @text[1], @text[2]])+(("%02x"*6) % @text[3..-1]) + "</#{$element_stack.pop.name}>" end end - class EndElement < Record - def self.record_type; 0x01; end + class Int8Text < Record + def self.record_type; 0x88; end def initialize(handle, record_type) + @value = handle.read(1)[0] end def to_s - "</#{$element_stack.pop.name}>" + @value.to_s end end - class TrueTextWithEndElement < Record - def self.record_type; 0x87; end + class Int8TextWithEndElement < Record + def self.record_type; 0x89; end - #TODO: return true as value def initialize(handle, record_type) - #@value = "true" + @value = handle.read(1)[0] end def to_s - "true" + @value.to_s end end - class Int8Text < Record - def self.record_type; 0x88; end + class Int16Text < Record + def self.record_type; 0x8a; end def initialize(handle, record_type) - @value = handle.read(1) + @value = handle.read(2).unpack("n")[0] end def to_s - @value[0].to_s + @value.to_s end end - class Int8TextWithEndElement < Record - def self.record_type; 0x89; end + class Int16TextWithEndElement < Record + def self.record_type; 0x8b; end def initialize(handle, record_type) - @value = handle.read(1) + @value = handle.read(2).unpack("n")[0] end def to_s - @value[0].to_s + @value.to_s end end end
yan/msbin
d0369464af9ed7c85364b80ddef40b936ff97397
more changes
diff --git a/encode.rb b/encode.rb new file mode 100644 index 0000000..7473f6b --- /dev/null +++ b/encode.rb @@ -0,0 +1,3 @@ +#!/usr/bin/env ruby + +
yan/msbin
c679c9dba5dfdf6381caf043ce3a611d388ee010
more changes
diff --git a/.main.rb.swp b/.main.rb.swp index ce607c7..ee9a7ca 100644 Binary files a/.main.rb.swp and b/.main.rb.swp differ diff --git a/.types.rb.swp b/.types.rb.swp index 72256d0..1a65658 100644 Binary files a/.types.rb.swp and b/.types.rb.swp differ diff --git a/main.rb b/main.rb index b217570..141a559 100755 --- a/main.rb +++ b/main.rb @@ -1,37 +1,31 @@ #!/usr/bin/env ruby require 'records' require 'types' if ARGV.size == 0 $stderr.write("Usage: #{$0} file.msbin\n") exit 1 end -# def read_byte(handle) -# return handle.read(1)[0] -# end -# -# def read_long(handle) -# return handle.read(4).unpack('L') -# end -# -# def read_string(handle) -# return handle.read(read_long(handle)) -# end -# -# def read_record(handle) -# record_type = read_byte(handle) -# -# print "record type: #{Records[record_type]}" -# end def read_msbin(handle) while !handle.eof() - MSBIN::Record.MakeRecord(handle) + a = MSBIN::Record.MakeRecord(handle) + indent = 0 + if a.class == MSBIN::EndElement + indent = -1 + else + indent = 1 + end + write_xml a, indent + + if a.class.to_s =~ /WithEndElement$/# or ret.class == EndElement + write_xml("</#{($element_stack.pop).name}>", -1) + end end end f = File.new(ARGV[0], "rb") read_msbin(f) #puts f diff --git a/msbin_types.rb b/msbin_types.rb new file mode 100644 index 0000000..b2bdf90 --- /dev/null +++ b/msbin_types.rb @@ -0,0 +1,490 @@ + +MSBIN_DictionaryStrings = { + 0x00 => "mustUnderstand", + 0x02 => "Envelope", + 0x04 => "http://www.w3.org/2003/05/soap-envelope", + 0x06 => "http://www.w3.org/2005/08/addressing", + 0x08 => "Header", + 0x0A => "Action", + 0x0C => "To", + 0x0E => "Body", + 0x10 => "Algorithm", + 0x12 => "RelatesTo", + 0x14 => "http://www.w3.org/2005/08/addressing/anonymous", + 0x16 => "URI", + 0x18 => "Reference", + 0x1A => "MessageID", + 0x1C => "Id", + 0x1E => "Identifier", + 0x20 => "http://schemas.xmlsoap.org/ws/2005/02/rm", + 0x22 => "Transforms", + 0x24 => "Transform", + 0x26 => "DigestMethod", + 0x28 => "DigestValue", + 0x2A => "Address", + 0x2C => "ReplyTo", + 0x2E => "SequenceAcknowledgement", + 0x30 => "AcknowledgementRange", + 0x32 => "Upper", + 0x34 => "Lower", + 0x36 => "BufferRemaining", + 0x38 => "http://schemas.microsoft.com/ws/2006/05/rm", + 0x3A => "http://schemas.xmlsoap.org/ws/2005/02/rm/SequenceAcknowledgement", + 0x3C => "SecurityTokenReference", + 0x3E => "Sequence", + 0x40 => "MessageNumber", + 0x42 => "http://www.w3.org/2000/09/xmldsig#", + 0x44 => "http://www.w3.org/2000/09/xmldsig#enveloped-signature", + 0x46 => "KeyInfo", + 0x48 => "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", + 0x4A => "http://www.w3.org/2001/04/xmlenc#", + 0x4C => "http://schemas.xmlsoap.org/ws/2005/02/sc", + 0x4E => "DerivedKeyToken", + 0x50 => "Nonce", + 0x52 => "Signature", + 0x54 => "SignedInfo", + 0x56 => "CanonicalizationMethod", + 0x58 => "SignatureMethod", + 0x5A => "SignatureValue", + 0x5C => "DataReference", + 0x5E => "EncryptedData", + 0x60 => "EncryptionMethod", + 0x62 => "CipherData", + 0x64 => "CipherValue", + 0x66 => "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd", + 0x68 => "Security", + 0x6A => "Timestamp", + 0x6C => "Created", + 0x6E => "Expires", + 0x70 => "Length", + 0x72 => "ReferenceList", + 0x74 => "ValueType", + 0x76 => "Type", + 0x78 => "EncryptedHeader", + 0x7A => "http://docs.oasis-open.org/wss/oasis-wss-wssecurity-secext-1.1.xsd", + 0x7C => "RequestSecurityTokenResponseCollection", + 0x7E => "http://schemas.xmlsoap.org/ws/2005/02/trust", + 0x80 => "http://schemas.xmlsoap.org/ws/2005/02/trust#BinarySecret", + 0x82 => "http://schemas.microsoft.com/ws/2006/02/transactions", + 0x84 => "s", + 0x86 => "Fault", + 0x88 => "MustUnderstand", + 0x8A => "role", + 0x8C => "relay", + 0x8E => "Code", + 0x90 => "Reason", + 0x92 => "Text", + 0x94 => "Node", + 0x96 => "Role", + 0x98 => "Detail", + 0x9A => "Value", + 0x9C => "Subcode", + 0x9E => "NotUnderstood", + 0xA0 => "qname", + 0xA2 => "", + 0xA4 => "From", + 0xA6 => "FaultTo", + 0xA8 => "EndpointReference", + 0xAA => "PortType", + 0xAC => "ServiceName", + 0xAE => "PortName", + 0xB0 => "ReferenceProperties", + 0xB2 => "RelationshipType", + 0xB4 => "Reply", + 0xB6 => "a", + 0xB8 => "http://schemas.xmlsoap.org/ws/2006/02/addressingidentity", + 0xBA => "Identity", + 0xBC => "Spn", + 0xBE => "Upn", + 0xC0 => "Rsa", + 0xC2 => "Dns", + 0xC4 => "X509v3Certificate", + 0xC6 => "http://www.w3.org/2005/08/addressing/fault", + 0xC8 => "ReferenceParameters", + 0xCA => "IsReferenceParameter", + 0xCC => "http://www.w3.org/2005/08/addressing/reply", + 0xCE => "http://www.w3.org/2005/08/addressing/none", + 0xD0 => "Metadata", + 0xD2 => "http://schemas.xmlsoap.org/ws/2004/08/addressing", + 0xD4 => "http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous", + 0xD6 => "http://schemas.xmlsoap.org/ws/2004/08/addressing/fault", + 0xD8 => "http://schemas.xmlsoap.org/ws/2004/06/addressingex", + 0xDA => "RedirectTo", + 0xDC => "Via", + 0xDE => "http://www.w3.org/2001/10/xml-exc-c14n#", + 0xE0 => "PrefixList", + 0xE2 => "InclusiveNamespaces", + 0xE4 => "ec", + 0xE6 => "SecurityContextToken", + 0xE8 => "Generation", + 0xEA => "Label", + 0xEC => "Offset", + 0xEE => "Properties", + 0xF0 => "Cookie", + 0xF2 => "wsc", + 0xF4 => "http://schemas.xmlsoap.org/ws/2004/04/sc", + 0xF6 => "http://schemas.xmlsoap.org/ws/2004/04/security/sc/dk", + 0xF8 => "http://schemas.xmlsoap.org/ws/2004/04/security/sc/sct", + 0xFA => "http://schemas.xmlsoap.org/ws/2004/04/security/trust/RST/SCT", + 0xFC => "http://schemas.xmlsoap.org/ws/2004/04/security/trust/RSTR/SCT", + 0xFE => "RenewNeeded", + 0x100 => "BadContextToken", + 0x102 => "c", + 0x104 => "http://schemas.xmlsoap.org/ws/2005/02/sc/dk", + 0x106 => "http://schemas.xmlsoap.org/ws/2005/02/sc/sct", + 0x108 => "http://schemas.xmlsoap.org/ws/2005/02/trust/RST/SCT", + 0x10A => "http://schemas.xmlsoap.org/ws/2005/02/trust/RSTR/SCT", + 0x10C => "http://schemas.xmlsoap.org/ws/2005/02/trust/RST/SCT/Renew", + 0x10E => "http://schemas.xmlsoap.org/ws/2005/02/trust/RSTR/SCT/Renew", + 0x110 => "http://schemas.xmlsoap.org/ws/2005/02/trust/RST/SCT/Cancel", + 0x112 => "http://schemas.xmlsoap.org/ws/2005/02/trust/RSTR/SCT/Cancel", + 0x114 => "http://www.w3.org/2001/04/xmlenc#aes128-cbc", + 0x116 => "http://www.w3.org/2001/04/xmlenc#kw-aes128", + 0x118 => "http://www.w3.org/2001/04/xmlenc#aes192-cbc", + 0x11A => "http://www.w3.org/2001/04/xmlenc#kw-aes192", + 0x11C => "http://www.w3.org/2001/04/xmlenc#aes256-cbc", + 0x11E => "http://www.w3.org/2001/04/xmlenc#kw-aes256", + 0x120 => "http://www.w3.org/2001/04/xmlenc#des-cbc", + 0x122 => "http://www.w3.org/2000/09/xmldsig#dsa-sha1", + 0x124 => "http://www.w3.org/2001/10/xml-exc-c14n#WithComments", + 0x126 => "http://www.w3.org/2000/09/xmldsig#hmac-sha1", + 0x128 => "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256", + 0x12A => "http://schemas.xmlsoap.org/ws/2005/02/sc/dk/p_sha1", + 0x12C => "http://www.w3.org/2001/04/xmlenc#ripemd160", + 0x12E => "http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p", + 0x130 => "http://www.w3.org/2000/09/xmldsig#rsa-sha1", + 0x132 => "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256", + 0x134 => "http://www.w3.org/2001/04/xmlenc#rsa-1_5", + 0x136 => "http://www.w3.org/2000/09/xmldsig#sha1", + 0x138 => "http://www.w3.org/2001/04/xmlenc#sha256", + 0x13A => "http://www.w3.org/2001/04/xmlenc#sha512", + 0x13C => "http://www.w3.org/2001/04/xmlenc#tripledes-cbc", + 0x13E => "http://www.w3.org/2001/04/xmlenc#kw-tripledes", + 0x140 => "http://schemas.xmlsoap.org/2005/02/trust/tlsnego#TLS_Wrap", + 0x142 => "http://schemas.xmlsoap.org/2005/02/trust/spnego#GSS_Wrap", + 0x144 => "http://schemas.microsoft.com/ws/2006/05/security", + 0x146 => "dnse", + 0x148 => "o", + 0x14A => "Password", + 0x14C => "PasswordText", + 0x14E => "Username", + 0x150 => "UsernameToken", + 0x152 => "BinarySecurityToken", + 0x154 => "EncodingType", + 0x156 => "KeyIdentifier", + 0x158 => "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security- 1.0#Base64Binary", + 0x15A => "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security- 1.0#HexBinary", + 0x15C => "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Text", + 0x15E => "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile- 1.0#X509SubjectKeyIdentifier", + 0x160 => "http://docs.oasis-open.org/wss/oasis-wss-kerberos-token-profile-1.1#GSS_Kerberosv5_AP_REQ", + 0x162 => "http://docs.oasis-open.org/wss/oasis-wss-kerberos-token-profile- 1.1#GSS_Kerberosv5_AP_REQ1510", + 0x164 => "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.0#SAMLAssertionID", + 0x166 => "Assertion", + 0x168 => "urn:oasis:names:tc:SAML:1.0:assertion", + 0x16A => "http://docs.oasis-open.org/wss/oasis-wss-rel-token-profile-1.0.pdf#license", + 0x16C => "FailedAuthentication", + 0x16E => "InvalidSecurityToken", + 0x170 => "InvalidSecurity", + 0x172 => "k", + 0x174 => "SignatureConfirmation", + 0x176 => "TokenType", + 0x178 => "http://docs.oasis-open.org/wss/oasis-wss-soap-message-security-1.1#ThumbprintSHA1", + 0x17A => "http://docs.oasis-open.org/wss/oasis-wss-soap-message-security-1.1#EncryptedKey", + 0x17C => "http://docs.oasis-open.org/wss/oasis-wss-soap-message-security-1.1#EncryptedKeySHA1", + 0x17E => "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV1.1", + 0x180 => "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0", + 0x182 => "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLID", + 0x184 => "AUTH-HASH", + 0x186 => "RequestSecurityTokenResponse", + 0x188 => "KeySize", + 0x18A => "RequestedTokenReference", + 0x18C => "AppliesTo", + 0x18E => "Authenticator", + 0x190 => "CombinedHash", + 0x192 => "BinaryExchange", + 0x194 => "Lifetime", + 0x196 => "RequestedSecurityToken", + 0x198 => "Entropy", + 0x19A => "RequestedProofToken", + 0x19C => "ComputedKey", + 0x19E => "RequestSecurityToken", + 0x1A0 => "RequestType", + 0x1A2 => "Context", + 0x1A4 => "BinarySecret", + 0x1A6 => "http://schemas.xmlsoap.org/ws/2005/02/trust/spnego", + 0x1A8 => "http://schemas.xmlsoap.org/ws/2005/02/trust/tlsnego", + 0x1AA => "wst", + 0x1AC => "http://schemas.xmlsoap.org/ws/2004/04/trust", + 0x1AE => "http://schemas.xmlsoap.org/ws/2004/04/security/trust/RST/Issue", + 0x1B0 => "http://schemas.xmlsoap.org/ws/2004/04/security/trust/RSTR/Issue", + 0x1B2 => "http://schemas.xmlsoap.org/ws/2004/04/security/trust/Issue", + 0x1B4 => "http://schemas.xmlsoap.org/ws/2004/04/security/trust/CK/PSHA1", + 0x1B6 => "http://schemas.xmlsoap.org/ws/2004/04/security/trust/SymmetricKey", + 0x1B8 => "http://schemas.xmlsoap.org/ws/2004/04/security/trust/Nonce", + 0x1BA => "KeyType", + 0x1BC => "http://schemas.xmlsoap.org/ws/2004/04/trust/SymmetricKey", + 0x1BE => "http://schemas.xmlsoap.org/ws/2004/04/trust/PublicKey", + 0x1C0 => "Claims", + 0x1C2 => "InvalidRequest", + 0x1C4 => "RequestFailed", + 0x1C6 => "SignWith", + 0x1C8 => "EncryptWith", + 0x1CA => "EncryptionAlgorithm", + 0x1CC => "CanonicalizationAlgorithm", + 0x1CE => "ComputedKeyAlgorithm", + 0x1D0 => "UseKey", + 0x1D2 => "http://schemas.microsoft.com/net/2004/07/secext/WS-SPNego", + 0x1D4 => "http://schemas.microsoft.com/net/2004/07/secext/TLSNego", + 0x1D6 => "t", + 0x1D8 => "http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue", + 0x1DA => "http://schemas.xmlsoap.org/ws/2005/02/trust/RSTR/Issue", + 0x1DC => "http://schemas.xmlsoap.org/ws/2005/02/trust/Issue", + 0x1DE => "http://schemas.xmlsoap.org/ws/2005/02/trust/SymmetricKey", + 0x1E0 => "http://schemas.xmlsoap.org/ws/2005/02/trust/CK/PSHA1", + 0x1E2 => "http://schemas.xmlsoap.org/ws/2005/02/trust/Nonce", + 0x1E4 => "RenewTarget", + 0x1E6 => "CancelTarget", + 0x1E8 => "RequestedTokenCancelled", + 0x1EA => "RequestedAttachedReference", + 0x1EC => "RequestedUnattachedReference", + 0x1EE => "IssuedTokens", + 0x1F0 => "http://schemas.xmlsoap.org/ws/2005/02/trust/Renew", + 0x1F2 => "http://schemas.xmlsoap.org/ws/2005/02/trust/Cancel", + 0x1F4 => "http://schemas.xmlsoap.org/ws/2005/02/trust/PublicKey", + 0x1F6 => "Access", + 0x1F8 => "AccessDecision", + 0x1FA => "Advice", + 0x1FC => "AssertionID", + 0x1FE => "AssertionIDReference", + 0x200 => "Attribute", + 0x202 => "AttributeName", + 0x204 => "AttributeNamespace", + 0x206 => "AttributeStatement", + 0x208 => "AttributeValue", + 0x20A => "Audience", + 0x20C => "AudienceRestrictionCondition", + 0x20E => "AuthenticationInstant", + 0x210 => "AuthenticationMethod", + 0x212 => "AuthenticationStatement", + 0x214 => "AuthorityBinding", + 0x216 => "AuthorityKind", + 0x218 => "AuthorizationDecisionStatement", + 0x21A => "Binding", + 0x21C => "Condition", + 0x21E => "Conditions", + 0x220 => "Decision", + 0x222 => "DoNotCacheCondition", + 0x224 => "Evidence", + 0x226 => "IssueInstant", + 0x228 => "Issuer", + 0x22A => "Location", + 0x22C => "MajorVersion", + 0x22E => "MinorVersion", + 0x230 => "NameIdentifier", + 0x232 => "Format", + 0x234 => "NameQualifier", + 0x236 => "Namespace", + 0x238 => "NotBefore", + 0x23A => "NotOnOrAfter", + 0x23C => "saml", + 0x23E => "Statement", + 0x240 => "Subject", + 0x242 => "SubjectConfirmation", + 0x244 => "SubjectConfirmationData", + 0x246 => "ConfirmationMethod", + 0x248 => "urn:oasis:names:tc:SAML:1.0:cm:holder-of-key", + 0x24A => "urn:oasis:names:tc:SAML:1.0:cm:sender-vouches", + 0x24C => "SubjectLocality", + 0x24E => "DNSAddress", + 0x250 => "IPAddress", + 0x252 => "SubjectStatement", + 0x254 => "urn:oasis:names:tc:SAML:1.0:am:unspecified", + 0x256 => "xmlns", + 0x258 => "Resource", + 0x25A => "UserName", + 0x25C => "urn:oasis:names:tc:SAML:1.1:nameid-format:WindowsDomainQualifiedName", + 0x25E => "EmailName", + 0x260 => "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress", + 0x262 => "u", + 0x264 => "ChannelInstance", + 0x266 => "http://schemas.microsoft.com/ws/2005/02/duplex", + 0x268 => "Encoding", + 0x26A => "MimeType", + 0x26C => "CarriedKeyName", + 0x26E => "Recipient", + 0x270 => "EncryptedKey", + 0x272 => "KeyReference", + 0x274 => "e", + 0x276 => "http://www.w3.org/2001/04/xmlenc#Element", + 0x278 => "http://www.w3.org/2001/04/xmlenc#Content", + 0x27A => "KeyName", + 0x27C => "MgmtData", + 0x27E => "KeyValue", + 0x280 => "RSAKeyValue", + 0x282 => "Modulus", + 0x284 => "Exponent", + 0x286 => "X509Data", + 0x288 => "X509IssuerSerial", + 0x28A => "X509IssuerName", + 0x28C => "X509SerialNumber", + 0x28E => "X509Certificate", + 0x290 => "AckRequested", + 0x292 => "http://schemas.xmlsoap.org/ws/2005/02/rm/AckRequested", + 0x294 => "AcksTo", + 0x296 => "Accept", + 0x298 => "CreateSequence", + 0x29A => "http://schemas.xmlsoap.org/ws/2005/02/rm/CreateSequence", + 0x29C => "CreateSequenceRefused", + 0x29E => "CreateSequenceResponse", + 0x2A0 => "http://schemas.xmlsoap.org/ws/2005/02/rm/CreateSequenceResponse", + 0x2A2 => "FaultCode", + 0x2A4 => "InvalidAcknowledgement", + 0x2A6 => "LastMessage", + 0x2A8 => "http://schemas.xmlsoap.org/ws/2005/02/rm/LastMessage", + 0x2AA => "LastMessageNumberExceeded", + 0x2AC => "MessageNumberRollover", + 0x2AE => "Nack", + 0x2B0 => "netrm", + 0x2B2 => "Offer", + 0x2B4 => "r", + 0x2B6 => "SequenceFault", + 0x2B8 => "SequenceTerminated", + 0x2BA => "TerminateSequence", + 0x2BC => "http://schemas.xmlsoap.org/ws/2005/02/rm/TerminateSequence", + 0x2BE => "UnknownSequence", + 0x2C0 => "http://schemas.microsoft.com/ws/2006/02/tx/oletx", + 0x2C2 => "oletx", + 0x2C4 => "OleTxTransaction", + 0x2C6 => "PropagationToken", + 0x2C8 => "http://schemas.xmlsoap.org/ws/2004/10/wscoor", + 0x2CA => "wscoor", + 0x2CC => "CreateCoordinationContext", + 0x2CE => "CreateCoordinationContextResponse", + 0x2D0 => "CoordinationContext", + 0x2D2 => "CurrentContext", + 0x2D4 => "CoordinationType", + 0x2D6 => "RegistrationService", + 0x2D8 => "Register", + 0x2DA => "RegisterResponse", + 0x2DC => "ProtocolIdentifier", + 0x2DE => "CoordinatorProtocolService", + 0x2E0 => "ParticipantProtocolService", + 0x2E2 => "http://schemas.xmlsoap.org/ws/2004/10/wscoor/CreateCoordinationContext", + 0x2E4 => "http://schemas.xmlsoap.org/ws/2004/10/wscoor/CreateCoordinationContextResponse", + 0x2E6 => "http://schemas.xmlsoap.org/ws/2004/10/wscoor/Register", + 0x2E8 => "http://schemas.xmlsoap.org/ws/2004/10/wscoor/RegisterResponse", + 0x2EA => "http://schemas.xmlsoap.org/ws/2004/10/wscoor/fault", + 0x2EC => "ActivationCoordinatorPortType", + 0x2EE => "RegistrationCoordinatorPortType", + 0x2F0 => "InvalidState", + 0x2F2 => "InvalidProtocol", + 0x2F4 => "InvalidParameters", + 0x2F6 => "NoActivity", + 0x2F8 => "ContextRefused", + 0x2FA => "AlreadyRegistered", + 0x2FC => "http://schemas.xmlsoap.org/ws/2004/10/wsat", + 0x2FE => "wsat", + 0x300 => "http://schemas.xmlsoap.org/ws/2004/10/wsat/Completion", + 0x302 => "http://schemas.xmlsoap.org/ws/2004/10/wsat/Durable2PC", + 0x304 => "http://schemas.xmlsoap.org/ws/2004/10/wsat/Volatile2PC", + 0x306 => "Prepare", + 0x308 => "Prepared", + 0x30A => "ReadOnly", + 0x30C => "Commit", + 0x30E => "Rollback", + 0x310 => "Committed", + 0x312 => "Aborted", + 0x314 => "Replay", + 0x316 => "http://schemas.xmlsoap.org/ws/2004/10/wsat/Commit", + 0x318 => "http://schemas.xmlsoap.org/ws/2004/10/wsat/Rollback", + 0x31A => "http://schemas.xmlsoap.org/ws/2004/10/wsat/Committed", + 0x31C => "http://schemas.xmlsoap.org/ws/2004/10/wsat/Aborted", + 0x31E => "http://schemas.xmlsoap.org/ws/2004/10/wsat/Prepare", + 0x320 => "http://schemas.xmlsoap.org/ws/2004/10/wsat/Prepared", + 0x322 => "http://schemas.xmlsoap.org/ws/2004/10/wsat/ReadOnly", + 0x324 => "http://schemas.xmlsoap.org/ws/2004/10/wsat/Replay", + 0x326 => "http://schemas.xmlsoap.org/ws/2004/10/wsat/fault", + 0x328 => "CompletionCoordinatorPortType", + 0x32A => "CompletionParticipantPortType", + 0x32C => "CoordinatorPortType", + 0x32E => "ParticipantPortType", + 0x330 => "InconsistentInternalState", + 0x332 => "mstx", + 0x334 => "Enlistment", + 0x336 => "protocol", + 0x338 => "LocalTransactionId", + 0x33A => "IsolationLevel", + 0x33C => "IsolationFlags", + 0x33E => "Description", + 0x340 => "Loopback", + 0x342 => "RegisterInfo", + 0x344 => "ContextId", + 0x346 => "TokenId", + 0x348 => "AccessDenied", + 0x34A => "InvalidPolicy", + 0x34C => "CoordinatorRegistrationFailed", + 0x34E => "TooManyEnlistments", + 0x350 => "Disabled", + 0x352 => "ActivityId", + 0x354 => "http://schemas.microsoft.com/2004/09/ServiceModel/Diagnostics", + 0x356 => "http://docs.oasis-open.org/wss/oasis-wss-kerberos-token-profile-1.1#Kerberosv5APREQSHA1", + 0x358 => "http://schemas.xmlsoap.org/ws/2002/12/policy", + 0x35A => "FloodMessage", + 0x35C => "LinkUtility", + 0x35E => "Hops", + 0x360 => "http://schemas.microsoft.com/net/2006/05/peer/HopCount", + 0x362 => "PeerVia", + 0x364 => "http://schemas.microsoft.com/net/2006/05/peer", + 0x366 => "PeerFlooder", + 0x368 => "PeerTo", + 0x36A => "http://schemas.microsoft.com/ws/2005/05/routing", + 0x36C => "PacketRoutable", + 0x36E => "http://schemas.microsoft.com/ws/2005/05/addressing/none", + 0x370 => "http://schemas.microsoft.com/ws/2005/05/envelope/none", + 0x372 => "http://www.w3.org/2001/XMLSchema-instance", + 0x374 => "http://www.w3.org/2001/XMLSchema", + 0x376 => "nil", + 0x378 => "type", + 0x37A => "char", + 0x37C => "boolean", + 0x37E => "byte", + 0x380 => "unsignedByte", + 0x382 => "short", + 0x384 => "unsignedShort", + 0x386 => "int", + 0x388 => "unsignedInt", + 0x38A => "long", + 0x38C => "unsignedLong", + 0x38E => "float", + 0x390 => "double", + 0x392 => "decimal", + 0x394 => "dateTime", + 0x396 => "string", + 0x398 => "base64Binary", + 0x39A => "anyType", + 0x39C => "duration", + 0x39E => "guid", + 0x3A0 => "anyURI", + 0x3A2 => "QName", + 0x3A4 => "time", + 0x3A6 => "date", + 0x3A8 => "hexBinary", + 0x3AA => "gYearMonth", + 0x3AC => "gYear", + 0x3AE => "gMonthDay", + 0x3B0 => "gDay", + 0x3B2 => "gMonth", + 0x3B4 => "integer", + 0x3B6 => "positiveInteger", + 0x3B8 => "negativeInteger", + 0x3BA => "nonPositiveInteger", + 0x3BC => "nonNegativeInteger", + 0x3BE => "normalizedString", + 0x3C0 => "ConnectionLimitReached", + 0x3C2 => "http://schemas.xmlsoap.org/soap/envelope/", + 0x3C4 => "actor", + 0x3C6 => "faultcode", + 0x3C8 => "faultstring", + 0x3CA => "faultactor", + 0x3CC => "detail" +} diff --git a/types.rb b/types.rb index 0c2f8bb..b4327fb 100644 --- a/types.rb +++ b/types.rb @@ -1,310 +1,434 @@ #!/usr/bin/env ruby +require 'msbin_types' + +$indent = 0 +def write_xml(s, increase=1) + $indent += increase + if $indent < 0 + $indent = 0 + end + indent = " "*$indent + #"(#{$indent} #{increase}) + puts "#{indent}#{s}" +end def read_byte(handle) return handle.read(1)[0] end def read_int31(handle) val = byte = read_byte(handle) if byte & 0x7f return byte end byte = read_byte(handle) - puts "#{val.to_s(16)} #{byte.to_s(16)}" + #puts "#{val.to_s(16)} #{byte.to_s(16)}" val <<= 8 val |= (byte = read_byte(handle)) return val end def read_long(handle) return handle.read(4).unpack('L').first end def read_string(handle) len = read_int31(handle) str = handle.read(len) return str end +$element_stack = [] + module MSBIN class Record - @RECORDS = [] + RECORDS = [] def self.inherited(klass) - @RECORDS << klass + Record::RECORDS << klass + end + + def self.is_attribute?(type) + nil != Record::RECORDS.select {|klass| klass.to_s =~ /Attribute$/}.find {|klass| klass.record_type === type} end def type_of?(type) raise NotImplementedError end def self.MakeRecord(handle) record_type = read_byte(handle) - ret = nil - @RECORDS.each do |klass| - if klass.record_type === record_type - #TODO: move the 2-arg initializer to the base class somehow - ret = klass.new(handle, record_type) - end + klass = Record::RECORDS.find{|klass| klass.record_type === record_type} + #TODO: move the 2-arg initializer to the base class somehow + ret = klass.new(handle, record_type) + raise "Unsupported type: 0x#{record_type.to_s(16)}" if not ret + + if ret.class.to_s =~ /Element$/ and ret.class.to_s !~ /EndElement$/ + $element_stack.push ret end - raise record_type.to_s(16) if not ret - puts "Returning #{ret}" + ret end end end module MSBIN class PrefixElement < Record def self.record_type return 0x5e .. 0x77 end + attr_accessor :name + def initialize(handle, record_type) - @name = read_string(handle) + @name = "#{(record_type-self.class.record_type.first+?a).chr}:" + read_string(handle) @record_type = record_type - @attributes = Record.MakeRecord(handle) + @attributes = [] + + loop do + where = handle.pos + next_type = read_byte(handle) + handle.seek(where) + + break if not Record.is_attribute? next_type + @attributes << Record.MakeRecord(handle) + end + end def to_s - "<#{(?a+@record_type-self.class.record_type.first).chr}:#{@name} #{@attributes}>" + attribs = "" + if @attributes + attribs = " #{@attributes}" + end + "<#{@name}#{attribs}>" end end class PrefixDictionaryElement < Record - attr :children + attr_accessor :attributes def self.record_type 0x44 .. 0x5D end def initialize(handle, record_type) - @children = [] + @attributes = [] @record_type = record_type # read name val = read_int31(handle) - @name = "str#{val}" # handle.read(val) + @name = "#{MSBIN_DictionaryStrings[val]}" # handle.read(val) # TODO fill proper string names #puts "got name #{@name}" - # read attributes - @children = Record.MakeRecord(handle) + loop do + where = handle.pos + next_type = read_byte(handle) + handle.seek(where) + + break if not Record.is_attribute? next_type + @attributes << Record.MakeRecord(handle) + end + end + + def name + "#{(?a+@record_type-self.class.record_type.first).chr}:#{@name}" end def to_s - "<#{(?a+@record_type-self.class.record_type.first).chr}" + attribs = "" + if @attributes + attribs = " #{@attributes}" + end + "<#{(?a+@record_type-self.class.record_type.first).chr}:#{@name}#{attribs}>" end end class PrefixDictionaryAttribute < Record def self.record_type 0x0c .. 0x25 end def initialize(handle, record_type) val = read_int31(handle) - @name = "str#{val}" + @name = "#{MSBIN_DictionaryStrings[val]}" @value = Record.MakeRecord(handle) @record_type = record_type end def to_s "#{@name}=\"#{@value}\"" end end class ShortDictionaryXmlnsAttribute < Record def self.record_type; 0x0a; end # TODO Isolate classes that do DictionaryStrings # TODO: the value will be ' xmlns="@{value}"' def initialize(handle, record_type) - @value = "str#{read_long(handle)}" + @value = "#{MSBIN_DictionaryStrings[read_long(handle)]}" end def to_s " xmlns=\"#{@value}\"" end end class DictionaryXmlnsAttribute < Record def self.record_type 0x0B end def initialize(handle, record_type) @prefix = read_string(handle) - @attributes = "str#{read_int31(handle)}"#Record.MakeRecord(handle) + @attributes = "#{MSBIN_DictionaryStrings[read_int31(handle)]}"#Record.MakeRecord(handle) end def to_s - " xmlns:#{@prefix}=\"#{@attributes}" + " xmlns:#{@prefix}=\"#{@attributes}\"" end end class ShortXmlnsAttribute < Record def self.record_type; 0x08; end def initialize(handle, record_type) @value = read_string(handle) end def to_s " xmlns=\"#{@value}\"" end end class XmlnsAttribute < Record def self.record_type; 0x09; end def initialize(handle, record_type) @prefix = read_string(handle) @value = read_string(handle) end def to_s " xmlns:#{@prefix}=\"#{@value}\"" end end class ShortAttribute < Record def self.record_type; 0x04; end def initialize(handle, record_type) @name = read_string(handle) @value = Record.MakeRecord(handle) end def to_s " #{@name}=\"#{@vlaue}\"" end end class ShortElement < Record def self.record_type; 0x40; end def initialize(handle, record_type) @name = read_string(handle) - @attribs = Record.MakeRecord(handle) + @attributes = []#Record.MakeRecord(handle) + loop do + where = handle.pos + next_type = read_byte(handle) + handle.seek(where) + + break if not Record.is_attribute? next_type + @attributes << Record.MakeRecord(handle) + end + end + + def name + @name end def to_s "<#{@name} #{@attributes}>" end end # Make this an ADT class TextRecord < Record def self.record_type; 0x00; end end # TODO: make this derive from TextRecord class FalseTextWithEndElement < Record def self.record_type; 0x85; end # TODO: Set a to_s to return false, that's it. def initialize(handle, record_type) #@text = read_string(handle) end + + def to_s; "false"; end end class OneText < Record def self.record_type; 0x82; end def initialize(handle, record_type) - @text = "1" + #@text = "1" end + + def to_s; "1"; end end class OneTextWithEndElement < Record def self.record_type; 0x83; end def initialize(handle, record_type) - @text = "1" + #@text = "1" end + + def to_s; "1"; end end # TODO: Parse this better class DateTimeTextWithEndElement < Record def self.record_type; 0x97; end def initialize(handle, record_type) - @date_date = handle.read(8) + # TODO: validate it + @date_date + val = handle.read(8).unpack("Q")[0] + @tz = val & 0xff + val >>= 2 + + # to microseconds + val /= 10 + + # to seconds + val /= (10**6) + + # seconds since year 1 until epoch + start = Time.utc(1, "jan", 1, 0, 0, 0, 0) + epoch = Time.at(0) + # seconds since 0 + val -= (epoch - start) + + # val is now epoch + # not sure if this is correct, but it'll do for now + @value = Time.at(val) + end + + def to_s + if @value.hour == 0 and @value.minutes == 0 and @value.seconds == 0 + return @value.strftime("%Y-%m-%d") + else + return @value.strftime("%Y-%m-%dT%H:%M:%S") + end end end class Chars8Text < Record def self.record_type; 0x98; end def initialize(handle, record_type) @length = handle.read(1)[0] @text = handle.read(@length) end + + def to_s + "#{@text}" + end end # TODO: Clean up the end element class Chars8TextWithEndElement < Record def self.record_type; 0x99; end def initialize(handle, record_type) @length = handle.read(1)[0] - @text = handle.read(@length) + @value = handle.read(@length) + end + + def to_s + "#{@value}" end end class UniqueIdText < Record def self.record_type; 0xac; end def initialize(handle, record_type) - @text = handle.read(16).unpack('H*') - puts "Got UUID: #{@text}" + @text = handle.read(16).unpack('VvvC*') + end + + def to_s + return ("%08x-%04x-%04x-" % [@text[0], @text[1], @text[2]])+(("%02x"*6) % [@text[3..-1]]) end end # TODO: Separate this - class UniqueIdText < Record + class UniqueIdTextWithEndElement < Record def self.record_type; 0xad; end def initialize(handle, record_type) - @text = handle.read(16).unpack('H*') - puts "Got UUID: #{@text}" + #@text = handle.read(16).unpack('H*') + @text = handle.read(16).unpack('VvvC*') + end + def to_s + return ("%08x-%04x-%04x-" % [@text[0], @text[1], @text[2]])+(("%02x"*6) % @text[3..-1]) end end class EndElement < Record def self.record_type; 0x01; end def initialize(handle, record_type) end + + def to_s + "</#{$element_stack.pop.name}>" + end end class TrueTextWithEndElement < Record def self.record_type; 0x87; end #TODO: return true as value def initialize(handle, record_type) - @value = "true" + #@value = "true" + end + + def to_s + "true" end end class Int8Text < Record def self.record_type; 0x88; end def initialize(handle, record_type) @value = handle.read(1) end + + def to_s + @value[0].to_s + end end class Int8TextWithEndElement < Record def self.record_type; 0x89; end def initialize(handle, record_type) @value = handle.read(1) end + + def to_s + @value[0].to_s + end end end
yan/msbin
f912a4c668c04e306826be097114c20e6b665e4f
added a gitignore
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..584aca0 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +.sw* +.*.swp
yan/msbin
3eca1de7f53aed04b22a829e91daaa12fdbd971c
more changes
diff --git a/.main.rb.swp b/.main.rb.swp new file mode 100644 index 0000000..ce607c7 Binary files /dev/null and b/.main.rb.swp differ diff --git a/.records.rb.swp b/.records.rb.swp new file mode 100644 index 0000000..efdf44e Binary files /dev/null and b/.records.rb.swp differ diff --git a/.swo b/.swo new file mode 100644 index 0000000..0cf85e9 Binary files /dev/null and b/.swo differ diff --git a/.swp b/.swp new file mode 100644 index 0000000..11791ff Binary files /dev/null and b/.swp differ diff --git a/.types.rb.swp b/.types.rb.swp new file mode 100644 index 0000000..72256d0 Binary files /dev/null and b/.types.rb.swp differ diff --git a/out b/out index 4371b13..c05e6fe 100644 Binary files a/out and b/out differ diff --git a/remove_me b/remove_me new file mode 100644 index 0000000..e69de29 diff --git a/types.rb b/types.rb index 96d5a40..0c2f8bb 100644 --- a/types.rb +++ b/types.rb @@ -1,138 +1,310 @@ #!/usr/bin/env ruby def read_byte(handle) return handle.read(1)[0] end def read_int31(handle) - val = first_byte = read_byte(handle) - if (0x00 .. 0x7f) === first_byte - return first_byte + val = byte = read_byte(handle) + if byte & 0x7f + return byte end - raise "unsupported int" - val <<= (second_byte = read_byte(handle)) - print val.to_s(16) - #when 0x00 .. 0x7F: return first_byte + byte = read_byte(handle) + puts "#{val.to_s(16)} #{byte.to_s(16)}" + + val <<= 8 + val |= (byte = read_byte(handle)) + return val end def read_long(handle) return handle.read(4).unpack('L').first end def read_string(handle) - return handle.read(read_int31(handle)) + len = read_int31(handle) + str = handle.read(len) + return str end -$indent = " " module MSBIN class Record @RECORDS = [] def self.inherited(klass) @RECORDS << klass end def type_of?(type) raise NotImplementedError end def self.MakeRecord(handle) record_type = read_byte(handle) ret = nil @RECORDS.each do |klass| if klass.record_type === record_type - ret = klass.new(handle) + #TODO: move the 2-arg initializer to the base class somehow + ret = klass.new(handle, record_type) end end raise record_type.to_s(16) if not ret + puts "Returning #{ret}" ret end end end module MSBIN class PrefixElement < Record def self.record_type return 0x5e .. 0x77 end - def initialize(handle) + def initialize(handle, record_type) @name = read_string(handle) + @record_type = record_type @attributes = Record.MakeRecord(handle) end + + def to_s + "<#{(?a+@record_type-self.class.record_type.first).chr}:#{@name} #{@attributes}>" + end end class PrefixDictionaryElement < Record attr :children def self.record_type 0x44 .. 0x5D end - def initialize(handle) + def initialize(handle, record_type) @children = [] + @record_type = record_type # read name val = read_int31(handle) @name = "str#{val}" # handle.read(val) - puts "got name #{@name}" + # TODO fill proper string names + #puts "got name #{@name}" # read attributes @children = Record.MakeRecord(handle) end + + def to_s + "<#{(?a+@record_type-self.class.record_type.first).chr}" + end end class PrefixDictionaryAttribute < Record def self.record_type 0x0c .. 0x25 end - def initialize(handle) + def initialize(handle, record_type) val = read_int31(handle) @name = "str#{val}" + @value = Record.MakeRecord(handle) + @record_type = record_type + end + + def to_s + "#{@name}=\"#{@value}\"" + end + end + + class ShortDictionaryXmlnsAttribute < Record + def self.record_type; 0x0a; end + + # TODO Isolate classes that do DictionaryStrings + # TODO: the value will be ' xmlns="@{value}"' + def initialize(handle, record_type) + @value = "str#{read_long(handle)}" + end + + def to_s + " xmlns=\"#{@value}\"" end end class DictionaryXmlnsAttribute < Record def self.record_type 0x0B end - def initialize(handle) + def initialize(handle, record_type) @prefix = read_string(handle) @attributes = "str#{read_int31(handle)}"#Record.MakeRecord(handle) end + + def to_s + " xmlns:#{@prefix}=\"#{@attributes}" + end + end + + class ShortXmlnsAttribute < Record + def self.record_type; 0x08; end + + def initialize(handle, record_type) + @value = read_string(handle) + end + + def to_s + " xmlns=\"#{@value}\"" + end + end + + class XmlnsAttribute < Record + def self.record_type; 0x09; end + + def initialize(handle, record_type) + @prefix = read_string(handle) + @value = read_string(handle) + end + + def to_s + " xmlns:#{@prefix}=\"#{@value}\"" + end end class ShortAttribute < Record def self.record_type; 0x04; end - def initialize(handle) + def initialize(handle, record_type) @name = read_string(handle) @value = Record.MakeRecord(handle) end + + def to_s + " #{@name}=\"#{@vlaue}\"" + end end class ShortElement < Record def self.record_type; 0x40; end - def initialize(handle) + def initialize(handle, record_type) @name = read_string(handle) @attribs = Record.MakeRecord(handle) end + + def to_s + "<#{@name} #{@attributes}>" + end end + # Make this an ADT class TextRecord < Record def self.record_type; 0x00; end end + + # TODO: make this derive from TextRecord class FalseTextWithEndElement < Record def self.record_type; 0x85; end - def initialize(handle) - @text = read_string(handle) + # TODO: Set a to_s to return false, that's it. + def initialize(handle, record_type) + #@text = read_string(handle) + end + end + + class OneText < Record + def self.record_type; 0x82; end + + def initialize(handle, record_type) + @text = "1" + end + end + + class OneTextWithEndElement < Record + def self.record_type; 0x83; end + + def initialize(handle, record_type) + @text = "1" + end + end + + # TODO: Parse this better + class DateTimeTextWithEndElement < Record + def self.record_type; 0x97; end + + def initialize(handle, record_type) + @date_date = handle.read(8) + end + end + + class Chars8Text < Record + def self.record_type; 0x98; end + + def initialize(handle, record_type) + @length = handle.read(1)[0] + @text = handle.read(@length) + end + end + + # TODO: Clean up the end element + class Chars8TextWithEndElement < Record + def self.record_type; 0x99; end + + def initialize(handle, record_type) + @length = handle.read(1)[0] + @text = handle.read(@length) + end + end + + class UniqueIdText < Record + def self.record_type; 0xac; end + + def initialize(handle, record_type) + @text = handle.read(16).unpack('H*') + puts "Got UUID: #{@text}" + end + end + + # TODO: Separate this + class UniqueIdText < Record + def self.record_type; 0xad; end + + def initialize(handle, record_type) + @text = handle.read(16).unpack('H*') + puts "Got UUID: #{@text}" + end + end + + class EndElement < Record + def self.record_type; 0x01; end + + def initialize(handle, record_type) + end + end + + class TrueTextWithEndElement < Record + def self.record_type; 0x87; end + + #TODO: return true as value + def initialize(handle, record_type) + @value = "true" + end + end + + class Int8Text < Record + def self.record_type; 0x88; end + + def initialize(handle, record_type) + @value = handle.read(1) + end + end + + class Int8TextWithEndElement < Record + def self.record_type; 0x89; end + + def initialize(handle, record_type) + @value = handle.read(1) end end end
yan/msbin
87d8383a836d33be0a78d6424f9f77d7aa0fd157
more work
diff --git a/main.rb b/main.rb index d439752..b217570 100755 --- a/main.rb +++ b/main.rb @@ -1,34 +1,37 @@ #!/usr/bin/env ruby +require 'records' +require 'types' if ARGV.size == 0 $stderr.write("Usage: #{$0} file.msbin\n") exit 1 end -def read_byte(handle) - return handle.read(1)[0] -end - -def read_long(handle) - return handle.read(4).unpack('L') -end - -def read_string(handle) - return handle.read(read_long(handle)) -end - -def read_record(handle) - record_type = read_byte(handle) - print "record type: #{record_type}" -end +# def read_byte(handle) +# return handle.read(1)[0] +# end +# +# def read_long(handle) +# return handle.read(4).unpack('L') +# end +# +# def read_string(handle) +# return handle.read(read_long(handle)) +# end +# +# def read_record(handle) +# record_type = read_byte(handle) +# +# print "record type: #{Records[record_type]}" +# end def read_msbin(handle) while !handle.eof() - read_record(handle) + MSBIN::Record.MakeRecord(handle) end end f = File.new(ARGV[0], "rb") read_msbin(f) -puts f +#puts f diff --git a/records.rb b/records.rb index d9fb2a7..86a22c6 100644 --- a/records.rb +++ b/records.rb @@ -1,256 +1,258 @@ -0x00 => "Reserved" -0x01 => "EndElement" -0x02 => "Comment" -0x03 => "Array" -0x04 => "ShortAttribute" -0x05 => "Attribute" -0x06 => "ShortDictionaryAttribute" -0x07 => "DictionaryAttribute" -0x08 => "ShortXmlnsAttribute" -0x09 => "XmlnsAttribute" -0x0A => "ShortDictionaryXmlnsAttribute" -0x0B => "DictionaryXmlnsAttribute" -0x0C => "PrefixDictionaryAttributeA" -0x0D => "PrefixDictionaryAttributeB" -0x0E => "PrefixDictionaryAttributeC" -0x0F => "PrefixDictionaryAttributeD" -0x10 => "PrefixDictionaryAttributeE" -0x11 => "PrefixDictionaryAttributeF" -0x12 => "PrefixDictionaryAttributeG" -0x13 => "PrefixDictionaryAttributeH" -0x14 => "PrefixDictionaryAttributeI" -0x15 => "PrefixDictionaryAttributeJ" -0x16 => "PrefixDictionaryAttributeK" -0x17 => "PrefixDictionaryAttributeL" -0x18 => "PrefixDictionaryAttributeM" -0x19 => "PrefixDictionaryAttributeN" -0x1A => "PrefixDictionaryAttributeO" -0x1B => "PrefixDictionaryAttributeP" -0x1C => "PrefixDictionaryAttributeQ" -0x1D => "PrefixDictionaryAttributeR" -0x1E => "PrefixDictionaryAttributeS" -0x1F => "PrefixDictionaryAttributeT" -0x20 => "PrefixDictionaryAttributeU" -0x21 => "PrefixDictionaryAttributeV" -0x22 => "PrefixDictionaryAttributeW" -0x23 => "PrefixDictionaryAttributeX" -0x24 => "PrefixDictionaryAttributeY" -0x25 => "PrefixDictionaryAttributeZ" -0x26 => "PrefixAttributeA" -0x27 => "PrefixAttributeB" -0x28 => "PrefixAttributeC" -0x29 => "PrefixAttributeD" -0x2A => "PrefixAttributeE" -0x2B => "PrefixAttributeF" -0x2C => "PrefixAttributeG" -0x2D => "PrefixAttributeH" -0x2E => "PrefixAttributeI" -0x2F => "PrefixAttributeJ" -0x30 => "PrefixAttributeK" -0x31 => "PrefixAttributeL" -0x32 => "PrefixAttributeM" -0x33 => "PrefixAttributeN" -0x34 => "PrefixAttributeO" -0x35 => "PrefixAttributeP" -0x36 => "PrefixAttributeQ" -0x37 => "PrefixAttributeR" -0x38 => "PrefixAttributeS" -0x39 => "PrefixAttributeT" -0x3A => "PrefixAttributeU" -0x3B => "PrefixAttributeV" -0x3C => "PrefixAttributeW" -0x3D => "PrefixAttributeX" -0x3E => "PrefixAttributeY" -0x3F => "PrefixAttributeZ" -0x40 => "ShortElement" -0x41 => "Element" -0x42 => "ShortDictionaryElement" -0x43 => "DictionaryElement" -0x44 => "PrefixDictionaryElementA" -0x45 => "PrefixDictionaryElementB" -0x46 => "PrefixDictionaryElementC" -0x47 => "PrefixDictionaryElementD" -0x48 => "PrefixDictionaryElementE" -0x49 => "PrefixDictionaryElementF" -0x4A => "PrefixDictionaryElementG" -0x4B => "PrefixDictionaryElementH" -0x4C => "PrefixDictionaryElementI" -0x4D => "PrefixDictionaryElementJ" -0x4E => "PrefixDictionaryElementK" -0x4F => "PrefixDictionaryElementL" -0x50 => "PrefixDictionaryElementM" -0x51 => "PrefixDictionaryElementN" -0x52 => "PrefixDictionaryElementO" -0x53 => "PrefixDictionaryElementP" -0x54 => "PrefixDictionaryElementQ" -0x55 => "PrefixDictionaryElementR" -0x56 => "PrefixDictionaryElementS" -0x57 => "PrefixDictionaryElementT" -0x58 => "PrefixDictionaryElementU" -0x59 => "PrefixDictionaryElementV" -0x5A => "PrefixDictionaryElementW" -0x5B => "PrefixDictionaryElementX" -0x5C => "PrefixDictionaryElementY" -0x5D => "PrefixDictionaryElementZ" -0x5E => "PrefixElementA" -0x5F => "PrefixElementB" -0x60 => "PrefixElementC" -0x61 => "PrefixElementD" -0x62 => "PrefixElementE" -0x63 => "PrefixElementF" -0x64 => "PrefixElementG" -0x65 => "PrefixElementH" -0x66 => "PrefixElementI" -0x67 => "PrefixElementJ" -0x68 => "PrefixElementK" -0x69 => "PrefixElementL" -0x6A => "PrefixElementM" -0x6B => "PrefixElementN" -0x6C => "PrefixElementO" -0x6D => "PrefixElementP" -0x6E => "PrefixElementQ" -0x6F => "PrefixElementR" -0x70 => "PrefixElementS" -0x71 => "PrefixElementT" -0x72 => "PrefixElementU" -0x73 => "PrefixElementV" -0x74 => "PrefixElementW" -0x75 => "PrefixElementX" -0x76 => "PrefixElementY" -0x77 => "PrefixElementZ" -0x78 => "Reserved" -0x79 => "Reserved" -0x7A => "Reserved" -0x7B => "Reserved" -0x7C => "Reserved" -0x7D => "Reserved" -0x7E => "Reserved" -0x7F => "Reserved" -0x80 => "ZeroText" -0x81 => "ZeroTextWithEndElement" -0x82 => "OneText" -0x83 => "OneTextWithEndElement" -0x84 => "FalseText" -0x85 => "FalseTextWithEndElement" -0x86 => "TrueText" -0x87 => "TrueTextWithEndElement" -0x88 => "Int8Text" -0x89 => "Int8TextWithEndElement" -0x8A => "Int16Text" -0x8B => "Int16TextWithEndElement" -0x8C => "Int32Text" -0x8D => "Int32TextWithEndElement" -0x8E => "Int64Text" -0x8F => "Int64TextWithEndElement" -0x90 => "FloatText" -0x91 => "FloatTextWithEndElement" -0x92 => "DoubleText" -0x93 => "DoubleTextWithEndElement" -0x94 => "DecimalText" -0x95 => "DecimalTextWithEndElement" -0x96 => "DateTimeText" -0x97 => "DateTimeTextWithEndElement" -0x98 => "Chars8Text" -0x99 => "Chars8TextWithEndElement" -0x9A => "Chars16Text" -0x9B => "Chars16TextWithEndElement" -0x9C => "Chars32Text" -0x9D => "Chars32TextWithEndElement" -0x9E => "Bytes8Text" -0x9F => "Bytes8TextWithEndElement" -0xA0 => "Bytes16Text" -0xA1 => "Bytes16TextWithEndElement" -0xA2 => "Bytes32Text" -0xA3 => "Bytes32TextWithEndElement" -0xA4 => "StartListText" -0xA5 => "Reserved" -0xA6 => "EndListText" -0xA7 => "Reserved" -0xA8 => "EmptyText" -0xA9 => "EmptyTextWithEndElement" -0xAA => "DictionaryText" -0xAB => "DictionaryTextWithEndElement" -0xAC => "UniqueIdText" -0xAD => "UniqueIdTextWithEndElement" -0xAE => "TimeSpanText" -0xAF => "TimeSpanTextWithEndElement" -0xB0 => "UuidText" -0xB1 => "UuidTextWithEndElement" -0xB2 => "UInt64Text" -0xB3 => "UInt64TextWithEndElement" -0xB4 => "BoolText" -0xB5 => "BoolTextWithEndElement" -0xB6 => "UnicodeChars8Text" -0xB7 => "UnicodeChars8TextWithEndElement" -0xB8 => "UnicodeChars16Text" -0xB9 => "UnicodeChars16TextWithEndElement" -0xBA => "UnicodeChars32Text" -0xBB => "UnicodeChars32TextWithEndElement" -0xBC => "QNameDictionaryText" -0xBD => "QNameDictionaryTextWithEndElement" -0xBE => "Reserved" -0xBF => "Reserved" -0xC0 => "Reserved" -0xC1 => "Reserved" -0xC2 => "Reserved" -0xC3 => "Reserved" -0xC4 => "Reserved" -0xC5 => "Reserved" -0xC6 => "Reserved" -0xC7 => "Reserved" -0xC8 => "Reserved" -0xC9 => "Reserved" -0xCA => "Reserved" -0xCB => "Reserved" -0xCC => "Reserved" -0xCD => "Reserved" -0xCE => "Reserved" -0xCF => "Reserved" -0xD0 => "Reserved" -0xD1 => "Reserved" -0xD2 => "Reserved" -0xD3 => "Reserved" -0xD4 => "Reserved" -0xD5 => "Reserved" -0xD6 => "Reserved" -0xD7 => "Reserved" -0xD8 => "Reserved" -0xD9 => "Reserved" -0xDA => "Reserved" -0xDB => "Reserved" -0xDC => "Reserved" -0xDD => "Reserved" -0xDE => "Reserved" -0xDF => "Reserved" -0xE0 => "Reserved" -0xE1 => "Reserved" -0xE2 => "Reserved" -0xE3 => "Reserved" -0xE4 => "Reserved" -0xE5 => "Reserved" -0xE6 => "Reserved" -0xE7 => "Reserved" -0xE8 => "Reserved" -0xE9 => "Reserved" -0xEA => "Reserved" -0xEB => "Reserved" -0xEC => "Reserved" -0xED => "Reserved" -0xEE => "Reserved" -0xEF => "Reserved" -0xF0 => "Reserved" -0xF1 => "Reserved" -0xF2 => "Reserved" -0xF3 => "Reserved" -0xF4 => "Reserved" -0xF5 => "Reserved" -0xF6 => "Reserved" -0xF7 => "Reserved" -0xF8 => "Reserved" -0xF9 => "Reserved" -0xFA => "Reserved" -0xFB => "Reserved" -0xFC => "Reserved" -0xFD => "Reserved" -0xFE => "Reserved" +Records = { +0x00 => "Reserved", +0x01 => "EndElement", +0x02 => "Comment", +0x03 => "Array", +0x04 => "ShortAttribute", +0x05 => "Attribute", +0x06 => "ShortDictionaryAttribute", +0x07 => "DictionaryAttribute", +0x08 => "ShortXmlnsAttribute", +0x09 => "XmlnsAttribute", +0x0A => "ShortDictionaryXmlnsAttribute", +0x0B => "DictionaryXmlnsAttribute", +0x0C => "PrefixDictionaryAttributeA", +0x0D => "PrefixDictionaryAttributeB", +0x0E => "PrefixDictionaryAttributeC", +0x0F => "PrefixDictionaryAttributeD", +0x10 => "PrefixDictionaryAttributeE", +0x11 => "PrefixDictionaryAttributeF", +0x12 => "PrefixDictionaryAttributeG", +0x13 => "PrefixDictionaryAttributeH", +0x14 => "PrefixDictionaryAttributeI", +0x15 => "PrefixDictionaryAttributeJ", +0x16 => "PrefixDictionaryAttributeK", +0x17 => "PrefixDictionaryAttributeL", +0x18 => "PrefixDictionaryAttributeM", +0x19 => "PrefixDictionaryAttributeN", +0x1A => "PrefixDictionaryAttributeO", +0x1B => "PrefixDictionaryAttributeP", +0x1C => "PrefixDictionaryAttributeQ", +0x1D => "PrefixDictionaryAttributeR", +0x1E => "PrefixDictionaryAttributeS", +0x1F => "PrefixDictionaryAttributeT", +0x20 => "PrefixDictionaryAttributeU", +0x21 => "PrefixDictionaryAttributeV", +0x22 => "PrefixDictionaryAttributeW", +0x23 => "PrefixDictionaryAttributeX", +0x24 => "PrefixDictionaryAttributeY", +0x25 => "PrefixDictionaryAttributeZ", +0x26 => "PrefixAttributeA", +0x27 => "PrefixAttributeB", +0x28 => "PrefixAttributeC", +0x29 => "PrefixAttributeD", +0x2A => "PrefixAttributeE", +0x2B => "PrefixAttributeF", +0x2C => "PrefixAttributeG", +0x2D => "PrefixAttributeH", +0x2E => "PrefixAttributeI", +0x2F => "PrefixAttributeJ", +0x30 => "PrefixAttributeK", +0x31 => "PrefixAttributeL", +0x32 => "PrefixAttributeM", +0x33 => "PrefixAttributeN", +0x34 => "PrefixAttributeO", +0x35 => "PrefixAttributeP", +0x36 => "PrefixAttributeQ", +0x37 => "PrefixAttributeR", +0x38 => "PrefixAttributeS", +0x39 => "PrefixAttributeT", +0x3A => "PrefixAttributeU", +0x3B => "PrefixAttributeV", +0x3C => "PrefixAttributeW", +0x3D => "PrefixAttributeX", +0x3E => "PrefixAttributeY", +0x3F => "PrefixAttributeZ", +0x40 => "ShortElement", +0x41 => "Element", +0x42 => "ShortDictionaryElement", +0x43 => "DictionaryElement", +0x44 => "PrefixDictionaryElementA", +0x45 => "PrefixDictionaryElementB", +0x46 => "PrefixDictionaryElementC", +0x47 => "PrefixDictionaryElementD", +0x48 => "PrefixDictionaryElementE", +0x49 => "PrefixDictionaryElementF", +0x4A => "PrefixDictionaryElementG", +0x4B => "PrefixDictionaryElementH", +0x4C => "PrefixDictionaryElementI", +0x4D => "PrefixDictionaryElementJ", +0x4E => "PrefixDictionaryElementK", +0x4F => "PrefixDictionaryElementL", +0x50 => "PrefixDictionaryElementM", +0x51 => "PrefixDictionaryElementN", +0x52 => "PrefixDictionaryElementO", +0x53 => "PrefixDictionaryElementP", +0x54 => "PrefixDictionaryElementQ", +0x55 => "PrefixDictionaryElementR", +0x56 => "PrefixDictionaryElementS", +0x57 => "PrefixDictionaryElementT", +0x58 => "PrefixDictionaryElementU", +0x59 => "PrefixDictionaryElementV", +0x5A => "PrefixDictionaryElementW", +0x5B => "PrefixDictionaryElementX", +0x5C => "PrefixDictionaryElementY", +0x5D => "PrefixDictionaryElementZ", +0x5E => "PrefixElementA", +0x5F => "PrefixElementB", +0x60 => "PrefixElementC", +0x61 => "PrefixElementD", +0x62 => "PrefixElementE", +0x63 => "PrefixElementF", +0x64 => "PrefixElementG", +0x65 => "PrefixElementH", +0x66 => "PrefixElementI", +0x67 => "PrefixElementJ", +0x68 => "PrefixElementK", +0x69 => "PrefixElementL", +0x6A => "PrefixElementM", +0x6B => "PrefixElementN", +0x6C => "PrefixElementO", +0x6D => "PrefixElementP", +0x6E => "PrefixElementQ", +0x6F => "PrefixElementR", +0x70 => "PrefixElementS", +0x71 => "PrefixElementT", +0x72 => "PrefixElementU", +0x73 => "PrefixElementV", +0x74 => "PrefixElementW", +0x75 => "PrefixElementX", +0x76 => "PrefixElementY", +0x77 => "PrefixElementZ", +0x78 => "Reserved", +0x79 => "Reserved", +0x7A => "Reserved", +0x7B => "Reserved", +0x7C => "Reserved", +0x7D => "Reserved", +0x7E => "Reserved", +0x7F => "Reserved", +0x80 => "ZeroText", +0x81 => "ZeroTextWithEndElement", +0x82 => "OneText", +0x83 => "OneTextWithEndElement", +0x84 => "FalseText", +0x85 => "FalseTextWithEndElement", +0x86 => "TrueText", +0x87 => "TrueTextWithEndElement", +0x88 => "Int8Text", +0x89 => "Int8TextWithEndElement", +0x8A => "Int16Text", +0x8B => "Int16TextWithEndElement", +0x8C => "Int32Text", +0x8D => "Int32TextWithEndElement", +0x8E => "Int64Text", +0x8F => "Int64TextWithEndElement", +0x90 => "FloatText", +0x91 => "FloatTextWithEndElement", +0x92 => "DoubleText", +0x93 => "DoubleTextWithEndElement", +0x94 => "DecimalText", +0x95 => "DecimalTextWithEndElement", +0x96 => "DateTimeText", +0x97 => "DateTimeTextWithEndElement", +0x98 => "Chars8Text", +0x99 => "Chars8TextWithEndElement", +0x9A => "Chars16Text", +0x9B => "Chars16TextWithEndElement", +0x9C => "Chars32Text", +0x9D => "Chars32TextWithEndElement", +0x9E => "Bytes8Text", +0x9F => "Bytes8TextWithEndElement", +0xA0 => "Bytes16Text", +0xA1 => "Bytes16TextWithEndElement", +0xA2 => "Bytes32Text", +0xA3 => "Bytes32TextWithEndElement", +0xA4 => "StartListText", +0xA5 => "Reserved", +0xA6 => "EndListText", +0xA7 => "Reserved", +0xA8 => "EmptyText", +0xA9 => "EmptyTextWithEndElement", +0xAA => "DictionaryText", +0xAB => "DictionaryTextWithEndElement", +0xAC => "UniqueIdText", +0xAD => "UniqueIdTextWithEndElement", +0xAE => "TimeSpanText", +0xAF => "TimeSpanTextWithEndElement", +0xB0 => "UuidText", +0xB1 => "UuidTextWithEndElement", +0xB2 => "UInt64Text", +0xB3 => "UInt64TextWithEndElement", +0xB4 => "BoolText", +0xB5 => "BoolTextWithEndElement", +0xB6 => "UnicodeChars8Text", +0xB7 => "UnicodeChars8TextWithEndElement", +0xB8 => "UnicodeChars16Text", +0xB9 => "UnicodeChars16TextWithEndElement", +0xBA => "UnicodeChars32Text", +0xBB => "UnicodeChars32TextWithEndElement", +0xBC => "QNameDictionaryText", +0xBD => "QNameDictionaryTextWithEndElement", +0xBE => "Reserved", +0xBF => "Reserved", +0xC0 => "Reserved", +0xC1 => "Reserved", +0xC2 => "Reserved", +0xC3 => "Reserved", +0xC4 => "Reserved", +0xC5 => "Reserved", +0xC6 => "Reserved", +0xC7 => "Reserved", +0xC8 => "Reserved", +0xC9 => "Reserved", +0xCA => "Reserved", +0xCB => "Reserved", +0xCC => "Reserved", +0xCD => "Reserved", +0xCE => "Reserved", +0xCF => "Reserved", +0xD0 => "Reserved", +0xD1 => "Reserved", +0xD2 => "Reserved", +0xD3 => "Reserved", +0xD4 => "Reserved", +0xD5 => "Reserved", +0xD6 => "Reserved", +0xD7 => "Reserved", +0xD8 => "Reserved", +0xD9 => "Reserved", +0xDA => "Reserved", +0xDB => "Reserved", +0xDC => "Reserved", +0xDD => "Reserved", +0xDE => "Reserved", +0xDF => "Reserved", +0xE0 => "Reserved", +0xE1 => "Reserved", +0xE2 => "Reserved", +0xE3 => "Reserved", +0xE4 => "Reserved", +0xE5 => "Reserved", +0xE6 => "Reserved", +0xE7 => "Reserved", +0xE8 => "Reserved", +0xE9 => "Reserved", +0xEA => "Reserved", +0xEB => "Reserved", +0xEC => "Reserved", +0xED => "Reserved", +0xEE => "Reserved", +0xEF => "Reserved", +0xF0 => "Reserved", +0xF1 => "Reserved", +0xF2 => "Reserved", +0xF3 => "Reserved", +0xF4 => "Reserved", +0xF5 => "Reserved", +0xF6 => "Reserved", +0xF7 => "Reserved", +0xF8 => "Reserved", +0xF9 => "Reserved", +0xFA => "Reserved", +0xFB => "Reserved", +0xFC => "Reserved", +0xFD => "Reserved", +0xFE => "Reserved", 0xFF => "Reserved" +} diff --git a/types.rb b/types.rb new file mode 100644 index 0000000..96d5a40 --- /dev/null +++ b/types.rb @@ -0,0 +1,138 @@ +#!/usr/bin/env ruby + + +def read_byte(handle) + return handle.read(1)[0] +end + +def read_int31(handle) + val = first_byte = read_byte(handle) + if (0x00 .. 0x7f) === first_byte + return first_byte + end + + raise "unsupported int" + val <<= (second_byte = read_byte(handle)) + print val.to_s(16) + #when 0x00 .. 0x7F: return first_byte +end + +def read_long(handle) + return handle.read(4).unpack('L').first +end + +def read_string(handle) + return handle.read(read_int31(handle)) +end + +$indent = " " +module MSBIN + class Record + @RECORDS = [] + + def self.inherited(klass) + @RECORDS << klass + end + + def type_of?(type) + raise NotImplementedError + end + + def self.MakeRecord(handle) + record_type = read_byte(handle) + ret = nil + @RECORDS.each do |klass| + if klass.record_type === record_type + ret = klass.new(handle) + end + end + raise record_type.to_s(16) if not ret + ret + end + end +end + +module MSBIN + class PrefixElement < Record + def self.record_type + return 0x5e .. 0x77 + end + + def initialize(handle) + @name = read_string(handle) + @attributes = Record.MakeRecord(handle) + end + end + + class PrefixDictionaryElement < Record + attr :children + + def self.record_type + 0x44 .. 0x5D + end + + def initialize(handle) + @children = [] + + # read name + val = read_int31(handle) + @name = "str#{val}" # handle.read(val) + puts "got name #{@name}" + + # read attributes + @children = Record.MakeRecord(handle) + end + end + + class PrefixDictionaryAttribute < Record + def self.record_type + 0x0c .. 0x25 + end + + def initialize(handle) + val = read_int31(handle) + @name = "str#{val}" + end + end + + class DictionaryXmlnsAttribute < Record + def self.record_type + 0x0B + end + + def initialize(handle) + @prefix = read_string(handle) + @attributes = "str#{read_int31(handle)}"#Record.MakeRecord(handle) + end + end + + class ShortAttribute < Record + def self.record_type; 0x04; end + + def initialize(handle) + @name = read_string(handle) + @value = Record.MakeRecord(handle) + end + end + + class ShortElement < Record + def self.record_type; 0x40; end + + def initialize(handle) + @name = read_string(handle) + @attribs = Record.MakeRecord(handle) + end + end + + class TextRecord < Record + def self.record_type; 0x00; end + end + + class FalseTextWithEndElement < Record + def self.record_type; 0x85; end + + def initialize(handle) + @text = read_string(handle) + end + end +end
benjamw/pharaoh
e4c0da28c606236a8efacc5785f8a27853ddc086
allow clicks on finished games
diff --git a/scripts/index.js b/scripts/index.js index 4d330d0..e86b0a1 100644 --- a/scripts/index.js +++ b/scripts/index.js @@ -1,133 +1,133 @@ // index javascript var reload = true; // do not change this var refresh_timer = false; var refresh_timeout = 30001; // 30 seconds $(document).ready( function( ) { // make the table row clicks work - $('.datatable tbody tr:not(tr.lowlight)').css('cursor', 'pointer').click( function( ) { + $('.datatable tbody tr').css('cursor', 'pointer').click( function( ) { var id = $(this).attr('id').substr(1); var state = $($(this).children( )[2]).text( ); //* -- SWITCH -- if (state == 'Waiting') { window.location = 'join.php?id='+id+debug_query_; } else { window.location = 'game.php?id='+id+debug_query_; } //*/ }); // blinky menu items $('.blink').fadeOut( ).fadeIn( ).fadeOut( ).fadeIn( ).fadeOut( ).fadeIn( ); // chat box functions $('#chatbox form').submit( function( ) { if ('' == $.trim($('#chatbox input#chat').val( ))) { return false; } if (debug) { window.location = 'ajax_helper.php'+debug_query+'&'+$('#chatbox form').serialize( ); return false; } $.ajax({ type: 'POST', url: 'ajax_helper.php', data: $('#chatbox form').serialize( ), success: function(msg) { var reply = JSON.parse(msg); if (reply.error) { alert(reply.error); } else { var entry = '<dt>'+reply.username+'</dt>'+ '<dd>'+reply.message+'</dd>'; $('#chats').prepend(entry); $('#chatbox input#chat').val(''); } } }); return false; }); // run the sounds if (('#refresh' == document.location.hash) && turn_msg_count) { $('#sounds').jPlayer({ ready: function ( ) { $(this).jPlayer('setMedia', { mp3: 'sounds/message.mp3', oga: 'sounds/message.ogg' }).jPlayer('play'); }, volume: 1, swfPath: 'scripts' }); } // run the ajax refresher ajax_refresh( ); // set some things that will halt the timer $('#chatbox form input').focus( function( ) { clearTimeout(refresh_timer); }); $('#chatbox form input').blur( function( ) { if ('' != $(this).val( )) { refresh_timer = setTimeout('ajax_refresh( )', refresh_timeout); } }); }); var jqXHR = false; function ajax_refresh( ) { // no debug redirect, just do it // only run this if the previous ajax call has completed if (false == jqXHR) { jqXHR = $.ajax({ type: 'POST', url: 'ajax_helper.php', data: 'timer=1', success: function(msg) { if (('' != msg) && (msg != turn_msg_count)) { // we don't want to play sounds when they hit the page manually // so set a hash on the URL that we can test when we embed the sounds // we don't care what the hash is, just refresh if there is a hash // (the user may have silenced the sounds with #silent) if ('' != window.location.hash) { if (reload) { window.location.reload( ); } } else { // stick the hash on the end of the URL window.location = window.location.href+'#refresh' if (reload) { window.location.reload( ); } } } } }).always( function( ) { jqXHR = false; }); } // successively increase the timeout time in case someone // leaves their window open, don't poll the server every // 30 seconds for the rest of time if (0 == (refresh_timeout % 5)) { refresh_timeout += Math.floor(refresh_timeout * 0.001) * 1000; } ++refresh_timeout; refresh_timer = setTimeout('ajax_refresh( )', refresh_timeout); }
benjamw/pharaoh
28f9d1554479dc2255ba584800f384097fc754fe
recompiled css
diff --git a/css/game.css b/css/game.css index 06f1621..7fe974b 100644 --- a/css/game.css +++ b/css/game.css @@ -1 +1 @@ -.msg,.sunk,.finished{color:#FFF;font-weight:bold;font-size:16px;line-height:24px;background:#C00;padding:4px;text-align:center;margin-bottom:1ex}.won{background:#093}.lost{background:#C00}div.board,div.noboard{float:left;margin:10px}div.noboard{width:354px;height:354px;border:2px solid black;font-size:28px;vertical-align:middle;text-align:center;background-color:#DEF;color:#333;line-height:335px}* html div.noboard{width:358px;height:358px}div#board_data:after{content:'.';display:block;height:0;clear:both;visibility:hidden}* html div#board_data{zoom:1}div.board_info{float:left;margin:0 10px;width:356px;text-align:right}div.board_info span{float:right;display:block;line-height:16px}div.board_info .fleet{float:left;font-size:16px;font-weight:bold}div.boats{text-align:left;width:200px;height:354px;float:left;margin:10px}div.boats div.boat{width:180px;height:35px;float:left;clear:right}div.board div,div.boat div{float:left;width:30px;height:30px;border:1px solid #005;background-color:#79F;font-weight:bold;color:#000}div.board div.row{float:none;clear:both;width:auto;height:32px;border:2px solid #000;border-width:0 2px 0;background-color:transparent;font-weight:normal;overflow:visible}div.board div.row.top,div.board div.row.bottom{height:17px;border:2px solid #000;border-width:2px 2px 0}div.board div.row.bottom{border:2px solid #000;border-width:0 2px 2px}div.board div.top div,div.board div.bottom div{height:15px;line-height:15px;border:1px solid #DDD;background-color:#EFF4FF;text-align:center}div.board div.top div.corner,div.board div.bottom div.corner{width:15px;height:15px;border:1px solid #DDD;background-color:#EFF4FF}div.board div.side{width:15px;line-height:30px;border:1px solid #DDD;background-color:#EFF4FF;text-align:center}div.v-bow{background-image:url("../images/v_bow.gif")}div.v-fore{background-image:url("../images/v_fore.gif")}div.v-mid{background-image:url("../images/v_mid.gif")}div.v-aft{background-image:url("../images/v_aft.gif")}div.v-stern{background-image:url("../images/v_stern.gif")}div.h-bow{background-image:url("../images/h_bow.gif")}div.h-fore{background-image:url("../images/h_fore.gif")}div.h-mid{background-image:url("../images/h_mid.gif")}div.h-aft{background-image:url("../images/h_aft.gif")}div.h-stern{background-image:url("../images/h_stern.gif")}div.board div.prevshot{border:2px solid yellow;margin:-1px;position:relative;z-index:2}div.board div.curshot{border:2px solid white;margin:-1px;position:relative;z-index:4}.clr{clear:both}#game div{clear:both;text-align:center}.shots{text-align:center;width:200px;margin:5px auto -20px;font-size:14px;font-weight:bold;color:#C00}.shots img{width:15px;height:15px;border:0;vertical-align:middle}h2 span{margin:0 3em}#chats{height:auto}#chats .bla{color:#DDD;background-color:#333}#chats .whi{color:#333;background-color:#DDD}#chats .blu{color:#00D;background-color:#333}#chats .private{background-color:#BBF;color:#000}#contents{margin:10px}#chatbox{margin-left:732px}#chats{height:450px}#game_page #chatbox input[type=text]{width:80%}#game_page #chatbox dd{padding-left:1em}#board_wrapper{float:left;width:550px;margin-left:5px}#board{width:550px;height:450px}#history{float:left;width:170px}#history table{margin:0}#history table td{padding:0 5px;font-size:1.1em;line-height:130%}#history table td.active,#history table td:hover{font-weight:bold;background-color:#444;color:#FFF}#history table td.turn{width:1%;text-align:right}#history div div{margin-bottom:2px;text-align:center}#history div div span{padding:2px 5px 1px;border:1px solid #555;-moz-border-radius:3px;-webkit-border-radius:3px;border-radius:3px;cursor:pointer}#history div div span:hover{border-color:#AAA}#history div div span.disabled{color:#AAA;border-color:#333;cursor:default}form#game{clear:both;text-align:center;padding-top:20px}#setup{display:none} +.a_board{background-color:#1F2023;color:#CCC;width:550px;height:450px}.a_board .header{text-align:center;font-weight:bold;font-size:16px}.a_board div{border:1px solid #000;float:left;clear:none;width:44px;height:44px;margin:1px;padding:1px;position:relative;overflow:hidden}.a_board .vert{border:0;margin:0;padding:0;width:25px;height:50px;line-height:50px}.a_board .horz{border:0;margin:0;padding:0;width:50px;height:25px;line-height:25px}.a_board .corner{border:0;margin:0;padding:0;width:25px;height:25px}.a_board .corner div{border:2px solid #FFF;width:14px;height:14px;margin:4px;padding:0;line-height:10px;-moz-border-radius:14px;-webkit-border-radius:14px;border-radius:14px}.a_board .corner div.alive{border-color:#0C0;background:#090}.a_board .corner div.immune{border-color:#CC0;background:#990;color:#FFF}.a_board .corner div.dead{border-color:#C00;background:#900;color:#FFF}.a_board .c_silver{background-color:#555}.a_board .c_red{background-color:#500}.a_board .highlight{background-color:#550}.a_board .piece{background-position:center center;background-repeat:no-repeat}.a_board div img{position:absolute;top:0;left:0}.a_board div img.piece{position:absolute;top:1px;left:1px}.a_board img.ccw{margin-left:23px}#contents{margin:10px}#chatbox{margin-left:732px}#chats{height:450px}#game_page #chatbox input[type=text]{width:80%}#game_page #chatbox dd{padding-left:1em}#board_wrapper{float:left;width:550px;margin-left:5px}#board{width:550px;height:450px}#history{float:left;width:170px}#history table{margin:0}#history table td{padding:0 5px;font-size:1.1em;line-height:130%}#history table td.active,#history table td:hover{font-weight:bold;background-color:#444;color:#FFF}#history table td.turn{width:1%;text-align:right}#history div div{margin-bottom:2px;text-align:center}#history div div span{padding:2px 5px 1px;border:1px solid #555;-moz-border-radius:3px;-webkit-border-radius:3px;border-radius:3px;cursor:pointer}#history div div span:hover{border-color:#AAA}#history div div span.disabled{color:#AAA;border-color:#333;cursor:default}form#game{clear:both;text-align:center;padding-top:20px}#setup{display:none}
benjamw/pharaoh
30dc07ba503b25301a05ebc545d9a562de259d19
minor changes
diff --git a/.gitignore b/.gitignore index a29f844..f72f8d1 100644 --- a/.gitignore +++ b/.gitignore @@ -1,19 +1,21 @@ /.sass-cache /config /old_css /testpages +/.idea *.epp *.err +*.orig *.log .svn /games/*.pgn /logs/* /includes/config.php /scripts/ba-debug.js !/logs/.htaccess diff --git a/ajax_helper.php b/ajax_helper.php index 264c609..40aa346 100644 --- a/ajax_helper.php +++ b/ajax_helper.php @@ -1,290 +1,290 @@ <?php $GLOBALS['NODEBUG'] = true; $GLOBALS['AJAX'] = true; // don't require log in when testing for used usernames and emails if (isset($_POST['validity_test']) || (isset($_GET['validity_test']) && isset($_GET['DEBUG']))) { define('LOGIN', false); } require_once 'includes/inc.global.php'; // if we are debugging, change some things for us // (although REQUEST_METHOD may not always be valid) -if (('GET' == $_SERVER['REQUEST_METHOD']) && defined('DEBUG') && DEBUG) { +if (('GET' === $_SERVER['REQUEST_METHOD']) && defined('DEBUG') && DEBUG) { $GLOBALS['NODEBUG'] = false; $GLOBALS['AJAX'] = false; $_GET['token'] = $_SESSION['token']; $_GET['keep_token'] = true; $_POST = $_GET; $DEBUG = true; call('AJAX HELPER'); call($_POST); } // run the index page refresh checks if (isset($_POST['timer'])) { $message_count = (int) Message::check_new($_SESSION['player_id']); $turn_count = (int) Game::check_turns($_SESSION['player_id']); echo $message_count + $turn_count; exit; } // run registration checks if (isset($_POST['validity_test'])) { # if (('email' == $_POST['type']) && ('' == $_POST['value'])) { # echo 'OK'; # exit; # } $player_id = 0; if ( ! empty($_POST['profile'])) { $player_id = (int) $_SESSION['player_id']; } switch ($_POST['validity_test']) { case 'username' : case 'email' : $username = ''; $email = ''; ${$_POST['validity_test']} = sani($_POST['value']); $player_id = (isset($_POST['player_id']) ? (int) $_POST['player_id'] : 0); try { Player::check_database($username, $email, $player_id); } catch (MyException $e) { echo $e->getCode( ); exit; } break; default : break; } echo 'OK'; exit; } // run the in game chat if (isset($_POST['chat'])) { try { if ( ! isset($_SESSION['game_id'])) { $_SESSION['game_id'] = 0; } $Chat = new Chat((int) $_SESSION['player_id'], (int) $_SESSION['game_id']); $Chat->send_message($_POST['chat'], isset($_POST['private']), isset($_POST['lobby'])); $return = $Chat->get_box_list(1); $return = $return[0]; } catch (MyException $e) { $return['error'] = 'ERROR: '.$e->outputMessage( ); } echo json_encode($return); exit; } // run setup validation if (isset($_POST['test_setup'])) { try { Setup::is_valid_reflection($_POST['setup'], $_POST['reflection']); $return['valid'] = true; } catch (MyException $e) { $return['error'] = 'ERROR: '.$e->outputMessage( ); } echo json_encode($return); exit; } // run setup laser test fire if (isset($_POST['test_fire'])) { try { // returns laser_path and hits arrays $return = Pharaoh::fire_laser($_POST['color'], $_POST['board']); } catch (MyException $e) { $return['error'] = 'ERROR: '.$e->outputMessage( ); } echo json_encode($return); exit; } // run the invites stuff if (isset($_POST['invite'])) { if ('delete' == $_POST['invite']) { // make sure we are one of the two people in the invite if (Game::has_invite($_POST['game_id'], $_SESSION['player_id'])) { if (Game::delete_invite($_POST['game_id'])) { echo 'Invite Deleted'; } else { echo 'ERROR: Invite not deleted'; } } else { echo 'ERROR: Not your invite'; } } else if ('resend' == $_POST['invite']) { // make sure we are one of the two people in the invite if (Game::has_invite($_POST['game_id'], $_SESSION['player_id'])) { try { if (Game::resend_invite($_POST['game_id'])) { echo 'Invite Resent'; } else { echo 'ERROR: Could not resend invite'; } } catch (MyException $e) { echo 'ERROR: '.$e->outputMessage( ); } } else { echo 'ERROR: Not your invite'; } } else { // make sure we are one of the two people in the invite if (Game::has_invite($_POST['game_id'], $_SESSION['player_id'], $accept = true)) { if ($game_id = Game::accept_invite($_POST['game_id'])) { // single equals intended echo $game_id; } else { echo 'ERROR: Could not create game'; } } else { echo 'ERROR: Not your invite'; } } exit; } // we'll need a game id from here forward, so make sure we have one if (empty($_SESSION['game_id'])) { echo 'ERROR: Game not found'; exit; } // init our game if ( ! isset($Game)) { $Game = new Game((int) $_SESSION['game_id']); } // run the game refresh check if (isset($_POST['refresh'])) { echo $Game->last_move; exit; } // do some validity checking if (empty($DEBUG) && empty($_POST['notoken'])) { test_token( ! empty($_POST['keep_token'])); } if ($_POST['game_id'] != $_SESSION['game_id']) { throw new MyException('ERROR: Incorrect game id given. Was #'.$_POST['game_id'].', should be #'.$_SESSION['game_id'].'.'); } // make sure we are the player we say we are // unless we're an admin, then it's ok $player_id = (int) $_POST['player_id']; if (($player_id != $_SESSION['player_id']) && ! $GLOBALS['Player']->is_admin) { throw new MyException('ERROR: Incorrect player id given'); } // run the simple button actions $actions = array( 'nudge', 'resign', 'offer_draw', 'accept_draw', 'reject_draw', 'request_undo', 'accept_undo', 'reject_undo', ); foreach ($actions as $action) { if (isset($_POST[$action])) { try { $Game->{$action}($player_id); echo 'OK'; } catch (MyException $e) { echo $e; } exit; } } // run the game actions if (isset($_POST['turn'])) { $return = array( ); try { if (false !== strpos($_POST['to'], 'split')) { // splitting obelisk $to = substr($_POST['to'], 0, 2); call($to); $from = Pharaoh::index_to_target($_POST['from']); $to = Pharaoh::index_to_target($to); call($from.'.'.$to); $Game->do_move($from.'.'.$to); } elseif ((string) $_POST['to'] === (string) (int) $_POST['to']) { // moving $to = $_POST['to']; call($to); $from = Pharaoh::index_to_target($_POST['from']); $to = Pharaoh::index_to_target($to); call($from.':'.$to); $Game->do_move($from.':'.$to); } else { // rotating $target = Pharaoh::index_to_target($_POST['from']); $dir = (int) ('r' == strtolower($_POST['to'])); call($target.'-'.$dir); $Game->do_move($target.'-'.$dir); } $return['action'] = 'RELOAD'; } catch (MyException $e) { $return['error'] = 'ERROR: '.$e->outputMessage( ); } echo json_encode($return); exit; }
benjamw/pharaoh
00965bb233ae253be32e8c1cb82711593af12789
change debug seettings
diff --git a/includes/func.global.php b/includes/func.global.php index bbb2ceb..0e86e8b 100644 --- a/includes/func.global.php +++ b/includes/func.global.php @@ -1,353 +1,354 @@ <?php /** function call [dump] [debug] * This function is for debugging only * Outputs given var to screen * or, if no var given, outputs stars to note position * * @param mixed optional var to output * @param bool optional bypass debug value and output anyway * @action outputs var to screen * @return void */ +if ( ! function_exists('call')) { function call($var = 'Th&F=xUFucreSp2*ezAhe=ApuPR*$axe', $bypass = false, $show_from = true, $new_window = false, $error = false) { if ((( ! defined('DEBUG') || ! DEBUG) || ! empty($GLOBALS['NODEBUG'])) && ! (bool) $bypass) { return false; } if ('Th&F=xUFucreSp2*ezAhe=ApuPR*$axe' === $var) { $contents = '<span style="font-size:larger;font-weight:bold;color:red;">--==((OO88OO))==--</span>'; } else { // begin output buffering so we can escape any html // and print_r is better at catching recursion than var_export ob_start( ); if ((is_string($var) && ! preg_match('/^\\s*$/', $var))) { // non-whitespace strings print_r($var); } else { if ( ! function_exists('xdebug_disable')) { if (is_array($var) || is_object($var)) { print_r($var); } else { var_dump($var); } } else { var_dump($var); } } // end output buffering and output the result if ( ! function_exists('xdebug_disable')) { $contents = htmlentities(ob_get_contents( )); } else { $contents = ob_get_contents( ); } ob_end_clean( ); } $j = 0; $html = ''; $debug_funcs = array('dump', 'debug'); if ((bool) $show_from) { $called_from = debug_backtrace( ); if (isset($called_from[$j + 1]) && in_array($called_from[$j + 1]['function'], $debug_funcs)) { ++$j; } $file0 = substr($called_from[$j]['file'], strlen($_SERVER['DOCUMENT_ROOT'])); $line0 = $called_from[$j]['line']; $called = ''; if (isset($called_from[$j + 1]['file'])) { $file1 = substr($called_from[$j + 1]['file'], strlen($_SERVER['DOCUMENT_ROOT'])); $line1 = $called_from[$j + 1]['line']; $called = "{$file1} : {$line1} called "; } elseif (isset($called_from[$j + 1]['class'])) { $called = $called_from[$j + 1]['class'].$called_from[$j + 1]['type'].$called_from[$j + 1]['function'].' called '; } $html = "<strong>{$called}{$file0} : {$line0}</strong>\n"; } if ( ! $new_window) { $color = '#000'; if ($error) { $color = '#F00'; } echo "\n\n<pre style=\"background:#FFF;color:{$color};font-size:larger;\">{$html}{$contents}\n<hr /></pre>\n\n"; } else { ?> <script language="javascript"> myRef = window.open('','debugWindow'); myRef.document.write('\n\n<pre style="background:#FFF;color:#000;font-size:larger;">'); myRef.document.write('<?php echo str_replace("'", "\'", str_replace("\n", "<br />", "{$html}{$contents}")); ?>'); myRef.document.write('\n<hr /></pre>\n\n'); </script> <?php } } function dump($var = 'Th&F=xUFucreSp2*ezAhe=ApuPR*$axe', $bypass = false, $show_from = true, $new_window = false, $error = false) { call($var, $bypass, $show_from, $new_window, $error); } function debug($var = 'Th&F=xUFucreSp2*ezAhe=ApuPR*$axe', $bypass = true, $show_from = true, $new_window = false, $error = false) { call($var, $bypass, $show_from, $new_window, $error); } - +} /** function load_class * This function automagically loads the class * via the spl_autoload_register function above * as it is instantiated (jit). * * @param string class name * @action loads given class name if found * @return bool success */ function load_class($class_name) { $class_file = CLASSES_DIR.strtolower($class_name).'.class.php'; if (class_exists($class_name)) { return true; } elseif (file_exists($class_file) && is_readable($class_file)) { require_once $class_file; return true; } else { throw new MyException(__FUNCTION__.': Class file ('.$class_file.') not found'); } } /** function test_token * This function tests the token given by the * form and checks it against the session token * and if they do not match, dies * * @param bool optional keep original token flag * @action tests tokens and dies if bad * @action optionally renews the session token * @return void */ function test_token($keep = false) { call($_SESSION['token']); call($_REQUEST['token']); if (DEBUG || ('games' == $_SERVER['HTTP_HOST']) || empty($GLOBALS['_DETECTHACKS'])) { return; } if ( ! isset($_SESSION['token']) || ! isset($_REQUEST['token']) || (0 !== strcmp($_SESSION['token'], $_REQUEST['token']))) { die('Hacking attempt detected.<br /><br />If you have reached this page in error, please go back,<br />clear your cache, refresh the page, and try again.'); } // renew the token if ( ! $keep) { $_SESSION['token'] = md5(uniqid(rand( ), true)); } } /** function test_debug * This function tests the debug given by the * URL and checks it against the globals debug password * and if they do not match, doesn't debug * * @param void * @action tests debug pass * @return bool success */ function test_debug( ) { if ( ! isset($_GET['DEBUG'])) { return false; } if ( ! class_exists('Settings') || ! Settings::test( )) { return false; } if ('' == trim(Settings::read('debug_pass'))) { return false; } if (0 !== strcmp($_GET['DEBUG'], Settings::read('debug_pass'))) { return false; } $GLOBALS['_&_DEBUG_QUERY'] = '&DEBUG='.$_GET['DEBUG']; $GLOBALS['_?_DEBUG_QUERY'] = '?DEBUG='.$_GET['DEBUG']; return true; } /** function expandFEN * This function expands a packed FEN into a * string where each index is a valid location * * @param string packed FEN * @return string expanded FEN */ function expandFEN($FEN) { $FEN = preg_replace('/\s+/', '', $FEN); // remove spaces $FEN = preg_replace_callback('/\d+/', 'replace_callback', $FEN); // unpack the 0s $xFEN = str_replace('/', '', $FEN); // remove the row separators return $xFEN; } function replace_callback($match) { return (((int) $match[0]) ? str_repeat('0', (int) $match[0]) : $match[0]); } /** function packFEN * This function packs an expanded FEN into a * string that takes up less space * * @param string expanded FEN * @param int [optional] length of rows * @return string packed FEN */ function packFEN($xFEN, $row_length = 10) { $xFEN = preg_replace('/\s+/', '', $xFEN); // remove spaces $xFEN = preg_replace('/\//', '', $xFEN); // remove any row separators $xFEN = trim(chunk_split($xFEN, $row_length, '/'), '/'); // add the row separators // /e modifier got depricated in PHP 5.5.0 if (version_compare(PHP_VERSION, '5.5.0', '>=')) { $FEN = preg_replace_callback('/(0+)/', function($m) { return strlen($m[1]); }, $xFEN); // pack the 0s } else { $FEN = preg_replace('/(0+)/e', "strlen('\\1')", $xFEN); // pack the 0s } return $FEN; } /** function get_index * * Gets the FEN string index for a 2D location * of a square array of blocks each containing * a square array of elements within those blocks * * This was designed for use within foreach structures * The first foreach ($i) is the outer blocks, and the * second ($j) is for the inner elements. * * Example Structure: * +----+----+----++----+----+----+ * | 0 | 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 | 29 | * +----+----+----++----+----+----+ * | 30 | 31 | 32 || 33 | 34 | 35 | * +----+----+----++----+----+----+ * * Where $i = 2 (bottom left big block) * and $j = 5 (center element) * $blocks = 2 (number of blocks per side) * $elems = 3 (numer of elements per side in each block) * will return 25 (the index of the string) * * @param int the current block number * @param int the current element number * @param int the number of blocks per side * @param int the number of elements per side per block * @return int the FEN string index */ function get_index($i, $j, $blocks = 3, $elems = 3) { $bits = array( ($j % $elems), // across within block (across elems) ((int) floor($j / $elems) * $blocks * $elems), // down within block (down elems) (($i % $blocks) * $elems), // across blocks ((int) floor($i / $blocks) * $blocks * $elems * $elems), // down blocks ); return array_sum($bits); } /** function ife * if-else * This function returns the value if it exists (or is optionally not empty) * or a default value if it does not exist (or is empty) * * @param mixed var to test * @param mixed optional default value * @param bool optional allow empty value * @param bool optional change the passed reference var * @return mixed $var if exists (and not empty) or default otherwise */ function ife( & $var, $default = null, $allow_empty = true, $change_reference = false) { if ( ! isset($var) || ( ! (bool) $allow_empty && empty($var))) { if ((bool) $change_reference) { $var = $default; // so it can also be used by reference } return $default; } return $var; } /** function ifer * if-else reference * This function returns the value if it exists (or is optionally not empty) * or a default value if it does not exist (or is empty) * It also changes the reference var * * @param mixed var to test * @param mixed optional default value * @param bool optional allow empty value * @action updates/sets the reference var if needed * @return mixed $var if exists (and not empty) or default otherwise */ function ifer( & $var, $default = null, $allow_empty = true) { return ife($var, $default, $allow_empty, true); } /** function ifenr * if-else non-reference * This function returns the value if it is not empty * or a default value if it is empty * * @param mixed var to test * @param mixed optional default value * @return mixed $var if not empty or default otherwise */ function ifenr($var, $default = null) { if (empty($var)) { return $default; } return $var; } diff --git a/includes/inc.global.php b/includes/inc.global.php index e70acc2..ba92ad7 100644 --- a/includes/inc.global.php +++ b/includes/inc.global.php @@ -1,187 +1,183 @@ <?php $debug = false; // set some ini stuff ini_set('register_globals', 0); // you really should have this off anyways // deal with those lame magic quotes if (get_magic_quotes_gpc( )) { function stripslashes_deep($value) { $value = is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value); return $value; } $_POST = array_map('stripslashes_deep', $_POST); $_GET = array_map('stripslashes_deep', $_GET); $_COOKIE = array_map('stripslashes_deep', $_COOKIE); $_REQUEST = array_map('stripslashes_deep', $_REQUEST); } /** * GLOBAL INCLUDES * * * * * * * * * * * * * * * * * * * * * * * * * * */ define('ROOT_DIR', dirname(dirname(__FILE__)).DIRECTORY_SEPARATOR); define('INCLUDE_DIR', ROOT_DIR.'includes'.DIRECTORY_SEPARATOR); define('CLASSES_DIR', ROOT_DIR.'classes'.DIRECTORY_SEPARATOR); define('GAMES_DIR', ROOT_DIR.'games'.DIRECTORY_SEPARATOR); define('LOG_DIR', ROOT_DIR.'logs'.DIRECTORY_SEPARATOR); ini_set('error_log', LOG_DIR.'php.err'); if (is_file(INCLUDE_DIR.'config.php')) { require_once INCLUDE_DIR.'config.php'; } #/*/ #elseif ('setup-config.php' != basename($_SERVER['PHP_SELF'])) { # header('Location: setup-config.php'); #/*/ #elseif ('install.php' != basename($_SERVER['PHP_SELF'])) { # header('Location: install.php'); #//*/ # exit; #} require_once INCLUDE_DIR.'inc.settings.php'; require_once INCLUDE_DIR.'func.global.php'; require_once INCLUDE_DIR.'html.general.php'; require_once INCLUDE_DIR.'html.tables.php'; // MAKE SURE TO LOAD CLASS FILES BEFORE STARTING THE SESSION // OR YOU END UP WITH INCOMPLETE OBJECTS PULLED FROM SESSION spl_autoload_register('load_class'); // set the proper timezone date_default_timezone_set($GLOBALS['_DEFAULT_TIMEZONE']); /** * GLOBAL DATA * * * * * * * * * * * * * * * * * * * * * * * * * * */ // make a list of all the color files available to use $GLOBALS['_COLORS'] = array( ); $dh = opendir(realpath(dirname(__FILE__).'/../css')); while (false !== ($file = readdir($dh))) { if (preg_match('/^c_(.+)\\.css$/i', $file, $match)) { // scanning for color files only $GLOBALS['_COLORS'][] = $match[1]; } } // convert the full color file name to just the color portion $GLOBALS['_DEFAULT_COLOR'] = ''; if (class_exists('Settings') && Settings::test( )) { $GLOBALS['_DEFAULT_COLOR'] = preg_replace('/c_(.+)\\.css/i', '$1', Settings::read('default_color')); } if ('' == $GLOBALS['_DEFAULT_COLOR']) { if (in_array('red_black', $GLOBALS['_COLORS'])) { $GLOBALS['_DEFAULT_COLOR'] = 'red_black'; } elseif ($GLOBALS['_COLORS']) { $GLOBALS['_DEFAULT_COLOR'] = $GLOBALS['_COLORS'][0]; } else { $GLOBALS['_DEFAULT_COLOR'] = ''; } } // set the session cookie parameters so the cookie is only valid for this game $parts = pathinfo($_SERVER['REQUEST_URI']); $path = $parts['dirname']; if (empty($parts['extension'])) { $path .= $parts['basename']; } $path = str_replace('\\', '/', $path).'/'; session_set_cookie_params(0, $path); session_start( ); // make sure we don't cross site session steal in our own site if ( ! isset($_SESSION['PWD']) || (__FILE__ != $_SESSION['PWD'])) { $_SESSION = array( ); } $_SESSION['PWD'] = __FILE__; // set a token, we'll be passing one around a lot if ( ! isset($_SESSION['token'])) { $_SESSION['token'] = md5(uniqid(rand( ), true)); } // set our DEBUG constant $GLOBALS['_&_DEBUG_QUERY'] = ''; $GLOBALS['_?_DEBUG_QUERY'] = ''; if ( ! defined('DEBUG')) { if (test_debug( )) { define('DEBUG', true); // DO NOT CHANGE THIS ONE } else { define('DEBUG', (bool) $debug); // set to true for output of debugging code } } $GLOBALS['_LOGGING'] = DEBUG; // do not change, rather, change debug value if (Mysql::test( )) { $Mysql = Mysql::get_instance( ); $Mysql->set_settings(array( 'log_path' => LOG_DIR, 'email_subject' => GAME_NAME.' Query Error', )); if (class_exists('Settings') && Settings::test( )) { $Mysql->set_settings(array( 'log_errors' => Settings::read('DB_error_log'), 'email_errors' => Settings::read('DB_error_email'), 'email_from' => Settings::read('from_email'), 'email_to' => Settings::read('to_email'), )); } } if (defined('DEBUG') && DEBUG) { ini_set('display_errors','On'); - error_reporting(E_ALL | E_STRICT); // all errors, notices, and strict warnings + error_reporting(-1); // everything if (isset($Mysql)) { $Mysql->set_error(3); } } -else { // do not edit the following - ini_set('display_errors','Off'); - error_reporting(E_ALL & ~ E_NOTICE); // show errors, but not notices -} // log the player in if (( ! defined('LOGIN') || LOGIN) && isset($Mysql)) { $GLOBALS['Player'] = new GamePlayer( ); // this will redirect to login if failed $GLOBALS['Player']->log_in( ); if (0 != $_SESSION['player_id']) { $Message = new Message($_SESSION['player_id'], $GLOBALS['Player']->is_admin); } // set the default color for the player if (('' != $GLOBALS['Player']->color) && (in_array($GLOBALS['Player']->color, $GLOBALS['_COLORS']))) { $GLOBALS['_DEFAULT_COLOR'] = $GLOBALS['Player']->color; } // set the default timezone for the player if ('' !== $GLOBALS['Player']->timezone) { date_default_timezone_set($GLOBALS['Player']->timezone); } } // grab the list of players if (isset($Mysql)) { $GLOBALS['_PLAYERS'] = Player::get_array( ); }
benjamw/pharaoh
279c37c77297376648fb4a0dba565865472e9b27
fix hack detection issues
diff --git a/includes/config.php.sample b/includes/config.php.sample index 77edc83..6e36873 100644 --- a/includes/config.php.sample +++ b/includes/config.php.sample @@ -1,46 +1,47 @@ <?php // ---------------------------------------------------------- // DO NOT MODIFY THIS FILE UNLESS YOU KNOW WHAT YOU ARE DOING // ---------------------------------------------------------- /* Database settings */ /* ----------------- */ $GLOBALS['_DEFAULT_DATABASE']['hostname'] = 'localhost'; // the URI of the MySQL server host $GLOBALS['_DEFAULT_DATABASE']['username'] = 'username_here'; // the MySQL user's name $GLOBALS['_DEFAULT_DATABASE']['password'] = 'password_here'; // the MySQL user's password $GLOBALS['_DEFAULT_DATABASE']['database'] = 'database_here'; // the MySQL database name $GLOBALS['_DEFAULT_DATABASE']['log_path'] = LOG_DIR; // the MySQL log path /* Root settings */ /* ------------- */ - $GLOBALS['_ROOT_ADMIN'] = 'yourname'; // Permanent admin username (case-sensitive) - $GLOBALS['_ROOT_URI'] = 'http://www.yoursite.com/pharaoh/'; // The root URL of the game script (include closing / ) - $GLOBALS['_USEEMAIL'] = true; // SMTP operations. Test it before putting it into production + $GLOBALS['_ROOT_ADMIN'] = 'yourname'; // Permanent admin username (case-sensitive) + $GLOBALS['_ROOT_URI'] = 'http://www.yoursite.com/pharaoh/'; // The root URL of the game script (include closing / ) + $GLOBALS['_USEEMAIL'] = true; // SMTP operations. Test it before putting it into production + $GLOBALS['_DETECTHACKS'] = true; // disable this if it causes problems /* Date settings */ /* ------------- */ $GLOBALS['_DEFAULT_TIMEZONE'] = 'UTC'; // Your timezone (http://php.net/manual/en/timezones.php) /* Table settings */ /* -------------- */ $master_prefix = ''; // master database table prefix $game_prefix = 'ph_'; // game table name prefix // note this table does not have the same prefix as the other tables define('T_PLAYER' , $master_prefix . 'player'); // the player data table (NOTE: THERE IS NO GAME PREFIX) define('T_CHAT' , $master_prefix . $game_prefix . 'chat'); // the in-game chat/personal notes table define('T_GAME' , $master_prefix . $game_prefix . 'game'); // the game data table define('T_GAME_HISTORY' , $master_prefix . $game_prefix . 'game_history'); // the game move history table define('T_GAME_NUDGE' , $master_prefix . $game_prefix . 'game_nudge'); // the game nudge table define('T_MESSAGE' , $master_prefix . $game_prefix . 'message'); // the message table define('T_MSG_GLUE' , $master_prefix . $game_prefix . 'message_glue'); // the player messaging glue table define('T_SETTINGS' , $master_prefix . $game_prefix . 'settings'); // the settings table define('T_SETUP' , $master_prefix . $game_prefix . 'setup'); // the board setups table define('T_STATS' , $master_prefix . $game_prefix . 'stats'); // the game stats table define('T_PHARAOH' , $master_prefix . $game_prefix . 'ph_player'); // the pharaoh player data table diff --git a/includes/func.global.php b/includes/func.global.php index 18d115e..bbb2ceb 100644 --- a/includes/func.global.php +++ b/includes/func.global.php @@ -1,353 +1,353 @@ <?php /** function call [dump] [debug] * This function is for debugging only * Outputs given var to screen * or, if no var given, outputs stars to note position * * @param mixed optional var to output * @param bool optional bypass debug value and output anyway * @action outputs var to screen * @return void */ function call($var = 'Th&F=xUFucreSp2*ezAhe=ApuPR*$axe', $bypass = false, $show_from = true, $new_window = false, $error = false) { if ((( ! defined('DEBUG') || ! DEBUG) || ! empty($GLOBALS['NODEBUG'])) && ! (bool) $bypass) { return false; } if ('Th&F=xUFucreSp2*ezAhe=ApuPR*$axe' === $var) { $contents = '<span style="font-size:larger;font-weight:bold;color:red;">--==((OO88OO))==--</span>'; } else { // begin output buffering so we can escape any html // and print_r is better at catching recursion than var_export ob_start( ); if ((is_string($var) && ! preg_match('/^\\s*$/', $var))) { // non-whitespace strings print_r($var); } else { if ( ! function_exists('xdebug_disable')) { if (is_array($var) || is_object($var)) { print_r($var); } else { var_dump($var); } } else { var_dump($var); } } // end output buffering and output the result if ( ! function_exists('xdebug_disable')) { $contents = htmlentities(ob_get_contents( )); } else { $contents = ob_get_contents( ); } ob_end_clean( ); } $j = 0; $html = ''; $debug_funcs = array('dump', 'debug'); if ((bool) $show_from) { $called_from = debug_backtrace( ); if (isset($called_from[$j + 1]) && in_array($called_from[$j + 1]['function'], $debug_funcs)) { ++$j; } $file0 = substr($called_from[$j]['file'], strlen($_SERVER['DOCUMENT_ROOT'])); $line0 = $called_from[$j]['line']; $called = ''; if (isset($called_from[$j + 1]['file'])) { $file1 = substr($called_from[$j + 1]['file'], strlen($_SERVER['DOCUMENT_ROOT'])); $line1 = $called_from[$j + 1]['line']; $called = "{$file1} : {$line1} called "; } elseif (isset($called_from[$j + 1]['class'])) { $called = $called_from[$j + 1]['class'].$called_from[$j + 1]['type'].$called_from[$j + 1]['function'].' called '; } $html = "<strong>{$called}{$file0} : {$line0}</strong>\n"; } if ( ! $new_window) { $color = '#000'; if ($error) { $color = '#F00'; } echo "\n\n<pre style=\"background:#FFF;color:{$color};font-size:larger;\">{$html}{$contents}\n<hr /></pre>\n\n"; } else { ?> <script language="javascript"> myRef = window.open('','debugWindow'); myRef.document.write('\n\n<pre style="background:#FFF;color:#000;font-size:larger;">'); myRef.document.write('<?php echo str_replace("'", "\'", str_replace("\n", "<br />", "{$html}{$contents}")); ?>'); myRef.document.write('\n<hr /></pre>\n\n'); </script> <?php } } function dump($var = 'Th&F=xUFucreSp2*ezAhe=ApuPR*$axe', $bypass = false, $show_from = true, $new_window = false, $error = false) { call($var, $bypass, $show_from, $new_window, $error); } function debug($var = 'Th&F=xUFucreSp2*ezAhe=ApuPR*$axe', $bypass = true, $show_from = true, $new_window = false, $error = false) { call($var, $bypass, $show_from, $new_window, $error); } /** function load_class * This function automagically loads the class * via the spl_autoload_register function above * as it is instantiated (jit). * * @param string class name * @action loads given class name if found * @return bool success */ function load_class($class_name) { $class_file = CLASSES_DIR.strtolower($class_name).'.class.php'; if (class_exists($class_name)) { return true; } elseif (file_exists($class_file) && is_readable($class_file)) { require_once $class_file; return true; } else { throw new MyException(__FUNCTION__.': Class file ('.$class_file.') not found'); } } /** function test_token * This function tests the token given by the * form and checks it against the session token * and if they do not match, dies * * @param bool optional keep original token flag * @action tests tokens and dies if bad * @action optionally renews the session token * @return void */ function test_token($keep = false) { call($_SESSION['token']); - call($_POST['token']); + call($_REQUEST['token']); - if (DEBUG) { + if (DEBUG || ('games' == $_SERVER['HTTP_HOST']) || empty($GLOBALS['_DETECTHACKS'])) { return; } - if ( ! isset($_SESSION['token']) || ! isset($_POST['token']) - || (0 !== strcmp($_SESSION['token'], $_POST['token']))) + if ( ! isset($_SESSION['token']) || ! isset($_REQUEST['token']) + || (0 !== strcmp($_SESSION['token'], $_REQUEST['token']))) { die('Hacking attempt detected.<br /><br />If you have reached this page in error, please go back,<br />clear your cache, refresh the page, and try again.'); } // renew the token if ( ! $keep) { $_SESSION['token'] = md5(uniqid(rand( ), true)); } } /** function test_debug * This function tests the debug given by the * URL and checks it against the globals debug password * and if they do not match, doesn't debug * * @param void * @action tests debug pass * @return bool success */ function test_debug( ) { if ( ! isset($_GET['DEBUG'])) { return false; } if ( ! class_exists('Settings') || ! Settings::test( )) { return false; } if ('' == trim(Settings::read('debug_pass'))) { return false; } if (0 !== strcmp($_GET['DEBUG'], Settings::read('debug_pass'))) { return false; } $GLOBALS['_&_DEBUG_QUERY'] = '&DEBUG='.$_GET['DEBUG']; $GLOBALS['_?_DEBUG_QUERY'] = '?DEBUG='.$_GET['DEBUG']; return true; } /** function expandFEN * This function expands a packed FEN into a * string where each index is a valid location * * @param string packed FEN * @return string expanded FEN */ function expandFEN($FEN) { $FEN = preg_replace('/\s+/', '', $FEN); // remove spaces $FEN = preg_replace_callback('/\d+/', 'replace_callback', $FEN); // unpack the 0s $xFEN = str_replace('/', '', $FEN); // remove the row separators return $xFEN; } function replace_callback($match) { return (((int) $match[0]) ? str_repeat('0', (int) $match[0]) : $match[0]); } /** function packFEN * This function packs an expanded FEN into a * string that takes up less space * * @param string expanded FEN * @param int [optional] length of rows * @return string packed FEN */ function packFEN($xFEN, $row_length = 10) { $xFEN = preg_replace('/\s+/', '', $xFEN); // remove spaces $xFEN = preg_replace('/\//', '', $xFEN); // remove any row separators $xFEN = trim(chunk_split($xFEN, $row_length, '/'), '/'); // add the row separators // /e modifier got depricated in PHP 5.5.0 if (version_compare(PHP_VERSION, '5.5.0', '>=')) { $FEN = preg_replace_callback('/(0+)/', function($m) { return strlen($m[1]); }, $xFEN); // pack the 0s } else { $FEN = preg_replace('/(0+)/e', "strlen('\\1')", $xFEN); // pack the 0s } return $FEN; } /** function get_index * * Gets the FEN string index for a 2D location * of a square array of blocks each containing * a square array of elements within those blocks * * This was designed for use within foreach structures * The first foreach ($i) is the outer blocks, and the * second ($j) is for the inner elements. * * Example Structure: * +----+----+----++----+----+----+ * | 0 | 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 | 29 | * +----+----+----++----+----+----+ * | 30 | 31 | 32 || 33 | 34 | 35 | * +----+----+----++----+----+----+ * * Where $i = 2 (bottom left big block) * and $j = 5 (center element) * $blocks = 2 (number of blocks per side) * $elems = 3 (numer of elements per side in each block) * will return 25 (the index of the string) * * @param int the current block number * @param int the current element number * @param int the number of blocks per side * @param int the number of elements per side per block * @return int the FEN string index */ function get_index($i, $j, $blocks = 3, $elems = 3) { $bits = array( ($j % $elems), // across within block (across elems) ((int) floor($j / $elems) * $blocks * $elems), // down within block (down elems) (($i % $blocks) * $elems), // across blocks ((int) floor($i / $blocks) * $blocks * $elems * $elems), // down blocks ); return array_sum($bits); } /** function ife * if-else * This function returns the value if it exists (or is optionally not empty) * or a default value if it does not exist (or is empty) * * @param mixed var to test * @param mixed optional default value * @param bool optional allow empty value * @param bool optional change the passed reference var * @return mixed $var if exists (and not empty) or default otherwise */ function ife( & $var, $default = null, $allow_empty = true, $change_reference = false) { if ( ! isset($var) || ( ! (bool) $allow_empty && empty($var))) { if ((bool) $change_reference) { $var = $default; // so it can also be used by reference } return $default; } return $var; } /** function ifer * if-else reference * This function returns the value if it exists (or is optionally not empty) * or a default value if it does not exist (or is empty) * It also changes the reference var * * @param mixed var to test * @param mixed optional default value * @param bool optional allow empty value * @action updates/sets the reference var if needed * @return mixed $var if exists (and not empty) or default otherwise */ function ifer( & $var, $default = null, $allow_empty = true) { return ife($var, $default, $allow_empty, true); } /** function ifenr * if-else non-reference * This function returns the value if it is not empty * or a default value if it is empty * * @param mixed var to test * @param mixed optional default value * @return mixed $var if not empty or default otherwise */ function ifenr($var, $default = null) { if (empty($var)) { return $default; } return $var; }
benjamw/pharaoh
51e3107e8ead504c9ffadd35b5eaa802d8930824
css updates
diff --git a/css/board.css b/css/board.css index 2f6eeb3..e1f85f3 100644 --- a/css/board.css +++ b/css/board.css @@ -1 +1 @@ -.a_board{background-color:#1F2023;color:#CCC;width:550px;height:450px}.a_board .header{text-align:center;font-weight:bold;font-size:16px}.a_board div{border:1px solid #000;float:left;clear:none;width:44px;height:44px;margin:1px;padding:1px;position:relative;overflow:hidden}.a_board .vert{border:0;margin:0;padding:0;width:25px;height:50px;line-height:50px}.a_board .horz{border:0;margin:0;padding:0;width:50px;height:25px;line-height:25px}.a_board .corner{border:0;margin:0;padding:0;width:25px;height:25px}.a_board .corner div{border:2px solid #FFF;width:14px;height:14px;margin:4px;padding:0;line-height:10px;-moz-border-radius:14px;-webkit-border-radius:14px;border-radius:14px}.a_board .corner div.alive{border-color:#0C0;background:#090}.a_board .corner div.immune{border-color:#CC0;background:#990;color:#FFF}.a_board .corner div.dead{border-color:#C00;background:#900;color:#FFF}.a_board .c_silver{background-color:#555}.a_board .c_red{background-color:#500}.a_board .highlight{background-color:#550}.a_board .piece{background-position:center center;background-repeat:no-repeat}.a_board div img{position:absolute;top:0;left:0}.a_board div img.piece{position:absolute;top:1px;left:1px}.a_board img.ccw{margin-left:23px} +.a_board{background-color:#1F2023;color:#CCC;width:550px;height:450px}.a_board .header{text-align:center;font-weight:bold;font-size:16px}.a_board div{border:1px solid #000;float:left;clear:none;width:44px;height:44px;margin:1px;padding:1px;position:relative;overflow:hidden}.a_board .vert{border:0;margin:0;padding:0;width:25px;height:50px;line-height:50px}.a_board .horz{border:0;margin:0;padding:0;width:50px;height:25px;line-height:25px}.a_board .corner{border:0;margin:0;padding:0;width:25px;height:25px}.a_board .corner div{border:2px solid #FFF;width:14px;height:14px;margin:4px;padding:0;line-height:10px;-moz-border-radius:14px;-webkit-border-radius:14px;border-radius:14px}.a_board .corner div.alive{border-color:#0C0;background:#090}.a_board .corner div.immune{border-color:#CC0;background:#990;color:#FFF}.a_board .corner div.dead{border-color:#C00;background:#900;color:#FFF}.a_board .c_silver{background-color:#555}.a_board .c_red{background-color:#500}.a_board .highlight{background-color:#550}.a_board .piece{background-position:center center;background-repeat:no-repeat}.a_board div img{position:absolute;top:0;left:0}.a_board div img.piece{position:absolute;top:1px;left:1px}.a_board img.ccw{margin-left:23px} diff --git a/css/c_pink_black.css b/css/c_pink_black.css new file mode 100644 index 0000000..3d46e81 --- /dev/null +++ b/css/c_pink_black.css @@ -0,0 +1 @@ +html,body{background-color:#27282B;color:#FFF}a{color:#FFF}a.help{border:1px solid #777}a.help:hover{border:1px solid #999}abbr,acronym{border-bottom:1px dashed #777}hr.fancy{background-color:#999;border:1px solid #777}fieldset{border:1px solid #555}form+form{border-top:1px solid #F12C9B}.warning,.warning *{color:#B00}.notice,.notice *{color:#DD0}.highlight,.highlight *{color:#EE4CA8}.instruction,.instruction *{color:#AAA}header{border-bottom:1px solid #F12C9B;background-color:#282828;background:-o-radial-gradient(50% 100%, ellipse cover, #CA2281 30%, #282828 80%) #282828;background:-ms-radial-gradient(50% 100%, ellipse cover, #CA2281 30%, #282828 80%) #282828;background:-moz-radial-gradient(50% 100%, ellipse cover, #CA2281 30%, #282828 80%) #282828;background:-webkit-radial-gradient(50% 100%, ellipse cover, #CA2281 30%, #282828 80%) #282828;background:radial-gradient(ellipse cover at 50% 100%, #ca2281 30%,#282828 80%) #282828}h1{height:45px}h1 a{background-image:url(../images/Pharaoh.png)}nav.site a{color:#DDD;text-shadow:#000 0 1px 1px}nav.site a:hover{color:#FFF;background:-o-radial-gradient(50% 90%, ellipse closest-corner, rgba(255,255,255,0.35) 30%, rgba(255,255,255,0.01) 70%) transparent;background:-ms-radial-gradient(50% 90%, ellipse closest-corner, rgba(255,255,255,0.35) 30%, rgba(255,255,255,0.01) 70%) transparent;background:-moz-radial-gradient(50% 90%, ellipse closest-corner, rgba(255,255,255,0.35) 30%, rgba(255,255,255,0.01) 70%) transparent;background:-webkit-radial-gradient(50% 100%, 80% 20%, rgba(255,255,255,0.35) 30%, rgba(255,255,255,0.01) 70%) transparent;background:radial-gradient(80% 20% at 50% 100%, rgba(255,255,255,0.35) 30%,rgba(255,255,255,0.01) 70%) transparent}*.box{background-color:#000;background:-o-linear-gradient(#232323, #000) #000;background:-ms-linear-gradient(#232323, #000) #000;background:-moz-linear-gradient(#232323, #000) #000;background:-webkit-linear-gradient(#232323, #000) #000;background:linear-gradient(#232323, #000) #000}*.box>*{background-color:#2E2F34;background:-o-linear-gradient(#2E2F34, #212225) #2E2F34;background:-ms-linear-gradient(#2E2F34, #212225) #2E2F34;background:-moz-linear-gradient(#2E2F34, #212225) #2E2F34;background:-webkit-linear-gradient(#2E2F34, #212225) #2E2F34;background:linear-gradient(#2E2F34, #212225) #2E2F34;-o-box-shadow:0px 1px 0px rgba(255,255,255,0.1) inset,0px -2px 1px rgba(0,0,0,0.2) inset;-ms-box-shadow:0px 1px 0px rgba(255,255,255,0.1) inset,0px -2px 1px rgba(0,0,0,0.2) inset;-moz-box-shadow:0px 1px 0px rgba(255,255,255,0.1) inset,0px -2px 1px rgba(0,0,0,0.2) inset;-webkit-box-shadow:0px 1px 0px rgba(255,255,255,0.1) inset,0px -2px 1px rgba(0,0,0,0.2) inset;box-shadow:0px 1px 0px rgba(255,255,255,0.1) inset,0px -2px 1px rgba(0,0,0,0.2) inset}nav#menu a,nav#mygames a{color:#DDD;background-color:transparent;border-bottom:1px solid #333}nav#menu a:hover,nav#mygames a:hover{color:#FFF;background-color:rgba(41,12,28,0.5)}nav#menu li.active a,nav#mygames li.active a{color:inherit;background-color:rgba(255,255,255,0.1)}nav#menu li span.sep,nav#mygames li span.sep{color:#666}nav#mygames .finished a{color:#999}nav#mygames .playing a{color:#EE4CA8}nav#mygames .my_turn a{color:#EE4CA8}nav#mygames .none a{color:#FFF}aside#info #chatbox{background-color:#EEE;border:1px solid #777}h2{border-bottom:1px solid #777}#index_page #chatbox{border:1px solid #777}#index_page #chats{border-top:1px solid #777}#index_page #chats dt{border-bottom:1px solid #777;background:transparent}#index_page #chats dd{border-bottom:1px solid #777}footer{color:#DDD;background-color:#651140;-o-box-shadow:0px 3px 16px #000 inset;-ms-box-shadow:0px 3px 16px #000 inset;-moz-box-shadow:0px 3px 16px #000 inset;-webkit-box-shadow:0px 3px 16px #000 inset;box-shadow:0px 3px 16px #000 inset}#buttons a{border:1px solid #333;border-width:0 1px}#history table td.active,#history table td:hover{background-color:#444;color:#FFF}#history div div span{border:1px solid #555}#history div div span:hover{border-color:#AAA}#history div div span.disabled{color:#AAA;border-color:#333} diff --git a/css/game.css b/css/game.css index 71ddc92..06f1621 100644 --- a/css/game.css +++ b/css/game.css @@ -1 +1 @@ -.a_board{background-color:#1F2023;color:#CCC;width:550px;height:450px}.a_board .header{text-align:center;font-weight:bold;font-size:16px}.a_board div{border:1px solid #000;float:left;clear:none;width:44px;height:44px;margin:1px;padding:1px;position:relative;overflow:hidden}.a_board .vert{border:0;margin:0;padding:0;width:25px;height:50px;line-height:50px}.a_board .horz{border:0;margin:0;padding:0;width:50px;height:25px;line-height:25px}.a_board .corner{border:0;margin:0;padding:0;width:25px;height:25px}.a_board .corner div{border:2px solid #FFF;width:14px;height:14px;margin:4px;padding:0;line-height:10px;-moz-border-radius:14px;-webkit-border-radius:14px;border-radius:14px}.a_board .corner div.alive{border-color:#0C0;background:#090}.a_board .corner div.immune{border-color:#CC0;background:#990;color:#FFF}.a_board .corner div.dead{border-color:#C00;background:#900;color:#FFF}.a_board .c_silver{background-color:#555}.a_board .c_red{background-color:#500}.a_board .highlight{background-color:#550}.a_board .piece{background-position:center center;background-repeat:no-repeat}.a_board div img{position:absolute;top:0;left:0}.a_board div img.piece{position:absolute;top:1px;left:1px}.a_board img.ccw{margin-left:23px}#contents{margin:10px}#chatbox{margin-left:732px}#chats{height:450px}#game_page #chatbox input[type=text]{width:80%}#game_page #chatbox dd{padding-left:1em}#board_wrapper{float:left;width:550px;margin-left:5px}#board{width:550px;height:450px}#history{float:left;width:170px}#history table{margin:0}#history table td{padding:0 5px;font-size:1.1em;line-height:130%}#history table td.active,#history table td:hover{font-weight:bold;background-color:#444;color:#FFF}#history table td.turn{width:1%;text-align:right}#history div div{margin-bottom:2px;text-align:center}#history div div span{padding:2px 5px 1px;border:1px solid #555;-moz-border-radius:3px;-webkit-border-radius:3px;border-radius:3px;cursor:pointer}#history div div span:hover{border-color:#AAA}#history div div span.disabled{color:#AAA;border-color:#333;cursor:default}form#game{clear:both;text-align:center;padding-top:20px}#setup{display:none} +.msg,.sunk,.finished{color:#FFF;font-weight:bold;font-size:16px;line-height:24px;background:#C00;padding:4px;text-align:center;margin-bottom:1ex}.won{background:#093}.lost{background:#C00}div.board,div.noboard{float:left;margin:10px}div.noboard{width:354px;height:354px;border:2px solid black;font-size:28px;vertical-align:middle;text-align:center;background-color:#DEF;color:#333;line-height:335px}* html div.noboard{width:358px;height:358px}div#board_data:after{content:'.';display:block;height:0;clear:both;visibility:hidden}* html div#board_data{zoom:1}div.board_info{float:left;margin:0 10px;width:356px;text-align:right}div.board_info span{float:right;display:block;line-height:16px}div.board_info .fleet{float:left;font-size:16px;font-weight:bold}div.boats{text-align:left;width:200px;height:354px;float:left;margin:10px}div.boats div.boat{width:180px;height:35px;float:left;clear:right}div.board div,div.boat div{float:left;width:30px;height:30px;border:1px solid #005;background-color:#79F;font-weight:bold;color:#000}div.board div.row{float:none;clear:both;width:auto;height:32px;border:2px solid #000;border-width:0 2px 0;background-color:transparent;font-weight:normal;overflow:visible}div.board div.row.top,div.board div.row.bottom{height:17px;border:2px solid #000;border-width:2px 2px 0}div.board div.row.bottom{border:2px solid #000;border-width:0 2px 2px}div.board div.top div,div.board div.bottom div{height:15px;line-height:15px;border:1px solid #DDD;background-color:#EFF4FF;text-align:center}div.board div.top div.corner,div.board div.bottom div.corner{width:15px;height:15px;border:1px solid #DDD;background-color:#EFF4FF}div.board div.side{width:15px;line-height:30px;border:1px solid #DDD;background-color:#EFF4FF;text-align:center}div.v-bow{background-image:url("../images/v_bow.gif")}div.v-fore{background-image:url("../images/v_fore.gif")}div.v-mid{background-image:url("../images/v_mid.gif")}div.v-aft{background-image:url("../images/v_aft.gif")}div.v-stern{background-image:url("../images/v_stern.gif")}div.h-bow{background-image:url("../images/h_bow.gif")}div.h-fore{background-image:url("../images/h_fore.gif")}div.h-mid{background-image:url("../images/h_mid.gif")}div.h-aft{background-image:url("../images/h_aft.gif")}div.h-stern{background-image:url("../images/h_stern.gif")}div.board div.prevshot{border:2px solid yellow;margin:-1px;position:relative;z-index:2}div.board div.curshot{border:2px solid white;margin:-1px;position:relative;z-index:4}.clr{clear:both}#game div{clear:both;text-align:center}.shots{text-align:center;width:200px;margin:5px auto -20px;font-size:14px;font-weight:bold;color:#C00}.shots img{width:15px;height:15px;border:0;vertical-align:middle}h2 span{margin:0 3em}#chats{height:auto}#chats .bla{color:#DDD;background-color:#333}#chats .whi{color:#333;background-color:#DDD}#chats .blu{color:#00D;background-color:#333}#chats .private{background-color:#BBF;color:#000}#contents{margin:10px}#chatbox{margin-left:732px}#chats{height:450px}#game_page #chatbox input[type=text]{width:80%}#game_page #chatbox dd{padding-left:1em}#board_wrapper{float:left;width:550px;margin-left:5px}#board{width:550px;height:450px}#history{float:left;width:170px}#history table{margin:0}#history table td{padding:0 5px;font-size:1.1em;line-height:130%}#history table td.active,#history table td:hover{font-weight:bold;background-color:#444;color:#FFF}#history table td.turn{width:1%;text-align:right}#history div div{margin-bottom:2px;text-align:center}#history div div span{padding:2px 5px 1px;border:1px solid #555;-moz-border-radius:3px;-webkit-border-radius:3px;border-radius:3px;cursor:pointer}#history div div span:hover{border-color:#AAA}#history div div span.disabled{color:#AAA;border-color:#333;cursor:default}form#game{clear:both;text-align:center;padding-top:20px}#setup{display:none} diff --git a/css/scss/_board.scss b/css/scss/_board_settings.scss similarity index 100% rename from css/scss/_board.scss rename to css/scss/_board_settings.scss diff --git a/css/scss/board.scss b/css/scss/board.scss index ef9034a..ddc2185 100644 --- a/css/scss/board.scss +++ b/css/scss/board.scss @@ -1,8 +1,8 @@ /* Board specific CSS */ // this file needs to be here for the invitation page -@import "board"; +@import "board_settings"; diff --git a/css/scss/c_pink_black.scss b/css/scss/c_pink_black.scss new file mode 100644 index 0000000..30be859 --- /dev/null +++ b/css/scss/c_pink_black.scss @@ -0,0 +1,24 @@ + +/* Game colors */ +/* pink-black created by Luke Larsen, coded by Benjam Welker */ + +/* + all the layout for the webpages are specified in the layout.css + file. the colors have been separated out for ease of customization +*/ + +// set our default styles for blue_black + +$main_back_color: #282828 !default; +$main_highlight_color: #CA2281 !default; + +$highlight_color: #EE4CA8 !default; + +$header_border_bottom: 1px solid #F12C9B !default; + +$nav_hover_background_color: rgba(41, 12, 28, 0.5) !default; + +$footer_background_color: $main_highlight_color / 2 !default; + + +@import "c_template"; diff --git a/css/scss/game.scss b/css/scss/game.scss index acbd364..bd3bc62 100644 --- a/css/scss/game.scss +++ b/css/scss/game.scss @@ -1,104 +1,104 @@ /* Game page specific CSS */ -@import "board"; +@import "board_settings"; #contents { margin: 10px; } #chatbox { margin-left: 732px; } #chats { height: 450px; } #game_page { #chatbox { input[type=text] { width: 80%; } dd { padding-left: 1em; } } } #board_wrapper { float: left; width: 550px; margin-left: 5px; } #board { width: 550px; height: 450px; } #history { float: left; width: 170px; table { margin: 0; td { padding: 0 5px; font-size: 1.1em; line-height: 130%; &.active, &:hover { font-weight: bold; background-color: #444; color: #FFF; } &.turn { width: 1%; text-align: right; } } } div div { margin-bottom: 2px; text-align: center; span { padding: 2px 5px 1px; border: 1px solid #555; -moz-border-radius: 3px; -webkit-border-radius: 3px; border-radius: 3px; cursor: pointer; &:hover { border-color: #AAA; } &.disabled { color: #AAA; border-color: #333; cursor: default; } } } } form#game { clear: both; text-align: center; padding-top: 20px; } #setup { display: none; }
benjamw/pharaoh
5b125b49031046087fb827ae5bf049ca6cf659b2
minor updates
diff --git a/game.php b/game.php index b64cb11..718002d 100644 --- a/game.php +++ b/game.php @@ -1,265 +1,265 @@ <?php require_once 'includes/inc.global.php'; // grab the game id if (isset($_GET['id'])) { $_SESSION['game_id'] = (int) $_GET['id']; } elseif ( ! isset($_SESSION['game_id'])) { if ( ! defined('DEBUG') || ! DEBUG) { Flash::store('No Game Id Given !'); } else { call('NO GAME ID GIVEN'); } exit; } // load the game // always refresh the game data, there may be more than one person online try { $Game = new Game((int) $_SESSION['game_id']); $players = $Game->get_players( ); } catch (MyException $e) { if ( ! defined('DEBUG') || ! DEBUG) { Flash::store('Error Accessing Game !'); } else { call('ERROR ACCESSING GAME :'.$e->outputMessage( )); } exit; } // MOST FORM SUBMISSIONS ARE AJAXED THROUGH /scripts/game.js // game buttons and moves are passed through the game controller if ( ! $Game->is_player($_SESSION['player_id'])) { $Game->watch_mode = true; $chat_html = ''; unset($Chat); } if ( ! $Game->watch_mode || $GLOBALS['Player']->is_admin) { $Chat = new Chat($_SESSION['player_id'], $_SESSION['game_id']); $chat_data = $Chat->get_box_list( ); $chat_html = ' <div id="chatbox"> <form action="'.$_SERVER['REQUEST_URI'].'" method="post"><div> <input id="chat" type="text" name="chat" /> <label for="private" class="inline"><input type="checkbox" name="private" id="private" value="yes" /> Private</label> </div></form> <dl id="chats">'; if (is_array($chat_data)) { foreach ($chat_data as $chat) { if ('' == $chat['username']) { $chat['username'] = '[deleted]'; } $color = 'blue'; if ( ! empty($players[$chat['player_id']]['color']) && ('white' == $players[$chat['player_id']]['color'])) { $color = 'silver'; } if ( ! empty($players[$chat['player_id']]['color']) && ('black' == $players[$chat['player_id']]['color'])) { $color = 'red'; } // preserve spaces in the chat text $chat['message'] = htmlentities($chat['message'], ENT_QUOTES, 'ISO-8859-1', false); $chat['message'] = str_replace("\t", ' ', $chat['message']); $chat['message'] = str_replace(' ', ' &nbsp;', $chat['message']); $chat_html .= ' <dt class="'.substr($color, 0, 3).'"><span>'.$chat['create_date'].'</span> '.$chat['username'].'</dt> <dd'.($chat['private'] ? ' class="private"' : '').'>'.$chat['message'].'</dd>'; } } $chat_html .= ' </dl> <!-- #chats --> </div> <!-- #chatbox -->'; } // build the history table $history_html = ''; $moves = $Game->get_move_history( ); foreach ($moves as $i => $move) { if ( ! is_array($move)) { break; } $id = ($i * 2) + 1; $history_html .= ' <tr> <td class="turn">'.($i + 1).'</td> <td id="mv_'.$id.'">'.$move[0].'</td> <td'.( ! empty($move[1]) ? ' id="mv_'.($id + 1).'"' : '').'>'.$move[1].'</td> </tr>'; } $turn = $Game->get_turn( ); if ($Game->draw_offered( )) { $turn = '<span>Draw Offered</span>'; } elseif ($Game->undo_requested( )) { $turn = '<span>Undo Requested</span>'; } elseif ($GLOBALS['Player']->username == $turn) { $turn = '<span class="'.$Game->get_color( ).'">Your turn</span>'; } elseif ( ! $turn) { $turn = ''; } else { $turn = '<span class="'.$Game->get_color(false).'">'.$turn.'\'s turn</span>'; } if (in_array($Game->state, array('Finished', 'Draw'))) { list($win_text, $win_class) = $Game->get_outcome($_SESSION['player_id']); $turn = '<span class="'.$win_class.'">Game Over: '.$win_text.'</span>'; } $extra_info = $Game->get_extra_info( ); $meta['title'] = htmlentities($Game->name, ENT_QUOTES, 'ISO-8859-1', false).' - #'.$_SESSION['game_id']; $meta['show_menu'] = false; $meta['head_data'] = ' <link rel="stylesheet" type="text/css" media="screen" href="css/game.css" /> <script type="text/javascript" src="scripts/board.js"></script> - <script type="text/javascript">/*<![CDATA[*/ + <script type="text/javascript"> var draw_offered = '.json_encode($Game->draw_offered($_SESSION['player_id'])).'; var undo_requested = '.json_encode($Game->undo_requested($_SESSION['player_id'])).'; var color = "'.(isset($players[$_SESSION['player_id']]) ? (('white' == $players[$_SESSION['player_id']]['color']) ? 'silver' : 'red') : '').'"; var state = "'.(( ! $Game->watch_mode) ? (( ! $Game->paused) ? strtolower($Game->state) : 'paused') : 'watching').'"; var invert = '.(( ! empty($players[$_SESSION['player_id']]['color']) && ('black' == $players[$_SESSION['player_id']]['color'])) ? 'true' : 'false').'; var last_move = '.$Game->last_move.'; var my_turn = '.($Game->is_turn( ) ? 'true' : 'false').'; var game_history = '.$Game->get_history(true).'; var move_count = game_history.length; var move_index = (move_count - 1); var laser_battle = '.json_encode( !! $extra_info['battle_dead']).'; var move_sphynx = '.json_encode( !! $extra_info['move_sphynx']).'; - /*]]>*/</script> + </script> '; $meta['foot_data'] = ' <script type="text/javascript" src="scripts/game.js"></script> '; echo get_header($meta); ?> <div id="contents"> <ul id="buttons"> <li><a href="index.php<?php echo $GLOBALS['_?_DEBUG_QUERY']; ?>">Main Page</a></li> <li><a href="game.php<?php echo $GLOBALS['_?_DEBUG_QUERY']; ?>">Reload Game Board</a></li> </ul> <h2>Game #<?php echo $_SESSION['game_id'].': '.htmlentities($Game->name, ENT_QUOTES, 'ISO-8859-1', false); ?> <span class="turn"><?php echo $turn; ?></span> <span class="setup"><a href="#setup" class="fancybox"><?php echo $Game->get_setup_name( ); ?></a> <a href="help/pieces.help" class="help">?</a></span> <span class="extra"><?php echo $Game->get_extra( ); ?></span> </h2> <div id="history" class="box"> <div> <div> <span id="first">|&lt;</span> <span id="prev5">&lt;&lt;</span> <span id="prev">&lt;</span> <span id="next">&gt;</span> <span id="next5">&gt;&gt;</span> <span id="last">&gt;|</span> </div> <table> <thead> <tr> <th>#</th> <th>Silver</th> <th>Red</th> </tr> </thead> <tbody> <?php echo $history_html; ?> </tbody> </table> </div> </div> <!-- #history --> <div id="board_wrapper"> <div id="board"></div> <!-- #board --> <div class="buttons"> <a href="javascript:;" id="invert" style="float:right;">Invert Board</a> <a href="javascript:;" id="show_full">Show Full Move</a> | | <a href="javascript:;" id="show_move">Show Move</a> | <a href="javascript:;" id="clear_move">Clear Move</a> | <a href="javascript:;" id="fire_laser">Fire Laser</a> | <a href="javascript:;" id="clear_laser">Clear Laser</a> </div> <!-- .buttons --> <form id="game" method="post" action="<?php echo $_SERVER['REQUEST_URI']; ?>"><div class="formdiv"> <input type="hidden" name="token" value="<?php echo $_SESSION['token']; ?>" /> <input type="hidden" name="game_id" value="<?php echo $_SESSION['game_id']; ?>" /> <input type="hidden" name="player_id" value="<?php echo $_SESSION['player_id']; ?>" /> <input type="hidden" name="from" id="from" value="" /> <input type="hidden" name="to" id="to" value="" /> <?php if (('Playing' == $Game->state) && $Game->is_player($_SESSION['player_id'])) { ?> <?php if ( ! $Game->draw_offered( )) { ?> <input type="button" name="offer_draw" id="offer_draw" value="Offer Draw" /> <?php } elseif ($Game->draw_offered($_SESSION['player_id'])) { ?> <input type="button" name="accept_draw" id="accept_draw" value="Accept Draw Offer" /> <input type="button" name="reject_draw" id="reject_draw" value="Reject Draw Offer" /> <?php } ?> <?php if ( ! $Game->undo_requested( ) && ! $Game->is_turn( ) && ! empty($moves)) { ?> <input type="button" name="request_undo" id="request_undo" value="Request Undo" /> <?php } elseif ($Game->undo_requested($_SESSION['player_id'])) { ?> <input type="button" name="accept_undo" id="accept_undo" value="Accept Undo Request" /> <input type="button" name="reject_undo" id="reject_undo" value="Reject Undo Request" /> <?php } ?> <input type="button" name="resign" id="resign" value="Resign" /> <?php if ($Game->test_nudge( )) { ?> <input type="button" name="nudge" id="nudge" value="Nudge" /> <?php } ?> <?php } ?> </div></form> </div> <!-- #board_wrapper --> <?php echo $chat_html; ?> </div> <!-- #contents --> <script type="text/javascript"> document.write('<'+'div id="setup"'+'>'+create_board('<?php echo expandFEN($Game->get_setup( )); ?>', true)+'<'+'/'+'div'+'>'); </script> <?php call($GLOBALS); echo get_footer($meta); diff --git a/includes/func.global.php b/includes/func.global.php index 4485289..18d115e 100644 --- a/includes/func.global.php +++ b/includes/func.global.php @@ -1,346 +1,353 @@ <?php /** function call [dump] [debug] * This function is for debugging only * Outputs given var to screen * or, if no var given, outputs stars to note position * * @param mixed optional var to output * @param bool optional bypass debug value and output anyway * @action outputs var to screen * @return void */ function call($var = 'Th&F=xUFucreSp2*ezAhe=ApuPR*$axe', $bypass = false, $show_from = true, $new_window = false, $error = false) { if ((( ! defined('DEBUG') || ! DEBUG) || ! empty($GLOBALS['NODEBUG'])) && ! (bool) $bypass) { return false; } if ('Th&F=xUFucreSp2*ezAhe=ApuPR*$axe' === $var) { $contents = '<span style="font-size:larger;font-weight:bold;color:red;">--==((OO88OO))==--</span>'; } else { // begin output buffering so we can escape any html // and print_r is better at catching recursion than var_export ob_start( ); if ((is_string($var) && ! preg_match('/^\\s*$/', $var))) { // non-whitespace strings print_r($var); } else { if ( ! function_exists('xdebug_disable')) { if (is_array($var) || is_object($var)) { print_r($var); } else { var_dump($var); } } else { var_dump($var); } } // end output buffering and output the result if ( ! function_exists('xdebug_disable')) { $contents = htmlentities(ob_get_contents( )); } else { $contents = ob_get_contents( ); } ob_end_clean( ); } $j = 0; $html = ''; $debug_funcs = array('dump', 'debug'); if ((bool) $show_from) { $called_from = debug_backtrace( ); if (isset($called_from[$j + 1]) && in_array($called_from[$j + 1]['function'], $debug_funcs)) { ++$j; } $file0 = substr($called_from[$j]['file'], strlen($_SERVER['DOCUMENT_ROOT'])); $line0 = $called_from[$j]['line']; $called = ''; if (isset($called_from[$j + 1]['file'])) { $file1 = substr($called_from[$j + 1]['file'], strlen($_SERVER['DOCUMENT_ROOT'])); $line1 = $called_from[$j + 1]['line']; $called = "{$file1} : {$line1} called "; } elseif (isset($called_from[$j + 1]['class'])) { $called = $called_from[$j + 1]['class'].$called_from[$j + 1]['type'].$called_from[$j + 1]['function'].' called '; } $html = "<strong>{$called}{$file0} : {$line0}</strong>\n"; } if ( ! $new_window) { $color = '#000'; if ($error) { $color = '#F00'; } echo "\n\n<pre style=\"background:#FFF;color:{$color};font-size:larger;\">{$html}{$contents}\n<hr /></pre>\n\n"; } else { ?> <script language="javascript"> myRef = window.open('','debugWindow'); myRef.document.write('\n\n<pre style="background:#FFF;color:#000;font-size:larger;">'); myRef.document.write('<?php echo str_replace("'", "\'", str_replace("\n", "<br />", "{$html}{$contents}")); ?>'); myRef.document.write('\n<hr /></pre>\n\n'); </script> <?php } } function dump($var = 'Th&F=xUFucreSp2*ezAhe=ApuPR*$axe', $bypass = false, $show_from = true, $new_window = false, $error = false) { call($var, $bypass, $show_from, $new_window, $error); } function debug($var = 'Th&F=xUFucreSp2*ezAhe=ApuPR*$axe', $bypass = true, $show_from = true, $new_window = false, $error = false) { call($var, $bypass, $show_from, $new_window, $error); } /** function load_class * This function automagically loads the class * via the spl_autoload_register function above * as it is instantiated (jit). * * @param string class name * @action loads given class name if found * @return bool success */ function load_class($class_name) { $class_file = CLASSES_DIR.strtolower($class_name).'.class.php'; if (class_exists($class_name)) { return true; } elseif (file_exists($class_file) && is_readable($class_file)) { require_once $class_file; return true; } else { throw new MyException(__FUNCTION__.': Class file ('.$class_file.') not found'); } } /** function test_token * This function tests the token given by the * form and checks it against the session token * and if they do not match, dies * * @param bool optional keep original token flag * @action tests tokens and dies if bad * @action optionally renews the session token * @return void */ function test_token($keep = false) { call($_SESSION['token']); call($_POST['token']); if (DEBUG) { return; } if ( ! isset($_SESSION['token']) || ! isset($_POST['token']) || (0 !== strcmp($_SESSION['token'], $_POST['token']))) { die('Hacking attempt detected.<br /><br />If you have reached this page in error, please go back,<br />clear your cache, refresh the page, and try again.'); } // renew the token if ( ! $keep) { $_SESSION['token'] = md5(uniqid(rand( ), true)); } } /** function test_debug * This function tests the debug given by the * URL and checks it against the globals debug password * and if they do not match, doesn't debug * * @param void * @action tests debug pass * @return bool success */ function test_debug( ) { if ( ! isset($_GET['DEBUG'])) { return false; } if ( ! class_exists('Settings') || ! Settings::test( )) { return false; } if ('' == trim(Settings::read('debug_pass'))) { return false; } if (0 !== strcmp($_GET['DEBUG'], Settings::read('debug_pass'))) { return false; } $GLOBALS['_&_DEBUG_QUERY'] = '&DEBUG='.$_GET['DEBUG']; $GLOBALS['_?_DEBUG_QUERY'] = '?DEBUG='.$_GET['DEBUG']; return true; } /** function expandFEN * This function expands a packed FEN into a * string where each index is a valid location * * @param string packed FEN * @return string expanded FEN */ function expandFEN($FEN) { $FEN = preg_replace('/\s+/', '', $FEN); // remove spaces $FEN = preg_replace_callback('/\d+/', 'replace_callback', $FEN); // unpack the 0s $xFEN = str_replace('/', '', $FEN); // remove the row separators return $xFEN; } function replace_callback($match) { return (((int) $match[0]) ? str_repeat('0', (int) $match[0]) : $match[0]); } /** function packFEN * This function packs an expanded FEN into a * string that takes up less space * * @param string expanded FEN * @param int [optional] length of rows * @return string packed FEN */ function packFEN($xFEN, $row_length = 10) { $xFEN = preg_replace('/\s+/', '', $xFEN); // remove spaces $xFEN = preg_replace('/\//', '', $xFEN); // remove any row separators $xFEN = trim(chunk_split($xFEN, $row_length, '/'), '/'); // add the row separators - $FEN = preg_replace('/(0+)/e', "strlen('\\1')", $xFEN); // pack the 0s + + // /e modifier got depricated in PHP 5.5.0 + if (version_compare(PHP_VERSION, '5.5.0', '>=')) { + $FEN = preg_replace_callback('/(0+)/', function($m) { return strlen($m[1]); }, $xFEN); // pack the 0s + } + else { + $FEN = preg_replace('/(0+)/e', "strlen('\\1')", $xFEN); // pack the 0s + } return $FEN; } /** function get_index * * Gets the FEN string index for a 2D location * of a square array of blocks each containing * a square array of elements within those blocks * * This was designed for use within foreach structures * The first foreach ($i) is the outer blocks, and the * second ($j) is for the inner elements. * * Example Structure: * +----+----+----++----+----+----+ * | 0 | 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 | 29 | * +----+----+----++----+----+----+ * | 30 | 31 | 32 || 33 | 34 | 35 | * +----+----+----++----+----+----+ * * Where $i = 2 (bottom left big block) * and $j = 5 (center element) * $blocks = 2 (number of blocks per side) * $elems = 3 (numer of elements per side in each block) * will return 25 (the index of the string) * * @param int the current block number * @param int the current element number * @param int the number of blocks per side * @param int the number of elements per side per block * @return int the FEN string index */ function get_index($i, $j, $blocks = 3, $elems = 3) { $bits = array( ($j % $elems), // across within block (across elems) ((int) floor($j / $elems) * $blocks * $elems), // down within block (down elems) (($i % $blocks) * $elems), // across blocks ((int) floor($i / $blocks) * $blocks * $elems * $elems), // down blocks ); return array_sum($bits); } /** function ife * if-else * This function returns the value if it exists (or is optionally not empty) * or a default value if it does not exist (or is empty) * * @param mixed var to test * @param mixed optional default value * @param bool optional allow empty value * @param bool optional change the passed reference var * @return mixed $var if exists (and not empty) or default otherwise */ function ife( & $var, $default = null, $allow_empty = true, $change_reference = false) { if ( ! isset($var) || ( ! (bool) $allow_empty && empty($var))) { if ((bool) $change_reference) { $var = $default; // so it can also be used by reference } return $default; } return $var; } /** function ifer * if-else reference * This function returns the value if it exists (or is optionally not empty) * or a default value if it does not exist (or is empty) * It also changes the reference var * * @param mixed var to test * @param mixed optional default value * @param bool optional allow empty value * @action updates/sets the reference var if needed * @return mixed $var if exists (and not empty) or default otherwise */ function ifer( & $var, $default = null, $allow_empty = true) { return ife($var, $default, $allow_empty, true); } /** function ifenr * if-else non-reference * This function returns the value if it is not empty * or a default value if it is empty * * @param mixed var to test * @param mixed optional default value * @return mixed $var if not empty or default otherwise */ function ifenr($var, $default = null) { if (empty($var)) { return $default; } return $var; } diff --git a/invite.php b/invite.php index 9839397..520649d 100644 --- a/invite.php +++ b/invite.php @@ -1,271 +1,275 @@ <?php require_once 'includes/inc.global.php'; // this has nothing to do with creating a game // but I'm running it here to prevent long load // times on other pages where it would be run more often GamePlayer::delete_inactive(Settings::read('expire_users')); Game::delete_inactive(Settings::read('expire_games')); Game::delete_finished(Settings::read('expire_finished_games')); if (isset($_POST['invite'])) { + call($_POST); + // make sure this user is not full if ($GLOBALS['Player']->max_games && ($GLOBALS['Player']->max_games <= $GLOBALS['Player']->current_games)) { Flash::store('You have reached your maximum allowed games !', false); } test_token( ); try { Game::invite( ); Flash::store('Invitation Sent Successfully', true); } catch (MyException $e) { Flash::store('Invitation FAILED !', false); } } // grab the full list of players $players_full = GamePlayer::get_list(true); $invite_players = array_shrink($players_full, 'player_id'); +$invite_players = ife($invite_players, array( ), false); // grab the players who's max game count has been reached $players_maxed = GamePlayer::get_maxed( ); $players_maxed[] = $_SESSION['player_id']; // remove the maxed players from the invite list $players = array_diff($invite_players, $players_maxed); $opponent_selection = ''; $opponent_selection .= '<option value="">-- Open --</option>'; foreach ($players_full as $player) { if ($_SESSION['player_id'] == $player['player_id']) { continue; } if (in_array($player['player_id'], $players)) { $opponent_selection .= ' <option value="'.$player['player_id'].'">'.$player['username'].'</option>'; } } $groups = array( 'Normal' => array(0, 0), 'Eye of Horus' => array(0, 1), 'Sphynx' => array(1, 0), 'Sphynx & Horus' => array(1, 1), ); $group_names = array_keys($groups); $group_markers = array_values($groups); $setups = Setup::get_list( ); $setup_selection = '<option value="0">Random</option>'; $setup_javascript = ''; $cur_group = false; $group_open = false; foreach ($setups as $setup) { $marker = array((int) $setup['has_sphynx'], (int) $setup['has_horus']); $group_index = array_search($marker, $group_markers, true); if ($cur_group !== $group_names[$group_index]) { if ($group_open) { $setup_selection .= '</optgroup>'; $group_open = false; } $cur_group = $group_names[$group_index]; $setup_selection .= '<optgroup label="'.$cur_group.'">'; $group_open = true; } $setup_selection .= ' <option value="'.$setup['setup_id'].'">'.$setup['name'].'</option>'; $setup_javascript .= "'".$setup['setup_id']."' : '".expandFEN($setup['board'])."',\n"; } $setup_javascript = substr(trim($setup_javascript), 0, -1); if ($group_open) { $setup_selection .= '</optgroup>'; } $meta['title'] = 'Send Game Invitation'; $meta['head_data'] = ' <link rel="stylesheet" type="text/css" media="screen" href="css/board.css" /> - +'; +$meta['foot_data'] = ' <script type="text/javascript">//<![CDATA[ var setups = { '.$setup_javascript.' }; /*]]>*/</script> <script type="text/javascript" src="scripts/board.js"></script> <script type="text/javascript" src="scripts/invite.js"></script> '; $hints = array( 'Invite a player to a game by filling out your desired game options.' , '<span class="highlight">WARNING!</span><br />Games will be deleted after '.Settings::read('expire_games').' days of inactivity.' , ); // make sure this user is not full $submit_button = '<div><input type="submit" name="invite" value="Send Invitation" /></div>'; $warning = ''; if ($GLOBALS['Player']->max_games && ($GLOBALS['Player']->max_games <= $GLOBALS['Player']->current_games)) { $submit_button = $warning = '<p class="warning">You have reached your maximum allowed games, you can not create this game !</p>'; } $contents = <<< EOF <form method="post" action="{$_SERVER['REQUEST_URI']}" id="send"><div class="formdiv"> <input type="hidden" name="token" value="{$_SESSION['token']}" /> <input type="hidden" name="player_id" value="{$_SESSION['player_id']}" /> {$warning} <div><label for="opponent">Opponent</label><select id="opponent" name="opponent">{$opponent_selection}</select></div> <div><label for="setup">Setup</label><select id="setup" name="setup">{$setup_selection}</select> <a href="#setup_display" id="show_setup" class="options">Show Setup</a></div> <div><label for="color">Your Color</label><select id="color" name="color"><option value="random">Random</option><option value="white">Silver</option><option value="black">Red</option></select></div> <div class="random_convert options"> <fieldset> <legend>Conversion</legend> <p> If your random game is a v1.0 game, you can convert it to play v2.0 Pharaoh.<br /> Or, if your random game is a v2.0 game, you can convert it to play v1.0 Pharaoh.<br /> </p> <p> When you select to convert, more options may be shown below. </p> <div><label class="inline"><input type="checkbox" id="rand_convert_to_1" name="rand_convert_to_1" /> Convert to 1.0</label></div> <div><label class="inline"><input type="checkbox" id="rand_convert_to_2" name="rand_convert_to_2" /> Convert to 2.0</label></div> </fieldset> </div> <!-- .random_convert --> <div class="pharaoh_1 options"> <fieldset> <legend>v1.0 Options</legend> <p class="conversion"> Here you can convert v1.0 setups to play v2.0 Pharaoh.<br /> The conversion places a Sphynx in your lower-right corner facing upwards (and opposite for your opponent) and converts any double-stacked Obelisks to Anubises which face forward. </p> <p class="conversion"> When you select to convert, more options will be shown below, as well as the "Show Setup" link will show the updated setup. </p> <div class="conversion"><label class="inline"><input type="checkbox" id="convert_to_2" name="convert_to_2" /> Convert to 2.0</label></div> </fieldset> </div> <!-- .pharaoh_1 --> <div class="pharaoh_2 p2_box options"> <fieldset> <legend>v2.0 Options</legend> <p class="conversion"> Here you can convert the v2.0 setups to play v1.0 Pharaoh.<br /> The conversion removes any Sphynxes from the board and converts any Anubises to double-stacked Obelisks. </p> <p class="conversion"> When you select to convert, the "Show Setup" link will show the updated setup. </p> <div class="conversion"><label class="inline"><input type="checkbox" id="convert_to_1" name="convert_to_1" /> Convert to 1.0</label></div> <div class="pharaoh_2"><label class="inline"><input type="checkbox" id="move_sphynx" name="move_sphynx" /> Sphynx is movable</label></div> </fieldset> </div> <!-- .pharaoh_2 --> <fieldset> <legend><label class="inline"><input type="checkbox" name="laser_battle_box" id="laser_battle_box" class="fieldset_box" /> Laser Battle</label></legend> <div id="laser_battle" class="options"> <p> When a laser gets shot by the opponents laser, it will be disabled for a set number of turns, making that laser unable to shoot until those turns have passed.<br /> After those turns have passed, and the laser has recovered, it will be immune from further shots for a set number of turns.<br /> After the immunity turns have passed, whether or not the laser was shot again, it will now be susceptible to being shot again. <span class="pharaoh_2"><br />You can also select if the Sphynx is hittable only in the front, or on all four sides.</span> </p> <div><label for="battle_dead">Dead for:</label><input type="text" id="battle_dead" name="battle_dead" size="4" /> <span class="info">(Default: 1; Minimum: 1)</span></div> <div><label for="battle_immune">Immune for:</label><input type="text" id="battle_immune" name="battle_immune" size="4" /> <span class="info">(Default: 1; Minimum: 0)</span></div> <div class="pharaoh_2"><label class="inline"><input type="checkbox" id="battle_front_only" name="battle_front_only" checked="checked" /> Only front hits on Sphynx count</label></div> <!-- <div class="pharaoh_2"><label class="inline"><input type="checkbox" id="battle_hit_self" name="battle_hit_self" /> Hit Self</label></div> --> <p>You can set the "Immune for" value to 0 to allow a laser to be shot continuously, but the minimum value for the "Dead for" value is 1, as it makes no sense otherwise.</p> </div> <!-- #laser_battle --> </fieldset> {$submit_button} <div class="clr"></div> </div></form> <div id="setup_display"></div> EOF; // create our invitation tables list($in_vites, $out_vites, $open_vites) = Game::get_invites($_SESSION['player_id']); $contents .= <<< EOT <form method="post" action="{$_SERVER['REQUEST_URI']}"><div class="formdiv" id="invites"> EOT; $table_meta = array( 'sortable' => true , 'no_data' => '<p>There are no received invites to show</p>' , 'caption' => 'Invitations Received' , ); $table_format = array( array('Invitor', 'invitor') , array('Setup', '<a href="#[[[board]]]" class="setup" id="s_[[[setup_id]]]">[[[setup]]]</a>') , array('Color', 'color') , array('Extra', '<abbr title="[[[hover_text]]]">Hover</abbr>') , array('Date Sent', '###date(Settings::read(\'long_date\'), strtotime(\'[[[create_date]]]\'))', null, ' class="date"') , array('Action', '<input type="button" id="accept-[[[game_id]]]" value="Accept" /><input type="button" id="decline-[[[game_id]]]" value="Decline" />', false) , ); $contents .= get_table($table_format, $in_vites, $table_meta); $table_meta = array( 'sortable' => true , 'no_data' => '<p>There are no sent invites to show</p>' , 'caption' => 'Invitations Sent' , ); $table_format = array( array('Invitee', '###ifenr(\'[[[invitee]]]\', \'-- OPEN --\')') , array('Setup', '<a href="#[[[board]]]" class="setup" id="s_[[[setup_id]]]">[[[setup]]]</a>') , array('Color', 'color') , array('Extra', '<abbr title="[[[hover_text]]]">Hover</abbr>') , array('Date Sent', '###date(Settings::read(\'long_date\'), strtotime(\'[[[create_date]]]\'))', null, ' class="date"') , array('Action', '###\'<input type="button" id="withdraw-[[[game_id]]]" value="Withdraw" />\'.((strtotime(\'[[[create_date]]]\') >= strtotime(\'[[[resend_limit]]]\')) ? \'\' : \'<input type="button" id="resend-[[[game_id]]]" value="Resend" />\')', false) , ); $contents .= get_table($table_format, $out_vites, $table_meta); $table_meta = array( 'sortable' => true , 'no_data' => '<p>There are no open invites to show</p>' , 'caption' => 'Open Invitations' , ); $table_format = array( array('Invitor', 'invitor') , array('Setup', '<a href="#[[[board]]]" class="setup" id="s_[[[setup_id]]]">[[[setup]]]</a>') , array('Color', 'color') , array('Extra', '<abbr title="[[[hover_text]]]">Hover</abbr>') , array('Date Sent', '###date(Settings::read(\'long_date\'), strtotime(\'[[[create_date]]]\'))', null, ' class="date"') , array('Action', '<input type="button" id="accept-[[[game_id]]]" value="Accept" />', false) , ); $contents .= get_table($table_format, $open_vites, $table_meta); $contents .= <<< EOT </div></form> EOT; echo get_header($meta); echo get_item($contents, $hints, $meta['title']); call($GLOBALS); echo get_footer($meta); diff --git a/scripts/index.js b/scripts/index.js index e86b0a1..4d330d0 100644 --- a/scripts/index.js +++ b/scripts/index.js @@ -1,133 +1,133 @@ // index javascript var reload = true; // do not change this var refresh_timer = false; var refresh_timeout = 30001; // 30 seconds $(document).ready( function( ) { // make the table row clicks work - $('.datatable tbody tr').css('cursor', 'pointer').click( function( ) { + $('.datatable tbody tr:not(tr.lowlight)').css('cursor', 'pointer').click( function( ) { var id = $(this).attr('id').substr(1); var state = $($(this).children( )[2]).text( ); //* -- SWITCH -- if (state == 'Waiting') { window.location = 'join.php?id='+id+debug_query_; } else { window.location = 'game.php?id='+id+debug_query_; } //*/ }); // blinky menu items $('.blink').fadeOut( ).fadeIn( ).fadeOut( ).fadeIn( ).fadeOut( ).fadeIn( ); // chat box functions $('#chatbox form').submit( function( ) { if ('' == $.trim($('#chatbox input#chat').val( ))) { return false; } if (debug) { window.location = 'ajax_helper.php'+debug_query+'&'+$('#chatbox form').serialize( ); return false; } $.ajax({ type: 'POST', url: 'ajax_helper.php', data: $('#chatbox form').serialize( ), success: function(msg) { var reply = JSON.parse(msg); if (reply.error) { alert(reply.error); } else { var entry = '<dt>'+reply.username+'</dt>'+ '<dd>'+reply.message+'</dd>'; $('#chats').prepend(entry); $('#chatbox input#chat').val(''); } } }); return false; }); // run the sounds if (('#refresh' == document.location.hash) && turn_msg_count) { $('#sounds').jPlayer({ ready: function ( ) { $(this).jPlayer('setMedia', { mp3: 'sounds/message.mp3', oga: 'sounds/message.ogg' }).jPlayer('play'); }, volume: 1, swfPath: 'scripts' }); } // run the ajax refresher ajax_refresh( ); // set some things that will halt the timer $('#chatbox form input').focus( function( ) { clearTimeout(refresh_timer); }); $('#chatbox form input').blur( function( ) { if ('' != $(this).val( )) { refresh_timer = setTimeout('ajax_refresh( )', refresh_timeout); } }); }); var jqXHR = false; function ajax_refresh( ) { // no debug redirect, just do it // only run this if the previous ajax call has completed if (false == jqXHR) { jqXHR = $.ajax({ type: 'POST', url: 'ajax_helper.php', data: 'timer=1', success: function(msg) { if (('' != msg) && (msg != turn_msg_count)) { // we don't want to play sounds when they hit the page manually // so set a hash on the URL that we can test when we embed the sounds // we don't care what the hash is, just refresh if there is a hash // (the user may have silenced the sounds with #silent) if ('' != window.location.hash) { if (reload) { window.location.reload( ); } } else { // stick the hash on the end of the URL window.location = window.location.href+'#refresh' if (reload) { window.location.reload( ); } } } } }).always( function( ) { jqXHR = false; }); } // successively increase the timeout time in case someone // leaves their window open, don't poll the server every // 30 seconds for the rest of time if (0 == (refresh_timeout % 5)) { refresh_timeout += Math.floor(refresh_timeout * 0.001) * 1000; } ++refresh_timeout; refresh_timer = setTimeout('ajax_refresh( )', refresh_timeout); } diff --git a/scripts/invite.js b/scripts/invite.js index c1ebddc..84969c9 100644 --- a/scripts/invite.js +++ b/scripts/invite.js @@ -1,300 +1,300 @@ var reload = true; // do not change this var new_setup = false; function check_fieldset_box( ) { $('input.fieldset_box').each( function(i, elem) { var $this = $(this); var id = $this.attr('id').slice(0,-4); if ($this.prop('checked')) { $('div#'+id).show( ); } else { $('div#'+id).hide( ); } }); } $(document).ready( function( ) { // hide the setup div $('div#setup_display').hide( ); check_fieldset_box( ); show_link( ); show_version( ); // show the setup div in a fancybox $('a#show_setup').fancybox({ padding : 10, onStart : function( ) { var setup = setups[$('select#setup').val( )]; if (new_setup) { setup = new_setup; } $('div#setup_display') .empty( ) .append(create_board(setup)) .show( ); }, onClosed :function( ) { $('div#setup_display').hide( ); } }); // only show the setup link when a setup is selected $('select#setup').change( function( ) { show_link( ); show_version( ); }); $('input#convert_to_1, input#convert_to_2, input#rand_convert_to_1, input#rand_convert_to_2').change( function( ) { show_version( ); }); // show the setup div for the invites $('a.setup').fancybox({ type : 'inline', href : '#setup_display', padding : 10, onStart : function(arr, idx, opts) { var $elem = $(arr[idx]); var setup = setups[$(arr[idx]).attr('id').slice(2)]; if ('#setup_display' != $elem.attr('href')) { setup = $elem.attr('href').slice(1); } $('div#setup_display') .empty( ) .append(create_board(setup)) .show( ); }, onClosed :function( ) { $('div#setup_display').hide( ); } }); $('form#send').submit( function( ) { if ( ! $('select#setup').val( )) { alert('You must select a setup'); return false; } return true; }); // hide the collapsable fieldsets - $('input.fieldset_box').change( function( ) { + $('input.fieldset_box').on('change', function( ) { check_fieldset_box( ); }); // this runs all the ...vites $('div#invites input').click( function( ) { var $this = $(this); var id = $this.attr('id').split('-'); if ('accept' == id[0]) { // invites and openvites // accept the invite if (debug) { window.location = 'ajax_helper.php'+debug_query+'&'+'invite=accept&game_id='+id[1]; return; } $.ajax({ type: 'POST', url: 'ajax_helper.php', data: 'invite=accept&game_id='+id[1], success: function(msg) { if ('ERROR' == msg.slice(0, 5)) { alert(msg); if (reload) { window.location.reload( ); } } else { window.location = 'game.php?id='+msg+debug_query_; } return; } }); } else if ('resend' == id[0]) { // resends outvites // resend the invite if (debug) { window.location = 'ajax_helper.php'+debug_query+'&'+'invite=resend&game_id='+id[1]; return; } $.ajax({ type: 'POST', url: 'ajax_helper.php', data: 'invite=resend&game_id='+id[1], success: function(msg) { alert(msg); if ('ERROR' == msg.slice(0, 5)) { if (reload) { window.location.reload( ); } } else { // remove the resend button $this.remove( ); } return; } }); } else { // invites decline and outvites withdraw // delete the invite if (debug) { window.location = 'ajax_helper.php'+debug_query+'&'+'invite=delete&game_id='+id[1]; return; } $.ajax({ type: 'POST', url: 'ajax_helper.php', data: 'invite=delete&game_id='+id[1], success: function(msg) { alert(msg); if ('ERROR' == msg.slice(0, 5)) { if (reload) { window.location.reload( ); } } else { // remove the parent TR $this.parent( ).parent( ).remove( ); } return; } }); } }); }); function show_link( ) { if (0 != $('select#setup').val( )) { $('a#show_setup').show( ); } else { $('a#show_setup').hide( ); } } function show_version( ) { if (0 != $('select#setup').val( )) { if (setups[$('select#setup').val( )].match(/[efjk]/i)) { $('.random_convert').hide( ); $('.pharaoh_1').hide( ); $('.pharaoh_2').show( ); $('.pharaoh_2 .conversion').show( ); if ($('input#convert_to_1').prop('checked')) { $('.pharaoh_2').hide( ); $('.p2_box').show( ); convert_setup(1); } else { new_setup = false; } } else { $('.random_convert').hide( ); $('.pharaoh_2').hide( ); $('.pharaoh_1').show( ); if ($('input#convert_to_2').prop('checked')) { $('.pharaoh_2').show( ); $('.pharaoh_2 .conversion').hide( ); convert_setup(2); } else { new_setup = false; } } } else { $('.pharaoh_1, .pharaoh_2').hide( ); $('.random_convert').show( ); if ($('input#rand_convert_to_2').prop('checked')) { $('.pharaoh_2').show( ); $('.pharaoh_2 .conversion').hide( ); } } } function convert_setup(to) { to = parseInt(to || 1); var setup = setups[$('select#setup').val( )]; // the p1 pieces are repeated here for the TO v1 conversion // just make sure that the TO v2 conversion pieces are listed first // that way they will get converted and be correct var p1 = ['w','w','w','w','W','W','W','W']; var p2 = ['n','l','m','o','L','M','N','O']; switch (to) { case 1 : // swap out the anubises with obelisks new_setup = str_replace(p2, p1, setup); // remove the sphynxes new_setup = new_setup.replace(/[efjk]/ig, '0'); break; case 2 : // swap out the obelisks with anubises new_setup = str_replace(p1, p2, setup); // replace anything on the laser corners with a sphynx new_setup = new_setup.replaceAt(0, 'j').replaceAt(79, 'E'); break; } return new_setup; } // http://phpjs.org/functions/str_replace:527 function str_replace(search, replace, subject, count) { var i = 0, j = 0, temp = '', repl = '', sl = 0, fl = 0, f = [].concat(search), r = [].concat(replace), s = subject, ra = Object.prototype.toString.call(r) === '[object Array]', sa = Object.prototype.toString.call(s) === '[object Array]'; s = [].concat(s); if (count) { this.window[count] = 0; } for (i = 0, sl = s.length; i < sl; i++) { if (s[i] === '') { continue; } for (j = 0, fl = f.length; j < fl; j++) { temp = s[i] + ''; repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0]; s[i] = (temp).split(f[j]).join(repl); if (count && s[i] !== temp) { this.window[count] += (temp.length - s[i].length) / f[j].length; } } } return sa ? s : s[0]; } String.prototype.replaceAt = function(index, str) { index = parseInt(index); return this.slice(0, index) + str + this.slice(index + str.length); }
benjamw/pharaoh
4df3a59ded13940d09450586402799762f71fcc7
recognize immediate hits on the laser
diff --git a/classes/pharaoh.class.php b/classes/pharaoh.class.php index 4989dfc..5fc328d 100644 --- a/classes/pharaoh.class.php +++ b/classes/pharaoh.class.php @@ -1,1030 +1,1047 @@ <?php /* +--------------------------------------------------------------------------- | | pharaoh.class.php (php 5.x) | | by Benjam Welker | http://iohelix.net | +--------------------------------------------------------------------------- | | This module is built to play the game of Pharaoh (Khet), it cares not about | database structure or the goings on of the website, only about Pharaoh | +--------------------------------------------------------------------------- | | > Pharaoh game module | > Date started: 2009-12-22 | | > Module Version Number: 0.8.0 | +--------------------------------------------------------------------------- */ // set some constants for laser path directions // directions are stored as values to add to // current board index to get next board index // when travelling in that direction define('I_RIGHT', 1); define('I_LEFT', -1); define('I_UP', -10); define('I_DOWN', 10); class Pharaoh { /** * PROPERTIES * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** static public property EXTRA_INFO_DEFAULTS * Holds the default extra info data * Values: * - move_sphynx (laser) - boolean default false * - battle_front_only (sphynx) - boolean default true - hit sphynx in front only (n/a for Khet 1.0) * - battle_hit_self (sphynx) - boolean default false - hit your own sphynx (from side only) (n/a for Khet 1.0) * * @var array */ static public $EXTRA_INFO_DEFAULTS = array( 'move_sphynx' => false, 'battle_front_only' => true, 'battle_hit_self' => false, ); /** public property players * Holds our player's data * format: (indexed by player_id then associative) * array( * player_id => array('player_id', 'color', 'turn', 'extra_info' => array( ... )) , * player_id => array('player_id', 'color', 'turn', 'extra_info' => array( ... )) , * 'silver' => reference to $this->players[silver_player_id] , * 'red' => reference to $this->players[red_player_id] , * 'player' => reference to $this->players[player_id] , * 'opponent' => reference to $this->players[opponent_id] , * ) * * extra_info is an array that holds information about the current player state * * @var array of player data * @info not used yet */ public $players; /** public property current_player * The current player's id * * @var int * @info not used yet */ public $current_player; /** public property winner * Holds the winner * 'silver' or 'red' (or 'draw') * * @var string */ public $winner; /** protected property _board * Holds the game board * * @var string */ protected $_board; /** public property has_sphynx * True if there is a sphynx on the board * * @var bool board has sphynx */ public $has_sphynx; /** protected property _move * Holds the last move * * @var string */ protected $_move; /** protected property _laser_path * Holds the path the laser took * around the board * array( * array([board index], [incoming direction]), * array([board index], [incoming direction]), * ... * ) * * Path is not necessarily continuous * ... but most likely * * @var array */ protected $_laser_path; /** protected property _hits * Holds the indexes of pieces hit * * @var array of int board indexes */ protected $_hits; /** protected property laser_hit * Holds the laser hit flag * * @var bool did we hit the laser? */ protected $laser_hit = false; /** protected property _extra_info * Holds the extra info for the game * * @see $EXTRA_INFO_DEFAULTS * @var array */ protected $_extra_info; /** * METHODS * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** public function __construct * Class constructor * Sets all outside data * * @param void * @action instantiates object * @return void */ public function __construct( ) { call(__METHOD__); } /** public function __get * Class getter * Returns the requested property if the * requested property is not _private * * @param string property name * @return mixed property value */ public function __get($property) { if ( ! property_exists($this, $property)) { throw new MyException(__METHOD__.': Trying to access non-existent property ('.$property.')', 2); } if ('_' === $property[0]) { throw new MyException(__METHOD__.': Trying to access _private property ('.$property.')', 2); } return $this->$property; } /** public function __set * Class setter * Sets the requested property if the * requested property is not _private * * @param string property name * @param mixed property value * @action optional validation * @return bool success */ public function __set($property, $value) { switch ($property) { case 'board' : try { $this->set_board($value); } catch (MyException $e) { throw $e; } return; break; default : // do nothing break; } if ( ! property_exists($this, $property)) { throw new MyException(__METHOD__.': Trying to access non-existent property ('.$property.')', 3); } if ('_' === $property[0]) { throw new MyException(__METHOD__.': Trying to access _private property ('.$property.')', 3); } $this->$property = $value; } /** public function __toString * Returns the ascii version of the board * when asked to output the object * * @param void * @return string ascii version of the board */ public function __toString( ) { return $this->_get_board_ascii( ); } /** public function set_extra_info * Sets the extra info for the game * * @param array extra game info * @return void */ public function set_extra_info($extra_info) { call(__METHOD__); $this->_extra_info = self::extra_info($extra_info); } /** public function get_extra_info * Returns the extra info for the game * * @param void * @return array extra game info */ public function get_extra_info( ) { call(__METHOD__); $diff = array_compare($this->_extra_info, self::$EXTRA_INFO_DEFAULTS); $extra_info = $diff[0]; ksort($extra_info); return $extra_info; } /** public function do_move * Performs the given move * and then calls the laser firing method (if needed) * Move syntax: * -move: from:to e.g.- B4:B5 * - if splitting an obelisk tower, replace : with . * - e.g.- B4.B5 * -rotate: square-direction (0 = CCW, 1 = CW)) e.g.- B4-0 * * @param string move * @param bool whether or not to fire the laser after the move * @return array pieces hit if laser fired or string board after move */ public function do_move($move, $fire_laser = true) { call(__METHOD__); call($move); $fire_laser = (bool) $fire_laser; call($fire_laser); $index = self::target_to_index(substr($move, 0, 2)); // grab the color of the current piece $piece = $this->_board[$index]; $color = self::get_piece_color($piece); // check for move or rotate try { if ('-' == $move[2]) { // rotate $this->_rotate_piece($index, $move[3]); } else { // move $this->_move_piece($index, self::target_to_index(substr($move, 3, 2)), (':' == $move[2])); } } catch (MyException $e) { throw $e; } $this->_move = $move; // if we're not firing the laser, return the current board if ( ! $fire_laser) { call('NOT FIRING LASER'); call($this->_board); return $this->_board; } $hits = $this->_fire_laser($color); $this->_hits = $hits; foreach ($hits as $hit) { // check if we hit a pharaoh if ('p' == $this->_board[$hit]) { if (in_array($this->winner, array('red', 'draw'))) { $this->winner = 'draw'; } else { $this->winner = 'silver'; } } elseif ('P' == $this->_board[$hit]) { if (in_array($this->winner, array('silver', 'draw'))) { $this->winner = 'draw'; } else { $this->winner = 'red'; } } // remove the piece // or remove one of the stacked obelisks if ('W' == $this->_board[$hit]) { $this->_board[$hit] = 'V'; } elseif ('w' == $this->_board[$hit]) { $this->_board[$hit] = 'v'; } else { $this->_board[$hit] = '0'; } } call($this->_get_board_ascii( )); return $hits; } /** protected function _fire_laser * FIRE ZEE MISSILES !!! * But I am le tired * * Fires the laser of the given color * * @param string color (red or silver) * @action creates $this->_laser_path array * @return array of squares hit (empty array if none) */ protected function _fire_laser($color) { try { $return = self::fire_laser($color, $this->_board, $this->_extra_info); $this->_laser_path = $return['laser_path']; $this->laser_hit = $return['laser_hit']; return $return['hits']; } catch (MyException $e) { throw $e; } } /** static public function fire_laser * FIRE ZEE MISSILES !!! * But I am le tired * * Fires the laser of the given color * * @param string color (red or silver) * @param string board (expanded FEN) * @param array [optional] extra info * @return array (laser path array, and squares hit (empty array if none) array) */ static public function fire_laser($color, $board, $extra_info = false) { call(__METHOD__); // search for the sphynx in the board $has_sphynx = Setup::has_sphynx($board); $color = strtolower($color); $board = expandFEN($board); $extra_info = self::extra_info($extra_info); call($color); call($board); call($extra_info); if ( ! in_array($color, array('silver', 'red'))) { throw new MyException(__METHOD__.': Trying to fire laser for unknown color: '.$color); } $reflections = array( // pyramid 'A' => array(I_LEFT => I_UP, I_DOWN => I_RIGHT), // .\ 'B' => array(I_LEFT => I_DOWN, I_UP => I_RIGHT), // `/ 'C' => array(I_RIGHT => I_DOWN, I_UP => I_LEFT), // \` 'D' => array(I_RIGHT => I_UP, I_DOWN => I_LEFT), // /. // djed 'X' => array( // \ I_RIGHT => I_DOWN, I_LEFT => I_UP, I_DOWN => I_RIGHT, I_UP => I_LEFT, ), 'Y' => array( // / I_RIGHT => I_UP, I_LEFT => I_DOWN, I_DOWN => I_LEFT, I_UP => I_RIGHT, ), // eye of horus 'H' => array( // \ I_RIGHT => array(I_RIGHT, I_DOWN), I_LEFT => array(I_LEFT, I_UP), I_DOWN => array(I_RIGHT, I_DOWN), I_UP => array(I_LEFT, I_UP), ), 'I' => array( // / I_RIGHT => array(I_RIGHT, I_UP), I_LEFT => array(I_LEFT, I_DOWN), I_DOWN => array(I_LEFT, I_DOWN), I_UP => array(I_RIGHT, I_UP), ), ); // fire the laser if ( ! $has_sphynx) { if ('silver' == $color) { $laser_path = array(array(array(79, I_UP))); } else { // red $laser_path = array(array(array(0, I_DOWN))); } } else { - list($shoot_sphynx_idx, $shoot_sphynx_dir) = self::find_sphynx($board, ('silver' == $color)); - list($hit_sphynx_idx, $hit_sphynx_dir) = self::find_sphynx($board, ('silver' != $color)); + list($shoot_sphynx_idx, $shoot_sphynx_dir) = self::find_sphynx($board, ('silver' === $color)); + list($hit_sphynx_idx, $hit_sphynx_dir) = self::find_sphynx($board, ('silver' !== $color)); $laser_path = array(array(array($shoot_sphynx_idx + $shoot_sphynx_dir, $shoot_sphynx_dir))); } // because we can now possibly move the laser around and rotate it // make sure we don't hit a wall right out of the gate // check if we hit a wall list($current, $dir) = $laser_path[0][0]; $long_wall = (0 > $current) || (80 <= $current); $short_wall = (1 == abs($dir)) && (floor($current / 10) !== floor(($current - $dir) / 10)); if ($long_wall || $short_wall) { // we hit the wall... just stop $laser_path[0][0][0] = false; - return array('laser_path' => $laser_path, 'hits' => array( ), 'hit_laser' => false); + return array('laser_path' => $laser_path, 'hits' => array( ), 'laser_hit' => false); + } + + // also check and make sure that the sphynx was not hit right out of the gate + $hit_silver = $hit_red = false; + $var_name = 'hit_'.(('silver' == $color) ? 'silver' : 'red'); + if ($has_sphynx && ($hit_sphynx_idx == $current)) { + if ( ! $extra_info['battle_front_only']) { + ${$var_name} = true; + } + elseif ($hit_sphynx_dir == -$dir) { + ${$var_name} = true; + } + } + if ($hit_red || $hit_silver) { + // we hit the sphynx... just stop + $laser_path[] = array(array(true, $dir)); + return array('laser_path' => $laser_path, 'hits' => array( ), 'laser_hit' => true); } $i = 0; // infinite loop protection $paths = $laser_path[0]; $used = array( ); $next = array( ); $hits = array( ); $laser_hit = false; while ($i < 999) { // no ad infinitum here $split = 0; $continue = false; foreach ($paths as $key => $node) { if ((false === $node[0]) || (true === $node[0])) { unset($node[2]); $next[$key] = $node; // propagate the individual path indexes continue; } // let the loop know we still have valid nodes $continue = true; // current is the current board index // dir is the direction that the laser was heading // when it entered the current index list($current, $dir) = $node; // check the current location for a piece - if ('0' != ($piece = $board[$current])) { + if ('0' !== ($piece = $board[$current])) { // check for hit or reflection if ( ! isset($reflections[strtoupper($piece)][$dir])) { // dont track the hit for the following situations: // is an anubis and hit the front $front_anubis = (preg_match('/[LMNO]/i', $piece) && ($dir == -self::get_anubis_dir($piece))); // hit the sphynx (laser hits get tracked elsewhere) $hit_sphynx = ($has_sphynx && (($current == $hit_sphynx_idx) || ($current == $shoot_sphynx_idx))); // if any of those hit, don't track the hit if ( ! ($front_anubis || $hit_sphynx)) { $hits[] = $current; } // but still change the path data to recognize the path stopped // we store dir here because it keeps the output format consistent // we don't really care at this point because we just hit a piece // ... the laser isn't going any further $next[$key] = array(true, $dir); // stop this path continue; } $dir = $reflections[strtoupper($piece)][$dir]; } // this is where we split off in two directions through the beam splitter $do_split = false; if (is_array($dir)) { // add a new entry in the paths for the reflection // and change dir to be the pass-through beam // if we've already split a beam once, // we'll need to add a few more to the index // (it is possible to hit a single splitter from two sides, // as well as hit both splitters from two sides, so...) // also note: if there are no beam splitters, there is no way // of doubling back or going over the same path again, ever // before we add to $next, make sure we haven't been here, or hit any walls $do_split = true; $split_dir = $dir[0]; $split_current = $current + $split_dir; // make sure we haven't been here before if (in_array(array($split_current, $split_dir), $used, true)) { // don't even create a new path $do_split = false; } else { // check if we hit the laser $hit_silver = $hit_red = false; if ( ! $has_sphynx) { $hit_red = (-10 == $split_current) && ('silver' == $color); $hit_silver = (89 == $split_current) && ('red' == $color); } else { // find the laser $var_name = 'hit_'.(('silver' == $color) ? 'silver' : 'red'); if ($hit_sphynx_idx == $split_current) { if ( ! $extra_info['battle_front_only']) { ${$var_name} = true; } elseif ($hit_sphynx_dir == -$split_dir) { ${$var_name} = true; } } } if ($hit_red || $hit_silver) { $laser_hit = true; } // check if we hit a wall $long_wall = (0 > $split_current) || (80 <= $split_current); $short_wall = (1 == abs($split_dir)) && (floor($split_current / 10) !== floor(($split_current - $split_dir) / 10)); if ($long_wall || $short_wall) { // set split_current to false, so we know we hit a wall, // but keep going, we need to store the dir so we can show any reflection properly // and we need to add the new path index below // we store dir here because we need to know in which direction the laser left the node // for edge/corner piece hits that send the laser through the wall $split_current = false; } $next[count($paths) + $split] = array($split_current, $split_dir); if (false !== $split_current) { $used[] = array($split_current, $split_dir); } $split += 1; } // now that the split is done, go back and keep processing the new path $dir = $dir[1]; } // increment $current and run a few tests // so we don't shoot through walls // or loop back on ourselves forever $current += $dir; // make sure we haven't been here before if (in_array(array($current, $dir), $used, true)) { // we store dir here because it keeps the output format consistent // we don't really care at this point because we've been here before // and know what's going to happen $next[$key] = array(false, $dir); // stop this path continue; } // check if we hit the laser $hit_silver = $hit_red = false; if ( ! $has_sphynx) { $hit_red = (-10 == $current) && ('silver' == $color); $hit_silver = (89 == $current) && ('red' == $color); } else { $var_name = 'hit_'.(('silver' == $color) ? 'silver' : 'red'); if ($hit_sphynx_idx == $current) { if ( ! $extra_info['battle_front_only']) { ${$var_name} = true; } elseif ($hit_sphynx_dir == -$dir) { ${$var_name} = true; } } } if ($hit_red || $hit_silver) { $laser_hit = true; } // check if we hit a wall $long_wall = (0 > $current) || (80 <= $current); $short_wall = (1 == abs($dir)) && (floor($current / 10) !== floor(($current - $dir) / 10)); if ($long_wall || $short_wall) { // set current to false, so we know we hit a wall, // but keep going, we need to store the dir so we can show any reflection properly // and we need to add the new path index below // we store dir here because we need to know which direction the laser left the node in // for corner piece hits that send the laser through the wall $current = false; } $next[$key] = array($current, $dir); if ($do_split) { // add the new path index here so we know which path was the original path // and where are the splits came from $next[$key][2] = count($paths) + $split - 1; } if (false !== $current) { $used[] = array($current, $dir); } } // end foreach $current // if we have no valid nodes left // break the loop if ( ! $continue) { break; } // add to our laser path // and pass along to the next round $laser_path[] = $paths = $next; ++$i; // keep those pesky infinite loops at bay } // end while call(self::get_laser_ascii($board, $laser_path)); call($hits); // straighten up the laser path array_walk($laser_path, create_function('& $val', 'ksort($val);')); return compact('laser_path', 'hits', 'laser_hit'); } /** static public function find_sphynx * Finds the sphynx on the board and * returns both the index and orientation * * @param string expanded board * @param bool [optional] silver * @return array sphynx index, orientation */ static public function find_sphynx($board, $silver = true) { $sphynxes = ($silver) ? array('E','F','J','K') : array('e','f','j','k'); // find the sphynx foreach ($sphynxes as $sphynx) { if (false !== ($idx = strpos($board, $sphynx))) { break; } } if ( ! isset($idx)) { throw new MyException(__METHOD__.': Sphynx not found on board'); } // get the orientation switch (strtoupper($sphynx)) { case 'E' : $dir = I_UP; break; case 'F' : $dir = I_RIGHT; break; case 'J' : $dir = I_DOWN; break; case 'K' : $dir = I_LEFT; break; } return array($idx, $dir); } /** static public function get_anubis_dir * Gets the direction the anubis is facing * * @param string piece * @return int anubis direction (or false otherwise) */ static public function get_anubis_dir($piece) { switch (strtoupper($piece)) { case 'L' : return I_UP; break; case 'M' : return I_RIGHT; break; case 'N' : return I_DOWN; break; case 'O' : return I_LEFT; break; } return false; } /** public function get_laser_path * Returns the laser path array * * @param void * @return array laser path */ public function get_laser_path( ) { return $this->_laser_path; } /** public function set_board * Tests and sets the board * * @param string expanded FEN of board * @return void */ public function set_board($xFEN) { call(__METHOD__); call($xFEN); // test the board and make sure all is well if (80 != strlen($xFEN)) { throw new MyException(__METHOD__.': Board is not the right size'); } $this->_board = $xFEN; $this->has_sphynx = Setup::has_sphynx($this->_board); call($this->_get_board_ascii( )); } /** public function get_board * Returns the board * * @param void * @return string expanded FEN of board */ public function get_board( ) { call(__METHOD__); return $this->_board; } /** public function get_move * Returns the latest move and hits * * @param void * @return array string move, array hits */ public function get_move( ) { call(__METHOD__); return array( 0 => $this->_move, 'move' => $this->_move, 1 => $this->_hits, 'hits' => $this->_hits, ); } /** protected function _move_piece * Tests and moves a piece * * @param int board from index * @param int board to index * @param bool optional move both obelisks * @return void */ protected function _move_piece($from_index, $to_index, $both_obelisks = true) { call(__METHOD__); $from_index = (int) $from_index; $to_index = (int) $to_index; $both_obelisks = (bool) $both_obelisks; call($from_index); call($to_index); call($both_obelisks); $piece = $this->_board[$from_index]; $to_piece = $this->_board[$to_index]; $silver = ($piece == strtoupper($piece)); call($piece); call($to_piece); call($silver); // check for a piece on the from square if ('0' == $piece) { throw new MyException(__METHOD__.': No piece found to move'); } // check for only one square away $difference = abs($from_index - $to_index); if (0 == $difference) { throw new MyException(__METHOD__.': The from square and to square are the same'); } if ( ! in_array($difference, array(1, 9, 10, 11))) { throw new MyException(__METHOD__.': Piece can only move one square'); } // TODO: this needs work, it works, but it's not pretty // TOWER: this is going to get _complicated_ // check for moving off edge of board $off_vertical = ((0 > $to_index) || (80 <= $to_index)); $off_horizontal = ((1 == abs($from_index - $to_index)) && (floor($to_index / 10) !== floor($from_index / 10))); if ($off_vertical || $off_horizontal) { throw new MyException(__METHOD__.': Piece cannot move off the edge of the board'); } // TODO: this needs work, it works, but it's not pretty // check for wrong color piece moving onto a colored square $not_silver = array(0, 10, 20, 30, 40, 50, 60, 70, 8, 78); $not_red = array(9, 19, 29, 39, 49, 59, 69, 79, 1, 71); $color_array = 'not_'.self::get_piece_color($piece); if (in_array($to_index, ${$color_array})) { throw new MyException(__METHOD__.': Cannot move onto square of opposite color'); } // TODO: this needs work, it works, but it's not pretty // TOWER: test for moving a pharaoh into a corner of the tower // it's not allowed // check for trying to move stationary sphynx if (in_array(strtoupper($piece), array('E','F','J','K')) && ! $this->_extra_info['move_sphynx']) { throw new MyException(__METHOD__.': Cannot move stationary sphynx'); } // check for a piece in the way if ('0' != $to_piece) { $to_color_array = 'not_'.self::get_piece_color($to_piece); // make sure we are not moving obelisks around if (in_array(strtoupper($piece), array('V','W')) && ('V' != strtoupper($to_piece))) { throw new MyException(__METHOD__.': Target square not empty - '.$piece); } // both the Djed and Eye of Horus can swap places with other pieces // as well as swapping a single and double obelisk tower if the from is double elseif ( ! in_array(strtoupper($piece), array('H','I','X','Y','W','V'))) { throw new MyException(__METHOD__.': Target square not empty - '.$piece); } // but only with pyramids, obelisks, or anubises elseif ( ! in_array(strtoupper($to_piece), array('A','B','C','D','V','W','L','M','N','O'))) { throw new MyException(__METHOD__.': Target piece not swappable - '.$to_piece); } // make sure the swapped piece isn't going onto an off-color square elseif (in_array($from_index, ${$to_color_array})) { throw new MyException(__METHOD__.': Target piece not swappable due to ending on opposite color square - '.$to_piece.': '.self::get_piece_color($to_piece).' on '.self::get_piece_color($piece)); } } // make sure we are not trying to split a non-obelisk tower (or single tower) if ( ! $both_obelisks && ('W' != strtoupper($piece))) { $both_obelisks = true; } // if we made it here, the move is easy // if we are joining / swapping obelisk towers if (in_array(strtoupper($piece), array('V','W')) && ('V' == strtoupper($to_piece))) { if ('V' == strtoupper($piece)) { $this->_board[$from_index] = '0'; $this->_board[$to_index] = ($silver ? 'W' : 'w'); } else { // swap the two places $temp = $to_piece; $this->_board[$to_index] = $piece; $this->_board[$from_index] = $temp; } } elseif ($both_obelisks) { // swap the two places $temp = $to_piece; $this->_board[$to_index] = $piece; $this->_board[$from_index] = $temp; } else { // we're splitting an obelisk tower // set both from and to equal to a single obelisk $this->_board[$from_index] = $this->_board[$to_index] = ($silver ? 'V' : 'v'); } call($this->_get_board_ascii( )); } /** protected function _rotate_piece * Tests and rotates a piece * * @param int board index * @param int direction (0 = CCW, 1 = CW) * @return void */ protected function _rotate_piece($index, $direction) { call(__METHOD__); $rotation = array( 'A' => array('D', 'B'), 'B' => array('A', 'C'), 'C' => array('B', 'D'), 'D' => array('C', 'A'), 'X' => array('Y', 'Y'), 'Y' => array('X', 'X'), 'H' => array('I', 'I'), 'I' => array('H', 'H'), 'E' => array('K', 'F'), 'F' => array('E', 'J'), 'J' => array('F', 'K'), 'K' => array('J', 'E'), 'L' => array('O', 'M'), 'M' => array('L', 'N'), 'N' => array('M', 'O'), 'O' => array('N', 'L'), ); $piece = $this->_board[$index]; call($piece); $silver = ($piece == strtoupper($piece)); $piece = strtoupper($piece); if ( ! isset($rotation[$piece])) { throw new MyException(__METHOD__.': Piece rotation not found'); } $this->_board[$index] = ($silver ? $rotation[$piece][$direction] : strtolower($rotation[$piece][$direction])); } /** static public function extra_info * Returns the extra info merged with the default values * * @param array [optional] extra info * @return array extra info */ static public function extra_info($extra_info = array( )) { $extra_info = array_clean($extra_info, array_keys(self::$EXTRA_INFO_DEFAULTS)); return array_merge_plus(self::$EXTRA_INFO_DEFAULTS, $extra_info); } /** static public function get_board_ascii * Returns the board in an ASCII format * * @param string expanded board FEN * @return string ascii board */ static public function get_board_ascii($board) { $ascii = "\n" .' A B C D E F G H I J'."\n" .' +---+---+---+---+---+---+---+---+---+---+'; for ($length = strlen($board), $i = 0; $i < $length; ++$i) { $char = $board[$i]; if (0 == ($i % 10)) { $ascii .= "\n ".(8 - floor($i / 10)).' |'; }
benjamw/pharaoh
f5c0ab258324f96d7cf66557fc4bd491b955b825
minor updates
diff --git a/classes/gameplayer.class.php b/classes/gameplayer.class.php index 6129446..0b76d1e 100644 --- a/classes/gameplayer.class.php +++ b/classes/gameplayer.class.php @@ -1,677 +1,648 @@ <?php /* +--------------------------------------------------------------------------- | | gameplayer.class.php (php 5.x) | | by Benjam Welker | http://iohelix.net | +--------------------------------------------------------------------------- | -| > Game Player Extension module for Pharaoh (Khet) +| > Game Player Extension module | > Date started: 2008-02-28 | | > Module Version Number: 0.8.0 | +--------------------------------------------------------------------------- */ // TODO: comments & organize better class GamePlayer extends Player { /** * PROPERTIES * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** const property EXTEND_TABLE * Holds the player extend table name * * @var string */ const EXTEND_TABLE = T_PHARAOH; /** protected property allow_email * Flag shows whether or not to send emails to this player * * @var bool */ protected $allow_email; /** protected property max_games * Number of games player can be in at one time * * @var int */ protected $max_games; /** protected property current_games * Number of games player is currently playing in * * @var int */ protected $current_games; /** protected property color * Holds the players skin color preference * * @var string */ protected $color; /** protected property wins * Holds the players win count * * @var int */ protected $wins; /** protected property draws * Holds the players draw count * * @var int */ protected $draws; /** protected property losses * Holds the players loss count * * @var int */ protected $losses; /** protected property last_online * Holds the date the player was last online * * @var int (unix timestamp) */ protected $last_online; /** * METHODS * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** public function __construct * Class constructor * Sets all outside data * * @param int optional player id * @action instantiates object * @return void */ public function __construct($id = null) { $this->_mysql = Mysql::get_instance( ); // check and make sure we have logged into this game before if (0 != (int) $id) { $query = " SELECT COUNT(*) FROM ".self::EXTEND_TABLE." WHERE player_id = '{$id}' "; $count = (int) $this->_mysql->fetch_value($query); if (0 == $count) { throw new MyException(__METHOD__.': '.GAME_NAME.' Player (#'.$id.') not found in database'); } } parent::__construct($id); } - /** public function __destruct - * Class destructor - * Gets object ready for destruction - * - * @param void - * @action destroys object - * @return void - */ -/* - public function __destruct( ) - { - return; // until i can figure out WTF? - - // save anything changed to the database - // BUT... only if PHP didn't die because of an error - $error = error_get_last( ); - - if (0 == ((E_ERROR | E_WARNING | E_PARSE) & $error['type'])) { - try { - $this->save( ); - } - catch (MyException $e) { - // do nothing, it will be logged - } - } - } -*/ - - /** public function log_in * Runs the parent's log_in function * then, if success, tests game player * database to see if this player has been * here before, if not, it adds then to the * database, and if so, refreshes the last_online value * * @param void * @action logs the player in * @action optionally adds new game player data to the database * @return bool success */ public function log_in( ) { // this will redirect and exit upon failure parent::log_in( ); // test an arbitrary property for existence, so we don't _pull twice unnecessarily // but don't test color, because it might actually be null when valid if (is_null($this->last_online)) { $this->_mysql->insert(self::EXTEND_TABLE, array('player_id' => $this->id)); $this->_pull( ); } // don't update the last online time if we logged in as an admin if ( ! isset($_SESSION['admin_id'])) { $this->_mysql->insert(self::EXTEND_TABLE, array('last_online' => NULL), " WHERE player_id = '{$this->id}' "); } return true; } /** public function register * Registers a new player in the extend table * also calls the parent register function * which performs some validity checks * * @param void * @action creates a new player in the database * @return bool success */ public function register( ) { call(__METHOD__); try { parent::register( ); } catch (MyException $e) { call('Exception Thrown: '.$e->getMessage( )); throw $e; } if ($this->id) { // add the user to the table $this->_mysql->insert(self::EXTEND_TABLE, array('player_id' => $this->id)); // update the last_online time so we don't break things later $this->_mysql->insert(self::EXTEND_TABLE, array('last_online' => NULL), " WHERE player_id = '{$this->id}' "); } } /** public function add_win * Adds a win to this player's stats * both here, and in the database * * @param void * @action adds a win in the database * @return void */ public function add_win( ) { $this->wins++; // note the trailing space on the field name, it's not a typo $this->_mysql->insert(self::EXTEND_TABLE, array('wins ' => 'wins + 1'), " WHERE player_id = '{$this->id}' "); } /** public function add_draw * Adds a draw to this player's stats * both here, and in the database * * @param void * @action adds a draw in the database * @return void */ public function add_draw( ) { $this->draws++; // note the trailing space on the field name, it's not a typo $this->_mysql->insert(self::EXTEND_TABLE, array('draws ' => 'draws + 1'), " WHERE player_id = '{$this->id}' "); } /** public function add_loss * Adds a loss to this player's stats * both here, and in the database * * @param void * @action adds a loss in the database * @return void */ public function add_loss( ) { $this->losses++; // note the trailing space on the field name, it's not a typo $this->_mysql->insert(self::EXTEND_TABLE, array('losses ' => 'losses + 1'), " WHERE player_id = '{$this->id}' "); } /** public function admin_delete * Deletes the given players from the players database * * @param mixed csv or array of player IDs * @action deletes the players from the database * @return void */ public function admin_delete($player_ids) { call(__METHOD__); // make sure the user doing this is an admin if ( ! $this->is_admin) { throw new MyException(__METHOD__.': Player is not an admin'); } array_trim($player_ids, 'int'); $player_ids = Player::clean_deleted($player_ids); if ( ! $player_ids) { throw new MyException(__METHOD__.': No player IDs given'); } $this->_mysql->delete(self::EXTEND_TABLE, " WHERE player_id IN (".implode(',', $player_ids).") "); } /** public function admin_add_admin * Gives the given players admin status * * @param mixed csv or array of player IDs * @action gives the given players admin status * @return void */ public function admin_add_admin($player_ids) { // make sure the user doing this is an admin if ( ! $this->is_admin) { throw new MyException(__METHOD__.': Player is not an admin'); } array_trim($player_ids, 'int'); $player_ids[] = 0; // make sure we have at least one entry if (isset($GLOBALS['_ROOT_ADMIN'])) { $query = " SELECT player_id FROM ".Player::PLAYER_TABLE." WHERE username = '{$GLOBALS['_ROOT_ADMIN']}' "; $player_ids[] = (int) $this->_mysql->fetch_value($query); } $this->_mysql->insert(self::EXTEND_TABLE, array('is_admin' => 1), " WHERE player_id IN (".implode(',', $player_ids).") "); } /** public function admin_remove_admin * Removes admin status from the given players * * @param mixed csv or array of player IDs * @action removes the given players admin status * @return void */ public function admin_remove_admin($player_ids) { // make sure the user doing this is an admin if ( ! $this->is_admin) { throw new MyException(__METHOD__.': Player is not an admin'); } array_trim($player_ids, 'int'); $player_ids[] = 0; // make sure we have at least one entry if (isset($GLOBALS['_ROOT_ADMIN'])) { $query = " SELECT player_id FROM ".Player::PLAYER_TABLE." WHERE username = '{$GLOBALS['_ROOT_ADMIN']}' "; $root_admin = (int) $this->_mysql->fetch_value($query); if (in_array($root_admin, $player_ids)) { unset($player_ids[array_search($root_admin, $player_ids)]); } } // remove the player doing the removing unset($player_ids[array_search($_SESSION['player_id'], $player_ids)]); // remove the admin doing the removing unset($player_ids[array_search($_SESSION['admin_id'], $player_ids)]); $this->_mysql->insert(self::EXTEND_TABLE, array('is_admin' => 0), " WHERE player_id IN (".implode(',', $player_ids).") "); } /** public function save * Saves all changed data to the database * * @param void * @action saves the player data * @return void */ public function save( ) { // update the player data $query = " SELECT allow_email , max_games , color FROM ".self::EXTEND_TABLE." WHERE player_id = '{$this->id}' "; $player = $this->_mysql->fetch_assoc($query); if ( ! $player) { throw new MyException(__METHOD__.': Player data not found for player #'.$this->id); } // TODO: test the last online date and make sure we still have valid data $update_player = false; if ((bool) $player['allow_email'] != $this->allow_email) { $update_player['allow_email'] = (int) $this->allow_email; } if ($player['max_games'] != $this->max_games) { $update_player['max_games'] = (int) $this->max_games; } if ($player['color'] != $this->color) { $update_player['color'] = $this->color; } if ($update_player) { $this->_mysql->insert(self::EXTEND_TABLE, $update_player, " WHERE player_id = '{$this->id}' "); } } /** protected function _pull * Pulls all game player data from the database * as well as the parent's data * * @param void * @action pulls the player data * @action pulls the game player data * @return void */ protected function _pull( ) { parent::_pull( ); $query = " SELECT * FROM ".self::EXTEND_TABLE." WHERE player_id = '{$this->id}' "; $result = $this->_mysql->fetch_assoc($query); if ( ! $result) { // TODO: find out what is going on here and fix. # throw new MyException(__METHOD__.': Data not found in database (#'.$this->id.')'); return false; } $this->is_admin = ( ! $this->is_admin) ? (bool) $result['is_admin'] : true; $this->allow_email = (bool) $result['allow_email']; $this->max_games = (int) $result['max_games']; $this->color = $result['color']; $this->wins = (int) $result['wins']; $this->draws = (int) $result['draws']; $this->losses = (int) $result['losses']; $this->last_online = strtotime($result['last_online']); // grab the player's current game count $query = " SELECT COUNT(*) FROM ".Game::GAME_TABLE." AS G LEFT JOIN ".Game::GAME_HISTORY_TABLE." AS GH USING (game_id) WHERE ((G.white_id = '{$this->id}' OR G.black_id = '{$this->id}') AND GH.board IS NOT NULL) AND G.state = 'Playing' "; $this->current_games = $this->_mysql->fetch_value($query); } /** * STATIC METHODS * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** static public function get_list * Returns a list array of all game players * in the database * This function supersedes the parent's function and * just grabs the whole lot in one query * * @param bool restrict to approved players * @return array game player list (or bool false on failure) */ static public function get_list($only_approved = false) { $Mysql = Mysql::get_instance( ); $WHERE = ($only_approved) ? " WHERE P.is_approved = 1 " : ''; $query = " SELECT * , P.is_admin AS full_admin , E.is_admin AS half_admin FROM ".Player::PLAYER_TABLE." AS P INNER JOIN ".self::EXTEND_TABLE." AS E USING (player_id) {$WHERE} ORDER BY P.username "; $list = $Mysql->fetch_array($query); return $list; } /** static public function get_count * Returns a count of all game players * in the database * * @param void * @return int game player count */ static public function get_count( ) { $Mysql = Mysql::get_instance( ); $query = " SELECT COUNT(*) FROM ".self::EXTEND_TABLE." AS E JOIN ".Player::PLAYER_TABLE." AS P USING (player_id) WHERE P.is_approved = 1 -- TODO: AND E.is_approved = 1 "; $count = $Mysql->fetch_value($query); return $count; } /** static public function get_maxed * Returns an array of all player IDs * who have reached their max games count * * @param void * @return array of int player IDs */ static public function get_maxed( ) { $Mysql = Mysql::get_instance( ); // run through the maxed invites and set the key // to the player id and the value to the invite count // for ease of use later $invites = array( ); // TODO: set a setting for this if (true || $invites_count_toward_max_games) { $query = " SELECT COUNT(G.game_id) AS invite_count , PE.player_id FROM ".Game::GAME_TABLE." AS G LEFT JOIN ".self::EXTEND_TABLE." AS PE ON (PE.player_id = G.white_id OR PE.player_id = G.black_id) WHERE G.state = 'Waiting' AND PE.max_games > 0 GROUP BY PE.player_id "; $maxed_invites = $Mysql->fetch_array($query); foreach ($maxed_invites as $invite) { $invites[$invite['player_id']] = $invite['invite_count']; } } $query = " SELECT COUNT(G.game_id) AS game_count , PE.player_id , PE.max_games FROM ".Game::GAME_TABLE." AS G LEFT JOIN ".self::EXTEND_TABLE." AS PE ON (PE.player_id = G.white_id OR PE.player_id = G.black_id) WHERE G.state = 'Playing' AND PE.max_games > 0 GROUP BY PE.player_id "; $maxed_players = $Mysql->fetch_array($query); $player_ids = array( ); foreach ($maxed_players as $data) { if ( ! isset($invites[$data['player_id']])) { $invites[$data['player_id']] = 0; } if (($data['game_count'] + $invites[$data['player_id']]) >= $data['max_games']) { $player_ids[] = $data['player_id']; } } return $player_ids; } /** static public function delete_inactive * Deletes the inactive users from the database * * @param int age in days * @return void */ static public function delete_inactive($age) { call(__METHOD__); $Mysql = Mysql::get_instance( ); $age = (int) abs($age); if (0 == $age) { return false; } $exception_ids = array( ); // make sure the 'unused' player is not an admin $query = " SELECT EP.player_id FROM ".self::EXTEND_TABLE." AS EP JOIN ".Player::PLAYER_TABLE." AS P USING (player_id) WHERE P.is_admin = 1 OR EP.is_admin = 1 "; $results = $Mysql->fetch_value_array($query); $exception_ids = array_merge($exception_ids, $results); // make sure the 'unused' player is not currently in a game $query = " SELECT DISTINCT white_id FROM ".Game::GAME_TABLE." WHERE state = 'Playing' "; $results = $Mysql->fetch_value_array($query); $exception_ids = array_merge($exception_ids, $results); $query = " SELECT DISTINCT black_id FROM ".Game::GAME_TABLE." WHERE state = 'Playing' "; $results = $Mysql->fetch_value_array($query); $exception_ids = array_merge($exception_ids, $results); // make sure the 'unused' player isn't awaiting approval $query = " SELECT player_id FROM ".Player::PLAYER_TABLE." WHERE is_approved = 0 "; $results = $Mysql->fetch_value_array($query); $exception_ids = array_merge($exception_ids, $results); $exception_ids[] = 0; // don't break the IN clause $exception_id_list = implode(',', $exception_ids); // select unused accounts $query = " SELECT player_id FROM ".self::EXTEND_TABLE." WHERE wins + losses <= 2 AND player_id NOT IN ({$exception_id_list}) AND last_online < DATE_SUB(NOW( ), INTERVAL {$age} DAY) "; $player_ids = $Mysql->fetch_value_array($query); call($player_ids); if ($player_ids) { Game::player_deleted($player_ids); $Mysql->delete(self::EXTEND_TABLE, " WHERE player_id IN (".implode(',', $player_ids).") "); } } diff --git a/css/c_blue_black.css b/css/c_blue_black.css index 2d2b595..0c9a721 100644 --- a/css/c_blue_black.css +++ b/css/c_blue_black.css @@ -1 +1 @@ -html,body{background-color:#27282b;color:#fff}a{color:#fff}a.help{border:1px solid #777777}a.help:hover{border:1px solid #999999}abbr,acronym{border-bottom:1px dashed #777777}hr.fancy{background-color:#999;border:1px solid #777777}fieldset{border:1px solid #555555}.warning,.warning *{color:#b00}.notice,.notice *{color:#dd0}.highlight,.highlight *{color:#3380d7}.instruction,.instruction *{color:#aaa}header{border-bottom:1px solid #2473e3;background-color:#282828;background:-o-radial-gradient(50% 100%, ellipse cover, #165aa6 30%, #282828 80%) #282828;background:-ms-radial-gradient(50% 100%, ellipse cover, #165aa6 30%, #282828 80%) #282828;background:-moz-radial-gradient(50% 100%, ellipse cover, #165aa6 30%, #282828 80%) #282828;background:-webkit-radial-gradient(50% 100%, ellipse cover, #165aa6 30%, #282828 80%) #282828;background:radial-gradient(50% 100%, ellipse cover, #165aa6 30%,#282828 80%) #282828}h1{height:45px}h1 a{background-image:url(../images/Pharaoh.png)}nav.site a{color:#ddd;text-shadow:black 0 1px 1px}nav.site a:hover{color:#fff;background:-o-radial-gradient(50% 90%, ellipse closest-corner, rgba(255,255,255,0.35) 30%, rgba(255,255,255,0.01) 70%) transparent;background:-ms-radial-gradient(50% 90%, ellipse closest-corner, rgba(255,255,255,0.35) 30%, rgba(255,255,255,0.01) 70%) transparent;background:-moz-radial-gradient(50% 90%, ellipse closest-corner, rgba(255,255,255,0.35) 30%, rgba(255,255,255,0.01) 70%) transparent;background:-webkit-radial-gradient(50% 100%, 80% 20%, rgba(255,255,255,0.35) 30%, rgba(255,255,255,0.01) 70%) transparent;background:radial-gradient(50% 100%, 80% 20%, rgba(255,255,255,0.35) 30%,rgba(255,255,255,0.01) 70%) transparent}*.box{background-color:black;background:-o-linear-gradient(#232323, black) #000;background:-ms-linear-gradient(#232323, #000) #000;background:-moz-linear-gradient(#232323, #000) #000;background:-webkit-linear-gradient(#232323, #000) #000;background:linear-gradient(#232323,#000000) #000}*.box > *{background-color:#2e2f34;background:-o-linear-gradient(#2e2f34, #212225) #2e2f34;background:-ms-linear-gradient(#2e2f34, #212225) #2e2f34;background:-moz-linear-gradient(#2e2f34, #212225) #2e2f34;background:-webkit-linear-gradient(#2e2f34, #212225) #2e2f34;background:linear-gradient(#2e2f34,#212225) #2e2f34;-o-box-shadow:0px 1px 0px rgba(255,255,255,0.1) inset,0px -2px 1px rgba(0,0,0,0.2) inset;-ms-box-shadow:0px 1px 0px rgba(255,255,255,0.1) inset,0px -2px 1px rgba(0,0,0,0.2) inset;-moz-box-shadow:0px 1px 0px rgba(255,255,255,0.1) inset,0px -2px 1px rgba(0,0,0,0.2) inset;-webkit-box-shadow:0px 1px 0px rgba(255,255,255,0.1) inset,0px -2px 1px rgba(0,0,0,0.2) inset;box-shadow:0px 1px 0px rgba(255,255,255,0.1) inset,0px -2px 1px rgba(0,0,0,0.2) inset}nav#menu a,nav#mygames a{color:#ddd;background-color:transparent;border-bottom:1px solid #333333}nav#menu a:hover,nav#mygames a:hover{color:#fff;background-color:rgba(12,14,40,0.5)}nav#menu li.active a,nav#mygames li.active a{color:inherit;background-color:rgba(255,255,255,0.1)}nav#menu li span.sep,nav#mygames li span.sep{color:#666}nav#mygames .finished a{color:#999}nav#mygames .playing a{color:#3380d7}nav#mygames .my_turn a{color:#3380d7}nav#mygames .none a{color:#fff}aside#info #chatbox{background-color:#eee;border:1px solid #777777}h2{border-bottom:1px solid #777777}#index_page #chatbox{border:1px solid #777777}#index_page #chats{border-top:1px solid #777777}#index_page #chats dt{border-bottom:1px solid #777777;background:transparent}#index_page #chats dd{border-bottom:1px solid #777777}footer{color:#ddd;background-color:#0b2d53;-o-box-shadow:0px 3px 16px #000 inset;-ms-box-shadow:0px 3px 16px #000 inset;-moz-box-shadow:0px 3px 16px #000 inset;-webkit-box-shadow:0px 3px 16px #000 inset;box-shadow:0px 3px 16px #000 inset}#buttons a{border:1px solid #333333;border-width:0 1px}#history table td.active,#history table td:hover{background-color:#444;color:#fff}#history div div span{border:1px solid #555555}#history div div span:hover{border-color:#aaa}#history div div span.disabled{color:#aaa;border-color:#333} +html,body{background-color:#27282b;color:#fff}a{color:#fff}a.help{border:1px solid #777}a.help:hover{border:1px solid #999}abbr,acronym{border-bottom:1px dashed #777}hr.fancy{background-color:#999;border:1px solid #777}fieldset{border:1px solid #555}form+form{border-top:1px solid #2473e3}.warning,.warning *{color:#b00}.notice,.notice *{color:#dd0}.highlight,.highlight *{color:#3380d7}.instruction,.instruction *{color:#aaa}header{border-bottom:1px solid #2473e3;background-color:#282828;background:-o-radial-gradient(50% 100%, ellipse cover, #165aa6 30%, #282828 80%) #282828;background:-ms-radial-gradient(50% 100%, ellipse cover, #165aa6 30%, #282828 80%) #282828;background:-moz-radial-gradient(50% 100%, ellipse cover, #165aa6 30%, #282828 80%) #282828;background:-webkit-radial-gradient(50% 100%, ellipse cover, #165aa6 30%, #282828 80%) #282828;background:radial-gradient(50% 100%, ellipse cover, #165aa6 30%,#282828 80%) #282828}h1{height:45px}h1 a{background-image:url(../images/Pharaoh.png)}nav.site a{color:#ddd;text-shadow:#000 0 1px 1px}nav.site a:hover{color:#fff;background:-o-radial-gradient(50% 90%, ellipse closest-corner, rgba(255,255,255,0.35) 30%, rgba(255,255,255,0.01) 70%) transparent;background:-ms-radial-gradient(50% 90%, ellipse closest-corner, rgba(255,255,255,0.35) 30%, rgba(255,255,255,0.01) 70%) transparent;background:-moz-radial-gradient(50% 90%, ellipse closest-corner, rgba(255,255,255,0.35) 30%, rgba(255,255,255,0.01) 70%) transparent;background:-webkit-radial-gradient(50% 100%, 80% 20%, rgba(255,255,255,0.35) 30%, rgba(255,255,255,0.01) 70%) transparent;background:radial-gradient(50% 100%, 80% 20%, rgba(255,255,255,0.35) 30%,rgba(255,255,255,0.01) 70%) transparent}*.box{background-color:#000;background:-o-linear-gradient(#232323, #000) #000;background:-ms-linear-gradient(#232323, #000) #000;background:-moz-linear-gradient(#232323, #000) #000;background:-webkit-linear-gradient(#232323, #000) #000;background:linear-gradient(#232323,#000000) #000}*.box>*{background-color:#2e2f34;background:-o-linear-gradient(#2e2f34, #212225) #2e2f34;background:-ms-linear-gradient(#2e2f34, #212225) #2e2f34;background:-moz-linear-gradient(#2e2f34, #212225) #2e2f34;background:-webkit-linear-gradient(#2e2f34, #212225) #2e2f34;background:linear-gradient(#2e2f34,#212225) #2e2f34;-o-box-shadow:0px 1px 0px rgba(255,255,255,0.1) inset,0px -2px 1px rgba(0,0,0,0.2) inset;-ms-box-shadow:0px 1px 0px rgba(255,255,255,0.1) inset,0px -2px 1px rgba(0,0,0,0.2) inset;-moz-box-shadow:0px 1px 0px rgba(255,255,255,0.1) inset,0px -2px 1px rgba(0,0,0,0.2) inset;-webkit-box-shadow:0px 1px 0px rgba(255,255,255,0.1) inset,0px -2px 1px rgba(0,0,0,0.2) inset;box-shadow:0px 1px 0px rgba(255,255,255,0.1) inset,0px -2px 1px rgba(0,0,0,0.2) inset}nav#menu a,nav#mygames a{color:#ddd;background-color:transparent;border-bottom:1px solid #333}nav#menu a:hover,nav#mygames a:hover{color:#fff;background-color:rgba(12,14,40,0.5)}nav#menu li.active a,nav#mygames li.active a{color:inherit;background-color:rgba(255,255,255,0.1)}nav#menu li span.sep,nav#mygames li span.sep{color:#666}nav#mygames .finished a{color:#999}nav#mygames .playing a{color:#3380d7}nav#mygames .my_turn a{color:#3380d7}nav#mygames .none a{color:#fff}aside#info #chatbox{background-color:#eee;border:1px solid #777}h2{border-bottom:1px solid #777}#index_page #chatbox{border:1px solid #777}#index_page #chats{border-top:1px solid #777}#index_page #chats dt{border-bottom:1px solid #777;background:transparent}#index_page #chats dd{border-bottom:1px solid #777}footer{color:#ddd;background-color:#0b2d53;-o-box-shadow:0px 3px 16px #000 inset;-ms-box-shadow:0px 3px 16px #000 inset;-moz-box-shadow:0px 3px 16px #000 inset;-webkit-box-shadow:0px 3px 16px #000 inset;box-shadow:0px 3px 16px #000 inset}#buttons a{border:1px solid #333;border-width:0 1px}#history table td.active,#history table td:hover{background-color:#444;color:#fff}#history div div span{border:1px solid #555}#history div div span:hover{border-color:#aaa}#history div div span.disabled{color:#aaa;border-color:#333} diff --git a/css/c_red_black.css b/css/c_red_black.css index 4ec6622..ce80741 100644 --- a/css/c_red_black.css +++ b/css/c_red_black.css @@ -1 +1 @@ -html,body{background-color:#27282b;color:#fff}a{color:#fff}a.help{border:1px solid #777777}a.help:hover{border:1px solid #999999}abbr,acronym{border-bottom:1px dashed #777777}hr.fancy{background-color:#999;border:1px solid #777777}fieldset{border:1px solid #555555}.warning,.warning *{color:#b00}.notice,.notice *{color:#dd0}.highlight,.highlight *{color:#b00}.instruction,.instruction *{color:#aaa}header{border-bottom:1px solid #ce3e47;background-color:#670b0c;background:-o-radial-gradient(50% 100%, ellipse cover, #a72819 30%, #670b0c 80%) #670b0c;background:-ms-radial-gradient(50% 100%, ellipse cover, #a72819 30%, #670b0c 80%) #670b0c;background:-moz-radial-gradient(50% 100%, ellipse cover, #a72819 30%, #670b0c 80%) #670b0c;background:-webkit-radial-gradient(50% 100%, ellipse cover, #a72819 30%, #670b0c 80%) #670b0c;background:radial-gradient(50% 100%, ellipse cover, #a72819 30%,#670b0c 80%) #670b0c}h1{height:45px}h1 a{background-image:url(../images/Pharaoh.png)}nav.site a{color:#ddd;text-shadow:black 0 1px 1px}nav.site a:hover{color:#fff;background:-o-radial-gradient(50% 90%, ellipse closest-corner, rgba(255,255,255,0.35) 30%, rgba(255,255,255,0.01) 70%) transparent;background:-ms-radial-gradient(50% 90%, ellipse closest-corner, rgba(255,255,255,0.35) 30%, rgba(255,255,255,0.01) 70%) transparent;background:-moz-radial-gradient(50% 90%, ellipse closest-corner, rgba(255,255,255,0.35) 30%, rgba(255,255,255,0.01) 70%) transparent;background:-webkit-radial-gradient(50% 100%, 80% 20%, rgba(255,255,255,0.35) 30%, rgba(255,255,255,0.01) 70%) transparent;background:radial-gradient(50% 100%, 80% 20%, rgba(255,255,255,0.35) 30%,rgba(255,255,255,0.01) 70%) transparent}*.box{background-color:black;background:-o-linear-gradient(#232323, black) #000;background:-ms-linear-gradient(#232323, #000) #000;background:-moz-linear-gradient(#232323, #000) #000;background:-webkit-linear-gradient(#232323, #000) #000;background:linear-gradient(#232323,#000000) #000}*.box > *{background-color:#2e2f34;background:-o-linear-gradient(#2e2f34, #212225) #2e2f34;background:-ms-linear-gradient(#2e2f34, #212225) #2e2f34;background:-moz-linear-gradient(#2e2f34, #212225) #2e2f34;background:-webkit-linear-gradient(#2e2f34, #212225) #2e2f34;background:linear-gradient(#2e2f34,#212225) #2e2f34;-o-box-shadow:0px 1px 0px rgba(255,255,255,0.1) inset,0px -2px 1px rgba(0,0,0,0.2) inset;-ms-box-shadow:0px 1px 0px rgba(255,255,255,0.1) inset,0px -2px 1px rgba(0,0,0,0.2) inset;-moz-box-shadow:0px 1px 0px rgba(255,255,255,0.1) inset,0px -2px 1px rgba(0,0,0,0.2) inset;-webkit-box-shadow:0px 1px 0px rgba(255,255,255,0.1) inset,0px -2px 1px rgba(0,0,0,0.2) inset;box-shadow:0px 1px 0px rgba(255,255,255,0.1) inset,0px -2px 1px rgba(0,0,0,0.2) inset}nav#menu a,nav#mygames a{color:#ddd;background-color:transparent;border-bottom:1px solid #333333}nav#menu a:hover,nav#mygames a:hover{color:#fff;background-color:rgba(40,14,12,0.5)}nav#menu li.active a,nav#mygames li.active a{color:inherit;background-color:rgba(255,255,255,0.1)}nav#menu li span.sep,nav#mygames li span.sep{color:#666}nav#mygames .finished a{color:#999}nav#mygames .playing a{color:#b00}nav#mygames .my_turn a{color:#b00}nav#mygames .none a{color:#fff}aside#info #chatbox{background-color:#eee;border:1px solid #777777}h2{border-bottom:1px solid #777777}#index_page #chatbox{border:1px solid #777777}#index_page #chats{border-top:1px solid #777777}#index_page #chats dt{border-bottom:1px solid #777777;background:transparent}#index_page #chats dd{border-bottom:1px solid #777777}footer{color:#ddd;background-color:#670b0c;-o-box-shadow:0px 3px 16px #000 inset;-ms-box-shadow:0px 3px 16px #000 inset;-moz-box-shadow:0px 3px 16px #000 inset;-webkit-box-shadow:0px 3px 16px #000 inset;box-shadow:0px 3px 16px #000 inset}#buttons a{border:1px solid #333333;border-width:0 1px}#history table td.active,#history table td:hover{background-color:#444;color:#fff}#history div div span{border:1px solid #555555}#history div div span:hover{border-color:#aaa}#history div div span.disabled{color:#aaa;border-color:#333} +html,body{background-color:#27282b;color:#fff}a{color:#fff}a.help{border:1px solid #777}a.help:hover{border:1px solid #999}abbr,acronym{border-bottom:1px dashed #777}hr.fancy{background-color:#999;border:1px solid #777}fieldset{border:1px solid #555}form+form{border-top:1px solid #ce3e47}.warning,.warning *{color:#b00}.notice,.notice *{color:#dd0}.highlight,.highlight *{color:#b00}.instruction,.instruction *{color:#aaa}header{border-bottom:1px solid #ce3e47;background-color:#670b0c;background:-o-radial-gradient(50% 100%, ellipse cover, #a72819 30%, #670b0c 80%) #670b0c;background:-ms-radial-gradient(50% 100%, ellipse cover, #a72819 30%, #670b0c 80%) #670b0c;background:-moz-radial-gradient(50% 100%, ellipse cover, #a72819 30%, #670b0c 80%) #670b0c;background:-webkit-radial-gradient(50% 100%, ellipse cover, #a72819 30%, #670b0c 80%) #670b0c;background:radial-gradient(50% 100%, ellipse cover, #a72819 30%,#670b0c 80%) #670b0c}h1{height:45px}h1 a{background-image:url(../images/Pharaoh.png)}nav.site a{color:#ddd;text-shadow:#000 0 1px 1px}nav.site a:hover{color:#fff;background:-o-radial-gradient(50% 90%, ellipse closest-corner, rgba(255,255,255,0.35) 30%, rgba(255,255,255,0.01) 70%) transparent;background:-ms-radial-gradient(50% 90%, ellipse closest-corner, rgba(255,255,255,0.35) 30%, rgba(255,255,255,0.01) 70%) transparent;background:-moz-radial-gradient(50% 90%, ellipse closest-corner, rgba(255,255,255,0.35) 30%, rgba(255,255,255,0.01) 70%) transparent;background:-webkit-radial-gradient(50% 100%, 80% 20%, rgba(255,255,255,0.35) 30%, rgba(255,255,255,0.01) 70%) transparent;background:radial-gradient(50% 100%, 80% 20%, rgba(255,255,255,0.35) 30%,rgba(255,255,255,0.01) 70%) transparent}*.box{background-color:#000;background:-o-linear-gradient(#232323, #000) #000;background:-ms-linear-gradient(#232323, #000) #000;background:-moz-linear-gradient(#232323, #000) #000;background:-webkit-linear-gradient(#232323, #000) #000;background:linear-gradient(#232323,#000000) #000}*.box>*{background-color:#2e2f34;background:-o-linear-gradient(#2e2f34, #212225) #2e2f34;background:-ms-linear-gradient(#2e2f34, #212225) #2e2f34;background:-moz-linear-gradient(#2e2f34, #212225) #2e2f34;background:-webkit-linear-gradient(#2e2f34, #212225) #2e2f34;background:linear-gradient(#2e2f34,#212225) #2e2f34;-o-box-shadow:0px 1px 0px rgba(255,255,255,0.1) inset,0px -2px 1px rgba(0,0,0,0.2) inset;-ms-box-shadow:0px 1px 0px rgba(255,255,255,0.1) inset,0px -2px 1px rgba(0,0,0,0.2) inset;-moz-box-shadow:0px 1px 0px rgba(255,255,255,0.1) inset,0px -2px 1px rgba(0,0,0,0.2) inset;-webkit-box-shadow:0px 1px 0px rgba(255,255,255,0.1) inset,0px -2px 1px rgba(0,0,0,0.2) inset;box-shadow:0px 1px 0px rgba(255,255,255,0.1) inset,0px -2px 1px rgba(0,0,0,0.2) inset}nav#menu a,nav#mygames a{color:#ddd;background-color:transparent;border-bottom:1px solid #333}nav#menu a:hover,nav#mygames a:hover{color:#fff;background-color:rgba(40,14,12,0.5)}nav#menu li.active a,nav#mygames li.active a{color:inherit;background-color:rgba(255,255,255,0.1)}nav#menu li span.sep,nav#mygames li span.sep{color:#666}nav#mygames .finished a{color:#999}nav#mygames .playing a{color:#b00}nav#mygames .my_turn a{color:#b00}nav#mygames .none a{color:#fff}aside#info #chatbox{background-color:#eee;border:1px solid #777}h2{border-bottom:1px solid #777}#index_page #chatbox{border:1px solid #777}#index_page #chats{border-top:1px solid #777}#index_page #chats dt{border-bottom:1px solid #777;background:transparent}#index_page #chats dd{border-bottom:1px solid #777}footer{color:#ddd;background-color:#670b0c;-o-box-shadow:0px 3px 16px #000 inset;-ms-box-shadow:0px 3px 16px #000 inset;-moz-box-shadow:0px 3px 16px #000 inset;-webkit-box-shadow:0px 3px 16px #000 inset;box-shadow:0px 3px 16px #000 inset}#buttons a{border:1px solid #333;border-width:0 1px}#history table td.active,#history table td:hover{background-color:#444;color:#fff}#history div div span{border:1px solid #555}#history div div span:hover{border-color:#aaa}#history div div span.disabled{color:#aaa;border-color:#333} diff --git a/css/game.css b/css/game.css index d387e11..71ddc92 100644 --- a/css/game.css +++ b/css/game.css @@ -1 +1 @@ -.a_board{background-color:#1F2023;color:#CCC;width:550px;height:450px}.a_board .header{text-align:center;font-weight:bold;font-size:16px}.a_board div{border:1px solid #000;float:left;clear:none;width:44px;height:44px;margin:1px;padding:1px;position:relative;overflow:hidden}.a_board .vert{border:0;margin:0;padding:0;width:25px;height:50px;line-height:50px}.a_board .horz{border:0;margin:0;padding:0;width:50px;height:25px;line-height:25px}.a_board .corner{border:0;margin:0;padding:0;width:25px;height:25px}.a_board .corner div{border:2px solid #FFF;width:14px;height:14px;margin:4px;padding:0;line-height:10px;-moz-border-radius:14px;-webkit-border-radius:14px;border-radius:14px}.a_board .corner div.alive{border-color:#0C0;background:#090}.a_board .corner div.immune{border-color:#CC0;background:#990;color:#FFF}.a_board .corner div.dead{border-color:#C00;background:#900;color:#FFF}.a_board .c_silver{background-color:#555}.a_board .c_red{background-color:#500}.a_board .highlight{background-color:#550}.a_board .piece{background-position:center center;background-repeat:no-repeat}.a_board div img{position:absolute;top:0;left:0}.a_board div img.piece{position:absolute;top:1px;left:1px}.a_board img.ccw{margin-left:23px}#contents{margin:10px}#chatbox{margin-left:732px}#chats{height:450px}#game_page #chatbox input[type=text]{width:80%}#board_wrapper{float:left;width:550px;margin-left:5px}#board{width:550px;height:450px}#history{float:left;width:170px}#history table{margin:0}#history table td{padding:0 5px;font-size:1.1em;line-height:130%}#history table td.active,#history table td:hover{font-weight:bold;background-color:#444;color:#FFF}#history table td.turn{width:1%;text-align:right}#history div div{margin-bottom:2px;text-align:center}#history div div span{padding:2px 5px 1px;border:1px solid #555;-moz-border-radius:3px;-webkit-border-radius:3px;border-radius:3px;cursor:pointer}#history div div span:hover{border-color:#AAA}#history div div span.disabled{color:#AAA;border-color:#333;cursor:default}form#game{clear:both;text-align:center;padding-top:20px}#setup{display:none} +.a_board{background-color:#1F2023;color:#CCC;width:550px;height:450px}.a_board .header{text-align:center;font-weight:bold;font-size:16px}.a_board div{border:1px solid #000;float:left;clear:none;width:44px;height:44px;margin:1px;padding:1px;position:relative;overflow:hidden}.a_board .vert{border:0;margin:0;padding:0;width:25px;height:50px;line-height:50px}.a_board .horz{border:0;margin:0;padding:0;width:50px;height:25px;line-height:25px}.a_board .corner{border:0;margin:0;padding:0;width:25px;height:25px}.a_board .corner div{border:2px solid #FFF;width:14px;height:14px;margin:4px;padding:0;line-height:10px;-moz-border-radius:14px;-webkit-border-radius:14px;border-radius:14px}.a_board .corner div.alive{border-color:#0C0;background:#090}.a_board .corner div.immune{border-color:#CC0;background:#990;color:#FFF}.a_board .corner div.dead{border-color:#C00;background:#900;color:#FFF}.a_board .c_silver{background-color:#555}.a_board .c_red{background-color:#500}.a_board .highlight{background-color:#550}.a_board .piece{background-position:center center;background-repeat:no-repeat}.a_board div img{position:absolute;top:0;left:0}.a_board div img.piece{position:absolute;top:1px;left:1px}.a_board img.ccw{margin-left:23px}#contents{margin:10px}#chatbox{margin-left:732px}#chats{height:450px}#game_page #chatbox input[type=text]{width:80%}#game_page #chatbox dd{padding-left:1em}#board_wrapper{float:left;width:550px;margin-left:5px}#board{width:550px;height:450px}#history{float:left;width:170px}#history table{margin:0}#history table td{padding:0 5px;font-size:1.1em;line-height:130%}#history table td.active,#history table td:hover{font-weight:bold;background-color:#444;color:#FFF}#history table td.turn{width:1%;text-align:right}#history div div{margin-bottom:2px;text-align:center}#history div div span{padding:2px 5px 1px;border:1px solid #555;-moz-border-radius:3px;-webkit-border-radius:3px;border-radius:3px;cursor:pointer}#history div div span:hover{border-color:#AAA}#history div div span.disabled{color:#AAA;border-color:#333;cursor:default}form#game{clear:both;text-align:center;padding-top:20px}#setup{display:none} diff --git a/css/layout.css b/css/layout.css index 445fa4f..0e7bd70 100644 --- a/css/layout.css +++ b/css/layout.css @@ -1 +1 @@ -html,body,div,span,applet,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,big,cite,code,del,dfn,em,font,img,ins,kbd,q,s,samp,small,strike,strong,sub,sup,tt,var,dl,dt,dd,ol,ul,li,fieldset,form,label,legend,table,caption,tbody,tfoot,thead,tr,th,td{margin:0;padding:0;border:0;outline:0;font-weight:inherit;font-style:inherit;font-size:100%;font-family:inherit}:focus{outline:0}body{line-height:1;color:black;background:white}ol,ul{list-style:none}table{border-collapse:separate;border-spacing:0}caption,th,td{text-align:left;font-weight:normal}blockquote:before,blockquote:after,q:before,q:after{content:""}blockquote,q{quotes:"" ""}strong{font-weight:bold}em{font-style:italic}em em{font-style:normal}pre{font-family:monospace}html,body{background-color:#27282B;color:#FFF;margin:0;padding:0;font-size:14px;line-height:1.5;font-weight:normal;font-family:Calibri, sans-serif}a{font-weight:bold;text-decoration:underline;color:#FFF}a:hover{text-decoration:none}a.help{border:1px solid #777;font-weight:bold;padding:0 4px;text-decoration:none}a.help:hover{border:1px solid #999}abbr,acronym{border-bottom:1px dashed #777;cursor:help}hr{width:90%;margin:1em auto}hr.fancy{height:5px;margin:1em;background-color:#999;border:1px solid #777}p{margin:0.5em 0 1em;line-height:1.2}fieldset{padding:5px;margin:5px;border:1px solid #555}legend{font-weight:bold;line-height:1;padding:0 5px}.warning,.warning *{color:#B00;font-weight:bold}.notice,.notice *{color:#DD0;font-weight:bold}.highlight,.highlight *{color:#B00;font-weight:bold}.instruction,.instruction *{color:#AAA}.caption{margin:1ex 0}.clr{clear:both !important;float:none !important}#date{font-size:0.85em;font-weight:bold;white-space:nowrap;text-align:right}header{min-height:60px;width:100%;margin:0 0 10px;padding:5px;position:relative;border-bottom:1px solid #CE3E47;background-color:#670B0C;background:-o-radial-gradient(50% 100%, ellipse cover, #a72819 30%, #670b0c 80%) #670b0c;background:-ms-radial-gradient(50% 100%, ellipse cover, #a72819 30%, #670b0c 80%) #670b0c;background:-moz-radial-gradient(50% 100%, ellipse cover, #a72819 30%, #670b0c 80%) #670b0c;background:-webkit-radial-gradient(50% 100%, ellipse cover, #a72819 30%, #670b0c 80%) #670b0c;background:radial-gradient(50% 100%, ellipse cover, #a72819 30%,#670b0c 80%) #670b0c;-o-box-shadow:0px 3px 16px #000,0px -3px 0px rgba(0,0,0,0.4) inset;-ms-box-shadow:0px 3px 16px #000,0px -3px 0px rgba(0,0,0,0.4) inset;-moz-box-shadow:0px 3px 16px #000,0px -3px 0px rgba(0,0,0,0.4) inset;-webkit-box-shadow:0px 3px 16px #000,0px -3px 0px rgba(0,0,0,0.4) inset;box-shadow:0px 3px 16px #000,0px -3px 0px rgba(0,0,0,0.4) inset;-o-box-sizing:border-box;-ms-box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;box-sizing:border-box}h1{height:45px;margin:0 0 3px;padding:0;font-size:1.1em;font-weight:bold;text-indent:-9999em}h1 a{background:transparent url(../images/Pharaoh.png) no-repeat scroll 15px center;display:block;text-decoration:none;height:100%}nav.site{float:right;position:absolute;top:15px;right:10px;margin:10px}nav.site a{text-decoration:none;padding:3px 10px;color:#DDD;font-weight:bold;text-shadow:#000 0 1px 1px}nav.site a:hover{color:#FFF;background:-o-radial-gradient(50% 90%, ellipse closest-corner, rgba(255,255,255,0.35) 30%, rgba(255,255,255,0.01) 70%) transparent;background:-ms-radial-gradient(50% 90%, ellipse closest-corner, rgba(255,255,255,0.35) 30%, rgba(255,255,255,0.01) 70%) transparent;background:-moz-radial-gradient(50% 90%, ellipse closest-corner, rgba(255,255,255,0.35) 30%, rgba(255,255,255,0.01) 70%) transparent;background:-webkit-radial-gradient(50% 100%, 80% 20%, rgba(255,255,255,0.35) 30%, rgba(255,255,255,0.01) 70%) transparent;background:radial-gradient(50% 100%, 80% 20%, rgba(255,255,255,0.35) 30%,rgba(255,255,255,0.01) 70%) transparent}*.box{display:block;margin:0;padding:1px;-o-border-radius:4px;-ms-border-radius:4px;-moz-border-radius:4px;-webkit-border-radius:4px;border-radius:4px;background-color:#000000;background:-o-linear-gradient(#232323, #000) #000;background:-ms-linear-gradient(#232323, #000) #000;background:-moz-linear-gradient(#232323, #000) #000;background:-webkit-linear-gradient(#232323, #000) #000;background:linear-gradient(#232323,#000000) #000;-o-box-sizing:border-box;-ms-box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;box-sizing:border-box}*.box > *{padding:5px;display:block;margin:0;height:100%;overflow:auto;-o-border-radius:2px;-ms-border-radius:2px;-moz-border-radius:2px;-webkit-border-radius:2px;border-radius:2px;background-color:#2E2F34;background:-o-linear-gradient(#2e2f34, #212225) #2e2f34;background:-ms-linear-gradient(#2e2f34, #212225) #2e2f34;background:-moz-linear-gradient(#2e2f34, #212225) #2e2f34;background:-webkit-linear-gradient(#2e2f34, #212225) #2e2f34;background:linear-gradient(#2e2f34,#212225) #2e2f34;-o-box-shadow:0px 1px 0px rgba(255,255,255,0.1) inset,0px -2px 1px rgba(0,0,0,0.2) inset;-ms-box-shadow:0px 1px 0px rgba(255,255,255,0.1) inset,0px -2px 1px rgba(0,0,0,0.2) inset;-moz-box-shadow:0px 1px 0px rgba(255,255,255,0.1) inset,0px -2px 1px rgba(0,0,0,0.2) inset;-webkit-box-shadow:0px 1px 0px rgba(255,255,255,0.1) inset,0px -2px 1px rgba(0,0,0,0.2) inset;box-shadow:0px 1px 0px rgba(255,255,255,0.1) inset,0px -2px 1px rgba(0,0,0,0.2) inset;-o-box-sizing:border-box;-ms-box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;box-sizing:border-box}aside#nav{float:left}aside#nav nav{margin:10px;width:160px;float:left;clear:left;margin-bottom:2em}aside#nav #mygames_title{clear:left;margin:0 10px 0;white-space:nowrap;font-weight:bold}nav#menu a,nav#mygames a{text-align:right;font-size:0.85em;padding:6px 5px;width:100%;white-space:nowrap;margin:0;font-weight:bold;text-decoration:none;display:block;color:#DDD;background-color:transparent;border-bottom:1px solid #333;-o-box-sizing:border-box;-ms-box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;box-sizing:border-box}nav#menu a:hover,nav#mygames a:hover{color:#FFF;background-color:rgba(40,14,12,0.5)}nav#menu ul,nav#mygames ul{margin:0;padding:0}nav#menu li,nav#mygames li{text-indent:0;margin:0;padding:0;list-style:none outside none}nav#menu li.active a,nav#mygames li.active a{color:inherit;background-color:rgba(255,255,255,0.1)}nav#menu li:first-child a,nav#mygames li:first-child a{-o-border-radius:2px 2px 0 0;-ms-border-radius:2px 2px 0 0;-moz-border-radius:2px 2px 0 0;-webkit-border-radius:2px 2px 0 0;border-radius:2px 2px 0 0}nav#menu li:last-child a,nav#mygames li:last-child a{border-bottom:0;-o-border-radius:0 0 2px 2px;-ms-border-radius:0 0 2px 2px;-moz-border-radius:0 0 2px 2px;-webkit-border-radius:0 0 2px 2px;border-radius:0 0 2px 2px}nav#menu li span.sep,nav#mygames li span.sep{color:#666}nav#mygames a{white-space:normal}nav#mygames .finished a{color:#999}nav#mygames .playing a{color:#B00}nav#mygames .my_turn a{color:#FF0}nav#mygames .none a{color:#FFF}aside#info{float:right;width:160px}aside#info #chatbox{float:right;width:160px;padding:5px;margin:3px;background-color:#EEE;border:1px solid #777}aside#info #chatbox input{width:95%}aside#info #chats{height:300px}aside#info .active{position:relative;top:0;right:0;width:500px}div#notes{float:right;width:200px;margin:10px}div#notes.box > *{min-height:300px}#chatbox input[type=text]{width:90%}#game_page #chatbox input[type=text]{width:auto}h2{font-size:100%;font-weight:bold;margin-bottom:1ex;border-bottom:1px solid #777}.type{font-size:smaller;padding-left:2em}.type .number{font-weight:bold;margin-right:2em}.type a{margin:0 2em}#content{margin:20px 220px 20px 180px;position:relative}#content.box > *{min-height:300px}#content.full{margin:5px}#content .sidebar{float:right;width:300px;margin-top:10px}#content form .buttons #delete{float:right}#content form .buttons .prevnext{margin-bottom:20px}#content form .buttons .prevnext span{padding:0 10px}#content #recipient_list{margin-top:20px}#content.msg{width:850px;margin:auto}.stats{width:150px;float:left;margin:3px}#index_page .tableholder{max-height:300px;overflow-y:auto}#index_page #chatbox{border:1px solid #777}#index_page #chatbox input[type=text]{width:99%}#index_page #chats{border-top:1px solid #777;max-height:500px;overflow:auto}#index_page #chats dt{height:50px;width:150px;float:left;border-bottom:3px solid #777;padding:5px;margin:0 20px 5px 0;position:relative;text-align:right;background:transparent;font-weight:bold}#index_page #chats dd{min-height:50px;border-bottom:1px solid #AAA;padding:5px 5px 6px 5px;margin:0 0 6px 0}#index_page #chats img{float:left}#index_page #chats span{position:absolute;bottom:5px;right:5px;font-size:80%;font-weight:normal}h2.subject,p.message{width:70ex}.sender{margin-left:3em;font-size:smaller}.link_date{float:right;text-align:right;width:300px}.link_date a{float:left}#recipient_list ul{margin:10px}#recipient_list .unread{font-weight:bold}#recipient_list .deleted{text-decoration:line-through}.action select{float:right}#footerspacer{height:50px;clear:both}footer{font-size:0.9em;font-weight:bold;line-height:26px;clear:both;padding:3px 0;left:0;z-index:100;position:fixed;bottom:0;left:-25%;width:150%;padding:15px 5px 5px;text-align:center;color:#DDD;background-color:#670B0C;-o-box-shadow:0px 3px 16px #000000 inset;-ms-box-shadow:0px 3px 16px #000000 inset;-moz-box-shadow:0px 3px 16px #000000 inset;-webkit-box-shadow:0px 3px 16px #000000 inset;box-shadow:0px 3px 16px #000000 inset;-o-box-sizing:border-box;-ms-box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;box-sizing:border-box}footer span{margin:0 2em}footer p{margin:0;padding:0;line-height:130%}.notice{font-weight:bold}.afterthought{font-size:0.85em;font-weight:normal}.instruction{margin:0 0 10px 10px;font-size:0.85em;line-height:11px}ul.settings li{float:left;width:100%}ul.settings label{clear:left}#buttons{float:right;margin-right:1px}#buttons li{float:left;margin-left:1px}#buttons a{display:block;padding:0 1em;border:1px solid #333;border-width:0 1px;margin:0 -1px}.clone{display:none;visibility:hidden}div.help{padding:10px}div.help ol,div.help ul{text-indent:-1em;margin:0 0 1ex 2em}div.help li{text-indent:-1em;margin-bottom:1ex}div.help li strong{color:#F00}div.help table{width:auto;margin:0 auto}h2 span{margin-left:50px}h2 span span{margin-left:0}#pieces_display{height:200px;width:700px;float:left;clear:left;margin-top:20px}#pieces_display #cancel_delete{float:left;height:200px;width:50px}#pieces_display #silver_pieces,#pieces_display #red_pieces{float:left;height:100px;width:530px}#pieces_display #red_pieces{margin-top:5px}#pieces_display img{border:2px solid transparent}#pieces_display img.selected{border-color:#FFF}#setup_display{float:left;clear:left;margin:20px 10px;width:auto}.sil{background-color:#AAA !important;color:#000 !important}.red{background-color:#B00 !important;color:#FFF !important}.blu{background-color:#36F !important;color:#FFF !important}#fancybox-content{background-color:#000 !important}table{height:1px;margin:1em 0;width:100%;line-height:120%}th{font-weight:bold;text-align:center;vertical-align:bottom;border-bottom:1px solid #B1B1B1;padding:2px 1ex 1px;white-space:nowrap}.datatable tr:hover > td,.datatable tr.alt:hover > td{background-color:#444;color:#FFF}td{border-right:1px solid #433F3F;padding:0 7px;text-align:left;vertical-align:middle;line-height:180%}td:last-child{border-right:none}.alt{background-color:#1D1D21}td.numeric{text-align:right}td.date,td.fortify{white-space:nowrap}td.join,td.remove,td.edit{text-align:center;vertical-align:middle;width:1px}.highlight,.highlight td{font-weight:bold}.lowlight,.lowlight td{color:#666}th.remove{width:1px}caption{font-weight:bold}thead tr th{background-color:transparent;border-top:1px solid transparent}thead tr .header{cursor:pointer}thead tr .headerSortDown,thead tr .headerSortUp{color:#FFF}thead tr .headerSortUp{border-top:1px solid #FFF}thead tr .headerSortDown{border-bottom:1px solid #FFF}.formdiv hr{border:0;border-bottom:2px solid #AAA;width:90%;height:1px;margin:0 auto}.label{font-weight:bold}label{margin-top:1px;font-weight:bold;float:left;width:130px}.block{margin-left:130px}label.unlabel,label.inside,label.inline{float:none;width:auto;margin:0}label.unlabel{font-weight:normal}label.error{display:none !important;border:0}.error{border:1px solid #C00}.input,input,textarea,select{margin:1px}.input{line-height:2;font-weight:bold}.input,input,select{vertical-align:middle}input[type="checkbox"],input[type="radio"]{margin:3px 3px 3px 4px}input[type="text"]:focus,input[type="password"]:focus,textarea:focus{border:2px solid #848B97}input[type="text"].error:focus,input[type="password"].error:focus,textarea.error:focus{border-color:#C00}.req:before{content:'*';font-size:larger;color:#C00;font-weight:bold;padding-right:2px;vertical-align:middle}.formdiv .submit{border-top:1px solid #AAA;text-align:center;padding:10px}.formdiv .errors{border-top:1px solid #AAA;border-bottom:1px dashed #AAA;display:none;color:#C00;font-weight:bold;font-size:14px;padding:10px;text-align:center}.formdiv > div{float:left;clear:left;width:100%}.formdiv > fieldset{clear:both}.formdiv .options{display:none}.test img{vertical-align:middle}table.form{width:auto}.info{color:#999}div.color{margin-top:1em}div.info{margin:1em 0 0 130px;width:400px;float:none;clear:both}.forminfo{width:400px;color:#444;margin-bottom:1em}.overlabel-apply{position:absolute;top:1px;left:5px;z-index:5;color:#AAA}.overlabel-float{float:left;margin:2px;position:relative} +html,body,div,span,applet,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,big,cite,code,del,dfn,em,font,img,ins,kbd,q,s,samp,small,strike,strong,sub,sup,tt,var,dl,dt,dd,ol,ul,li,fieldset,form,label,legend,table,caption,tbody,tfoot,thead,tr,th,td{margin:0;padding:0;border:0;outline:0;font-weight:inherit;font-style:inherit;font-size:100%;font-family:inherit}:focus{outline:0}body{line-height:1;color:black;background:white}ol,ul{list-style:none}table{border-collapse:separate;border-spacing:0}caption,th,td{text-align:left;font-weight:normal}blockquote:before,blockquote:after,q:before,q:after{content:""}blockquote,q{quotes:"" ""}strong{font-weight:bold}em{font-style:italic}em em{font-style:normal}pre{font-family:monospace}html,body{background-color:#27282B;color:#FFF;margin:0;padding:0;font-size:14px;line-height:1.5;font-weight:normal;font-family:Calibri, sans-serif}a{font-weight:bold;text-decoration:underline;color:#FFF}a:hover{text-decoration:none}a.help{border:1px solid #777;font-weight:bold;padding:0 4px;text-decoration:none}a.help:hover{border:1px solid #999}abbr,acronym{border-bottom:1px dashed #777;cursor:help}hr{width:90%;margin:1em auto}hr.fancy{height:5px;margin:1em;background-color:#999;border:1px solid #777}p{margin:0.5em 0 1em;line-height:1.2}fieldset{padding:5px;margin:5px;border:1px solid #555}legend{font-weight:bold;line-height:1;padding:0 5px}.warning,.warning *{color:#B00;font-weight:bold}.notice,.notice *{color:#DD0;font-weight:bold}.highlight,.highlight *{color:#B00;font-weight:bold}.instruction,.instruction *{color:#AAA}.caption{margin:1ex 0}.clr{clear:both !important;float:none !important}#date{font-size:0.85em;font-weight:bold;white-space:nowrap;text-align:right}header{min-height:60px;width:100%;margin:0 0 10px;padding:5px;position:relative;border-bottom:1px solid #CE3E47;background-color:#670B0C;background:-o-radial-gradient(50% 100%, ellipse cover, #a72819 30%, #670b0c 80%) #670b0c;background:-ms-radial-gradient(50% 100%, ellipse cover, #a72819 30%, #670b0c 80%) #670b0c;background:-moz-radial-gradient(50% 100%, ellipse cover, #a72819 30%, #670b0c 80%) #670b0c;background:-webkit-radial-gradient(50% 100%, ellipse cover, #a72819 30%, #670b0c 80%) #670b0c;background:radial-gradient(50% 100%, ellipse cover, #a72819 30%,#670b0c 80%) #670b0c;-o-box-shadow:0px 3px 16px #000,0px -3px 0px rgba(0,0,0,0.4) inset;-ms-box-shadow:0px 3px 16px #000,0px -3px 0px rgba(0,0,0,0.4) inset;-moz-box-shadow:0px 3px 16px #000,0px -3px 0px rgba(0,0,0,0.4) inset;-webkit-box-shadow:0px 3px 16px #000,0px -3px 0px rgba(0,0,0,0.4) inset;box-shadow:0px 3px 16px #000,0px -3px 0px rgba(0,0,0,0.4) inset;-o-box-sizing:border-box;-ms-box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;box-sizing:border-box}h1{height:45px;margin:0 0 3px;padding:0;font-size:1.1em;font-weight:bold;text-indent:-9999em}h1 a{background:transparent url(../images/Pharaoh.png) no-repeat scroll 15px center;display:block;text-decoration:none;height:100%}nav.site{float:right;position:absolute;top:15px;right:10px;margin:10px}nav.site a{text-decoration:none;padding:3px 10px;color:#DDD;font-weight:bold;text-shadow:#000 0 1px 1px}nav.site a:hover{color:#FFF;background:-o-radial-gradient(50% 90%, ellipse closest-corner, rgba(255,255,255,0.35) 30%, rgba(255,255,255,0.01) 70%) transparent;background:-ms-radial-gradient(50% 90%, ellipse closest-corner, rgba(255,255,255,0.35) 30%, rgba(255,255,255,0.01) 70%) transparent;background:-moz-radial-gradient(50% 90%, ellipse closest-corner, rgba(255,255,255,0.35) 30%, rgba(255,255,255,0.01) 70%) transparent;background:-webkit-radial-gradient(50% 100%, 80% 20%, rgba(255,255,255,0.35) 30%, rgba(255,255,255,0.01) 70%) transparent;background:radial-gradient(50% 100%, 80% 20%, rgba(255,255,255,0.35) 30%,rgba(255,255,255,0.01) 70%) transparent}*.box{display:block;margin:0;padding:1px;-o-border-radius:4px;-ms-border-radius:4px;-moz-border-radius:4px;-webkit-border-radius:4px;border-radius:4px;background-color:#000000;background:-o-linear-gradient(#232323, #000) #000;background:-ms-linear-gradient(#232323, #000) #000;background:-moz-linear-gradient(#232323, #000) #000;background:-webkit-linear-gradient(#232323, #000) #000;background:linear-gradient(#232323,#000000) #000;-o-box-sizing:border-box;-ms-box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;box-sizing:border-box}*.box>*{padding:5px;display:block;margin:0;height:100%;overflow:auto;-o-border-radius:2px;-ms-border-radius:2px;-moz-border-radius:2px;-webkit-border-radius:2px;border-radius:2px;background-color:#2E2F34;background:-o-linear-gradient(#2e2f34, #212225) #2e2f34;background:-ms-linear-gradient(#2e2f34, #212225) #2e2f34;background:-moz-linear-gradient(#2e2f34, #212225) #2e2f34;background:-webkit-linear-gradient(#2e2f34, #212225) #2e2f34;background:linear-gradient(#2e2f34,#212225) #2e2f34;-o-box-shadow:0px 1px 0px rgba(255,255,255,0.1) inset,0px -2px 1px rgba(0,0,0,0.2) inset;-ms-box-shadow:0px 1px 0px rgba(255,255,255,0.1) inset,0px -2px 1px rgba(0,0,0,0.2) inset;-moz-box-shadow:0px 1px 0px rgba(255,255,255,0.1) inset,0px -2px 1px rgba(0,0,0,0.2) inset;-webkit-box-shadow:0px 1px 0px rgba(255,255,255,0.1) inset,0px -2px 1px rgba(0,0,0,0.2) inset;box-shadow:0px 1px 0px rgba(255,255,255,0.1) inset,0px -2px 1px rgba(0,0,0,0.2) inset;-o-box-sizing:border-box;-ms-box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;box-sizing:border-box}aside#nav{float:left}aside#nav nav{margin:10px;width:160px;float:left;clear:left;margin-bottom:2em}aside#nav #mygames_title{clear:left;margin:0 10px 0;white-space:nowrap;font-weight:bold}nav#menu a,nav#mygames a{text-align:right;font-size:0.85em;padding:6px 5px;width:100%;white-space:nowrap;margin:0;font-weight:bold;text-decoration:none;display:block;color:#DDD;background-color:transparent;border-bottom:1px solid #333;-o-box-sizing:border-box;-ms-box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;box-sizing:border-box}nav#menu a:hover,nav#mygames a:hover{color:#FFF;background-color:rgba(40,14,12,0.5)}nav#menu ul,nav#mygames ul{margin:0;padding:0}nav#menu li,nav#mygames li{text-indent:0;margin:0;padding:0;list-style:none outside none}nav#menu li.active a,nav#mygames li.active a{color:inherit;background-color:rgba(255,255,255,0.1)}nav#menu li:first-child a,nav#mygames li:first-child a{-o-border-radius:2px 2px 0 0;-ms-border-radius:2px 2px 0 0;-moz-border-radius:2px 2px 0 0;-webkit-border-radius:2px 2px 0 0;border-radius:2px 2px 0 0}nav#menu li:last-child a,nav#mygames li:last-child a{border-bottom:0;-o-border-radius:0 0 2px 2px;-ms-border-radius:0 0 2px 2px;-moz-border-radius:0 0 2px 2px;-webkit-border-radius:0 0 2px 2px;border-radius:0 0 2px 2px}nav#menu li span.sep,nav#mygames li span.sep{color:#666}nav#mygames a{white-space:normal}nav#mygames .finished a{color:#999}nav#mygames .playing a{color:#B00}nav#mygames .my_turn a{color:#FF0}nav#mygames .none a{color:#FFF}aside#info{float:right;width:160px}aside#info #chatbox{float:right;width:160px;padding:5px;margin:3px;background-color:#EEE;border:1px solid #777}aside#info #chatbox input{width:95%}aside#info #chats{height:300px}aside#info .active{position:relative;top:0;right:0;width:500px}div#notes{float:right;width:200px;margin:10px}div#notes.box>*{min-height:300px}#chatbox input[type=text]{width:90%}#game_page #chatbox input[type=text]{width:auto}h2{font-size:100%;font-weight:bold;margin-bottom:1ex;border-bottom:1px solid #777}.type{font-size:smaller;padding-left:2em}.type .number{font-weight:bold;margin-right:2em}.type a{margin:0 2em}#content{margin:20px 220px 20px 180px;position:relative}#content.box>*{min-height:300px}#content.full{margin:5px}#content .sidebar{float:right;width:300px;margin-top:10px}#content form .buttons #delete{float:right}#content form .buttons .prevnext{margin-bottom:20px}#content form .buttons .prevnext span{padding:0 10px}#content #recipient_list{margin-top:20px}#content.msg{width:850px;margin:auto}.stats{width:150px;float:left;margin:3px}#index_page .tableholder{max-height:300px;overflow-y:auto}#index_page #chatbox{border:1px solid #777}#index_page #chatbox input[type=text]{width:99%}#index_page #chats{border-top:1px solid #777;max-height:500px;overflow:auto}#index_page #chats dt{height:50px;width:150px;float:left;border-bottom:3px solid #777;padding:5px;margin:0 20px 5px 0;position:relative;text-align:right;background:transparent;font-weight:bold}#index_page #chats dd{min-height:50px;border-bottom:1px solid #AAA;padding:5px 5px 6px 5px;margin:0 0 6px 0}#index_page #chats img{float:left}#index_page #chats span{position:absolute;bottom:5px;right:5px;font-size:80%;font-weight:normal}#invites{float:none}h2.subject,p.message{width:70ex}.sender{margin-left:3em;font-size:smaller}.link_date{float:right;text-align:right;width:300px}.link_date a{float:left}#recipient_list ul{margin:10px}#recipient_list .unread{font-weight:bold}#recipient_list .deleted{text-decoration:line-through}.action select{float:right}#footerspacer{height:50px;clear:both}footer{font-size:0.9em;font-weight:bold;line-height:26px;clear:both;padding:3px 0;left:0;z-index:100;position:fixed;bottom:0;left:-25%;width:150%;padding:15px 5px 5px;text-align:center;color:#DDD;background-color:#670B0C;-o-box-shadow:0px 3px 16px #000000 inset;-ms-box-shadow:0px 3px 16px #000000 inset;-moz-box-shadow:0px 3px 16px #000000 inset;-webkit-box-shadow:0px 3px 16px #000000 inset;box-shadow:0px 3px 16px #000000 inset;-o-box-sizing:border-box;-ms-box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;box-sizing:border-box}footer span{margin:0 2em}footer p{margin:0;padding:0;line-height:130%}.notice{font-weight:bold}.afterthought{font-size:0.85em;font-weight:normal}.instruction{margin:0 0 10px 10px;font-size:0.85em;line-height:11px}ul.settings li{float:left;width:100%}ul.settings label{clear:left}#buttons{float:right;margin-right:1px}#buttons li{float:left;margin-left:1px}#buttons a{display:block;padding:0 1em;border:1px solid #333;border-width:0 1px;margin:0 -1px}.clone{display:none;visibility:hidden}div.help{padding:10px}div.help ol,div.help ul{text-indent:-1em;margin:0 0 1ex 2em}div.help li{text-indent:-1em;margin-bottom:1ex}div.help li strong{color:#F00}div.help table{width:auto;margin:0 auto}h2 span{margin-left:50px}h2 span span{margin-left:0}#pieces_display{height:200px;width:700px;float:left;clear:left;margin-top:20px}#pieces_display #cancel_delete{float:left;height:200px;width:50px}#pieces_display #silver_pieces,#pieces_display #red_pieces{float:left;height:100px;width:530px}#pieces_display #red_pieces{margin-top:5px}#pieces_display img{border:2px solid transparent}#pieces_display img.selected{border-color:#FFF}#setup_display{float:left;clear:left;margin:20px 10px;width:auto}.sil{background-color:#AAA !important;color:#000 !important}.red{background-color:#B00 !important;color:#FFF !important}.blu{background-color:#36F !important;color:#FFF !important}#fancybox-content{background-color:#000 !important}table{height:1px;margin:1em 0;width:100%;line-height:120%}th{font-weight:bold;text-align:center;vertical-align:bottom;border-bottom:1px solid #B1B1B1;padding:2px 1ex 1px;white-space:nowrap}.datatable tr:hover>td,.datatable tr.alt:hover>td{background-color:#444;color:#FFF}td{border-right:1px solid #433F3F;padding:0 7px;text-align:left;vertical-align:middle;line-height:180%}td:last-child{border-right:none}.alt{background-color:#1D1D21}td.numeric{text-align:right}td.date,td.fortify{white-space:nowrap}td.join,td.remove,td.edit{text-align:center;vertical-align:middle;width:1px}.highlight,.highlight td{font-weight:bold}.lowlight,.lowlight td{color:#666}th.remove{width:1px}caption{font-weight:bold}thead tr th{background-color:transparent;border-top:1px solid transparent}thead tr .header{cursor:pointer}thead tr .headerSortDown,thead tr .headerSortUp{color:#FFF}thead tr .headerSortUp{border-top:1px solid #FFF}thead tr .headerSortDown{border-bottom:1px solid #FFF}.formdiv{float:left}form+form{clear:left;margin-top:1em}.formdiv:before,.formdiv:after{content:"";display:table}.formdiv:after{clear:both}.formdiv hr{border:0;border-bottom:2px solid #AAA;width:90%;height:1px;margin:0 auto}.label{font-weight:bold}label{margin-top:1px;font-weight:bold;float:left;width:130px}.block{margin-left:130px}label.unlabel,label.inside,label.inline{float:none;width:auto;margin:0}label.unlabel{font-weight:normal}label.error{display:none !important;border:0}.error{border:1px solid #C00}.input,input,textarea,select{margin:1px}.input{line-height:2;font-weight:bold}.input,input,select{vertical-align:middle}input[type="checkbox"],input[type="radio"]{margin:3px 3px 3px 4px}input[type="text"]:focus,input[type="password"]:focus,textarea:focus{border:2px solid #848B97}input[type="text"].error:focus,input[type="password"].error:focus,textarea.error:focus{border-color:#C00}.req:before{content:'*';font-size:larger;color:#C00;font-weight:bold;padding-right:2px;vertical-align:middle}.formdiv .submit{border-top:1px solid #AAA;text-align:center;padding:10px}.formdiv .errors{border-top:1px solid #AAA;border-bottom:1px dashed #AAA;display:none;color:#C00;font-weight:bold;font-size:14px;padding:10px;text-align:center}.formdiv>div{float:left;clear:left;width:100%}.formdiv>fieldset{clear:both}.formdiv .options{display:none}.test img{vertical-align:middle}table.form{width:auto}.info{color:#999}div.color{margin-top:1em}div.info{margin:1em 0 0 130px;width:400px;float:none;clear:both}.forminfo{width:400px;color:#444;margin-bottom:1em}.overlabel-apply{position:absolute;top:1px;left:5px;z-index:5;color:#AAA}.overlabel-float{float:left;margin:2px;position:relative} diff --git a/css/scss/_board.scss b/css/scss/_board.scss index b9c707e..6560aa9 100644 --- a/css/scss/_board.scss +++ b/css/scss/_board.scss @@ -1,122 +1,123 @@ /* the board styles ------------ + pharaoh specific do not edit these, if things need to be moved edit #board in game.scss, things will break horribly if these sizes are changed */ .a_board { background-color: #1F2023; color: #CCC; width: 550px; height: 450px; .header { text-align: center; font-weight: bold; font-size: 16px; } div { border: 1px solid #000; float: left; clear: none; width: 44px; height: 44px; margin: 1px; padding: 1px; position: relative; overflow: hidden; } .vert { border: 0; margin: 0; padding: 0; width: 25px; height: 50px; line-height: 50px; } .horz { border: 0; margin: 0; padding: 0; width: 50px; height: 25px; line-height: 25px; } .corner { border: 0; margin: 0; padding: 0; width: 25px; height: 25px; div { border: 2px solid #FFF; width: 14px; height: 14px; margin: 4px; padding: 0; line-height: 10px; -moz-border-radius: 14px; -webkit-border-radius: 14px; border-radius: 14px; &.alive { border-color: #0C0; background: #090; } &.immune { border-color: #CC0; background: #990; color: #FFF; } &.dead { border-color: #C00; background: #900; color: #FFF; } } } .c_silver { background-color: #555; } .c_red { background-color: #500; } .highlight { background-color: #550; } .piece { background-position: center center; background-repeat: no-repeat; } div { img { position: absolute; top: 0; left: 0; &.piece { position: absolute; top: 1px; left: 1px; } } } img.ccw { margin-left: 23px; } } diff --git a/css/scss/game.scss b/css/scss/game.scss index 6a85153..acbd364 100644 --- a/css/scss/game.scss +++ b/css/scss/game.scss @@ -1,100 +1,104 @@ /* Game page specific CSS */ @import "board"; #contents { margin: 10px; } #chatbox { margin-left: 732px; } #chats { height: 450px; } #game_page { #chatbox { input[type=text] { width: 80%; } + + dd { + padding-left: 1em; + } } } #board_wrapper { float: left; width: 550px; margin-left: 5px; } #board { width: 550px; height: 450px; } #history { float: left; width: 170px; table { margin: 0; td { padding: 0 5px; font-size: 1.1em; line-height: 130%; &.active, &:hover { font-weight: bold; background-color: #444; color: #FFF; } &.turn { width: 1%; text-align: right; } } } div div { margin-bottom: 2px; text-align: center; span { padding: 2px 5px 1px; border: 1px solid #555; -moz-border-radius: 3px; -webkit-border-radius: 3px; border-radius: 3px; cursor: pointer; &:hover { border-color: #AAA; } &.disabled { color: #AAA; border-color: #333; cursor: default; } } } } form#game { clear: both; text-align: center; padding-top: 20px; } #setup { display: none; } diff --git a/includes/func.global.php b/includes/func.global.php index 57d23e3..4485289 100644 --- a/includes/func.global.php +++ b/includes/func.global.php @@ -1,296 +1,346 @@ <?php /** function call [dump] [debug] * This function is for debugging only * Outputs given var to screen * or, if no var given, outputs stars to note position * * @param mixed optional var to output * @param bool optional bypass debug value and output anyway * @action outputs var to screen * @return void */ function call($var = 'Th&F=xUFucreSp2*ezAhe=ApuPR*$axe', $bypass = false, $show_from = true, $new_window = false, $error = false) { if ((( ! defined('DEBUG') || ! DEBUG) || ! empty($GLOBALS['NODEBUG'])) && ! (bool) $bypass) { return false; } if ('Th&F=xUFucreSp2*ezAhe=ApuPR*$axe' === $var) { $contents = '<span style="font-size:larger;font-weight:bold;color:red;">--==((OO88OO))==--</span>'; } else { // begin output buffering so we can escape any html // and print_r is better at catching recursion than var_export ob_start( ); if ((is_string($var) && ! preg_match('/^\\s*$/', $var))) { // non-whitespace strings print_r($var); } else { if ( ! function_exists('xdebug_disable')) { if (is_array($var) || is_object($var)) { print_r($var); } else { var_dump($var); } } else { var_dump($var); } } // end output buffering and output the result if ( ! function_exists('xdebug_disable')) { $contents = htmlentities(ob_get_contents( )); } else { $contents = ob_get_contents( ); } ob_end_clean( ); } $j = 0; $html = ''; $debug_funcs = array('dump', 'debug'); if ((bool) $show_from) { $called_from = debug_backtrace( ); if (isset($called_from[$j + 1]) && in_array($called_from[$j + 1]['function'], $debug_funcs)) { ++$j; } $file0 = substr($called_from[$j]['file'], strlen($_SERVER['DOCUMENT_ROOT'])); $line0 = $called_from[$j]['line']; $called = ''; if (isset($called_from[$j + 1]['file'])) { $file1 = substr($called_from[$j + 1]['file'], strlen($_SERVER['DOCUMENT_ROOT'])); $line1 = $called_from[$j + 1]['line']; $called = "{$file1} : {$line1} called "; } elseif (isset($called_from[$j + 1]['class'])) { $called = $called_from[$j + 1]['class'].$called_from[$j + 1]['type'].$called_from[$j + 1]['function'].' called '; } $html = "<strong>{$called}{$file0} : {$line0}</strong>\n"; } if ( ! $new_window) { $color = '#000'; if ($error) { $color = '#F00'; } echo "\n\n<pre style=\"background:#FFF;color:{$color};font-size:larger;\">{$html}{$contents}\n<hr /></pre>\n\n"; } else { ?> <script language="javascript"> myRef = window.open('','debugWindow'); myRef.document.write('\n\n<pre style="background:#FFF;color:#000;font-size:larger;">'); myRef.document.write('<?php echo str_replace("'", "\'", str_replace("\n", "<br />", "{$html}{$contents}")); ?>'); myRef.document.write('\n<hr /></pre>\n\n'); </script> <?php } } function dump($var = 'Th&F=xUFucreSp2*ezAhe=ApuPR*$axe', $bypass = false, $show_from = true, $new_window = false, $error = false) { call($var, $bypass, $show_from, $new_window, $error); } function debug($var = 'Th&F=xUFucreSp2*ezAhe=ApuPR*$axe', $bypass = true, $show_from = true, $new_window = false, $error = false) { call($var, $bypass, $show_from, $new_window, $error); } /** function load_class * This function automagically loads the class * via the spl_autoload_register function above * as it is instantiated (jit). * * @param string class name * @action loads given class name if found * @return bool success */ function load_class($class_name) { $class_file = CLASSES_DIR.strtolower($class_name).'.class.php'; if (class_exists($class_name)) { return true; } elseif (file_exists($class_file) && is_readable($class_file)) { require_once $class_file; return true; } else { throw new MyException(__FUNCTION__.': Class file ('.$class_file.') not found'); } } /** function test_token * This function tests the token given by the * form and checks it against the session token * and if they do not match, dies * * @param bool optional keep original token flag * @action tests tokens and dies if bad * @action optionally renews the session token * @return void */ function test_token($keep = false) { call($_SESSION['token']); call($_POST['token']); if (DEBUG) { return; } if ( ! isset($_SESSION['token']) || ! isset($_POST['token']) || (0 !== strcmp($_SESSION['token'], $_POST['token']))) { die('Hacking attempt detected.<br /><br />If you have reached this page in error, please go back,<br />clear your cache, refresh the page, and try again.'); } // renew the token if ( ! $keep) { $_SESSION['token'] = md5(uniqid(rand( ), true)); } } /** function test_debug * This function tests the debug given by the * URL and checks it against the globals debug password * and if they do not match, doesn't debug * * @param void * @action tests debug pass * @return bool success */ function test_debug( ) { if ( ! isset($_GET['DEBUG'])) { return false; } if ( ! class_exists('Settings') || ! Settings::test( )) { return false; } if ('' == trim(Settings::read('debug_pass'))) { return false; } if (0 !== strcmp($_GET['DEBUG'], Settings::read('debug_pass'))) { return false; } $GLOBALS['_&_DEBUG_QUERY'] = '&DEBUG='.$_GET['DEBUG']; $GLOBALS['_?_DEBUG_QUERY'] = '?DEBUG='.$_GET['DEBUG']; return true; } /** function expandFEN * This function expands a packed FEN into a * string where each index is a valid location * * @param string packed FEN * @return string expanded FEN */ function expandFEN($FEN) { $FEN = preg_replace('/\s+/', '', $FEN); // remove spaces $FEN = preg_replace_callback('/\d+/', 'replace_callback', $FEN); // unpack the 0s $xFEN = str_replace('/', '', $FEN); // remove the row separators return $xFEN; } function replace_callback($match) { return (((int) $match[0]) ? str_repeat('0', (int) $match[0]) : $match[0]); } /** function packFEN * This function packs an expanded FEN into a * string that takes up less space * * @param string expanded FEN * @param int [optional] length of rows * @return string packed FEN */ function packFEN($xFEN, $row_length = 10) { $xFEN = preg_replace('/\s+/', '', $xFEN); // remove spaces $xFEN = preg_replace('/\//', '', $xFEN); // remove any row separators $xFEN = trim(chunk_split($xFEN, $row_length, '/'), '/'); // add the row separators $FEN = preg_replace('/(0+)/e', "strlen('\\1')", $xFEN); // pack the 0s return $FEN; } +/** function get_index + * + * Gets the FEN string index for a 2D location + * of a square array of blocks each containing + * a square array of elements within those blocks + * + * This was designed for use within foreach structures + * The first foreach ($i) is the outer blocks, and the + * second ($j) is for the inner elements. + * + * Example Structure: + * +----+----+----++----+----+----+ + * | 0 | 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 | 29 | + * +----+----+----++----+----+----+ + * | 30 | 31 | 32 || 33 | 34 | 35 | + * +----+----+----++----+----+----+ + * + * Where $i = 2 (bottom left big block) + * and $j = 5 (center element) + * $blocks = 2 (number of blocks per side) + * $elems = 3 (numer of elements per side in each block) + * will return 25 (the index of the string) + * + * @param int the current block number + * @param int the current element number + * @param int the number of blocks per side + * @param int the number of elements per side per block + * @return int the FEN string index + */ +function get_index($i, $j, $blocks = 3, $elems = 3) { + $bits = array( + ($j % $elems), // across within block (across elems) + ((int) floor($j / $elems) * $blocks * $elems), // down within block (down elems) + (($i % $blocks) * $elems), // across blocks + ((int) floor($i / $blocks) * $blocks * $elems * $elems), // down blocks + ); + + return array_sum($bits); +} + + + /** function ife * if-else * This function returns the value if it exists (or is optionally not empty) * or a default value if it does not exist (or is empty) * * @param mixed var to test * @param mixed optional default value * @param bool optional allow empty value * @param bool optional change the passed reference var * @return mixed $var if exists (and not empty) or default otherwise */ function ife( & $var, $default = null, $allow_empty = true, $change_reference = false) { if ( ! isset($var) || ( ! (bool) $allow_empty && empty($var))) { if ((bool) $change_reference) { $var = $default; // so it can also be used by reference } return $default; } return $var; } /** function ifer * if-else reference * This function returns the value if it exists (or is optionally not empty) * or a default value if it does not exist (or is empty) * It also changes the reference var * * @param mixed var to test * @param mixed optional default value * @param bool optional allow empty value * @action updates/sets the reference var if needed * @return mixed $var if exists (and not empty) or default otherwise */ function ifer( & $var, $default = null, $allow_empty = true) { return ife($var, $default, $allow_empty, true); } /** function ifenr * if-else non-reference * This function returns the value if it is not empty * or a default value if it is empty * * @param mixed var to test * @param mixed optional default value * @return mixed $var if not empty or default otherwise */ function ifenr($var, $default = null) { if (empty($var)) { return $default; } return $var; } diff --git a/install.sql b/install.sql index 46825af..5b6ccd7 100644 --- a/install.sql +++ b/install.sql @@ -1,262 +1,302 @@ -- phpMyAdmin SQL Dump -- version 3.4.2 -- http://www.phpmyadmin.net -- -- Host: localhost -- Generation Time: Jun 28, 2011 at 01:47 AM -- Server version: 5.5.10 -- PHP Version: 5.3.6 SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; -- --- Database: `iohelixn_games` +-- Database: `iohelix_games` -- -- -------------------------------------------------------- -- -- Table structure for table `ph_chat` -- CREATE TABLE IF NOT EXISTS `ph_chat` ( `chat_id` int(10) unsigned NOT NULL AUTO_INCREMENT, `message` text COLLATE latin1_general_ci NOT NULL, `from_id` int(10) unsigned NOT NULL DEFAULT '0', `game_id` int(10) unsigned NOT NULL DEFAULT '0', `private` tinyint(1) unsigned NOT NULL DEFAULT '0', `create_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`chat_id`), KEY `game_id` (`game_id`), KEY `private` (`private`), KEY `from_id` (`from_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci; -- -------------------------------------------------------- -- -- Table structure for table `ph_game` -- CREATE TABLE IF NOT EXISTS `ph_game` ( `game_id` int(10) unsigned NOT NULL AUTO_INCREMENT, `white_id` int(10) unsigned DEFAULT NULL, `black_id` int(10) unsigned DEFAULT NULL, `state` enum('Waiting','Playing','Finished','Draw') COLLATE latin1_general_ci NOT NULL DEFAULT 'Playing', `extra_info` text COLLATE latin1_general_ci, `winner_id` int(10) unsigned DEFAULT NULL, `setup_id` int(10) unsigned NOT NULL, `paused` tinyint(1) NOT NULL DEFAULT '0', `create_date` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', `modify_date` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`game_id`), KEY `state` (`state`), KEY `white_id` (`white_id`), KEY `black_id` (`black_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci; -- -------------------------------------------------------- -- -- Table structure for table `ph_game_history` -- CREATE TABLE IF NOT EXISTS `ph_game_history` ( `game_id` int(10) unsigned NOT NULL DEFAULT '0', `move` varchar(255) COLLATE latin1_general_ci DEFAULT NULL, `hits` varchar(255) COLLATE latin1_general_ci DEFAULT NULL, `board` varchar(87) COLLATE latin1_general_ci NOT NULL, `extra_info` text COLLATE latin1_general_ci, `move_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, KEY `game_id` (`game_id`), KEY `move_date` (`move_date`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci; -- -------------------------------------------------------- -- -- Table structure for table `ph_game_nudge` -- CREATE TABLE IF NOT EXISTS `ph_game_nudge` ( `game_id` int(10) unsigned NOT NULL DEFAULT '0', `player_id` int(10) unsigned NOT NULL DEFAULT '0', `nudged` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, UNIQUE KEY `game_player` (`game_id`,`player_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci; -- -------------------------------------------------------- -- -- Table structure for table `ph_message` -- CREATE TABLE IF NOT EXISTS `ph_message` ( `message_id` int(10) unsigned NOT NULL AUTO_INCREMENT, `subject` varchar(255) COLLATE latin1_general_ci NOT NULL DEFAULT '', `message` text COLLATE latin1_general_ci NOT NULL, `create_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`message_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci; -- -------------------------------------------------------- -- -- Table structure for table `ph_message_glue` -- CREATE TABLE IF NOT EXISTS `ph_message_glue` ( `message_glue_id` int(10) unsigned NOT NULL AUTO_INCREMENT, `message_id` int(10) unsigned NOT NULL DEFAULT '0', `from_id` int(10) unsigned NOT NULL DEFAULT '0', `to_id` int(10) unsigned NOT NULL DEFAULT '0', `send_date` datetime DEFAULT NULL, `expire_date` datetime DEFAULT NULL, `view_date` datetime DEFAULT NULL, `create_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `deleted` tinyint(1) unsigned NOT NULL DEFAULT '0', PRIMARY KEY (`message_glue_id`), KEY `outbox` (`from_id`,`message_id`), KEY `created` (`create_date`), KEY `expire_date` (`expire_date`), KEY `inbox` (`to_id`,`from_id`,`send_date`,`deleted`), KEY `message_id` (`message_id`,`to_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci; -- -------------------------------------------------------- -- -- Table structure for table `ph_ph_player` -- CREATE TABLE IF NOT EXISTS `ph_ph_player` ( `player_id` int(11) unsigned NOT NULL DEFAULT '0', `is_admin` tinyint(1) unsigned NOT NULL DEFAULT '0', `allow_email` tinyint(1) unsigned NOT NULL DEFAULT '1', `color` varchar(25) COLLATE latin1_general_ci NOT NULL DEFAULT 'blue_white', `invite_opt_out` tinyint(1) NOT NULL DEFAULT '0', `max_games` tinyint(3) unsigned NOT NULL DEFAULT '0', `wins` smallint(5) unsigned NOT NULL DEFAULT '0', `draws` smallint(5) unsigned NOT NULL DEFAULT '0', `losses` smallint(5) unsigned NOT NULL DEFAULT '0', `last_online` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP, UNIQUE KEY `id` (`player_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci; -- -------------------------------------------------------- -- -- Table structure for table `ph_settings` -- CREATE TABLE IF NOT EXISTS `ph_settings` ( `setting` varchar(255) COLLATE latin1_general_ci NOT NULL DEFAULT '', `value` text COLLATE latin1_general_ci NOT NULL, `notes` text COLLATE latin1_general_ci, `sort` smallint(5) unsigned NOT NULL DEFAULT '0', UNIQUE KEY `setting` (`setting`), KEY `sort` (`sort`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci; -- -- Dumping data for table `ph_settings` -- INSERT INTO `ph_settings` (`setting`, `value`, `notes`, `sort`) VALUES ('site_name', 'Your Site', 'The name of your site', 10), ('default_color', 'c_red_black.css', 'The default theme color for the script pages', 20), ('nav_links', '<a href="/">Home</a>', 'HTML code for your site''s navigation links to display on the script pages', 30), ('from_email', '[email protected]', 'The email address used to send game emails', 40), ('to_email', '[email protected]', 'The email address to send admin notices to (comma separated)', 50), ('new_users', '1', '(1/0) Allow new users to register (0 = off)', 60), ('approve_users', '0', '(1/0) Require admin approval for new users (0 = off)', 70), ('confirm_email', '0', '(1/0) Require email confirmation for new users (0 = off)', 80), ('max_users', '0', 'Max users allowed to register (0 = off)', 90), ('default_pass', 'change!me', 'The password to use when resetting a user''s password', 100), ('expire_users', '45', 'Number of days until untouched user accounts are deleted (0 = off)', 110), ('save_games', '1', '(1/0) Save games in the ''games'' directory on the server (0 = off)', 120), ('expire_finished_games', '7', 'Number of days until finished games are deleted (0 = off)', 128), ('expire_games', '30', 'Number of days until untouched games are deleted (0 = off)', 130), ('nudge_flood_control', '24', 'Number of hours between nudges. (-1 = no nudging, 0 = no flood control)', 135), ('timezone', 'UTC', 'The timezone to use for dates (<a href="http://www.php.net/manual/en/timezones.php">List of Timezones</a>)', 140), ('long_date', 'M j, Y g:i a', 'The long format for dates (<a href="http://www.php.net/manual/en/function.date.php">Date Format Codes</a>)', 150), ('short_date', 'Y.m.d H:i', 'The short format for dates (<a href="http://www.php.net/manual/en/function.date.php">Date Format Codes</a>)', 160), ('debug_pass', '', 'The DEBUG password to use to set temporary DEBUG status for the script', 170), ('DB_error_log', '1', '(1/0) Log database errors to the ''logs'' directory on the server (0 = off)', 180), ('DB_error_email', '0', '(1/0) Email database errors to the admin email addresses given (0 = off)', 190); -- -------------------------------------------------------- -- -- Table structure for table `ph_setup` -- CREATE TABLE IF NOT EXISTS `ph_setup` ( `setup_id` int(10) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(255) COLLATE latin1_general_ci NOT NULL, `board` varchar(87) COLLATE latin1_general_ci NOT NULL, `reflection` enum('Origin','Short','Long','None') COLLATE latin1_general_ci NOT NULL DEFAULT 'Origin', `has_horus` tinyint(1) NOT NULL DEFAULT '0', `has_tower` tinyint(1) NOT NULL DEFAULT '0', `used` int(11) NOT NULL DEFAULT '0', `silver_wins` int(10) unsigned NOT NULL DEFAULT '0', `draws` int(10) unsigned NOT NULL DEFAULT '0', `red_wins` int(10) unsigned NOT NULL DEFAULT '0', `shortest_game` int(10) unsigned DEFAULT NULL, `longest_game` int(10) unsigned DEFAULT NULL, `active` tinyint(1) NOT NULL DEFAULT '1', `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `created_by` int(10) unsigned NOT NULL DEFAULT '0' COMMENT 'the player id of the player that created the setup', PRIMARY KEY (`setup_id`), KEY `has_horus` (`has_horus`), KEY `has_tower` (`has_tower`), KEY `active` (`active`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci; +-- +-- Dumping data for table `ph_setup` +-- + +INSERT INTO `ph_setup` (`setup_id`, `name`, `board`, `reflection`, `has_horus`, `has_sphynx`, `has_anubis`, `has_tower`, `used`, `created`, `created_by`) VALUES +(NULL, 'Classic', '4wpwb2/2c7/3D6/a1C1xy1b1D/b1D1YX1a1C/6b3/7A2/2DWPW4', 'Origin', 0, 0, 0, 0, 0, NOW(), 0), +(NULL, 'Dynasty', '4cwb3/5p4/a3cwy3/b1x1D1B3/3d1b1X1D/3YWA3C/4P5/3DWA4', 'Origin', 0, 0, 0, 0, 0, NOW(), 0), +(NULL, 'Imhotep', '4wpwy2/10/3D2a3/aC2By2bD/bD2Yd2aC/3C2b3/10/2YWPW4', 'Origin', 0, 0, 0, 0, 0, NOW(), 0), +(NULL, 'Osiris', '1Y3cp1bC/2w3wb2/6D3/a3ix3D/b3XI3C/3b6/2DW3W2/aD1PA3y1', 'Origin', 1, 0, 0, 0, 0, NOW(), 0), +(NULL, 'Isis', '6wpb1/a1x3cw2/1X8/a1a1DI2c1/1A2ib1C1C/8x1/2WA3X1C/1DPW6', 'Origin', 1, 0, 0, 0, 0, NOW(), 0), +(NULL, 'Classic 2', '4wpwb2/2c7/3D6/a1C1xi1b1D/b1D1IX1a1C/6b3/7A2/2DWPW4', 'Origin', 1, 0, 0, 0, 0, NOW(), 0), +(NULL, 'Dynasty 2', '4cwb3/5p4/a3cwy3/b1h1D1B3/3d1b1H1D/3YWA3C/4P5/3DWA4', 'Origin', 1, 0, 0, 0, 0, NOW(), 0), +(NULL, 'Imhotep 2', '4wpwy2/10/3D2a3/aC2Bi2bD/bD2Id2aC/3C2b3/10/2YWPW4', 'Origin', 1, 0, 0, 0, 0, NOW(), 0), +(NULL, 'Khufu', '4wpwb2/5cb3/a5D3/4yX1a1D/b1C1Xy4/3b5C/3DA5/2DWPW4', 'Origin', 0, 0, 0, 0, 0, NOW(), 0), +(NULL, 'Imseti', '1B1wpb4/2Xbcw4/10/a3xc3D/b3AX3C/10/4WADx2/4DPW1d1', 'Origin', 0, 0, 0, 0, 0, NOW(), 0), +(NULL, 'Nefertiti', '4w1w3/3c1pb3/2C1cy1c2/a1Y6D/b6y1C/2A1YA1a2/3DP1A3/3W1W4', 'Origin', 0, 0, 0, 0, 0, NOW(), 0), +(NULL, 'Rameses', '3w1pwb2/4bc4/2Cb2x3/a4X3D/b3x4C/3X2Da2/4AD4/2DWP1W3', 'Origin', 0, 0, 0, 0, 0, NOW(), 0), +(NULL, 'Amarna', '1CBcwpw3/4bcb3/10/a2x2x3/3X2X2C/10/3DAD4/3WPWAda1', 'Origin', 0, 0, 0, 0, 0, NOW(), 0), +(NULL, 'Saqqara', '3cwp1wb1/4bxb3/a2D6/4X4D/b4x4/6b2C/3DXD4/1DW1PWA3', 'Origin', 0, 0, 0, 0, 0, NOW(), 0), +(NULL, 'Djoser''s Step', '3cw1w1b1/5p1b2/4bxb3/a4y3D/b3Y4C/3DXD4/2D1P5/1D1W1WA3', 'Origin', 0, 0, 0, 0, 0, NOW(), 0), +(NULL, 'Horemheb', '3c3b2/4wpw3/3x1x1b2/a3c1b2D/b2D1A3C/2D1X1X3/3WPW4/2D3A3', 'Origin', 0, 0, 0, 0, 0, NOW(), 0), +(NULL, 'Senet', '4cwb3/a2c1p1b2/4xwy3/5b3C/a3D5/3YWX4/2D1P1A2C/3DWA4', 'Origin', 0, 0, 0, 0, 0, NOW(), 0), +(NULL, 'Tutankhamun', '3w4b1/a1cpb5/3w1b4/b1x1y1b3/3D1Y1X1D/4D1W3/5DPA1C/1D4W3', 'Origin', 0, 0, 0, 0, 0, NOW(), 0), +(NULL, 'Offla', '3c1pwb2/4cwb3/2X2x4/a4D3D/b3b4C/4X2x2/3DWA4/2DWP1A3', 'Origin', 0, 0, 0, 0, 0, NOW(), 0), +(NULL, 'Ebana', '3xwpwb2/5x4/2DA6/a1CB5D/b5da1C/6cb2/4X5/2DWPWX3', 'Origin', 0, 0, 0, 0, 0, NOW(), 0), +(NULL, 'Qa''a', '3xwpwb2/4cy4/8bD/3c2b2C/a2D2A3/bD8/4YA4/2DWPWX3', 'Origin', 0, 0, 0, 0, 0, NOW(), 0), +(NULL, 'Qa''a 2', '3xwpwb2/4cy4/8bD/3c2b1hC/aH1D2A3/bD8/4YA4/2DWPWX3', 'Origin', 1, 0, 0, 0, 0, NOW(), 0), +(NULL, 'Seti I', '1XB1cw1pb1/a4cwy1D/6b3/10/10/3D6/b1YWA4C/1DP1WA1dx1', 'Origin', 0, 0, 0, 0, 0, NOW(), 0), +(NULL, 'Seti II', '1XB1cw1pb1/a4cwy1D/6b3/5i4/4I5/3D6/b1YWA4C/1DP1WA1dx1', 'Origin', 1, 0, 0, 0, 0, NOW(), 0), +(NULL, 'Ay', '4cw1wbC/3CB5/5x4/a3Ypb3/3DPy3C/4X5/5da3/aDW1WA4', 'Origin', 0, 0, 0, 0, 0, NOW(), 0), +(NULL, 'Horemheb 2', '3c3b2/4wpw3/3h1x1b2/a3c1b2D/b2D1A3C/2D1X1H3/3WPW4/2D3A3', 'Origin', 1, 0, 0, 0, 0, NOW(), 0), +(NULL, 'Akhenaten 2', '1B1c1p1bc1/4cwb3/h1y7/4da1X1H/h1x1CB4/7Y1H/3DWA4/1AD1P1A1d1', 'Origin', 1, 0, 0, 0, 0, NOW(), 0), +(NULL, 'Akhenaten', '1B1c1p1bc1/4cwb3/a1y7/4da1X1D/b1x1CB4/7Y1C/3DWA4/1AD1P1A1d1', 'Origin', 0, 0, 0, 0, 0, NOW(), 0), +(NULL, 'Dendera', '2c4b2/1x2da2y1/3d2a3/2d1pi1a2/2C1IP1B2/3C2B3/1Y2CB2X1/2D4A2', 'Origin', 1, 0, 0, 0, 0, NOW(), 0), +(NULL, 'Nefertiti B', '4w1w3/3c1pb3/a1C1cy1c2/b1Y7/7y1D/2A1YA1a1C/3DP1A3/3W1W4', 'Origin', 0, 0, 0, 0, 0, NOW(), 0), +(NULL, 'Tutankhamun B', '4w3b1/a2cpb4/4w1b3/b2x1y1b2/2D1Y1X2D/3D1W4/4DPA2C/1D3W4', 'Origin', 0, 0, 0, 0, 0, NOW(), 0), +(NULL, 'Setup No. 1', '4wpw3/5b4/4b1c2C/a4xy1bD/bD1YX4C/a2A1D4/4D5/3WPW4', 'Origin', 0, 0, 0, 0, 0, NOW(), 0), +(NULL, 'Diamond', '3cwb4/4p5/3Dw5/aC2yx2cD/bA2XY2aC/5Wb3/5P4/4DWA3', 'Origin', 0, 0, 0, 0, 0, NOW(), 0), +(NULL, 'Ivory', '2cpw1B2C/3w6/1a6c1/aC2x1X3/3x1X2aC/1A6C1/6W3/a2d1WPA2', 'Origin', 0, 0, 0, 0, 0, NOW(), 0); + -- -------------------------------------------------------- -- -- Table structure for table `ph_stats` -- DROP TABLE IF EXISTS `ph_stats`; CREATE TABLE IF NOT EXISTS `ph_stats` ( `player_id` int(10) unsigned NOT NULL, `game_id` int(10) unsigned NOT NULL, `setup_id` int(10) unsigned NOT NULL, `color` enum('white','black') COLLATE latin1_general_ci NOT NULL, `win` tinyint(1) NOT NULL DEFAULT '0', `move_count` int(10) unsigned NOT NULL DEFAULT '0', `start_date` datetime NOT NULL, `end_date` datetime NOT NULL, `hour_count` float(8,3) NOT NULL DEFAULT '0.000', UNIQUE KEY `player_id` (`player_id`,`game_id`,`setup_id`), KEY `move_count` (`move_count`), KEY `hour_count` (`hour_count`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci; -- -------------------------------------------------------- -- -- Table structure for table `player` -- CREATE TABLE IF NOT EXISTS `player` ( `player_id` int(11) unsigned NOT NULL AUTO_INCREMENT, `username` varchar(20) COLLATE latin1_general_ci NOT NULL DEFAULT '', `first_name` varchar(20) COLLATE latin1_general_ci DEFAULT NULL, `last_name` varchar(20) COLLATE latin1_general_ci DEFAULT NULL, `email` varchar(255) COLLATE latin1_general_ci NOT NULL DEFAULT '', `timezone` varchar(255) COLLATE latin1_general_ci NOT NULL DEFAULT '', `is_admin` tinyint(1) unsigned NOT NULL DEFAULT '0', `password` varchar(32) COLLATE latin1_general_ci NOT NULL DEFAULT '', `alt_pass` varchar(32) COLLATE latin1_general_ci NOT NULL DEFAULT '', `ident` varchar(32) COLLATE latin1_general_ci DEFAULT NULL, `token` varchar(32) COLLATE latin1_general_ci DEFAULT NULL, `create_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `is_approved` tinyint(1) unsigned NOT NULL DEFAULT '0', PRIMARY KEY (`player_id`), UNIQUE KEY `username` (`username`), UNIQUE KEY `email` (`email`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci;
benjamw/pharaoh
638da92b1c92ca3674f97f6e1e578ff556fb28e5
fixed spacing in readme
diff --git a/README.md b/README.md index f13a7ed..3dbf57a 100644 --- a/README.md +++ b/README.md @@ -1,47 +1,48 @@ Pharoah v1.0 + 2012-08-07 Benjam Welker (http://iohelix.net) INSTALLATION ---------------------------------- 1. Copy the /includes/config.php.sample file and rename to /inludes/config.php 2. Edit the file to your specifications 3. Upload all files to your server 4. Run install.sql on your MySQL server (via phpMyAdmin or any other method) This will create the tables and insert some basic settings 5. Register your admin account 6. Get into your MySQL server, and edit the account you just created in the "players" table, and set both `is_admin` and `is_approved` to 1 7. That's it, you're done UPGRADING ---------------------------------- 1. I apologize, but there is no upgrade script, you will have to manually compare the given install.sql file with your own tables and make any adjustments needed 2. Copy the /includes/config.php.sample file and rename to /inludes/config.php 3. Edit the file to your specifications 4. Delete all your old files (including the config file) 5. Upload all new files to your server 6. That's it, you're done SUPPORT ---------------------------------- If you find any bugs, have any feature requests or suggestions, or have any questions, please use the Issues system on github https://github.com/benjamw/pharaoh/issues
benjamw/pharaoh
85406494d5563dc9afcff99673220c69a0c6a15c
added readme
diff --git a/README.md b/README.md new file mode 100644 index 0000000..f13a7ed --- /dev/null +++ b/README.md @@ -0,0 +1,47 @@ +Pharoah v1.0 +2012-08-07 + +Benjam Welker (http://iohelix.net) + +INSTALLATION +---------------------------------- +1. Copy the /includes/config.php.sample file and rename to /inludes/config.php + +2. Edit the file to your specifications + +3. Upload all files to your server + +4. Run install.sql on your MySQL server (via phpMyAdmin or any other method) +This will create the tables and insert some basic settings + +5. Register your admin account + +6. Get into your MySQL server, and edit the account you just created in the +"players" table, and set both `is_admin` and `is_approved` to 1 + +7. That's it, you're done + + +UPGRADING +---------------------------------- +1. I apologize, but there is no upgrade script, you will have to manually compare +the given install.sql file with your own tables and make any adjustments needed + +2. Copy the /includes/config.php.sample file and rename to /inludes/config.php + +3. Edit the file to your specifications + +4. Delete all your old files (including the config file) + +5. Upload all new files to your server + +6. That's it, you're done + + +SUPPORT +---------------------------------- +If you find any bugs, have any feature requests or suggestions, or have +any questions, please use the Issues system on github +https://github.com/benjamw/pharaoh/issues + +
benjamw/pharaoh
61e640a985171a2296db822790a9f015a22294dc
moved game.js to end of file and incorporated end of file scripts
diff --git a/game.php b/game.php index 514e2b8..b64cb11 100644 --- a/game.php +++ b/game.php @@ -1,272 +1,265 @@ <?php require_once 'includes/inc.global.php'; // grab the game id if (isset($_GET['id'])) { $_SESSION['game_id'] = (int) $_GET['id']; } elseif ( ! isset($_SESSION['game_id'])) { if ( ! defined('DEBUG') || ! DEBUG) { Flash::store('No Game Id Given !'); } else { call('NO GAME ID GIVEN'); } exit; } // load the game // always refresh the game data, there may be more than one person online try { $Game = new Game((int) $_SESSION['game_id']); $players = $Game->get_players( ); } catch (MyException $e) { if ( ! defined('DEBUG') || ! DEBUG) { Flash::store('Error Accessing Game !'); } else { call('ERROR ACCESSING GAME :'.$e->outputMessage( )); } exit; } // MOST FORM SUBMISSIONS ARE AJAXED THROUGH /scripts/game.js // game buttons and moves are passed through the game controller if ( ! $Game->is_player($_SESSION['player_id'])) { $Game->watch_mode = true; $chat_html = ''; unset($Chat); } if ( ! $Game->watch_mode || $GLOBALS['Player']->is_admin) { $Chat = new Chat($_SESSION['player_id'], $_SESSION['game_id']); $chat_data = $Chat->get_box_list( ); $chat_html = ' <div id="chatbox"> <form action="'.$_SERVER['REQUEST_URI'].'" method="post"><div> <input id="chat" type="text" name="chat" /> <label for="private" class="inline"><input type="checkbox" name="private" id="private" value="yes" /> Private</label> </div></form> <dl id="chats">'; if (is_array($chat_data)) { foreach ($chat_data as $chat) { if ('' == $chat['username']) { $chat['username'] = '[deleted]'; } $color = 'blue'; if ( ! empty($players[$chat['player_id']]['color']) && ('white' == $players[$chat['player_id']]['color'])) { $color = 'silver'; } if ( ! empty($players[$chat['player_id']]['color']) && ('black' == $players[$chat['player_id']]['color'])) { $color = 'red'; } // preserve spaces in the chat text $chat['message'] = htmlentities($chat['message'], ENT_QUOTES, 'ISO-8859-1', false); $chat['message'] = str_replace("\t", ' ', $chat['message']); $chat['message'] = str_replace(' ', ' &nbsp;', $chat['message']); $chat_html .= ' <dt class="'.substr($color, 0, 3).'"><span>'.$chat['create_date'].'</span> '.$chat['username'].'</dt> <dd'.($chat['private'] ? ' class="private"' : '').'>'.$chat['message'].'</dd>'; } } $chat_html .= ' </dl> <!-- #chats --> </div> <!-- #chatbox -->'; } // build the history table $history_html = ''; $moves = $Game->get_move_history( ); foreach ($moves as $i => $move) { if ( ! is_array($move)) { break; } $id = ($i * 2) + 1; $history_html .= ' <tr> <td class="turn">'.($i + 1).'</td> <td id="mv_'.$id.'">'.$move[0].'</td> <td'.( ! empty($move[1]) ? ' id="mv_'.($id + 1).'"' : '').'>'.$move[1].'</td> </tr>'; } $turn = $Game->get_turn( ); if ($Game->draw_offered( )) { $turn = '<span>Draw Offered</span>'; } elseif ($Game->undo_requested( )) { $turn = '<span>Undo Requested</span>'; } elseif ($GLOBALS['Player']->username == $turn) { $turn = '<span class="'.$Game->get_color( ).'">Your turn</span>'; } elseif ( ! $turn) { $turn = ''; } else { $turn = '<span class="'.$Game->get_color(false).'">'.$turn.'\'s turn</span>'; } if (in_array($Game->state, array('Finished', 'Draw'))) { list($win_text, $win_class) = $Game->get_outcome($_SESSION['player_id']); $turn = '<span class="'.$win_class.'">Game Over: '.$win_text.'</span>'; } $extra_info = $Game->get_extra_info( ); $meta['title'] = htmlentities($Game->name, ENT_QUOTES, 'ISO-8859-1', false).' - #'.$_SESSION['game_id']; $meta['show_menu'] = false; $meta['head_data'] = ' <link rel="stylesheet" type="text/css" media="screen" href="css/game.css" /> <script type="text/javascript" src="scripts/board.js"></script> <script type="text/javascript">/*<![CDATA[*/ var draw_offered = '.json_encode($Game->draw_offered($_SESSION['player_id'])).'; var undo_requested = '.json_encode($Game->undo_requested($_SESSION['player_id'])).'; var color = "'.(isset($players[$_SESSION['player_id']]) ? (('white' == $players[$_SESSION['player_id']]['color']) ? 'silver' : 'red') : '').'"; var state = "'.(( ! $Game->watch_mode) ? (( ! $Game->paused) ? strtolower($Game->state) : 'paused') : 'watching').'"; var invert = '.(( ! empty($players[$_SESSION['player_id']]['color']) && ('black' == $players[$_SESSION['player_id']]['color'])) ? 'true' : 'false').'; var last_move = '.$Game->last_move.'; var my_turn = '.($Game->is_turn( ) ? 'true' : 'false').'; var game_history = '.$Game->get_history(true).'; var move_count = game_history.length; var move_index = (move_count - 1); var laser_battle = '.json_encode( !! $extra_info['battle_dead']).'; var move_sphynx = '.json_encode( !! $extra_info['move_sphynx']).'; /*]]>*/</script> +'; + +$meta['foot_data'] = ' <script type="text/javascript" src="scripts/game.js"></script> '; echo get_header($meta); ?> <div id="contents"> <ul id="buttons"> <li><a href="index.php<?php echo $GLOBALS['_?_DEBUG_QUERY']; ?>">Main Page</a></li> <li><a href="game.php<?php echo $GLOBALS['_?_DEBUG_QUERY']; ?>">Reload Game Board</a></li> </ul> <h2>Game #<?php echo $_SESSION['game_id'].': '.htmlentities($Game->name, ENT_QUOTES, 'ISO-8859-1', false); ?> <span class="turn"><?php echo $turn; ?></span> <span class="setup"><a href="#setup" class="fancybox"><?php echo $Game->get_setup_name( ); ?></a> <a href="help/pieces.help" class="help">?</a></span> <span class="extra"><?php echo $Game->get_extra( ); ?></span> </h2> <div id="history" class="box"> <div> <div> <span id="first">|&lt;</span> <span id="prev5">&lt;&lt;</span> <span id="prev">&lt;</span> <span id="next">&gt;</span> <span id="next5">&gt;&gt;</span> <span id="last">&gt;|</span> </div> <table> <thead> <tr> <th>#</th> <th>Silver</th> <th>Red</th> </tr> </thead> <tbody> <?php echo $history_html; ?> </tbody> </table> </div> </div> <!-- #history --> <div id="board_wrapper"> <div id="board"></div> <!-- #board --> <div class="buttons"> <a href="javascript:;" id="invert" style="float:right;">Invert Board</a> <a href="javascript:;" id="show_full">Show Full Move</a> | | <a href="javascript:;" id="show_move">Show Move</a> | <a href="javascript:;" id="clear_move">Clear Move</a> | <a href="javascript:;" id="fire_laser">Fire Laser</a> | <a href="javascript:;" id="clear_laser">Clear Laser</a> </div> <!-- .buttons --> <form id="game" method="post" action="<?php echo $_SERVER['REQUEST_URI']; ?>"><div class="formdiv"> <input type="hidden" name="token" value="<?php echo $_SESSION['token']; ?>" /> <input type="hidden" name="game_id" value="<?php echo $_SESSION['game_id']; ?>" /> <input type="hidden" name="player_id" value="<?php echo $_SESSION['player_id']; ?>" /> <input type="hidden" name="from" id="from" value="" /> <input type="hidden" name="to" id="to" value="" /> <?php if (('Playing' == $Game->state) && $Game->is_player($_SESSION['player_id'])) { ?> <?php if ( ! $Game->draw_offered( )) { ?> <input type="button" name="offer_draw" id="offer_draw" value="Offer Draw" /> <?php } elseif ($Game->draw_offered($_SESSION['player_id'])) { ?> <input type="button" name="accept_draw" id="accept_draw" value="Accept Draw Offer" /> <input type="button" name="reject_draw" id="reject_draw" value="Reject Draw Offer" /> <?php } ?> <?php if ( ! $Game->undo_requested( ) && ! $Game->is_turn( ) && ! empty($moves)) { ?> <input type="button" name="request_undo" id="request_undo" value="Request Undo" /> <?php } elseif ($Game->undo_requested($_SESSION['player_id'])) { ?> <input type="button" name="accept_undo" id="accept_undo" value="Accept Undo Request" /> <input type="button" name="reject_undo" id="reject_undo" value="Reject Undo Request" /> <?php } ?> <input type="button" name="resign" id="resign" value="Resign" /> <?php if ($Game->test_nudge( )) { ?> <input type="button" name="nudge" id="nudge" value="Nudge" /> <?php } ?> <?php } ?> </div></form> </div> <!-- #board_wrapper --> <?php echo $chat_html; ?> </div> <!-- #contents --> <script type="text/javascript"> document.write('<'+'div id="setup"'+'>'+create_board('<?php echo expandFEN($Game->get_setup( )); ?>', true)+'<'+'/'+'div'+'>'); - - // run draw offer alert - if (draw_offered && ('watching' != state)) { - alert('Your opponent has offered you a draw.\n\nMake your decision with the draw\nbuttons below the game board.'); - } - - // run undo request alert - if (undo_requested && ('watching' != state)) { - alert('Your opponent has requested an undo.\n\nMake your decision with the undo\nbuttons below the game board.'); - } </script> <?php call($GLOBALS); -echo get_footer( ); +echo get_footer($meta); diff --git a/scripts/game.js b/scripts/game.js index dba861d..6384f3a 100644 --- a/scripts/game.js +++ b/scripts/game.js @@ -1,699 +1,714 @@ var reload = true; // do not change this var refresh_timer = false; var refresh_timeout = 2001; // 2 seconds var old_board = false; -$(document).ready( function( ) { - // show the board - // this will show the current board if no old board is available - show_old_board(true); - - // set our move history active class and disabled review buttons - update_history( ); - // invert board button - $('a#invert').click( function( ) { - invert = ! invert; - show_old_board( ); - show_new_board( ); - clear_laser( ); - return false; - }); +// show the board +// this will show the current board if no old board is available +show_old_board(true); - // show full move button - $('a#show_full').click( function( ) { - show_old_board(true); - return false; - }); - - // show move button - $('a#show_move').click( function( ) { - show_old_board( ); - blink_move( ); // calls show_new_board when done - return false; - }); +// set our move history active class and disabled review buttons +update_history( ); - // clear move button - $('a#clear_move').click( function( ) { - show_new_board( ); - return false; - }); - - // fire laser button - $('a#fire_laser').click( function( ) { - if (false != timer) { - return false; - } +// invert board button +$('a#invert').click( function( ) { + invert = ! invert; + show_old_board( ); + show_new_board( ); + clear_laser( ); + return false; +}); - show_new_board( ); +// show full move button +$('a#show_full').click( function( ) { + show_old_board(true); + return false; +}); - // show the hit piece - $('img.hit').show( ).fadeTo(50, 0.75); +// show move button +$('a#show_move').click( function( ) { + show_old_board( ); + blink_move( ); // calls show_new_board when done + return false; +}); - fire_laser(game_history[move_index][2]); - return false; - }); +// clear move button +$('a#clear_move').click( function( ) { + show_new_board( ); + return false; +}); - // clear laser button - $('a#clear_laser').click( function( ) { - clear_laser( ); +// fire laser button +$('a#fire_laser').click( function( ) { + if (false != timer) { return false; - }); - - // move history clicks - $('#history table td[id^=mv_]').click( function( ) { - clear_laser( ); + } - move_index = parseInt($(this).attr('id').slice(3)); + show_new_board( ); - update_history( ); + // show the hit piece + $('img.hit').show( ).fadeTo(50, 0.75); - show_old_board(true); - }).css('cursor', 'pointer'); + fire_laser(game_history[move_index][2]); + return false; +}); +// clear laser button +$('a#clear_laser').click( function( ) { + clear_laser( ); + return false; +}); - // review button clicks - $('#history div span:not(.disabled)').live('click', review); +// move history clicks +$('#history table td[id^=mv_]').click( function( ) { + clear_laser( ); + move_index = parseInt($(this).attr('id').slice(3)); - // ajax form on input button clicks - $('form input[type=button]').click( function( ) { - var $this = $(this); - var confirmed = true; + update_history( ); - switch ($this.prop('name')) { - case 'nudge' : - confirmed = confirm('Are you sure you wish to nudge this person?'); - break; + show_old_board(true); +}).css('cursor', 'pointer'); - case 'resign' : - confirmed = confirm('Are you sure you wish to resign?'); - break; - } - if (confirmed) { - if (debug) { - window.location = 'ajax_helper.php'+debug_query+'&'+$this.parents('form').serialize( )+'&'+$this.prop('name')+'='+$this.prop('value'); - return false; - } +// review button clicks +$('#history div span:not(.disabled)').live('click', review); - $.ajax({ - type: 'POST', - url: 'ajax_helper.php', - data: $this.parents('form').serialize( )+'&'+$this.prop('name')+'='+$this.prop('value'), - success: function(msg) { - if ('OK' != msg) { - alert('ERROR: AJAX failed'); - } - if (reload) { window.location.reload( ); } - } - }); - } - }); +// ajax form on input button clicks +$('form input[type=button]').click( function( ) { + var $this = $(this); + var confirmed = true; + switch ($this.prop('name')) { + case 'nudge' : + confirmed = confirm('Are you sure you wish to nudge this person?'); + break; - // chat box functions - $('#chatbox form').submit( function( ) { - if ('' == $.trim($('#chatbox input#chat').val( ))) { - return false; - } + case 'resign' : + confirmed = confirm('Are you sure you wish to resign?'); + break; + } + if (confirmed) { if (debug) { - window.location = 'ajax_helper.php'+debug_query+'&'+$('#chatbox form').serialize( ); + window.location = 'ajax_helper.php'+debug_query+'&'+$this.parents('form').serialize( )+'&'+$this.prop('name')+'='+$this.prop('value'); return false; } $.ajax({ type: 'POST', url: 'ajax_helper.php', - data: $('#chatbox form').serialize( ), + data: $this.parents('form').serialize( )+'&'+$this.prop('name')+'='+$this.prop('value'), success: function(msg) { - // if something happened, just reload - if ('{' != msg[0]) { + if ('OK' != msg) { alert('ERROR: AJAX failed'); - if (reload) { window.location.reload( ); } } - var reply = JSON.parse(msg); - - if (reply.error) { - alert(reply.error); - } - else { - var entry = '<dt><span>'+reply.create_date+'</span> '+reply.username+'</dt>'+ - '<dd'+(('1' == reply.private) ? ' class="private"' : '')+'>'+reply.message+'</dd>'; - - $('#chats').prepend(entry); - $('#chatbox input#chat').val(''); - } + if (reload) { window.location.reload( ); } } }); + } +}); + +// chat box functions +$('#chatbox form').submit( function( ) { + if ('' == $.trim($('#chatbox input#chat').val( ))) { return false; - }); + } + + if (debug) { + window.location = 'ajax_helper.php'+debug_query+'&'+$('#chatbox form').serialize( ); + return false; + } + + $.ajax({ + type: 'POST', + url: 'ajax_helper.php', + data: $('#chatbox form').serialize( ), + success: function(msg) { + // if something happened, just reload + if ('{' != msg[0]) { + alert('ERROR: AJAX failed'); + if (reload) { window.location.reload( ); } + } + + var reply = JSON.parse(msg); + if (reply.error) { + alert(reply.error); + } + else { + var entry = '<dt><span>'+reply.create_date+'</span> '+reply.username+'</dt>'+ + '<dd'+(('1' == reply.private) ? ' class="private"' : '')+'>'+reply.message+'</dd>'; - // tha fancybox stuff - $('a.fancybox').fancybox({ - autoDimensions : true, - onStart : function(link) { - $($(link).attr('href')).show( ); - }, - onCleanup : function( ) { - $(this.href).hide( ); + $('#chats').prepend(entry); + $('#chatbox input#chat').val(''); + } } }); + return false; +}); - // run the ajax refresher - if ( ! my_turn && ('finished' != state)) { - ajax_refresh( ); - - // set some things that will halt the timer - $('#chatbox form input').focus( function( ) { - clearTimeout(refresh_timer); - }); - $('#chatbox form input').blur( function( ) { - if ('' != $(this).val( )) { - refresh_timer = setTimeout('ajax_refresh( )', refresh_timeout); - } - }); +// tha fancybox stuff +$('a.fancybox').fancybox({ + autoDimensions : true, + onStart : function(link) { + $($(link).attr('href')).show( ); + }, + onCleanup : function( ) { + $(this.href).hide( ); } }); +// run the ajax refresher +if ( ! my_turn && ('finished' != state)) { + ajax_refresh( ); + + // set some things that will halt the timer + $('#chatbox form input').focus( function( ) { + clearTimeout(refresh_timer); + }); + + $('#chatbox form input').blur( function( ) { + if ('' != $(this).val( )) { + refresh_timer = setTimeout('ajax_refresh( )', refresh_timeout); + } + }); +} + + +// run draw offer alert +if (draw_offered && ('watching' != state)) { + alert('Your opponent has offered you a draw.\n\nMake your decision with the draw\nbuttons below the game board.'); +} + + +// run undo request alert +if (undo_requested && ('watching' != state)) { + alert('Your opponent has requested an undo.\n\nMake your decision with the undo\nbuttons below the game board.'); +} + + + +// FUNCTIONS + + function show_old_board(cont) { move_index = parseInt(move_index) || (move_count - 1); cont = ( !! cont) || false; clearTimeout(timer); timer = false; old_board = true; if (('undefined' == typeof game_history[move_index - 1]) || ('' == typeof game_history[move_index - 1][0])) { show_new_board(cont); return false; } $('div#board').empty( ).append(create_board(game_history[move_index - 1][0])); show_battle_data(true); if (cont) { blink_move(true); } return true; } function blink_move(cont) { move_index = parseInt(move_index) || (move_count - 1); cont = ( !! cont) || false; if ('undefined' == typeof game_history[move_index][1][0]) { return false; } if ( ! old_board) { show_old_board( ); } // flash the moved piece $('div#idx_'+game_history[move_index][1][0]+' img.piece') .delay(125).fadeIn(50).delay(125).fadeOut(50) .delay(125).fadeIn(50).delay(125).fadeOut(50) .delay(125).fadeIn(50).delay(125).fadeOut(50) .delay(125).fadeIn(50).delay(125).fadeOut(50, function( ) { show_new_board(cont); }); return true; } function show_new_board(cont) { move_index = parseInt(move_index) || (move_count - 1); cont = ( !! cont) || false; clearTimeout(timer); timer = false; if ( ! old_board) { return true; } $('div#board').empty( ).append(create_board(game_history[move_index][0])); old_board = false; show_battle_data( ); // add the hit piece (if any) if ('undefined' != typeof game_history[move_index][3]['hits']) { var piece, i; for (i in game_history[move_index][3]['hits']) { piece = game_history[move_index][3]['pieces'][i]; if (invert) { piece = rotate_piece(piece); } $('div#idx_'+game_history[move_index][3]['hits'][i]).append(create_piece(piece, true)); } } if ((move_count - 1) == move_index) { enable_moves( ); } if (cont) { timer = setTimeout('fire_laser(game_history[move_index][2]);', 1000); } else { // hide the hit piece $('img.hit').hide( ); } return true; } function clear_laser( ) { if (old_board) { show_new_board( ); } clearTimeout(timer); timer = false; $('img.laser').remove( ); $('img.hit').hide( ); } function do_full_move(idx) { // stop any previous moves and/or animations show_old_board( ); show_new_board( ); clear_laser( ); if (idx > (move_count - 1)) { return false; } // set the global move index move_index = parseInt(move_index) || (move_count - 1); // and do the move show_old_board(true); } function review( ) { var type = $(this).attr('id'); switch (type) { case 'first' : move_index = 1; break; case 'prev5' : move_index -= 5; break; case 'prev' : move_index -= 1; break; case 'next' : move_index += 1; break; case 'next5' : move_index += 5; break; case 'last' : move_index = (move_count - 1); break; } if (move_index < 1) { move_index = 1; } else if (move_index > (move_count - 1)) { move_index = (move_count - 1); } update_history( ); do_full_move(move_index); } function update_history( ) { // update our active move history item $('#history table td.active').removeClass('active'); $('td#mv_'+move_index).addClass('active'); // update our disabled review buttons as needed $('#history div .disabled').removeClass('disabled'); if (1 >= move_index) { $('#prev, #prev5, #first').addClass('disabled'); } if (move_index >= (move_count - 1)) { $('#next, #next5, #last').addClass('disabled'); } } function enable_moves( ) { move_index = parseInt(move_index) || (move_count - 1); if ( ! my_turn || draw_offered || undo_requested || ('finished' == state) || ('draw' == state) || ((move_count - 1) != move_index)) { return; } if (old_board) { show_new_board( ); return false; } // make all our pieces clickable $('div#board div.piece.p_'+color) .click(set_square) .css('cursor', 'pointer'); } function highlight_valid_moves(elem) { var $elem = $(elem); clear_highlights( ); // highlight all adjacent non-occupied squares var adj = get_adjacent($elem.attr('id').slice(4)); $.each(adj, function(i, val) { var $idx = $('#idx_'+val); var to_class = $idx.prop('class'); var to_color = to_class.match(/p_[^\s]+/ig); var fr_class = $elem.prop('class'); var fr_color = fr_class.match(/p_[^\s]+/ig); // check the ability to move the sphynx if ((-1 != fr_class.indexOf('sphynx')) && ! move_sphynx) { return; } // if the class is an empty string, just set the class and exit here if ('' == to_class) { add_highlight($idx); return; } // now run some tests to see if we should be highlighting this square // if it's a color square, make sure it's the same color var to_square_color = to_class.match(/c_[^\s]+/ig); var fr_square_color = fr_class.replace(/c_[^\s]+/ig, '').replace(/p_([^\s]+)/ig, 'c_$1').match(/c_[^\s]+/ig); if ((null != to_square_color) && (to_square_color[0] != fr_square_color[0])) { return; } // remove all squares with pieces that are not obelisks or pyramids // (they may get allowed in the next step) if (-1 != to_class.indexOf('piece')) { if (-1 != to_class.indexOf('pyramid')) { // do nothing } else if (-1 != to_class.indexOf('obelisk')) { // do nothing } else if (-1 != to_class.indexOf('anubis')) { // do nothing } else { return; } // test for djed and eye of horus // if it's not one of those, remove all pieces // we also want to allow a same colored single stack obelisk // if the piece we are moving is an obelisk if (-1 != fr_class.indexOf('djed')) { // do nothing } else if (-1 != fr_class.indexOf('horus')) { // do nothing } else if (-1 != fr_class.indexOf('obelisk')) { // make sure it's moving onto a single stack obelisk of the same color if ((-1 != to_class.indexOf('obelisk')) && (-1 == to_class.indexOf('obelisk_stack')) && (fr_color[0] == to_color[0])) { // do nothing } else { return; } } else { return; } // make sure if we're swapping pieces that the swapped piece // doesn't end up on a color square where they shouldn't be var fr_sqr_color = fr_class.match(/c_[^\s]+/ig); var to_sqr_color = to_class.replace(/c_[^\s]+/ig, '').replace(/p_([^\s]+)/ig, 'c_$1').match(/c_[^\s]+/ig); if ((null != fr_sqr_color) && (to_sqr_color[0] != fr_sqr_color[0])) { return; } } // we made it through the gauntlet, set the highlight add_highlight($idx); }); } function add_highlight($elem) { $elem .addClass('highlight'); if ( ! $elem.is('div.piece.p_'+color)) { $elem .click(set_square) .css('cursor', 'pointer'); } } function clear_highlights( ) { $('div.highlight') .removeClass('highlight') .each( function( ) { var $elem = $(this); if ( ! $elem.is('div.piece.p_'+color)) { $elem .unbind('click', set_square) .css('cursor', 'default'); } }); } var stage_1 = false; var from_index = -1; var time = []; function set_square(event) { // don't allow the event to bubble up the DOM tree event.stopPropagation( ); // set the time of the click time.push(new Date( ).getTime( )); clear_laser( ); var $elem = $(event.currentTarget); var board_index = $elem.attr('id').slice(4).toLowerCase( ); if ( ! stage_1) { stage_1 = true; from_index = board_index; highlight_valid_moves($elem); // create our two images // if the piece is not an obelisk or pharaoh var piece_code = $elem.prop('class').match(/i_[^\s]+/ig)[0].slice(2).toLowerCase( ); if (('v' != piece_code) && ('w' != piece_code) && ('p' != piece_code)) { var allow_right = true; var allow_left = true; // make sure the sphynx doesn't get rotated toward a wall if (piece_code.match(/[efjk]/i)) { var up_right = (piece_code.match(/[e]/i) && (9 == (board_index % 10))); // pointing up against right wall var down_right = (piece_code.match(/[j]/i) && (9 == (board_index % 10))); // pointing down against right wall var up_left = (piece_code.match(/[e]/i) && (0 == (board_index % 10))); // pointing up against left wall var down_left = (piece_code.match(/[j]/i) && (0 == (board_index % 10))); // pointing down against left wall var right_top = (piece_code.match(/[f]/i) && (board_index < 10)); // pointing right against top wall var left_top = (piece_code.match(/[k]/i) && (board_index < 10)); // pointing left against top wall var right_bottom = (piece_code.match(/[f]/i) && (board_index >= 70)); // pointing right against bottom wall var left_bottom = (piece_code.match(/[k]/i) && (board_index >= 70)); // pointing left against bottom wall if (( ! invert && (up_right || down_left || left_top || right_bottom)) || (invert && (up_left || down_right || left_bottom || right_top))) { allow_right = false; } if (( ! invert && (up_left || down_right || left_bottom || right_top)) || (invert && (up_right || down_left || left_top || right_bottom))) { allow_left = false; } } if (allow_right) { $('div#idx_'+board_index) .append($('<img/>', { 'id' : 'rot_r', 'class' : 'rotate cw', 'src' : 'images/rotate_cw.png', 'alt' : '->', 'click' : set_square })); } if (allow_left) { $('div#idx_'+board_index) .append($('<img/>', { 'id' : 'rot_l', 'class' : 'rotate ccw', 'src' : 'images/rotate_ccw.png', 'alt' : '<-', 'click' : set_square })); } } $('input#from').val(board_index); } else { // grab some info about the piece var $fr_elem = $('div#idx_'+from_index); var fr_class = $fr_elem.prop('class'); var fr_color = fr_class.match(/p_[^\s]+/ig); // if we are not rotating the piece, we need // to grab some more info about where the piece // is going if ( ! isNaN(parseInt(board_index))) { var $to_elem = $('div#idx_'+board_index); var to_class = $to_elem.prop('class'); var to_color = to_class.match(/p_[^\s]+/ig); } var rotating = false; if (('r' == board_index) || ('l' == board_index)) { // check the time between clicks and make sure this wasn't a mistake if (1000 > (time[1] - time[0])) { if ( ! confirm('You clicked that rotate button awfully fast... ('+(time[1] - time[0])+' ms)\nWas that what you meant to do? (Rotating '+board_index.toUpperCase( )+')')) { // reset stage_1 = false; from_index = -1; time = [] clear_highlights( ); $('img.rotate').remove( ); // perform the original click again $fr_elem.click( ); return; } } rotating = true; } else if (board_index == from_index) { // reset stage_1 = false; from_index = -1; time = [] clear_highlights( ); $('img.rotate').remove( ); return; } else if (-1 == $elem.prop('class').indexOf('highlight')) { // reset stage_1 = false; from_index = -1; time = []; clear_highlights( ); $('img.rotate').remove( ); // perform the click again $to_elem.click( ); return; } else { // if the FROM piece is a djed, // or eye of horus, or obelisk // moving onto another single stack obelisk... var moveable_piece = (fr_color && to_color && (fr_color[0] == to_color[0])); // set this piece as the TO index // as long as it's okay with the player if (moveable_piece) { var piece_code = $elem.prop('class').match(/i_[^\s]+/ig)[0].slice(2).toLowerCase( ); var swap = 'swap'; if (('v' == piece_code.toLowerCase( )) && ('v' == fr_class.match(/i_[^\s]+/ig)[0].slice(2).toLowerCase( ))) { swap = 'stack'; } if ( ! confirm('Do you want to '+swap+' this piece?\n\nOK- '+swap.capitalize( )+' these two pieces | Cancel- Move this new piece')) { // reset stage_1 = false; from_index = -1; time = [] clear_highlights( ); $('img.rotate').remove( ); // perform the click again $to_elem.click( ); return; } } } // set the TO value and send the form $('input#to').val(board_index); // if FROM piece is a stacked obelisk and the TO space is empty // test for splitting an obelisk and confirm with player if ( ! rotating) { var stacked_obelisk = (-1 != fr_class.indexOf('obelisk_stack')); var empty_to = (-1 == to_class.indexOf('piece')); if (stacked_obelisk && empty_to && confirm('Do you want to split this obelisk stack?\n\nOK- Split obelisk stack | Cancel- Move stack as whole')) { $('input#to').val(board_index+'-split'); } } if (debug) { window.location = 'ajax_helper.php'+debug_query+'&'+$('form#game').serialize( )+'&turn=1'; return false; } // ajax the form $.ajax({ type: 'POST', url: 'ajax_helper.php', data: $('form#game').serialize( )+'&turn=1', success: function(msg) { // if something happened, just reload if ('{' != msg[0]) { alert('ERROR: AJAX Failed'); if (reload) { window.location.reload( ); } return; } var reply = JSON.parse(msg); if (reply.error) { alert(reply.error); if (reload) { window.location.reload( ); } return; } if (reload) { window.location.reload( ); } } }); } }
benjamw/pharaoh
9ff685adef5645c0588852ac89083927d13310cf
Added missing Game::save calls Moved all Game::save calls to Game class
diff --git a/ajax_helper.php b/ajax_helper.php index 482d554..80244a4 100644 --- a/ajax_helper.php +++ b/ajax_helper.php @@ -1,291 +1,290 @@ <?php $GLOBALS['NODEBUG'] = true; $GLOBALS['AJAX'] = true; // don't require log in when testing for used usernames and emails if (isset($_POST['validity_test']) || (isset($_GET['validity_test']) && isset($_GET['DEBUG']))) { define('LOGIN', false); } require_once 'includes/inc.global.php'; // if we are debugging, change some things for us // (although REQUEST_METHOD may not always be valid) if (('GET' == $_SERVER['REQUEST_METHOD']) && test_debug( )) { $GLOBALS['NODEBUG'] = false; $GLOBALS['AJAX'] = false; $_GET['token'] = $_SESSION['token']; $_GET['keep_token'] = true; $_POST = $_GET; $DEBUG = true; call('AJAX HELPER'); call($_POST); } // run the index page refresh checks if (isset($_POST['timer'])) { $message_count = (int) Message::check_new($_SESSION['player_id']); $turn_count = (int) Game::check_turns($_SESSION['player_id']); echo $message_count + $turn_count; exit; } // run registration checks if (isset($_POST['validity_test'])) { # if (('email' == $_POST['type']) && ('' == $_POST['value'])) { # echo 'OK'; # exit; # } $player_id = 0; if ( ! empty($_POST['profile'])) { $player_id = (int) $_SESSION['player_id']; } switch ($_POST['validity_test']) { case 'username' : case 'email' : $username = ''; $email = ''; ${$_POST['validity_test']} = sani($_POST['value']); $player_id = (isset($_POST['player_id']) ? (int) $_POST['player_id'] : 0); try { Player::check_database($username, $email, $player_id); } catch (MyException $e) { echo $e->getCode( ); exit; } break; default : break; } echo 'OK'; exit; } // run the in game chat if (isset($_POST['chat'])) { try { if ( ! isset($_SESSION['game_id'])) { $_SESSION['game_id'] = 0; } $Chat = new Chat((int) $_SESSION['player_id'], (int) $_SESSION['game_id']); $Chat->send_message($_POST['chat'], isset($_POST['private']), isset($_POST['lobby'])); $return = $Chat->get_box_list(1); $return = $return[0]; } catch (MyException $e) { $return['error'] = 'ERROR: '.$e->outputMessage( ); } echo json_encode($return); exit; } // run setup validation if (isset($_POST['test_setup'])) { try { Setup::is_valid_reflection($_POST['setup'], $_POST['reflection']); $return['valid'] = true; } catch (MyException $e) { $return['error'] = 'ERROR: '.$e->outputMessage( ); } echo json_encode($return); exit; } // run setup laser test fire if (isset($_POST['test_fire'])) { try { // returns laser_path and hits arrays $return = Pharaoh::fire_laser($_POST['color'], $_POST['board']); } catch (MyException $e) { $return['error'] = 'ERROR: '.$e->outputMessage( ); } echo json_encode($return); exit; } // run the invites stuff if (isset($_POST['invite'])) { if ('delete' == $_POST['invite']) { // make sure we are one of the two people in the invite if (Game::has_invite($_POST['game_id'], $_SESSION['player_id'])) { if (Game::delete_invite($_POST['game_id'])) { echo 'Invite Deleted'; } else { echo 'ERROR: Invite not deleted'; } } else { echo 'ERROR: Not your invite'; } } else if ('resend' == $_POST['invite']) { // make sure we are one of the two people in the invite if (Game::has_invite($_POST['game_id'], $_SESSION['player_id'])) { try { if (Game::resend_invite($_POST['game_id'])) { echo 'Invite Resent'; } else { echo 'ERROR: Could not resend invite'; } } catch (MyException $e) { echo 'ERROR: '.$e->outputMessage( ); } } else { echo 'ERROR: Not your invite'; } } else { // make sure we are one of the two people in the invite if (Game::has_invite($_POST['game_id'], $_SESSION['player_id'], $accept = true)) { if ($game_id = Game::accept_invite($_POST['game_id'])) { // single equals intended echo $game_id; } else { echo 'ERROR: Could not create game'; } } else { echo 'ERROR: Not your invite'; } } exit; } // we'll need a game id from here forward, so make sure we have one if (empty($_SESSION['game_id'])) { echo 'ERROR: Game not found'; exit; } // init our game if ( ! isset($Game)) { $Game = new Game((int) $_SESSION['game_id']); } // run the game refresh check if (isset($_POST['refresh'])) { echo $Game->last_move; exit; } // do some validity checking if (empty($DEBUG) && empty($_POST['notoken'])) { test_token( ! empty($_POST['keep_token'])); } if ($_POST['game_id'] != $_SESSION['game_id']) { throw new MyException('ERROR: Incorrect game id given. Was #'.$_POST['game_id'].', should be #'.$_SESSION['game_id'].'.'); } // make sure we are the player we say we are // unless we're an admin, then it's ok $player_id = (int) $_POST['player_id']; if (($player_id != $_SESSION['player_id']) && ! $GLOBALS['Player']->is_admin) { throw new MyException('ERROR: Incorrect player id given'); } // run the simple button actions $actions = array( 'nudge', 'resign', 'offer_draw', 'accept_draw', 'reject_draw', 'request_undo', 'accept_undo', 'reject_undo', ); foreach ($actions as $action) { if (isset($_POST[$action])) { try { $Game->{$action}($player_id); echo 'OK'; } catch (MyException $e) { echo $e; } exit; } } // run the game actions if (isset($_POST['turn'])) { $return = array( ); try { if (false !== strpos($_POST['to'], 'split')) { // splitting obelisk $to = substr($_POST['to'], 0, 2); call($to); $from = Pharaoh::index_to_target($_POST['from']); $to = Pharaoh::index_to_target($to); call($from.'.'.$to); $Game->do_move($from.'.'.$to); } elseif ((string) $_POST['to'] === (string) (int) $_POST['to']) { // moving $to = $_POST['to']; call($to); $from = Pharaoh::index_to_target($_POST['from']); $to = Pharaoh::index_to_target($to); call($from.':'.$to); $Game->do_move($from.':'.$to); } else { // rotating $target = Pharaoh::index_to_target($_POST['from']); $dir = (int) ('r' == strtolower($_POST['to'])); call($target.'-'.$dir); $Game->do_move($target.'-'.$dir); } - $Game->save( ); $return['action'] = 'RELOAD'; } catch (MyException $e) { $return['error'] = 'ERROR: '.$e->outputMessage( ); } echo json_encode($return); exit; } diff --git a/classes/game.class.php b/classes/game.class.php index ba14c7c..77c995b 100644 --- a/classes/game.class.php +++ b/classes/game.class.php @@ -282,1318 +282,1335 @@ class Game * @action saves changed data * @action destroys object * @return void */ /* public function __destruct( ) { // save anything changed to the database // BUT... only if PHP didn't die because of an error $error = error_get_last( ); if ($this->id && (0 == ((E_ERROR | E_WARNING | E_PARSE) & $error['type']))) { try { $this->save( ); } catch (MyException $e) { // do nothing, it will be logged } } } */ /** public function __get * Class getter * Returns the requested property if the * requested property is not _private * * @param string property name * @return mixed property value */ public function __get($property) { switch ($property) { case 'name' : return $this->_players['white']['object']->username.' vs '.$this->_players['black']['object']->username; break; case 'first_name' : if ($_SESSION['player_id'] == $this->_players['player']['player_id']) { return 'Your'; } else { return $this->_players['white']['object']->username.'\'s'; } break; case 'second_name' : if ($_SESSION['player_id'] == $this->_players['player']['player_id']) { return $this->_players['opponent']['object']->username.'\'s'; } else { return $this->_players['black']['object']->username.'\'s'; } break; default : // go to next step break; } if ( ! property_exists($this, $property)) { throw new MyException(__METHOD__.': Trying to access non-existent property ('.$property.')', 2); } if ('_' === $property[0]) { throw new MyException(__METHOD__.': Trying to access _private property ('.$property.')', 2); } return $this->$property; } /** public function __set * Class setter * Sets the requested property if the * requested property is not _private * * @param string property name * @param mixed property value * @action optional validation * @return bool success */ public function __set($property, $value) { if ( ! property_exists($this, $property)) { throw new MyException(__METHOD__.': Trying to access non-existent property ('.$property.')', 3); } if ('_' === $property[0]) { throw new MyException(__METHOD__.': Trying to access _private property ('.$property.')', 3); } $this->$property = $value; } /** static public function invite * Creates the game from _POST data * * @param void * @action creates an invite * @return int game id */ static public function invite( ) { call(__METHOD__); call($_POST); $Mysql = Mysql::get_instance( ); // DON'T sanitize the data // it gets sani'd in the MySQL->insert method $_P = $_POST; // translate (filter/sanitize) the data $_P['white_id'] = (int) $_SESSION['player_id']; $_P['black_id'] = (int) $_P['opponent']; $_P['setup_id'] = (int) $_P['setup']; $_P['laser_battle'] = is_checked($_P['laser_battle_box']); $_P['battle_front_only'] = is_checked($_P['battle_front_only']); $_P['battle_hit_self'] = is_checked($_P['battle_hit_self']); $_P['move_sphynx'] = is_checked($_P['move_sphynx']); call($_P); // grab the setup $query = " SELECT setup_id FROM ".Setup::SETUP_TABLE." "; $setup_ids = $Mysql->fetch_value_array($query); call($setup_ids); // check for random setup if (0 == $_P['setup_id']) { shuffle($setup_ids); shuffle($setup_ids); $_P['setup_id'] = (int) reset($setup_ids); sort($setup_ids); } // make sure the setup id is valid if ( ! in_array($_P['setup_id'], $setup_ids)) { throw new MyException(__METHOD__.': Setup is not valid'); } $query = " SELECT board FROM ".Setup::SETUP_TABLE." WHERE setup_id = '{$_P['setup_id']}' "; $setup = $Mysql->fetch_value($query); // laser battle cleanup // only run this if the laser battle box was open if ($_P['laser_battle']) { ifer($_P['battle_dead'], 1, false); ifer($_P['battle_immune'], 1); // we can only hit ourselves in the sides or back, never front if ($_P['battle_front_only']) { $_P['battle_hit_self'] = false; } $extra_info = array( 'battle_dead' => (int) max((int) $_P['battle_dead'], 1), 'battle_immune' => (int) max((int) $_P['battle_immune'], 0), 'battle_front_only' => (bool) $_P['battle_front_only'], 'battle_hit_self' => (bool) $_P['battle_hit_self'], ); } $extra_info['white_color'] = $_P['color']; $extra_info['move_sphynx'] = $_P['move_sphynx']; $setup = expandFEN($setup); try { if (is_checked($_P['convert_to_1']) || is_checked($_P['rand_convert_to_1'])) { $setup = Setup::convert_to_1($setup); } elseif (is_checked($_P['convert_to_2']) || is_checked($_P['rand_convert_to_2'])) { $setup = Setup::convert_to_2($setup); } } catch (MyException $e) { throw $e; } $extra_info['invite_setup'] = packFEN($setup); call($extra_info); $diff = array_compare($extra_info, self::$_EXTRA_INFO_DEFAULTS); $extra_info = $diff[0]; ksort($extra_info); call($extra_info); if ( ! empty($extra_info)) { $_P['extra_info'] = serialize($extra_info); } // create the game $required = array( 'white_id' , 'setup_id' , ); $key_list = array_merge($required, array( 'black_id' , 'extra_info' , )); try { $_DATA = array_clean($_P, $key_list, $required); } catch (MyException $e) { throw $e; } $_DATA['state'] = 'Waiting'; $_DATA['create_date '] = 'NOW( )'; // note the trailing space in the field name, this is not a typo $_DATA['modify_date '] = 'NOW( )'; // note the trailing space in the field name, this is not a typo $insert_id = $Mysql->insert(self::GAME_TABLE, $_DATA); if (empty($insert_id)) { throw new MyException(__METHOD__.': Invite could not be created'); } // send the email if ($_DATA['black_id']) { Email::send('invite', $_DATA['black_id'], array('opponent' => $GLOBALS['_PLAYERS'][$_DATA['white_id']], 'page' => 'invite.php')); } return $insert_id; } /** static public function resend_invite * Resends the invite email (if allowed) * * @param int game id * @action resends an invite email * @return bool invite email sent */ static public function resend_invite($game_id) { call(__METHOD__); $game_id = (int) $game_id; $white_id = (int) $_SESSION['player_id']; $Mysql = Mysql::get_instance( ); // grab the invite from the database $query = " SELECT * , DATE_ADD(NOW( ), INTERVAL -1 DAY) AS resend_limit FROM ".self::GAME_TABLE." WHERE game_id = '{$game_id}' AND state = 'Waiting' "; $invite = $Mysql->fetch_assoc($query); if ( ! $invite) { throw new MyException(__METHOD__.': Player (#'.$white_id.') trying to resend a non-existant invite (#'.$game_id.')'); } if ((int) $invite['white_id'] !== (int) $white_id) { throw new MyException(__METHOD__.': Player (#'.$white_id.') trying to resend an invite (#'.$game_id.') that is not theirs'); } if ( ! (int) $invite['black_id']) { throw new MyException(__METHOD__.': Player (#'.$white_id.') trying to resend an invite (#'.$game_id.') that is open'); } if (strtotime($invite['modify_date']) >= strtotime($invite['resend_limit'])) { throw new MyException(__METHOD__.': Player (#'.$white_id.') trying to resend an invite (#'.$game_id.') that is too new'); } // if we get here, all is good... $sent = Email::send('invite', $invite['black_id'], array('opponent' => $GLOBALS['_PLAYERS'][$invite['white_id']], 'page' => 'invite.php')); if ($sent) { // update the modify_date to prevent invite resend flooding $_DATA['modify_date '] = 'NOW( )'; // note the trailing space in the field name, this is not a typo $Mysql->insert(self::GAME_TABLE, $_DATA, " WHERE game_id = '{$game_id}' AND state = 'Waiting' "); } return $sent; } /** static public function accept_invite * Creates the game from invite data * * @param int game id * @action creates a game * @return int game id */ static public function accept_invite($game_id) { call(__METHOD__); $game_id = (int) $game_id; $Mysql = Mysql::get_instance( ); // basically all we do, is set the state to Playing // and set the player order based on the invite data $query = " SELECT * FROM ".self::GAME_TABLE." WHERE game_id = '{$game_id}' AND state = 'Waiting' "; $game = $Mysql->fetch_assoc($query); $invitor_id = $game['white_id']; // for use later $extra_info = array_merge_plus(self::$_EXTRA_INFO_DEFAULTS, unserialize($game['extra_info'])); if ((('random' == $extra_info['white_color']) && mt_rand(0, 1)) || ('white' == $extra_info['white_color'])) { $game['white_id'] = $game['white_id']; $game['black_id'] = $_SESSION['player_id']; } else { $game['black_id'] = $game['white_id']; $game['white_id'] = $_SESSION['player_id']; } call($extra_info); unset($extra_info['white_color']); $board = false; if ( ! empty($extra_info['invite_setup'])) { $board = $extra_info['invite_setup']; } $extra_info['invite_setup'] = ''; $diff = array_compare($extra_info, self::$_EXTRA_INFO_DEFAULTS); $extra_info = $diff[0]; ksort($extra_info); call($extra_info); unset($game['extra_info']); if ( ! empty($extra_info)) { $game['extra_info'] = serialize($extra_info); } $game['state'] = 'Playing'; $Mysql->insert(self::GAME_TABLE, $game, " WHERE game_id = '{$game_id}' "); // add the first entry in the history table if (empty($board)) { $query = " INSERT INTO ".self::GAME_HISTORY_TABLE." (game_id, board) VALUES ('{$game_id}', ( SELECT board FROM ".Setup::SETUP_TABLE." WHERE setup_id = '{$game['setup_id']}' )) "; $Mysql->query($query); } else { $query = " INSERT INTO ".self::GAME_HISTORY_TABLE." (game_id, board) VALUES ('{$game_id}', '{$board}') "; $Mysql->query($query); } // add a used count to the setup table Setup::add_used($game['setup_id']); // send the email Email::send('start', $invitor_id, array('opponent' => $GLOBALS['_PLAYERS'][$_SESSION['player_id']], 'game_id' => $game_id)); return $game_id; } /** static public function delete_invite * Deletes the given invite * * @param int game id * @action deletes the invite * @return void */ static public function delete_invite($game_id) { call(__METHOD__); $game_id = (int) $game_id; $Mysql = Mysql::get_instance( ); return $Mysql->delete(self::GAME_TABLE, " WHERE game_id = '{$game_id}' AND state = 'Waiting' "); } /** static public function has_invite * Tests if the given player has the given invite * * @param int game id * @param int player id * @param bool optional player can accept invite * @return bool player has invite */ static public function has_invite($game_id, $player_id, $accept = false) { call(__METHOD__); $game_id = (int) $game_id; $player_id = (int) $player_id; $accept = (bool) $accept; $Mysql = Mysql::get_instance( ); $open = ""; if ($accept) { $open = " OR black_id IS NULL OR black_id = FALSE "; } $query = " SELECT COUNT(*) FROM ".self::GAME_TABLE." WHERE game_id = '{$game_id}' AND state = 'Waiting' AND (white_id = '{$player_id}' OR black_id = '{$player_id}' {$open} ) "; $has_invite = (bool) $Mysql->fetch_value($query); return $has_invite; } public function can_fire_laser( ) { call(__METHOD__); if ( ! $this->_extra_info['battle_dead']) { return true; } return ! $this->_current_move_extra_info['dead_for']; } public function prev_laser_fired( ) { $last = end($this->_history); return (bool) $last['laser_fired']; } /** public function do_move * Do the given move and send out emails * * @param string move code * @action performs the move * @return array indexes hit */ public function do_move($move) { call(__METHOD__); try { $this->_laser_fired = $this->can_fire_laser( ); $hits = $this->_pharaoh->do_move($move, $this->_laser_fired); $winner = $this->_pharaoh->winner; } catch (MyException $e) { throw $e; } if ($winner) { if ('draw' == $winner) { $this->state = 'Draw'; $this->_players['silver']['object']->add_draw( ); $this->_players['red']['object']->add_draw( ); // send the email Email::send('draw', $this->_players['opponent']['player_id'], array('opponent' => $this->_players['player']['object']->username)); } else { $this->state = 'Finished'; $this->_players[$winner]['object']->add_win( ); $this->_players[$this->_players[$winner]['opp_color']]['object']->add_loss( ); // send the email $type = (($this->_players[$winner]['player_id'] == $_SESSION['player_id']) ? 'defeated' : 'won'); Email::send($type, $this->_players['opponent']['player_id'], array('opponent' => $this->_players['player']['object']->username)); } } else { // send the email Email::send('turn', $this->_players['opponent']['player_id'], array('opponent' => $this->_players['player']['object']->username, 'game_id' => $this->id)); } + $this->save( ); + return $hits; } /** public function resign * Resigns the given player from the game * * @param int player id * @return void */ public function resign($player_id) { call(__METHOD__); if ($this->paused) { throw new MyException(__METHOD__.': Trying to perform an action on a paused game'); } $player_id = (int) $player_id; if (empty($player_id)) { throw new MyException(__METHOD__.': Missing required argument'); } if ( ! $this->is_player($player_id)) { throw new MyException(__METHOD__.': Player (#'.$player_id.') trying to resign from a game (#'.$this->id.') they are not playing in'); } if ($this->_players['player']['player_id'] != $player_id) { throw new MyException(__METHOD__.': Player (#'.$player_id.') trying to resign opponent from a game (#'.$this->id.')'); } $this->_players['opponent']['object']->add_win( ); $this->_players['player']['object']->add_loss( ); $this->state = 'Finished'; $this->_pharaoh->winner = 'opponent'; + Email::send('resigned', $this->_players['opponent']['player_id'], array('opponent' => $this->_players['player']['object']->username, 'game_id' => $this->id)); + + $this->save( ); } /** public function offer_draw * Offers a draw to the given player's apponent * * @param int player id * @return void */ public function offer_draw($player_id) { call(__METHOD__); if ($this->paused) { throw new MyException(__METHOD__.': Trying to perform an action on a paused game'); } $player_id = (int) $player_id; if (empty($player_id)) { throw new MyException(__METHOD__.': Missing required argument'); } if ( ! $this->is_player($player_id)) { throw new MyException(__METHOD__.': Player (#'.$player_id.') trying to offer draw in a game (#'.$this->id.') they are not playing in'); } if ($this->_players['player']['player_id'] != $player_id) { throw new MyException(__METHOD__.': Player (#'.$player_id.') trying to offer draw for an opponent in game (#'.$this->id.')'); } $this->_extra_info['draw_offered'] = $player_id; Email::send('draw_offered', $this->_players['opponent']['player_id'], array('opponent' => $this->_players['player']['object']->username, 'game_id' => $this->id)); + + $this->save( ); } /** public function draw_offered * Returns the state of the game draw for the given player * or in general if no player given * * @param int [optional] player id * @return bool draw state */ public function draw_offered($player_id = false) { call(__METHOD__); $player_id = (int) $player_id; // if the draw was offered AND player is blank or player is not the one who offered the draw if (($this->_extra_info['draw_offered']) && ( ! $player_id || ($player_id != $this->_extra_info['draw_offered']))) { return true; } return false; } /** public function accept_draw * Accepts a draw offered to the given player * * @param int player id * @return void */ public function accept_draw($player_id) { call(__METHOD__); if ($this->paused) { throw new MyException(__METHOD__.': Trying to perform an action on a paused game'); } $player_id = (int) $player_id; if (empty($player_id)) { throw new MyException(__METHOD__.': Missing required argument'); } if ( ! $this->is_player($player_id)) { throw new MyException(__METHOD__.': Player (#'.$player_id.') trying to accept draw in a game (#'.$this->id.') they are not playing in'); } if (($this->_players['player']['player_id'] != $player_id) || ($this->_extra_info['draw_offered'] == $player_id)) { throw new MyException(__METHOD__.': Player (#'.$player_id.') trying to accept draw for an opponent in game (#'.$this->id.')'); } $this->_players['opponent']['object']->add_draw( ); $this->_players['player']['object']->add_draw( ); $this->state = 'Draw'; $this->_extra_info['draw_offered'] = false; Email::send('draw', $this->_players['opponent']['player_id'], array('opponent' => $this->_players['player']['object']->username, 'game_id' => $this->id)); + + $this->save( ); } /** public function reject_draw * Rejects a draw offered to the given player * * @param int player id * @return void */ public function reject_draw($player_id) { call(__METHOD__); if ($this->paused) { throw new MyException(__METHOD__.': Trying to perform an action on a paused game'); } $player_id = (int) $player_id; if (empty($player_id)) { throw new MyException(__METHOD__.': Missing required argument'); } if ( ! $this->is_player($player_id)) { throw new MyException(__METHOD__.': Player (#'.$player_id.') trying to reject draw in a game (#'.$this->id.') they are not playing in'); } if (($this->_players['player']['player_id'] != $player_id) || ($this->_extra_info['draw_offered'] == $player_id)) { throw new MyException(__METHOD__.': Player (#'.$player_id.') trying to reject draw for an opponent in game (#'.$this->id.')'); } $this->_extra_info['draw_offered'] = false; + + $this->save( ); } /** public function request_undo * Requests an undo from the given player's apponent * * @param int player id * @return void */ public function request_undo($player_id) { call(__METHOD__); if ($this->paused) { throw new MyException(__METHOD__.': Trying to perform an action on a paused game'); } $player_id = (int) $player_id; if (empty($player_id)) { throw new MyException(__METHOD__.': Missing required argument'); } if ( ! $this->is_player($player_id)) { throw new MyException(__METHOD__.': Player (#'.$player_id.') trying to request undo in a game (#'.$this->id.') they are not playing in'); } if ($this->_players['player']['player_id'] != $player_id) { throw new MyException(__METHOD__.': Player (#'.$player_id.') trying to request undo from an opponent in game (#'.$this->id.')'); } $this->_extra_info['undo_requested'] = $player_id; Email::send('undo_requested', $this->_players['opponent']['player_id'], array('opponent' => $this->_players['player']['object']->username, 'game_id' => $this->id)); + + $this->save( ); } /** public function undo_requested * Returns the state of the game undo for the given player * or in general if no player given * * @param int [optional] player id * @return bool draw state */ public function undo_requested($player_id = false) { call(__METHOD__); $player_id = (int) $player_id; // if the undo was requested AND player is blank or player is not the one who offered the draw if (($this->_extra_info['undo_requested']) && ( ! $player_id || ($player_id != $this->_extra_info['undo_requested']))) { return true; } return false; } /** public function accept_undo * Accepts an undo requested to the given player * * @param int player id * @return void */ public function accept_undo($player_id) { call(__METHOD__); if ($this->paused) { throw new MyException(__METHOD__.': Trying to perform an action on a paused game'); } $player_id = (int) $player_id; if (empty($player_id)) { throw new MyException(__METHOD__.': Missing required argument'); } if ( ! $this->is_player($player_id)) { throw new MyException(__METHOD__.': Player (#'.$player_id.') trying to accept undo in a game (#'.$this->id.') they are not playing in'); } if (($this->_players['player']['player_id'] != $player_id) || ($this->_extra_info['draw_offered'] == $player_id)) { throw new MyException(__METHOD__.': Player (#'.$player_id.') trying to accept undo for an opponent in game (#'.$this->id.')'); } // we need to adjust the database here // it's not really possible via the save function $this->_mysql->delete(self::GAME_HISTORY_TABLE, " WHERE `game_id` = '{$this->id}' ORDER BY `move_date` DESC LIMIT 1 "); // and fix up the game data $this->_pull( ); $this->_extra_info['undo_requested'] = false; Email::send('undo_accepted', $this->_players['opponent']['player_id'], array('opponent' => $this->_players['player']['object']->username, 'game_id' => $this->id)); + + $this->save( ); } /** public function reject_undo * Rejects an undo requested to the given player * * @param int player id * @return void */ public function reject_undo($player_id) { call(__METHOD__); if ($this->paused) { throw new MyException(__METHOD__.': Trying to perform an action on a paused game'); } $player_id = (int) $player_id; if (empty($player_id)) { throw new MyException(__METHOD__.': Missing required argument'); } if ( ! $this->is_player($player_id)) { throw new MyException(__METHOD__.': Player (#'.$player_id.') trying to reject undo in a game (#'.$this->id.') they are not playing in'); } if (($this->_players['player']['player_id'] != $player_id) || ($this->_extra_info['draw_offered'] == $player_id)) { throw new MyException(__METHOD__.': Player (#'.$player_id.') trying to reject undo for an opponent in game (#'.$this->id.')'); } $this->_extra_info['undo_requested'] = false; + + $this->save( ); } /** public function is_player * Tests if the given ID is a player in the game * * @param int player id * @return bool player is in game */ public function is_player($player_id) { $player_id = (int) $player_id; return ((isset($this->_players['white']['player_id']) && ($player_id == $this->_players['white']['player_id'])) || (isset($this->_players['black']['player_id']) && ($player_id == $this->_players['black']['player_id']))); } /** public function get_color * Returns the requested player's color * * @param bool current player is requested player * @return string requested player's color (or false on failure) */ public function get_color($player = true) { $request = (((bool) $player) ? 'player' : 'opponent'); return ((isset($this->_players[$request]['color'])) ? $this->_players[$request]['color'] : false); } /** public function is_turn * Returns the requested player's turn * * @param bool current player is requested player * @return bool is the requested player's turn */ public function is_turn($player = true) { if ('Playing' != $this->state) { return false; } if ($this->_extra_info['draw_offered']) { return false; } $request = (((bool) $player) ? 'player' : 'opponent'); return ((isset($this->_players[$request]['turn'])) ? (bool) $this->_players[$request]['turn'] : false); } /** public function get_turn * Returns the name of the player who's turn it is * * @param void * @return string current player's name */ public function get_turn( ) { return ((isset($this->turn) && isset($this->_players[$this->turn]['object'])) ? $this->_players[$this->turn]['object']->username : false); } /** public function get_extra * Returns details of the extra_info var * * @param void * @return string extra info details */ public function get_extra( ) { call(__METHOD__); $return = array( ); if ($this->_extra_info['battle_dead']) { $front_abbr = $front_text = ''; if ($this->_pharaoh->has_sphynx) { $front_abbr = ', Front Only'; $front_text = ($this->_extra_info['battle_front_only'] ? ', Yes' : ', No'); } $return[] = '<span>Laser Battle (<abbr title="Dead, Immune'.$front_abbr.'">'.$this->_extra_info['battle_dead'].', '.$this->_extra_info['battle_immune'].$front_text.'</abbr>)</span>'; } if ($this->_pharaoh->has_sphynx && $this->_extra_info['move_sphynx']) { $return[] = '<span>Movable Sphynx</span>'; } return implode(' | ', $return); } /** public function get_extra_info * Returns the extra_info var * * @param void * @return array extra info */ public function get_extra_info( ) { return $this->_extra_info; } /** public function get_board * Returns the current board * * @param bool optional return expanded FEN * @param int optional history index * @return string board FEN (or xFEN) */ public function get_board($index = null, $expanded = false) { call(__METHOD__); if (is_null($index)) { $index = count($this->_history) - 1; } $index = (int) $index; $expanded = (bool) $expanded; if (isset($this->_history[$index])) { $board = $this->_history[$index]['board']; } else { return false; } if ($expanded) { return expandFEN($board); } return $board; } /** public function get_move_history * Returns the game move history * * @param void * @return array game history */ public function get_move_history( ) { call(__METHOD__); $history = $this->_history; array_shift($history); // remove the empty first move $return = array( ); foreach ($history as $i => $ply) { if (false !== strpos($ply['move'], '-')) { $ply['move'] = str_replace(array('-0','-1'), array('-L','-R'), $ply['move']); } $return[floor($i / 2)][$i % 2] = $ply['move']; } if (isset($i) && (0 == ($i % 2))) { ++$i; $return[floor($i / 2)][$i % 2] = ''; } return $return; } /** public function get_history * Returns the game history * * @param bool optional return as JSON string * @return array or string game history */ public function get_history($json = false) { call(__METHOD__); call($json); $json = (bool) $json; if ( ! $json) { return $this->_history; } $history = array( ); foreach ($this->_history as $i => $node) { $move = $this->get_move($i); if ($move) { $move = array_unique(array_values($move)); } $history[] = array( expandFEN($node['board']), $move, (($this->_history[$i]['laser_fired']) ? $this->get_laser_path($i) : array( )), $this->get_hit_data($i), $this->get_battle_data($i, true), ); } return json_encode($history); } /** public function get_move * Returns the data for the given move index * * @param int optional move history index * @param bool optional return as JSON string * @return array or string previous turn */ public function get_move($index = null, $json = false) { call(__METHOD__); call($index); call($json); if (is_null($index)) { $index = count($this->_history) - 1; } $index = (int) $index; $json = (bool) $json; $turn = $this->_history[$index]; $board = expandFEN($turn['board']); if ( ! empty($this->_history[$index - 1])) { $board = expandFEN($this->_history[$index - 1]['board']); } if ( ! $turn['move']) { if ($json) { return 'false'; } return false; } $move = array( ); $move[0] = Pharaoh::target_to_index(substr($turn['move'], 0, 2)); if ('-' == $turn['move'][2]) { $move[1] = $move[0][0]; $move[2] = $turn['move'][3]; } else { $move[1] = Pharaoh::target_to_index(substr($turn['move'], 3, 2)); $move[2] = (int) (':' == $turn['move'][2]); } $move[3] = Pharaoh::get_piece_color($board[$move[0]]); if ($json) { return json_encode($move); } $move['from'] = $move[0]; $move['to'] = $move[1]; $move['extra'] = $move[2]; $move['color'] = $move[3]; return $move; } /** public function get_laser_path * Returns the laser path for the given move index * * @param int optional move history index * @param bool optional return as JSON string * @return array or JSON string laser path */ public function get_laser_path($index = null, $json = false) { call(__METHOD__); call($index); call($json); if (is_null($index)) { $index = count($this->_history) - 1; } $index = (int) $index; $json = (bool) $json; $count = count($this->_history); call($count); call($this->_history[$index]); if ((1 > $index) || ($index > ($count - 1))) { if ($json) { return '[]'; } return false; } $color = ((0 != ($index % 2)) ? 'silver' : 'red'); call($color); // here we need to do the move, store the board as is // and then fire the laser. // the reason being: if we just fire the laser at the previous board, // if the piece hit was rotated into the beam, it will not display correctly // and if we try and fire the laser at the current board, it will pass through // any hit piece because it's no longer there (unless it's a stacked obelisk, of course) // create a dummy pharaoh class and set the board as it was prior to the laser (-1) $PH = new Pharaoh( ); $PH->set_board(expandFEN($this->_history[$index - 1]['board'])); $PH->set_extra_info($this->_extra_info); // do the move, but do not fire the laser, and store the board $pre_board = $PH->do_move($this->_history[$index]['move'], false); // now fire the laser at that board $return = Pharaoh::fire_laser($color, $pre_board, $this->_pharaoh->get_extra_info( )); if ($json) { return json_encode($return['laser_path']); } return $return['laser_path']; } /** public function get_hit_data * Returns the turn data for the given move index * * @param int optional move history index * @param bool optional return as JSON string * @return array or string previous turn */ public function get_hit_data($index = null, $json = false) { call(__METHOD__); call($index); call($json); if (is_null($index)) { $index = count($this->_history) - 1; } $index = (int) $index; $json = (bool) $json; $move_data = array( ); // because we may have only hit the piece at A8 (idx: 0), this will // return false unless we test for that location specifically if ($this->_history[$index]['hits'] || ('0' === $this->_history[$index]['hits'])) { // we need to grab the previous board here, and perform the move // without firing the laser so we get the proper orientation // of the pieces as they were hit in case any pieces were rotated // into the beam // create a dummy pharaoh class and set the board as it was prior to the laser (-1) $PH = new Pharaoh( ); $PH->set_board(expandFEN($this->_history[$index - 1]['board'])); $PH->set_extra_info($this->_extra_info); // do the move and store that board $prev_board = $PH->do_move($this->_history[$index]['move'], false); $pieces = array( ); $hits = array_trim($this->_history[$index]['hits'], 'int'); foreach ($hits as $hit) { $pieces[] = $prev_board[$hit]; } $move_data = compact('hits', 'pieces'); } if ($json) { return json_encode($move_data); } return $move_data; } /** public function get_battle_data * Returns the battle data for the given move index * * @param int optional move history index * @param bool optional return as JSON string * @return array or string battle data */ public function get_battle_data($index = null, $simple = false, $json = false) { call(__METHOD__); call($index); call($simple); call($json); if (is_null($index)) { $index = count($this->_history) - 1; } $index = (int) $index; $simple = (bool) $simple; $json = (bool) $json; $battle_data = array( 'silver' => array( 'dead' => 0, 'immune' => 0, ), 'red' => array( 'dead' => 0, 'immune' => 0, ), ); $color = ((0 != ($index % 2)) ? 'silver' : 'red'); $other = (('silver' == $color) ? 'red' : 'silver'); call($color); if (isset($this->_history[$index])) { // grab the current data $battle_data[$color]['dead'] = $this->_history[$index]['dead_for']; $battle_data[$color]['immune'] = $this->_history[$index]['immune_for']; // for the game display, we want to decrease the value here $dead = false; if ($battle_data[$color]['dead']) { $dead = true; --$battle_data[$color]['dead']; } if ($battle_data[$color]['immune']) { --$battle_data[$color]['immune']; } // if we recently came back to life, show that if ($dead && ! $battle_data[$color]['dead']) { $battle_data[$color]['immune'] = $this->_extra_info['battle_immune']; } // grab the future data for the other player if (isset($this->_history[$index + 1])) { $battle_data[$other]['dead'] = $this->_history[$index + 1]['dead_for']; $battle_data[$other]['immune'] = $this->_history[$index + 1]['immune_for']; } else { // there is no next move, we need to calculate it based on the previous one // if there is no previous move data, the values will stay as defaults if (isset($this->_history[$index - 1])) { $m_extra_info = $this->_gen_move_extra_info($this->_history[$index], $this->_history[$index - 1]); $battle_data[$other]['dead'] = $m_extra_info['dead_for']; $battle_data[$other]['immune'] = $m_extra_info['immune_for']; } } } if ($simple) { $battle_data = array( array($battle_data['silver']['dead'], $battle_data['silver']['immune']), array($battle_data['red']['dead'], $battle_data['red']['immune']), ); } if ($json) { return json_encode($battle_data); } return $battle_data; } /** public function get_setup_name * Returns the name of the initial setup * used for this game * * @param void * @return string initial setup name */ public function get_setup_name( ) { return $this->_setup['name']; } /** public function get_setup * Returns the board of the initial setup * used for this game * * @param void * @return string initial setup name */ public function get_setup( ) { return $this->_history[0]['board']; } /** public function nudge * Nudges the given player to take their turn * * @param void * @return bool success */ public function nudge( ) { call(__METHOD__); if ($this->paused) { throw new MyException(__METHOD__.': Trying to perform an action on a paused game'); }
benjamw/pharaoh
ff3922bf55e927e29e91a968ec334e43a2c6900c
made nudge function use exceptions instead of return values
diff --git a/classes/game.class.php b/classes/game.class.php index 58530ff..ba14c7c 100644 --- a/classes/game.class.php +++ b/classes/game.class.php @@ -1089,1036 +1089,1036 @@ class Game /** public function is_player * Tests if the given ID is a player in the game * * @param int player id * @return bool player is in game */ public function is_player($player_id) { $player_id = (int) $player_id; return ((isset($this->_players['white']['player_id']) && ($player_id == $this->_players['white']['player_id'])) || (isset($this->_players['black']['player_id']) && ($player_id == $this->_players['black']['player_id']))); } /** public function get_color * Returns the requested player's color * * @param bool current player is requested player * @return string requested player's color (or false on failure) */ public function get_color($player = true) { $request = (((bool) $player) ? 'player' : 'opponent'); return ((isset($this->_players[$request]['color'])) ? $this->_players[$request]['color'] : false); } /** public function is_turn * Returns the requested player's turn * * @param bool current player is requested player * @return bool is the requested player's turn */ public function is_turn($player = true) { if ('Playing' != $this->state) { return false; } if ($this->_extra_info['draw_offered']) { return false; } $request = (((bool) $player) ? 'player' : 'opponent'); return ((isset($this->_players[$request]['turn'])) ? (bool) $this->_players[$request]['turn'] : false); } /** public function get_turn * Returns the name of the player who's turn it is * * @param void * @return string current player's name */ public function get_turn( ) { return ((isset($this->turn) && isset($this->_players[$this->turn]['object'])) ? $this->_players[$this->turn]['object']->username : false); } /** public function get_extra * Returns details of the extra_info var * * @param void * @return string extra info details */ public function get_extra( ) { call(__METHOD__); $return = array( ); if ($this->_extra_info['battle_dead']) { $front_abbr = $front_text = ''; if ($this->_pharaoh->has_sphynx) { $front_abbr = ', Front Only'; $front_text = ($this->_extra_info['battle_front_only'] ? ', Yes' : ', No'); } $return[] = '<span>Laser Battle (<abbr title="Dead, Immune'.$front_abbr.'">'.$this->_extra_info['battle_dead'].', '.$this->_extra_info['battle_immune'].$front_text.'</abbr>)</span>'; } if ($this->_pharaoh->has_sphynx && $this->_extra_info['move_sphynx']) { $return[] = '<span>Movable Sphynx</span>'; } return implode(' | ', $return); } /** public function get_extra_info * Returns the extra_info var * * @param void * @return array extra info */ public function get_extra_info( ) { return $this->_extra_info; } /** public function get_board * Returns the current board * * @param bool optional return expanded FEN * @param int optional history index * @return string board FEN (or xFEN) */ public function get_board($index = null, $expanded = false) { call(__METHOD__); if (is_null($index)) { $index = count($this->_history) - 1; } $index = (int) $index; $expanded = (bool) $expanded; if (isset($this->_history[$index])) { $board = $this->_history[$index]['board']; } else { return false; } if ($expanded) { return expandFEN($board); } return $board; } /** public function get_move_history * Returns the game move history * * @param void * @return array game history */ public function get_move_history( ) { call(__METHOD__); $history = $this->_history; array_shift($history); // remove the empty first move $return = array( ); foreach ($history as $i => $ply) { if (false !== strpos($ply['move'], '-')) { $ply['move'] = str_replace(array('-0','-1'), array('-L','-R'), $ply['move']); } $return[floor($i / 2)][$i % 2] = $ply['move']; } if (isset($i) && (0 == ($i % 2))) { ++$i; $return[floor($i / 2)][$i % 2] = ''; } return $return; } /** public function get_history * Returns the game history * * @param bool optional return as JSON string * @return array or string game history */ public function get_history($json = false) { call(__METHOD__); call($json); $json = (bool) $json; if ( ! $json) { return $this->_history; } $history = array( ); foreach ($this->_history as $i => $node) { $move = $this->get_move($i); if ($move) { $move = array_unique(array_values($move)); } $history[] = array( expandFEN($node['board']), $move, (($this->_history[$i]['laser_fired']) ? $this->get_laser_path($i) : array( )), $this->get_hit_data($i), $this->get_battle_data($i, true), ); } return json_encode($history); } /** public function get_move * Returns the data for the given move index * * @param int optional move history index * @param bool optional return as JSON string * @return array or string previous turn */ public function get_move($index = null, $json = false) { call(__METHOD__); call($index); call($json); if (is_null($index)) { $index = count($this->_history) - 1; } $index = (int) $index; $json = (bool) $json; $turn = $this->_history[$index]; $board = expandFEN($turn['board']); if ( ! empty($this->_history[$index - 1])) { $board = expandFEN($this->_history[$index - 1]['board']); } if ( ! $turn['move']) { if ($json) { return 'false'; } return false; } $move = array( ); $move[0] = Pharaoh::target_to_index(substr($turn['move'], 0, 2)); if ('-' == $turn['move'][2]) { $move[1] = $move[0][0]; $move[2] = $turn['move'][3]; } else { $move[1] = Pharaoh::target_to_index(substr($turn['move'], 3, 2)); $move[2] = (int) (':' == $turn['move'][2]); } $move[3] = Pharaoh::get_piece_color($board[$move[0]]); if ($json) { return json_encode($move); } $move['from'] = $move[0]; $move['to'] = $move[1]; $move['extra'] = $move[2]; $move['color'] = $move[3]; return $move; } /** public function get_laser_path * Returns the laser path for the given move index * * @param int optional move history index * @param bool optional return as JSON string * @return array or JSON string laser path */ public function get_laser_path($index = null, $json = false) { call(__METHOD__); call($index); call($json); if (is_null($index)) { $index = count($this->_history) - 1; } $index = (int) $index; $json = (bool) $json; $count = count($this->_history); call($count); call($this->_history[$index]); if ((1 > $index) || ($index > ($count - 1))) { if ($json) { return '[]'; } return false; } $color = ((0 != ($index % 2)) ? 'silver' : 'red'); call($color); // here we need to do the move, store the board as is // and then fire the laser. // the reason being: if we just fire the laser at the previous board, // if the piece hit was rotated into the beam, it will not display correctly // and if we try and fire the laser at the current board, it will pass through // any hit piece because it's no longer there (unless it's a stacked obelisk, of course) // create a dummy pharaoh class and set the board as it was prior to the laser (-1) $PH = new Pharaoh( ); $PH->set_board(expandFEN($this->_history[$index - 1]['board'])); $PH->set_extra_info($this->_extra_info); // do the move, but do not fire the laser, and store the board $pre_board = $PH->do_move($this->_history[$index]['move'], false); // now fire the laser at that board $return = Pharaoh::fire_laser($color, $pre_board, $this->_pharaoh->get_extra_info( )); if ($json) { return json_encode($return['laser_path']); } return $return['laser_path']; } /** public function get_hit_data * Returns the turn data for the given move index * * @param int optional move history index * @param bool optional return as JSON string * @return array or string previous turn */ public function get_hit_data($index = null, $json = false) { call(__METHOD__); call($index); call($json); if (is_null($index)) { $index = count($this->_history) - 1; } $index = (int) $index; $json = (bool) $json; $move_data = array( ); // because we may have only hit the piece at A8 (idx: 0), this will // return false unless we test for that location specifically if ($this->_history[$index]['hits'] || ('0' === $this->_history[$index]['hits'])) { // we need to grab the previous board here, and perform the move // without firing the laser so we get the proper orientation // of the pieces as they were hit in case any pieces were rotated // into the beam // create a dummy pharaoh class and set the board as it was prior to the laser (-1) $PH = new Pharaoh( ); $PH->set_board(expandFEN($this->_history[$index - 1]['board'])); $PH->set_extra_info($this->_extra_info); // do the move and store that board $prev_board = $PH->do_move($this->_history[$index]['move'], false); $pieces = array( ); $hits = array_trim($this->_history[$index]['hits'], 'int'); foreach ($hits as $hit) { $pieces[] = $prev_board[$hit]; } $move_data = compact('hits', 'pieces'); } if ($json) { return json_encode($move_data); } return $move_data; } /** public function get_battle_data * Returns the battle data for the given move index * * @param int optional move history index * @param bool optional return as JSON string * @return array or string battle data */ public function get_battle_data($index = null, $simple = false, $json = false) { call(__METHOD__); call($index); call($simple); call($json); if (is_null($index)) { $index = count($this->_history) - 1; } $index = (int) $index; $simple = (bool) $simple; $json = (bool) $json; $battle_data = array( 'silver' => array( 'dead' => 0, 'immune' => 0, ), 'red' => array( 'dead' => 0, 'immune' => 0, ), ); $color = ((0 != ($index % 2)) ? 'silver' : 'red'); $other = (('silver' == $color) ? 'red' : 'silver'); call($color); if (isset($this->_history[$index])) { // grab the current data $battle_data[$color]['dead'] = $this->_history[$index]['dead_for']; $battle_data[$color]['immune'] = $this->_history[$index]['immune_for']; // for the game display, we want to decrease the value here $dead = false; if ($battle_data[$color]['dead']) { $dead = true; --$battle_data[$color]['dead']; } if ($battle_data[$color]['immune']) { --$battle_data[$color]['immune']; } // if we recently came back to life, show that if ($dead && ! $battle_data[$color]['dead']) { $battle_data[$color]['immune'] = $this->_extra_info['battle_immune']; } // grab the future data for the other player if (isset($this->_history[$index + 1])) { $battle_data[$other]['dead'] = $this->_history[$index + 1]['dead_for']; $battle_data[$other]['immune'] = $this->_history[$index + 1]['immune_for']; } else { // there is no next move, we need to calculate it based on the previous one // if there is no previous move data, the values will stay as defaults if (isset($this->_history[$index - 1])) { $m_extra_info = $this->_gen_move_extra_info($this->_history[$index], $this->_history[$index - 1]); $battle_data[$other]['dead'] = $m_extra_info['dead_for']; $battle_data[$other]['immune'] = $m_extra_info['immune_for']; } } } if ($simple) { $battle_data = array( array($battle_data['silver']['dead'], $battle_data['silver']['immune']), array($battle_data['red']['dead'], $battle_data['red']['immune']), ); } if ($json) { return json_encode($battle_data); } return $battle_data; } /** public function get_setup_name * Returns the name of the initial setup * used for this game * * @param void * @return string initial setup name */ public function get_setup_name( ) { return $this->_setup['name']; } /** public function get_setup * Returns the board of the initial setup * used for this game * * @param void * @return string initial setup name */ public function get_setup( ) { return $this->_history[0]['board']; } /** public function nudge * Nudges the given player to take their turn * * @param void * @return bool success */ public function nudge( ) { call(__METHOD__); if ($this->paused) { throw new MyException(__METHOD__.': Trying to perform an action on a paused game'); } - if ($this->test_nudge( )) { - $sent = Email::send('nudge', $this->_players['opponent']['player_id'], array('opponent' => $this->_players['player']['object']->username, 'game_id' => $this->id)); + if ( ! $this->test_nudge( )) { + throw new MyException(__METHOD__.': Trying to nudge a person who is not nudgable'); + } - if ($sent) { - $this->_mysql->delete(self::GAME_NUDGE_TABLE, " WHERE game_id = '{$this->id}' "); - $this->_mysql->insert(self::GAME_NUDGE_TABLE, array('game_id' => $this->id, 'player_id' => $this->_players['opponent']['player_id'])); - } + $sent = Email::send('nudge', $this->_players['opponent']['player_id'], array('opponent' => $this->_players['player']['object']->username, 'game_id' => $this->id)); - return $sent; + if ( ! $sent) { + throw new MyException(__METHOD__.': Failed to send email'); } - return false; + $this->_mysql->delete(self::GAME_NUDGE_TABLE, " WHERE game_id = '{$this->id}' "); + $this->_mysql->insert(self::GAME_NUDGE_TABLE, array('game_id' => $this->id, 'player_id' => $this->_players['opponent']['player_id'])); } /** public function test_nudge * Tests if the current player can nudge or not * * @param void * @return bool player can be nudged */ public function test_nudge( ) { call(__METHOD__); $player_id = (int) $this->_players['opponent']['player_id']; if ( ! $this->is_player($player_id) || $this->is_turn( ) || ('Playing' != $this->state) || $this->paused) { return false; } if ( ! $this->_players['opponent']['object']->allow_email || ('' == $this->_players['opponent']['object']->email)) { return false; } try { $nudge_time = Settings::read('nudge_flood_control'); } catch (MyException $e) { return false; } if (-1 == $nudge_time) { return false; } elseif (0 == $nudge_time) { return true; } // check the nudge status for this game/player // 'now' is taken from the DB because it may // have a different time from the PHP server $query = " SELECT NOW( ) AS now , G.modify_date AS move_date , GN.nudged FROM ".self::GAME_TABLE." AS G LEFT JOIN ".self::GAME_NUDGE_TABLE." AS GN ON (GN.game_id = G.game_id AND GN.player_id = '{$player_id}') WHERE G.game_id = '{$this->id}' AND G.state = 'Playing' "; $dates = $this->_mysql->fetch_assoc($query); if ( ! $dates) { return false; } // check the dates // if the move date is far enough in the past // AND the player has not been nudged // OR the nudge date is far enough in the past if ((strtotime($dates['move_date']) <= strtotime('-'.$nudge_time.' hour', strtotime($dates['now']))) && ((empty($dates['nudged'])) || (strtotime($dates['nudged']) <= strtotime('-'.$nudge_time.' hour', strtotime($dates['now']))))) { return true; } return false; } /** public function get_players * Grabs the player array * * @param void * @return array player data */ public function get_players( ) { $players = array( ); foreach (array('white','black') as $color) { $player_id = $this->_players[$color]['player_id']; $players[$player_id] = $this->_players[$color]; $players[$player_id]['username'] = $this->_players[$color]['object']->username; unset($players[$player_id]['object']); } return $players; } /** public function get_outcome * Returns the outcome string and outcome * * @param int id of observing player * @return array (outcome text, outcome string) */ public function get_outcome($player_id) { call(__METHOD__); $player_id = (int) $player_id; if ( ! in_array($this->state, array('Finished', 'Draw'))) { return false; } if ('Draw' == $this->state) { return array('Draw Game', 'lost'); } if ( ! empty($this->_pharaoh->winner) && isset($this->_players[$this->_pharaoh->winner]['player_id'])) { $winner = $this->_players[$this->_pharaoh->winner]['player_id']; } else { $query = " SELECT G.winner_id FROM ".self::GAME_TABLE." AS G WHERE G.game_id = '{$this->id}' "; $winner = $this->_mysql->fetch_value($query); } if ( ! $winner) { return false; } if ($player_id == $winner) { return array('You Won !', 'won'); } else { return array($GLOBALS['_PLAYERS'][$winner].' Won', 'lost'); } } /** static public function write_game_file * Writes the game to a text file for storage * * @param int game id * @action writes the game PGN file * @return string PGN */ static public function write_game_file($game_id) { // the PGN export format is very exact when it comes to what is allowed // and what is not allowed when creating a PGN file. // first, the only new line character that is allowed is a single line feed character // output in PHP as \n, this means that \r is not allowed, nor is \r\n // second, no tab characters are allowed, neither vertical, nor horizontal (\t) // third, comments do NOT nest, thus { { } } will be in error, as will { ; } // fourth, { } denotes an inline comment, where ; denotes a 'rest of line' comment // fifth, a percent sign (%) at the beginning of a line denotes a whole line comment // sixth, comments may not be included in the meta tags ( [Meta "data"] ) $Mysql = Mysql::get_instance( ); if (empty($game_id)) { throw new MyException(__METHOD__.': No game id given'); } try { $Game = new Game($game_id); } catch (MyException $e) { throw $e; } if ( ! isset($Game->_history[1])) { return false; } $start_date = date('Y-m-d', strtotime($Game->_history[1]['move_date'])); $white_name = $Game->_players['white']['object']->lastname.', '.$Game->_players['white']['object']->firstname.' ('.$Game->_players['white']['object']->username.')'; $black_name = $Game->_players['black']['object']->lastname.', '.$Game->_players['black']['object']->firstname.' ('.$Game->_players['black']['object']->username.')'; $extra_info = $Game->_extra_info; $diff = array_compare($extra_info, self::$_EXTRA_INFO_DEFAULTS); $extra_info = $diff[0]; unset($extra_info['white_color']); unset($extra_info['draw_offered']); unset($extra_info['undo_requested']); $xheadxtra = ''; $xheader = "[Event \"Pharaoh (Khet) Casual Game #{$Game->id}\"]\n" . "[Site \"{$GLOBALS['_ROOT_URI']}\"]\n" . "[Date \"{$start_date}\"]\n" . "[Round \"-\"]\n" . "[White \"{$white_name}\"]\n" . "[Black \"{$black_name}\"]\n" . "[Setup \"{$Game->_history[0]['board']}\"]\n"; if ($extra_info) { $options = serialize($extra_info); $xheadxtra .= "[Options \"{$options}\"]\n"; } $xheadxtra .= "[Mode \"ICS\"]\n"; $body = ''; $line = ''; $token = ''; foreach ($Game->_history as $key => $move) { // skip the first entry if ( ! $key) { continue; } if (0 != ($key % 2)) { $token = floor(($key + 1) / 2) . '. ' . $move['move']; } else { $token .= ' ' . $move['move']; if ((strlen($line) + strlen($token)) > 79) { $body .= $line . "\n"; $line = ''; } elseif (strlen($line) > 0) { $line .= ' '; } $line .= $token; $token = ''; } } if ($token) { if ((strlen($line) + strlen($token)) > 79) { $body .= $line . "\n"; $line = ''; } elseif (strlen($line) > 0) { $line .= ' '; } $line .= $token; $token = ''; } // finish up the PGN with the game result $result = '*'; if ('Finished' == $Game->state) { if ('white' == $Game->turn) { $result = '1-0'; } else { $result = '0-1'; } } elseif ('Draw' == $Game->state) { $result = '1/2-1/2'; } $body .= $line; if ((strlen($line) + strlen($result)) > 79) { $body .= "\n"; } elseif (strlen($line) > 0) { $body .= ' '; } $body .= $result . "\n"; $xheader .= "[Result \"$result\"]\n"; $data = $xheader . $xheadxtra . "\n" . $body; $filename = GAMES_DIR."/Pharoah_Game_{$Game->id}_".str_replace(array(' ','-',':'), '', $Game->_history[count($Game->_history) - 1]['move_date']).'.pgn'; file_put_contents($filename, $data); return $data; } protected function _gen_move_extra_info($curr_move, $prev_move = null) { call(__METHOD__); $m_extra_info = self::$_HISTORY_EXTRA_INFO_DEFAULTS; if ( ! $this->_extra_info['battle_dead']) { return $m_extra_info; } if ( ! $curr_move) { throw new MyException(__METHOD__.': Move data not present for calculation'); } // set our current move extra info if ($prev_move) { $m_extra_info['dead_for'] = $prev_move['dead_for']; $m_extra_info['immune_for'] = $prev_move['immune_for']; } $dead = false; if ($m_extra_info['dead_for']) { $dead = true; } if (0 < $m_extra_info['dead_for']) { --$m_extra_info['dead_for']; } // we are allowed to shoot now, set our immunity if ($dead && ! $m_extra_info['dead_for']) { $m_extra_info['immune_for'] = $this->_extra_info['battle_immune']; } if ( ! $dead && (0 < $m_extra_info['immune_for'])) { --$m_extra_info['immune_for']; } if ( ! $m_extra_info['dead_for'] && ! $m_extra_info['immune_for'] && $curr_move['laser_hit']) { $m_extra_info['dead_for'] = $this->_extra_info['battle_dead']; } return $m_extra_info; } /** protected function _pull * Pulls the data from the database * and sets up the objects * * @param void * @action pulls the game data * @return void */ protected function _pull( ) { call(__METHOD__); if ( ! $this->id) { return false; } if ( ! $_SESSION['player_id']) { throw new MyException(__METHOD__.': Player id is not in session when pulling game data'); } // grab the game data $query = " SELECT * FROM ".self::GAME_TABLE." WHERE game_id = '{$this->id}' "; $result = $this->_mysql->fetch_assoc($query); call($result); if ( ! $result) { throw new MyException(__METHOD__.': Game data not found for game #'.$this->id); } if ('Waiting' == $result['state']) { throw new MyException(__METHOD__.': Game (#'.$this->id.') is still only an invite'); } // set the properties $this->state = $result['state']; $this->paused = (bool) $result['paused']; $this->create_date = strtotime($result['create_date']); $this->modify_date = strtotime($result['modify_date']); $this->_extra_info = array_merge_plus(self::$_EXTRA_INFO_DEFAULTS, unserialize($result['extra_info'])); // just empty this out, we don't need it anymore $this->_extra_info['invite_setup'] = ''; // grab the initial setup // TODO: convert to the setup object // (need to build more in the setup object) $query = " SELECT * FROM ".Setup::SETUP_TABLE." WHERE setup_id = '{$result['setup_id']}' "; $setup = $this->_mysql->fetch_assoc($query); call($setup); // the setup may have been deleted if ( ! $setup) { $this->_setup = array( 'id' => $result['setup_id'], 'name' => '[DELETED]', ); } else { $this->_setup = array( 'id' => $result['setup_id'], 'name' => $setup['name'], ); } // set up the players $this->_players['white']['player_id'] = $result['white_id']; $this->_players['white']['object'] = new GamePlayer($result['white_id']); $this->_players['silver'] = & $this->_players['white']; $this->_players['black']['player_id'] = $result['black_id']; if (0 != $result['black_id']) { // we may have an open game $this->_players['black']['object'] = new GamePlayer($result['black_id']); $this->_players['red'] = & $this->_players['black']; } // we test this first one against the black id, so if it fails because // the person viewing the game is not playing in the game (viewing it // after it's finished) we want "player" to be equal to "white" if ($_SESSION['player_id'] == $result['black_id']) { $this->_players['player'] = & $this->_players['black']; $this->_players['player']['color'] = 'black'; $this->_players['player']['opp_color'] = 'white'; $this->_players['opponent'] = & $this->_players['white']; $this->_players['opponent']['color'] = 'white'; $this->_players['opponent']['opp_color'] = 'black'; } else { $this->_players['player'] = & $this->_players['white']; $this->_players['player']['color'] = 'white'; $this->_players['player']['opp_color'] = 'black'; $this->_players['opponent'] = & $this->_players['black']; $this->_players['opponent']['color'] = 'black'; $this->_players['opponent']['opp_color'] = 'white'; } // set up the board $query = " SELECT * FROM ".self::GAME_HISTORY_TABLE." WHERE game_id = '{$this->id}' ORDER BY move_date ASC "; $result = $this->_mysql->fetch_array($query); call($result); if ($result) { $count = count($result); // integrate the extra info into the history array foreach ($result as & $move) { $m_extra = array_merge_plus(self::$_HISTORY_EXTRA_INFO_DEFAULTS, unserialize($move['extra_info'])); $move = array_merge($move, $m_extra); } unset($move); // kill the reference $this->_history = $result; $this->turn = ((0 == ($count % 2)) ? 'black' : 'white'); $this->last_move = strtotime($result[$count - 1]['move_date']); try { $this->_pharaoh = new Pharaoh( ); $this->_pharaoh->set_board(expandFEN($this->_history[$count - 1]['board'])); $this->_pharaoh->set_extra_info($this->_extra_info); } catch (MyException $e) { throw $e; } $m_extra_info = $this->_gen_move_extra_info($this->_history[$count - 1], (isset($this->_history[$count - 2]) ? $this->_history[$count - 2] : null)); $this->_current_move_extra_info = array_merge_plus(self::$_HISTORY_EXTRA_INFO_DEFAULTS, $m_extra_info); } else { $this->last_move = $this->create_date; } $this->_players[$this->turn]['turn'] = true; } /** public function save * Saves all changed data to the database * * @param void * @action saves the game data * @return void */ public function save( ) { call(__METHOD__); // grab the base game data $query = " SELECT state , extra_info , modify_date FROM ".self::GAME_TABLE." WHERE game_id = '{$this->id}' AND state <> 'Waiting' "; $game = $this->_mysql->fetch_assoc($query); call($game); $update_modified = false; if ( ! $game) { throw new MyException(__METHOD__.': Game data not found for game #'.$this->id); } $this->_log('DATA SAVE: #'.$this->id.' @ '.time( )."\n".' - '.$this->modify_date."\n".' - '.strtotime($game['modify_date'])); // test the modified date and make sure we still have valid data call($this->modify_date); call(strtotime($game['modify_date'])); if ($this->modify_date != strtotime($game['modify_date'])) { $this->_log('== FAILED =='); throw new MyException(__METHOD__.': Trying to save game (#'.$this->id.') with out of sync data'); } $update_game = false; call($game['state']);
benjamw/pharaoh
b90ed76723a0a1ea39621b24b104a2f1d63e2bb0
removed localhost specific code
diff --git a/includes/func.global.php b/includes/func.global.php index 447ad93..87974c6 100644 --- a/includes/func.global.php +++ b/includes/func.global.php @@ -1,296 +1,296 @@ <?php /** function call [dump] [debug] * This function is for debugging only * Outputs given var to screen * or, if no var given, outputs stars to note position * * @param mixed optional var to output * @param bool optional bypass debug value and output anyway * @action outputs var to screen * @return void */ function call($var = 'Th&F=xUFucreSp2*ezAhe=ApuPR*$axe', $bypass = false, $show_from = true, $new_window = false, $error = false) { if ((( ! defined('DEBUG') || ! DEBUG) || ! empty($GLOBALS['NODEBUG'])) && ! (bool) $bypass) { return false; } if ('Th&F=xUFucreSp2*ezAhe=ApuPR*$axe' === $var) { $contents = '<span style="font-size:larger;font-weight:bold;color:red;">--==((OO88OO))==--</span>'; } else { // begin output buffering so we can escape any html // and print_r is better at catching recursion than var_export ob_start( ); if ( ! function_exists('xdebug_disable')) { if ((is_string($var) && ! preg_match('/^\\s*$/', $var))) { // non-whitespace strings print_r($var); } else { if (is_array($var) || is_object($var)) { print_r($var); } else { var_dump($var); } } } else { var_dump($var); } // end output buffering and output the result if ( ! function_exists('xdebug_disable')) { $contents = htmlentities(ob_get_contents( )); } else { $contents = ob_get_contents( ); } ob_end_clean( ); } $j = 0; $html = ''; $debug_funcs = array('dump', 'debug'); if ((bool) $show_from) { $called_from = debug_backtrace( ); if (isset($called_from[$j + 1]) && in_array($called_from[$j + 1]['function'], $debug_funcs)) { ++$j; } $file0 = substr($called_from[$j]['file'], strlen($_SERVER['DOCUMENT_ROOT'])); $line0 = $called_from[$j]['line']; $called = ''; if (isset($called_from[$j + 1]['file'])) { $file1 = substr($called_from[$j + 1]['file'], strlen($_SERVER['DOCUMENT_ROOT'])); $line1 = $called_from[$j + 1]['line']; $called = "{$file1} : {$line1} called "; } elseif (isset($called_from[$j + 1]['class'])) { $called = $called_from[$j + 1]['class'].$called_from[$j + 1]['type'].$called_from[$j + 1]['function'].' called '; } $html = "<strong>{$called}{$file0} : {$line0}</strong>\n"; } if ( ! $new_window) { $color = '#000'; if ($error) { $color = '#F00'; } echo "\n\n<pre style=\"background:#FFF;color:{$color};font-size:larger;\">{$html}{$contents}\n<hr /></pre>\n\n"; } else { ?> <script language="javascript"> myRef = window.open('','debugWindow'); myRef.document.write('\n\n<pre style="background:#FFF;color:#000;font-size:larger;">'); myRef.document.write('<?php echo str_replace("'", "\'", str_replace("\n", "<br />", "{$html}{$contents}")); ?>'); myRef.document.write('\n<hr /></pre>\n\n'); </script> <?php } } function dump($var = 'Th&F=xUFucreSp2*ezAhe=ApuPR*$axe', $bypass = false, $show_from = true, $new_window = false, $error = false) { call($var, $bypass, $show_from, $new_window, $error); } function debug($var = 'Th&F=xUFucreSp2*ezAhe=ApuPR*$axe', $bypass = true, $show_from = true, $new_window = false, $error = false) { call($var, $bypass, $show_from, $new_window, $error); } /** function load_class * This function automagically loads the class * via the spl_autoload_register function above * as it is instantiated (jit). * * @param string class name * @action loads given class name if found * @return bool success */ function load_class($class_name) { $class_file = CLASSES_DIR.strtolower($class_name).'.class.php'; if (class_exists($class_name)) { return true; } elseif (file_exists($class_file)) { require_once $class_file; return true; } else { throw new MyException(__FUNCTION__.': Class file ('.$class_file.') not found'); } } /** function test_token * This function tests the token given by the * form and checks it against the session token * and if they do not match, dies * * @param bool optional keep original token flag * @action tests tokens and dies if bad * @action optionally renews the session token * @return void */ function test_token($keep = false) { call($_SESSION['token']); call($_POST['token']); - if (DEBUG || ('games' == $_SERVER['HTTP_HOST'])) { + if (DEBUG) { return; } if ( ! isset($_SESSION['token']) || ! isset($_POST['token']) || (0 !== strcmp($_SESSION['token'], $_POST['token']))) { die('Hacking attempt detected.<br /><br />If you have reached this page in error, please go back,<br />clear your cache, refresh the page, and try again.'); } // renew the token if ( ! $keep) { $_SESSION['token'] = md5(uniqid(rand( ), true)); } } /** function test_debug * This function tests the debug given by the * URL and checks it against the globals debug password * and if they do not match, doesn't debug * * @param void * @action tests debug pass * @return bool success */ function test_debug( ) { if ( ! isset($_GET['DEBUG'])) { return false; } if ( ! class_exists('Settings') || ! Settings::test( )) { return false; } if ('' == trim(Settings::read('debug_pass'))) { return false; } if (0 !== strcmp($_GET['DEBUG'], Settings::read('debug_pass'))) { return false; } $GLOBALS['_&_DEBUG_QUERY'] = '&DEBUG='.$_GET['DEBUG']; $GLOBALS['_?_DEBUG_QUERY'] = '?DEBUG='.$_GET['DEBUG']; return true; } /** function expandFEN * This function expands a packed FEN into a * string where each index is a valid location * * @param string packed FEN * @return string expanded FEN */ function expandFEN($FEN) { $FEN = preg_replace('/\s+/', '', $FEN); // remove spaces $FEN = preg_replace_callback('/\d+/', 'replace_callback', $FEN); // unpack the 0s $xFEN = str_replace('/', '', $FEN); // remove the row separators return $xFEN; } function replace_callback($match) { return (((int) $match[0]) ? str_repeat('0', (int) $match[0]) : $match[0]); } /** function packFEN * This function packs an expanded FEN into a * string that takes up less space * * @param string expanded FEN * @param int [optional] length of rows * @return string packed FEN */ function packFEN($xFEN, $row_length = 10) { $xFEN = preg_replace('/\s+/', '', $xFEN); // remove spaces $xFEN = preg_replace('/\//', '', $xFEN); // remove any row separators $xFEN = trim(chunk_split($xFEN, $row_length, '/'), '/'); // add the row separators $FEN = preg_replace('/(0+)/e', "strlen('\\1')", $xFEN); // pack the 0s return $FEN; } /** function ife * if-else * This function returns the value if it exists (or is optionally not empty) * or a default value if it does not exist (or is empty) * * @param mixed var to test * @param mixed optional default value * @param bool optional allow empty value * @param bool optional change the passed reference var * @return mixed $var if exists (and not empty) or default otherwise */ function ife( & $var, $default = null, $allow_empty = true, $change_reference = false) { if ( ! isset($var) || ( ! (bool) $allow_empty && empty($var))) { if ((bool) $change_reference) { $var = $default; // so it can also be used by reference } return $default; } return $var; } /** function ifer * if-else reference * This function returns the value if it exists (or is optionally not empty) * or a default value if it does not exist (or is empty) * It also changes the reference var * * @param mixed var to test * @param mixed optional default value * @param bool optional allow empty value * @action updates/sets the reference var if needed * @return mixed $var if exists (and not empty) or default otherwise */ function ifer( & $var, $default = null, $allow_empty = true) { return ife($var, $default, $allow_empty, true); } /** function ifenr * if-else non-reference * This function returns the value if it is not empty * or a default value if it is empty * * @param mixed var to test * @param mixed optional default value * @return mixed $var if not empty or default otherwise */ function ifenr($var, $default = null) { if (empty($var)) { return $default; } return $var; } diff --git a/includes/inc.global.php b/includes/inc.global.php index bec0a24..0f4a42f 100644 --- a/includes/inc.global.php +++ b/includes/inc.global.php @@ -1,187 +1,186 @@ <?php $debug = false; // set some ini stuff ini_set('register_globals', 0); // you really should have this off anyways // deal with those lame magic quotes if (get_magic_quotes_gpc( )) { function stripslashes_deep($value) { $value = is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value); return $value; } $_POST = array_map('stripslashes_deep', $_POST); $_GET = array_map('stripslashes_deep', $_GET); $_COOKIE = array_map('stripslashes_deep', $_COOKIE); $_REQUEST = array_map('stripslashes_deep', $_REQUEST); } /** * GLOBAL INCLUDES * * * * * * * * * * * * * * * * * * * * * * * * * * */ define('ROOT_DIR', dirname(dirname(__FILE__)).DIRECTORY_SEPARATOR); define('INCLUDE_DIR', dirname(__FILE__).DIRECTORY_SEPARATOR); define('CLASSES_DIR', ROOT_DIR.'classes'.DIRECTORY_SEPARATOR); define('GAMES_DIR', ROOT_DIR.'games'.DIRECTORY_SEPARATOR); define('LOG_DIR', ROOT_DIR.'logs'.DIRECTORY_SEPARATOR); ini_set('error_log', LOG_DIR.'php.err'); if (is_file(INCLUDE_DIR.'config.php')) { require_once INCLUDE_DIR.'config.php'; } #/*/ #elseif ('setup-config.php' != basename($_SERVER['PHP_SELF'])) { # header('Location: setup-config.php'); #/*/ #elseif ('install.php' != basename($_SERVER['PHP_SELF'])) { # header('Location: install.php'); #//*/ # exit; #} require_once INCLUDE_DIR.'inc.settings.php'; require_once INCLUDE_DIR.'func.global.php'; require_once INCLUDE_DIR.'html.general.php'; require_once INCLUDE_DIR.'html.tables.php'; // MAKE SURE TO LOAD CLASS FILES BEFORE STARTING THE SESSION // OR YOU END UP WITH INCOMPLETE OBJECTS PULLED FROM SESSION spl_autoload_register('load_class'); // set the proper timezone date_default_timezone_set($GLOBALS['_DEFAULT_TIMEZONE']); /** * GLOBAL DATA * * * * * * * * * * * * * * * * * * * * * * * * * * */ $GLOBALS['_&_DEBUG_QUERY'] = ''; $GLOBALS['_?_DEBUG_QUERY'] = ''; // make a list of all the color files available to use $GLOBALS['_COLORS'] = array( ); $dh = opendir(realpath(dirname(__FILE__).'/../css')); while (false !== ($file = readdir($dh))) { if (preg_match('/^c_(.+)\\.css$/i', $file, $match)) { // scanning for color files only $GLOBALS['_COLORS'][] = $match[1]; } } // convert the full color file name to just the color portion $GLOBALS['_DEFAULT_COLOR'] = ''; if (class_exists('Settings') && Settings::test( )) { $GLOBALS['_DEFAULT_COLOR'] = preg_replace('/c_(.+)\\.css/i', '$1', Settings::read('default_color')); } if ('' == $GLOBALS['_DEFAULT_COLOR']) { if (in_array('red_black', $GLOBALS['_COLORS'])) { $GLOBALS['_DEFAULT_COLOR'] = 'red_black'; } elseif ($GLOBALS['_COLORS']) { $GLOBALS['_DEFAULT_COLOR'] = $GLOBALS['_COLORS'][0]; } else { $GLOBALS['_DEFAULT_COLOR'] = ''; } } // set the session cookie parameters so the cookie is only valid for this game $parts = pathinfo($_SERVER['REQUEST_URI']); $path = $parts['dirname']; if (empty($parts['extension'])) { $path .= $parts['basename']; } $path = str_replace('\\', '/', $path).'/'; session_set_cookie_params(0, $path); session_start( ); // make sure we don't cross site session steal in our own site if ( ! isset($_SESSION['PWD']) || (__FILE__ != $_SESSION['PWD'])) { $_SESSION = array( ); } $_SESSION['PWD'] = __FILE__; // set a token, we'll be passing one around a lot if ( ! isset($_SESSION['token'])) { $_SESSION['token'] = md5(uniqid(rand( ), true)); } -call($_SESSION['token']); if ( ! defined('DEBUG')) { if (test_debug( )) { define('DEBUG', true); // DO NOT CHANGE THIS ONE } else { define('DEBUG', (bool) $debug); // set to true for output of debugging code } } $GLOBALS['_LOGGING'] = DEBUG; // do not change, rather, change debug value if (Mysql::test( )) { $Mysql = Mysql::get_instance( ); $Mysql->set_settings(array( 'log_path' => LOG_DIR, 'email_subject' => GAME_NAME.' Query Error', )); if (class_exists('Settings') && Settings::test( )) { $Mysql->set_settings(array( 'log_errors' => Settings::read('DB_error_log'), 'email_errors' => Settings::read('DB_error_email'), 'email_from' => Settings::read('from_email'), 'email_to' => Settings::read('to_email'), )); } } if (defined('DEBUG') && DEBUG) { ini_set('display_errors','On'); error_reporting(E_ALL | E_STRICT); // all errors, notices, and strict warnings if (isset($Mysql)) { $Mysql->set_error(3); } } else { // do not edit the following ini_set('display_errors','Off'); error_reporting(E_ALL & ~ E_NOTICE); // show errors, but not notices } // log the player in if (( ! defined('LOGIN') || LOGIN) && isset($Mysql)) { $GLOBALS['Player'] = new GamePlayer( ); // this will redirect to login if failed $GLOBALS['Player']->log_in( ); if (0 != $_SESSION['player_id']) { $Message = new Message($_SESSION['player_id'], $GLOBALS['Player']->is_admin); } // set the default color for the player if (('' != $GLOBALS['Player']->color) && (in_array($GLOBALS['Player']->color, $GLOBALS['_COLORS']))) { $GLOBALS['_DEFAULT_COLOR'] = $GLOBALS['Player']->color; } // set the default timezone for the player if ('' !== $GLOBALS['Player']->timezone) { date_default_timezone_set($GLOBALS['Player']->timezone); } } // grab the list of players if (isset($Mysql)) { $GLOBALS['_PLAYERS'] = Player::get_array( ); }
benjamw/pharaoh
fb9920da8d81ae0e9555883b8fc1732f2f3cdefb
added array_filter_recursive function
diff --git a/includes/func.array.php b/includes/func.array.php index bfb63bb..5c42e55 100644 --- a/includes/func.array.php +++ b/includes/func.array.php @@ -1,370 +1,405 @@ <?php /** * ARRAY FUNCTIONS * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** function array_trim [arrayTrim] * Performs the trim function recursively on * every element in an array and optionally typecasts * the element to the given type * * @param mixed csv list or array by reference * @param string optional typecast type * @return array */ function array_trim( & $array, $type = null) { $types = array( 'int' , 'integer' , 'bool' , 'boolean' , 'float' , 'double' , 'real' , 'string' , 'array' , 'object' , ); // if a non-empty string value comes through, don't erase it // this is specifically for '0', but may work for others $is_non_empty_string = (is_string($array) && strlen(trim($array))); if ( ! $array && ! $is_non_empty_string) { $array = array( ); } if ( ! in_array($type, $types)) { $type = null; } if ( ! is_array($array)) { $array = explode(',', $array); } if ( ! is_null($type)) { array_walk_recursive($array, create_function('&$v', '$v = ('.$type.') trim($v);')); } else { array_walk_recursive($array, create_function('&$v', '$v = trim($v);')); } return $array; // returns by reference as well } function arrayTrim( & $array, $type = null) { return array_trim($array, $type); } /** function array_clean [arrayClean] * Strips out the unnecessary bits from an array * so it can be input into a database, or to just * generally clean an array of fluff * * @param array data array to be cleaned * @param mixed csv or array of allowed keys * @param mixed optional csv or array of required keys * @return array */ function array_clean($array, $keys, $reqd = array( )) { if ( ! is_array($array)) { return array( ); } array_trim($keys); array_trim($reqd); $keys = array_unique(array_merge($keys, $reqd)); if (empty($keys)) { return array( ); } $return = array( ); foreach ($keys as $key) { if (in_array($key, $reqd) && (empty($array[$key]))) { throw new MyException(__FUNCTION__.': Required element ('.$key.') missing'); } if (isset($array[$key])) { $return[$key] = $array[$key]; } } return $return; } function arrayClean($array, $keys, $reqd = array( )) { return array_clean($array, $keys, $reqd); } /** function array_transpose [arrayTranspose] * Transposes a 2-D array * array[i][j] becomes array[j][i] * * Not to be confused with the PHP function array_flip * * @param array * @return mixed array (or bool false on failure) */ function array_transpose($array) { if ( ! is_array($array)) { throw new MyException(__FUNCTION__.': Data given was not an array'); } $return = array( ); foreach ($array as $key1 => $value1) { if ( ! is_array($value1)) { continue; } foreach ($value1 as $key2 => $value2) { $return[$key2][$key1] = $value2; } } if (0 == count($return)) { return false; } return $return; } function arrayTranspose($array) { return array_transpose($array); } /** function array_shrink [arrayShrink] * Returns all elements with second level key $key * from a 2-D array * e.g.- * $array[0]['foo'] = 'bar'; * $array[1]['foo'] = 'baz'; * * array_shrink($array, 'foo') returns * array( * [0] = 'bar' * [1] = 'baz' * ) * * This function returns the input if it is not * an array, or returns false if the key is not * present in the array * * @param array data array * @param mixed second level key * @return mixed array (or original input or bool false on failure) */ function array_shrink($array, $key) { if ( ! is_array($array)) { return $array; } $array = array_transpose($array); if ( ! isset($array[$key])) { return false; } return $array[$key]; } function arrayShrink($array, $key) { return array_shrink($array, $key); } /** function array_sum_field [arraySumField] * Returns the sum of all elements with key $key * from a 2-D array, no matter if $key is a first level * or second level key * * @param array * @param mixed element key * @return mixed float/int total (or bool false on failure) */ function array_sum_field($array, $key) { if ( ! is_array($array)) { return false; } $total = 0; if (isset($array[$key]) && is_array($array[$key])) { $total = array_sum($array[$key]); } else { foreach ($array as $row) { if (is_array($row) && isset($row[$key])) { $total += $row[$key]; } } } return $total; } function arraySumField($array, $key) { return array_sum_field($array, $key); } /** function implode_full [implodeFull] * Much like implode, but including the keys with an * extra divider between key-value pairs * Can be used to create URL GET strings from arrays * * @param array * @param string optional separator between elements (for URL GET, use '&', default) * @param string optional divider between key-value pairs (for URL GET, use '=', default) * @param bitwise int optional URL encode flag * @return string */ define('URL_ENCODE_NONE', 0); define('URL_ENCODE_KEY', 1); define('URL_ENCODE_VAL', 2); define('URL_ENCODE_FULL', 4); function implode_full($array, $separator = '&', $divider = '=', $url = URL_ENCODE_NONE) { if ( ! is_array($array) || (0 == count($array))) { return $array; } $str = ''; foreach ($array as $key => $val) { if (URL_ENCODE_KEY & $url) { $key = urlencode($key); } if (URL_ENCODE_VAL & $url) { $val = urlencode($val); } $str .= $key.$divider.$val.$separator; } $str = substr($str, 0, -(strlen($separator))); if (URL_ENCODE_FULL & $url) { $str = urlencode($str); } return $str; } function implodeFull($array, $separator = '&', $divider = '=', $url = URL_ENCODE_NONE) { return implode_full($array, $separator, $divider, $url); } /** function explode_full [explodeFull] * Much like explode, but including the keys with an * extra divider between key-value pairs * Can be used to create arrays from URL GET strings * * @param string * @param string optional separator between elements (for URL GET, use '&', default) * @param string optional divider between key-value pairs (for URL GET, use '=', default) * @return array */ function explode_full($string, $separator = '&', $divider = '=') { // explode the string about the separator $first = explode($separator, $string); // now go through each element in the first array and explode each about the divider foreach ($first as $element) { list($key, $value) = explode($divider, $element); $array[$key] = $value; } return $array; } function explodeFull($string, $separator = '&', $divider = '=') { return explode_full($string, $separator, $divider); } /** function kshuffle * Exactly the same as shuffle except this function * preserves the original keys of the array * * @param array the array to shuffle by reference * @return array */ function kshuffle( & $array) { uasort($array, create_function('$a,$b', 'rand(1, -1);')); } /** function array_merge_plus * * Exactly the same as array_merge except this function * allows entry of non-arrays without throwing errors * If an empty argument is encountered, it removes it. * If a non-empty, non-array value is encountered, * it appends it to the array in the order received. * * @param mixed item to merge into array * @param ... * @return array merged array */ function array_merge_plus($array1) { // grab the arguments of this function // and parse through them, removing any empty arguments // and converting non-empty, non-arrays to arrays $args = func_get_args( ); foreach ($args as $key => $arg) { if ( ! is_array($arg)) { if (empty($arg)) { unset($args[$key]); continue; } } $args[$key] = (array) $arg; } // generate an eval string to pass the clean arguments to array_merge $eval_string = '$return = array_merge('; foreach ($args as $key => $null) { $eval_string .= '$args['.$key.'],'; } $eval_string = substr($eval_string, 0, -1).');'; $return = false; eval($eval_string); return $return; } function array_compare($array1, $array2) { $diff = array(array( ), array( )); // Left-to-right foreach ($array1 as $key => $value) { if ( ! array_key_exists($key, $array2)) { $diff[0][$key] = $value; } elseif (is_array($value)) { if ( ! is_array($array2[$key])) { $diff[0][$key] = $value; $diff[1][$key] = $array2[$key]; } else { $new = array_compare($value, $array2[$key]); if ($new !== false) { if (isset($new[0])) { $diff[0][$key] = $new[0]; } if (isset($new[1])) { $diff[1][$key] = $new[1]; } } } } elseif ($array2[$key] !== $value) { $diff[0][$key] = $value; $diff[1][$key] = $array2[$key]; } } // Right-to-left foreach ($array2 as $key => $value) { if ( ! array_key_exists($key, $array1)) { $diff[1][$key] = $value; } // No direct comparison because matching keys were compared in the // left-to-right loop earlier, recursively. } return $diff; } + + +/** function array_filter_recursive + * + * Exactly the same as array_filter except this function + * filters within multi-dimensional arrays + * + * @param array + * @param string optional callback function name + * @param bool optional flag removal of empty arrays after filtering + * @return array merged array + */ +function array_filter_recursive($array, $callback = null, $remove_empty_arrays = false) { + foreach ($array as $key => & $value) { // mind the reference + if (is_array($value)) { + $value = array_filter_recursive($value, $callback); + + if ($remove_empty_arrays && ! (bool) $value) { + unset($array[$key]); + } + } + else { + if ( ! is_null($callback) && ! $callback($value)) { + unset($array[$key]); + } + elseif ( ! (bool) $value) { + unset($array[$key]); + } + } + } + unset($value); // kill the reference + + return $array; +} +
benjamw/pharaoh
189402d1f062d25ba0408054a05ba60adf7f7925
refactored the (im|ex)plode_full functions
diff --git a/includes/func.array.php b/includes/func.array.php index adb9497..bfb63bb 100644 --- a/includes/func.array.php +++ b/includes/func.array.php @@ -1,358 +1,370 @@ <?php /** * ARRAY FUNCTIONS * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** function array_trim [arrayTrim] * Performs the trim function recursively on * every element in an array and optionally typecasts * the element to the given type * * @param mixed csv list or array by reference * @param string optional typecast type * @return array */ function array_trim( & $array, $type = null) { $types = array( 'int' , 'integer' , 'bool' , 'boolean' , 'float' , 'double' , 'real' , 'string' , 'array' , 'object' , ); // if a non-empty string value comes through, don't erase it // this is specifically for '0', but may work for others $is_non_empty_string = (is_string($array) && strlen(trim($array))); if ( ! $array && ! $is_non_empty_string) { $array = array( ); } if ( ! in_array($type, $types)) { $type = null; } if ( ! is_array($array)) { $array = explode(',', $array); } if ( ! is_null($type)) { array_walk_recursive($array, create_function('&$v', '$v = ('.$type.') trim($v);')); } else { array_walk_recursive($array, create_function('&$v', '$v = trim($v);')); } return $array; // returns by reference as well } function arrayTrim( & $array, $type = null) { return array_trim($array, $type); } /** function array_clean [arrayClean] * Strips out the unnecessary bits from an array * so it can be input into a database, or to just * generally clean an array of fluff * * @param array data array to be cleaned * @param mixed csv or array of allowed keys * @param mixed optional csv or array of required keys * @return array */ function array_clean($array, $keys, $reqd = array( )) { if ( ! is_array($array)) { return array( ); } array_trim($keys); array_trim($reqd); $keys = array_unique(array_merge($keys, $reqd)); if (empty($keys)) { return array( ); } $return = array( ); foreach ($keys as $key) { if (in_array($key, $reqd) && (empty($array[$key]))) { throw new MyException(__FUNCTION__.': Required element ('.$key.') missing'); } if (isset($array[$key])) { $return[$key] = $array[$key]; } } return $return; } function arrayClean($array, $keys, $reqd = array( )) { return array_clean($array, $keys, $reqd); } /** function array_transpose [arrayTranspose] * Transposes a 2-D array * array[i][j] becomes array[j][i] * * Not to be confused with the PHP function array_flip * * @param array * @return mixed array (or bool false on failure) */ function array_transpose($array) { if ( ! is_array($array)) { throw new MyException(__FUNCTION__.': Data given was not an array'); } $return = array( ); foreach ($array as $key1 => $value1) { if ( ! is_array($value1)) { continue; } foreach ($value1 as $key2 => $value2) { $return[$key2][$key1] = $value2; } } if (0 == count($return)) { return false; } return $return; } function arrayTranspose($array) { return array_transpose($array); } /** function array_shrink [arrayShrink] * Returns all elements with second level key $key * from a 2-D array * e.g.- * $array[0]['foo'] = 'bar'; * $array[1]['foo'] = 'baz'; * * array_shrink($array, 'foo') returns * array( * [0] = 'bar' * [1] = 'baz' * ) * * This function returns the input if it is not * an array, or returns false if the key is not * present in the array * * @param array data array * @param mixed second level key * @return mixed array (or original input or bool false on failure) */ function array_shrink($array, $key) { if ( ! is_array($array)) { return $array; } $array = array_transpose($array); if ( ! isset($array[$key])) { return false; } return $array[$key]; } function arrayShrink($array, $key) { return array_shrink($array, $key); } /** function array_sum_field [arraySumField] * Returns the sum of all elements with key $key * from a 2-D array, no matter if $key is a first level * or second level key * * @param array * @param mixed element key * @return mixed float/int total (or bool false on failure) */ function array_sum_field($array, $key) { if ( ! is_array($array)) { return false; } $total = 0; if (isset($array[$key]) && is_array($array[$key])) { $total = array_sum($array[$key]); } else { foreach ($array as $row) { if (is_array($row) && isset($row[$key])) { $total += $row[$key]; } } } return $total; } function arraySumField($array, $key) { return array_sum_field($array, $key); } /** function implode_full [implodeFull] * Much like implode, but including the keys with an * extra divider between key-value pairs * Can be used to create URL GET strings from arrays * - * @param string separator between elements (for URL GET, use '&') - * @param string divider between key-value pairs (for URL GET, use '=') * @param array - * @param bool optional URL encode flag + * @param string optional separator between elements (for URL GET, use '&', default) + * @param string optional divider between key-value pairs (for URL GET, use '=', default) + * @param bitwise int optional URL encode flag * @return string */ -function implode_full($separator, $divider, $array, $url = false) +define('URL_ENCODE_NONE', 0); +define('URL_ENCODE_KEY', 1); +define('URL_ENCODE_VAL', 2); +define('URL_ENCODE_FULL', 4); +function implode_full($array, $separator = '&', $divider = '=', $url = URL_ENCODE_NONE) { if ( ! is_array($array) || (0 == count($array))) { return $array; } $str = ''; foreach ($array as $key => $val) { + if (URL_ENCODE_KEY & $url) { + $key = urlencode($key); + } + + if (URL_ENCODE_VAL & $url) { + $val = urlencode($val); + } + $str .= $key.$divider.$val.$separator; } $str = substr($str, 0, -(strlen($separator))); - if ($url) { - $str = url_encode($str); + if (URL_ENCODE_FULL & $url) { + $str = urlencode($str); } return $str; } -function implodeFull($separator, $divider, $array, $url = false) { return implode_full($separator, $divider, $array, $url); } +function implodeFull($array, $separator = '&', $divider = '=', $url = URL_ENCODE_NONE) { return implode_full($array, $separator, $divider, $url); } /** function explode_full [explodeFull] * Much like explode, but including the keys with an * extra divider between key-value pairs * Can be used to create arrays from URL GET strings * - * @param string separator between elements (for URL GET, use '&') - * @param string divider between key-value pairs (for URL GET, use '=') * @param string - * @param bool optional URL encode flag + * @param string optional separator between elements (for URL GET, use '&', default) + * @param string optional divider between key-value pairs (for URL GET, use '=', default) * @return array */ -function explode_full($separator, $divider, $string, $url = false) +function explode_full($string, $separator = '&', $divider = '=') { // explode the string about the separator $first = explode($separator, $string); // now go through each element in the first array and explode each about the divider foreach ($first as $element) { list($key, $value) = explode($divider, $element); $array[$key] = $value; } return $array; } -function explodeFull($separator, $divider, $string, $url = false) { return explode_full($separator, $divider, $string, $url); } +function explodeFull($string, $separator = '&', $divider = '=') { return explode_full($string, $separator, $divider); } /** function kshuffle * Exactly the same as shuffle except this function * preserves the original keys of the array * * @param array the array to shuffle by reference * @return array */ function kshuffle( & $array) { uasort($array, create_function('$a,$b', 'rand(1, -1);')); } /** function array_merge_plus + * * Exactly the same as array_merge except this function * allows entry of non-arrays without throwing errors * If an empty argument is encountered, it removes it. * If a non-empty, non-array value is encountered, * it appends it to the array in the order received. * * @param mixed item to merge into array * @param ... * @return array merged array */ function array_merge_plus($array1) { // grab the arguments of this function // and parse through them, removing any empty arguments // and converting non-empty, non-arrays to arrays $args = func_get_args( ); foreach ($args as $key => $arg) { if ( ! is_array($arg)) { if (empty($arg)) { unset($args[$key]); continue; } } $args[$key] = (array) $arg; } // generate an eval string to pass the clean arguments to array_merge $eval_string = '$return = array_merge('; foreach ($args as $key => $null) { $eval_string .= '$args['.$key.'],'; } $eval_string = substr($eval_string, 0, -1).');'; $return = false; eval($eval_string); return $return; } function array_compare($array1, $array2) { $diff = array(array( ), array( )); // Left-to-right foreach ($array1 as $key => $value) { if ( ! array_key_exists($key, $array2)) { $diff[0][$key] = $value; } elseif (is_array($value)) { if ( ! is_array($array2[$key])) { $diff[0][$key] = $value; $diff[1][$key] = $array2[$key]; } else { $new = array_compare($value, $array2[$key]); if ($new !== false) { if (isset($new[0])) { $diff[0][$key] = $new[0]; } if (isset($new[1])) { $diff[1][$key] = $new[1]; } } } } elseif ($array2[$key] !== $value) { $diff[0][$key] = $value; $diff[1][$key] = $array2[$key]; } } // Right-to-left foreach ($array2 as $key => $value) { if ( ! array_key_exists($key, $array1)) { $diff[1][$key] = $value; } // No direct comparison because matching keys were compared in the // left-to-right loop earlier, recursively. } return $diff; }
benjamw/pharaoh
ab5187b054e0e33bc081745e55b65f41bfe80043
added missing _backtrace property
diff --git a/classes/mysql.class.php b/classes/mysql.class.php index 2616570..1879b5c 100644 --- a/classes/mysql.class.php +++ b/classes/mysql.class.php @@ -539,634 +539,636 @@ class Mysql * * @param string table name * @param string where clause * @action execute a mysql query * @return result */ public function delete($table, $where) { $query = " DELETE FROM `{$table}` {$where} "; $this->query = $query; try { return $this->query( ); } catch (MySQLException $e) { throw $e; } } /** public function multi_delete * Delete the array of data from the table. * $table[0] = table name * $table[1] = table name * * $where[0] = where clause * $where[1] = where clause * * If recursive is true, all combinations of table name * and where clauses will be executed. * * If only one table name is set, that table will * be used for all of the queries, looping through * the where array * * If only one where clause is set, that where clause * will be used for all of the queries, looping through * the table array * * @param mixed table name array or single string * @param mixed where clause array or single string * @param bool optional recursive (default false) * @action execute multiple mysql queries * @return array results */ public function multi_delete($table_array, $where_array, $recursive = false) { if ( ! is_array($table_array)) { $recursive = false; $table_array = (array) $table_array; } if ( ! is_array($where_array)) { $recursive = false; $where_array = (array) $where_array; } if ($recursive) { foreach ($table_array as $table) { foreach ($where_array as $where) { $result[] = $this->delete($table, $where); } } } else { if (count($table_array) == count($where_array)) { for ($i = 0, $count = count($table_array); $i < $count; ++$i) { $result[] = $this->delete($table_array[$i], $where_array[$i]); } } elseif (1 == count($table_array)) { $table = $table_array[0]; foreach ($where_array as $where) { $result[] = $this->delete($table, $where); } } elseif (1 == count($where_array)) { $where = $where_array[0]; foreach ($table_array as $table) { $result[] = $this->delete($table, $where); } } else { throw new MySQLException(__METHOD__.': Trying to multi-delete with incompatible array sizes'); } } return $result; } /** public function fetch_object * Execute a database query and return the next result row as object. * Each subsequent call to this method returns the next result row. * * @param string [optional] SQL query string * @action [optional] execute a mysql query * @return mysql next result object row */ public function fetch_object($query = null) { if ( ! is_null($query)) { $this->query = $query; $this->query( ); } $row = @mysql_fetch_object($this->result); return $row; } /** public function fetch_row * Execute a database query and return result as an indexed array. * Each subsequent call to this method returns the next result row. * * @param string [optional] SQL query string * @action [optional] execute a mysql query * @return array indexed mysql result array */ public function fetch_row($query = null) { if ( ! is_null($query)) { $this->query = $query; $this->query( ); } $row = @mysql_fetch_row($this->result); if ( ! $row) { $row = array( ); } return $row; } /** public function fetch_assoc * Execute a database query and return result as an associative array. * Each subsequent call to this method returns the next result row. * * @param string [optional] SQL query string * @action [optional] execute a mysql query * @return array associative mysql result array */ public function fetch_assoc($query = null) { if ( ! is_null($query)) { $this->query = $query; $this->query( ); } $row = @mysql_fetch_assoc($this->result); if ( ! $row) { $row = array( ); } return $row; } /** public function fetch_both * Execute a database query and return result as both * an associative array and indexed array. * Each subsequent call to this method returns the next result row. * * @param string [optional] SQL query string * @action [optional] execute a mysql query * @return array associative and indexed mysql result array */ public function fetch_both($query = null) { if ( ! is_null($query)) { $this->query = $query; $this->query( ); } $row = @mysql_fetch_array($this->result, MYSQL_BOTH); if ( ! $row) { $row = array( ); } return $row; } /** public function fetch_array * Execute a database query and return result as * an indexed array of both indexed and associative arrays. * This method returns the entire result set in a single call. * * @param string [optional] SQL query string * @param int [optional] SQL result type ( One of: MYSQL_ASSOC, MYSQL_NUM, MYSQL_BOTH ) * @action [optional] execute a mysql query * @return array indexed array of mysql result arrays of type $result_type */ public function fetch_array($query = null, $result_type = MYSQL_ASSOC) { if ( ! is_null($query)) { $this->query = $query; $this->query( ); } $arr = array( ); while ($row = @mysql_fetch_array($this->result, $result_type)) { $arr[] = $row; } return $arr; } /** public function fetch_value * Execute a database query and return result as * a single result value. * This method only returns the single value at index 0. * Each subsequent call to this method returns the next value. * * @param string [optional] SQL query string * @action [optional] execute a mysql query * @return mixed single mysql result value */ public function fetch_value($query = null) { if ( ! is_null($query)) { $this->query = $query; $this->query( ); } $row = @mysql_fetch_row($this->result); if (false !== $row) { return $row[0]; } else { // no data found return null; } } /** public function fetch_value_array * Execute a database query and return result as * an indexed array of single result values. * This method returns the entire result set in a single call. * * @param string [optional] SQL query string * @action [optional] execute a mysql query * @return array indexed array of single mysql result values */ public function fetch_value_array($query = null) { if ( ! is_null($query)) { $this->query = $query; $this->query( ); } $arr = array( ); while ($row = @mysql_fetch_row($this->result)) { $arr[] = $row[0]; } return $arr; } /** public function paginate NOT TESTED * Paginates a query result set based on supplied information * NOTE: It is not necessary to include the SQL_CALC_FOUND_ROWS * nor the LIMIT clause in the query, in fact, including the * LIMIT clause in the query will probably break MySQL. * * @param int [optional] current page number * @param int [optional] number of records per page * @param string [optional] SQL query string * @return array pagination result and data */ public function paginate($page = null, $num_per_page = null, $query = null) { if ( ! is_null($page)) { $this->_page = $page; } else { // we don't have a page, either increment, or set equal to 1 $this->_page = (isset($this->_page)) ? ($this->_page + 1) : 1; } if ( ! is_null($num_per_page)) { $this->_num_per_page = $num_per_page; } else { $this->_num_per_page = (isset($this->_num_per_page)) ? $this->_num_per_page : 50; } if ( ! $this->_page || ! $this->_num_per_page) { throw new MySQLException(__METHOD__.': No pagination data given'); } if ( ! is_null($query)) { $this->_page_query = $query; // add the SQL_CALC_FOUND_ROWS keyword to the query if (false === strpos($query, 'SQL_CALC_FOUND_ROWS')) { $query = preg_replace('/SELECT\\s+(?!SQL_)/i', 'SELECT SQL_CALC_FOUND_ROWS ', $query); } $start = ($this->_num_per_page * ($this->_page - 1)); // add the LIMIT clause to the query $query .= " LIMIT {$start}, {$this->_num_per_page} "; $this->_page_result = $this->fetch_array($query); if ( ! $this->_page_result) { // no data found return array( ); } $query = " SELECT FOUND_ROWS( ) AS count "; $this->_num_results = $this->fetch_value($query); $this->_num_pages = (int) ceil($this->_num_results / $this->_num_per_page); } else { // we are using the previous data if ($this->_num_results < ($this->_num_per_page * ($this->_page - 1))) { return array( ); } $query = $this->_page_query; $start = $this->_num_per_page * ($this->_page - 1); // add the LIMIT clause to the query $query .= " LIMIT {$start}, {$this->_num_per_page} "; $this->_page_result = $this->fetch_array($query); if ( ! $this->_page_result) { // no data found return array( ); } } // clean up the data and output to user $output = array( ); $output['num_rows'] = $this->_num_results; $output['num_per_page'] = $this->_num_per_page; $output['num_pages'] = $this->_num_pages; $output['cur_page'] = $this->_page; $output['data'] = $this->_page_result; return $output; } /** public function fetch_insert_id * Return the insert id for the most recent query. * * @param void * @return int previous insert id */ public function fetch_insert_id( ) { return @mysql_insert_id($this->link_id); } /** protected function _log * Report messages to a file * * @param string message * @action log messages to file * @return void */ protected function _log($msg) { if (false && $this->_log_errors && class_exists('Log')) { Log::write($msg, __CLASS__); } } /** protected function _error_report * Report the errors * * @param void * @action log errors * @return void */ protected function _error_report( ) { $this->_log($this->error); // generate an error report and then act according to configuration $error_report = date('Y-m-d H:i:s')."\n\tAn error has been generated by the server.\n\tFollowing is the debug information:\n\n"; // we don't need this function in the error report, just delete it $debug_array = debug_backtrace( ); unset($debug_array[0]); // if a database query caused the error, show the query if ('' != $this->query) { $error_report .= "\t* Query: {$this->query}\n"; } $error_report .= "\t* Error: {$this->error}\n"; $error_report .= "\t* Backtrace: ".print_r($debug_array, true)."\n\n"; // send the error as email if set if ($this->_email_errors && ('' != $this->_email_to) && ('' != $this->_email_from)) { mail($this->_email_to, trim($this->_email_subject), $error_report, 'From: '.$this->_email_from."\r\n"); } // log the error if ($this->_log_errors) { $log = $this->_log_path.'mysql.err'; $fp = fopen($log, 'a+'); fwrite($fp, $error_report); @chmod($log, 0777); fclose($fp); } } /** protected function _get_backtrace * Grab the data for the file that called the mysql function * * @param void * @return mixed array backtrace data, or bool false on failure */ protected function _get_backtrace( ) { // grab the debug_backtrace $debug = debug_backtrace(false); // parse through it, and find the first instance that isn't from this file $file = false; foreach ($debug as $file) { if (__FILE__ == $file['file']) { continue; } else { // $file will be the file that called the mysql function break; } } return $file; } /** static public function get_instance * Returns the singleton instance * of the MySQL Object as a reference * * @param array optional configuration array * @action optionally creates the instance * @return MySQL Object reference */ static public function get_instance($config = null) { try { if (is_null(self::$_instance)) { self::$_instance = new Mysql($config); } self::$_instance->test_connection( ); self::$_instance->_log(__METHOD__.' --------------------------------------'); } catch (MySQLException $e) { throw $e; } return self::$_instance; } /** static public function test * Test the MySQL connection * * @param void * @return bool connection OK */ static public function test( ) { try { self::get_instance( ); return true; } catch (MySQLException $e) { return false; } } } // end of Mysql class class MySQLException extends Exception { + protected $_backtrace = true; + /** * METHODS * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** public function __construct * Class constructor * Sets all outside data * * @param string error message * @param int optional error code * @action instantiates object * @action writes the exception to the log * @return void */ public function __construct($message, $code = 1) { parent::__construct($message, $code); // our own exception handling stuff if ( ! empty($GLOBALS['_LOGGING'])) { $this->_write_error( ); } } /** public function outputMessage * cleans the message for use * * @param void * @return cleaned message */ public function outputMessage( ) { // strip off the __METHOD__ bit of the error, if possible $message = $this->message; $message = preg_replace('/(?:\\w+::)+\\w+:\\s+/', '', $message); return $message; } /** protected function _write_error * writes the exception to the log file * * @param void * @action writes the exception to the log * @return void */ protected function _write_error( ) { // first, lets make sure we can actually open and write to directory // specified by the global variable... and lets also do daily logs for now $log_name = 'mysql_exception_'.date('Ymd', time( )).'.log'; // okay, write our log message $str = date('Y/m/d H:i:s')." == ({$this->code}) {$this->message} : {$this->file} @ {$this->line}\n"; if ($this->_backtrace) { $str .= "---------- [ BACKTRACE ] ----------\n"; $str .= $this->getTraceAsString( )."\n"; $str .= "-------- [ END BACKTRACE ] --------\n\n"; } if ($fp = @fopen(LOG_DIR.$log_name, 'a')) { fwrite($fp, $str); fclose($fp); } call($str, $bypass = false, $show_from = true, $new_window = false, $error = true); } } // end of MySQLException class /* +--------------------------------------------------------------------------- | > Extra SQL Functions +--------------------------------------------------------------------------- */ // escape the data before it gets queried into the database // NOTE: this function does NOT take any magic quotes into account // it is therefore recommended to run something like the following // before anything else is done in the script /* if (get_magic_quotes_gpc( )) { function stripslashes_deep($value) { $value = is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value); return $value; } $_POST = array_map('stripslashes_deep', $_POST); $_GET = array_map('stripslashes_deep', $_GET); $_COOKIE = array_map('stripslashes_deep', $_COOKIE); $_REQUEST = array_map('stripslashes_deep', $_REQUEST); } */ if ( ! function_exists('sani')) { function sani($data) { if (is_array($data)) { return array_map('sani', $data); } else { return mysql_real_escape_string($data); } } } if ( ! function_exists('microtime_float')) { function microtime_float( ) { list($usec, $sec) = explode(' ', microtime( )); return ((float) $usec + (float) $sec); } }
benjamw/pharaoh
828ec335bb694e8bf03fa2d1f444b2e376d4cf88
renamed tables in EOF comments
diff --git a/classes/chat.class.php b/classes/chat.class.php index a087d5f..2d8aec0 100644 --- a/classes/chat.class.php +++ b/classes/chat.class.php @@ -1,253 +1,253 @@ <?php /* +--------------------------------------------------------------------------- | | chat.class.php (php 5.x) | | by Benjam Welker | http://iohelix.net | +--------------------------------------------------------------------------- | | > In-game chat module | > Date started: 2008-06-15 | | > Module Version Number: 0.8.0 | +--------------------------------------------------------------------------- */ /* Requires ---------------------------------------------------------------------------- Mysql class: Mysql::get_instance( MyException class */ // TODO: comments & organize better // TODO: exceptions class Chat { /** * PROPERTIES * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** const property CHAT_TABLE * Stores the name of the chat table * * @param string */ const CHAT_TABLE = T_CHAT; /** protected property _user_id * Stores the id of the user * * @param int */ protected $_user_id; /** protected property _game_id * Stores the id of the game * * @param int */ protected $_game_id; /** protected property _mysql * Stores a reference to the Mysql class object * * @param Mysql object */ protected $_mysql; /** protected property _DEBUG * Holds the DEBUG state for the class * * @var bool */ protected $_DEBUG = false; /** * METHODS * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** public function __construct * Class constructor * Sets all outside data * * @param int user id * @param int game id * @action instantiates object * @return void */ public function __construct($user_id, $game_id) { if (empty($user_id)) { throw new MyException(__METHOD__.': No user id given'); } $Mysql = Mysql::get_instance( ); $this->_user_id = (int) $user_id; $this->_game_id = (int) $game_id; $this->_mysql = $Mysql; if (defined('DEBUG')) { $this->_DEBUG = DEBUG; } } /** public function __get * Class getter * Returns the requested property if the * requested property is not _private * * @param string property name * @return mixed property value */ public function __get($property) { if ( ! property_exists($this, $property)) { throw new MyException(__METHOD__.': Trying to access non-existent property ('.$property.')', 2); } if ('_' === $property[0]) { throw new MyException(__METHOD__.': Trying to access _private property ('.$property.')', 2); } return $this->$property; } /** public function __set * Class setter * Sets the requested property if the * requested property is not _private * * @param string property name * @param mixed property value * @action optional validation * @return bool success */ public function __set($property, $value) { if ( ! property_exists($this, $property)) { throw new MyException(__METHOD__.': Trying to access non-existent property ('.$property.')', 3); } if ('_' === $property[0]) { throw new MyException(__METHOD__.': Trying to access _private property ('.$property.')', 3); } $this->$property = $value; } /** public function get_box_list * Retrieves the list of chats in the box * * @param int optional number of chats to retrieve (pulls most recent) * @return html list table */ public function get_box_list($num = null) { if ((0 == $this->_game_id) && is_null($num)) { $num = 30; } $LIMIT = (( ! is_null($num)) ? " LIMIT ".(int) $num." " : ''); $query = " SELECT C.* , P.player_id , P.username , P.email FROM ".self::CHAT_TABLE." AS C LEFT JOIN ".Player::PLAYER_TABLE." AS P ON P.player_id = C.from_id WHERE C.game_id = {$this->_game_id} AND ((C.from_id = {$this->_user_id}) OR (C.private = 0)) ORDER BY C.create_date DESC {$LIMIT} "; $result = $this->_mysql->fetch_array($query); return $result; } /** public function send_message * Adds a message to the in-game chat * * @param string message * @param bool optional private message * @action saves all relevant data to database * @return void */ public function send_message($message, $private = false, $lobby = false) { // run through htmlentities first (no html allowed) $message = htmlentities($message, ENT_QUOTES, 'ISO-8859-1', false); // check the lobby if ( ! (bool) $lobby && ! $this->_game_id) { throw new MyException(__METHOD__.': Game ID missing from chat'); } // grab the last message and make sure it isn't exactly the same $last = $this->get_box_list(1); if ($last) { $last = $last[0]; $last_date = strtotime($last['create_date']); // because there may be a time difference between the DB server and the WebServer $date = strtotime($this->_mysql->fetch_value(" SELECT NOW( ) ")); if (($message == $last['message']) && ($private == $last['private']) && ($date <= ($last_date + 60))) { throw new MyException(__METHOD__.': Duplicate message'); } } // save the message $this->_mysql->insert(self::CHAT_TABLE, array('message' => $message, 'private' => (int) $private, 'from_id' => $this->_user_id, 'game_id' => $this->_game_id)); } } // end of Chat class /* schemas // =================================== -- --- Table structure for table `wr_chat` +-- Table structure for table `chat` -- -DROP TABLE IF EXISTS `wr_chat`; -CREATE TABLE IF NOT EXISTS `wr_chat` ( +DROP TABLE IF EXISTS `chat`; +CREATE TABLE IF NOT EXISTS `chat` ( `chat_id` int(10) unsigned NOT NULL AUTO_INCREMENT, `message` text NOT NULL, `from_id` int(10) unsigned NOT NULL DEFAULT '0', `game_id` int(10) unsigned NOT NULL DEFAULT '0', `private` tinyint(1) unsigned NOT NULL DEFAULT '0', `create_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`chat_id`), KEY `game_id` (`game_id`), KEY `private` (`private`), KEY `from_id` (`from_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci ; */ diff --git a/classes/gravatar.class.php b/classes/gravatar.class.php index 3088709..50337d5 100644 --- a/classes/gravatar.class.php +++ b/classes/gravatar.class.php @@ -1,272 +1,271 @@ <?php - /* +--------------------------------------------------------------------------- | | gravatar.class.php (php 5.x) | | by Benjam Welker | http://iohelix.net | +--------------------------------------------------------------------------- | | > Gravatar module | > Date started: 2009-08-01 | | > Module Version Number: 0.8.0 | +--------------------------------------------------------------------------- */ class Gravatar { /** * PROPERTIES * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** const property GRAVATAR_SITE_URL * Stores the url of the gravatar access page * * @param string */ const GRAVATAR_SITE_URL = 'http://www.gravatar.com/avatar/%s?s=%d&amp;r=%s&amp;d=%s'; /** protected property _default * Stores the default image string * Can be one of: identicon, monsterid, wavatar, [empty string] * or the url of the default image * * @param string */ protected $_default; /** protected property _email_hash * Stores the md5 hash of the email address * * @param string */ protected $_email_hash; /** protected property _rating * Stores the maximum rating of the returned image * Cane be one of: g, pg, r, x * * @param string */ protected $_rating; /** protected property _size * Stores the size of the returned image * Must be between 1 and 512 * * @param int */ protected $_size; /** static private property _instance * Holds the instance of this object * * @var Gravatar object */ static private $_instance; /** * METHODS * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** public function __construct * Class constructor * Sets all outside data * * @param array settings * @action instantiates object * @return void */ public function __construct($settings = array( )) { foreach ($settings as $key => $value) { switch ($key) { case 'size' : $value = (int) $value; if (0 == $value) { unset($settings[$key]); break; } if (1 > $value) { $value = 1; } if (512 < $value) { $value = 512; } break; case 'rating' : $value = strtolower($value); if ( ! in_array($value, array('g', 'pg', 'r', 'x'))) { unset($settings[$key]); break; } break; case 'default' : $value = strtolower($value); if ( ! in_array($value, array('identicon', 'monsterid', 'wavatar', '')) && ! preg_match('%^http://%i', $value)) { unset($settings[$key]); break; } break; } if (isset($settings[$key])) { $settings[$key] = $value; } } // you can set your own default settings here // or leave blank to use gravatar.com's defaults $defaults = array( 'size' => 45, 'rating' => 'pg', 'default' => 'identicon', ); $opts = array_merge($defaults, $settings); // set some defaults $this->_size = (int) $opts['size']; $this->_rating = strtolower($opts['rating']); $this->_default = $opts['default']; } /** public function __get * Class getter * Returns the requested property if the * requested property is not _private * * @param string property name * @return mixed property value */ public function __get($property) { if ( ! property_exists($this, $property)) { throw new MyException(__METHOD__.': Trying to access non-existent property ('.$property.')', 2); } if ('_' === $property[0]) { throw new MyException(__METHOD__.': Trying to access _private property ('.$property.')', 2); } return $this->$property; } /** public function __set * Class setter * Sets the requested property if the * requested property is not _private * * @param string property name * @param mixed property value * @action optional validation * @return bool success */ public function __set($property, $value) { if ( ! property_exists($this, $property)) { throw new MyException(__METHOD__.': Trying to access non-existent property ('.$property.')', 3); } if ('_' === $property[0]) { throw new MyException(__METHOD__.': Trying to access _private property ('.$property.')', 3); } $this->$property = $value; } /** public function get_src * Returns the src for the image tag * * @param void * @return string image src */ public function get_src( ) { return (string) sprintf( self::GRAVATAR_SITE_URL, $this->_email_hash, $this->_size, strtolower($this->_rating), $this->_default ); } /** public function set_email * Sets the email hash based on the given email * * @param string email address * @action sets email hash * @return void */ public function set_email($email) { $this->_email_hash = md5($email); } /** static public function get_instance * Returns the singleton instance * of the Gravatar Object as a reference * * @param array optional settings * @action optionally creates the instance * @return Log Object reference */ static public function get_instance($settings = array( )) { if (is_null(self::$_instance)) { self::$_instance = new Gravatar($settings); } return self::$_instance; } /** static public function src * Returns the src for the image tag * * @param string optional email address * @param array optional settings * @return string image src */ static public function src($email = null, $settings = array( )) { $_this = self::get_instance($settings); if ( ! empty($email)) { $_this->set_email($email); } return $_this->get_src( ); } } // end of Gravatar class diff --git a/classes/message.class.php b/classes/message.class.php index d8bfca0..04c8fc3 100644 --- a/classes/message.class.php +++ b/classes/message.class.php @@ -359,552 +359,552 @@ class Message if (0 == $recipient['to_id']) { $row['recipient_data'][] = array( 'id' => $recipient['to_id'] , 'name' => 'GLOBAL' , 'viewed' => true ); break; } $row['recipient_data'][] = array( 'id' => $recipient['to_id'] , 'name' => $GLOBALS['_PLAYERS'][$recipient['to_id']] , 'viewed' => ( ! is_null($recipient['view_date'])) ); $result[$key] = $row; } } // now convert the recipients for each message to a string $recip_string = ''; if (is_array($row['recipient_data'])) { foreach ($row['recipient_data'] as $recipient) { if (empty($recipient['name'])) { continue; } $recip_string .= ( ! $recipient['viewed']) ? '<span class="highlight">'.$recipient['name'].'</span>, ' : $recipient['name'].', '; } } $result[$key]['recipients'] = substr($recip_string, 0, -2); } } return $result; } /** public function get_message * Retrieves the message from the database * but makes sure this user can see this message first * * @param int message id * @param bool is admin * @action tests to make sure this user can see this message * @return array message data */ public function get_message($message_id, $admin = false) { call(__METHOD__); $message_id = (int) $message_id; $admin = (bool) $admin; if (empty($message_id)) { throw new MyException(__METHOD__.': No message id given'); } $query = " SELECT M.* FROM ".self::MESSAGE_TABLE." AS M WHERE M.message_id = {$message_id} "; $message = $this->_mysql->fetch_assoc($query); if ( ! $message) { throw new MyException(__METHOD__.': Message not found'); } // find out who this message was sent by $query = " SELECT G.* , P.username AS recipient , S.username AS sender FROM ".self::GLUE_TABLE." AS G LEFT JOIN ".GamePlayer::EXTEND_TABLE." AS R ON (R.player_id = G.to_id) LEFT JOIN ".Player::PLAYER_TABLE." AS P ON (P.player_id = R.player_id) LEFT JOIN ".Player::PLAYER_TABLE." AS S ON (S.player_id = G.from_id) WHERE G.message_id = '{$message['message_id']}' ORDER BY recipient "; $message['recipients'] = $this->_mysql->fetch_array($query); // parse through the recipients and find out // if we are allowed to view this message // and set some various message flags $message['allowed'] = false; $message['inbox'] = false; $message['global'] = false; foreach ($message['recipients'] as $recipient) { if ($recipient['from_id'] == $this->_user_id) { $message['allowed'] = true; $message['inbox'] = true; } if ($recipient['to_id'] == $this->_user_id) { $message['allowed'] = true; } if (0 == $recipient['to_id']) { $message['global'] = true; } } if ( ! $message['allowed'] && ! $admin) { throw new MyException(__METHOD__.': Not allowed to view this message'); } else { $this->set_message_read($message_id); } if ('' == $message['subject']) { $message['subject'] = '<No Subject>'; } return $message; } /** public function get_message_reply * Retrieves the message from the database * but makes sure this user can see this message first * and then appends data to the message so it can be replied to * * @param int message id * @action tests to make sure this user can see this message * @action appends data to the subject and message so it can be replied to * @return array [subject, message, to] */ public function get_message_reply($message_id) { call(__METHOD__); try { $message = $this->_get_message_data($message_id, true); $message['subject'] = (0 === strpos($message['subject'], 'RE')) ? $message['subject'] : 'RE: '.$message['subject']; } catch (MyExeption $e) { throw $e; } return $message; } /** public function get_message_forward * Retrieves the message from the database * but makes sure this user can see this message first * and then appends data to the message so it can be forwarded * * @param int message id * @action tests to make sure this user can see this message * @action appends data to the subject and message so it can be forwarded * @return array [subject, message, to] */ public function get_message_forward($message_id) { call(__METHOD__); try { $message = $this->_get_message_data($message_id, false); $message['subject'] = (0 === strpos($message['subject'], 'FW')) ? $message['subject'] : 'FW: '.$message['subject']; } catch (MyExeption $e) { throw $e; } return $message; } /** public function set_message_read * Sets the given messages as read by this user * * @param array or csv string message id(s) * @action sets read date for these messages * @return void */ public function set_message_read($message_ids) { call(__METHOD__); // if we are admin logged in as another player // don't mark it as read if we view the message if ( ! empty($_SESSION['admin_id'])) { return; } array_trim($message_ids, 'int'); if (0 != count($message_ids)) { $WHERE = " WHERE to_id = '{$this->_user_id}' AND message_id IN (".implode(',', $message_ids).") "; $this->_mysql->insert(self::GLUE_TABLE, array('view_date ' => 'NOW( )'), $WHERE); } } /** public function set_message_unread * Sets the given messages as unread by this user * * @param array or csv string message id(s) * @action removes read date for these messages * @return void */ public function set_message_unread($message_ids) { call(__METHOD__); array_trim($message_ids, 'int'); if (0 != count($message_ids)) { $WHERE = " WHERE to_id = '{$this->_user_id}' AND message_id IN (".implode(',', $message_ids).") "; $this->_mysql->insert(self::GLUE_TABLE, array('view_date' => NULL), $WHERE); } } /** public function delete_message * Deletes the glue table entry for these messages for this user * * @param array or csv string message id(s) * @action deletes the glue table entries * @return void */ public function delete_message($message_ids) { call(__METHOD__); array_trim($message_ids, 'int'); if (0 != count($message_ids)) { foreach ($message_ids as $message_id) { $query = " SELECT * FROM ".self::GLUE_TABLE." WHERE to_id = '{$this->_user_id}' AND message_id = '{$message_id}' "; $result = $this->_mysql->fetch_assoc($query); // test and see if the message is from this user if ($result['from_id'] == $this->_user_id) { if (strtotime($result['send_date']) > time( )) { // the message has not been sent yet, delete them all // (use actual deletions here) $this->_mysql->multi_delete(array(self::GLUE_TABLE, self::MESSAGE_TABLE), " WHERE message_id = '{$message_id}' "); } // check for global message and delete if found // (use actual deletion here) if ($this->_can_send_global) { $WHERE = " WHERE to_id = 0 AND message_id = '{$message_id}' "; $this->_mysql->delete(self::GLUE_TABLE, $WHERE); } } // delete our own entry $WHERE = " WHERE to_id = '{$this->_user_id}' AND message_id = '{$message_id}' "; $this->_mysql->insert(self::GLUE_TABLE, array('deleted' => 1), $WHERE); } } } /** static public function player_deleted * Deletes the given players messages * * @param mixed array or csv of player ids * @action deletes the players messages * @return void */ static public function player_deleted($player_ids) { call(__METHOD__); $Mysql = Mysql::get_instance( ); array_trim($player_ids, 'int'); if ( ! $player_ids) { throw new MyException(__METHOD__.': No player IDs given'); } $player_ids = implode(',', $player_ids); $Mysql->delete(Message::GLUE_TABLE, " WHERE from_id IN ({$player_ids}) OR to_id IN ({$player_ids}) "); } /** public function send_message * Deletes the glue table entry for this message for this user * * @param string message subject * @param string message body * @param array (or csv string) message recipient user ids * @param int optional message send date as unix timestamp (default: now) * @param int optional message expire date as unix timestamp (default: never) * @action saves all relevant data to database * @return void */ public function send_message($subject, $message, $user_ids, $send_date = false, $expire_date = false) { call(__METHOD__); array_trim($user_ids, 'int'); // check for a global message if ($this->_can_send_global) { // just replace the user_ids, everybody's gonna get it anyway if (in_array(0, $user_ids)) { $query = " SELECT player_id FROM ".Player::PLAYER_TABLE." "; $user_ids = $this->_mysql->fetch_value_array($query); $user_ids[] = 0; } } else { // this is not an admin // remove all instances of 0 from the id list $user_ids = array_diff(array_unique($user_ids), array(0)); } if ( ! is_array($user_ids) || (0 == count($user_ids))) { throw new MyException(__METHOD__.': Trying to send a message to nobody'); } // clean the message bits $subject = htmlentities($subject, ENT_QUOTES, 'ISO-8859-1', false); $message = htmlentities($message, ENT_QUOTES, 'ISO-8859-1', false); // save the message so we can grab the id $message_id = $this->_mysql->insert(self::MESSAGE_TABLE, array('subject' => $subject, 'message' => $message)); // add ourselves to the recipient list and clean it up $user_ids[] = $this->_user_id; $user_ids = array_unique($user_ids); // convert 04/24/2008 -> 2008-04-24 $send_date = ( ! preg_match('%^(\\d+)/(\\d+)/(\\d+)$%', $send_date)) ? NULL : preg_replace('%^(\\d+)/(\\d+)/(\\d+)$%', '$3-$1-$2', $send_date); $expire_date = ( ! preg_match('%^(\\d+)/(\\d+)/(\\d+)$%', $expire_date)) ? NULL : preg_replace('%^(\\d+)/(\\d+)/(\\d+)$%', '$3-$1-$2', $expire_date); foreach($user_ids as $user_id) { $data = array( 'message_id' => $message_id, 'from_id' => $this->_user_id, 'to_id' => $user_id, 'send_date' => $send_date, 'expire_date' => $expire_date, ); $this->_mysql->insert(self::GLUE_TABLE, $data); } } /** public function grab_global_messages * Searches the glue table for global messages and copies * those entries to this user * * @param void * @action copies global messages to this users inbox * @return void */ public function grab_global_messages( ) { call(__METHOD__); $query = " SELECT * FROM ".self::GLUE_TABLE." WHERE to_id = 0 AND deleted = 0 "; $result = $this->_mysql->fetch_array($query); if ($result) { foreach ($result as $row) { unset($row['message_glue_id']); unset($row['view_date']); unset($row['create_date']); unset($row['deleted']); $row['to_id'] = $this->_user_id; $this->_mysql->insert(self::GLUE_TABLE, $row); } } } /** protected function _get_message_data * Retrieves the message from the database for sending * but makes sure this user can see this message first * and then appends data to the message so it can be sent * * @param int message id * @action tests to make sure this user can see this message * @action appends data to the subject and message so it can be sent * @return array [subject, message, to] */ protected function _get_message_data($message_id) { call(__METHOD__); try { $message = $this->get_message($message_id); } catch (MyExeption $e) { throw $e; } $message['from'] = Player::get_username($message['recipients'][0]['from_id']); $message['date'] = (empty($message['send_date']) ? $message['create_date'] : $message['send_date']); $message['date'] = date(Settings::read('long_date'), strtotime($message['date'])); $message['subject'] = ('' == $message['subject']) ? '<No Subject>' : $message['subject']; $message['message'] = "\n\n\n".str_repeat('=', 50)."\n\n{$message['from']} said: ({$message['date']})\n".str_repeat('-', 50)."\n{$message['message']}"; return $message; } /** static public function get_count * Grab the inbox count of new and total messages * for the given player * * @param int player id * @return array (int total messages, int new messages) */ static public function get_count($player_id) { call(__METHOD__); $player_id = (int) $player_id; $Mysql = Mysql::get_instance( ); $query = " SELECT COUNT(*) FROM ".self::GLUE_TABLE." WHERE to_id = '{$player_id}' AND from_id <> '{$player_id}' AND (send_date <= NOW( ) OR send_date IS NULL) AND deleted = 0 "; $msgs = $Mysql->fetch_value($query); $query .= " AND view_date IS NULL "; $new_msgs = $Mysql->fetch_value($query); return array($msgs, $new_msgs); } /** static public function check_new * Checks if the given player has any new messages * * @param int player id * @return number of new messages */ static public function check_new($player_id) { call(__METHOD__); $player_id = (int) $player_id; if ( ! $player_id) { return false; } $Mysql = Mysql::get_instance( ); $query = " SELECT COUNT(*) FROM ".self::GLUE_TABLE." WHERE to_id = '{$player_id}' AND from_id <> '{$player_id}' AND (send_date <= NOW( ) OR send_date IS NULL) AND deleted = 0 AND view_date IS NULL "; $new = $Mysql->fetch_value($query); return $new; } } // end of Message class /* schemas // =================================== -- --- Table structure for table `wr_message` +-- Table structure for table `message` -- -DROP TABLE IF EXISTS `wr_message`; -CREATE TABLE IF NOT EXISTS `wr_message` ( +DROP TABLE IF EXISTS `message`; +CREATE TABLE IF NOT EXISTS `message` ( `message_id` int(10) unsigned NOT NULL AUTO_INCREMENT, `subject` varchar(255) NOT NULL DEFAULT '', `message` text NOT NULL, `create_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`message_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci ; -- -------------------------------------------------------- -- --- Table structure for table `wr_message_glue` +-- Table structure for table `message_glue` -- -DROP TABLE IF EXISTS `wr_message_glue`; -CREATE TABLE IF NOT EXISTS `wr_message_glue` ( +DROP TABLE IF EXISTS `message_glue`; +CREATE TABLE IF NOT EXISTS `message_glue` ( `message_glue_id` int(10) unsigned NOT NULL AUTO_INCREMENT, `message_id` int(10) unsigned NOT NULL DEFAULT '0', `from_id` int(10) unsigned NOT NULL DEFAULT '0', `to_id` int(10) unsigned NOT NULL DEFAULT '0', `send_date` datetime DEFAULT NULL, `expire_date` datetime DEFAULT NULL, `view_date` datetime DEFAULT NULL, `create_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `deleted` tinyint(1) unsigned NOT NULL DEFAULT '0', PRIMARY KEY (`message_glue_id`), KEY `outbox` (`from_id`,`message_id`), KEY `inbox` (`to_id`,`message_id`), KEY `created` (`create_date`), KEY `expire_date` (`expire_date`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci ; */ diff --git a/classes/settings.class.php b/classes/settings.class.php index 1055389..e644150 100644 --- a/classes/settings.class.php +++ b/classes/settings.class.php @@ -1,476 +1,476 @@ <?php /* +--------------------------------------------------------------------------- | | settings.class.php (php 5.x) | | by Benjam Welker | http://iohelix.net | +--------------------------------------------------------------------------- | | > Settings module | > Date started: 2009-04-15 | | > Module Version Number: 0.8.0 | +--------------------------------------------------------------------------- */ class Settings { /** * PROPERTIES * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** const property SETTINGS_TABLE * Holds the settings table name * * @var string */ const SETTINGS_TABLE = T_SETTINGS; /** protected property _settings * Stores the site settings in an * associative array * * @param array */ protected $_settings = array( ); /** protected property _notes * Stores the site settings notes in an * associative array * * @param array */ protected $_notes = array( ); /** protected property _delete_missing * Deletes missing settings from the database * when saving settings * * @param bool */ protected $_delete_missing = false; /** protected property _save_new * Saves new (previously unsaved) settings * to the database when saving settings * * @param bool */ protected $_save_new = false; /** static private property _instance * Holds the instance of this object * * @var Settings object */ static private $_instance; /** protected property _mysql * Stores a reference to the Mysql class object * * @param Mysql object */ protected $_mysql; /** * METHODS * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** protected function __construct * Class constructor * * @param void * @action instantiates object * @action pulls settings from settings table * @return void */ protected function __construct( ) { $this->_mysql = Mysql::get_instance( ); if ($this->test( )) { $this->_pull( ); } } /** public function __destruct * Class destructor * * @param void * @action saves settings to DB * @action destroys object * @return void */ /* public function __destruct( ) { // save anything changed to the database // BUT... only if PHP didn't die because of an error $error = error_get_last( ); if (0 == ((E_ERROR | E_WARNING | E_PARSE) & $error['type'])) { try { $this->save( ); } catch (MyException $e) { // do nothing, it will be logged } } } */ /** public function __get * Class getter * Returns the requested property if the * requested property is not _private * * @param string property name * @return mixed property value */ public function __get($property) { if ( ! isset($this->_settings[$property]) && ! property_exists($this, $property)) { throw new MyException(__METHOD__.': Trying to access non-existent property ('.$property.')', 2); } if ('_' === $property[0]) { throw new MyException(__METHOD__.': Trying to access _private property ('.$property.')', 2); } if (isset($this->_settings[$property])) { return $this->_settings[$property]; } else { return $this->$property; } } /** public function __set * Class setter * Sets the requested property if the * requested property is not _private * * @param string property name * @param mixed property value * @action optional validation * @return void */ public function __set($property, $value) { if ('_' === $property[0]) { throw new MyException(__METHOD__.': Trying to access _private property ('.$property.')', 3); } if (property_exists($this, $property)) { $this->$property = $value; } else { $this->_settings[$property] = $value; } } /** protected function _pull * Pulls all settings data from the database * * @param void * @action pulls the settings data * @return void */ protected function _pull( ) { $query = " SELECT * FROM ".self::SETTINGS_TABLE." ORDER BY sort "; $results = $this->_mysql->fetch_array($query); if ( ! $results) { die('Settings were not pulled properly'); } $this->_settings = array( ); foreach ((array) $results as $result) { $this->_settings[$result['setting']] = $result['value']; $this->_notes[$result['setting']] = $result['notes']; } } /** public function save * Saves all settings data to the database * if the settings are different * * @param void * @action saves the settings data * @return void */ public function save( ) { call(__METHOD__); $query = " SELECT * FROM ".self::SETTINGS_TABLE." ORDER BY sort "; $results = $this->_mysql->fetch_array($query); $data = array( ); $settings = $this->_settings; foreach ($results as $result) { if (isset($settings[$result['setting']])) { if ($result['value'] != $settings[$result['setting']]) { $result['value'] = $settings[$result['setting']]; $data[] = $result; } unset($settings[$result['setting']]); } elseif ($this->_delete_missing) { $this->_mysql->delete(self::SETTINGS_TABLE, " WHERE setting = {$result['setting']} "); } } if ($this->_save_new) { foreach ($settings as $setting => $value) { $addition['setting'] = $setting; $addition['value'] = $value; $data[] = $addition; } } $this->_mysql->multi_insert(self::SETTINGS_TABLE, $data, true); } /** protected function get_settings * Grabs the whole settings array and returns it * * @param void * @return array settings */ protected function get_settings( ) { return $this->_settings; } /** protected function put_settings * Merges the submitted settings into * the settings array * * @param array settings * @return void */ protected function put_settings($settings) { if (is_array($settings)) { $this->_settings = array_merge($this->_settings, $settings); } } /** static public function get_instance * Returns the singleton instance * of the Settings Object as a reference * * @param void * @action optionally creates the instance * @return Settings Object reference */ static public function get_instance( ) { if (is_null(self::$_instance) && self::test( )) { self::$_instance = new Settings( ); } return self::$_instance; } /** static public function read * Gets the requested property if the * requested property is not _private * * @param string property name * @return mixed property value * @see __get */ static public function read($property) { if (self::get_instance( )) { return self::get_instance( )->$property; } else { return false; } } /** static public function read_all * Gets all the properties * * @param void * @return array property => value pairs */ static public function read_all( ) { if (self::get_instance( )) { return self::get_instance( )->get_settings( ); } else { return false; } } /** static public function write * Sets the requested property if the * requested property is not _private * * @param string property name * @param mixed property value * @return void * @see __set */ static public function write($property, $value) { if (self::get_instance( )) { self::get_instance( )->$property = $value; self::get_instance( )->save( ); } } /** static public function write_all * Sets all the properties * * @param array property => value pairs * @return void * @see __set */ static public function write_all($settings) { if (self::get_instance( )) { self::get_instance( )->put_settings($settings); self::get_instance( )->save( ); return self::get_instance( )->get_settings( ); } else { return false; } } /** static public function read_setting_notes * Reads the notes associated with the settings * * @param void * @return array settings notes */ static public function read_setting_notes( ) { if ($_this = self::get_instance( )) { // single equals intended return $_this->_notes; } else { return false; } } /** static public function test * Test the MySQL connection * * @param void * @return bool connection OK */ static public function test( ) { if ( ! is_null(self::$_instance)) { return true; } if ( ! Mysql::test( )) { return false; } // look for anything in the settings table $query = " SELECT * FROM ".self::SETTINGS_TABLE." "; $return = Mysql::get_instance( )->query($query); return (bool) $return; } } // end of Settings class /* schemas // =================================== -- --- Table structure for table `ph_settings` +-- Table structure for table `settings` -- -DROP TABLE IF EXISTS `ph_settings`; -CREATE TABLE IF NOT EXISTS `ph_settings` ( +DROP TABLE IF EXISTS `settings`; +CREATE TABLE IF NOT EXISTS `settings` ( `setting` varchar(255) NOT NULL DEFAULT '', `value` text NOT NULL, `notes` text, `sort` smallint(5) unsigned NOT NULL DEFAULT '0', UNIQUE KEY `setting` (`setting`), KEY `sort` (`sort`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci ; -- --- Dumping data for table `ph_settings` +-- Dumping data for table `settings` -- -INSERT INTO `ph_settings` (`setting`, `value`, `notes`, `sort`) VALUES +INSERT INTO `settings` (`setting`, `value`, `notes`, `sort`) VALUES ('site_name', 'Your Site Name', 'The name of your site', 10), - ('default_color', 'c_green_white.css', 'The default theme color for the script pages', 20), - ('nav_links', '<!-- your nav links here -->', 'HTML code for your site''s navigation links to display on the script pages', 30), + ('default_color', 'c_blue_black.css', 'The default theme color for the script pages', 20), + ('nav_links', '<a href="/">Home</a>', 'HTML code for your site''s navigation links to display on the script pages', 30), ('from_email', '[email protected]', 'The email address used to send game emails', 40), ('to_email', '[email protected]', 'The email address to send admin notices to (comma separated)', 50), ('new_users', '1', '(1/0) Allow new users to register (0 = off)', 60), ('approve_users', '0', '(1/0) Require admin approval for new users (0 = off)', 70), ('confirm_email', '0', '(1/0) Require email confirmation for new users (0 = off)', 80), ('max_users', '0', 'Max users allowed to register (0 = off)', 90), ('default_pass', 'change!me', 'The password to use when resetting a user''s password', 100), ('expire_users', '45', 'Number of days until untouched games are deleted (0 = off)', 110), ('save_games', '1', '(1/0) Save games in the ''games'' directory on the server (0 = off)', 120), ('expire_games', '30', 'Number of days until untouched user accounts are deleted (0 = off)', 130), ('nudge_flood_control', '24', 'Number of hours between nudges. (-1 = no nudging, 0 = no flood control)', 135), ('timezone', 'UTC', 'The timezone to use for dates (<a href="http://www.php.net/manual/en/timezones.php">List of Timezones</a>)', 140), ('long_date', 'M j, Y g:i a', 'The long format for dates (<a href="http://www.php.net/manual/en/function.date.php">Date Format Codes</a>)', 150), ('short_date', 'Y.m.d H:i', 'The short format for dates (<a href="http://www.php.net/manual/en/function.date.php">Date Format Codes</a>)', 160), ('debug_pass', '', 'The DEBUG password to use to set temporary DEBUG status for the script', 170), ('DB_error_log', '1', '(1/0) Log database errors to the ''logs'' directory on the server (0 = off)', 180), ('DB_error_email', '1', '(1/0) Email database errors to the admin email addresses given (0 = off)', 190); */
benjamw/pharaoh
4a6db8ebedfef4a8845755e289f2412ca12eb44a
reverted changes that broke some AJAX
diff --git a/ajax_helper.php b/ajax_helper.php index dc5cc91..482d554 100644 --- a/ajax_helper.php +++ b/ajax_helper.php @@ -1,295 +1,291 @@ <?php $GLOBALS['NODEBUG'] = true; $GLOBALS['AJAX'] = true; // don't require log in when testing for used usernames and emails if (isset($_POST['validity_test']) || (isset($_GET['validity_test']) && isset($_GET['DEBUG']))) { define('LOGIN', false); } require_once 'includes/inc.global.php'; // if we are debugging, change some things for us // (although REQUEST_METHOD may not always be valid) if (('GET' == $_SERVER['REQUEST_METHOD']) && test_debug( )) { $GLOBALS['NODEBUG'] = false; $GLOBALS['AJAX'] = false; $_GET['token'] = $_SESSION['token']; $_GET['keep_token'] = true; $_POST = $_GET; $DEBUG = true; call('AJAX HELPER'); call($_POST); } // run the index page refresh checks if (isset($_POST['timer'])) { $message_count = (int) Message::check_new($_SESSION['player_id']); $turn_count = (int) Game::check_turns($_SESSION['player_id']); echo $message_count + $turn_count; exit; } // run registration checks if (isset($_POST['validity_test'])) { # if (('email' == $_POST['type']) && ('' == $_POST['value'])) { # echo 'OK'; # exit; # } $player_id = 0; if ( ! empty($_POST['profile'])) { $player_id = (int) $_SESSION['player_id']; } switch ($_POST['validity_test']) { case 'username' : case 'email' : $username = ''; $email = ''; ${$_POST['validity_test']} = sani($_POST['value']); $player_id = (isset($_POST['player_id']) ? (int) $_POST['player_id'] : 0); try { Player::check_database($username, $email, $player_id); } catch (MyException $e) { echo $e->getCode( ); exit; } break; default : break; } echo 'OK'; exit; } // run the in game chat if (isset($_POST['chat'])) { try { if ( ! isset($_SESSION['game_id'])) { $_SESSION['game_id'] = 0; } $Chat = new Chat((int) $_SESSION['player_id'], (int) $_SESSION['game_id']); $Chat->send_message($_POST['chat'], isset($_POST['private']), isset($_POST['lobby'])); $return = $Chat->get_box_list(1); $return = $return[0]; } catch (MyException $e) { $return['error'] = 'ERROR: '.$e->outputMessage( ); } echo json_encode($return); exit; } // run setup validation if (isset($_POST['test_setup'])) { try { Setup::is_valid_reflection($_POST['setup'], $_POST['reflection']); $return['valid'] = true; } catch (MyException $e) { $return['error'] = 'ERROR: '.$e->outputMessage( ); } echo json_encode($return); exit; } // run setup laser test fire if (isset($_POST['test_fire'])) { try { // returns laser_path and hits arrays $return = Pharaoh::fire_laser($_POST['color'], $_POST['board']); } catch (MyException $e) { $return['error'] = 'ERROR: '.$e->outputMessage( ); } echo json_encode($return); exit; } // run the invites stuff if (isset($_POST['invite'])) { if ('delete' == $_POST['invite']) { // make sure we are one of the two people in the invite if (Game::has_invite($_POST['game_id'], $_SESSION['player_id'])) { if (Game::delete_invite($_POST['game_id'])) { echo 'Invite Deleted'; } else { echo 'ERROR: Invite not deleted'; } } else { echo 'ERROR: Not your invite'; } } else if ('resend' == $_POST['invite']) { // make sure we are one of the two people in the invite if (Game::has_invite($_POST['game_id'], $_SESSION['player_id'])) { try { if (Game::resend_invite($_POST['game_id'])) { echo 'Invite Resent'; } else { echo 'ERROR: Could not resend invite'; } } catch (MyException $e) { echo 'ERROR: '.$e->outputMessage( ); } } else { echo 'ERROR: Not your invite'; } } else { // make sure we are one of the two people in the invite if (Game::has_invite($_POST['game_id'], $_SESSION['player_id'], $accept = true)) { if ($game_id = Game::accept_invite($_POST['game_id'])) { // single equals intended echo $game_id; } else { echo 'ERROR: Could not create game'; } } else { echo 'ERROR: Not your invite'; } } exit; } // we'll need a game id from here forward, so make sure we have one if (empty($_SESSION['game_id'])) { echo 'ERROR: Game not found'; exit; } // init our game if ( ! isset($Game)) { $Game = new Game((int) $_SESSION['game_id']); } // run the game refresh check if (isset($_POST['refresh'])) { echo $Game->last_move; exit; } // do some validity checking if (empty($DEBUG) && empty($_POST['notoken'])) { test_token( ! empty($_POST['keep_token'])); } if ($_POST['game_id'] != $_SESSION['game_id']) { throw new MyException('ERROR: Incorrect game id given. Was #'.$_POST['game_id'].', should be #'.$_SESSION['game_id'].'.'); } // make sure we are the player we say we are // unless we're an admin, then it's ok $player_id = (int) $_POST['player_id']; if (($player_id != $_SESSION['player_id']) && ! $GLOBALS['Player']->is_admin) { throw new MyException('ERROR: Incorrect player id given'); } // run the simple button actions $actions = array( 'nudge', 'resign', 'offer_draw', 'accept_draw', 'reject_draw', 'request_undo', 'accept_undo', 'reject_undo', ); foreach ($actions as $action) { if (isset($_POST[$action])) { try { - if ($Game->{$action}($player_id)) { - echo 'OK'; - } - else { - echo 'ERROR'; - } + $Game->{$action}($player_id); + echo 'OK'; } catch (MyException $e) { echo $e; } exit; } } // run the game actions if (isset($_POST['turn'])) { $return = array( ); try { if (false !== strpos($_POST['to'], 'split')) { // splitting obelisk $to = substr($_POST['to'], 0, 2); call($to); $from = Pharaoh::index_to_target($_POST['from']); $to = Pharaoh::index_to_target($to); call($from.'.'.$to); $Game->do_move($from.'.'.$to); } elseif ((string) $_POST['to'] === (string) (int) $_POST['to']) { // moving $to = $_POST['to']; call($to); $from = Pharaoh::index_to_target($_POST['from']); $to = Pharaoh::index_to_target($to); call($from.':'.$to); $Game->do_move($from.':'.$to); } else { // rotating $target = Pharaoh::index_to_target($_POST['from']); $dir = (int) ('r' == strtolower($_POST['to'])); call($target.'-'.$dir); $Game->do_move($target.'-'.$dir); } $Game->save( ); $return['action'] = 'RELOAD'; } catch (MyException $e) { $return['error'] = 'ERROR: '.$e->outputMessage( ); } echo json_encode($return); exit; }